Validate legacy imports and preserve metadata and scoped character references

This commit is contained in:
Nick Beckley 2026-11-04 01:59:30 +00:00
parent 65fb81e218
commit 6332522568
10 changed files with 299 additions and 23 deletions

View File

@ -32,7 +32,7 @@ PlotLines,2,2,2,Stored field comparison passed; only populated values exercised;
PlotThreads,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
ThreadEvents,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
StoryAssets,2,2,2,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
AssetStates,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
AssetStates,2,2,2,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
AssetEvents,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
AssetDependencies,1,1,1,Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
AssetCustodyEvents,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
32 PlotThreads 1 1 1 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
33 ThreadEvents 1 1 1 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
34 StoryAssets 2 2 2 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
35 AssetStates 1 2 1 2 1 2 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
36 AssetEvents 1 1 1 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
37 AssetDependencies 1 1 1 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present
38 AssetCustodyEvents 1 1 1 Stored field comparison passed; only populated values exercised; Exact uploaded bytes and independent paths compared where present

View File

@ -0,0 +1,29 @@
Workflow,Direction,Formats,IntendedPurpose,Implementation,Verification,Limits
StoryBible,Export,html; markdown/md; text/txt,Project planning reference,ExportsController; ExportService; ExportRepository; Export_* SPs,Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries,Reference documents; no manuscript prose or full-project preservation; no matching importer
NarrativeTimeline,Export,html; markdown/md; text/txt,Ordered narrative summary,ExportsController; ExportService; ExportRepository; Export_* SPs,Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries,Reference documents; no manuscript prose or full-project preservation; no matching importer
Character,Export,html; markdown/md; text/txt,Character appearances/relationships/knowledge reference,ExportsController; ExportService; ExportRepository; Export_* SPs,Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries,Reference documents; no manuscript prose or full-project preservation; no matching importer
SceneBrief,Export,html; markdown/md; text/txt,Scene planning brief,ExportsController; ExportService; ExportRepository; Export_* SPs,Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries,Reference documents; no manuscript prose or full-project preservation; no matching importer
ChapterBrief,Export,html; markdown/md; text/txt,Chapter goal and scene brief,ExportsController; ExportService; ExportRepository; Export_* SPs,Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries,Reference documents; no manuscript prose or full-project preservation; no matching importer
WritingSession,Export,html; markdown/md; text/txt,Scene writing-session brief,ExportsController; ExportService; ExportRepository; Export_* SPs,Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries,Reference documents; no manuscript prose or full-project preservation; no matching importer
ResearchPack,Export,html; markdown/md; text/txt,Research notes and attachment links,ExportsController; ExportService; ExportRepository; Export_* SPs,Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries,Reference documents; no manuscript prose or full-project preservation; no matching importer
Search,Export,html; markdown/md; text/txt,Project-scoped search results,ExportsController; ExportService; ExportRepository; Export_* SPs,Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries,Reference documents; no manuscript prose or full-project preservation; no matching importer
Project backup download/import-as-new,Export + import,PlotDirector.ProjectBackup JSON 1.3; readers accept 1.0/1.1/1.2,Portable serialized project data and active uploaded files,ProjectExportService; ImportService; ProjectBackupRepository; ProjectRestore_ApplyFromJson,65 populated persistent collections; exact file/map bytes; copy references/actors; real SQL rollback; HTTP download,Unrepresented SI/review/provenance and project-derived illustration catalogue remain outside coverage; historical full-backup fixtures unavailable; request/upstream size limits apply
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,Pending focused isolated SQL verification; existing harness checks are separate,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
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
Story Intelligence reviewed Relationships,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 Knowledge,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 Narrative,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
Character/gallery images,Upload,PNG; JPEG; WebP,Project-owned visual asset,Image upload controller/service; VisualIdentityImageService,Active file bytes and portable backup paths verified; map normalization is covered separately,Normal upload UI for every format is not newly verified; normalized output is WebP; 10 MiB source upload limit
Asset images,Upload,PNG; JPEG; WebP,Project-owned visual asset,Image upload controller/service; VisualIdentityImageService,Active file bytes and portable backup paths verified; map normalization is covered separately,Normal upload UI for every format is not newly verified; normalized output is WebP; 10 MiB source upload limit
Book covers,Upload,PNG; JPEG; WebP,Project-owned visual asset,Image upload controller/service; BookCoverService,Active file bytes and portable backup paths verified; map normalization is covered separately,Normal upload UI for every format is not newly verified; normalized output is WebP; 10 MiB source upload limit
Floor-plan backgrounds,Upload,PNG; JPEG; WebP,Project-owned visual asset,Image upload controller/service; FloorPlanBackgroundImageService,Active file bytes and portable backup paths verified; map normalization is covered separately,Normal upload UI for every format is not newly verified; normalized output is WebP; 10 MiB source upload limit
Map reference images,Upload,PNG; JPEG; WebP,Project-owned visual asset,Image upload controller/service; MapReferenceImageService,Active file bytes and portable backup paths verified; map normalization is covered separately,Normal upload UI for every format is not newly verified; normalized output is WebP; 10 MiB source upload limit
Character avatar crop,Image operation,Existing gallery raster -> WebP,Crop an avatar from a selected gallery image,VisualIdentityImageService,Avatar/gallery identity remap and file independence verified in backup SQL matrix,Crop UI/geometry is not a new acceptance claim
Scene attachments,Upload/link,Uploaded file bytes or external URL,Scene-associated reference material,ScenesController; writer workspace/storage services,Empty and long Unicode attachments; external link metadata; exact backup bytes and storage ledger,External URLs are metadata; remote content is not downloaded or embedded
Solver review record,Export,JSON diagnostic record,Download one solver review record,WritingSolverReviewController,Existing solver review harness; no new HTTP data-transfer claim,Diagnostic workflow; not project backup or manuscript transfer
Admin full-chapter test text,Diagnostic input,Text upload,Administrator analysis preflight/test input,AdminController; full chapter test service,Not executed during this programme,Not a project import; paid analysis/generation deliberately not invoked
1 Workflow Direction Formats IntendedPurpose Implementation Verification Limits
2 StoryBible Export html; markdown/md; text/txt Project planning reference ExportsController; ExportService; ExportRepository; Export_* SPs Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries Reference documents; no manuscript prose or full-project preservation; no matching importer
3 NarrativeTimeline Export html; markdown/md; text/txt Ordered narrative summary ExportsController; ExportService; ExportRepository; Export_* SPs Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries Reference documents; no manuscript prose or full-project preservation; no matching importer
4 Character Export html; markdown/md; text/txt Character appearances/relationships/knowledge reference ExportsController; ExportService; ExportRepository; Export_* SPs Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries Reference documents; no manuscript prose or full-project preservation; no matching importer
5 SceneBrief Export html; markdown/md; text/txt Scene planning brief ExportsController; ExportService; ExportRepository; Export_* SPs Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries Reference documents; no manuscript prose or full-project preservation; no matching importer
6 ChapterBrief Export html; markdown/md; text/txt Chapter goal and scene brief ExportsController; ExportService; ExportRepository; Export_* SPs Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries Reference documents; no manuscript prose or full-project preservation; no matching importer
7 WritingSession Export html; markdown/md; text/txt Scene writing-session brief ExportsController; ExportService; ExportRepository; Export_* SPs Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries Reference documents; no manuscript prose or full-project preservation; no matching importer
8 ResearchPack Export html; markdown/md; text/txt Research notes and attachment links ExportsController; ExportService; ExportRepository; Export_* SPs Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries Reference documents; no manuscript prose or full-project preservation; no matching importer
9 Search Export html; markdown/md; text/txt Project-scoped search results ExportsController; ExportService; ExportRepository; Export_* SPs Real HTTP/SQL 5 formats; Unicode and applicable metadata/order/empty/long content; author/anonymous/missing boundaries Reference documents; no manuscript prose or full-project preservation; no matching importer
10 Project backup download/import-as-new Export + import PlotDirector.ProjectBackup JSON 1.3; readers accept 1.0/1.1/1.2 Portable serialized project data and active uploaded files ProjectExportService; ImportService; ProjectBackupRepository; ProjectRestore_ApplyFromJson 65 populated persistent collections; exact file/map bytes; copy references/actors; real SQL rollback; HTTP download Unrepresented SI/review/provenance and project-derived illustration catalogue remain outside coverage; historical full-backup fixtures unavailable; request/upstream size limits apply
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 Pending focused isolated SQL verification; existing harness checks are separate 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 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
18 Story Intelligence reviewed Relationships 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
19 Story Intelligence reviewed Knowledge 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
20 Story Intelligence reviewed Narrative 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
21 Character/gallery images Upload PNG; JPEG; WebP Project-owned visual asset Image upload controller/service; VisualIdentityImageService Active file bytes and portable backup paths verified; map normalization is covered separately Normal upload UI for every format is not newly verified; normalized output is WebP; 10 MiB source upload limit
22 Asset images Upload PNG; JPEG; WebP Project-owned visual asset Image upload controller/service; VisualIdentityImageService Active file bytes and portable backup paths verified; map normalization is covered separately Normal upload UI for every format is not newly verified; normalized output is WebP; 10 MiB source upload limit
23 Book covers Upload PNG; JPEG; WebP Project-owned visual asset Image upload controller/service; BookCoverService Active file bytes and portable backup paths verified; map normalization is covered separately Normal upload UI for every format is not newly verified; normalized output is WebP; 10 MiB source upload limit
24 Floor-plan backgrounds Upload PNG; JPEG; WebP Project-owned visual asset Image upload controller/service; FloorPlanBackgroundImageService Active file bytes and portable backup paths verified; map normalization is covered separately Normal upload UI for every format is not newly verified; normalized output is WebP; 10 MiB source upload limit
25 Map reference images Upload PNG; JPEG; WebP Project-owned visual asset Image upload controller/service; MapReferenceImageService Active file bytes and portable backup paths verified; map normalization is covered separately Normal upload UI for every format is not newly verified; normalized output is WebP; 10 MiB source upload limit
26 Character avatar crop Image operation Existing gallery raster -> WebP Crop an avatar from a selected gallery image VisualIdentityImageService Avatar/gallery identity remap and file independence verified in backup SQL matrix Crop UI/geometry is not a new acceptance claim
27 Scene attachments Upload/link Uploaded file bytes or external URL Scene-associated reference material ScenesController; writer workspace/storage services Empty and long Unicode attachments; external link metadata; exact backup bytes and storage ledger External URLs are metadata; remote content is not downloaded or embedded
28 Solver review record Export JSON diagnostic record Download one solver review record WritingSolverReviewController Existing solver review harness; no new HTTP data-transfer claim Diagnostic workflow; not project backup or manuscript transfer
29 Admin full-chapter test text Diagnostic input Text upload Administrator analysis preflight/test input AdminController; full chapter test service Not executed during this programme Not a project import; paid analysis/generation deliberately not invoked

