Repair chapter acceptance, selective reconciliation and native text evidence

This commit is contained in:
Nick Beckley 2026-11-09 16:20:08 +00:00
parent 20000adfbf
commit b78a88eeab
26 changed files with 828 additions and 46 deletions

View File

@ -27,3 +27,13 @@ Versioned fingerprint/XML reader, accepted-snapshot checkpoint model, read-only
### Integrated candidate
The subsequent implementation extends the existing native/agent/presence/recovery paths end to end, with optional chapter capability, progressive validation, explicit repair, compact status and version 1.0.0.23 source. Migrations 245–247 have been applied to Development after verified backups; the original 245 ledger above records the earlier source-only milestone. See [the current implementation/deployment evidence](2026-11-09-chapter-sync-implementation.md) and [Windows qualification instructions](WindowsHandover/2026-11-09-chapter-sync.md) for the actual final status. Real Word COM timings and execution are not verified on Atlas.
### Atlas acceptance repair and native picture evidence (1.0.0.27 source)
The server acceptance investigation reproduced SQL timeouts on an isolated 8,457-paragraph fixture. Forward migrations 248–250 materialise the accepted paragraph/prior-scene indices once, scope scene projections and statistics to the changed chapter, and shift later source paragraph bounds without replacing their prose. Acceptance replies are tied to the checkpoint transaction; a subsequent progress refresh cannot undo a committed acceptance. Diagnostics include stage, chapter, request/session identifiers and SQL error number, without prose or authentication material.
The optional `chapter-native-text-v1` pipe capability adds `chapter-chunk` action `ids-exact`. Its payload retains the existing eight-hex-digit native ID plus eight-hex-digit UTF-16 span per paragraph. The new action certifies that the VSTO reader has also read each native paragraph's `Range.Text`, checked its length against the measured range span, and checked their concatenation against the chapter's aggregate `Range.Text`. This extra COM work is confined to chapters whose range XML contains drawing elements. Both pipe peers must advertise the capability; ordinary `ids` evidence remains unchanged. Older agents/add-ins cannot certify the picture fallback. The HTTP chapter observation and fingerprint version are unchanged.
For drawings, the parser uses that exact native text partition and still checks paragraph count, IDs, spans, outline and complete chapter coverage. Non-picture paragraphs must additionally match their XML text. It does not project inline/anchored object characters from XML. Tables, text boxes, fields, tracked changes and other previously unsafe structures remain refused. The server still independently requires exact accepted chapter content and ordered paragraph evidence; changed content requires the existing explicit reconciliation authority.
Version 1.0.0.27 is source and installer metadata only on Atlas. Actual VSTO compilation, package signing/install/upgrade, picture-span behaviour and Word responsiveness require Windows qualification. No Windows execution is claimed by portable fixture tests.

View File

@ -0,0 +1,74 @@
# Atlas chapter acceptance repair and Windows qualification handover
Continue `codex/word-companion-native-phase1-20261104`. Atlas fetched and fast-forwarded the clean checkout to Windows handover `20000adfbf3fe33ec4c6c6fd859dc9e8725bef5c`. No new branch/worktree, reset, rebase, reimport or Production operation was used. The attached instruction text ended mid-sentence in section 9; sections 1–8 were available in full.
## Confirmed failures
Discovery's accepted snapshot is revision 2, 8,457 paragraphs, 12,854,412 bytes. It initially had no durable chapter checkpoints or live validations. Existing diagnostics swallowed SQL errors behind a generic refusal, so the historical Windows requests cannot individually be assigned a SQL error after the fact.
A read-only reproduction of the existing adoption loop against a local JSON variable took 23,622 ms for 100 bindings. The old procedure repeatedly parsed and rewrote the whole snapshot for each adopted paragraph. An independent synthetic 8,457-paragraph fixture with a 233-paragraph first chapter then passed protocol/engine validation but hit SQL error -2 after 30,042 ms in actual checkpoint persistence. The agent's HTTP deadline is 15 seconds. This establishes a reproducible server acceptance defect without attributing an unrecorded exception to a particular Windows request.
The first correction persisted that same fixture's checkpoint in 3,219 ms. A new connection/repository read confirmed persistence and preservation of every PlotDirector paragraph GUID, exact paragraph, chapter assignment and scene identity. Only after proving that acceptance boundary did Atlas extend the investigation.
Changed-chapter integration exposed another SQL timeout. Active-request profiling identified the canonical-scene decision guard in `dbo.ParagraphManuscript`: a direct `OPENJSON(@Previous,'$.Scenes')` join to the global scenes table accumulated over a million logical reads, repeatedly parsing the large prior snapshot. The guard is retained using a materialised prior-scene index. Changed saves also unnecessarily projected all chapter sources and recalculated all scene statistics; the new path scopes those operations to the affected chapter. Insertions/deletions shift later source paragraph indices separately without replacing later prose or source kinds.
## Implementation and acceptance boundaries
- Migration 248 replaces per-binding full-document JSON mutation with one indexed paragraph materialisation, local row updates and one ordered array reconstruction. Existing binding conflicts, uniqueness, range overlap, revision CAS and transaction checks remain.
- Migration 249 materialises prior canonical scene decisions and adds optional `@ChangedChapterID` to the established snapshot procedure. The application uses Dapper/stored procedures throughout. Full snapshot callers retain their previous path.
- Migration 250 updates later scene source bounds after paragraph insertion/deletion while retaining their prose and source kind. The accepted manuscript remains one coherent snapshot.
- The checkpoint transaction determines acceptance. Its response no longer depends on an expensive subsequent full manifest reload. Live progress counts committed checkpoints, not attempted reads. A failed optional progress refresh does not turn a durable commit into a failed acceptance.
- Sanitised diagnostics distinguish received/decoded request, validation completion, durable persistence, rejection stage/category and finish result. They carry chapter, request/session IDs, elapsed time and SQL number. Controller trace IDs connect public failure references to logs. Prose, payloads and authentication material are omitted.
- Source version 1.0.0.27 distinguishes sign-in required from a lost document association, reports accepted counts separately from checking progress, and retains explicit review reasons. The ribbon layout is unchanged.
- The optional `chapter-native-text-v1` capability handles picture chapters by reading exact native paragraph text in the existing STA scheduler. Each paragraph text length must equal its measured native span, and their concatenation must equal the chapter range. `ids-exact` frames certify that verification. The parser uses those exact partitions rather than projecting picture characters from XML. Ordinary paragraphs still need XML equality; unsafe tables/fields/text boxes/tracked changes remain refused. Older clients keep their original protocol; both peers must support the new capability for picture certification. The HTTP observation/fingerprint format is unchanged.
## Architecture conclusions
| Question | Existing authority and resulting behaviour |
| --- | --- |
| What the import already provides | The accepted manuscript contains paragraph GUIDs and text, chapter heading GUIDs/canonical IDs, scene GUIDs/canonical IDs, assignments and evidence. Reuse it. |
| Why adopt native identities | Legacy imports can lack Word native paragraph IDs. Explicit repair binds them only with unique complete exact chapter content, boundaries and ordered paragraph evidence. It does not replace PlotDirector GUIDs or scenes. |
| What proves an unchanged chapter | Exact UTF-16 content fingerprint, paragraph count/length/outline, unique native IDs, accepted lineage and a current authenticated saved Word lease. A text hash alone cannot distinguish reordering identical paragraphs. |
| What can skip reads | Committed current-session/current-Word-revision manifest positions and the agent's checked-range cache. A new session needs fresh position evidence; durable source checkpoints survive. |
| What still needs native Word access | Current boundaries, paragraph IDs/spans and, for drawing chapters, exact native paragraph text. Portable hashing timings are not COM timings. |
| Edits, insertion and deletion | Complete authorised changed-chapter evidence goes through the existing reconciliation engine. Only that chapter's prose projections/statistics are rebuilt; later logical/source bounds shift when necessary. Unaffected IDs/assignments are preserved and tested. |
| Moved/new/deleted chapter headings | Ambiguous structure or cross-boundary identity conflicts require review. Canonical order and mappings are not guessed. |
| Interrupted work | Persisted checkpoints and current-session validations survive process loss. A new manifest recovers completed chapters; same-request retries are idempotent. Explicit repair authority remains grant/revision scoped and expires separately from stored source evidence. |
| Writing Context availability | A chapter's committed verified positions can resolve its canonical scene before unrelated chapters finish. Other sessions/revisions cannot reuse those absolute positions. |
| Authentication expiry | Trusted-installation renewal preserves account context when possible. Saved document/account/site associations remain available and are restored after verified book access. Sign-in state is distinct from linkage. |
| Upgrade/downgrade | Migrations retain old call compatibility; native text certification is separately negotiated. 1.0.0.27 installer metadata has a new ProductCode and the existing UpgradeCode. Actual Windows packaging/upgrade/downgrade gates remain mandatory. No Windows installation was attempted on Atlas. |
## Development protection
Before database writes Atlas created the copy-only checksum backup `/var/opt/mssql/backup/PlotDirector_Development_chapter_investigation_20261109_1630.bak`; the file exists and SQL `RESTORE VERIFYONLY ... WITH CHECKSUM` succeeded. Verification is not a restore test. Each opt-in integration run creates another uniquely named copy-only checksum backup before provisioning its own synthetic project.
All acceptance/reconciliation mutations used newly created synthetic books. Synthetic projects are archived for evidence. Discovery was not used for a state-changing test. Its fresh post-test state remains revision 2, 48 active chapters, 290 active scenes, 8,457 paragraphs/paragraph positions, zero adopted chapter checkpoints and zero live validations. No Story Intelligence analysis was started.
## Reproducible verification
Run build/tests serially:
```sh
dotnet build PlotLine.slnx
dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj
dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj -- --chapter-sync
dotnet run --project PlotDirector.NativeCompanion/Tests/PlotDirector.Companion.Tests.csproj
dotnet run --project PlotDirector.NativeCompanion/Tests/PlotDirector.Companion.Tests.csproj -- --chapter-sync
dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj -- --chapter-acceptance-dev <development-fixture-owner-id>
```
The opt-in Development command verifies the effective runtime database, backs it up, creates an isolated 48-chapter/8,457-paragraph synthetic book through repositories, and exercises the controller/service and actual SQL repositories with a scoped authenticated test principal and saved live lease. It is an in-process controller integration, not a claim that HTTP pairing middleware or real Word executed. It checks durable acceptance/fresh reads, immediate accepted counts, incomplete finish reporting, restart recovery, repeat verification, manual-mode change detection, selective edits, insert/delete source-bound shifts, specific rejections, separate session trust and Writing Context before whole-book completion. The native suites cover renewal/reconnection, saved association, repeated cursor observations, explicit rejection text, late frames and capability negotiation. Picture fixtures test exact native text, inline/anchored forms, missing capability/evidence, incomplete spans and continued field refusal.
## Remaining Windows qualification
1. Build VSTO and package/sign 1.0.0.27 using the established Windows scripts. Run payload/MSI/upgrade gates and record actual hashes; Atlas prepared source/metadata only. Preserve the retained 1.0.0.26 installer and development DOCX backup.
2. Open the associated development test copy, reauthenticate if necessary and confirm its existing book association returns automatically. Do not delete/reimport or clear mappings.
3. Start explicit repair, inspect server acceptance diagnostics for one chapter, and read its persisted checkpoint independently before judging ribbon progress. Confirm Writing Context follows within that chapter while other chapters remain unchecked.
4. Verify the final picture-containing range 838510–845456 with native text certification. The new source removes guessed XML object projection, but actual Word span/text behaviour remains unmeasured on Atlas. If a native span/text mismatch remains, preserve the refusal and capture sanitised structural measurements only.
5. Interrupt/reopen, verify completed chapters are recovered, test an isolated changed chapter and confirm unchanged cursor observations do not reread Word. Qualify actual responsiveness and final server-confirmed 48/48 completion.
Atlas cannot certify real Word behaviour or claim Discovery is synchronised without that Windows execution.
## Atlas verification result
The final portable runs passed: solution build with zero warnings/errors; full application harness (456 PASS records); focused chapter engine (43); native foundation (273); focused chapter agent (136). The final Development scale run passed first/multiple acceptance, fresh reads, early Context, resumed/idempotent verification, immediate progress, incomplete completion, changed-chapter detection/reconciliation, insertion/deletion, shifted source bounds, specific rejection and separate-session trust. Timings in that run were about 2–4 seconds for unchanged acceptance, 6,086 ms for an edit, 6,642 ms for insertion and 6,409 ms for deletion, all below the existing 15-second client deadline. These are in-process controller/real Development SQL measurements, not Word COM or public network timings. The final scale fixture is archived project 8188; earlier synthetic investigation projects 8182–8187 are also archived.

View File

@ -56,8 +56,8 @@ public sealed class PipeHost(string pipeName, SessionManager sessions, Action<st
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="unsupported-version"},cancellation); return;
}
var trayAdapter=(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.TrayCapability);
instance = hello.WordInstanceId; sessions.Attach(instance,lease,(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterSyncCapability));if(trayAdapter)control?.Attach(instance,lease,(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.CaptureCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.MaintenanceCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ParagraphCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterSyncCapability));
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="ready",WordInstanceId=instance,Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability+","+ProtocolVersion.CaptureCapability+","+ProtocolVersion.MaintenanceCapability+","+ProtocolVersion.ParagraphCapability+","+ProtocolVersion.ChapterSyncCapability},cancellation);
instance = hello.WordInstanceId; sessions.Attach(instance,lease,(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterSyncCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.NativeChapterTextCapability));if(trayAdapter)control?.Attach(instance,lease,(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.CaptureCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.MaintenanceCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ParagraphCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterSyncCapability));
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="ready",WordInstanceId=instance,Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability+","+ProtocolVersion.CaptureCapability+","+ProtocolVersion.MaintenanceCapability+","+ProtocolVersion.ParagraphCapability+","+ProtocolVersion.ChapterSyncCapability+","+ProtocolVersion.NativeChapterTextCapability},cancellation);
log?.Invoke("peer-connected");
while (!cancellation.IsCancellationRequested)
{

View File

@ -17,13 +17,13 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai
private int totalBoundaries;
private int totalSuggestions;
public int SessionCount { get { lock (gate) return instances.Values.Sum(i => i.Documents.Count); } }
public void Attach(Guid instance, Guid lease,bool chapters=false)
public void Attach(Guid instance, Guid lease,bool chapters=false,bool nativeChapterText=false)
{
lock (gate)
{
if (instance == Guid.Empty || (!instances.ContainsKey(instance) && instances.Count >= 8)) throw new InvalidDataException("Word instance capacity/identity invalid.");
DetachCore(instance);
instances[instance] = new WordInstance(lease){ChapterCapable=chapters};
instances[instance] = new WordInstance(lease){ChapterCapable=chapters,NativeChapterTextCapable=chapters&&nativeChapterText};
}
}
public void Detach(Guid instance, Guid lease) { lock (gate) { if (instances.TryGetValue(instance, out var state) && state.Lease == lease) DetachCore(instance); } }
@ -98,7 +98,7 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai
if(message.Kind is "workspace-select" or "workspace-refresh"){var position=new Message();Resolve(document,position);message.ChapterId=position.ChapterId;message.SceneId=position.SceneId;}
answer.Kind="workspace-response";return workspace?.Handle(document.Descriptor,message,answer)??Reject(answer,"workspace-unavailable");}
if(message.Kind.StartsWith("chapter-",StringComparison.Ordinal)){
if(!word.ChapterCapable||message.SnapshotId==Guid.Empty||message.OperationMessage==null||message.OperationMessage.Length>2048||message.Kind is not ("chapter-begin" or "chapter-chunk" or "chapter-end")||(message.Kind=="chapter-begin"&&(message.Start<0||message.End<=message.Start||message.End-message.Start>PlotDirector.Companion.Protocol.Manuscript.ChapterFingerprint.MaxCharacters||message.DocumentEnd<message.End||message.DocumentEnd>16000000))||(message.Kind=="chapter-chunk"&&(message.Start<0||message.Start>8*1024*1024||message.Action is not ("text" or "xml" or "ids"))))return Reject(answer,"invalid-chapter-frame");
if(!word.ChapterCapable||(message.Action=="ids-exact"&&!word.NativeChapterTextCapable)||message.SnapshotId==Guid.Empty||message.OperationMessage==null||message.OperationMessage.Length>2048||message.Kind is not ("chapter-begin" or "chapter-chunk" or "chapter-end")||(message.Kind=="chapter-begin"&&(message.Start<0||message.End<=message.Start||message.End-message.Start>PlotDirector.Companion.Protocol.Manuscript.ChapterFingerprint.MaxCharacters||message.DocumentEnd<message.End||message.DocumentEnd>16000000))||(message.Kind=="chapter-chunk"&&(message.Start<0||message.Start>8*1024*1024||message.Action is not ("text" or "xml" or "ids" or "ids-exact"))))return Reject(answer,"invalid-chapter-frame");
return answer;
}
if(message.Kind.StartsWith("ai-",StringComparison.Ordinal))return ai?.Handle(document.Descriptor,message,answer)??Reject(answer,"ai-unavailable");
@ -180,7 +180,7 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai
}
public Guid? ActiveSession(Guid instance) { lock(gate) return instances.GetValueOrDefault(instance)?.ActiveSession; }
public bool HasSession(Guid instance, Guid session) { lock(gate) return instances.TryGetValue(instance,out var word) && word.Documents.ContainsKey(session); }
private sealed class WordInstance(Guid lease) { public bool ChapterCapable;public Guid Lease = lease; public long LastSequence; public Guid? ActiveSession; public Dictionary<Guid,DocumentState> Documents = []; }
private sealed class WordInstance(Guid lease) { public bool ChapterCapable,NativeChapterTextCapable;public Guid Lease = lease; public long LastSequence; public Guid? ActiveSession; public Dictionary<Guid,DocumentState> Documents = []; }
private sealed class DocumentState(DocumentDescriptor descriptor) { public DocumentDescriptor Descriptor = descriptor; public int Cursor;public int StructureEnd; public int? WordCount; public Snapshot? Pending; public Guid SnapshotId; public string ContentFingerprint=""; public List<StructuralBoundary> Boundaries = []; public DocumentAnalysis? Analysis; }
private sealed class Snapshot(Guid id,int expectedEnd,bool analyze) { public readonly DocumentAnalysis Counter=new(analyze); public DocumentAnalysis? Analysis=>analyze?Counter:null; public Guid Id = id; public int ExpectedEnd=expectedEnd; public bool LastComplete; public int End; public int NextParagraph=1; public int Characters; public List<ParagraphFragment> Fragments = []; }
}

View File

