Preserve Core Import build provenance through project transfers

This commit is contained in:
Nick Beckley 2026-11-04 02:54:25 +00:00
parent 168ff4d8e0
commit 5c11203ddb
14 changed files with 602 additions and 14 deletions

View File

@ -62,10 +62,10 @@ NameLocales,Global/user/independent,,Reference/user/system; scope review pending
NameReferenceImports,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending
NameRelationships,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending
NameUsages,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending
OnboardingManuscriptBuildChapterMap,ProjectID or FK descendant,,Pending classification,Pending,Pending
OnboardingManuscriptBuildCharacterMap,ProjectID or FK descendant,,Pending classification,Pending,Pending
OnboardingManuscriptBuilds,ProjectID or FK descendant,,Pending classification,Pending,Pending
OnboardingManuscriptBuildSceneMap,ProjectID or FK descendant,,Pending classification,Pending,Pending
OnboardingManuscriptBuildChapterMap,ProjectID or FK descendant,OnboardingManuscriptBuildChapterMap,Persistent Core Import provenance and canonical maps; serialized and remapped,Pass: source SQL stored fields; copy refs/actor/new preview; in-place completed history; active/older restore refusal,No file bytes; copied documents remain inactive; unfinished copied operation cancelled
OnboardingManuscriptBuildCharacterMap,ProjectID or FK descendant,OnboardingManuscriptBuildCharacterMap,Persistent Core Import provenance and canonical maps; serialized and remapped,Pass: source SQL stored fields; copy refs/actor/new preview; in-place completed history; active/older restore refusal,No file bytes; copied documents remain inactive; unfinished copied operation cancelled
OnboardingManuscriptBuilds,ProjectID or FK descendant,OnboardingManuscriptBuilds,Persistent Core Import provenance and canonical maps; serialized and remapped,Pass: source SQL stored fields; copy refs/actor/new preview; in-place completed history; active/older restore refusal,No file bytes; copied documents remain inactive; unfinished copied operation cancelled
OnboardingManuscriptBuildSceneMap,ProjectID or FK descendant,OnboardingManuscriptBuildSceneMap,Persistent Core Import provenance and canonical maps; serialized and remapped,Pass: source SQL stored fields; copy refs/actor/new preview; in-place completed history; active/older restore refusal,No file bytes; copied documents remain inactive; unfinished copied operation cancelled
PlotEventTargetPlotLines,ProjectID or FK descendant,PlotEventTargetPlotLines,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
PlotEventTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending
PlotImportance,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending

1 Table ProjectOwnershipEvidence BackupCollection Classification RestoreVerified AssetsVerified
62 NameReferenceImports Global/user/independent Reference/user/system; scope review pending Pending Pending
63 NameRelationships Global/user/independent Reference/user/system; scope review pending Pending Pending
64 NameUsages Global/user/independent Reference/user/system; scope review pending Pending Pending
65 OnboardingManuscriptBuildChapterMap ProjectID or FK descendant OnboardingManuscriptBuildChapterMap Pending classification Persistent Core Import provenance and canonical maps; serialized and remapped Pending Pass: source SQL stored fields; copy refs/actor/new preview; in-place completed history; active/older restore refusal Pending No file bytes; copied documents remain inactive; unfinished copied operation cancelled
66 OnboardingManuscriptBuildCharacterMap ProjectID or FK descendant OnboardingManuscriptBuildCharacterMap Pending classification Persistent Core Import provenance and canonical maps; serialized and remapped Pending Pass: source SQL stored fields; copy refs/actor/new preview; in-place completed history; active/older restore refusal Pending No file bytes; copied documents remain inactive; unfinished copied operation cancelled
67 OnboardingManuscriptBuilds ProjectID or FK descendant OnboardingManuscriptBuilds Pending classification Persistent Core Import provenance and canonical maps; serialized and remapped Pending Pass: source SQL stored fields; copy refs/actor/new preview; in-place completed history; active/older restore refusal Pending No file bytes; copied documents remain inactive; unfinished copied operation cancelled
68 OnboardingManuscriptBuildSceneMap ProjectID or FK descendant OnboardingManuscriptBuildSceneMap Pending classification Persistent Core Import provenance and canonical maps; serialized and remapped Pending Pass: source SQL stored fields; copy refs/actor/new preview; in-place completed history; active/older restore refusal Pending No file bytes; copied documents remain inactive; unfinished copied operation cancelled
69 PlotEventTargetPlotLines ProjectID or FK descendant PlotEventTargetPlotLines 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
70 PlotEventTypes Global/user/independent Reference/user/system; scope review pending Pending Pending
71 PlotImportance Global/user/independent Reference/user/system; scope review pending Pending Pending

View File

@ -412,6 +412,33 @@ MapRelationships,MapRelationships,MeasuredDistance,decimal,True,False,True,Repre
MapRelationships,MapRelationships,Unit,nvarchar,True,False,True,Represented; projection and semantic comparison still required
MapRelationships,MapRelationships,TypicalTravelTime,nvarchar,True,False,True,Represented; projection and semantic comparison still required
MapRelationships,MapRelationships,Notes,nvarchar,True,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuildChapterMap,OnboardingManuscriptBuildChapterMap,OnboardingManuscriptBuildID,int,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuildChapterMap,OnboardingManuscriptBuildChapterMap,TemporaryChapterKey,nvarchar,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuildChapterMap,OnboardingManuscriptBuildChapterMap,ChapterID,int,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuildCharacterMap,OnboardingManuscriptBuildCharacterMap,OnboardingManuscriptBuildID,int,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuildCharacterMap,OnboardingManuscriptBuildCharacterMap,TemporaryCharacterKey,nvarchar,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuildCharacterMap,OnboardingManuscriptBuildCharacterMap,CharacterID,int,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuildCharacterMap,OnboardingManuscriptBuildCharacterMap,Created,bit,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuilds,OnboardingManuscriptBuilds,OnboardingManuscriptBuildID,int,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuilds,OnboardingManuscriptBuilds,PreviewID,uniqueidentifier,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuilds,OnboardingManuscriptBuilds,UserID,int,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuilds,OnboardingManuscriptBuilds,ProjectID,int,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuilds,OnboardingManuscriptBuilds,BookID,int,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuilds,OnboardingManuscriptBuilds,ManuscriptDocumentID,int,True,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuilds,OnboardingManuscriptBuilds,Status,nvarchar,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuilds,OnboardingManuscriptBuilds,MarkerStatus,nvarchar,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuilds,OnboardingManuscriptBuilds,ChaptersCreated,int,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuilds,OnboardingManuscriptBuilds,ScenesCreated,int,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuilds,OnboardingManuscriptBuilds,CharactersCreated,int,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuilds,OnboardingManuscriptBuilds,CharactersReused,int,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuilds,OnboardingManuscriptBuilds,SceneAppearancesCreated,int,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuilds,OnboardingManuscriptBuilds,CreatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuilds,OnboardingManuscriptBuilds,UpdatedUtc,datetime2,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuilds,OnboardingManuscriptBuilds,MarkerSyncMessage,nvarchar,True,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuilds,OnboardingManuscriptBuilds,MarkerSyncCompletedUtc,datetime2,True,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuildSceneMap,OnboardingManuscriptBuildSceneMap,OnboardingManuscriptBuildID,int,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuildSceneMap,OnboardingManuscriptBuildSceneMap,TemporarySceneKey,nvarchar,False,False,True,Represented; projection and semantic comparison still required
OnboardingManuscriptBuildSceneMap,OnboardingManuscriptBuildSceneMap,SceneID,int,False,False,True,Represented; projection and semantic comparison still required
PlotEventTargetPlotLines,PlotEventTargetPlotLines,PlotEventID,int,False,False,True,Represented; projection and semantic comparison still required
PlotEventTargetPlotLines,PlotEventTargetPlotLines,PlotLineID,int,False,False,True,Represented; projection and semantic comparison still required
PlotEventTargetPlotLines,PlotEventTargetPlotLines,CreatedDate,datetime2,False,False,True,Represented; projection and semantic comparison still required

