Preserve character enrichment evidence and explain safe restore refusals

This commit is contained in:
Nick Beckley 2026-11-04 04:13:33 +00:00
parent 3177484f2f
commit 57625e0b02
12 changed files with 724 additions and 10 deletions

View File

@ -18,8 +18,8 @@ Chapters,ProjectID or FK descendant,Chapters,Serialized persistent set; populate
CharacterAliases,ProjectID or FK descendant,CharacterAliases,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
CharacterAttributeEvents,ProjectID or FK descendant,CharacterAttributeEvents,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
CharacterAttributeTypes,ProjectID or FK descendant,CharacterAttributeTypes,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
CharacterEnrichmentEvidence,ProjectID or FK descendant,,Pending classification,Pending,Pending
CharacterEnrichmentRuns,ProjectID or FK descendant,,Pending classification,Pending,Pending
CharacterEnrichmentEvidence,ProjectID or FK descendant,CharacterEnrichmentEvidence,Persisted enrichment run audit and scene/book-wide evidence; full stored projection,Pass: completed/failed histories; owner/character/book/pipeline/scene remapping; exact evidence; in-place; missing/active guards,No file columns; canonical character images are handled by the separate file manifest; no provider invocation
CharacterEnrichmentRuns,ProjectID or FK descendant,CharacterEnrichmentRuns,Persisted enrichment run audit and scene/book-wide evidence; full stored projection,Pass: completed/failed histories; owner/character/book/pipeline/scene remapping; exact evidence; in-place; missing/active guards,No file columns; canonical character images are handled by the separate file manifest; no provider invocation
CharacterImages,ProjectID or FK descendant,CharacterImages,Version 1.3 gallery metadata including deleted history; populated stored-value comparison passed,"Copy/in-place graph, avatar target, metadata and SQL failure rollback passed","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"
CharacterIntelligenceEvidenceEvents,ProjectID or FK descendant,CharacterIntelligenceEvidenceEvents,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
CharacterIntelligenceProfiles,ProjectID or FK descendant,CharacterIntelligenceProfiles,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained

1 Table ProjectOwnershipEvidence BackupCollection Classification RestoreVerified AssetsVerified
18 CharacterAliases ProjectID or FK descendant CharacterAliases 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
19 CharacterAttributeEvents ProjectID or FK descendant CharacterAttributeEvents 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
20 CharacterAttributeTypes ProjectID or FK descendant CharacterAttributeTypes 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
21 CharacterEnrichmentEvidence ProjectID or FK descendant CharacterEnrichmentEvidence Pending classification Persisted enrichment run audit and scene/book-wide evidence; full stored projection Pending Pass: completed/failed histories; owner/character/book/pipeline/scene remapping; exact evidence; in-place; missing/active guards Pending No file columns; canonical character images are handled by the separate file manifest; no provider invocation
22 CharacterEnrichmentRuns ProjectID or FK descendant CharacterEnrichmentRuns Pending classification Persisted enrichment run audit and scene/book-wide evidence; full stored projection Pending Pass: completed/failed histories; owner/character/book/pipeline/scene remapping; exact evidence; in-place; missing/active guards Pending No file columns; canonical character images are handled by the separate file manifest; no provider invocation
23 CharacterImages ProjectID or FK descendant CharacterImages Version 1.3 gallery metadata including deleted history; populated stored-value comparison passed Copy/in-place graph, avatar target, metadata and SQL failure rollback passed 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
24 CharacterIntelligenceEvidenceEvents ProjectID or FK descendant CharacterIntelligenceEvidenceEvents Persistent pipeline/memory/profile evidence graph; complete stored projection Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
25 CharacterIntelligenceProfiles ProjectID or FK descendant CharacterIntelligenceProfiles Persistent pipeline/memory/profile evidence graph; complete stored projection Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained

View File

@ -144,6 +144,42 @@ CharacterAttributeTypes,CharacterAttributeTypes,DataType,nvarchar,False,False,Tr
CharacterAttributeTypes,CharacterAttributeTypes,IsNormallyStable,bit,False,False,True,Represented; projection and semantic comparison still required
CharacterAttributeTypes,CharacterAttributeTypes,SortOrder,int,False,False,True,Represented; projection and semantic comparison still required
CharacterAttributeTypes,CharacterAttributeTypes,IsActive,bit,False,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentEvidence,CharacterEnrichmentEvidence,CharacterEnrichmentEvidenceID,int,False,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentEvidence,CharacterEnrichmentEvidence,CharacterEnrichmentRunID,int,False,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentEvidence,CharacterEnrichmentEvidence,CharacterID,int,False,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentEvidence,CharacterEnrichmentEvidence,SceneID,int,True,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentEvidence,CharacterEnrichmentEvidence,FieldName,nvarchar,False,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentEvidence,CharacterEnrichmentEvidence,Value,nvarchar,True,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentEvidence,CharacterEnrichmentEvidence,Evidence,nvarchar,True,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentEvidence,CharacterEnrichmentEvidence,Confidence,decimal,False,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentEvidence,CharacterEnrichmentEvidence,Source,nvarchar,False,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentEvidence,CharacterEnrichmentEvidence,CreatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,CharacterEnrichmentRunID,int,False,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,ProjectID,int,False,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,BookID,int,False,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,UserID,int,False,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,StoryIntelligenceBookPipelineID,int,True,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,CharacterResolutionVersion,nvarchar,False,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,Status,nvarchar,False,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,TotalCharacters,int,False,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,ProcessedCharacters,int,False,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,CurrentStage,nvarchar,True,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,CurrentMessage,nvarchar,True,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,QueuedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,StartedUtc,datetime2,True,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,CompletedUtc,datetime2,True,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,FailedUtc,datetime2,True,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,AttemptCount,int,False,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,Model,nvarchar,True,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,InputTokens,int,True,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,OutputTokens,int,True,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,TotalTokens,int,True,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,DurationMs,bigint,True,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,ErrorMessage,nvarchar,True,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,ErrorDetail,nvarchar,True,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,IsCurrent,bit,False,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,UpdatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
CharacterEnrichmentRuns,CharacterEnrichmentRuns,CharacterID,int,True,False,True,Represented; projection and semantic comparison still required
CharacterImages,CharacterImages,CharacterImageID,int,False,False,True,Represented; projection and semantic comparison still required
CharacterImages,CharacterImages,CharacterID,int,False,False,True,Represented; projection and semantic comparison still required
CharacterImages,CharacterImages,ProjectID,int,False,False,True,Represented; projection and semantic comparison still required

