diff --git a/Docs/Sprints/2026-11-03-phase2-data-coverage.csv b/Docs/Sprints/2026-11-03-phase2-data-coverage.csv index 0e52d79e..89ebdc53 100644 --- a/Docs/Sprints/2026-11-03-phase2-data-coverage.csv +++ b/Docs/Sprints/2026-11-03-phase2-data-coverage.csv @@ -119,9 +119,9 @@ StoryIntelligenceConsents,UserID and account onboarding consent ledger; project/ StoryIntelligenceIllustrationDemands,ProjectID or FK descendant,,Pending classification,Pending,Pending StoryIntelligenceImportCommits,ProjectID or FK descendant,StoryIntelligenceImportCommits,Retained analysis source/results and import audit; full stored fields serialized,Pass: exact long raw JSON/source; copy canonical/run/actor refs; in-place; old snapshot and active-analysis refusal,Raw JSON is historical audit and is not parsed/rebuilt during backup; unfinished copied runs cancelled; review/pipeline graph separate pending scope StoryIntelligenceJobs,UserID/consent operation ledger; project/book references,,Operational job history retained rather than ported or replayed; paid results are backed up separately,Pass: exact later operational state retained; active job refusal; protected-book removal refusal; no copied jobs,Not a cache; no paid providers or workers invoked -StoryIntelligenceNarrativeCandidateEvents,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending -StoryIntelligenceNarrativeCandidateEvidence,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending -StoryIntelligenceNarrativeCandidates,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending +StoryIntelligenceNarrativeCandidateEvents,ProjectID or FK descendant,StoryIntelligenceNarrativeCandidateEvents,"Persisted synthesis provider output, author review/merge decisions and accepted/ignored events; complete stored projection",Pass: completed/failed audit; parent/merge/seed/canonical refs; both event-source forms; idempotent event replay; in-place; missing/active/cycle guards,"Provider ResultJson retained exactly as historical audit; synthetic nullable-run grammar tested, not a historical backup file" +StoryIntelligenceNarrativeCandidateEvidence,ProjectID or FK descendant,StoryIntelligenceNarrativeCandidateEvidence,"Persisted synthesis provider output, author review/merge decisions and accepted/ignored events; complete stored projection",Pass: completed/failed audit; parent/merge/seed/canonical refs; both event-source forms; idempotent event replay; in-place; missing/active/cycle guards,"Provider ResultJson retained exactly as historical audit; synthetic nullable-run grammar tested, not a historical backup file" +StoryIntelligenceNarrativeCandidates,ProjectID or FK descendant,StoryIntelligenceNarrativeCandidates,"Persisted synthesis provider output, author review/merge decisions and accepted/ignored events; complete stored projection",Pass: completed/failed audit; parent/merge/seed/canonical refs; both event-source forms; idempotent event replay; in-place; missing/active/cycle guards,"Provider ResultJson retained exactly as historical audit; synthetic nullable-run grammar tested, not a historical backup file" StoryIntelligenceReviewCandidateEvidence,ProjectID or FK descendant,StoryIntelligenceReviewCandidateEvidence,Persistent prepared entity review generations/author decisions/evidence; full stored projection,Pass: all five modules; pending/reviewed/tracked; operational JSON refs and review keys remap; canonical source-key idempotence; in-place; old/active guards,"Unknown JSON extensions and raw audit retained; synthetic legacy-key grammar tested, not a historical backup fixture" StoryIntelligenceReviewCandidateGenerations,ProjectID or FK descendant,StoryIntelligenceReviewCandidateGenerations,Persistent prepared entity review generations/author decisions/evidence; full stored projection,Pass: all five modules; pending/reviewed/tracked; operational JSON refs and review keys remap; canonical source-key idempotence; in-place; old/active guards,"Unknown JSON extensions and raw audit retained; synthetic legacy-key grammar tested, not a historical backup fixture" StoryIntelligenceReviewCandidates,ProjectID or FK descendant,StoryIntelligenceReviewCandidates,Persistent prepared entity review generations/author decisions/evidence; full stored projection,Pass: all five modules; pending/reviewed/tracked; operational JSON refs and review keys remap; canonical source-key idempotence; in-place; old/active guards,"Unknown JSON extensions and raw audit retained; synthetic legacy-key grammar tested, not a historical backup fixture" @@ -160,7 +160,7 @@ UserTwoFactor,Global/user/independent,,Account/authentication/billing state; out ValidationRuns,ProjectID or FK descendant,ValidationRuns,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 WarningSeverities,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee WarningTypes,Global/user/independent,,Shared application reference vocabulary; used by project entities but not owned by a project,Excluded from portable project creation; existing lookup resolution exercised where populated,Cross-install vocabulary/version equivalence is not a tested guarantee -WholeBookPlotSynthesisRuns,ProjectID or FK descendant,,Pending classification,Pending,Pending +WholeBookPlotSynthesisRuns,ProjectID or FK descendant,WholeBookPlotSynthesisRuns,"Persisted synthesis provider output, author review/merge decisions and accepted/ignored events; complete stored projection",Pass: completed/failed audit; parent/merge/seed/canonical refs; both event-source forms; idempotent event replay; in-place; missing/active/cycle guards,"Provider ResultJson retained exactly as historical audit; synthetic nullable-run grammar tested, not a historical backup file" WordCompanionSceneAssets,ProjectID or FK descendant,WordCompanionSceneAssets,Version 1.2 additive explicit Word associations; populated SQL stored-value round trip passed,Copy/in-place/safety/SQL rollback passed,Entity associations; file bytes not applicable WordCompanionSceneLocations,ProjectID or FK descendant,WordCompanionSceneLocations,Version 1.2 additive explicit Word associations; populated SQL stored-value round trip passed,Copy/in-place/safety/SQL rollback passed,Entity associations; file bytes not applicable WritingPlans,ProjectID or FK descendant,WritingPlans,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 diff --git a/Docs/Sprints/2026-11-03-phase2-field-coverage.csv b/Docs/Sprints/2026-11-03-phase2-field-coverage.csv index f0534961..f648c7e8 100644 --- a/Docs/Sprints/2026-11-03-phase2-field-coverage.csv +++ b/Docs/Sprints/2026-11-03-phase2-field-coverage.csv @@ -962,6 +962,61 @@ StoryIntelligenceImportCommits,StoryIntelligenceImportCommits,MetricsCreated,int StoryIntelligenceImportCommits,StoryIntelligenceImportCommits,Status,nvarchar,False,False,True,Represented; projection and semantic comparison still required StoryIntelligenceImportCommits,StoryIntelligenceImportCommits,Notes,nvarchar,True,False,True,Represented; projection and semantic comparison still required StoryIntelligenceImportCommits,StoryIntelligenceImportCommits,CreatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvents,StoryIntelligenceNarrativeCandidateEvents,NarrativeCandidateEventID,int,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvents,StoryIntelligenceNarrativeCandidateEvents,NarrativeCandidateID,int,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvents,StoryIntelligenceNarrativeCandidateEvents,WholeBookPlotSynthesisRunID,int,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvents,StoryIntelligenceNarrativeCandidateEvents,EventKey,nvarchar,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvents,StoryIntelligenceNarrativeCandidateEvents,SceneID,int,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvents,StoryIntelligenceNarrativeCandidateEvents,EventType,nvarchar,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvents,StoryIntelligenceNarrativeCandidateEvents,EventTitle,nvarchar,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvents,StoryIntelligenceNarrativeCandidateEvents,EventDescription,nvarchar,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvents,StoryIntelligenceNarrativeCandidateEvents,Evidence,nvarchar,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvents,StoryIntelligenceNarrativeCandidateEvents,Confidence,decimal,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvents,StoryIntelligenceNarrativeCandidateEvents,SortOrder,int,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvents,StoryIntelligenceNarrativeCandidateEvents,IsIgnored,bit,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvents,StoryIntelligenceNarrativeCandidateEvents,AcceptedThreadEventID,int,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvents,StoryIntelligenceNarrativeCandidateEvents,CreatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvents,StoryIntelligenceNarrativeCandidateEvents,UpdatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvidence,StoryIntelligenceNarrativeCandidateEvidence,NarrativeCandidateEvidenceID,int,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvidence,StoryIntelligenceNarrativeCandidateEvidence,NarrativeCandidateID,int,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvidence,StoryIntelligenceNarrativeCandidateEvidence,SceneID,int,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvidence,StoryIntelligenceNarrativeCandidateEvidence,ContributionType,nvarchar,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvidence,StoryIntelligenceNarrativeCandidateEvidence,Evidence,nvarchar,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvidence,StoryIntelligenceNarrativeCandidateEvidence,SortOrder,int,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidateEvidence,StoryIntelligenceNarrativeCandidateEvidence,CreatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,NarrativeCandidateID,int,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,ProjectID,int,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,BookID,int,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,CandidateType,nvarchar,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,CandidateKey,nvarchar,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,ProposedTitle,nvarchar,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,ProposedDescription,nvarchar,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,Category,nvarchar,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,InferredState,nvarchar,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,ExistingPlotLineID,int,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,ExistingPlotThreadID,int,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,RelatedPlotLineID,int,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,Confidence,decimal,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,Status,nvarchar,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,ReviewAction,nvarchar,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,AcceptedPlotLineID,int,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,AcceptedPlotThreadID,int,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,ReviewedByUserID,int,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,ReviewedUtc,datetime2,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,CreatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,UpdatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,ChangeType,nvarchar,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,Significance,nvarchar,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,ParentCandidateKey,nvarchar,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,ParentNarrativeCandidateID,int,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,MergeTargetNarrativeCandidateID,int,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,WholeBookPlotSynthesisRunID,int,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,AuthorPlotSeedID,int,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,ExistingPlotLineMatchConfidence,decimal,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,ExistingPlotLineMatchReason,nvarchar,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,SeedMatchConfidence,decimal,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,SeedMatchReason,nvarchar,True,False,True,Represented; projection and semantic comparison still required +StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,Source,nvarchar,True,False,True,Represented; projection and semantic comparison still required StoryIntelligenceReviewCandidateEvidence,StoryIntelligenceReviewCandidateEvidence,ReviewCandidateEvidenceID,int,False,False,True,Represented; projection and semantic comparison still required StoryIntelligenceReviewCandidateEvidence,StoryIntelligenceReviewCandidateEvidence,ReviewCandidateID,int,False,False,True,Represented; projection and semantic comparison still required StoryIntelligenceReviewCandidateEvidence,StoryIntelligenceReviewCandidateEvidence,SceneID,int,True,False,True,Represented; projection and semantic comparison still required @@ -1224,6 +1279,31 @@ ValidationRuns,ValidationRuns,StartedDate,datetime2,False,False,True,Represented ValidationRuns,ValidationRuns,CompletedDate,datetime2,True,False,True,Represented; projection and semantic comparison still required ValidationRuns,ValidationRuns,TriggeredBy,nvarchar,True,False,True,Represented; projection and semantic comparison still required ValidationRuns,ValidationRuns,ScopeDescription,nvarchar,True,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRunID,int,False,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,ProjectID,int,False,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,BookID,int,False,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,UserID,int,False,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,SourceStoryIntelligenceRunID,int,True,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,SourceStoryIntelligenceRunKey,int,False,True,False,Computed database value +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,CharacterResolutionVersion,nvarchar,False,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,Status,nvarchar,False,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,QueuedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,StartedUtc,datetime2,True,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,CompletedUtc,datetime2,True,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,FailedUtc,datetime2,True,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,AttemptCount,int,False,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,Model,nvarchar,True,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,OpenAIResponseID,nvarchar,True,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,InputTokens,int,True,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,OutputTokens,int,True,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,CachedInputTokens,int,True,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,TotalTokens,int,True,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,DurationMs,bigint,True,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,ErrorMessage,nvarchar,True,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,ErrorDetail,nvarchar,True,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,ResultJson,nvarchar,True,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,IsCurrent,bit,False,False,True,Represented; projection and semantic comparison still required +WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,UpdatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required WordCompanionSceneAssets,WordCompanionSceneAssets,WordCompanionSceneAssetID,int,False,False,True,Represented; projection and semantic comparison still required WordCompanionSceneAssets,WordCompanionSceneAssets,SceneID,int,False,False,True,Represented; projection and semantic comparison still required WordCompanionSceneAssets,WordCompanionSceneAssets,StoryAssetID,int,False,False,True,Represented; projection and semantic comparison still required diff --git a/Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv b/Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv index a43aeb22..04b35d66 100644 --- a/Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv +++ b/Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv @@ -1,4 +1,8 @@ Collection,SourceRows,CopyRows,InPlaceRows,Verification +WholeBookPlotSynthesisRuns,2,2,2,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present +StoryIntelligenceNarrativeCandidates,6,6,6,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present +StoryIntelligenceNarrativeCandidateEvidence,6,6,6,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present +StoryIntelligenceNarrativeCandidateEvents,2,2,2,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present 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 @@ -61,7 +65,7 @@ TimelineMetricSettings,1,1,1,Stored field comparison passed; only populated valu TimelineViewPresets,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present PlotLines,2,2,2,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present PlotThreads,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present -ThreadEvents,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present +ThreadEvents,3,3,3,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present StoryAssets,2,2,2,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present AssetStates,2,2,2,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present AssetEvents,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present diff --git a/Docs/Sprints/2026-11-03-phase2.md b/Docs/Sprints/2026-11-03-phase2.md index 6dea0d53..e19e1700 100644 --- a/Docs/Sprints/2026-11-03-phase2.md +++ b/Docs/Sprints/2026-11-03-phase2.md @@ -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 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. +5. COMPLETE CHECKPOINT: serialized backup/restore coverage now has 104 collections (100 persistent plus 4 diagnostic/shared vocabulary), 105 SQL entities / 1,342 columns with no missing non-computed model properties. All 100 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: illustration catalogue/provenance/files and final ownership-scope row census. Narrative synthesis and enrichment evidence now pass. 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. @@ -300,3 +300,15 @@ The restore service previously hid even safe, fixed preflight refusal reasons be 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. + +## Narrative synthesis and persisted Plot/Thread review history — 4 November + +Confirmed four omitted sets: synthesis runs, narrative candidates, evidence and candidate events. Migration 228 carries complete non-computed stored fields; SourceStoryIntelligenceRunKey remains a database-computed value. Fixtures include completed/failed provider history, long exact ResultJson, accepted/pending/rejected/merged decisions, parent and merge targets, author seed links, ignored events and two accepted canonical event source forms. The initial comparison needed explicit semantic mappings for candidate synthesis-run and author-seed IDs because those schema columns lack FKs; the copy implementation already remapped them. + +Provider ResultJson is retained exactly as historical output, including original embedded source IDs. Persisted operational references are remapped separately. Canonical ThreadEvents can reference either an explicit candidate event or candidate evidence; both source identities and composite source keys now follow the copied graph, and AcceptedThreadEventID follows back to the canonical event. Opaque provider event tokens are preserved, including colons/Unicode. Matching uses indexed source records rather than repeated full scans. Ambiguous/unresolved links are refused for portable copy when the source graph is present; same-project history is retained. Older graph-less backups keep the existing detached-copy behaviour with an explicit warning. + +Production narrative readers returned all six candidate states/records, six evidence rows and both active/ignored candidate events. Two repeated calls per source form through the production ThreadEvent_Save procedure returned existing canonical IDs, without duplicates. A synthetic nullable-run grammar case also passed both remapping and replay; it is not a historical backup fixture. Parent/merge cycles, foreign refs and mismatched parent keys fail preview before allocation. Current or snapshot unfinished synthesis is refused, while copies become failed/inactive history with decisions/evidence retained. Actual restore service returns the safe actionable refusal and retains the safety backup. All four old-shaped missing collections are independently protected. + +Final indexed real SQL matrix passed all 100 populated persistent collections (104 serialized collections): source 2,427 stored values across 103 populated entities; copy 2,301 generic comparisons plus explicit review/provenance assertions; in-place 2,391. Invalid preview count 47. Field census 105 entities / 1,342 columns / zero missing non-computed model properties (one computed synthesis key intentionally omitted from the DTO). Build zero warnings/errors. Evidence `/tmp/plotdirector-phase2-narrative-before.log`, `narrative-after.log` (comparison-harness semantic mapping gap), `narrative-guards.log`, `narrative-index.log` (final pass), `build-narrative-index.log`, `census-narrative.log` (all `/tmp/plotdirector-phase2-` prefix). Remaining feature scope: illustration catalogue/provenance/files; final independent owned-row census still pending. No Development writes/deployment. + +Narrative checkpoint: full 405-check regression harness passed, exit 0 (`/tmp/plotdirector-phase2-tests-narrative.log`). Migration 228 remains synthetic-only; no Production or Development schema/data writes. diff --git a/PlotLine.Tests/Fixtures/ProjectTransferPlanning.sql b/PlotLine.Tests/Fixtures/ProjectTransferPlanning.sql index e5062eb7..1d664384 100644 --- a/PlotLine.Tests/Fixtures/ProjectTransferPlanning.sql +++ b/PlotLine.Tests/Fixtures/ProjectTransferPlanning.sql @@ -217,3 +217,43 @@ INSERT dbo.CharacterEnrichmentEvidence(CharacterEnrichmentRunID,CharacterID,Scen 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); + +DECLARE @synthesis int,@plotCandidate int,@threadCandidate int,@fallbackCandidate int,@pendingCandidate int,@rejectedCandidate int,@mergedCandidate int,@narrativeEvent int,@canonicalEvent int,@fallbackEvent int; +DECLARE @narrativeSeed int=(SELECT MIN(AuthorPlotSeedID) FROM dbo.AuthorPlotSeeds WHERE ProjectID=@project),@synthesisJson nvarchar(max); +SET @synthesisJson=CONCAT(N'{"metadata":{"summary":"',REPLICATE(CONVERT(nvarchar(max),N'Retained narrative audit Ω 雨. '),5000),N'"},"plotLines":[{"key":"arc-Ω","existingPlotLineID":',@line,N',"authorPlotSeedID":',@narrativeSeed,N',"threads":[{"key":"question-Ω","existingPlotThreadID":',@thread,N',"events":[{"key":"arrival:Ω","sceneID":',@scene,N',"evidence":"Original provider output 雨"}]}]}],"extension":{"keep":"Audit Ω"}}'); +INSERT dbo.WholeBookPlotSynthesisRuns(ProjectID,BookID,UserID,SourceStoryIntelligenceRunID,CharacterResolutionVersion,Status,StartedUtc,CompletedUtc,AttemptCount,Model,OpenAIResponseID,InputTokens,OutputTokens,CachedInputTokens,TotalTokens,DurationMs,ResultJson,IsCurrent) +VALUES(@project,@book,@user,@siRun,N'synthetic-narrative-v1',N'Completed','2026-11-01','2026-11-02',1,N'synthetic-no-provider',N'synthetic-response-no-provider',300,100,20,400,4500,@synthesisJson,1); +SET @synthesis=SCOPE_IDENTITY(); +INSERT dbo.WholeBookPlotSynthesisRuns(ProjectID,BookID,UserID,CharacterResolutionVersion,Status,StartedUtc,FailedUtc,AttemptCount,Model,ErrorMessage,ErrorDetail,IsCurrent) +VALUES(@project,@book,@user,N'synthetic-narrative-failed',N'Failed','2026-10-01','2026-10-01',1,N'synthetic-no-provider',N'Synthetic synthesis error 雨',N'{"error":"Retained diagnostic Ω"}',0); +INSERT dbo.StoryIntelligenceNarrativeCandidates(ProjectID,BookID,CandidateType,CandidateKey,ProposedTitle,ProposedDescription,Category,InferredState,ExistingPlotLineID,Confidence,Status,ReviewAction,AcceptedPlotLineID,ReviewedByUserID,ReviewedUtc,ChangeType,Significance,WholeBookPlotSynthesisRunID,AuthorPlotSeedID,ExistingPlotLineMatchConfidence,ExistingPlotLineMatchReason,SeedMatchConfidence,SeedMatchReason,Source) +VALUES(@project,@book,N'PlotLine',N'PlotLine:arc-Ω',N'Accepted narrative arc Ω',N'Author-preserved arc description 雨',N'Plot Line',N'Active',@line,.95,N'Accepted',N'MergeExisting',@line,@user,'2026-11-03',N'Progression',N'Major',@synthesis,@narrativeSeed,.9,N'Existing arc evidence Ω',.9,N'Author seed match 雨',N'WholeBookPlotSynthesis'); +SET @plotCandidate=SCOPE_IDENTITY(); +INSERT dbo.StoryIntelligenceNarrativeCandidates(ProjectID,BookID,CandidateType,CandidateKey,ProposedTitle,ProposedDescription,Category,ExistingPlotThreadID,RelatedPlotLineID,Confidence,Status,ReviewAction,AcceptedPlotThreadID,ReviewedByUserID,ReviewedUtc,ParentCandidateKey,ParentNarrativeCandidateID,WholeBookPlotSynthesisRunID,Source) +VALUES(@project,@book,N'Thread',N'Thread:question-Ω',N'Accepted narrative thread Ω',N'Explicit event source 雨',N'Thread',@thread,@line,.9,N'Accepted',N'MergeExisting',@thread,@user,'2026-11-03',N'PlotLine:arc-Ω',@plotCandidate,@synthesis,N'WholeBookPlotSynthesis'); +SET @threadCandidate=SCOPE_IDENTITY(); +INSERT dbo.StoryIntelligenceNarrativeCandidates(ProjectID,BookID,CandidateType,CandidateKey,ProposedTitle,ProposedDescription,ExistingPlotThreadID,RelatedPlotLineID,Confidence,Status,ReviewAction,AcceptedPlotThreadID,ReviewedByUserID,ReviewedUtc,ParentCandidateKey,ParentNarrativeCandidateID,WholeBookPlotSynthesisRunID,Source) +VALUES(@project,@book,N'Thread',N'Thread:evidence-雨',N'Accepted evidence thread 雨',N'Legacy evidence-only source Ω',@thread,@line,.85,N'Accepted',N'MergeExisting',@thread,@user,'2026-11-03',N'PlotLine:arc-Ω',@plotCandidate,@synthesis,N'WholeBookPlotSynthesis'); +SET @fallbackCandidate=SCOPE_IDENTITY(); +INSERT dbo.StoryIntelligenceNarrativeCandidates(ProjectID,BookID,CandidateType,CandidateKey,ProposedTitle,RelatedPlotLineID,Confidence,Status,ParentCandidateKey,ParentNarrativeCandidateID,WholeBookPlotSynthesisRunID,Source) +VALUES(@project,@book,N'Thread',N'Thread:pending-Ω',N'Pending narrative decision Ω',@line,.7,N'Pending',N'PlotLine:arc-Ω',@plotCandidate,@synthesis,N'WholeBookPlotSynthesis'); +SET @pendingCandidate=SCOPE_IDENTITY(); +INSERT dbo.StoryIntelligenceNarrativeCandidates(ProjectID,BookID,CandidateType,CandidateKey,ProposedTitle,RelatedPlotLineID,Confidence,Status,ReviewAction,ReviewedByUserID,ReviewedUtc,ParentCandidateKey,ParentNarrativeCandidateID,WholeBookPlotSynthesisRunID,Source) +VALUES(@project,@book,N'Thread',N'Thread:rejected-Ω',N'Rejected narrative observation Ω',@line,.5,N'Rejected',N'Reject',@user,'2026-11-03',N'PlotLine:arc-Ω',@plotCandidate,@synthesis,N'WholeBookPlotSynthesis'); +SET @rejectedCandidate=SCOPE_IDENTITY(); +INSERT dbo.StoryIntelligenceNarrativeCandidates(ProjectID,BookID,CandidateType,CandidateKey,ProposedTitle,ExistingPlotThreadID,RelatedPlotLineID,Confidence,Status,ReviewAction,ReviewedByUserID,ReviewedUtc,ParentCandidateKey,ParentNarrativeCandidateID,MergeTargetNarrativeCandidateID,WholeBookPlotSynthesisRunID,Source) +VALUES(@project,@book,N'Thread',N'Thread:merged-雪',N'Merged narrative observation 雪',@thread,@line,.8,N'Merged',N'MergeCandidate',@user,'2026-11-03',N'PlotLine:arc-Ω',@plotCandidate,@threadCandidate,@synthesis,N'WholeBookPlotSynthesis'); +SET @mergedCandidate=SCOPE_IDENTITY(); +INSERT dbo.StoryIntelligenceNarrativeCandidateEvidence(NarrativeCandidateID,SceneID,ContributionType,Evidence,SortOrder) +VALUES(@plotCandidate,@scene,N'Introduced',N'Plot evidence Ω',1),(@threadCandidate,@scene,N'Progressed',N'Thread evidence 雨',1),(@fallbackCandidate,@secondScene,N'Resolved',N'Fallback evidence café',1),(@pendingCandidate,@scene,N'Mentioned',N'Pending evidence Ω',1),(@rejectedCandidate,@scene,N'Mentioned',N'Rejected evidence Ω',1),(@mergedCandidate,@scene,N'Mentioned',N'Merged evidence 雪',1); +INSERT dbo.StoryIntelligenceNarrativeCandidateEvents(NarrativeCandidateID,WholeBookPlotSynthesisRunID,EventKey,SceneID,EventType,EventTitle,EventDescription,Evidence,Confidence,SortOrder,IsIgnored) +VALUES(@threadCandidate,@synthesis,N'arrival:Ω',@scene,N'Progressed',N'Accepted synthesis event Ω',N'Event description 雨',N'Provider event evidence café',.9,1,0); +SET @narrativeEvent=SCOPE_IDENTITY(); +INSERT dbo.StoryIntelligenceNarrativeCandidateEvents(NarrativeCandidateID,WholeBookPlotSynthesisRunID,EventKey,SceneID,EventType,EventTitle,Evidence,Confidence,SortOrder,IsIgnored) +VALUES(@threadCandidate,@synthesis,N'ignored:雨',@secondScene,N'Mentioned',N'Ignored synthesis event 雨',N'Author ignored event Ω',.6,2,1); +INSERT dbo.ThreadEvents(PlotThreadID,SceneID,EventTypeID,PlotEventTypeID,EventTitle,EventDescription,Source,SourceReferenceID,SourceKey,Confidence) +VALUES(@thread,@scene,@eventType,@plotEventType,N'Accepted synthesis event Ω',N'Canonical explicit event 雨',N'WholeBookPlotSynthesis',@narrativeEvent,CONCAT(@synthesis,N':',@threadCandidate,N':arrival:Ω'),.9); +SET @canonicalEvent=SCOPE_IDENTITY(); +UPDATE dbo.StoryIntelligenceNarrativeCandidateEvents SET AcceptedThreadEventID=@canonicalEvent WHERE NarrativeCandidateEventID=@narrativeEvent; +INSERT dbo.ThreadEvents(PlotThreadID,SceneID,EventTypeID,PlotEventTypeID,EventTitle,EventDescription,Source,SourceReferenceID,SourceKey,Confidence) +VALUES(@thread,@secondScene,@eventType,@plotEventType,N'Accepted evidence event 雨',N'Canonical evidence-only event Ω',N'WholeBookPlotSynthesis',@fallbackCandidate,CONCAT(@synthesis,N':',@fallbackCandidate,N':',@secondScene,N':1'),.85); diff --git a/PlotLine.Tests/ProjectTransferDatabaseTests.cs b/PlotLine.Tests/ProjectTransferDatabaseTests.cs index ef2fe82b..3dfee013 100644 --- a/PlotLine.Tests/ProjectTransferDatabaseTests.cs +++ b/PlotLine.Tests/ProjectTransferDatabaseTests.cs @@ -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","PlotLine/Sql/227_ProjectBackupCharacterEnrichment.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","PlotLine/Sql/228_ProjectBackupNarrativeHistory.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."); @@ -128,7 +128,7 @@ internal static class ProjectTransferDatabaseTests var plan=await db.ExecuteScalarAsync("INSERT dbo.WritingPlans(UserID,ProjectID,BookID,PlanName,GoalType,StartDate,DeadlineDate,AvailableDaysJson,SessionLengthMinutes) VALUES(@user,@project,@book,N'Synthetic drafting plan',N'Draft','2026-11-01','2026-12-01',N'[1,3,5]',45);SELECT CONVERT(int,SCOPE_IDENTITY());",new{user,project,book}); await db.ExecuteAsync("INSERT dbo.WritingScheduleItems(WritingPlanID,SceneID,ScheduledDate,TaskType,ScheduleStatus,Notes) VALUES(@plan,@scene,'2026-11-03',N'Draft',N'Pending',N'Synthetic task café');",new{plan,scene}); await db.ExecuteAsync("UPDATE dbo.Books SET CreatedByUserID=@user,ModifiedByUserID=@user,CreatedDateUTC='2026-09-01',ModifiedDateUTC='2026-10-01' WHERE BookID=@book;UPDATE dbo.Scenes SET CreatedByUserID=@user,ModifiedByUserID=@user,CreatedDateUTC='2026-09-01',ModifiedDateUTC='2026-10-01' WHERE SceneID=@scene;",new{user,book,scene}); - var planningParameters=new DynamicParameters(new{project,book,chapter,scene,revision,timeMode,confidence,location,asset,kind,character,line,thread,threadEvent,map,user,observer,relationship,relationshipType,relationshipState}){RemoveUnused=false}; + var planningParameters=new DynamicParameters(new{project,book,chapter,scene,revision,timeMode,confidence,location,asset,kind,character,line,thread,threadEvent,map,user,observer,relationship,relationshipType,relationshipState,eventType,plotEventType}){RemoveUnused=false}; await db.ExecuteAsync(await File.ReadAllTextAsync("PlotLine.Tests/Fixtures/ProjectTransferPlanning.sql"),planningParameters); async Task SaveFile(string folder,string name,byte[] bytes) { @@ -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","CharacterEnrichmentRuns","CharacterEnrichmentEvidence"}) + 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","WholeBookPlotSynthesisRuns","StoryIntelligenceNarrativeCandidates","StoryIntelligenceNarrativeCandidateEvidence","StoryIntelligenceNarrativeCandidateEvents"}) 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."); @@ -224,6 +224,13 @@ internal static class ProjectTransferDatabaseTests root=>root["Data"]!["StoryIntelligenceReviewCandidates"]![0]!["CandidatePayloadJson"]="[]", root=>root["Data"]!["CharacterEnrichmentEvidence"]![0]!["CharacterEnrichmentRunID"]=-12345, root=>root["Data"]!["CharacterEnrichmentRuns"]![0]!["CharacterID"]=-12345, + root=>root["Data"]!["WholeBookPlotSynthesisRuns"]![0]!["SourceStoryIntelligenceRunID"]=-12345, + root=>root["Data"]!["StoryIntelligenceNarrativeCandidates"]![0]!["AuthorPlotSeedID"]=-12345, + root=>root["Data"]!["StoryIntelligenceNarrativeCandidateEvents"]![0]!["SceneID"]=-12345, + root=> {var row=root["Data"]!["StoryIntelligenceNarrativeCandidates"]![0]!;row["ParentNarrativeCandidateID"]=row["NarrativeCandidateID"]!.DeepClone();row["ParentCandidateKey"]=row["CandidateKey"]!.DeepClone();}, + root=> {var row=root["Data"]!["StoryIntelligenceNarrativeCandidates"]![5]!;row["MergeTargetNarrativeCandidateID"]=row["NarrativeCandidateID"]!.DeepClone();}, + root=>root["Data"]!["StoryIntelligenceNarrativeCandidates"]![1]!["ParentCandidateKey"]="different-parent", + root=>root["Data"]!["ThreadEvents"]!.AsArray().Single(row=>row!["EventTitle"]!.GetValue()=="Accepted synthesis event Ω")!["SourceReferenceID"]=-12345, root=> { var row=root["Data"]!["StoryIntelligenceReviewCandidates"]![12]!;var payload=System.Text.Json.Nodes.JsonNode.Parse(row["CandidatePayloadJson"]!.GetValue())!;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())!;payload["key"]="different-review-key";row["CandidatePayloadJson"]=payload.ToJsonString(); }, root=>root["Data"]!["MapReferenceImages"]![0]!["ImageData"]="", @@ -308,6 +315,7 @@ internal static class ProjectTransferDatabaseTests if(before.FormatVersion=="1.2" || requireWritingPlans) Check(restoredPlans==1,"Persistent writing plan restored."); var copiedReview=after.Data.CoreImportBasicLocationReviews.Single(); await ProjectTransferEntityReviewAssertions.VerifyCopyAsync(before,after,factory); + await ProjectTransferNarrativeAssertions.VerifyCopyAsync(before,after,factory); var expectedProfile=System.Text.Json.Nodes.JsonNode.Parse(before.Data.CharacterIntelligenceProfiles.Single().ProfileJson)!; var copiedSceneResult=after.Data.StoryIntelligenceSceneResults.Single().SceneResultID; expectedProfile["EvidenceTimeline"]![0]!["SceneResultID"]=copiedSceneResult; @@ -324,7 +332,7 @@ internal static class ProjectTransferDatabaseTests Check(after.Data.AuthorPlotSeeds.Single().Description=="The author’s Unicode intention 雪" && after.Data.AuthorPlotSeeds.Single().MatchedPlotLineID==after.Data.PlotLines.Single(x=>x.PlotLineName=="Second arc 雨").PlotLineID,"Authored plot seed and target retained."); var acknowledgement=after.Data.ContinuityWarningAcknowledgements.Single(); Check(acknowledgement.Notes=="Author acknowledgement café" && acknowledgement.SceneID==after.Data.Scenes.Single(x=>x.SceneTitle=="Scene café").SceneID && acknowledgement.CharacterID==after.Data.Characters.Single(x=>x.CharacterName=="Narrator Ω").CharacterID && acknowledgement.AssetID==after.Data.StoryAssets.Single(x=>x.AssetName=="Notebook 雨").StoryAssetID,"Acknowledged warning and all entity references retained."); - Check(after.Data.PlotEventTargetPlotLines.Single().PlotEventID==after.Data.ThreadEvents.Single().ThreadEventID && after.Data.PlotEventTargetPlotLines.Single().PlotLineID==after.Data.PlotLines.Single(x=>x.PlotLineName=="Second arc 雨").PlotLineID,"Additional plot-event target retained."); + Check(after.Data.PlotEventTargetPlotLines.Single().PlotEventID==after.Data.ThreadEvents.Single(x=>x.EventTitle=="Revelation 雪").ThreadEventID && after.Data.PlotEventTargetPlotLines.Single().PlotLineID==after.Data.PlotLines.Single(x=>x.PlotLineName=="Second arc 雨").PlotLineID,"Additional plot-event target retained."); Check(after.Data.RelationshipEvents.Single().SourceReviewKey==$"scene:{after.Data.Scenes.Single(x=>x.SceneTitle=="Scene café").SceneID}:{after.Data.Characters.Single(x=>x.CharacterName=="Narrator Ω").CharacterID}>{after.Data.Characters.Single(x=>x.CharacterName=="Observer 雪").CharacterID}:Development:000000000000000000000002" && after.Data.RelationshipEvents.Single().CharacterRelationshipID==after.Data.CharacterRelationships.Single().CharacterRelationshipID,"Relationship review source key and relationship link retained."); Check(after.Data.Scenarios.Single().ArchivedReason=="Synthetic archive reason 雨" && after.Data.Scenarios.Single().ArchivedDate==new DateTime(2026,10,12),"Scenario archive reason and date retained."); Check(after.Data.Books.Single().CreatedByUserID==importingUser && after.Data.Books.Single().CreatedDateUTC==new DateTime(2026,9,1) && after.Data.Scenes.Single(x=>x.SceneTitle=="Scene café").ModifiedDateUTC==new DateTime(2026,10,1),"Imported audit actors are rebound while stored audit timestamps are retained."); @@ -359,6 +367,41 @@ 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[]{"WholeBookPlotSynthesisRuns","StoryIntelligenceNarrativeCandidates","StoryIntelligenceNarrativeCandidateEvidence","StoryIntelligenceNarrativeCandidateEvents"}) + { + 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 narrative synthesis/review history."); } + catch(SqlException error) when(error.Number==51021) { } + Check(await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.StoryIntelligenceNarrativeCandidates WHERE ProjectID=@project",new{project})==6,"Refused snapshot preserves every narrative review state."); + } + var unfinishedSynthesis=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!; + unfinishedSynthesis["Data"]!["WholeBookPlotSynthesisRuns"]![0]!["Status"]="Queued"; + try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=unfinishedSynthesis.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore requeued paid narrative synthesis."); } + catch(SqlException error) when(error.Number==51022) { } + Check((await service.PreviewAsync(new(){JsonText=unfinishedSynthesis.ToJsonString()})).Preview!.Validation.Warnings.Any(w=>w.Contains("Unfinished narrative synthesis",StringComparison.Ordinal)),"Unfinished synthesis warning is explicit."); + var synthesisCopy=await service.ImportAsync(new(){JsonText=unfinishedSynthesis.ToJsonString(),ConfirmImport=true,AcknowledgeWarnings=true,AllowDuplicateProjectTitle=true}); + Check(synthesisCopy.Succeeded,"Incomplete synthesis copy retains inactive history: "+synthesisCopy.TechnicalDetail); + var copiedSynthesis=(await backups.GetProjectBackupAsync(synthesisCopy.ProjectID!.Value,importingUser))!; + Check(copiedSynthesis.Data.WholeBookPlotSynthesisRuns.All(run=>run.Status=="Failed" && !run.IsCurrent) && copiedSynthesis.Data.StoryIntelligenceNarrativeCandidates.Count==6 && copiedSynthesis.Data.StoryIntelligenceNarrativeCandidateEvents.Count==2,"Copied synthesis cannot be claimed as queued/running work; decisions/events survive."); + var sourceSynthesis=before.Data.WholeBookPlotSynthesisRuns.First().WholeBookPlotSynthesisRunID; + await db.ExecuteAsync("UPDATE dbo.WholeBookPlotSynthesisRuns SET Status=N'Running' WHERE WholeBookPlotSynthesisRunID=@id",new{id=sourceSynthesis}); + try + { + var refusal=await restoreService.RestoreAsync(project,savedPoint.ProjectRestorePointID); + Check(!refusal.Succeeded && refusal.SafetyBackup is not null && refusal.Message.Contains("Narrative synthesis is unfinished",StringComparison.Ordinal),"Actual restore service explains active synthesis refusal and retains safety backup."); + } + finally { await db.ExecuteAsync("UPDATE dbo.WholeBookPlotSynthesisRuns SET Status=N'Completed' WHERE WholeBookPlotSynthesisRunID=@id",new{id=sourceSynthesis}); } + // Synthetic nullable-run key contract, not a historical backup file fixture. + var legacyNarrative=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!; + foreach(var row in legacyNarrative["Data"]!["StoryIntelligenceNarrativeCandidates"]!.AsArray())row!["WholeBookPlotSynthesisRunID"]=null; + foreach(var row in legacyNarrative["Data"]!["StoryIntelligenceNarrativeCandidateEvents"]!.AsArray())row!["WholeBookPlotSynthesisRunID"]=null; + foreach(var row in legacyNarrative["Data"]!["ThreadEvents"]!.AsArray().Where(row=>row!["Source"]!.GetValue()=="WholeBookPlotSynthesis")) + { + var key=row!["SourceKey"]!.GetValue();row["SourceKey"]=key[key.IndexOf(':')..]; + } + var legacyNarrativeCopy=await service.ImportAsync(new(){JsonText=legacyNarrative.ToJsonString(),ConfirmImport=true,AcknowledgeWarnings=true,AllowDuplicateProjectTitle=true}); + Check(legacyNarrativeCopy.Succeeded,"Nullable-run narrative source contract imports: "+legacyNarrativeCopy.TechnicalDetail); + await ProjectTransferNarrativeAssertions.VerifyCopyAsync(before,(await backups.GetProjectBackupAsync(legacyNarrativeCopy.ProjectID!.Value,importingUser))!,factory,legacyNullRun:true); foreach(var omitted in new[]{"CharacterEnrichmentRuns","CharacterEnrichmentEvidence"}) { var older=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!;older["Data"]!.AsObject().Remove(omitted); @@ -525,7 +568,7 @@ internal static class ProjectTransferDatabaseTests var removeNavigationBook=await restoreService.RestoreAsync(project,savedPoint.ProjectRestorePointID); Check(removeNavigationBook.Succeeded && await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.Books WHERE BookID=@navigationBook",new{navigationBook})==0 && await db.ExecuteScalarAsync("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 96 populated persistent collections: copy/in-place stored values and actual safety/rollback; unrepresented project tables remain pending."); + Console.WriteLine("PASS 100 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) { @@ -571,7 +614,8 @@ 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" or "CharacterEnrichmentRuns" && 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" or "WholeBookPlotSynthesisRuns" && column=="UserID")expected=importingUser.Value; + if(collection.Name=="ThreadEvents" && Read(collection.Before[index],"Source") as string=="WholeBookPlotSynthesis" && column is "SourceKey" or "SourceReferenceID")continue; // Both source kinds asserted separately. 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"; @@ -582,7 +626,7 @@ internal static class ProjectTransferDatabaseTests { if(links.TryGetValue(column,out var target) && ids.TryGetValue((target,expected),out var mapped))expected=mapped; else if(identities.GetValueOrDefault(collection.Table)==column && ids.TryGetValue((collection.Table,expected),out mapped))expected=mapped; - var semanticTarget=column switch {"BuildID"=>"OnboardingManuscriptBuilds","ImportRunID"=>"StoryIntelligenceRuns","LastRunID"=>"StoryIntelligenceRuns","CreatedSceneResultID" or "SourceSceneResultID" or "LastUpdatedSceneResultID" or "FirstSeenSceneResultID" or "LastSeenSceneResultID"=>"StoryIntelligenceSceneResults","ProjectID"=>"Projects","BookID" or "InitialBookID"=>"Books","ChapterID" or "ProposedChapterID"=>"Chapters","SceneID" or "FromSceneID" or "ToSceneID" or "SourceSceneID" or "TargetSceneID" or "AgeReferenceSceneID"=>"Scenes","CharacterID" or "CharacterAID" or "CharacterBID" or "POVCharacterID"=>"Characters","StoryAssetID" or "AssetID" or "SourceAssetID" or "TargetAssetID"=>"StoryAssets","LocationID" or "FromLocationID" or "ToLocationID" or "EntryLocationID" or "ExitLocationID" or "ParentLocationID" or "CurrentLocationID" or "PrimaryLocationID"=>"Locations","MapID" or "ParentMapID"=>"StoryMaps","MetricTypeID"=>"SceneMetricTypes","AvatarSourceCharacterImageID"=>"CharacterImages","SourceEventID" or "PlotEventID"=>"ThreadEvents",_=>""}; + var semanticTarget=column switch {"BuildID"=>"OnboardingManuscriptBuilds","ImportRunID"=>"StoryIntelligenceRuns","WholeBookPlotSynthesisRunID"=>"WholeBookPlotSynthesisRuns","AuthorPlotSeedID"=>"AuthorPlotSeeds","LastRunID"=>"StoryIntelligenceRuns","CreatedSceneResultID" or "SourceSceneResultID" or "LastUpdatedSceneResultID" or "FirstSeenSceneResultID" or "LastSeenSceneResultID"=>"StoryIntelligenceSceneResults","ProjectID"=>"Projects","BookID" or "InitialBookID"=>"Books","ChapterID" or "ProposedChapterID"=>"Chapters","SceneID" or "FromSceneID" or "ToSceneID" or "SourceSceneID" or "TargetSceneID" or "AgeReferenceSceneID"=>"Scenes","CharacterID" or "CharacterAID" or "CharacterBID" or "POVCharacterID"=>"Characters","StoryAssetID" or "AssetID" or "SourceAssetID" or "TargetAssetID"=>"StoryAssets","LocationID" or "FromLocationID" or "ToLocationID" or "EntryLocationID" or "ExitLocationID" or "ParentLocationID" or "CurrentLocationID" or "PrimaryLocationID"=>"Locations","MapID" or "ParentMapID"=>"StoryMaps","MetricTypeID"=>"SceneMetricTypes","AvatarSourceCharacterImageID"=>"CharacterImages","SourceEventID" or "PlotEventID"=>"ThreadEvents",_=>""}; var sourceValue=Read(collection.Before[index],column)!; if(ids.TryGetValue((semanticTarget,sourceValue),out mapped))expected=mapped; if(collection.Name=="StoryMemoryRelationships" && column is "SourceEntityID" or "TargetEntityID") diff --git a/PlotLine.Tests/ProjectTransferNarrativeAssertions.cs b/PlotLine.Tests/ProjectTransferNarrativeAssertions.cs new file mode 100644 index 00000000..0b6783a0 --- /dev/null +++ b/PlotLine.Tests/ProjectTransferNarrativeAssertions.cs @@ -0,0 +1,52 @@ +using Dapper; +using PlotLine.Data; +using PlotLine.Models; + +internal static class ProjectTransferNarrativeAssertions +{ + private static void Check(bool condition,string message){if(!condition)throw new InvalidOperationException(message);} + internal static async Task VerifyCopyAsync(ProjectBackupExport before,ProjectBackupExport after,ISqlConnectionFactory factory,bool legacyNullRun=false) + { + var data=after.Data; + Check(before.Data.WholeBookPlotSynthesisRuns.Count==2 && before.Data.StoryIntelligenceNarrativeCandidates.Count==6 + && before.Data.StoryIntelligenceNarrativeCandidateEvidence.Count==6 && before.Data.StoryIntelligenceNarrativeCandidateEvents.Count==2 + && before.Data.ThreadEvents.Count==3,"Backup includes completed/failed synthesis, every review state, ignored events and both accepted source forms."); + var run=data.WholeBookPlotSynthesisRuns.Single(x=>x.Status=="Completed"); + var explicitCandidate=data.StoryIntelligenceNarrativeCandidates.Single(x=>x.CandidateKey=="Thread:question-Ω"); + var fallbackCandidate=data.StoryIntelligenceNarrativeCandidates.Single(x=>x.CandidateKey=="Thread:evidence-雨"); + var plotCandidate=data.StoryIntelligenceNarrativeCandidates.Single(x=>x.CandidateType=="PlotLine"); + var merged=data.StoryIntelligenceNarrativeCandidates.Single(x=>x.Status=="Merged"); + var candidateEvent=data.StoryIntelligenceNarrativeCandidateEvents.Single(x=>x.EventKey=="arrival:Ω"); + var explicitCanonical=data.ThreadEvents.Single(x=>x.EventTitle=="Accepted synthesis event Ω"); + var fallbackCanonical=data.ThreadEvents.Single(x=>x.EventTitle=="Accepted evidence event 雨"); + var evidence=data.StoryIntelligenceNarrativeCandidateEvidence.Single(x=>x.NarrativeCandidateID==fallbackCandidate.NarrativeCandidateID); + int? linkedRun=legacyNullRun ? null : run.WholeBookPlotSynthesisRunID; + Check(explicitCandidate.WholeBookPlotSynthesisRunID==linkedRun && fallbackCandidate.WholeBookPlotSynthesisRunID==linkedRun && candidateEvent.WholeBookPlotSynthesisRunID==linkedRun,"Narrative source run associations follow the copied graph."); + Check(explicitCanonical.SourceReferenceID==candidateEvent.NarrativeCandidateEventID + && explicitCanonical.SourceKey==$"{linkedRun}:{explicitCandidate.NarrativeCandidateID}:arrival:Ω" + && candidateEvent.AcceptedThreadEventID==explicitCanonical.ThreadEventID,"Explicit narrative candidate-event/canonical provenance remaps in both directions."); + Check(fallbackCanonical.SourceReferenceID==fallbackCandidate.NarrativeCandidateID + && fallbackCanonical.SourceKey==$"{linkedRun}:{fallbackCandidate.NarrativeCandidateID}:{evidence.SceneID}:{evidence.SortOrder}","Evidence-only narrative source remaps candidate and original evidence scene identities."); + Check(explicitCandidate.ParentNarrativeCandidateID==plotCandidate.NarrativeCandidateID && merged.MergeTargetNarrativeCandidateID==explicitCandidate.NarrativeCandidateID,"Narrative parent and merge targets retain their meaning."); + Check(run.ResultJson==before.Data.WholeBookPlotSynthesisRuns.Single(x=>x.Status=="Completed").ResultJson,"Provider result JSON is retained exactly as audit, including original embedded source identifiers."); + var reader=new StoryIntelligenceNarrativeCandidateRepository(factory); + var records=await reader.ListByBookAsync(data.Books.Single().BookID); + Check(records.Count==6 && records.Count(x=>x.Status=="Accepted")==3 && records.Any(x=>x.Status=="Pending") + && records.Any(x=>x.Status=="Rejected") && records.Any(x=>x.Status=="Merged") + && records.Sum(x=>x.Evidence.Count)==6 && records.Sum(x=>x.Events.Count)==2 + && records.SelectMany(x=>x.Events).Any(x=>x.IsIgnored),"Production narrative reader retains all settled/pending states and ignored event evidence."); + using var db=factory.CreateConnection(); + Check(await db.ExecuteScalarAsync("SELECT DB_NAME()") == "PlotDirector_Phase2_20261103_2305" + && await db.ExecuteScalarAsync("SELECT COUNT(*) FROM sys.extended_properties WHERE class=0 AND name=N'PlotDirector.Phase2.SyntheticOnly' AND CONVERT(nvarchar(20),value)=N'true'")==1,"Narrative replay is synthetic-only."); + foreach(var item in new[]{explicitCanonical,fallbackCanonical})for(var attempt=0;attempt<2;attempt++) + { + // Same production procedure and metadata parameters used by narrative materialization. + var id=await db.QuerySingleAsync("dbo.ThreadEvent_Save",new { + ThreadEventID=0,item.PlotThreadID,item.SceneID,item.EventTypeID,item.PlotEventTypeID,item.TargetPlotLineID, + item.EventTitle,item.EventDescription,item.Source,item.SourceReferenceID,item.SourceKey,item.Confidence + },commandType:System.Data.CommandType.StoredProcedure); + Check(id==item.ThreadEventID,"Copied narrative source keys remain idempotent through production event persistence."); + } + Check(await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.ThreadEvents WHERE PlotThreadID=@id",new{id=explicitCanonical.PlotThreadID})==3,"Replayed copied narrative sources create no duplicate canonical events."); + } +} diff --git a/PlotLine/Data/ProjectBackupRepository.cs b/PlotLine/Data/ProjectBackupRepository.cs index cf9d7137..be08b99e 100644 --- a/PlotLine/Data/ProjectBackupRepository.cs +++ b/PlotLine/Data/ProjectBackupRepository.cs @@ -136,6 +136,11 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact data.StoryIntelligenceReviewCandidateEvidence = (await state.ReadAsync()).ToList(); data.CharacterEnrichmentRuns = (await state.ReadAsync()).ToList(); data.CharacterEnrichmentEvidence = (await state.ReadAsync()).ToList(); + data.WholeBookPlotSynthesisRuns = (await state.ReadAsync()).ToList(); + data.StoryIntelligenceNarrativeCandidates = (await state.ReadAsync()).ToList(); + data.StoryIntelligenceNarrativeCandidateEvidence = (await state.ReadAsync()).ToList(); + data.StoryIntelligenceNarrativeCandidateEvents = (await state.ReadAsync()).ToList(); + @@ -181,6 +186,10 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact ProjectId = projectId, IncludedEntitySets = [ + nameof(data.WholeBookPlotSynthesisRuns), + nameof(data.StoryIntelligenceNarrativeCandidates), + nameof(data.StoryIntelligenceNarrativeCandidateEvidence), + nameof(data.StoryIntelligenceNarrativeCandidateEvents), nameof(data.CharacterEnrichmentRuns), nameof(data.CharacterEnrichmentEvidence), nameof(data.StoryIntelligenceReviewCandidateGenerations), diff --git a/PlotLine/Models/ProjectBackupModels.cs b/PlotLine/Models/ProjectBackupModels.cs index 00344786..3118d9d8 100644 --- a/PlotLine/Models/ProjectBackupModels.cs +++ b/PlotLine/Models/ProjectBackupModels.cs @@ -14,6 +14,11 @@ public sealed class ProjectBackupExport public sealed class ProjectBackupData { + public IReadOnlyList WholeBookPlotSynthesisRuns { get; set; } = []; + public IReadOnlyList StoryIntelligenceNarrativeCandidates { get; set; } = []; + public IReadOnlyList StoryIntelligenceNarrativeCandidateEvidence { get; set; } = []; + public IReadOnlyList StoryIntelligenceNarrativeCandidateEvents { get; set; } = []; + public IReadOnlyList CharacterEnrichmentRuns { get; set; } = []; public IReadOnlyList CharacterEnrichmentEvidence { get; set; } = []; @@ -847,3 +852,98 @@ public sealed class ProjectBackupCharacterEnrichmentEvidence public string Source { get; set; } = ""; public DateTime CreatedUtc { get; set; } } + +public sealed class ProjectBackupWholeBookPlotSynthesisRuns +{ + public int WholeBookPlotSynthesisRunID { get; set; } + public int ProjectID { get; set; } + public int BookID { get; set; } + public int UserID { get; set; } + public int? SourceStoryIntelligenceRunID { get; set; } + public string CharacterResolutionVersion { get; set; } = ""; + public string Status { 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 string? OpenAIResponseID { get; set; } + public int? InputTokens { get; set; } + public int? OutputTokens { get; set; } + public int? CachedInputTokens { get; set; } + public int? TotalTokens { get; set; } + public long? DurationMs { get; set; } + public string? ErrorMessage { get; set; } + public string? ErrorDetail { get; set; } + public string? ResultJson { get; set; } + public bool IsCurrent { get; set; } + public DateTime UpdatedUtc { get; set; } +} + +public sealed class ProjectBackupStoryIntelligenceNarrativeCandidates +{ + public int NarrativeCandidateID { get; set; } + public int ProjectID { get; set; } + public int BookID { get; set; } + public string CandidateType { get; set; } = ""; + public string CandidateKey { get; set; } = ""; + public string ProposedTitle { get; set; } = ""; + public string? ProposedDescription { get; set; } + public string? Category { get; set; } + public string? InferredState { get; set; } + public int? ExistingPlotLineID { get; set; } + public int? ExistingPlotThreadID { get; set; } + public int? RelatedPlotLineID { get; set; } + public decimal? Confidence { get; set; } + public string Status { get; set; } = ""; + public string? ReviewAction { get; set; } + public int? AcceptedPlotLineID { get; set; } + public int? AcceptedPlotThreadID { get; set; } + public int? ReviewedByUserID { get; set; } + public DateTime? ReviewedUtc { get; set; } + public DateTime CreatedUtc { get; set; } + public DateTime UpdatedUtc { get; set; } + public string? ChangeType { get; set; } + public string? Significance { get; set; } + public string? ParentCandidateKey { get; set; } + public int? ParentNarrativeCandidateID { get; set; } + public int? MergeTargetNarrativeCandidateID { get; set; } + public int? WholeBookPlotSynthesisRunID { get; set; } + public int? AuthorPlotSeedID { get; set; } + public decimal? ExistingPlotLineMatchConfidence { get; set; } + public string? ExistingPlotLineMatchReason { get; set; } + public decimal? SeedMatchConfidence { get; set; } + public string? SeedMatchReason { get; set; } + public string? Source { get; set; } +} + +public sealed class ProjectBackupStoryIntelligenceNarrativeCandidateEvidence +{ + public int NarrativeCandidateEvidenceID { get; set; } + public int NarrativeCandidateID { get; set; } + public int SceneID { get; set; } + public string? ContributionType { get; set; } + public string? Evidence { get; set; } + public int SortOrder { get; set; } + public DateTime CreatedUtc { get; set; } +} + +public sealed class ProjectBackupStoryIntelligenceNarrativeCandidateEvents +{ + public int NarrativeCandidateEventID { get; set; } + public int NarrativeCandidateID { get; set; } + public int? WholeBookPlotSynthesisRunID { get; set; } + public string EventKey { get; set; } = ""; + public int SceneID { get; set; } + public string EventType { get; set; } = ""; + public string EventTitle { get; set; } = ""; + public string? EventDescription { get; set; } + public string? Evidence { get; set; } + public decimal? Confidence { get; set; } + public int SortOrder { get; set; } + public bool IsIgnored { get; set; } + public int? AcceptedThreadEventID { get; set; } + public DateTime CreatedUtc { get; set; } + public DateTime UpdatedUtc { get; set; } +} diff --git a/PlotLine/Services/ImportServices.cs b/PlotLine/Services/ImportServices.cs index 2edffedc..7d0df57c 100644 --- a/PlotLine/Services/ImportServices.cs +++ b/PlotLine/Services/ImportServices.cs @@ -349,7 +349,9 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService if (backup.Data.ManuscriptDocuments.Any() || backup.Data.Chapters.Any(x => x.IsLinkedToManuscript) || backup.Data.Scenes.Any(x => x.IsLinkedToManuscript)) 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."); + validation.Warnings.Add("Copied plot event source identities are remapped. Source links absent from this backup are detached."); + if(backup.Data.WholeBookPlotSynthesisRuns.Any(run=>run.Status is not ("Completed" or "Failed" or "Superseded"))) + validation.Warnings.Add("Unfinished narrative synthesis is copied as failed, inactive history. No paid synthesis is restarted."); 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")) @@ -632,7 +634,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService validation.Errors.Add("The project backup does not contain a project name."); } - var mapError = ProjectBackupMapValidation.Validate(backup) ?? ProjectBackupGraphValidation.Validate(backup) ?? ProjectBackupFiles.Validate(backup); + var mapError = ProjectBackupMapValidation.Validate(backup) ?? ProjectBackupGraphValidation.Validate(backup) ?? ProjectBackupNarrative.ValidatePortableSources(backup) ?? ProjectBackupFiles.Validate(backup); if(mapError is null && backup.Data.StoryMemoryLocations.Any(location=>location.ParentLocationID.HasValue)) mapError="This backup contains a story-memory parent identifier whose portable relationship is not defined. Same-project restore retains it, but import as a copy is not supported for this field."; if (mapError is not null) @@ -849,7 +851,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService private static readonly string[] ProjectBackupIdentityTables = [ "ProjectTimelineSettings", "TimelineViewPresets", "SceneMetricTypes", "Books", "Chapters", "Scenes", "StoryMaps", - "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", + "WholeBookPlotSynthesisRuns", "StoryIntelligenceNarrativeCandidates", "StoryIntelligenceNarrativeCandidateEvidence", "StoryIntelligenceNarrativeCandidateEvents", "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", @@ -893,6 +895,11 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService } int ExistingOrNew(string table, int oldId) => maps.TryGetValue(table, out var map) && map.TryGetValue(oldId, out var newId) ? newId : oldId; int? ExistingOrNewNullable(string table, int? oldId) => oldId.HasValue ? ExistingOrNew(table, oldId.Value) : null; + var narrativeSources=ProjectBackupNarrative.CaptureSources(backup); + foreach(var row in backup.Data.WholeBookPlotSynthesisRuns) NewId("WholeBookPlotSynthesisRuns",row.WholeBookPlotSynthesisRunID); + foreach(var row in backup.Data.StoryIntelligenceNarrativeCandidates) NewId("StoryIntelligenceNarrativeCandidates",row.NarrativeCandidateID); + foreach(var row in backup.Data.StoryIntelligenceNarrativeCandidateEvents) NewId("StoryIntelligenceNarrativeCandidateEvents",row.NarrativeCandidateEventID); + static Dictionary LookupByName(IEnumerable rows) => rows.Where(x => !string.IsNullOrWhiteSpace(x.LookupName)) .GroupBy(x => x.LookupName.Trim(), StringComparer.OrdinalIgnoreCase) @@ -1197,6 +1204,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService foreach (var threadEvent in backup.Data.ThreadEvents) { + var narrativeSource=narrativeSources.GetValueOrDefault(threadEvent.ThreadEventID); threadEvent.ThreadEventID = NewId("ThreadEvents", threadEvent.ThreadEventID); threadEvent.PlotThreadID = ExistingOrNew("PlotThreads", threadEvent.PlotThreadID); threadEvent.PlotLineID = ExistingOrNew("PlotLines", threadEvent.PlotLineID); @@ -1204,8 +1212,26 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService threadEvent.EventTypeID = ResolveLookupID(threadEventTypeIds, threadEvent.EventTypeID, threadEvent.EventTypeName, $"Thread event \"{threadEvent.EventTitle}\" type"); threadEvent.PlotEventTypeID = ResolveLookupID(plotEventTypeIds, threadEvent.PlotEventTypeID, threadEvent.PlotEventTypeName, $"Thread event \"{threadEvent.EventTitle}\" plot event type"); threadEvent.TargetPlotLineID = ExistingOrNewNullable("PlotLines", threadEvent.TargetPlotLineID); - if (threadEvent.SourceKey is not null) threadEvent.SourceKey = $"backup:{projectId}:{threadEvent.ThreadEventID}"; - threadEvent.SourceReferenceID = null; // Copied events cannot refer into the original analysis/review. + if(narrativeSource is not null) + { + var run=ExistingOrNewNullable("WholeBookPlotSynthesisRuns",narrativeSource.RunID); + var candidate=ExistingOrNew("StoryIntelligenceNarrativeCandidates",narrativeSource.CandidateID); + if(narrativeSource.CandidateEventID.HasValue) + { + threadEvent.SourceReferenceID=ExistingOrNew("StoryIntelligenceNarrativeCandidateEvents",narrativeSource.CandidateEventID.Value); + threadEvent.SourceKey=$"{run}:{candidate}:{narrativeSource.EventKey}"; + } + else + { + threadEvent.SourceReferenceID=candidate; + threadEvent.SourceKey=$"{run}:{candidate}:{ExistingOrNew("Scenes",narrativeSource.EvidenceSceneID!.Value)}:{narrativeSource.EvidenceSortOrder}"; + } + } + else + { + if(threadEvent.SourceKey is not null)threadEvent.SourceKey=$"backup:{projectId}:{threadEvent.ThreadEventID}"; + threadEvent.SourceReferenceID=null; // Older backups may not carry the source graph. + } } foreach (var asset in backup.Data.StoryAssets) @@ -1812,6 +1838,49 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService row.CharacterID=ExistingOrNew("Characters",row.CharacterID); row.SceneID=ExistingOrNewNullable("Scenes",row.SceneID); } + foreach(var row in backup.Data.WholeBookPlotSynthesisRuns) + { + row.WholeBookPlotSynthesisRunID=NewId("WholeBookPlotSynthesisRuns",row.WholeBookPlotSynthesisRunID); + row.ProjectID=projectId; + row.BookID=ExistingOrNew("Books",row.BookID); + row.UserID=importingUserId; + row.SourceStoryIntelligenceRunID=ExistingOrNewNullable("StoryIntelligenceRuns",row.SourceStoryIntelligenceRunID); + if(row.Status is not ("Completed" or "Failed" or "Superseded")) + { + row.Status="Failed";row.IsCurrent=false; + row.ErrorMessage="Copied unfinished synthesis; explicit analysis is required."; + } + } + foreach(var row in backup.Data.StoryIntelligenceNarrativeCandidates) + { + row.NarrativeCandidateID=NewId("StoryIntelligenceNarrativeCandidates",row.NarrativeCandidateID); + row.ProjectID=projectId; + row.BookID=ExistingOrNew("Books",row.BookID); + row.ExistingPlotLineID=ExistingOrNewNullable("PlotLines",row.ExistingPlotLineID); + row.ExistingPlotThreadID=ExistingOrNewNullable("PlotThreads",row.ExistingPlotThreadID); + row.RelatedPlotLineID=ExistingOrNewNullable("PlotLines",row.RelatedPlotLineID); + row.AcceptedPlotLineID=ExistingOrNewNullable("PlotLines",row.AcceptedPlotLineID); + row.AcceptedPlotThreadID=ExistingOrNewNullable("PlotThreads",row.AcceptedPlotThreadID); + if(row.ReviewedByUserID.HasValue)row.ReviewedByUserID=importingUserId; + row.ParentNarrativeCandidateID=ExistingOrNewNullable("StoryIntelligenceNarrativeCandidates",row.ParentNarrativeCandidateID); + row.MergeTargetNarrativeCandidateID=ExistingOrNewNullable("StoryIntelligenceNarrativeCandidates",row.MergeTargetNarrativeCandidateID); + row.WholeBookPlotSynthesisRunID=ExistingOrNewNullable("WholeBookPlotSynthesisRuns",row.WholeBookPlotSynthesisRunID); + row.AuthorPlotSeedID=ExistingOrNewNullable("AuthorPlotSeeds",row.AuthorPlotSeedID); + } + foreach(var row in backup.Data.StoryIntelligenceNarrativeCandidateEvidence) + { + row.NarrativeCandidateEvidenceID=NewId("StoryIntelligenceNarrativeCandidateEvidence",row.NarrativeCandidateEvidenceID); + row.NarrativeCandidateID=ExistingOrNew("StoryIntelligenceNarrativeCandidates",row.NarrativeCandidateID); + row.SceneID=ExistingOrNew("Scenes",row.SceneID); + } + foreach(var row in backup.Data.StoryIntelligenceNarrativeCandidateEvents) + { + row.NarrativeCandidateEventID=NewId("StoryIntelligenceNarrativeCandidateEvents",row.NarrativeCandidateEventID); + row.NarrativeCandidateID=ExistingOrNew("StoryIntelligenceNarrativeCandidates",row.NarrativeCandidateID); + row.WholeBookPlotSynthesisRunID=ExistingOrNewNullable("WholeBookPlotSynthesisRuns",row.WholeBookPlotSynthesisRunID); + row.SceneID=ExistingOrNew("Scenes",row.SceneID); + row.AcceptedThreadEventID=ExistingOrNewNullable("ThreadEvents",row.AcceptedThreadEventID); + } foreach (var image in backup.Data.CharacterImages) { image.CharacterImageID=NewId("CharacterImages",image.CharacterImageID); diff --git a/PlotLine/Services/ProjectBackupGraphValidation.cs b/PlotLine/Services/ProjectBackupGraphValidation.cs index 552bff84..4f2b2421 100644 --- a/PlotLine/Services/ProjectBackupGraphValidation.cs +++ b/PlotLine/Services/ProjectBackupGraphValidation.cs @@ -8,6 +8,10 @@ internal static class ProjectBackupGraphValidation private sealed record Link(string Column, string TargetCollection, string TargetColumn); private sealed record Entity(string Collection, string? Identity, params Link[] Links); private static readonly Entity[] Entities = [ + new("WholeBookPlotSynthesisRuns","WholeBookPlotSynthesisRunID",new Link("ProjectID","Project","ProjectID"),new Link("BookID","Books","BookID"),new Link("SourceStoryIntelligenceRunID","StoryIntelligenceRuns","StoryIntelligenceRunID")), + new("StoryIntelligenceNarrativeCandidates","NarrativeCandidateID",new Link("ProjectID","Project","ProjectID"),new Link("BookID","Books","BookID"),new Link("ExistingPlotLineID","PlotLines","PlotLineID"),new Link("ExistingPlotThreadID","PlotThreads","PlotThreadID"),new Link("RelatedPlotLineID","PlotLines","PlotLineID"),new Link("AcceptedPlotLineID","PlotLines","PlotLineID"),new Link("AcceptedPlotThreadID","PlotThreads","PlotThreadID"),new Link("ParentNarrativeCandidateID","StoryIntelligenceNarrativeCandidates","NarrativeCandidateID"),new Link("MergeTargetNarrativeCandidateID","StoryIntelligenceNarrativeCandidates","NarrativeCandidateID"),new Link("WholeBookPlotSynthesisRunID","WholeBookPlotSynthesisRuns","WholeBookPlotSynthesisRunID"),new Link("AuthorPlotSeedID","AuthorPlotSeeds","AuthorPlotSeedID")), + new("StoryIntelligenceNarrativeCandidateEvidence","NarrativeCandidateEvidenceID",new Link("NarrativeCandidateID","StoryIntelligenceNarrativeCandidates","NarrativeCandidateID"),new Link("SceneID","Scenes","SceneID")), + new("StoryIntelligenceNarrativeCandidateEvents","NarrativeCandidateEventID",new Link("NarrativeCandidateID","StoryIntelligenceNarrativeCandidates","NarrativeCandidateID"),new Link("WholeBookPlotSynthesisRunID","WholeBookPlotSynthesisRuns","WholeBookPlotSynthesisRunID"),new Link("SceneID","Scenes","SceneID"),new Link("AcceptedThreadEventID","ThreadEvents","ThreadEventID")), 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")), @@ -135,6 +139,6 @@ internal static class ProjectBackupGraphValidation } if(backup.Data.StoryIntelligenceRuns.Count>0 && backup.Data.Scenes.Any(scene=>scene.ImportRunID.HasValue && !backup.Data.StoryIntelligenceRuns.Any(run=>run.StoryIntelligenceRunID==scene.ImportRunID))) return "Project backup scene analysis provenance references a missing or foreign run."; - return ProjectBackupEntityReview.Validate(backup) ?? ProjectBackupStoryMemory.Validate(backup) ?? ProjectBackupTimelineState.Validate(backup); + return ProjectBackupNarrative.Validate(backup) ?? ProjectBackupEntityReview.Validate(backup) ?? ProjectBackupStoryMemory.Validate(backup) ?? ProjectBackupTimelineState.Validate(backup); } } diff --git a/PlotLine/Services/ProjectBackupNarrative.cs b/PlotLine/Services/ProjectBackupNarrative.cs new file mode 100644 index 00000000..0c04229e --- /dev/null +++ b/PlotLine/Services/ProjectBackupNarrative.cs @@ -0,0 +1,104 @@ +using PlotLine.Models; + +namespace PlotLine.Services; + +internal static class ProjectBackupNarrative +{ + internal sealed record EventSource(int? RunID,int CandidateID,int? CandidateEventID,string? EventKey,int? EvidenceSceneID,int? EvidenceSortOrder); + + private sealed class SourceIndex + { + internal readonly Dictionary<(int Reference,string Key),List<(EventSource Link,int? AcceptedID)>> Events=[]; + internal readonly Dictionary<(int Reference,string Key),List> Evidence=[]; + internal SourceIndex(ProjectBackupExport backup) + { + foreach(var row in backup.Data.StoryIntelligenceNarrativeCandidateEvents) + { + var key=(row.NarrativeCandidateEventID,$"{row.WholeBookPlotSynthesisRunID}:{row.NarrativeCandidateID}:{row.EventKey}"); + if(!Events.TryGetValue(key,out var matches))Events[key]=matches=[]; + matches.Add((new(row.WholeBookPlotSynthesisRunID,row.NarrativeCandidateID,row.NarrativeCandidateEventID,row.EventKey,null,null),row.AcceptedThreadEventID)); + } + var candidates=backup.Data.StoryIntelligenceNarrativeCandidates.ToDictionary(row=>row.NarrativeCandidateID); + foreach(var row in backup.Data.StoryIntelligenceNarrativeCandidateEvidence) + { + var candidate=candidates[row.NarrativeCandidateID]; + var key=(candidate.NarrativeCandidateID,$"{candidate.WholeBookPlotSynthesisRunID}:{candidate.NarrativeCandidateID}:{row.SceneID}:{row.SortOrder}"); + if(!Evidence.TryGetValue(key,out var matches))Evidence[key]=matches=[]; + matches.Add(new(candidate.WholeBookPlotSynthesisRunID,candidate.NarrativeCandidateID,null,null,row.SceneID,row.SortOrder)); + } + } + } + + private static List Sources(SourceIndex index,ThreadEvent canonical) + { + if(!string.Equals(canonical.Source,WholeBookPlotSynthesisSources.WholeBook,StringComparison.OrdinalIgnoreCase) + || !canonical.SourceReferenceID.HasValue || canonical.SourceKey is null)return []; + var key=(canonical.SourceReferenceID.Value,canonical.SourceKey); + var events=index.Events.GetValueOrDefault(key) ?? []; + var accepted=events.Where(row=>row.AcceptedID==canonical.ThreadEventID).ToArray(); + if(accepted.Length==1)return [accepted[0].Link]; + return events.Select(row=>row.Link).Concat(index.Evidence.GetValueOrDefault(key) ?? []).Distinct().ToList(); + } + + internal static Dictionary CaptureSources(ProjectBackupExport backup) + { + var links=new Dictionary(); + var index=new SourceIndex(backup); + foreach(var row in backup.Data.ThreadEvents) + { + var matches=Sources(index,row); + if(matches.Count==1)links[row.ThreadEventID]=matches[0]; + } + return links; + } + + internal static string? ValidatePortableSources(ProjectBackupExport backup) + { + // Older backups did not carry this graph; their copies keep the established detached-history behaviour. + if(backup.Data.StoryIntelligenceNarrativeCandidates.Count==0 && backup.Data.StoryIntelligenceNarrativeCandidateEvents.Count==0)return null; + var index=new SourceIndex(backup); + foreach(var row in backup.Data.ThreadEvents.Where(row=>string.Equals(row.Source,WholeBookPlotSynthesisSources.WholeBook,StringComparison.OrdinalIgnoreCase) && row.SourceReferenceID.HasValue)) + if(Sources(index,row).Count!=1)return "A narrative event source is missing or ambiguous in this backup. Its source identity cannot safely be copied; same-project restore retains the original history."; + return null; + } + + internal static string? Validate(ProjectBackupExport backup) + { + var rows=backup.Data.StoryIntelligenceNarrativeCandidates.ToDictionary(row=>row.NarrativeCandidateID); + var runs=backup.Data.WholeBookPlotSynthesisRuns.ToDictionary(row=>row.WholeBookPlotSynthesisRunID); + var seeds=backup.Data.AuthorPlotSeeds.ToDictionary(row=>row.AuthorPlotSeedID); + var chapters=backup.Data.Chapters.ToDictionary(row=>row.ChapterID,row=>row.BookID); + var sceneBooks=backup.Data.Scenes.ToDictionary(row=>row.SceneID,row=>chapters[row.ChapterID]); + foreach(var row in rows.Values) + { + if(row.WholeBookPlotSynthesisRunID.HasValue && runs[row.WholeBookPlotSynthesisRunID.Value].BookID!=row.BookID) + return "A narrative candidate belongs to a different book from its synthesis run."; + if(row.AuthorPlotSeedID.HasValue && seeds[row.AuthorPlotSeedID.Value].BookID!=row.BookID) + return "A narrative candidate references another book's author seed."; + foreach(var target in new[]{row.ParentNarrativeCandidateID,row.MergeTargetNarrativeCandidateID}) + if(target.HasValue && rows[target.Value].BookID!=row.BookID)return "A narrative parent or merge target belongs to another book."; + if(row.ParentNarrativeCandidateID.HasValue && !string.IsNullOrEmpty(row.ParentCandidateKey) + && !row.ParentCandidateKey.Equals(rows[row.ParentNarrativeCandidateID.Value].CandidateKey,StringComparison.OrdinalIgnoreCase)) + return "A narrative parent key does not match its candidate reference."; + } + foreach(var evidence in backup.Data.StoryIntelligenceNarrativeCandidateEvidence) + if(sceneBooks[evidence.SceneID]!=rows[evidence.NarrativeCandidateID].BookID)return "Narrative evidence references a scene in another book."; + foreach(var item in backup.Data.StoryIntelligenceNarrativeCandidateEvents) + { + var parent=rows[item.NarrativeCandidateID]; + if(sceneBooks[item.SceneID]!=parent.BookID)return "A narrative candidate event references another book's scene."; + if(item.WholeBookPlotSynthesisRunID.HasValue && runs[item.WholeBookPlotSynthesisRunID.Value].BookID!=parent.BookID) + return "A narrative candidate event references another book's synthesis run."; + } + // Iterative topological check avoids recursion on large or malicious parent/merge chains. + var incoming=rows.Keys.ToDictionary(id=>id,_=>0); + foreach(var row in rows.Values)foreach(var target in new[]{row.ParentNarrativeCandidateID,row.MergeTargetNarrativeCandidateID})if(target.HasValue)incoming[target.Value]++; + var ready=new Queue(incoming.Where(pair=>pair.Value==0).Select(pair=>pair.Key));var visited=0; + while(ready.TryDequeue(out var id)) + { + visited++;var row=rows[id]; + foreach(var target in new[]{row.ParentNarrativeCandidateID,row.MergeTargetNarrativeCandidateID})if(target.HasValue && --incoming[target.Value]==0)ready.Enqueue(target.Value); + } + return visited==rows.Count ? null : "The narrative parent or merge graph contains a cycle."; + } +} diff --git a/PlotLine/Services/ProjectRestoreService.cs b/PlotLine/Services/ProjectRestoreService.cs index 8292e9c6..f67f76e0 100644 --- a/PlotLine/Services/ProjectRestoreService.cs +++ b/PlotLine/Services/ProjectRestoreService.cs @@ -95,7 +95,7 @@ public sealed class ProjectRestoreService( Succeeded = false, // 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 + Message = ex is Microsoft.Data.SqlClient.SqlException { Number: >= 51006 and <= 51022 } refusal ? refusal.Message + " The safety backup was retained." : "Restore failed. The safety backup was created, and the project data was left unchanged.", SafetyBackup = safetyBackup diff --git a/PlotLine/Sql/228_ProjectBackupNarrativeHistory.sql b/PlotLine/Sql/228_ProjectBackupNarrativeHistory.sql new file mode 100644 index 00000000..801a9d51 --- /dev/null +++ b/PlotLine/Sql/228_ProjectBackupNarrativeHistory.sql @@ -0,0 +1,575 @@ +-- Version 1.3 additive narrative synthesis, decisions, evidence and candidate event provenance. +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; + SELECT r.* FROM dbo.WholeBookPlotSynthesisRuns r WHERE r.ProjectID=@ProjectID ORDER BY r.WholeBookPlotSynthesisRunID; + SELECT r.* FROM dbo.StoryIntelligenceNarrativeCandidates r WHERE r.ProjectID=@ProjectID ORDER BY r.NarrativeCandidateID; + SELECT r.* FROM dbo.StoryIntelligenceNarrativeCandidateEvidence r JOIN dbo.StoryIntelligenceNarrativeCandidates p ON p.NarrativeCandidateID=r.NarrativeCandidateID WHERE p.ProjectID=@ProjectID ORDER BY r.NarrativeCandidateEvidenceID; + SELECT r.* FROM dbo.StoryIntelligenceNarrativeCandidateEvents r JOIN dbo.StoryIntelligenceNarrativeCandidates p ON p.NarrativeCandidateID=r.NarrativeCandidateID WHERE p.ProjectID=@ProjectID ORDER BY r.NarrativeCandidateEventID; +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'WholeBookPlotSynthesisRuns'), + (N'StoryIntelligenceNarrativeCandidates'), + (N'StoryIntelligenceNarrativeCandidateEvidence'), + (N'StoryIntelligenceNarrativeCandidateEvents'), + (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; + IF JSON_QUERY(@JsonData,'$.Data.WholeBookPlotSynthesisRuns') IS NULL AND EXISTS(SELECT 1 FROM dbo.WholeBookPlotSynthesisRuns r WHERE r.ProjectID=@ProjectID) + THROW 51021,'This older restore point omits existing narrative synthesis or review history. Restore was aborted without changing it.',1; + IF JSON_QUERY(@JsonData,'$.Data.StoryIntelligenceNarrativeCandidates') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryIntelligenceNarrativeCandidates r WHERE r.ProjectID=@ProjectID) + THROW 51021,'This older restore point omits existing narrative synthesis or review history. Restore was aborted without changing it.',1; + IF JSON_QUERY(@JsonData,'$.Data.StoryIntelligenceNarrativeCandidateEvidence') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryIntelligenceNarrativeCandidateEvidence r JOIN dbo.StoryIntelligenceNarrativeCandidates p ON p.NarrativeCandidateID=r.NarrativeCandidateID WHERE p.ProjectID=@ProjectID) + THROW 51021,'This older restore point omits existing narrative synthesis or review history. Restore was aborted without changing it.',1; + IF JSON_QUERY(@JsonData,'$.Data.StoryIntelligenceNarrativeCandidateEvents') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryIntelligenceNarrativeCandidateEvents r JOIN dbo.StoryIntelligenceNarrativeCandidates p ON p.NarrativeCandidateID=r.NarrativeCandidateID WHERE p.ProjectID=@ProjectID) + THROW 51021,'This older restore point omits existing narrative synthesis or review history. Restore was aborted without changing it.',1; + IF EXISTS(SELECT 1 FROM dbo.WholeBookPlotSynthesisRuns WHERE ProjectID=@ProjectID AND Status NOT IN(N'Completed',N'Failed',N'Superseded')) + OR EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.WholeBookPlotSynthesisRuns') WITH(Status nvarchar(40) '$.Status') WHERE Status NOT IN(N'Completed',N'Failed',N'Superseded')) + THROW 51022,'Narrative synthesis 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.StoryIntelligenceNarrativeCandidateEvents r JOIN dbo.StoryIntelligenceNarrativeCandidates p ON p.NarrativeCandidateID=r.NarrativeCandidateID WHERE p.ProjectID=@ProjectID; + DELETE r FROM dbo.StoryIntelligenceNarrativeCandidateEvidence r JOIN dbo.StoryIntelligenceNarrativeCandidates p ON p.NarrativeCandidateID=r.NarrativeCandidateID WHERE p.ProjectID=@ProjectID; + DELETE r FROM dbo.StoryIntelligenceNarrativeCandidates r WHERE r.ProjectID=@ProjectID; + DELETE r FROM dbo.WholeBookPlotSynthesisRuns r WHERE r.ProjectID=@ProjectID; + 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; + + EXEC dbo.ProjectRestore_InsertJsonTable N'WholeBookPlotSynthesisRuns',N'$.Data.WholeBookPlotSynthesisRuns',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'StoryIntelligenceNarrativeCandidates',N'$.Data.StoryIntelligenceNarrativeCandidates',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'StoryIntelligenceNarrativeCandidateEvidence',N'$.Data.StoryIntelligenceNarrativeCandidateEvidence',@JsonData,@ProjectID,0; + EXEC dbo.ProjectRestore_InsertJsonTable N'StoryIntelligenceNarrativeCandidateEvents',N'$.Data.StoryIntelligenceNarrativeCandidateEvents',@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