View File

@ -17,7 +17,7 @@
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. Next: actual SQL export packets in all supported formats, then legacy JSON and manuscript import semantics.
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.
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.
@ -191,3 +191,20 @@ Verified supported content, Unicode/punctuation, book subtitles, scene ordering/
Confirmed defect: all eight actions returned a successful empty document when an ID was missing/zero. Controllers now reject invalid context with a clear 400 response; normal ownership checks remain intact. The initial Search test also expected a notebook whose name did not match the query; corrected that test expectation, not product search behavior.
Evidence: `/tmp/plotdirector-phase2-exports-before.log` (invalid-context failures), `/tmp/plotdirector-phase2-exports-after.log` (pass); build zero warnings/errors. Next: legacy JSON import structural validation/content/rollback and Word manuscript/core-import workflows. No Development writes/deployment.
### Current legacy JSON repair group (uncommitted)
Real SQL verification found the legacy lookup procedure loading custom asset states from every project into a name-keyed dictionary. Repeated project-local state names made valid imports fail; forward-only migration 218 restricts this result to shared states, consistent with the already-correct portable-backup lookup procedure. The fixture now includes a real shared state and another project's state name; only the shared state can become a reference.
Thirty malformed root/nested collections/records now fail preview cleanly instead of throwing. Chapter/scene numbers are checked against SQL's decimal(9,2) range/precision before allocation. Legacy books previously flattened subtitle into title and left explicit scene imports marked as having no explicit scenes; title/subtitle and scene mode are now stored separately. Long separately valid title/subtitle fields are retained without truncation. Initial asset owner resolution previously discarded the resolved character ID and passed alias text into a free-text custody parameter; using the existing character-ID parameter preserves the canonical custody link, including names with commas.
Expanded SQL fixture passed book/chapter/scene order and fractional numbers; empty book/chapter/scene records; long Unicode/plain formatting; aliases/hierarchy; plot/thread/event references; assets/state/event/custody; hard dependencies; dry-run isolation; author boundaries; and a forced SQL parameter failure that rolls back shell/children. The actual downloadable sample imports and its book/chapter/scene content/metadata are compared. Server UTF-8/UTF-16 BOM decoding and edited-text precedence after upload are checked separately from browser transport. The first expanded setup attempt supplied an implicit ID to a non-identity lookup table; fixed that synthetic setup, not product behavior.
Further compatibility tests reproduced rejection of the documented optional packageVersion and casing rejected by detection despite case-insensitive deserialization. Detection is now being aligned with those contracts; final rechecks pending. Evidence: `/tmp/plotdirector-phase2-legacy-before.log`, `...-legacy-lookup-repair.log`, `...-legacy-optional-version-before.log`; earlier repaired expanded SQL run passed in `...-legacy-after.log`. The 405-check harness passed before the final detector changes; rebuild/rechecks are underway. No actual historical full-project backup fixture was found by targeted filename discovery in tests/documentation, and none is fabricated.
Workflow inventory: `2026-11-03-phase2-transfer-workflows.csv` records 28 exports/imports/synchronization/materialization/upload/diagnostic flows and their distinct verification/limits. Word structure/core-import SQL checks remain next. These fixtures never start paid model/image generation or application workers. Development is unchanged and undeployed.
### Legacy repair verification checkpoint
Final legacy SQL run passed (`/tmp/plotdirector-phase2-legacy-after.log`), including optional version and case-insensitive detection, BOM decoding, edited-text precedence, all top-level planning entity groups and the real downloadable sample. The portable-backup matrix was rerun with shared reference states and uppercase root keys: 1,021 source values, 982 copied values and 985 in-place values across 65 persistent collections; twelve files, storage limits/ownership, safety backups and SQL failure cleanup still pass (`/tmp/plotdirector-phase2-transfer-files-final-legacy.log`). Broad harness passed again: 405 checks, exit 0 (`/tmp/plotdirector-phase2-tests-legacy-final.log`). Build zero warnings/errors. Migration 218 only exists in the synthetic database; no Development changes/deployment. Remaining Word/core-import and unrepresented persisted SI scope remain explicit, not treated as completed.