1 Table Collection Column SqlType Nullable Computed WritableModelProperty Classification
412 MapRelationships MapRelationships Unit nvarchar True False True Represented; projection and semantic comparison still required
413 MapRelationships MapRelationships TypicalTravelTime nvarchar True False True Represented; projection and semantic comparison still required
414 MapRelationships MapRelationships Notes nvarchar True False True Represented; projection and semantic comparison still required
415 OnboardingManuscriptBuildChapterMap OnboardingManuscriptBuildChapterMap OnboardingManuscriptBuildID int False False True Represented; projection and semantic comparison still required
416 OnboardingManuscriptBuildChapterMap OnboardingManuscriptBuildChapterMap TemporaryChapterKey nvarchar False False True Represented; projection and semantic comparison still required
417 OnboardingManuscriptBuildChapterMap OnboardingManuscriptBuildChapterMap ChapterID int False False True Represented; projection and semantic comparison still required
418 OnboardingManuscriptBuildCharacterMap OnboardingManuscriptBuildCharacterMap OnboardingManuscriptBuildID int False False True Represented; projection and semantic comparison still required
419 OnboardingManuscriptBuildCharacterMap OnboardingManuscriptBuildCharacterMap TemporaryCharacterKey nvarchar False False True Represented; projection and semantic comparison still required
420 OnboardingManuscriptBuildCharacterMap OnboardingManuscriptBuildCharacterMap CharacterID int False False True Represented; projection and semantic comparison still required
421 OnboardingManuscriptBuildCharacterMap OnboardingManuscriptBuildCharacterMap Created bit False False True Represented; projection and semantic comparison still required
422 OnboardingManuscriptBuilds OnboardingManuscriptBuilds OnboardingManuscriptBuildID int False False True Represented; projection and semantic comparison still required
423 OnboardingManuscriptBuilds OnboardingManuscriptBuilds PreviewID uniqueidentifier False False True Represented; projection and semantic comparison still required
424 OnboardingManuscriptBuilds OnboardingManuscriptBuilds UserID int False False True Represented; projection and semantic comparison still required
425 OnboardingManuscriptBuilds OnboardingManuscriptBuilds ProjectID int False False True Represented; projection and semantic comparison still required
426 OnboardingManuscriptBuilds OnboardingManuscriptBuilds BookID int False False True Represented; projection and semantic comparison still required
427 OnboardingManuscriptBuilds OnboardingManuscriptBuilds ManuscriptDocumentID int True False True Represented; projection and semantic comparison still required
428 OnboardingManuscriptBuilds OnboardingManuscriptBuilds Status nvarchar False False True Represented; projection and semantic comparison still required
429 OnboardingManuscriptBuilds OnboardingManuscriptBuilds MarkerStatus nvarchar False False True Represented; projection and semantic comparison still required
430 OnboardingManuscriptBuilds OnboardingManuscriptBuilds ChaptersCreated int False False True Represented; projection and semantic comparison still required
431 OnboardingManuscriptBuilds OnboardingManuscriptBuilds ScenesCreated int False False True Represented; projection and semantic comparison still required
432 OnboardingManuscriptBuilds OnboardingManuscriptBuilds CharactersCreated int False False True Represented; projection and semantic comparison still required
433 OnboardingManuscriptBuilds OnboardingManuscriptBuilds CharactersReused int False False True Represented; projection and semantic comparison still required
434 OnboardingManuscriptBuilds OnboardingManuscriptBuilds SceneAppearancesCreated int False False True Represented; projection and semantic comparison still required
435 OnboardingManuscriptBuilds OnboardingManuscriptBuilds CreatedUtc datetime2 False False True Represented; projection and semantic comparison still required
436 OnboardingManuscriptBuilds OnboardingManuscriptBuilds UpdatedUtc datetime2 False False True Represented; projection and semantic comparison still required
437 OnboardingManuscriptBuilds OnboardingManuscriptBuilds MarkerSyncMessage nvarchar True False True Represented; projection and semantic comparison still required
438 OnboardingManuscriptBuilds OnboardingManuscriptBuilds MarkerSyncCompletedUtc datetime2 True False True Represented; projection and semantic comparison still required
439 OnboardingManuscriptBuildSceneMap OnboardingManuscriptBuildSceneMap OnboardingManuscriptBuildID int False False True Represented; projection and semantic comparison still required
440 OnboardingManuscriptBuildSceneMap OnboardingManuscriptBuildSceneMap TemporarySceneKey nvarchar False False True Represented; projection and semantic comparison still required
441 OnboardingManuscriptBuildSceneMap OnboardingManuscriptBuildSceneMap SceneID int False False True Represented; projection and semantic comparison still required
442 PlotEventTargetPlotLines PlotEventTargetPlotLines PlotEventID int False False True Represented; projection and semantic comparison still required
443 PlotEventTargetPlotLines PlotEventTargetPlotLines PlotLineID int False False True Represented; projection and semantic comparison still required
444 PlotEventTargetPlotLines PlotEventTargetPlotLines CreatedDate datetime2 False False True Represented; projection and semantic comparison still required

View File

@ -1,4 +1,8 @@
Collection,SourceRows,CopyRows,InPlaceRows,Verification
OnboardingManuscriptBuilds,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
OnboardingManuscriptBuildChapterMap,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
OnboardingManuscriptBuildSceneMap,2,2,2,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
OnboardingManuscriptBuildCharacterMap,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
CharacterImages,2,2,2,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
WordCompanionSceneAssets,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
WordCompanionSceneLocations,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present

1 Collection SourceRows CopyRows InPlaceRows Verification
2 OnboardingManuscriptBuilds 1 1 1 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
3 OnboardingManuscriptBuildChapterMap 1 1 1 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
4 OnboardingManuscriptBuildSceneMap 2 2 2 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
5 OnboardingManuscriptBuildCharacterMap 1 1 1 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
6 CharacterImages 2 2 2 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
7 WordCompanionSceneAssets 1 1 1 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
8 WordCompanionSceneLocations 1 1 1 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present

View File

