PlotDirector/PlotLine.Tests/Fixtures/ProjectTransferPlanning.sql

220 lines
29 KiB
Transact-SQL

-- Only executed after the specialist harness verifies its literal synthetic-only database.
DECLARE @secondScene int, @otherLocation int, @otherAsset int, @state int, @metric int,
@attribute int, @custody int, @floorPlan int, @floor int, @validation int,
@scenario int, @scenarioValidation int;
INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,Summary,SortOrder,RevisionStatusID,TimeModeID,TimeConfidenceID)
VALUES(@chapter,2.5,N'Second empty scene',N'',2,@revision,@timeMode,@confidence);
SET @secondScene=SCOPE_IDENTITY();
INSERT dbo.Locations(ProjectID,LocationName,ParentLocationID) VALUES(@project,N'Corridor 雪',@location);
SET @otherLocation=SCOPE_IDENTITY();
INSERT dbo.StoryAssets(ProjectID,AssetName,AssetKindID) VALUES(@project,N'Envelope Ω',@kind);
SET @otherAsset=SCOPE_IDENTITY();
INSERT dbo.AssetStates(ProjectID,AssetKindID,StateName,SortOrder,Description) VALUES(@project,@kind,N'Sealed Ω',1,N'Authored state café');
SET @state=SCOPE_IDENTITY();
UPDATE dbo.StoryAssets SET CurrentStateID=@state,CurrentLocationID=@location WHERE StoryAssetID=@asset;
INSERT dbo.ScenePurposes(SceneID,ScenePurposeTypeID) SELECT @scene,MIN(ScenePurposeTypeID) FROM dbo.ScenePurposeTypes;
INSERT dbo.SceneOutcomes(SceneID,OutcomeDescription) VALUES(@scene,N'An outcome — 雨');
INSERT dbo.SceneMetricTypes(ProjectID,MetricName,Description,MinValue,MaxValue,DefaultValue,SortOrder)
VALUES(@project,N'Tension Ω',N'Custom metric 雪',0,20,7,1);
SET @metric=SCOPE_IDENTITY();
INSERT dbo.SceneMetricValues(SceneID,MetricTypeID,Value,Notes) VALUES(@scene,@metric,8,N'Escalates café');
IF NOT EXISTS(SELECT 1 FROM dbo.ProjectTimelineSettings WHERE ProjectID=@project)
INSERT dbo.ProjectTimelineSettings(ProjectID,ShowStoryAssets,ShowCharacterAppearances) VALUES(@project,1,1);
UPDATE dbo.ProjectTimelineSettings SET ShowSceneCards=0,ShowStoryAssets=1 WHERE ProjectID=@project;
INSERT dbo.ProjectTimelineMetricSettings(ProjectID,MetricTypeID,SortOrder) VALUES(@project,@metric,2);
INSERT dbo.TimelineViewPresets(ProjectID,BookID,PresetName,FilterJson,VisibilityJson,FocusType,FocusID)
VALUES(@project,@book,N'Authored view Ω',N'{"query":"café"}',N'{"warnings":true}',N'Character',@character);
UPDATE dbo.TimelineViewPresets SET FilterJson=CONCAT(N'{"ProjectID":',@project,N',"BookID":',@book,N',"SelectedSceneID":',@scene,N',"ChapterFromID":',@chapter,N',"ChapterToID":',@chapter,N',"SceneFromID":',@scene,N',"SceneToID":',@secondScene,N',"PlotLineID":',@line,N',"PlotThreadID":',@thread,N',"StoryAssetID":',@asset,N',"CharacterID":',@character,N',"POVCharacterID":',@character,N',"LocationID":',@location,N',"FocusType":"character","FocusID":',@character,N',"ShowWarningsOnly":true,"extension":{"query":"café"}}') WHERE ProjectID=@project;
INSERT dbo.AssetEvents(StoryAssetID,SceneID,AssetEventTypeID,ToStateID,EventTitle,EventDescription)
SELECT @asset,@scene,MIN(AssetEventTypeID),@state,N'Sealed Ω',N'Unicode event 雨' FROM dbo.AssetEventTypes;
INSERT dbo.AssetDependencies(SourceAssetID,TargetAssetID,AssetDependencyTypeID,SourceRequiredStateID,TargetBlockedStateID,Description)
SELECT @asset,@otherAsset,MIN(AssetDependencyTypeID),@state,@state,N'Asset prerequisite 雪' FROM dbo.AssetDependencyTypes;
INSERT dbo.AssetCustodyEvents(StoryAssetID,SceneID,AssetCustodyEventTypeID,Description)
SELECT @asset,@scene,MIN(AssetCustodyEventTypeID),N'Custody café' FROM dbo.AssetCustodyEventTypes;
SET @custody=SCOPE_IDENTITY();
INSERT dbo.AssetCustodyEventCharacters(AssetCustodyEventID,CharacterID,CustodyRoleID)
SELECT @custody,@character,MIN(CustodyRoleID) FROM dbo.CustodyRoles;
INSERT dbo.SceneCharacters(SceneID,CharacterID,RoleInSceneTypeID,PresenceTypeID,LocationID,EntryLocationID,ExitLocationID,AppearanceNotes,OutfitDescription,EmotionalState,MatchSource,MatchedText,OccurrenceCount,FirstOccurrenceIndex)
SELECT @scene,@character,(SELECT MIN(CharacterRoleInSceneTypeID) FROM dbo.CharacterRoleInSceneTypes),MIN(PresenceTypeID),@location,@location,@otherLocation,N'Appears 雪',N'Coat Ω',N'Uneasy café',N'Manual',N'Narrator Ω',2,5 FROM dbo.PresenceTypes;
INSERT dbo.CharacterAttributeTypes(ProjectID,AttributeName,DataType,SortOrder) VALUES(@project,N'Voice Ω',N'Text',1);
SET @attribute=SCOPE_IDENTITY();
INSERT dbo.CharacterAttributeEvents(CharacterID,CharacterAttributeTypeID,SceneID,AttributeValue,Description)
VALUES(@character,@attribute,@scene,N'Whispering 雨',N'Authored trait');
INSERT dbo.CharacterKnowledge(CharacterID,StoryAssetID,PlotThreadID,SceneID,KnowledgeStateID,SourceEventID,Description,SourceReviewKey)
SELECT @character,@asset,@thread,@scene,MIN(KnowledgeStateID),@threadEvent,N'Knows the secret 雨',N'synthetic-knowledge-review' FROM dbo.KnowledgeStates;
INSERT dbo.LocationRelationships(FromLocationID,ToLocationID,LocationRelationshipTypeID,IsBidirectional,CanTravelDirectly,Notes)
SELECT @location,@otherLocation,MIN(LocationRelationshipTypeID),1,1,N'Connected rooms 雨' FROM dbo.LocationRelationshipTypes;
INSERT dbo.FloorPlans(ProjectID,Name,Description,LocationID) VALUES(@project,N'Layout Ω',N'Floor plan café',@location);
SET @floorPlan=SCOPE_IDENTITY();
INSERT dbo.FloorPlanFloors(FloorPlanID,Name,SortOrder,GridWidth,GridHeight,LocationID,BackgroundOpacity,BackgroundScale,BackgroundOffsetX,BackgroundOffsetY,Description)
VALUES(@floorPlan,N'Ground 雪',1,30,20,@location,.6,1.5,3,4,N'Floor notes Ω');
SET @floor=SCOPE_IDENTITY();
INSERT dbo.FloorPlanBlocks(FloorPlanFloorID,LocationID,X,Y,WidthCells,HeightCells,BlockType,LabelOverride,Notes)
VALUES(@floor,@location,2,3,6,4,N'Room',N'Room label 雪',N'Block notes café');
INSERT dbo.FloorPlanTransitions(FloorPlanFloorID,FromLocationID,ToLocationID,TransitionType,Notes,IsLocked,DisplayLabel)
VALUES(@floor,@location,@otherLocation,N'Door',N'Transition Ω',1,N'Locked café');
UPDATE dbo.Scenes SET FloorPlanID=@floorPlan,InitialFloorPlanFloorID=@floor WHERE SceneID=@scene;
INSERT dbo.SceneAssetLocations(SceneID,StoryAssetID,LocationID,Description) VALUES(@scene,@asset,@location,N'On desk 雨');
INSERT dbo.SceneFloorPlanOccupancy(SceneID,FloorPlanID,FloorPlanFloorID,CharacterID,LocationID)
VALUES(@scene,@floorPlan,@floor,@character,@location);
INSERT dbo.SceneDependencies(SourceSceneID,TargetSceneID,SceneDependencyTypeID,Description,ProjectID,IsHardDependency)
SELECT @scene,@secondScene,MIN(SceneDependencyTypeID),N'Before the next scene 雨',@project,1 FROM dbo.SceneDependencyTypes;
INSERT dbo.ValidationRuns(ProjectID,BookID,CompletedDate,TriggeredBy,ScopeDescription)
VALUES(@project,@book,'2026-11-03',N'Synthetic fixture',N'Book Ω');
SET @validation=SCOPE_IDENTITY();
INSERT dbo.ContinuityWarnings(ValidationRunID,ProjectID,BookID,ChapterID,SceneID,EntityType,EntityID,WarningTypeID,WarningSeverityID,Message,Details,IsIntentional)
SELECT @validation,@project,@book,@chapter,@scene,N'Character',@character,(SELECT MIN(WarningTypeID) FROM dbo.WarningTypes),MIN(WarningSeverityID),N'Warning café',N'Intentional 雨',1 FROM dbo.WarningSeverities;
INSERT dbo.SceneNotes(SceneID,SceneNoteTypeID,NoteTitle,NoteText,SortOrder,IsPinned)
SELECT @scene,MIN(SceneNoteTypeID),N'Note Ω',N'Long-form author note “雨”',1,1 FROM dbo.SceneNoteTypes;
INSERT dbo.SceneWorkflow(SceneID,DraftStatus,EstimatedWordCount,ActualWordCount,ReadyForDraft,IsBlocked,BlockedReason,Priority)
VALUES(@scene,N'Drafting',2500,1234,1,1,N'Needs research café',2);
INSERT dbo.SceneChecklistItems(SceneID,ItemText,IsCompleted,SortOrder) VALUES(@scene,N'Check continuity 雨',1,3);
INSERT dbo.SceneAttachments(SceneID,SceneAttachmentTypeID,Title,ExternalUrl,Notes)
SELECT @scene,MIN(SceneAttachmentTypeID),N'Research Ω',N'https://example.invalid/synthetic',N'External link only; no file-byte claim' FROM dbo.SceneAttachmentTypes;
INSERT dbo.ChapterGoals(ChapterID,GoalSummary,EmotionalGoal,ReaderTakeaway,MustInclude,RisksOrConcerns)
VALUES(@chapter,N'Goal Ω',N'Unease 雨',N'Question café',N'A clue',N'Ambiguity');
SELECT @scenario=ScenarioID FROM dbo.Scenarios WHERE ProjectID=@project;
INSERT dbo.ScenarioSceneOrder(ScenarioID,SceneID,ProposedChapterID,ProposedSortOrder,Notes)
VALUES(@scenario,@scene,@chapter,2,N'Alternative sequence 雨');
INSERT dbo.ScenarioValidationRuns(ScenarioID,CompletedDate,WarningCount) VALUES(@scenario,'2026-11-03',1);
SET @scenarioValidation=SCOPE_IDENTITY();
INSERT dbo.ScenarioWarnings(ScenarioValidationRunID,ScenarioID,SceneID,EntityType,EntityID,WarningTypeName,SeverityName,Message,Details)
VALUES(@scenarioValidation,@scenario,@scene,N'Character',@character,N'SyntheticWarning',N'Warning',N'Scenario warning 雨',N'Alternative detail café');
INSERT dbo.MapJourneyNotes(MapID,CharacterID,FromSceneID,ToSceneID,TravelMethod,TypicalMinutes)
VALUES(@map,@character,@scene,@secondScene,N'Walking café',18);
UPDATE dbo.StoryMaps SET AppearanceJson=JSON_MODIFY(AppearanceJson,'$.extension',JSON_QUERY(N'{"texture":"雨"}')),
ReferenceJson=JSON_MODIFY(ReferenceJson,'$.extension',JSON_QUERY(N'{"source":"café"}')) WHERE MapID=@map;
UPDATE dbo.Locations SET DetectionPriority=7,ExcludeFromCompanionDetection=1 WHERE LocationID=@otherLocation;
UPDATE dbo.ThreadEvents SET Source=N'Manual',SourceKey=CONCAT(N'synthetic-event-source-key-',@project),Confidence=.85 WHERE ThreadEventID=@threadEvent;
INSERT dbo.WordCompanionSceneAssets(SceneID,StoryAssetID) VALUES(@scene,@asset);
INSERT dbo.WordCompanionSceneLocations(SceneID,LocationID) VALUES(@scene,@otherLocation);
DECLARE @completedBuild int;
INSERT dbo.OnboardingManuscriptBuilds(PreviewID,UserID,ProjectID,BookID,ManuscriptDocumentID,Status,MarkerStatus,ChaptersCreated,ScenesCreated,CharactersCreated,MarkerSyncMessage,MarkerSyncCompletedUtc)
SELECT NEWID(),@user,@project,@book,ManuscriptDocumentID,N'Built',N'UserConfirmedSave',1,2,1,N'Synthetic completed marker history',SYSUTCDATETIME() FROM dbo.Scenes WHERE SceneID=@scene;
SET @completedBuild=SCOPE_IDENTITY();
INSERT dbo.OnboardingManuscriptBuildChapterMap(OnboardingManuscriptBuildID,TemporaryChapterKey,ChapterID) VALUES(@completedBuild,N'fixture-chapter-Ω',@chapter);
INSERT dbo.OnboardingManuscriptBuildSceneMap(OnboardingManuscriptBuildID,TemporarySceneKey,SceneID) VALUES(@completedBuild,N'fixture-scene-雨',@scene),(@completedBuild,N'fixture-scene-雪',@secondScene);
INSERT dbo.OnboardingManuscriptBuildCharacterMap(OnboardingManuscriptBuildID,TemporaryCharacterKey,CharacterID,Created) VALUES(@completedBuild,N'fixture-narrator-Ω',@character,1);
INSERT dbo.SceneAssetSuggestions(SceneID,AssetID,Status,Confidence,Reason,CreatedByUserID,ReviewedByUserID,ReviewedUtc) VALUES(@scene,@asset,N'Accepted',N'Medium',N'Author accepted asset 雨',@user,@user,'2026-10-02');
INSERT dbo.SceneCharacterSuggestions(SceneID,CharacterID,Status,Confidence,Reason,CreatedByUserID,ReviewedByUserID,ReviewedUtc) VALUES(@scene,@character,N'Rejected',N'Low',N'Author rejected identity Ω',@user,@user,'2026-10-03');
INSERT dbo.SceneLocationSuggestions(SceneID,LocationID,Status,Confidence,Reason,CreatedByUserID) VALUES(@scene,@location,N'Pending',N'High',N'Awaiting author café',@user);
INSERT dbo.SceneTextStatistics(SceneID,TotalWordCount,DialogueWordCount,ProseWordCount,TotalParagraphCount,DialogueParagraphCount,ProseParagraphCount) VALUES(@scene,1234,234,1000,8,2,6);
INSERT dbo.SceneAssetSuggestions(SceneID,AssetID,Status,Confidence,Reason,CreatedByUserID,ReviewedByUserID,ReviewedUtc) SELECT @scene,@asset,v.Status,N'Medium',N'Synthetic complete status coverage 雨',@user,CASE WHEN v.Status=N'Pending' THEN NULL ELSE @user END,CASE WHEN v.Status=N'Pending' THEN NULL ELSE CONVERT(datetime2,'2026-10-04') END FROM (VALUES(N'Pending'),(N'Accepted'),(N'Rejected'),(N'Dismissed')) v(Status) WHERE NOT EXISTS(SELECT 1 FROM dbo.SceneAssetSuggestions x WHERE x.SceneID=@scene AND x.AssetID=@asset AND x.Status=v.Status);
INSERT dbo.SceneCharacterSuggestions(SceneID,CharacterID,Status,Confidence,Reason,CreatedByUserID,ReviewedByUserID,ReviewedUtc) SELECT @scene,@character,v.Status,N'Medium',N'Synthetic complete status coverage 雨',@user,CASE WHEN v.Status=N'Pending' THEN NULL ELSE @user END,CASE WHEN v.Status=N'Pending' THEN NULL ELSE CONVERT(datetime2,'2026-10-04') END FROM (VALUES(N'Pending'),(N'Accepted'),(N'Rejected'),(N'Dismissed')) v(Status) WHERE NOT EXISTS(SELECT 1 FROM dbo.SceneCharacterSuggestions x WHERE x.SceneID=@scene AND x.CharacterID=@character AND x.Status=v.Status);
INSERT dbo.SceneLocationSuggestions(SceneID,LocationID,Status,Confidence,Reason,CreatedByUserID,ReviewedByUserID,ReviewedUtc) SELECT @scene,@location,v.Status,N'Medium',N'Synthetic complete status coverage 雨',@user,CASE WHEN v.Status=N'Pending' THEN NULL ELSE @user END,CASE WHEN v.Status=N'Pending' THEN NULL ELSE CONVERT(datetime2,'2026-10-04') END FROM (VALUES(N'Pending'),(N'Accepted'),(N'Rejected'),(N'Dismissed')) v(Status) WHERE NOT EXISTS(SELECT 1 FROM dbo.SceneLocationSuggestions x WHERE x.SceneID=@scene AND x.LocationID=@location AND x.Status=v.Status);
DECLARE @locationReview int,@locationCandidate int;
INSERT dbo.CoreImportBasicLocationReviews(PreviewID,UserID,ProjectID,BookID,BuildID,Status,RawObservationCount,CandidateCount,CompletedUtc)
SELECT PreviewID,@user,@project,@book,@completedBuild,N'Completed',1,1,'2026-11-03' FROM dbo.OnboardingManuscriptBuilds WHERE OnboardingManuscriptBuildID=@completedBuild;
SET @locationReview=SCOPE_IDENTITY();
INSERT dbo.CoreImportBasicLocationCandidates(CoreImportBasicLocationReviewID,StableKey,ProposedName,PreferredName,KnownNamesJson,ParentLocationID,ExistingLocationID,Action,SameAsLocationID,ResultLocationID,FirstChapterNumber,FirstSceneNumber,FirstOccurrenceIndex,ObservationCount,SortOrder)
VALUES(@locationReview,N'synthetic-location-Ω',N'Room detected 雨',N'Room approved Ω',N'["Room Ω","Chamber café"]',@otherLocation,@location,N'SameLocation',@location,@location,1,1,3,1,1);
SET @locationCandidate=SCOPE_IDENTITY();
INSERT dbo.CoreImportBasicLocationEvidence(CoreImportBasicLocationCandidateID,SceneID,ChapterID,ChapterNumber,SceneNumber,OccurrenceIndex,EvidenceText,SortOrder)
VALUES(@locationCandidate,@scene,@chapter,1,1,3,N'“Entered the room”—exact evidence 雨',1);
DECLARE @siRun int,@siChapter int,@siRaw nvarchar(max);
SET @siRaw=N'{"source":"retained audit 雨","originalSceneID":'+CONVERT(nvarchar(20),@scene)+N',"text":"'+REPLICATE(CONVERT(nvarchar(max),N'Quoted Ω café—雪. '),10000)+N'"}';
INSERT dbo.StoryIntelligenceRuns(UserID,ProjectID,BookID,ChapterID,ChapterNumber,Status,SourceType,PromptVersion,Model,StartedUtc,CompletedUtc,SourceFileName,SourceFileSizeBytes,SourceWordCount,SourceCharacterCount,SourceChapterCount,SourceParagraphCount,SourceLabel,SourceText,KnownCharactersJson,TotalInputTokens,TotalOutputTokens,TotalTokens,TotalDurationMs,EstimatedCostGBP,EstimatedCostUSD,CurrentStage,CurrentMessage,TotalDetectedScenes,CompletedScenes,FailedScenes)
VALUES(@user,@project,@book,@chapter,1,N'Completed',N'Manuscript',N'synthetic-v1',N'synthetic-no-provider','2026-11-01','2026-11-02',N'Synthetic café.docx',4096,1234,9000,1,8,N'Original source Ω',N'“Source text”—雪'+CHAR(13)+CHAR(10)+N'Another paragraph',N'[{"name":"Narrator Ω"}]',150,60,210,4250,.005,.007,N'Completed',N'Retained synthetic audit',2,2,0);
SET @siRun=SCOPE_IDENTITY();
INSERT dbo.StoryIntelligenceChapterResults(StoryIntelligenceRunID,ProjectID,BookID,ChapterID,ChapterNumber,SourceLabel,PromptVersion,Model,RawResponseJson,OutputTextJson,ParsedJson,ValidationErrorsCount,ValidationWarningsCount,InputTokens,OutputTokens,TotalTokens,DurationMs)
VALUES(@siRun,@project,@book,@chapter,1,N'Chapter audit Ω',N'synthetic-v1',N'synthetic-no-provider',@siRaw,N'{"chapter":"雨"}',N'{"scenes":[]}',0,1,100,40,140,3000);
SET @siChapter=SCOPE_IDENTITY();
INSERT dbo.StoryIntelligenceSceneResults(StoryIntelligenceRunID,ChapterResultID,ProjectID,BookID,ChapterID,SceneID,TemporarySceneNumber,StartParagraph,EndParagraph,SourceLabel,PromptVersion,Model,RawResponseJson,OutputTextJson,ParsedJson,ValidationErrorsCount,ValidationWarningsCount,InputTokens,OutputTokens,TotalTokens,DurationMs)
VALUES(@siRun,@siChapter,@project,@book,@chapter,@scene,1,1,8,N'Scene audit 雨',N'synthetic-v1',N'synthetic-no-provider',@siRaw,N'{"scene":"Ω"}',N'{"observations":[]}',0,1,50,20,70,1250);
INSERT dbo.StoryIntelligenceImportCommits(StoryIntelligenceRunID,ProjectID,BookID,ChapterID,CommittedByUserID,ScenesCreated,MetricsCreated,Status,Notes)
VALUES(@siRun,@project,@book,@chapter,@user,2,1,N'Completed',N'Synthetic canonical materialization audit Ω');
UPDATE dbo.Scenes SET ImportRunID=@siRun WHERE SceneID=@scene;
DECLARE @pipeline int,@memoryCharacter int,@memoryAsset int,@memoryLocation int,@profile int,@sceneResult int;
SELECT @sceneResult=SceneResultID FROM dbo.StoryIntelligenceSceneResults WHERE StoryIntelligenceRunID=@siRun;
INSERT dbo.StoryIntelligenceBookPipelines(ProjectID,BookID,CurrentStage,LastCompletedStage,CurrentReviewStage,Status,CompletedUtc,LastRunID,CompletionEmailQueuedUtc,FailureEmailQueuedUtc,CharacterReviewCompletedUtc,LocationReviewCompletedUtc,AssetReviewCompletedUtc,RelationshipReviewCompletedUtc,KnowledgeReviewCompletedUtc,NarrativeReviewCompletedUtc)
VALUES(@project,@book,N'Complete',N'NarrativeImport',NULL,N'Complete','2026-11-03',@siRun,'2026-11-03',NULL,'2026-11-03','2026-11-03','2026-11-03','2026-11-03','2026-11-03','2026-11-03');
SET @pipeline=SCOPE_IDENTITY();
INSERT dbo.StoryMemoryCharacters(ImportSessionID,ProjectID,BookID,CanonicalIdentityKey,DisplayName,EntityContext,SourceSectionType,IsNamed,IsGroupEntity,IsResolved,IsNarrator,IsPrimaryPOV,Significance,EvidenceVersion,CreatedSceneResultID,LastUpdatedSceneResultID)
VALUES(@pipeline,@project,@book,N'memory-character-Ω',N'Remembered narrator 雨',N'Character',N'Body',1,0,1,1,1,3,1,@sceneResult,@sceneResult);
SET @memoryCharacter=SCOPE_IDENTITY();
INSERT dbo.StoryMemoryCharacterAliases(StoryMemoryCharacterID,Alias,NormalisedAlias,ResolutionReason,SourceSceneResultID,Confidence)
VALUES(@memoryCharacter,N'Alias Ω',N'alias ω',N'Exact source evidence café',@sceneResult,.85);
INSERT dbo.StoryMemoryCharacterAttributes(StoryMemoryCharacterID,AttributeType,NormalisedValue,Confidence,IsExplicit,EvidenceSummary,SourceSceneResultID,SupersededUtc)
VALUES(@memoryCharacter,N'EyeColour',N'grey',.9,1,N'Retained authored evidence 雨',@sceneResult,'2026-11-02');
INSERT dbo.StoryMemoryAssets(ImportSessionID,ProjectID,BookID,CanonicalIdentityKey,DisplayName,SemanticType,Subtype,Colour,Era,FirstSeenSceneResultID,LastSeenSceneResultID)
VALUES(@pipeline,@project,@book,N'memory-asset-Ω',N'Remembered notebook 雨',N'Object',N'Notebook',N'Blue',N'Future',@sceneResult,@sceneResult);
SET @memoryAsset=SCOPE_IDENTITY();
INSERT dbo.StoryMemoryLocations(ImportSessionID,ProjectID,BookID,CanonicalIdentityKey,DisplayName,SemanticType,Subtype,InteriorExterior,FirstSeenSceneResultID,LastSeenSceneResultID)
VALUES(@pipeline,@project,@book,N'memory-location-Ω',N'Remembered room 雨',N'Room',N'Workshop',N'Interior',@sceneResult,@sceneResult);
SET @memoryLocation=SCOPE_IDENTITY();
INSERT dbo.StoryMemoryRelationships(ImportSessionID,SourceEntityType,SourceEntityID,TargetEntityType,TargetEntityID,RelationshipType,Confidence,IsExplicit,FirstSeenSceneResultID,LastUpdatedSceneResultID,Active)
VALUES(@pipeline,N'Character',@memoryCharacter,N'Asset',@memoryAsset,N'owns',.85,1,@sceneResult,@sceneResult,1),(@pipeline,N'Asset',@memoryAsset,N'Location',@memoryLocation,N'located-in',.8,1,@sceneResult,@sceneResult,0);
INSERT dbo.StoryMemoryProcessedSceneResults(ImportSessionID,SceneResultID,ProcessorVersion,SnapshotHash) VALUES(@pipeline,@sceneResult,N'synthetic-v1',N'0123456789abcdef');
INSERT dbo.StoryMemoryImportPreferences(ImportSessionID,AppearancePreference,ResolverVersion,PrimaryAgeGroup,StoryEra,StoryLocation)
VALUES(@pipeline,N'ExplicitEvidenceOnly',N'synthetic-v1',N'Adult',N'Future era Ω',N'City 雨');
INSERT dbo.CharacterIntelligenceProfiles(ImportSessionID,ProjectID,BookID,CanonicalIdentityKey,CanonicalName,ProfileJson,Confidence,NarrativeImportance,IsRecurring,EvidenceVersion,LastUpdatedSceneResultID)
VALUES(@pipeline,@project,@book,N'profile-Ω',N'Profile narrator 雨',N'{"CanonicalName":"Profile narrator 雨","EvidenceTimeline":[{"SceneResultID":'+CONVERT(nvarchar(20),@sceneResult)+N',"Evidence":"Exact evidence Ω"}],"Contradictions":[{"SceneResultID":'+CONVERT(nvarchar(20),@sceneResult)+N',"Evidence":"Contradiction café"}],"extension":{"SceneResultID":7654321,"note":"Unknown property preserved 雨"}}',.9,N'Primary',1,N'synthetic-v1',@sceneResult);
SET @profile=SCOPE_IDENTITY();
INSERT dbo.CharacterIntelligenceEvidenceEvents(CharacterIntelligenceProfileID,SceneResultID,FieldName,PreviousValue,NewValue,Evidence,Confidence,IsContradiction,Source)
VALUES(@profile,@sceneResult,N'EyeColour',N'blue',N'grey',N'“Grey eyes”—雨',.9,1,N'Synthetic source');
DECLARE @reviewModules table(RowID int IDENTITY,ModuleName nvarchar(40),CanonicalID int,Payload nvarchar(max));
DECLARE @knowledgeID int=(SELECT MIN(CharacterKnowledgeID) FROM dbo.CharacterKnowledge WHERE CharacterID=@character AND SceneID=@scene);
INSERT @reviewModules(ModuleName,CanonicalID,Payload) VALUES
(N'Characters',@character,CONCAT(N'{"characterName":"Reviewed character Ω","existingCharacterID":',@character,N',"selectedExistingCharacterID":',@observer,N',"existingCharacterOptions":[{"characterID":',@character,N',"characterName":"Narrator Ω"},{"characterID":',@observer,N',"characterName":"Observer 雪"}]}')),
(N'Locations',@location,CONCAT(N'{"locationName":"Reviewed location 雨","existingLocationID":',@location,N',"proposedParentLocationID":',@otherLocation,N',"existingParentLocationID":',@otherLocation,N',"proposedParentCandidateKey":"locations-Ω-1"}')),
(N'Assets',@asset,CONCAT(N'{"assetName":"Reviewed asset café","existingAssetID":',@asset,N',"possibleAliases":["Notebook 雨"]}')),
(N'Relationships',@relationship,CONCAT(N'{"characterAID":',@character,N',"characterBID":',@observer,N',"firstSceneID":',@scene,N',"existingRelationshipID":',@relationship,N',"relationshipTypeID":',@relationshipType,N',"relationshipStateID":',@relationshipState,N',"proposalKind":"Development","observations":[{"sceneID":',@scene,N',"evidence":"Directional evidence 雨","confidence":0.95}]}')),
(N'Knowledge',@knowledgeID,CONCAT(N'{"characterID":',@character,N',"storyAssetID":',@asset,N',"existingKnowledgeID":',@knowledgeID,N',"knowledgeStatement":"Knows the secret 雨","knowledgeStateID":',(SELECT MIN(KnowledgeStateID) FROM dbo.KnowledgeStates),N',"observations":[{"sceneID":',@scene,N',"evidence":"Knowledge evidence Ω","confidence":0.95}]}'));
DECLARE @moduleIndex int=1,@moduleName nvarchar(40),@canonicalID int,@payload nvarchar(max),@generation int,@candidate int,@candidateIndex int,@candidatePayload nvarchar(max),@stableKey nvarchar(450),@firstKey nvarchar(450);
WHILE @moduleIndex<=5
BEGIN
SELECT @moduleName=ModuleName,@canonicalID=CanonicalID,@payload=JSON_MODIFY(Payload,'$.extension',JSON_QUERY(N'{"sceneID":7654321,"note":"Unknown extension 雨"}')) FROM @reviewModules WHERE RowID=@moduleIndex;
INSERT dbo.StoryIntelligenceReviewCandidateGenerations(ProjectID,BookID,Module,Status,Source,CandidateCount,PendingCount,IsCurrent,PreparedUtc)
VALUES(@project,@book,@moduleName,N'Ready',N'Synthetic persisted review',CASE WHEN @moduleName=N'Relationships' THEN 4 ELSE 3 END,1,1,'2026-11-03');
SET @generation=SCOPE_IDENTITY(); SET @candidateIndex=1;
IF @moduleName=N'Relationships'
BEGIN
SET @payload=JSON_MODIFY(@payload,'$.relationshipType',(SELECT TypeName FROM dbo.RelationshipTypes WHERE RelationshipTypeID=@relationshipType));
SET @payload=JSON_MODIFY(@payload,'$.relationshipState',(SELECT StateName FROM dbo.RelationshipStates WHERE RelationshipStateID=@relationshipState));
END;
IF @moduleName=N'Locations' SET @payload=JSON_MODIFY(@payload,'$.significance',JSON_QUERY(CONCAT(N'{"score":60,"keyScenes":[{"sceneID":',@scene,N',"chapterID":',@chapter,N',"bookID":',@book,N',"sceneLabel":"Chapter 雨","reasons":["Consequence Ω"]}],"extension":{"sceneID":777}}')));
IF @moduleName=N'Knowledge' SET @payload=JSON_MODIFY(@payload,'$.knowledgeStateName',(SELECT StateName FROM dbo.KnowledgeStates WHERE KnowledgeStateID=(SELECT MIN(KnowledgeStateID) FROM dbo.KnowledgeStates)));
WHILE @candidateIndex<=CASE WHEN @moduleName=N'Relationships' THEN 4 ELSE 3 END
BEGIN
SET @stableKey=CASE WHEN @moduleName=N'Relationships' THEN CASE WHEN @candidateIndex=4 THEN CONCAT(@character,N':',@observer) ELSE CONCAT(N'scene:',@scene,N':',@character,CASE WHEN @candidateIndex=3 THEN N':' ELSE N'>' END,@observer,N':Development:',REPLICATE(N'0',23),@candidateIndex) END WHEN @moduleName=N'Knowledge' THEN CONCAT(@character,N':knows:synthetic-proof-',@candidateIndex) ELSE CONCAT(LOWER(@moduleName),N'-Ω-',@candidateIndex) END;
IF @candidateIndex=1 SET @firstKey=@stableKey;
SET @candidatePayload=JSON_MODIFY(@payload,'$.key',@stableKey);
IF @moduleName=N'Relationships' SET @candidatePayload=JSON_MODIFY(@candidatePayload,'$.isReciprocal',CONVERT(bit,CASE WHEN @candidateIndex>=3 THEN 1 ELSE 0 END));
INSERT dbo.StoryIntelligenceReviewCandidates(ReviewCandidateGenerationID,ProjectID,BookID,Module,StableKey,CandidateType,DisplayName,SortOrder,Confidence,ExistingCanonicalID,DecisionStatus,DecisionAction,DecisionTargetKey,DecisionCanonicalID,CandidatePayloadJson,ReviewedUtc,ReviewPriority,AssessmentJson)
VALUES(@generation,@project,@book,@moduleName,@stableKey,N'Synthetic observation',CONCAT(@moduleName,N' decision 雨 ',@candidateIndex),@candidateIndex,.95,@canonicalID,CASE @candidateIndex WHEN 1 THEN N'Pending' WHEN 2 THEN N'Reviewed' WHEN 4 THEN N'Reviewed' ELSE N'AutoAccepted' END,CASE WHEN @candidateIndex=1 THEN NULL ELSE N'LinkExisting' END,CASE WHEN @candidateIndex=3 THEN @firstKey ELSE NULL END,CASE WHEN @candidateIndex=1 THEN NULL ELSE @canonicalID END,@candidatePayload,CASE WHEN @candidateIndex=1 THEN NULL ELSE CONVERT(datetime2,'2026-11-03') END,CASE @candidateIndex WHEN 1 THEN N'Attention' WHEN 2 THEN N'Optional' ELSE N'Tracked' END,N'{"Priority":"Attention","Reasons":["Evidence Ω"],"extension":{"sceneID":777}}');
SET @candidate=SCOPE_IDENTITY();
INSERT dbo.StoryIntelligenceReviewCandidateEvidence(ReviewCandidateID,SceneID,EvidenceText,Confidence,SortOrder) VALUES(@candidate,@scene,CONCAT(N'Persisted compact evidence 雨 ',@moduleName),.95,@candidateIndex);
IF @candidateIndex=2 AND @moduleName=N'Knowledge' UPDATE dbo.CharacterKnowledge SET SourceReviewKey=@stableKey WHERE CharacterKnowledgeID=@knowledgeID;
IF @candidateIndex=2 AND @moduleName=N'Relationships' UPDATE dbo.RelationshipEvents SET SourceReviewKey=@stableKey WHERE CharacterRelationshipID=@relationship;
SET @candidateIndex+=1;
END;
SET @moduleIndex+=1;
END;
-- Account-wide workflow/consent/job state is retained live, not portable author content.
DECLARE @onboardingState int,@consent int;
INSERT dbo.UserOnboardingState(UserID,ProjectID,BookID) VALUES(@user,@project,@book);
SET @onboardingState=SCOPE_IDENTITY();
INSERT dbo.StoryIntelligenceConsents(UserID,UserOnboardingStateID,ProjectID,BookID,ConsentText)
VALUES(@user,@onboardingState,@project,@book,N'Synthetic fixture consent audit; no human consent or external analysis is performed. 雨');
SET @consent=SCOPE_IDENTITY();
INSERT dbo.StoryIntelligenceJobs(StoryIntelligenceJobID,StoryIntelligenceConsentID,UserID,ProjectID,BookID,Status,StartedUtc,CompletedUtc,ProgressPercent,CurrentStage,CurrentMessage)
VALUES(NEWID(),@consent,@user,@project,@book,N'Completed','2026-11-01','2026-11-02',100,N'Completed',N'Synthetic completed operational audit Ω');
INSERT dbo.ProjectActivity(ProjectID,UserID,ActivityType,EntityType,EntityID,EntityName,Description) VALUES(@project,@user,N'Updated',N'Book',@book,N'Synthetic book Ω',N'Retained synthetic activity audit 雨');
DECLARE @enrichment int;
INSERT dbo.CharacterEnrichmentRuns(ProjectID,BookID,UserID,CharacterID,StoryIntelligenceBookPipelineID,CharacterResolutionVersion,Status,TotalCharacters,ProcessedCharacters,CurrentStage,CurrentMessage,StartedUtc,CompletedUtc,AttemptCount,Model,InputTokens,OutputTokens,TotalTokens,DurationMs,IsCurrent)
VALUES(@project,@book,@user,@character,@pipeline,N'synthetic-enrichment-v1',N'Completed',1,1,N'Completed',N'Synthetic enrichment evidence retained Ω','2026-11-01','2026-11-02',2,N'synthetic-no-provider',150,50,200,2500,1);
SET @enrichment=SCOPE_IDENTITY();
INSERT dbo.CharacterEnrichmentEvidence(CharacterEnrichmentRunID,CharacterID,SceneID,FieldName,Value,Evidence,Confidence,Source)
VALUES(@enrichment,@character,@scene,N'EyeColour',N'Grey',N'“Grey eyes”—source evidence 雨',.95,N'Synthetic source'),(@enrichment,@character,NULL,N'Role',N'Narrator Ω',N'Book-wide source evidence café',.8,N'Synthetic book context');
INSERT dbo.CharacterEnrichmentRuns(ProjectID,BookID,UserID,StoryIntelligenceBookPipelineID,CharacterResolutionVersion,Status,TotalCharacters,ProcessedCharacters,CurrentStage,CurrentMessage,StartedUtc,FailedUtc,AttemptCount,Model,ErrorMessage,ErrorDetail,IsCurrent)
VALUES(@project,@book,@user,@pipeline,N'synthetic-enrichment-failed',N'Failed',2,0,N'Failed',N'Synthetic prior failure audit','2026-10-01','2026-10-01',1,N'synthetic-no-provider',N'Synthetic error Ω',N'{"error":"Synthetic retained failure 雨"}',0);