Preserve retained analysis source and result audit in project backups

This commit is contained in:
Nick Beckley 2026-11-04 03:15:09 +00:00
parent 379aad34d1
commit 1467a61718
11 changed files with 786 additions and 14 deletions

View File

@ -114,10 +114,10 @@ SceneTextStatistics,ProjectID or FK descendant,SceneTextStatistics,Persistent sc
SceneWorkflow,ProjectID or FK descendant,SceneWorkflow,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated
StoryAssets,ProjectID or FK descendant,StoryAssets,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,"Version 1.3: exact active file bytes, independent paths, checksums, ledger owner/size, quota refusal and rollback verified; deleted gallery metadata retained without absent deleted files"
StoryIntelligenceBookPipelines,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending
StoryIntelligenceChapterResults,ProjectID or FK descendant,,Pending classification,Pending,Pending
StoryIntelligenceChapterResults,ProjectID or FK descendant,StoryIntelligenceChapterResults,Retained analysis source/results and import audit; full stored fields serialized,Pass: exact long raw JSON/source; copy canonical/run/actor refs; in-place; old snapshot and active-analysis refusal,Raw JSON is historical audit and is not parsed/rebuilt during backup; unfinished copied runs cancelled; review/pipeline graph separate pending scope
StoryIntelligenceConsents,ProjectID or FK descendant,,Pending classification,Pending,Pending
StoryIntelligenceIllustrationDemands,ProjectID or FK descendant,,Pending classification,Pending,Pending
StoryIntelligenceImportCommits,ProjectID or FK descendant,,Pending classification,Pending,Pending
StoryIntelligenceImportCommits,ProjectID or FK descendant,StoryIntelligenceImportCommits,Retained analysis source/results and import audit; full stored fields serialized,Pass: exact long raw JSON/source; copy canonical/run/actor refs; in-place; old snapshot and active-analysis refusal,Raw JSON is historical audit and is not parsed/rebuilt during backup; unfinished copied runs cancelled; review/pipeline graph separate pending scope
StoryIntelligenceJobs,ProjectID or FK descendant,,Pending classification,Pending,Pending
StoryIntelligenceNarrativeCandidateEvents,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending
StoryIntelligenceNarrativeCandidateEvidence,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending
@ -125,8 +125,8 @@ StoryIntelligenceNarrativeCandidates,ProjectID or FK descendant,,Persisted SI so
StoryIntelligenceReviewCandidateEvidence,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending
StoryIntelligenceReviewCandidateGenerations,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending
StoryIntelligenceReviewCandidates,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending
StoryIntelligenceRuns,ProjectID or FK descendant,,Pending classification,Pending,Pending
StoryIntelligenceSceneResults,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending
StoryIntelligenceRuns,ProjectID or FK descendant,StoryIntelligenceRuns,Retained analysis source/results and import audit; full stored fields serialized,Pass: exact long raw JSON/source; copy canonical/run/actor refs; in-place; old snapshot and active-analysis refusal,Raw JSON is historical audit and is not parsed/rebuilt during backup; unfinished copied runs cancelled; review/pipeline graph separate pending scope
StoryIntelligenceSceneResults,ProjectID or FK descendant,StoryIntelligenceSceneResults,Retained analysis source/results and import audit; full stored fields serialized,Pass: exact long raw JSON/source; copy canonical/run/actor refs; in-place; old snapshot and active-analysis refusal,Raw JSON is historical audit and is not parsed/rebuilt during backup; unfinished copied runs cancelled; review/pipeline graph separate pending scope
StoryMaps,ProjectID or FK descendant,StoryMaps,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated
StoryMemoryAssets,ProjectID or FK descendant,,Pending classification,Pending,Pending
StoryMemoryCharacterAliases,ProjectID or FK descendant,,Pending classification,Pending,Pending

1 Table ProjectOwnershipEvidence BackupCollection Classification RestoreVerified AssetsVerified
114 SceneWorkflow ProjectID or FK descendant SceneWorkflow Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback External file bytes not covered; embedded/text/JSON values compared where populated
115 StoryAssets ProjectID or FK descendant StoryAssets Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback Version 1.3: exact active file bytes, independent paths, checksums, ledger owner/size, quota refusal and rollback verified; deleted gallery metadata retained without absent deleted files
116 StoryIntelligenceBookPipelines ProjectID or FK descendant Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending Pending Pending
117 StoryIntelligenceChapterResults ProjectID or FK descendant StoryIntelligenceChapterResults Pending classification Retained analysis source/results and import audit; full stored fields serialized Pending Pass: exact long raw JSON/source; copy canonical/run/actor refs; in-place; old snapshot and active-analysis refusal Pending Raw JSON is historical audit and is not parsed/rebuilt during backup; unfinished copied runs cancelled; review/pipeline graph separate pending scope
118 StoryIntelligenceConsents ProjectID or FK descendant Pending classification Pending Pending
119 StoryIntelligenceIllustrationDemands ProjectID or FK descendant Pending classification Pending Pending
120 StoryIntelligenceImportCommits ProjectID or FK descendant StoryIntelligenceImportCommits Pending classification Retained analysis source/results and import audit; full stored fields serialized Pending Pass: exact long raw JSON/source; copy canonical/run/actor refs; in-place; old snapshot and active-analysis refusal Pending Raw JSON is historical audit and is not parsed/rebuilt during backup; unfinished copied runs cancelled; review/pipeline graph separate pending scope
121 StoryIntelligenceJobs ProjectID or FK descendant Pending classification Pending Pending
122 StoryIntelligenceNarrativeCandidateEvents ProjectID or FK descendant Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending Pending Pending
123 StoryIntelligenceNarrativeCandidateEvidence ProjectID or FK descendant Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending Pending Pending
125 StoryIntelligenceReviewCandidateEvidence ProjectID or FK descendant Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending Pending Pending
126 StoryIntelligenceReviewCandidateGenerations ProjectID or FK descendant Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending Pending Pending
127 StoryIntelligenceReviewCandidates ProjectID or FK descendant Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending Pending Pending
128 StoryIntelligenceRuns ProjectID or FK descendant StoryIntelligenceRuns Pending classification Retained analysis source/results and import audit; full stored fields serialized Pending Pass: exact long raw JSON/source; copy canonical/run/actor refs; in-place; old snapshot and active-analysis refusal Pending Raw JSON is historical audit and is not parsed/rebuilt during backup; unfinished copied runs cancelled; review/pipeline graph separate pending scope
129 StoryIntelligenceSceneResults ProjectID or FK descendant StoryIntelligenceSceneResults Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending Retained analysis source/results and import audit; full stored fields serialized Pending Pass: exact long raw JSON/source; copy canonical/run/actor refs; in-place; old snapshot and active-analysis refusal Pending Raw JSON is historical audit and is not parsed/rebuilt during backup; unfinished copied runs cancelled; review/pipeline graph separate pending scope
130 StoryMaps ProjectID or FK descendant StoryMaps Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback External file bytes not covered; embedded/text/JSON values compared where populated
131 StoryMemoryAssets ProjectID or FK descendant Pending classification Pending Pending
132 StoryMemoryCharacterAliases ProjectID or FK descendant Pending classification Pending Pending

View File

@ -851,6 +851,104 @@ StoryAssets,StoryAssets,CreatedDateUTC,datetime2,True,False,True,Represented; pr
StoryAssets,StoryAssets,ModifiedDateUTC,datetime2,True,False,True,Represented; projection and semantic comparison still required
StoryAssets,StoryAssets,ImagePath,nvarchar,True,False,True,Represented; projection and semantic comparison still required
StoryAssets,StoryAssets,ThumbnailPath,nvarchar,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,ChapterResultID,int,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,StoryIntelligenceRunID,int,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,ProjectID,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,BookID,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,ChapterID,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,ChapterNumber,decimal,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,SourceLabel,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,PromptVersion,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,Model,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,RawResponseJson,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,OutputTextJson,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,ParsedJson,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,ValidationErrorsCount,int,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,ValidationWarningsCount,int,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,InputTokens,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,OutputTokens,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,TotalTokens,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,DurationMs,bigint,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,CreatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceImportCommits,StoryIntelligenceImportCommits,StoryIntelligenceImportCommitID,int,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceImportCommits,StoryIntelligenceImportCommits,StoryIntelligenceRunID,int,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceImportCommits,StoryIntelligenceImportCommits,ProjectID,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceImportCommits,StoryIntelligenceImportCommits,BookID,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceImportCommits,StoryIntelligenceImportCommits,ChapterID,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceImportCommits,StoryIntelligenceImportCommits,CommittedAt,datetime2,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceImportCommits,StoryIntelligenceImportCommits,CommittedByUserID,int,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceImportCommits,StoryIntelligenceImportCommits,ScenesCreated,int,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceImportCommits,StoryIntelligenceImportCommits,MetricsCreated,int,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceImportCommits,StoryIntelligenceImportCommits,Status,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceImportCommits,StoryIntelligenceImportCommits,Notes,nvarchar,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceImportCommits,StoryIntelligenceImportCommits,CreatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,StoryIntelligenceRunID,int,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,UserID,int,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,ProjectID,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,BookID,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,Status,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,SourceType,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,PromptVersion,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,Model,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,StartedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,CompletedUtc,datetime2,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,TotalInputTokens,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,TotalOutputTokens,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,TotalTokens,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,TotalDurationMs,bigint,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,ErrorMessage,nvarchar,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,CreatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,UpdatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,SourceFileName,nvarchar,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,SourceFileSizeBytes,bigint,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,SourceWordCount,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,SourceCharacterCount,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,SourceChapterCount,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,SourceDetectedImagesCount,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,SourceDetectedTablesCount,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,SourceDetectedFootnotesCount,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,SourceDetectedCommentsCount,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,FailureStage,nvarchar,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,ErrorDetail,nvarchar,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,EstimatedCostGBP,decimal,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,EstimatedCostUSD,decimal,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,PromptVersionsSummary,nvarchar,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,SourceLabel,nvarchar,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,SourceText,nvarchar,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,CurrentStage,nvarchar,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,CurrentMessage,nvarchar,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,TotalDetectedScenes,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,CompletedScenes,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,FailedScenes,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,CancellationRequestedUtc,datetime2,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,CancelledUtc,datetime2,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,ChapterID,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,ChapterNumber,decimal,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,SourceParagraphCount,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceRuns,StoryIntelligenceRuns,KnownCharactersJson,nvarchar,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,SceneResultID,int,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,StoryIntelligenceRunID,int,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,ChapterResultID,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,ProjectID,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,BookID,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,ChapterID,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,SceneID,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,TemporarySceneNumber,int,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,StartParagraph,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,EndParagraph,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,SourceLabel,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,PromptVersion,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,Model,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,RawResponseJson,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,OutputTextJson,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,ParsedJson,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,ValidationErrorsCount,int,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,ValidationWarningsCount,int,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,InputTokens,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,OutputTokens,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,TotalTokens,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,DurationMs,bigint,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceSceneResults,StoryIntelligenceSceneResults,CreatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
StoryMaps,StoryMaps,MapID,int,False,False,True,Represented; projection and semantic comparison still required
StoryMaps,StoryMaps,ProjectID,int,False,False,True,Represented; projection and semantic comparison still required
StoryMaps,StoryMaps,ParentMapID,int,True,False,True,Represented; projection and semantic comparison still required

