fix: retain project illustration history without shared catalogue authority

This commit is contained in:
Nick Beckley 2026-11-04 05:39:21 +00:00
parent 4eee8e1e70
commit a880e1c973
15 changed files with 899 additions and 23 deletions

View File

@ -21,8 +21,8 @@ CharacterAttributeTypes,ProjectID or FK descendant,CharacterAttributeTypes,Seria
CharacterEnrichmentEvidence,ProjectID or FK descendant,CharacterEnrichmentEvidence,Persisted enrichment run audit and scene/book-wide evidence; full stored projection,Pass: completed/failed histories; owner/character/book/pipeline/scene remapping; exact evidence; in-place; missing/active guards,No file columns; canonical character images are handled by the separate file manifest; no provider invocation
CharacterEnrichmentRuns,ProjectID or FK descendant,CharacterEnrichmentRuns,Persisted enrichment run audit and scene/book-wide evidence; full stored projection,Pass: completed/failed histories; owner/character/book/pipeline/scene remapping; exact evidence; in-place; missing/active guards,No file columns; canonical character images are handled by the separate file manifest; no provider invocation
CharacterImages,ProjectID or FK descendant,CharacterImages,Version 1.3 gallery metadata including deleted history; populated stored-value comparison passed,"Copy/in-place graph, avatar target, metadata and SQL failure rollback passed","Version 1.3: exact active file bytes, independent paths, checksums, ledger owner/size, quota refusal and rollback verified; deleted gallery metadata retained without absent deleted files"
CharacterIntelligenceEvidenceEvents,ProjectID or FK descendant,CharacterIntelligenceEvidenceEvents,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
CharacterIntelligenceProfiles,ProjectID or FK descendant,CharacterIntelligenceProfiles,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
CharacterIntelligenceEvidenceEvents,ProjectID or FK descendant,CharacterIntelligenceEvidenceEvents,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
CharacterIntelligenceProfiles,ProjectID or FK descendant,CharacterIntelligenceProfiles,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
CharacterKnowledge,ProjectID or FK descendant,CharacterKnowledge,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
CharacterRelationships,ProjectID or FK descendant,CharacterRelationships,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
CharacterRoleInSceneTypes,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
@ -45,7 +45,7 @@ FloorPlanTransitions,ProjectID or FK descendant,FloorPlanTransitions,Serialized
GenreMetricPresetMetrics,ProjectID or FK descendant,GenreMetricPresetMetrics,Serialized; field completeness unverified,Pending,Pending
GenreMetricPresets,Global/user/independent,GenreMetricPresets,Serialized; field completeness unverified,Pending,Pending
GivenNames,Global/user/independent,,Shared name reference dataset and import metadata; outside author project ownership,Deliberately excluded from portable project payload,Project character names/aliases are separate serialized collections
IllustrationLibraryItems,SourceProjectID/SourceBookID soft references; shared and project-derived items,,Persistent generated asset catalogue and provenance; not included; separate scope/remapping needed,Pending,Not covered by current project backup file manifest
IllustrationLibraryItems,SourceProjectID/SourceBookID soft references; shared and project-derived items,,"Shared administrator-managed catalogue, approval/usage/archive state and soft source provenance; excluded from author-controlled project restore",Pass: no catalogue rows created/reapproved by copy; every shared catalogue field and global request unchanged after copy/in-place,Library files not bundled; explicit diagnostic and import warning. Project-origin shared catalogue recovery requires separate administrator backup; no portable recovery claim
KnowledgeStates,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
LocationAliases,ProjectID or FK descendant,LocationAliases,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
LocationRelationships,ProjectID or FK descendant,LocationRelationships,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
@ -113,10 +113,10 @@ Scenes,ProjectID or FK descendant,Scenes,Serialized persistent set; populated SQ
SceneTextStatistics,ProjectID or FK descendant,SceneTextStatistics,Persistent scene suggestion decisions or stored derived manuscript statistics; serialized,Pass: populated SQL projection; copy actor/reference mapping; in-place stored values; old-snapshot review-history refusal,No file payloads; pending/accepted/rejected/dismissed status fixtures populated for each suggestion kind
SceneWorkflow,ProjectID or FK descendant,SceneWorkflow,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated
StoryAssets,ProjectID or FK descendant,StoryAssets,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,"Version 1.3: exact active file bytes, independent paths, checksums, ledger owner/size, quota refusal and rollback verified; deleted gallery metadata retained without absent deleted files"
StoryIntelligenceBookPipelines,ProjectID or FK descendant,StoryIntelligenceBookPipelines,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
StoryIntelligenceBookPipelines,ProjectID or FK descendant,StoryIntelligenceBookPipelines,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
StoryIntelligenceChapterResults,ProjectID or FK descendant,StoryIntelligenceChapterResults,Retained analysis source/results and import audit; full stored fields serialized,Pass: exact long raw JSON/source; copy canonical/run/actor refs; in-place; old snapshot and active-analysis refusal,Raw JSON is historical audit and is not parsed/rebuilt during backup; unfinished copied runs cancelled; review/pipeline graph separate pending scope
StoryIntelligenceConsents,UserID and account onboarding consent ledger; project/book references,,Immutable account consent history: never recreated for importer or rewound from project JSON,Pass: exact retained fields; book FK protected; snapshot removing required book refused before mutation,Not an author-content cache; consent text remains in original account
StoryIntelligenceIllustrationDemands,ProjectID or FK descendant,,Pending classification,Pending,Pending
StoryIntelligenceIllustrationDemands,ProjectID-specific request aggregate; NULL global requests excluded,StoryIntelligenceIllustrationDemands,Persistent project-scoped illustration association/request history; complete stored projection,Pass: source fields; typed copy remapping/inactive history; in-place; old-snapshot and active-generation guards,Shared catalogue IDs detached on copy; assignments inactive with explicit warning; same-project links retained; shared library files excluded and require administrator backup
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,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"
@ -128,16 +128,16 @@ StoryIntelligenceReviewCandidates,ProjectID or FK descendant,StoryIntelligenceRe
StoryIntelligenceRuns,ProjectID or FK descendant,StoryIntelligenceRuns,Retained analysis source/results and import audit; full stored fields serialized,Pass: exact long raw JSON/source; copy canonical/run/actor refs; in-place; old snapshot and active-analysis refusal,Raw JSON is historical audit and is not parsed/rebuilt during backup; unfinished copied runs cancelled; review/pipeline graph separate pending scope
StoryIntelligenceSceneResults,ProjectID or FK descendant,StoryIntelligenceSceneResults,Retained analysis source/results and import audit; full stored fields serialized,Pass: exact long raw JSON/source; copy canonical/run/actor refs; in-place; old snapshot and active-analysis refusal,Raw JSON is historical audit and is not parsed/rebuilt during backup; unfinished copied runs cancelled; review/pipeline graph separate pending scope
StoryMaps,ProjectID or FK descendant,StoryMaps,Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed,Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback,External file bytes not covered; embedded/text/JSON values compared where populated
StoryMemoryAssets,ProjectID or FK descendant,StoryMemoryAssets,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
StoryMemoryCharacterAliases,ProjectID or FK descendant,StoryMemoryCharacterAliases,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
StoryMemoryCharacterAttributes,ProjectID or FK descendant,StoryMemoryCharacterAttributes,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
StoryMemoryCharacters,ProjectID or FK descendant,StoryMemoryCharacters,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
StoryMemoryIllustrationAssignments,ProjectID or FK descendant,,Pending classification,Pending,Pending
StoryMemoryIllustrationDemands,ProjectID or FK descendant,,Pending classification,Pending,Pending
StoryMemoryImportPreferences,ProjectID or FK descendant,StoryMemoryImportPreferences,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
StoryMemoryLocations,ProjectID or FK descendant,StoryMemoryLocations,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
StoryMemoryProcessedSceneResults,ProjectID or FK descendant,StoryMemoryProcessedSceneResults,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
StoryMemoryRelationships,ProjectID or FK descendant,StoryMemoryRelationships,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
StoryMemoryAssets,ProjectID or FK descendant,StoryMemoryAssets,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
StoryMemoryCharacterAliases,ProjectID or FK descendant,StoryMemoryCharacterAliases,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
StoryMemoryCharacterAttributes,ProjectID or FK descendant,StoryMemoryCharacterAttributes,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
StoryMemoryCharacters,ProjectID or FK descendant,StoryMemoryCharacters,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
StoryMemoryIllustrationAssignments,ImportSessionID -> project pipeline,StoryMemoryIllustrationAssignments,Persistent project-scoped illustration association/request history; complete stored projection,Pass: source fields; typed copy remapping/inactive history; in-place; old-snapshot and active-generation guards,Shared catalogue IDs detached on copy; assignments inactive with explicit warning; same-project links retained; shared library files excluded and require administrator backup
StoryMemoryIllustrationDemands,ImportSessionID -> project pipeline,StoryMemoryIllustrationDemands,Persistent project-scoped illustration association/request history; complete stored projection,Pass: source fields; typed copy remapping/inactive history; in-place; old-snapshot and active-generation guards,Shared catalogue IDs detached on copy; assignments inactive with explicit warning; same-project links retained; shared library files excluded and require administrator backup
StoryMemoryImportPreferences,ProjectID or FK descendant,StoryMemoryImportPreferences,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
StoryMemoryLocations,ProjectID or FK descendant,StoryMemoryLocations,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
StoryMemoryProcessedSceneResults,ProjectID or FK descendant,StoryMemoryProcessedSceneResults,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
StoryMemoryRelationships,ProjectID or FK descendant,StoryMemoryRelationships,Persistent pipeline/memory/profile evidence graph; complete stored projection,Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards,nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
StripeWebhookEvent,Global/user/independent,,Account/authentication/billing state; outside project backup ownership,Deliberately excluded; copy creates only importer project access,Never recreate credentials or billing state from project JSON
SubscriptionAdministrationAudit,Global/user/independent,,Account/authentication/billing state; outside project backup ownership,Deliberately excluded; copy creates only importer project access,Never recreate credentials or billing state from project JSON
SubscriptionBookSlotReservation,Global/user/independent,,Account/authentication/billing state; outside project backup ownership,Deliberately excluded; copy creates only importer project access,Never recreate credentials or billing state from project JSON