View File

@ -0,0 +1,155 @@
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Nodes;
using Dapper;
using Microsoft.Extensions.Logging.Abstractions;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.ViewModels;
internal static class LegacyImportDatabaseTests
{
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;}
private static void Check(bool condition,string message){if(!condition)throw new InvalidOperationException(message);}
public static async Task RunAsync(ISqlConnectionFactory factory,IProjectBackupFiles files,int user,int other,int untouchedProject)
{
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,"Legacy fixtures require the verified synthetic-only 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);IF NOT EXISTS(SELECT 1 FROM dbo.TimeModes WHERE TimeModeName=N'Relative') INSERT dbo.TimeModes(TimeModeName,SortOrder) VALUES(N'Relative',0);IF NOT EXISTS(SELECT 1 FROM dbo.TimeConfidences WHERE TimeConfidenceName=N'Unknown') INSERT dbo.TimeConfidences(TimeConfidenceName,SortOrder) VALUES(N'Unknown',0);");
await db.ExecuteAsync("IF NOT EXISTS(SELECT 1 FROM dbo.AssetStates WHERE ProjectID IS NULL AND StateName=N'Shared state Ω') INSERT dbo.AssetStates(ProjectID,StateName,SortOrder) VALUES(NULL,N'Shared state Ω',1);IF NOT EXISTS(SELECT 1 FROM dbo.PlotEventTypes WHERE PlotEventTypeID=2) INSERT dbo.PlotEventTypes(PlotEventTypeID,TypeName,SortOrder) VALUES(2,N'Legacy synthetic event',2);");
var current=Proxy<ICurrentUserService>((name,args)=>name switch {"get_UserId"=>(int?)user,"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}),_=>throw new NotSupportedException(name)});
var repository=new ImportRepository(factory);var service=new ImportService(repository,current,subscription,NullLogger<ImportService>.Instance,files);
var failures=new List<string>();var longText=string.Concat(Enumerable.Repeat("“Dialogue”—雨 café 🖋\n\nPlain <em>formatting</em>.\n",5000));
var package=new PlotLineImportPackage {
PackageVersion="1.0",Source="Published structured JSON schema",CreatedBy="Synthetic author",CreatedDate="2026-11-04",
Project=new(){Title="Legacy synthetic Ω",Description="Project description 雨",Notes="Author notes café"},
Aliases=new(){Characters=new(){{"N.","Legacy narrator, Ω"}},Locations=new(){{"The room","Hall Ω"}}},
Characters=[new(){Name="Legacy narrator, Ω",ShortName="N.",Description="Narrator description 雨"}],
Locations=[new(){Name="Hall Ω",Type="Synthetic"},new(){Name="Door 雨",Type="Synthetic",ParentLocationName="Hall Ω"}],
PlotLines=[new(){Name="Legacy arc Ω",Type="Main",Threads=[new(){Name="Legacy question 雨",Type="Question",Status="Open",Events=[new(){BookOrder=1,ChapterOrder=1,SceneOrder=1,Title="Legacy reveal 雨",EventType="Reveal",Summary="Event intent café"}]}]}],
StoryAssets=[new(){Name="Legacy artifact Ω",Type="Object",InitialOwnerCharacterName="n.",InitialLocationName="the ROOM",States=[new(){BookOrder=1,ChapterOrder=1,SceneOrder=1,StateName="Shared state Ω",Description="State intent 雨"}],Events=[new(){BookOrder=1,ChapterOrder=1,SceneOrder=2,EventType="Synthetic",Title="Asset event 雨",Summary="Event detail café"}]},new(){Name="Foreign state guard Ω",Type="Object",States=[new(){BookOrder=1,ChapterOrder=1,SceneOrder=1,StateName="Sealed Ω"}]}],
SceneDependencies=[new(){FromScene=new(){BookOrder=1,ChapterOrder=1,SceneOrder=1},ToScene=new(){BookOrder=1,ChapterOrder=1,SceneOrder=2},DependencyType="Synthetic",Strength="Hard",Description="Before the second scene 雨"}],
Books=[new(){Title="Empty book 雨",SeriesOrder=2},new(){Title="Legacy book Ω",Subtitle="Subtitle é",SeriesOrder=1,Description="Book description 雨",Chapters=[
new(){Title="Second logical chapter",Order=2,ChapterNumber=2.75m},
new(){Title="First logical chapter",Order=1,ChapterNumber=9.5m,Summary="Chapter summary 雨",Scenes=[
new(){Title="Second logical scene",Order=2,SceneNumber=2.5m,Summary=""},
new(){Title="First logical scene Ω",Order=1,SceneNumber=10.25m,Summary=longText,PovCharacterName="n.",LocationName="the ROOM",PurposeText="Intent Ω",OutcomeText="Outcome 雨",Notes="Scene notes café",SceneCharacters=[new(){CharacterName="n.",Notes="Appearance 雨"}]}]}]}]
};
var json=JsonSerializer.Serialize(package);var projectsBefore=await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects");
var malformed=new List<(string Label,string Json)>();
void Mutation(string label,Action<JsonObject> mutate){var root=JsonNode.Parse(json)!.AsObject();mutate(root);malformed.Add((label,root.ToJsonString()));}
Mutation("project=null",root=>root["Project"]=null);
foreach(var collection in new[]{"Books","Characters","Locations","PlotLines","StoryAssets","SceneDependencies"})
{Mutation(collection+"=null",root=>root[collection]=null);Mutation(collection+" contains null",root=>root[collection]!.AsArray().Add(null));}
Mutation("aliases=null",root=>root["Aliases"]=null);
Mutation("character aliases=null",root=>root["Aliases"]!["Characters"]=null);
Mutation("chapters=null",root=>root["Books"]![1]!["Chapters"]=null);
Mutation("chapter contains null",root=>root["Books"]![1]!["Chapters"]!.AsArray().Add(null));
Mutation("scenes=null",root=>root["Books"]![1]!["Chapters"]![1]!["Scenes"]=null);
Mutation("scene contains null",root=>root["Books"]![1]!["Chapters"]![1]!["Scenes"]!.AsArray().Add(null));
Mutation("scene appearances=null",root=>root["Books"]![1]!["Chapters"]![1]!["Scenes"]![1]!["SceneCharacters"]=null);
Mutation("location aliases=null",root=>root["Aliases"]!["Locations"]=null);
Mutation("threads=null",root=>root["PlotLines"]![0]!["Threads"]=null);
Mutation("thread contains null",root=>root["PlotLines"]![0]!["Threads"]!.AsArray().Add(null));
Mutation("thread events=null",root=>root["PlotLines"]![0]!["Threads"]![0]!["Events"]=null);
Mutation("thread event contains null",root=>root["PlotLines"]![0]!["Threads"]![0]!["Events"]!.AsArray().Add(null));
Mutation("asset states=null",root=>root["StoryAssets"]![0]!["States"]=null);
Mutation("asset state contains null",root=>root["StoryAssets"]![0]!["States"]!.AsArray().Add(null));
Mutation("asset events=null",root=>root["StoryAssets"]![0]!["Events"]=null);
Mutation("asset event contains null",root=>root["StoryAssets"]![0]!["Events"]!.AsArray().Add(null));
Mutation("scene appearance contains null",root=>root["Books"]![1]!["Chapters"]![1]!["Scenes"]![1]!["SceneCharacters"]!.AsArray().Add(null));
foreach(var item in malformed)
{
try {var preview=await service.PreviewAsync(new(){JsonText=item.Json});if(preview.Preview?.Validation.IsValid!=false)failures.Add(item.Label+": malformed shape accepted");}
catch(Exception ex){failures.Add(item.Label+": preview threw "+ex.GetType().Name);}
}
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects")==projectsBefore,"Malformed previews allocate no projects.");
foreach(var number in new[]{100_000_000m,1.234m})
{
var root=JsonNode.Parse(json)!.AsObject();root["Books"]![1]!["Chapters"]![1]!["ChapterNumber"]=number;
if((await service.PreviewAsync(new(){JsonText=root.ToJsonString()})).Preview!.Validation.IsValid)failures.Add("Chapter numbering outside SQL precision/range accepted by preview");
root=JsonNode.Parse(json)!.AsObject();root["Books"]![1]!["Chapters"]![1]!["Scenes"]![1]!["SceneNumber"]=number;
if((await service.PreviewAsync(new(){JsonText=root.ToJsonString()})).Preview!.Validation.IsValid)failures.Add("Scene numbering outside SQL precision/range accepted by preview");
}
if(failures.Count>0)Console.WriteLine(string.Join(Environment.NewLine,failures.Distinct()));
foreach(var encoding in new System.Text.Encoding[]{System.Text.Encoding.UTF8,System.Text.Encoding.Unicode})
{
var bytes=encoding.GetPreamble().Concat(encoding.GetBytes(json)).ToArray();
using var stream=new MemoryStream(bytes);
var formFile=new Microsoft.AspNetCore.Http.FormFile(stream,0,bytes.Length,"JsonFile","synthetic.json");
var uploaded=await service.PreviewAsync(new(){JsonFile=formFile,JsonText=ImportIndexViewModel.SampleJson});
Check(uploaded.Preview!.Validation.IsValid && uploaded.JsonText==json,"Server upload decoder preserves Unicode and BOM encoding: "+encoding.WebName);
var edited=JsonNode.Parse(json)!.AsObject();edited["Project"]!["Title"]="Edited uploaded package Ω";
var editedPreview=await service.PreviewAsync(new(){JsonFile=formFile,JsonText=edited.ToJsonString()});
Check(editedPreview.Preview!.Package!.Project.Title=="Edited uploaded package Ω","Edited textarea remains authoritative after upload.");
}
var withoutVersion=JsonNode.Parse(json)!.AsObject();withoutVersion.Remove("PackageVersion");
if(!(await service.PreviewAsync(new(){JsonText=withoutVersion.ToJsonString()})).Preview!.Validation.IsValid)failures.Add("The documented optional packageVersion blocks an otherwise valid legacy package");
var uppercase=new JsonObject();foreach(var property in JsonNode.Parse(json)!.AsObject())uppercase[property.Key.ToUpperInvariant()]=property.Value?.DeepClone();
if(!(await service.PreviewAsync(new(){JsonText=uppercase.ToJsonString()})).Preview!.Validation.IsValid)failures.Add("Legacy format detection disagrees with case-insensitive deserialization");
var previewModel=await service.PreviewAsync(new(){JsonText=json});Check(previewModel.Preview!.Validation.IsValid,"Representative legacy JSON must validate: "+string.Join("; ",previewModel.Preview.Validation.Errors));
var dry=await service.ImportAsync(new(){JsonText=json,ConfirmImport=true,AcknowledgeWarnings=true,DryRun=true});
Check(dry.Succeeded && dry.IsDryRun && await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects")==projectsBefore,"Legacy dry run saves no data.");
var imported=await service.ImportAsync(new(){JsonText=json,ConfirmImport=true,AcknowledgeWarnings=true,AllowDuplicateProjectTitle=true});
Check(imported.Succeeded,"Legacy SQL import failed: "+imported.Message+" "+imported.TechnicalDetail);
var backup=(await new ProjectBackupRepository(factory).GetProjectBackupAsync(imported.ProjectID!.Value,user))!;
var books=backup.Data.Books.OrderBy(book=>book.SortOrder).ToArray();
if(books[0].BookTitle!="Legacy book Ω" || books[0].Subtitle!="Subtitle é")failures.Add("Legacy book title/subtitle are not retained as separate metadata");
if(!books[0].UsesExplicitScenes)failures.Add("Legacy explicit scenes imported into a book marked as having no explicit scenes");
Check(books.Length==2 && books[1].BookTitle=="Empty book 雨","Book ordering/empty book retained.");
var chapters=backup.Data.Chapters.OrderBy(chapter=>chapter.SortOrder).ToArray();
Check(chapters.Length==2 && chapters[0].ChapterTitle=="First logical chapter" && chapters[0].ChapterNumber==9.5m && chapters[1].ChapterNumber==2.75m,"Chapter order and decimal numbers retained independently.");
var scenes=backup.Data.Scenes.OrderBy(scene=>scene.SortOrder).ToArray();
Check(scenes.Length==2 && scenes[0].SceneTitle=="First logical scene Ω" && scenes[0].SceneNumber==10.25m && scenes[1].SceneNumber==2.5m,"Scene order and decimal numbers retained.");
Check(scenes[0].Summary!.Contains(longText.Trim(),StringComparison.Ordinal) && scenes[0].ScenePurposeNotes=="Intent Ω" && scenes[0].SceneOutcomeNotes=="Outcome 雨","Long Unicode/plain formatting and purpose/outcome retained.");
Check(scenes[0].POVCharacterID==backup.Data.Characters.Single().CharacterID && scenes[0].PrimaryLocationID==backup.Data.Locations.Single(location=>location.LocationName=="Hall Ω").LocationID && backup.Data.SceneCharacters.Single().CharacterID==backup.Data.Characters.Single().CharacterID,"Aliases map POV, primary location and appearance references.");
Check(backup.Data.Locations.Single(location=>location.LocationName=="Door 雨").ParentLocationID==backup.Data.Locations.Single(location=>location.LocationName=="Hall Ω").LocationID,"Imported location hierarchy retained.");
var artifact=backup.Data.StoryAssets.Single(asset=>asset.AssetName=="Legacy artifact Ω");
var globalState=await db.ExecuteScalarAsync<int>("SELECT AssetStateID FROM dbo.AssetStates WHERE ProjectID IS NULL AND StateName=N'Shared state Ω'");
Check(artifact.CurrentStateID==globalState && artifact.CurrentLocationID==scenes[0].PrimaryLocationID && backup.Data.StoryAssets.Single(asset=>asset.AssetName=="Foreign state guard Ω").CurrentStateID is null,"Only shared state names resolve; another project's custom state cannot be attached.");
Check(backup.Data.PlotLines.Single().PlotLineName=="Legacy arc Ω" && backup.Data.PlotThreads.Single().ThreadTitle=="Legacy question 雨" && backup.Data.ThreadEvents.Single().EventDescription!.Contains("Event intent café") && backup.Data.ThreadEvents.Single().SceneID==scenes[0].SceneID,"Plot/thread/event text and order-based scene references retained.");
Check(backup.Data.SceneDependencies.Single().SourceSceneID==scenes[0].SceneID && backup.Data.SceneDependencies.Single().TargetSceneID==scenes[1].SceneID && backup.Data.SceneDependencies.Single().IsHardDependency,"Dependency references use supplied ordering and preserve hard strength.");
Check(backup.Data.AssetEvents.Any(item=>item.EventTitle=="Asset event 雨" && item.SceneID==scenes[1].SceneID) && backup.Data.AssetCustodyCharacters.Any(item=>item.CharacterID==backup.Data.Characters.Single().CharacterID),"Asset event/custody content and character references retained.");
Check(!await new ProjectAccessRepository(factory).UserCanAccessProjectAsync(imported.ProjectID.Value,other),"Imported legacy project does not cross authors.");
Check((await new ProjectBackupRepository(factory).GetProjectBackupAsync(untouchedProject,other)) is not null,"Other author's original project remains available.");
// Force an actual SQL parameter conversion failure after shell/book creation, bypassing service validation deliberately.
var badPackage=JsonSerializer.Deserialize<PlotLineImportPackage>(json)!;badPackage.Books[1].Chapters[1].ChapterNumber=100_000_000m;
var beforeFault=await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects");var rejected=false;
try {await repository.ImportAsync(badPackage,"Synthetic forced SQL rollback",user);}catch(Microsoft.Data.SqlClient.SqlException){rejected=true;}
Check(rejected && await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects")==beforeFault,"Actual legacy repository transaction rolls back shell and children after SQL failure.");
var metadataPackage=JsonSerializer.Deserialize<PlotLineImportPackage>(json)!;metadataPackage.Project.Title="Long metadata synthetic Ω";
metadataPackage.Books[1].Title=new string('Ω',150);metadataPackage.Books[1].Subtitle=new string('é',100);
var metadataJson=JsonSerializer.Serialize(metadataPackage);
Check((await service.PreviewAsync(new(){JsonText=metadataJson})).Preview!.Validation.IsValid,"Separate title/subtitle bounds allow valid combined display titles over 200 characters.");
var metadataImport=await service.ImportAsync(new(){JsonText=metadataJson,ConfirmImport=true,AcknowledgeWarnings=true,AllowDuplicateProjectTitle=true});
Check(metadataImport.Succeeded,"Long separate metadata import must succeed.");
var metadataBook=await db.QuerySingleAsync<Book>("SELECT * FROM dbo.Books WHERE ProjectID=@project AND BookNumber=1",new{project=metadataImport.ProjectID});
Check(metadataBook.BookTitle==metadataPackage.Books[1].Title && metadataBook.Subtitle==metadataPackage.Books[1].Subtitle,"Separate long title/subtitle retained without truncation.");
var sample=JsonSerializer.Deserialize<PlotLineImportPackage>(ImportIndexViewModel.SampleJson,new JsonSerializerOptions{PropertyNameCaseInsensitive=true})!;
sample.Project.Title="Published sample synthetic import";
var sampleJson=JsonSerializer.Serialize(sample);
Check((await service.PreviewAsync(new(){JsonText=sampleJson})).Preview!.Validation.IsValid,"The actual downloadable published sample must validate.");
var sampleImport=await service.ImportAsync(new(){JsonText=sampleJson,ConfirmImport=true,AcknowledgeWarnings=true,AllowDuplicateProjectTitle=true});
Check(sampleImport.Succeeded,"The actual published sample must import: "+sampleImport.TechnicalDetail);
var sampleBackup=(await new ProjectBackupRepository(factory).GetProjectBackupAsync(sampleImport.ProjectID!.Value,user))!;
Check(sampleBackup.Data.Books.Count==sample.Books.Count && sampleBackup.Data.Chapters.Count==sample.Books.Sum(item=>item.Chapters.Count) && sampleBackup.Data.Scenes.Count==sample.Books.Sum(item=>item.Chapters.Sum(chapter=>chapter.Scenes.Count)),"Published sample preserves all books, chapters and scenes.");
foreach(var sourceBook in sample.Books)
{
var targetBook=sampleBackup.Data.Books.Single(item=>item.BookNumber==sourceBook.SeriesOrder);
Check(targetBook.BookTitle==sourceBook.Title.Trim() && targetBook.Subtitle==(string.IsNullOrWhiteSpace(sourceBook.Subtitle)?null:sourceBook.Subtitle.Trim()),"Published sample title/subtitle metadata retained.");
foreach(var sourceChapter in sourceBook.Chapters)
{
var targetChapter=sampleBackup.Data.Chapters.Single(item=>item.BookID==targetBook.BookID && item.ChapterNumber==sourceChapter.ChapterNumber);
foreach(var sourceScene in sourceChapter.Scenes)
{
var targetScene=sampleBackup.Data.Scenes.Single(item=>item.ChapterID==targetChapter.ChapterID && item.SceneNumber==sourceScene.SceneNumber);
Check(targetScene.SceneTitle==sourceScene.Title.Trim() && (string.IsNullOrWhiteSpace(sourceScene.Summary)||targetScene.Summary!.Contains(sourceScene.Summary.Trim(),StringComparison.Ordinal)),"Published sample scene titles and summary content retained.");
}
}
}
if(failures.Count>0)throw new InvalidOperationException(string.Join(Environment.NewLine,failures.Distinct()));
Console.WriteLine($"PASS legacy JSON 1.0: {malformed.Count} malformed shapes rejected, number bounds, dry run, ordering/decimal numbers, empty book/chapter/scene, long Unicode/plain formatting, separate metadata, aliases/hierarchy/custody, shared state scope, plots/events/dependencies, actual published sample, BOM decoding, author isolation and real SQL transaction rollback. This is structured planning import, not a manuscript or historical-backup compatibility claim.");
}
}

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")); }
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")); }
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)
public static async Task RunAsync(string target, bool applyMigrations = false, bool requireWritingPlans = false, bool schemaCoverageOnly = false, bool exportsOnly = false, bool legacyOnly = 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"})
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"})
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.");
@ -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(legacyOnly)
{
await LegacyImportDatabaseTests.RunAsync(factory,assetFiles,importingUser,user,project);
return;
}
if(exportsOnly)
{
await ProjectExportDatabaseTests.RunAsync(factory,assetFiles,user,importingUser,project,book,chapter,scene,character);
@ -196,6 +201,9 @@ internal static class ProjectTransferDatabaseTests
{
var invalid=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!.AsObject();mutation(invalid);invalidPayloads.Add(invalid.ToJsonString());
}
var upperBackup=new System.Text.Json.Nodes.JsonObject();
foreach(var property in System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!.AsObject())upperBackup[property.Key.ToUpperInvariant()]=property.Value?.DeepClone();
Check((await service.PreviewAsync(new(){JsonText=upperBackup.ToJsonString()})).Preview!.Validation.IsValid,"Backup format detection agrees with case-insensitive JSON deserialization.");
foreach(var payload in invalidPayloads)
{
var preview=await service.PreviewAsync(new(){JsonText=payload});

View File

@ -258,7 +258,9 @@ public sealed class ImportRepository(ISqlConnectionFactory connectionFactory) :
{
BookID = 0,
ProjectID = projectId,
BookTitle = Clean(FormatBookTitle(book)),
BookTitle = Clean(book.Title),
Subtitle = string.IsNullOrWhiteSpace(book.Subtitle) ? null : book.Subtitle.Trim(),
UsesExplicitScenes = book.Chapters.Any(chapter => chapter.Scenes.Count > 0),
BookNumber = book.SeriesOrder,
Description = CombineText(
book.Description,
@ -514,7 +516,8 @@ public sealed class ImportRepository(ISqlConnectionFactory connectionFactory) :
SceneID = firstSceneId,
AssetCustodyEventTypeID = ResolveAssetCustodyEventTypeId(lookupIds, "Has"),
Description = CombineText("Initial owner imported from JSON.", ImportMarker),
CustodianNames = storyAsset.InitialOwnerCharacterName,
CustodianNames = (string?)null,
CustodianCharacterIds = initialOwnerCharacterId.Value.ToString(System.Globalization.CultureInfo.InvariantCulture),
CustodyRoleID = ResolveCustodyRoleId(lookupIds, "Has Custody")
},
transaction,
@ -721,9 +724,6 @@ public sealed class ImportRepository(ISqlConnectionFactory connectionFactory) :
custodyRoles);
}
private static string FormatBookTitle(ImportBookDto book)
=> string.IsNullOrWhiteSpace(book.Subtitle) ? book.Title : $"{book.Title}: {book.Subtitle}";
private static string ImportMetadata(PlotLineImportPackage package)
{
var source = string.IsNullOrWhiteSpace(package.Source) ? null : $"Source: {package.Source.Trim()}";

View File

@ -285,6 +285,13 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
return new ImportPreview { Validation = invalidPackage };
}
var shapeError=ValidateLegacyShape(package);
if(shapeError is not null)
{
var invalidShape=new ImportValidationResult();invalidShape.Errors.Add(shapeError);
return new ImportPreview {Validation=invalidShape};
}
var validation = Validate(package);
AddMetadataWarnings(package, validation);
var aliasWarnings = FindAliasWarnings(package);
@ -652,13 +659,11 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
return ProjectImportFormat.Unsupported;
}
if ((TryGetString(root, "packageVersion", out _) || TryGetString(root, "PackageVersion", out _))
&& (root.TryGetProperty("books", out _)
|| root.TryGetProperty("Books", out _)
|| root.TryGetProperty("characters", out _)
|| root.TryGetProperty("Characters", out _)
|| root.TryGetProperty("locations", out _)
|| root.TryGetProperty("Locations", out _)))
var hasLegacyProject=TryGetPropertyIgnoreCase(root,"project",out var project)
&& project.ValueKind==JsonValueKind.Object && TryGetString(project,"title",out _);
var hasLegacyCollections=new[]{"books","characters","locations","plotLines","storyAssets","sceneDependencies"}
.Any(name=>TryGetPropertyIgnoreCase(root,name,out _));
if (hasLegacyProject || TryGetString(root,"packageVersion",out _) && hasLegacyCollections)
{
return ProjectImportFormat.LegacyPackage;
}
@ -673,10 +678,18 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
}
}
private static bool TryGetPropertyIgnoreCase(JsonElement element,string name,out JsonElement value)
{
if(element.ValueKind==JsonValueKind.Object)
foreach(var property in element.EnumerateObject())
if(string.Equals(property.Name,name,StringComparison.OrdinalIgnoreCase)){value=property.Value;return true;}
value=default;return false;
}
private static bool TryGetString(JsonElement element, string propertyName, out string? value)
{
value = null;
if (!element.TryGetProperty(propertyName, out var property) || property.ValueKind != JsonValueKind.String)
if (!TryGetPropertyIgnoreCase(element, propertyName, out var property) || property.ValueKind != JsonValueKind.String)
{
return false;
}
@ -1607,6 +1620,25 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
};
}
private static string? ValidateLegacyShape(PlotLineImportPackage package)
{
static bool Invalid(System.Collections.IEnumerable? collection)=>collection is null || collection.Cast<object?>().Any(item=>item is null);
if(package.Project is null)return "The legacy import requires a project object.";
if(package.Aliases is null || package.Aliases.Characters is null || package.Aliases.Locations is null)
return "Legacy import aliases must be objects. Omit them or use empty objects when no aliases are needed.";
if(Invalid(package.Books)||Invalid(package.Characters)||Invalid(package.Locations)||Invalid(package.PlotLines)||Invalid(package.StoryAssets)||Invalid(package.SceneDependencies))
return "Legacy import collections must be arrays without null records. Use empty arrays for absent content.";
if(package.Books.Any(book=>Invalid(book.Chapters)) || package.Books.Any(book=>book.Chapters.Any(chapter=>Invalid(chapter.Scenes)))
|| package.Books.Any(book=>book.Chapters.Any(chapter=>chapter.Scenes.Any(scene=>Invalid(scene.SceneCharacters)))))
return "Legacy chapters, scenes and scene appearances must be arrays without null records.";
if(package.PlotLines.Any(line=>Invalid(line.Threads)) || package.PlotLines.Any(line=>line.Threads.Any(thread=>Invalid(thread.Events)))
|| package.StoryAssets.Any(asset=>Invalid(asset.States)||Invalid(asset.Events)))
return "Legacy plot threads, events and asset states must be arrays without null records.";
return null;
}
private static bool FitsStoredNumber(decimal number)=>number>=-9_999_999.99m && number<=9_999_999.99m && decimal.Round(number,2)==number;
private static ImportValidationResult Validate(PlotLineImportPackage package)
{
var result = new ImportValidationResult();
@ -1670,11 +1702,14 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
{
result.Errors.Add($"Book {bookIndex + 1} is missing a title.");
}
else if (FormatBookTitle(book).Length > TitleMaxLength)
else if (book.Title.Trim().Length > TitleMaxLength)
{
result.Errors.Add($"{bookLabel} title is longer than {TitleMaxLength} characters after combining title and subtitle.");
result.Errors.Add($"{bookLabel} title is longer than {TitleMaxLength} characters.");
}
if (book.Subtitle?.Trim().Length > TitleMaxLength)
result.Errors.Add($"{bookLabel} subtitle is longer than {TitleMaxLength} characters.");
if (book.SeriesOrder <= 0)
{
result.Errors.Add($"{bookLabel} is missing a valid seriesOrder.");
@ -1705,6 +1740,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
{
var chapter = book.Chapters[chapterIndex];
var chapterLabel = string.IsNullOrWhiteSpace(chapter.Title) ? $"chapter {chapterIndex + 1}" : chapter.Title;
if(!FitsStoredNumber(chapter.ChapterNumber))result.Errors.Add($"{bookLabel} / {chapterLabel}: chapter numbers support seven digits before and two after the decimal point.");
if (string.IsNullOrWhiteSpace(chapter.Title))
{
result.Errors.Add($"{bookLabel} chapter {chapterIndex + 1} is missing a title.");
@ -1748,6 +1784,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
{
var scene = chapter.Scenes[sceneIndex];
var sceneLabel = string.IsNullOrWhiteSpace(scene.Title) ? $"scene {sceneIndex + 1}" : scene.Title;
if(!FitsStoredNumber(scene.SceneNumber))result.Errors.Add($"{bookLabel} / {chapterLabel} / {sceneLabel}: scene numbers support seven digits before and two after the decimal point.");
if (string.IsNullOrWhiteSpace(scene.Title))
{
result.Errors.Add($"{bookLabel} / {chapterLabel} scene {sceneIndex + 1} is missing a title.");

View File

@ -0,0 +1,30 @@
-- A new project import may resolve shared reference states only, never another project's custom states.
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER PROCEDURE dbo.Import_LookupIds
AS
BEGIN
SET NOCOUNT ON;
SELECT
(SELECT TOP (1) RevisionStatusID FROM dbo.RevisionStatuses WHERE StatusName = N'Planned' ORDER BY SortOrder) AS RevisionStatusID,
(SELECT TOP (1) TimeModeID FROM dbo.TimeModes WHERE TimeModeName = N'Relative' ORDER BY SortOrder) AS TimeModeID,
(SELECT TOP (1) TimeConfidenceID FROM dbo.TimeConfidences WHERE TimeConfidenceName = N'Unknown' ORDER BY SortOrder) AS TimeConfidenceID;
SELECT LocationTypeID AS LookupID, TypeName FROM dbo.LocationTypes WHERE IsActive = 1;
SELECT CharacterRoleInSceneTypeID AS LookupID, TypeName FROM dbo.CharacterRoleInSceneTypes WHERE IsActive = 1;
SELECT PresenceTypeID AS LookupID, TypeName FROM dbo.PresenceTypes WHERE IsActive = 1;
SELECT PlotLineTypeID AS LookupID, TypeName FROM dbo.PlotLineTypes WHERE IsActive = 1;
SELECT PlotImportanceID AS LookupID, ImportanceName AS TypeName FROM dbo.PlotImportance WHERE IsActive = 1;
SELECT ThreadTypeID AS LookupID, TypeName FROM dbo.ThreadTypes WHERE IsActive = 1;
SELECT ThreadStatusID AS LookupID, StatusName FROM dbo.ThreadStatuses WHERE IsActive = 1;
SELECT ThreadEventTypeID AS LookupID, TypeName FROM dbo.ThreadEventTypes WHERE IsActive = 1;
SELECT SceneDependencyTypeID AS LookupID, TypeName FROM dbo.SceneDependencyTypes WHERE IsActive = 1;
SELECT AssetKindID AS LookupID, KindName AS TypeName FROM dbo.AssetKinds WHERE IsActive = 1;
SELECT AssetStateID AS LookupID, StateName AS TypeName FROM dbo.AssetStates WHERE IsActive = 1 AND ProjectID IS NULL;
SELECT AssetEventTypeID AS LookupID, TypeName FROM dbo.AssetEventTypes WHERE IsActive = 1;
SELECT AssetCustodyEventTypeID AS LookupID, TypeName FROM dbo.AssetCustodyEventTypes WHERE IsActive = 1;
SELECT CustodyRoleID AS LookupID, RoleName AS TypeName FROM dbo.CustodyRoles WHERE IsActive = 1;
END;
GO

View File

@ -58,7 +58,7 @@
<section class="list-section import-docs mt-3">
<details>
<summary>Supported JSON schema</summary>
<summary>Legacy JSON schema</summary>
<div class="import-doc-grid">
<div>
<h3>Required</h3>
@ -77,8 +77,8 @@
<p><code>sceneDependencies</code> use <code>fromScene</code> and <code>toScene</code> objects. Link scenes with <code>bookOrder</code>, <code>chapterOrder</code>, and <code>sceneOrder</code>; <code>sceneRef</code> is optional future-friendly text. <code>dependencyType</code>, <code>strength</code>, <code>description</code>, and <code>notes</code> are optional. Warnings can be acknowledged; errors block import. Unknown fields are ignored safely.</p>
</div>
<div>
<h3>Not imported yet</h3>
<p>No AI extraction, Word/text parsing, manuscript parsing, metrics import, continuity warning import, relationship graphs, merge/update, or export logic. This importer is ready for manuscript-derived JSON, and unknown fields are ignored safely.</p>
<h3>Legacy schema limits</h3>
<p>The legacy schema imports structured planning data. It does not parse Word documents or manuscript text, import metrics, continuity warnings or relationship graphs, or merge into an existing project. Project backup files use a separate versioned format with additional supported data.</p>
</div>
</div>
</details>