1 Table Collection Column SqlType Nullable Computed WritableModelProperty Classification
851 StoryAssets StoryAssets ModifiedDateUTC datetime2 True False True Represented; projection and semantic comparison still required
852 StoryAssets StoryAssets ImagePath nvarchar True False True Represented; projection and semantic comparison still required
853 StoryAssets StoryAssets ThumbnailPath nvarchar True False True Represented; projection and semantic comparison still required
854 StoryIntelligenceChapterResults StoryIntelligenceChapterResults ChapterResultID int False False True Represented; projection and semantic comparison still required
855 StoryIntelligenceChapterResults StoryIntelligenceChapterResults StoryIntelligenceRunID int False False True Represented; projection and semantic comparison still required
856 StoryIntelligenceChapterResults StoryIntelligenceChapterResults ProjectID int True False True Represented; projection and semantic comparison still required
857 StoryIntelligenceChapterResults StoryIntelligenceChapterResults BookID int True False True Represented; projection and semantic comparison still required
858 StoryIntelligenceChapterResults StoryIntelligenceChapterResults ChapterID int True False True Represented; projection and semantic comparison still required
859 StoryIntelligenceChapterResults StoryIntelligenceChapterResults ChapterNumber decimal True False True Represented; projection and semantic comparison still required
860 StoryIntelligenceChapterResults StoryIntelligenceChapterResults SourceLabel nvarchar False False True Represented; projection and semantic comparison still required
861 StoryIntelligenceChapterResults StoryIntelligenceChapterResults PromptVersion nvarchar False False True Represented; projection and semantic comparison still required
862 StoryIntelligenceChapterResults StoryIntelligenceChapterResults Model nvarchar False False True Represented; projection and semantic comparison still required
863 StoryIntelligenceChapterResults StoryIntelligenceChapterResults RawResponseJson nvarchar False False True Represented; projection and semantic comparison still required
864 StoryIntelligenceChapterResults StoryIntelligenceChapterResults OutputTextJson nvarchar False False True Represented; projection and semantic comparison still required
865 StoryIntelligenceChapterResults StoryIntelligenceChapterResults ParsedJson nvarchar False False True Represented; projection and semantic comparison still required
866 StoryIntelligenceChapterResults StoryIntelligenceChapterResults ValidationErrorsCount int False False True Represented; projection and semantic comparison still required
867 StoryIntelligenceChapterResults StoryIntelligenceChapterResults ValidationWarningsCount int False False True Represented; projection and semantic comparison still required
868 StoryIntelligenceChapterResults StoryIntelligenceChapterResults InputTokens int True False True Represented; projection and semantic comparison still required
869 StoryIntelligenceChapterResults StoryIntelligenceChapterResults OutputTokens int True False True Represented; projection and semantic comparison still required
870 StoryIntelligenceChapterResults StoryIntelligenceChapterResults TotalTokens int True False True Represented; projection and semantic comparison still required
871 StoryIntelligenceChapterResults StoryIntelligenceChapterResults DurationMs bigint True False True Represented; projection and semantic comparison still required
872 StoryIntelligenceChapterResults StoryIntelligenceChapterResults CreatedUtc datetime2 False False True Represented; projection and semantic comparison still required
873 StoryIntelligenceImportCommits StoryIntelligenceImportCommits StoryIntelligenceImportCommitID int False False True Represented; projection and semantic comparison still required
874 StoryIntelligenceImportCommits StoryIntelligenceImportCommits StoryIntelligenceRunID int False False True Represented; projection and semantic comparison still required
875 StoryIntelligenceImportCommits StoryIntelligenceImportCommits ProjectID int True False True Represented; projection and semantic comparison still required
876 StoryIntelligenceImportCommits StoryIntelligenceImportCommits BookID int True False True Represented; projection and semantic comparison still required
877 StoryIntelligenceImportCommits StoryIntelligenceImportCommits ChapterID int True False True Represented; projection and semantic comparison still required
878 StoryIntelligenceImportCommits StoryIntelligenceImportCommits CommittedAt datetime2 False False True Represented; projection and semantic comparison still required
879 StoryIntelligenceImportCommits StoryIntelligenceImportCommits CommittedByUserID int False False True Represented; projection and semantic comparison still required
880 StoryIntelligenceImportCommits StoryIntelligenceImportCommits ScenesCreated int False False True Represented; projection and semantic comparison still required
881 StoryIntelligenceImportCommits StoryIntelligenceImportCommits MetricsCreated int False False True Represented; projection and semantic comparison still required
882 StoryIntelligenceImportCommits StoryIntelligenceImportCommits Status nvarchar False False True Represented; projection and semantic comparison still required
883 StoryIntelligenceImportCommits StoryIntelligenceImportCommits Notes nvarchar True False True Represented; projection and semantic comparison still required
884 StoryIntelligenceImportCommits StoryIntelligenceImportCommits CreatedUtc datetime2 False False True Represented; projection and semantic comparison still required
885 StoryIntelligenceRuns StoryIntelligenceRuns StoryIntelligenceRunID int False False True Represented; projection and semantic comparison still required
886 StoryIntelligenceRuns StoryIntelligenceRuns UserID int False False True Represented; projection and semantic comparison still required
887 StoryIntelligenceRuns StoryIntelligenceRuns ProjectID int True False True Represented; projection and semantic comparison still required
888 StoryIntelligenceRuns StoryIntelligenceRuns BookID int True False True Represented; projection and semantic comparison still required
889 StoryIntelligenceRuns StoryIntelligenceRuns Status nvarchar False False True Represented; projection and semantic comparison still required
890 StoryIntelligenceRuns StoryIntelligenceRuns SourceType nvarchar False False True Represented; projection and semantic comparison still required
891 StoryIntelligenceRuns StoryIntelligenceRuns PromptVersion nvarchar False False True Represented; projection and semantic comparison still required
892 StoryIntelligenceRuns StoryIntelligenceRuns Model nvarchar False False True Represented; projection and semantic comparison still required
893 StoryIntelligenceRuns StoryIntelligenceRuns StartedUtc datetime2 False False True Represented; projection and semantic comparison still required
894 StoryIntelligenceRuns StoryIntelligenceRuns CompletedUtc datetime2 True False True Represented; projection and semantic comparison still required
895 StoryIntelligenceRuns StoryIntelligenceRuns TotalInputTokens int True False True Represented; projection and semantic comparison still required
896 StoryIntelligenceRuns StoryIntelligenceRuns TotalOutputTokens int True False True Represented; projection and semantic comparison still required
897 StoryIntelligenceRuns StoryIntelligenceRuns TotalTokens int True False True Represented; projection and semantic comparison still required
898 StoryIntelligenceRuns StoryIntelligenceRuns TotalDurationMs bigint True False True Represented; projection and semantic comparison still required
899 StoryIntelligenceRuns StoryIntelligenceRuns ErrorMessage nvarchar True False True Represented; projection and semantic comparison still required
900 StoryIntelligenceRuns StoryIntelligenceRuns CreatedUtc datetime2 False False True Represented; projection and semantic comparison still required
901 StoryIntelligenceRuns StoryIntelligenceRuns UpdatedUtc datetime2 False False True Represented; projection and semantic comparison still required
902 StoryIntelligenceRuns StoryIntelligenceRuns SourceFileName nvarchar True False True Represented; projection and semantic comparison still required
903 StoryIntelligenceRuns StoryIntelligenceRuns SourceFileSizeBytes bigint True False True Represented; projection and semantic comparison still required
904 StoryIntelligenceRuns StoryIntelligenceRuns SourceWordCount int True False True Represented; projection and semantic comparison still required
905 StoryIntelligenceRuns StoryIntelligenceRuns SourceCharacterCount int True False True Represented; projection and semantic comparison still required
906 StoryIntelligenceRuns StoryIntelligenceRuns SourceChapterCount int True False True Represented; projection and semantic comparison still required
907 StoryIntelligenceRuns StoryIntelligenceRuns SourceDetectedImagesCount int True False True Represented; projection and semantic comparison still required
908 StoryIntelligenceRuns StoryIntelligenceRuns SourceDetectedTablesCount int True False True Represented; projection and semantic comparison still required
909 StoryIntelligenceRuns StoryIntelligenceRuns SourceDetectedFootnotesCount int True False True Represented; projection and semantic comparison still required
910 StoryIntelligenceRuns StoryIntelligenceRuns SourceDetectedCommentsCount int True False True Represented; projection and semantic comparison still required
911 StoryIntelligenceRuns StoryIntelligenceRuns FailureStage nvarchar True False True Represented; projection and semantic comparison still required
912 StoryIntelligenceRuns StoryIntelligenceRuns ErrorDetail nvarchar True False True Represented; projection and semantic comparison still required
913 StoryIntelligenceRuns StoryIntelligenceRuns EstimatedCostGBP decimal True False True Represented; projection and semantic comparison still required
914 StoryIntelligenceRuns StoryIntelligenceRuns EstimatedCostUSD decimal True False True Represented; projection and semantic comparison still required
915 StoryIntelligenceRuns StoryIntelligenceRuns PromptVersionsSummary nvarchar True False True Represented; projection and semantic comparison still required
916 StoryIntelligenceRuns StoryIntelligenceRuns SourceLabel nvarchar True False True Represented; projection and semantic comparison still required
917 StoryIntelligenceRuns StoryIntelligenceRuns SourceText nvarchar True False True Represented; projection and semantic comparison still required
918 StoryIntelligenceRuns StoryIntelligenceRuns CurrentStage nvarchar True False True Represented; projection and semantic comparison still required
919 StoryIntelligenceRuns StoryIntelligenceRuns CurrentMessage nvarchar True False True Represented; projection and semantic comparison still required
920 StoryIntelligenceRuns StoryIntelligenceRuns TotalDetectedScenes int True False True Represented; projection and semantic comparison still required
921 StoryIntelligenceRuns StoryIntelligenceRuns CompletedScenes int True False True Represented; projection and semantic comparison still required
922 StoryIntelligenceRuns StoryIntelligenceRuns FailedScenes int True False True Represented; projection and semantic comparison still required
923 StoryIntelligenceRuns StoryIntelligenceRuns CancellationRequestedUtc datetime2 True False True Represented; projection and semantic comparison still required
924 StoryIntelligenceRuns StoryIntelligenceRuns CancelledUtc datetime2 True False True Represented; projection and semantic comparison still required
925 StoryIntelligenceRuns StoryIntelligenceRuns ChapterID int True False True Represented; projection and semantic comparison still required
926 StoryIntelligenceRuns StoryIntelligenceRuns ChapterNumber decimal True False True Represented; projection and semantic comparison still required
927 StoryIntelligenceRuns StoryIntelligenceRuns SourceParagraphCount int True False True Represented; projection and semantic comparison still required
928 StoryIntelligenceRuns StoryIntelligenceRuns KnownCharactersJson nvarchar True False True Represented; projection and semantic comparison still required
929 StoryIntelligenceSceneResults StoryIntelligenceSceneResults SceneResultID int False False True Represented; projection and semantic comparison still required
930 StoryIntelligenceSceneResults StoryIntelligenceSceneResults StoryIntelligenceRunID int False False True Represented; projection and semantic comparison still required
931 StoryIntelligenceSceneResults StoryIntelligenceSceneResults ChapterResultID int True False True Represented; projection and semantic comparison still required
932 StoryIntelligenceSceneResults StoryIntelligenceSceneResults ProjectID int True False True Represented; projection and semantic comparison still required
933 StoryIntelligenceSceneResults StoryIntelligenceSceneResults BookID int True False True Represented; projection and semantic comparison still required
934 StoryIntelligenceSceneResults StoryIntelligenceSceneResults ChapterID int True False True Represented; projection and semantic comparison still required
935 StoryIntelligenceSceneResults StoryIntelligenceSceneResults SceneID int True False True Represented; projection and semantic comparison still required
936 StoryIntelligenceSceneResults StoryIntelligenceSceneResults TemporarySceneNumber int False False True Represented; projection and semantic comparison still required
937 StoryIntelligenceSceneResults StoryIntelligenceSceneResults StartParagraph int True False True Represented; projection and semantic comparison still required
938 StoryIntelligenceSceneResults StoryIntelligenceSceneResults EndParagraph int True False True Represented; projection and semantic comparison still required
939 StoryIntelligenceSceneResults StoryIntelligenceSceneResults SourceLabel nvarchar False False True Represented; projection and semantic comparison still required
940 StoryIntelligenceSceneResults StoryIntelligenceSceneResults PromptVersion nvarchar False False True Represented; projection and semantic comparison still required
941 StoryIntelligenceSceneResults StoryIntelligenceSceneResults Model nvarchar False False True Represented; projection and semantic comparison still required
942 StoryIntelligenceSceneResults StoryIntelligenceSceneResults RawResponseJson nvarchar False False True Represented; projection and semantic comparison still required
943 StoryIntelligenceSceneResults StoryIntelligenceSceneResults OutputTextJson nvarchar False False True Represented; projection and semantic comparison still required
944 StoryIntelligenceSceneResults StoryIntelligenceSceneResults ParsedJson nvarchar False False True Represented; projection and semantic comparison still required
945 StoryIntelligenceSceneResults StoryIntelligenceSceneResults ValidationErrorsCount int False False True Represented; projection and semantic comparison still required
946 StoryIntelligenceSceneResults StoryIntelligenceSceneResults ValidationWarningsCount int False False True Represented; projection and semantic comparison still required
947 StoryIntelligenceSceneResults StoryIntelligenceSceneResults InputTokens int True False True Represented; projection and semantic comparison still required
948 StoryIntelligenceSceneResults StoryIntelligenceSceneResults OutputTokens int True False True Represented; projection and semantic comparison still required
949 StoryIntelligenceSceneResults StoryIntelligenceSceneResults TotalTokens int True False True Represented; projection and semantic comparison still required
950 StoryIntelligenceSceneResults StoryIntelligenceSceneResults DurationMs bigint True False True Represented; projection and semantic comparison still required
951 StoryIntelligenceSceneResults StoryIntelligenceSceneResults CreatedUtc datetime2 False False True Represented; projection and semantic comparison still required
952 StoryMaps StoryMaps MapID int False False True Represented; projection and semantic comparison still required
953 StoryMaps StoryMaps ProjectID int False False True Represented; projection and semantic comparison still required
954 StoryMaps StoryMaps ParentMapID int True False True Represented; projection and semantic comparison still required

View File

@ -1,4 +1,8 @@
Collection,SourceRows,CopyRows,InPlaceRows,Verification
StoryIntelligenceRuns,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
StoryIntelligenceChapterResults,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
StoryIntelligenceSceneResults,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
StoryIntelligenceImportCommits,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
CoreImportBasicLocationReviews,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
CoreImportBasicLocationCandidates,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
CoreImportBasicLocationEvidence,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present

1 Collection SourceRows CopyRows InPlaceRows Verification
2 StoryIntelligenceRuns 1 1 1 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
3 StoryIntelligenceChapterResults 1 1 1 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
4 StoryIntelligenceSceneResults 1 1 1 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
5 StoryIntelligenceImportCommits 1 1 1 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
6 CoreImportBasicLocationReviews 1 1 1 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
7 CoreImportBasicLocationCandidates 1 1 1 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
8 CoreImportBasicLocationEvidence 1 1 1 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present

View File