1 Table ProjectOwnershipEvidence BackupCollection Classification RestoreVerified AssetsVerified
21 CharacterEnrichmentEvidence ProjectID or FK descendant CharacterEnrichmentEvidence Persisted enrichment run audit and scene/book-wide evidence; full stored projection Pass: completed/failed histories; owner/character/book/pipeline/scene remapping; exact evidence; in-place; missing/active guards No file columns; canonical character images are handled by the separate file manifest; no provider invocation
22 CharacterEnrichmentRuns ProjectID or FK descendant CharacterEnrichmentRuns Persisted enrichment run audit and scene/book-wide evidence; full stored projection Pass: completed/failed histories; owner/character/book/pipeline/scene remapping; exact evidence; in-place; missing/active guards No file columns; canonical character images are handled by the separate file manifest; no provider invocation
23 CharacterImages ProjectID or FK descendant CharacterImages Version 1.3 gallery metadata including deleted history; populated stored-value comparison passed Copy/in-place graph, avatar target, metadata and SQL failure rollback passed Version 1.3: exact active file bytes, independent paths, checksums, ledger owner/size, quota refusal and rollback verified; deleted gallery metadata retained without absent deleted files
24 CharacterIntelligenceEvidenceEvents ProjectID or FK descendant CharacterIntelligenceEvidenceEvents Persistent pipeline/memory/profile evidence graph; complete stored projection Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
25 CharacterIntelligenceProfiles ProjectID or FK descendant CharacterIntelligenceProfiles Persistent pipeline/memory/profile evidence graph; complete stored projection Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
26 CharacterKnowledge ProjectID or FK descendant CharacterKnowledge 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
27 CharacterRelationships ProjectID or FK descendant CharacterRelationships 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
28 CharacterRoleInSceneTypes 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
45 GenreMetricPresetMetrics ProjectID or FK descendant GenreMetricPresetMetrics Serialized; field completeness unverified Pending Pending
46 GenreMetricPresets Global/user/independent GenreMetricPresets Serialized; field completeness unverified Pending Pending
47 GivenNames Global/user/independent Shared name reference dataset and import metadata; outside author project ownership Deliberately excluded from portable project payload Project character names/aliases are separate serialized collections
48 IllustrationLibraryItems SourceProjectID/SourceBookID soft references; shared and project-derived items Persistent generated asset catalogue and provenance; not included; separate scope/remapping needed Shared administrator-managed catalogue, approval/usage/archive state and soft source provenance; excluded from author-controlled project restore Pending Pass: no catalogue rows created/reapproved by copy; every shared catalogue field and global request unchanged after copy/in-place Not covered by current project backup file manifest Library files not bundled; explicit diagnostic and import warning. Project-origin shared catalogue recovery requires separate administrator backup; no portable recovery claim
49 KnowledgeStates 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
50 LocationAliases ProjectID or FK descendant LocationAliases 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
51 LocationRelationships ProjectID or FK descendant LocationRelationships 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
113 SceneTextStatistics ProjectID or FK descendant SceneTextStatistics Persistent scene suggestion decisions or stored derived manuscript statistics; serialized Pass: populated SQL projection; copy actor/reference mapping; in-place stored values; old-snapshot review-history refusal No file payloads; pending/accepted/rejected/dismissed status fixtures populated for each suggestion kind
114 SceneWorkflow ProjectID or FK descendant SceneWorkflow Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback External file bytes not covered; embedded/text/JSON values compared where populated
115 StoryAssets ProjectID or FK descendant StoryAssets Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback Version 1.3: exact active file bytes, independent paths, checksums, ledger owner/size, quota refusal and rollback verified; deleted gallery metadata retained without absent deleted files
116 StoryIntelligenceBookPipelines ProjectID or FK descendant StoryIntelligenceBookPipelines Persistent pipeline/memory/profile evidence graph; complete stored projection Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
117 StoryIntelligenceChapterResults ProjectID or FK descendant StoryIntelligenceChapterResults Retained analysis source/results and import audit; full stored fields serialized Pass: exact long raw JSON/source; copy canonical/run/actor refs; in-place; old snapshot and active-analysis refusal Raw JSON is historical audit and is not parsed/rebuilt during backup; unfinished copied runs cancelled; review/pipeline graph separate pending scope
118 StoryIntelligenceConsents UserID and account onboarding consent ledger; project/book references Immutable account consent history: never recreated for importer or rewound from project JSON Pass: exact retained fields; book FK protected; snapshot removing required book refused before mutation Not an author-content cache; consent text remains in original account
119 StoryIntelligenceIllustrationDemands ProjectID or FK descendant ProjectID-specific request aggregate; NULL global requests excluded StoryIntelligenceIllustrationDemands Pending classification Persistent project-scoped illustration association/request history; complete stored projection Pending Pass: source fields; typed copy remapping/inactive history; in-place; old-snapshot and active-generation guards Pending Shared catalogue IDs detached on copy; assignments inactive with explicit warning; same-project links retained; shared library files excluded and require administrator backup
120 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
121 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
122 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
128 StoryIntelligenceRuns ProjectID or FK descendant StoryIntelligenceRuns Retained analysis source/results and import audit; full stored fields serialized Pass: exact long raw JSON/source; copy canonical/run/actor refs; in-place; old snapshot and active-analysis refusal Raw JSON is historical audit and is not parsed/rebuilt during backup; unfinished copied runs cancelled; review/pipeline graph separate pending scope
129 StoryIntelligenceSceneResults ProjectID or FK descendant StoryIntelligenceSceneResults Retained analysis source/results and import audit; full stored fields serialized Pass: exact long raw JSON/source; copy canonical/run/actor refs; in-place; old snapshot and active-analysis refusal Raw JSON is historical audit and is not parsed/rebuilt during backup; unfinished copied runs cancelled; review/pipeline graph separate pending scope
130 StoryMaps ProjectID or FK descendant StoryMaps Serialized persistent set; populated SQL projection and stored-value copy/in-place comparisons passed Pass: source SQL fields; copy references/actors; in-place restore; SQL failure rollback External file bytes not covered; embedded/text/JSON values compared where populated
131 StoryMemoryAssets ProjectID or FK descendant StoryMemoryAssets Persistent pipeline/memory/profile evidence graph; complete stored projection Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
132 StoryMemoryCharacterAliases ProjectID or FK descendant StoryMemoryCharacterAliases Persistent pipeline/memory/profile evidence graph; complete stored projection Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
133 StoryMemoryCharacterAttributes ProjectID or FK descendant StoryMemoryCharacterAttributes Persistent pipeline/memory/profile evidence graph; complete stored projection Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
134 StoryMemoryCharacters ProjectID or FK descendant StoryMemoryCharacters Persistent pipeline/memory/profile evidence graph; complete stored projection Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
135 StoryMemoryIllustrationAssignments ProjectID or FK descendant ImportSessionID -> project pipeline StoryMemoryIllustrationAssignments Pending classification Persistent project-scoped illustration association/request history; complete stored projection Pending Pass: source fields; typed copy remapping/inactive history; in-place; old-snapshot and active-generation guards Pending Shared catalogue IDs detached on copy; assignments inactive with explicit warning; same-project links retained; shared library files excluded and require administrator backup
136 StoryMemoryIllustrationDemands ProjectID or FK descendant ImportSessionID -> project pipeline StoryMemoryIllustrationDemands Pending classification Persistent project-scoped illustration association/request history; complete stored projection Pending Pass: source fields; typed copy remapping/inactive history; in-place; old-snapshot and active-generation guards Pending Shared catalogue IDs detached on copy; assignments inactive with explicit warning; same-project links retained; shared library files excluded and require administrator backup
137 StoryMemoryImportPreferences ProjectID or FK descendant StoryMemoryImportPreferences Persistent pipeline/memory/profile evidence graph; complete stored projection Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
138 StoryMemoryLocations ProjectID or FK descendant StoryMemoryLocations Persistent pipeline/memory/profile evidence graph; complete stored projection Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
139 StoryMemoryProcessedSceneResults ProjectID or FK descendant StoryMemoryProcessedSceneResults Persistent pipeline/memory/profile evidence graph; complete stored projection Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
140 StoryMemoryRelationships ProjectID or FK descendant StoryMemoryRelationships Persistent pipeline/memory/profile evidence graph; complete stored projection Pass: source fields; memory vs canonical identity mapping; profile evidence JSON; copy and in-place; old-snapshot/active guards Illustration assignment/demand graph separate pending; nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained nullable memory ParentLocationID portable target undefined: non-null copies refused; same-project value retained
141 StripeWebhookEvent Global/user/independent Account/authentication/billing state; outside project backup ownership Deliberately excluded; copy creates only importer project access Never recreate credentials or billing state from project JSON
142 SubscriptionAdministrationAudit Global/user/independent Account/authentication/billing state; outside project backup ownership Deliberately excluded; copy creates only importer project access Never recreate credentials or billing state from project JSON
143 SubscriptionBookSlotReservation Global/user/independent Account/authentication/billing state; outside project backup ownership Deliberately excluded; copy creates only importer project access Never recreate credentials or billing state from project JSON

