fix: refuse inferred defaults for absent stored backup fields

This commit is contained in:
Nick Beckley 2026-11-04 08:42:36 +00:00
parent 20be2c792d
commit e7e71de1c4
10 changed files with 1717 additions and 2 deletions

File diff suppressed because it is too large Load Diff

View File

@ -386,3 +386,17 @@ Restore now verifies the complete stored safety snapshot, compares original coll
Actual service matrix passed all 103 independently metadata/SQL-owned collection omissions with exact original data/file-byte equality. Any safety point created was read back and compared for complete data. Camel-case and three required-header cases passed; explicit empty remains a valid historical state. An observed-and-forwarded real repository/SQL call confirmed that a safely absent unused category remains absent after staging. Copy warning, required-header and lenient-JSON preview checks passed. These are synthetic compatibility shapes, not historical backup fixtures. Inventory `2026-11-03-phase2-restore-omission-coverage.csv`; evidence `/tmp/plotdirector-phase2-service-omission-matrix.log`.
Checkpoint: build zero warnings/errors; complete 103-collection transfer/safety/rollback/account matrix passed (`/tmp/plotdirector-phase2-transfer-service-presence.log`); all 405 regression checks passed (`/tmp/plotdirector-phase2-tests-service-presence.log`). No migration or Development/Production writes. Next check: field-level default inference in older-shaped rows, distinct from absent collections. No historical full-backup compatibility claim.
## Stored-field presence before restore defaults — 4 November
Confirmed the same inference defect inside a row: a real service restore from a synthetic snapshot lacking Books.StoryEra succeeded and replaced its stored `Future era` value with NULL (`/tmp/plotdirector-phase2-service-field-before.log`). Collection presence alone could not prevent this. The repaired real service refusal retains the entire original data state before allocation (`/tmp/plotdirector-phase2-service-field-fixed.log`).
Added a compiled stored-field contract generated from the independently audited schema CSV (104 restored entities / 1,351 non-computed columns before explicit JSON/audit semantics). It avoids treating UI-only model properties as persisted requirements. Computed/derived and diagnostic permission/quota categories are excluded; explicitly global lookup rows are retained rather than overwritten. Root UpdatedDate is server-maintained, while the existing version-1.2 root audit replay is handled conditionally. Nullable values remain valid when explicitly present. Omitted stored fields refuse same-project restore instead of acquiring DTO defaults. New-copy preview can recover supplied data with a clear existing warning acknowledgement that absent field values cannot be reconstructed.
The generator is `PlotLine.Tests/Tools/generate-backup-field-contract.py`: first produce the verified synthetic `--schema-coverage-only` inventory, regenerate, review its diff, build and run the field gate. Regeneration was byte-for-byte deterministic. No production schema reflection, inline application SQL, database option/permission changes or new migration.
The specialist matrix derived its field universe from actual synthetic sys.columns and public model serialization attributes, independently of the generated requirement list. All 1,353 cases passed before safety/write allocation, including the four conditional legacy audit fields, camel-case and a later record. Fast per-field probes use repository/safety observers to prove allocation was not attempted; the original era regression and the complete explicit-null positive restore use the real repositories/SQL/files. The first later-record test mistakenly selected a non-stored word-count property; corrected to actual Scenes.Summary and asserted removal before testing. That fixture mistake was not treated as a production defect. Inventory `2026-11-03-phase2-stored-field-omission-coverage.csv`; final evidence `/tmp/plotdirector-phase2-stored-fields-later-row.log` and build log of the same prefix.
These are current-schema and synthetic older-shaped validations. They cannot recover values an old writer never saved, and are not proof that historical backup files are complete. Actual historical fixtures remain unavailable. Collection/full-transfer/regression gates are being rerun before commit.
Stored-field final checkpoint: all 103 actual collection-service omission cases passed again (`/tmp/plotdirector-phase2-collections-stored-fields.log`), followed by the full 103-collection copy/in-place/safety/rollback/account matrix (`/tmp/plotdirector-phase2-transfer-stored-fields.log`) and all 405 executable regressions (`/tmp/plotdirector-phase2-tests-stored-fields.log`), exit 0. Final field matrix: 1,353 cases including later stored summary and camel-case; actual complete explicit-null restore succeeded. Build zero warnings/errors. Completed verification/reproduction logs are also retained under `/srv/repos/plotdirector-phase2-artifacts/verification/`.

View File

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

View File