@ -8,7 +8,7 @@ public sealed partial class TrayCoordinator
{
public int Book, Attempts, Retries; public string ReviewReason = "";public Guid Manuscript;public long Revision;public Guid Context,Operation,Command;public bool Busy,Supported,Processing,Begun;public long FailedRevision=-1;public DateTime Started,RetryAfter;
public ChapterManifest? Manifest; public ChapterSyncProgress? Completion;public readonly Dictionary<int,(int Start,int End)> Checked=[];
public StringBuilder Text=new(),Xml=new(),Identities=new();public int Start,End,DocumentEnd,CursorWhenQueued,FirstStart=-1;public bool Finished;public bool Wrapped;public readonly HashSet<int> Reviewed=[];public readonly HashSet<int> Visited=[];public string Next="";
public StringBuilder Text=new(),Xml=new(),Identities=new();public int Start,End,DocumentEnd,CursorWhenQueued,FirstStart=-1;public bool Finished;public bool Wrapped;public bool NativeTextVerified;public string IdentityAction="";public readonly HashSet<int> Reviewed=[];public readonly HashSet<int> Visited=[];public string Next="";
}
private readonly Dictionary<Guid,ChapterWork> chapterWork=[];
private readonly SemaphoreSlim chapterProcessing=new(2,2);
@ -21,6 +21,8 @@ public sealed partial class TrayCoordinator
private ChapterSyncProgress? VisibleChapterProgress(TrayDocument doc)
{
if (cloud.Status().Health?.Authentication != "verified")
return new() { State = "Sign-in required", Message = "Sign in to resume synchronisation. The manuscript's saved book association is retained." };
if (!chapterWork.TryGetValue(doc.Session, out var work) || !CurrentChapterWork(doc, work))
return doc.ChapterProgress;
@ -31,7 +33,9 @@ public sealed partial class TrayCoordinator
if (work.Busy || !work.Finished && work.Attempts > 0)
{
var step = work.Processing ? "Verifying chapter with PlotDirector" : "Checking Word chapter";
if (work.Attempts > 0 && work.Attempts <= total) step += $" {work.Attempts} of {total}";
var chapter = work.Manifest?.Chapters.FirstOrDefault(c => c.Start <= work.CursorWhenQueued && work.CursorWhenQueued < c.End);
if (chapter != null) step += $" {Array.IndexOf(work.Manifest!.Chapters, chapter) + 1} of {total}";
step += $" · {accepted} accepted";
return new() { State = "Checking", Total = total, Matching = accepted, Message = step };
}
return doc.ChapterProgress;
@ -121,7 +125,7 @@ public sealed partial class TrayCoordinator
return;
}
var command=new AdapterCommand{Kind="chapter-check",OperationId=work.Operation,BookId=doc.Book,Chapter=new(){Start=position}};
if(Queue(doc,command)){work.Command=command.Id;work.Attempts++;work.CursorWhenQueued=doc.Cursor;work.Busy=true;work.Processing=false;work.Begun=false;work.Start=work.End=0;work.Started=DateTime.UtcNow;work.Text.Clear();work.Xml.Clear();work.Identities.Clear();doc.Status=$"Checking chapter positions ({work.Checked.Count}/{work.Manifest!.Chapters.Length} accepted); Word prose is unchanged.";}
if(Queue(doc,command)){work.Command=command.Id;work.Attempts++;work.CursorWhenQueued=doc.Cursor;work.Busy=true;work.Processing=false;work.Begun=false;work.Start=work.End=0;work.Started=DateTime.UtcNow;work.Text.Clear();work.Xml.Clear();work.Identities.Clear();work.NativeTextVerified=false;work.IdentityAction="";doc.Status=$"Checking chapter positions ({work.Checked.Count}/{work.Manifest!.Chapters.Length} accepted); Word prose is unchanged.";}
}
private void ChapterFrame(TrayDocument doc,Message message,Message answer)
{
@ -131,7 +135,9 @@ public sealed partial class TrayCoordinator
if(answer.Status!="ok"){work.Busy=false;work.FailedRevision=doc.Revision;doc.Status="Chapter reading was rejected; accepted checkpoints are unchanged.";return;}
if(message.Kind=="chapter-begin"){if(work.Begun)return;work.Begun=true;work.Start=message.Start;if(work.FirstStart<0)work.FirstStart=message.Start;work.End=message.End;work.DocumentEnd=message.DocumentEnd;work.Next=message.ChapterTitle;work.Text.Clear();work.Xml.Clear();work.Identities.Clear();return;}
if(message.Kind=="chapter-chunk"){if(!work.Begun||work.Processing)return;
var value=message.Action=="text"?work.Text:message.Action=="ids"?work.Identities:work.Xml;var limit=message.Action=="text"?ChapterFingerprint.MaxCharacters:message.Action=="ids"?ChapterFingerprint.MaxParagraphs*16:8*1024*1024;
var identityFrame=message.Action is "ids" or "ids-exact";
if(identityFrame){if(work.IdentityAction!=""&&work.IdentityAction!=message.Action){StopChapterWork(doc,work,"Mixed native paragraph evidence was rejected.");return;}work.IdentityAction=message.Action;work.NativeTextVerified=message.Action=="ids-exact";}
var value=message.Action=="text"?work.Text:identityFrame?work.Identities:work.Xml;var limit=message.Action=="text"?ChapterFingerprint.MaxCharacters:identityFrame?ChapterFingerprint.MaxParagraphs*16:8*1024*1024;
if(message.Start!=value.Length||value.Length+message.OperationMessage.Length>limit){work.Busy=false;work.FailedRevision=doc.Revision;doc.Status="Incomplete or oversized chapter frames; no checkpoint accepted.";return;}value.Append(message.OperationMessage);return;
}
if(message.Kind=="chapter-end"){if(!work.Begun||work.Processing)return;work.Processing=true;var text=work.Text.ToString();var xml=work.Xml.ToString();var identities=work.Identities.Length==0?null:work.Identities.ToString();work.Text=new();work.Xml=new();work.Identities=new();_ = ProcessChapter(doc,work,text,xml,identities,work.Command,work.Start,work.End,work.Next,work.Operation);}
@ -166,7 +172,8 @@ public sealed partial class TrayCoordinator
if(!await chapterProcessing.WaitAsync(0)){lock(gate)if(CurrentChapterWork(doc,work)&&work.Command==command){work.Busy=false;work.Command=Guid.Empty;work.RetryAfter=DateTime.UtcNow.AddSeconds(1);doc.Status="Waiting for bounded chapter processing; accepted checkpoints are retained.";}return;}
try{
lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;if(work.Wrapped&&start==work.FirstStart){CompleteChapters(doc,work);return;}}
var rows=await Task.Run(()=>ChapterFingerprint.ReadXml(xml,text,identities));xml="";text="";
var nativeTextVerified=work.NativeTextVerified;
var rows=await Task.Run(()=>ChapterFingerprint.ReadXml(xml,text,identities,nativeTextVerified));xml="";text="";
ChapterManifest manifest;lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;manifest=work.Manifest!;}
var hash=ChapterFingerprint.Content(rows.Select(p=>p.Text!));
var candidates=manifest.Chapters.Where(c=>c.HeadingNativeId==rows[0].NativeId).ToArray();

View File

@ -97,7 +97,7 @@ public sealed class AgentLink : IDisposable
lock (gate) activePipe = pipe;
await pipe.ConnectAsync(700, stop.Token).ConfigureAwait(false);
if (!verifyServer(pipe)) throw new UnauthorizedAccessException("Unexpected agent owner.");
await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability+","+ProtocolVersion.CaptureCapability+","+ProtocolVersion.MaintenanceCapability+","+ProtocolVersion.ParagraphCapability+","+ProtocolVersion.ChapterSyncCapability }, stop.Token).ConfigureAwait(false);
await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability+","+ProtocolVersion.TrayCapability+","+ProtocolVersion.CaptureCapability+","+ProtocolVersion.MaintenanceCapability+","+ProtocolVersion.ParagraphCapability+","+ProtocolVersion.ChapterSyncCapability+","+ProtocolVersion.NativeChapterTextCapability }, stop.Token).ConfigureAwait(false);
mailbox.Clear(); // Reconcile authoritative open documents; never replay stale extraction fragments.
await ExchangeAsync(pipe, Reconcile(), stop.Token).ConfigureAwait(false);
attempt = 0; StateChanged?.Invoke("connected");

View File

@ -1 +1 @@
<Project><PropertyGroup><ApplicationVersion>1.0.0.26</ApplicationVersion></PropertyGroup></Project>
<Project><PropertyGroup><ApplicationVersion>1.0.0.27</ApplicationVersion></PropertyGroup></Project>

View File

@ -57,15 +57,17 @@ public static class ChapterFingerprint
public static string Mapping(IEnumerable<string> assignments)=>Content(assignments);
// Parses only the main Word part. Complex constructs require the established bounded reader rather than guessed offsets.
public static ChapterParagraph[] ReadXml(string xml,string rangeText,string? liveIdentities=null)
public static ChapterParagraph[] ReadXml(string xml,string rangeText,string? liveIdentities=null,bool nativeParagraphTextVerified=false)
{
if(xml.Length>8*1024*1024||rangeText.Length>MaxCharacters)throw new ArgumentException("Chapter XML exceeds the bounded reader.");
using var reader=XmlReader.Create(new StringReader(xml),new XmlReaderSettings{DtdProcessing=DtdProcessing.Prohibit,XmlResolver=null,MaxCharactersInDocument=8*1024*1024});
var root=XDocument.Load(reader);XNamespace w="http://schemas.openxmlformats.org/wordprocessingml/2006/main",pkg="http://schemas.microsoft.com/office/2006/xmlPackage",w14="http://schemas.microsoft.com/office/word/2010/wordml";
var document=root.Root?.Name==w+"document"?root.Root:root.Descendants(pkg+"part").Where(p=>(string?)p.Attribute(pkg+"name")=="/word/document.xml").SelectMany(p=>p.Descendants(w+"document")).SingleOrDefault();
var body=document?.Element(w+"body")??throw new ArgumentException("Main Word document part is missing.");
var unsafeNames=new HashSet<XName>(new[]{"tbl","txbxContent","fldChar","instrText","footnoteReference","endnoteReference","drawing","object","ins","del","moveFrom","moveTo","altChunk","sym"}.Select(n=>w+n));
var unsafeNames=new HashSet<XName>(new[]{"tbl","txbxContent","fldChar","instrText","footnoteReference","endnoteReference","object","ins","del","moveFrom","moveTo","altChunk","sym"}.Select(n=>w+n));
if(body.Descendants().Any(e=>unsafeNames.Contains(e.Name)))throw new ArgumentException("Complex chapter content needs bounded reconciliation; positions were not guessed.");
var hasDrawings=body.Descendants(w+"drawing").Any();
if(hasDrawings&&(!nativeParagraphTextVerified||liveIdentities==null))throw new ArgumentException("Pictures require exact native paragraph text and span verification; XML projection was not guessed.");
var styles=root.Descendants(w+"style").Where(e=>e.Attribute(w+"styleId")!=null).GroupBy(e=>(string)e.Attribute(w+"styleId")!).ToDictionary(g=>g.Key,g=>g.First());
int Outline(XElement paragraph){
var properties=paragraph.Element(w+"pPr");var seen=new HashSet<string>();
@ -87,21 +89,33 @@ public static class ChapterFingerprint
var outline=Outline(p);
return new ChapterParagraph{NativeId=WordParagraphIdentity.Normalise((string?)p.Attribute(w14+"paraId")),Text=text.ToString(),Length=text.Length,Outline=outline};
}).ToArray();
if(string.Concat(rows.Select(p=>p.Text))!=rangeText)throw new ArgumentException("XML paragraph text does not equal Word Range.Text; no positions were accepted.");
if(!hasDrawings&&string.Concat(rows.Select(p=>p.Text))!=rangeText)throw new ArgumentException("XML paragraph text does not equal Word Range.Text; no positions were accepted.");
if (liveIdentities != null)
{
// Each live paragraph contributes an eight-digit ID and an eight-digit UTF-16 span.
if (liveIdentities.Length != rows.Length * 16)
throw new ArgumentException("Live Word paragraph count differs from chapter XML.");
var offset=0;
var paragraphs=body.Descendants(w+"p").Where(p=>!p.Ancestors(w+"p").Any()).ToArray();
for (var i = 0; i < rows.Length; i++)
{
var id = WordParagraphIdentity.Normalise(liveIdentities.Substring(i * 16, 8));
if(nativeParagraphTextVerified)
{
if(!int.TryParse(liveIdentities.Substring(i*16+8,8),System.Globalization.NumberStyles.HexNumber,System.Globalization.CultureInfo.InvariantCulture,out var measured)||measured<=0||measured>rangeText.Length-offset)
throw new ArgumentException("Native paragraph text spans do not cover the exact chapter range.");
var nativeText=rangeText.Substring(offset,measured);
if(!paragraphs[i].Descendants(w+"drawing").Any()&&rows[i].Text!=nativeText)
throw new ArgumentException("Native paragraph text differs from XML outside picture content.");
rows[i].Text=nativeText;rows[i].Length=measured;offset+=measured;
}
var span = rows[i].Length.ToString("X8", System.Globalization.CultureInfo.InvariantCulture);
if (id.Length == 0 || liveIdentities.Substring(i * 16 + 8, 8) != span ||
(rows[i].NativeId.Length != 0 && rows[i].NativeId != id))
throw new ArgumentException("Live Word paragraph identity or span differs from chapter XML.");
rows[i].NativeId = id;
}
if(nativeParagraphTextVerified&&offset!=rangeText.Length)throw new ArgumentException("Native paragraph text spans leave an incomplete chapter range.");
}
Identity(rows);Content(rows.Select(p=>p.Text!));return rows;
}

View File

@ -5,6 +5,7 @@ namespace PlotDirector.Companion.Protocol;
public static class ProtocolVersion
{
public const int Current = 1;
public const string NativeChapterTextCapability="chapter-native-text-v1";
public const string ChapterSyncCapability="chapter-sync-v1";
public const string ParagraphCapability="paragraph-snapshots-v1";
public const string MaintenanceCapability="document-maintenance-v1";

View File

@ -10,7 +10,7 @@ internal static class ChapterAgentTests
{
var handler=new Handler();using var cloud=new CloudGateway(handler,_=>{});cloud.Connect("https://chapters.test/");await Until(()=>cloud.Status().Books.Any());await cloud.CheckConnection();
var sessions=new SessionManager();using var ai=new ChapterAiWork(cloud);var tray=new TrayCoordinator(sessions,cloud,ai);var instance=Guid.NewGuid();var session=Guid.NewGuid();var lease=Guid.NewGuid();handler.Manuscript=Guid.NewGuid();long sequence=0;
sessions.Attach(instance,lease,chapters:true);tray.Attach(instance,lease,capture:true,paragraphs:true,chapters:true);
sessions.Attach(instance,lease,chapters:true,nativeChapterText:true);tray.Attach(instance,lease,capture:true,paragraphs:true,chapters:true);
Message Send(Message message){message.WordInstanceId=instance;message.SessionId=session;message.Revision=1;message.Sequence=++sequence;return tray.Exchange(instance,message,sessions.Apply(lease,message),lease);}
Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Synthetic chapter manuscript.docx"}]});tray.SelectBook(session,3,false);Send(new(){Kind="active"});Send(new(){Kind="selection",Start=0,End=0,WordSaved=true});
using var stop=new CancellationTokenSource();var heartbeats=tray.Heartbeat(stop.Token);
@ -18,7 +18,7 @@ internal static class ChapterAgentTests
AdapterCommand? command=null;for(int n=0;n<200&&command==null;n++){var pending=Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command;if(pending?.Kind=="chapter-check")command=pending;await Task.Delay(20);}
Check(command?.Kind=="chapter-check","Reopened chapter-capable document requests a bounded current-chapter read, never a full snapshot");
var text="Chapter 1\rExact prose\r";var xml="<w:document xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' xmlns:w14='http://schemas.microsoft.com/office/word/2010/wordml'><w:body><w:p w14:paraId='00000001'><w:pPr><w:outlineLvl w:val='0'/></w:pPr><w:r><w:t>Chapter 1</w:t></w:r></w:p><w:p w14:paraId='00000002'><w:r><w:t>Exact prose</w:t></w:r></w:p></w:body></w:document>";
void Frames(AdapterCommand read){Send(new(){Kind="chapter-begin",SnapshotId=read.Id,BookId=3,Start=0,End=text.Length,DocumentEnd=text.Length,WordSaved=true});Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="text",Start=0,OperationMessage=text});Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="xml",Start=0,OperationMessage=xml});Send(new(){Kind="chapter-end",SnapshotId=read.Id});}
void Frames(AdapterCommand read,bool exact=false){Send(new(){Kind="chapter-begin",SnapshotId=read.Id,BookId=3,Start=0,End=text.Length,DocumentEnd=text.Length,WordSaved=true});Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="text",Start=0,OperationMessage=text});Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="xml",Start=0,OperationMessage=xml});if(exact){var evidence=ChapterFingerprint.ReadXml(xml,text);Send(new(){Kind="chapter-chunk",SnapshotId=read.Id,Action="ids-exact",Start=0,OperationMessage=string.Concat(evidence.Select(p=>p.NativeId+p.Length.ToString("X8")))});}Send(new(){Kind="chapter-end",SnapshotId=read.Id});}
Frames(command!);await Until(()=>handler.Validations>0);await Until(()=>handler.Finishes>0);
Check(handler.Bodies.All(b=>JsonSerializer.Deserialize<ChapterObservation>(b,new JsonSerializerOptions(JsonSerializerDefaults.Web))!.Paragraphs.All(p=>p.Text==null)),"Unchanged chapter uploads hashes and native identity evidence, not manuscript prose");
Check(!handler.Paths.Any(p=>p.Contains("manuscript-capture")),"Chapter lifecycle does not invoke the full manuscript capture endpoint");
@ -39,23 +39,36 @@ internal static class ChapterAgentTests
await Until(() => tray.ChapterProgressForDisplay(session)?.State == "Needs review");
Check(tray.ChapterProgressForDisplay(session)!.Message.Contains("native chapter identities"), "Unindexed legacy identity displays actionable review instead of a zero-count scan");
Check(Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command?.Kind != "chapter-check" && handler.Validations == before, "No automatic chapter read is queued when every legacy heading lacks a native ID");
handler.LegacyManifest = false; handler.RejectValidation = true;
session = Guid.NewGuid();
Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Rejected chapter fixture.docx"}]});
tray.SelectBook(session,3,false);Send(new(){Kind="active"});Send(new(){Kind="selection",Start=0,End=0,WordSaved=true});
AdapterCommand? rejectedRead=null;for(int n=0;n<200&&rejectedRead==null;n++){var pending=Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command;if(pending?.Kind=="chapter-check")rejectedRead=pending;await Task.Delay(20);}
Check(rejectedRead!=null,"Rejected-chapter fixture starts a bounded read");Frames(rejectedRead!,true);
await Until(()=>tray.ChapterProgressForDisplay(session)?.State=="Needs review");
Check(tray.ChapterProgressForDisplay(session)!.Message.Contains("Synthetic storage refusal"),"Specific server rejection survives completion and is displayed to the author");
var rejectedCount=handler.Validations;
for(int n=0;n<20;n++)Check(Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command?.Kind!="chapter-check","Stationary cursor does not restart a rejected chapter");
await Task.Delay(650);Check(handler.Validations==rejectedCount,"Rejected chapter waits for an explicit retry rather than reading Word repeatedly");
session = oldSession;
var wrong=new Message{Kind="chapter-chunk",SnapshotId=command!.Id,Action="xml",Start=0,OperationMessage="wrong"};var legacySessions=new SessionManager();legacySessions.Attach(instance,lease);long legacySequence=0;Message Legacy(Message m){m.WordInstanceId=instance;m.SessionId=session;m.Sequence=++legacySequence;m.Revision=1;return legacySessions.Apply(lease,m);}Legacy(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Legacy"}]});Check(Legacy(wrong).Status=="invalid-chapter-frame","Chapter frames require negotiated native capability; legacy clients remain isolated");
legacySessions.Attach(instance,lease,chapters:true);Legacy(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Legacy native IDs"}]});
Check(Legacy(new(){Kind="chapter-chunk",SnapshotId=Guid.NewGuid(),Action="ids-exact",OperationMessage="000000010000000A"}).Status=="invalid-chapter-frame","Native text certification requires its separately negotiated capability");
}finally{stop.Cancel();try{await heartbeats;}catch(OperationCanceledException){}}
}
private static void Check(bool ok,string message){if(!ok)throw new Exception(message);Console.WriteLine("PASS "+message);}
private static async Task Until(Func<bool> condition){for(int i=0;i<300;i++){if(condition())return;await Task.Delay(30);}throw new Exception("Chapter test timed out");}
private sealed class Handler:HttpMessageHandler
{
public Guid Manuscript;public bool LegacyManifest;public int Validations,Finishes;public List<string> Bodies=[];public List<string> Paths=[];
public Guid Manuscript;public bool LegacyManifest,RejectValidation;public int Validations,Finishes;public List<string> Bodies=[];public List<string> Paths=[];
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancel)
{
var path=request.RequestUri!.AbsolutePath;Paths.Add(path);HttpResponseMessage Json(object value)=>new(HttpStatusCode.OK){Content=JsonContent.Create(value)};
if(path.EndsWith("/pair"))return Json(new{code="00112233445566778899AABB"});if(path.EndsWith("/token"))return Json(new{accessToken="fixture"});if(path.EndsWith("/books"))return Json(new[]{new{bookId=3,title="Synthetic book"}});if(path.EndsWith("/connection"))return Json(new{state="Connected",authentication="verified",server="online",expiresUtc=DateTime.UtcNow.AddHours(4)});
if(path.EndsWith("/presence")){var value=await request.Content!.ReadFromJsonAsync<NativePresence>(cancel);value!.ChapterSyncSupported=true;value.ParagraphRevision=1;return Json(value);}
if(path.EndsWith("/chapter-sync"))return Json(new ChapterManifest{BookId=3,ManuscriptId=Manuscript,Revision=1,Chapters=[new(){ChapterId=10,HeadingNativeId=LegacyManifest?"":"00000001",ContentHash=ChapterFingerprint.Content(["Chapter 1\r","Exact prose\r"]),Start=0,End=22,ParagraphCount=2}]});
if(path.EndsWith("/validate")){var body=await request.Content!.ReadAsStringAsync(cancel);Bodies.Add(body);Validations++;return Json(new ChapterSyncReply{Accepted=true,State="Synchronised",ChapterId=10,Revision=1,Message="Chapter accepted."});}
if(path.EndsWith("/finish")){Finishes++;return Json(new ChapterSyncProgress{Total=1,Checked=1,Matching=1,State="Synchronised",Message="All chapters accepted."});}
if(path.EndsWith("/validate")){var body=await request.Content!.ReadAsStringAsync(cancel);Bodies.Add(body);Validations++;if(RejectValidation)return Json(new ChapterSyncReply{State="Failed",ChapterId=10,Revision=1,Message="Synthetic storage refusal: retry the chapter."});return Json(new ChapterSyncReply{Accepted=true,State="Synchronised",ChapterId=10,Revision=1,Message="Chapter accepted."});}
if(path.EndsWith("/finish")){Finishes++;if(RejectValidation)return Json(new ChapterSyncProgress{Total=1,Matching=0,State="Needs review",Message="No chapters accepted."});return Json(new ChapterSyncProgress{Total=1,Checked=1,Matching=1,State="Synchronised",Message="All chapters accepted."});}
return Json(new{});
}
}