@ -16,8 +16,8 @@
2. COMPLETE: Writer/shared surface spacing, requested icon changes, Locations conventional commands/grips, mobile Chapter table repair and rendered coverage inventory (9d78a63, 016b58f, 869e305).
3. DEFERRED ACCEPTANCE: authenticated live Writer/PWA testing; no session is available. Real full-layout browser/Hub fixture results are recorded separately.
4. DEFERRED DEPLOYMENT: two illustration records were Generating at restart preflight. No interruption authorised; expanded gate b523a86 refuses restart. Recheck only at the next meaningful deployment checkpoint.
5. COMPLETE CHECKPOINT: serialized backup/restore coverage now has 80 collections (76 persistent plus 4 diagnostic/shared vocabulary), 81 SQL entities / 948 columns with no missing non-computed model properties. All 76 persistent collections have populated stored-value copy/in-place comparisons; 12 uploaded files and embedded map image bytes are verified. Commits f12ad43, dbb2e2d, 6ae3715, 571f670, 28397ff.
6. CURRENT: HTTP Import/Export transport and workflow/format inventory. Reproduced 5 MiB carried-forward JSON rejection across three POST actions; per-field limit repair under HTTP verification. Eight HTTP/SQL export packets and five formats/aliases passed; expanded legacy JSON verification passed. Word structure API and Core Import SQL/source/provenance workflows now pass; next: remaining persistent project review data.
5. COMPLETE CHECKPOINT: serialized backup/restore coverage now has 84 collections (80 persistent plus 4 diagnostic/shared vocabulary), 85 SQL entities / 1,046 columns with no missing non-computed model properties. All 80 persistent collections have populated stored-value copy/in-place comparisons; 12 uploaded files and embedded map image bytes are verified. Commits f12ad43, dbb2e2d, 6ae3715, 571f670, 28397ff.
6. CURRENT: remaining persistent SI pipeline/memory/review and illustration graphs. HTTP JSON transport repair, 40 packet/format cases, legacy JSON, Word structure API and Core Import SQL/source/provenance workflows passed. Retained SI analysis audit now passes isolated stored-value copy/in-place tests.
7. PENDING: remaining persistent table classification and historical fixture discovery. Unrepresented SI review/audit/provenance is persistent under its runtime contract, not an expendable cache; project-derived illustration catalogue/files also remain outside verified backup coverage. Do not claim a complete 167-table audit.
8. PENDING: finish independently safe data gaps and meaningful format round trips; record concrete limits/deferred work. No historical compatibility claim without actual fixtures.
9. PENDING: final serial build/harness and focused browser/integration checks; meaningful restart-gate recheck, safe Development deployment if idle, concise handover.
@ -246,3 +246,13 @@ Inventory classification now explicitly separates shared vocabularies/name datas
## Restart-gate checkpoint and active-state repair — 4 November
At commit a37f1c8 the read-only Development gate still refused restart because illustration generation is queued/active. No Development writes, cancellation or restart. Subsequent SI source review found that the gate's generic Pending/Running list omitted actual job stage statuses and the pipeline InProgress status. The read-only gate now includes all nine StoryIntelligenceJob.IsActive states and InProgress; checked mechanically against the model definition. No repeat live inspection is needed while the existing illustration blocker remains.
## Retained SI analysis source/results and import audit — 4 November
Confirmed four omitted persistent sets: analysis runs, chapter results, scene results and import commits. Migration 223 now exports their complete stored projections (including long source/raw/parsed JSON, usage/cost metadata, timings and provenance), scopes older runs through Book/Chapter when ProjectID is null, and restores their graph transactionally. Copy remaps operational canonical/run/result/actor links and retains raw audit JSON exactly, including original embedded source IDs as historical audit. Scene.ImportRunID now follows the copied retained run rather than being detached when the run is available. Older backups without retained runs keep the existing detached-copy behaviour. No review GET reconstruction was introduced.
Unfinished copied analysis becomes cancelled audit history with an explicit warning; no paid provider runs. Restore refuses active current runs, unfinished snapshot runs/materialization and old-shaped snapshots missing any existing audit collection. Tests removed each of the four collections independently, verified source/raw JSON remains exact on refusal, rejected an unfinished snapshot, verified a cancelled copied history and refused replacement of a current Running run (synthetic status reset in finally). Three new invalid run/scene reference previews also fail before allocation.
Final real SQL matrix: 84 serialized collections; all 80 persistent collections populated; source 1,331 stored values across 83 populated entities, copy 1,290, in-place 1,295. Field census 85 entities / 1,046 columns / zero missing non-computed model properties. Build zero warnings/errors. Evidence `/tmp/plotdirector-phase2-si-audit-before.log`, `si-audit-after.log`, `build-si-audit-guards.log`, `census-si-audit.log` (all `/tmp/plotdirector-phase2-` prefix). Pipeline/memory/review/consent/illustration graphs remain unrepresented; this is not a complete SI or 167-table claim. No Development writes/deployment.
SI audit checkpoint: all 405 broad regression checks passed, exit 0 (`/tmp/plotdirector-phase2-tests-si-audit.log`). Additional focused coverage passed after the final test-only build: legacy run scope through ChapterID with null ProjectID/BookID; independent unfinished materialization snapshot refusal; both run and commit cancelled on copy (`/tmp/plotdirector-phase2-si-audit-scope.log`).

View File