@ -0,0 +1,100 @@
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using Dapper;
using Microsoft.Extensions.Logging.Abstractions;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
internal static class ProjectBackupStoredFieldTests
{
private sealed class Column
{
public string TableName {get;set;}="";
public string ColumnName {get;set;}="";
public bool IsNullable {get;set;}
public bool IsComputed {get;set;}
}
private static void Check(bool condition,string message){if(!condition)throw new InvalidOperationException(message);}
private static T Proxy<T>(Func<string,object?[]?,object?> handler) where T:class
{var result=DispatchProxy.Create<T,StoryPointProxy>();((StoryPointProxy)(object)result).Handler=handler;return result;}
internal static async Task RunAsync(ISqlConnectionFactory factory,IProjectBackupFiles files,int owner,int project,ProjectBackupExport before,IReadOnlyDictionary<string,int> owned,IProjectRestoreService actual,IProjectRestorePointRepository repository)
{
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,"Stored-field fixture requires marked synthetic database.");
var aliases=new Dictionary<string,string>{{"Project","Projects"},{"TimelineSettings","ProjectTimelineSettings"},{"TimelineMetricSettings","ProjectTimelineMetricSettings"},{"AssetCustodyCharacters","AssetCustodyEventCharacters"}};
var collections=owned.Where(pair=>pair.Value>0 && pair.Key is not ("UserFiles" or "ProjectAccess")).Select(pair=>pair.Key).ToArray();
var tables=collections.Select(name=>aliases.GetValueOrDefault(name,name)).ToArray();
var columns=(await db.QueryAsync<Column>("SELECT t.name AS TableName,c.name AS ColumnName,c.is_nullable AS IsNullable,c.is_computed AS IsComputed FROM sys.tables t JOIN sys.columns c ON c.object_id=t.object_id WHERE SCHEMA_NAME(t.schema_id)=N'dbo' AND t.name IN @tables ORDER BY t.name,c.column_id",new{tables})).Where(column=>!column.IsComputed).GroupBy(column=>column.TableName).ToDictionary(group=>group.Key,group=>group.ToArray());
var original=JsonSerializer.Serialize(before);string? probe=null;var safetyAttempts=0;var writes=0;
var source=Proxy<IProjectRestorePointRepository>((name,args)=>name switch
{
"GetAsync"=>Task.FromResult<ProjectRestorePoint?>(new(){ProjectRestorePointID=123,ProjectID=project,RestorePointName="Stored-field preflight probe",JsonData=probe}),
"RestoreAsync"=>Write(),
_=>throw new NotSupportedException(name)
});
Task Write(){writes++;throw new InvalidOperationException("Malformed field reached SQL mutation.");}
var safety=Proxy<IProjectRestorePointService>((name,args)=>name=="CreatePreRestoreAsync" ? Safety() : throw new NotSupportedException(name));
Task<ProjectRestorePoint?> Safety(){safetyAttempts++;return Task.FromResult<ProjectRestorePoint?>(null);}
var guarded=new ProjectRestoreService(source,safety,NullLogger<ProjectRestoreService>.Instance,files);
var coverage=new List<string>{"Collection,Column,Execution,Result"};
var audit=new HashSet<string>(StringComparer.OrdinalIgnoreCase){"CreatedByUserID","ModifiedByUserID","CreatedDateUTC","ModifiedDateUTC"};
foreach(var collection in collections)
{
var model=collection=="Project" ? typeof(Project) : typeof(ProjectBackupData).GetProperty(collection)!.PropertyType.GetGenericArguments().Single();
var full=JsonNode.Parse(original)!;
var rowIndex=0;
if(collection!="Project")
{
var rows=full["Data"]![collection]!.AsArray();
rowIndex=rows.Select((row,index)=>(row,index)).OrderByDescending(pair=>pair.row?["ProjectID"] is JsonValue value && value.TryGetValue<int>(out var id) && id==project).First().index;
}
foreach(var column in columns[aliases.GetValueOrDefault(collection,collection)])
{
if(collection=="Project" && (column.ColumnName=="UpdatedDate" || audit.Contains(column.ColumnName)))continue;
var member=model.GetProperty(column.ColumnName,BindingFlags.Public|BindingFlags.Instance|BindingFlags.IgnoreCase)!;
var ignore=member.GetCustomAttribute<JsonIgnoreAttribute>();
if(ignore?.Condition==JsonIgnoreCondition.Always || ignore?.Condition==JsonIgnoreCondition.WhenWritingDefault
|| ignore?.Condition==JsonIgnoreCondition.WhenWritingNull && column.IsNullable)continue;
var wire=member.GetCustomAttribute<JsonPropertyNameAttribute>()?.Name ?? member.Name;
var changed=JsonNode.Parse(original)!;
var row=collection=="Project" ? changed["Project"]!.AsObject() : changed["Data"]![collection]![rowIndex]!.AsObject();
Check(row.Remove(wire),"Current complete backup serializes stored field "+collection+"."+wire);
probe=changed.ToJsonString();var attempts=safetyAttempts;
var result=await guarded.RestoreAsync(project,123);
Check(!result.Succeeded && safetyAttempts==attempts && writes==0,"Missing "+collection+"."+wire+" is refused before safety/write allocation.");
coverage.Add($"{collection},{column.ColumnName},Actual service preflight + independent SQL field metadata,Refused before allocation");
}
}
var second=JsonNode.Parse(original)!;Check(second["Data"]!["Scenes"]!.AsArray().Count>1,"Later-row omission fixture has multiple scenes.");
Check(second["Data"]!["Scenes"]![1]!.AsObject().Remove("Summary"),"Later-row probe removes a stored scene field.");probe=second.ToJsonString();var prior=safetyAttempts;
Check(!(await guarded.RestoreAsync(project,123)).Succeeded && safetyAttempts==prior && writes==0,"Stored-field checking covers records after the first row.");
coverage.Add("Scenes,Summary (second row),Actual service preflight,Refused before allocation");
var camel=JsonNode.Parse(JsonSerializer.Serialize(before,new JsonSerializerOptions{PropertyNamingPolicy=JsonNamingPolicy.CamelCase}))!;
camel["data"]!["books"]![0]!.AsObject().Remove("storyEra");probe=camel.ToJsonString();prior=safetyAttempts;
Check(!(await guarded.RestoreAsync(project,123)).Succeeded && safetyAttempts==prior && writes==0,"Stored-field presence is case insensitive.");
coverage.Add("Books,StoryEra (camel case),Actual service preflight,Refused before allocation");
foreach(var field in audit)
{
var changed=JsonNode.Parse(original)!;changed["FormatVersion"]="1.2";changed["Project"]!.AsObject().Remove(field);probe=changed.ToJsonString();var attempts=safetyAttempts;
var result=await guarded.RestoreAsync(project,123);
Check(!result.Succeeded && safetyAttempts==attempts && writes==0,"Legacy project audit field is required when SQL restores it: "+field);
coverage.Add($"Project,{field} (version 1.2),Actual service preflight,Refused before allocation");
}
var user=Proxy<ICurrentUserService>((name,args)=>name=="get_UserId" ? (int?)owner : throw new NotSupportedException(name));
var subscriptions=Proxy<ISubscriptionService>((name,args)=>name=="CanUseResourcesAsync" ? Task.FromResult(new EntitlementDecision{Allowed=true}) : throw new NotSupportedException(name));
var import=new ImportService(new ImportRepository(factory),user,subscriptions,NullLogger<ImportService>.Instance,files);
var partial=JsonNode.Parse(original)!;partial["Data"]!["Books"]![0]!.AsObject().Remove("StoryEra");
var preview=await import.PreviewAsync(new(){JsonText=partial.ToJsonString()});
Check(preview.Preview!.Validation.IsValid && preview.Preview.Validation.Warnings.Any(message=>message.Contains("stored project fields",StringComparison.Ordinal)),"Partial new-copy preview explicitly warns about missing stored fields.");
// Null is declared state; absence must not be guessed as null.
var explicitNull=JsonNode.Parse(original)!;explicitNull["Data"]!["Books"]![0]!["StoryEra"]=null;
var point=await repository.CreateAsync(project,"Synthetic explicit null era","Manual",explicitNull.ToJsonString(),"Explicit null is intentional, not absent.");
var restored=await actual.RestoreAsync(project,point.ProjectRestorePointID);
Check(restored.Succeeded && (await new ProjectBackupRepository(factory).GetProjectBackupAsync(project,owner))!.Data.Books.First().StoryEra is null,"Complete current snapshot with explicitly null metadata restores successfully.");
await File.WriteAllLinesAsync("Docs/Sprints/2026-11-03-phase2-stored-field-omission-coverage.csv",coverage);
Console.WriteLine($"PASS {coverage.Count-1} independently SQL-derived stored-field omissions refused before mutation/allocation; legacy audit semantics; partial-copy warning; actual complete explicit-null restore.");
}
}

View File

@ -28,6 +28,17 @@ internal static class ProjectRestoreOmissionTests
var before=(await backups.GetProjectBackupAsync(project,owner))!;await files.CaptureAsync(before);
var counts=await ProjectTransferOwnedRowCensus.VerifyAsync((SqlConnection)db,before,false);
var original=JsonSerializer.Serialize(before);var dataBefore=JsonSerializer.Serialize(before.Data);
if(Environment.GetCommandLineArgs().Contains("--restore-field-omission-only"))
{
var source=JsonNode.Parse(original)!;source["Data"]!["Books"]![0]!.AsObject().Remove("StoryEra");
var point=await repository.CreateAsync(project,"Synthetic missing book era field","Manual",source.ToJsonString(),"Synthetic older-shaped row, not a historical fixture.");
var result=await service.RestoreAsync(project,point.ProjectRestorePointID);
var after=(await backups.GetProjectBackupAsync(project,owner))!;
Console.WriteLine($"Service field omission: succeeded={result.Succeeded}; era={before.Data.Books.First().StoryEra}->{after.Data.Books.First().StoryEra ?? "<null>"}; safety={result.SafetyBackup is not null}.");
Check(!result.Succeeded && JsonSerializer.Serialize(after.Data)==dataBefore,"Actual restore service must not infer an absent stored book field as null and overwrite existing metadata.");
await ProjectBackupStoredFieldTests.RunAsync(factory,files,owner,project,before,counts,service,repository);
return;
}
string FileState()=>string.Join('|',Directory.GetFiles(uploads.UploadsRootPath,"*",SearchOption.AllDirectories).Order().Select(path=>path+":"+Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path)))));
var fileState=FileState();var coverage=new List<string>{"Case,Execution,Result,SafetyBackup"};
async Task Refused(string name,string json)

View File