View File

@ -950,6 +950,22 @@ StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,OutputTokens,int
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,TotalTokens,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,DurationMs,bigint,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceChapterResults,StoryIntelligenceChapterResults,CreatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceIllustrationDemands,StoryIntelligenceIllustrationDemands,StoryIntelligenceIllustrationDemandID,int,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceIllustrationDemands,StoryIntelligenceIllustrationDemands,ProjectID,int,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceIllustrationDemands,StoryIntelligenceIllustrationDemands,DemandKey,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceIllustrationDemands,StoryIntelligenceIllustrationDemands,AgeBand,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceIllustrationDemands,StoryIntelligenceIllustrationDemands,Presentation,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceIllustrationDemands,StoryIntelligenceIllustrationDemands,HairColour,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceIllustrationDemands,StoryIntelligenceIllustrationDemands,SkinTone,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceIllustrationDemands,StoryIntelligenceIllustrationDemands,HairLength,nvarchar,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceIllustrationDemands,StoryIntelligenceIllustrationDemands,Glasses,nvarchar,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceIllustrationDemands,StoryIntelligenceIllustrationDemands,FacialHair,nvarchar,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceIllustrationDemands,StoryIntelligenceIllustrationDemands,RequestCount,int,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceIllustrationDemands,StoryIntelligenceIllustrationDemands,LastRequestedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceIllustrationDemands,StoryIntelligenceIllustrationDemands,CreatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceIllustrationDemands,StoryIntelligenceIllustrationDemands,UpdatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceIllustrationDemands,StoryIntelligenceIllustrationDemands,QueuedUtc,datetime2,True,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceIllustrationDemands,StoryIntelligenceIllustrationDemands,GenerationSource,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceImportCommits,StoryIntelligenceImportCommits,StoryIntelligenceImportCommitID,int,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceImportCommits,StoryIntelligenceImportCommits,StoryIntelligenceRunID,int,False,False,True,Represented; projection and semantic comparison still required
StoryIntelligenceImportCommits,StoryIntelligenceImportCommits,ProjectID,int,True,False,True,Represented; projection and semantic comparison still required
@ -1187,6 +1203,36 @@ StoryMemoryCharacters,StoryMemoryCharacters,CreatedSceneResultID,int,True,False,
StoryMemoryCharacters,StoryMemoryCharacters,LastUpdatedSceneResultID,int,True,False,True,Represented; projection and semantic comparison still required
StoryMemoryCharacters,StoryMemoryCharacters,CreatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryCharacters,StoryMemoryCharacters,UpdatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationAssignments,StoryMemoryIllustrationAssignments,StoryMemoryIllustrationAssignmentID,int,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationAssignments,StoryMemoryIllustrationAssignments,ImportSessionID,int,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationAssignments,StoryMemoryIllustrationAssignments,EntityType,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationAssignments,StoryMemoryIllustrationAssignments,EntityID,int,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationAssignments,StoryMemoryIllustrationAssignments,IllustrationLibraryItemID,int,True,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationAssignments,StoryMemoryIllustrationAssignments,StableCode,nvarchar,True,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationAssignments,StoryMemoryIllustrationAssignments,AssignmentStatus,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationAssignments,StoryMemoryIllustrationAssignments,IsFallback,bit,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationAssignments,StoryMemoryIllustrationAssignments,MatchScore,int,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationAssignments,StoryMemoryIllustrationAssignments,Confidence,decimal,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationAssignments,StoryMemoryIllustrationAssignments,AssignmentReason,nvarchar,True,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationAssignments,StoryMemoryIllustrationAssignments,EvidenceVersion,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationAssignments,StoryMemoryIllustrationAssignments,AssignedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationAssignments,StoryMemoryIllustrationAssignments,LastValidatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationAssignments,StoryMemoryIllustrationAssignments,InvalidatedUtc,datetime2,True,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationAssignments,StoryMemoryIllustrationAssignments,InvalidationReason,nvarchar,True,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationAssignments,StoryMemoryIllustrationAssignments,CreatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationAssignments,StoryMemoryIllustrationAssignments,UpdatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationDemands,StoryMemoryIllustrationDemands,StoryMemoryIllustrationDemandID,int,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationDemands,StoryMemoryIllustrationDemands,ImportSessionID,int,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationDemands,StoryMemoryIllustrationDemands,ProjectID,int,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationDemands,StoryMemoryIllustrationDemands,EntityType,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationDemands,StoryMemoryIllustrationDemands,ArchetypeKey,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationDemands,StoryMemoryIllustrationDemands,DemandCount,int,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationDemands,StoryMemoryIllustrationDemands,WaitingEntityCount,int,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationDemands,StoryMemoryIllustrationDemands,Status,nvarchar,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationDemands,StoryMemoryIllustrationDemands,QueuedIllustrationLibraryItemID,int,True,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationDemands,StoryMemoryIllustrationDemands,GeneratedIllustrationLibraryItemID,int,True,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationDemands,StoryMemoryIllustrationDemands,CreatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryIllustrationDemands,StoryMemoryIllustrationDemands,UpdatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryImportPreferences,StoryMemoryImportPreferences,StoryMemoryImportPreferenceID,int,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryImportPreferences,StoryMemoryImportPreferences,ImportSessionID,int,False,False,True,Represented; projection and semantic comparison still required
StoryMemoryImportPreferences,StoryMemoryImportPreferences,AppearancePreference,nvarchar,False,False,True,Represented; projection and semantic comparison still required