@ -11,7 +11,7 @@ Project backup download/import-as-new,Export + import,PlotDirector.ProjectBackup
Saved restore point create/download/restore,Export + restore,Same versioned project backup JSON,Recover a prior state inside the same project,ProjectRestorePointService; ProjectRestoreService; ProjectRestorePointsController,Actual SQL safety/rollback; 65 populated collections; exact files; HTTP download and ownership,Same remaining persistent-table limits; older points cannot recreate files they never contained; active operations require care
Legacy structured JSON package,Import,PackageVersion 1.0 JSON,Create planning entities from explicitly structured external data,ImportsController; ImportService; ImportRepository,Real SQL: all top-level entity groups; 30 malformed shapes; order/fractional numbers; long/empty content; title/subtitle; aliases/custody/dependencies; global-state scope; sample/BOM decoding; dry-run/rollback; optional version/casing,One-way planning import; no manuscript parsing or document formatting; unknown fields and unresolved references follow explicit warnings/skipped diagnostics
Word manuscript structure API,Import + sync,Word Companion JSON structure/binding protocol,Create or sync Word-linked chapters/scenes and word counts,WordCompanionController; WordCompanionService/Repository; WordCompanion_Manuscript_Import and sync SPs,Real HTTP/controllers/access and subscription filters/services/SQL: malformed shapes/title bounds; Unicode/order/word counts; empty scene; confirmation/archive safety; repeated imports/sync; document-binding conflict rollback; synthetic entitlement decisions,Structure protocol is not DOCX file import or full prose export; desktop Word acceptance unavailable
Core Import from current Word document,Import,Chunked paragraph scan + approved structure/marker protocol,Retain source paragraphs and materialize approved canonical book structure,WordCompanionFollowHub; ManuscriptScanPreviewStore; OnboardingService and build repository,Existing 405-check parser/review/source coverage; isolated SQL workflow verification pending,External model calls and desktop marker saving must be distinguished from fixture boundaries; no paid generation in these tests
Core Import from current Word document,Import,Chunked paragraph scan + approved structure/marker protocol,Retain source paragraphs and materialize approved canonical book structure,WordCompanionFollowHub; ManuscriptScanPreviewStore; OnboardingService and build repository,Existing 405-check parser/review/source coverage; real isolated SQL build/source protocol; canonical mapping and retry; exact long Unicode/CRLF/empty text; completed provenance restore; copy ownership and inactive bindings,External model calls and desktop marker saving must be distinguished from fixture boundaries; no paid generation in these tests
Story Intelligence reviewed Characters,Import/materialize,Persisted review form/candidate protocol,Apply accepted evidence-backed decisions to canonical planning data,OnboardingController; module import/commit services and stored procedures,Existing focused harness checks; no new all-module SQL round-trip claim,Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work
Story Intelligence reviewed Locations,Import/materialize,Persisted review form/candidate protocol,Apply accepted evidence-backed decisions to canonical planning data,OnboardingController; module import/commit services and stored procedures,Existing focused harness checks; no new all-module SQL round-trip claim,Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work
Story Intelligence reviewed Assets,Import/materialize,Persisted review form/candidate protocol,Apply accepted evidence-backed decisions to canonical planning data,OnboardingController; module import/commit services and stored procedures,Existing focused harness checks; no new all-module SQL round-trip claim,Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work

1 Workflow Direction Formats IntendedPurpose Implementation Verification Limits
11 Saved restore point create/download/restore Export + restore Same versioned project backup JSON Recover a prior state inside the same project ProjectRestorePointService; ProjectRestoreService; ProjectRestorePointsController Actual SQL safety/rollback; 65 populated collections; exact files; HTTP download and ownership Same remaining persistent-table limits; older points cannot recreate files they never contained; active operations require care
12 Legacy structured JSON package Import PackageVersion 1.0 JSON Create planning entities from explicitly structured external data ImportsController; ImportService; ImportRepository Real SQL: all top-level entity groups; 30 malformed shapes; order/fractional numbers; long/empty content; title/subtitle; aliases/custody/dependencies; global-state scope; sample/BOM decoding; dry-run/rollback; optional version/casing One-way planning import; no manuscript parsing or document formatting; unknown fields and unresolved references follow explicit warnings/skipped diagnostics
13 Word manuscript structure API Import + sync Word Companion JSON structure/binding protocol Create or sync Word-linked chapters/scenes and word counts WordCompanionController; WordCompanionService/Repository; WordCompanion_Manuscript_Import and sync SPs Real HTTP/controllers/access and subscription filters/services/SQL: malformed shapes/title bounds; Unicode/order/word counts; empty scene; confirmation/archive safety; repeated imports/sync; document-binding conflict rollback; synthetic entitlement decisions Structure protocol is not DOCX file import or full prose export; desktop Word acceptance unavailable
14 Core Import from current Word document Import Chunked paragraph scan + approved structure/marker protocol Retain source paragraphs and materialize approved canonical book structure WordCompanionFollowHub; ManuscriptScanPreviewStore; OnboardingService and build repository Existing 405-check parser/review/source coverage; isolated SQL workflow verification pending Existing 405-check parser/review/source coverage; real isolated SQL build/source protocol; canonical mapping and retry; exact long Unicode/CRLF/empty text; completed provenance restore; copy ownership and inactive bindings External model calls and desktop marker saving must be distinguished from fixture boundaries; no paid generation in these tests
15 Story Intelligence reviewed Characters Import/materialize Persisted review form/candidate protocol Apply accepted evidence-backed decisions to canonical planning data OnboardingController; module import/commit services and stored procedures Existing focused harness checks; no new all-module SQL round-trip claim Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work
16 Story Intelligence reviewed Locations Import/materialize Persisted review form/candidate protocol Apply accepted evidence-backed decisions to canonical planning data OnboardingController; module import/commit services and stored procedures Existing focused harness checks; no new all-module SQL round-trip claim Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work
17 Story Intelligence reviewed Assets Import/materialize Persisted review form/candidate protocol Apply accepted evidence-backed decisions to canonical planning data OnboardingController; module import/commit services and stored procedures Existing focused harness checks; no new all-module SQL round-trip claim Review materialization is not an interchange file format; retained human decisions/provenance need separate backup work

View File