@ -0,0 +1,40 @@
#!/usr/bin/env python3
"""Generate the compiled field contract from the verified specialist schema inventory.
First run the marked synthetic database --schema-coverage-only gate, then this script,
review its diff, build, and run --restore-field-omission-only. No database access here.
"""
import csv
import json
from collections import defaultdict
from pathlib import Path
root = Path(__file__).resolve().parents[2]
source = root / "Docs/Sprints/2026-11-03-phase2-field-coverage.csv"
output = root / "PlotLine/Services/ProjectBackupStoredFieldContract.Schema.cs"
excluded = {"GenreMetricPresets", "GenreMetricPresetMetrics", "ProjectAccess", "UserFiles"}
groups = defaultdict(list)
with source.open() as stream:
for row in csv.DictReader(stream):
if row["Collection"] in excluded or row["Computed"] == "True":
continue
if row["Collection"] == "Project" and row["Column"] == "UpdatedDate":
continue
groups[row["Collection"]].append(row)
text = """namespace PlotLine.Services;
internal static partial class ProjectBackupStoredFieldContract
{
// Generated from the independently audited stored schema inventory.
// Update alongside stored columns/backup DTOs; specialist field-omission checks use live synthetic metadata.
private static readonly IReadOnlyDictionary<string,(string Columns,string Nullable)> StoredColumns=
new Dictionary<string,(string,string)>(StringComparer.OrdinalIgnoreCase)
{
"""
for collection, rows in sorted(groups.items()):
columns = ",".join(row["Column"] for row in rows)
nullable = ",".join(row["Column"] for row in rows if row["Nullable"] == "True")
text += f" [{json.dumps(collection)}]=({json.dumps(columns)},{json.dumps(nullable)}),\n"
output.write_text(text + " };\n}\n")
print(f"Generated {len(groups)} stored entity contracts; review the diff and run the field-omission specialist gate.")

View File

@ -648,6 +648,8 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
}
if(mapError is null && validation.Errors.Count==0 && ProjectBackupCollectionPresence.AbsentPersistentCollections(jsonText).Count>0)
validation.Warnings.Add("Some project data categories are absent from this backup. They will remain empty in the imported copy; information not saved in the file cannot be reconstructed.");
if(mapError is null && validation.Errors.Count==0 && ProjectBackupStoredFieldContract.Missing(jsonText,includeShared:true).Count>0)
validation.Warnings.Add("Some stored project fields are absent from this backup and will use defaults in the new copy. Values not saved in the file cannot be reconstructed.");
return true;
}

View File