1 Table Collection Column SqlType Nullable Computed WritableModelProperty Classification
950 StoryIntelligenceChapterResults StoryIntelligenceChapterResults TotalTokens int True False True Represented; projection and semantic comparison still required
951 StoryIntelligenceChapterResults StoryIntelligenceChapterResults DurationMs bigint True False True Represented; projection and semantic comparison still required
952 StoryIntelligenceChapterResults StoryIntelligenceChapterResults CreatedUtc datetime2 False False True Represented; projection and semantic comparison still required
953 StoryIntelligenceIllustrationDemands StoryIntelligenceIllustrationDemands StoryIntelligenceIllustrationDemandID int False False True Represented; projection and semantic comparison still required
954 StoryIntelligenceIllustrationDemands StoryIntelligenceIllustrationDemands ProjectID int True False True Represented; projection and semantic comparison still required
955 StoryIntelligenceIllustrationDemands StoryIntelligenceIllustrationDemands DemandKey nvarchar False False True Represented; projection and semantic comparison still required
956 StoryIntelligenceIllustrationDemands StoryIntelligenceIllustrationDemands AgeBand nvarchar False False True Represented; projection and semantic comparison still required
957 StoryIntelligenceIllustrationDemands StoryIntelligenceIllustrationDemands Presentation nvarchar False False True Represented; projection and semantic comparison still required
958 StoryIntelligenceIllustrationDemands StoryIntelligenceIllustrationDemands HairColour nvarchar False False True Represented; projection and semantic comparison still required
959 StoryIntelligenceIllustrationDemands StoryIntelligenceIllustrationDemands SkinTone nvarchar False False True Represented; projection and semantic comparison still required
960 StoryIntelligenceIllustrationDemands StoryIntelligenceIllustrationDemands HairLength nvarchar True False True Represented; projection and semantic comparison still required
961 StoryIntelligenceIllustrationDemands StoryIntelligenceIllustrationDemands Glasses nvarchar True False True Represented; projection and semantic comparison still required
962 StoryIntelligenceIllustrationDemands StoryIntelligenceIllustrationDemands FacialHair nvarchar True False True Represented; projection and semantic comparison still required
963 StoryIntelligenceIllustrationDemands StoryIntelligenceIllustrationDemands RequestCount int False False True Represented; projection and semantic comparison still required
964 StoryIntelligenceIllustrationDemands StoryIntelligenceIllustrationDemands LastRequestedUtc datetime2 False False True Represented; projection and semantic comparison still required
965 StoryIntelligenceIllustrationDemands StoryIntelligenceIllustrationDemands CreatedUtc datetime2 False False True Represented; projection and semantic comparison still required
966 StoryIntelligenceIllustrationDemands StoryIntelligenceIllustrationDemands UpdatedUtc datetime2 False False True Represented; projection and semantic comparison still required
967 StoryIntelligenceIllustrationDemands StoryIntelligenceIllustrationDemands QueuedUtc datetime2 True False True Represented; projection and semantic comparison still required
968 StoryIntelligenceIllustrationDemands StoryIntelligenceIllustrationDemands GenerationSource nvarchar False False True Represented; projection and semantic comparison still required
969 StoryIntelligenceImportCommits StoryIntelligenceImportCommits StoryIntelligenceImportCommitID int False False True Represented; projection and semantic comparison still required
970 StoryIntelligenceImportCommits StoryIntelligenceImportCommits StoryIntelligenceRunID int False False True Represented; projection and semantic comparison still required
971 StoryIntelligenceImportCommits StoryIntelligenceImportCommits ProjectID int True False True Represented; projection and semantic comparison still required
1203 StoryMemoryCharacters StoryMemoryCharacters LastUpdatedSceneResultID int True False True Represented; projection and semantic comparison still required
1204 StoryMemoryCharacters StoryMemoryCharacters CreatedUtc datetime2 False False True Represented; projection and semantic comparison still required
1205 StoryMemoryCharacters StoryMemoryCharacters UpdatedUtc datetime2 False False True Represented; projection and semantic comparison still required
1206 StoryMemoryIllustrationAssignments StoryMemoryIllustrationAssignments StoryMemoryIllustrationAssignmentID int False False True Represented; projection and semantic comparison still required
1207 StoryMemoryIllustrationAssignments StoryMemoryIllustrationAssignments ImportSessionID int False False True Represented; projection and semantic comparison still required
1208 StoryMemoryIllustrationAssignments StoryMemoryIllustrationAssignments EntityType nvarchar False False True Represented; projection and semantic comparison still required
1209 StoryMemoryIllustrationAssignments StoryMemoryIllustrationAssignments EntityID int False False True Represented; projection and semantic comparison still required
1210 StoryMemoryIllustrationAssignments StoryMemoryIllustrationAssignments IllustrationLibraryItemID int True False True Represented; projection and semantic comparison still required
1211 StoryMemoryIllustrationAssignments StoryMemoryIllustrationAssignments StableCode nvarchar True False True Represented; projection and semantic comparison still required
1212 StoryMemoryIllustrationAssignments StoryMemoryIllustrationAssignments AssignmentStatus nvarchar False False True Represented; projection and semantic comparison still required
1213 StoryMemoryIllustrationAssignments StoryMemoryIllustrationAssignments IsFallback bit False False True Represented; projection and semantic comparison still required
1214 StoryMemoryIllustrationAssignments StoryMemoryIllustrationAssignments MatchScore int False False True Represented; projection and semantic comparison still required
1215 StoryMemoryIllustrationAssignments StoryMemoryIllustrationAssignments Confidence decimal False False True Represented; projection and semantic comparison still required
1216 StoryMemoryIllustrationAssignments StoryMemoryIllustrationAssignments AssignmentReason nvarchar True False True Represented; projection and semantic comparison still required
1217 StoryMemoryIllustrationAssignments StoryMemoryIllustrationAssignments EvidenceVersion nvarchar False False True Represented; projection and semantic comparison still required
1218 StoryMemoryIllustrationAssignments StoryMemoryIllustrationAssignments AssignedUtc datetime2 False False True Represented; projection and semantic comparison still required
1219 StoryMemoryIllustrationAssignments StoryMemoryIllustrationAssignments LastValidatedUtc datetime2 False False True Represented; projection and semantic comparison still required
1220 StoryMemoryIllustrationAssignments StoryMemoryIllustrationAssignments InvalidatedUtc datetime2 True False True Represented; projection and semantic comparison still required
1221 StoryMemoryIllustrationAssignments StoryMemoryIllustrationAssignments InvalidationReason nvarchar True False True Represented; projection and semantic comparison still required
1222 StoryMemoryIllustrationAssignments StoryMemoryIllustrationAssignments CreatedUtc datetime2 False False True Represented; projection and semantic comparison still required
1223 StoryMemoryIllustrationAssignments StoryMemoryIllustrationAssignments UpdatedUtc datetime2 False False True Represented; projection and semantic comparison still required
1224 StoryMemoryIllustrationDemands StoryMemoryIllustrationDemands StoryMemoryIllustrationDemandID int False False True Represented; projection and semantic comparison still required
1225 StoryMemoryIllustrationDemands StoryMemoryIllustrationDemands ImportSessionID int False False True Represented; projection and semantic comparison still required
1226 StoryMemoryIllustrationDemands StoryMemoryIllustrationDemands ProjectID int False False True Represented; projection and semantic comparison still required
1227 StoryMemoryIllustrationDemands StoryMemoryIllustrationDemands EntityType nvarchar False False True Represented; projection and semantic comparison still required
1228 StoryMemoryIllustrationDemands StoryMemoryIllustrationDemands ArchetypeKey nvarchar False False True Represented; projection and semantic comparison still required
1229 StoryMemoryIllustrationDemands StoryMemoryIllustrationDemands DemandCount int False False True Represented; projection and semantic comparison still required
1230 StoryMemoryIllustrationDemands StoryMemoryIllustrationDemands WaitingEntityCount int False False True Represented; projection and semantic comparison still required
1231 StoryMemoryIllustrationDemands StoryMemoryIllustrationDemands Status nvarchar False False True Represented; projection and semantic comparison still required
1232 StoryMemoryIllustrationDemands StoryMemoryIllustrationDemands QueuedIllustrationLibraryItemID int True False True Represented; projection and semantic comparison still required
1233 StoryMemoryIllustrationDemands StoryMemoryIllustrationDemands GeneratedIllustrationLibraryItemID int True False True Represented; projection and semantic comparison still required
1234 StoryMemoryIllustrationDemands StoryMemoryIllustrationDemands CreatedUtc datetime2 False False True Represented; projection and semantic comparison still required
1235 StoryMemoryIllustrationDemands StoryMemoryIllustrationDemands UpdatedUtc datetime2 False False True Represented; projection and semantic comparison still required
1236 StoryMemoryImportPreferences StoryMemoryImportPreferences StoryMemoryImportPreferenceID int False False True Represented; projection and semantic comparison still required
1237 StoryMemoryImportPreferences StoryMemoryImportPreferences ImportSessionID int False False True Represented; projection and semantic comparison still required
1238 StoryMemoryImportPreferences StoryMemoryImportPreferences AppearancePreference nvarchar False False True Represented; projection and semantic comparison still required

View File

@ -1,4 +1,7 @@
Collection,SourceRows,CopyRows,InPlaceRows,Verification
StoryMemoryIllustrationAssignments,4,4,4,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
StoryMemoryIllustrationDemands,3,3,3,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
StoryIntelligenceIllustrationDemands,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
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

1 Collection SourceRows CopyRows InPlaceRows Verification
2 StoryMemoryIllustrationAssignments 4 4 4 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
3 StoryMemoryIllustrationDemands 3 3 3 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
4 StoryIntelligenceIllustrationDemands 1 1 1 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
5 WholeBookPlotSynthesisRuns 2 2 2 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
6 StoryIntelligenceNarrativeCandidates 6 6 6 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
7 StoryIntelligenceNarrativeCandidateEvidence 6 6 6 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present

View File

@ -1,4 +1,7 @@
Table,Collection,OwnedDatabaseRows,ExportedRows,ExtraSharedRows,MissingOwnedRows
StoryMemoryIllustrationAssignments,StoryMemoryIllustrationAssignments,4,4,0,0
StoryMemoryIllustrationDemands,StoryMemoryIllustrationDemands,3,3,0,0
StoryIntelligenceIllustrationDemands,StoryIntelligenceIllustrationDemands,1,1,0,0
WholeBookPlotSynthesisRuns,WholeBookPlotSynthesisRuns,2,2,0,0
StoryIntelligenceNarrativeCandidates,StoryIntelligenceNarrativeCandidates,6,6,0,0
StoryIntelligenceNarrativeCandidateEvidence,StoryIntelligenceNarrativeCandidateEvidence,6,6,0,0

1 Table Collection OwnedDatabaseRows ExportedRows ExtraSharedRows MissingOwnedRows
2 StoryMemoryIllustrationAssignments StoryMemoryIllustrationAssignments 4 4 0 0
3 StoryMemoryIllustrationDemands StoryMemoryIllustrationDemands 3 3 0 0
4 StoryIntelligenceIllustrationDemands StoryIntelligenceIllustrationDemands 1 1 0 0
5 WholeBookPlotSynthesisRuns WholeBookPlotSynthesisRuns 2 2 0 0
6 StoryIntelligenceNarrativeCandidates StoryIntelligenceNarrativeCandidates 6 6 0 0
7 StoryIntelligenceNarrativeCandidateEvidence StoryIntelligenceNarrativeCandidateEvidence 6 6 0 0

View File