View File

@ -21,6 +21,20 @@ internal static class PersistentConnectionTests
using var stop=new CancellationTokenSource();var loop=cloud.RunConnectionLoop(stop.Token);await Until(()=>cloud.Status().Health?.State=="Reconnecting");await Task.Delay(200);check(server.RenewAttempts==1,"offline startup makes a bounded renewal attempt without browser approval");
server.Offline=false;clock.Advance(TimeSpan.FromMinutes(1));await Until(()=>cloud.Status().Health?.State=="Connected");stop.Cancel();await loop;
check(approvals==1&&cloud.RestoreBinding(manuscript)==3&&cloud.Preferences.Width==975&&cloud.Preferences.RememberInDocument&&cloud.Preferences.AdvancedMode,"process/network recovery restores scoped association and preferences without interaction");
var sessions=new SessionManager();using var ai=new ChapterAiWork(cloud);var tray=new TrayCoordinator(sessions,cloud,ai);
var instance=Guid.NewGuid();var session=Guid.NewGuid();var lease=Guid.NewGuid();
sessions.Attach(instance,lease,chapters:true);tray.Attach(instance,lease,chapters:true);
var registration=new Message{Kind="document",WordInstanceId=instance,SessionId=session,Sequence=1,Documents=[new(){SessionId=session,ManuscriptId=manuscript,Title="Synthetic linked manuscript.docx",RememberedBook=3,AssociationSite="https://fixture.invalid/"}]};
tray.Exchange(instance,registration,sessions.Apply(lease,registration),lease);
using var trayStop=new CancellationTokenSource();var ticking=tray.Tick(trayStop.Token);
try{
await Until(()=>tray.Documents.Single().Book==3);
server.Offline=true;clock.Advance(TimeSpan.FromMinutes(11));_ = cloud.Status();await cloud.ReconnectAsync();
check(tray.ChapterProgressForDisplay(session)?.State=="Sign-in required"&&tray.Documents.Single().RememberedBook==3,"expired authentication displays sign-in required and retains the open document's saved association");
server.Offline=false;clock.Advance(TimeSpan.FromMinutes(1));await cloud.ReconnectAsync();
await Until(()=>tray.Documents.Single().Book==3&&cloud.Status().Health?.State=="Connected");
check(tray.Documents.Single().RememberedBook==3&&cloud.RestoreBinding(manuscript)==3,"reauthentication restores the existing open manuscript without writing a new association");
}finally{trayStop.Cancel();try{await ticking;}catch(OperationCanceledException){}}
var context=cloud.Status().AuthenticationContext;clock.Advance(TimeSpan.FromMinutes(11));await cloud.ReconnectAsync();
check(cloud.Status().AuthenticationContext==context&&cloud.Status().Health?.State=="Connected"&&approvals==1,"access expiry renews without changing account context or asking for browser approval");
server.AllowBook=false;await cloud.CheckConnection();check(cloud.RestoreBinding(manuscript)==null,"persisted association is not restored when current book permission is missing");server.AllowBook=true;await cloud.CheckConnection();

View File

@ -3,6 +3,6 @@ using System.Runtime.InteropServices;
[assembly: AssemblyTitle("PlotDirector Word Companion — Native development")]
[assembly: AssemblyCompany("Nick Beckley")]
[assembly: AssemblyProduct("PlotDirector")]
[assembly: AssemblyVersion("1.0.0.26")]
[assembly: AssemblyFileVersion("1.0.0.26")]
[assembly: AssemblyVersion("1.0.0.27")]
[assembly: AssemblyFileVersion("1.0.0.27")]
[assembly: ComVisible(false)]

View File