@ -0,0 +1,115 @@
namespace PlotLine.Services;
internal static partial class ProjectBackupStoredFieldContract
{
// Generated from the independently audited stored schema inventory.
// Update alongside stored columns/backup DTOs; specialist field-omission checks use live synthetic metadata.
private static readonly IReadOnlyDictionary<string,(string Columns,string Nullable)> StoredColumns=
new Dictionary<string,(string,string)>(StringComparer.OrdinalIgnoreCase)
{
["AssetAliases"]=("AssetAliasID,StoryAssetID,Alias,SortOrder,CreatedUtc",""),
["AssetCustodyCharacters"]=("AssetCustodyEventCharacterID,AssetCustodyEventID,CharacterID,CharacterNameText,CustodyRoleID","CharacterID,CharacterNameText"),
["AssetCustodyEvents"]=("AssetCustodyEventID,StoryAssetID,SceneID,AssetCustodyEventTypeID,Description,CreatedDate,UpdatedDate","Description"),
["AssetDependencies"]=("AssetDependencyID,SourceAssetID,TargetAssetID,AssetDependencyTypeID,SourceRequiredStateID,TargetBlockedStateID,Description,CreatedDate,UpdatedDate,IsArchived","SourceRequiredStateID,TargetBlockedStateID,Description"),
["AssetEvents"]=("AssetEventID,StoryAssetID,SceneID,AssetEventTypeID,FromStateID,ToStateID,EventTitle,EventDescription,CreatedDate,UpdatedDate,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC","FromStateID,ToStateID,EventDescription,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC"),
["AssetStates"]=("AssetStateID,ProjectID,AssetKindID,StateName,SortOrder,Description,IsResolvedState,IsActive","ProjectID,AssetKindID,Description"),
["AuthorPlotSeeds"]=("AuthorPlotSeedID,ProjectID,BookID,Description,Status,MatchedPlotLineID,Source,CreatedUtc,UpdatedUtc","MatchedPlotLineID"),
["Books"]=("BookID,ProjectID,BookTitle,BookNumber,Description,SortOrder,CreatedDate,UpdatedDate,IsArchived,ArchivedDate,ArchivedReason,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,Subtitle,Tagline,ShortDescription,Status,TargetWordCount,WritingStartDate,TargetCompletionDate,PublicationDate,CoverThumbnailPath,CoverStandardPath,UsesExplicitScenes,StoryEra,PrimaryLocaleCode","Description,ArchivedDate,ArchivedReason,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,Subtitle,Tagline,ShortDescription,TargetWordCount,WritingStartDate,TargetCompletionDate,PublicationDate,CoverThumbnailPath,CoverStandardPath,StoryEra,PrimaryLocaleCode"),
["ChapterGoals"]=("ChapterGoalID,ChapterID,GoalSummary,EmotionalGoal,ReaderTakeaway,MustInclude,RisksOrConcerns,CreatedDate,UpdatedDate,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC","GoalSummary,EmotionalGoal,ReaderTakeaway,MustInclude,RisksOrConcerns,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC"),
["Chapters"]=("ChapterID,BookID,ChapterNumber,ChapterTitle,POVCharacterID,Summary,SortOrder,RevisionStatusID,CreatedDate,UpdatedDate,IsArchived,ArchivedDate,ArchivedReason,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,IsLinkedToManuscript,ManuscriptDocumentID,ExternalReference,LinkedUtc,ChapterPurposeID,POVSource,POVConfidence,POVEvidence,POVSuggestedName","POVCharacterID,Summary,ArchivedDate,ArchivedReason,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,ManuscriptDocumentID,ExternalReference,LinkedUtc,ChapterPurposeID,POVSource,POVConfidence,POVEvidence,POVSuggestedName"),
["CharacterAliases"]=("CharacterAliasID,CharacterID,Alias,SortOrder,CreatedUtc",""),
["CharacterAttributeEvents"]=("CharacterAttributeEventID,CharacterID,CharacterAttributeTypeID,SceneID,AttributeValue,Description,CreatedDate,UpdatedDate","Description"),
["CharacterAttributeTypes"]=("CharacterAttributeTypeID,ProjectID,AttributeName,DataType,IsNormallyStable,SortOrder,IsActive","ProjectID"),
["CharacterEnrichmentEvidence"]=("CharacterEnrichmentEvidenceID,CharacterEnrichmentRunID,CharacterID,SceneID,FieldName,Value,Evidence,Confidence,Source,CreatedUtc","SceneID,Value,Evidence"),
["CharacterEnrichmentRuns"]=("CharacterEnrichmentRunID,ProjectID,BookID,UserID,StoryIntelligenceBookPipelineID,CharacterResolutionVersion,Status,TotalCharacters,ProcessedCharacters,CurrentStage,CurrentMessage,QueuedUtc,StartedUtc,CompletedUtc,FailedUtc,AttemptCount,Model,InputTokens,OutputTokens,TotalTokens,DurationMs,ErrorMessage,ErrorDetail,IsCurrent,UpdatedUtc,CharacterID","StoryIntelligenceBookPipelineID,CurrentStage,CurrentMessage,StartedUtc,CompletedUtc,FailedUtc,Model,InputTokens,OutputTokens,TotalTokens,DurationMs,ErrorMessage,ErrorDetail,CharacterID"),
["CharacterImages"]=("CharacterImageID,CharacterID,ProjectID,ImagePath,ThumbnailPath,Caption,SortOrder,UploadedDateUTC,IsDeleted,DeletedDateUTC","Caption,DeletedDateUTC"),
["CharacterIntelligenceEvidenceEvents"]=("CharacterIntelligenceEvidenceEventID,CharacterIntelligenceProfileID,SceneResultID,FieldName,PreviousValue,NewValue,Evidence,Confidence,IsContradiction,Source,CreatedUtc","PreviousValue,NewValue,Evidence"),
["CharacterIntelligenceProfiles"]=("CharacterIntelligenceProfileID,ImportSessionID,ProjectID,BookID,CanonicalIdentityKey,CanonicalName,ProfileJson,Confidence,NarrativeImportance,IsRecurring,EvidenceVersion,LastUpdatedSceneResultID,CreatedUtc,UpdatedUtc","NarrativeImportance,LastUpdatedSceneResultID"),
["CharacterKnowledge"]=("CharacterKnowledgeID,CharacterID,StoryAssetID,PlotThreadID,SceneID,KnowledgeStateID,SourceEventID,Description,CreatedDate,UpdatedDate,SourceReviewKey","StoryAssetID,PlotThreadID,SourceEventID,Description,SourceReviewKey"),
["CharacterRelationships"]=("CharacterRelationshipID,ProjectID,CharacterAID,CharacterBID,RelationshipTypeID,IsPermanent,StartSceneID,EndSceneID,IsKnownToReader,Notes,CreatedDate,UpdatedDate,IsArchived,ArchivedDate,ArchivedReason,IsInitialRelationship,InitialBookID,ReaderInitiallyKnows,InitialRelationshipStateID,InitialIntensity,IsReciprocal,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC","StartSceneID,EndSceneID,Notes,ArchivedDate,ArchivedReason,InitialBookID,InitialRelationshipStateID,InitialIntensity,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC"),
["Characters"]=("CharacterID,ProjectID,CharacterName,ShortName,Sex,BirthDate,AgeAtSeriesStart,AgeReferenceSceneID,Height,EyeColour,CharacterImportance,DefaultDescription,CreatedDate,UpdatedDate,IsArchived,ArchivedDate,ArchivedReason,ShowInQuickAddBar,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,ImagePath,ThumbnailPath,AvatarSourceCharacterImageID,AvatarImagePath,AvatarThumbnailPath,SexValueID","ShortName,Sex,BirthDate,AgeAtSeriesStart,AgeReferenceSceneID,Height,EyeColour,CharacterImportance,DefaultDescription,ArchivedDate,ArchivedReason,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,ImagePath,ThumbnailPath,AvatarSourceCharacterImageID,AvatarImagePath,AvatarThumbnailPath,SexValueID"),
["ContinuityWarningAcknowledgements"]=("ContinuityWarningAcknowledgementID,ProjectID,WarningType,SceneID,CharacterID,AssetID,AcknowledgedDate,AcknowledgedByUserID,Notes","SceneID,CharacterID,AssetID,AcknowledgedByUserID,Notes"),
["ContinuityWarnings"]=("ContinuityWarningID,ValidationRunID,ProjectID,BookID,ChapterID,SceneID,EntityType,EntityID,WarningTypeID,WarningSeverityID,Message,Details,IsDismissed,IsIntentional,CreatedDate,LastDetectedDate","ValidationRunID,BookID,ChapterID,SceneID,EntityID,Details"),
["CoreImportBasicLocationCandidates"]=("CoreImportBasicLocationCandidateID,CoreImportBasicLocationReviewID,StableKey,ProposedName,PreferredName,KnownNamesJson,ParentLocationID,ParentCandidateKey,ExistingLocationID,Action,SameAsLocationID,SameAsCandidateKey,ResultLocationID,FirstChapterNumber,FirstSceneNumber,FirstOccurrenceIndex,ObservationCount,SortOrder,CreatedUtc,UpdatedUtc","ParentLocationID,ParentCandidateKey,ExistingLocationID,SameAsLocationID,SameAsCandidateKey,ResultLocationID"),
["CoreImportBasicLocationEvidence"]=("CoreImportBasicLocationEvidenceID,CoreImportBasicLocationCandidateID,SceneID,ChapterID,ChapterNumber,SceneNumber,OccurrenceIndex,EvidenceText,SortOrder",""),
["CoreImportBasicLocationReviews"]=("CoreImportBasicLocationReviewID,PreviewID,UserID,ProjectID,BookID,BuildID,Status,RawObservationCount,CandidateCount,CreatedUtc,UpdatedUtc,CompletedUtc","BuildID,CompletedUtc"),
["FloorPlanBlocks"]=("FloorPlanBlockID,FloorPlanFloorID,LocationID,X,Y,WidthCells,HeightCells,BlockType,LabelOverride,Notes,CreatedDate,ModifiedDate","LabelOverride,Notes,ModifiedDate"),
["FloorPlanFloors"]=("FloorPlanFloorID,FloorPlanID,Name,SortOrder,GridWidth,GridHeight,CreatedDate,ModifiedDate,LocationID,BackgroundImagePath,BackgroundImageOriginalFileName,BackgroundOpacity,BackgroundScale,BackgroundOffsetX,BackgroundOffsetY,BackgroundLocked,Description","ModifiedDate,LocationID,BackgroundImagePath,BackgroundImageOriginalFileName,BackgroundOpacity,BackgroundScale,BackgroundOffsetX,BackgroundOffsetY,Description"),
["FloorPlanTransitions"]=("FloorPlanTransitionID,FloorPlanFloorID,FromLocationID,ToLocationID,TransitionType,Notes,IsLocked,DisplayLabel,CreatedDate,ModifiedDate,PositionWithinLocation","Notes,DisplayLabel,ModifiedDate"),
["FloorPlans"]=("FloorPlanID,ProjectID,Name,Description,CreatedDate,ModifiedDate,LocationID","Description,ModifiedDate,LocationID"),
["LocationAliases"]=("LocationAliasID,LocationID,Alias,SortOrder,CreatedUtc",""),
["LocationRelationships"]=("LocationRelationshipID,FromLocationID,ToLocationID,LocationRelationshipTypeID,IsBidirectional,Strength,CanHearNormalSpeech,CanHearLoudNoise,CanSeeMovement,CanSeeClearly,CanTravelDirectly,Notes,CreatedDate,UpdatedDate,IsArchived","Strength,Notes"),
["Locations"]=("LocationID,ProjectID,ParentLocationID,LocationName,LocationTypeID,Description,CreatedDate,UpdatedDate,IsArchived,ArchivedDate,ArchivedReason,ShowInQuickAddBar,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,ExcludeFromCompanionDetection,DetectionPriority","ParentLocationID,LocationTypeID,Description,ArchivedDate,ArchivedReason,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC"),
["ManuscriptDocuments"]=("ManuscriptDocumentID,BookID,ProjectID,DocumentGuid,BindingVersion,CreatedUtc,LastSyncUtc,LastOpenedUtc,IsActive,CreatedByUserID","LastSyncUtc,LastOpenedUtc,CreatedByUserID"),
["ManuscriptStructuralChapterSources"]=("ChapterID,ProjectID,BookID,SourceText,SourceWordCount,SourceCharacterCount,ParagraphMapJson,CreatedUtc,UpdatedUtc,StructuralParsedJson,DefaultPovName,ExplicitNarratorName","ParagraphMapJson,StructuralParsedJson,DefaultPovName,ExplicitNarratorName"),
["MapFeatures"]=("MapID,FeatureID,Name,Type,GeometryClass,Layer,X,Y,Width,Height,Rotation,ZOrder,IsPlaced,IsProvisional,IsLocked,ShowLabel,LabelX,LabelY,LocationID,FloorPlanID,StartFeatureID,EndFeatureID,GeometryJson,Notes","LocationID,FloorPlanID,StartFeatureID,EndFeatureID,Notes"),
["MapJourneyNotes"]=("MapID,CharacterID,FromSceneID,ToSceneID,RouteFeatureID,TravelMethod,TypicalMinutes","RouteFeatureID,TravelMethod,TypicalMinutes"),
["MapReferenceImages"]=("ImageID,ProjectID,OriginalFileName,ContentType,Width,Height,ImageData",""),
["MapRelationships"]=("MapID,RelationshipID,SourceID,TargetID,Direction,RelativeDistance,MeasuredDistance,Unit,TypicalTravelTime,Notes","Direction,RelativeDistance,MeasuredDistance,Unit,TypicalTravelTime,Notes"),
["OnboardingManuscriptBuildChapterMap"]=("OnboardingManuscriptBuildID,TemporaryChapterKey,ChapterID",""),
["OnboardingManuscriptBuildCharacterMap"]=("OnboardingManuscriptBuildID,TemporaryCharacterKey,CharacterID,Created",""),
["OnboardingManuscriptBuildSceneMap"]=("OnboardingManuscriptBuildID,TemporarySceneKey,SceneID",""),
["OnboardingManuscriptBuilds"]=("OnboardingManuscriptBuildID,PreviewID,UserID,ProjectID,BookID,ManuscriptDocumentID,Status,MarkerStatus,ChaptersCreated,ScenesCreated,CharactersCreated,CharactersReused,SceneAppearancesCreated,CreatedUtc,UpdatedUtc,MarkerSyncMessage,MarkerSyncCompletedUtc","ManuscriptDocumentID,MarkerSyncMessage,MarkerSyncCompletedUtc"),
["PlotEventTargetPlotLines"]=("PlotEventID,PlotLineID,CreatedDate",""),
["PlotLines"]=("PlotLineID,ProjectID,BookID,PlotLineName,PlotLineTypeID,Description,ParentPlotLineID,SortOrder,Colour,IsVisibleOnTimeline,CreatedDate,UpdatedDate,IsArchived,ArchivedDate,ArchivedReason,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,PlotImportanceID,EmergesFromPlotLineID","BookID,Description,ParentPlotLineID,ArchivedDate,ArchivedReason,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,EmergesFromPlotLineID"),
["PlotThreads"]=("PlotThreadID,PlotLineID,ThreadTitle,ThreadTypeID,ThreadStatusID,Importance,Summary,IntroducedSceneID,PlannedResolutionSceneID,ActualResolutionSceneID,CreatedDate,UpdatedDate,IsArchived,ArchivedDate,ArchivedReason,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC","Summary,IntroducedSceneID,PlannedResolutionSceneID,ActualResolutionSceneID,ArchivedDate,ArchivedReason,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC"),
["Project"]=("ProjectID,ProjectName,Description,CreatedDate,IsArchived,ArchivedDate,ArchivedReason,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC","Description,ArchivedDate,ArchivedReason,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC"),
["RelationshipEvents"]=("RelationshipEventID,CharacterRelationshipID,SceneID,RelationshipStateID,Intensity,IsKnownToOtherCharacter,Description,CreatedDate,UpdatedDate,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,SourceReviewKey","Intensity,Description,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,SourceReviewKey"),
["ScenarioSceneOrder"]=("ScenarioSceneOrderID,ScenarioID,SceneID,ProposedChapterID,ProposedSortOrder,Notes,CreatedDate,UpdatedDate","ProposedChapterID,Notes"),
["ScenarioValidationRuns"]=("ScenarioValidationRunID,ScenarioID,StartedDate,CompletedDate,WarningCount","CompletedDate"),
["ScenarioWarnings"]=("ScenarioWarningID,ScenarioValidationRunID,ScenarioID,SceneID,EntityType,EntityID,WarningTypeName,SeverityName,Message,Details,CreatedDate","SceneID,EntityID,Details"),
["Scenarios"]=("ScenarioID,ProjectID,BookID,ScenarioName,Description,BaseCreatedDate,IsAppliedToMain,IsArchived,CreatedDate,UpdatedDate,ArchivedDate,ArchivedReason","BookID,Description,ArchivedDate,ArchivedReason"),
["SceneAssetLocations"]=("SceneAssetLocationID,SceneID,StoryAssetID,LocationID,Description,CreatedDate,UpdatedDate","Description"),
["SceneAssetSuggestions"]=("SceneAssetSuggestionID,SceneID,AssetID,SuggestionSource,DetectedUtc,Status,Confidence,Reason,CreatedByUserID,ReviewedByUserID,ReviewedUtc","Reason,ReviewedByUserID,ReviewedUtc"),
["SceneAttachments"]=("SceneAttachmentID,SceneID,SceneAttachmentTypeID,Title,FilePath,ExternalUrl,Notes,CreatedDate,UpdatedDate,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC","FilePath,ExternalUrl,Notes,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC"),
["SceneCharacterSuggestions"]=("SceneCharacterSuggestionID,SceneID,CharacterID,SuggestionSource,DetectedUtc,Status,Confidence,Reason,CreatedByUserID,ReviewedByUserID,ReviewedUtc","Reason,ReviewedByUserID,ReviewedUtc"),
["SceneCharacters"]=("SceneCharacterID,SceneID,CharacterID,RoleInSceneTypeID,PresenceTypeID,LocationID,EntryLocationID,ExitLocationID,AppearanceNotes,OutfitDescription,PhysicalCondition,EmotionalState,KnowledgeNotes,CreatedDate,UpdatedDate,MatchSource,MatchedText,OccurrenceCount,FirstOccurrenceIndex","RoleInSceneTypeID,PresenceTypeID,LocationID,EntryLocationID,ExitLocationID,AppearanceNotes,OutfitDescription,PhysicalCondition,EmotionalState,KnowledgeNotes,MatchSource,MatchedText,OccurrenceCount,FirstOccurrenceIndex"),
["SceneChecklistItems"]=("SceneChecklistItemID,SceneID,ItemText,IsCompleted,SortOrder,CreatedDate,UpdatedDate,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC","SortOrder,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC"),
["SceneDependencies"]=("SceneDependencyID,SourceSceneID,TargetSceneID,SceneDependencyTypeID,Description,CreatedDate,UpdatedDate,IsArchived,ProjectID,IsHardDependency","Description,ProjectID"),
["SceneFloorPlanOccupancy"]=("SceneFloorPlanOccupancyID,SceneID,FloorPlanID,FloorPlanFloorID,CharacterID,StoryAssetID,LocationID,CreatedDate,ModifiedDate","FloorPlanFloorID,CharacterID,StoryAssetID,ModifiedDate"),
["SceneLocationSuggestions"]=("SceneLocationSuggestionID,SceneID,LocationID,SuggestionSource,DetectedUtc,Status,Confidence,Reason,CreatedByUserID,ReviewedByUserID,ReviewedUtc","Reason,ReviewedByUserID,ReviewedUtc"),
["SceneManuscriptSources"]=("SceneID,ProjectID,BookID,ChapterID,SourceText,SourceWordCount,SourceCharacterCount,SourceStartParagraph,SourceEndParagraph,WordStartParagraphIndex,WordEndParagraphIndex,SourceKind,CreatedUtc,UpdatedUtc","SourceStartParagraph,SourceEndParagraph,WordStartParagraphIndex,WordEndParagraphIndex"),
["SceneMetricTypes"]=("MetricTypeID,ProjectID,MetricName,Description,MinValue,MaxValue,DefaultValue,SortOrder,IsActive","ProjectID,Description"),
["SceneMetricValues"]=("SceneID,MetricTypeID,Value,Notes","Notes"),
["SceneNotes"]=("SceneNoteID,SceneID,SceneNoteTypeID,NoteTitle,NoteText,SortOrder,IsPinned,IsResolved,CreatedDate,UpdatedDate,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC","NoteTitle,SortOrder,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC"),
["SceneOutcomes"]=("SceneOutcomeID,SceneID,OutcomeDescription,OutcomeTypeID,CreatedDate,UpdatedDate","OutcomeTypeID"),
["ScenePurposes"]=("SceneID,ScenePurposeTypeID",""),
["SceneTextStatistics"]=("SceneID,TotalWordCount,DialogueWordCount,ProseWordCount,TotalParagraphCount,DialogueParagraphCount,ProseParagraphCount,CalculatedUtc,UpdatedUtc",""),
["SceneWorkflow"]=("SceneWorkflowID,SceneID,DraftStatus,EstimatedWordCount,ActualWordCount,DraftedDate,LastWorkedOn,ReadyForDraft,ReadyForRevision,ReadyForPolish,IsBlocked,BlockedReason,Priority,CreatedDate,UpdatedDate,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC","EstimatedWordCount,ActualWordCount,DraftedDate,LastWorkedOn,BlockedReason,Priority,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC"),
["Scenes"]=("SceneID,ChapterID,SceneNumber,SceneTitle,Summary,POVCharacterID,PrimaryLocationID,SortOrder,TimeModeID,StartDateTime,EndDateTime,DurationAmount,DurationUnitID,RelativeTimeText,TimeConfidenceID,ScenePurposeNotes,SceneOutcomeNotes,RevisionStatusID,CreatedDate,UpdatedDate,IsArchived,ArchivedDate,ArchivedReason,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,FloorPlanID,InitialFloorPlanFloorID,IsLinkedToManuscript,ManuscriptDocumentID,ExternalReference,LinkedUtc,ImportSource,ImportRunID,SourceStartParagraph,SourceEndParagraph,StructuralSummary,SceneTitleSource,POVSource,POVConfidence,POVEvidence,POVSuggestedName,StructuralSetting","Summary,POVCharacterID,PrimaryLocationID,StartDateTime,EndDateTime,DurationAmount,DurationUnitID,RelativeTimeText,ScenePurposeNotes,SceneOutcomeNotes,ArchivedDate,ArchivedReason,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,FloorPlanID,InitialFloorPlanFloorID,ManuscriptDocumentID,ExternalReference,LinkedUtc,ImportSource,ImportRunID,SourceStartParagraph,SourceEndParagraph,StructuralSummary,SceneTitleSource,POVSource,POVConfidence,POVEvidence,POVSuggestedName,StructuralSetting"),
["StoryAssets"]=("StoryAssetID,ProjectID,AssetName,AssetKindID,Description,Importance,CurrentStateID,CurrentLocationID,IsResolved,CreatedDate,UpdatedDate,IsArchived,ArchivedDate,ArchivedReason,ShowInQuickAddBar,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,ImagePath,ThumbnailPath","Description,CurrentStateID,CurrentLocationID,ArchivedDate,ArchivedReason,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,ImagePath,ThumbnailPath"),
["StoryIntelligenceBookPipelines"]=("StoryIntelligenceBookPipelineID,ProjectID,BookID,CurrentStage,LastCompletedStage,CurrentReviewStage,Status,CompletedUtc,LastRunID,CreatedUtc,UpdatedUtc,CompletionEmailQueuedUtc,FailureEmailQueuedUtc,CharacterReviewCompletedUtc,LocationReviewCompletedUtc,AssetReviewCompletedUtc,RelationshipReviewCompletedUtc,KnowledgeReviewCompletedUtc,NarrativeReviewCompletedUtc","LastCompletedStage,CurrentReviewStage,CompletedUtc,LastRunID,CompletionEmailQueuedUtc,FailureEmailQueuedUtc,CharacterReviewCompletedUtc,LocationReviewCompletedUtc,AssetReviewCompletedUtc,RelationshipReviewCompletedUtc,KnowledgeReviewCompletedUtc,NarrativeReviewCompletedUtc"),
["StoryIntelligenceChapterResults"]=("ChapterResultID,StoryIntelligenceRunID,ProjectID,BookID,ChapterID,ChapterNumber,SourceLabel,PromptVersion,Model,RawResponseJson,OutputTextJson,ParsedJson,ValidationErrorsCount,ValidationWarningsCount,InputTokens,OutputTokens,TotalTokens,DurationMs,CreatedUtc","ProjectID,BookID,ChapterID,ChapterNumber,InputTokens,OutputTokens,TotalTokens,DurationMs"),
["StoryIntelligenceIllustrationDemands"]=("StoryIntelligenceIllustrationDemandID,ProjectID,DemandKey,AgeBand,Presentation,HairColour,SkinTone,HairLength,Glasses,FacialHair,RequestCount,LastRequestedUtc,CreatedUtc,UpdatedUtc,QueuedUtc,GenerationSource","ProjectID,HairLength,Glasses,FacialHair,QueuedUtc"),
["StoryIntelligenceImportCommits"]=("StoryIntelligenceImportCommitID,StoryIntelligenceRunID,ProjectID,BookID,ChapterID,CommittedAt,CommittedByUserID,ScenesCreated,MetricsCreated,Status,Notes,CreatedUtc","ProjectID,BookID,ChapterID,Notes"),
["StoryIntelligenceNarrativeCandidateEvents"]=("NarrativeCandidateEventID,NarrativeCandidateID,WholeBookPlotSynthesisRunID,EventKey,SceneID,EventType,EventTitle,EventDescription,Evidence,Confidence,SortOrder,IsIgnored,AcceptedThreadEventID,CreatedUtc,UpdatedUtc","WholeBookPlotSynthesisRunID,EventDescription,Evidence,Confidence,AcceptedThreadEventID"),
["StoryIntelligenceNarrativeCandidateEvidence"]=("NarrativeCandidateEvidenceID,NarrativeCandidateID,SceneID,ContributionType,Evidence,SortOrder,CreatedUtc","ContributionType,Evidence"),
["StoryIntelligenceNarrativeCandidates"]=("NarrativeCandidateID,ProjectID,BookID,CandidateType,CandidateKey,ProposedTitle,ProposedDescription,Category,InferredState,ExistingPlotLineID,ExistingPlotThreadID,RelatedPlotLineID,Confidence,Status,ReviewAction,AcceptedPlotLineID,AcceptedPlotThreadID,ReviewedByUserID,ReviewedUtc,CreatedUtc,UpdatedUtc,ChangeType,Significance,ParentCandidateKey,ParentNarrativeCandidateID,MergeTargetNarrativeCandidateID,WholeBookPlotSynthesisRunID,AuthorPlotSeedID,ExistingPlotLineMatchConfidence,ExistingPlotLineMatchReason,SeedMatchConfidence,SeedMatchReason,Source","ProposedDescription,Category,InferredState,ExistingPlotLineID,ExistingPlotThreadID,RelatedPlotLineID,Confidence,ReviewAction,AcceptedPlotLineID,AcceptedPlotThreadID,ReviewedByUserID,ReviewedUtc,ChangeType,Significance,ParentCandidateKey,ParentNarrativeCandidateID,MergeTargetNarrativeCandidateID,WholeBookPlotSynthesisRunID,AuthorPlotSeedID,ExistingPlotLineMatchConfidence,ExistingPlotLineMatchReason,SeedMatchConfidence,SeedMatchReason,Source"),
["StoryIntelligenceReviewCandidateEvidence"]=("ReviewCandidateEvidenceID,ReviewCandidateID,SceneID,EvidenceText,Confidence,SortOrder,CreatedUtc","SceneID,Confidence"),
["StoryIntelligenceReviewCandidateGenerations"]=("ReviewCandidateGenerationID,ProjectID,BookID,Module,Status,Source,CandidateCount,PendingCount,ErrorMessage,IsCurrent,CreatedUtc,PreparedUtc,FailedUtc,UpdatedUtc","ErrorMessage,PreparedUtc,FailedUtc"),
["StoryIntelligenceReviewCandidates"]=("ReviewCandidateID,ReviewCandidateGenerationID,ProjectID,BookID,Module,StableKey,CandidateType,DisplayName,SortOrder,Confidence,ExistingCanonicalID,DecisionStatus,DecisionAction,DecisionTargetKey,DecisionCanonicalID,CandidatePayloadJson,CreatedUtc,ReviewedUtc,UpdatedUtc,ReviewPriority,AssessmentJson","CandidateType,Confidence,ExistingCanonicalID,DecisionAction,DecisionTargetKey,DecisionCanonicalID,ReviewedUtc,AssessmentJson"),
["StoryIntelligenceRuns"]=("StoryIntelligenceRunID,UserID,ProjectID,BookID,Status,SourceType,PromptVersion,Model,StartedUtc,CompletedUtc,TotalInputTokens,TotalOutputTokens,TotalTokens,TotalDurationMs,ErrorMessage,CreatedUtc,UpdatedUtc,SourceFileName,SourceFileSizeBytes,SourceWordCount,SourceCharacterCount,SourceChapterCount,SourceDetectedImagesCount,SourceDetectedTablesCount,SourceDetectedFootnotesCount,SourceDetectedCommentsCount,FailureStage,ErrorDetail,EstimatedCostGBP,EstimatedCostUSD,PromptVersionsSummary,SourceLabel,SourceText,CurrentStage,CurrentMessage,TotalDetectedScenes,CompletedScenes,FailedScenes,CancellationRequestedUtc,CancelledUtc,ChapterID,ChapterNumber,SourceParagraphCount,KnownCharactersJson","ProjectID,BookID,CompletedUtc,TotalInputTokens,TotalOutputTokens,TotalTokens,TotalDurationMs,ErrorMessage,SourceFileName,SourceFileSizeBytes,SourceWordCount,SourceCharacterCount,SourceChapterCount,SourceDetectedImagesCount,SourceDetectedTablesCount,SourceDetectedFootnotesCount,SourceDetectedCommentsCount,FailureStage,ErrorDetail,EstimatedCostGBP,EstimatedCostUSD,PromptVersionsSummary,SourceLabel,SourceText,CurrentStage,CurrentMessage,TotalDetectedScenes,CompletedScenes,FailedScenes,CancellationRequestedUtc,CancelledUtc,ChapterID,ChapterNumber,SourceParagraphCount,KnownCharactersJson"),
["StoryIntelligenceSceneResults"]=("SceneResultID,StoryIntelligenceRunID,ChapterResultID,ProjectID,BookID,ChapterID,SceneID,TemporarySceneNumber,StartParagraph,EndParagraph,SourceLabel,PromptVersion,Model,RawResponseJson,OutputTextJson,ParsedJson,ValidationErrorsCount,ValidationWarningsCount,InputTokens,OutputTokens,TotalTokens,DurationMs,CreatedUtc","ChapterResultID,ProjectID,BookID,ChapterID,SceneID,StartParagraph,EndParagraph,InputTokens,OutputTokens,TotalTokens,DurationMs"),
["StoryMaps"]=("MapID,ProjectID,ParentMapID,ParentFeatureID,Name,Kind,Revision,ModifiedDate,AppearanceJson,ReferenceJson","ParentMapID,ParentFeatureID"),
["StoryMemoryAssets"]=("StoryMemoryAssetID,ImportSessionID,ProjectID,BookID,CanonicalIdentityKey,DisplayName,SemanticType,Subtype,Colour,Era,FirstSeenSceneResultID,LastSeenSceneResultID,CreatedUtc,UpdatedUtc","Subtype,Colour,Era,FirstSeenSceneResultID,LastSeenSceneResultID"),
["StoryMemoryCharacterAliases"]=("StoryMemoryCharacterAliasID,StoryMemoryCharacterID,Alias,NormalisedAlias,ResolutionReason,SourceSceneResultID,Confidence,CreatedUtc","ResolutionReason,SourceSceneResultID"),
["StoryMemoryCharacterAttributes"]=("StoryMemoryCharacterAttributeID,StoryMemoryCharacterID,AttributeType,NormalisedValue,Confidence,IsExplicit,EvidenceSummary,SourceSceneResultID,SupersededUtc,CreatedUtc","EvidenceSummary,SourceSceneResultID,SupersededUtc"),
["StoryMemoryCharacters"]=("StoryMemoryCharacterID,ImportSessionID,ProjectID,BookID,CanonicalIdentityKey,DisplayName,EntityContext,SourceSectionType,IsNamed,IsGroupEntity,IsResolved,IsNarrator,IsPrimaryPOV,Significance,EvidenceVersion,CreatedSceneResultID,LastUpdatedSceneResultID,CreatedUtc,UpdatedUtc","CreatedSceneResultID,LastUpdatedSceneResultID"),
["StoryMemoryIllustrationAssignments"]=("StoryMemoryIllustrationAssignmentID,ImportSessionID,EntityType,EntityID,IllustrationLibraryItemID,StableCode,AssignmentStatus,IsFallback,MatchScore,Confidence,AssignmentReason,EvidenceVersion,AssignedUtc,LastValidatedUtc,InvalidatedUtc,InvalidationReason,CreatedUtc,UpdatedUtc","IllustrationLibraryItemID,StableCode,AssignmentReason,InvalidatedUtc,InvalidationReason"),
["StoryMemoryIllustrationDemands"]=("StoryMemoryIllustrationDemandID,ImportSessionID,ProjectID,EntityType,ArchetypeKey,DemandCount,WaitingEntityCount,Status,QueuedIllustrationLibraryItemID,GeneratedIllustrationLibraryItemID,CreatedUtc,UpdatedUtc","QueuedIllustrationLibraryItemID,GeneratedIllustrationLibraryItemID"),
["StoryMemoryImportPreferences"]=("StoryMemoryImportPreferenceID,ImportSessionID,AppearancePreference,ResolverVersion,CreatedUtc,UpdatedUtc,PrimaryAgeGroup,StoryEra,StoryLocation","PrimaryAgeGroup,StoryEra,StoryLocation"),
["StoryMemoryLocations"]=("StoryMemoryLocationID,ImportSessionID,ProjectID,BookID,CanonicalIdentityKey,DisplayName,SemanticType,Subtype,InteriorExterior,ParentLocationID,FirstSeenSceneResultID,LastSeenSceneResultID,CreatedUtc,UpdatedUtc","Subtype,InteriorExterior,ParentLocationID,FirstSeenSceneResultID,LastSeenSceneResultID"),
["StoryMemoryProcessedSceneResults"]=("StoryMemoryProcessedSceneResultID,ImportSessionID,SceneResultID,ProcessorVersion,SnapshotHash,ProcessedUtc","SnapshotHash"),
["StoryMemoryRelationships"]=("StoryMemoryRelationshipID,ImportSessionID,SourceEntityType,SourceEntityID,TargetEntityType,TargetEntityID,RelationshipType,Confidence,IsExplicit,FirstSeenSceneResultID,LastUpdatedSceneResultID,Active,CreatedUtc,UpdatedUtc","FirstSeenSceneResultID,LastUpdatedSceneResultID"),
["ThreadEvents"]=("ThreadEventID,PlotThreadID,SceneID,EventTypeID,EventTitle,EventDescription,CreatedDate,UpdatedDate,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,PlotEventTypeID,TargetPlotLineID,Source,SourceReferenceID,SourceKey,Confidence","EventDescription,CreatedByUserID,ModifiedByUserID,CreatedDateUTC,ModifiedDateUTC,TargetPlotLineID,SourceReferenceID,SourceKey,Confidence"),
["TimelineMetricSettings"]=("ProjectID,MetricTypeID,SortOrder,CreatedDate",""),
["TimelineSettings"]=("ProjectTimelineSettingsID,ProjectID,ShowSceneCards,ShowMetricShape,ShowPlotLines,ShowStoryAssets,ShowCharacterAppearances,ShowWarnings,CreatedDate,UpdatedDate",""),
["TimelineViewPresets"]=("TimelineViewPresetID,ProjectID,BookID,PresetName,FilterJson,VisibilityJson,FocusType,FocusID,CreatedDate,UpdatedDate,IsArchived","BookID,FocusType,FocusID"),
["ValidationRuns"]=("ValidationRunID,ProjectID,BookID,StartedDate,CompletedDate,TriggeredBy,ScopeDescription","BookID,CompletedDate,TriggeredBy,ScopeDescription"),
["WholeBookPlotSynthesisRuns"]=("WholeBookPlotSynthesisRunID,ProjectID,BookID,UserID,SourceStoryIntelligenceRunID,CharacterResolutionVersion,Status,QueuedUtc,StartedUtc,CompletedUtc,FailedUtc,AttemptCount,Model,OpenAIResponseID,InputTokens,OutputTokens,CachedInputTokens,TotalTokens,DurationMs,ErrorMessage,ErrorDetail,ResultJson,IsCurrent,UpdatedUtc","SourceStoryIntelligenceRunID,StartedUtc,CompletedUtc,FailedUtc,Model,OpenAIResponseID,InputTokens,OutputTokens,CachedInputTokens,TotalTokens,DurationMs,ErrorMessage,ErrorDetail,ResultJson"),
["WordCompanionSceneAssets"]=("WordCompanionSceneAssetID,SceneID,StoryAssetID,CreatedDate,UpdatedDate",""),
["WordCompanionSceneLocations"]=("WordCompanionSceneLocationID,SceneID,LocationID,CreatedDate,UpdatedDate",""),
["WritingPlans"]=("WritingPlanID,UserID,ProjectID,BookID,PlanName,GoalType,StartDate,DeadlineDate,AvailableDaysJson,SessionLengthMinutes,IncludeBlockedScenes,RebalanceMode,IsActive,CreatedDateUtc,ModifiedDateUtc","BookID"),
["WritingScheduleItems"]=("WritingScheduleItemID,WritingPlanID,SceneID,ScheduledDate,TaskType,EstimatedMinutes,TargetWords,ScheduleStatus,CompletedDateUtc,Notes,CreatedDateUtc,ModifiedDateUtc","EstimatedMinutes,TargetWords,CompletedDateUtc,Notes"),
};
}