@ -114,3 +114,17 @@ VALUES(@locationReview,N'synthetic-location-Ω',N'Room detected 雨',N'Room appr
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;

View File

@ -43,7 +43,7 @@ internal static class ProjectTransferDatabaseTests
}
if(applyMigrations)
{
foreach(var file in new[]{"PlotLine/Sql/213_ProjectBackupBookContext.sql","PlotLine/Sql/214_ProjectBackupPersistentSourceState.sql","PlotLine/Sql/215_ProjectBackupMapStoredMetadata.sql","PlotLine/Sql/216_ProjectBackupCompanionSceneLinks.sql","PlotLine/Sql/217_ProjectBackupUploadedFiles.sql","PlotLine/Sql/218_ImportSharedAssetStateLookups.sql","PlotLine/Sql/219_WordManuscriptImportCurrentSceneModel.sql","PlotLine/Sql/220_ProjectBackupCoreBuildProvenance.sql","PlotLine/Sql/221_ProjectBackupSceneReviewState.sql","PlotLine/Sql/222_ProjectBackupCoreLocationReview.sql"})
foreach(var file in new[]{"PlotLine/Sql/213_ProjectBackupBookContext.sql","PlotLine/Sql/214_ProjectBackupPersistentSourceState.sql","PlotLine/Sql/215_ProjectBackupMapStoredMetadata.sql","PlotLine/Sql/216_ProjectBackupCompanionSceneLinks.sql","PlotLine/Sql/217_ProjectBackupUploadedFiles.sql","PlotLine/Sql/218_ImportSharedAssetStateLookups.sql","PlotLine/Sql/219_WordManuscriptImportCurrentSceneModel.sql","PlotLine/Sql/220_ProjectBackupCoreBuildProvenance.sql","PlotLine/Sql/221_ProjectBackupSceneReviewState.sql","PlotLine/Sql/222_ProjectBackupCoreLocationReview.sql","PlotLine/Sql/223_ProjectBackupAnalysisAudit.sql"})
foreach(var batch in System.Text.RegularExpressions.Regex.Split(await File.ReadAllTextAsync(file), @"^\s*GO\s*$", System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.IgnoreCase))
if(!string.IsNullOrWhiteSpace(batch)) await db.ExecuteAsync(batch,commandTimeout:180);
Console.WriteLine("Applied required migrations to the verified synthetic database only.");
@ -156,8 +156,12 @@ internal static class ProjectTransferDatabaseTests
await db.ExecuteAsync("UPDATE dbo.SceneAttachments SET FilePath=@attachment WHERE SceneID=@scene;INSERT dbo.SceneAttachments(SceneID,SceneAttachmentTypeID,Title,FilePath) SELECT @scene,MIN(SceneAttachmentTypeID),N'Empty text attachment',@emptyAttachment FROM dbo.SceneAttachmentTypes",new{scene,attachment,emptyAttachment});
var before=(await backups.GetProjectBackupAsync(project,user))!;
await assetFiles.CaptureAsync(before);Check(before.Project is not null,"Fixture project exported.");
var retainedRun=before.Data.StoryIntelligenceRuns.Single();
await db.ExecuteAsync("UPDATE dbo.StoryIntelligenceRuns SET ProjectID=NULL,BookID=NULL WHERE StoryIntelligenceRunID=@id",new{id=retainedRun.StoryIntelligenceRunID});
try { Check((await backups.GetProjectBackupAsync(project,user))!.Data.StoryIntelligenceRuns.Any(run=>run.StoryIntelligenceRunID==retainedRun.StoryIntelligenceRunID),"Legacy analysis remains scoped through its chapter when ProjectID and BookID are null."); }
finally { await db.ExecuteAsync("UPDATE dbo.StoryIntelligenceRuns SET ProjectID=@project,BookID=@book WHERE StoryIntelligenceRunID=@id",new{project,book,id=retainedRun.StoryIntelligenceRunID}); }
using(var encoded=JsonDocument.Parse(JsonSerializer.Serialize(before)))
foreach(var required in new[]{"SceneAssetSuggestions","SceneCharacterSuggestions","SceneLocationSuggestions","SceneTextStatistics","CoreImportBasicLocationReviews","CoreImportBasicLocationCandidates","CoreImportBasicLocationEvidence"})
foreach(var required in new[]{"SceneAssetSuggestions","SceneCharacterSuggestions","SceneLocationSuggestions","SceneTextStatistics","CoreImportBasicLocationReviews","CoreImportBasicLocationCandidates","CoreImportBasicLocationEvidence","StoryIntelligenceRuns","StoryIntelligenceChapterResults","StoryIntelligenceSceneResults","StoryIntelligenceImportCommits"})
Check(encoded.RootElement.GetProperty("Data").TryGetProperty(required,out var rows) && rows.GetArrayLength()>0,"Backup must retain populated review/statistics set: "+required);
await VerifyStoredProjectionAsync(db,before);
Check(before.Data.Books.Single().BookTitle=="Book Ω" && before.Data.Scenes.Single(x=>x.SceneTitle=="Scene café").Summary=="“Hello”—雪 🖋","Core Unicode export content.");
@ -200,6 +204,9 @@ internal static class ProjectTransferDatabaseTests
root=>root["Data"]!["StoryMaps"]![0]!["ParentMapID"]=-1,
root=>root["Data"]!["MapFeatures"]![0]!["MapID"]=-1,
root=>root["Data"]!["Scenes"]![0]!["ChapterID"]=-12345,
root=>root["Data"]!["Scenes"]![0]!["ImportRunID"]=-12345,
root=>root["Data"]!["StoryIntelligenceSceneResults"]![0]!["StoryIntelligenceRunID"]=-12345,
root=>root["Data"]!["StoryIntelligenceSceneResults"]![0]!["SceneID"]=-12345,
root=>root["Data"]!["MapReferenceImages"]![0]!["ImageData"]="",
root=>root["Data"]!["TimelineViewPresets"]![0]!["FocusID"]=-12345,
root=>root["Data"]!["TimelineViewPresets"]![0]!["FilterJson"]="{\"SceneFromID\":-12345}",
@ -311,6 +318,34 @@ internal static class ProjectTransferDatabaseTests
var pointService=new ProjectRestorePointService(new ProjectRepository(factory),exportService,pointRepository,NullLogger<ProjectRestorePointService>.Instance);
var restoreService=new ProjectRestoreService(pointRepository,pointService,NullLogger<ProjectRestoreService>.Instance,assetFiles);
var savedPoint=(await pointService.CreateManualAsync(project,"Synthetic baseline","Round-trip fixture"))!;
foreach(var omitted in new[]{"StoryIntelligenceRuns","StoryIntelligenceChapterResults","StoryIntelligenceSceneResults","StoryIntelligenceImportCommits"})
{
var older=System.Text.Json.Nodes.JsonNode.Parse(JsonSerializer.Serialize(before))!;
older["Data"]!.AsObject().Remove(omitted);
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=older.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Older snapshot erased retained analysis audit."); }
catch(SqlException error) when(error.Number==51011) { }
Check(await db.ExecuteScalarAsync<string>("SELECT RawResponseJson FROM dbo.StoryIntelligenceSceneResults WHERE SceneResultID=@id",new{id=before.Data.StoryIntelligenceSceneResults.Single().SceneResultID})==before.Data.StoryIntelligenceSceneResults.Single().RawResponseJson,"Refused restore retains raw audit JSON exactly.");
}
var unfinished=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!;
unfinished["Data"]!["StoryIntelligenceImportCommits"]![0]!["Status"]="Pending";
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=unfinished.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore reintroduced unfinished materialization."); }
catch(SqlException error) when(error.Number==51012) { }
unfinished["Data"]!["StoryIntelligenceRuns"]![0]!["Status"]="Pending";
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=unfinished.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore reintroduced unfinished paid analysis."); }
catch(SqlException error) when(error.Number==51012) { }
var unfinishedPreview=(await service.PreviewAsync(new(){JsonText=unfinished.ToJsonString()})).Preview!;
Check(unfinishedPreview.Validation.Warnings.Any(w=>w.Contains("cancelled audit history",StringComparison.Ordinal)),"Unfinished analysis copy warning is explicit.");
var cancelledCopy=await service.ImportAsync(new(){JsonText=unfinished.ToJsonString(),ConfirmImport=true,AcknowledgeWarnings=true,AllowDuplicateProjectTitle=true});
Check(cancelledCopy.Succeeded,"Unfinished analysis can be copied as inactive audit history.");
var cancelledAudit=(await backups.GetProjectBackupAsync(cancelledCopy.ProjectID!.Value,importingUser))!;
Check(cancelledAudit.Data.StoryIntelligenceRuns.Single().Status=="Cancelled" && cancelledAudit.Data.StoryIntelligenceImportCommits.Single().Status=="Cancelled" && cancelledAudit.Data.StoryIntelligenceSceneResults.Single().RawResponseJson==before.Data.StoryIntelligenceSceneResults.Single().RawResponseJson,"Copied analysis/materialization is cancelled and retained raw JSON remains exact historical audit.");
await db.ExecuteAsync("UPDATE dbo.StoryIntelligenceRuns SET Status=N'Running' WHERE StoryIntelligenceRunID=@id",new{id=before.Data.StoryIntelligenceRuns.Single().StoryIntelligenceRunID});
try
{
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=sourceJson},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore replaced active analysis."); }
catch(SqlException error) when(error.Number==51012) { }
}
finally { await db.ExecuteAsync("UPDATE dbo.StoryIntelligenceRuns SET Status=N'Completed' WHERE StoryIntelligenceRunID=@id",new{id=before.Data.StoryIntelligenceRuns.Single().StoryIntelligenceRunID}); }
foreach(var omitted in new[]{"CoreImportBasicLocationReviews","CoreImportBasicLocationCandidates","CoreImportBasicLocationEvidence"})
{
var older=System.Text.Json.Nodes.JsonNode.Parse(JsonSerializer.Serialize(before))!;
@ -366,7 +401,7 @@ internal static class ProjectTransferDatabaseTests
coverage.Add($"{property.Name},{Count(before)},{Count(after)},{Count(sameProject)},{(diagnostic?"Diagnostic/shared vocabulary; excluded from portable restoration comparison":"Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present")}");
}
await File.WriteAllLinesAsync("Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv",coverage);
Console.WriteLine("PASS 76 populated persistent collections: copy/in-place stored values and actual safety/rollback; unrepresented project tables remain pending.");
Console.WriteLine("PASS 80 populated persistent collections: copy/in-place stored values and actual safety/rollback; unrepresented project tables remain pending.");
}
private static async Task VerifyStoredRoundTripAsync(SqlConnection db, ProjectBackupExport original, ProjectBackupExport restored, int? importingUser)
{
@ -409,8 +444,8 @@ internal static class ProjectTransferDatabaseTests
if(collection.Name is "OnboardingManuscriptBuilds" or "CoreImportBasicLocationReviews" && column=="PreviewID") {Check(!Equals(expected,actual),"Copied build preview identity must change");continue;}
if(collection.Name=="ManuscriptDocuments" && column=="DocumentGuid") {Check(!Equals(expected,actual),"Copy document GUID must change");continue;}
if(collection.Name=="ManuscriptDocuments" && column=="IsActive" || collection.Name is "Scenes" or "Chapters" && column=="IsLinkedToManuscript")expected=false;
if(collection.Name is "Scenes" or "Chapters" && column=="LinkedUtc" || collection.Name=="Scenes" && column=="ImportRunID")expected=null;
if(column is "CreatedByUserID" or "ModifiedByUserID" or "AcknowledgedByUserID" || column=="ReviewedByUserID" && expected is not null || collection.Name is "WritingPlans" or "OnboardingManuscriptBuilds" or "CoreImportBasicLocationReviews" && column=="UserID")expected=importingUser.Value;
if(collection.Name is "Scenes" or "Chapters" && column=="LinkedUtc")expected=null;
if(column is "CreatedByUserID" or "ModifiedByUserID" or "AcknowledgedByUserID" or "CommittedByUserID" || column=="ReviewedByUserID" && expected is not null || collection.Name is "WritingPlans" or "OnboardingManuscriptBuilds" or "CoreImportBasicLocationReviews" or "StoryIntelligenceRuns" && column=="UserID")expected=importingUser.Value;
if(collection.Name=="ThreadEvents" && column=="SourceKey" && expected is not null)expected=$"backup:{restored.Project.ProjectID}:{Read(collection.After[index],"ThreadEventID")}";
if(collection.Name=="ThreadEvents" && column=="SourceReferenceID")expected=null;
if(collection.Name=="StoryMaps" && column=="ReferenceJson")continue; // Exact placement/image identity asserted separately.
@ -419,7 +454,7 @@ internal static class ProjectTransferDatabaseTests
{
if(links.TryGetValue(column,out var target) && ids.TryGetValue((target,expected),out var mapped))expected=mapped;
else if(identities.GetValueOrDefault(collection.Table)==column && ids.TryGetValue((collection.Table,expected),out mapped))expected=mapped;
var semanticTarget=column switch {"BuildID"=>"OnboardingManuscriptBuilds","ProjectID"=>"Projects","BookID" or "InitialBookID"=>"Books","ChapterID" or "ProposedChapterID"=>"Chapters","SceneID" or "FromSceneID" or "ToSceneID" or "SourceSceneID" or "TargetSceneID" or "AgeReferenceSceneID"=>"Scenes","CharacterID" or "CharacterAID" or "CharacterBID" or "POVCharacterID"=>"Characters","StoryAssetID" or "AssetID" or "SourceAssetID" or "TargetAssetID"=>"StoryAssets","LocationID" or "FromLocationID" or "ToLocationID" or "EntryLocationID" or "ExitLocationID" or "ParentLocationID" or "CurrentLocationID" or "PrimaryLocationID"=>"Locations","MapID" or "ParentMapID"=>"StoryMaps","MetricTypeID"=>"SceneMetricTypes","AvatarSourceCharacterImageID"=>"CharacterImages","SourceEventID" or "PlotEventID"=>"ThreadEvents",_=>""};
var semanticTarget=column switch {"BuildID"=>"OnboardingManuscriptBuilds","ImportRunID"=>"StoryIntelligenceRuns","ProjectID"=>"Projects","BookID" or "InitialBookID"=>"Books","ChapterID" or "ProposedChapterID"=>"Chapters","SceneID" or "FromSceneID" or "ToSceneID" or "SourceSceneID" or "TargetSceneID" or "AgeReferenceSceneID"=>"Scenes","CharacterID" or "CharacterAID" or "CharacterBID" or "POVCharacterID"=>"Characters","StoryAssetID" or "AssetID" or "SourceAssetID" or "TargetAssetID"=>"StoryAssets","LocationID" or "FromLocationID" or "ToLocationID" or "EntryLocationID" or "ExitLocationID" or "ParentLocationID" or "CurrentLocationID" or "PrimaryLocationID"=>"Locations","MapID" or "ParentMapID"=>"StoryMaps","MetricTypeID"=>"SceneMetricTypes","AvatarSourceCharacterImageID"=>"CharacterImages","SourceEventID" or "PlotEventID"=>"ThreadEvents",_=>""};
var sourceValue=Read(collection.Before[index],column)!;
if(ids.TryGetValue((semanticTarget,sourceValue),out mapped))expected=mapped;
if(column=="EntityID" || collection.Name=="TimelineViewPresets" && column=="FocusID")

View File

@ -116,6 +116,11 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
data.CoreImportBasicLocationReviews = (await state.ReadAsync<ProjectBackupCoreImportBasicLocationReviews>()).ToList();
data.CoreImportBasicLocationCandidates = (await state.ReadAsync<ProjectBackupCoreImportBasicLocationCandidates>()).ToList();
data.CoreImportBasicLocationEvidence = (await state.ReadAsync<ProjectBackupCoreImportBasicLocationEvidence>()).ToList();
data.StoryIntelligenceRuns = (await state.ReadAsync<ProjectBackupStoryIntelligenceRuns>()).ToList();
data.StoryIntelligenceChapterResults = (await state.ReadAsync<ProjectBackupStoryIntelligenceChapterResults>()).ToList();
data.StoryIntelligenceSceneResults = (await state.ReadAsync<ProjectBackupStoryIntelligenceSceneResults>()).ToList();
data.StoryIntelligenceImportCommits = (await state.ReadAsync<ProjectBackupStoryIntelligenceImportCommits>()).ToList();
@ -157,6 +162,10 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
ProjectId = projectId,
IncludedEntitySets =
[
nameof(data.StoryIntelligenceRuns),
nameof(data.StoryIntelligenceChapterResults),
nameof(data.StoryIntelligenceSceneResults),
nameof(data.StoryIntelligenceImportCommits),
nameof(data.CoreImportBasicLocationReviews),
nameof(data.CoreImportBasicLocationCandidates),
nameof(data.CoreImportBasicLocationEvidence),

View File

@ -14,6 +14,11 @@ public sealed class ProjectBackupExport
public sealed class ProjectBackupData
{
public IReadOnlyList<ProjectBackupStoryIntelligenceRuns> StoryIntelligenceRuns { get; set; } = [];
public IReadOnlyList<ProjectBackupStoryIntelligenceChapterResults> StoryIntelligenceChapterResults { get; set; } = [];
public IReadOnlyList<ProjectBackupStoryIntelligenceSceneResults> StoryIntelligenceSceneResults { get; set; } = [];
public IReadOnlyList<ProjectBackupStoryIntelligenceImportCommits> StoryIntelligenceImportCommits { get; set; } = [];
public IReadOnlyList<ProjectBackupCoreImportBasicLocationReviews> CoreImportBasicLocationReviews { get; set; } = [];
public IReadOnlyList<ProjectBackupCoreImportBasicLocationCandidates> CoreImportBasicLocationCandidates { get; set; } = [];
public IReadOnlyList<ProjectBackupCoreImportBasicLocationEvidence> CoreImportBasicLocationEvidence { get; set; } = [];
@ -429,3 +434,117 @@ public sealed class ProjectBackupCoreImportBasicLocationEvidence
public string EvidenceText { get; set; } = "";
public int SortOrder { get; set; }
}
public sealed class ProjectBackupStoryIntelligenceRuns
{
public int StoryIntelligenceRunID { get; set; }
public int UserID { get; set; }
public int? ProjectID { get; set; }
public int? BookID { get; set; }
public string Status { get; set; } = "";
public string SourceType { get; set; } = "";
public string PromptVersion { get; set; } = "";
public string Model { get; set; } = "";
public DateTime StartedUtc { get; set; }
public DateTime? CompletedUtc { get; set; }
public int? TotalInputTokens { get; set; }
public int? TotalOutputTokens { get; set; }
public int? TotalTokens { get; set; }
public long? TotalDurationMs { get; set; }
public string? ErrorMessage { get; set; }
public DateTime CreatedUtc { get; set; }
public DateTime UpdatedUtc { get; set; }
public string? SourceFileName { get; set; }
public long? SourceFileSizeBytes { get; set; }
public int? SourceWordCount { get; set; }
public int? SourceCharacterCount { get; set; }
public int? SourceChapterCount { get; set; }
public int? SourceDetectedImagesCount { get; set; }
public int? SourceDetectedTablesCount { get; set; }
public int? SourceDetectedFootnotesCount { get; set; }
public int? SourceDetectedCommentsCount { get; set; }
public string? FailureStage { get; set; }
public string? ErrorDetail { get; set; }
public decimal? EstimatedCostGBP { get; set; }
public decimal? EstimatedCostUSD { get; set; }
public string? PromptVersionsSummary { get; set; }
public string? SourceLabel { get; set; }
public string? SourceText { get; set; }
public string? CurrentStage { get; set; }
public string? CurrentMessage { get; set; }
public int? TotalDetectedScenes { get; set; }
public int? CompletedScenes { get; set; }
public int? FailedScenes { get; set; }
public DateTime? CancellationRequestedUtc { get; set; }
public DateTime? CancelledUtc { get; set; }
public int? ChapterID { get; set; }
public decimal? ChapterNumber { get; set; }
public int? SourceParagraphCount { get; set; }
public string? KnownCharactersJson { get; set; }
}
public sealed class ProjectBackupStoryIntelligenceChapterResults
{
public int ChapterResultID { get; set; }
public int StoryIntelligenceRunID { get; set; }
public int? ProjectID { get; set; }
public int? BookID { get; set; }
public int? ChapterID { get; set; }
public decimal? ChapterNumber { get; set; }
public string SourceLabel { get; set; } = "";
public string PromptVersion { get; set; } = "";
public string Model { get; set; } = "";
public string RawResponseJson { get; set; } = "";
public string OutputTextJson { get; set; } = "";
public string ParsedJson { get; set; } = "";
public int ValidationErrorsCount { get; set; }
public int ValidationWarningsCount { get; set; }
public int? InputTokens { get; set; }
public int? OutputTokens { get; set; }
public int? TotalTokens { get; set; }
public long? DurationMs { get; set; }
public DateTime CreatedUtc { get; set; }
}
public sealed class ProjectBackupStoryIntelligenceSceneResults
{
public int SceneResultID { get; set; }
public int StoryIntelligenceRunID { get; set; }
public int? ChapterResultID { get; set; }
public int? ProjectID { get; set; }
public int? BookID { get; set; }
public int? ChapterID { get; set; }
public int? SceneID { get; set; }
public int TemporarySceneNumber { get; set; }
public int? StartParagraph { get; set; }
public int? EndParagraph { get; set; }
public string SourceLabel { get; set; } = "";
public string PromptVersion { get; set; } = "";
public string Model { get; set; } = "";
public string RawResponseJson { get; set; } = "";
public string OutputTextJson { get; set; } = "";
public string ParsedJson { get; set; } = "";
public int ValidationErrorsCount { get; set; }
public int ValidationWarningsCount { get; set; }
public int? InputTokens { get; set; }
public int? OutputTokens { get; set; }
public int? TotalTokens { get; set; }
public long? DurationMs { get; set; }
public DateTime CreatedUtc { get; set; }
}
public sealed class ProjectBackupStoryIntelligenceImportCommits
{
public int StoryIntelligenceImportCommitID { get; set; }
public int StoryIntelligenceRunID { get; set; }
public int? ProjectID { get; set; }
public int? BookID { get; set; }
public int? ChapterID { get; set; }
public DateTime CommittedAt { get; set; }
public int CommittedByUserID { get; set; }
public int ScenesCreated { get; set; }
public int MetricsCreated { get; set; }
public string Status { get; set; } = "";
public string? Notes { get; set; }
public DateTime CreatedUtc { get; set; }
}

View File

@ -350,6 +350,8 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
validation.Warnings.Add("Word manuscript links in an imported copy must be reconnected. Saved manuscript text is retained when present in the backup.");
if (backup.Data.ThreadEvents.Any(x => x.SourceKey is not null || x.SourceReferenceID.HasValue))
validation.Warnings.Add("Copied plot events receive new source identities and are detached from the original analysis review records.");
if(backup.Data.StoryIntelligenceRuns.Any(run=>run.Status is not ("Completed" or "CompletedWithWarnings" or "Failed" or "Cancelled")))
validation.Warnings.Add("Unfinished analysis will be copied as cancelled audit history. No paid analysis is restarted; retained source and raw result JSON remain historical audit data.");
if(backup.Data.OnboardingManuscriptBuilds.Any(build=>build.Status is not ("Built" or "Complete" or "Completed" or "Failed" or "Cancelled") || build.Status=="Built" && build.MarkerStatus is not ("UserConfirmedSave" or "Completed" or "Complete")))
validation.Warnings.Add("Unfinished Word import operations will be copied as cancelled history. They will not restart or send markers to the original document.");
if (backup.FormatVersion != "1.3" && ProjectBackupFiles.HasUploads(backup))
@ -839,7 +841,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
private static readonly string[] ProjectBackupIdentityTables =
[
"ProjectTimelineSettings", "TimelineViewPresets", "SceneMetricTypes", "Books", "Chapters", "Scenes", "StoryMaps",
"CoreImportBasicLocationReviews", "CoreImportBasicLocationCandidates", "CoreImportBasicLocationEvidence", "SceneAssetSuggestions", "SceneCharacterSuggestions", "SceneLocationSuggestions", "OnboardingManuscriptBuilds", "CharacterImages", "WordCompanionSceneAssets", "WordCompanionSceneLocations", "ManuscriptDocuments", "WritingPlans", "WritingScheduleItems", "CharacterAliases", "AssetAliases", "LocationAliases", "AuthorPlotSeeds", "ContinuityWarningAcknowledgements",
"StoryIntelligenceRuns", "StoryIntelligenceChapterResults", "StoryIntelligenceSceneResults", "StoryIntelligenceImportCommits", "CoreImportBasicLocationReviews", "CoreImportBasicLocationCandidates", "CoreImportBasicLocationEvidence", "SceneAssetSuggestions", "SceneCharacterSuggestions", "SceneLocationSuggestions", "OnboardingManuscriptBuilds", "CharacterImages", "WordCompanionSceneAssets", "WordCompanionSceneLocations", "ManuscriptDocuments", "WritingPlans", "WritingScheduleItems", "CharacterAliases", "AssetAliases", "LocationAliases", "AuthorPlotSeeds", "ContinuityWarningAcknowledgements",
"SceneOutcomes", "PlotLines", "PlotThreads", "ThreadEvents", "AssetStates", "StoryAssets", "AssetEvents",
"AssetDependencies", "AssetCustodyEvents", "AssetCustodyEventCharacters", "Characters", "SceneCharacters",
"CharacterAttributeTypes", "CharacterAttributeEvents", "CharacterKnowledge", "CharacterRelationships",
@ -997,6 +999,8 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
if (property?.CanWrite == true) property.SetValue(row, importingUserId);
}
}
// Reserve analysis identities before remapping scene provenance links.
foreach(var run in backup.Data.StoryIntelligenceRuns) NewId("StoryIntelligenceRuns",run.StoryIntelligenceRunID);
RebindAuditActors(backup.Project);
foreach (var collection in typeof(ProjectBackupData).GetProperties())
foreach (var row in (System.Collections.IEnumerable)collection.GetValue(backup.Data)!)
@ -1104,7 +1108,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
scene.ManuscriptDocumentID = scene.ManuscriptDocumentID.HasValue && Map("ManuscriptDocuments").TryGetValue(scene.ManuscriptDocumentID.Value, out var sceneDocument) ? sceneDocument : null;
scene.IsLinkedToManuscript = false;
scene.LinkedUtc = null;
scene.ImportRunID = null; // A copied scene cannot point into the original project's analysis run.
scene.ImportRunID = scene.ImportRunID.HasValue && Map("StoryIntelligenceRuns").TryGetValue(scene.ImportRunID.Value,out var copiedRun) ? copiedRun : null;
scene.POVCharacterID = ExistingOrNewNullable("Characters", scene.POVCharacterID);
scene.PrimaryLocationID = ExistingOrNewNullable("Locations", scene.PrimaryLocationID);
scene.FloorPlanID = ExistingOrNewNullable("FloorPlans", scene.FloorPlanID);
@ -1611,6 +1615,52 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
row.SceneID=ExistingOrNew("Scenes",row.SceneID);
row.ChapterID=ExistingOrNew("Chapters",row.ChapterID);
}
foreach(var row in backup.Data.StoryIntelligenceRuns)
{
row.StoryIntelligenceRunID=NewId("StoryIntelligenceRuns",row.StoryIntelligenceRunID);
row.UserID=importingUserId;
if(row.ProjectID.HasValue) row.ProjectID=projectId;
row.BookID=ExistingOrNewNullable("Books",row.BookID);
row.ChapterID=ExistingOrNewNullable("Chapters",row.ChapterID);
if(row.Status is not ("Completed" or "CompletedWithWarnings" or "Failed" or "Cancelled"))
{
row.Status="Cancelled";
row.CurrentStage="Cancelled";
row.CurrentMessage="Imported historical analysis; original work was not resumed.";
}
}
foreach(var row in backup.Data.StoryIntelligenceChapterResults)
{
row.ChapterResultID=NewId("StoryIntelligenceChapterResults",row.ChapterResultID);
row.StoryIntelligenceRunID=ExistingOrNew("StoryIntelligenceRuns",row.StoryIntelligenceRunID);
if(row.ProjectID.HasValue) row.ProjectID=projectId;
row.BookID=ExistingOrNewNullable("Books",row.BookID);
row.ChapterID=ExistingOrNewNullable("Chapters",row.ChapterID);
}
foreach(var row in backup.Data.StoryIntelligenceSceneResults)
{
row.SceneResultID=NewId("StoryIntelligenceSceneResults",row.SceneResultID);
row.StoryIntelligenceRunID=ExistingOrNew("StoryIntelligenceRuns",row.StoryIntelligenceRunID);
row.ChapterResultID=ExistingOrNewNullable("StoryIntelligenceChapterResults",row.ChapterResultID);
if(row.ProjectID.HasValue) row.ProjectID=projectId;
row.BookID=ExistingOrNewNullable("Books",row.BookID);
row.ChapterID=ExistingOrNewNullable("Chapters",row.ChapterID);
row.SceneID=ExistingOrNewNullable("Scenes",row.SceneID);
}
foreach(var row in backup.Data.StoryIntelligenceImportCommits)
{
row.StoryIntelligenceImportCommitID=NewId("StoryIntelligenceImportCommits",row.StoryIntelligenceImportCommitID);
row.StoryIntelligenceRunID=ExistingOrNew("StoryIntelligenceRuns",row.StoryIntelligenceRunID);
if(row.ProjectID.HasValue) row.ProjectID=projectId;
row.BookID=ExistingOrNewNullable("Books",row.BookID);
row.ChapterID=ExistingOrNewNullable("Chapters",row.ChapterID);
row.CommittedByUserID=importingUserId;
if(row.Status is not ("Completed" or "Failed" or "Cancelled"))
{
row.Status="Cancelled";
row.Notes="Imported historical materialization; original work was not resumed.";
}
}
foreach (var image in backup.Data.CharacterImages)
{
image.CharacterImageID=NewId("CharacterImages",image.CharacterImageID);

View File

@ -8,6 +8,10 @@ internal static class ProjectBackupGraphValidation
private sealed record Link(string Column, string TargetCollection, string TargetColumn);
private sealed record Entity(string Collection, string? Identity, params Link[] Links);
private static readonly Entity[] Entities = [
new("StoryIntelligenceRuns","StoryIntelligenceRunID",new Link("ProjectID","Project","ProjectID"),new Link("BookID","Books","BookID"),new Link("ChapterID","Chapters","ChapterID")),
new("StoryIntelligenceChapterResults","ChapterResultID",new Link("StoryIntelligenceRunID","StoryIntelligenceRuns","StoryIntelligenceRunID"),new Link("ProjectID","Project","ProjectID"),new Link("BookID","Books","BookID"),new Link("ChapterID","Chapters","ChapterID")),
new("StoryIntelligenceSceneResults","SceneResultID",new Link("StoryIntelligenceRunID","StoryIntelligenceRuns","StoryIntelligenceRunID"),new Link("ChapterResultID","StoryIntelligenceChapterResults","ChapterResultID"),new Link("ProjectID","Project","ProjectID"),new Link("BookID","Books","BookID"),new Link("ChapterID","Chapters","ChapterID"),new Link("SceneID","Scenes","SceneID")),
new("StoryIntelligenceImportCommits","StoryIntelligenceImportCommitID",new Link("StoryIntelligenceRunID","StoryIntelligenceRuns","StoryIntelligenceRunID"),new Link("ProjectID","Project","ProjectID"),new Link("BookID","Books","BookID"),new Link("ChapterID","Chapters","ChapterID")),
new("CoreImportBasicLocationReviews","CoreImportBasicLocationReviewID",new Link("BookID","Books","BookID"),new Link("ProjectID","Project","ProjectID"),new Link("BuildID","OnboardingManuscriptBuilds","OnboardingManuscriptBuildID")),
new("CoreImportBasicLocationCandidates","CoreImportBasicLocationCandidateID",new Link("ExistingLocationID","Locations","LocationID"),new Link("ParentLocationID","Locations","LocationID"),new Link("ResultLocationID","Locations","LocationID"),new Link("CoreImportBasicLocationReviewID","CoreImportBasicLocationReviews","CoreImportBasicLocationReviewID"),new Link("SameAsLocationID","Locations","LocationID")),
new("CoreImportBasicLocationEvidence","CoreImportBasicLocationEvidenceID",new Link("CoreImportBasicLocationCandidateID","CoreImportBasicLocationCandidates","CoreImportBasicLocationCandidateID"),new Link("SceneID","Scenes","SceneID"),new Link("ChapterID","Chapters","ChapterID")),
@ -113,6 +117,8 @@ internal static class ProjectBackupGraphValidation
return $"Project backup {entity.Collection}.{link.Column} references a missing or foreign {link.TargetCollection} record.";
}
}
if(backup.Data.StoryIntelligenceRuns.Count>0 && backup.Data.Scenes.Any(scene=>scene.ImportRunID.HasValue && !backup.Data.StoryIntelligenceRuns.Any(run=>run.StoryIntelligenceRunID==scene.ImportRunID)))
return "Project backup scene analysis provenance references a missing or foreign run.";
return ProjectBackupTimelineState.Validate(backup);
}
}

