diff --git a/Docs/Sprints/2026-11-03-phase2-data-coverage.csv b/Docs/Sprints/2026-11-03-phase2-data-coverage.csv new file mode 100644 index 00000000..37a02d11 --- /dev/null +++ b/Docs/Sprints/2026-11-03-phase2-data-coverage.csv @@ -0,0 +1,168 @@ +Table,ProjectOwnershipEvidence,BackupCollection,Classification,RestoreVerified,AssetsVerified +AppUser,Global/user/independent,,Account/billing/system execution state; excluded from portable project backup,Pending,Pending +AssetAliases,ProjectID or FK descendant,,Pending classification,Pending,Pending +AssetCustodyEventCharacters,ProjectID or FK descendant,AssetCustodyCharacters,Serialized; field completeness unverified,Pending,Pending +AssetCustodyEvents,ProjectID or FK descendant,AssetCustodyEvents,Serialized; field completeness unverified,Pending,Pending +AssetCustodyEventTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +AssetDependencies,ProjectID or FK descendant,AssetDependencies,Serialized; field completeness unverified,Pending,Pending +AssetDependencyTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +AssetEvents,ProjectID or FK descendant,AssetEvents,Serialized; field completeness unverified,Pending,Pending +AssetEventTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +AssetKinds,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +AssetStates,ProjectID or FK descendant,AssetStates,Serialized; field completeness unverified,Pending,Pending +AuthorPlotSeeds,ProjectID or FK descendant,,Pending classification,Pending,Pending +Books,ProjectID or FK descendant,Books,Serialized; era/locale omission repaired by migration 213 (isolated only),Unicode title and era/locale initial import comparison passed; other fields pending,Pending +ChapterGoals,ProjectID or FK descendant,ChapterGoals,Serialized; field completeness unverified,Pending,Pending +ChapterPurposeTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +Chapters,ProjectID or FK descendant,Chapters,Serialized; field completeness unverified,Pending,Pending +CharacterAliases,ProjectID or FK descendant,,Pending classification,Pending,Pending +CharacterAttributeEvents,ProjectID or FK descendant,CharacterAttributeEvents,Serialized; field completeness unverified,Pending,Pending +CharacterAttributeTypes,ProjectID or FK descendant,CharacterAttributeTypes,Serialized; field completeness unverified,Pending,Pending +CharacterEnrichmentEvidence,ProjectID or FK descendant,,Pending classification,Pending,Pending +CharacterEnrichmentRuns,ProjectID or FK descendant,,Pending classification,Pending,Pending +CharacterImages,ProjectID or FK descendant,,Pending classification,Pending,Pending +CharacterIntelligenceEvidenceEvents,ProjectID or FK descendant,,Pending classification,Pending,Pending +CharacterIntelligenceProfiles,ProjectID or FK descendant,,Pending classification,Pending,Pending +CharacterKnowledge,ProjectID or FK descendant,CharacterKnowledge,Serialized; field completeness unverified,Pending,Pending +CharacterRelationships,ProjectID or FK descendant,CharacterRelationships,Serialized; field completeness unverified,Pending,Pending +CharacterRoleInSceneTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +Characters,ProjectID or FK descendant,Characters,Serialized; field completeness unverified,Pending,Pending +CharacterSexValues,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +ContinuityWarningAcknowledgements,ProjectID or FK descendant,,Pending classification,Pending,Pending +ContinuityWarnings,ProjectID or FK descendant,ContinuityWarnings,Serialized; field completeness unverified,Pending,Pending +CoreImportBasicLocationCandidates,ProjectID or FK descendant,,Pending classification,Pending,Pending +CoreImportBasicLocationEvidence,ProjectID or FK descendant,,Pending classification,Pending,Pending +CoreImportBasicLocationReviews,ProjectID or FK descendant,,Pending classification,Pending,Pending +CustodyRoles,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +DurationUnits,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +EmailQueue,Global/user/independent,,Account/billing/system execution state; excluded from portable project backup,Pending,Pending +FeatureRequestMessages,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +FeatureRequests,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +FloorPlanBlocks,ProjectID or FK descendant,FloorPlanBlocks,Serialized; field completeness unverified,Pending,Pending +FloorPlanFloors,ProjectID or FK descendant,FloorPlanFloors,Serialized; field completeness unverified,Pending,Pending +FloorPlans,ProjectID or FK descendant,FloorPlans,Serialized; field completeness unverified,Pending,Pending +FloorPlanTransitions,ProjectID or FK descendant,FloorPlanTransitions,Serialized; field completeness unverified,Pending,Pending +GenreMetricPresetMetrics,ProjectID or FK descendant,GenreMetricPresetMetrics,Serialized; field completeness unverified,Pending,Pending +GenreMetricPresets,Global/user/independent,GenreMetricPresets,Serialized; field completeness unverified,Pending,Pending +GivenNames,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +IllustrationLibraryItems,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +KnowledgeStates,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +LocationAliases,ProjectID or FK descendant,,Pending classification,Pending,Pending +LocationRelationships,ProjectID or FK descendant,LocationRelationships,Serialized; field completeness unverified,Pending,Pending +LocationRelationshipTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +Locations,ProjectID or FK descendant,Locations,Serialized; field completeness unverified,Pending,Pending +LocationTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +ManuscriptDocuments,ProjectID or FK descendant,,Pending classification,Pending,Pending +ManuscriptStructuralChapterSources,ProjectID or FK descendant,,Authoritative persisted manuscript text omitted; source/schema evidence; SQL case pending,Pending,Pending +MapFeatures,ProjectID or FK descendant,MapFeatures,Serialized; initial isolated semantic import comparison passed,Initial import graph compared; same-project restore and broader cases pending,Pending +MapJourneyNotes,ProjectID or FK descendant,MapJourneyNotes,Serialized; field completeness unverified,Pending,Pending +MapReferenceImages,ProjectID or FK descendant,MapReferenceImages,Serialized; initial isolated semantic import comparison passed,Initial import graph compared; same-project restore and broader cases pending,Exact normalized bytes and remapped image placement passed +MapRelationships,ProjectID or FK descendant,MapRelationships,Serialized; initial isolated semantic import comparison passed,Initial import graph compared; same-project restore and broader cases pending,Pending +NameLocales,Global/user/independent,,Reference/user/system; scope review pending,Pending,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 +PlotEventTargetPlotLines,ProjectID or FK descendant,,Pending classification,Pending,Pending +PlotEventTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +PlotImportance,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +PlotLines,ProjectID or FK descendant,PlotLines,Serialized; field completeness unverified,Pending,Pending +PlotLineTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +PlotThreads,ProjectID or FK descendant,PlotThreads,Serialized; field completeness unverified,Pending,Pending +PresenceTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +ProjectActivity,ProjectID or FK descendant,,Pending classification,Pending,Pending +ProjectInvitation,ProjectID or FK descendant,,Pending classification,Pending,Pending +ProjectRestoreHistory,ProjectID or FK descendant,,Pending classification,Pending,Pending +ProjectRestorePoints,ProjectID or FK descendant,,Pending classification,Pending,Pending +Projects,ProjectID or FK descendant,Project,Serialized; field completeness unverified,Pending,Pending +ProjectTimelineMetricSettings,ProjectID or FK descendant,TimelineMetricSettings,Serialized; field completeness unverified,Pending,Pending +ProjectTimelineSettings,ProjectID or FK descendant,TimelineSettings,Serialized; field completeness unverified,Pending,Pending +ProjectUserAccess,ProjectID or FK descendant,ProjectAccess,Serialized; field completeness unverified,Pending,Pending +RelationshipCategories,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +RelationshipEvents,ProjectID or FK descendant,RelationshipEvents,Serialized; field completeness unverified,Pending,Pending +RelationshipStates,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +RelationshipTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +RevisionStatuses,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +Scenarios,ProjectID or FK descendant,Scenarios,Serialized; field completeness unverified,Pending,Pending +ScenarioSceneOrder,ProjectID or FK descendant,ScenarioSceneOrder,Serialized; field completeness unverified,Pending,Pending +ScenarioValidationRuns,ProjectID or FK descendant,ScenarioValidationRuns,Serialized; field completeness unverified,Pending,Pending +ScenarioWarnings,ProjectID or FK descendant,ScenarioWarnings,Serialized; field completeness unverified,Pending,Pending +SceneAssetLocations,ProjectID or FK descendant,SceneAssetLocations,Serialized; field completeness unverified,Pending,Pending +SceneAssetSuggestions,ProjectID or FK descendant,,Pending classification,Pending,Pending +SceneAttachments,ProjectID or FK descendant,SceneAttachments,Serialized; field completeness unverified,Pending,Pending +SceneAttachmentTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +SceneCharacters,ProjectID or FK descendant,SceneCharacters,Serialized; field completeness unverified,Pending,Pending +SceneCharacterSuggestions,ProjectID or FK descendant,,Pending classification,Pending,Pending +SceneChecklistItems,ProjectID or FK descendant,SceneChecklistItems,Serialized; field completeness unverified,Pending,Pending +SceneDependencies,ProjectID or FK descendant,SceneDependencies,Serialized; field completeness unverified,Pending,Pending +SceneDependencyTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +SceneFloorPlanOccupancy,ProjectID or FK descendant,SceneFloorPlanOccupancy,Serialized; field completeness unverified,Pending,Pending +SceneLocationSuggestions,ProjectID or FK descendant,,Pending classification,Pending,Pending +SceneManuscriptSources,ProjectID or FK descendant,,Authoritative persisted manuscript text omitted; source/schema evidence; SQL case pending,Pending,Pending +SceneMetricTypes,ProjectID or FK descendant,SceneMetricTypes,Serialized; field completeness unverified,Pending,Pending +SceneMetricValues,ProjectID or FK descendant,SceneMetricValues,Serialized; field completeness unverified,Pending,Pending +SceneNotes,ProjectID or FK descendant,SceneNotes,Serialized; field completeness unverified,Pending,Pending +SceneNoteTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +SceneOutcomes,ProjectID or FK descendant,SceneOutcomes,Serialized; field completeness unverified,Pending,Pending +ScenePurposes,ProjectID or FK descendant,ScenePurposes,Serialized; field completeness unverified,Pending,Pending +ScenePurposeTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +Scenes,ProjectID or FK descendant,Scenes,Serialized; field completeness unverified,Pending,Pending +SceneTextStatistics,ProjectID or FK descendant,,Pending classification,Pending,Pending +SceneWorkflow,ProjectID or FK descendant,SceneWorkflow,Serialized; field completeness unverified,Pending,Pending +StoryAssets,ProjectID or FK descendant,StoryAssets,Serialized; field completeness unverified,Pending,Pending +StoryIntelligenceBookPipelines,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending +StoryIntelligenceChapterResults,ProjectID or FK descendant,,Pending classification,Pending,Pending +StoryIntelligenceConsents,ProjectID or FK descendant,,Pending classification,Pending,Pending +StoryIntelligenceIllustrationDemands,ProjectID or FK descendant,,Pending classification,Pending,Pending +StoryIntelligenceImportCommits,ProjectID or FK descendant,,Pending classification,Pending,Pending +StoryIntelligenceJobs,ProjectID or FK descendant,,Pending classification,Pending,Pending +StoryIntelligenceNarrativeCandidateEvents,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending +StoryIntelligenceNarrativeCandidateEvidence,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending +StoryIntelligenceNarrativeCandidates,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending +StoryIntelligenceReviewCandidateEvidence,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending +StoryIntelligenceReviewCandidateGenerations,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending +StoryIntelligenceReviewCandidates,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending +StoryIntelligenceRuns,ProjectID or FK descendant,,Pending classification,Pending,Pending +StoryIntelligenceSceneResults,ProjectID or FK descendant,,Persisted SI source/audit/review decisions per runtime contract; omitted; graph coverage pending,Pending,Pending +StoryMaps,ProjectID or FK descendant,StoryMaps,Serialized; initial isolated semantic import comparison passed,Initial import graph compared; same-project restore and broader cases pending,Pending +StoryMemoryAssets,ProjectID or FK descendant,,Pending classification,Pending,Pending +StoryMemoryCharacterAliases,ProjectID or FK descendant,,Pending classification,Pending,Pending +StoryMemoryCharacterAttributes,ProjectID or FK descendant,,Pending classification,Pending,Pending +StoryMemoryCharacters,ProjectID or FK descendant,,Pending classification,Pending,Pending +StoryMemoryIllustrationAssignments,ProjectID or FK descendant,,Pending classification,Pending,Pending +StoryMemoryIllustrationDemands,ProjectID or FK descendant,,Pending classification,Pending,Pending +StoryMemoryImportPreferences,ProjectID or FK descendant,,Pending classification,Pending,Pending +StoryMemoryLocations,ProjectID or FK descendant,,Pending classification,Pending,Pending +StoryMemoryProcessedSceneResults,ProjectID or FK descendant,,Pending classification,Pending,Pending +StoryMemoryRelationships,ProjectID or FK descendant,,Pending classification,Pending,Pending +StripeWebhookEvent,Global/user/independent,,Account/billing/system execution state; excluded from portable project backup,Pending,Pending +SubscriptionAdministrationAudit,Global/user/independent,,Account/billing/system execution state; excluded from portable project backup,Pending,Pending +SubscriptionBookSlotReservation,Global/user/independent,,Account/billing/system execution state; excluded from portable project backup,Pending,Pending +SubscriptionLevel,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +SubscriptionOverride,Global/user/independent,,Account/billing/system execution state; excluded from portable project backup,Pending,Pending +ThreadEvents,ProjectID or FK descendant,ThreadEvents,Serialized; field completeness unverified,Pending,Pending +ThreadEventTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +ThreadStatuses,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +ThreadTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +TimeConfidences,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +TimelineViewPresets,ProjectID or FK descendant,TimelineViewPresets,Serialized; field completeness unverified,Pending,Pending +TimeModes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +UserEmailVerificationToken,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +UserFile,ProjectID or FK descendant,UserFiles,Serialized; field completeness unverified,Pending,Pending +UserLoginAudit,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +UserOnboardingState,ProjectID or FK descendant,,Pending classification,Pending,Pending +UserPasswordResetToken,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +UserSubscription,Global/user/independent,,Account/billing/system execution state; excluded from portable project backup,Pending,Pending +UserTwoFactor,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +ValidationRuns,ProjectID or FK descendant,ValidationRuns,Serialized; field completeness unverified,Pending,Pending +WarningSeverities,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +WarningTypes,Global/user/independent,,Reference/user/system; scope review pending,Pending,Pending +WholeBookPlotSynthesisRuns,ProjectID or FK descendant,,Pending classification,Pending,Pending +WordCompanionSceneAssets,ProjectID or FK descendant,,Pending classification,Pending,Pending +WordCompanionSceneLocations,ProjectID or FK descendant,,Pending classification,Pending,Pending +WritingPlans,ProjectID or FK descendant,,Persistent writer state omitted; synthetic source plan imports as zero plans,Confirmed omission; repair pending,Pending +WritingScheduleItems,ProjectID or FK descendant,,Persistent writer state omitted; synthetic source plan imports as zero plans,Confirmed omission; repair pending,Pending +WritingSolverVersions,Global/user/independent,,Account/billing/system execution state; excluded from portable project backup,Pending,Pending diff --git a/Docs/Sprints/2026-11-03-phase2.md b/Docs/Sprints/2026-11-03-phase2.md index 3ec19d0e..f8bb8b00 100644 --- a/Docs/Sprints/2026-11-03-phase2.md +++ b/Docs/Sprints/2026-11-03-phase2.md @@ -12,17 +12,15 @@ ## Durable queue -1. COMPLETE: Writer connection recovery and distinct window identities; commit 81833c6. -2. COMPLETE: Writer command/re-entry and chapter-goal unsaved navigation tests; urgent Development checkpoint being prepared. -3. NEXT: repair Writer spacing after the verified functional checkpoint and documented live-acceptance deferral. -4. Build rendered page inventory covering all requested areas/modes/themes; capture and inspect screenshots; repair evidenced shared spacing defects. -5. Distinguish Maps/Floor Plans navigation icons. -6. Replace Locations segments with conventional icon/label ribbon commands and depressed active styling. -7. Add established right-edge drag handles and verify both drag modes/accessibility. -8. Build persistent project-entity/file/format inventory against actual schema and backup/restore implementations. -9. Repair backup/restore omissions safely; verify synthetic isolated database round trips, references, assets, transactions and available historical fixtures. -10. Inventory every import/export workflow and its intended fidelity; verify applicable synthetic round trips, compatibility and errors. -11. Final serial build/harness, focused integration/browser/visual checks; safe Development deployment and handover. +1. COMPLETE: Writer recovery, distinct window identities, book-scoped focus/presence, repeated browser/PWA navigation and unsaved chapter-goal protection (81833c6, 408ea95, 735a7d8, 597915f). +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. CURRENT: persistent-data inventory (167 schema tables / 114 project candidates / 55 existing serialized entity sets); initial isolated map/asset/book-metadata/rollback repairs under broader verification. +6. NEXT: extend backed-up authoritative manuscript sources, writing plans and other confirmed persistent omissions; populate and compare all supported entity sets in isolated SQL, including same-project restore, references, assets and failure recovery. Human SI review/audit data is persistent under its runtime contract, not an expendable cache. +7. PENDING: complete table/file classification and historical-backup fixture discovery; do not claim comprehensive backup coverage from the initial map/core cases. +8. PENDING: inventory every import/export workflow and intended fidelity; run applicable synthetic semantic round trips and repair confirmed defects. +9. PENDING: final serial build/harness, focused integration/browser/visual verification; safe Development deployment and concise handover. ## Execution record @@ -34,7 +32,7 @@ Coverage inventories will record tested pages, entities and formats explicitly. ## Deployment -Phase 2 not deployed. Production excluded. No database state changes performed. +Phase 2 not deployed. Production excluded. Running Development database remains unchanged; schema and synthetic fixtures exist only in `PlotDirector_Phase2_20261103_2305`. New migration 213 is verified there only. ### Writer investigation checkpoint @@ -119,3 +117,8 @@ Maximised Maps, Floor Plan Editor and Relationships: 48 cases captured and inspe Isolated SQL round trip reproduced silent map loss: import returned success, but no map appeared in the new project. Added map identity/project/hierarchy remapping, map feature/relationship/journey reference remapping and new GUIDs for copied embedded images/placement references. Verified parent/child maps, geometry JSON, Unicode labels, relationship distance/map references, exact image bytes, changed asset IDs, placement reference and original-project preservation. Eleven invalid JSON/data/map/version preview cases fail before project allocation. Book era and primary locale were also lost; new forward-only migration 213 and metadata projection repair them, verified only in the synthetic database so far. Persistent writing-plan fixture confirms a separate omission (one source plan / zero imported); repair pending. Further reproduced failure atomicity defect: an invalid scene→chapter reference failed SQL restore, but project count increased from 13 to 14, leaving the earlier-created empty shell despite the message saying no data was saved. A transaction around shell creation/remapping/apply is now under isolated verification. No current Development schema/data changes or Phase 2 deployment have occurred. + + +### Import atomicity and graph validation checkpoint + +Reproduced the failed-import shell leak before repair (project count 13→14). An ambient asynchronous transaction now covers shell creation, identity/remapping reads, SQL apply and diagnostics. Isolated verification passed with a real SQL uniqueness failure after allocation: project count remains unchanged, and a subsequent valid import succeeds. Added explicit graph validation for 55 serialized collections / 135 declared persisted and application references, rejecting missing/foreign targets before allocation; these declarations are not a claim that all 55 entity sets have completed semantic round trips. Null collections/records and scalar/array JSON are rejected cleanly. Initial map/asset/hierarchy/book-context comparison and 12 malformed preview cases passed. Broad harness is running. Writing-plan omission remains an explicit separate failing coverage gate; manuscript source text and SI review/audit omissions are now recorded in the schema inventory for subsequent work. diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 4ba122a6..93ffc4a6 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -64,6 +64,13 @@ if (args.Contains("--maps-story-dev-fixture")) await MapStoryDevFixture.RunAsync(args); return; } +if(args.Contains("--project-transfer-database")) +{ + try { await ProjectTransferDatabaseTests.RunAsync(args.Last(), args.Contains("--apply-required-migrations"), args.Contains("--require-writing-plans")); } + catch(Exception error) { Console.Error.WriteLine(error.Message); Environment.ExitCode=1; } + return; +} + if(args.Contains("--maps-appearance-database")){await MapAppearanceDatabaseTests.RunAsync(args.Last());return;} if(args.Contains("--maps-appearance")){MapAppearanceTests.ValidationAndImages();MapAppearanceTests.Access();Console.WriteLine("PASS Maps appearance/image processing, validation, backup and access");return;} diff --git a/PlotLine.Tests/ProjectTransferDatabaseTests.cs b/PlotLine.Tests/ProjectTransferDatabaseTests.cs new file mode 100644 index 00000000..8ea16eff --- /dev/null +++ b/PlotLine.Tests/ProjectTransferDatabaseTests.cs @@ -0,0 +1,129 @@ +using System.Data; +using System.Diagnostics; +using System.Reflection; +using System.Text.Json; +using Dapper; +using Microsoft.Data.SqlClient; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging.Abstractions; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services; +using PlotLine.ViewModels; + +// Explicit specialist mode. Never connects for writes to the running Development database. +internal static class ProjectTransferDatabaseTests +{ + const string Database = "PlotDirector_Phase2_20261103_2305"; + static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); } + static T Proxy(Func handler) where T : class + { var proxy=DispatchProxy.Create();((StoryPointProxy)(object)proxy).Handler=handler;return proxy; } + public static async Task RunAsync(string target, bool applyMigrations = false, bool requireWritingPlans = false) + { + Check(target==Database,"An explicitly named Phase 2 synthetic database is required."); + var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true,RedirectStandardError=true}; + foreach(var arg in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})start.ArgumentList.Add(arg); + using var process=Process.Start(start)!;var settings=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync(); + Check(process.ExitCode==0,"Development connection configuration unavailable."); + var configured=settings.Split('\n').Single(x=>x.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('"','\''); + var builder=new SqlConnectionStringBuilder(configured);Check(builder.InitialCatalog=="PlotDirector_Development","Unexpected source configuration."); + builder.InitialCatalog=target;using var db=new SqlConnection(builder.ConnectionString);await db.OpenAsync(); + Check(await db.ExecuteScalarAsync("SELECT DB_NAME()") == Database,"Synthetic target identity failed."); + var marker=await db.ExecuteScalarAsync("SELECT COUNT(*) FROM sys.extended_properties WHERE class=0 AND name=N'PlotDirector.Phase2.SyntheticOnly' AND CONVERT(nvarchar(20),value)=N'true'"); + if(marker==0) + { + Check(await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.Projects")==0 && await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.AppUser")==0,"Refusing to initialise a populated database."); + await db.ExecuteAsync("EXEC sys.sp_addextendedproperty @name=N'PlotDirector.Phase2.SyntheticOnly',@value=N'true';"); + } + if(applyMigrations) + { + foreach(var file in new[]{"PlotLine/Sql/213_ProjectBackupBookContext.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."); + } + var user=await db.ExecuteScalarAsync("INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+N'@phase2-synthetic.invalid',N'Synthetic author',N'not-an-authentication-credential');SELECT CONVERT(int,SCOPE_IDENTITY());"); + var level=await db.ExecuteScalarAsync("IF NOT EXISTS(SELECT 1 FROM dbo.SubscriptionLevel WHERE Name=N'Phase2Synthetic') INSERT dbo.SubscriptionLevel(Name,DisplayName,MaxBooks,MaxChaptersPerBook,MaxScenesPerBook,MaxCharactersPerProject,MaxStorageMB,MaxCollaborators,SortOrder,RequiresStripeSubscription) VALUES(N'Phase2Synthetic',N'Synthetic test only',1000,1000,10000,10000,10000,100,0,0);SELECT TOP(1) SubscriptionLevelID FROM dbo.SubscriptionLevel WHERE Name=N'Phase2Synthetic';"); + await db.ExecuteAsync("INSERT dbo.UserSubscription(UserID,SubscriptionLevelID,IsActive,IsTrial,TrialExpiryDateUTC) VALUES(@user,@level,1,1,'2030-01-01');",new{user,level}); + var revision=await db.ExecuteScalarAsync("IF NOT EXISTS(SELECT 1 FROM dbo.RevisionStatuses WHERE StatusName=N'Outlined') INSERT dbo.RevisionStatuses(StatusName,SortOrder) VALUES(N'Outlined',0);SELECT TOP(1) RevisionStatusID FROM dbo.RevisionStatuses WHERE StatusName=N'Outlined';"); + var timeMode=await db.ExecuteScalarAsync("IF NOT EXISTS(SELECT 1 FROM dbo.TimeModes WHERE TimeModeName=N'Exact') INSERT dbo.TimeModes(TimeModeName,SortOrder) VALUES(N'Exact',0);SELECT TOP(1) TimeModeID FROM dbo.TimeModes WHERE TimeModeName=N'Exact';"); + var confidence=await db.ExecuteScalarAsync("IF NOT EXISTS(SELECT 1 FROM dbo.TimeConfidences WHERE TimeConfidenceName=N'Known') INSERT dbo.TimeConfidences(TimeConfidenceName,SortOrder) VALUES(N'Known',0);SELECT TOP(1) TimeConfidenceID FROM dbo.TimeConfidences WHERE TimeConfidenceName=N'Known';"); + var configuration=new ConfigurationBuilder().AddInMemoryCollection(new Dictionary{{"ConnectionStrings:DefaultConnection",builder.ConnectionString}}).Build(); + var factory=new SqlConnectionFactory(configuration);var repository=new ImportRepository(factory);var backups=new ProjectBackupRepository(factory); + var project=await repository.CreateProjectShellAsync("Synthetic transfer – 雨 and café", "Synthetic data only: dialogue “Hello”—and Unicode 🖋.", user); + var book=await db.ExecuteScalarAsync("INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder,Subtitle,StoryEra,PrimaryLocaleCode) VALUES(@project,N'Book Ω',1,1,N'Subtitle é',N'Future era',N'en-GB');SELECT CONVERT(int,SCOPE_IDENTITY());",new{project}); + var chapter=await db.ExecuteScalarAsync("INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) VALUES(@book,1.5,N'Chapter 雨',1,@revision);SELECT CONVERT(int,SCOPE_IDENTITY());",new{book,revision}); + var scene=await db.ExecuteScalarAsync("INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,Summary,SortOrder,RevisionStatusID,TimeModeID,TimeConfidenceID) VALUES(@chapter,1.25,N'Scene café',N'“Hello”—雪 🖋',1,@revision,@timeMode,@confidence);SELECT CONVERT(int,SCOPE_IDENTITY());",new{chapter,revision,timeMode,confidence}); + var map=await db.ExecuteScalarAsync("INSERT dbo.StoryMaps(ProjectID,Name,Kind,AppearanceJson) VALUES(@project,N'Synthetic map 雨',N'World',N'{\"preset\":\"paper\"}');SELECT CONVERT(int,SCOPE_IDENTITY());",new{project}); + var maps=new MapRepository(factory); + var image=await maps.AddImageAsync(project,user,MapReferenceImageService.Normalize(MapAppearanceTests.Image(),"synthetic-reference.png")); + var sourceImageBytes=(await maps.GetImageAsync(project,user,image.ImageID))!.ImageData!; + var document=(await maps.GetAsync(project,map,user))!; + document.Map.ReferenceJson=JsonSerializer.Serialize(new MapReferencePlacement { ImageID=image.ImageID, X=15, Y=25, Width=640, Height=480, Rotation=12, Opacity=.45 }); + var first=new MapFeature { MapID=map, Name="Port Ω", Type="Town", X=12, Y=34, LabelX=5, LabelY=6, Notes="Unicode 雨", GeometryJson="{}" }; + var second=new MapFeature { MapID=map, Name="Island 雪", GeometryClass="Area", Type="Island", X=56, Y=78, Width=160, Height=80, GeometryJson="{\"points\":[[0,0],[1,1],[0,1]]}" }; + document.Features=[first,second]; + document.Relationships=[new() { MapID=map, SourceID=first.FeatureID, TargetID=second.FeatureID, Direction="NE", MeasuredDistance=12.5m, Unit="km", Notes="Synthetic relationship café" }]; + await maps.SaveAsync(document,user); + await maps.CreateAsync(new() { ProjectID=project, Name="Child map 雨", Kind="Region", ParentMapID=map, ParentFeatureID=first.FeatureID },user); + var plan=await db.ExecuteScalarAsync("INSERT dbo.WritingPlans(UserID,ProjectID,BookID,PlanName,GoalType,StartDate,DeadlineDate,AvailableDaysJson,SessionLengthMinutes) VALUES(@user,@project,@book,N'Synthetic drafting plan',N'Draft','2026-11-01','2026-12-01',N'[1,3,5]',45);SELECT CONVERT(int,SCOPE_IDENTITY());",new{user,project,book}); + await db.ExecuteAsync("INSERT dbo.WritingScheduleItems(WritingPlanID,SceneID,ScheduledDate,TaskType,ScheduleStatus,Notes) VALUES(@plan,@scene,'2026-11-03',N'Draft',N'Pending',N'Synthetic task café');",new{plan,scene}); + var before=(await backups.GetProjectBackupAsync(project,user))!;Check(before.Project is not null,"Fixture project exported."); + Check(before.Data.Books.Single().BookTitle=="Book Ω" && before.Data.Scenes.Single().Summary=="“Hello”—雪 🖋","Core Unicode export content."); + Console.WriteLine($"Synthetic project {project}: core, map and writing schedule populated; {before.Diagnostics.IncludedEntitySets.Count} advertised backup sets."); + var userService=Proxy((name,args)=>name switch {"get_UserId"=>(int?)user,"get_IsAuthenticated"=>true,"get_Email"=>"phase2-synthetic@example.invalid","get_DisplayName"=>"Synthetic author",_=>throw new NotSupportedException(name)}); + var subscription=Proxy((name,args)=>name switch {"CanUseResourcesAsync"=>Task.FromResult(new EntitlementDecision{Allowed=true}),"ReserveBookSlotsAsync"=>Task.FromResult(new BookSlotReservation{Allowed=true}),_=>throw new NotSupportedException(name)}); + var service=new ImportService(repository,userService,subscription,NullLogger.Instance); + var baselineProjectCount=await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.Projects"); + var sourceJson=JsonSerializer.Serialize(before); + var invalidPayloads=new List{"null","[]","42"}; + foreach(var mutation in new Action[] { + root=>root["Data"]=null, + root=>root["Data"]!["StoryMaps"]=null, + root=>root["Data"]!["MapFeatures"]![0]=null, + root=>root["Data"]!["StoryMaps"]![0]!["ProjectID"]=-1, + root=>root["Data"]!["StoryMaps"]![0]!["ParentMapID"]=-1, + root=>root["Data"]!["MapFeatures"]![0]!["MapID"]=-1, + root=>root["Data"]!["Scenes"]![0]!["ChapterID"]=-12345, + root=>root["Data"]!["MapReferenceImages"]![0]!["ImageData"]="", + root=>root["FormatVersion"]="999.0" + }) + { + var invalid=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!.AsObject();mutation(invalid);invalidPayloads.Add(invalid.ToJsonString()); + } + foreach(var payload in invalidPayloads) + { + var preview=await service.PreviewAsync(new(){JsonText=payload}); + Check(preview.Preview is not null && !preview.Preview.Validation.IsValid,"Invalid map/data payload must fail preview validation."); + } + Check(await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.Projects")==baselineProjectCount,"Invalid previews create no project shells."); + Console.WriteLine($"PASS {invalidPayloads.Count} invalid JSON/map/data/version preview cases before allocation."); + var invalidReference=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!.AsObject(); + var duplicateImage=invalidReference["Data"]!["MapReferenceImages"]![0]!.DeepClone(); + duplicateImage["ImageID"]=Guid.NewGuid().ToString(); + invalidReference["Data"]!["MapReferenceImages"]!.AsArray().Add(duplicateImage); + var failed=await service.ImportAsync(new(){JsonText=invalidReference.ToJsonString(),ConfirmImport=true,AcknowledgeWarnings=true,AllowDuplicateProjectTitle=true}); + Check(!failed.Succeeded,"Invalid cross-entity reference must fail import."); + var afterFailure=await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.Projects"); + Console.WriteLine($"Failure rollback: projects before={baselineProjectCount}, after={afterFailure}."); + Check(afterFailure==baselineProjectCount,"Failed backup import must not retain an empty project shell."); + var result=await service.ImportAsync(new ImportIndexViewModel {JsonText=JsonSerializer.Serialize(before),ConfirmImport=true,AcknowledgeWarnings=true,AllowDuplicateProjectTitle=true}); + Console.WriteLine($"Import result: {result.Succeeded}; {result.Message}; {result.TechnicalDetail}"); + Check(result.Succeeded,"Full project backup import must preserve a synthetic map and core structure."); + var after=(await backups.GetProjectBackupAsync(result.ProjectID!.Value,user))!; + Check(after.Data.StoryMaps.Count==2,"Restored maps are present."); + var restoredMap=after.Data.StoryMaps.Single(x=>x.Name=="Synthetic map 雨"); + Check(restoredMap.MapID!=map && after.Data.StoryMaps.Single(x=>x.Name=="Child map 雨").ParentMapID==restoredMap.MapID,"Map hierarchy is remapped."); + Check(after.Data.MapFeatures.Count==2 && after.Data.MapFeatures.Single(x=>x.Name=="Island 雪").GeometryJson==second.GeometryJson,"Map shapes and Unicode retained."); + Check(after.Data.MapRelationships.Single().MeasuredDistance==12.5m && after.Data.MapRelationships.Single().MapID==restoredMap.MapID,"Map relationship content and map reference retained."); + var restoredImage=after.Data.MapReferenceImages.Single(); + Check(restoredImage.ImageID!=image.ImageID && restoredImage.ImageData!.SequenceEqual(sourceImageBytes),"Embedded image ID remapped and exact bytes retained."); + Check(MapAppearanceJson.Read(restoredMap.ReferenceJson).ImageID==restoredImage.ImageID,"Map image placement references the new embedded asset."); + Check((await maps.GetAsync(project,map,user))!.Map.Name=="Synthetic map 雨","Original project remains unchanged."); + Check(after.Data.Books.Single().StoryEra=="Future era" && after.Data.Books.Single().PrimaryLocaleCode=="en-GB","Book era and locale preserved."); + var restoredPlans=await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.WritingPlans WHERE ProjectID=@id",new{id=result.ProjectID}); + Console.WriteLine($"Writing plan coverage: source=1, imported={restoredPlans}; separate coverage gate."); + if(requireWritingPlans) Check(restoredPlans==1,"Persistent writing plan restored."); + Console.WriteLine("PASS isolated SQL maps/assets/hierarchy and book-context backup/import comparison; other entity coverage remains pending."); + } +} diff --git a/PlotLine/Data/ProjectBackupRepository.cs b/PlotLine/Data/ProjectBackupRepository.cs index 68d70008..fba01202 100644 --- a/PlotLine/Data/ProjectBackupRepository.cs +++ b/PlotLine/Data/ProjectBackupRepository.cs @@ -100,6 +100,9 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact continue; } + book.UsesExplicitScenes = metadata.UsesExplicitScenes; + book.StoryEra = metadata.StoryEra; + book.PrimaryLocaleCode = metadata.PrimaryLocaleCode; book.Subtitle = metadata.Subtitle; book.Tagline = metadata.Tagline; book.ShortDescription = metadata.ShortDescription; diff --git a/PlotLine/Services/ImportServices.cs b/PlotLine/Services/ImportServices.cs index d0b059c4..93f918e4 100644 --- a/PlotLine/Services/ImportServices.cs +++ b/PlotLine/Services/ImportServices.cs @@ -414,6 +414,10 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService try { + using var transaction = new System.Transactions.TransactionScope( + System.Transactions.TransactionScopeOption.Required, + new System.Transactions.TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.Serializable, Timeout = TimeSpan.FromMinutes(5) }, + System.Transactions.TransactionScopeAsyncFlowOption.Enabled); var projectName = preview.HasDuplicateProjectTitle ? preview.DuplicateImportProjectTitle! : preview.Package!.Project.Title; @@ -453,6 +457,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService logger.LogWarning("Imported project {ProjectID} has relationship records that are not compatible with Relationship Map joins. Check relationship import diagnostics for missing endpoint/type/state counts.", projectId); } + transaction.Complete(); return new ImportResult { Succeeded = true, @@ -589,6 +594,12 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService validation.Errors.Add("The project backup does not contain a project name."); } + var mapError = ProjectBackupMapValidation.Validate(backup) ?? ProjectBackupGraphValidation.Validate(backup); + if (mapError is not null) + { + validation.Errors.Add(mapError); + backup = null; + } return true; } @@ -602,6 +613,11 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService CommentHandling = JsonCommentHandling.Skip }); var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object) + { + validation.Errors.Add("The project import must be a JSON object."); + return ProjectImportFormat.Unsupported; + } if (TryGetString(root, "format", out var format) || TryGetString(root, "Format", out format)) @@ -786,7 +802,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService private static readonly string[] ProjectBackupIdentityTables = [ - "ProjectTimelineSettings", "TimelineViewPresets", "SceneMetricTypes", "Books", "Chapters", "Scenes", + "ProjectTimelineSettings", "TimelineViewPresets", "SceneMetricTypes", "Books", "Chapters", "Scenes", "StoryMaps", "SceneOutcomes", "PlotLines", "PlotThreads", "ThreadEvents", "AssetStates", "StoryAssets", "AssetEvents", "AssetDependencies", "AssetCustodyEvents", "AssetCustodyEventCharacters", "Characters", "SceneCharacters", "CharacterAttributeTypes", "CharacterAttributeEvents", "CharacterKnowledge", "CharacterRelationships", @@ -1334,6 +1350,47 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService warning.SceneID = ExistingOrNewNullable("Scenes", warning.SceneID); warning.EntityID = RemapPolymorphicEntityID(warning.EntityType, warning.EntityID, ExistingOrNewNullable); } + // Map IDs share database identity space; embedded assets use globally unique IDs. + // Register all maps first so child maps can refer to parents in either export order. + foreach (var map in backup.Data.StoryMaps) + { + map.MapID = NewId("StoryMaps", map.MapID); + map.ProjectID = projectId; + } + var imageIds = new Dictionary(); + foreach (var image in backup.Data.MapReferenceImages) + { + var oldId = image.ImageID; + image.ImageID = Guid.NewGuid(); + image.ProjectID = projectId; + imageIds.Add(oldId, image.ImageID); + } + foreach (var map in backup.Data.StoryMaps) + { + map.ParentMapID = ExistingOrNewNullable("StoryMaps", map.ParentMapID); + var placement = MapAppearanceJson.Read(map.ReferenceJson); + if (placement.ImageID.HasValue) + { + var reference = System.Text.Json.Nodes.JsonNode.Parse(map.ReferenceJson, new System.Text.Json.Nodes.JsonNodeOptions { PropertyNameCaseInsensitive = true })!.AsObject(); + reference["imageID"] = imageIds[placement.ImageID.Value].ToString(); + map.ReferenceJson = reference.ToJsonString(); + } + } + foreach (var feature in backup.Data.MapFeatures) + { + feature.MapID = ExistingOrNew("StoryMaps", feature.MapID); + feature.LocationID = ExistingOrNewNullable("Locations", feature.LocationID); + feature.FloorPlanID = ExistingOrNewNullable("FloorPlans", feature.FloorPlanID); + } + foreach (var relationship in backup.Data.MapRelationships) + relationship.MapID = ExistingOrNew("StoryMaps", relationship.MapID); + foreach (var note in backup.Data.MapJourneyNotes) + { + note.MapID = ExistingOrNew("StoryMaps", note.MapID); + note.CharacterID = ExistingOrNew("Characters", note.CharacterID); + note.FromSceneID = ExistingOrNew("Scenes", note.FromSceneID); + note.ToSceneID = ExistingOrNew("Scenes", note.ToSceneID); + } } private static int? RemapPolymorphicEntityID(string? entityType, int? entityId, Func remap) diff --git a/PlotLine/Services/ProjectBackupGraphValidation.cs b/PlotLine/Services/ProjectBackupGraphValidation.cs new file mode 100644 index 00000000..986763ac --- /dev/null +++ b/PlotLine/Services/ProjectBackupGraphValidation.cs @@ -0,0 +1,90 @@ +using System.Collections; +using PlotLine.Models; +namespace PlotLine.Services; + +// Explicit persisted relationships for the current serialized entity sets, not inferred author names. +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("AssetCustodyCharacters", "AssetCustodyEventCharacterID", new Link("AssetCustodyEventID", "AssetCustodyEvents", "AssetCustodyEventID"), new Link("CharacterID", "Characters", "CharacterID")), + new("AssetCustodyEvents", "AssetCustodyEventID", new Link("SceneID", "Scenes", "SceneID"), new Link("StoryAssetID", "StoryAssets", "StoryAssetID")), + new("AssetDependencies", "AssetDependencyID", new Link("SourceAssetID", "StoryAssets", "StoryAssetID"), new Link("SourceRequiredStateID", "AssetStates", "AssetStateID"), new Link("TargetAssetID", "StoryAssets", "StoryAssetID"), new Link("TargetBlockedStateID", "AssetStates", "AssetStateID")), + new("AssetEvents", "AssetEventID", new Link("FromStateID", "AssetStates", "AssetStateID"), new Link("SceneID", "Scenes", "SceneID"), new Link("StoryAssetID", "StoryAssets", "StoryAssetID"), new Link("ToStateID", "AssetStates", "AssetStateID")), + new("AssetStates", "AssetStateID", new Link("ProjectID", "Project", "ProjectID")), + new("Books", "BookID", new Link("ProjectID", "Project", "ProjectID")), + new("ChapterGoals", "ChapterGoalID", new Link("ChapterID", "Chapters", "ChapterID")), + new("Chapters", "ChapterID", new Link("BookID", "Books", "BookID"), new Link("POVCharacterID", "Characters", "CharacterID")), + new("CharacterAttributeEvents", "CharacterAttributeEventID", new Link("CharacterAttributeTypeID", "CharacterAttributeTypes", "CharacterAttributeTypeID"), new Link("CharacterID", "Characters", "CharacterID"), new Link("SceneID", "Scenes", "SceneID")), + new("CharacterAttributeTypes", "CharacterAttributeTypeID", new Link("ProjectID", "Project", "ProjectID")), + new("CharacterKnowledge", "CharacterKnowledgeID", new Link("CharacterID", "Characters", "CharacterID"), new Link("PlotThreadID", "PlotThreads", "PlotThreadID"), new Link("SceneID", "Scenes", "SceneID"), new Link("SourceEventID", "ThreadEvents", "ThreadEventID"), new Link("StoryAssetID", "StoryAssets", "StoryAssetID")), + new("CharacterRelationships", "CharacterRelationshipID", new Link("CharacterAID", "Characters", "CharacterID"), new Link("CharacterBID", "Characters", "CharacterID"), new Link("EndSceneID", "Scenes", "SceneID"), new Link("InitialBookID", "Books", "BookID"), new Link("ProjectID", "Project", "ProjectID"), new Link("StartSceneID", "Scenes", "SceneID")), + new("Characters", "CharacterID", new Link("AgeReferenceSceneID", "Scenes", "SceneID"), new Link("ProjectID", "Project", "ProjectID")), + new("ContinuityWarnings", "ContinuityWarningID", new Link("BookID", "Books", "BookID"), new Link("ChapterID", "Chapters", "ChapterID"), new Link("ProjectID", "Project", "ProjectID"), new Link("SceneID", "Scenes", "SceneID"), new Link("ValidationRunID", "ValidationRuns", "ValidationRunID")), + new("FloorPlanBlocks", "FloorPlanBlockID", new Link("FloorPlanFloorID", "FloorPlanFloors", "FloorPlanFloorID"), new Link("LocationID", "Locations", "LocationID")), + new("FloorPlanFloors", "FloorPlanFloorID", new Link("FloorPlanID", "FloorPlans", "FloorPlanID"), new Link("LocationID", "Locations", "LocationID")), + new("FloorPlanTransitions", "FloorPlanTransitionID", new Link("FloorPlanFloorID", "FloorPlanFloors", "FloorPlanFloorID"), new Link("FromLocationID", "Locations", "LocationID"), new Link("ToLocationID", "Locations", "LocationID")), + new("FloorPlans", "FloorPlanID", new Link("LocationID", "Locations", "LocationID"), new Link("ProjectID", "Project", "ProjectID")), + new("GenreMetricPresetMetrics", null, new Link("GenreMetricPresetID", "GenreMetricPresets", "GenreMetricPresetID"), new Link("MetricTypeID", "SceneMetricTypes", "MetricTypeID")), + new("GenreMetricPresets", "GenreMetricPresetID"), + new("LocationRelationships", "LocationRelationshipID", new Link("FromLocationID", "Locations", "LocationID"), new Link("ToLocationID", "Locations", "LocationID")), + new("Locations", "LocationID", new Link("ParentLocationID", "Locations", "LocationID"), new Link("ProjectID", "Project", "ProjectID")), + new("MapFeatures", null, new Link("FloorPlanID", "FloorPlans", "FloorPlanID"), new Link("LocationID", "Locations", "LocationID"), new Link("MapID", "StoryMaps", "MapID")), + new("MapJourneyNotes", null, new Link("CharacterID", "Characters", "CharacterID"), new Link("FromSceneID", "Scenes", "SceneID"), new Link("MapID", "StoryMaps", "MapID"), new Link("ToSceneID", "Scenes", "SceneID")), + new("MapReferenceImages", null, new Link("ProjectID", "Project", "ProjectID")), + new("MapRelationships", null, new Link("MapID", "MapFeatures", "MapID"), new Link("MapID", "StoryMaps", "MapID"), new Link("SourceID", "MapFeatures", "FeatureID"), new Link("TargetID", "MapFeatures", "FeatureID")), + new("PlotLines", "PlotLineID", new Link("BookID", "Books", "BookID"), new Link("EmergesFromPlotLineID", "PlotLines", "PlotLineID"), new Link("ParentPlotLineID", "PlotLines", "PlotLineID"), new Link("ProjectID", "Project", "ProjectID")), + new("PlotThreads", "PlotThreadID", new Link("ActualResolutionSceneID", "Scenes", "SceneID"), new Link("IntroducedSceneID", "Scenes", "SceneID"), new Link("PlannedResolutionSceneID", "Scenes", "SceneID"), new Link("PlotLineID", "PlotLines", "PlotLineID")), + new("TimelineMetricSettings", null, new Link("MetricTypeID", "SceneMetricTypes", "MetricTypeID"), new Link("ProjectID", "Project", "ProjectID")), + new("TimelineSettings", "ProjectTimelineSettingsID", new Link("ProjectID", "Project", "ProjectID")), + new("ProjectAccess", "ProjectUserAccessID", new Link("ProjectID", "Project", "ProjectID")), + new("RelationshipEvents", "RelationshipEventID", new Link("CharacterAID", "Characters", "CharacterID"), new Link("CharacterBID", "Characters", "CharacterID"), new Link("CharacterRelationshipID", "CharacterRelationships", "CharacterRelationshipID"), new Link("SceneID", "Scenes", "SceneID")), + new("ScenarioSceneOrder", "ScenarioSceneOrderID", new Link("ProposedChapterID", "Chapters", "ChapterID"), new Link("ScenarioID", "Scenarios", "ScenarioID"), new Link("SceneID", "Scenes", "SceneID")), + new("ScenarioValidationRuns", "ScenarioValidationRunID", new Link("ScenarioID", "Scenarios", "ScenarioID")), + new("ScenarioWarnings", "ScenarioWarningID", new Link("ScenarioID", "Scenarios", "ScenarioID"), new Link("ScenarioValidationRunID", "ScenarioValidationRuns", "ScenarioValidationRunID"), new Link("SceneID", "Scenes", "SceneID")), + new("Scenarios", "ScenarioID", new Link("BookID", "Books", "BookID"), new Link("ProjectID", "Project", "ProjectID")), + new("SceneAssetLocations", "SceneAssetLocationID", new Link("LocationID", "Locations", "LocationID"), new Link("SceneID", "Scenes", "SceneID"), new Link("StoryAssetID", "StoryAssets", "StoryAssetID")), + new("SceneAttachments", "SceneAttachmentID", new Link("SceneID", "Scenes", "SceneID")), + new("SceneCharacters", "SceneCharacterID", new Link("CharacterID", "Characters", "CharacterID"), new Link("EntryLocationID", "Locations", "LocationID"), new Link("ExitLocationID", "Locations", "LocationID"), new Link("LocationID", "Locations", "LocationID"), new Link("SceneID", "Scenes", "SceneID")), + new("SceneChecklistItems", "SceneChecklistItemID", new Link("SceneID", "Scenes", "SceneID")), + new("SceneDependencies", "SceneDependencyID", new Link("SourceSceneID", "Scenes", "SceneID"), new Link("TargetSceneID", "Scenes", "SceneID")), + new("SceneFloorPlanOccupancy", "SceneFloorPlanOccupancyID", new Link("CharacterID", "Characters", "CharacterID"), new Link("FloorPlanFloorID", "FloorPlanFloors", "FloorPlanFloorID"), new Link("FloorPlanID", "FloorPlans", "FloorPlanID"), new Link("LocationID", "Locations", "LocationID"), new Link("SceneID", "Scenes", "SceneID"), new Link("StoryAssetID", "StoryAssets", "StoryAssetID")), + new("SceneMetricTypes", "MetricTypeID", new Link("ProjectID", "Project", "ProjectID")), + new("SceneMetricValues", null, new Link("MetricTypeID", "SceneMetricTypes", "MetricTypeID"), new Link("SceneID", "Scenes", "SceneID")), + new("SceneNotes", "SceneNoteID", new Link("SceneID", "Scenes", "SceneID")), + new("SceneOutcomes", "SceneOutcomeID", new Link("SceneID", "Scenes", "SceneID")), + new("ScenePurposes", null, new Link("SceneID", "Scenes", "SceneID")), + new("SceneWorkflow", "SceneWorkflowID", new Link("SceneID", "Scenes", "SceneID")), + new("Scenes", "SceneID", new Link("ChapterID", "Chapters", "ChapterID"), new Link("FloorPlanID", "FloorPlans", "FloorPlanID"), new Link("InitialFloorPlanFloorID", "FloorPlanFloors", "FloorPlanFloorID"), new Link("POVCharacterID", "Characters", "CharacterID"), new Link("PrimaryLocationID", "Locations", "LocationID")), + new("StoryAssets", "StoryAssetID", new Link("CurrentLocationID", "Locations", "LocationID"), new Link("CurrentStateID", "AssetStates", "AssetStateID"), new Link("ProjectID", "Project", "ProjectID")), + new("StoryMaps", "MapID", new Link("ParentMapID", "StoryMaps", "MapID"), new Link("ProjectID", "Project", "ProjectID")), + new("ThreadEvents", "ThreadEventID", new Link("PlotLineID", "PlotLines", "PlotLineID"), new Link("PlotThreadID", "PlotThreads", "PlotThreadID"), new Link("SceneID", "Scenes", "SceneID"), new Link("TargetPlotLineID", "PlotLines", "PlotLineID")), + new("TimelineViewPresets", "TimelineViewPresetID", new Link("BookID", "Books", "BookID"), new Link("ProjectID", "Project", "ProjectID")), + new("UserFiles", "UserFileID", new Link("ProjectID", "Project", "ProjectID")), + new("ValidationRuns", "ValidationRunID", new Link("BookID", "Books", "BookID"), new Link("ProjectID", "Project", "ProjectID")) + ]; + public static string? Validate(ProjectBackupExport backup) + { + if(backup.Project is null || backup.Project.ProjectID<=0) return "Project backup contains an invalid source project identifier."; + var rows=Entities.ToDictionary(entity=>entity.Collection,entity=>((IEnumerable)typeof(ProjectBackupData).GetProperty(entity.Collection)!.GetValue(backup.Data)!).Cast().ToArray()); + object? Value(object row,string column)=>row.GetType().GetProperty(column)?.GetValue(row); + foreach(var entity in Entities) + { + if(entity.Identity is not null) + { + var ids=rows[entity.Collection].Select(row=>Value(row,entity.Identity)).ToArray(); + if(ids.Any(id=>id is null || id is int integer && integer<=0 || id is long wide && wide<=0) || ids.Distinct().Count()!=ids.Length) + return $"Project backup contains duplicate or missing {entity.Collection} identifiers."; + } + foreach(var link in entity.Links) + { + var allowed=link.TargetCollection=="Project" ? new HashSet { backup.Project.ProjectID } + : rows[link.TargetCollection].Select(row=>Value(row,link.TargetColumn)).Where(value=>value is not null).ToHashSet(); + if(rows[entity.Collection].Any(row=>Value(row,link.Column) is object value && !allowed.Contains(value))) + return $"Project backup {entity.Collection}.{link.Column} references a missing or foreign {link.TargetCollection} record."; + } + } + return null; + } +} diff --git a/PlotLine/Services/ProjectBackupMapValidation.cs b/PlotLine/Services/ProjectBackupMapValidation.cs new file mode 100644 index 00000000..08a8807c --- /dev/null +++ b/PlotLine/Services/ProjectBackupMapValidation.cs @@ -0,0 +1,54 @@ +using PlotLine.Models; + +namespace PlotLine.Services; + +// Validate the exported graph before allocating a new project or remapping any identifiers. +internal static class ProjectBackupMapValidation +{ + public static string? Validate(ProjectBackupExport backup) + { + if (backup.Data is null || typeof(ProjectBackupData).GetProperties().Any(property => property.GetValue(backup.Data) is null)) + return "Project backup data contains a null entity collection."; + var data=backup.Data; + if (typeof(ProjectBackupData).GetProperties().Any(property => ((System.Collections.IEnumerable)property.GetValue(data)!).Cast().Any(item=>item is null))) + return "Project backup contains a null entity record."; + if(data.MapFeatures.Any(x=>x.Type is null || x.Layer is null || x.GeometryJson is null)) return "Project backup contains invalid map feature fields."; + if (data.StoryMaps.Any(x=>x is null) || data.MapFeatures.Any(x=>x is null) || data.MapRelationships.Any(x=>x is null) + || data.MapJourneyNotes.Any(x=>x is null) || data.MapReferenceImages.Any(x=>x is null)) + return "Project backup contains a null map record."; + var mapIds=data.StoryMaps.Select(x=>x.MapID).ToHashSet(); + if(mapIds.Count!=data.StoryMaps.Count || mapIds.Any(id=>id<=0)) return "Project backup map identifiers must be positive and unique."; + var imageIds=data.MapReferenceImages.Select(x=>x.ImageID).ToHashSet(); + if(imageIds.Count!=data.MapReferenceImages.Count || imageIds.Contains(Guid.Empty)) return "Project backup reference image identifiers must be unique."; + if(data.MapReferenceImages.Any(image=>image.ProjectID!=backup.Project?.ProjectID || !MapReferenceImageService.ValidBackupImage(image))) + return "Project backup contains invalid or foreign reference images."; + var maps=data.StoryMaps.ToDictionary(x=>x.MapID); + foreach(var map in data.StoryMaps) + { + if(map.ProjectID!=backup.Project?.ProjectID) return "Project backup contains a map belonging to another project."; + var error=MapValidation.Validate(new() { Map=map, Features=data.MapFeatures.Where(x=>x.MapID==map.MapID).ToList(), Relationships=data.MapRelationships.Where(x=>x.MapID==map.MapID).ToList() }); + if(error is not null) return "Project backup map is invalid: "+error; + var placement=MapAppearanceJson.Read(map.ReferenceJson); + if(placement.ImageID.HasValue && !imageIds.Contains(placement.ImageID.Value)) return "Project backup map references a missing image."; + if(map.ParentMapID.HasValue && !mapIds.Contains(map.ParentMapID.Value)) return "Project backup map references a missing parent map."; + if(map.ParentFeatureID.HasValue && (!map.ParentMapID.HasValue || !data.MapFeatures.Any(x=>x.MapID==map.ParentMapID && x.FeatureID==map.ParentFeatureID))) + return "Project backup map references a missing parent feature."; + var visited=new HashSet();var current=map; + while(current.ParentMapID.HasValue) + { + if(!visited.Add(current.MapID)) return "Project backup map hierarchy contains a cycle."; + if(!maps.TryGetValue(current.ParentMapID.Value,out var parent)) return "Project backup map references a missing parent map."; + current=parent; + } + } + var locations=data.Locations.Select(x=>x.LocationID).ToHashSet();var floors=data.FloorPlans.Select(x=>x.FloorPlanID).ToHashSet(); + if(data.MapFeatures.Any(x=>!mapIds.Contains(x.MapID) || x.LocationID.HasValue&&!locations.Contains(x.LocationID.Value) || x.FloorPlanID.HasValue&&!floors.Contains(x.FloorPlanID.Value))) + return "Project backup map feature references a missing map, location or floor plan."; + if(data.MapRelationships.Any(x=>!mapIds.Contains(x.MapID))) return "Project backup relationship references a missing map."; + var scenes=data.Scenes.Select(x=>x.SceneID).ToHashSet();var characters=data.Characters.Select(x=>x.CharacterID).ToHashSet(); + if(data.MapJourneyNotes.Any(x=>!mapIds.Contains(x.MapID) || !characters.Contains(x.CharacterID) || !scenes.Contains(x.FromSceneID) || !scenes.Contains(x.ToSceneID) + || x.RouteFeatureID.HasValue&&!data.MapFeatures.Any(f=>f.MapID==x.MapID && f.FeatureID==x.RouteFeatureID && f.GeometryClass=="Path"))) + return "Project backup journey references a missing map, character, scene or route."; + return null; + } +} diff --git a/PlotLine/Sql/213_ProjectBackupBookContext.sql b/PlotLine/Sql/213_ProjectBackupBookContext.sql new file mode 100644 index 00000000..295ea4de --- /dev/null +++ b/PlotLine/Sql/213_ProjectBackupBookContext.sql @@ -0,0 +1,16 @@ +-- Preserve persistent book context added after the original backup metadata projection. +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +CREATE OR ALTER PROCEDURE dbo.ProjectBackup_BookMetadata_List + @ProjectID int +AS +BEGIN + SET NOCOUNT ON; + SELECT BookID, Subtitle, Tagline, ShortDescription, Status, TargetWordCount, + WritingStartDate, TargetCompletionDate, PublicationDate, CoverThumbnailPath, CoverStandardPath, + UsesExplicitScenes, StoryEra, PrimaryLocaleCode + FROM dbo.Books + WHERE ProjectID = @ProjectID; +END; +GO