1 Table Collection Column SqlType Nullable Computed WritableModelProperty Classification
144 CharacterAttributeTypes CharacterAttributeTypes IsNormallyStable bit False False True Represented; projection and semantic comparison still required
145 CharacterAttributeTypes CharacterAttributeTypes SortOrder int False False True Represented; projection and semantic comparison still required
146 CharacterAttributeTypes CharacterAttributeTypes IsActive bit False False True Represented; projection and semantic comparison still required
147 CharacterEnrichmentEvidence CharacterEnrichmentEvidence CharacterEnrichmentEvidenceID int False False True Represented; projection and semantic comparison still required
148 CharacterEnrichmentEvidence CharacterEnrichmentEvidence CharacterEnrichmentRunID int False False True Represented; projection and semantic comparison still required
149 CharacterEnrichmentEvidence CharacterEnrichmentEvidence CharacterID int False False True Represented; projection and semantic comparison still required
150 CharacterEnrichmentEvidence CharacterEnrichmentEvidence SceneID int True False True Represented; projection and semantic comparison still required
151 CharacterEnrichmentEvidence CharacterEnrichmentEvidence FieldName nvarchar False False True Represented; projection and semantic comparison still required
152 CharacterEnrichmentEvidence CharacterEnrichmentEvidence Value nvarchar True False True Represented; projection and semantic comparison still required
153 CharacterEnrichmentEvidence CharacterEnrichmentEvidence Evidence nvarchar True False True Represented; projection and semantic comparison still required
154 CharacterEnrichmentEvidence CharacterEnrichmentEvidence Confidence decimal False False True Represented; projection and semantic comparison still required
155 CharacterEnrichmentEvidence CharacterEnrichmentEvidence Source nvarchar False False True Represented; projection and semantic comparison still required
156 CharacterEnrichmentEvidence CharacterEnrichmentEvidence CreatedUtc datetime2 False False True Represented; projection and semantic comparison still required
157 CharacterEnrichmentRuns CharacterEnrichmentRuns CharacterEnrichmentRunID int False False True Represented; projection and semantic comparison still required
158 CharacterEnrichmentRuns CharacterEnrichmentRuns ProjectID int False False True Represented; projection and semantic comparison still required
159 CharacterEnrichmentRuns CharacterEnrichmentRuns BookID int False False True Represented; projection and semantic comparison still required
160 CharacterEnrichmentRuns CharacterEnrichmentRuns UserID int False False True Represented; projection and semantic comparison still required
161 CharacterEnrichmentRuns CharacterEnrichmentRuns StoryIntelligenceBookPipelineID int True False True Represented; projection and semantic comparison still required
162 CharacterEnrichmentRuns CharacterEnrichmentRuns CharacterResolutionVersion nvarchar False False True Represented; projection and semantic comparison still required
163 CharacterEnrichmentRuns CharacterEnrichmentRuns Status nvarchar False False True Represented; projection and semantic comparison still required
164 CharacterEnrichmentRuns CharacterEnrichmentRuns TotalCharacters int False False True Represented; projection and semantic comparison still required
165 CharacterEnrichmentRuns CharacterEnrichmentRuns ProcessedCharacters int False False True Represented; projection and semantic comparison still required
166 CharacterEnrichmentRuns CharacterEnrichmentRuns CurrentStage nvarchar True False True Represented; projection and semantic comparison still required
167 CharacterEnrichmentRuns CharacterEnrichmentRuns CurrentMessage nvarchar True False True Represented; projection and semantic comparison still required
168 CharacterEnrichmentRuns CharacterEnrichmentRuns QueuedUtc datetime2 False False True Represented; projection and semantic comparison still required
169 CharacterEnrichmentRuns CharacterEnrichmentRuns StartedUtc datetime2 True False True Represented; projection and semantic comparison still required
170 CharacterEnrichmentRuns CharacterEnrichmentRuns CompletedUtc datetime2 True False True Represented; projection and semantic comparison still required
171 CharacterEnrichmentRuns CharacterEnrichmentRuns FailedUtc datetime2 True False True Represented; projection and semantic comparison still required
172 CharacterEnrichmentRuns CharacterEnrichmentRuns AttemptCount int False False True Represented; projection and semantic comparison still required
173 CharacterEnrichmentRuns CharacterEnrichmentRuns Model nvarchar True False True Represented; projection and semantic comparison still required
174 CharacterEnrichmentRuns CharacterEnrichmentRuns InputTokens int True False True Represented; projection and semantic comparison still required
175 CharacterEnrichmentRuns CharacterEnrichmentRuns OutputTokens int True False True Represented; projection and semantic comparison still required
176 CharacterEnrichmentRuns CharacterEnrichmentRuns TotalTokens int True False True Represented; projection and semantic comparison still required
177 CharacterEnrichmentRuns CharacterEnrichmentRuns DurationMs bigint True False True Represented; projection and semantic comparison still required
178 CharacterEnrichmentRuns CharacterEnrichmentRuns ErrorMessage nvarchar True False True Represented; projection and semantic comparison still required
179 CharacterEnrichmentRuns CharacterEnrichmentRuns ErrorDetail nvarchar True False True Represented; projection and semantic comparison still required
180 CharacterEnrichmentRuns CharacterEnrichmentRuns IsCurrent bit False False True Represented; projection and semantic comparison still required
181 CharacterEnrichmentRuns CharacterEnrichmentRuns UpdatedUtc datetime2 False False True Represented; projection and semantic comparison still required
182 CharacterEnrichmentRuns CharacterEnrichmentRuns CharacterID int True False True Represented; projection and semantic comparison still required
183 CharacterImages CharacterImages CharacterImageID int False False True Represented; projection and semantic comparison still required
184 CharacterImages CharacterImages CharacterID int False False True Represented; projection and semantic comparison still required
185 CharacterImages CharacterImages ProjectID int False False True Represented; projection and semantic comparison still required

View File

@ -1,4 +1,6 @@
Collection,SourceRows,CopyRows,InPlaceRows,Verification
CharacterEnrichmentRuns,2,2,2,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
CharacterEnrichmentEvidence,2,2,2,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
StoryIntelligenceReviewCandidateGenerations,5,5,5,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
StoryIntelligenceReviewCandidates,16,16,16,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
StoryIntelligenceReviewCandidateEvidence,16,16,16,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present