View File

@ -0,0 +1,427 @@
-- Version 1.3 additive retained analysis source/results and import audit.
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER PROCEDURE dbo.ProjectBackup_PersistentState_List @ProjectID int
AS
BEGIN
SET NOCOUNT ON;
SELECT * FROM dbo.ManuscriptDocuments WHERE ProjectID=@ProjectID ORDER BY ManuscriptDocumentID;
SELECT * FROM dbo.SceneManuscriptSources WHERE ProjectID=@ProjectID ORDER BY SceneID;
SELECT * FROM dbo.ManuscriptStructuralChapterSources WHERE ProjectID=@ProjectID ORDER BY ChapterID;
SELECT * FROM dbo.WritingPlans WHERE ProjectID=@ProjectID ORDER BY WritingPlanID;
SELECT i.* FROM dbo.WritingScheduleItems i JOIN dbo.WritingPlans p ON p.WritingPlanID=i.WritingPlanID WHERE p.ProjectID=@ProjectID ORDER BY i.WritingScheduleItemID;
SELECT a.* FROM dbo.CharacterAliases a JOIN dbo.Characters c ON c.CharacterID=a.CharacterID WHERE c.ProjectID=@ProjectID ORDER BY a.CharacterAliasID;
SELECT a.* FROM dbo.AssetAliases a JOIN dbo.StoryAssets s ON s.StoryAssetID=a.StoryAssetID WHERE s.ProjectID=@ProjectID ORDER BY a.AssetAliasID;
SELECT a.* FROM dbo.LocationAliases a JOIN dbo.Locations l ON l.LocationID=a.LocationID WHERE l.ProjectID=@ProjectID ORDER BY a.LocationAliasID;
SELECT * FROM dbo.AuthorPlotSeeds WHERE ProjectID=@ProjectID ORDER BY AuthorPlotSeedID;
SELECT * FROM dbo.ContinuityWarningAcknowledgements WHERE ProjectID=@ProjectID ORDER BY ContinuityWarningAcknowledgementID;
SELECT x.* FROM dbo.PlotEventTargetPlotLines x JOIN dbo.ThreadEvents e ON e.ThreadEventID=x.PlotEventID JOIN dbo.PlotThreads t ON t.PlotThreadID=e.PlotThreadID JOIN dbo.PlotLines p ON p.PlotLineID=t.PlotLineID WHERE p.ProjectID=@ProjectID ORDER BY x.PlotEventID,x.PlotLineID;
SELECT x.* FROM dbo.WordCompanionSceneAssets x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID ORDER BY x.WordCompanionSceneAssetID;
SELECT x.* FROM dbo.WordCompanionSceneLocations x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID ORDER BY x.WordCompanionSceneLocationID;
SELECT * FROM dbo.CharacterImages WHERE ProjectID=@ProjectID ORDER BY CharacterImageID;
SELECT * FROM dbo.OnboardingManuscriptBuilds WHERE ProjectID=@ProjectID ORDER BY OnboardingManuscriptBuildID;
SELECT m.* FROM dbo.OnboardingManuscriptBuildChapterMap m JOIN dbo.OnboardingManuscriptBuilds b ON b.OnboardingManuscriptBuildID=m.OnboardingManuscriptBuildID WHERE b.ProjectID=@ProjectID ORDER BY m.OnboardingManuscriptBuildID,m.TemporaryChapterKey;
SELECT m.* FROM dbo.OnboardingManuscriptBuildSceneMap m JOIN dbo.OnboardingManuscriptBuilds b ON b.OnboardingManuscriptBuildID=m.OnboardingManuscriptBuildID WHERE b.ProjectID=@ProjectID ORDER BY m.OnboardingManuscriptBuildID,m.TemporarySceneKey;
SELECT m.* FROM dbo.OnboardingManuscriptBuildCharacterMap m JOIN dbo.OnboardingManuscriptBuilds b ON b.OnboardingManuscriptBuildID=m.OnboardingManuscriptBuildID WHERE b.ProjectID=@ProjectID ORDER BY m.OnboardingManuscriptBuildID,m.TemporaryCharacterKey;
SELECT x.* FROM dbo.SceneAssetSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID ORDER BY x.SceneAssetSuggestionID;
SELECT x.* FROM dbo.SceneCharacterSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID ORDER BY x.SceneCharacterSuggestionID;
SELECT x.* FROM dbo.SceneLocationSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID ORDER BY x.SceneLocationSuggestionID;
SELECT x.* FROM dbo.SceneTextStatistics x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID ORDER BY x.SceneID;
SELECT * FROM dbo.CoreImportBasicLocationReviews WHERE ProjectID=@ProjectID ORDER BY CoreImportBasicLocationReviewID;
SELECT c.* FROM dbo.CoreImportBasicLocationCandidates c JOIN dbo.CoreImportBasicLocationReviews r ON r.CoreImportBasicLocationReviewID=c.CoreImportBasicLocationReviewID WHERE r.ProjectID=@ProjectID ORDER BY c.CoreImportBasicLocationCandidateID;
SELECT e.* FROM dbo.CoreImportBasicLocationEvidence e JOIN dbo.CoreImportBasicLocationCandidates c ON c.CoreImportBasicLocationCandidateID=e.CoreImportBasicLocationCandidateID JOIN dbo.CoreImportBasicLocationReviews r ON r.CoreImportBasicLocationReviewID=c.CoreImportBasicLocationReviewID WHERE r.ProjectID=@ProjectID ORDER BY e.CoreImportBasicLocationEvidenceID;
SELECT r.StoryIntelligenceRunID INTO #BackupAnalysisRunIds FROM dbo.StoryIntelligenceRuns r WHERE r.ProjectID=@ProjectID OR EXISTS(SELECT 1 FROM dbo.Books b WHERE b.BookID=r.BookID AND b.ProjectID=@ProjectID) OR EXISTS(SELECT 1 FROM dbo.Chapters c JOIN dbo.Books b ON b.BookID=c.BookID WHERE c.ChapterID=r.ChapterID AND b.ProjectID=@ProjectID);
SELECT r.* FROM dbo.StoryIntelligenceRuns r JOIN #BackupAnalysisRunIds x ON x.StoryIntelligenceRunID=r.StoryIntelligenceRunID ORDER BY r.StoryIntelligenceRunID;
SELECT r.* FROM dbo.StoryIntelligenceChapterResults r JOIN #BackupAnalysisRunIds x ON x.StoryIntelligenceRunID=r.StoryIntelligenceRunID ORDER BY r.ChapterResultID;
SELECT r.* FROM dbo.StoryIntelligenceSceneResults r JOIN #BackupAnalysisRunIds x ON x.StoryIntelligenceRunID=r.StoryIntelligenceRunID ORDER BY r.SceneResultID;
SELECT r.* FROM dbo.StoryIntelligenceImportCommits r JOIN #BackupAnalysisRunIds x ON x.StoryIntelligenceRunID=r.StoryIntelligenceRunID ORDER BY r.StoryIntelligenceImportCommitID;
END;
GO
CREATE OR ALTER PROCEDURE dbo.ProjectRestore_ApplyFromJson
@ProjectID int,
@SourceRestorePointID int = NULL,
@SafetyRestorePointID int = NULL,
@JsonData nvarchar(max)
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
IF ISNULL(ISJSON(@JsonData), 0) <> 1
THROW 51001, 'Restore JSON is invalid.', 1;
IF ISNULL(JSON_VALUE(@JsonData, '$.Format'), N'') <> N'PlotDirector.ProjectBackup'
THROW 51002, 'Restore JSON format is not recognised.', 1;
IF ISNULL(JSON_VALUE(@JsonData, '$.FormatVersion'), N'') NOT IN (N'1.0', N'1.1', N'1.2', N'1.3')
THROW 51003, 'Restore JSON format version is not supported.', 1;
IF ISNULL(@ProjectID,0)<=0 OR ISNULL(TRY_CONVERT(int, JSON_VALUE(@JsonData, '$.Project.ProjectID')),-1) <> @ProjectID
THROW 51004, 'Restore point does not belong to this project.', 1;
DECLARE @RestoreTables table (TableName sysname NOT NULL PRIMARY KEY);
INSERT INTO @RestoreTables (TableName)
VALUES
(N'StoryIntelligenceRuns'),
(N'StoryIntelligenceChapterResults'),
(N'StoryIntelligenceSceneResults'),
(N'StoryIntelligenceImportCommits'),
(N'CoreImportBasicLocationReviews'),
(N'CoreImportBasicLocationCandidates'),
(N'CoreImportBasicLocationEvidence'),
(N'SceneAssetSuggestions'),
(N'SceneCharacterSuggestions'),
(N'SceneLocationSuggestions'),
(N'SceneTextStatistics'),
(N'OnboardingManuscriptBuilds'),
(N'OnboardingManuscriptBuildChapterMap'),
(N'OnboardingManuscriptBuildSceneMap'),
(N'OnboardingManuscriptBuildCharacterMap'),
(N'CharacterImages'), (N'WordCompanionSceneAssets'), (N'WordCompanionSceneLocations'), (N'ManuscriptDocuments'), (N'SceneManuscriptSources'), (N'ManuscriptStructuralChapterSources'), (N'WritingPlans'), (N'WritingScheduleItems'), (N'CharacterAliases'), (N'AssetAliases'), (N'LocationAliases'), (N'AuthorPlotSeeds'), (N'ContinuityWarningAcknowledgements'), (N'PlotEventTargetPlotLines'),
(N'ProjectTimelineSettings'), (N'ProjectTimelineMetricSettings'), (N'TimelineViewPresets'),
(N'SceneMetricTypes'), (N'SceneMetricValues'), (N'Books'), (N'Chapters'), (N'Scenes'),
(N'ScenePurposes'), (N'SceneOutcomes'), (N'PlotLines'), (N'PlotThreads'), (N'ThreadEvents'),
(N'AssetStates'), (N'StoryAssets'), (N'AssetEvents'), (N'AssetDependencies'),
(N'AssetCustodyEvents'), (N'AssetCustodyEventCharacters'), (N'Characters'), (N'SceneCharacters'),
(N'CharacterAttributeTypes'), (N'CharacterAttributeEvents'), (N'CharacterKnowledge'),
(N'CharacterRelationships'), (N'RelationshipEvents'), (N'Locations'), (N'LocationRelationships'),
(N'MapReferenceImages'), (N'StoryMaps'), (N'MapFeatures'), (N'MapRelationships'), (N'MapJourneyNotes'),
(N'FloorPlans'), (N'FloorPlanFloors'), (N'FloorPlanBlocks'), (N'FloorPlanTransitions'),
(N'SceneAssetLocations'), (N'SceneFloorPlanOccupancy'), (N'SceneDependencies'), (N'ValidationRuns'), (N'ContinuityWarnings'),
(N'SceneNotes'), (N'SceneWorkflow'), (N'SceneChecklistItems'), (N'SceneAttachments'),
(N'ChapterGoals'), (N'Scenarios'), (N'ScenarioSceneOrder'), (N'ScenarioValidationRuns'),
(N'ScenarioWarnings');
IF JSON_VALUE(@JsonData,'$.FormatVersion')<>N'1.3' AND EXISTS(SELECT 1 FROM dbo.CharacterImages WHERE ProjectID=@ProjectID)
THROW 51006,'This older restore point does not include the existing character gallery. Restore was aborted without changing it.',1;
IF EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds WHERE ProjectID=@ProjectID)
AND JSON_QUERY(@JsonData,'$.Data.OnboardingManuscriptBuilds') IS NULL
THROW 51007,'This older restore point does not include existing Core Import build history. Restore was aborted without changing it.',1;
IF EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds WHERE ProjectID=@ProjectID
AND (Status NOT IN (N'Built',N'Complete',N'Completed',N'Failed',N'Cancelled')
OR (Status=N'Built' AND ISNULL(MarkerStatus,N'') NOT IN (N'UserConfirmedSave',N'Completed',N'Complete'))))
THROW 51008,'Core Import is unfinished for this project. Complete or cancel it before restoring.',1;
IF JSON_QUERY(@JsonData,'$.Data.SceneAssetSuggestions') IS NULL AND EXISTS(SELECT 1 FROM dbo.SceneAssetSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID)
THROW 51009,'This older restore point omits existing scene suggestion history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.SceneCharacterSuggestions') IS NULL AND EXISTS(SELECT 1 FROM dbo.SceneCharacterSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID)
THROW 51009,'This older restore point omits existing scene suggestion history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.SceneLocationSuggestions') IS NULL AND EXISTS(SELECT 1 FROM dbo.SceneLocationSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID)
THROW 51009,'This older restore point omits existing scene suggestion history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.CoreImportBasicLocationReviews') IS NULL AND EXISTS(SELECT 1 FROM dbo.CoreImportBasicLocationReviews WHERE ProjectID=@ProjectID)
THROW 51010,'This older restore point omits existing Core Import location review history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.CoreImportBasicLocationCandidates') IS NULL AND EXISTS(SELECT 1 FROM dbo.CoreImportBasicLocationCandidates c JOIN dbo.CoreImportBasicLocationReviews r ON r.CoreImportBasicLocationReviewID=c.CoreImportBasicLocationReviewID WHERE r.ProjectID=@ProjectID)
THROW 51010,'This older restore point omits existing Core Import location choices. Restore was aborted without changing them.',1;
IF JSON_QUERY(@JsonData,'$.Data.CoreImportBasicLocationEvidence') IS NULL AND EXISTS(SELECT 1 FROM dbo.CoreImportBasicLocationEvidence e JOIN dbo.CoreImportBasicLocationCandidates c ON c.CoreImportBasicLocationCandidateID=e.CoreImportBasicLocationCandidateID JOIN dbo.CoreImportBasicLocationReviews r ON r.CoreImportBasicLocationReviewID=c.CoreImportBasicLocationReviewID WHERE r.ProjectID=@ProjectID)
THROW 51010,'This older restore point omits existing Core Import location evidence. Restore was aborted without changing it.',1;
SELECT r.StoryIntelligenceRunID INTO #ExistingAnalysisRunIds FROM dbo.StoryIntelligenceRuns r WHERE r.ProjectID=@ProjectID OR EXISTS(SELECT 1 FROM dbo.Books b WHERE b.BookID=r.BookID AND b.ProjectID=@ProjectID) OR EXISTS(SELECT 1 FROM dbo.Chapters c JOIN dbo.Books b ON b.BookID=c.BookID WHERE c.ChapterID=r.ChapterID AND b.ProjectID=@ProjectID);
IF JSON_QUERY(@JsonData,'$.Data.StoryIntelligenceRuns') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryIntelligenceRuns r JOIN #ExistingAnalysisRunIds x ON x.StoryIntelligenceRunID=r.StoryIntelligenceRunID)
THROW 51011,'This older restore point omits existing analysis audit history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.StoryIntelligenceChapterResults') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryIntelligenceChapterResults r JOIN #ExistingAnalysisRunIds x ON x.StoryIntelligenceRunID=r.StoryIntelligenceRunID)
THROW 51011,'This older restore point omits existing analysis audit history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.StoryIntelligenceSceneResults') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryIntelligenceSceneResults r JOIN #ExistingAnalysisRunIds x ON x.StoryIntelligenceRunID=r.StoryIntelligenceRunID)
THROW 51011,'This older restore point omits existing analysis audit history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.StoryIntelligenceImportCommits') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryIntelligenceImportCommits r JOIN #ExistingAnalysisRunIds x ON x.StoryIntelligenceRunID=r.StoryIntelligenceRunID)
THROW 51011,'This older restore point omits existing analysis audit history. Restore was aborted without changing it.',1;
IF EXISTS(SELECT 1 FROM dbo.StoryIntelligenceRuns r JOIN #ExistingAnalysisRunIds x ON x.StoryIntelligenceRunID=r.StoryIntelligenceRunID WHERE r.Status NOT IN(N'Completed',N'CompletedWithWarnings',N'Failed',N'Cancelled'))
THROW 51012,'Analysis is unfinished for this project. Complete or cancel it before restoring.',1;
IF EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.StoryIntelligenceRuns') WITH(Status nvarchar(40) '$.Status') WHERE Status NOT IN(N'Completed',N'CompletedWithWarnings',N'Failed',N'Cancelled'))
THROW 51012,'This restore point contains unfinished analysis. It cannot resume paid work through restore.',1;
IF EXISTS(SELECT 1 FROM dbo.StoryIntelligenceImportCommits r JOIN #ExistingAnalysisRunIds x ON x.StoryIntelligenceRunID=r.StoryIntelligenceRunID WHERE r.Status NOT IN(N'Completed',N'Failed',N'Cancelled'))
OR EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.StoryIntelligenceImportCommits') WITH(Status nvarchar(40) '$.Status') WHERE Status NOT IN(N'Completed',N'Failed',N'Cancelled'))
THROW 51012,'Analysis materialization is unfinished in the project or restore point. Restore was aborted without changing it.',1;
BEGIN TRANSACTION;
DECLARE @PreviousMapRevision int = ISNULL((SELECT MAX(Revision) FROM dbo.StoryMaps WHERE ProjectID=@ProjectID),0);
DECLARE @TableName sysname;
DECLARE DisableCursor CURSOR LOCAL FAST_FORWARD FOR SELECT TableName FROM @RestoreTables;
OPEN DisableCursor;
FETCH NEXT FROM DisableCursor INTO @TableName;
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @DisableSql nvarchar(max) = N'ALTER TABLE dbo.' + QUOTENAME(@TableName) + N' NOCHECK CONSTRAINT ALL;';
EXEC (@DisableSql);
FETCH NEXT FROM DisableCursor INTO @TableName;
END
CLOSE DisableCursor;
DEALLOCATE DisableCursor;
DELETE r FROM dbo.StoryIntelligenceImportCommits r JOIN #ExistingAnalysisRunIds x ON x.StoryIntelligenceRunID=r.StoryIntelligenceRunID;
DELETE r FROM dbo.StoryIntelligenceSceneResults r JOIN #ExistingAnalysisRunIds x ON x.StoryIntelligenceRunID=r.StoryIntelligenceRunID;
DELETE r FROM dbo.StoryIntelligenceChapterResults r JOIN #ExistingAnalysisRunIds x ON x.StoryIntelligenceRunID=r.StoryIntelligenceRunID;
DELETE r FROM dbo.StoryIntelligenceRuns r JOIN #ExistingAnalysisRunIds x ON x.StoryIntelligenceRunID=r.StoryIntelligenceRunID;
DELETE e FROM dbo.CoreImportBasicLocationEvidence e JOIN dbo.CoreImportBasicLocationCandidates c ON c.CoreImportBasicLocationCandidateID=e.CoreImportBasicLocationCandidateID JOIN dbo.CoreImportBasicLocationReviews r ON r.CoreImportBasicLocationReviewID=c.CoreImportBasicLocationReviewID WHERE r.ProjectID=@ProjectID;
DELETE c FROM dbo.CoreImportBasicLocationCandidates c JOIN dbo.CoreImportBasicLocationReviews r ON r.CoreImportBasicLocationReviewID=c.CoreImportBasicLocationReviewID WHERE r.ProjectID=@ProjectID;
DELETE FROM dbo.CoreImportBasicLocationReviews WHERE ProjectID=@ProjectID;
DELETE x FROM dbo.SceneAssetSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID;
DELETE x FROM dbo.SceneCharacterSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID;
DELETE x FROM dbo.SceneLocationSuggestions x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID;
DELETE x FROM dbo.SceneTextStatistics x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID;
DELETE m FROM dbo.OnboardingManuscriptBuildChapterMap m JOIN dbo.OnboardingManuscriptBuilds b ON b.OnboardingManuscriptBuildID=m.OnboardingManuscriptBuildID WHERE b.ProjectID=@ProjectID;
DELETE m FROM dbo.OnboardingManuscriptBuildSceneMap m JOIN dbo.OnboardingManuscriptBuilds b ON b.OnboardingManuscriptBuildID=m.OnboardingManuscriptBuildID WHERE b.ProjectID=@ProjectID;
DELETE m FROM dbo.OnboardingManuscriptBuildCharacterMap m JOIN dbo.OnboardingManuscriptBuilds b ON b.OnboardingManuscriptBuildID=m.OnboardingManuscriptBuildID WHERE b.ProjectID=@ProjectID;
DELETE FROM dbo.OnboardingManuscriptBuilds WHERE ProjectID=@ProjectID;
DELETE FROM dbo.CharacterImages WHERE ProjectID=@ProjectID;
DELETE x FROM dbo.WordCompanionSceneAssets x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID;
DELETE x FROM dbo.WordCompanionSceneLocations x JOIN dbo.Scenes s ON s.SceneID=x.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID;
DELETE i FROM dbo.WritingScheduleItems i JOIN dbo.WritingPlans p ON p.WritingPlanID=i.WritingPlanID WHERE p.ProjectID=@ProjectID;
DELETE dbo.WritingPlans WHERE ProjectID=@ProjectID;
DELETE dbo.AuthorPlotSeeds WHERE ProjectID=@ProjectID;
DELETE dbo.ContinuityWarningAcknowledgements WHERE ProjectID=@ProjectID;
DELETE a FROM dbo.CharacterAliases a JOIN dbo.Characters c ON c.CharacterID=a.CharacterID WHERE c.ProjectID=@ProjectID;
DELETE a FROM dbo.AssetAliases a JOIN dbo.StoryAssets s ON s.StoryAssetID=a.StoryAssetID WHERE s.ProjectID=@ProjectID;
DELETE a FROM dbo.LocationAliases a JOIN dbo.Locations l ON l.LocationID=a.LocationID WHERE l.ProjectID=@ProjectID;
DELETE x FROM dbo.PlotEventTargetPlotLines x JOIN dbo.ThreadEvents e ON e.ThreadEventID=x.PlotEventID JOIN dbo.PlotThreads t ON t.PlotThreadID=e.PlotThreadID JOIN dbo.PlotLines p ON p.PlotLineID=t.PlotLineID WHERE p.ProjectID=@ProjectID;
DELETE dbo.SceneManuscriptSources WHERE ProjectID=@ProjectID;
DELETE dbo.ManuscriptStructuralChapterSources WHERE ProjectID=@ProjectID;
DELETE dbo.ManuscriptDocuments WHERE ProjectID=@ProjectID;
DELETE n FROM dbo.MapJourneyNotes n JOIN dbo.StoryMaps m ON m.MapID=n.MapID WHERE m.ProjectID=@ProjectID;
DELETE r FROM dbo.MapRelationships r JOIN dbo.StoryMaps m ON m.MapID=r.MapID WHERE m.ProjectID=@ProjectID;
DELETE f FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID WHERE m.ProjectID=@ProjectID;
DELETE dbo.StoryMaps WHERE ProjectID=@ProjectID;
DELETE dbo.MapReferenceImages WHERE ProjectID=@ProjectID;
UPDATE dbo.UserFile SET IsDeleted=1,DeletedDateUTC=SYSUTCDATETIME() WHERE ProjectID=@ProjectID AND EntityType=N'MapReferenceImage';
DELETE sw FROM dbo.ScenarioWarnings sw INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = sw.ScenarioID WHERE sc.ProjectID = @ProjectID;
DELETE svr FROM dbo.ScenarioValidationRuns svr INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = svr.ScenarioID WHERE sc.ProjectID = @ProjectID;
DELETE sso FROM dbo.ScenarioSceneOrder sso INNER JOIN dbo.Scenarios sc ON sc.ScenarioID = sso.ScenarioID WHERE sc.ProjectID = @ProjectID;
DELETE FROM dbo.Scenarios WHERE ProjectID = @ProjectID;
DELETE FROM dbo.ContinuityWarnings WHERE ProjectID = @ProjectID;
DELETE FROM dbo.ValidationRuns WHERE ProjectID = @ProjectID;
DELETE sa FROM dbo.SceneAttachments sa INNER JOIN dbo.Scenes s ON s.SceneID = sa.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID;
DELETE sci FROM dbo.SceneChecklistItems sci INNER JOIN dbo.Scenes s ON s.SceneID = sci.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID;
DELETE sw FROM dbo.SceneWorkflow sw INNER JOIN dbo.Scenes s ON s.SceneID = sw.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID;
DELETE sn FROM dbo.SceneNotes sn INNER JOIN dbo.Scenes s ON s.SceneID = sn.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID;
DELETE cg FROM dbo.ChapterGoals cg INNER JOIN dbo.Chapters c ON c.ChapterID = cg.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID;
DELETE sfpo FROM dbo.SceneFloorPlanOccupancy sfpo
INNER JOIN dbo.Scenes s ON s.SceneID = sfpo.SceneID
INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID
INNER JOIN dbo.Books b ON b.BookID = c.BookID
WHERE b.ProjectID = @ProjectID;
DELETE sd FROM dbo.SceneDependencies sd
LEFT JOIN dbo.Scenes ss ON ss.SceneID = sd.SourceSceneID
LEFT JOIN dbo.Chapters sc ON sc.ChapterID = ss.ChapterID
LEFT JOIN dbo.Books sb ON sb.BookID = sc.BookID
LEFT JOIN dbo.Scenes ts ON ts.SceneID = sd.TargetSceneID
LEFT JOIN dbo.Chapters tc ON tc.ChapterID = ts.ChapterID
LEFT JOIN dbo.Books tb ON tb.BookID = tc.BookID
WHERE sd.ProjectID = @ProjectID OR sb.ProjectID = @ProjectID OR tb.ProjectID = @ProjectID;
DELETE re FROM dbo.RelationshipEvents re INNER JOIN dbo.CharacterRelationships cr ON cr.CharacterRelationshipID = re.CharacterRelationshipID WHERE cr.ProjectID = @ProjectID;
DELETE FROM dbo.CharacterRelationships WHERE ProjectID = @ProjectID;
DELETE ck FROM dbo.CharacterKnowledge ck INNER JOIN dbo.Characters ch ON ch.CharacterID = ck.CharacterID WHERE ch.ProjectID = @ProjectID;
DELETE cae FROM dbo.CharacterAttributeEvents cae INNER JOIN dbo.Characters ch ON ch.CharacterID = cae.CharacterID WHERE ch.ProjectID = @ProjectID;
DELETE sc FROM dbo.SceneCharacters sc INNER JOIN dbo.Characters ch ON ch.CharacterID = sc.CharacterID WHERE ch.ProjectID = @ProjectID;
DELETE acec FROM dbo.AssetCustodyEventCharacters acec INNER JOIN dbo.AssetCustodyEvents ace ON ace.AssetCustodyEventID = acec.AssetCustodyEventID INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ace.StoryAssetID WHERE sa.ProjectID = @ProjectID;
DELETE ace FROM dbo.AssetCustodyEvents ace INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ace.StoryAssetID WHERE sa.ProjectID = @ProjectID;
DELETE ad FROM dbo.AssetDependencies ad INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ad.SourceAssetID WHERE sa.ProjectID = @ProjectID;
DELETE ae FROM dbo.AssetEvents ae INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ae.StoryAssetID WHERE sa.ProjectID = @ProjectID;
DELETE sal FROM dbo.SceneAssetLocations sal INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = sal.StoryAssetID WHERE sa.ProjectID = @ProjectID;
DELETE FROM dbo.StoryAssets WHERE ProjectID = @ProjectID;
DELETE fpt FROM dbo.FloorPlanTransitions fpt INNER JOIN dbo.FloorPlanFloors fpf ON fpf.FloorPlanFloorID = fpt.FloorPlanFloorID INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID;
DELETE fpb FROM dbo.FloorPlanBlocks fpb INNER JOIN dbo.FloorPlanFloors fpf ON fpf.FloorPlanFloorID = fpb.FloorPlanFloorID INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID;
DELETE fpf FROM dbo.FloorPlanFloors fpf INNER JOIN dbo.FloorPlans fp ON fp.FloorPlanID = fpf.FloorPlanID WHERE fp.ProjectID = @ProjectID;
DELETE FROM dbo.FloorPlans WHERE ProjectID = @ProjectID;
DELETE lr FROM dbo.LocationRelationships lr INNER JOIN dbo.Locations l ON l.LocationID = lr.FromLocationID WHERE l.ProjectID = @ProjectID;
DELETE FROM dbo.Locations WHERE ProjectID = @ProjectID;
DELETE te FROM dbo.ThreadEvents te INNER JOIN dbo.PlotThreads pt ON pt.PlotThreadID = te.PlotThreadID INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID WHERE pl.ProjectID = @ProjectID;
DELETE pt FROM dbo.PlotThreads pt INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID WHERE pl.ProjectID = @ProjectID;
DELETE FROM dbo.PlotLines WHERE ProjectID = @ProjectID;
DELETE FROM dbo.TimelineViewPresets WHERE ProjectID = @ProjectID;
DELETE FROM dbo.ProjectTimelineMetricSettings WHERE ProjectID = @ProjectID;
DELETE FROM dbo.ProjectTimelineSettings WHERE ProjectID = @ProjectID;
DELETE smv FROM dbo.SceneMetricValues smv INNER JOIN dbo.Scenes s ON s.SceneID = smv.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID;
DELETE FROM dbo.SceneMetricTypes WHERE ProjectID = @ProjectID;
DELETE FROM dbo.CharacterAttributeTypes WHERE ProjectID = @ProjectID;
DELETE FROM dbo.AssetStates WHERE ProjectID = @ProjectID;
DELETE sp FROM dbo.ScenePurposes sp INNER JOIN dbo.Scenes s ON s.SceneID = sp.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID;
DELETE so FROM dbo.SceneOutcomes so INNER JOIN dbo.Scenes s ON s.SceneID = so.SceneID INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID;
DELETE s FROM dbo.Scenes s INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID;
DELETE c FROM dbo.Chapters c INNER JOIN dbo.Books b ON b.BookID = c.BookID WHERE b.ProjectID = @ProjectID;
DELETE FROM dbo.Books WHERE ProjectID = @ProjectID;
DELETE FROM dbo.Characters WHERE ProjectID = @ProjectID;
UPDATE p
SET ProjectName = src.ProjectName,
Description = src.Description,
CreatedDate = src.CreatedDate,
UpdatedDate = SYSUTCDATETIME(),
CreatedByUserID = CASE WHEN JSON_VALUE(@JsonData,'$.FormatVersion')=N'1.2' THEN src.CreatedByUserID ELSE p.CreatedByUserID END,
ModifiedByUserID = CASE WHEN JSON_VALUE(@JsonData,'$.FormatVersion')=N'1.2' THEN src.ModifiedByUserID ELSE p.ModifiedByUserID END,
CreatedDateUTC = CASE WHEN JSON_VALUE(@JsonData,'$.FormatVersion')=N'1.2' THEN src.CreatedDateUTC ELSE p.CreatedDateUTC END,
ModifiedDateUTC = CASE WHEN JSON_VALUE(@JsonData,'$.FormatVersion')=N'1.2' THEN src.ModifiedDateUTC ELSE p.ModifiedDateUTC END,
IsArchived = src.IsArchived,
ArchivedDate = src.ArchivedDate,
ArchivedReason = src.ArchivedReason
FROM dbo.Projects p
CROSS APPLY OPENJSON(@JsonData, '$.Project')
WITH
(
ProjectID int '$.ProjectID',
ProjectName nvarchar(200) '$.ProjectName',
Description nvarchar(max) '$.Description',
CreatedDate datetime2 '$.CreatedDate',
CreatedByUserID int '$.CreatedByUserID',
ModifiedByUserID int '$.ModifiedByUserID',
CreatedDateUTC datetime2 '$.CreatedDateUTC',
ModifiedDateUTC datetime2 '$.ModifiedDateUTC',
IsArchived bit '$.IsArchived',
ArchivedDate datetime2 '$.ArchivedDate',
ArchivedReason nvarchar(1000) '$.ArchivedReason'
) src
WHERE p.ProjectID = @ProjectID AND src.ProjectID = @ProjectID;
EXEC dbo.ProjectRestore_InsertJsonTable N'SceneMetricTypes', N'$.Data.SceneMetricTypes', @JsonData, @ProjectID, 1;
EXEC dbo.ProjectRestore_InsertJsonTable N'AssetStates', N'$.Data.AssetStates', @JsonData, @ProjectID, 1;
EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterAttributeTypes', N'$.Data.CharacterAttributeTypes', @JsonData, @ProjectID, 1;
EXEC dbo.ProjectRestore_InsertJsonTable N'Books', N'$.Data.Books', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'Chapters', N'$.Data.Chapters', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'Characters', N'$.Data.Characters', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'Locations', N'$.Data.Locations', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlans', N'$.Data.FloorPlans', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanFloors', N'$.Data.FloorPlanFloors', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanBlocks', N'$.Data.FloorPlanBlocks', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'FloorPlanTransitions', N'$.Data.FloorPlanTransitions', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'Scenes', N'$.Data.Scenes', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'ScenePurposes', N'$.Data.ScenePurposes', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'SceneOutcomes', N'$.Data.SceneOutcomes', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'SceneMetricValues', N'$.Data.SceneMetricValues', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'ProjectTimelineSettings', N'$.Data.TimelineSettings', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'ProjectTimelineMetricSettings', N'$.Data.TimelineMetricSettings', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'TimelineViewPresets', N'$.Data.TimelineViewPresets', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'PlotLines', N'$.Data.PlotLines', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'PlotThreads', N'$.Data.PlotThreads', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'ThreadEvents', N'$.Data.ThreadEvents', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryAssets', N'$.Data.StoryAssets', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'AssetEvents', N'$.Data.AssetEvents', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'AssetDependencies', N'$.Data.AssetDependencies', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'AssetCustodyEvents', N'$.Data.AssetCustodyEvents', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'AssetCustodyEventCharacters', N'$.Data.AssetCustodyCharacters', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'SceneCharacters', N'$.Data.SceneCharacters', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterAttributeEvents', N'$.Data.CharacterAttributeEvents', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterKnowledge', N'$.Data.CharacterKnowledge', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterImages',N'$.Data.CharacterImages',@JsonData,@ProjectID,1;
EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterRelationships', N'$.Data.CharacterRelationships', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'RelationshipEvents', N'$.Data.RelationshipEvents', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'LocationRelationships', N'$.Data.LocationRelationships', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'SceneAssetLocations', N'$.Data.SceneAssetLocations', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'SceneFloorPlanOccupancy', N'$.Data.SceneFloorPlanOccupancy', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'SceneDependencies', N'$.Data.SceneDependencies', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'ValidationRuns', N'$.Data.ValidationRuns', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'ContinuityWarnings', N'$.Data.ContinuityWarnings', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'SceneNotes', N'$.Data.SceneNotes', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'SceneWorkflow', N'$.Data.SceneWorkflow', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'SceneChecklistItems', N'$.Data.SceneChecklistItems', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'SceneAttachments', N'$.Data.SceneAttachments', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'ChapterGoals', N'$.Data.ChapterGoals', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'Scenarios', N'$.Data.Scenarios', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioSceneOrder', N'$.Data.ScenarioSceneOrder', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioValidationRuns', N'$.Data.ScenarioValidationRuns', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'ScenarioWarnings', N'$.Data.ScenarioWarnings', @JsonData, @ProjectID, 0;
-- Older backups contain no Maps sets. The automatic safety restore point preserves current geography.
IF EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapReferenceImages') WITH(ProjectID int '$.ProjectID') WHERE ProjectID IS NULL OR ProjectID<>@ProjectID) THROW 51005,'Reference images cross project boundaries.',1;
INSERT dbo.MapReferenceImages(ImageID,ProjectID,OriginalFileName,ContentType,Width,Height,ImageData)
SELECT x.ImageID,@ProjectID,x.OriginalFileName,x.ContentType,x.Width,x.Height,CAST(N'' AS xml).value('xs:base64Binary(sql:column("x.ImageData"))','varbinary(max)')
FROM OPENJSON(@JsonData,'$.Data.MapReferenceImages') WITH(ImageID uniqueidentifier '$.ImageID',OriginalFileName nvarchar(200) '$.OriginalFileName',ContentType nvarchar(40) '$.ContentType',Width int '$.Width',Height int '$.Height',ImageData nvarchar(max) '$.ImageData') x;
DECLARE @ImageOwner int=(SELECT TOP(1) UserID FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND AccessRole='Owner' AND IsActive=1 ORDER BY ProjectUserAccessID);
INSERT dbo.UserFile(UserID,ProjectID,EntityType,EntityID,FileName,OriginalFileName,ContentType,FileSizeBytes,StoragePath)
SELECT @ImageOwner,@ProjectID,N'MapReferenceImage',@ProjectID,CONVERT(nvarchar(36),ImageID)+N'.webp',OriginalFileName,ContentType,FileSizeBytes,N'db:map-reference/'+CONVERT(nvarchar(20),@ProjectID)+N'/'+CONVERT(nvarchar(36),ImageID) FROM dbo.MapReferenceImages WHERE ProjectID=@ProjectID;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryMaps', N'$.Data.StoryMaps', @JsonData, @ProjectID, 1;
IF EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapFeatures') WITH(MapID int '$.MapID') x WHERE NOT EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.MapID=x.MapID AND m.ProjectID=@ProjectID))
OR EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapRelationships') WITH(MapID int '$.MapID') x WHERE NOT EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.MapID=x.MapID AND m.ProjectID=@ProjectID))
THROW 51005,'Map backup contains features outside this project.',1;
EXEC dbo.ProjectRestore_InsertJsonTable N'MapFeatures', N'$.Data.MapFeatures', @JsonData, @ProjectID, 0;
EXEC dbo.ProjectRestore_InsertJsonTable N'MapRelationships', N'$.Data.MapRelationships', @JsonData, @ProjectID, 0;
IF EXISTS(SELECT 1 FROM dbo.StoryMaps m JOIN dbo.StoryMaps parent ON parent.MapID=m.ParentMapID WHERE m.ProjectID=@ProjectID AND parent.ProjectID<>@ProjectID)
OR EXISTS(SELECT 1 FROM dbo.MapFeatures f JOIN dbo.StoryMaps m ON m.MapID=f.MapID JOIN dbo.Locations l ON l.LocationID=f.LocationID WHERE m.ProjectID=@ProjectID AND l.ProjectID<>@ProjectID)
THROW 51005,'Map hierarchy or Location links cross projects.',1;
IF EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.MapJourneyNotes') WITH(MapID int '$.MapID',CharacterID int '$.CharacterID',FromSceneID int '$.FromSceneID',ToSceneID int '$.ToSceneID',RouteFeatureID uniqueidentifier '$.RouteFeatureID') n
WHERE NOT EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.MapID=n.MapID AND m.ProjectID=@ProjectID)
OR NOT EXISTS(SELECT 1 FROM dbo.Characters c WHERE c.CharacterID=n.CharacterID AND c.ProjectID=@ProjectID)
OR (SELECT COUNT(*) FROM dbo.Scenes s JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=ch.BookID WHERE b.ProjectID=@ProjectID AND s.SceneID IN(n.FromSceneID,n.ToSceneID))<>2
OR (n.RouteFeatureID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.MapFeatures f WHERE f.MapID=n.MapID AND f.FeatureID=n.RouteFeatureID AND f.GeometryClass='Path')))
THROW 51005,'Journey annotations cross project or map boundaries.',1;
EXEC dbo.ProjectRestore_InsertJsonTable N'MapJourneyNotes',N'$.Data.MapJourneyNotes',@JsonData,@ProjectID,0;
IF EXISTS(SELECT 1 FROM dbo.StoryMaps m WHERE m.ProjectID=@ProjectID AND (ISJSON(m.AppearanceJson)<>1 OR ISJSON(m.ReferenceJson)<>1 OR (JSON_VALUE(m.ReferenceJson,'$.imageID') IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.MapReferenceImages i WHERE i.ProjectID=@ProjectID AND i.ImageID=TRY_CONVERT(uniqueidentifier,JSON_VALUE(m.ReferenceJson,'$.imageID')))))) THROW 51005,'Invalid map appearance or foreign reference image.',1;
UPDATE dbo.StoryMaps SET Revision=CASE WHEN Revision>@PreviousMapRevision THEN Revision+1 ELSE @PreviousMapRevision+1 END WHERE ProjectID=@ProjectID;
EXEC dbo.ProjectRestore_InsertJsonTable N'ManuscriptDocuments',N'$.Data.ManuscriptDocuments',@JsonData,@ProjectID,1;
EXEC dbo.ProjectRestore_InsertJsonTable N'SceneManuscriptSources',N'$.Data.SceneManuscriptSources',@JsonData,@ProjectID,1;
EXEC dbo.ProjectRestore_InsertJsonTable N'ManuscriptStructuralChapterSources',N'$.Data.ManuscriptStructuralChapterSources',@JsonData,@ProjectID,1;
EXEC dbo.ProjectRestore_InsertJsonTable N'WritingPlans',N'$.Data.WritingPlans',@JsonData,@ProjectID,1;
EXEC dbo.ProjectRestore_InsertJsonTable N'WritingScheduleItems',N'$.Data.WritingScheduleItems',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterAliases',N'$.Data.CharacterAliases',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'AssetAliases',N'$.Data.AssetAliases',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'LocationAliases',N'$.Data.LocationAliases',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'AuthorPlotSeeds',N'$.Data.AuthorPlotSeeds',@JsonData,@ProjectID,1;
EXEC dbo.ProjectRestore_InsertJsonTable N'ContinuityWarningAcknowledgements',N'$.Data.ContinuityWarningAcknowledgements',@JsonData,@ProjectID,1;
EXEC dbo.ProjectRestore_InsertJsonTable N'PlotEventTargetPlotLines',N'$.Data.PlotEventTargetPlotLines',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'WordCompanionSceneAssets',N'$.Data.WordCompanionSceneAssets',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'WordCompanionSceneLocations',N'$.Data.WordCompanionSceneLocations',@JsonData,@ProjectID,0;
INSERT dbo.UserFile(UserID,ProjectID,EntityType,EntityID,FileName,OriginalFileName,ContentType,FileSizeBytes,StoragePath)
SELECT @ImageOwner,@ProjectID,x.EntityType,x.EntityID,x.RestoredFileName,x.OriginalFileName,x.ContentType,x.FileSizeBytes,x.RestoredPath
FROM OPENJSON(@JsonData,'$.Files') WITH(
EntityType nvarchar(80) '$.EntityType',EntityID int '$.EntityID',RestoredFileName nvarchar(260) '$.RestoredFileName',
OriginalFileName nvarchar(260) '$.OriginalFileName',ContentType nvarchar(200) '$.ContentType',
FileSizeBytes bigint '$.FileSizeBytes',RestoredPath nvarchar(1000) '$.RestoredPath') x
WHERE x.RestoredPath LIKE N'/uploads/%';
EXEC dbo.ProjectRestore_InsertJsonTable N'OnboardingManuscriptBuilds',N'$.Data.OnboardingManuscriptBuilds',@JsonData,@ProjectID,1;
EXEC dbo.ProjectRestore_InsertJsonTable N'OnboardingManuscriptBuildChapterMap',N'$.Data.OnboardingManuscriptBuildChapterMap',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'OnboardingManuscriptBuildSceneMap',N'$.Data.OnboardingManuscriptBuildSceneMap',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'OnboardingManuscriptBuildCharacterMap',N'$.Data.OnboardingManuscriptBuildCharacterMap',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'SceneAssetSuggestions',N'$.Data.SceneAssetSuggestions',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'SceneCharacterSuggestions',N'$.Data.SceneCharacterSuggestions',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'SceneLocationSuggestions',N'$.Data.SceneLocationSuggestions',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'SceneTextStatistics',N'$.Data.SceneTextStatistics',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'CoreImportBasicLocationReviews',N'$.Data.CoreImportBasicLocationReviews',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'CoreImportBasicLocationCandidates',N'$.Data.CoreImportBasicLocationCandidates',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'CoreImportBasicLocationEvidence',N'$.Data.CoreImportBasicLocationEvidence',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryIntelligenceRuns',N'$.Data.StoryIntelligenceRuns',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryIntelligenceChapterResults',N'$.Data.StoryIntelligenceChapterResults',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryIntelligenceSceneResults',N'$.Data.StoryIntelligenceSceneResults',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryIntelligenceImportCommits',N'$.Data.StoryIntelligenceImportCommits',@JsonData,@ProjectID,0;
DECLARE EnableCursor CURSOR LOCAL FAST_FORWARD FOR SELECT TableName FROM @RestoreTables;
OPEN EnableCursor;
FETCH NEXT FROM EnableCursor INTO @TableName;
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @EnableSql nvarchar(max) = N'ALTER TABLE dbo.' + QUOTENAME(@TableName) + N' WITH CHECK CHECK CONSTRAINT ALL;';
EXEC (@EnableSql);
FETCH NEXT FROM EnableCursor INTO @TableName;
END
CLOSE EnableCursor;
DEALLOCATE EnableCursor;
IF @SourceRestorePointID IS NOT NULL AND @SafetyRestorePointID IS NOT NULL
BEGIN
INSERT INTO dbo.ProjectRestoreHistory (ProjectID, SourceRestorePointID, SafetyRestorePointID, PerformedBy, Notes)
VALUES (@ProjectID, @SourceRestorePointID, @SafetyRestorePointID, SUSER_SNAME(), N'Project restored from saved restore point.');
END;
COMMIT TRANSACTION;
END;
GO