View File

@ -0,0 +1,69 @@
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using PlotLine.Models;
namespace PlotLine.Services;
internal static partial class ProjectBackupStoredFieldContract
{
private sealed record Field(string Name,bool LegacyProjectAudit);
private static readonly JsonDocumentOptions ReadOptions=new(){AllowTrailingCommas=true,CommentHandling=JsonCommentHandling.Skip};
private static readonly HashSet<string> MixedReferenceCollections=new(StringComparer.OrdinalIgnoreCase)
{nameof(ProjectBackupData.AssetStates),nameof(ProjectBackupData.CharacterAttributeTypes),nameof(ProjectBackupData.SceneMetricTypes)};
private static readonly HashSet<string> LegacyProjectAudit=new(StringComparer.OrdinalIgnoreCase)
{nameof(Project.CreatedByUserID),nameof(Project.ModifiedByUserID),nameof(Project.CreatedDateUTC),nameof(Project.ModifiedDateUTC)};
private static readonly Lazy<IReadOnlyDictionary<string,Field[]>> Required=new(Build);
private static IReadOnlyDictionary<string,Field[]> Build()
{
var result=new Dictionary<string,Field[]>(StringComparer.OrdinalIgnoreCase);
foreach(var contract in StoredColumns)
{
var type=contract.Key=="Project" ? typeof(Project) : typeof(ProjectBackupData).GetProperty(contract.Key)!.PropertyType.GetGenericArguments().Single();
var nullable=contract.Value.Nullable.Split(',',StringSplitOptions.RemoveEmptyEntries).ToHashSet(StringComparer.OrdinalIgnoreCase);
var fields=new List<Field>();
foreach(var column in contract.Value.Columns.Split(','))
{
var member=type.GetProperty(column,BindingFlags.Instance|BindingFlags.Public|BindingFlags.IgnoreCase)
?? throw new InvalidOperationException("Stored backup field has no model property: "+contract.Key+"."+column);
var ignore=member.GetCustomAttribute<JsonIgnoreAttribute>();
if(ignore?.Condition==JsonIgnoreCondition.Always || ignore?.Condition==JsonIgnoreCondition.WhenWritingDefault
|| ignore?.Condition==JsonIgnoreCondition.WhenWritingNull && nullable.Contains(column))continue;
fields.Add(new(member.GetCustomAttribute<JsonPropertyNameAttribute>()?.Name ?? member.Name,contract.Key=="Project" && LegacyProjectAudit.Contains(column)));
}
result[contract.Key]=fields.ToArray();
}
return result;
}
private static JsonElement Property(JsonElement root,string name)
{
var result=default(JsonElement);
if(root.ValueKind==JsonValueKind.Object)
foreach(var property in root.EnumerateObject())if(property.Name.Equals(name,StringComparison.OrdinalIgnoreCase))result=property.Value;
return result;
}
internal static IReadOnlyList<string> Missing(string json,bool includeShared=false)
{
using var document=JsonDocument.Parse(json,ReadOptions);
var root=document.RootElement;var data=Property(root,"Data");
var version=Property(root,"FormatVersion");var legacyAudit=version.ValueKind==JsonValueKind.String && version.GetString()=="1.2";
var missing=new List<string>();
foreach(var contract in Required.Value)
{
var value=contract.Key=="Project" ? Property(root,"Project") : Property(data,contract.Key);
// Absent categories are handled using the complete safety snapshot; an explicit empty is valid.
if(contract.Key!="Project" && value.ValueKind!=JsonValueKind.Array)continue;
var rows=contract.Key=="Project" ? new[]{value} : value.EnumerateArray().ToArray();
foreach(var row in rows)
{
if(row.ValueKind!=JsonValueKind.Object){missing.Add(contract.Key+" record");continue;}
// Explicitly global reference rows are retained in place, rather than restored from author JSON.
if(!includeShared && MixedReferenceCollections.Contains(contract.Key) && Property(row,"ProjectID").ValueKind==JsonValueKind.Null)continue;
var names=row.EnumerateObject().Select(property=>property.Name).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach(var field in contract.Value)
if((!field.LegacyProjectAudit || legacyAudit) && !names.Contains(field.Name))missing.Add(contract.Key+"."+field.Name);
}
}
return missing.Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
}
}

View File

@ -46,7 +46,17 @@ public sealed class ProjectRestoreService(
return Failure("Restore point JSON is invalid. No project data was changed.");
}
var validationMessage = ProjectBackupCollectionPresence.ValidateRequiredShape(restorePoint.JsonData) ?? ValidateBackup(projectId, backup);
var validationMessage=ProjectBackupCollectionPresence.ValidateRequiredShape(restorePoint.JsonData);
if(validationMessage is null)
{
var missingFields=ProjectBackupStoredFieldContract.Missing(restorePoint.JsonData);
if(missingFields.Count>0)
{
logger.LogWarning("Restore point {RestorePointID} omits stored fields {Fields}; refusing inferred defaults.",projectRestorePointId,string.Join(", ",missingFields));
validationMessage="This older restore point omits stored project fields. Restore was aborted rather than guessing their values. No project data was changed.";
}
}
validationMessage ??= ValidateBackup(projectId,backup);
if (validationMessage is not null)
{
return Failure(validationMessage);