@ -16,8 +16,8 @@
2. COMPLETE: Writer/shared surface spacing, requested icon changes, Locations conventional commands/grips, mobile Chapter table repair and rendered coverage inventory (9d78a63, 016b58f, 869e305).
3. DEFERRED ACCEPTANCE: authenticated live Writer/PWA testing; no session is available. Real full-layout browser/Hub fixture results are recorded separately.
4. DEFERRED DEPLOYMENT: two illustration records were Generating at restart preflight. No interruption authorised; expanded gate b523a86 refuses restart. Recheck only at the next meaningful deployment checkpoint.
5. COMPLETE CHECKPOINT: serialized backup/restore coverage now has 69 collections (65 persistent plus 4 diagnostic/shared vocabulary), 70 SQL entities / 838 columns with no missing non-computed model properties. All 65 persistent collections have populated stored-value copy/in-place comparisons; 12 uploaded files and embedded map image bytes are verified. Commits f12ad43, dbb2e2d, 6ae3715, 571f670, 28397ff.
6. CURRENT: HTTP Import/Export transport and workflow/format inventory. Reproduced 5 MiB carried-forward JSON rejection across three POST actions; per-field limit repair under HTTP verification. Eight HTTP/SQL export packets and five formats/aliases passed; expanded legacy JSON verification passed. Next: Word manuscript/core-import SQL workflows.
5. COMPLETE CHECKPOINT: serialized backup/restore coverage now has 73 collections (69 persistent plus 4 diagnostic/shared vocabulary), 74 SQL entities / 865 columns with no missing non-computed model properties. All 69 persistent collections have populated stored-value copy/in-place comparisons; 12 uploaded files and embedded map image bytes are verified. Commits f12ad43, dbb2e2d, 6ae3715, 571f670, 28397ff.
6. CURRENT: HTTP Import/Export transport and workflow/format inventory. Reproduced 5 MiB carried-forward JSON rejection across three POST actions; per-field limit repair under HTTP verification. Eight HTTP/SQL export packets and five formats/aliases passed; expanded legacy JSON verification passed. Word structure API and Core Import SQL/source/provenance workflows now pass; next: remaining persistent project review data.
7. PENDING: remaining persistent table classification and historical fixture discovery. Unrepresented SI review/audit/provenance is persistent under its runtime contract, not an expendable cache; project-derived illustration catalogue/files also remain outside verified backup coverage. Do not claim a complete 167-table audit.
8. PENDING: finish independently safe data gaps and meaningful format round trips; record concrete limits/deferred work. No historical compatibility claim without actual fixtures.
9. PENDING: final serial build/harness and focused browser/integration checks; meaningful restart-gate recheck, safe Development deployment if idle, concise handover.
@ -218,3 +218,11 @@ Replacement confirmation returned HTTP 500 because the procedure deliberately re
Expanded HTTP/SQL verification passed valid Unicode/order/word counts including an empty scene, canonical document links, read-back, unconfirmed replacement protection, preservation of archived planning records on confirmed replacement, repeated import/sync without duplicate identities, and real binding-conflict rollback. The fixture runs actual controllers/access/subscription filters/services/repositories/SQL, with synthetic identity and entitlement decisions and unused external-service boundaries; no application workers, paid providers, or desktop Word run. Final denied-entitlement case and broad harness are being completed before commit. Evidence: `/tmp/plotdirector-phase2-word-transfer-before.log`, `...-word-transfer-sql-repair.log`, `...-word-transfer-conflict-before.log`, `...-word-transfer-after.log`. Development remains unchanged.
Word structure checkpoint verified: final HTTP/SQL run passed, including a denied fixture entitlement returning 403 without changing the book, other-author/anonymous rejection, repeated sync retaining scene IDs and updated word counts, and confirmed replacement preserving the original archived planning text. The complete 405-check harness passed (exit 0) at `/tmp/plotdirector-phase2-tests-word-transfer.log`; solution build zero warnings/errors. Migration 219 only applied in the synthetic database. Desktop Word and full prose/Core Import remain distinct next work, and no Development deployment has occurred.
## Core Import source and build provenance — 4 November
Real isolated SQL Core Import builds now cover two chapters/three scenes, canonical identity maps, an existing and a new character, preview retry idempotence, author isolation, exact long Unicode/CRLF and empty manuscript text, structural paragraph coordinates and completed marker history. Desktop Word, model calls and full service orchestration are separate boundaries; no paid provider was invoked.
Reproduced same-project restore failure against retained Core Import build-map foreign keys. Migration 220 and backup models now carry all four build/map sets, retain completed history in place, remap canonical IDs/ownership on copy and assign new preview identities. Copies never activate Word bindings; unfinished operations become cancelled history with a preview warning. Older snapshots missing existing build history and restores during unfinished marker operations are refused before mutation.
Combined matrix passed: 73 serialized data collections, all 69 persistent collections populated; SQL projection 1,051 values across 72 populated entities; copy 1,011 values; in-place 1,015 values. Schema census: 74 entities / 865 columns / zero missing non-computed model properties. Evidence: `/tmp/plotdirector-phase2-core-transfer-before.log`, `core-transfer-after.log`, `transfer-core-matrix.log`, `core-guards.log` (all prefixed `/tmp/plotdirector-phase2-`). Solution build zero warnings/errors; full 405-check harness passed before the added refusal guards. Development unchanged; migration 220 applied only to the isolated synthetic database.

View File