@ -16,9 +16,9 @@
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 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. Independent ownership-scope row census passed. 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.
5. COMPLETE CHECKPOINT: serialized backup/restore coverage now has 107 collections (103 persistent plus 4 diagnostic/shared vocabulary), 108 SQL entities / 1,388 columns with no missing non-computed model properties. All 103 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. COMPLETE CHECKPOINT: project illustration history and independent ownership-scope row census passed. 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. CLASSIFIED: all 167 schema tables now have an explicit disposition. Shared administrator-managed illustration catalogue/approval/archive/usage state and library files are excluded dependencies, with diagnostics and copy warnings; project source provenance in that shared catalogue is not portable project-owned artwork. No standalone shared-catalogue recovery claim. No real historical backup fixture found; synthetic legacy-shaped cases do not establish historical compatibility.
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.
@ -318,3 +318,15 @@ Narrative checkpoint: full 405-check regression harness passed, exit 0 (`/tmp/pl
Added a census independent of the backup selectors and DTO graph descriptor. Actual database foreign keys, composite primary keys, non-null ProjectID anchors and the documented legacy BookID soft reference determine the owned rows. The check rejects omitted owned rows, duplicate primary keys and foreign rows; explicitly shared vocabulary is checked separately. Per-table counts are in `2026-11-03-phase2-row-coverage.csv`.
Final real SQL run passed all 173 owned rows across 103 scoped entities, plus the existing 100 populated persistent collection copy/in-place matrix. Negative probes omitted a deleted gallery record and an ignored narrative event; both were detected despite every remaining exported value being valid. Build zero warnings/errors. Evidence `/tmp/plotdirector-phase2-row-census-final.log` and `/tmp/plotdirector-phase2-build-row-census-final.log`. Full 405 checks last passed at narrative checkpoint; this group changes only the specialist test harness. The census covers advertised entities, not the still-unclassified illustration tables.
## Project illustration association and request history — 4 November
Migration 229 adds complete persisted projections for StoryMemoryIllustrationAssignments, StoryMemoryIllustrationDemands and ProjectID-specific StoryIntelligenceIllustrationDemands. The last table has a unique ProjectID/DemandKey aggregate; NULL-project requests are shared and excluded. Memory assignment EntityID is typed and pipeline-scoped, with explicit preview validation and copy remapping. Fixtures include all three entity types, waiting and active assignments, invalidated/rejected history and recorded/queued/generated demand history.
Same-project restore preserves every stored field and catalogue reference, without rewinding shared catalogue state. Three old-shaped missing-collection guards prevent destructive omission. Current or referenced snapshot catalogue Queued/Generating work refuses restore before mutation. Imported copies retain stable codes, status/counters/evidence and original invalidation history; active assignments become explicitly inactive, and all queued/generated/shared catalogue links are detached. No worker/provider runs, catalogue rows, approvals or source provenance are manufactured. Warning acknowledgement is required under the existing import workflow.
The shared catalogue is selected without project ownership by the runtime and has administrator approval/archive/usage state plus soft SourceProject/Book/Scene provenance. Author-controlled backup JSON must not recreate/reapprove those shared rows or overwrite other projects' usage. It is therefore an explicit external dependency: catalogue records and library files need separate administrator-level recovery. Backup diagnostics and preview warnings state this boundary. Project-origin artwork in the shared catalogue is not bundled by the project-owned upload manifest; portable catalogue/file recovery remains unsupported. This is a declared limit, not verified image recovery.
Real SQL source projection passed 2,551 values across 106 populated entities. Independent census found all 181 owned rows across 106 scoped entities. All 103 populated persistent collections passed copy (2,419 generic comparisons plus semantic assertions) and in-place (2,515 comparisons). Shared catalogue every-field/global-request snapshots remained exactly equal through successful copy and restore; old omission and active-generation refusals also preserved state. Fifty malformed preview cases failed before allocation. All 167 schema tables are now classified, with explicit exclusions/limits. Evidence `/tmp/plotdirector-phase2-illustrations-sql.log`; build and final field/regression checkpoints follow. Migration 229 remains isolated-synthetic-only. No Development/Production schema or data writes, provider calls or deployment.
Illustration checkpoint: build zero warnings/errors; full 405-check regression harness passed, exit 0 (`/tmp/plotdirector-phase2-tests-illustrations.log`). Field census passed 108 entities / 1,388 columns / zero missing non-computed model properties (`/tmp/plotdirector-phase2-census-illustrations.log`). Actual shared catalogue/global-demand equality assertion passed through successful copy and in-place restore. No standalone library asset recovery or historical fixture claim.

View File

@ -257,3 +257,24 @@ 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);
-- Synthetic shared catalogue dependencies; never queue a provider or approve production artwork.
DECLARE @illustration int,@rejectedIllustration int;
INSERT dbo.IllustrationLibraryItems(Category,StableCode,DisplayTitle,Status,IsApproved,SourceProjectID,SourceBookID,SourceSceneID,AdminNotes,UsageCount,ReuseScope)
VALUES(N'Character',CONCAT(N'phase2-approved-',@project),N'Synthetic shared artwork Ω',N'Approved',1,@project,@book,@scene,N'Private administrator history must never be copied or rewound',7,N'Global');
SET @illustration=SCOPE_IDENTITY();
INSERT dbo.IllustrationLibraryItems(Category,StableCode,DisplayTitle,Status,IsApproved,SourceProjectID,RejectionReason,IsArchived,ArchiveReason)
VALUES(N'Character',CONCAT(N'phase2-rejected-',@project),N'Synthetic rejected artwork 雨',N'Rejected',0,@project,N'Synthetic rejection reason',1,N'Synthetic archive history');
SET @rejectedIllustration=SCOPE_IDENTITY();
INSERT dbo.StoryMemoryIllustrationAssignments(ImportSessionID,EntityType,EntityID,IllustrationLibraryItemID,StableCode,AssignmentStatus,IsFallback,MatchScore,Confidence,AssignmentReason,EvidenceVersion,AssignedUtc,LastValidatedUtc,InvalidatedUtc,InvalidationReason,CreatedUtc,UpdatedUtc)
VALUES(@pipeline,N'Character',@memoryCharacter,@illustration,CONCAT(N'phase2-approved-',@project),N'Assigned',0,91,.91,N'Explicit character evidence Ω',N'21S','2026-11-01','2026-11-02',NULL,NULL,'2026-11-01','2026-11-02'),
(@pipeline,N'Location',@memoryLocation,@illustration,CONCAT(N'phase2-approved-',@project),N'Assigned',1,81,.81,N'Fallback location evidence 雨',N'21S','2026-11-01','2026-11-02',NULL,NULL,'2026-11-01','2026-11-02'),
(@pipeline,N'Asset',@memoryAsset,NULL,N'pending-synthetic-asset',N'Waiting',0,0,0,N'Waiting for explicit artwork',N'21S','2026-11-01','2026-11-02',NULL,NULL,'2026-11-01','2026-11-02'),
(@pipeline,N'Character',@memoryCharacter,@rejectedIllustration,CONCAT(N'phase2-rejected-',@project),N'Assigned',0,61,.61,N'Historical rejected evidence',N'21R','2026-10-01','2026-10-02','2026-10-03',N'Author invalidated this artwork 雪','2026-10-01','2026-10-03');
INSERT dbo.StoryMemoryIllustrationDemands(ImportSessionID,ProjectID,EntityType,ArchetypeKey,DemandCount,WaitingEntityCount,Status,QueuedIllustrationLibraryItemID,GeneratedIllustrationLibraryItemID,CreatedUtc,UpdatedUtc)
VALUES(@pipeline,@project,N'Character',N'synthetic-character-Ω',4,2,N'Generated',@illustration,@illustration,'2026-11-01','2026-11-02'),
(@pipeline,@project,N'Location',N'synthetic-location-雨',3,1,N'Queued',@rejectedIllustration,NULL,'2026-11-01','2026-11-02'),
(@pipeline,@project,N'Asset',N'synthetic-asset-雪',1,1,N'Recorded',NULL,NULL,'2026-11-01','2026-11-02');
INSERT dbo.StoryIntelligenceIllustrationDemands(ProjectID,DemandKey,AgeBand,Presentation,HairColour,SkinTone,HairLength,Glasses,FacialHair,RequestCount,LastRequestedUtc,CreatedUtc,UpdatedUtc,QueuedUtc,GenerationSource)
VALUES(@project,N'synthetic-archetype-Ω',N'Adult',N'Neutral',N'Brown',N'Olive',N'Short',N'None',N'None',9,'2026-11-02','2026-11-01','2026-11-02','2026-11-02',N'Synthetic historical request'),
(NULL,CONCAT(N'synthetic-global-demand-',@project),N'Adult',N'Neutral',N'Brown',N'Olive',NULL,NULL,NULL,8,'2026-11-02','2026-11-01','2026-11-02',NULL,N'Shared global request remains outside author restore');

View File

@ -43,7 +43,7 @@ internal static class ProjectTransferDatabaseTests
}
if(applyMigrations)
{
foreach(var file in new[]{"PlotLine/Sql/213_ProjectBackupBookContext.sql","PlotLine/Sql/214_ProjectBackupPersistentSourceState.sql","PlotLine/Sql/215_ProjectBackupMapStoredMetadata.sql","PlotLine/Sql/216_ProjectBackupCompanionSceneLinks.sql","PlotLine/Sql/217_ProjectBackupUploadedFiles.sql","PlotLine/Sql/218_ImportSharedAssetStateLookups.sql","PlotLine/Sql/219_WordManuscriptImportCurrentSceneModel.sql","PlotLine/Sql/220_ProjectBackupCoreBuildProvenance.sql","PlotLine/Sql/221_ProjectBackupSceneReviewState.sql","PlotLine/Sql/222_ProjectBackupCoreLocationReview.sql","PlotLine/Sql/223_ProjectBackupAnalysisAudit.sql","PlotLine/Sql/224_ProjectBackupStoryMemory.sql","PlotLine/Sql/225_ProjectBackupEntityReviews.sql","PlotLine/Sql/226_ProjectRestoreAccountReferences.sql","PlotLine/Sql/227_ProjectBackupCharacterEnrichment.sql","PlotLine/Sql/228_ProjectBackupNarrativeHistory.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","PlotLine/Sql/229_ProjectBackupIllustrationHistory.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.");
@ -197,6 +197,7 @@ internal static class ProjectTransferDatabaseTests
var importUserService=Proxy<ICurrentUserService>((name,args)=>name switch {"get_UserId"=>(int?)importingUser,"get_IsAuthenticated"=>true,"get_Email"=>"phase2-importer@example.invalid","get_DisplayName"=>"Synthetic importing author",_=>throw new NotSupportedException(name)});
var service=new ImportService(repository,importUserService,subscription,NullLogger<ImportService>.Instance,assetFiles);
var baselineProjectCount=await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects");
var sharedIllustrationsBefore=await ProjectTransferIllustrationAssertions.SharedStateAsync(db);
var sourceJson=JsonSerializer.Serialize(before);
foreach(var probe in new[]{(Collection:"CharacterImages",Flag:"IsDeleted"),(Collection:"StoryIntelligenceNarrativeCandidateEvents",Flag:"IsIgnored")})
{
@ -233,6 +234,9 @@ internal static class ProjectTransferDatabaseTests
root=>root["Data"]!["StoryIntelligenceReviewCandidates"]![0]!["Module"]="Assets",
root=>root["Data"]!["StoryIntelligenceReviewCandidates"]![0]!["CandidatePayloadJson"]=null,
root=>root["Data"]!["StoryIntelligenceReviewCandidates"]![0]!["CandidatePayloadJson"]="[]",
root=>root["Data"]!["StoryMemoryIllustrationAssignments"]![0]!["EntityID"]=-12345,
root=>root["Data"]!["StoryMemoryIllustrationAssignments"]![0]!["EntityType"]="Unsupported",
root=>root["Data"]!["StoryMemoryIllustrationDemands"]![0]!["ImportSessionID"]=-12345,
root=>root["Data"]!["CharacterEnrichmentEvidence"]![0]!["CharacterEnrichmentRunID"]=-12345,
root=>root["Data"]!["CharacterEnrichmentRuns"]![0]!["CharacterID"]=-12345,
root=>root["Data"]!["WholeBookPlotSynthesisRuns"]![0]!["SourceStoryIntelligenceRunID"]=-12345,
@ -327,6 +331,8 @@ internal static class ProjectTransferDatabaseTests
var copiedReview=after.Data.CoreImportBasicLocationReviews.Single();
await ProjectTransferEntityReviewAssertions.VerifyCopyAsync(before,after,factory);
await ProjectTransferNarrativeAssertions.VerifyCopyAsync(before,after,factory);
await ProjectTransferIllustrationAssertions.VerifyAsync(db,before,after);
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;
@ -378,6 +384,7 @@ 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();
await ProjectTransferIllustrationAssertions.VerifyRestoreGuardsAsync(db,before,sourceJson,project);
foreach(var omitted in new[]{"WholeBookPlotSynthesisRuns","StoryIntelligenceNarrativeCandidates","StoryIntelligenceNarrativeCandidateEvidence","StoryIntelligenceNarrativeCandidateEvents"})
{
var older=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!;older["Data"]!.AsObject().Remove(omitted);
@ -541,6 +548,7 @@ internal static class ProjectTransferDatabaseTests
var sameProject=(await backups.GetProjectBackupAsync(project,user))!;
await assetFiles.CaptureAsync(sameProject);
await VerifyStoredRoundTripAsync(db,before,sameProject,null);
Check(sharedIllustrationsBefore==await ProjectTransferIllustrationAssertions.SharedStateAsync(db),"Successful copy and in-place restore preserve every shared catalogue field and global request row.");
Check(System.Text.Json.Nodes.JsonNode.DeepEquals(System.Text.Json.Nodes.JsonNode.Parse(before.Data.TimelineViewPresets.Single().FilterJson),System.Text.Json.Nodes.JsonNode.Parse(sameProject.Data.TimelineViewPresets.Single().FilterJson)),"In-place restore preserves every timeline filter property.");
Check(sameProject.Data.SceneManuscriptSources.Single().SourceText==manuscriptText && sameProject.Data.WritingPlans.Single().PlanName=="Synthetic drafting plan" && sameProject.Data.CharacterAliases.Single().Alias=="N. Ω","Same-project restore recovers text, schedule and authored alias.");
Check(sameProject.Data.ManuscriptDocuments.Single().DocumentGuid==before.Data.ManuscriptDocuments.Single().DocumentGuid && sameProject.Data.ManuscriptDocuments.Single().IsActive && sameProject.Data.Scenes.Single(x=>x.SceneTitle=="Scene café").IsLinkedToManuscript,"Same-project restore preserves original Word binding.");
@ -579,7 +587,7 @@ internal static class ProjectTransferDatabaseTests
var removeNavigationBook=await restoreService.RestoreAsync(project,savedPoint.ProjectRestorePointID);
Check(removeNavigationBook.Succeeded && await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Books WHERE BookID=@navigationBook",new{navigationBook})==0 && await db.ExecuteScalarAsync<int?>("SELECT BookID FROM dbo.UserOnboardingState WHERE UserID=@user",new{user}) is null,"Restore clears an account navigation pointer only when its unprotected book is deliberately removed.");
Console.WriteLine("PASS retained account/consent/job state: source unchanged by copy; no copied authority; completed history survives restore; active jobs/protected book removal refused; removed-book navigation pointer cleared.");
Console.WriteLine("PASS 100 populated persistent collections: copy/in-place stored values and actual safety/rollback; unrepresented project tables remain pending.");
Console.WriteLine("PASS project transfer: populated collection counts reported above; copy/in-place stored values and actual safety/rollback. Shared catalogue recovery is outside project transfer.");
}
private static async Task VerifyStoredRoundTripAsync(SqlConnection db, ProjectBackupExport original, ProjectBackupExport restored, int? importingUser)
{
@ -631,6 +639,9 @@ internal static class ProjectTransferDatabaseTests
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";
if(column=="SourceReviewKey" && collection.Name=="RelationshipEvents")expected=$"scene:{restored.Data.Scenes.Single(x=>x.SceneTitle=="Scene café").SceneID}:{restored.Data.Characters.Single(x=>x.CharacterName=="Narrator Ω").CharacterID}>{restored.Data.Characters.Single(x=>x.CharacterName=="Observer 雪").CharacterID}:Development:000000000000000000000002";
if(collection.Name=="StoryMemoryIllustrationAssignments" && column=="IllustrationLibraryItemID")expected=null;
if(collection.Name=="StoryMemoryIllustrationAssignments" && column is "InvalidatedUtc" or "InvalidationReason" && Read(collection.Before[index],"InvalidatedUtc") is null)continue; // Copy policy asserted separately.
if(collection.Name=="StoryMemoryIllustrationDemands" && column is "QueuedIllustrationLibraryItemID" or "GeneratedIllustrationLibraryItemID")expected=null;
if(collection.Name=="StoryMaps" && column=="ReferenceJson")continue; // Exact placement/image identity asserted separately.
}
if(expected is not null)
@ -640,6 +651,11 @@ internal static class ProjectTransferDatabaseTests
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=="StoryMemoryIllustrationAssignments" && column=="EntityID")
{
var targetMemory=Read(collection.Before[index],"EntityType")!.ToString() switch {"Character"=>"StoryMemoryCharacters","Location"=>"StoryMemoryLocations",_=>"StoryMemoryAssets"};
if(ids.TryGetValue((targetMemory,expected),out mapped))expected=mapped;
}
if(collection.Name=="StoryMemoryRelationships" && column is "SourceEntityID" or "TargetEntityID")
{
var type=Read(collection.Before[index],column=="SourceEntityID"?"SourceEntityType":"TargetEntityType") as string;

View File

@ -0,0 +1,53 @@
using System.Text.Json.Nodes;
using Dapper;
using Microsoft.Data.SqlClient;
using PlotLine.Models;
internal static class ProjectTransferIllustrationAssertions
{
private static void Check(bool condition,string message){if(!condition)throw new InvalidOperationException(message);}
private static async Task GuardAsync(SqlConnection db)=>Check(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()") == "PlotDirector_Phase2_20261103_2305" && await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM sys.extended_properties WHERE class=0 AND name=N'PlotDirector.Phase2.SyntheticOnly' AND CONVERT(nvarchar(20),value)=N'true'")==1,"Illustration assertions require synthetic database.");
internal static async Task<string> SharedStateAsync(SqlConnection db)
{
await GuardAsync(db);
return await db.ExecuteScalarAsync<string>("SELECT * FROM dbo.IllustrationLibraryItems ORDER BY IllustrationLibraryItemID FOR JSON PATH,INCLUDE_NULL_VALUES")
+ await db.ExecuteScalarAsync<string>("SELECT * FROM dbo.StoryIntelligenceIllustrationDemands WHERE ProjectID IS NULL ORDER BY StoryIntelligenceIllustrationDemandID FOR JSON PATH,INCLUDE_NULL_VALUES");
}
internal static async Task VerifyAsync(SqlConnection db,ProjectBackupExport before,ProjectBackupExport after)
{
await GuardAsync(db);
Check(before.Data.StoryMemoryIllustrationAssignments.Count==4 && before.Data.StoryMemoryIllustrationDemands.Count==3 && before.Data.StoryIntelligenceIllustrationDemands.Count==1,"Source contains active/waiting/invalidated assignments, three demand types and only project-scoped requests.");
Check(after.Data.StoryMemoryIllustrationAssignments.Count==4 && after.Data.StoryMemoryIllustrationAssignments.All(x=>x.InvalidatedUtc.HasValue && x.IllustrationLibraryItemID is null),"Copied assignments retain history without active/shared catalogue authority.");
Check(after.Data.StoryMemoryIllustrationAssignments.Where(x=>x.InvalidationReason!.StartsWith("Imported as inactive")).Count()==3 && after.Data.StoryMemoryIllustrationAssignments.Single(x=>x.EvidenceVersion=="21R").InvalidationReason=="Author invalidated this artwork 雪","New inactivity is explicit; original invalidation history survives.");
Check(after.Data.StoryMemoryIllustrationDemands.Count==3 && after.Data.StoryMemoryIllustrationDemands.All(x=>x.QueuedIllustrationLibraryItemID is null && x.GeneratedIllustrationLibraryItemID is null),"Copied demand history cannot attach another author's private/queued catalogue rows.");
foreach(var assignment in after.Data.StoryMemoryIllustrationAssignments)
{
var exists=assignment.EntityType switch {"Character"=>after.Data.StoryMemoryCharacters.Any(x=>x.StoryMemoryCharacterID==assignment.EntityID && x.ImportSessionID==assignment.ImportSessionID),"Location"=>after.Data.StoryMemoryLocations.Any(x=>x.StoryMemoryLocationID==assignment.EntityID && x.ImportSessionID==assignment.ImportSessionID),_=>after.Data.StoryMemoryAssets.Any(x=>x.StoryMemoryAssetID==assignment.EntityID && x.ImportSessionID==assignment.ImportSessionID)};
Check(exists,"Illustration assignment follows typed memory entity/pipeline identity.");
}
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.IllustrationLibraryItems WHERE SourceProjectID=@id",new{id=after.Project!.ProjectID})==0,"Copy never creates/reapproves shared catalogue rows.");
}
internal static async Task VerifyRestoreGuardsAsync(SqlConnection db,ProjectBackupExport before,string json,int project)
{
await GuardAsync(db);
var sourceLibrary=await db.ExecuteScalarAsync<string>("SELECT * FROM dbo.IllustrationLibraryItems WHERE SourceProjectID=@project ORDER BY IllustrationLibraryItemID FOR JSON PATH,INCLUDE_NULL_VALUES",new{project});
var globalDemand=await db.ExecuteScalarAsync<string>("SELECT * FROM dbo.StoryIntelligenceIllustrationDemands WHERE ProjectID IS NULL ORDER BY StoryIntelligenceIllustrationDemandID FOR JSON PATH,INCLUDE_NULL_VALUES");
foreach(var table in new[]{"StoryMemoryIllustrationAssignments","StoryMemoryIllustrationDemands","StoryIntelligenceIllustrationDemands"})
{
var old=JsonNode.Parse(json)!;old["Data"]!.AsObject().Remove(table);
try{await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=old.ToJsonString()},commandType:System.Data.CommandType.StoredProcedure);throw new InvalidOperationException("Missing illustration collection accepted: "+table);}
catch(SqlException ex) when(ex.Number==51023){}
}
var item=before.Data.StoryMemoryIllustrationAssignments.First(x=>x.InvalidatedUtc is null && x.IllustrationLibraryItemID.HasValue).IllustrationLibraryItemID!.Value;
try
{
await db.ExecuteAsync("UPDATE dbo.IllustrationLibraryItems SET Status=N'Generating' WHERE IllustrationLibraryItemID=@item",new{item});
try{await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=json},commandType:System.Data.CommandType.StoredProcedure);throw new InvalidOperationException("Active illustration generation accepted.");}
catch(SqlException ex) when(ex.Number==51024){}
}
finally{await db.ExecuteAsync("UPDATE dbo.IllustrationLibraryItems SET Status=N'Approved' WHERE IllustrationLibraryItemID=@item",new{item});}
Check(sourceLibrary==await db.ExecuteScalarAsync<string>("SELECT * FROM dbo.IllustrationLibraryItems WHERE SourceProjectID=@project ORDER BY IllustrationLibraryItemID FOR JSON PATH,INCLUDE_NULL_VALUES",new{project}),"Refused restore never mutates shared catalogue approval/provenance.");
Check(globalDemand==await db.ExecuteScalarAsync<string>("SELECT * FROM dbo.StoryIntelligenceIllustrationDemands WHERE ProjectID IS NULL ORDER BY StoryIntelligenceIllustrationDemandID FOR JSON PATH,INCLUDE_NULL_VALUES"),"Global illustration demand remains unchanged.");
Console.WriteLine("PASS illustration history: typed memory copy/remap; inactive copied assignments; no catalogue authority; three omission guards and active generation refusal.");
}
}

View File

@ -140,6 +140,10 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
data.StoryIntelligenceNarrativeCandidates = (await state.ReadAsync<ProjectBackupStoryIntelligenceNarrativeCandidates>()).ToList();
data.StoryIntelligenceNarrativeCandidateEvidence = (await state.ReadAsync<ProjectBackupStoryIntelligenceNarrativeCandidateEvidence>()).ToList();
data.StoryIntelligenceNarrativeCandidateEvents = (await state.ReadAsync<ProjectBackupStoryIntelligenceNarrativeCandidateEvents>()).ToList();
data.StoryMemoryIllustrationAssignments = (await state.ReadAsync<ProjectBackupStoryMemoryIllustrationAssignments>()).ToList();
data.StoryMemoryIllustrationDemands = (await state.ReadAsync<ProjectBackupStoryMemoryIllustrationDemands>()).ToList();
data.StoryIntelligenceIllustrationDemands = (await state.ReadAsync<ProjectBackupStoryIntelligenceIllustrationDemands>()).ToList();
@ -190,6 +194,9 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
nameof(data.StoryIntelligenceNarrativeCandidates),
nameof(data.StoryIntelligenceNarrativeCandidateEvidence),
nameof(data.StoryIntelligenceNarrativeCandidateEvents),
nameof(data.StoryMemoryIllustrationAssignments),
nameof(data.StoryMemoryIllustrationDemands),
nameof(data.StoryIntelligenceIllustrationDemands),
nameof(data.CharacterEnrichmentRuns),
nameof(data.CharacterEnrichmentEvidence),
nameof(data.StoryIntelligenceReviewCandidateGenerations),
@ -291,7 +298,7 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
nameof(data.ProjectAccess),
nameof(data.UserFiles)
],
Note = "Original database IDs are included for diagnostics. Project access records are exported for reference only; importing a project backup creates a new project owned by the importing user and does not recreate collaborators. Account onboarding and analysis consent/job records stay in their original account and are not recreated or rewound by project transfer. Existing project activity history is retained on same-project restore; copies do not recreate it."
Note = "Original database IDs are included for diagnostics. Project access records are exported for reference only; importing a project backup creates a new project owned by the importing user and does not recreate collaborators. Account onboarding and analysis consent/job records stay in their original account and are not recreated or rewound by project transfer. Existing project activity history is retained on same-project restore; copies do not recreate it. Shared illustration catalogue entries, approval/usage state and library files require a separate administrator backup and are never recreated or rewound by project transfer. Project illustration assignment/demand history is included; copied assignments become inactive and catalogue links are detached."
}
};
}

View File

@ -14,6 +14,10 @@ public sealed class ProjectBackupExport
public sealed class ProjectBackupData
{
public IReadOnlyList<ProjectBackupStoryMemoryIllustrationAssignments> StoryMemoryIllustrationAssignments { get; set; } = [];
public IReadOnlyList<ProjectBackupStoryMemoryIllustrationDemands> StoryMemoryIllustrationDemands { get; set; } = [];
public IReadOnlyList<ProjectBackupStoryIntelligenceIllustrationDemands> StoryIntelligenceIllustrationDemands { get; set; } = [];
public IReadOnlyList<ProjectBackupWholeBookPlotSynthesisRuns> WholeBookPlotSynthesisRuns { get; set; } = [];
public IReadOnlyList<ProjectBackupStoryIntelligenceNarrativeCandidates> StoryIntelligenceNarrativeCandidates { get; set; } = [];
public IReadOnlyList<ProjectBackupStoryIntelligenceNarrativeCandidateEvidence> StoryIntelligenceNarrativeCandidateEvidence { get; set; } = [];
@ -947,3 +951,61 @@ public sealed class ProjectBackupStoryIntelligenceNarrativeCandidateEvents
public DateTime CreatedUtc { get; set; }
public DateTime UpdatedUtc { get; set; }
}
public sealed class ProjectBackupStoryMemoryIllustrationAssignments
{
public int StoryMemoryIllustrationAssignmentID { get; set; }
public int ImportSessionID { get; set; }
public string EntityType { get; set; } = "";
public int EntityID { get; set; }
public int? IllustrationLibraryItemID { get; set; }
public string? StableCode { get; set; }
public string AssignmentStatus { get; set; } = "";
public bool IsFallback { get; set; }
public int MatchScore { get; set; }
public decimal Confidence { get; set; }
public string? AssignmentReason { get; set; }
public string EvidenceVersion { get; set; } = "";
public DateTime AssignedUtc { get; set; }
public DateTime LastValidatedUtc { get; set; }
public DateTime? InvalidatedUtc { get; set; }
public string? InvalidationReason { get; set; }
public DateTime CreatedUtc { get; set; }
public DateTime UpdatedUtc { get; set; }
}
public sealed class ProjectBackupStoryMemoryIllustrationDemands
{
public int StoryMemoryIllustrationDemandID { get; set; }
public int ImportSessionID { get; set; }
public int ProjectID { get; set; }
public string EntityType { get; set; } = "";
public string ArchetypeKey { get; set; } = "";
public int DemandCount { get; set; }
public int WaitingEntityCount { get; set; }
public string Status { get; set; } = "";
public int? QueuedIllustrationLibraryItemID { get; set; }
public int? GeneratedIllustrationLibraryItemID { get; set; }
public DateTime CreatedUtc { get; set; }
public DateTime UpdatedUtc { get; set; }
}
public sealed class ProjectBackupStoryIntelligenceIllustrationDemands
{
public int StoryIntelligenceIllustrationDemandID { get; set; }
public int? ProjectID { get; set; }
public string DemandKey { get; set; } = "";
public string AgeBand { get; set; } = "";
public string Presentation { get; set; } = "";
public string HairColour { get; set; } = "";
public string SkinTone { get; set; } = "";
public string? HairLength { get; set; }
public string? Glasses { get; set; }
public string? FacialHair { get; set; }
public int RequestCount { get; set; }
public DateTime LastRequestedUtc { get; set; }
public DateTime CreatedUtc { get; set; }
public DateTime UpdatedUtc { get; set; }
public DateTime? QueuedUtc { get; set; }
public string GenerationSource { get; set; } = "";
}

View File

@ -350,6 +350,8 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
validation.Warnings.Add("Word manuscript links in an imported copy must be reconnected. Saved manuscript text is retained when present in the backup.");
if (backup.Data.ThreadEvents.Any(x => x.SourceKey is not null || x.SourceReferenceID.HasValue))
validation.Warnings.Add("Copied plot event source identities are remapped. Source links absent from this backup are detached.");
if(backup.Data.StoryMemoryIllustrationAssignments.Any() || backup.Data.StoryMemoryIllustrationDemands.Any() || backup.Data.StoryIntelligenceIllustrationDemands.Any())
validation.Warnings.Add("Shared illustration catalogue entries and files are managed separately. Imported illustration assignments become inactive history and queued/generated catalogue links are detached; no artwork is approved or generation restarted. Saved stable codes and demand history are retained.");
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")))
@ -851,7 +853,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
private static readonly string[] ProjectBackupIdentityTables =
[
"ProjectTimelineSettings", "TimelineViewPresets", "SceneMetricTypes", "Books", "Chapters", "Scenes", "StoryMaps",
"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",
"StoryMemoryIllustrationAssignments", "StoryMemoryIllustrationDemands", "StoryIntelligenceIllustrationDemands", "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",
@ -1753,6 +1755,31 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
row.SourceEntityID=ExistingOrNew(ProjectBackupStoryMemory.EntityTable(row.SourceEntityType)!,row.SourceEntityID);
row.TargetEntityID=ExistingOrNew(ProjectBackupStoryMemory.EntityTable(row.TargetEntityType)!,row.TargetEntityID);
}
foreach(var row in backup.Data.StoryMemoryIllustrationAssignments)
{
row.StoryMemoryIllustrationAssignmentID=NewId("StoryMemoryIllustrationAssignments",row.StoryMemoryIllustrationAssignmentID);
row.ImportSessionID=ExistingOrNew("StoryIntelligenceBookPipelines",row.ImportSessionID);
row.EntityID=ExistingOrNew(ProjectBackupStoryMemory.EntityTable(row.EntityType)!,row.EntityID);
row.IllustrationLibraryItemID=null;
if(row.InvalidatedUtc is null)
{
row.InvalidatedUtc=DateTime.UtcNow;
row.InvalidationReason="Imported as inactive history; shared illustration catalogue links require explicit reassignment.";
}
}
foreach(var row in backup.Data.StoryMemoryIllustrationDemands)
{
row.StoryMemoryIllustrationDemandID=NewId("StoryMemoryIllustrationDemands",row.StoryMemoryIllustrationDemandID);
row.ImportSessionID=ExistingOrNew("StoryIntelligenceBookPipelines",row.ImportSessionID);
row.ProjectID=projectId;
row.QueuedIllustrationLibraryItemID=null;
row.GeneratedIllustrationLibraryItemID=null;
}
foreach(var row in backup.Data.StoryIntelligenceIllustrationDemands)
{
row.StoryIntelligenceIllustrationDemandID=NewId("StoryIntelligenceIllustrationDemands",row.StoryIntelligenceIllustrationDemandID);
row.ProjectID=projectId;
}
foreach(var row in backup.Data.StoryMemoryProcessedSceneResults)
{
row.StoryMemoryProcessedSceneResultID=NewId("StoryMemoryProcessedSceneResults",row.StoryMemoryProcessedSceneResultID);

View File

@ -8,6 +8,9 @@ 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("StoryMemoryIllustrationAssignments","StoryMemoryIllustrationAssignmentID",new Link("ImportSessionID","StoryIntelligenceBookPipelines","StoryIntelligenceBookPipelineID")),
new("StoryMemoryIllustrationDemands","StoryMemoryIllustrationDemandID",new Link("ImportSessionID","StoryIntelligenceBookPipelines","StoryIntelligenceBookPipelineID"),new Link("ProjectID","Project","ProjectID")),
new("StoryIntelligenceIllustrationDemands","StoryIntelligenceIllustrationDemandID",new Link("ProjectID","Project","ProjectID")),
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")),

View File

@ -44,6 +44,20 @@ internal static class ProjectBackupStoryMemory
["Asset"]=backup.Data.StoryMemoryAssets.Select(row=>row.StoryMemoryAssetID).ToHashSet(),
["Location"]=backup.Data.StoryMemoryLocations.Select(row=>row.StoryMemoryLocationID).ToHashSet()
};
foreach(var row in backup.Data.StoryMemoryIllustrationAssignments)
{
if(string.IsNullOrEmpty(row.EntityType) || !memory.TryGetValue(row.EntityType,out var entities) || !entities.Contains(row.EntityID))
return "Project backup illustration assignment references a missing or unsupported memory entity.";
var pipeline=row.EntityType.ToLowerInvariant() switch
{
"character" => backup.Data.StoryMemoryCharacters.Single(x=>x.StoryMemoryCharacterID==row.EntityID).ImportSessionID,
"location" => backup.Data.StoryMemoryLocations.Single(x=>x.StoryMemoryLocationID==row.EntityID).ImportSessionID,
_ => backup.Data.StoryMemoryAssets.Single(x=>x.StoryMemoryAssetID==row.EntityID).ImportSessionID
};
if(pipeline!=row.ImportSessionID)return "Project backup illustration assignment belongs to a different memory pipeline.";
}
foreach(var row in backup.Data.StoryMemoryIllustrationDemands)
if(EntityTable(row.EntityType) is null)return "Project backup illustration demand has an unsupported entity type.";
foreach(var row in backup.Data.StoryMemoryRelationships)
if(string.IsNullOrEmpty(row.SourceEntityType) || string.IsNullOrEmpty(row.TargetEntityType)
|| !memory.TryGetValue(row.SourceEntityType,out var source) || !source.Contains(row.SourceEntityID)

View File

@ -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 <= 51022 } refusal
Message = ex is Microsoft.Data.SqlClient.SqlException { Number: >= 51006 and <= 51024 } refusal
? refusal.Message + " The safety backup was retained."
: "Restore failed. The safety backup was created, and the project data was left unchanged.",
SafetyBackup = safetyBackup

View File

@ -0,0 +1,609 @@
-- Version 1.3 project-scoped illustration history; shared catalogue state is never imported or rewound.
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;
SELECT r.* FROM dbo.StoryMemoryIllustrationAssignments r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID ORDER BY r.StoryMemoryIllustrationAssignmentID;
SELECT r.* FROM dbo.StoryMemoryIllustrationDemands r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID ORDER BY r.StoryMemoryIllustrationDemandID;
SELECT * FROM dbo.StoryIntelligenceIllustrationDemands WHERE ProjectID=@ProjectID ORDER BY StoryIntelligenceIllustrationDemandID;
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'StoryMemoryIllustrationAssignments'),
(N'StoryMemoryIllustrationDemands'),
(N'StoryIntelligenceIllustrationDemands'),
(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;
IF JSON_QUERY(@JsonData,'$.Data.StoryMemoryIllustrationAssignments') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryMemoryIllustrationAssignments r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID)
THROW 51023,'This older restore point omits existing illustration assignment or demand history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.StoryMemoryIllustrationDemands') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryMemoryIllustrationDemands r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID)
THROW 51023,'This older restore point omits existing illustration assignment or demand history. Restore was aborted without changing it.',1;
IF JSON_QUERY(@JsonData,'$.Data.StoryIntelligenceIllustrationDemands') IS NULL AND EXISTS(SELECT 1 FROM dbo.StoryIntelligenceIllustrationDemands r WHERE r.ProjectID=@ProjectID)
THROW 51023,'This older restore point omits existing illustration assignment or demand history. Restore was aborted without changing it.',1;
IF EXISTS (
SELECT 1 FROM dbo.IllustrationLibraryItems i
WHERE (i.Status IN(N'Queued',N'Generating') OR i.GenerationStatus IN(N'Queued',N'Generating'))
AND (
i.SourceProjectID=@ProjectID
OR EXISTS(SELECT 1 FROM dbo.StoryMemoryIllustrationAssignments a JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=a.ImportSessionID WHERE p.ProjectID=@ProjectID AND a.IllustrationLibraryItemID=i.IllustrationLibraryItemID)
OR EXISTS(SELECT 1 FROM dbo.StoryMemoryIllustrationDemands d WHERE d.ProjectID=@ProjectID AND (d.QueuedIllustrationLibraryItemID=i.IllustrationLibraryItemID OR d.GeneratedIllustrationLibraryItemID=i.IllustrationLibraryItemID))
OR i.IllustrationLibraryItemID IN (
SELECT IllustrationLibraryItemID FROM OPENJSON(@JsonData,'$.Data.StoryMemoryIllustrationAssignments') WITH(IllustrationLibraryItemID int '$.IllustrationLibraryItemID')
UNION SELECT QueuedIllustrationLibraryItemID FROM OPENJSON(@JsonData,'$.Data.StoryMemoryIllustrationDemands') WITH(QueuedIllustrationLibraryItemID int '$.QueuedIllustrationLibraryItemID')
UNION SELECT GeneratedIllustrationLibraryItemID FROM OPENJSON(@JsonData,'$.Data.StoryMemoryIllustrationDemands') WITH(GeneratedIllustrationLibraryItemID int '$.GeneratedIllustrationLibraryItemID')
)
)
)
THROW 51024,'Illustration generation is queued or active for this project. Complete it before restoring.',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.StoryMemoryIllustrationAssignments r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID;
DELETE r FROM dbo.StoryMemoryIllustrationDemands r JOIN dbo.StoryIntelligenceBookPipelines p ON p.StoryIntelligenceBookPipelineID=r.ImportSessionID WHERE p.ProjectID=@ProjectID;
DELETE FROM dbo.StoryIntelligenceIllustrationDemands WHERE 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'StoryMemoryIllustrationAssignments',N'$.Data.StoryMemoryIllustrationAssignments',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryMemoryIllustrationDemands',N'$.Data.StoryMemoryIllustrationDemands',@JsonData,@ProjectID,0;
EXEC dbo.ProjectRestore_InsertJsonTable N'StoryIntelligenceIllustrationDemands',N'$.Data.StoryIntelligenceIllustrationDemands',@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