1 Collection SourceRows CopyRows InPlaceRows Verification
2 CharacterEnrichmentRuns 2 2 2 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
3 CharacterEnrichmentEvidence 2 2 2 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
4 StoryIntelligenceReviewCandidateGenerations 5 5 5 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
5 StoryIntelligenceReviewCandidates 16 16 16 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
6 StoryIntelligenceReviewCandidateEvidence 16 16 16 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 98 collections (94 persistent plus 4 diagnostic/shared vocabulary), 99 SQL entities / 1,226 columns with no missing non-computed model properties. All 94 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 narrative synthesis, enrichment and illustration graphs. Operational account reference preservation now passes. 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.
5. COMPLETE CHECKPOINT: serialized backup/restore coverage now has 100 collections (96 persistent plus 4 diagnostic/shared vocabulary), 101 SQL entities / 1,262 columns with no missing non-computed model properties. All 96 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 narrative synthesis and illustration graphs. Enrichment evidence now passes. Operational account reference preservation now passes. 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.
@ -290,3 +290,13 @@ Migration 226 keeps these existing account rows rather than replacing them from
Verification passed the full 94-collection stored-value matrix plus exact retained account/activity snapshots: source account unchanged by copy, no copied consent/job/onboarding authority or original activity event, newer operational values retained through actual restore, active-job refusal, protected-book removal refusal and real removal of an unprotected navigation-only book with safe pointer clearing. The first activity fixture used an invalid enum token; corrected to the existing Updated token from the authoritative check constraint (fixture issue, not product defect). Build zero warnings/errors. Evidence `/tmp/plotdirector-phase2-account-links-before.log` (restore failure), `account-links-after.log`, `account-activity.log` (fixture enum), `account-activity-final.log` (pass), `build-account-activity.log`, `account-core.log` (all `/tmp/plotdirector-phase2-` prefix). No Development writes/restart.
Operational-reference checkpoint: focused Core Import SQL/source/provenance restore passed with the new account references present (`/tmp/plotdirector-phase2-account-core.log`). Full 405-check regression harness passed, exit 0 (`/tmp/plotdirector-phase2-tests-account-links.log`). Schema remains unchanged; 99 serialized entities / 1,226 fields. Migration 226 remains synthetic-only.
## Character enrichment evidence and actionable restore refusals — 4 November
Confirmed two omitted persistent sets: character enrichment run audit and its scene/book-wide evidence. Migration 227 and complete DTOs now carry completed and failed histories, usage/duration/error metadata, current flags, canonical character/book/pipeline references and evidence values/text/confidence. Copy remaps owner and references. Unfinished enrichment is copied as failed/inactive history with a clear warning; it cannot be claimed as queued/running work. Current or snapshot unfinished enrichment is refused before restore mutation, and both missing old-shaped collections are independently protected.
The restore service previously hid even safe, fixed preflight refusal reasons behind a generic error. It now returns the application-defined 51006–51020 refusal message with confirmation that the safety backup was retained; unexpected SQL failures keep the generic response. A real service call against a synthetic Running enrichment run verified the actionable message, retained safety backup and complete staged-file cleanup; the fixture status resets in finally.
Real SQL matrix passed all 96 populated persistent collections (100 serialized collections): source 2,073 stored values across 99 populated entities; copy 1,951 generic comparisons plus module-specific review assertions; in-place 2,037. Invalid preview count now 40, with no allocation. Field census 101 entities / 1,262 columns / zero missing non-computed model properties. Build zero warnings/errors. Evidence `/tmp/plotdirector-phase2-enrichment-before.log`, `enrichment-after.log`, `build-enrichment-guards.log`, `census-enrichment.log` (all `/tmp/plotdirector-phase2-` prefix). No paid provider, worker or Development writes/deployment.
Enrichment checkpoint: full 405-check regression harness passed, exit 0 (`/tmp/plotdirector-phase2-tests-enrichment.log`). Migration 227 remains applied only in the isolated synthetic database.

View File