@ -0,0 +1,90 @@
using System.Reflection;
using System.Text.Json;
using Dapper;
using Microsoft.Extensions.Logging.Abstractions;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
internal static class CoreImportDatabaseTests
{
private static void Check(bool condition,string message){if(!condition)throw new InvalidOperationException(message);}
private static T Proxy<T>(Func<string,object?[]?,object?> handler) where T:class {var proxy=DispatchProxy.Create<T,StoryPointProxy>();((StoryPointProxy)(object)proxy).Handler=handler;return proxy;}
public static async Task RunAsync(ISqlConnectionFactory factory,IProjectBackupFiles files,int owner,int other,int project)
{
using var db=factory.CreateConnection();
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,"Core fixtures require the verified synthetic database.");
await db.ExecuteAsync("IF NOT EXISTS(SELECT 1 FROM dbo.RevisionStatuses WHERE StatusName=N'Planned') INSERT dbo.RevisionStatuses(StatusName,SortOrder) VALUES(N'Planned',0);");
var book=await db.QuerySingleAsync<int>("dbo.Book_Save",new{BookID=0,ProjectID=project,BookTitle="Core source text Ω",BookNumber=20,UsesExplicitScenes=true},commandType:System.Data.CommandType.StoredProcedure);
var existingCharacter=await db.ExecuteScalarAsync<int>("SELECT TOP(1) CharacterID FROM dbo.Characters WHERE ProjectID=@project ORDER BY CharacterID",new{project});
var source=string.Concat(Enumerable.Repeat("“Hello”—雪 café 🖋. Dialogue and plain source text.\r\n\r\n",10000));
var sourceWords=source.Split((char[]?)null,StringSplitOptions.RemoveEmptyEntries).Length;
var request=new OnboardingManuscriptBuildRequest {
PreviewID=Guid.NewGuid(),ProjectID=project,BookID=book,DocumentGuid=Guid.NewGuid(),
Chapters=[new(){TemporaryChapterKey="chapter-2",Title="Second core chapter 雨",SortOrder=2,WordCount=0},new(){TemporaryChapterKey="chapter-1",Title="First core chapter Ω",SortOrder=1,WordCount=sourceWords}],
Scenes=[new(){TemporarySceneKey="scene-2",TemporaryChapterKey="chapter-1",Title="Second core scene 雪",SortOrder=2,WordCount=0},new(){TemporarySceneKey="scene-1",TemporaryChapterKey="chapter-1",Title="First core scene Ω",SortOrder=1,WordCount=sourceWords},new(){TemporarySceneKey="scene-3",TemporaryChapterKey="chapter-2",Title="Empty core scene café",SortOrder=1,WordCount=0}],
Characters=[new(){TemporaryCharacterKey="known",Name="Existing synthetic narrator",ExistingCharacterID=existingCharacter},new(){TemporaryCharacterKey="new",Name="New core character 雨"}]
};
var builds=new OnboardingBuildRepository(factory);
Check(await builds.BuildAsync(other,request) is null,"Another author cannot build into this project.");
var result=await builds.BuildAsync(owner,request) ?? throw new InvalidOperationException("Core materialization returned no result.");
Check(result.ChapterMappings.Count==2 && result.SceneMappings.Count==3 && result.CharacterMappings.Count==2,"Core materialization returns every canonical mapping.");
var again=(await builds.BuildAsync(owner,request))!;
Check(again.AlreadyBuilt && again.BuildID==result.BuildID && again.SceneMappings.Select(item=>item.SceneID).SequenceEqual(result.SceneMappings.Select(item=>item.SceneID)),"Repeated preview build is idempotent and preserves scene identities.");
Check(await builds.GetByPreviewAsync(other,request.PreviewID) is null,"Build provenance does not cross authors.");
var chapter=result.ChapterMappings.Single(item=>item.TemporaryChapterKey=="chapter-1").ChapterID;
var first=result.SceneMappings.Single(item=>item.TemporarySceneKey=="scene-1").SceneID;
var second=result.SceneMappings.Single(item=>item.TemporarySceneKey=="scene-2").SceneID;
var third=result.SceneMappings.Single(item=>item.TemporarySceneKey=="scene-3").SceneID;
var secondChapter=result.ChapterMappings.Single(item=>item.TemporaryChapterKey=="chapter-2").ChapterID;
const string paragraphMap="[{\"paragraphIndex\":0,\"start\":0,\"length\":50},{\"paragraphIndex\":1,\"start\":50,\"length\":0}]";
await builds.SaveStructuralChapterSourceAsync(new(){ProjectID=project,BookID=book,ChapterID=chapter,SourceText=source,SourceWordCount=sourceWords,SourceCharacterCount=source.Length,ParagraphMapJson=paragraphMap,StructuralParsedJson="{\"summary\":\"Structural intent Ω\"}",DefaultPovName="New core character 雨",ExplicitNarratorName="New core character 雨"});
await builds.SaveSceneManuscriptSourceAsync(new(){ProjectID=project,BookID=book,ChapterID=chapter,SceneID=first,SourceText=source,SourceWordCount=sourceWords,SourceCharacterCount=source.Length,SourceStartParagraph=1,SourceEndParagraph=20000,WordStartParagraphIndex=0,WordEndParagraphIndex=19999});
await builds.SaveSceneManuscriptSourceAsync(new(){ProjectID=project,BookID=book,ChapterID=chapter,SceneID=second,SourceText="",SourceWordCount=0,SourceCharacterCount=0,SourceStartParagraph=20001,SourceEndParagraph=20001,WordStartParagraphIndex=20000,WordEndParagraphIndex=20000});
await builds.SaveSceneManuscriptSourceAsync(new(){ProjectID=project,BookID=book,ChapterID=secondChapter,SceneID=third,SourceText="Empty chapter source 雨",SourceWordCount=4,SourceCharacterCount=22,SourceStartParagraph=1,SourceEndParagraph=1,WordStartParagraphIndex=20001,WordEndParagraphIndex=20001});
var saved=await builds.ListSceneManuscriptSourcesByBookAsync(book);
Check(saved.Count==3 && saved.Single(item=>item.SceneID==first).SourceText==source && saved.Single(item=>item.SceneID==second).SourceText=="","Core source persistence retains exact long Unicode/CRLF and empty text.");
await builds.MarkMarkerSyncCompletedAsync(result.BuildID,"UserConfirmedSave","Synthetic marker completion; no desktop Word used.");
var current=Proxy<ICurrentUserService>((name,args)=>name switch {"get_UserId"=>(int?)owner,"get_IsAuthenticated"=>true,_=>null});
var activity=Proxy<IProjectActivityService>((name,args)=>name=="RecordAsync"?Task.CompletedTask:throw new NotSupportedException(name));
var backups=new ProjectBackupRepository(factory);var export=new ProjectExportService(backups,activity,current,NullLogger<ProjectExportService>.Instance,files);
var points=new ProjectRestorePointRepository(factory);var pointService=new ProjectRestorePointService(new ProjectRepository(factory),export,points,NullLogger<ProjectRestorePointService>.Instance);
var point=(await pointService.CreateManualAsync(project,"Core source baseline","Synthetic core workflow"))!;
await db.ExecuteAsync("UPDATE dbo.SceneManuscriptSources SET SourceText=N'Changed synthetic source' WHERE SceneID=@first",new{first});
var restore=new ProjectRestoreService(points,pointService,NullLogger<ProjectRestoreService>.Instance,files);
var restored=await restore.RestoreAsync(project,point.ProjectRestorePointID);
Check(restored.Succeeded,"A project with completed Core Import provenance must restore, not fail against retained build-map foreign keys.");
Check((await builds.ListSceneManuscriptSourcesByBookAsync(book)).Single(item=>item.SceneID==first).SourceText==source,"Same-project restore recovers long manuscript source text.");
Check((await builds.GetByPreviewAsync(owner,request.PreviewID))?.BuildID==result.BuildID,"Same-project restore preserves completed build provenance.");
var portable=(await backups.GetProjectBackupAsync(project,owner))!;await files.CaptureAsync(portable);
var coreBuild=portable.Data.OnboardingManuscriptBuilds.Single(build=>build.PreviewID==request.PreviewID);
Check(coreBuild.MarkerStatus=="UserConfirmedSave" && portable.Data.OnboardingManuscriptBuildSceneMap.Count(map=>map.OnboardingManuscriptBuildID==coreBuild.OnboardingManuscriptBuildID)==3,"Backup includes completed build state and all scene mappings.");
async Task ExpectRestoreRefusal(string json,int number)
{
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=json},commandType:System.Data.CommandType.StoredProcedure);throw new InvalidOperationException("Unsafe restore unexpectedly succeeded."); }
catch(Microsoft.Data.SqlClient.SqlException ex) when(ex.Number==number) { }
Check((await builds.ListSceneManuscriptSourcesByBookAsync(book)).Single(item=>item.SceneID==first).SourceText==source,"Refused restore must retain source text.");
}
var oldShape=System.Text.Json.Nodes.JsonNode.Parse(JsonSerializer.Serialize(portable))!;
oldShape["Data"]!.AsObject().Remove("OnboardingManuscriptBuilds");
await ExpectRestoreRefusal(oldShape.ToJsonString(),51007);
await db.ExecuteAsync("UPDATE dbo.OnboardingManuscriptBuilds SET MarkerStatus=N'Pending' WHERE OnboardingManuscriptBuildID=@id",new{id=result.BuildID});
await ExpectRestoreRefusal(JsonSerializer.Serialize(portable),51008);
await builds.MarkMarkerSyncCompletedAsync(result.BuildID,"UserConfirmedSave","Synthetic marker completion after refusal test.");
coreBuild.MarkerStatus="Pending"; // Deliberately import an unfinished snapshot; the original DB remains completed.
var importing=Proxy<ICurrentUserService>((name,args)=>name switch {"get_UserId"=>(int?)other,"get_IsAuthenticated"=>true,_=>null});
var subscription=Proxy<ISubscriptionService>((name,args)=>name switch {"CanUseResourcesAsync"=>Task.FromResult(new EntitlementDecision{Allowed=true}),"ReserveBookSlotsAsync"=>Task.FromResult(new BookSlotReservation{Allowed=true}),"CanUploadFileAsync"=>Task.FromResult(StorageLimitResult.AllowedResult(0,long.MaxValue)),_=>throw new NotSupportedException(name)});
var importer=new ImportService(new ImportRepository(factory),importing,subscription,NullLogger<ImportService>.Instance,files);
var imported=await importer.ImportAsync(new(){JsonText=JsonSerializer.Serialize(portable),ConfirmImport=true,AcknowledgeWarnings=true,AllowDuplicateProjectTitle=true});
Check(imported.Succeeded,"Copy of Core Import provenance must import: "+imported.TechnicalDetail);
var copied=(await backups.GetProjectBackupAsync(imported.ProjectID!.Value,other))!;
var copiedBook=copied.Data.Books.Single(item=>item.BookTitle=="Core source text Ω");
var copiedBuild=copied.Data.OnboardingManuscriptBuilds.Single(item=>item.BookID==copiedBook.BookID);
Check(copiedBuild.PreviewID!=request.PreviewID && copiedBuild.UserID==other && copiedBuild.Status=="Cancelled" && copiedBuild.MarkerStatus=="Cancelled","Copied workflow has a new preview/actor and unfinished operations become cancelled history.");
var copiedScene=copied.Data.Scenes.Single(item=>item.SceneTitle=="First core scene Ω");
Check(copied.Data.OnboardingManuscriptBuildSceneMap.Any(map=>map.OnboardingManuscriptBuildID==copiedBuild.OnboardingManuscriptBuildID&&map.SceneID==copiedScene.SceneID) && copied.Data.SceneManuscriptSources.Single(item=>item.SceneID==copiedScene.SceneID).SourceText==source,"Copied canonical mappings and exact manuscript text retained.");
Check(copied.Data.ManuscriptDocuments.Single(item=>item.BookID==copiedBook.BookID).IsActive==false,"Copied Core Import cannot activate the original Word binding.");
Check((await builds.GetByPreviewAsync(owner,request.PreviewID))?.MarkerStatus=="UserConfirmedSave","Copy did not alter the original completed marker history.");
Console.WriteLine("PASS Core Import SQL build/source protocol: canonical mapping, preview retry, author isolation, long Unicode/CRLF/empty source persistence and completed provenance restore. Parser, model calls and desktop marker sync are separate boundaries.");
}
}