@ -75,7 +75,7 @@ namespace PlotDirector.WordAddIn
link.StateChanged += state => PostToUi(() => {
ConnectionState = state;
if(state!="connected")
{traySupported=false;
{traySupported=false;nativeChapterTextSupported=false;
foreach(var doc in documents.Values){StopAi(doc,"Agent disconnected. Successful AI suggestions retained; reconnect before retrying.");}
}
if (state == "connected")
@ -86,7 +86,7 @@ namespace PlotDirector.WordAddIn
invalidateRibbon();
});
link.Received += message => {
if(message.Status=="ready")PostToUi(()=>traySupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.TrayCapability));
if(message.Status=="ready")PostToUi(()=>{var capabilities=(message.Capabilities??"").Split(',');traySupported=capabilities.Contains(ProtocolVersion.TrayCapability);nativeChapterTextSupported=capabilities.Contains(ProtocolVersion.NativeChapterTextCapability);});
if(message.ChapterStatusProvided&&message.SessionId!=Guid.Empty)PostToUi(()=>ReceiveChapterStatus(message));
if(message.Command!=null)PostToUi(()=>HandleCommand(message.Command));
if(message.WordCount.HasValue)PostToUi(()=>{var doc=documents.Values.FirstOrDefault(d=>d.Session==message.SessionId&&d.Revision==message.Revision);if(doc!=null)doc.WordCount=message.WordCount;});

View File

@ -11,10 +11,12 @@ namespace PlotDirector.WordAddIn
private string serverBook = "", serverChapter = "", serverScene = "";
private int serverBookId;
private long serverRevision = -1;
private bool nativeChapterTextSupported;
private ChapterSyncProgress serverChapterProgress;
public bool HasRibbonBook => active != null && ConnectionState == "connected" && serverBookId > 0;
public string RibbonBook => HasRibbonBook && serverBook.Length > 0 ? serverBook : "No linked book";
public bool HasRibbonBook => active != null && ConnectionState == "connected" && serverBookId > 0 && serverChapterProgress?.State != "Sign-in required";
public string RibbonBook => active != null && serverBook.Length > 0 ? serverBook
: active?.BookId > 0 ? "Saved book association" : "No linked book";
private bool HasCurrentRibbonState => HasRibbonBook && active.Revision == serverRevision;
public string RibbonLocation => HasCurrentRibbonState && serverScene.Length > 0
? (serverChapter.Length == 0 ? serverScene : serverChapter + " · " + serverScene)
@ -25,6 +27,7 @@ namespace PlotDirector.WordAddIn
get
{
if (ConnectionState != "connected") return "Not connected";
if (serverChapterProgress?.State == "Sign-in required") return "Sign-in required";
if (!HasRibbonBook) return "No linked book";
if (!HasCurrentRibbonState) return "Changes found";
if (serverChapterProgress == null) return "Not yet checked";
@ -45,7 +48,7 @@ namespace PlotDirector.WordAddIn
public string RibbonSyncProgress => ChapterStatusLabel == "Synchronising" && serverChapterProgress.Total > 0
? serverChapterProgress.Message
: ChapterStatusLabel == "Review needed" ? "See status tooltip" : " ";
public string ChapterStatusTip => (HasCurrentRibbonState ? serverChapterProgress?.Message : null)
public string ChapterStatusTip => (HasCurrentRibbonState || serverChapterProgress?.State == "Sign-in required" ? serverChapterProgress?.Message : null)
?? "Synchronise to verify the manuscript position.";
public void OpenWritingWorkspace(string command)
@ -98,7 +101,7 @@ namespace PlotDirector.WordAddIn
}
private sealed class ChapterRead
{
public AdapterCommand Command;public int Phase,Seek,Steps,Start,End,Offset;public string Text="",Xml="",NextId="";public bool Begun; public int IdentityPosition; public readonly System.Text.StringBuilder Identities = new System.Text.StringBuilder(); public string IdentityFrames = "";
public AdapterCommand Command;public int Phase,Seek,Steps,Start,End,Offset;public string Text="",Xml="",NextId="";public bool Begun; public int IdentityPosition; public readonly System.Text.StringBuilder Identities = new System.Text.StringBuilder(); public string IdentityFrames = ""; public bool NativeTextRequired; public readonly System.Text.StringBuilder NativeText = new System.Text.StringBuilder();
}
private readonly Dictionary<Guid,ChapterRead> chapterReads=new Dictionary<Guid,ChapterRead>();
private void CancelChapterRead(LocalDocument doc){chapterReads.Remove(doc.Session);scheduler.Cancel("chapter:"+doc.Session);}
@ -153,6 +156,10 @@ namespace PlotDirector.WordAddIn
}else if(read.Phase==3){
range=Com(()=>doc.Document.Range(read.Start,read.End));read.Xml=Com(()=>range.WordOpenXML,"chapter-range-xml")??"";
if(read.Xml.Length>8*1024*1024)throw new InvalidOperationException("Chapter XML exceeds the bounded transport. Use existing bounded synchronisation.");
// Only drawings need the more expensive direct paragraph text fallback.
// A lexical false positive merely performs extra verification.
read.NativeTextRequired=read.Xml.IndexOf(":drawing",StringComparison.Ordinal)>=0||read.Xml.IndexOf("<drawing",StringComparison.Ordinal)>=0;
if(read.NativeTextRequired&&!nativeChapterTextSupported)throw new InvalidOperationException("Update the Companion agent to verify picture paragraphs. Existing mappings are retained.");
read.IdentityPosition=read.Start;read.Phase=7;
}else if(read.Phase==7){
// One paragraph per scheduler turn. Word COM objects never leave the STA.
@ -161,15 +168,21 @@ namespace PlotDirector.WordAddIn
var start=Com(()=>range.Start);var end=Com(()=>range.End);
if(start!=read.IdentityPosition||end<=start||end>read.End||read.Identities.Length/16>=ChapterFingerprint.MaxParagraphs)
throw new InvalidOperationException("Live Word paragraph boundaries do not match the chapter.");
if(read.NativeTextRequired)
{
var nativeText=Com(()=>range.Text,"chapter-native-paragraph-text")??"";
if(nativeText.Length!=end-start)throw new InvalidOperationException("Native paragraph text and Word span disagree; picture positions were not guessed.");
read.NativeText.Append(nativeText);
}
read.Identities.Append(ReadLiveParagraphId(paragraph));
read.Identities.Append((end-start).ToString("X8",System.Globalization.CultureInfo.InvariantCulture));
read.IdentityPosition=end;
if(end==read.End){read.IdentityFrames=read.Identities.ToString();read.Phase=4;}
if(end==read.End){if(read.NativeTextRequired&&read.NativeText.ToString()!=read.Text)throw new InvalidOperationException("Native paragraph text does not equal the chapter range; retry after saving Word.");read.IdentityFrames=read.Identities.ToString();read.Phase=4;}
}else{
if(!read.Begun){if(!link.TryPost(new Message{Kind="chapter-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id,OperationId=read.Command.OperationId,BookId=read.Command.BookId,DocumentEnd=doc.End,Start=read.Start,End=read.End,WordSaved=true,ChapterTitle=read.NextId}))return;read.Begun=true;}
for(int n=0;n<4&&watch.ElapsedMilliseconds<20;n++){
var source=read.Phase==4?read.Text:read.Phase==5?read.Xml:read.IdentityFrames;
if(read.Offset<source.Length){var count=Math.Min(2048,source.Length-read.Offset);if(!link.TryPost(new Message{Kind="chapter-chunk",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id,Action=read.Phase==4?"text":read.Phase==5?"xml":"ids",Start=read.Offset,OperationMessage=source.Substring(read.Offset,count)}))return;read.Offset+=count;}
if(read.Offset<source.Length){var count=Math.Min(2048,source.Length-read.Offset);if(!link.TryPost(new Message{Kind="chapter-chunk",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id,Action=read.Phase==4?"text":read.Phase==5?"xml":read.NativeTextRequired?"ids-exact":"ids",Start=read.Offset,OperationMessage=source.Substring(read.Offset,count)}))return;read.Offset+=count;}
else if(read.Phase<8){read.Phase=read.Phase==4?5:8;read.Offset=0;}
else{if(!link.TryPost(new Message{Kind="chapter-end",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id}))return;CancelChapterRead(doc);return;}
}

View File

@ -1,7 +1,7 @@
{
"version": "1.0.0.26",
"msiVersion": "1.0.26",
"productCode": "{1C8B5834-0157-4E05-A31D-9E96C80FFBFF}",
"version": "1.0.0.27",
"msiVersion": "1.0.27",
"productCode": "{E804E119-8376-4439-9BAD-47F7F37C5734}",
"upgradeCode": "{641A087B-9779-458C-B290-BCBBAD49319A}",
"atlasBaseline": "c6cdfbc3b17107a8d269561c319d946c8e337835",
"baselineProductCode": "{98F46939-764D-407F-BD1F-1D88315D010A}",

View File

@ -0,0 +1,189 @@
using System.Diagnostics;
using System.Security.Claims;
using System.Text.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using PlotDirector.Companion.Protocol;
using PlotDirector.Companion.Protocol.Manuscript;
using PlotLine.Controllers;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Services.Manuscript;
using PlotLine.Services.NativeCompanion;
// Explicit opt-in Development integration. Creates only a new synthetic project;
// never updates an existing author's book. A copy-only backup precedes provisioning.
internal static class ChapterAcceptanceDevelopmentTests
{
public static async Task Run(string[] args)
{
if (!OperatingSystem.IsLinux() || args.Length != 2 || !int.TryParse(args[1], out var user) || user <= 0)
throw new InvalidOperationException("Use --chapter-acceptance-dev <development-fixture-owner-id>");
var start = new ProcessStartInfo("sudo") { RedirectStandardOutput = true };
foreach (var value in new[] { "-n", "cat", "/etc/plotdirector/plotdirector.env" }) start.ArgumentList.Add(value);
using var process = Process.Start(start)!;
var environment = await process.StandardOutput.ReadToEndAsync();
await process.WaitForExitAsync();
if (process.ExitCode != 0) throw new Exception("Development configuration inaccessible");
var connection = environment.Split('\n').Single(l => l.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=', 2)[1].Trim().Trim('"', '\'');
if (new SqlConnectionStringBuilder(connection).InitialCatalog != "PlotDirector_Development") throw new Exception("Wrong database");
using (var db = new SqlConnection(connection))
{
await db.OpenAsync();
using var verify = new SqlCommand("SELECT DB_NAME()", db);
if ((string?)await verify.ExecuteScalarAsync() != "PlotDirector_Development") throw new Exception("Wrong database");
var backup = $"/var/opt/mssql/backup/chapter-acceptance-{DateTime.UtcNow:yyyyMMddTHHmmss}-{Guid.NewGuid():N}.bak";
using var command = new SqlCommand("BACKUP DATABASE [PlotDirector_Development] TO DISK=@path WITH COPY_ONLY,CHECKSUM,COMPRESSION", db) { CommandTimeout = 300 };
command.Parameters.AddWithValue("@path", backup);
await command.ExecuteNonQueryAsync();
var check = new ProcessStartInfo("sudo");
foreach (var value in new[] { "-n", "docker", "exec", "atlas-sql-server", "test", "-s", backup }) check.ArgumentList.Add(value);
using var backupCheck = Process.Start(check)!;
await backupCheck.WaitForExitAsync();
if (backupCheck.ExitCode != 0) throw new Exception("Backup missing");
}
var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
{ ["ConnectionStrings:DefaultConnection"] = connection, ["Features:ParagraphManuscripts"] = "true" }).Build();
var factory = new SqlConnectionFactory(config);
var projects = new ProjectRepository(factory);
var project = await projects.SaveAsync(new() { ProjectName = "Synthetic chapter acceptance " + Guid.NewGuid().ToString("N"), CreatedByUserID = user }, user, null);
try
{
var books = new BookRepository(factory);
var book = await books.SaveAsync(new() { ProjectID = project, BookTitle = "Synthetic chapter scale qualification", CreatedByUserID = user });
var lookup = await new LookupRepository(factory).GetAllAsync();
var canonicalChapters = new List<int>();
var canonicalScenes = new List<int>();
for (var i = 0; i < 48; i++)
{
var chapter = await new ChapterRepository(factory).SaveAsync(new() { BookID = book, ChapterNumber = i + 1, ChapterTitle = "Synthetic chapter " + i, RevisionStatusID = lookup.RevisionStatuses.First().RevisionStatusID, SortOrder = i + 1 });
canonicalChapters.Add(chapter);
canonicalScenes.Add(await new SceneRepository(factory).SaveAsync(new() { ChapterID = chapter, SceneNumber = 1, SceneTitle = "Synthetic scene " + i, RevisionStatusID = lookup.RevisionStatuses.First().RevisionStatusID, TimeModeID = lookup.TimeModes.First().TimeModeID, TimeConfidenceID = lookup.TimeConfidences.First().TimeConfidenceID, SortOrder = 1 }));
}
var rows = new List<ParagraphOccurrence>();
var spans = new List<ParagraphBootstrapScene>();
var position = 0;
for (var chapter = 0; chapter < 48; chapter++)
{
var count = chapter == 0 ? 233 : chapter == 47 ? 128 : 176;
var firstOrdinal = rows.Count;
for (var n = 0; n < count; n++)
{
var text = n == 0 ? $"Synthetic chapter {chapter}\r" : $"Synthetic paragraph {rows.Count}: " + new string('x', 420) + "\r";
rows.Add(new() { Ordinal = rows.Count, Start = position, End = position + text.Length, Text = text, Outline = n == 0 ? 1 : 10 });
position += text.Length;
}
spans.Add(new() { ChapterId = canonicalChapters[chapter], SceneId = canonicalScenes[chapter], Start = firstOrdinal + 2, End = rows.Count, Title = "Synthetic scene " + chapter });
}
var repository = new ParagraphManuscriptRepository(factory);
var checkpoints = new ChapterSyncRepository(factory);
var original = ParagraphManuscriptEngine.Bootstrap(book, project, Guid.NewGuid(), rows.ToArray(), spans);
original.Mode = "Manual";
original.SnapshotHash = ParagraphManuscriptEngine.Hash(original.Paragraphs.Select(p => p.Occurrence).ToArray());
original = await repository.Save(user, original, -1, Guid.NewGuid());
Check(original.Paragraphs.Count == 8457, "Representative 8,457-paragraph, 48-chapter fixture");
var session = Guid.NewGuid(); var instance = Guid.NewGuid(); const string grant = "synthetic-chapter-test";
var presence = new NativePresenceStore(TimeProvider.System);
void Observe(long revision = 0) => Check(presence.Put(user, grant, DateTimeOffset.UtcNow.AddHours(1), instance, session, new() { BookId = book, ManuscriptId = original.ManuscriptId, Revision = revision, Sequence = DateTime.UtcNow.Ticks, WordAvailable = true, WordRunning = true, WordSaved = true, CanChapterSync = true }), "Eligible saved Word session");
var access = new WordCompanionRepository(factory);
var imports = new OnboardingBuildRepository(factory);
var reconciliation = new ParagraphManuscriptService(repository, access, books, imports, new ManuscriptTextStatisticsService(new ManuscriptTextStatisticsRepository(factory), imports), config);
var service = new ChapterSyncService(repository, checkpoints, access, reconciliation, presence, TimeProvider.System);
var controller = new NativeChapterSyncController(service) { ControllerContext = new() { HttpContext = new DefaultHttpContext() } };
controller.HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new(ClaimTypes.NameIdentifier, user.ToString()), new("NativeCompanion.Grant", grant)], "SyntheticAuthenticatedFixture"));
async Task<ChapterSyncReply> Accept(ChapterObservation proof)
{
Observe(proof.WordRevision);
var elapsed = Stopwatch.StartNew();
var action = await controller.Validate(book, proof);
var reply = (action as OkObjectResult)?.Value as ChapterSyncReply;
if(reply?.Accepted != true) throw new Exception($"Chapter acceptance refused after {elapsed.ElapsedMilliseconds} ms: {((action as ObjectResult)?.Value as ChapterSyncReply)?.Message ?? action.GetType().Name}");
Check(true, "Controller returned accepted after durable commit");
Check(elapsed.Elapsed < TimeSpan.FromSeconds(15), $"Acceptance fits the client deadline ({elapsed.ElapsedMilliseconds} ms)");
return reply!;
}
ChapterObservation Proof(ParagraphManuscript state, int chapter)
{
var part = ChapterCheckpointEngine.Parts(state)[chapter];
var evidence = part.Rows.Select(p => new ChapterParagraph { NativeId = p.Occurrence.NativeId.Length > 0 ? p.Occurrence.NativeId : (p.Occurrence.Ordinal + 1).ToString("X8"), Length = p.Occurrence.Text.Length, Outline = p.Occurrence.Outline }).ToArray();
return new() { InstanceId = instance, SessionId = session, ManuscriptId = original.ManuscriptId, BaseRevision = state.Revision, ChapterId = part.Chapter.CanonicalId, Start = part.Rows[0].Occurrence.Start, End = part.Rows[^1].Occurrence.End, NextHeadingId = part.End < state.Paragraphs.Count ? (state.Paragraphs[part.End].Occurrence.NativeId.Length > 0 ? state.Paragraphs[part.End].Occurrence.NativeId : (part.End + 1).ToString("X8")) : "", ContentHash = ChapterFingerprint.Content(part.Rows.Select(p => p.Occurrence.Text)), IdentityHash = ChapterFingerprint.Identity(evidence), Paragraphs = evidence };
}
Observe();
var repair = await service.Repair(user, book, instance, session);
var first = Proof(original, 0); first.OperationId = repair;
await Accept(first);
var saved = (await repository.Get(user, book))!;
Check(saved.ChapterCheckpoints.Count == 1 && (await checkpoints.List(user, book, session, 0)).Count == 1, "Fresh database read confirms durable checkpoint");
Check(saved.Paragraphs.Select(p => (p.Occurrence.Id, p.Occurrence.Text, p.SceneId, p.ChapterId)).SequenceEqual(original.Paragraphs.Select(p => (p.Occurrence.Id, p.Occurrence.Text, p.SceneId, p.ChapterId))), "Adoption preserves every GUID, exact paragraph and scene assignment");
var scenePosition = ChapterCheckpointEngine.Validate(saved, first, DateTime.UtcNow).Positions.First(p => p.SceneId.HasValue);
Check((await checkpoints.Position(user, book, original.ManuscriptId, session, 0, scenePosition.Start))?.SceneID == canonicalScenes[0], "Writing Context resolves the current chapter before unrelated chapters finish");
presence = new NativePresenceStore(TimeProvider.System); // Simulate process loss: trust is recovered through repository, not an in-memory cache.
// A fresh service reads the committed manifest even though no other chapter has been processed.
service = new ChapterSyncService(repository, checkpoints, access, reconciliation, presence, TimeProvider.System);
Observe();
var manifest = await service.Manifest(user, book, session, 0);
Check(manifest.Chapters.Count(c => c.State == "Synchronised") == 1, "Interrupted work resumes from the persisted first checkpoint");
controller = new NativeChapterSyncController(service) { ControllerContext = controller.ControllerContext };
await Accept(first); // Same request is idempotent after restart.
repair = await service.Repair(user, book, instance, session);
var second = Proof(saved, 1); second.OperationId = repair;
await Accept(second);
saved = (await repository.Get(user, book))!;
Check(saved.ChapterCheckpoints.Count == 2 && saved.SnapshotHash == ParagraphManuscriptEngine.Hash(saved.Paragraphs.Select(p => p.Occurrence).ToArray()), "Multiple durable adoptions retain the coherent full-snapshot hash");
Check(presence.ChapterProgress(user, book, instance, session, 0)?.Matching == 2, "Live progress counts persisted acceptances immediately");
var partial = await service.Finish(user, grant, book, new() { InstanceId = instance, SessionId = session, WordRevision = 0 });
Check(partial.State == "Needs review" && partial.Matching == 2 && partial.Total == 48, "Two accepted chapters cannot imply whole-manuscript completion");
var unchanged = Proof(saved, 0);
await Accept(unchanged);
var changed = Proof(saved, 0); changed.WordRevision = 1;
var partRows = ChapterCheckpointEngine.Parts(saved)[0].Rows;
changed.Paragraphs = partRows.Select(p => new ChapterParagraph { NativeId = p.Occurrence.NativeId, Text = p.Occurrence.Text, Length = p.Occurrence.Text.Length, Outline = p.Occurrence.Outline }).ToArray();
changed.Paragraphs[1].Text = "Changed synthetic paragraph.\r"; changed.Paragraphs[1].Length = changed.Paragraphs[1].Text!.Length;
changed.End = changed.Start + changed.Paragraphs.Sum(p => p.Length);
changed.ContentHash = ChapterFingerprint.Content(changed.Paragraphs.Select(p => p.Text!)); changed.IdentityHash = ChapterFingerprint.Identity(changed.Paragraphs);
Observe(1);
var detection = (await controller.Validate(book, changed) as OkObjectResult)?.Value as ChapterSyncReply;
Check(detection?.State == "Changed" && !detection.AllowText, "Manual mode detects edits without silently authorising reconciliation");
// Consume the old repair command before requesting a new revision-scoped operation.
presence.TakeNavigation(user, grant, instance, session);
changed.OperationId = await service.Repair(user, book, instance, session, 1);
changed.Reconcile = true;
await Accept(changed);
var reconciled = (await repository.Get(user, book))!;
Check(reconciled.Paragraphs.Skip(partRows.Length).Select(p => (p.Occurrence.Id, p.Occurrence.NativeId, p.Occurrence.Text, p.ChapterId, p.SceneId, p.PositionVerified, p.Story)).SequenceEqual(saved.Paragraphs.Skip(partRows.Length).Select(p => (p.Occurrence.Id, p.Occurrence.NativeId, p.Occurrence.Text, p.ChapterId, p.SceneId, p.PositionVerified, p.Story))) && reconciled.Scenes.Select(s => s.Id).SequenceEqual(saved.Scenes.Select(s => s.Id)), "Selective reconciliation preserves unaffected mappings and scene identities");
var sourceBefore = (await imports.ListSceneManuscriptSourcesByBookAsync(book)).Single(s => s.SceneID == canonicalScenes[1]);
foreach(var insert in new[]{true,false})
{
var current = (await repository.Get(user, book))!;
var edit = Proof(current, 0); edit.WordRevision = insert ? 2 : 3;
var evidence = ChapterCheckpointEngine.Parts(current)[0].Rows.Select(p => new ChapterParagraph { NativeId = p.Occurrence.NativeId, Text = p.Occurrence.Text, Length = p.Occurrence.Text.Length, Outline = p.Occurrence.Outline }).ToList();
if(insert) evidence.Insert(2,new() { NativeId="10000001", Text="Inserted synthetic paragraph.\r", Length="Inserted synthetic paragraph.\r".Length, Outline=10 });
else evidence.RemoveAll(p=>p.NativeId=="10000001");
edit.Paragraphs=evidence.ToArray();edit.End=edit.Start+evidence.Sum(p=>p.Length);
edit.ContentHash=ChapterFingerprint.Content(evidence.Select(p=>p.Text!));edit.IdentityHash=ChapterFingerprint.Identity(evidence);
Observe(edit.WordRevision);presence.TakeNavigation(user,grant,instance,session);
edit.OperationId=await service.Repair(user,book,instance,session,edit.WordRevision);edit.Reconcile=true;
await Accept(edit);
var sourceAfter=(await imports.ListSceneManuscriptSourcesByBookAsync(book)).Single(s=>s.SceneID==canonicalScenes[1]);
var shift=insert?1:0;
Check(sourceAfter.SourceText==sourceBefore.SourceText&&sourceAfter.SourceKind==sourceBefore.SourceKind&&sourceAfter.SourceStartParagraph==sourceBefore.SourceStartParagraph+shift&&sourceAfter.SourceEndParagraph==sourceBefore.SourceEndParagraph+shift&&sourceAfter.WordStartParagraphIndex==sourceBefore.WordStartParagraphIndex+shift&&sourceAfter.WordEndParagraphIndex==sourceBefore.WordEndParagraphIndex+shift, "Chapter "+(insert?"insertion":"deletion")+" shifts later source bounds without replacing unrelated prose");
}
reconciled=(await repository.Get(user,book))!;
var stale = Proof(reconciled, 0); stale.BaseRevision = 0; stale.WordRevision = 3;
var rejected = (await controller.Validate(book, stale) as ConflictObjectResult)?.Value as ChapterSyncReply;
Check(rejected?.Accepted == false && rejected.Message.Contains("Stale"), "Rejected chapter returns a specific validation reason");
var freshSession = Guid.NewGuid();
Check((await checkpoints.List(user, book, freshSession, 1)).Count == 0 && (await repository.Get(user, book))!.ChapterCheckpoints.Count >= 2, "New sessions preserve durable evidence and require fresh absolute position verification");
}
finally
{
await projects.ArchiveForUserAsync(project, user);
Console.WriteLine($"Synthetic project {project} archived for evidence; existing author books were not modified.");
}
}
private static void Check(bool condition, string message)
{ if (!condition) throw new Exception(message); Console.WriteLine("PASS " + message); }
}

View File

@ -71,6 +71,14 @@ internal static class ChapterSynchronisationTests
Refused(() => ChapterFingerprint.ReadXml(pageBreakXml, exactText), "Page break cannot be ignored when the live Word text disagrees");
Refused(()=>ChapterFingerprint.ReadXml(xml,"Different\r"),"XML/range disagreement is refused rather than inventing paragraph offsets");
Refused(()=>ChapterFingerprint.ReadXml(xml.Replace("<w:body>","<w:body><w:tbl/>"),"Chapter one\rExact\ttext\r"),"Complex Word tables require safe bounded fallback");
var pictureXml=xml.Replace("<w:t>Exact</w:t>","<w:t>Exact</w:t><w:drawing/>");
var pictureText="Chapter one\rExact\u0001\ttext\r";
var pictureIds=originalRows[0].NativeId+originalRows[0].Length.ToString("X8")+originalRows[1].NativeId+(pictureText.Length-originalRows[0].Length).ToString("X8");
Check(ChapterFingerprint.ReadXml(pictureXml,pictureText,pictureIds,true)[1].Text=="Exact\u0001\ttext\r","Picture evidence uses measured native paragraph text without projecting object characters");
Check(ChapterFingerprint.ReadXml(pictureXml,exactText,liveIds,true)[1].Text==originalRows[1].Text,"Anchored picture evidence preserves the exact native text when no object character is present");
Refused(()=>ChapterFingerprint.ReadXml(pictureXml,pictureText,pictureIds),"Older native-ID-only evidence cannot certify picture paragraph text");
Refused(()=>ChapterFingerprint.ReadXml(pictureXml,pictureText,pictureIds.Substring(0,24)+"00000001",true),"Picture native spans must cover the whole chapter");
Refused(()=>ChapterFingerprint.ReadXml(pictureXml.Replace("<w:drawing/>","<w:drawing/><w:fldChar/>"),pictureText,pictureIds,true),"Native picture fallback does not relax unsafe field handling");
var presence=new PlotLine.Services.NativeCompanion.NativePresenceStore(TimeProvider.System);var instance=Guid.NewGuid();var session=Guid.NewGuid();presence.Put(7,"grant",DateTimeOffset.UtcNow.AddHours(1),instance,session,new(){BookId=12,ManuscriptId=state.ManuscriptId,CanChapterSync=true,CanCapture=true,CanParagraphSync=true,WordAvailable=true,WordSaved=true,Sequence=1,Revision=1});var lease=presence.Read(7,12).Single();presence.RecordChapterProgress(7,12,instance,session,1,new(){State="Synchronised",Total=2,Matching=2});var operation=Guid.NewGuid();Check(presence.RequestChapterRepair(7,lease,operation)&&presence.ChapterTransfer(7,12,instance,session)?.State=="pending","A repeated repair cannot inherit a previous green completion before fresh acceptance");
Check(presence.CanRepairChapter(7,lease,operation)&&!presence.CanRepairChapter(7,lease with{Grant="different-installation"},operation),"Explicit repair authority is scoped to its approved installation grant and live revision");presence.CancelChapterRepairs(7,12);Check(!presence.CanRepairChapter(7,lease,operation)&&presence.ChapterTransfer(7,12,instance,session)?.State=="needs-review","Cancellation revokes transfer permission while retaining accepted checkpoints");
var watch=Stopwatch.StartNew();for(int i=0;i<48;i++)ChapterFingerprint.Content(Enumerable.Range(0,180).Select(n=>"Synthetic paragraph "+n+new string('x',100)+"\r"));watch.Stop();Console.WriteLine($"MEASURE portable exact SHA-256: 48 synthetic chapters / 8640 paragraphs in {watch.Elapsed.TotalMilliseconds:F1}ms. No Word COM or UI measurement.");

View File

@ -15,6 +15,7 @@ using PlotLine.Models;
using PlotLine.Services;
using PlotLine.ViewModels;
if(args.Contains("--chapter-acceptance-dev")){await ChapterAcceptanceDevelopmentTests.Run(args);return;}
if(args.Contains("--chapter-sync-dev")){await ChapterSyncDevelopmentTests.Run(args);return;}
if(args.Contains("--chapter-sync")){ChapterSynchronisationTests.Run();return;}
#pragma warning disable CS8321

View File

@ -6,17 +6,21 @@ using PlotLine.Services.Manuscript;
using PlotLine.Services.NativeCompanion;
namespace PlotLine.Controllers;
[ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion/books/{book:int}/chapter-sync")]
public sealed class NativeChapterSyncController(ChapterSyncService chapters):ControllerBase
public sealed class NativeChapterSyncController(ChapterSyncService chapters,ILogger<NativeChapterSyncController>? logger=null):ControllerBase
{
private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
[HttpGet]
public async Task<IActionResult> Manifest(int book,Guid session,long wordRevision)=>await Run(async()=>await chapters.Manifest(Author,book,session,wordRevision));
[HttpPost("validate"),RequestSizeLimit(4*1024*1024)]
public async Task<IActionResult> Validate(int book,ChapterObservation observation)=>await Run(async()=>await chapters.Accept(Author,User.FindFirstValue("NativeCompanion.Grant")??"",book,observation));
public async Task<IActionResult> Validate(int book,ChapterObservation observation)
{
logger?.LogInformation("Native chapter observation received Trace={Trace} Book={Book} Chapter={Chapter} Request={Request} Session={Session}",HttpContext.TraceIdentifier,book,observation.ChapterId,observation.RequestId,observation.SessionId);
return await Run(async()=>await chapters.Accept(Author,User.FindFirstValue("NativeCompanion.Grant")??"",book,observation));
}
[HttpPost("repair")]
public async Task<IActionResult> Repair(int book,ChapterFinish selected)=>await Run(async()=>new ChapterRepairRequested{OperationId=await chapters.Repair(Author,book,selected.InstanceId,selected.SessionId,selected.WordRevision),Message="Chapter repair requested; accepted import and author decisions are retained."});
[HttpPost("finish")]
public async Task<IActionResult> Finish(int book,ChapterFinish completion)=>await Run(async()=>await chapters.Finish(Author,User.FindFirstValue("NativeCompanion.Grant")??"",book,completion));
private async Task<IActionResult> Run(Func<Task<object>> read)
{try{return Ok(await read());}catch(UnauthorizedAccessException){return Forbid();}catch(Exception e)when(e is ArgumentException or InvalidOperationException){return Conflict(new ChapterSyncReply{State="Needs review",Message=e.Message});}catch(Microsoft.Data.SqlClient.SqlException){return Conflict(new ChapterSyncReply{State="Failed",Message="The accepted manuscript changed or chapter validation was refused. Existing work is preserved; refresh and retry."});}}
{try{return Ok(await read());}catch(UnauthorizedAccessException){return Forbid();}catch(Exception e)when(e is ArgumentException or InvalidOperationException){return Conflict(new ChapterSyncReply{State="Needs review",Message=e.Message});}catch(Microsoft.Data.SqlClient.SqlException e){logger?.LogWarning("Native chapter request storage failure Trace={Trace} SqlNumber={SqlNumber}",HttpContext.TraceIdentifier,e.Number);return Conflict(new ChapterSyncReply{State="Failed",Message=e.Number==-2?"Chapter checkpoint storage timed out. Previously accepted work is retained; retry synchronisation. Reference: "+HttpContext.TraceIdentifier:e.Number==51000?e.Message+" Reference: "+HttpContext.TraceIdentifier:"Chapter checkpoint storage failed. Previously accepted work is retained. Reference: "+HttpContext.TraceIdentifier});}}
}

View File

@ -9,6 +9,7 @@ public interface IParagraphManuscriptRepository
Task<ParagraphManuscript?> Get(int user,int book);
Task<ParagraphManuscript> SetMode(int user,int book,long expected,string mode);
Task<ParagraphManuscript> Save(int user,ParagraphManuscript state,long expected,Guid request);
Task<ParagraphManuscript> SaveChapter(int user,ParagraphManuscript state,long expected,Guid request,int chapter)=>Save(user,state,expected,request);
Task<ManuscriptScanPreview?> Capture(int user,int book);
Task<ParagraphSyncStatus?> Status(int user,int book);
Task<IReadOnlyList<ManuscriptEventOption>> Events(int user,int book);
@ -19,6 +20,7 @@ public sealed class ParagraphManuscriptRepository(ISqlConnectionFactory factory)
public async Task<ParagraphManuscript?> Get(int user,int book){using var db=factory.CreateConnection();var json=await db.QuerySingleOrDefaultAsync<string>("dbo.ParagraphManuscript",new{Action="get",UserID=user,BookID=book},commandType:CommandType.StoredProcedure);return json==null?null:JsonSerializer.Deserialize<ParagraphManuscript>(json);}
public async Task<ParagraphManuscript> SetMode(int user,int book,long expected,string mode){using var db=factory.CreateConnection();var json=await db.QuerySingleAsync<string>("dbo.ParagraphManuscript",new{Action="mode",UserID=user,BookID=book,ExpectedRevision=expected,Mode=mode},commandType:CommandType.StoredProcedure);return JsonSerializer.Deserialize<ParagraphManuscript>(json)!;}
public async Task<ParagraphManuscript> Save(int user,ParagraphManuscript state,long expected,Guid request){using var db=factory.CreateConnection();var json=await db.QuerySingleAsync<string>("dbo.ParagraphManuscript",new{Action="save",UserID=user,BookID=state.BookId,ExpectedRevision=expected,RequestID=request,Payload=JsonSerializer.Serialize(state)},commandType:CommandType.StoredProcedure);return JsonSerializer.Deserialize<ParagraphManuscript>(json)!;}
public async Task<ParagraphManuscript> SaveChapter(int user,ParagraphManuscript state,long expected,Guid request,int chapter){using var db=factory.CreateConnection();var json=await db.QuerySingleAsync<string>("dbo.ParagraphManuscript",new{Action="save",UserID=user,BookID=state.BookId,ExpectedRevision=expected,RequestID=request,ChangedChapterID=chapter,Payload=JsonSerializer.Serialize(state)},commandType:CommandType.StoredProcedure);return JsonSerializer.Deserialize<ParagraphManuscript>(json)!;}
public async Task<ManuscriptScanPreview?> Capture(int user,int book){using var db=factory.CreateConnection();var json=await db.QuerySingleOrDefaultAsync<string>("dbo.ParagraphManuscript",new{Action="capture",UserID=user,BookID=book},commandType:CommandType.StoredProcedure);return json==null?null:JsonSerializer.Deserialize<ManuscriptScanPreview>(json);}
public async Task<ParagraphSyncStatus?> Status(int user,int book){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync<ParagraphSyncStatus>("dbo.ParagraphManuscript",new{Action="status",UserID=user,BookID=book},commandType:CommandType.StoredProcedure);}
public async Task<IReadOnlyList<ManuscriptEventOption>> Events(int user,int book){using var db=factory.CreateConnection();return(await db.QueryAsync<ManuscriptEventOption>("dbo.ParagraphManuscript",new{Action="events",UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToList();}

View File

@ -51,12 +51,13 @@ public static class ChapterCheckpointEngine
if(identity!=proof.IdentityHash||proof.Paragraphs.Sum(p=>(long)p.Length)!=proof.End-proof.Start)throw new ArgumentException("Chapter identity/position evidence is incomplete.");
var all=Build(state,state.Revision);var checkpoint=all.Single(p=>p.ChapterId==proof.ChapterId);
if(checkpoint.ContentHash!=proof.ContentHash||part.Rows.Length!=proof.Paragraphs.Length)throw new InvalidOperationException("Changed chapter; bounded chapter reconciliation is required. Accepted mappings are unchanged.");
var nativeOwners=state.Paragraphs.Where(p=>p.Occurrence.NativeId!="").GroupBy(p=>p.Occurrence.NativeId).ToDictionary(g=>g.Key,g=>g.Select(p=>p.Occurrence.Id).ToHashSet());
var bindings=new List<NativeParagraphBinding>();
for(int n=0;n<part.Rows.Length;n++){
var accepted=part.Rows[n].Occurrence;var observed=proof.Paragraphs[n];
if(observed.Length!=accepted.Text.Length||observed.Outline!=accepted.Outline)throw new InvalidOperationException("Paragraph boundaries or outline changed; review this chapter.");
if(accepted.NativeId!=""&&accepted.NativeId!=observed.NativeId)throw new InvalidOperationException("Native paragraph identity changed; no identity was silently replaced.");
if(state.Paragraphs.Any(p=>p.Occurrence.Id!=accepted.Id&&p.Occurrence.NativeId==observed.NativeId))throw new InvalidOperationException("Cross-chapter duplicate native identity; review is required.");
if(nativeOwners.TryGetValue(observed.NativeId,out var owners)&&owners.Any(id=>id!=accepted.Id))throw new InvalidOperationException("Cross-chapter duplicate native identity; review is required.");
if(accepted.NativeId=="")bindings.Add(new(accepted.Id,observed.NativeId));
}
if(bindings.Count>0&&(!proof.Reconcile||all.Count(c=>c.ContentHash==proof.ContentHash)!=1))throw new InvalidOperationException("Legacy native identities require explicit repair and unique complete chapter evidence. No reimport is required.");

View File

@ -3,7 +3,7 @@ using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services.NativeCompanion;
namespace PlotLine.Services.Manuscript;
public sealed class ChapterSyncService(IParagraphManuscriptRepository manuscripts,IChapterSyncRepository checkpoints,IWordCompanionRepository access,ParagraphManuscriptService reconciliation,NativePresenceStore presence,TimeProvider clock)
public sealed class ChapterSyncService(IParagraphManuscriptRepository manuscripts,IChapterSyncRepository checkpoints,IWordCompanionRepository access,ParagraphManuscriptService reconciliation,NativePresenceStore presence,TimeProvider clock,ILogger<ChapterSyncService>? logger=null)
{
private void RequireFeature(){if(!reconciliation.Enabled)throw new InvalidOperationException("Paragraph synchronisation is not enabled on this server.");}
public async Task<ChapterManifest> Manifest(int user,int book,Guid session,long wordRevision)
@ -30,7 +30,9 @@ public sealed class ChapterSyncService(IParagraphManuscriptRepository manuscript
if(completion.HasIssues&&manifest.Chapters.Length>0){var ids=(completion.ReviewChapterIds??[]).Where(id=>manifest.Chapters.Any(c=>c.ChapterId==id)).Distinct().Take(256).ToArray();if(ids.Length==0)ids=[manifest.Chapters[0].ChapterId];foreach(var id in ids)await checkpoints.FlagReview(user,book,id,manifest.Revision);manifest=await Manifest(user,book,completion.SessionId,completion.WordRevision);}
var accepted=manifest.Chapters.Count(c=>c.State=="Synchronised");var complete=accepted==manifest.Chapters.Length&&accepted>0&&!completion.HasIssues;
var progress=new ChapterSyncProgress{Total=manifest.Chapters.Length,Checked=manifest.Chapters.Length,Matching=accepted,Repaired=presence.RepairedChapters(user,book,completion.InstanceId,completion.SessionId,completion.WordRevision),NeedsReview=complete?0:Math.Max(1,manifest.Chapters.Length-accepted),State=complete?"Synchronised":"Needs review",Message=complete?$"All {accepted} chapter mappings are accepted for this Word session.":$"{accepted}/{manifest.Chapters.Length} chapters accepted; remaining structure needs review. Successfully accepted repairs are retained."};
presence.RecordChapterProgress(user,book,completion.InstanceId,completion.SessionId,completion.WordRevision,progress);return progress;
presence.RecordChapterProgress(user,book,completion.InstanceId,completion.SessionId,completion.WordRevision,progress);
logger?.LogInformation("Chapter synchronisation finish Book={Book} Session={Session} WordRevision={WordRevision} State={State} Accepted={Accepted} Total={Total}",book,completion.SessionId,completion.WordRevision,progress.State,accepted,manifest.Chapters.Length);
return progress;
}
public async Task<Guid> Repair(int user,int book,Guid? instance,Guid? session,long? expectedWordRevision=null)
{
@ -48,28 +50,59 @@ public sealed class ChapterSyncService(IParagraphManuscriptRepository manuscript
}
public async Task<ChapterSyncReply> Accept(int user,string grant,int book,ChapterObservation proof)
{
var stage="protocol";
var elapsed=System.Diagnostics.Stopwatch.StartNew();
try
{
if(proof==null||proof.Paragraphs==null||proof.Paragraphs.Length==0||proof.Paragraphs.Length>ChapterFingerprint.MaxParagraphs||proof.Paragraphs.Any(p=>p==null))throw new ArgumentException("Complete bounded chapter evidence is required.");
RequireFeature();
stage="access";
if(await access.GetBookStructureAsync(book,user)==null)throw new UnauthorizedAccessException();
var status=await manuscripts.Status(user,book)??throw new InvalidOperationException("No accepted manuscript index.");
if(!status.CanWrite)throw new UnauthorizedAccessException();if(status.Paused)throw new InvalidOperationException("Existing import or analysis is active; chapter acceptance is paused.");
stage="session";
var lease=presence.Read(user,book).SingleOrDefault(l=>l.Instance==proof.InstanceId&&l.Session==proof.SessionId&&l.Grant==grant&&l.Position.CanChapterSync&&l.Position.WordAvailable&&l.Position.WordSaved==true&&l.Position.ManuscriptId==proof.ManuscriptId&&l.Position.Revision==proof.WordRevision);
if(lease==null)throw new InvalidOperationException("Word document closed, changed, became unsaved or was disconnected; no stale checkpoint was accepted.");
var permitted=status.Mode=="OnSave"||presence.CanRepairChapter(user,lease,proof.OperationId);
stage="snapshot";
var state=await manuscripts.Get(user,book)??throw new InvalidOperationException("Missing accepted snapshot.");
var source=ChapterCheckpointEngine.Build(state,state.Revision).SingleOrDefault(c=>c.ChapterId==proof.ChapterId)??throw new InvalidOperationException("Unknown accepted chapter.");
var changed=source.ContentHash!=proof.ContentHash;
if(changed){
if(!permitted||proof.Paragraphs.Any(p=>p.Text==null))return new(){State="Changed",ChapterId=proof.ChapterId,Revision=state.Revision,AllowText=permitted,Message=permitted?"Changed chapter; submit this chapter only for existing paragraph reconciliation.":"Changed chapter. Use Synchronise or Repair to authorise chapter reconciliation; no prose was uploaded."};
if(presence.Read(user,book).Count(l=>l.Position.WordAvailable&&l.Position.ManuscriptId==proof.ManuscriptId)>1)throw new InvalidOperationException("Competing Word copies are connected to this book. Close the other copy before reconciling changed prose; existing mappings are preserved.");
stage="reconciliation";
state=await reconciliation.ReconcileChapter(user,book,proof);proof.BaseRevision=state.Revision;
}
// Native adoption is explicit repair only; ordinary hash checks cannot mint trust.
proof.Reconcile=presence.CanRepairChapter(user,lease,proof.OperationId);
stage="validation";
var validated=ChapterCheckpointEngine.Validate(state,proof,clock.GetUtcNow().UtcDateTime);
await checkpoints.Accept(user,book,proof,validated);
logger?.LogInformation("Chapter validation completed Book={Book} Chapter={Chapter} Request={Request} Session={Session} ElapsedMs={ElapsedMs}",book,proof.ChapterId,proof.RequestId,proof.SessionId,elapsed.ElapsedMilliseconds);
stage="persistence";
var acceptedState=await checkpoints.Accept(user,book,proof,validated);
logger?.LogInformation("Chapter checkpoint persisted Book={Book} Chapter={Chapter} Request={Request} Session={Session} Revision={Revision} ElapsedMs={ElapsedMs}",book,proof.ChapterId,proof.RequestId,proof.SessionId,state.Revision,elapsed.ElapsedMilliseconds);
if(changed||validated.Bindings.Length>0)presence.RecordChapterRepair(user,book,proof.InstanceId,proof.SessionId,proof.WordRevision,proof.ChapterId);
await Manifest(user,book,proof.SessionId,proof.WordRevision);
try
{
var live=await checkpoints.List(user,book,proof.SessionId,proof.WordRevision);
var count=live.Count(v=>acceptedState.ChapterCheckpoints.Any(c=>c.ChapterId==v.ChapterID&&c.Status!="Needs review"&&c.ContentHash==v.ContentHash&&c.IdentityHash==v.IdentityHash&&c.MappingHash==v.MappingHash));
var total=ChapterCheckpointEngine.Parts(acceptedState).Length;
presence.RecordChapterProgress(user,book,proof.InstanceId,proof.SessionId,proof.WordRevision,new(){Total=total,Checked=count,Matching=count,Repaired=presence.RepairedChapters(user,book,proof.InstanceId,proof.SessionId,proof.WordRevision),State="Checking",Message=$"{count}/{total} chapter mappings accepted for this session."});
}
catch(Microsoft.Data.SqlClient.SqlException e)
{
logger?.LogWarning("Chapter committed; progress refresh unavailable Book={Book} Chapter={Chapter} Request={Request} SqlNumber={SqlNumber}",book,proof.ChapterId,proof.RequestId,e.Number);
}
// The transaction is the acceptance boundary. A later manifest refresh must
// not turn a durable commit into a failed validation response.
return new(){Accepted=true,State=validated.Checkpoint.Message.Contains("order needs review")?"Needs review":"Synchronised",ChapterId=proof.ChapterId,Revision=state.Revision,Message=validated.Checkpoint.Message};
}
catch(Exception e) when(e is UnauthorizedAccessException or ArgumentException or InvalidOperationException or Microsoft.Data.SqlClient.SqlException)
{
// Deliberately omit exception text, payloads and grant material.
logger?.LogWarning("Chapter checkpoint rejected Stage={Stage} Book={Book} Chapter={Chapter} Request={Request} Session={Session} Category={Category} SqlNumber={SqlNumber} ElapsedMs={ElapsedMs}",stage,book,proof?.ChapterId,proof?.RequestId,proof?.SessionId,e.GetType().Name,(e as Microsoft.Data.SqlClient.SqlException)?.Number,elapsed.ElapsedMilliseconds);
throw;
}
}
}

View File

@ -79,7 +79,7 @@ public sealed class ParagraphManuscriptService(IParagraphManuscriptRepository re
ParagraphManuscriptEngine.Reconcile(state,rows);
// Logical positions after a partial repair are not a claim that every physical Word offset was validated.
state.SessionId=Guid.Empty;state.WordRevision=-1;
return await Save(user,state,proof.BaseRevision,proof.RequestId);
return await Save(user,state,proof.BaseRevision,proof.RequestId,proof.ChapterId);
}
public async Task<ParagraphManuscript> Change(int user,int book,long expected,string action,Guid target=default,Guid other=default,string? text=null,string? kind=null,int eventId=0,bool primary=true,int from=0,int to=0,int? startOffset=null,int? endOffset=null)
{
@ -105,11 +105,11 @@ public sealed class ParagraphManuscriptService(IParagraphManuscriptRepository re
// Explicitly removed events from the established editors are not recreated by synchronisation.
state.Evidence.RemoveAll(e=>actual.All(a=>a.Kind!=e.EventKind||a.Id!=e.EventId));ParagraphManuscriptEngine.RefreshEvidence(state);return await Save(user,state,expected,Guid.NewGuid());
}
private async Task<ParagraphManuscript> Save(int user,ParagraphManuscript state,long expected,Guid request)
private async Task<ParagraphManuscript> Save(int user,ParagraphManuscript state,long expected,Guid request,int? chapter=null)
{
ParagraphManuscriptEngine.Validate(state);if(state.Chapters.Count>0)state.ChapterCheckpoints=ChapterCheckpointEngine.Build(state,expected+1).ToList();var result=await repository.Save(user,state,expected,request);
ParagraphManuscriptEngine.Validate(state);if(state.Chapters.Count>0)state.ChapterCheckpoints=ChapterCheckpointEngine.Build(state,expected+1).ToList();var result=chapter.HasValue?await repository.SaveChapter(user,state,expected,request,chapter.Value):await repository.Save(user,state,expected,request);
// Reuse deterministic continuity/statistics; never schedule whole-book AI.
try{await statistics.RecalculateBookAsync(state.BookId);}catch(Exception e)when(e is Microsoft.Data.SqlClient.SqlException or InvalidOperationException){logger?.LogWarning("Manuscript revision {Revision} committed; derived statistics require refresh ({FailureKind}).",result.Revision,e.GetType().Name);}
try{if(chapter.HasValue)await statistics.RecalculateChapterAsync(chapter.Value);else await statistics.RecalculateBookAsync(state.BookId);}catch(Exception e)when(e is Microsoft.Data.SqlClient.SqlException or InvalidOperationException){logger?.LogWarning("Manuscript revision {Revision} committed; derived statistics require refresh ({FailureKind}).",result.Revision,e.GetType().Name);}
return result;
}
}

View File

@ -0,0 +1,117 @@
-- Forward repair: parse the accepted manuscript once and adopt native identities set-wise.
-- Preserve the original JSON for every unaffected paragraph and canonical mapping.
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER PROCEDURE dbo.BookChapterSync
@Action varchar(16),@UserID int,@BookID int,@ChapterID int=NULL,@SessionID uniqueidentifier=NULL,@ManuscriptID uniqueidentifier=NULL,@WordRevision bigint=NULL,
@ExpectedRevision bigint=NULL,@RequestID uniqueidentifier=NULL,@Checkpoint nvarchar(max)=NULL,@Positions nvarchar(max)=NULL,@Bindings nvarchar(max)=NULL,@Position int=NULL,@SceneID int=NULL,@ParagraphID uniqueidentifier=NULL,@SnapshotHash char(64)=NULL
AS
BEGIN
SET NOCOUNT ON;SET XACT_ABORT ON;
DECLARE @ProjectID int;
SELECT @ProjectID=b.ProjectID FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID;
IF @ProjectID IS NULL THROW 51000,'Book access denied',1;
IF @Action='list' BEGIN SELECT ChapterID,SessionID,WordRevision,ContentHash,IdentityHash,MappingHash,SourceRevision,ValidatedUtc,(SELECT MIN(p.StartPosition) FROM OPENJSON(Positions) WITH(StartPosition int '$.Start') p) StartPosition,(SELECT MAX(p.EndPosition) FROM OPENJSON(Positions) WITH(EndPosition int '$.End') p) EndPosition FROM dbo.BookChapterValidations WHERE BookID=@BookID AND UserID=@UserID AND SessionID=@SessionID AND WordRevision=@WordRevision AND ExpiresUtc>SYSUTCDATETIME();RETURN;END;
IF @Action='scene-start'
BEGIN
SELECT TOP(1) CAST(1 AS bit) HasSnapshot,m.Revision,pos.ChapterID,pos.SceneID,pos.StartPosition
FROM dbo.BookParagraphManuscripts m JOIN dbo.BookChapterValidations v ON v.BookID=m.BookID
CROSS APPLY OPENJSON(m.Payload,'$.ChapterCheckpoints') WITH(ChapterID int '$.ChapterId',ContentHash char(64),IdentityHash char(64),MappingHash char(64)) c
CROSS APPLY OPENJSON(v.Positions) WITH(ParagraphID uniqueidentifier '$.ParagraphId',StartPosition int '$.Start',ChapterID int '$.ChapterId',SceneID int '$.SceneId',Verified bit) pos
JOIN dbo.Chapters ch ON ch.ChapterID=pos.ChapterID AND ch.BookID=m.BookID AND ch.IsArchived=0
JOIN dbo.Scenes scene ON scene.SceneID=pos.SceneID AND scene.ChapterID=pos.ChapterID AND scene.IsArchived=0
WHERE m.BookID=@BookID AND v.ChapterID=c.ChapterID AND pos.ChapterID=c.ChapterID AND v.UserID=@UserID AND v.SessionID=@SessionID AND v.ManuscriptID=@ManuscriptID AND v.WordRevision=@WordRevision
AND v.ExpiresUtc>SYSUTCDATETIME() AND v.ContentHash=c.ContentHash AND v.IdentityHash=c.IdentityHash AND v.MappingHash=c.MappingHash
AND pos.Verified=1 AND pos.SceneID=@SceneID AND pos.ParagraphID=@ParagraphID;RETURN;
END;
IF @Action='position'
BEGIN
SELECT CAST(1 AS bit) HasSnapshot,m.Revision,p.ChapterID,p.SceneID
FROM dbo.BookParagraphManuscripts m
OUTER APPLY(SELECT TOP(1) pos.ChapterID,CASE WHEN s.ChapterID=pos.ChapterID AND s.IsArchived=0 THEN pos.SceneID END SceneID
FROM dbo.BookChapterValidations v
CROSS APPLY OPENJSON(m.Payload,'$.ChapterCheckpoints') WITH(ChapterID int '$.ChapterId',ContentHash char(64),IdentityHash char(64),MappingHash char(64)) c
CROSS APPLY OPENJSON(v.Positions) WITH(StartPosition int '$.Start',EndPosition int '$.End',ChapterID int '$.ChapterId',SceneID int '$.SceneId',Verified bit) pos
JOIN dbo.Chapters ch ON ch.ChapterID=pos.ChapterID AND ch.BookID=m.BookID AND ch.IsArchived=0
LEFT JOIN dbo.Scenes s ON s.SceneID=pos.SceneID
WHERE v.BookID=m.BookID AND v.ChapterID=c.ChapterID AND pos.ChapterID=c.ChapterID AND v.UserID=@UserID AND v.SessionID=@SessionID AND v.ManuscriptID=@ManuscriptID AND v.WordRevision=@WordRevision
AND v.ExpiresUtc>SYSUTCDATETIME() AND v.ContentHash=c.ContentHash AND v.IdentityHash=c.IdentityHash AND v.MappingHash=c.MappingHash
AND pos.Verified=1 AND pos.StartPosition<=@Position AND pos.EndPosition>@Position) p WHERE m.BookID=@BookID;RETURN;
END;
IF @Action='review'
BEGIN
IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND AccessRole=N'Owner' AND IsActive=1) THROW 51000,'Project owner authority required',1;
BEGIN TRANSACTION;
DECLARE @ReviewPayload nvarchar(max),@ReviewRevision bigint,@ReviewIndex int;
SELECT @ReviewPayload=Payload,@ReviewRevision=Revision FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID;
IF @ReviewRevision IS NULL OR @ExpectedRevision IS NULL OR @ReviewRevision<>@ExpectedRevision THROW 51000,'Manuscript changed before structural warning',1;
SELECT @ReviewIndex=CONVERT(int,j.[key]) FROM OPENJSON(@ReviewPayload,'$.ChapterCheckpoints') j WHERE TRY_CONVERT(int,JSON_VALUE(j.value,'$.ChapterId'))=@ChapterID;
IF @ReviewIndex IS NOT NULL BEGIN
SET @ReviewPayload=JSON_MODIFY(@ReviewPayload,CONCAT('$.ChapterCheckpoints[',@ReviewIndex,'].Status'),'Needs review');
SET @ReviewPayload=JSON_MODIFY(@ReviewPayload,CONCAT('$.ChapterCheckpoints[',@ReviewIndex,'].Message'),'Document structure needs review; independently accepted scene positions are retained.');
UPDATE dbo.BookParagraphManuscripts SET Payload=@ReviewPayload WHERE BookID=@BookID;
END;
DELETE dbo.BookChapterValidations WHERE BookID=@BookID AND ChapterID=@ChapterID;
COMMIT;RETURN;
END;
IF @Action<>'accept' THROW 51000,'Unknown chapter operation',1;
IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND AccessRole=N'Owner' AND IsActive=1) THROW 51000,'Project owner authority required',1;
IF COALESCE(ISJSON(@Checkpoint),0)<>1 OR COALESCE(ISJSON(@Positions),0)<>1 OR COALESCE(ISJSON(@Bindings),0)<>1 OR DATALENGTH(@Positions)>4*1024*1024 OR DATALENGTH(@Checkpoint)>16384 OR @SessionID IS NULL OR @RequestID IS NULL OR @WordRevision IS NULL OR @WordRevision<0 OR @ExpectedRevision IS NULL OR @ManuscriptID IS NULL OR @ChapterID IS NULL THROW 51000,'Invalid chapter validation',1;
IF EXISTS(SELECT 1 FROM dbo.UserOnboardingState WHERE BookID=@BookID AND OnboardingCompletedUtc IS NULL) OR EXISTS(SELECT 1 FROM dbo.StoryIntelligenceJobs WHERE BookID=@BookID AND Status IN ('Pending','Queued','Running','Processing','Preparing','ReadingScenes','AnalysingCharacters','AnalysingRelationships','AnalysingLocations','AnalysingAssets','AnalysingTimeline','Finalising')) THROW 51000,'Active import or analysis protected',1;
BEGIN TRANSACTION;
DECLARE @Payload nvarchar(max),@Revision bigint;
SELECT @Payload=Payload,@Revision=Revision FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID;
IF @Revision IS NULL OR @Revision<>@ExpectedRevision OR TRY_CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.ManuscriptId'))<>@ManuscriptID THROW 51000,'Accepted manuscript changed; chapter validation refused',1;
IF NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE ChapterID=@ChapterID AND BookID=@BookID AND IsArchived=0) OR TRY_CONVERT(int,JSON_VALUE(@Checkpoint,'$.ChapterId'))<>@ChapterID THROW 51000,'Cross-book chapter rejected',1;
DECLARE @Index int;
-- Materialise once: reparsing/replacing a multi-megabyte payload for each binding
-- makes legitimate legacy adoption exceed both the HTTP and database deadlines.
DECLARE @Paragraphs TABLE(Ordinal int PRIMARY KEY,ParagraphID uniqueidentifier UNIQUE,ChapterID int,NativeID nvarchar(16),Payload nvarchar(max));
INSERT @Paragraphs
SELECT CONVERT(int,j.[key]),p.ParagraphID,p.ChapterID,p.NativeID,j.value
FROM OPENJSON(@Payload,'$.Paragraphs') j
CROSS APPLY OPENJSON(j.value) WITH(ParagraphID uniqueidentifier '$.Occurrence.Id',ChapterID int '$.ChapterId',NativeID nvarchar(16) '$.Occurrence.NativeId') p;
DECLARE @Adoption TABLE(ParagraphID uniqueidentifier,NativeID nvarchar(4000));
INSERT @Adoption SELECT ParagraphId,NativeId FROM OPENJSON(@Bindings) WITH(ParagraphId uniqueidentifier,NativeId nvarchar(4000));
IF EXISTS(SELECT ParagraphID FROM @Adoption GROUP BY ParagraphID HAVING COUNT(*)>1)
OR EXISTS(SELECT NativeID FROM @Adoption GROUP BY NativeID HAVING COUNT(*)>1)
OR EXISTS(SELECT 1 FROM @Adoption b LEFT JOIN @Paragraphs p ON p.ParagraphID=b.ParagraphID
WHERE p.ParagraphID IS NULL OR p.ChapterID<>@ChapterID OR b.NativeID IS NULL OR LEN(b.NativeID)<>8
OR b.NativeID COLLATE Latin1_General_100_BIN2 LIKE '%[^0-9A-F]%'
OR COALESCE(p.NativeID,'') NOT IN ('',b.NativeID)
OR EXISTS(SELECT 1 FROM @Paragraphs other WHERE other.ParagraphID<>b.ParagraphID AND other.NativeID=b.NativeID))
THROW 51000,'Native identity adoption conflicts with existing evidence',1;
IF EXISTS(SELECT 1 FROM @Adoption)
BEGIN
UPDATE p SET Payload=JSON_MODIFY(p.Payload,'$.Occurrence.NativeId',b.NativeID)
FROM @Paragraphs p JOIN @Adoption b ON b.ParagraphID=p.ParagraphID;
DECLARE @UpdatedParagraphs nvarchar(max);
SELECT @UpdatedParagraphs=CONCAT(N'[',STRING_AGG(CONVERT(nvarchar(max),Payload),N',') WITHIN GROUP(ORDER BY Ordinal),N']') FROM @Paragraphs;
SET @Payload=JSON_MODIFY(@Payload,'$.Paragraphs',JSON_QUERY(@UpdatedParagraphs));
END;
IF EXISTS(SELECT 1 FROM OPENJSON(@Bindings)) BEGIN
IF @SnapshotHash IS NULL OR LEN(@SnapshotHash)<>64 OR @SnapshotHash LIKE '%[^0-9A-F]%' THROW 51000,'Complete adopted snapshot digest required',1;
SET @Payload=JSON_MODIFY(@Payload,'$.SnapshotHash',@SnapshotHash);
END;
IF NOT EXISTS(SELECT 1 FROM OPENJSON(@Positions)) OR EXISTS(SELECT 1 FROM OPENJSON(@Positions) WITH(ParagraphId uniqueidentifier,ChapterId int,StartPosition int '$.Start',EndPosition int '$.End') p WHERE p.ParagraphId IS NULL OR p.ChapterId IS NULL OR p.ChapterId<>@ChapterID OR p.StartPosition IS NULL OR p.EndPosition IS NULL OR p.StartPosition<0 OR p.EndPosition<=p.StartPosition OR NOT EXISTS(SELECT 1 FROM @Paragraphs a WHERE a.ParagraphID=p.ParagraphId AND a.ChapterID=@ChapterID)) THROW 51000,'Chapter position refers to an unknown paragraph',1;
IF EXISTS(SELECT ParagraphId FROM OPENJSON(@Positions) WITH(ParagraphId uniqueidentifier) GROUP BY ParagraphId HAVING COUNT(*)>1) THROW 51000,'Duplicate chapter paragraph positions',1;
IF EXISTS(SELECT 1 FROM OPENJSON(@Positions) WITH(StartPosition int '$.Start',EndPosition int '$.End') a JOIN OPENJSON(@Positions) WITH(StartPosition int '$.Start',EndPosition int '$.End') b ON a.StartPosition<b.StartPosition AND a.EndPosition>b.StartPosition) THROW 51000,'Overlapping chapter paragraph positions',1;
IF EXISTS(SELECT 1 FROM dbo.BookChapterValidations v CROSS APPLY OPENJSON(v.Positions) WITH(StartPosition int '$.Start',EndPosition int '$.End') a CROSS APPLY OPENJSON(@Positions) WITH(StartPosition int '$.Start',EndPosition int '$.End') b WHERE v.BookID=@BookID AND v.UserID=@UserID AND v.SessionID=@SessionID AND v.WordRevision=@WordRevision AND v.ChapterID<>@ChapterID AND v.ExpiresUtc>SYSUTCDATETIME() AND a.StartPosition<b.EndPosition AND a.EndPosition>b.StartPosition) THROW 51000,'Conflicting physical chapter ranges',1;
IF EXISTS(SELECT 1 FROM dbo.BookChapterValidations WHERE UserID=@UserID AND BookID=@BookID AND RequestID=@RequestID AND (ChapterID<>@ChapterID OR SessionID<>@SessionID OR WordRevision<>@WordRevision OR Positions<>@Positions)) THROW 51000,'Request identity was reused for different chapter evidence',1;
IF JSON_QUERY(@Payload,'$.ChapterCheckpoints') IS NULL SET @Payload=JSON_MODIFY(@Payload,'$.ChapterCheckpoints',JSON_QUERY('[]'));
SET @Index=NULL;SELECT @Index=CONVERT(int,j.[key]) FROM OPENJSON(@Payload,'$.ChapterCheckpoints') j WHERE TRY_CONVERT(int,JSON_VALUE(j.value,'$.ChapterId'))=@ChapterID;
IF @Index IS NULL SET @Payload=JSON_MODIFY(@Payload,'append $.ChapterCheckpoints',JSON_QUERY(@Checkpoint));
ELSE SET @Payload=JSON_MODIFY(@Payload,CONCAT('$.ChapterCheckpoints[',@Index,']'),JSON_QUERY(@Checkpoint));
DECLARE @PriorPositions nvarchar(max),@PriorContent char(64),@PriorIdentity char(64);
SELECT @PriorPositions=Positions,@PriorContent=ContentHash,@PriorIdentity=IdentityHash FROM dbo.BookChapterValidations WHERE BookID=@BookID AND ChapterID=@ChapterID AND UserID=@UserID AND SessionID=@SessionID AND WordRevision=@WordRevision;
IF @PriorPositions IS NOT NULL AND (@PriorContent<>JSON_VALUE(@Checkpoint,'$.ContentHash') OR @PriorIdentity<>JSON_VALUE(@Checkpoint,'$.IdentityHash') OR EXISTS(SELECT ParagraphId,StartPosition,EndPosition FROM OPENJSON(@Positions) WITH(ParagraphId uniqueidentifier,StartPosition int '$.Start',EndPosition int '$.End') EXCEPT SELECT ParagraphId,StartPosition,EndPosition FROM OPENJSON(@PriorPositions) WITH(ParagraphId uniqueidentifier,StartPosition int '$.Start',EndPosition int '$.End')) OR EXISTS(SELECT ParagraphId,StartPosition,EndPosition FROM OPENJSON(@PriorPositions) WITH(ParagraphId uniqueidentifier,StartPosition int '$.Start',EndPosition int '$.End') EXCEPT SELECT ParagraphId,StartPosition,EndPosition FROM OPENJSON(@Positions) WITH(ParagraphId uniqueidentifier,StartPosition int '$.Start',EndPosition int '$.End'))) THROW 51000,'Conflicting evidence for the same live Word revision',1;
-- Metadata-only adoption: canonical prose, GUIDs, scene assignments and author decisions are not rewritten.
UPDATE dbo.BookParagraphManuscripts SET Payload=@Payload WHERE BookID=@BookID;
DELETE dbo.BookChapterValidations WHERE BookID=@BookID AND ExpiresUtc<SYSUTCDATETIME();
UPDATE dbo.BookChapterValidations SET ManuscriptID=@ManuscriptID,WordRevision=@WordRevision,RequestID=@RequestID,ContentHash=JSON_VALUE(@Checkpoint,'$.ContentHash'),IdentityHash=JSON_VALUE(@Checkpoint,'$.IdentityHash'),MappingHash=JSON_VALUE(@Checkpoint,'$.MappingHash'),Positions=@Positions,SourceRevision=@Revision,ValidatedUtc=SYSUTCDATETIME(),ExpiresUtc=DATEADD(hour,12,SYSUTCDATETIME()) WHERE BookID=@BookID AND ChapterID=@ChapterID AND UserID=@UserID AND SessionID=@SessionID;
IF @@ROWCOUNT=0 INSERT dbo.BookChapterValidations VALUES(@BookID,@ChapterID,@UserID,@SessionID,@ManuscriptID,@WordRevision,@RequestID,JSON_VALUE(@Checkpoint,'$.ContentHash'),JSON_VALUE(@Checkpoint,'$.IdentityHash'),JSON_VALUE(@Checkpoint,'$.MappingHash'),@Positions,@Revision,SYSUTCDATETIME(),DATEADD(hour,12,SYSUTCDATETIME()));
COMMIT;
SELECT @Payload;
END;
GO

View File

@ -0,0 +1,132 @@
-- Forward repair: bounded chapter saves project only the affected chapter.
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER PROCEDURE dbo.ParagraphManuscript
@Action varchar(16),@UserID int,@BookID int,@ExpectedRevision bigint=NULL,@RequestID uniqueidentifier=NULL,@Payload nvarchar(max)=NULL,@SessionID uniqueidentifier=NULL,@ManuscriptID uniqueidentifier=NULL,@WordRevision bigint=NULL,@Position int=NULL,@Mode nvarchar(16)=NULL,@ChangedChapterID int=NULL
AS
BEGIN
SET NOCOUNT ON;SET XACT_ABORT ON;
DECLARE @ProjectID int;
SELECT @ProjectID=b.ProjectID FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID;
IF @ProjectID IS NULL THROW 51000,'Book access denied',1;
IF @Action='position'
BEGIN
SELECT CAST(1 AS bit) AS HasSnapshot,m.Revision,p.ChapterID,p.SceneID
FROM dbo.BookParagraphManuscripts m OUTER APPLY(SELECT TOP(1) position.ChapterID,position.SceneID FROM dbo.BookParagraphPositions position
WHERE position.BookID=m.BookID AND position.Verified=1 AND position.StartPosition<=@Position AND position.EndPosition>@Position
AND m.ManuscriptID=@ManuscriptID AND TRY_CONVERT(uniqueidentifier,JSON_VALUE(m.Payload,'$.SessionId'))=@SessionID AND TRY_CONVERT(bigint,JSON_VALUE(m.Payload,'$.WordRevision'))=@WordRevision) p WHERE m.BookID=@BookID;RETURN;
END;
IF @Action='get' BEGIN SELECT Payload FROM dbo.BookParagraphManuscripts WHERE BookID=@BookID;RETURN;END;
IF @Action='status' BEGIN SELECT BookID,ManuscriptID,Revision,JSON_VALUE(Payload,'$.SnapshotHash') AS SnapshotHash,JSON_VALUE(Payload,'$.Mode') AS Mode,TRY_CONVERT(uniqueidentifier,JSON_VALUE(Payload,'$.SessionId')) AS SessionId,TRY_CONVERT(bigint,JSON_VALUE(Payload,'$.WordRevision')) AS WordRevision,
CAST(CASE WHEN EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND AccessRole=N'Owner' AND IsActive=1) THEN 1 ELSE 0 END AS bit) AS CanWrite,
CAST(CASE WHEN EXISTS(SELECT 1 FROM dbo.UserOnboardingState o WHERE o.BookID=@BookID AND o.OnboardingCompletedUtc IS NULL) OR EXISTS(SELECT 1 FROM dbo.StoryIntelligenceJobs j WHERE j.BookID=@BookID AND j.Status IN ('Pending','Queued','Running','Processing','Preparing','ReadingScenes','AnalysingCharacters','AnalysingRelationships','AnalysingLocations','AnalysingAssets','AnalysingTimeline','Finalising')) THEN 1 ELSE 0 END AS bit) AS Paused
FROM dbo.BookParagraphManuscripts WHERE BookID=@BookID;RETURN;END;
IF @Action='capture' BEGIN SELECT TOP(1) c.Payload FROM dbo.OnboardingManuscriptCaptures c WHERE c.BookID=@BookID AND EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds b WHERE b.PreviewID=c.PreviewID AND b.BookID=@BookID AND b.Status IN ('Complete','Built')) ORDER BY c.CreatedUtc DESC;RETURN;END;
IF @Action='events'
BEGIN
SELECT CAST('Knowledge' AS varchar(16)) AS Kind,k.CharacterKnowledgeID AS Id,k.SceneID,CONCAT(c.CharacterName,N': ',COALESCE(k.Description,N'Knowledge event')) AS Description
FROM dbo.CharacterKnowledge k JOIN dbo.Characters c ON c.CharacterID=k.CharacterID JOIN dbo.Scenes s ON s.SceneID=k.SceneID JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID WHERE ch.BookID=@BookID
UNION ALL SELECT 'Relationship',r.RelationshipEventID,r.SceneID,CONCAT(ca.CharacterName,N' / ',cb.CharacterName,N': ',COALESCE(r.Description,N'Relationship event'))
FROM dbo.RelationshipEvents r JOIN dbo.CharacterRelationships rel ON rel.CharacterRelationshipID=r.CharacterRelationshipID JOIN dbo.Characters ca ON ca.CharacterID=rel.CharacterAID JOIN dbo.Characters cb ON cb.CharacterID=rel.CharacterBID JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID WHERE ch.BookID=@BookID;RETURN;
END;
-- Conservative mutation contract: use the established project owner role, never expand collaborator permissions.
IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND IsActive=1 AND AccessRole=N'Owner') THROW 51000,'Project owner authority required',1;
IF @Action='mode'
BEGIN
IF COALESCE(@Mode,'') NOT IN ('Off','Manual','OnSave') THROW 51000,'Unsupported synchronisation mode',1;
BEGIN TRANSACTION;
DECLARE @PreferenceRevision bigint;
SELECT @Payload=Payload,@PreferenceRevision=Revision FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID;
IF @PreferenceRevision IS NULL OR @PreferenceRevision<>@ExpectedRevision THROW 51000,'Manuscript changed; refresh before changing preferences',1;
IF JSON_VALUE(@Payload,'$.Mode')<>@Mode BEGIN
SET @RequestID=NEWID();SET @PreferenceRevision+=1;SET @Payload=JSON_MODIFY(@Payload,'$.Mode',@Mode);SET @Payload=JSON_MODIFY(@Payload,'$.Revision',@PreferenceRevision);SET @Payload=JSON_MODIFY(@Payload,'$.LastRequestId',CONVERT(nvarchar(36),@RequestID));
UPDATE dbo.BookParagraphManuscripts SET Payload=@Payload,Revision=@PreferenceRevision,RequestID=@RequestID,UpdatedUtc=SYSUTCDATETIME() WHERE BookID=@BookID;
END;
COMMIT;SELECT @Payload;RETURN;
END;
IF @Action<>'save' THROW 51000,'Unknown manuscript operation',1;
IF @ChangedChapterID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE ChapterID=@ChangedChapterID AND BookID=@BookID AND IsArchived=0) THROW 51000,'Unknown chapter reconciliation scope',1;
IF ISJSON(@Payload)<>1 OR DATALENGTH(@Payload)>128*1024*1024 OR @RequestID IS NULL OR @ExpectedRevision IS NULL THROW 51000,'Invalid manuscript state',1;
IF COALESCE(TRY_CONVERT(int,JSON_VALUE(@Payload,'$.BookId')),-1)<>@BookID OR COALESCE(TRY_CONVERT(int,JSON_VALUE(@Payload,'$.ProjectId')),-1)<>@ProjectID OR TRY_CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.ManuscriptId')) IS NULL THROW 51000,'Manuscript scope mismatch',1;
IF COALESCE(JSON_VALUE(@Payload,'$.Mode'),'') NOT IN ('Off','Manual','OnSave') THROW 51000,'Unsupported synchronisation mode',1;
-- Do not adopt or replace a book while its accepted import is still awaiting a completed build.
IF EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptCaptures c WHERE c.BookID=@BookID AND c.IsCurrent=1 AND COALESCE(JSON_VALUE(c.Payload,'$.ParagraphTracking'),'false')<>'true' AND NOT EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds b WHERE b.PreviewID=c.PreviewID AND b.Status IN ('Complete','Built'))) THROW 51000,'Active import protected; finish the existing import before enabling paragraph tracking',1;
IF @ExpectedRevision>=0 AND (EXISTS(SELECT 1 FROM dbo.UserOnboardingState WHERE BookID=@BookID AND OnboardingCompletedUtc IS NULL) OR EXISTS(SELECT 1 FROM dbo.StoryIntelligenceJobs WHERE BookID=@BookID AND Status IN ('Pending','Queued','Running','Processing','Preparing','ReadingScenes','AnalysingCharacters','AnalysingRelationships','AnalysingLocations','AnalysingAssets','AnalysingTimeline','Finalising'))) THROW 51000,'Active import or analysis protected; synchronisation paused',1;
BEGIN TRANSACTION;
DECLARE @Revision bigint,@Previous nvarchar(max),@LastRequest uniqueidentifier;
SELECT @Revision=Revision,@Previous=Payload,@LastRequest=RequestID FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID;
IF @LastRequest=@RequestID BEGIN SELECT Payload FROM dbo.BookParagraphManuscripts WHERE BookID=@BookID;COMMIT;RETURN;END;
IF (@Revision IS NULL AND @ExpectedRevision<>-1) OR (@Revision IS NOT NULL AND @Revision<>@ExpectedRevision) THROW 51000,'Manuscript changed; refresh before retrying',1;
DECLARE @Scenes table(JsonIndex int,Id uniqueidentifier PRIMARY KEY,CanonicalId int,ChapterId int,Title nvarchar(200),Retired bit,MergedInto uniqueidentifier);
INSERT @Scenes SELECT CONVERT(int,j.[key]),s.Id,s.CanonicalId,s.ChapterId,s.Title,s.Retired,s.MergedInto FROM OPENJSON(@Payload,'$.Scenes') j CROSS APPLY OPENJSON(j.value) WITH(Id uniqueidentifier,CanonicalId int,ChapterId int,Title nvarchar(200),Retired bit,MergedInto uniqueidentifier) s;
IF EXISTS(SELECT 1 FROM @Scenes x LEFT JOIN dbo.Chapters c ON c.ChapterID=x.ChapterId AND c.BookID=@BookID WHERE c.ChapterID IS NULL) OR EXISTS(SELECT 1 FROM @Scenes x WHERE x.CanonicalId>0 AND NOT EXISTS(SELECT 1 FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE s.SceneID=x.CanonicalId AND c.BookID=@BookID)) THROW 51000,'Cross-book scene reference rejected',1;
IF EXISTS(SELECT 1 FROM dbo.Scenes actual WHERE actual.IsArchived=0 AND EXISTS(SELECT 1 FROM @Scenes tracked WHERE tracked.ChapterId=actual.ChapterID) AND NOT EXISTS(SELECT 1 FROM @Scenes tracked WHERE tracked.CanonicalId=actual.SceneID)) THROW 51000,'This chapter contains a scene outside the accepted paragraph map; review it before synchronising',1;
-- A snapshot is not authority to undo newer author archive/chapter decisions made elsewhere.
IF @Previous IS NULL AND EXISTS(SELECT 1 FROM @Scenes state JOIN dbo.Scenes actual ON actual.SceneID=state.CanonicalId WHERE actual.IsArchived<>state.Retired) THROW 51000,'An imported scene was archived; review its association before adoption',1;
-- A JSON rowset joined directly to the global Scenes table can be reparsed
-- once per candidate scene. Materialise the small prior decision index first.
IF @Previous IS NOT NULL
BEGIN
DECLARE @PriorSceneDecisions TABLE(CanonicalId int PRIMARY KEY,ChapterId int,Retired bit);
INSERT @PriorSceneDecisions SELECT CanonicalId,ChapterId,Retired FROM OPENJSON(@Previous,'$.Scenes') WITH(CanonicalId int,ChapterId int,Retired bit) WHERE CanonicalId>0;
IF EXISTS(SELECT 1 FROM @PriorSceneDecisions prior JOIN dbo.Scenes actual ON actual.SceneID=prior.CanonicalId WHERE actual.IsArchived<>prior.Retired OR actual.ChapterID<>prior.ChapterId)
THROW 51000,'Canonical scene decisions changed after this snapshot; automatic replacement refused',1;
END;
DECLARE @Paragraphs table(Id uniqueidentifier PRIMARY KEY,Ordinal int UNIQUE,StartPosition int,EndPosition int,Text nvarchar(max),SceneId uniqueidentifier NULL,ChapterId int NULL,Story bit,Verified bit,Outline int);
INSERT @Paragraphs SELECT p.Id,p.Ordinal,p.StartPosition,p.EndPosition,p.Text,x.SceneId,x.ChapterId,x.Story,x.PositionVerified,p.Outline FROM OPENJSON(@Payload,'$.Paragraphs') WITH(Occurrence nvarchar(max) AS JSON,SceneId uniqueidentifier,ChapterId int,Story bit,PositionVerified bit) x CROSS APPLY OPENJSON(x.Occurrence) WITH(Id uniqueidentifier,Ordinal int,StartPosition int '$.Start',EndPosition int '$.End',Text nvarchar(max),Outline int) p;
IF EXISTS(SELECT 1 FROM @Paragraphs p JOIN @Scenes s ON s.Id=p.SceneId WHERE p.ChapterId IS NULL OR p.ChapterId<>s.ChapterId) THROW 51000,'Paragraph scene assignment crosses chapter boundaries',1;
IF EXISTS(SELECT 1 FROM @Paragraphs p WHERE p.Story=1 AND NOT EXISTS(SELECT 1 FROM @Scenes s WHERE s.Id=p.SceneId AND s.Retired=0)) THROW 51000,'Story paragraph has no current scene',1;
IF (SELECT COUNT(*) FROM @Paragraphs)>100000 OR EXISTS(SELECT 1 FROM @Paragraphs HAVING MIN(Ordinal)<>0 OR MAX(Ordinal)<>COUNT(*)-1) THROW 51000,'Invalid paragraph ordering',1;
-- New scene identities materialise through the existing canonical scene table; existing metadata is not overwritten.
DECLARE @SceneKey uniqueidentifier,@Chapter int,@Title nvarchar(200),@JsonIndex int,@NewID int;
DECLARE createScenes CURSOR LOCAL FAST_FORWARD FOR SELECT Id,ChapterId,Title,JsonIndex FROM @Scenes WHERE CanonicalId=0 AND Retired=0 AND (@ChangedChapterID IS NULL OR ChapterId=@ChangedChapterID);
OPEN createScenes;FETCH NEXT FROM createScenes INTO @SceneKey,@Chapter,@Title,@JsonIndex;
WHILE @@FETCH_STATUS=0
BEGIN
INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID)
SELECT @Chapter,COALESCE((SELECT MAX(SceneNumber) FROM dbo.Scenes WHERE ChapterID=@Chapter),0)+1,@Title,COALESCE((SELECT MAX(SortOrder) FROM dbo.Scenes WHERE ChapterID=@Chapter),0)+1,COALESCE((SELECT TimeModeID FROM dbo.TimeModes WHERE TimeModeName=N'Unknown'),template.TimeModeID),template.TimeConfidenceID,template.RevisionStatusID FROM(SELECT TOP(1) TimeModeID,TimeConfidenceID,RevisionStatusID FROM dbo.Scenes WHERE ChapterID=@Chapter ORDER BY SceneID) template;
IF @@ROWCOUNT<>1 THROW 51000,'A canonical source scene is required for splitting',1;
SET @NewID=SCOPE_IDENTITY();UPDATE @Scenes SET CanonicalId=@NewID WHERE Id=@SceneKey;SET @Payload=JSON_MODIFY(@Payload,CONCAT('$.Scenes[',@JsonIndex,'].CanonicalId'),@NewID);
FETCH NEXT FROM createScenes INTO @SceneKey,@Chapter,@Title,@JsonIndex;
END;CLOSE createScenes;DEALLOCATE createScenes;
UPDATE existing SET ChapterID=state.ChapterId,IsArchived=state.Retired,UpdatedDate=SYSUTCDATETIME() FROM dbo.Scenes existing JOIN @Scenes state ON state.CanonicalId=existing.SceneID WHERE @ChangedChapterID IS NULL OR state.ChapterId=@ChangedChapterID;
;WITH ordering AS(SELECT s.CanonicalId,ROW_NUMBER() OVER(PARTITION BY s.ChapterId ORDER BY MIN(p.Ordinal),s.CanonicalId) AS Sequence FROM @Scenes s JOIN @Paragraphs p ON p.SceneId=s.Id WHERE s.Retired=0 AND (@ChangedChapterID IS NULL OR s.ChapterId=@ChangedChapterID) GROUP BY s.CanonicalId,s.ChapterId)
UPDATE scene SET SortOrder=o.Sequence,SceneNumber=o.Sequence FROM dbo.Scenes scene JOIN ordering o ON o.CanonicalId=scene.SceneID;
DELETE dbo.BookParagraphPositions WHERE BookID=@BookID;
INSERT dbo.BookParagraphPositions(BookID,StartPosition,EndPosition,ChapterID,SceneID,Verified)
SELECT @BookID,p.StartPosition,p.EndPosition,COALESCE(s.ChapterId,p.ChapterId),s.CanonicalId,p.Verified FROM @Paragraphs p LEFT JOIN @Scenes s ON s.Id=p.SceneId;
-- Explicit merge/undo positions, scoped to this book. Anchored verified primary passages take precedence below.
;WITH positions AS(SELECT * FROM OPENJSON(@Payload,'$.EventPositions') WITH(Kind varchar(16),Id int,SceneId int))
UPDATE k SET SceneID=p.SceneId,UpdatedDate=SYSUTCDATETIME() FROM dbo.CharacterKnowledge k JOIN positions p ON p.Kind='Knowledge' AND p.Id=k.CharacterKnowledgeID JOIN dbo.Scenes old ON old.SceneID=k.SceneID JOIN dbo.Chapters oc ON oc.ChapterID=old.ChapterID JOIN dbo.Scenes dest ON dest.SceneID=p.SceneId JOIN dbo.Chapters dc ON dc.ChapterID=dest.ChapterID WHERE oc.BookID=@BookID AND dc.BookID=@BookID;
;WITH positions AS(SELECT * FROM OPENJSON(@Payload,'$.EventPositions') WITH(Kind varchar(16),Id int,SceneId int))
UPDATE r SET SceneID=p.SceneId,UpdatedDate=SYSUTCDATETIME() FROM dbo.RelationshipEvents r JOIN positions p ON p.Kind='Relationship' AND p.Id=r.RelationshipEventID JOIN dbo.Scenes old ON old.SceneID=r.SceneID JOIN dbo.Chapters oc ON oc.ChapterID=old.ChapterID JOIN dbo.Scenes dest ON dest.SceneID=p.SceneId JOIN dbo.Chapters dc ON dc.ChapterID=dest.ChapterID WHERE oc.BookID=@BookID AND dc.BookID=@BookID;
DELETE dbo.ManuscriptEvidenceIndex WHERE BookID=@BookID;
INSERT dbo.ManuscriptEvidenceIndex(BookID,EvidenceID,EventKind,EventID,IsPrimary,EvidenceState,DerivedSceneID)
SELECT @BookID,e.Id,e.EventKind,e.EventId,e.[Primary],e.State,CASE WHEN e.State=N'Verified' THEN s.CanonicalId END FROM OPENJSON(@Payload,'$.Evidence') WITH(Id uniqueidentifier,EventKind varchar(16),EventId int,[Primary] bit,State nvarchar(20),CurrentScene uniqueidentifier) e LEFT JOIN @Scenes s ON s.Id=e.CurrentScene;
IF EXISTS(SELECT 1 FROM dbo.ManuscriptEvidenceIndex e WHERE e.BookID=@BookID AND ((e.EventKind='Knowledge' AND NOT EXISTS(SELECT 1 FROM dbo.CharacterKnowledge k JOIN dbo.Scenes s ON s.SceneID=k.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE k.CharacterKnowledgeID=e.EventID AND c.BookID=@BookID)) OR(e.EventKind='Relationship' AND NOT EXISTS(SELECT 1 FROM dbo.RelationshipEvents r JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE r.RelationshipEventID=e.EventID AND c.BookID=@BookID)))) THROW 51000,'Evidence event does not belong to this book',1;
UPDATE k SET SceneID=e.DerivedSceneID,UpdatedDate=SYSUTCDATETIME() FROM dbo.CharacterKnowledge k JOIN dbo.ManuscriptEvidenceIndex e ON e.EventKind='Knowledge' AND e.EventID=k.CharacterKnowledgeID AND e.BookID=@BookID AND e.IsPrimary=1 AND e.EvidenceState=N'Verified' WHERE e.DerivedSceneID>0;
UPDATE r SET SceneID=e.DerivedSceneID,UpdatedDate=SYSUTCDATETIME() FROM dbo.RelationshipEvents r JOIN dbo.ManuscriptEvidenceIndex e ON e.EventKind='Relationship' AND e.EventID=r.RelationshipEventID AND e.BookID=@BookID AND e.IsPrimary=1 AND e.EvidenceState=N'Verified' WHERE e.DerivedSceneID>0;
-- Current prose projections remain in the established source service's tables. No planning/AI records are rewritten.
DECLARE @Canonical int,@SceneText nvarchar(max),@First int,@Last int,@Words int,@Characters int,@ProjectionKind nvarchar(40);
DECLARE sceneText CURSOR LOCAL FAST_FORWARD FOR SELECT s.CanonicalId,s.ChapterId,COALESCE(STRING_AGG(CONVERT(nvarchar(max),p.Text),N'') WITHIN GROUP(ORDER BY p.Ordinal),N''),MIN(p.Ordinal)+1,MAX(p.Ordinal)+1 FROM @Scenes s LEFT JOIN @Paragraphs p ON p.SceneId=s.Id AND p.Story=1 WHERE s.CanonicalId>0 AND s.Retired=0 AND (@ChangedChapterID IS NULL OR s.ChapterId=@ChangedChapterID) AND EXISTS(SELECT 1 FROM @Paragraphs assigned WHERE assigned.SceneId=s.Id AND assigned.Story=1) AND NOT EXISTS(SELECT 1 FROM @Paragraphs unassigned WHERE unassigned.ChapterId=s.ChapterId AND unassigned.SceneId IS NULL AND COALESCE(unassigned.Outline,10)<>1) AND NOT EXISTS(SELECT 1 FROM @Paragraphs unresolved WHERE unresolved.SceneId=s.Id AND unresolved.Story=1 AND unresolved.Verified=0) GROUP BY s.CanonicalId,s.ChapterId;
OPEN sceneText;FETCH NEXT FROM sceneText INTO @Canonical,@Chapter,@SceneText,@First,@Last;
WHILE @@FETCH_STATUS=0
BEGIN
SET @Words=(SELECT COUNT(*) FROM STRING_SPLIT(REPLACE(REPLACE(REPLACE(@SceneText,CHAR(13),N' '),CHAR(10),N' '),CHAR(9),N' '),N' ') WHERE value<>N'');
SET @Characters=DATALENGTH(@SceneText)/2;
SET @ProjectionKind=CASE WHEN EXISTS(SELECT 1 FROM OPENJSON(@Payload,'$.Scenes') WITH(CanonicalId int,NeedsRefinement bit) state JOIN dbo.SceneManuscriptSources source ON source.SceneID=state.CanonicalId WHERE state.CanonicalId=@Canonical AND state.NeedsRefinement=1 AND source.SourceKind=N'StructuralFallback') THEN N'StructuralFallback' ELSE N'ParagraphSync' END;
EXEC dbo.SceneManuscriptSource_Save @ProjectID=@ProjectID,@BookID=@BookID,@ChapterID=@Chapter,@SceneID=@Canonical,@SourceText=@SceneText,@SourceWordCount=@Words,@SourceCharacterCount=@Characters,@SourceStartParagraph=@First,@SourceEndParagraph=@Last,@WordStartParagraphIndex=@First,@WordEndParagraphIndex=@Last,@SourceKind=@ProjectionKind;
FETCH NEXT FROM sceneText INTO @Canonical,@Chapter,@SceneText,@First,@Last;
END;CLOSE sceneText;DEALLOCATE sceneText;
DECLARE @ActualEvents nvarchar(max)=(SELECT Kind,Id,SceneId,Description FROM(
SELECT CAST('Knowledge' AS varchar(16)) AS Kind,k.CharacterKnowledgeID AS Id,k.SceneID AS SceneId,COALESCE(k.Description,N'') AS Description FROM dbo.CharacterKnowledge k JOIN dbo.Scenes s ON s.SceneID=k.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@BookID
UNION ALL SELECT 'Relationship',r.RelationshipEventID,r.SceneID,COALESCE(r.Description,N'') FROM dbo.RelationshipEvents r JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@BookID) rows FOR JSON PATH);
SET @Payload=JSON_MODIFY(@Payload,'$.EventPositions',JSON_QUERY(COALESCE(@ActualEvents,N'[]')));
SET @Revision=COALESCE(@Revision,0)+1;SET @Payload=JSON_MODIFY(@Payload,'$.Revision',@Revision);SET @Payload=JSON_MODIFY(@Payload,'$.LastRequestId',CONVERT(nvarchar(36),@RequestID));
IF @Previous IS NULL INSERT dbo.BookParagraphManuscripts(BookID,ManuscriptID,Revision,RequestID,Payload) VALUES(@BookID,CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.ManuscriptId')),@Revision,@RequestID,@Payload);
ELSE UPDATE dbo.BookParagraphManuscripts SET ManuscriptID=CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.ManuscriptId')),Revision=@Revision,RequestID=@RequestID,Payload=@Payload,UpdatedUtc=SYSUTCDATETIME() WHERE BookID=@BookID;
EXEC dbo.Dynamics_RunContinuityChecks @ProjectID=@ProjectID,@BookID=@BookID;
COMMIT;SELECT @Payload;
END;
GO

View File

@ -0,0 +1,149 @@
-- Forward repair: retain exact later scene paragraph indices after bounded insertion/deletion.
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER PROCEDURE dbo.ParagraphManuscript
@Action varchar(16),@UserID int,@BookID int,@ExpectedRevision bigint=NULL,@RequestID uniqueidentifier=NULL,@Payload nvarchar(max)=NULL,@SessionID uniqueidentifier=NULL,@ManuscriptID uniqueidentifier=NULL,@WordRevision bigint=NULL,@Position int=NULL,@Mode nvarchar(16)=NULL,@ChangedChapterID int=NULL
AS
BEGIN
SET NOCOUNT ON;SET XACT_ABORT ON;
DECLARE @ProjectID int;
SELECT @ProjectID=b.ProjectID FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID;
IF @ProjectID IS NULL THROW 51000,'Book access denied',1;
IF @Action='position'
BEGIN
SELECT CAST(1 AS bit) AS HasSnapshot,m.Revision,p.ChapterID,p.SceneID
FROM dbo.BookParagraphManuscripts m OUTER APPLY(SELECT TOP(1) position.ChapterID,position.SceneID FROM dbo.BookParagraphPositions position
WHERE position.BookID=m.BookID AND position.Verified=1 AND position.StartPosition<=@Position AND position.EndPosition>@Position
AND m.ManuscriptID=@ManuscriptID AND TRY_CONVERT(uniqueidentifier,JSON_VALUE(m.Payload,'$.SessionId'))=@SessionID AND TRY_CONVERT(bigint,JSON_VALUE(m.Payload,'$.WordRevision'))=@WordRevision) p WHERE m.BookID=@BookID;RETURN;
END;
IF @Action='get' BEGIN SELECT Payload FROM dbo.BookParagraphManuscripts WHERE BookID=@BookID;RETURN;END;
IF @Action='status' BEGIN SELECT BookID,ManuscriptID,Revision,JSON_VALUE(Payload,'$.SnapshotHash') AS SnapshotHash,JSON_VALUE(Payload,'$.Mode') AS Mode,TRY_CONVERT(uniqueidentifier,JSON_VALUE(Payload,'$.SessionId')) AS SessionId,TRY_CONVERT(bigint,JSON_VALUE(Payload,'$.WordRevision')) AS WordRevision,
CAST(CASE WHEN EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND AccessRole=N'Owner' AND IsActive=1) THEN 1 ELSE 0 END AS bit) AS CanWrite,
CAST(CASE WHEN EXISTS(SELECT 1 FROM dbo.UserOnboardingState o WHERE o.BookID=@BookID AND o.OnboardingCompletedUtc IS NULL) OR EXISTS(SELECT 1 FROM dbo.StoryIntelligenceJobs j WHERE j.BookID=@BookID AND j.Status IN ('Pending','Queued','Running','Processing','Preparing','ReadingScenes','AnalysingCharacters','AnalysingRelationships','AnalysingLocations','AnalysingAssets','AnalysingTimeline','Finalising')) THEN 1 ELSE 0 END AS bit) AS Paused
FROM dbo.BookParagraphManuscripts WHERE BookID=@BookID;RETURN;END;
IF @Action='capture' BEGIN SELECT TOP(1) c.Payload FROM dbo.OnboardingManuscriptCaptures c WHERE c.BookID=@BookID AND EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds b WHERE b.PreviewID=c.PreviewID AND b.BookID=@BookID AND b.Status IN ('Complete','Built')) ORDER BY c.CreatedUtc DESC;RETURN;END;
IF @Action='events'
BEGIN
SELECT CAST('Knowledge' AS varchar(16)) AS Kind,k.CharacterKnowledgeID AS Id,k.SceneID,CONCAT(c.CharacterName,N': ',COALESCE(k.Description,N'Knowledge event')) AS Description
FROM dbo.CharacterKnowledge k JOIN dbo.Characters c ON c.CharacterID=k.CharacterID JOIN dbo.Scenes s ON s.SceneID=k.SceneID JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID WHERE ch.BookID=@BookID
UNION ALL SELECT 'Relationship',r.RelationshipEventID,r.SceneID,CONCAT(ca.CharacterName,N' / ',cb.CharacterName,N': ',COALESCE(r.Description,N'Relationship event'))
FROM dbo.RelationshipEvents r JOIN dbo.CharacterRelationships rel ON rel.CharacterRelationshipID=r.CharacterRelationshipID JOIN dbo.Characters ca ON ca.CharacterID=rel.CharacterAID JOIN dbo.Characters cb ON cb.CharacterID=rel.CharacterBID JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters ch ON ch.ChapterID=s.ChapterID WHERE ch.BookID=@BookID;RETURN;
END;
-- Conservative mutation contract: use the established project owner role, never expand collaborator permissions.
IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND IsActive=1 AND AccessRole=N'Owner') THROW 51000,'Project owner authority required',1;
IF @Action='mode'
BEGIN
IF COALESCE(@Mode,'') NOT IN ('Off','Manual','OnSave') THROW 51000,'Unsupported synchronisation mode',1;
BEGIN TRANSACTION;
DECLARE @PreferenceRevision bigint;
SELECT @Payload=Payload,@PreferenceRevision=Revision FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID;
IF @PreferenceRevision IS NULL OR @PreferenceRevision<>@ExpectedRevision THROW 51000,'Manuscript changed; refresh before changing preferences',1;
IF JSON_VALUE(@Payload,'$.Mode')<>@Mode BEGIN
SET @RequestID=NEWID();SET @PreferenceRevision+=1;SET @Payload=JSON_MODIFY(@Payload,'$.Mode',@Mode);SET @Payload=JSON_MODIFY(@Payload,'$.Revision',@PreferenceRevision);SET @Payload=JSON_MODIFY(@Payload,'$.LastRequestId',CONVERT(nvarchar(36),@RequestID));
UPDATE dbo.BookParagraphManuscripts SET Payload=@Payload,Revision=@PreferenceRevision,RequestID=@RequestID,UpdatedUtc=SYSUTCDATETIME() WHERE BookID=@BookID;
END;
COMMIT;SELECT @Payload;RETURN;
END;
IF @Action<>'save' THROW 51000,'Unknown manuscript operation',1;
IF @ChangedChapterID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE ChapterID=@ChangedChapterID AND BookID=@BookID AND IsArchived=0) THROW 51000,'Unknown chapter reconciliation scope',1;
IF ISJSON(@Payload)<>1 OR DATALENGTH(@Payload)>128*1024*1024 OR @RequestID IS NULL OR @ExpectedRevision IS NULL THROW 51000,'Invalid manuscript state',1;
IF COALESCE(TRY_CONVERT(int,JSON_VALUE(@Payload,'$.BookId')),-1)<>@BookID OR COALESCE(TRY_CONVERT(int,JSON_VALUE(@Payload,'$.ProjectId')),-1)<>@ProjectID OR TRY_CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.ManuscriptId')) IS NULL THROW 51000,'Manuscript scope mismatch',1;
IF COALESCE(JSON_VALUE(@Payload,'$.Mode'),'') NOT IN ('Off','Manual','OnSave') THROW 51000,'Unsupported synchronisation mode',1;
-- Do not adopt or replace a book while its accepted import is still awaiting a completed build.
IF EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptCaptures c WHERE c.BookID=@BookID AND c.IsCurrent=1 AND COALESCE(JSON_VALUE(c.Payload,'$.ParagraphTracking'),'false')<>'true' AND NOT EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds b WHERE b.PreviewID=c.PreviewID AND b.Status IN ('Complete','Built'))) THROW 51000,'Active import protected; finish the existing import before enabling paragraph tracking',1;
IF @ExpectedRevision>=0 AND (EXISTS(SELECT 1 FROM dbo.UserOnboardingState WHERE BookID=@BookID AND OnboardingCompletedUtc IS NULL) OR EXISTS(SELECT 1 FROM dbo.StoryIntelligenceJobs WHERE BookID=@BookID AND Status IN ('Pending','Queued','Running','Processing','Preparing','ReadingScenes','AnalysingCharacters','AnalysingRelationships','AnalysingLocations','AnalysingAssets','AnalysingTimeline','Finalising'))) THROW 51000,'Active import or analysis protected; synchronisation paused',1;
BEGIN TRANSACTION;
DECLARE @Revision bigint,@Previous nvarchar(max),@LastRequest uniqueidentifier;
SELECT @Revision=Revision,@Previous=Payload,@LastRequest=RequestID FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID;
IF @LastRequest=@RequestID BEGIN SELECT Payload FROM dbo.BookParagraphManuscripts WHERE BookID=@BookID;COMMIT;RETURN;END;
IF (@Revision IS NULL AND @ExpectedRevision<>-1) OR (@Revision IS NOT NULL AND @Revision<>@ExpectedRevision) THROW 51000,'Manuscript changed; refresh before retrying',1;
DECLARE @Scenes table(JsonIndex int,Id uniqueidentifier PRIMARY KEY,CanonicalId int,ChapterId int,Title nvarchar(200),Retired bit,MergedInto uniqueidentifier);
INSERT @Scenes SELECT CONVERT(int,j.[key]),s.Id,s.CanonicalId,s.ChapterId,s.Title,s.Retired,s.MergedInto FROM OPENJSON(@Payload,'$.Scenes') j CROSS APPLY OPENJSON(j.value) WITH(Id uniqueidentifier,CanonicalId int,ChapterId int,Title nvarchar(200),Retired bit,MergedInto uniqueidentifier) s;
IF EXISTS(SELECT 1 FROM @Scenes x LEFT JOIN dbo.Chapters c ON c.ChapterID=x.ChapterId AND c.BookID=@BookID WHERE c.ChapterID IS NULL) OR EXISTS(SELECT 1 FROM @Scenes x WHERE x.CanonicalId>0 AND NOT EXISTS(SELECT 1 FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE s.SceneID=x.CanonicalId AND c.BookID=@BookID)) THROW 51000,'Cross-book scene reference rejected',1;
IF EXISTS(SELECT 1 FROM dbo.Scenes actual WHERE actual.IsArchived=0 AND EXISTS(SELECT 1 FROM @Scenes tracked WHERE tracked.ChapterId=actual.ChapterID) AND NOT EXISTS(SELECT 1 FROM @Scenes tracked WHERE tracked.CanonicalId=actual.SceneID)) THROW 51000,'This chapter contains a scene outside the accepted paragraph map; review it before synchronising',1;
-- A snapshot is not authority to undo newer author archive/chapter decisions made elsewhere.
IF @Previous IS NULL AND EXISTS(SELECT 1 FROM @Scenes state JOIN dbo.Scenes actual ON actual.SceneID=state.CanonicalId WHERE actual.IsArchived<>state.Retired) THROW 51000,'An imported scene was archived; review its association before adoption',1;
-- A JSON rowset joined directly to the global Scenes table can be reparsed
-- once per candidate scene. Materialise the small prior decision index first.
IF @Previous IS NOT NULL
BEGIN
DECLARE @PriorSceneDecisions TABLE(CanonicalId int PRIMARY KEY,ChapterId int,Retired bit);
INSERT @PriorSceneDecisions SELECT CanonicalId,ChapterId,Retired FROM OPENJSON(@Previous,'$.Scenes') WITH(CanonicalId int,ChapterId int,Retired bit) WHERE CanonicalId>0;
IF EXISTS(SELECT 1 FROM @PriorSceneDecisions prior JOIN dbo.Scenes actual ON actual.SceneID=prior.CanonicalId WHERE actual.IsArchived<>prior.Retired OR actual.ChapterID<>prior.ChapterId)
THROW 51000,'Canonical scene decisions changed after this snapshot; automatic replacement refused',1;
END;
DECLARE @Paragraphs table(Id uniqueidentifier PRIMARY KEY,Ordinal int UNIQUE,StartPosition int,EndPosition int,Text nvarchar(max),SceneId uniqueidentifier NULL,ChapterId int NULL,Story bit,Verified bit,Outline int);
INSERT @Paragraphs SELECT p.Id,p.Ordinal,p.StartPosition,p.EndPosition,p.Text,x.SceneId,x.ChapterId,x.Story,x.PositionVerified,p.Outline FROM OPENJSON(@Payload,'$.Paragraphs') WITH(Occurrence nvarchar(max) AS JSON,SceneId uniqueidentifier,ChapterId int,Story bit,PositionVerified bit) x CROSS APPLY OPENJSON(x.Occurrence) WITH(Id uniqueidentifier,Ordinal int,StartPosition int '$.Start',EndPosition int '$.End',Text nvarchar(max),Outline int) p;
IF EXISTS(SELECT 1 FROM @Paragraphs p JOIN @Scenes s ON s.Id=p.SceneId WHERE p.ChapterId IS NULL OR p.ChapterId<>s.ChapterId) THROW 51000,'Paragraph scene assignment crosses chapter boundaries',1;
IF EXISTS(SELECT 1 FROM @Paragraphs p WHERE p.Story=1 AND NOT EXISTS(SELECT 1 FROM @Scenes s WHERE s.Id=p.SceneId AND s.Retired=0)) THROW 51000,'Story paragraph has no current scene',1;
IF (SELECT COUNT(*) FROM @Paragraphs)>100000 OR EXISTS(SELECT 1 FROM @Paragraphs HAVING MIN(Ordinal)<>0 OR MAX(Ordinal)<>COUNT(*)-1) THROW 51000,'Invalid paragraph ordering',1;
-- New scene identities materialise through the existing canonical scene table; existing metadata is not overwritten.
DECLARE @SceneKey uniqueidentifier,@Chapter int,@Title nvarchar(200),@JsonIndex int,@NewID int;
DECLARE createScenes CURSOR LOCAL FAST_FORWARD FOR SELECT Id,ChapterId,Title,JsonIndex FROM @Scenes WHERE CanonicalId=0 AND Retired=0 AND (@ChangedChapterID IS NULL OR ChapterId=@ChangedChapterID);
OPEN createScenes;FETCH NEXT FROM createScenes INTO @SceneKey,@Chapter,@Title,@JsonIndex;
WHILE @@FETCH_STATUS=0
BEGIN
INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID)
SELECT @Chapter,COALESCE((SELECT MAX(SceneNumber) FROM dbo.Scenes WHERE ChapterID=@Chapter),0)+1,@Title,COALESCE((SELECT MAX(SortOrder) FROM dbo.Scenes WHERE ChapterID=@Chapter),0)+1,COALESCE((SELECT TimeModeID FROM dbo.TimeModes WHERE TimeModeName=N'Unknown'),template.TimeModeID),template.TimeConfidenceID,template.RevisionStatusID FROM(SELECT TOP(1) TimeModeID,TimeConfidenceID,RevisionStatusID FROM dbo.Scenes WHERE ChapterID=@Chapter ORDER BY SceneID) template;
IF @@ROWCOUNT<>1 THROW 51000,'A canonical source scene is required for splitting',1;
SET @NewID=SCOPE_IDENTITY();UPDATE @Scenes SET CanonicalId=@NewID WHERE Id=@SceneKey;SET @Payload=JSON_MODIFY(@Payload,CONCAT('$.Scenes[',@JsonIndex,'].CanonicalId'),@NewID);
FETCH NEXT FROM createScenes INTO @SceneKey,@Chapter,@Title,@JsonIndex;
END;CLOSE createScenes;DEALLOCATE createScenes;
UPDATE existing SET ChapterID=state.ChapterId,IsArchived=state.Retired,UpdatedDate=SYSUTCDATETIME() FROM dbo.Scenes existing JOIN @Scenes state ON state.CanonicalId=existing.SceneID WHERE @ChangedChapterID IS NULL OR state.ChapterId=@ChangedChapterID;
;WITH ordering AS(SELECT s.CanonicalId,ROW_NUMBER() OVER(PARTITION BY s.ChapterId ORDER BY MIN(p.Ordinal),s.CanonicalId) AS Sequence FROM @Scenes s JOIN @Paragraphs p ON p.SceneId=s.Id WHERE s.Retired=0 AND (@ChangedChapterID IS NULL OR s.ChapterId=@ChangedChapterID) GROUP BY s.CanonicalId,s.ChapterId)
UPDATE scene SET SortOrder=o.Sequence,SceneNumber=o.Sequence FROM dbo.Scenes scene JOIN ordering o ON o.CanonicalId=scene.SceneID;
DELETE dbo.BookParagraphPositions WHERE BookID=@BookID;
INSERT dbo.BookParagraphPositions(BookID,StartPosition,EndPosition,ChapterID,SceneID,Verified)
SELECT @BookID,p.StartPosition,p.EndPosition,COALESCE(s.ChapterId,p.ChapterId),s.CanonicalId,p.Verified FROM @Paragraphs p LEFT JOIN @Scenes s ON s.Id=p.SceneId;
-- Explicit merge/undo positions, scoped to this book. Anchored verified primary passages take precedence below.
;WITH positions AS(SELECT * FROM OPENJSON(@Payload,'$.EventPositions') WITH(Kind varchar(16),Id int,SceneId int))
UPDATE k SET SceneID=p.SceneId,UpdatedDate=SYSUTCDATETIME() FROM dbo.CharacterKnowledge k JOIN positions p ON p.Kind='Knowledge' AND p.Id=k.CharacterKnowledgeID JOIN dbo.Scenes old ON old.SceneID=k.SceneID JOIN dbo.Chapters oc ON oc.ChapterID=old.ChapterID JOIN dbo.Scenes dest ON dest.SceneID=p.SceneId JOIN dbo.Chapters dc ON dc.ChapterID=dest.ChapterID WHERE oc.BookID=@BookID AND dc.BookID=@BookID;
;WITH positions AS(SELECT * FROM OPENJSON(@Payload,'$.EventPositions') WITH(Kind varchar(16),Id int,SceneId int))
UPDATE r SET SceneID=p.SceneId,UpdatedDate=SYSUTCDATETIME() FROM dbo.RelationshipEvents r JOIN positions p ON p.Kind='Relationship' AND p.Id=r.RelationshipEventID JOIN dbo.Scenes old ON old.SceneID=r.SceneID JOIN dbo.Chapters oc ON oc.ChapterID=old.ChapterID JOIN dbo.Scenes dest ON dest.SceneID=p.SceneId JOIN dbo.Chapters dc ON dc.ChapterID=dest.ChapterID WHERE oc.BookID=@BookID AND dc.BookID=@BookID;
DELETE dbo.ManuscriptEvidenceIndex WHERE BookID=@BookID;
INSERT dbo.ManuscriptEvidenceIndex(BookID,EvidenceID,EventKind,EventID,IsPrimary,EvidenceState,DerivedSceneID)
SELECT @BookID,e.Id,e.EventKind,e.EventId,e.[Primary],e.State,CASE WHEN e.State=N'Verified' THEN s.CanonicalId END FROM OPENJSON(@Payload,'$.Evidence') WITH(Id uniqueidentifier,EventKind varchar(16),EventId int,[Primary] bit,State nvarchar(20),CurrentScene uniqueidentifier) e LEFT JOIN @Scenes s ON s.Id=e.CurrentScene;
IF EXISTS(SELECT 1 FROM dbo.ManuscriptEvidenceIndex e WHERE e.BookID=@BookID AND ((e.EventKind='Knowledge' AND NOT EXISTS(SELECT 1 FROM dbo.CharacterKnowledge k JOIN dbo.Scenes s ON s.SceneID=k.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE k.CharacterKnowledgeID=e.EventID AND c.BookID=@BookID)) OR(e.EventKind='Relationship' AND NOT EXISTS(SELECT 1 FROM dbo.RelationshipEvents r JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE r.RelationshipEventID=e.EventID AND c.BookID=@BookID)))) THROW 51000,'Evidence event does not belong to this book',1;
UPDATE k SET SceneID=e.DerivedSceneID,UpdatedDate=SYSUTCDATETIME() FROM dbo.CharacterKnowledge k JOIN dbo.ManuscriptEvidenceIndex e ON e.EventKind='Knowledge' AND e.EventID=k.CharacterKnowledgeID AND e.BookID=@BookID AND e.IsPrimary=1 AND e.EvidenceState=N'Verified' WHERE e.DerivedSceneID>0;
UPDATE r SET SceneID=e.DerivedSceneID,UpdatedDate=SYSUTCDATETIME() FROM dbo.RelationshipEvents r JOIN dbo.ManuscriptEvidenceIndex e ON e.EventKind='Relationship' AND e.EventID=r.RelationshipEventID AND e.BookID=@BookID AND e.IsPrimary=1 AND e.EvidenceState=N'Verified' WHERE e.DerivedSceneID>0;
-- Unchanged later prose keeps its source and decisions, but paragraph ordinals
-- may shift after an insertion/deletion in the reconciled chapter.
IF @ChangedChapterID IS NOT NULL
BEGIN
;WITH bounds AS(
SELECT s.CanonicalId,MIN(p.Ordinal)+1 FirstParagraph,MAX(p.Ordinal)+1 LastParagraph
FROM @Scenes s JOIN @Paragraphs p ON p.SceneId=s.Id AND p.Story=1
WHERE s.CanonicalId>0 AND s.Retired=0 AND s.ChapterId<>@ChangedChapterID
AND NOT EXISTS(SELECT 1 FROM @Paragraphs unassigned WHERE unassigned.ChapterId=s.ChapterId AND unassigned.SceneId IS NULL AND COALESCE(unassigned.Outline,10)<>1)
AND NOT EXISTS(SELECT 1 FROM @Paragraphs unresolved WHERE unresolved.SceneId=s.Id AND unresolved.Story=1 AND unresolved.Verified=0)
GROUP BY s.CanonicalId)
UPDATE source SET SourceStartParagraph=b.FirstParagraph,SourceEndParagraph=b.LastParagraph,
WordStartParagraphIndex=b.FirstParagraph,WordEndParagraphIndex=b.LastParagraph,UpdatedUtc=SYSUTCDATETIME()
FROM dbo.SceneManuscriptSources source JOIN bounds b ON b.CanonicalId=source.SceneID
WHERE source.BookID=@BookID AND (COALESCE(source.SourceStartParagraph,-1)<>b.FirstParagraph OR COALESCE(source.SourceEndParagraph,-1)<>b.LastParagraph
OR COALESCE(source.WordStartParagraphIndex,-1)<>b.FirstParagraph OR COALESCE(source.WordEndParagraphIndex,-1)<>b.LastParagraph);
END;
-- Current prose projections remain in the established source service's tables. No planning/AI records are rewritten.
DECLARE @Canonical int,@SceneText nvarchar(max),@First int,@Last int,@Words int,@Characters int,@ProjectionKind nvarchar(40);
DECLARE sceneText CURSOR LOCAL FAST_FORWARD FOR SELECT s.CanonicalId,s.ChapterId,COALESCE(STRING_AGG(CONVERT(nvarchar(max),p.Text),N'') WITHIN GROUP(ORDER BY p.Ordinal),N''),MIN(p.Ordinal)+1,MAX(p.Ordinal)+1 FROM @Scenes s LEFT JOIN @Paragraphs p ON p.SceneId=s.Id AND p.Story=1 WHERE s.CanonicalId>0 AND s.Retired=0 AND (@ChangedChapterID IS NULL OR s.ChapterId=@ChangedChapterID) AND EXISTS(SELECT 1 FROM @Paragraphs assigned WHERE assigned.SceneId=s.Id AND assigned.Story=1) AND NOT EXISTS(SELECT 1 FROM @Paragraphs unassigned WHERE unassigned.ChapterId=s.ChapterId AND unassigned.SceneId IS NULL AND COALESCE(unassigned.Outline,10)<>1) AND NOT EXISTS(SELECT 1 FROM @Paragraphs unresolved WHERE unresolved.SceneId=s.Id AND unresolved.Story=1 AND unresolved.Verified=0) GROUP BY s.CanonicalId,s.ChapterId;
OPEN sceneText;FETCH NEXT FROM sceneText INTO @Canonical,@Chapter,@SceneText,@First,@Last;
WHILE @@FETCH_STATUS=0
BEGIN
SET @Words=(SELECT COUNT(*) FROM STRING_SPLIT(REPLACE(REPLACE(REPLACE(@SceneText,CHAR(13),N' '),CHAR(10),N' '),CHAR(9),N' '),N' ') WHERE value<>N'');
SET @Characters=DATALENGTH(@SceneText)/2;
SET @ProjectionKind=CASE WHEN EXISTS(SELECT 1 FROM OPENJSON(@Payload,'$.Scenes') WITH(CanonicalId int,NeedsRefinement bit) state JOIN dbo.SceneManuscriptSources source ON source.SceneID=state.CanonicalId WHERE state.CanonicalId=@Canonical AND state.NeedsRefinement=1 AND source.SourceKind=N'StructuralFallback') THEN N'StructuralFallback' ELSE N'ParagraphSync' END;
EXEC dbo.SceneManuscriptSource_Save @ProjectID=@ProjectID,@BookID=@BookID,@ChapterID=@Chapter,@SceneID=@Canonical,@SourceText=@SceneText,@SourceWordCount=@Words,@SourceCharacterCount=@Characters,@SourceStartParagraph=@First,@SourceEndParagraph=@Last,@WordStartParagraphIndex=@First,@WordEndParagraphIndex=@Last,@SourceKind=@ProjectionKind;
FETCH NEXT FROM sceneText INTO @Canonical,@Chapter,@SceneText,@First,@Last;
END;CLOSE sceneText;DEALLOCATE sceneText;
DECLARE @ActualEvents nvarchar(max)=(SELECT Kind,Id,SceneId,Description FROM(
SELECT CAST('Knowledge' AS varchar(16)) AS Kind,k.CharacterKnowledgeID AS Id,k.SceneID AS SceneId,COALESCE(k.Description,N'') AS Description FROM dbo.CharacterKnowledge k JOIN dbo.Scenes s ON s.SceneID=k.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@BookID
UNION ALL SELECT 'Relationship',r.RelationshipEventID,r.SceneID,COALESCE(r.Description,N'') FROM dbo.RelationshipEvents r JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@BookID) rows FOR JSON PATH);
SET @Payload=JSON_MODIFY(@Payload,'$.EventPositions',JSON_QUERY(COALESCE(@ActualEvents,N'[]')));
SET @Revision=COALESCE(@Revision,0)+1;SET @Payload=JSON_MODIFY(@Payload,'$.Revision',@Revision);SET @Payload=JSON_MODIFY(@Payload,'$.LastRequestId',CONVERT(nvarchar(36),@RequestID));
IF @Previous IS NULL INSERT dbo.BookParagraphManuscripts(BookID,ManuscriptID,Revision,RequestID,Payload) VALUES(@BookID,CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.ManuscriptId')),@Revision,@RequestID,@Payload);
ELSE UPDATE dbo.BookParagraphManuscripts SET ManuscriptID=CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.ManuscriptId')),Revision=@Revision,RequestID=@RequestID,Payload=@Payload,UpdatedUtc=SYSUTCDATETIME() WHERE BookID=@BookID;
EXEC dbo.Dynamics_RunContinuityChecks @ProjectID=@ProjectID,@BookID=@BookID;
COMMIT;SELECT @Payload;
END;
GO