@ -208,3 +208,12 @@ INSERT dbo.StoryIntelligenceJobs(StoryIntelligenceJobID,StoryIntelligenceConsent
VALUES(NEWID(),@consent,@user,@project,@book,N'Completed','2026-11-01','2026-11-02',100,N'Completed',N'Synthetic completed operational audit Ω');
INSERT dbo.ProjectActivity(ProjectID,UserID,ActivityType,EntityType,EntityID,EntityName,Description) VALUES(@project,@user,N'Updated',N'Book',@book,N'Synthetic book Ω',N'Retained synthetic activity audit 雨');
DECLARE @enrichment int;
INSERT dbo.CharacterEnrichmentRuns(ProjectID,BookID,UserID,CharacterID,StoryIntelligenceBookPipelineID,CharacterResolutionVersion,Status,TotalCharacters,ProcessedCharacters,CurrentStage,CurrentMessage,StartedUtc,CompletedUtc,AttemptCount,Model,InputTokens,OutputTokens,TotalTokens,DurationMs,IsCurrent)
VALUES(@project,@book,@user,@character,@pipeline,N'synthetic-enrichment-v1',N'Completed',1,1,N'Completed',N'Synthetic enrichment evidence retained Ω','2026-11-01','2026-11-02',2,N'synthetic-no-provider',150,50,200,2500,1);
SET @enrichment=SCOPE_IDENTITY();
INSERT dbo.CharacterEnrichmentEvidence(CharacterEnrichmentRunID,CharacterID,SceneID,FieldName,Value,Evidence,Confidence,Source)
VALUES(@enrichment,@character,@scene,N'EyeColour',N'Grey',N'“Grey eyes”—source evidence 雨',.95,N'Synthetic source'),(@enrichment,@character,NULL,N'Role',N'Narrator Ω',N'Book-wide source evidence café',.8,N'Synthetic book context');
INSERT dbo.CharacterEnrichmentRuns(ProjectID,BookID,UserID,StoryIntelligenceBookPipelineID,CharacterResolutionVersion,Status,TotalCharacters,ProcessedCharacters,CurrentStage,CurrentMessage,StartedUtc,FailedUtc,AttemptCount,Model,ErrorMessage,ErrorDetail,IsCurrent)
VALUES(@project,@book,@user,@pipeline,N'synthetic-enrichment-failed',N'Failed',2,0,N'Failed',N'Synthetic prior failure audit','2026-10-01','2026-10-01',1,N'synthetic-no-provider',N'Synthetic error Ω',N'{"error":"Synthetic retained failure 雨"}',0);

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","PlotLine/Sql/223_ProjectBackupAnalysisAudit.sql","PlotLine/Sql/224_ProjectBackupStoryMemory.sql","PlotLine/Sql/225_ProjectBackupEntityReviews.sql","PlotLine/Sql/226_ProjectRestoreAccountReferences.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","PlotLine/Sql/224_ProjectBackupStoryMemory.sql","PlotLine/Sql/225_ProjectBackupEntityReviews.sql","PlotLine/Sql/226_ProjectRestoreAccountReferences.sql","PlotLine/Sql/227_ProjectBackupCharacterEnrichment.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.");
@ -163,7 +163,7 @@ internal static class ProjectTransferDatabaseTests
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","StoryIntelligenceRuns","StoryIntelligenceChapterResults","StoryIntelligenceSceneResults","StoryIntelligenceImportCommits","StoryIntelligenceBookPipelines","StoryMemoryCharacters","StoryMemoryCharacterAliases","StoryMemoryCharacterAttributes","StoryMemoryLocations","StoryMemoryAssets","StoryMemoryRelationships","StoryMemoryProcessedSceneResults","StoryMemoryImportPreferences","CharacterIntelligenceProfiles","CharacterIntelligenceEvidenceEvents","StoryIntelligenceReviewCandidateGenerations","StoryIntelligenceReviewCandidates","StoryIntelligenceReviewCandidateEvidence"})
foreach(var required in new[]{"SceneAssetSuggestions","SceneCharacterSuggestions","SceneLocationSuggestions","SceneTextStatistics","CoreImportBasicLocationReviews","CoreImportBasicLocationCandidates","CoreImportBasicLocationEvidence","StoryIntelligenceRuns","StoryIntelligenceChapterResults","StoryIntelligenceSceneResults","StoryIntelligenceImportCommits","StoryIntelligenceBookPipelines","StoryMemoryCharacters","StoryMemoryCharacterAliases","StoryMemoryCharacterAttributes","StoryMemoryLocations","StoryMemoryAssets","StoryMemoryRelationships","StoryMemoryProcessedSceneResults","StoryMemoryImportPreferences","CharacterIntelligenceProfiles","CharacterIntelligenceEvidenceEvents","StoryIntelligenceReviewCandidateGenerations","StoryIntelligenceReviewCandidates","StoryIntelligenceReviewCandidateEvidence","CharacterEnrichmentRuns","CharacterEnrichmentEvidence"})
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.");
@ -222,6 +222,8 @@ internal static class ProjectTransferDatabaseTests
root=>root["Data"]!["StoryIntelligenceReviewCandidates"]![0]!["Module"]="Assets",
root=>root["Data"]!["StoryIntelligenceReviewCandidates"]![0]!["CandidatePayloadJson"]=null,
root=>root["Data"]!["StoryIntelligenceReviewCandidates"]![0]!["CandidatePayloadJson"]="[]",
root=>root["Data"]!["CharacterEnrichmentEvidence"]![0]!["CharacterEnrichmentRunID"]=-12345,
root=>root["Data"]!["CharacterEnrichmentRuns"]![0]!["CharacterID"]=-12345,
root=> { var row=root["Data"]!["StoryIntelligenceReviewCandidates"]![12]!;var payload=System.Text.Json.Nodes.JsonNode.Parse(row["CandidatePayloadJson"]!.GetValue<string>())!;payload["observations"]![0]!["sceneID"]=-12345;row["CandidatePayloadJson"]=payload.ToJsonString(); },
root=> { var row=root["Data"]!["StoryIntelligenceReviewCandidates"]![0]!;var payload=System.Text.Json.Nodes.JsonNode.Parse(row["CandidatePayloadJson"]!.GetValue<string>())!;payload["key"]="different-review-key";row["CandidatePayloadJson"]=payload.ToJsonString(); },
root=>root["Data"]!["MapReferenceImages"]![0]!["ImageData"]="",
@ -357,6 +359,32 @@ internal static class ProjectTransferDatabaseTests
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=protectedBookRemoval.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore removed a book required by immutable account consent/job history."); }
catch(SqlException error) when(error.Number==51018) { }
var accountStateAtRestore=await AccountStateAsync();
foreach(var omitted in new[]{"CharacterEnrichmentRuns","CharacterEnrichmentEvidence"})
{
var older=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!;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 enrichment evidence."); }
catch(SqlException error) when(error.Number==51019) { }
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterEnrichmentEvidence WHERE CharacterID=@character",new{character})==2,"Refused snapshot preserves enrichment evidence.");
}
var unfinishedEnrichment=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!;
unfinishedEnrichment["Data"]!["CharacterEnrichmentRuns"]![0]!["Status"]="Queued";
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=unfinishedEnrichment.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore requeued paid enrichment."); }
catch(SqlException error) when(error.Number==51020) { }
Check((await service.PreviewAsync(new(){JsonText=unfinishedEnrichment.ToJsonString()})).Preview!.Validation.Warnings.Any(w=>w.Contains("Unfinished character enrichment",StringComparison.Ordinal)),"Unfinished enrichment warning is explicit.");
var enrichmentCopy=await service.ImportAsync(new(){JsonText=unfinishedEnrichment.ToJsonString(),ConfirmImport=true,AcknowledgeWarnings=true,AllowDuplicateProjectTitle=true});
Check(enrichmentCopy.Succeeded,"Incomplete enrichment copy retains failed, inactive history: "+enrichmentCopy.TechnicalDetail);
var copiedEnrichment=(await backups.GetProjectBackupAsync(enrichmentCopy.ProjectID!.Value,importingUser))!;
Check(copiedEnrichment.Data.CharacterEnrichmentRuns.All(run=>run.Status=="Failed" && !run.IsCurrent) && copiedEnrichment.Data.CharacterEnrichmentEvidence.Count==2,"Copied enrichment cannot be claimed as queued/running work; evidence remains intact.");
var sourceEnrichment=before.Data.CharacterEnrichmentRuns.First().CharacterEnrichmentRunID;
await db.ExecuteAsync("UPDATE dbo.CharacterEnrichmentRuns SET Status=N'Running' WHERE CharacterEnrichmentRunID=@id",new{id=sourceEnrichment});
try
{
var stagedFiles=Directory.GetFiles(uploadRoot,"*",SearchOption.AllDirectories).Order().ToArray();
var refusal=await restoreService.RestoreAsync(project,savedPoint.ProjectRestorePointID);
Check(!refusal.Succeeded && refusal.SafetyBackup is not null && refusal.Message.Contains("Character enrichment is unfinished",StringComparison.Ordinal),"Actual restore service returns the actionable safe preflight refusal and retains its safety backup.");
Check(stagedFiles.SequenceEqual(Directory.GetFiles(uploadRoot,"*",SearchOption.AllDirectories).Order()),"Preflight refusal removes staged files without changing existing uploads.");
}
finally { await db.ExecuteAsync("UPDATE dbo.CharacterEnrichmentRuns SET Status=N'Completed' WHERE CharacterEnrichmentRunID=@id",new{id=sourceEnrichment}); }
foreach(var omitted in new[]{"StoryIntelligenceReviewCandidateGenerations","StoryIntelligenceReviewCandidates","StoryIntelligenceReviewCandidateEvidence"})
{
var older=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!;older["Data"]!.AsObject().Remove(omitted);
@ -497,7 +525,7 @@ internal static class ProjectTransferDatabaseTests
var removeNavigationBook=await restoreService.RestoreAsync(project,savedPoint.ProjectRestorePointID);
Check(removeNavigationBook.Succeeded && await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Books WHERE BookID=@navigationBook",new{navigationBook})==0 && await db.ExecuteScalarAsync<int?>("SELECT BookID FROM dbo.UserOnboardingState WHERE UserID=@user",new{user}) is null,"Restore clears an account navigation pointer only when its unprotected book is deliberately removed.");
Console.WriteLine("PASS retained account/consent/job state: source unchanged by copy; no copied authority; completed history survives restore; active jobs/protected book removal refused; removed-book navigation pointer cleared.");
Console.WriteLine("PASS 94 populated persistent collections: copy/in-place stored values and actual safety/rollback; unrepresented project tables remain pending.");
Console.WriteLine("PASS 96 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)
{
@ -543,7 +571,7 @@ internal static class ProjectTransferDatabaseTests
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")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(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" or "CharacterEnrichmentRuns" && 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(column=="SourceReviewKey" && collection.Name=="CharacterKnowledge")expected=$"{restored.Data.Characters.Single(x=>x.CharacterName=="Narrator Ω").CharacterID}:knows:synthetic-proof-2";

View File

@ -134,6 +134,9 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
data.StoryIntelligenceReviewCandidateGenerations = (await state.ReadAsync<ProjectBackupStoryIntelligenceReviewCandidateGenerations>()).ToList();
data.StoryIntelligenceReviewCandidates = (await state.ReadAsync<ProjectBackupStoryIntelligenceReviewCandidates>()).ToList();
data.StoryIntelligenceReviewCandidateEvidence = (await state.ReadAsync<ProjectBackupStoryIntelligenceReviewCandidateEvidence>()).ToList();
data.CharacterEnrichmentRuns = (await state.ReadAsync<ProjectBackupCharacterEnrichmentRuns>()).ToList();
data.CharacterEnrichmentEvidence = (await state.ReadAsync<ProjectBackupCharacterEnrichmentEvidence>()).ToList();
@ -178,6 +181,8 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
ProjectId = projectId,
IncludedEntitySets =
[
nameof(data.CharacterEnrichmentRuns),
nameof(data.CharacterEnrichmentEvidence),
nameof(data.StoryIntelligenceReviewCandidateGenerations),
nameof(data.StoryIntelligenceReviewCandidates),
nameof(data.StoryIntelligenceReviewCandidateEvidence),

View File

@ -14,6 +14,9 @@ public sealed class ProjectBackupExport
public sealed class ProjectBackupData
{
public IReadOnlyList<ProjectBackupCharacterEnrichmentRuns> CharacterEnrichmentRuns { get; set; } = [];
public IReadOnlyList<ProjectBackupCharacterEnrichmentEvidence> CharacterEnrichmentEvidence { get; set; } = [];
public IReadOnlyList<ProjectBackupStoryIntelligenceReviewCandidateGenerations> StoryIntelligenceReviewCandidateGenerations { get; set; } = [];
public IReadOnlyList<ProjectBackupStoryIntelligenceReviewCandidates> StoryIntelligenceReviewCandidates { get; set; } = [];
public IReadOnlyList<ProjectBackupStoryIntelligenceReviewCandidateEvidence> StoryIntelligenceReviewCandidateEvidence { get; set; } = [];
@ -800,3 +803,47 @@ public sealed class ProjectBackupStoryIntelligenceReviewCandidateEvidence
public int SortOrder { get; set; }
public DateTime CreatedUtc { get; set; }
}
public sealed class ProjectBackupCharacterEnrichmentRuns
{
public int CharacterEnrichmentRunID { get; set; }
public int ProjectID { get; set; }
public int BookID { get; set; }
public int UserID { get; set; }
public int? StoryIntelligenceBookPipelineID { get; set; }
public string CharacterResolutionVersion { get; set; } = "";
public string Status { get; set; } = "";
public int TotalCharacters { get; set; }
public int ProcessedCharacters { get; set; }
public string? CurrentStage { get; set; }
public string? CurrentMessage { get; set; }
public DateTime QueuedUtc { get; set; }
public DateTime? StartedUtc { get; set; }
public DateTime? CompletedUtc { get; set; }
public DateTime? FailedUtc { get; set; }
public int AttemptCount { get; set; }
public string? Model { get; set; }
public int? InputTokens { get; set; }
public int? OutputTokens { get; set; }
public int? TotalTokens { get; set; }
public long? DurationMs { get; set; }
public string? ErrorMessage { get; set; }
public string? ErrorDetail { get; set; }
public bool IsCurrent { get; set; }
public DateTime UpdatedUtc { get; set; }
public int? CharacterID { get; set; }
}
public sealed class ProjectBackupCharacterEnrichmentEvidence
{
public int CharacterEnrichmentEvidenceID { get; set; }
public int CharacterEnrichmentRunID { get; set; }
public int CharacterID { get; set; }
public int? SceneID { get; set; }
public string FieldName { get; set; } = "";
public string? Value { get; set; }
public string? Evidence { get; set; }
public decimal Confidence { get; set; }
public string Source { 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.CharacterEnrichmentRuns.Any(run=>run.Status is not ("Completed" or "Failed" or "Superseded")))
validation.Warnings.Add("Unfinished character enrichment is copied as failed, inactive history. Analysis must be requested explicitly; no paid work is restarted.");
if(backup.Data.StoryIntelligenceReviewCandidateGenerations.Any(generation=>generation.Status=="Preparing"))
validation.Warnings.Add("Unfinished candidate preparation is retained as failed, inactive history in the copy. Candidate preparation must be requested explicitly.");
if(backup.Data.StoryIntelligenceBookPipelines.Any(pipeline=>pipeline.Status is not ("Complete" or "NeedsReview")))
@ -847,7 +849,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
private static readonly string[] ProjectBackupIdentityTables =
[
"ProjectTimelineSettings", "TimelineViewPresets", "SceneMetricTypes", "Books", "Chapters", "Scenes", "StoryMaps",
"StoryIntelligenceReviewCandidateGenerations", "StoryIntelligenceReviewCandidates", "StoryIntelligenceReviewCandidateEvidence", "StoryIntelligenceBookPipelines", "StoryMemoryCharacters", "StoryMemoryCharacterAliases", "StoryMemoryCharacterAttributes", "StoryMemoryLocations", "StoryMemoryAssets", "StoryMemoryRelationships", "StoryMemoryProcessedSceneResults", "StoryMemoryImportPreferences", "CharacterIntelligenceProfiles", "CharacterIntelligenceEvidenceEvents", "StoryIntelligenceRuns", "StoryIntelligenceChapterResults", "StoryIntelligenceSceneResults", "StoryIntelligenceImportCommits", "CoreImportBasicLocationReviews", "CoreImportBasicLocationCandidates", "CoreImportBasicLocationEvidence", "SceneAssetSuggestions", "SceneCharacterSuggestions", "SceneLocationSuggestions", "OnboardingManuscriptBuilds", "CharacterImages", "WordCompanionSceneAssets", "WordCompanionSceneLocations", "ManuscriptDocuments", "WritingPlans", "WritingScheduleItems", "CharacterAliases", "AssetAliases", "LocationAliases", "AuthorPlotSeeds", "ContinuityWarningAcknowledgements",
"CharacterEnrichmentRuns", "CharacterEnrichmentEvidence", "StoryIntelligenceReviewCandidateGenerations", "StoryIntelligenceReviewCandidates", "StoryIntelligenceReviewCandidateEvidence", "StoryIntelligenceBookPipelines", "StoryMemoryCharacters", "StoryMemoryCharacterAliases", "StoryMemoryCharacterAttributes", "StoryMemoryLocations", "StoryMemoryAssets", "StoryMemoryRelationships", "StoryMemoryProcessedSceneResults", "StoryMemoryImportPreferences", "CharacterIntelligenceProfiles", "CharacterIntelligenceEvidenceEvents", "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",
@ -1788,6 +1790,28 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
row.ReviewCandidateID=ExistingOrNew("StoryIntelligenceReviewCandidates",row.ReviewCandidateID);
row.SceneID=ExistingOrNewNullable("Scenes",row.SceneID);
}
foreach(var row in backup.Data.CharacterEnrichmentRuns)
{
row.CharacterEnrichmentRunID=NewId("CharacterEnrichmentRuns",row.CharacterEnrichmentRunID);
row.ProjectID=projectId;
row.BookID=ExistingOrNew("Books",row.BookID);
row.UserID=importingUserId;
row.StoryIntelligenceBookPipelineID=ExistingOrNewNullable("StoryIntelligenceBookPipelines",row.StoryIntelligenceBookPipelineID);
row.CharacterID=ExistingOrNewNullable("Characters",row.CharacterID);
if(row.Status is not ("Completed" or "Failed" or "Superseded"))
{
row.Status="Failed";row.IsCurrent=false;row.CurrentStage="Failed";
row.CurrentMessage="Copied unfinished enrichment; analysis was not resumed.";
row.ErrorMessage="Copied unfinished enrichment; explicit analysis is required.";
}
}
foreach(var row in backup.Data.CharacterEnrichmentEvidence)
{
row.CharacterEnrichmentEvidenceID=NewId("CharacterEnrichmentEvidence",row.CharacterEnrichmentEvidenceID);
row.CharacterEnrichmentRunID=ExistingOrNew("CharacterEnrichmentRuns",row.CharacterEnrichmentRunID);
row.CharacterID=ExistingOrNew("Characters",row.CharacterID);
row.SceneID=ExistingOrNewNullable("Scenes",row.SceneID);
}
foreach (var image in backup.Data.CharacterImages)
{
image.CharacterImageID=NewId("CharacterImages",image.CharacterImageID);

View File

@ -8,6 +8,8 @@ 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("CharacterEnrichmentRuns","CharacterEnrichmentRunID",new Link("ProjectID","Project","ProjectID"),new Link("BookID","Books","BookID"),new Link("StoryIntelligenceBookPipelineID","StoryIntelligenceBookPipelines","StoryIntelligenceBookPipelineID"),new Link("CharacterID","Characters","CharacterID")),
new("CharacterEnrichmentEvidence","CharacterEnrichmentEvidenceID",new Link("CharacterEnrichmentRunID","CharacterEnrichmentRuns","CharacterEnrichmentRunID"),new Link("CharacterID","Characters","CharacterID"),new Link("SceneID","Scenes","SceneID")),
new("StoryIntelligenceReviewCandidateGenerations","ReviewCandidateGenerationID",new Link("ProjectID","Project","ProjectID"),new Link("BookID","Books","BookID")),
new("StoryIntelligenceReviewCandidates","ReviewCandidateID",new Link("ReviewCandidateGenerationID","StoryIntelligenceReviewCandidateGenerations","ReviewCandidateGenerationID"),new Link("ProjectID","Project","ProjectID"),new Link("BookID","Books","BookID")),
new("StoryIntelligenceReviewCandidateEvidence","ReviewCandidateEvidenceID",new Link("ReviewCandidateID","StoryIntelligenceReviewCandidates","ReviewCandidateID"),new Link("SceneID","Scenes","SceneID")),

View File

@ -93,7 +93,11 @@ public sealed class ProjectRestoreService(
return new ProjectRestoreResult
{
Succeeded = false,
Message = "Restore failed. The safety backup was created, and the project data was left unchanged.",
// These application-defined preflight errors contain fixed, actionable messages.
// Unexpected SQL errors still use the generic response below.
Message = ex is Microsoft.Data.SqlClient.SqlException { Number: >= 51006 and <= 51020 } refusal
? refusal.Message + " The safety backup was retained."
: "Restore failed. The safety backup was created, and the project data was left unchanged.",
SafetyBackup = safetyBackup
};
}

View File

@ -0,0 +1,547 @@
-- Version 1.3 additive paid character-enrichment evidence and run 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;
SELECT r.* FROM dbo.StoryIntelligenceBookPipelines r WHERE r.ProjectID=@ProjectID ORDER BY r.StoryIntelligenceBookPipelineID;
SELECT r.* FROM dbo.StoryMemoryCharacters r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID ORDER BY r.StoryMemoryCharacterID;
SELECT r.* FROM dbo.StoryMemoryCharacterAliases r JOIN dbo.StoryMemoryCharacters c ON c.StoryMemoryCharacterID=r.StoryMemoryCharacterID JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=c.ImportSessionID WHERE p.ProjectID=@ProjectID ORDER BY r.StoryMemoryCharacterAliasID;
SELECT r.* FROM dbo.StoryMemoryCharacterAttributes r JOIN dbo.StoryMemoryCharacters c ON c.StoryMemoryCharacterID=r.StoryMemoryCharacterID JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=c.ImportSessionID WHERE p.ProjectID=@ProjectID ORDER BY r.StoryMemoryCharacterAttributeID;
SELECT r.* FROM dbo.StoryMemoryLocations r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID ORDER BY r.StoryMemoryLocationID;
SELECT r.* FROM dbo.StoryMemoryAssets r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID ORDER BY r.StoryMemoryAssetID;
SELECT r.* FROM dbo.StoryMemoryRelationships r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID ORDER BY r.StoryMemoryRelationshipID;
SELECT r.* FROM dbo.StoryMemoryProcessedSceneResults r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID ORDER BY r.StoryMemoryProcessedSceneResultID;
SELECT r.* FROM dbo.StoryMemoryImportPreferences r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID ORDER BY r.StoryMemoryImportPreferenceID;
SELECT r.* FROM dbo.CharacterIntelligenceProfiles r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID ORDER BY r.CharacterIntelligenceProfileID;
SELECT r.* FROM dbo.CharacterIntelligenceEvidenceEvents r JOIN dbo.CharacterIntelligenceProfiles c ON c.CharacterIntelligenceProfileID=r.CharacterIntelligenceProfileID JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=c.ImportSessionID WHERE p.ProjectID=@ProjectID ORDER BY r.CharacterIntelligenceEvidenceEventID;
SELECT r.* FROM dbo.StoryIntelligenceReviewCandidateGenerations r WHERE r.ProjectID=@ProjectID ORDER BY r.ReviewCandidateGenerationID;
SELECT r.* FROM dbo.StoryIntelligenceReviewCandidates r WHERE r.ProjectID=@ProjectID ORDER BY r.ReviewCandidateID;
SELECT r.* FROM dbo.StoryIntelligenceReviewCandidateEvidence r JOIN dbo.StoryIntelligenceReviewCandidates c ON c.ReviewCandidateID=r.ReviewCandidateID WHERE c.ProjectID=@ProjectID ORDER BY r.ReviewCandidateEvidenceID;
SELECT r.* FROM dbo.CharacterEnrichmentRuns r WHERE r.ProjectID=@ProjectID ORDER BY r.CharacterEnrichmentRunID;
SELECT r.* FROM dbo.CharacterEnrichmentEvidence r JOIN dbo.CharacterEnrichmentRuns p ON p.CharacterEnrichmentRunID=r.CharacterEnrichmentRunID WHERE p.ProjectID=@ProjectID ORDER BY r.CharacterEnrichmentEvidenceID;
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'CharacterEnrichmentRuns'),
(N'CharacterEnrichmentEvidence'),
(N'UserOnboardingState'), (N'StoryIntelligenceConsents'), (N'StoryIntelligenceJobs'),
(N'StoryIntelligenceReviewCandidateGenerations'),
(N'StoryIntelligenceReviewCandidates'),
(N'StoryIntelligenceReviewCandidateEvidence'),
(N'StoryIntelligenceBookPipelines'),
(N'StoryMemoryCharacters'),
(N'StoryMemoryCharacterAliases'),
(N'StoryMemoryCharacterAttributes'),
(N'StoryMemoryLocations'),
(N'StoryMemoryAssets'),
(N'StoryMemoryRelationships'),
(N'StoryMemoryProcessedSceneResults'),
(N'StoryMemoryImportPreferences'),
(N'CharacterIntelligenceProfiles'),
(N'CharacterIntelligenceEvidenceEvents'),
(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;
IF JSON_QUERY(@JsonData,'$.Data.StoryIntelligenceBookPipelines') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryIntelligenceBookPipelines r WHERE r.ProjectID=@ProjectID)
THROW 51013,'This older restore point omits existing pipeline or story-memory history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.StoryMemoryCharacters') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryMemoryCharacters r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID)
THROW 51013,'This older restore point omits existing pipeline or story-memory history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.StoryMemoryCharacterAliases') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryMemoryCharacterAliases r JOIN dbo.StoryMemoryCharacters c ON c.StoryMemoryCharacterID=r.StoryMemoryCharacterID JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=c.ImportSessionID WHERE p.ProjectID=@ProjectID)
THROW 51013,'This older restore point omits existing pipeline or story-memory history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.StoryMemoryCharacterAttributes') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryMemoryCharacterAttributes r JOIN dbo.StoryMemoryCharacters c ON c.StoryMemoryCharacterID=r.StoryMemoryCharacterID JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=c.ImportSessionID WHERE p.ProjectID=@ProjectID)
THROW 51013,'This older restore point omits existing pipeline or story-memory history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.StoryMemoryLocations') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryMemoryLocations r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID)
THROW 51013,'This older restore point omits existing pipeline or story-memory history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.StoryMemoryAssets') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryMemoryAssets r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID)
THROW 51013,'This older restore point omits existing pipeline or story-memory history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.StoryMemoryRelationships') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryMemoryRelationships r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID)
THROW 51013,'This older restore point omits existing pipeline or story-memory history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.StoryMemoryProcessedSceneResults') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryMemoryProcessedSceneResults r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID)
THROW 51013,'This older restore point omits existing pipeline or story-memory history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.StoryMemoryImportPreferences') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryMemoryImportPreferences r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID)
THROW 51013,'This older restore point omits existing pipeline or story-memory history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.CharacterIntelligenceProfiles') IS NULL AND EXISTS(SELECT 1 FROM dbo.CharacterIntelligenceProfiles r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID)
THROW 51013,'This older restore point omits existing pipeline or story-memory history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.CharacterIntelligenceEvidenceEvents') IS NULL AND EXISTS(SELECT 1 FROM dbo.CharacterIntelligenceEvidenceEvents r JOIN dbo.CharacterIntelligenceProfiles c ON c.CharacterIntelligenceProfileID=r.CharacterIntelligenceProfileID JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=c.ImportSessionID WHERE p.ProjectID=@ProjectID)
THROW 51013,'This older restore point omits existing pipeline or story-memory history. Restore was aborted without changing it.',1;
IF EXISTS(SELECT 1 FROM dbo.StoryIntelligenceBookPipelines WHERE ProjectID=@ProjectID AND Status NOT IN(N'Complete',N'NeedsReview'))
OR EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.StoryIntelligenceBookPipelines') WITH(Status nvarchar(40) '$.Status') WHERE Status NOT IN(N'Complete',N'NeedsReview'))
THROW 51014,'Analysis pipeline work is unfinished in the project or restore point. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.StoryIntelligenceReviewCandidateGenerations') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryIntelligenceReviewCandidateGenerations r WHERE r.ProjectID=@ProjectID)
THROW 51015,'This older restore point omits existing persisted entity review history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.StoryIntelligenceReviewCandidates') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryIntelligenceReviewCandidates r WHERE r.ProjectID=@ProjectID)
THROW 51015,'This older restore point omits existing persisted entity review history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.StoryIntelligenceReviewCandidateEvidence') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryIntelligenceReviewCandidateEvidence r JOIN dbo.StoryIntelligenceReviewCandidates c ON c.ReviewCandidateID=r.ReviewCandidateID WHERE c.ProjectID=@ProjectID)
THROW 51015,'This older restore point omits existing persisted entity review history. Restore was aborted without changing it.',1;
IF EXISTS(SELECT 1 FROM dbo.StoryIntelligenceReviewCandidateGenerations WHERE ProjectID=@ProjectID AND Status=N'Preparing')
OR EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.StoryIntelligenceReviewCandidateGenerations') WITH(Status nvarchar(40) '$.Status') WHERE Status=N'Preparing')
THROW 51016,'Candidate preparation is unfinished in the project or restore point. Restore was aborted without changing it.',1;
IF EXISTS(SELECT 1 FROM dbo.StoryIntelligenceJobs j WHERE (j.ProjectID=@ProjectID OR EXISTS(SELECT 1 FROM dbo.Books b WHERE b.BookID=j.BookID AND b.ProjectID=@ProjectID)) AND j.Status NOT IN(N'Completed',N'Failed',N'Cancelled'))
THROW 51017,'An analysis job is active for this project. Complete or cancel it before restoring.',1;
IF EXISTS(SELECT 1 FROM dbo.StoryIntelligenceConsents c JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID AND NOT EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.Books') WITH(BookID int '$.BookID') x WHERE x.BookID=c.BookID))
OR EXISTS(SELECT 1 FROM dbo.StoryIntelligenceJobs j JOIN dbo.Books b ON b.BookID=j.BookID WHERE b.ProjectID=@ProjectID AND NOT EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.Books') WITH(BookID int '$.BookID') x WHERE x.BookID=j.BookID))
THROW 51018,'This restore point removes a book required by retained consent or job history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.CharacterEnrichmentRuns') IS NULL AND EXISTS(SELECT 1 FROM dbo.CharacterEnrichmentRuns r WHERE r.ProjectID=@ProjectID)
THROW 51019,'This older restore point omits existing character enrichment history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.CharacterEnrichmentEvidence') IS NULL AND EXISTS(SELECT 1 FROM dbo.CharacterEnrichmentEvidence r JOIN dbo.CharacterEnrichmentRuns p ON p.CharacterEnrichmentRunID=r.CharacterEnrichmentRunID WHERE p.ProjectID=@ProjectID)
THROW 51019,'This older restore point omits existing character enrichment history. Restore was aborted without changing it.',1;
IF EXISTS(SELECT 1 FROM dbo.CharacterEnrichmentRuns WHERE ProjectID=@ProjectID AND Status NOT IN(N'Completed',N'Failed',N'Superseded'))
OR EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.CharacterEnrichmentRuns') WITH(Status nvarchar(40) '$.Status') WHERE Status NOT IN(N'Completed',N'Failed',N'Superseded'))
THROW 51020,'Character enrichment 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;
-- Only detach navigation pointers to books deliberately absent from the snapshot.
-- Account preferences, consent and job history are never replaced from project JSON.
UPDATE u SET BookID=NULL,UpdatedUtc=SYSUTCDATETIME()
FROM dbo.UserOnboardingState u JOIN dbo.Books b ON b.BookID=u.BookID
WHERE b.ProjectID=@ProjectID AND NOT EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.Books') WITH(BookID int '$.BookID') x WHERE x.BookID=u.BookID);
DELETE r FROM dbo.CharacterEnrichmentEvidence r JOIN dbo.CharacterEnrichmentRuns p ON p.CharacterEnrichmentRunID=r.CharacterEnrichmentRunID WHERE p.ProjectID=@ProjectID;
DELETE r FROM dbo.CharacterEnrichmentRuns r WHERE r.ProjectID=@ProjectID;
DELETE r FROM dbo.StoryIntelligenceReviewCandidateEvidence r JOIN dbo.StoryIntelligenceReviewCandidates c ON c.ReviewCandidateID=r.ReviewCandidateID WHERE c.ProjectID=@ProjectID;
DELETE r FROM dbo.StoryIntelligenceReviewCandidates r WHERE r.ProjectID=@ProjectID;
DELETE r FROM dbo.StoryIntelligenceReviewCandidateGenerations r WHERE r.ProjectID=@ProjectID;
DELETE r FROM dbo.CharacterIntelligenceEvidenceEvents r JOIN dbo.CharacterIntelligenceProfiles c ON c.CharacterIntelligenceProfileID=r.CharacterIntelligenceProfileID JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=c.ImportSessionID WHERE p.ProjectID=@ProjectID;
DELETE r FROM dbo.CharacterIntelligenceProfiles r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID;
DELETE r FROM dbo.StoryMemoryImportPreferences r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID;
DELETE r FROM dbo.StoryMemoryProcessedSceneResults r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID;
DELETE r FROM dbo.StoryMemoryRelationships r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID;
DELETE r FROM dbo.StoryMemoryAssets r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID;
DELETE r FROM dbo.StoryMemoryLocations r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID;
DELETE r FROM dbo.StoryMemoryCharacterAttributes r JOIN dbo.StoryMemoryCharacters c ON c.StoryMemoryCharacterID=r.StoryMemoryCharacterID JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=c.ImportSessionID WHERE p.ProjectID=@ProjectID;
DELETE r FROM dbo.StoryMemoryCharacterAliases r JOIN dbo.StoryMemoryCharacters c ON c.StoryMemoryCharacterID=r.StoryMemoryCharacterID JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=c.ImportSessionID WHERE p.ProjectID=@ProjectID;
DELETE r FROM dbo.StoryMemoryCharacters r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID;
DELETE r FROM dbo.StoryIntelligenceBookPipelines r WHERE r.ProjectID=@ProjectID;
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;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryIntelligenceBookPipelines',N'$.Data.StoryIntelligenceBookPipelines',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryMemoryCharacters',N'$.Data.StoryMemoryCharacters',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryMemoryCharacterAliases',N'$.Data.StoryMemoryCharacterAliases',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryMemoryCharacterAttributes',N'$.Data.StoryMemoryCharacterAttributes',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryMemoryLocations',N'$.Data.StoryMemoryLocations',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryMemoryAssets',N'$.Data.StoryMemoryAssets',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryMemoryRelationships',N'$.Data.StoryMemoryRelationships',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryMemoryProcessedSceneResults',N'$.Data.StoryMemoryProcessedSceneResults',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryMemoryImportPreferences',N'$.Data.StoryMemoryImportPreferences',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterIntelligenceProfiles',N'$.Data.CharacterIntelligenceProfiles',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterIntelligenceEvidenceEvents',N'$.Data.CharacterIntelligenceEvidenceEvents',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryIntelligenceReviewCandidateGenerations',N'$.Data.StoryIntelligenceReviewCandidateGenerations',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryIntelligenceReviewCandidates',N'$.Data.StoryIntelligenceReviewCandidates',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryIntelligenceReviewCandidateEvidence',N'$.Data.StoryIntelligenceReviewCandidateEvidence',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterEnrichmentRuns',N'$.Data.CharacterEnrichmentRuns',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'CharacterEnrichmentEvidence',N'$.Data.CharacterEnrichmentEvidence',@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