View File

@ -88,3 +88,11 @@ UPDATE dbo.Locations SET DetectionPriority=7,ExcludeFromCompanionDetection=1 WHE
UPDATE dbo.ThreadEvents SET Source=N'Manual',SourceKey=CONCAT(N'synthetic-event-source-key-',@project),Confidence=.85 WHERE ThreadEventID=@threadEvent;
INSERT dbo.WordCompanionSceneAssets(SceneID,StoryAssetID) VALUES(@scene,@asset);
INSERT dbo.WordCompanionSceneLocations(SceneID,LocationID) VALUES(@scene,@otherLocation);
DECLARE @completedBuild int;
INSERT dbo.OnboardingManuscriptBuilds(PreviewID,UserID,ProjectID,BookID,ManuscriptDocumentID,Status,MarkerStatus,ChaptersCreated,ScenesCreated,CharactersCreated,MarkerSyncMessage,MarkerSyncCompletedUtc)
SELECT NEWID(),@user,@project,@book,ManuscriptDocumentID,N'Built',N'UserConfirmedSave',1,2,1,N'Synthetic completed marker history',SYSUTCDATETIME() FROM dbo.Scenes WHERE SceneID=@scene;
SET @completedBuild=SCOPE_IDENTITY();
INSERT dbo.OnboardingManuscriptBuildChapterMap(OnboardingManuscriptBuildID,TemporaryChapterKey,ChapterID) VALUES(@completedBuild,N'fixture-chapter-Ω',@chapter);
INSERT dbo.OnboardingManuscriptBuildSceneMap(OnboardingManuscriptBuildID,TemporarySceneKey,SceneID) VALUES(@completedBuild,N'fixture-scene-雨',@scene),(@completedBuild,N'fixture-scene-雪',@secondScene);
INSERT dbo.OnboardingManuscriptBuildCharacterMap(OnboardingManuscriptBuildID,TemporaryCharacterKey,CharacterID,Created) VALUES(@completedBuild,N'fixture-narrator-Ω',@character,1);

View File

@ -73,7 +73,7 @@ if (args.Contains("--maps-story-dev-fixture"))
if(args.Contains("--project-transfer-database"))
{
try { await ProjectTransferDatabaseTests.RunAsync(args.Last(), args.Contains("--apply-required-migrations"), args.Contains("--require-writing-plans"), args.Contains("--schema-coverage-only"), args.Contains("--exports-only"), args.Contains("--legacy-import-only"), args.Contains("--word-transfer-only")); }
try { await ProjectTransferDatabaseTests.RunAsync(args.Last(), args.Contains("--apply-required-migrations"), args.Contains("--require-writing-plans"), args.Contains("--schema-coverage-only"), args.Contains("--exports-only"), args.Contains("--legacy-import-only"), args.Contains("--word-transfer-only"), args.Contains("--core-import-only")); }
catch(Exception error) { Console.Error.WriteLine(error.Message); Environment.ExitCode=1; }
return;
}

View File

@ -18,7 +18,7 @@ internal static class ProjectTransferDatabaseTests
static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); }
static T Proxy<T>(Func<string, object?[]?, object?> handler) where T : class
{ var proxy=DispatchProxy.Create<T,StoryPointProxy>();((StoryPointProxy)(object)proxy).Handler=handler;return proxy; }
public static async Task RunAsync(string target, bool applyMigrations = false, bool requireWritingPlans = false, bool schemaCoverageOnly = false, bool exportsOnly = false, bool legacyOnly = false, bool wordOnly = false)
public static async Task RunAsync(string target, bool applyMigrations = false, bool requireWritingPlans = false, bool schemaCoverageOnly = false, bool exportsOnly = false, bool legacyOnly = false, bool wordOnly = false, bool coreOnly = false)
{
Check(target==Database,"An explicitly named Phase 2 synthetic database is required.");
var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true,RedirectStandardError=true};
@ -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"})
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"})
foreach(var batch in System.Text.RegularExpressions.Regex.Split(await File.ReadAllTextAsync(file), @"^\s*GO\s*$", System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.IgnoreCase))
if(!string.IsNullOrWhiteSpace(batch)) await db.ExecuteAsync(batch,commandTimeout:180);
Console.WriteLine("Applied required migrations to the verified synthetic database only.");
@ -128,7 +128,7 @@ internal static class ProjectTransferDatabaseTests
var plan=await db.ExecuteScalarAsync<int>("INSERT dbo.WritingPlans(UserID,ProjectID,BookID,PlanName,GoalType,StartDate,DeadlineDate,AvailableDaysJson,SessionLengthMinutes) VALUES(@user,@project,@book,N'Synthetic drafting plan',N'Draft','2026-11-01','2026-12-01',N'[1,3,5]',45);SELECT CONVERT(int,SCOPE_IDENTITY());",new{user,project,book});
await db.ExecuteAsync("INSERT dbo.WritingScheduleItems(WritingPlanID,SceneID,ScheduledDate,TaskType,ScheduleStatus,Notes) VALUES(@plan,@scene,'2026-11-03',N'Draft',N'Pending',N'Synthetic task café');",new{plan,scene});
await db.ExecuteAsync("UPDATE dbo.Books SET CreatedByUserID=@user,ModifiedByUserID=@user,CreatedDateUTC='2026-09-01',ModifiedDateUTC='2026-10-01' WHERE BookID=@book;UPDATE dbo.Scenes SET CreatedByUserID=@user,ModifiedByUserID=@user,CreatedDateUTC='2026-09-01',ModifiedDateUTC='2026-10-01' WHERE SceneID=@scene;",new{user,book,scene});
var planningParameters=new DynamicParameters(new{project,book,chapter,scene,revision,timeMode,confidence,location,asset,kind,character,line,thread,threadEvent,map}){RemoveUnused=false};
var planningParameters=new DynamicParameters(new{project,book,chapter,scene,revision,timeMode,confidence,location,asset,kind,character,line,thread,threadEvent,map,user}){RemoveUnused=false};
await db.ExecuteAsync(await File.ReadAllTextAsync("PlotLine.Tests/Fixtures/ProjectTransferPlanning.sql"),planningParameters);
async Task<string> SaveFile(string folder,string name,byte[] bytes)
{
@ -158,6 +158,11 @@ internal static class ProjectTransferDatabaseTests
await assetFiles.CaptureAsync(before);Check(before.Project is not null,"Fixture project exported.");
await VerifyStoredProjectionAsync(db,before);
Check(before.Data.Books.Single().BookTitle=="Book Ω" && before.Data.Scenes.Single(x=>x.SceneTitle=="Scene café").Summary=="“Hello”—雪 🖋","Core Unicode export content.");
if(coreOnly)
{
await CoreImportDatabaseTests.RunAsync(factory,assetFiles,user,importingUser,project);
return;
}
if(wordOnly)
{
await WordTransferDatabaseTests.RunAsync(factory,user,importingUser,project);
@ -340,7 +345,7 @@ internal static class ProjectTransferDatabaseTests
coverage.Add($"{property.Name},{Count(before)},{Count(after)},{Count(sameProject)},{(diagnostic?"Diagnostic/shared vocabulary; excluded from portable restoration comparison":"Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present")}");
}
await File.WriteAllLinesAsync("Docs/Sprints/2026-11-03-phase2-roundtrip-coverage.csv",coverage);
Console.WriteLine("PASS 65 populated persistent collections: copy/in-place stored values and actual safety/rollback; unrepresented project tables remain pending.");
Console.WriteLine("PASS 69 populated persistent collections: copy/in-place stored values and actual safety/rollback; unrepresented project tables remain pending.");
}
private static async Task VerifyStoredRoundTripAsync(SqlConnection db, ProjectBackupExport original, ProjectBackupExport restored, int? importingUser)
{
@ -380,10 +385,11 @@ internal static class ProjectTransferDatabaseTests
if(collection.Name=="StoryMaps" && column=="Revision")continue; // Restore increments the optimistic concurrency token.
if(importingUser.HasValue)
{
if(collection.Name=="OnboardingManuscriptBuilds" && column=="PreviewID") {Check(!Equals(expected,actual),"Copied build preview identity must change");continue;}
if(collection.Name=="ManuscriptDocuments" && column=="DocumentGuid") {Check(!Equals(expected,actual),"Copy document GUID must change");continue;}
if(collection.Name=="ManuscriptDocuments" && column=="IsActive" || collection.Name is "Scenes" or "Chapters" && column=="IsLinkedToManuscript")expected=false;
if(collection.Name is "Scenes" or "Chapters" && column=="LinkedUtc" || collection.Name=="Scenes" && column=="ImportRunID")expected=null;
if(column is "CreatedByUserID" or "ModifiedByUserID" or "AcknowledgedByUserID" || collection.Name=="WritingPlans" && column=="UserID")expected=importingUser.Value;
if(column is "CreatedByUserID" or "ModifiedByUserID" or "AcknowledgedByUserID" || collection.Name is "WritingPlans" or "OnboardingManuscriptBuilds" && column=="UserID")expected=importingUser.Value;
if(collection.Name=="ThreadEvents" && column=="SourceKey" && expected is not null)expected=$"backup:{restored.Project.ProjectID}:{Read(collection.After[index],"ThreadEventID")}";
if(collection.Name=="ThreadEvents" && column=="SourceReferenceID")expected=null;
if(collection.Name=="StoryMaps" && column=="ReferenceJson")continue; // Exact placement/image identity asserted separately.

View File

@ -105,6 +105,11 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
data.WordCompanionSceneAssets = (await state.ReadAsync<ProjectBackupCompanionSceneAsset>()).ToList();
data.WordCompanionSceneLocations = (await state.ReadAsync<ProjectBackupCompanionSceneLocation>()).ToList();
data.CharacterImages = (await state.ReadAsync<CharacterImage>()).ToList();
data.OnboardingManuscriptBuilds = (await state.ReadAsync<ProjectBackupOnboardingManuscriptBuilds>()).ToList();
data.OnboardingManuscriptBuildChapterMap = (await state.ReadAsync<ProjectBackupOnboardingManuscriptBuildChapterMap>()).ToList();
data.OnboardingManuscriptBuildSceneMap = (await state.ReadAsync<ProjectBackupOnboardingManuscriptBuildSceneMap>()).ToList();
data.OnboardingManuscriptBuildCharacterMap = (await state.ReadAsync<ProjectBackupOnboardingManuscriptBuildCharacterMap>()).ToList();
}
var bookMetadata = (await connection.QueryAsync<Book>(
@ -143,6 +148,10 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
ProjectId = projectId,
IncludedEntitySets =
[
nameof(data.OnboardingManuscriptBuilds),
nameof(data.OnboardingManuscriptBuildChapterMap),
nameof(data.OnboardingManuscriptBuildSceneMap),
nameof(data.OnboardingManuscriptBuildCharacterMap),
nameof(data.CharacterImages),
nameof(data.WordCompanionSceneAssets),
nameof(data.WordCompanionSceneLocations),

View File

@ -14,6 +14,11 @@ public sealed class ProjectBackupExport
public sealed class ProjectBackupData
{
public IReadOnlyList<ProjectBackupOnboardingManuscriptBuilds> OnboardingManuscriptBuilds { get; set; } = [];
public IReadOnlyList<ProjectBackupOnboardingManuscriptBuildChapterMap> OnboardingManuscriptBuildChapterMap { get; set; } = [];
public IReadOnlyList<ProjectBackupOnboardingManuscriptBuildSceneMap> OnboardingManuscriptBuildSceneMap { get; set; } = [];
public IReadOnlyList<ProjectBackupOnboardingManuscriptBuildCharacterMap> OnboardingManuscriptBuildCharacterMap { get; set; } = [];
public IReadOnlyList<CharacterImage> CharacterImages { get; set; } = [];
public IReadOnlyList<ProjectBackupCompanionSceneAsset> WordCompanionSceneAssets { get; set; } = [];
public IReadOnlyList<ProjectBackupCompanionSceneLocation> WordCompanionSceneLocations { get; set; } = [];
@ -261,3 +266,46 @@ public sealed class ProjectBackupFile
public string? EntityType { get; set; }
public int EntityID { get; set; }
}
public sealed class ProjectBackupOnboardingManuscriptBuilds
{
public int OnboardingManuscriptBuildID { get; set; }
public Guid PreviewID { get; set; }
public int UserID { get; set; }
public int ProjectID { get; set; }
public int BookID { get; set; }
public int? ManuscriptDocumentID { get; set; }
public string Status { get; set; } = string.Empty;
public string MarkerStatus { get; set; } = string.Empty;
public int ChaptersCreated { get; set; }
public int ScenesCreated { get; set; }
public int CharactersCreated { get; set; }
public int CharactersReused { get; set; }
public int SceneAppearancesCreated { get; set; }
public DateTime CreatedUtc { get; set; }
public DateTime UpdatedUtc { get; set; }
public string? MarkerSyncMessage { get; set; }
public DateTime? MarkerSyncCompletedUtc { get; set; }
}
public sealed class ProjectBackupOnboardingManuscriptBuildChapterMap
{
public int OnboardingManuscriptBuildID { get; set; }
public string TemporaryChapterKey { get; set; } = string.Empty;
public int ChapterID { get; set; }
}
public sealed class ProjectBackupOnboardingManuscriptBuildSceneMap
{
public int OnboardingManuscriptBuildID { get; set; }
public string TemporarySceneKey { get; set; } = string.Empty;
public int SceneID { get; set; }
}
public sealed class ProjectBackupOnboardingManuscriptBuildCharacterMap
{
public int OnboardingManuscriptBuildID { get; set; }
public string TemporaryCharacterKey { get; set; } = string.Empty;
public int CharacterID { get; set; }
public bool Created { get; set; }
}

View File

@ -350,6 +350,8 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
validation.Warnings.Add("Word manuscript links in an imported copy must be reconnected. Saved manuscript text is retained when present in the backup.");
if (backup.Data.ThreadEvents.Any(x => x.SourceKey is not null || x.SourceReferenceID.HasValue))
validation.Warnings.Add("Copied plot events receive new source identities and are detached from the original analysis review records.");
if(backup.Data.OnboardingManuscriptBuilds.Any(build=>build.Status is not ("Built" or "Complete" or "Completed" or "Failed" or "Cancelled") || build.Status=="Built" && build.MarkerStatus is not ("UserConfirmedSave" or "Completed" or "Complete")))
validation.Warnings.Add("Unfinished Word import operations will be copied as cancelled history. They will not restart or send markers to the original document.");
if (backup.FormatVersion != "1.3" && ProjectBackupFiles.HasUploads(backup))
validation.Warnings.Add("This older backup does not contain uploaded file bytes. Imported copies retain text and link metadata, but uploaded images, covers and attachments must be added again.");
if (duplicate)
@ -837,7 +839,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
private static readonly string[] ProjectBackupIdentityTables =
[
"ProjectTimelineSettings", "TimelineViewPresets", "SceneMetricTypes", "Books", "Chapters", "Scenes", "StoryMaps",
"CharacterImages", "WordCompanionSceneAssets", "WordCompanionSceneLocations", "ManuscriptDocuments", "WritingPlans", "WritingScheduleItems", "CharacterAliases", "AssetAliases", "LocationAliases", "AuthorPlotSeeds", "ContinuityWarningAcknowledgements",
"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",
@ -1522,6 +1524,37 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
note.FromSceneID = ExistingOrNew("Scenes", note.FromSceneID);
note.ToSceneID = ExistingOrNew("Scenes", note.ToSceneID);
}
foreach(var build in backup.Data.OnboardingManuscriptBuilds)
{
build.OnboardingManuscriptBuildID=NewId("OnboardingManuscriptBuilds",build.OnboardingManuscriptBuildID);
build.PreviewID=Guid.NewGuid();
if(build.Status is not ("Built" or "Complete" or "Completed" or "Failed" or "Cancelled")
|| build.Status=="Built" && build.MarkerStatus is not ("UserConfirmedSave" or "Completed" or "Complete"))
{
build.Status="Cancelled";
build.MarkerStatus="Cancelled";
build.MarkerSyncMessage="Imported as historical provenance. The original Word operation was not resumed.";
}
build.UserID=importingUserId;
build.ProjectID=projectId;
build.BookID=ExistingOrNew("Books",build.BookID);
build.ManuscriptDocumentID=ExistingOrNewNullable("ManuscriptDocuments",build.ManuscriptDocumentID);
}
foreach(var map in backup.Data.OnboardingManuscriptBuildChapterMap)
{
map.OnboardingManuscriptBuildID=ExistingOrNew("OnboardingManuscriptBuilds",map.OnboardingManuscriptBuildID);
map.ChapterID=ExistingOrNew("Chapters",map.ChapterID);
}
foreach(var map in backup.Data.OnboardingManuscriptBuildSceneMap)
{
map.OnboardingManuscriptBuildID=ExistingOrNew("OnboardingManuscriptBuilds",map.OnboardingManuscriptBuildID);
map.SceneID=ExistingOrNew("Scenes",map.SceneID);
}
foreach(var map in backup.Data.OnboardingManuscriptBuildCharacterMap)
{
map.OnboardingManuscriptBuildID=ExistingOrNew("OnboardingManuscriptBuilds",map.OnboardingManuscriptBuildID);
map.CharacterID=ExistingOrNew("Characters",map.CharacterID);
}
foreach (var image in backup.Data.CharacterImages)
{
image.CharacterImageID=NewId("CharacterImages",image.CharacterImageID);

View File

@ -8,6 +8,10 @@ internal static class ProjectBackupGraphValidation
private sealed record Link(string Column, string TargetCollection, string TargetColumn);
private sealed record Entity(string Collection, string? Identity, params Link[] Links);
private static readonly Entity[] Entities = [
new("OnboardingManuscriptBuilds","OnboardingManuscriptBuildID",new Link("ProjectID","Project","ProjectID"),new Link("BookID","Books","BookID"),new Link("ManuscriptDocumentID","ManuscriptDocuments","ManuscriptDocumentID")),
new("OnboardingManuscriptBuildChapterMap",null,new Link("OnboardingManuscriptBuildID","OnboardingManuscriptBuilds","OnboardingManuscriptBuildID"),new Link("ChapterID","Chapters","ChapterID")),
new("OnboardingManuscriptBuildSceneMap",null,new Link("OnboardingManuscriptBuildID","OnboardingManuscriptBuilds","OnboardingManuscriptBuildID"),new Link("SceneID","Scenes","SceneID")),
new("OnboardingManuscriptBuildCharacterMap",null,new Link("OnboardingManuscriptBuildID","OnboardingManuscriptBuilds","OnboardingManuscriptBuildID"),new Link("CharacterID","Characters","CharacterID")),
new("CharacterImages","CharacterImageID",new Link("CharacterID","Characters","CharacterID"),new Link("ProjectID","Project","ProjectID")),
new("WordCompanionSceneAssets","WordCompanionSceneAssetID",new Link("SceneID","Scenes","SceneID"),new Link("StoryAssetID","StoryAssets","StoryAssetID")),
new("WordCompanionSceneLocations","WordCompanionSceneLocationID",new Link("SceneID","Scenes","SceneID"),new Link("LocationID","Locations","LocationID")),

View File

@ -0,0 +1,351 @@
-- Version 1.3 additive completed Core Import build provenance and canonical maps.
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;
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'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;
BEGIN TRANSACTION;
DECLARE @PreviousMapRevision int = ISNULL((SELECT MAX(Revision) FROM dbo.StoryMaps WHERE ProjectID=@ProjectID),0);
DECLARE @TableName sysname;
DECLARE DisableCursor CURSOR LOCAL FAST_FORWARD FOR SELECT TableName FROM @RestoreTables;
OPEN DisableCursor;
FETCH NEXT FROM DisableCursor INTO @TableName;
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @DisableSql nvarchar(max) = N'ALTER TABLE dbo.' + QUOTENAME(@TableName) + N' NOCHECK CONSTRAINT ALL;';
EXEC (@DisableSql);
FETCH NEXT FROM DisableCursor INTO @TableName;
END
CLOSE DisableCursor;
DEALLOCATE DisableCursor;
DELETE 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;
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