Integrate bounded native chapter synchronisation and resumable repair

This commit is contained in:
Nick Beckley 2026-11-09 12:25:13 +00:00
parent e6e2a33847
commit 59e17df43f
49 changed files with 972 additions and 84 deletions

View File

@ -23,3 +23,7 @@ Implementation, tests, measured portable timings, migration/deployment identity
### First portable milestone
Versioned fingerprint/XML reader, accepted-snapshot checkpoint model, read-only unchanged-chapter validation, explicit missing-native-ID adoption, conservative changed-chapter merging through the existing engine, authorised API/service, and forward migration 245 source are implemented. Migration is not yet applied and this milestone is not yet deployed. Solution build passes without warnings. Focused tests cover reordered/split paragraphs, Unicode/control characters, cross-session positions, stale lineage, duplicate IDs, preservation of unrelated GUIDs/scenes, hard boundaries and unsafe XML rejection. Portable SHA-256 measurement: 48 synthetic chapters / 8,640 paragraphs in 26.7 ms on Atlas; excludes Word/COM and is not a Windows performance claim.
### 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.

View File

@ -0,0 +1,83 @@
# Chapter-based synchronisation and repair — implementation evidence
Shared branch: `codex/word-companion-native-phase1-20261104`. Windows baseline `51316f0f834e71319bbca6e93002ffd32314bfe4` / installed 1.0.0.22. First foundation commit: `e6e2a33`. Final implementation/deployment ledger follows below.
## Implemented behaviour
The existing canonical paragraph snapshot, GUID reconciliation engine, saved scene assignments, evidence, authenticated presence, command mailbox and Word scheduler remain authoritative. This is an additive chapter path, negotiated with **`chapter-sync-v1`**, not a second import or scene-detection engine. .22 remains compatible and receives its existing commands; fast reopening requires the new **1.0.0.23 candidate** agent and VSTO. Nothing was installed or packaged on Atlas.
```mermaid
sequenceDiagram
participant W as Word STA / bounded scheduler
participant A as Existing per-user agent
participant S as Authenticated PlotDirector services
participant D as Existing snapshot + chapter validations
participant C as Writing Context / Intent
W->>A: Document, saved state, session/revision, cursor
A->>S: Existing exact-session presence
A->>S: Chapter manifest
S->>D: Accepted source checkpoints / same-session live ranges
A->>W: Bounded chapter-check at current cursor
W->>A: Range text + single chapter XML, bounded IPC chunks
Note over A: Exact XML/text match, native IDs, SHA-256 outside Word
A->>S: Hashes + paragraph identity/length evidence, no prose
alt Existing complete source matches
S->>D: CAS metadata adoption + current physical positions
else Changed chapter and existing mode / explicit repair permits prose
A->>S: Only this chapter's exact paragraphs
S->>D: Existing reconciliation, coherent snapshot CAS
S->>D: Independently accepted chapter positions
else Ambiguous / unapproved / complex
S-->>A: Changed / Needs review, preserve accepted work
end
A->>S: Presence at cursor, no navigation request
S->>D: Resolve only verified live chapter positions
S-->>C: Existing presence/fragment update, retain active tab
A->>W: Next bounded chapter check, current document prioritised
```
The current chapter is prioritised. Subsequent reads advance using actual Word range ends, not stale saved absolute positions, and wrap once. Two document reads and native queues are bounded; activating another document can supersede background work. Obsolete frames, revisions, accounts and closed sessions are rejected. A network interruption retains server checkpoints and retries on reconnection. Explicit cancellation revokes the prose permit and keeps committed chapters. New sessions revalidate content/identity evidence cheaply rather than trusting old offsets.
Changed prose is transferred only under the existing OnSave preference or an explicit owner repair request scoped to installation grant, manuscript, session, Word revision and expiry. Manual mode performs evidence checks without prose upload. Off stops automatic checking. Nothing triggers import or AI. No Word prose or permanent markers are written. Explicit full snapshot fallback remains available for unsupported content.
Repair is available in the **top-right Word connection dialog** and **book → Manuscript structure and evidence**. The latter also shows saved checkpoints and cancellation. The compact native ribbon adds chapter progress and a Manuscript menu with Synchronise, Repair and Troubleshooting; tray guidance reuses server progress. Saved acceptance is distinguished from live liveness. Newly requested repair cannot inherit an old green completion. Only explicit navigation uses the existing correlated Word command path; passive checking never calls Select or sends navigate.
## Persistence and identity
`ParagraphManuscript.ChapterCheckpoints` is additive JSON in the existing snapshot: canonical chapter/heading GUID, native boundary IDs, exact content/identity/mapping digests, ordering, paragraph count, algorithm, accepted lineage, last successful sync and status. Existing imports are not backfilled or declared corrupt. A server-authorised repair can fill missing native IDs only with unique, complete exact chapter evidence; existing IDs, GUIDs and scene assignments cannot be replaced by coincidental text or numeric identity.
Migration **245** adds `BookChapterValidations` and `dbo.BookChapterSync`: per-user, manuscript, session and Word revision; 12-hour expiring current physical positions; authorisation, owner mutations, protected-job checks, snapshot CAS, bounded JSON, unknown/cross-chapter/duplicate/overlapping-position rejection and conflicting same-revision evidence protection. Reads join accepted source content/identity/mapping digests and canonical nonarchived chapter/scene relationships. Validating one chapter cannot mark unchecked chapters trustworthy.
Forward migrations **246** and **247** respectively invalidate live chapter ranges when duplicate/ambiguous structure is flagged, and maintain the existing whole-snapshot digest when missing native IDs are adopted. These were found during integration testing after 245 had been applied; existing migrations were not rewritten after application. All three procedures remain compatible with .22.
Changed-chapter reconciliation reconstructs one coherent logical snapshot using the existing engine, CAS-saves it and clears the full-snapshot live-session claim. Unrelated canonical IDs/evidence remain intact. Its separate live acceptance commit is conservative: interruption after source save leaves valid canonical content but no new green position claim, and retry can complete acceptance. Other chapter position proofs remain reusable only while their source mapping hashes and exact live Word revision match. Canonical ordering and scene boundaries are never silently rewritten for moved/deleted/inserted chapters.
Existing backup format 1.5 / selective 2.1 carries checkpoint JSON through the established recovery graph. Typed chapter IDs and mapping hashes are remapped; paragraph/native/scene GUID evidence and source text hashes survive. Restore detaches live trust, starts Manual and removes old live validation rows through the snapshot FK. No leases, repair permissions or credentials are restored.
## Fingerprints and native access
`sha256-utf16le-paragraphs-v1`: encode version, paragraph count and each string's code-unit length with little-endian Int32 prefixes; write each exact UTF-16 code unit little endian. No whitespace, Unicode composition, CR/LF, paragraph delimiter or Word control-character normalisation. Isolated surrogates remain distinguishable. Splitting/merging, order and changed text alter the digest. Ordered native IDs, lengths and outline levels form a separate digest; GUID/chapter/scene/verification assignments form the mapping digest. Text alone never validates positions.
The native reader uses read-only Range.GoTo to find Heading 1 boundaries, staged Range.Text and **one chapter Range.WordOpenXML**, plus the next heading's tiny identity range. It never uses Selection/Select or passes COM objects outside the STA. XML parsing, styles, exact text comparison, hashing and network work run in the agent. Transport uses 2,048-character chunks, existing 256 KiB frames and mailbox backpressure. Bounds: 256 Ki UTF-16 code units /10,000 paragraphs per chapter, 8 Mi characters XML, two concurrent document readers and bounded heading search. COM calls and scheduler steps are instrumented. A single COM call remains unpreemptible, so the 20–30 ms goal needs actual measurement.
Supported XML is deliberately conservative: ordinary main-body paragraphs, styles/outline inheritance, text, tabs and soft breaks with exact equality to Range.Text and complete unique native IDs. Tables, fields, drawings, tracked insert/delete/moves, footnotes and page/column breaks are refused rather than assigned guessed offsets. Word-generated range wrappers and real style/export behaviour require Windows qualification. Unsupported/oversized content can use the explicit proven bounded full-reader fallback; it is not silently invoked during reopening.
Saved DOCX package inspection was considered: ZIP `/word/document.xml` and styles can be hashed off the STA without per-paragraph COM, but file evidence does not prove the current in-memory Word range, saved state or positions. Unsaved edits, background save, AutoSave/cloud paths, external replacement, fields/revisions and Word's text projection all complicate that correspondence. This delivery deliberately trusts measured live chapter Range evidence, not a file timestamp/hash or an unqualified file cache. No Track Changes dependency or saved-file speed claim is introduced. A later read-only package accelerator must preserve the same exact live validation checks.
Microsoft API references: [Range.GoTo](https://learn.microsoft.com/en-us/office/vba/api/word.range.goto), [Range.WordOpenXML](https://learn.microsoft.com/en-us/office/vba/api/word.range.wordopenxml). Source evidence is in `Vsto/WordChapterRead.cs`, `Agent/TrayCoordinator.Chapters.cs`, protocol `ChapterFingerprint.cs`, server `ChapterCheckpointEngine.cs`, `ChapterSyncService.cs`, `ChapterSyncRepository.cs` and migrations 245–247.
## Qualification and deployment ledger
To be completed with actual final verification; Windows measurements are explicitly outstanding. See [ready-to-use Windows handover](WindowsHandover/2026-11-09-chapter-sync.md).
### Pre-deployment gates
- `dotnet build PlotLine.slnx --no-restore --disable-build-servers -m:1 /p:UseSharedCompilation=false`: passed, zero warnings/errors, including the Windows-targeted managed agent; excludes VSTO host compilation.
- Full application executable harness: **455 PASS** results. Native foundation: **271 checks**. Focused chapter engine: **29 PASS** results; agent chapter protocol: **110 PASS** results (including 100 repeated passive selections). Paragraph/recovery/workflow regressions and server Context navigation regressions pass; a new receipt-ordering regression also passes after the full run.
- Chromium: actual compiled Context shell in browser/PWA/dedicated window variants, both legacy Sync and capability-gated Repair form routing, metadata-only acceptance without global revision increment, tab preservation and simulated follow/reconnect/navigation feedback tests pass. These are browser/protocol tests, not real Word.
- Disposable Development account/book: real repository/SP commits validate native-ID adoption, current scene position, stale CAS rollback, separate live-session isolation, preserved paragraph/prose/scene identities, retry/resume and cross-user refusal. The adopted full snapshot digest is checked against actual stored records.
- Portable hashing benchmark: **43.5 ms** for 48 synthetic chapters /8,640 paragraphs on the final focused run (earlier run 26.7 ms). This excludes all Word/COM, XML extraction, network and UI work; it is not a manuscript performance promise.
- Development backup `PlotDirector_Development_before_chapter_sync_245_20261109T120018Z.bak` passed CHECKSUM/VERIFYONLY. Separate verified backups precede 246 and 247 (`before_chapter_review_246_20261109T121300Z.bak`, `before_chapter_digest_247_20261109T122600Z.bak`). Every migration passed a transactionally rolled-back dry run before application. No database was reset/restored.
- Read-only before/after comparison: book **10152** has the identical accepted payload SHA-256, revision and payload length, **48 chapters /290 scenes** after schema work. No real-book backfill, repair, reimport, scene detection or AI operation was run.
Live deployment/protocol evidence is appended after the release is verified. Source 1.0.0.23 remains a Windows qualification candidate, not an installed/public release.

View File

@ -0,0 +1,70 @@
# Windows handover: chapter synchronisation, candidate 1.0.0.23
Use only `codex/word-companion-native-phase1-20261104`. Atlas implementation/deployment evidence and the exact handover commits are in [the implementation report](../2026-11-09-chapter-sync-implementation.md). Fetch the configured tracking remote, inspect/preserve the worktree, and fast-forward only. Stop on divergence. No branches, worktrees, rebase, force pushes, trust-store changes or installer redesign.
## Non-interactive build first
Do not use Computer Use, launch Word, steal focus, close applications or install anything during unattended qualification. Identify the actual Windows user/profile; a sandbox registry does not establish installation for the interactive author. Atlas did not build the VSTO, sign, package or install this candidate.
The managed/native-source changes are:
- `Protocol/Manuscript/ChapterFingerprint.cs`, `Messages.cs`, `TrayContracts.cs`: optional `chapter-sync-v1`; exact fingerprints, bounded chapter frames and server-owned progress.
- `Client/AgentLink.cs`, `Agent/PipeHost.cs`, `SessionManager.cs`, `TrayCoordinator.Chapters.cs`, `TrayCoordinator.cs`, `CloudGateway.cs`: negotiated current-chapter checking, progressive/resumable acceptance, changed-chapter-only upload under the existing synchronisation preference or explicit repair permit.
- `Vsto/WordChapterRead.cs` (explicitly included in `PlotDirector.WordAddIn.csproj`), `WordAdapter.cs`, `NativeRibbon.cs`, `Ribbon.xml`: owner-thread staged Range reads, no selection, compact chapter status and Synchronise/Repair/Troubleshooting. No permanent paragraph markers or prose edits.
- `Agent/TrayApplication.cs`: displays the existing server chapter progress in the compact guidance area; authentication/association/installer architecture retained.
Run serially from the existing checkout:
```powershell
.\PlotDirector.NativeCompanion\WindowsValidation\Update-WordCompanion.ps1
# Optional existing signing identity when discovery is ambiguous:
# ... -CertificateThumbprint '<existing thumbprint>'
dotnet run --project PlotDirector.NativeCompanion/Tests -- --chapter-sync
dotnet run --project PlotLine.Tests -- --chapter-sync
dotnet run --project PlotLine.Tests -- --paragraph-manuscripts
```
The update script builds the signed VSTO and managed components and prepares a developer package; it does **not** install. Expected package: the real user's Downloads known folder, `PlotDirectorWordCompanion\1.0.0.23-<first-eight-source-SHA>`. Verify `package.json`, both payload versions and clean source SHA. Preserve the installed 1.0.0.22 package. If a Windows compiler/API error occurs, make only a focused native compatibility fix, test, commit and push this same branch.
Use the existing unified installer, after build validation:
```powershell
.\PlotDirector.NativeCompanion\WindowsValidation\Setup\Build-Setup.ps1 `
-PackagePath '<verified developer package directory>' `
-ExpectedSourceCommit '<exact clean package SHA>' `
-OutputDirectory '<new candidate output directory>' `
-CertificateThumbprint '<existing thumbprint>'
```
`WindowsValidation/Setup/Release.json` selects application **1.0.0.23**, MSI **1.0.23**, a fresh ProductCode and unchanged upgrade family/baseline pins. Keep those qualified baseline pins; they are not invented hashes for .22. Verify using `Setup/README.md` and the existing `Test-SetupPackage.ps1` procedure. Deliver **PlotDirectorCompanionSetup.exe** with both VSTO and agent. Do not substitute a loose `.vsto` file. Installation is a separate explicitly scheduled step; do not open approval prompts unattended. Preserve protected credentials, settings and associations. Do not forcibly close Word or other applications.
## Native benchmark — scheduled interactive session only
Use a copy of an author-owned test manuscript, saved, with a representative complete Heading 1 chapter selected by the human. Do not automate that selection. Attach to already running Word:
```powershell
powershell.exe -STA -File .\PlotDirector.NativeCompanion\WindowsValidation\Measure-ChapterSync.ps1 `
-ProtocolAssembly '<verified netstandard2.0 protocol DLL from the package/build>' `
-OutputFile '<new absolute JSON report path>'
# Optional explicitly expensive, capped legacy baseline:
# ... -IncludeLegacyParagraphXml -MaximumParagraphs 100
```
The script never launches, selects, saves or closes Word. It records Range.Text, exact SHA-256, one chapter WordOpenXML, portable native-ID parsing and optional capped per-paragraph XML timings. Unsupported XML is recorded as a parse error, not hidden. Cross-process COM wall time is **not** in-add-in UI occupancy: also collect existing `chapter-range-text`, `chapter-range-xml`, `chapter-next-heading-identity` and `chapter-ui-step` metrics from Advanced/Troubleshooting. Report actual chapter sizes, max/median timings, observed typing/scrolling/save/cursor behaviour. No speed claim without measurements.
## Functional acceptance
First use disposable books and copied documents; never reimport/reset/delete book 10152 to test this work.
1. Verify both .23 binaries, retained sign-in/settings/book association and negotiated chapter capability. Development must expose `chapterSyncSupported=true`; .22 remains on its old path.
2. Open a previously indexed, unchanged Heading 1 manuscript in a new Word session. The active chapter should be checked first, then remaining chapters progressively. Confirm current Context scene across chapters, including a chapter not yet checked. No full snapshot request, per-paragraph XML loop, automatic AI call, passive `navigate`, Range.Select or prose edit should occur.
3. Measure the **target**, not an assumed result: current chapter following returns in seconds; individual COM steps aim around 20–30 ms where practical. A single Word COM call cannot be preempted; oversized/complex chapters must report review/fallback rather than freeze or guess.
4. Manual mode: edit/save a chapter, verify `Changed` without prose upload. Explicit Synchronise/Repair authorises that chapter only. On-save mode: verify changed chapter reconciliation, unchanged GUIDs/scenes, later chapters' shifted positions and no AI restart. Word saving must never await Companion.
5. Stop Companion, edit/save, restart. Validate actual chapter evidence again; do not reuse old absolute offsets merely because the book/session looks familiar.
6. Cancel after some chapters are accepted, reconnect/restart and Repair. Previously accepted current-session checkpoints resume; a new session revalidates cheaply. Chapter rename with stable identity may reconcile; inserted/deleted/moved chapter boundaries and duplicate native IDs must require review without canonical reassignment.
7. Switch three documents/books rapidly while checking; close one; terminate/restart the agent. Late frames must not affect another document. No flashing from repeated ribbon invalidation, unexpected focus or selection change. Repeated cursor notifications cannot command Word.
8. Inspect blank/headingless documents, tables/fields/track changes, large chapters and repeated prose. Fast-path refusal is safe; the explicit full snapshot fallback remains available. Do not use fallback automatically or claim unsupported content passed.
9. Check compact progress, book/chapter/scene tooltip, Sync, Repair and Troubleshooting; top-right website Word connection dialog and book → Manuscript structure and evidence show consistent server acceptance. A requested repair must not inherit an earlier green completion.
10. Backup/restore a disposable indexed book. Paragraph/native GUID evidence, canonical remapping, source fingerprints and author decisions must survive. Restored books start Manual and have no live-session trust.
Only after synthetic qualification, with the author's agreement, use **Repair Manuscript Synchronisation** on the existing 10152 import. Keep its 48 chapters/290 scenes/paragraph GUIDs and SI/author decisions. Missing checkpoints are not corruption. Do not rerun import or analysis. Compare accepted data before/after; stop on ambiguity. Report real Word results separately from automated/HTTP tests, with exact commits and installer hashes.

View File

@ -125,6 +125,10 @@ public sealed partial class CloudGateway : IDisposable
=>await Send<T>(HttpMethod.Get,path,null,expectedContext,cancellation);
public async Task<T> Post<T>(string path,object body,Guid expectedContext)
=>await Send<T>(HttpMethod.Post,path,body,expectedContext);
public Task<PlotDirector.Companion.Protocol.Manuscript.ChapterRepairRequested> RequestChapterRepair(int book,PlotDirector.Companion.Protocol.Manuscript.ChapterFinish selected,Guid context)=>Send<PlotDirector.Companion.Protocol.Manuscript.ChapterRepairRequested>(HttpMethod.Post,$"api/native-companion/books/{book}/chapter-sync/repair",selected,context);
public Task<PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress> FinishChapters(int book,PlotDirector.Companion.Protocol.Manuscript.ChapterFinish completion,Guid context)=>Send<PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress>(HttpMethod.Post,$"api/native-companion/books/{book}/chapter-sync/finish",completion,context);
public Task<PlotDirector.Companion.Protocol.Manuscript.ChapterManifest> ChapterManifest(int book,Guid session,long revision,Guid context)=>Send<PlotDirector.Companion.Protocol.Manuscript.ChapterManifest>(HttpMethod.Get,$"api/native-companion/books/{book}/chapter-sync?session={session}&wordRevision={revision}",null,context);
public Task<PlotDirector.Companion.Protocol.Manuscript.ChapterSyncReply> ValidateChapter(int book,PlotDirector.Companion.Protocol.Manuscript.ChapterObservation proof,Guid context)=>Send<PlotDirector.Companion.Protocol.Manuscript.ChapterSyncReply>(HttpMethod.Post,$"api/native-companion/books/{book}/chapter-sync/validate",proof,context);
public async Task FailCapture(Guid id,Guid context){try{await Send<NativePresence>(HttpMethod.Delete,"api/native-companion/manuscript-capture/"+id,null,context);}catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException or ObjectDisposedException){}}
public async Task<NativePresence> Capture(ManuscriptCapture capture,Guid context){var result=await Send<NativePresence>(HttpMethod.Post,"api/native-companion/manuscript-capture",capture,context);if(result.CaptureRequestId!=capture.RequestId||result.Revision!=capture.Revision)throw new InvalidDataException("Server did not acknowledge this manuscript capture. Update or reconnect before retrying.");return result;}
private static async Task<CaptureUploadException> ReadCaptureFailure(HttpResponseMessage response,CancellationToken cancellation)
@ -155,7 +159,7 @@ public sealed partial class CloudGateway : IDisposable
lock(gate)if(context==authenticationContext){health.Server=(int)response.StatusCode>=500?"degraded":"online";health.VerifiedUtc=Now.UtcDateTime;health.Explanation=failure.Message;}
throw failure;
}
if(!response.IsSuccessStatusCode&&!(response.StatusCode==HttpStatusCode.BadRequest&&path=="api/native-companion/import-preview")){lock(gate)if(context==authenticationContext){health.Server=response.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.NotFound?"online":"degraded";health.VerifiedUtc=Now.UtcDateTime;health.Explanation=$"PlotDirector rejected { (path.EndsWith("/presence",StringComparison.Ordinal)?"document registration":"the request") } (HTTP {(int)response.StatusCode}). Reconnect or check the selected book.";if(response.StatusCode==HttpStatusCode.Forbidden){if(body is NativePresence denied)books=books.Where(b=>b.BookId!=denied.BookId).ToArray();else if(path=="api/native-companion/books")books=[];}}throw new InvalidOperationException(response.StatusCode==HttpStatusCode.Forbidden?"Access denied or subscription unavailable.":response.StatusCode==HttpStatusCode.NotFound?"No saved chapter/scene matches this book and Word marker.":"Server request failed. Check connection or update the server.");}
if(!response.IsSuccessStatusCode&&!(response.StatusCode==HttpStatusCode.BadRequest&&path=="api/native-companion/import-preview")&&!(response.StatusCode==HttpStatusCode.Conflict&&(path.EndsWith("/chapter-sync/validate",StringComparison.Ordinal)||path.EndsWith("/chapter-sync/repair",StringComparison.Ordinal)))){lock(gate)if(context==authenticationContext){health.Server=response.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.NotFound?"online":"degraded";health.VerifiedUtc=Now.UtcDateTime;health.Explanation=$"PlotDirector rejected { (path.EndsWith("/presence",StringComparison.Ordinal)?"document registration":"the request") } (HTTP {(int)response.StatusCode}). Reconnect or check the selected book.";if(response.StatusCode==HttpStatusCode.Forbidden){if(body is NativePresence denied)books=books.Where(b=>b.BookId!=denied.BookId).ToArray();else if(path=="api/native-companion/books")books=[];}}throw new InvalidOperationException(response.StatusCode==HttpStatusCode.Forbidden?"Access denied or subscription unavailable.":response.StatusCode==HttpStatusCode.NotFound?"No saved chapter/scene matches this book and Word marker.":"Server request failed. Check connection or update the server.");}
await using var stream=await response.Content.ReadAsStreamAsync(stop.Token);using var buffer=new MemoryStream();var bytes=new byte[8192];int size;
while((size=await stream.ReadAsync(bytes,stop.Token))>0){if(buffer.Length+size>(path=="api/native-companion/manuscript-capture"?4:1)*1024*1024)throw new InvalidDataException();buffer.Write(bytes,0,size);}buffer.Position=0;
var result=await JsonSerializer.DeserializeAsync<T>(buffer,Json,stop.Token);

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);if(trayAdapter)control?.Attach(instance,lease,(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.CaptureCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.MaintenanceCapability),(hello.Capabilities??"").Split(',').Contains(ProtocolVersion.ParagraphCapability));
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},cancellation);
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);
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)
public void Attach(Guid instance, Guid lease,bool chapters=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);
instances[instance] = new WordInstance(lease){ChapterCapable=chapters};
}
}
public void Detach(Guid instance, Guid lease) { lock (gate) { if (instances.TryGetValue(instance, out var state) && state.Lease == lease) DetachCore(instance); } }
@ -97,9 +97,14 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai
if(message.Kind=="workspace-preview"&&(message.ImportSelection?.SnapshotId!=document.SnapshotId||message.ImportSelection?.ManuscriptId!=document.Descriptor.ManuscriptId)){answer.ImportPreview=new(){RequestId=message.ImportSelection?.RequestId??Guid.Empty,State="rejected",Message="Document snapshot changed. Detect structure and preview again."};return Reject(answer,"stale-preview");}
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"))))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");
switch (message.Kind)
{
case "tray-sync":case "tray-repair":if(!word.ChapterCapable)return Reject(answer,"unsupported-chapter-capability");break;
case "metrics": break;
case "adapter-result":break;
case "active": word.ActiveSession = message.SessionId; break;
@ -174,7 +179,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 Guid Lease = lease; public long LastSequence; public Guid? ActiveSession; public Dictionary<Guid,DocumentState> Documents = []; }
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 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

@ -116,7 +116,7 @@ internal sealed class CompanionWindow:Form
SetText(serverStatus,"PlotDirector · "+CompanionPresentation.Connection(state.Health,DateTime.UtcNow));SetText(account,state.Health?.AccountName??"Not signed in");
SetText(wordStatus,CompanionPresentation.WordStatus(doc!=null,doc?.Book??0,doc?.LastPresenceUtc??DateTime.MinValue,doc?.LastPresenceKey??"",DateTime.UtcNow));
authorise.Visible=CompanionPresentation.NeedsAuthorisation(state.Health);authorise.Enabled=!string.IsNullOrWhiteSpace(state.ServerUrl);
SetText(guidance,doc==null?"Open a manuscript in Microsoft Word. Your words stay in Word until you request an import in PlotDirector.":doc.Book==0?"Choose the PlotDirector book for this manuscript.":"Import, Context and Intent are available in PlotDirector.");
SetText(guidance,doc==null?"Open a manuscript in Microsoft Word. Your words stay in Word until you request an import in PlotDirector.":doc.Book==0?"Choose the PlotDirector book for this manuscript.":doc.ChapterProgress is {} chapters?$"{chapters.State} · {chapters.Matching}/{chapters.Total} chapters accepted. {chapters.Message}":"Import, Context and Intent are available in PlotDirector.");
SetText(bookTitle,book==null?"No book associated":string.IsNullOrEmpty(book.BookTitle)?book.Title:book.BookTitle);SetText(projectTitle,book?.ProjectTitle??"Choose a book to connect your writing workspace.");
var noticeText=error!=""?error:doc?.AssociationNotice??"";SetText(notice,noticeText);if(settingsNotice is {IsDisposed:false}){SetText(settingsNotice,error);settingsNotice.Visible=error!="";}notice.Visible=noticeText!="";tips.SetToolTip(serverStatus,state.Health?.Explanation??"Connect in Settings.");
var text=$"Server: {state.ServerUrl}\r\nAccount: {state.Health?.AccountName}\r\n{state.Health?.Explanation}\r\n"+string.Join("\r\n",displayed.Select(d=>$"{d.Title} · session {d.Session} · book {d.Book}"))+"\r\n"+doc?.WordDiagnostics+"\r\n"+doc?.Status+"\r\n"+doc?.MaintenanceReport;

View File

@ -0,0 +1,128 @@
using System.Text;
using PlotDirector.Companion.Protocol;
using PlotDirector.Companion.Protocol.Manuscript;
namespace PlotDirector.Companion.Agent;
public sealed partial class TrayCoordinator
{
private sealed class ChapterWork
{
public int Book;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 readonly Dictionary<int,(int Start,int End)> Checked=[];
public StringBuilder Text=new(),Xml=new();public int Start,End,DocumentEnd,FirstStart=-1;public bool Finished;public bool Wrapped;public readonly HashSet<int> Reviewed=[];public readonly HashSet<int> Visited=[];public string Next="";
}
private readonly Dictionary<Guid,ChapterWork> chapterWork=[];
private string ChapterIssue(TrayDocument doc){lock(gate)return chapterWork.TryGetValue(doc.Session,out var work)&&work.FailedRevision==doc.Revision?"needs_review":"";}
private bool ChapterCapable(Guid instance){lock(gate)return chapterInstances.Contains(instance);}
private readonly HashSet<Guid> ribbonRequests=[];
private async Task RequestChapterFromRibbon(TrayDocument doc,long revision)
{
int book;Guid context,instance,session;
lock(gate){if(ribbonRequests.Count>=32||!ribbonRequests.Add(doc.Session))return;book=doc.Book;context=doc.Authentication;instance=doc.Instance;session=doc.Session;}
try{if(!cloud.Allows(context,book))throw new InvalidOperationException("Connect and select an authorised book first.");var reply=await cloud.RequestChapterRepair(book,new(){InstanceId=instance,SessionId=session,WordRevision=revision},context);lock(gate)if(documents.GetValueOrDefault(session)==doc&&doc.Revision==revision&&doc.Authentication==context){doc.Status=reply.Message;doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;}}
catch(Exception e)when(NetworkFailure(e)){lock(gate)if(documents.GetValueOrDefault(session)==doc)doc.Status="Chapter request was not accepted: "+e.Message;}
finally{lock(gate)ribbonRequests.Remove(session);}
}
private bool IsChapterCommand(TrayDocument doc,Guid id)=>chapterWork.TryGetValue(doc.Session,out var work)&&id!=Guid.Empty&&work.Command==id;
private void CancelChapterWork(TrayDocument doc){if(chapterWork.TryGetValue(doc.Session,out var work)){work.Command=Guid.Empty;work.Operation=Guid.Empty;work.Text=new();work.Xml=new();doc.ChapterProgress=null;work.Busy=false;work.FailedRevision=doc.Revision;}}
private void BeginChapterRepair(TrayDocument doc,Guid operation)
{
if(!ChapterCapable(doc.Instance))return;
var work=GetChapterWork(doc);work.Operation=operation;work.FailedRevision=-1;work.Manifest=null;work.Checked.Clear();work.Reviewed.Clear();work.Visited.Clear();work.Wrapped=false;work.FirstStart=-1;work.Finished=false;work.Command=Guid.Empty;work.Busy=false;
doc.Status="Repairing existing chapter mappings; accepted scenes and author decisions are retained.";work.Busy=true;work.Started=DateTime.UtcNow;_ = LoadChapterManifest(doc,work);
}
private ChapterWork GetChapterWork(TrayDocument doc)
{
if(!chapterWork.TryGetValue(doc.Session,out var work)||work.Context!=doc.Authentication||work.Revision!=doc.Revision||work.Book!=doc.Book||work.Manuscript!=doc.Manuscript)chapterWork[doc.Session]=work=new(){Book=doc.Book,Manuscript=doc.Manuscript,Revision=doc.Revision,Context=doc.Authentication};return work;
}
private void ObserveChapterPresence(TrayDocument doc,NativePresence reply)
{
if(!ChapterCapable(doc.Instance))return;
lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc)return;var work=GetChapterWork(doc);work.Supported=reply.ChapterSyncSupported;
if(work.Manifest!=null&&reply.ParagraphRevision>0&&work.Manifest.Revision!=reply.ParagraphRevision){work.Manifest=null;work.Checked.Clear();work.Visited.Clear();work.Reviewed.Clear();work.Command=Guid.Empty;work.Finished=false;work.Busy=false;work.Wrapped=false;work.FirstStart=-1;work.FailedRevision=-1;}
if(DateTime.UtcNow<work.RetryAfter||work.Finished||!work.Supported||doc.WordSaved!=true||doc.Book<=0||work.FailedRevision==doc.Revision||doc.Capture!=null)return;
if(work.Busy){if(work.Command!=Guid.Empty&&work.End>work.Start&&doc.Active&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor<p.Value.End)&&(doc.Cursor<work.Start||doc.Cursor>=work.End)){QueueChapter(doc,work,doc.Cursor);return;}if(DateTime.UtcNow-work.Started>TimeSpan.FromMinutes(2)){work.Busy=false;work.FailedRevision=doc.Revision;doc.Status="Chapter validation timed out. Accepted checkpoints are retained; request Repair to resume.";}return;}
if(work.Manifest==null){work.Busy=true;work.Started=DateTime.UtcNow;_ = LoadChapterManifest(doc,work);return;}
var here=work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor<p.Value.End);
if(!here){QueueChapter(doc,work,doc.Cursor);return;}
var next=work.Manifest.Chapters.FirstOrDefault(c=>!work.Checked.ContainsKey(c.ChapterId)&&!work.Reviewed.Contains(c.ChapterId)&&(c.State!="Needs review"||work.Operation!=Guid.Empty));
if(next!=null)QueueChapter(doc,work,next.Start);
}
}
private async Task LoadChapterManifest(TrayDocument doc,ChapterWork work)
{
try{var manifest=await cloud.ChapterManifest(doc.Book,doc.Session,doc.Revision,doc.Authentication);
lock(gate){if(!CurrentChapterWork(doc,work))return;if(manifest.ManuscriptId!=doc.Manuscript)throw new InvalidOperationException("Saved manuscript identity does not match this Word document.");work.Manifest=manifest;work.Busy=false;if(manifest.Mode=="Off"&&work.Operation==Guid.Empty){work.Finished=true;doc.Status="Automatic synchronisation is off. Use Synchronise or Repair for an explicit chapter check.";return;}foreach(var chapter in manifest.Chapters.Where(c=>c.State=="Synchronised"))work.Checked[chapter.ChapterId]=(chapter.Start,chapter.End);doc.Status=$"Chapter index ready: {work.Checked.Count}/{manifest.Chapters.Length} accepted for this Word session.";if(manifest.Chapters.Length>0&&work.Checked.Count==manifest.Chapters.Length){CompleteChapters(doc,work);}else if(manifest.Chapters.Length>0&&!work.Checked.Any(p=>doc.Cursor>=p.Value.Start&&doc.Cursor<p.Value.End))QueueChapter(doc,work,doc.Cursor);else{var next=manifest.Chapters.FirstOrDefault(c=>!work.Checked.ContainsKey(c.ChapterId));if(next!=null)QueueChapter(doc,work,next.Start);}}
}catch(Exception e)when(NetworkFailure(e)){lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;doc.Status="Chapter index unavailable: "+e.Message+" Existing import is retained; no full extraction was started.";}}
}
private bool CurrentChapterWork(TrayDocument doc,ChapterWork work)=>documents.GetValueOrDefault(doc.Session)==doc&&chapterWork.GetValueOrDefault(doc.Session)==work&&doc.Revision==work.Revision&&doc.Authentication==work.Context&&doc.Book==work.Book&&doc.Manuscript==work.Manuscript;
private void QueueChapter(TrayDocument doc,ChapterWork work,int position)
{
if(chapterWork.Values.Count(w=>w!=work&&w.Busy&&w.Command!=Guid.Empty)>=2){
if(!doc.Active)return;
var background=chapterWork.FirstOrDefault(p=>p.Value!=work&&p.Value.Busy&&p.Value.Command!=Guid.Empty&&documents.TryGetValue(p.Key,out var candidate)&&!candidate.Active);
if(background.Value==null||!documents.TryGetValue(background.Key,out var backgroundDoc))return;
Queue(backgroundDoc,new(){Kind="chapter-cancel"});background.Value.Command=Guid.Empty;background.Value.Busy=false;background.Value.Text=new();background.Value.Xml=new();
}
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.Busy=true;work.Processing=false;work.Begun=false;work.Start=work.End=0;work.Started=DateTime.UtcNow;work.Text.Clear();work.Xml.Clear();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)
{
if(!chapterWork.TryGetValue(doc.Session,out var work)||!CurrentChapterWork(doc,work)||work.Command!=message.SnapshotId)return;
if(message.Kind=="adapter-result"&&message.OperationMessage!="ok"){work.Busy=false;work.FailedRevision=doc.Revision;doc.Status=message.OperationMessage;return;}
if(!message.Kind.StartsWith("chapter-",StringComparison.Ordinal))return;
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();return;}
if(message.Kind=="chapter-chunk"){if(!work.Begun||work.Processing)return;
var value=message.Action=="text"?work.Text:work.Xml;var limit=message.Action=="text"?ChapterFingerprint.MaxCharacters: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();work.Text=new();work.Xml=new();_ = ProcessChapter(doc,work,text,xml,work.Command,work.Start,work.End,work.Next,work.Operation);}
}
private void AdvanceChapter(TrayDocument doc,ChapterWork work)
{
if(work.Manifest==null)return;
var next=work.End;
for(int count=0;count<work.Manifest.Chapters.Length+1;count++){
if(work.Wrapped&&next==work.FirstStart){CompleteChapters(doc,work);return;}
var cached=work.Checked.FirstOrDefault(p=>p.Value.Start==next&&p.Value.End>next);
if(cached.Value.End>next){next=cached.Value.End;continue;}
break;
}
if(work.FirstStart==0&&next>=work.DocumentEnd){CompleteChapters(doc,work);return;}
if(next<work.DocumentEnd){QueueChapter(doc,work,next);return;}
if(!work.Wrapped){work.Wrapped=true;QueueChapter(doc,work,0);return;}
CompleteChapters(doc,work);
}
private void CompleteChapters(TrayDocument doc,ChapterWork work)
{
work.Busy=true;work.Finished=true;work.Started=DateTime.UtcNow;_ = CompleteChapterOperation(doc,work);
}
private async Task CompleteChapterOperation(TrayDocument doc,ChapterWork work)
{
try{var result=await cloud.FinishChapters(doc.Book,new(){InstanceId=doc.Instance,SessionId=doc.Session,WordRevision=work.Revision,OperationId=work.Operation,ReviewChapterIds=work.Reviewed.Where(id=>id>0).ToArray(),HasIssues=work.Reviewed.Count>0||work.Manifest!.Chapters.Any(c=>!work.Checked.ContainsKey(c.ChapterId))},work.Context);lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;doc.Status=result.Message;}}
catch(Exception e)when(NetworkFailure(e)){lock(gate)if(CurrentChapterWork(doc,work)){work.Busy=false;work.Finished=false;work.Manifest=null;work.RetryAfter=DateTime.UtcNow.AddSeconds(15);doc.Status="Accepted checkpoints are retained; final chapter status will be retried after reconnect: "+e.Message;}}
}
private async Task ProcessChapter(TrayDocument doc,ChapterWork work,string text,string xml,Guid command,int start,int end,string nextHeading,Guid operation)
{
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));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();
if(candidates.Length==0&&work.Operation!=Guid.Empty)candidates=manifest.Chapters.Where(c=>c.HeadingNativeId==""&&c.ContentHash==hash&&c.ParagraphCount==rows.Length).ToArray();
if(candidates.Length!=1){lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.Busy=false;work.Reviewed.Add(-work.Start-1);doc.Status="An unrecognised or ambiguous chapter needs review; no chapter was guessed by name.";AdvanceChapter(doc,work);}return;}
var chapter=candidates[0];lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;if(!work.Visited.Add(chapter.ChapterId)){work.Busy=false;if(!work.Checked.TryGetValue(chapter.ChapterId,out var earlier)||earlier.Start!=start||earlier.End!=end){work.Reviewed.Add(chapter.ChapterId);work.Checked.Remove(chapter.ChapterId);doc.Status="Duplicate chapter identity at another position; existing canonical structure is retained for review.";}AdvanceChapter(doc,work);return;}}var proof=new ChapterObservation{RequestId=command,OperationId=operation,InstanceId=doc.Instance,SessionId=doc.Session,ManuscriptId=doc.Manuscript,WordRevision=doc.Revision,BaseRevision=manifest.Revision,ChapterId=chapter.ChapterId,Start=start,End=end,NextHeadingId=nextHeading,ContentHash=hash,IdentityHash=ChapterFingerprint.Identity(rows),Paragraphs=rows.Select(p=>new ChapterParagraph{NativeId=p.NativeId,Length=p.Length,Outline=p.Outline}).ToArray()};
var result=await cloud.ValidateChapter(doc.Book,proof,doc.Authentication);
if(!result.Accepted&&result.State=="Changed"&&result.AllowText){proof.Reconcile=true;proof.Paragraphs=rows;result=await cloud.ValidateChapter(doc.Book,proof,doc.Authentication);}
lock(gate){if(!(CurrentChapterWork(doc,work)&&work.Command==command))return;work.Busy=false;
if(result.Accepted){work.Checked[chapter.ChapterId]=(start,end);manifest.Revision=result.Revision;if(result.State=="Needs review")work.Reviewed.Add(chapter.ChapterId);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;doc.Status=$"{work.Checked.Count}/{manifest.Chapters.Length} chapters accepted · "+result.Message;AdvanceChapter(doc,work);}
else{work.Reviewed.Add(chapter.ChapterId);doc.Status=result.Message+" Accepted chapter repairs are retained.";AdvanceChapter(doc,work);}
}
}catch(Exception e)when(NetworkFailure(e)||e is ArgumentException or System.Xml.XmlException){lock(gate)if(CurrentChapterWork(doc,work)&&work.Command==command){work.Busy=false;
if(e is HttpRequestException or OperationCanceledException||cloud.Status().Health?.Authentication!="verified"){work.Manifest=null;work.Command=Guid.Empty;work.Visited.Clear();work.RetryAfter=DateTime.UtcNow.AddSeconds(15);doc.Status="Chapter connection interrupted; accepted checkpoints are retained and validation will resume after reconnect.";}
else if(e is ArgumentException or System.Xml.XmlException&&end>start){work.Reviewed.Add(-start-1);doc.Status="Chapter content needs review: "+e.Message+" Other chapters can continue.";AdvanceChapter(doc,work);}
else{work.FailedRevision=doc.Revision;doc.Status="Chapter needs review: "+e.Message+" Existing import is unchanged.";}}}
}
}

View File

@ -2,18 +2,18 @@ using PlotDirector.Companion.Protocol;
namespace PlotDirector.Companion.Agent;
// One control centre in the existing agent. Exact-session commands only; no COM or UI objects.
public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,ChapterAiWork ai)
public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway cloud,ChapterAiWork ai)
{
private readonly Guid agentInstance=Guid.NewGuid(),agentSession=Guid.NewGuid();private int lastBook;private Guid lastAuthentication;private long agentSequence;private long presenceSequence=DateTime.UtcNow.Ticks;private int uploading;private DateTime lastAgentPresence;private bool agentOnlyPublished;
private bool ParagraphCapable(Guid instance){lock(gate)return paragraphInstances.Contains(instance);}
private readonly ParagraphSnapshotCache paragraphSnapshots=new();
private readonly HashSet<Guid> paragraphInstances=[];
private readonly HashSet<Guid> paragraphInstances=[];private readonly HashSet<Guid> chapterInstances=[];
private readonly object gate=new();private readonly Dictionary<Guid,TrayDocument> documents=[];
private readonly Dictionary<Guid,Queue<AdapterCommand>> commands=[];private readonly Dictionary<Guid,Guid> leases=[];private readonly HashSet<Guid> captureInstances=[];private readonly HashSet<Guid> maintenanceInstances=[];private readonly Dictionary<Guid,(Guid Session,Guid Manuscript,Guid Authentication,string Kind,DateTime Started)> maintenance=[];private readonly Dictionary<(Guid,Guid),(Guid Manuscript,Guid Authentication,int Book,DateTime Expires)> reconnectBindings=[];
public event Action? OpenRequested;
public TrayDocument[] Documents {get{lock(gate)return documents.Values.OrderByDescending(d=>d.Observed).ToArray();}}
public TrayDocument[] PresentationDocuments {get{lock(gate)return documents.Values.OrderByDescending(d=>d.Observed).Select(d=>d.Snapshot()).ToArray();}}
public void Attach(Guid instance,Guid lease,bool capture=false,bool canMaintain=false,bool paragraphs=false){lock(gate){Disconnected(instance);if(paragraphs)paragraphInstances.Add(instance);else paragraphInstances.Remove(instance);leases[instance]=lease;if(canMaintain)maintenanceInstances.Add(instance);else maintenanceInstances.Remove(instance);if(capture)captureInstances.Add(instance);else captureInstances.Remove(instance);}}
public void Attach(Guid instance,Guid lease,bool capture=false,bool canMaintain=false,bool paragraphs=false,bool chapters=false){lock(gate){Disconnected(instance);if(chapters)chapterInstances.Add(instance);else chapterInstances.Remove(instance);if(paragraphs)paragraphInstances.Add(instance);else paragraphInstances.Remove(instance);leases[instance]=lease;if(canMaintain)maintenanceInstances.Add(instance);else maintenanceInstances.Remove(instance);if(capture)captureInstances.Add(instance);else captureInstances.Remove(instance);}}
public Message Exchange(Guid instance,Message request,Message answer,Guid lease=default)
{
lock(gate)
@ -37,8 +37,10 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
doc.Observed=DateTime.UtcNow;
if(request.Kind=="active"){foreach(var d in documents.Values)d.Active=false;doc.Active=true;}
if(request.Kind=="selection"){doc.Cursor=request.Start;doc.WordSaved=request.WordSaved;if(request.WordSaved==true&&doc.AssociationNeedsSave){doc.AssociationNeedsSave=false;doc.AssociationNotice="";}}
ChapterFrame(doc,request,answer);
if(request.Kind is "tray-sync" or "tray-repair")_ = RequestChapterFromRibbon(doc,request.Revision);
CaptureFrame(doc,request,answer);
if(request.Kind=="selection"||request.Kind=="snapshot-end"){doc.ChapterId=answer.ChapterId;doc.SceneId=answer.SceneId;doc.ChapterTitle=answer.ChapterTitle;doc.SceneTitle=answer.SceneTitle;}
if((request.Kind=="selection"||request.Kind=="snapshot-end")&&!ChapterCapable(instance)){doc.ChapterId=answer.ChapterId;doc.SceneId=answer.SceneId;doc.ChapterTitle=answer.ChapterTitle;doc.SceneTitle=answer.SceneTitle;}
if(answer.WordCount.HasValue)doc.Words=answer.WordCount;
if(request.Kind.StartsWith("snapshot-",StringComparison.Ordinal)&&answer.Status is not ("ok" or "analysis-complete" or "awaiting-structure")){Cancel(doc);doc.Status="Local reading failed: "+answer.Status+". Detect chapters again.";}
if(request.Kind=="snapshot-fragment")doc.Progress=answer.Progress;
@ -49,19 +51,22 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
doc.AssociationNeedsSave=request.OperationMessage=="association-written";
doc.AssociationNotice=doc.AssociationNeedsSave?"Book remembered in Word. Save the document to keep this association.":request.OperationMessage=="ok"?"Update the Word add-in to confirm the association was written.":request.OperationMessage;
}
else if(request.Kind=="adapter-result"&&request.OperationMessage!="ok"&&request.OperationMessage!="association-written"){doc.Status=request.OperationMessage;Cancel(doc);}
else if(request.Kind=="adapter-result"&&!IsChapterCommand(doc,request.SnapshotId)&&request.OperationMessage!="ok"&&request.OperationMessage!="association-written"){doc.Status=request.OperationMessage;Cancel(doc);}
if(request.Kind=="ai-cancel"){Cancel(doc);doc.Status="Extraction cancelled or document changed. Successful server suggestions are retained.";}
if(request.Kind=="metrics")doc.WordDiagnostics=request.OperationMessage.Length<=6000?request.OperationMessage:"Diagnostics size exceeded";
if(request.Kind=="ai-fragment")doc.Progress=answer.Progress;
if(request.Kind.StartsWith("ai-",StringComparison.Ordinal)&&answer.Status!="ok"){doc.Status="Chapter could not be read: "+answer.Status;Cancel(doc);}
}
}
if(documents.TryGetValue(request.SessionId,out var activeDocument)&&ChapterCapable(instance)&&request.Kind is "selection" or "metrics"){
answer.ChapterStatusProvided=true;answer.BookId=activeDocument.Book;answer.BookTitle=cloud.Status().Books.FirstOrDefault(b=>b.BookId==activeDocument.Book)?.Title??"";answer.ChapterTitle=activeDocument.ChapterTitle;answer.SceneTitle=activeDocument.SceneTitle;answer.ChapterProgress=activeDocument.ChapterProgress;
}
if(commands.TryGetValue(instance,out var queue)&&queue.Count>0)answer.Command=queue.Dequeue();
return answer;
}
}
public void Disconnected(Guid instance,Guid lease=default){lock(gate){if(lease!=Guid.Empty&&leases.GetValueOrDefault(instance)!=lease)return;leases.Remove(instance);foreach(var expired in reconnectBindings.Where(p=>p.Value.Expires<=DateTime.UtcNow).Select(p=>p.Key).ToArray())reconnectBindings.Remove(expired);foreach(var doc in documents.Values.Where(d=>d.Instance==instance).ToArray()){if(doc.Book>0&&reconnectBindings.Count<256)reconnectBindings[(instance,doc.Session)]=(doc.Manuscript,doc.Authentication,doc.Book,DateTime.UtcNow.AddMinutes(2));Remove(doc.Session);}commands.Remove(instance);}}
private void Remove(Guid session){paragraphSnapshots.Remove(session);foreach(var key in maintenance.Where(p=>p.Value.Session==session).Select(p=>p.Key).ToArray())maintenance.Remove(key);if(documents.Remove(session,out var doc)){Cancel(doc);_ = cloud.RemovePresence(doc.Instance,doc.Session,doc.PresenceSequence);}}
public void Disconnected(Guid instance,Guid lease=default){lock(gate){if(lease!=Guid.Empty&&leases.GetValueOrDefault(instance)!=lease)return;leases.Remove(instance);chapterInstances.Remove(instance);paragraphInstances.Remove(instance);captureInstances.Remove(instance);maintenanceInstances.Remove(instance);foreach(var expired in reconnectBindings.Where(p=>p.Value.Expires<=DateTime.UtcNow).Select(p=>p.Key).ToArray())reconnectBindings.Remove(expired);foreach(var doc in documents.Values.Where(d=>d.Instance==instance).ToArray()){if(doc.Book>0&&reconnectBindings.Count<256)reconnectBindings[(instance,doc.Session)]=(doc.Manuscript,doc.Authentication,doc.Book,DateTime.UtcNow.AddMinutes(2));Remove(doc.Session);}commands.Remove(instance);}}
private void Remove(Guid session){chapterWork.Remove(session);paragraphSnapshots.Remove(session);foreach(var key in maintenance.Where(p=>p.Value.Session==session).Select(p=>p.Key).ToArray())maintenance.Remove(key);if(documents.Remove(session,out var doc)){Cancel(doc);_ = cloud.RemovePresence(doc.Instance,doc.Session,doc.PresenceSequence);}}
private bool Queue(TrayDocument doc,AdapterCommand command){if(!commands.TryGetValue(doc.Instance,out var queue))commands[doc.Instance]=queue=new();if(queue.Count>=16){doc.Status="Word request queue is busy. Retry after current operation.";return false;}command.SessionId=doc.Session;command.Revision=doc.Revision;queue.Enqueue(command);return true;}
public bool CanMaintain(Guid session){lock(gate)return documents.TryGetValue(session,out var d)&&maintenanceInstances.Contains(d.Instance);}
public void Maintain(Guid session,string kind)
@ -97,7 +102,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
if(!Queue(doc,new(){Id=doc.Job,Kind="extract-ai",Chapter=doc.Current,BookId=doc.Book,AuthenticationContext=doc.Authentication})){doc.Job=Guid.Empty;doc.Pending.Clear();}
}
public void Cancel(Guid session){lock(gate)if(documents.TryGetValue(session,out var doc)){Cancel(doc);doc.Status="Cancelled. Successful server suggestions remain available.";}}
private void Cancel(TrayDocument doc){doc.RetryCapture=null;foreach(var request in maintenance.Where(p=>p.Value.Session==doc.Session).Select(p=>p.Key).ToArray()){maintenance.Remove(request);doc.MaintenanceReport="Stopped: superseded by a document or account change. Inspect before retrying cleanup.";}if(doc.Capture!=null)_=cloud.FailCapture(doc.Capture.RequestId,doc.Authentication);doc.Capture=null;doc.CaptureFragments.Clear();if(doc.Job!=Guid.Empty)ai.Clear(doc.Session);doc.Job=Guid.Empty;doc.Pending.Clear();if(commands.TryGetValue(doc.Instance,out var q))commands[doc.Instance]=new(q.Where(c=>c.SessionId!=doc.Session));Queue(doc,new(){Kind="cancel"});}
private void Cancel(TrayDocument doc){CancelChapterWork(doc);doc.RetryCapture=null;foreach(var request in maintenance.Where(p=>p.Value.Session==doc.Session).Select(p=>p.Key).ToArray()){maintenance.Remove(request);doc.MaintenanceReport="Stopped: superseded by a document or account change. Inspect before retrying cleanup.";}if(doc.Capture!=null)_=cloud.FailCapture(doc.Capture.RequestId,doc.Authentication);doc.Capture=null;doc.CaptureFragments.Clear();if(doc.Job!=Guid.Empty)ai.Clear(doc.Session);doc.Job=Guid.Empty;doc.Pending.Clear();if(commands.TryGetValue(doc.Instance,out var q))commands[doc.Instance]=new(q.Where(c=>c.SessionId!=doc.Session));Queue(doc,new(){Kind="cancel"});}
public void Navigate(Guid session,int start){lock(gate)if(documents.TryGetValue(session,out var doc))Queue(doc,new(){Kind="navigate",Chapter=new(){Start=start}});}
public async Task Tick(CancellationToken cancellation)
{
@ -119,13 +124,13 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
public async Task Heartbeat(CancellationToken cancellation)
{
while(!cancellation.IsCancellationRequested){await Task.Delay(TimeSpan.FromMilliseconds(500),cancellation);var available=Documents.Where(d=>d.Authentication==cloud.Status().AuthenticationContext&&cloud.Status().Health?.Authentication=="verified").ToArray();
foreach(var doc in available){if(doc.LastPresenceKey==""&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(2))continue;var key=$"{doc.Capture?.RequestId}:{(doc.Capture!=null?doc.Progress/5:0)}:{doc.WordSaved}:{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}:{(ParagraphCapable(doc.Instance)||!doc.SceneId.HasValue?doc.Cursor:0)}";if(key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(15))continue;try{var reply=await cloud.Presence(doc.Instance,doc.Session,new(){CaptureRequestId=doc.Capture?.RequestId,CaptureProgress=doc.Progress,CanParagraphSync=ParagraphCapable(doc.Instance),CanCapture=captureInstances.Contains(doc.Instance),WordRunning=true,WordSaved=doc.WordSaved,CursorStart=doc.Cursor,ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=doc.PresenceSequence=Interlocked.Increment(ref presenceSequence),ChapterId=doc.ChapterId,SceneId=doc.SceneId,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication);doc.LastPresenceKey=key;doc.LastPresenceUtc=DateTime.UtcNow;
if(reply.ParagraphRevision>0)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext){if(doc.ChapterId!=reply.ChapterId)doc.ChapterTitle="";if(doc.SceneId!=reply.SceneId)doc.SceneTitle="";doc.ChapterId=reply.ChapterId;doc.SceneId=reply.SceneId;}
foreach(var doc in available){if(doc.LastPresenceKey==""&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(2))continue;var key=$"{doc.Capture?.RequestId}:{(doc.Capture!=null?doc.Progress/5:0)}:{doc.WordSaved}:{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}:{(ParagraphCapable(doc.Instance)||!doc.SceneId.HasValue?doc.Cursor:0)}";if(key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(15))continue;try{var reply=await cloud.Presence(doc.Instance,doc.Session,new(){CaptureRequestId=doc.Capture?.RequestId,CaptureProgress=doc.Progress,ChapterIssue=ChapterIssue(doc),CanChapterSync=ChapterCapable(doc.Instance),CanParagraphSync=ParagraphCapable(doc.Instance),CanCapture=captureInstances.Contains(doc.Instance),WordRunning=true,WordSaved=doc.WordSaved,CursorStart=doc.Cursor,ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=doc.PresenceSequence=Interlocked.Increment(ref presenceSequence),ChapterId=doc.ChapterId,SceneId=doc.SceneId,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication);lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc||(ChapterCapable(doc.Instance)&&reply.Revision!=doc.Revision)||doc.Authentication!=cloud.Status().AuthenticationContext)continue;doc.LastPresenceKey=key;doc.LastPresenceUtc=DateTime.UtcNow;doc.ChapterProgress=reply.ChapterProgress;doc.ChapterTitle=reply.ChapterTitle;doc.SceneTitle=reply.SceneTitle;ObserveChapterPresence(doc,reply);}
if(reply.ParagraphRevision>0)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext){doc.ChapterId=reply.ChapterId;doc.SceneId=reply.SceneId;}
if(reply.Navigation is {Kind:"wizard-capture",BookId:>0} requested&&requested.SessionId==doc.Session&&requested.Revision==doc.Revision&&doc.Book==0){await cloud.CheckConnection();lock(gate){if(doc.Book==0&&requested.SessionId==doc.Session&&requested.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext&&cloud.Allows(doc.Authentication,requested.BookId)&&documents.GetValueOrDefault(doc.Session)==doc){doc.Book=requested.BookId;cloud.RememberBinding(doc.Manuscript,doc.Book,doc.Authentication);doc.LastPresenceKey="";}}}
if(reply.Navigation!=null)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Navigation.SessionId==doc.Session&&reply.Navigation.Revision==doc.Revision){if((reply.Navigation.Kind is "wizard-capture" or "paragraph-snapshot")&&captureInstances.Contains(doc.Instance)&&(reply.Navigation.BookId==0||reply.Navigation.BookId==doc.Book)&&cloud.Allows(doc.Authentication,doc.Book)){if(uploading!=0||documents.Values.Any(d=>d.Capture!=null)){_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);continue;}var retained=doc.RetryCapture;var reusable=retained!=null&&doc.RetryAuthentication==doc.Authentication&&doc.RetryBook==doc.Book&&retained.ManuscriptId==doc.Manuscript&&retained.Revision==doc.Revision&&retained.ParagraphTracking==reply.Navigation.ParagraphTracking;
Cancel(doc);doc.Capture=new(){RequestId=reply.Navigation.Id,InstanceId=doc.Instance,SessionId=doc.Session,ManuscriptId=doc.Manuscript,Revision=doc.Revision,ParagraphTracking=reply.Navigation.ParagraphTracking,End=reusable?retained!.End:0};doc.CaptureBaseRevision=reply.Navigation.BaseRevision;doc.CaptureBaseHash=reply.Navigation.BaseSnapshotHash;doc.CaptureFragments.Clear();
if(reusable){doc.CaptureFragments.AddRange(retained!.Paragraphs);doc.Status="Retrying the retained unchanged manuscript at your import request…";CaptureFrame(doc,new(){Kind="snapshot-end",SnapshotId=reply.Navigation.Id},new(){Status="ok"});}
else{doc.Status="Reading manuscript for the PlotDirector import wizard…";Queue(doc,reply.Navigation);}}else if(reply.Navigation.Kind is "wizard-capture" or "paragraph-snapshot")_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);else if(reply.Navigation.Kind=="cancel")Cancel(doc);else if(reply.Navigation.Kind=="navigate")Queue(doc,reply.Navigation);}}catch(Exception e)when(NetworkFailure(e)) {doc.Status=e.Message;doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.UtcNow;}}
else{doc.Status="Reading manuscript for the PlotDirector import wizard…";Queue(doc,reply.Navigation);}}else if(reply.Navigation.Kind is "wizard-capture" or "paragraph-snapshot")_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);else if(reply.Navigation.Kind=="cancel")Cancel(doc);else if(reply.Navigation.Kind=="chapter-repair"){BeginChapterRepair(doc,reply.Navigation.Id);}else if(reply.Navigation.Kind=="navigate")Queue(doc,reply.Navigation);}}catch(Exception e)when(NetworkFailure(e)) {doc.Status=e.Message;doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.UtcNow;}}
if(available.Length==0&&cloud.Status().Health?.Authentication=="verified"&&DateTime.UtcNow-lastAgentPresence>=TimeSpan.FromSeconds(15)){lastAgentPresence=DateTime.UtcNow;agentOnlyPublished=true;try{await cloud.Presence(agentInstance,agentSession,new(){WordRunning=leases.Count>0,BookId=0,Sequence=Interlocked.Increment(ref agentSequence),WordAvailable=false,DocumentTitle="No Word document"},cloud.Status().AuthenticationContext);}catch(Exception e)when(NetworkFailure(e)) {}}
else if(available.Length>0&&agentOnlyPublished){agentOnlyPublished=false;await cloud.RemovePresence(agentInstance,agentSession);}
}
@ -172,6 +177,7 @@ public sealed class TrayCoordinator(SessionManager sessions,CloudGateway cloud,C
}
public sealed class TrayDocument
{
public PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress? ChapterProgress;
public string LastPresenceKey="";public DateTime LastPresenceUtc;public Guid Instance,Session,Manuscript,Authentication,Job;public long Revision,PresenceSequence;public string Title="",AssociationSite="",ChapterTitle="",SceneTitle="",Status="Link this manuscript to a book, then use Import manuscript in PlotDirector.",ReviewPath="";
internal ManuscriptCapture? RetryCapture;internal Guid RetryAuthentication;internal int RetryBook;
public long CaptureBaseRevision;public string CaptureBaseHash="";public ManuscriptCapture? Capture;public List<ParagraphFragment> CaptureFragments=[];public bool? WordSaved;public long? AcceptedRevision;

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 }, 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 }, 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.22</ApplicationVersion></PropertyGroup></Project>
<Project><PropertyGroup><ApplicationVersion>1.0.0.23</ApplicationVersion></PropertyGroup></Project>

View File

@ -101,3 +101,21 @@ public sealed class ChapterSyncReply
{
public bool Accepted{get;set;}public string State{get;set;}="Not yet checked";public string Message{get;set;}="";public int ChapterId{get;set;}public long Revision{get;set;}public bool AllowText{get;set;}
}
[DataContract]
public sealed class ChapterSyncProgress
{
[DataMember] public int Total {get;set;}
[DataMember] public int Checked {get;set;}
[DataMember] public int Matching {get;set;}
[DataMember] public int Repaired {get;set;}
[DataMember] public int NeedsReview {get;set;}
[DataMember] public int? CurrentChapterId {get;set;}
[DataMember] public string State {get;set;}="Not yet checked";
[DataMember] public string Message {get;set;}="";
}
public sealed class ChapterFinish
{
public Guid InstanceId{get;set;}public Guid SessionId{get;set;}public long WordRevision{get;set;}public Guid OperationId{get;set;}public bool HasIssues{get;set;}public int[] ReviewChapterIds{get;set;}=Array.Empty<int>();
}
public sealed class ChapterRepairRequested {public Guid OperationId{get;set;}public string Message{get;set;}="";}

View File

@ -5,6 +5,7 @@ namespace PlotDirector.Companion.Protocol;
public static class ProtocolVersion
{
public const int Current = 1;
public const string ChapterSyncCapability="chapter-sync-v1";
public const string ParagraphCapability="paragraph-snapshots-v1";
public const string MaintenanceCapability="document-maintenance-v1";
public const string CaptureCapability="wizard-capture-v1";
@ -28,6 +29,10 @@ public static class ProtocolVersion
[DataContract]
public sealed class Message
{
[DataMember] public bool ChapterStatusProvided {get;set;}
[DataMember] public PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress? ChapterProgress {get;set;}
[DataMember] public string BookTitle {get;set;}="";
[DataMember] public Guid OperationId {get;set;}
[DataMember] public AdapterCommand? Command {get;set;}
[DataMember] public string OperationMessage {get;set;}="";
[DataMember] public int Version { get; set; } = ProtocolVersion.Current;
@ -38,6 +43,7 @@ public sealed class Message
[DataMember] public long Sequence { get; set; }
[DataMember] public long Revision { get; set; }
[DataMember] public Guid SnapshotId { get; set; }
[DataMember] public int DocumentEnd {get;set;}
[DataMember] public int Start { get; set; }
[DataMember] public int End { get; set; }
[DataMember] public DocumentDescriptor[] Documents { get; set; } = Array.Empty<DocumentDescriptor>();

View File

@ -3,6 +3,7 @@ namespace PlotDirector.Companion.Protocol;
[DataContract]
public sealed class AdapterCommand
{
[DataMember] public Guid OperationId {get;set;}
[DataMember] public bool ParagraphTracking {get;set;}
[DataMember] public long BaseRevision {get;set;}
[DataMember] public string BaseSnapshotHash {get;set;}="";
@ -22,6 +23,10 @@ public sealed class NativePresence
[DataMember] public Guid[]? CanonicalParagraphIds {get;set;}
[DataMember] public long ParagraphRevision {get;set;}
[DataMember] public string ParagraphSnapshotHash {get;set;}="";
[DataMember] public PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress? ChapterProgress {get;set;}
[DataMember] public string ChapterIssue {get;set;}="";
[DataMember] public string ChapterTitle {get;set;}="";
[DataMember] public string SceneTitle {get;set;}="";
[DataMember] public bool CanChapterSync {get;set;}
[DataMember] public bool ChapterSyncSupported {get;set;}
[DataMember] public bool CanParagraphSync {get;set;}

View File

@ -0,0 +1,52 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using PlotDirector.Companion.Agent;
using PlotDirector.Companion.Protocol;
using PlotDirector.Companion.Protocol.Manuscript;
internal static class ChapterAgentTests
{
public static async Task Run()
{
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);
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);
try{
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});}
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");
var before=handler.Validations;for(int n=0;n<100;n++){var response=Send(new(){Kind="selection",Start=12,End=12,WordSaved=true});Check(response.Command?.Kind!="navigate","Passive selection never returns a navigation command");}await Task.Delay(650);Check(handler.Validations==before,"Repeated cursor events reuse accepted current-session chapter validation");
Check(tray.Documents.Single().Status.Contains("accepted"),"Chapter completion is reported only after server acceptance");
var chunkReply=Send(new(){Kind="chapter-chunk",SnapshotId=Guid.NewGuid(),Action="xml",Start=0,OperationMessage="late"});Check(!chunkReply.ChapterStatusProvided,"Chapter chunks do not schedule repeated ribbon updates or invalidate Word during extraction");
Frames(command!);await Task.Delay(100);Check(handler.Validations==before,"Delayed duplicate chapter frames cannot resubmit an accepted operation");
var oldSession=session;session=Guid.NewGuid();Send(new(){Kind="document",Documents=[new(){SessionId=session,ManuscriptId=handler.Manuscript,Revision=1,Title="Second synthetic document.docx"}]});tray.SelectBook(session,3,false);Send(new(){Kind="active"});Send(new(){Kind="selection",Start=0,End=0,WordSaved=true});
AdapterCommand? second=null;for(int n=0;n<200&&second==null;n++){var pending=Send(new(){Kind="selection",Start=0,End=0,WordSaved=true}).Command;if(pending?.Kind=="chapter-check")second=pending;await Task.Delay(20);}
Check(second?.Kind=="chapter-check"&&second.SessionId==session,"A second Word document has independent chapter work and cannot inherit the first session's trust");
Send(new(){Kind="close"});Frames(second!);await Task.Delay(100);Check(handler.Validations==before,"Closing a document rejects late extraction frames and preserves already accepted chapters");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");
}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 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="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."});}
return Json(new{});
}
}
}

View File

@ -3,6 +3,7 @@ using PlotDirector.Companion.Agent;
using PlotDirector.Companion.Client;
using PlotDirector.Companion.Protocol;
if(args.Contains("--chapter-sync")){await ChapterAgentTests.Run();return;}
if(args.Contains("--native-capture-upload")){await NativeCaptureUploadTests.Run();return;}
var passed = 0;
void Check(bool value,string name) {if(!value)throw new Exception(name);passed++;Console.WriteLine("PASS "+name);}

View File

@ -8,11 +8,16 @@ namespace PlotDirector.WordAddIn
[ComVisible(true)]
public sealed class NativeRibbon:Office.IRibbonExtensibility
{
private readonly Func<WordAdapter> adapter;private Office.IRibbonUI ui;private string lastStatus;
private readonly Func<WordAdapter> adapter;private Office.IRibbonUI ui;private string lastStatus,lastSync;
public NativeRibbon(Func<WordAdapter> adapter){this.adapter=adapter;}
public string GetCustomUI(string ribbonID){using(var reader=new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("PlotDirector.WordAddIn.Ribbon.xml")))return reader.ReadToEnd();}
public void OnLoad(Office.IRibbonUI ribbonUI){ui=ribbonUI;lastStatus=GetStatus(null);}
public void Invalidate(){try{var status=GetStatus(null);if(status==lastStatus)return;lastStatus=status;ui?.InvalidateControl("PlotDirectorStatus");}catch(COMException){}}
public void OnLoad(Office.IRibbonUI ribbonUI){ui=ribbonUI;lastStatus=GetStatus(null);lastSync=GetSyncStatus(null)+GetSyncTip(null);}
public void Invalidate(){try{var status=GetStatus(null);if(status!=lastStatus){lastStatus=status;ui?.InvalidateControl("PlotDirectorStatus");}var sync=GetSyncStatus(null)+GetSyncTip(null);if(sync!=lastSync){lastSync=sync;ui?.InvalidateControl("PlotDirectorSyncStatus");}}catch(COMException){}}
public string GetSyncStatus(Office.IRibbonControl control)=>adapter()?.ChapterStatusLabel??"Chapter index unavailable";
public string GetSyncTip(Office.IRibbonControl control)=>adapter()?.ChapterStatusTip??"Open Companion to connect this manuscript.";
public void Synchronise(Office.IRibbonControl control)=>adapter()?.RequestChapterSynchronisation(false);
public void Repair(Office.IRibbonControl control)=>adapter()?.RequestChapterSynchronisation(true);
public void Troubleshooting(Office.IRibbonControl control)=>adapter()?.ShowTroubleshooting();
public string GetStatus(Office.IRibbonControl control)=>"Local Companion: "+(adapter()?.ConnectionState??"unavailable");
public void RemoveLegacyMarkers(Office.IRibbonControl control)=>adapter()?.RemoveLegacyMarkers();
public void OpenCompanion(Office.IRibbonControl control)=>adapter()?.OpenCompanion();

View File

@ -23,7 +23,7 @@
<ProjectReference Include="..\Protocol\PlotDirector.Companion.Protocol.csproj"><Name>PlotDirector.Companion.Protocol</Name></ProjectReference>
<ProjectReference Include="..\Client\PlotDirector.Companion.Client.csproj"><Name>PlotDirector.Companion.Client</Name></ProjectReference>
<Compile Include="ThisAddIn.cs" /><Compile Include="ThisAddIn.Designer.cs"><DependentUpon>ThisAddIn.cs</DependentUpon></Compile>
<Compile Include="WordAdapter.cs" /><Compile Include="NativeRibbon.cs" /><Compile Include="AgentProcess.cs" /><Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="WordAdapter.cs" /><Compile Include="WordChapterRead.cs" /><Compile Include="NativeRibbon.cs" /><Compile Include="AgentProcess.cs" /><Compile Include="Properties\AssemblyInfo.cs" />
<None Include="ThisAddIn.Designer.xml"><DependentUpon>ThisAddIn.cs</DependentUpon></None>
<EmbeddedResource Include="Ribbon.xml" />
</ItemGroup>

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.22")]
[assembly: AssemblyFileVersion("1.0.0.22")]
[assembly: AssemblyVersion("1.0.0.23")]
[assembly: AssemblyFileVersion("1.0.0.23")]
[assembly: ComVisible(false)]

View File

@ -1,6 +1,12 @@
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="OnLoad">
<ribbon><tabs><tab id="PlotDirectorTab" label="PlotDirector"><group id="PlotDirectorConnection" label="Companion">
<labelControl id="PlotDirectorStatus" getLabel="GetStatus" />
<labelControl id="PlotDirectorSyncStatus" getLabel="GetSyncStatus" getSupertip="GetSyncTip" />
<menu id="PlotDirectorManuscript" label="Manuscript">
<button id="PlotDirectorSynchronise" label="Synchronise now" onAction="Synchronise" supertip="Check current chapter mappings using the separate Companion agent." />
<button id="PlotDirectorRepair" label="Repair synchronisation" onAction="Repair" supertip="Validate or repair the existing import. Existing chapters, scenes and author decisions are preserved." />
<button id="PlotDirectorTroubleshooting" label="Troubleshooting" onAction="Troubleshooting" />
</menu>
<button id="PlotDirectorOpen" label="Open Companion" imageMso="FileOpen" onAction="OpenCompanion" supertip="Open the Windows tray Companion. The indicator reports local communication only." />
<button id="PlotDirectorRemoveLegacyMarkers" label="Remove Legacy Markers" onAction="RemoveLegacyMarkers" supertip="Remove old PlotDirector chapter and scene anchors from this document while keeping the manuscript and its identity." />
</group></tab></tabs></ribbon>

View File

@ -14,7 +14,7 @@ namespace PlotDirector.WordAddIn
{
// This object and every retained RCW are owned exclusively by Word's UI thread.
// AgentLink sees only fresh value DTOs. It never receives this object as a callback.
public sealed class WordAdapter : IDisposable
public sealed partial class WordAdapter : IDisposable
{
private readonly int ownerThread = Environment.CurrentManagedThreadId;
private readonly Word.Application application;
@ -87,6 +87,7 @@ namespace PlotDirector.WordAddIn
});
link.Received += message => {
if(message.Status=="ready")PostToUi(()=>traySupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.TrayCapability));
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;});
if(message.Status!="ok"&&message.Status!="ready")lastResult=message.Status;
@ -182,9 +183,9 @@ namespace PlotDirector.WordAddIn
try
{
selection = Com(() => application.Selection);
if(selection==null){active=null;return;}
if(selection==null){ChangeActiveDocument(null);return;}
var document = Com(() => selection.Document);
if(document==null){active=null;return;}
if(document==null){ChangeActiveDocument(null);return;}
if (!documents.TryGetValue(document,out var state)) { Open(document); return; }
range = Com(() => selection.Range);
if(range==null)return;
@ -201,7 +202,7 @@ namespace PlotDirector.WordAddIn
state.WasSaved = saved;
if(active!=state||activationPending){link.TryPost(new Message {Kind="active",SessionId=state.Session,Revision=state.Revision});activationPending=false;}
active = state;
ChangeActiveDocument(state);
link.TryPost(new Message {Kind="selection",SessionId=state.Session,Revision=state.Revision,Start=start,End=end,WordSaved=saved&&Com(()=>application.BackgroundSavingStatus)==0,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth});
// Prose is read only on an explicit Companion request; cursor observations never rescan it.
@ -232,6 +233,8 @@ namespace PlotDirector.WordAddIn
if(!documents.ContainsKey(doc.Document)||doc.Revision!=command.Revision){Reply(command,"Document changed; request again.");return;}
try{
if(doc.Maintenance!=null){var previous=doc.Maintenance;scheduler.Cancel("maintenance:"+doc.Session);Reply(previous,"Stopped: superseded by a new document request. Inspect before retrying cleanup.");}
if(command.Kind=="chapter-cancel"){CancelChapterRead(doc);Reply(command,"ok");return;}
if(command.Kind=="chapter-check"){StartChapterRead(doc,command);return;}
if(command.Kind.StartsWith("maintenance-",StringComparison.Ordinal)){StartMaintenance(doc,command);return;}
else if((command.Kind=="wizard-capture"||command.Kind=="paragraph-snapshot")){
CancelExtraction(doc);
@ -248,7 +251,7 @@ namespace PlotDirector.WordAddIn
doc.Extraction=new Extraction{Snapshot=command.Id,Revision=doc.Revision,Position=chapter.Start,Limit=chapter.End,IsAi=true};
if(!scheduler.Post("extract:"+doc.Session,()=>ExtractBatch(doc))){CancelExtraction(doc);throw new InvalidOperationException("Word queue is busy.");}
}
else if(command.Kind=="cancel"){CancelExtraction(doc);doc.AiJob=Guid.Empty;}
else if(command.Kind=="cancel"){CancelChapterRead(doc);CancelExtraction(doc);doc.AiJob=Guid.Empty;}
else if(command.Kind=="navigate"&&command.Chapter!=null){
if(completedNavigationIds.Contains(command.Id)){Reply(command,"ok");return;}
var position=command.Chapter.Start;if(position<0||position>DocumentEnd(doc.Document))throw new InvalidOperationException("Position no longer exists.");
@ -520,6 +523,7 @@ namespace PlotDirector.WordAddIn
}
private void CancelExtraction(LocalDocument doc)
{
CancelChapterRead(doc);
scheduler.Cancel("extract:"+doc.Session);
if(doc.Extraction!=null&&!link.TryPost(new Message{Kind=doc.Extraction.IsAi?"ai-cancel":"snapshot-cancel",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.Extraction.Snapshot})&&doc.Extraction.IsAi)link.Reset();
doc.Extraction=null;
@ -559,7 +563,7 @@ namespace PlotDirector.WordAddIn
foreach(var doc in closing.ToArray())
{
if(!present.Contains(doc)&&documents.TryGetValue(doc,out var state))
{CancelExtraction(state);documents.Remove(doc);link.Retire(state.Session);if(active==state)active=null;}
{CancelExtraction(state);documents.Remove(doc);link.Retire(state.Session);if(active==state)ChangeActiveDocument(null);}
closing.Remove(doc);
}
}

View File

@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Word=Microsoft.Office.Interop.Word;
using PlotDirector.Companion.Protocol;
using PlotDirector.Companion.Protocol.Manuscript;
namespace PlotDirector.WordAddIn
{
public sealed partial class WordAdapter
{
private string serverBook="",serverChapter="",serverScene="";private ChapterSyncProgress serverChapterProgress;
public string ChapterStatusLabel=>active==null?"No active manuscript":serverChapterProgress==null?"Chapters not yet checked":$"Chapters {serverChapterProgress.Matching}/{serverChapterProgress.Total} · {serverChapterProgress.State}";
public string ChapterStatusTip=>string.Join("\n",new[]{serverBook,serverChapter,serverScene,serverChapterProgress==null?"Connect and validate the current chapter.":serverChapterProgress.Message});
public void RequestChapterSynchronisation(bool repair)
{if(active==null||ConnectionState!="connected"){lastResult="Open a manuscript and connect Companion first.";return;}if(!link.TryPost(new Message{Kind=repair?"tray-repair":"tray-sync",SessionId=active.Session,Revision=active.Revision}))lastResult="Local queue is busy. Word remains usable; retry shortly.";}
public void ShowTroubleshooting()=>System.Windows.Forms.MessageBox.Show(Diagnostics,"PlotDirector Troubleshooting");
private void ReceiveChapterStatus(Message message)
{if(active==null||active.Session!=message.SessionId||active.Revision!=message.Revision)return;var before=ChapterStatusLabel+ChapterStatusTip;serverBook=message.BookTitle;serverChapter=message.ChapterTitle;serverScene=message.SceneTitle;serverChapterProgress=message.ChapterProgress;if(before!=ChapterStatusLabel+ChapterStatusTip)invalidateRibbon();}
private void ChangeActiveDocument(LocalDocument document)
{if(active==document)return;active=document;serverBook=serverChapter=serverScene="";serverChapterProgress=null;invalidateRibbon();}
private sealed class ChapterRead
{
public AdapterCommand Command;public int Phase,Seek,Steps,Start,End,Offset;public string Text="",Xml="",NextId="";public bool Begun;
}
private readonly Dictionary<Guid,ChapterRead> chapterReads=new Dictionary<Guid,ChapterRead>();
private void CancelChapterRead(LocalDocument doc){chapterReads.Remove(doc.Session);scheduler.Cancel("chapter:"+doc.Session);}
private void StartChapterRead(LocalDocument doc,AdapterCommand command)
{
if(doc.Extraction!=null||doc.Maintenance!=null)throw new InvalidOperationException("Word already has an explicit read or maintenance request. Retry chapter validation afterwards.");
if(chapterReads.Count>=2&&!chapterReads.ContainsKey(doc.Session))throw new InvalidOperationException("Two document chapter reads are already pending. Activate this manuscript and retry.");
CancelChapterRead(doc);chapterReads[doc.Session]=new ChapterRead{Command=command,Seek=Math.Max(0,Math.Min(command.Chapter==null?0:command.Chapter.Start,doc.End-1))};
if(!scheduler.Post("chapter:"+doc.Session,()=>ReadChapterStep(doc))){CancelChapterRead(doc);throw new InvalidOperationException("Word queue is busy; accepted checkpoints are preserved. Retry shortly.");}
}
private void ReadChapterStep(LocalDocument doc)
{
ChapterRead read;if(!chapterReads.TryGetValue(doc.Session,out read))return;
if(!documents.ContainsKey(doc.Document)||doc.Revision!=read.Command.Revision||closing.Contains(doc.Document)||ConnectionState!="connected"){CancelChapterRead(doc);return;}
var watch=Stopwatch.StartNew();Word.Range point=null,heading=null,range=null;Word.Paragraphs paragraphs=null;Word.Paragraph paragraph=null;
try
{
if(read.Phase<4&&(!Com(()=>doc.Document.Saved)||Com(()=>application.BackgroundSavingStatus)!=0))throw new InvalidOperationException("Save Word and wait for background saving before validating chapters.");
if(read.Phase==0){
if(++read.Steps>128)throw new InvalidOperationException("No bounded Heading 1 boundary could be verified. Use manuscript repair; existing mappings are preserved.");
point=Com(()=>doc.Document.Range(read.Seek,read.Seek));paragraphs=Com(()=>point.Paragraphs);paragraph=Com(()=>paragraphs[1]);range=Com(()=>paragraph.Range);
var start=Com(()=>range.Start);var outline=(int)Com(()=>paragraph.OutlineLevel);
if(outline==1){read.Start=start;read.Seek=start+1;read.Phase=1;}
else{heading=Com(()=>point.GoTo(What:Word.WdGoToItem.wdGoToHeading,Which:Word.WdGoToDirection.wdGoToPrevious));var previous=Com(()=>heading.Start);if(previous>=read.Seek||previous==0&&start==0){read.Start=-1;read.Seek=0;read.Phase=1;}else read.Seek=previous;}
}else if(read.Phase==1){
if(++read.Steps>256)throw new InvalidOperationException("Chapter boundary search exceeded its bound; review the document structure.");
point=Com(()=>doc.Document.Range(read.Seek,read.Seek));heading=Com(()=>point.GoTo(What:Word.WdGoToItem.wdGoToHeading,Which:Word.WdGoToDirection.wdGoToNext));var next=Com(()=>heading.Start);
if(next<=read.Seek||next>=doc.End){if(read.Start<0)throw new InvalidOperationException("No Heading 1 chapter is available at this Word location.");read.End=DocumentEnd(doc.Document);read.Phase=2;}
else{paragraphs=Com(()=>heading.Paragraphs);paragraph=Com(()=>paragraphs[1]);var level=(int)Com(()=>paragraph.OutlineLevel);
if(level==1){if(read.Start<0){read.Start=next;read.Seek=next+1;}else{read.End=next;read.Seek=next;read.Phase=6;}}
else read.Seek=next+1;
}
}else if(read.Phase==6){
range=Com(()=>doc.Document.Range(read.Seek,Math.Min(read.Seek+1,doc.End)));read.NextId=WordParagraphIdentity.Read(Com(()=>range.WordOpenXML,"chapter-next-heading-identity"));read.Phase=2;
}else if(read.Phase==2){
if(read.End<=read.Start||read.End-read.Start>ChapterFingerprint.MaxCharacters)throw new InvalidOperationException("This chapter exceeds the bounded fast reader. Use bounded manuscript synchronisation; no mapping was guessed.");
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;}
range=Com(()=>doc.Document.Range(read.Start,read.End));read.Text=Com(()=>range.Text,"chapter-range-text")??"";
if(read.Text.Length!=read.End-read.Start)throw new InvalidOperationException("Word range length contains unsupported structural content; positions were not guessed.");read.Phase=3;
}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.");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.Xml;
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":"xml",Start=read.Offset,OperationMessage=source.Substring(read.Offset,count)}))return;read.Offset+=count;}
else if(read.Phase==4){read.Phase=5;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;}
}
}
}
catch(Exception error)when(error is System.Runtime.InteropServices.COMException||error is InvalidOperationException||error is ArgumentException||error is NullReferenceException){CancelChapterRead(doc);Reply(read.Command,"Chapter validation stopped: "+error.Message);lastResult="Chapter validation stopped; existing accepted mappings are preserved.";}
finally{Release(range);Release(paragraph);Release(paragraphs);Release(heading);Release(point);Metric("chapter-ui-step",watch.Elapsed.TotalMilliseconds);if(chapterReads.ContainsKey(doc.Session)&&!scheduler.Post("chapter:"+doc.Session,()=>ReadChapterStep(doc))){CancelChapterRead(doc);Reply(read.Command,"Chapter validation stopped: Word queue is busy. Accepted checkpoints are preserved.");}}
}
}
}

View File

@ -25,7 +25,7 @@ try{
foreach($piece in $text.Split([char]13)){if($offset -ge $text.Length){break};$length=$piece.Length+1;if($offset+$length -gt $text.Length){throw 'Selection must end on a complete Word paragraph.'};$rows.Add($text.Substring($offset,$length));$offset+=$length}
$watch.Restart();$hash=[PlotDirector.Companion.Protocol.Manuscript.ChapterFingerprint]::Content($rows);$watch.Stop();$times.sha256Milliseconds=$watch.Elapsed.TotalMilliseconds
$watch.Restart();$xml=[string]$range.WordOpenXML;$watch.Stop();$times.chapterWordOpenXmlMilliseconds=$watch.Elapsed.TotalMilliseconds
$watch.Restart();$parsed=[PlotDirector.Companion.Protocol.Manuscript.ChapterFingerprint]::ReadXml($xml,$text);$watch.Stop();$times.portableXmlIdentityParseMilliseconds=$watch.Elapsed.TotalMilliseconds
$parseError=$null;$parsed=@();$watch.Restart();try{$parsed=[PlotDirector.Companion.Protocol.Manuscript.ChapterFingerprint]::ReadXml($xml,$text)}catch{$parseError=$_.Exception.Message};$watch.Stop();$times.portableXmlIdentityParseMilliseconds=$watch.Elapsed.TotalMilliseconds
$nativeCount=0
if($IncludeLegacyParagraphXml){
# Explicit expensive baseline, capped and cancellable with Ctrl+C; never part of unattended qualification.
@ -38,7 +38,7 @@ try{
$watch.Stop();$times.legacyParagraphXmlMilliseconds=$watch.Elapsed.TotalMilliseconds
}
# Cross-process COM call wall times include RPC/marshalling. Use in-add-in metrics for exact UI operation timings.
$report=[ordered]@{utc=[DateTime]::UtcNow.ToString('o');wordVersion=[string]$word.Version;characters=$text.Length;paragraphs=$count;nativeIds=$parsed.Length;legacyMeasuredParagraphs=$(if($IncludeLegacyParagraphXml){[Math]::Min($count,$MaximumParagraphs)}else{0});legacyNativeIds=$nativeCount;algorithm=[PlotDirector.Companion.Protocol.Manuscript.ChapterFingerprint]::Version;hash=$hash;timings=$times;measurementScope='Human-selected chapter, running Word, cross-process STA COM wall time. No UI responsiveness claim.'}
$report=[ordered]@{utc=[DateTime]::UtcNow.ToString('o');wordVersion=[string]$word.Version;characters=$text.Length;paragraphs=$count;nativeIds=$parsed.Length;parseError=$parseError;legacyMeasuredParagraphs=$(if($IncludeLegacyParagraphXml){[Math]::Min($count,$MaximumParagraphs)}else{0});legacyNativeIds=$nativeCount;algorithm=[PlotDirector.Companion.Protocol.Manuscript.ChapterFingerprint]::Version;hash=$hash;timings=$times;measurementScope='Human-selected chapter, running Word, cross-process STA COM wall time. No UI responsiveness claim.'}
$report|ConvertTo-Json -Depth 5|Set-Content -LiteralPath $OutputFile -Encoding UTF8
Write-Output "Recorded chapter benchmark: $OutputFile. No document was changed, saved or closed."
}finally{

View File

@ -1,7 +1,7 @@
{
"version": "1.0.0.22",
"msiVersion": "1.0.22",
"productCode": "{79A10C5C-D417-4F93-A854-C6E114B4532D}",
"version": "1.0.0.23",
"msiVersion": "1.0.23",
"productCode": "{CAE67DDC-8303-4D11-BE3E-2C70333EBF68}",
"upgradeCode": "{641A087B-9779-458C-B290-BCBBAD49319A}",
"atlasBaseline": "c6cdfbc3b17107a8d269561c319d946c8e337835",
"baselineProductCode": "{98F46939-764D-407F-BD1F-1D88315D010A}",

View File

@ -0,0 +1,33 @@
// Opt-in real Development protocol and recovery test. Synthetic account/scope only; no Word automation.
const {chromium}=require('playwright'),fs=require('fs'),crypto=require('crypto'),assert=require('assert/strict');
const identityPath=process.argv[2],scopePath=process.argv[3];
(async()=>{assert.ok(identityPath?.startsWith('/tmp/pd-dev-browser-')&&scopePath?.startsWith('/tmp/pd-context-'));assert.equal(fs.statSync(identityPath).mode&0o077,0);const identity=JSON.parse(fs.readFileSync(identityPath)),scope=JSON.parse(fs.readFileSync(scopePath)),evidence=JSON.parse(fs.readFileSync(scopePath+'.evidence.json'));assert.equal(identity.Database,'PlotDirector_Development');assert.match(identity.Email,/^pwa-browser-[a-f0-9]+@example.invalid$/);assert.equal(identity.UserID,scope.User);assert.equal(evidence.Book,scope.Book);
const base='https://dev.plotdirector.com',browser=await chromium.launch();try{const page=await browser.newPage();await page.goto(base+'/Account/Login');await page.locator('[name=Email]').fill(identity.Email);await page.locator('[name=Password]').fill(identity.Password);await Promise.all([page.waitForURL(u=>u.pathname!='/Account/Login'),page.locator('form:has(input[name=Password]) button[type=submit]').click()]);
const verifier=crypto.randomBytes(32).toString('base64url'),challenge=crypto.createHash('sha256').update(verifier).digest('hex').toUpperCase();let r=await page.request.post(base+'/api/native-companion/pair',{data:{challenge}});assert.equal(r.status(),200);const {code}=await r.json();await page.goto(base+'/native-companion/authorize?code='+code);const csrf=await page.locator('[name=__RequestVerificationToken]').inputValue();r=await page.request.post(base+'/native-companion/authorize',{form:{code,__RequestVerificationToken:csrf}});assert.equal(r.status(),200);r=await page.request.post(base+'/api/native-companion/token',{data:{code,verifier}});assert.equal(r.status(),200);const {accessToken}=await r.json(),headers={Authorization:'Bearer '+accessToken};
const session=crypto.randomUUID(),instance=crypto.randomUUID(),endpoint=base+'/api/native-companion/books/'+scope.Book+'/chapter-sync',presence=base+`/api/native-companion/instances/${instance}/documents/${session}/presence`;let sequence=0,wordRevision=0;
async function observe(cursor){const res=await page.request.post(presence,{headers,data:{bookId:scope.Book,manuscriptId:scope.Manuscript,revision:wordRevision,sequence:++sequence,documentTitle:'Synthetic chapter qualification.docx',wordAvailable:true,wordRunning:true,wordSaved:true,active:true,canCapture:true,canParagraphSync:true,canChapterSync:true,cursorStart:cursor}});assert.equal(res.status(),200);return res.json();}
async function manifest(){const res=await page.request.get(endpoint+`?session=${session}&wordRevision=${wordRevision}`,{headers});assert.equal(res.status(),200,await res.text());return res.json();}
async function validate(proof,status=200){const res=await page.request.post(endpoint+'/validate',{headers,data:proof});assert.equal(res.status(),status,await res.text());return res.json();}
let reply=await observe(1000);assert.equal(reply.navigation,null,'automatic reopening must not request a full extraction or navigation');assert.equal(reply.sceneId,null);let current=await manifest();assert.equal(current.chapters.length,2);assert.equal(current.chapters.filter(c=>c.state==='Synchronised').length,0);
const proofs=evidence.Proofs.map(p=>({...p,InstanceId:instance,SessionId:session,WordRevision:wordRevision,OperationId:'00000000-0000-0000-0000-000000000000',RequestId:crypto.randomUUID(),Reconcile:false}));
for(const proof of proofs){const accepted=await validate(proof);assert.equal(accepted.accepted,true);await validate(proof);const cursor=proof.Start+proof.Paragraphs[0].Length;reply=await observe(cursor);assert.equal(reply.chapterId,proof.ChapterId);assert.equal(reply.sceneId,scope.Scenes[proofs.indexOf(proof)]);assert.equal(reply.navigation,null);}
r=await page.request.post(endpoint+'/finish',{headers,data:{instanceId:instance,sessionId:session,wordRevision}});assert.equal(r.status(),200);assert.equal((await r.json()).state,'Synchronised');console.log('PASS deployed authenticated cross-session chapter adoption, current positions across chapters, idempotent retry, no automatic full capture/navigation and server-confirmed progress');
// Same live revision cannot acquire contradictory ranges.
await validate({...proofs[0],RequestId:crypto.randomUUID(),Start:proofs[0].Start+1,End:proofs[0].End+1},409);
await validate({...proofs[0],RequestId:crypto.randomUUID(),BaseRevision:0},409);
wordRevision=1;await observe(1000);let changed={...proofs[0],RequestId:crypto.randomUUID(),WordRevision:wordRevision};
const rows=evidence.Paragraphs.filter(p=>p.ChapterId===changed.ChapterId).map(p=>({NativeId:p.Occurrence.NativeId,Text:p.Occurrence.Text,Length:p.Occurrence.Text.length,Outline:p.Occurrence.Outline}));rows[1].Text='Edited exact synthetic paragraph.\r';rows[1].Length=rows[1].Text.length;
const i32=n=>{const b=Buffer.alloc(4);b.writeInt32LE(n);return b;},text=s=>Buffer.concat([i32(s.length),Buffer.from(s,'utf16le')]),version='sha256-utf16le-paragraphs-v1';
changed.ContentHash=crypto.createHash('sha256').update(Buffer.concat([text(version),i32(rows.length),...rows.map(p=>text(p.Text))])).digest('hex').toUpperCase();changed.IdentityHash=crypto.createHash('sha256').update(Buffer.concat([text(version+'/identity'),i32(rows.length),...rows.flatMap(p=>[text(p.NativeId),i32(p.Length),i32(p.Outline)])])).digest('hex').toUpperCase();changed.End=changed.Start+rows.reduce((n,p)=>n+p.Length,0);changed.Paragraphs=rows.map(({Text,...p})=>p);
let refused=await validate(changed);assert.equal(refused.state,'Changed');assert.equal(refused.allowText,false,'manual mode must not upload changed prose automatically');
r=await page.request.post(endpoint+'/repair',{headers,data:{instanceId:instance,sessionId:session,wordRevision}});assert.equal(r.status(),200,await r.text());changed.OperationId=(await r.json()).operationId;reply=await observe(1000);assert.equal(reply.navigation.kind,'chapter-repair');assert.equal(reply.navigation.id,changed.OperationId);assert.equal((await observe(1000)).navigation,null,'repair command is consumed once');
assert.equal((await validate(changed)).allowText,true);changed.Paragraphs=rows;changed.Reconcile=true;const reconciled=await validate(changed);assert.equal(reconciled.accepted,true);assert.equal(reconciled.revision,evidence.Revision+1);
const second={...proofs[1],RequestId:crypto.randomUUID(),WordRevision:wordRevision,BaseRevision:reconciled.revision,Start:proofs[1].Start+(changed.End-proofs[0].End),End:proofs[1].End+(changed.End-proofs[0].End)};assert.equal((await validate(second)).accepted,true);reply=await observe(second.Start+second.Paragraphs[0].Length);assert.equal(reply.sceneId,scope.Scenes[1]);assert.equal(reply.navigation,null);await validate({...changed,BaseRevision:evidence.Revision,RequestId:crypto.randomUUID()},409);
r=await page.request.post(endpoint+'/finish',{headers,data:{instanceId:instance,sessionId:session,wordRevision,operationId:changed.OperationId}});assert.equal(r.status(),200);const progress=await r.json();assert.equal(progress.state,'Synchronised');assert.equal(progress.repaired,1);
console.log('PASS manual-mode upload refusal, explicit existing repair command, changed-chapter-only reconciliation, stale CAS rejection and shifted later-chapter cursor mapping');
// Download and restore through the established author-facing recovery workflow.
await page.goto(base+'/BookRecovery/Backup?projectId='+scope.Project);let token=await page.locator('form[action="/BookRecovery/ReviewBackup"] input[name=__RequestVerificationToken]').inputValue();r=await page.request.post(base+'/BookRecovery/Download',{form:{projectId:String(scope.Project),books:String(scope.Book),__RequestVerificationToken:token}});assert.equal(r.status(),200);assert.match(r.headers()['content-disposition'],/\.plotdirector/);const buffer=await r.body(),backup=JSON.parse(buffer);const source=backup.Snapshot.Recovery.ParagraphManuscripts[0];assert.equal(source.ChapterCheckpoints.length,2);assert.equal(source.Paragraphs[1].Occurrence.Text,rows[1].Text);assert.deepEqual(source.Paragraphs.map(p=>p.Occurrence.Id),evidence.Paragraphs.map(p=>p.Occurrence.Id));
await page.goto(base+'/BookRecovery/Restore');await page.locator('input[type=file]').setInputFiles({name:'chapter-checkpoint.plotdirector',mimeType:'application/json',buffer});await page.getByRole('button',{name:'Validate backup',exact:true}).click();await page.locator('[name=name]').fill('Chapter sync restored synthetic fixture');await page.getByRole('button',{name:'Preview restore',exact:true}).click();await page.locator('#confirm').check();await page.getByRole('button',{name:'Restore books',exact:true}).click();assert.match(await page.locator('main').innerText(),/restor/i);assert.ok(!(await page.locator('main').innerText()).includes('could not be confirmed'));const link=page.locator('a[href*="/Projects/Details/"]').first();const restoredProject=Number((await link.getAttribute('href')).match(/\d+$/)[0]);assert.ok(restoredProject&&restoredProject!==scope.Project);
await page.goto(base+'/BookRecovery/Backup?projectId='+restoredProject);token=await page.locator('form[action="/BookRecovery/ReviewBackup"] input[name=__RequestVerificationToken]').inputValue();const restoredBook=Number(await page.locator('[name=books]').first().inputValue());r=await page.request.post(base+'/BookRecovery/Download',{form:{projectId:String(restoredProject),books:String(restoredBook),__RequestVerificationToken:token}});assert.equal(r.status(),200);const restored=(await r.json()).Snapshot.Recovery.ParagraphManuscripts[0];assert.deepEqual(restored.Paragraphs.map(p=>[p.Occurrence.Id,p.Occurrence.NativeId,p.Occurrence.Text,p.SceneId]),source.Paragraphs.map(p=>[p.Occurrence.Id,p.Occurrence.NativeId,p.Occurrence.Text,p.SceneId]));assert.deepEqual(restored.ChapterCheckpoints.map(p=>p.ContentHash),source.ChapterCheckpoints.map(p=>p.ContentHash));assert.ok(restored.ChapterCheckpoints.every(p=>p.Status==='Not yet checked'));assert.equal(restored.SessionId,'00000000-0000-0000-0000-000000000000');console.log('PASS real backup/download/upload/preview/transactional restore and re-export: checkpoint hashes, paragraph/native IDs, exact prose and scene GUIDs survive; live session trust detached');
await page.request.delete(presence,{headers});
}finally{await browser.close();}})().catch(e=>{console.error('Synthetic chapter Development qualification: '+e.message);process.exit(1)});

View File

@ -3,13 +3,14 @@ const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
(async()=>{const browser=await chromium.launch();try{
for(const embedded of [false,true])for(const installed of [false,true]){
const page=await browser.newPage({viewport:{width:1280,height:900}});await page.addInitScript(installed=>{if(installed){const match=window.matchMedia.bind(window);window.matchMedia=query=>query==='(display-mode: standalone)'?{matches:true,media:query,addEventListener(){},removeEventListener(){},addListener(){},removeListener(){}}:match(query);}},installed);
let snapshotRevision=1,syncFailure=false,syncRequests=0,transferState='pending';
let snapshotRevision=1,syncFailure=false,syncRequests=0,repairRequests=0,modern=false,transferState='pending';
await page.route('**/manuscript/paragraphs/snapshot',async r=>{syncRequests++;const body=new URLSearchParams(r.request().postData());assert.equal(body.get('bookId'),'12');assert.equal(body.get('instanceId'),'fixture');assert.equal(body.get('sessionId'),'doc');assert.ok(body.get('__RequestVerificationToken'));await r.fulfill({status:syncFailure?409:200,json:{requestId:'11111111-1111-4111-8111-111111111111',message:syncFailure?'Word is unavailable; saved snapshot preserved.':'Word snapshot requested; awaiting acceptance.'}});});
await page.route('**/native-companion/status',r=>r.fulfill({json:[{instanceId:'fixture',sessionId:'doc',bookId:12,chapterId:10,sceneId:22,active:true,wordAvailable:true,wordSaved:true,canParagraphSync:true,snapshotRevision,mappingCurrent:true,paragraphTransfer:syncRequests?{requestId:'11111111-1111-4111-8111-111111111111',state:transferState}:null,documentTitle:'Synthetic manuscript.docx',updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}]}));
await page.route('**/manuscript/paragraphs/repair',async r=>{repairRequests++;assert.equal(new URLSearchParams(r.request().postData()).get('bookId'),'12');await r.fulfill({json:{requestId:'22222222-2222-4222-8222-222222222222',message:'Chapter repair requested.'}});});
await page.route('**/native-companion/status',r=>r.fulfill({json:[{instanceId:'fixture',sessionId:'doc',bookId:12,chapterId:10,sceneId:22,active:true,wordAvailable:true,wordSaved:true,canParagraphSync:true,canChapterSync:modern,snapshotRevision,mappingCurrent:true,paragraphTransfer:repairRequests?{requestId:'22222222-2222-4222-8222-222222222222',state:transferState,kind:'chapter',message:'Chapter repair '+transferState}:syncRequests?{requestId:'11111111-1111-4111-8111-111111111111',state:transferState}:null,documentTitle:'Synthetic manuscript.docx',updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}]}));
await page.route('**/Writing/Context/Scene?*',async r=>r.fulfill({response:await r.fetch({url:base+'/writing-desk-fixture/context?fragment=true&sceneId='+new URL(r.request().url()).searchParams.get('sceneId')})}));
await page.route(/\/Writing\/Context\/(PlotLines|Metrics|Map)\?/,async r=>{const url=new URL(r.request().url()),kind=url.pathname.endsWith('PlotLines')?'plots':url.pathname.endsWith('Metrics')?'metrics':'map';await r.fulfill({response:await r.fetch({url:base+'/writing-context-component/'+kind+url.search})});});
const response=await page.goto(base+'/Writing/Context?bookId=12'+(embedded?'&embedded=true':''));assert.equal(response.status(),200);
await page.waitForSelector('[data-writing-context-fragment][data-scene-id="22"]');assert.equal(await page.locator('iframe').count(),0);assert.equal(await page.locator('#native-companion-status').count(),1);await page.click('#native-companion-status');assert.ok(await page.locator('#writing-connection-details').isVisible());assert.ok(await page.getByRole('option',{name:'Synthetic manuscript.docx · active in Word'}).count());await page.locator('[data-word-sync-button]').click();await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('requested'));assert.equal(syncRequests,1);assert.ok(await page.locator('[data-word-sync-button]').isDisabled(),'request is not completion');snapshotRevision=2;await page.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await page.waitForTimeout(100);assert.ok(!(await page.locator('[data-word-sync-feedback]').textContent()).includes('accepted'),'an unrelated revision is not snapshot acceptance');transferState='accepted';await page.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('accepted'));assert.ok(await page.locator('[data-word-sync-button]').isEnabled());syncFailure=true;await page.locator('[data-word-sync-button]').click();await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('unavailable'));assert.equal(syncRequests,2);await page.click('[data-close-word-details]');
await page.waitForSelector('[data-writing-context-fragment][data-scene-id="22"]');assert.equal(await page.locator('iframe').count(),0);assert.equal(await page.locator('#native-companion-status').count(),1);await page.click('#native-companion-status');assert.ok(await page.locator('#writing-connection-details').isVisible());assert.ok(await page.getByRole('option',{name:'Synthetic manuscript.docx · active in Word'}).count());await page.locator('[data-word-sync-button]').click();await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('requested'));assert.equal(syncRequests,1);assert.ok(await page.locator('[data-word-sync-button]').isDisabled(),'request is not completion');snapshotRevision=2;await page.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await page.waitForTimeout(100);assert.ok(!(await page.locator('[data-word-sync-feedback]').textContent()).includes('accepted'),'an unrelated revision is not snapshot acceptance');transferState='accepted';await page.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('accepted'));assert.ok(await page.locator('[data-word-sync-button]').isEnabled());syncFailure=true;await page.locator('[data-word-sync-button]').click();await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('unavailable'));assert.equal(syncRequests,2);assert.ok(await page.locator('[data-word-repair-button]').isDisabled(),'legacy add-in must not receive chapter commands');modern=true;transferState='pending';await page.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await page.waitForFunction(()=>!document.querySelector('[data-word-repair-button]').disabled);await page.locator('[data-word-repair-button]').click();await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('repair pending'));assert.equal(repairRequests,1);transferState='accepted';await page.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('repair accepted'));assert.equal(snapshotRevision,2,'metadata-only chapter acceptance does not need a new global prose revision');await page.click('[data-close-word-details]');
await page.click('[data-writing-context-tab=people]');await page.selectOption('[data-writing-context-scene-select]','23');await page.waitForSelector('[data-writing-context-fragment][data-scene-id="23"]');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());assert.equal(await page.locator('iframe').count(),0);
await page.click('#native-companion-status');await page.click('[data-word-return-to-current]');await page.waitForSelector('[data-writing-context-fragment][data-scene-id="22"]');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());
if(embedded)assert.equal(await page.locator('.pd-application-header').count(),0,'dedicated workspace has no normal ribbon');

View File

@ -0,0 +1,40 @@
using System.Diagnostics;
using System.Text.Json;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using PlotDirector.Companion.Protocol.Manuscript;
using PlotLine.Data;
using PlotLine.Services.Manuscript;
// Opt-in, owned synthetic Development fixture only. Never uses a fixed author book ID.
internal static class ChapterSyncDevelopmentTests
{
public static async Task Run(string[] args)
{
if(!OperatingSystem.IsLinux()||args.Length!=3||!args[1].StartsWith("/tmp/pd-dev-browser-",StringComparison.Ordinal)||!args[2].StartsWith("/tmp/pd-context-",StringComparison.Ordinal))throw new Exception("Explicit synthetic fixture required");
if((File.GetUnixFileMode(args[1])&(UnixFileMode.GroupRead|UnixFileMode.OtherRead))!=0)throw new Exception("Private identity required");
using var identity=JsonDocument.Parse(await File.ReadAllTextAsync(args[1]));var who=identity.RootElement;var scope=JsonSerializer.Deserialize<WritingContextDevelopmentFixture.Scope>(await File.ReadAllTextAsync(args[2]))!;
var email=who.GetProperty("Email").GetString()!;if(who.GetProperty("Database").GetString()!="PlotDirector_Development"||who.GetProperty("UserID").GetInt32()!=scope.User||!email.StartsWith("pwa-browser-")||!email.EndsWith("@example.invalid"))throw new Exception("Synthetic identity mismatch");
var processInfo=new ProcessStartInfo("sudo"){RedirectStandardOutput=true};foreach(var value in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})processInfo.ArgumentList.Add(value);using var process=Process.Start(processInfo)!;var environment=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync();if(process.ExitCode!=0)throw new Exception("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");
var factory=new SqlConnectionFactory(new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{{"ConnectionStrings:DefaultConnection",connection}}).Build());
if((await new UserRepository(factory).GetByEmailAsync(email))?.UserID!=scope.User||(await new ProjectRepository(factory).GetForUserAsync(scope.Project,scope.User))?.IsOwner!=true||(await new BookRepository(factory).GetAsync(scope.Book))?.ProjectID!=scope.Project)throw new Exception("Synthetic ownership mismatch");
var repository=new ParagraphManuscriptRepository(factory);var chapters=new ChapterSyncRepository(factory);var original=await repository.Get(scope.User,scope.Book)??throw new Exception("Seed missing");if(original.Paragraphs.Count!=6||original.Scenes.Count!=2||original.Chapters.Count!=2||original.ManuscriptId!=scope.Manuscript||original.Paragraphs.Any(p=>p.Occurrence.NativeId!=""))throw new Exception("Unexpected fixture; do not overwrite");
var before=JsonSerializer.Serialize(original);var session=Guid.NewGuid();var proofs=new List<ChapterObservation>();
foreach(var part in ChapterCheckpointEngine.Parts(original)){
var evidence=part.Rows.Select(p=>new ChapterParagraph{NativeId=(p.Occurrence.Ordinal+1).ToString("X8"),Length=p.Occurrence.Text.Length,Outline=p.Occurrence.Outline}).ToArray();
var proof=new ChapterObservation{InstanceId=scope.Instance,SessionId=session,ManuscriptId=scope.Manuscript,WordRevision=0,BaseRevision=original.Revision,ChapterId=part.Chapter.CanonicalId,Start=1000+part.Rows[0].Occurrence.Start,End=1000+part.Rows[^1].Occurrence.End,ContentHash=ChapterFingerprint.Content(part.Rows.Select(p=>p.Occurrence.Text)),IdentityHash=ChapterFingerprint.Identity(evidence),Paragraphs=evidence,Reconcile=true,NextHeadingId=part.End<original.Paragraphs.Count?(part.End+1).ToString("X8"):""};
var source=await repository.Get(scope.User,scope.Book)??throw new Exception();var result=ChapterCheckpointEngine.Validate(source,proof,DateTime.UtcNow);await chapters.Accept(scope.User,scope.Book,proof,result);await chapters.Accept(scope.User,scope.Book,proof,result);proofs.Add(proof);
var scenePosition=result.Positions.First(p=>p.SceneId.HasValue);var cursor=await chapters.Position(scope.User,scope.Book,scope.Manuscript,session,0,scenePosition.Start);Check(cursor?.ChapterID==part.Chapter.CanonicalId&&cursor.SceneID==scenePosition.SceneId,"Committed chapter position resolves its own canonical scene");
Check((await chapters.Position(scope.User,scope.Book,scope.Manuscript,Guid.NewGuid(),0,scenePosition.Start))?.SceneID==null,"Another Word session cannot reuse live absolute positions");
var saved=await repository.Get(scope.User,scope.Book)??throw new Exception();var payload=JsonSerializer.Serialize(saved);
var stale=new ChapterObservation{RequestId=Guid.NewGuid(),SessionId=session,ManuscriptId=scope.Manuscript,WordRevision=0,BaseRevision=source.Revision-1,ChapterId=proof.ChapterId};bool denied=false;try{await chapters.Accept(scope.User,scope.Book,stale,result);}catch(SqlException){denied=true;}Check(denied&&JsonSerializer.Serialize(await repository.Get(scope.User,scope.Book))==payload,"Stale CAS refuses without partially changing checkpoint or canonical snapshot");
}
var accepted=await repository.Get(scope.User,scope.Book)??throw new Exception();Check(accepted.Revision==original.Revision&&accepted.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)))&&accepted.Scenes.Select(s=>s.Id).SequenceEqual(original.Scenes.Select(s=>s.Id)),"Legacy adoption preserves every paragraph GUID, exact prose, scene GUID/assignment and coherent snapshot revision");
Check(accepted.SnapshotHash==ParagraphManuscriptEngine.Hash(accepted.Paragraphs.Select(p=>p.Occurrence).ToArray()),"Legacy native-ID adoption keeps the existing full-snapshot digest coherent");
Check(accepted.ChapterCheckpoints.Count==2&&(await chapters.List(scope.User,scope.Book,session,0)).Count==2,"Independent accepted chapters survive interrupted processing and same-request retry");
var unauthorised=false;try{await chapters.List(0,scope.Book,session,0);}catch(SqlException){unauthorised=true;}Check(unauthorised,"Unauthorised account cannot access chapter checkpoint evidence");
await File.WriteAllTextAsync(args[2]+".evidence.json",JsonSerializer.Serialize(new{scope.Book,scope.Manuscript,Revision=accepted.Revision,Proofs=proofs,Paragraphs=accepted.Paragraphs}));File.SetUnixFileMode(args[2]+".evidence.json",UnixFileMode.UserRead|UnixFileMode.UserWrite);
// Metadata adoption is the only mutation in this fixture. Author data never participates.
}
private static void Check(bool ok,string message){if(!ok)throw new Exception(message);Console.WriteLine("PASS "+message);}
}

View File

@ -34,10 +34,30 @@ internal static class ChapterSynchronisationTests
var legacy=JsonSerializer.Deserialize<ParagraphManuscript>(before)!;foreach(var p in legacy.Paragraphs)p.Occurrence.NativeId="";var adoption=Proof();adoption.Reconcile=true;
var adopted=ChapterCheckpointEngine.Validate(legacy,adoption,DateTime.UtcNow);Check(adopted.Bindings.Length==3&&legacy.Paragraphs.All(p=>p.Occurrence.NativeId==""),"Explicit legacy repair proposes native bindings while preserving every original PlotDirector GUID");
adoption.Reconcile=false;Refused(()=>ChapterCheckpointEngine.Validate(legacy,adoption,DateTime.UtcNow),"Passive hash checks cannot silently adopt missing legacy identities");
var renamed=Proof();renamed.Reconcile=true;renamed.Paragraphs[0].Text="A renamed chapter\r";renamed.Paragraphs[0].Length=renamed.Paragraphs[0].Text!.Length;renamed.ContentHash=ChapterFingerprint.Content(renamed.Paragraphs.Select(p=>p.Text!));renamed.IdentityHash=ChapterFingerprint.Identity(renamed.Paragraphs);renamed.End=renamed.Start+renamed.Paragraphs.Sum(p=>p.Length);
var renamedState=JsonSerializer.Deserialize<ParagraphManuscript>(before)!;ParagraphManuscriptEngine.Reconcile(renamedState,ChapterCheckpointEngine.MergeChapter(state,renamed));Check(renamedState.Chapters[0].CanonicalId==10&&renamedState.Chapters[0].HeadingId==state.Chapters[0].HeadingId,"Renamed heading preserves canonical chapter and paragraph identities");
foreach(var kind in new[]{"insert","delete","split","merge"}){
var mutation=Proof();mutation.Reconcile=true;var altered=mutation.Paragraphs.ToList();
if(kind=="insert")altered.Insert(2,new(){NativeId="000000FF",Text="Inserted paragraph.\r",Length=20});
if(kind=="delete")altered.RemoveAt(2);
if(kind=="split"){altered[1].Text="First\r";altered[1].Length=6;altered.Insert(2,new(){NativeId="000000FF",Text=" passage.\r",Length=10});}
if(kind=="merge"){altered[1].Text+=altered[2].Text;altered[1].Length=altered[1].Text!.Length;altered.RemoveAt(2);}
foreach(var row in altered)row.Length=row.Text!.Length;
mutation.Paragraphs=altered.ToArray();mutation.ContentHash=ChapterFingerprint.Content(altered.Select(p=>p.Text!));mutation.IdentityHash=ChapterFingerprint.Identity(altered);mutation.End=mutation.Start+altered.Sum(p=>p.Length);
var candidate=JsonSerializer.Deserialize<ParagraphManuscript>(before)!;ParagraphManuscriptEngine.Reconcile(candidate,ChapterCheckpointEngine.MergeChapter(state,mutation));
Check(candidate.Paragraphs.Where(p=>p.ChapterId==11).Select(p=>p.Occurrence.Id).SequenceEqual(state.Paragraphs.Where(p=>p.ChapterId==11).Select(p=>p.Occurrence.Id))&&candidate.Scenes.Select(s=>s.Id).SequenceEqual(state.Scenes.Select(s=>s.Id)),"Chapter "+kind+" preserves unrelated paragraph and scene identities");
}
var insertedHeading=Proof();insertedHeading.Reconcile=true;insertedHeading.Paragraphs[1].Outline=1;insertedHeading.IdentityHash=ChapterFingerprint.Identity(insertedHeading.Paragraphs);Refused(()=>ChapterCheckpointEngine.MergeChapter(state,insertedHeading),"Inserted chapter headings require review instead of silently splitting canonical chapters");
state.ChapterCheckpoints=ChapterCheckpointEngine.Build(state,state.Revision).ToList();state.ChapterCheckpoints[0]=accepted.Checkpoint;
var graph=new ProjectBackupExport{FormatVersion="1.5",Project=new(){ProjectID=7},Data=new(){Books=[new(){BookID=12,ProjectID=7}],Chapters=[new(){ChapterID=10,BookID=12},new(){ChapterID=11,BookID=12}],Scenes=[new(){SceneID=22,ChapterID=10},new(){SceneID=23,ChapterID=11}]},Recovery=new(){ParagraphManuscripts=[state]}};
ParagraphRecovery.Validate(graph);var portable=PlotLine.Services.BookBackupGraph.Clone(graph);portable.Project!.ProjectID=107;ParagraphRecovery.Remap(portable,(kind,id)=>id+100);var restored=portable.Recovery.ParagraphManuscripts!.Single();
Check(restored.ChapterCheckpoints[0].ChapterId==110&&restored.ChapterCheckpoints[0].HeadingId==state.Chapters[0].HeadingId&&restored.ChapterCheckpoints[0].ContentHash==state.ChapterCheckpoints[0].ContentHash&&restored.ChapterCheckpoints[0].Status=="Not yet checked"&&restored.SessionId==Guid.Empty,"Backup remaps canonical checkpoint IDs, preserves content/GUID evidence and detaches live trust");
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 one</w:t></w:r></w:p><w:p w14:paraId='00000002'><w:r><w:t>Exact</w:t><w:tab/><w:t>text</w:t></w:r></w:p></w:body></w:document>";
Check(ChapterFingerprint.ReadXml(xml,"Chapter one\rExact\ttext\r").Length==2,"Portable chapter XML identity enumeration matches exact Word range text");
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 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

@ -49,5 +49,7 @@ internal static class ParagraphWorkflowTests
var id=await capture.RequestParagraphSnapshot(7,3);await capture.CancelParagraphSnapshot(7,3);Check(presence.TakeNavigation(7,"grant",instance,session)?.Kind=="cancel"&&memory.Writes==1,"Cancellation retires only pending snapshot and retains already accepted revision");
bool foreign=false;try{await capture.RequestParagraphSnapshot(8,3);}catch(UnauthorizedAccessException){foreign=true;}Check(foreign&&memory.Writes==1,"Another account cannot request manuscript synchronisation");
memory.Paused=true;await services.GetRequiredService<ParagraphManuscriptService>().Enable(7,3,"Off");Check(memory.State.Mode=="Off"&&memory.Writes==1,"Turning off automatic synchronisation changes only preferences even while imports or scene conflicts pause snapshots");
input.CanChapterSync=true;input.Sequence=2;presence.Put(7,"grant",DateTimeOffset.UtcNow.AddHours(1),instance,session,input);var repair=Guid.NewGuid();var currentLease=presence.Read(7,3).Single();presence.TakeNavigation(7,"grant",instance,session);Check(presence.RequestChapterRepair(7,currentLease,repair)&&capture.ParagraphTransferStatus(7,3,instance,session)?.RequestId==repair,"A new chapter repair is not hidden behind an older completed full snapshot receipt");
}
}

View File

@ -15,6 +15,7 @@ using PlotLine.Models;
using PlotLine.Services;
using PlotLine.ViewModels;
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

@ -13,6 +13,10 @@ public sealed class NativeChapterSyncController(ChapterSyncService chapters):Con
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));
[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."});}}
}

View File

@ -8,7 +8,7 @@ using PlotLine.Data;
using PlotLine.Services.NativeCompanion;
namespace PlotLine.Controllers;
[ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion")]
public sealed class NativePresenceController(NativePresenceStore presence,IWordCompanionRepository access,IHubContext<NativeCompanionPresenceHub>? live=null,INativePositionRepository? positions=null,NativeManuscriptCapture? capture=null,IHubContext<WordCompanionFollowHub>? wizard=null,ILogger<NativePresenceController>? logger=null):ControllerBase
public sealed class NativePresenceController(NativePresenceStore presence,IWordCompanionRepository access,IHubContext<NativeCompanionPresenceHub>? live=null,INativePositionRepository? positions=null,NativeManuscriptCapture? capture=null,IHubContext<WordCompanionFollowHub>? wizard=null,ILogger<NativePresenceController>? logger=null,IChapterSyncRepository? chapterPositions=null):ControllerBase
{
private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
private string Grant=>User.FindFirstValue("NativeCompanion.Grant")??throw new InvalidOperationException();
@ -23,19 +23,27 @@ public sealed class NativePresenceController(NativePresenceStore presence,IWordC
if(input.CursorStart is <0)return BadRequest("Invalid cursor position.");
if(input.CanCapture&&input.WordSaved!=true){input.ChapterId=null;input.SceneId=null;}
var paragraphPosition=book!=null&&input.WordAvailable&&input.CanParagraphSync&&input.CursorStart.HasValue&&capture!=null?await capture.ResolveParagraphPosition(Author,input.BookId,input.ManuscriptId,session,input.Revision,input.CursorStart.Value):null;
input.ChapterSyncSupported=chapterPositions!=null&&capture?.ParagraphEnabled==true;
if(book!=null&&input.WordAvailable&&input.CanChapterSync&&input.ChapterSyncSupported&&input.WordSaved==true&&input.CursorStart.HasValue){var fast=await chapterPositions!.Position(Author,input.BookId,input.ManuscriptId,session,input.Revision,input.CursorStart.Value);if(fast?.ChapterID!=null)paragraphPosition=fast;}
if(paragraphPosition!=null){input.ParagraphRevision=paragraphPosition.Revision;input.ChapterId=input.WordSaved==true?paragraphPosition.ChapterID:null;input.SceneId=input.WordSaved==true?paragraphPosition.SceneID:null;}
if(paragraphPosition==null&&book!=null&&input.WordAvailable&&input.SceneId==null&&presence.Resolve(Author,input,session) is {} known){input.ChapterId=known.Chapter;input.SceneId=known.Scene;}
if(paragraphPosition==null&&book!=null&&input.WordAvailable&&input.SceneId==null&&input.CursorStart.HasValue&&positions!=null&&(!input.CanCapture||input.WordSaved==true)){var mapped=await positions.Resolve(Author,input.BookId,input.ManuscriptId,session,input.Revision,input.CursorStart.Value);if(mapped!=null&&(!input.ChapterId.HasValue||input.ChapterId==mapped.ChapterID)){input.ChapterId=mapped.ChapterID;input.SceneId=mapped.SceneID;}}
var chapter=input.ChapterId.HasValue?book!.Chapters.FirstOrDefault(c=>c.ChapterId==input.ChapterId):null;
if(input.SceneId.HasValue){var parent=book!.Chapters.FirstOrDefault(c=>c.Scenes.Any(s=>s.SceneId==input.SceneId));if(parent==null||(chapter!=null&&chapter!=parent)){input.SceneId=null;input.ChapterId=null;chapter=null;}else{chapter=parent;input.ChapterId=parent.ChapterId;}}
if(input.ChapterId.HasValue&&chapter==null){input.ChapterId=null;input.SceneId=null;}
input.ChapterTitle=book?.Chapters.FirstOrDefault(c=>c.ChapterId==input.ChapterId)?.Title??"";
input.SceneTitle=book?.Chapters.SelectMany(c=>c.Scenes).FirstOrDefault(s=>s.SceneId==input.SceneId)?.Title??"";
var before=presence.Read(Author,input.BookId).FirstOrDefault(l=>l.Instance==instance&&l.Session==session);
if(!presence.Put(Author,Grant,Expires,instance,session,input))return Conflict(new{message="Stale, revoked or invalid native session."});
if(before==null||before.Position.ChapterId!=input.ChapterId||before.Position.SceneId!=input.SceneId||before.Position.WordSaved!=input.WordSaved||before.Position.Revision!=input.Revision)
logger?.LogInformation("Native cursor observation User={User} Book={Book} Instance={Instance} Session={Session} Sequence={Sequence} Manuscript={Manuscript} WordRevision={WordRevision} Saved={Saved} Cursor={Cursor} Chapter={Chapter} Scene={Scene} ParagraphSnapshot={HasSnapshot} ParagraphRevision={ParagraphRevision}; observation does not request navigation",Author,input.BookId,instance,session,input.Sequence,input.ManuscriptId,input.Revision,input.WordSaved,input.CursorStart,input.ChapterId,input.SceneId,paragraphPosition?.HasSnapshot,paragraphPosition?.Revision);
if(live!=null&&(before==null||before.Position.BookId!=input.BookId||before.Position.ManuscriptId!=input.ManuscriptId||before.Position.Revision!=input.Revision||before.Position.ChapterId!=input.ChapterId||before.Position.SceneId!=input.SceneId||before.Position.Active!=input.Active||before.Position.WordAvailable!=input.WordAvailable||before.Position.WordRunning!=input.WordRunning||before.Position.WordSaved!=input.WordSaved||before.Position.CaptureRequestId!=input.CaptureRequestId||before.Position.CaptureProgress/5!=input.CaptureProgress/5))await live.Clients.Group(NativeCompanionPresenceHub.UserGroup(Author)).SendAsync("NativePresenceChanged",new{bookId=input.BookId},HttpContext.RequestAborted);
if(input.CaptureRequestId.HasValue&&capture!=null&&wizard!=null){var progress=await capture.Progress(Author,Grant,input.CaptureRequestId.Value,input.CaptureProgress,instance,session,input.ManuscriptId,input.Revision);if(progress!=null)await wizard.Clients.Group(WordCompanionFollowHub.PresenceGroup(Author)).SendAsync("OnboardingScanProgress",progress,HttpContext.RequestAborted);}
if(input.CanParagraphSync&&capture!=null){var lease=presence.Read(Author,input.BookId).FirstOrDefault(l=>l.Instance==instance&&l.Session==session);if(lease!=null)await capture.ObserveParagraphSave(Author,lease);}
if(input.CanParagraphSync&&!input.CanChapterSync&&capture!=null){var lease=presence.Read(Author,input.BookId).FirstOrDefault(l=>l.Instance==instance&&l.Session==session);if(lease!=null)await capture.ObserveParagraphSave(Author,lease);}
if(input.CanChapterSync&&input.ChapterIssue=="needs_review"){
var earlier=presence.ChapterProgress(Author,input.BookId,instance,session,input.Revision);presence.RecordChapterProgress(Author,input.BookId,instance,session,input.Revision,new(){Total=earlier?.Total??0,Checked=earlier?.Checked??0,Matching=earlier?.Matching??0,NeedsReview=Math.Max(1,(earlier?.Total??1)-(earlier?.Matching??0)),State="Needs review",Message="Chapter reading needs review or retry in Companion Troubleshooting. Independently accepted checkpoints are retained."});
}
input.ChapterProgress=presence.ChapterProgress(Author,input.BookId,instance,session,input.Revision);
input.CatalogVersion=presence.CatalogVersion(Author);input.Navigation=presence.TakeNavigation(Author,Grant,instance,session);
if(input.Navigation is {Kind:"navigate"} command)logger?.LogInformation("Deliver explicit Word navigation Id={NavigationId} User={User} Book={Book} Instance={Instance} Session={Session} Revision={Revision} Position={Position}",command.Id,Author,input.BookId,instance,session,command.Revision,command.Chapter?.Start);
return Ok(input);

View File

@ -37,11 +37,11 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB
foreach(var book in leases.Select(l=>l.Position.BookId).Where(b=>b>0).Distinct())if(await access.GetBookStructureAsync(book,Author)!=null)allowed.Add(book);
var snapshots=new Dictionary<int,ParagraphSyncStatus?>();
if(paragraphs!=null)foreach(var book in leases.Where(l=>l.Position.WordAvailable&&allowed.Contains(l.Position.BookId)&&l.Position.BookId>0).Select(l=>l.Position.BookId).Distinct())snapshots[book]=await paragraphs.Status(Author,book);
return Json(leases.Where(l=>allowed.Contains(l.Position.BookId)).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,l.Position.BookId,l.Position.DocumentTitle,l.Position.ChapterId,l.Position.SceneId,l.Position.Active,l.Position.WordAvailable,l.Position.WordRunning,l.Position.WordSaved,l.Position.CanCapture,l.Position.CanParagraphSync,l.Position.CaptureRequestId,l.Position.CaptureProgress,
return Json(leases.Where(l=>allowed.Contains(l.Position.BookId)).Select(l=>new{instanceId=l.Instance,sessionId=l.Session,l.Position.BookId,l.Position.DocumentTitle,l.Position.ChapterId,l.Position.SceneId,l.Position.Active,l.Position.WordAvailable,l.Position.WordRunning,l.Position.WordSaved,l.Position.CanCapture,l.Position.ChapterIssue,l.Position.CanChapterSync,chapterProgress=presence.ChapterProgress(Author,l.Position.BookId,l.Instance,l.Session,l.Position.Revision),l.Position.CanParagraphSync,l.Position.CaptureRequestId,l.Position.CaptureProgress,
paragraphTransfer=capture?.ParagraphTransferStatus(Author,l.Position.BookId,l.Instance,l.Session),
snapshotRevision=snapshots.GetValueOrDefault(l.Position.BookId)?.Revision,
mappingCurrent=snapshots.GetValueOrDefault(l.Position.BookId) is {} saved&&saved.ManuscriptId==l.Position.ManuscriptId&&saved.SessionId==l.Session&&saved.WordRevision==l.Position.Revision,
positionMessage=l.Position.WordSaved==false?"Save Word, then synchronise to refresh its scene mapping":l.Position.SceneId.HasValue?null:snapshots.GetValueOrDefault(l.Position.BookId) is {} snapshot?(snapshot.ManuscriptId!=l.Position.ManuscriptId?"This Word document does not match the book's saved manuscript identity":snapshot.SessionId!=l.Session||snapshot.WordRevision!=l.Position.Revision?"Word reopened or changed; synchronise from Word to verify this session's paragraph positions":snapshot.Paused?"Scene mapping is unresolved; synchronisation is paused while existing book processing finishes":"Current paragraph has no verified scene assignment") : "Synchronise from Word to establish a verified paragraph mapping",
positionMessage=l.Position.WordSaved==false?"Save Word, then synchronise to refresh its scene mapping":l.Position.SceneId.HasValue?null:l.Position.CanChapterSync?(l.Position.ChapterIssue=="needs_review"?"Chapter reading needs review or retry; accepted mappings are preserved":l.Position.ChapterId.HasValue?"Current paragraph is checked but has no scene assignment; move into scene prose":"Checking the current chapter for this Word session; saved scenes remain available"):snapshots.GetValueOrDefault(l.Position.BookId) is {} snapshot?(snapshot.ManuscriptId!=l.Position.ManuscriptId?"This Word document does not match the book's saved manuscript identity":snapshot.SessionId!=l.Session||snapshot.WordRevision!=l.Position.Revision?"Word reopened or changed; synchronise from Word to verify this session's paragraph positions":snapshot.Paused?"Scene mapping is unresolved; synchronisation is paused while existing book processing finishes":"Current paragraph has no verified scene assignment") : "Synchronise from Word to establish a verified paragraph mapping",
updated=l.Updated,expires=l.Updated.AddSeconds(45)}));
}
[HttpGet("reviews/{id:guid}")]

View File

@ -18,11 +18,14 @@ public sealed class ParagraphManuscriptController(ParagraphManuscriptService man
[HttpPost("enable"),ValidateAntiForgeryToken]
public Task<IActionResult> Enable(int bookId,string mode)=>Run(bookId,async()=>{await manuscripts.Enable(Author,bookId,mode);return "Paragraph tracking preference saved. Word prose is never rewritten by PlotDirector.";});
[HttpPost("snapshot"),ValidateAntiForgeryToken]
public Task<IActionResult> Snapshot(int bookId,Guid? instanceId=null,Guid? sessionId=null)
public Task<IActionResult> Snapshot(int bookId,Guid? instanceId=null,Guid? sessionId=null,bool fullSnapshot=false)
{
Guid requested=Guid.Empty;
return Run(bookId,async()=>{if(!ModelState.IsValid)throw new ArgumentException("Invalid Word document selection.");requested=await capture.RequestParagraphSnapshot(Author,bookId,instanceId:instanceId,sessionId:sessionId);return requested==Guid.Empty?"A transfer is already pending. Refresh after it finishes.":"Word snapshot requested. Keep Word open until the transfer is acknowledged.";},()=>requested);
return Run(bookId,async()=>{if(!ModelState.IsValid)throw new ArgumentException("Invalid Word document selection.");requested=await capture.RequestParagraphSnapshot(Author,bookId,instanceId:instanceId,sessionId:sessionId,fullSnapshot:fullSnapshot);return requested==Guid.Empty?"A transfer is already pending. Refresh after it finishes.":"Word snapshot requested. Keep Word open until the transfer is acknowledged.";},()=>requested);
}
[HttpPost("repair"),ValidateAntiForgeryToken]
public Task<IActionResult> Repair(int bookId,[FromServices] PlotLine.Services.Manuscript.ChapterSyncService chapters,Guid? instanceId=null,Guid? sessionId=null)
{Guid id=Guid.Empty;return Run(bookId,async()=>{id=await chapters.Repair(Author,bookId,instanceId,sessionId);return "Chapter repair requested. Existing identities and accepted repairs are preserved; keep Word open while chapters are checked.";},()=>id);}
[HttpPost("cancel"),ValidateAntiForgeryToken]
public Task<IActionResult> Cancel(int bookId)=>Run(bookId,async()=>{await capture.CancelParagraphSnapshot(Author,bookId);return "Pending snapshot cancelled. Already acknowledged snapshots remain saved.";});
[HttpPost("change"),ValidateAntiForgeryToken]

View File

@ -250,7 +250,7 @@ public sealed class WritingController(
[HttpPost("Context/Navigate"),ValidateAntiForgeryToken]
public async Task<IActionResult> NavigateWord(int bookId,int sceneId,Guid? instanceId,Guid? sessionId,
[FromServices] IWordCompanionRepository access,[FromServices] IParagraphManuscriptRepository paragraphs,[FromServices] NativePresenceStore presence,Guid? navigationId=null)
[FromServices] IWordCompanionRepository access,[FromServices] IParagraphManuscriptRepository paragraphs,[FromServices] NativePresenceStore presence,Guid? navigationId=null,[FromServices] IChapterSyncRepository? chapterPositions=null)
{
if(!ModelState.IsValid||bookId<=0||sceneId<=0||instanceId.HasValue!=sessionId.HasValue)return BadRequest(new{message="Choose a valid scene and a complete Word document session. No navigation was sent."});
var user=int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
@ -261,14 +261,20 @@ public sealed class WritingController(
var lease=candidates.Length==1?candidates[0]:!instanceId.HasValue&&leases.Length==1?leases[0]:null;
if(lease==null)return Conflict(new{message="No single connected Word document is selected. Scene navigation remains available here."});
var state=await paragraphs.Get(user,bookId);
if(state==null||lease.Position.WordSaved!=true||state.SessionId!=lease.Session||state.WordRevision!=lease.Position.Revision||state.ManuscriptId!=lease.Position.ManuscriptId)return Conflict(new{message="Word has no current saved paragraph mapping. Synchronise from Word before requesting navigation."});
if(state==null||lease.Position.WordSaved!=true||(!lease.Position.CanChapterSync&&(state.SessionId!=lease.Session||state.WordRevision!=lease.Position.Revision))||state.ManuscriptId!=lease.Position.ManuscriptId)return Conflict(new{message="Word has no current saved paragraph mapping. Synchronise from Word before requesting navigation."});
var target=state.Scenes.FirstOrDefault(s=>!s.Retired&&s.CanonicalId==sceneId&&s.ChapterId==chapter.ChapterId);
var first=target==null?null:state.Paragraphs.Where(p=>p.Story&&p.SceneId==target.Id).OrderBy(p=>p.Occurrence.Ordinal).FirstOrDefault();
if(first?.PositionVerified!=true)return Conflict(new{message="The scene start is unresolved. Saved scene information remains available."});
var commandId=navigationId??Guid.NewGuid();
var verified=await paragraphs.Position(user,bookId,state.ManuscriptId,state.SessionId,state.WordRevision,first.Occurrence.Start);
if(HttpContext.RequestAborted.IsCancellationRequested||verified?.HasSnapshot!=true||verified.Revision!=state.Revision||verified.SceneID!=sceneId||verified.ChapterID!=chapter.ChapterId||!presence.Navigate(user,bookId,lease.Instance,lease.Session,state.ManuscriptId,state.WordRevision,first.Occurrence.Start,requireSaved:true,navigationId:commandId))return Conflict(new{message="The Word mapping changed or Word is busy. No navigation was sent."});
logger.LogInformation("Explicit Context navigation queued Id={NavigationId} Trace={Trace} User={User} Book={Book} Scene={Scene} Instance={Instance} Session={Session} Revision={Revision} Position={Position}",commandId,HttpContext.TraceIdentifier,user,bookId,sceneId,lease.Instance,lease.Session,state.WordRevision,first.Occurrence.Start);
var commandId=navigationId??Guid.NewGuid();var position=first.Occurrence.Start;var revision=lease.Position.Revision;
if(lease.Position.CanChapterSync&&(state.SessionId!=lease.Session||state.WordRevision!=revision)){
var anchor=chapterPositions==null?null:await chapterPositions.SceneStart(user,bookId,sceneId,first.Occurrence.Id,state.ManuscriptId,lease.Session,revision);
if(anchor==null||anchor.Revision!=state.Revision||anchor.SceneID!=sceneId||anchor.ChapterID!=chapter.ChapterId)return Conflict(new{message="This chapter has no current verified Word position. Validate or repair it in Word first; saved scene browsing remains available."});position=anchor.StartPosition;
}else{
var verified=await paragraphs.Position(user,bookId,state.ManuscriptId,state.SessionId,state.WordRevision,position);
if(verified?.HasSnapshot!=true||verified.Revision!=state.Revision||verified.SceneID!=sceneId||verified.ChapterID!=chapter.ChapterId)return Conflict(new{message="The saved Word mapping changed. Synchronise before navigating."});
}
if(HttpContext.RequestAborted.IsCancellationRequested||!presence.Navigate(user,bookId,lease.Instance,lease.Session,state.ManuscriptId,revision,position,requireSaved:true,navigationId:commandId))return Conflict(new{message="The Word mapping changed or Word is busy. No navigation was sent."});
logger.LogInformation("Explicit Context navigation accepted Id={NavigationId} Trace={Trace} User={User} Book={Book} Scene={Scene} Instance={Instance} Session={Session} Revision={Revision} Position={Position}",commandId,HttpContext.TraceIdentifier,user,bookId,sceneId,lease.Instance,lease.Session,revision,position);
return Ok(new{navigationId=commandId,message="Navigation requested in Word."});
}

View File

@ -7,14 +7,19 @@ using PlotDirector.Companion.Protocol.Manuscript;
namespace PlotLine.Data;
public interface IChapterSyncRepository
{
Task<ChapterSceneAnchor?> SceneStart(int user,int book,int scene,Guid paragraph,Guid manuscript,Guid session,long wordRevision);
Task FlagReview(int user,int book,int chapter,long revision);
Task<ParagraphManuscript> Accept(int user,int book,ChapterObservation observation,ChapterValidationResult result);
Task<ParagraphPosition?> Position(int user,int book,Guid manuscript,Guid session,long wordRevision,int position);
Task<IReadOnlyList<ChapterLiveValidation>> List(int user,int book,Guid session,long wordRevision);
}
public sealed class ChapterLiveValidation{public int ChapterID{get;set;}public Guid SessionID{get;set;}public long WordRevision{get;set;}public string ContentHash{get;set;}="";public string IdentityHash{get;set;}="";public string MappingHash{get;set;}="";public long SourceRevision{get;set;}public DateTime ValidatedUtc{get;set;}}
public sealed class ChapterSceneAnchor{public long Revision{get;set;}public int ChapterID{get;set;}public int SceneID{get;set;}public int StartPosition{get;set;}}
public sealed class ChapterLiveValidation{public int ChapterID{get;set;}public int StartPosition{get;set;}public int EndPosition{get;set;}public Guid SessionID{get;set;}public long WordRevision{get;set;}public string ContentHash{get;set;}="";public string IdentityHash{get;set;}="";public string MappingHash{get;set;}="";public long SourceRevision{get;set;}public DateTime ValidatedUtc{get;set;}}
public sealed class ChapterSyncRepository(ISqlConnectionFactory factory):IChapterSyncRepository
{
public async Task<ParagraphManuscript> Accept(int user,int book,ChapterObservation observation,ChapterValidationResult result){using var db=factory.CreateConnection();var json=await db.QuerySingleAsync<string>("dbo.BookChapterSync",new{Action="accept",UserID=user,BookID=book,ChapterID=observation.ChapterId,SessionID=observation.SessionId,ManuscriptID=observation.ManuscriptId,WordRevision=observation.WordRevision,ExpectedRevision=observation.BaseRevision,RequestID=observation.RequestId,Checkpoint=JsonSerializer.Serialize(result.Checkpoint),Positions=JsonSerializer.Serialize(result.Positions),Bindings=JsonSerializer.Serialize(result.Bindings)},commandType:CommandType.StoredProcedure);return JsonSerializer.Deserialize<ParagraphManuscript>(json)!;}
public async Task<ChapterSceneAnchor?> SceneStart(int user,int book,int scene,Guid paragraph,Guid manuscript,Guid session,long wordRevision){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync<ChapterSceneAnchor>("dbo.BookChapterSync",new{Action="scene-start",UserID=user,BookID=book,SceneID=scene,ParagraphID=paragraph,ManuscriptID=manuscript,SessionID=session,WordRevision=wordRevision},commandType:CommandType.StoredProcedure);}
public async Task FlagReview(int user,int book,int chapter,long revision){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.BookChapterSync",new{Action="review",UserID=user,BookID=book,ChapterID=chapter,ExpectedRevision=revision},commandType:CommandType.StoredProcedure);}
public async Task<ParagraphManuscript> Accept(int user,int book,ChapterObservation observation,ChapterValidationResult result){using var db=factory.CreateConnection();var json=await db.QuerySingleAsync<string>("dbo.BookChapterSync",new{Action="accept",UserID=user,BookID=book,ChapterID=observation.ChapterId,SessionID=observation.SessionId,ManuscriptID=observation.ManuscriptId,WordRevision=observation.WordRevision,ExpectedRevision=observation.BaseRevision,RequestID=observation.RequestId,Checkpoint=JsonSerializer.Serialize(result.Checkpoint),Positions=JsonSerializer.Serialize(result.Positions),Bindings=JsonSerializer.Serialize(result.Bindings),SnapshotHash=result.AdoptedSnapshotHash},commandType:CommandType.StoredProcedure);return JsonSerializer.Deserialize<ParagraphManuscript>(json)!;}
public async Task<ParagraphPosition?> Position(int user,int book,Guid manuscript,Guid session,long wordRevision,int position){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync<ParagraphPosition>("dbo.BookChapterSync",new{Action="position",UserID=user,BookID=book,ManuscriptID=manuscript,SessionID=session,WordRevision=wordRevision,Position=position},commandType:CommandType.StoredProcedure);}
public async Task<IReadOnlyList<ChapterLiveValidation>> List(int user,int book,Guid session,long wordRevision){using var db=factory.CreateConnection();return(await db.QueryAsync<ChapterLiveValidation>("dbo.BookChapterSync",new{Action="list",UserID=user,BookID=book,SessionID=session,WordRevision=wordRevision},commandType:CommandType.StoredProcedure)).ToArray();}
}

View File

@ -30,7 +30,9 @@ Use Heading 1 for chapter headings. In the website’s existing manuscript impor
Review the detected chapters before starting server analysis. Once the capture has been accepted, analysis and review do not require Word or the Companion to remain connected. Existing story records and Word prose are not silently replaced. If transfer is interrupted before acceptance, reconnect and retry from the wizard.
Save Word normally before capturing when you want live positional scene mapping. **Word reports saved** and **PlotDirector acknowledged this captured revision** are separate states. Saving does not upload prose. After editing or saving again, use a fresh wizard capture when synchronisation is needed; automatic prose synchronisation is not implemented. The Companion’s **Check document connection** verifies presence only.
Save Word normally before capturing when you want live positional scene mapping. **Word reports saved** and **PlotDirector acknowledged this revision** are separate states. Open the top-right Word connection indicator for **Synchronise from Word** and **Repair Manuscript Synchronisation**. The book’s **Manuscript structure and evidence** workspace also offers these actions, cancellation and saved chapter checkpoints.
Chapter-capable Companion builds validate the current Heading 1 chapter first and continue through remaining chapters without a per-paragraph XML read. Only server-accepted position evidence permits live scene following. Manual mode never uploads changed prose until you explicitly synchronise or repair. Save/reconnect mode permits changed-chapter updates; it does not start AI. Repair works on the existing import and preserves its identities and author decisions. Ambiguous identities, moved boundaries and unsupported Word content require review; the full snapshot fallback remains available without reimporting. Installed builds without chapter capability keep their existing synchronisation path.
[Get started without Word](/help/getting-started/first-book)

View File

@ -12,7 +12,7 @@ public sealed class ChapterCheckpoint
}
public sealed record ChapterPart(ParagraphChapter Chapter,int Index,int End,StoryParagraph[] Rows);
public sealed record NativeParagraphBinding(Guid ParagraphId,string NativeId);
public sealed record ChapterValidationResult(ChapterCheckpoint Checkpoint,NativeParagraphBinding[] Bindings,ChapterPosition[] Positions);
public sealed record ChapterValidationResult(ChapterCheckpoint Checkpoint,NativeParagraphBinding[] Bindings,ChapterPosition[] Positions){public string? AdoptedSnapshotHash{get;init;}}
public sealed record ChapterPosition(Guid ParagraphId,int Start,int End,int ChapterId,int? SceneId,bool Verified);
public static class ChapterCheckpointEngine
@ -25,7 +25,9 @@ public static class ChapterCheckpointEngine
}
public static ChapterCheckpoint[] Build(ParagraphManuscript state,long acceptedRevision)
{
var parts=Parts(state);var duplicateNative=state.Paragraphs.Select(p=>p.Occurrence.NativeId).Where(id=>id!="").GroupBy(id=>id).Where(g=>g.Count()>1).Select(g=>g.Key).ToHashSet();
ChapterPart[] parts;
try{parts=Parts(state);}catch(InvalidOperationException e){return state.Chapters.Where(c=>c.CanonicalId>0).GroupBy(c=>c.CanonicalId).Select(g=>new ChapterCheckpoint{ChapterId=g.Key,HeadingId=g.First().HeadingId,AcceptedRevision=acceptedRevision,Status="Needs review",Message=e.Message+" Existing accepted snapshot is preserved; a bounded full read remains available without reimport."}).ToArray();}
var duplicateNative=state.Paragraphs.Select(p=>p.Occurrence.NativeId).Where(id=>id!="").GroupBy(id=>id).Where(g=>g.Count()>1).Select(g=>g.Key).ToHashSet();
return parts.Select((part,i)=>{
var checkpoint=new ChapterCheckpoint{ChapterId=part.Chapter.CanonicalId,HeadingId=part.Chapter.HeadingId,NativeHeadingId=part.Rows[0].Occurrence.NativeId,ParagraphCount=part.Rows.Length,Order=i,AcceptedRevision=acceptedRevision,NextHeadingId=part.End<state.Paragraphs.Count?state.Paragraphs[part.End].Occurrence.NativeId:""};
try{
@ -34,8 +36,8 @@ public static class ChapterCheckpointEngine
if(part.Rows.Any(p=>duplicateNative.Contains(p.Occurrence.NativeId)))throw new ArgumentException("Native paragraph identity is duplicated elsewhere in this manuscript.");
checkpoint.IdentityHash=ChapterFingerprint.Identity(Evidence(part));
}catch(ArgumentException e){checkpoint.Status="Needs review";checkpoint.Message=e.Message;}
var prior=state.ChapterCheckpoints.FirstOrDefault(c=>c.ChapterId==checkpoint.ChapterId&&c.ContentHash==checkpoint.ContentHash&&c.IdentityHash==checkpoint.IdentityHash&&c.MappingHash==checkpoint.MappingHash);
if(prior!=null){checkpoint.LastSuccessfulSyncUtc=prior.LastSuccessfulSyncUtc;checkpoint.AcceptedRevision=prior.AcceptedRevision;}
var prior=state.ChapterCheckpoints.FirstOrDefault(c=>c.ChapterId==checkpoint.ChapterId&&c.ContentHash==checkpoint.ContentHash&&c.IdentityHash==checkpoint.IdentityHash&&c.MappingHash==checkpoint.MappingHash&&c.NextHeadingId==checkpoint.NextHeadingId);
if(prior!=null){checkpoint.LastSuccessfulSyncUtc=prior.LastSuccessfulSyncUtc;checkpoint.AcceptedRevision=prior.AcceptedRevision;if(prior.Status=="Needs review"){checkpoint.Status=prior.Status;checkpoint.Message=prior.Message;}}
return checkpoint;
}).ToArray();
}
@ -60,9 +62,12 @@ public static class ChapterCheckpointEngine
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.");
// A moved chapter may be validated locally, but its canonical ordering is never silently rewritten.
checkpoint.Status="Synchronised";checkpoint.Message=checkpoint.NextHeadingId!=""&&checkpoint.NextHeadingId!=proof.NextHeadingId?"Chapter text and paragraph map verified; surrounding chapter order needs review.":"Accepted chapter positions verified for this session.";
if(checkpoint.Message.Contains("order needs review"))checkpoint.Status="Needs review";
checkpoint.IdentityHash=identity;checkpoint.NativeHeadingId=proof.Paragraphs[0].NativeId;checkpoint.LastSuccessfulSyncUtc=now;
var start=proof.Start;var positions=part.Rows.Select((row,i)=>{var end=checked(start+proof.Paragraphs[i].Length);var scene=state.Scenes.FirstOrDefault(s=>!s.Retired&&s.Id==row.SceneId&&s.ChapterId==proof.ChapterId);var value=new ChapterPosition(row.Occurrence.Id,start,end,proof.ChapterId,scene?.CanonicalId>0?scene.CanonicalId:null,row.PositionVerified&&row.ChapterId==proof.ChapterId);start=end;return value;}).ToArray();
return new(checkpoint,bindings.ToArray(),positions);
var bindingsById=bindings.ToDictionary(b=>b.ParagraphId,b=>b.NativeId);
var adoptedHash=bindings.Count==0?null:ParagraphManuscriptEngine.Hash(state.Paragraphs.Select(p=>new ParagraphOccurrence{Id=p.Occurrence.Id,NativeId=bindingsById.GetValueOrDefault(p.Occurrence.Id,p.Occurrence.NativeId),Text=p.Occurrence.Text,Outline=p.Occurrence.Outline,Start=p.Occurrence.Start,End=p.Occurrence.End}).ToArray());
return new(checkpoint,bindings.ToArray(),positions){AdoptedSnapshotHash=adoptedHash};
}
public static ParagraphOccurrence[] MergeChapter(ParagraphManuscript state,ChapterObservation proof)
{

View File

@ -5,29 +5,51 @@ using PlotLine.Services.NativeCompanion;
namespace PlotLine.Services.Manuscript;
public sealed class ChapterSyncService(IParagraphManuscriptRepository manuscripts,IChapterSyncRepository checkpoints,IWordCompanionRepository access,ParagraphManuscriptService reconciliation,NativePresenceStore presence,TimeProvider clock)
{
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)
{
RequireFeature();
if(await access.GetBookStructureAsync(book,user)==null)throw new UnauthorizedAccessException();
var state=await manuscripts.Get(user,book)??throw new InvalidOperationException("Finish the existing manuscript import first; no saved index is available.");
var live=await checkpoints.List(user,book,session,wordRevision);var sources=ChapterCheckpointEngine.Build(state,state.Revision);
return new(){BookId=book,ManuscriptId=state.ManuscriptId,Revision=state.Revision,Mode=state.Mode,Chapters=ChapterCheckpointEngine.Parts(state).Select(part=>{
var source=sources.Single(c=>c.ChapterId==part.Chapter.CanonicalId);var accepted=live.Any(c=>c.ChapterID==source.ChapterId&&c.ContentHash==source.ContentHash&&c.IdentityHash==source.IdentityHash&&c.MappingHash==source.MappingHash);
return new ChapterManifestItem{ChapterId=source.ChapterId,Title=part.Chapter.Title,HeadingNativeId=source.NativeHeadingId,ContentHash=source.ContentHash,IdentityHash=source.IdentityHash,Start=part.Rows[0].Occurrence.Start,End=part.Rows[^1].Occurrence.End,ParagraphCount=source.ParagraphCount,State=accepted?"Synchronised":source.Status};
var manifest=new ChapterManifest(){BookId=book,ManuscriptId=state.ManuscriptId,Revision=state.Revision,Mode=state.Mode,Chapters=ChapterCheckpointEngine.Parts(state).Select(part=>{
var source=sources.Single(c=>c.ChapterId==part.Chapter.CanonicalId);var accepted=live.FirstOrDefault(c=>c.ChapterID==source.ChapterId&&c.ContentHash==source.ContentHash&&c.IdentityHash==source.IdentityHash&&c.MappingHash==source.MappingHash);
return new ChapterManifestItem{ChapterId=source.ChapterId,Title=part.Chapter.Title,HeadingNativeId=source.NativeHeadingId,ContentHash=source.ContentHash,IdentityHash=source.IdentityHash,Start=accepted?.StartPosition??part.Rows[0].Occurrence.Start,End=accepted?.EndPosition??part.Rows[^1].Occurrence.End,ParagraphCount=source.ParagraphCount,State=accepted!=null&&source.Status!="Needs review"?"Synchronised":source.Status};
}).ToArray()};
var lease=presence.Read(user,book).SingleOrDefault(l=>l.Session==session&&l.Position.Revision==wordRevision&&l.Position.CanChapterSync);
if(lease!=null){var count=manifest.Chapters.Count(c=>c.State=="Synchronised");presence.RecordChapterProgress(user,book,lease.Instance,session,wordRevision,new(){Total=manifest.Chapters.Length,Checked=count,Matching=count,Repaired=presence.RepairedChapters(user,book,lease.Instance,session,wordRevision),State="Checking",Message=$"{count}/{manifest.Chapters.Length} chapter mappings accepted for this session."});}
return manifest;
}
public async Task<Guid> Repair(int user,int book,Guid? instance,Guid? session)
public async Task<ChapterSyncProgress> Finish(int user,string grant,int book,ChapterFinish completion)
{
RequireFeature();
var lease=presence.Read(user,book).SingleOrDefault(l=>l.Grant==grant&&l.Instance==completion.InstanceId&&l.Session==completion.SessionId&&l.Position.Revision==completion.WordRevision&&l.Position.CanChapterSync&&l.Position.WordSaved==true)??throw new InvalidOperationException("The live document changed before completion.");
if(completion.OperationId!=Guid.Empty&&!presence.CanRepairChapter(user,lease,completion.OperationId))throw new UnauthorizedAccessException();
var status=await manuscripts.Status(user,book);if(status?.CanWrite!=true)throw new UnauthorizedAccessException();if(status.Paused)throw new InvalidOperationException("Existing import or analysis is active; completion is paused and accepted checkpoints are retained.");
var manifest=await Manifest(user,book,completion.SessionId,completion.WordRevision);
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;
}
public async Task<Guid> Repair(int user,int book,Guid? instance,Guid? session,long? expectedWordRevision=null)
{
RequireFeature();
var status=await manuscripts.Status(user,book)??throw new InvalidOperationException("The accepted snapshot is missing; finish the existing import, do not reimport an already indexed book.");
if(!status.CanWrite)throw new UnauthorizedAccessException();if(status.Paused)throw new InvalidOperationException("Existing import or analysis is active. Accepted checkpoints are preserved.");
if(instance.HasValue!=session.HasValue)throw new InvalidOperationException("Choose a complete Word session.");
var live=presence.Read(user,book).Where(l=>l.Position.WordAvailable&&l.Position.CanChapterSync&&l.Position.WordSaved==true).ToArray();
var selected=instance.HasValue?live.SingleOrDefault(l=>l.Instance==instance&&l.Session==session):live.Count(l=>l.Position.Active)==1?live.Single(l=>l.Position.Active):live.Length==1?live[0]:null;
if(selected==null)throw new InvalidOperationException("Open and save the intended manuscript with a chapter-capable Companion, then select its document connection.");
if(expectedWordRevision.HasValue&&selected.Position.Revision!=expectedWordRevision)throw new InvalidOperationException("Word changed before the explicit repair request arrived. Request again from the current document.");
if(selected.Position.ManuscriptId!=status.ManuscriptId)throw new InvalidOperationException("This document has a different manuscript identity. No existing import was changed.");
var source=await manuscripts.Get(user,book)??throw new InvalidOperationException("No accepted source snapshot.");if(ChapterCheckpointEngine.Parts(source).Length==0)throw new InvalidOperationException("No reversible chapter boundaries are recorded. Use the existing bounded full snapshot reader or review structure; the import does not need to be recreated.");
var id=Guid.NewGuid();if(!presence.RequestChapterRepair(user,selected,id))throw new InvalidOperationException("Word is busy with another request. Accepted chapter checkpoints are preserved.");return id;
}
public async Task<ChapterSyncReply> Accept(int user,string grant,int book,ChapterObservation proof)
{
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();
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.");
@ -36,14 +58,18 @@ public sealed class ChapterSyncService(IParagraphManuscriptRepository manuscript
var permitted=status.Mode=="OnSave"||presence.CanRepairChapter(user,lease,proof.OperationId);
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.");
if(source.ContentHash!=proof.ContentHash){
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.");
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);
var validated=ChapterCheckpointEngine.Validate(state,proof,clock.GetUtcNow().UtcDateTime);
await checkpoints.Accept(user,book,proof,validated);
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);
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};
}
}

View File

@ -75,6 +75,7 @@ public sealed class ParagraphManuscriptService(IParagraphManuscriptRepository re
if(state.LastRequestId==proof.RequestId)return state;
var rows=ChapterCheckpointEngine.MergeChapter(state,proof);
state.EventPositions=(await repository.Events(user,book)).ToList();
state.Evidence.RemoveAll(e=>state.EventPositions.All(a=>a.Kind!=e.EventKind||a.Id!=e.EventId));
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;

View File

@ -13,6 +13,7 @@ public static class ParagraphRecovery
if(states.Select(s=>s.BookId).Distinct().Count()!=states.Count)throw new ArgumentException("Duplicate paragraph manuscripts.");
foreach(var state in states){
if(state.Paragraphs==null||state.Scenes==null||state.Chapters==null||state.Evidence==null||state.Undo==null||state.EventPositions==null||state.Paragraphs.Any(p=>p?.Occurrence?.Text==null)||state.Scenes.Any(s=>s==null)||state.Evidence.Any(e=>e==null||e.OriginalText==null||e.ConfirmedText==null||e.CurrentText==null)||state.Chapters.Any(c=>c==null)||state.EventPositions.Any(e=>e==null)||state.Undo.Any(l=>l==null||l.Scenes==null||l.Chapters==null||l.EventPositions==null||l.Assignments==null||l.Scenes.Any(s=>s==null)||l.Chapters.Any(c=>c==null)||l.EventPositions.Any(e=>e==null)||l.Assignments.Any(a=>a==null)))throw new ArgumentException("Paragraph recovery is incomplete.");
if(state.ChapterCheckpoints==null||state.ChapterCheckpoints.Any(c=>c==null||c.Algorithm!=PlotDirector.Companion.Protocol.Manuscript.ChapterFingerprint.Version||!state.Chapters.Any(h=>h.CanonicalId==c.ChapterId&&h.HeadingId==c.HeadingId)))throw new ArgumentException("Chapter checkpoint recovery references are invalid or unsupported.");
ParagraphManuscriptEngine.Validate(state);
if(state.Evidence.Any(e=>e.State is not ("Verified" or "Needs review" or "Missing"))||state.Evidence.GroupBy(e=>(e.EventKind,e.EventId)).Any(g=>g.Count(e=>e.Primary)>1))throw new ArgumentException("Paragraph evidence state or primary passage is invalid.");
int end=0;for(int n=0;n<state.Paragraphs.Count;n++){var p=state.Paragraphs[n].Occurrence;if(p.Ordinal!=n||p.Start!=end||p.End<=p.Start||p.End>16*1024*1024)throw new ArgumentException("Paragraph positions are not contiguous.");end=p.End;}
@ -37,6 +38,8 @@ public static class ParagraphRecovery
foreach(var p in state.Paragraphs)if(p.ChapterId.HasValue)p.ChapterId=id("Chapters",p.ChapterId.Value);
foreach(var e in state.Evidence){e.EventId=EventId(e.EventKind,e.EventId);if(e.DerivedSceneId>0)e.DerivedSceneId=id("Scenes",e.DerivedSceneId.Value);}
foreach(var layout in state.Undo){Layout(layout.Scenes,layout.Chapters,layout.EventPositions);foreach(var a in layout.Assignments)if(a.ChapterId.HasValue)a.ChapterId=id("Chapters",a.ChapterId.Value);}
if(state.ChapterCheckpoints.Count>0){foreach(var checkpoint in state.ChapterCheckpoints)checkpoint.ChapterId=id("Chapters",checkpoint.ChapterId);
var historical=state.ChapterCheckpoints.ToDictionary(c=>c.ChapterId,c=>c.LastSuccessfulSyncUtc);state.ChapterCheckpoints=ChapterCheckpointEngine.Build(state,state.Revision).ToList();foreach(var checkpoint in state.ChapterCheckpoints){checkpoint.LastSuccessfulSyncUtc=historical.GetValueOrDefault(checkpoint.ChapterId);checkpoint.Status="Not yet checked";checkpoint.Message="Restored source checkpoint; this installation has not validated live Word positions.";}}
Detach(state);
}
}

View File

@ -11,6 +11,7 @@ namespace PlotLine.Services.NativeCompanion;
public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManuscriptScanPreviewStore scans,TimeProvider clock,IServiceScopeFactory scopes,IConfiguration? configuration=null,ILogger<NativeManuscriptCapture>? logger=null)
{
private sealed record Pending(int User,int Onboarding,int Project,int Book,NativeLease Lease,DateTimeOffset Expires,string? Hash=null,bool Paragraphs=false,bool Sync=false,long BaseRevision=-1,ManuscriptScanPreview? Prepared=null,ParagraphManuscript? AcceptedSnapshot=null,DateTimeOffset Created=default,DateTimeOffset HardExpires=default,string? FailureCode=null,DateTimeOffset RetainUntil=default);
public bool ParagraphEnabled=>configuration?.GetValue<bool>("Features:ParagraphManuscripts")==true;
private readonly ConcurrentDictionary<Guid,Pending> pending=new();
private readonly SemaphoreSlim acceptance=new(1,1);
public async Task<ManuscriptScanState?> Start(int user,int onboarding,int project,int book,bool paragraphs=false)
@ -38,15 +39,15 @@ public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManusc
}finally{acceptance.Release();}
}
public async Task<ParagraphPosition?> ResolveParagraphPosition(int user,int book,Guid manuscript,Guid session,long revision,int position){if(configuration?.GetValue<bool>("Features:ParagraphManuscripts")!=true)return null;using var scope=scopes.CreateScope();return await scope.ServiceProvider.GetRequiredService<PlotLine.Data.IParagraphManuscriptRepository>().Position(user,book,manuscript,session,revision,position);}
public async Task CancelParagraphSnapshot(int user,int book){using var scope=scopes.CreateScope();var status=await scope.ServiceProvider.GetRequiredService<PlotLine.Data.IParagraphManuscriptRepository>().Status(user,book);if(status?.CanWrite!=true)throw new UnauthorizedAccessException();foreach(var item in pending.Where(p=>p.Value.User==user&&p.Value.Book==book&&p.Value.Sync&&p.Value.Hash==null).ToArray()){presence.RequestCancellation(user,item.Value.Lease);await Fail(user,item.Value.Lease.Grant,item.Key);}}
public sealed record ParagraphTransfer(Guid RequestId,string State);
public async Task CancelParagraphSnapshot(int user,int book){using var scope=scopes.CreateScope();var status=await scope.ServiceProvider.GetRequiredService<PlotLine.Data.IParagraphManuscriptRepository>().Status(user,book);if(status?.CanWrite!=true)throw new UnauthorizedAccessException();presence.CancelChapterRepairs(user,book);foreach(var item in pending.Where(p=>p.Value.User==user&&p.Value.Book==book&&p.Value.Sync&&p.Value.Hash==null).ToArray()){presence.RequestCancellation(user,item.Value.Lease);await Fail(user,item.Value.Lease.Grant,item.Key);}}
public sealed record ParagraphTransfer(Guid RequestId,string State,string? Message=null,string Kind="snapshot");
public ParagraphTransfer? ParagraphTransferStatus(int user,int book,Guid instance,Guid session)
{
var latest=pending.Where(p=>p.Value.User==user&&p.Value.Book==book&&p.Value.Sync&&p.Value.Lease.Instance==instance&&p.Value.Lease.Session==session).OrderByDescending(p=>p.Value.Created).FirstOrDefault();
return latest.Value==null?null:new(latest.Key,latest.Value.Hash!=null?"accepted":latest.Value.FailureCode!=null||latest.Value.Expires<=clock.GetUtcNow()?"failed":"pending");
var chapter=presence.ChapterTransfer(user,book,instance,session);if(latest.Value==null||chapter.HasValue&&chapter.Value.Created>latest.Value.Created){return chapter.HasValue?new(chapter.Value.Id,chapter.Value.State,chapter.Value.Message,"chapter"):null;}return new(latest.Key,latest.Value.Hash!=null?"accepted":latest.Value.FailureCode!=null||latest.Value.Expires<=clock.GetUtcNow()?"failed":"pending");
}
private readonly Dictionary<(int,Guid,Guid),DateTimeOffset> autoChecks=[];
public async Task<Guid> RequestParagraphSnapshot(int user,int book,NativeLease? automatic=null,Guid? instanceId=null,Guid? sessionId=null)
public async Task<Guid> RequestParagraphSnapshot(int user,int book,NativeLease? automatic=null,Guid? instanceId=null,Guid? sessionId=null,bool fullSnapshot=false)
{
if(configuration?.GetValue<bool>("Features:ParagraphManuscripts")!=true)throw new InvalidOperationException("Paragraph tracking is not enabled.");
await acceptance.WaitAsync();try{
@ -59,6 +60,7 @@ public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManusc
var active=documents.Where(l=>l.Position.Active).ToArray();
var selected=instanceId.HasValue?documents.SingleOrDefault(l=>l.Instance==instanceId&&l.Session==sessionId)??throw new InvalidOperationException("The selected Word document is no longer connected. Select it again before synchronising."):automatic??(active.Length==1?active[0]:documents.Length==1?documents[0]:throw new InvalidOperationException("Activate the intended Word manuscript. Multiple or no eligible documents are connected."));
if(selected.Position.ManuscriptId!=status.ManuscriptId)throw new InvalidOperationException("This is a different document. Import a different manuscript into a separate book; automatic cross-document evidence matching is refused.");
if(selected.Position.CanChapterSync&&!fullSnapshot)return await scope.ServiceProvider.GetRequiredService<PlotLine.Services.Manuscript.ChapterSyncService>().Repair(user,book,selected.Instance,selected.Session);
if(pending.Values.Any(p=>p.User==user&&p.Hash==null&&p.FailureCode==null&&p.Expires>clock.GetUtcNow()))return Guid.Empty;
if(pending.Count>=128)throw new InvalidOperationException("Manuscript transfer capacity is busy.");var id=Guid.NewGuid();
pending[id]=new(user,0,0,book,selected,clock.GetUtcNow().AddMinutes(20),Paragraphs:true,Sync:true,BaseRevision:status.Revision,Created:clock.GetUtcNow(),HardExpires:clock.GetUtcNow().AddHours(4));

View File

@ -16,19 +16,28 @@ public sealed class NativePresenceStore(TimeProvider clock)
public (int Chapter,int? Scene)? Resolve(int user,NativePresence position,Guid session){lock(gate){if(position.WordSaved!=true||!position.CursorStart.HasValue||!mappings.TryGetValue((user,position.BookId,position.ManuscriptId,session,position.Revision),out var map)||position.CursorStart<0||position.CursorStart>=map.End)return null;var boundary=map.Items.LastOrDefault(i=>i.Start<=position.CursorStart);return boundary.Chapter>0?(boundary.Chapter,boundary.Scene):null;}}
public bool Put(int user,string grant,DateTimeOffset expires,Guid instance,Guid session,NativePresence value)
{
lock(gate){Prune();var key=(user,instance,session);if(instance==Guid.Empty||session==Guid.Empty||(value.WordAvailable&&value.ManuscriptId==Guid.Empty)||value.Revision<0||value.Sequence<=0||value.BookId<0||value.DocumentTitle==null||value.DocumentTitle.Length>260||value.DocumentTitle.IndexOfAny(['\\','/'])>=0||expires<=clock.GetUtcNow()||revoked.ContainsKey(grant))return false;
lock(gate){Prune();var key=(user,instance,session);if(instance==Guid.Empty||session==Guid.Empty||(value.WordAvailable&&value.ManuscriptId==Guid.Empty)||(value.ChapterIssue is not ("" or "needs_review"))||value.Revision<0||value.Sequence<=0||value.BookId<0||value.DocumentTitle==null||value.DocumentTitle.Length>260||value.DocumentTitle.IndexOfAny(['\\','/'])>=0||expires<=clock.GetUtcNow()||revoked.ContainsKey(grant))return false;
if(leases.TryGetValue(key,out var prior)){if(prior.Grant!=grant||value.Sequence<=prior.Position.Sequence||value.Revision<prior.Position.Revision)return false;}
else if(leases.Count>=4096||leases.Values.Count(p=>p.User==user)>=64)return false;
leases[key]=new(user,grant,expires,instance,session,new NativePresence{CanChapterSync=value.CanChapterSync,CaptureRequestId=value.CaptureRequestId,CaptureProgress=value.CaptureProgress,ParagraphRevision=value.ParagraphRevision,CanCapture=value.CanCapture,CanParagraphSync=value.CanParagraphSync,WordSaved=value.WordSaved,CursorStart=value.CursorStart,ManuscriptId=value.ManuscriptId,BookId=value.BookId,Revision=value.Revision,Sequence=value.Sequence,ChapterId=value.ChapterId,SceneId=value.SceneId,Active=value.Active,WordRunning=value.WordRunning,WordAvailable=value.WordAvailable,DocumentTitle=value.DocumentTitle},clock.GetUtcNow());return true;}
leases[key]=new(user,grant,expires,instance,session,new NativePresence{ChapterIssue=value.ChapterIssue,ChapterTitle=value.ChapterTitle,SceneTitle=value.SceneTitle,CanChapterSync=value.CanChapterSync,CaptureRequestId=value.CaptureRequestId,CaptureProgress=value.CaptureProgress,ParagraphRevision=value.ParagraphRevision,CanCapture=value.CanCapture,CanParagraphSync=value.CanParagraphSync,WordSaved=value.WordSaved,CursorStart=value.CursorStart,ManuscriptId=value.ManuscriptId,BookId=value.BookId,Revision=value.Revision,Sequence=value.Sequence,ChapterId=value.ChapterId,SceneId=value.SceneId,Active=value.Active,WordRunning=value.WordRunning,WordAvailable=value.WordAvailable,DocumentTitle=value.DocumentTitle},clock.GetUtcNow());return true;}
}
public NativeLease[] Read(int user,int book){lock(gate){Prune();return leases.Values.Where(p=>p.User==user&&(book==0||p.Position.BookId==book)).OrderByDescending(p=>p.Updated).ToArray();}}
public bool Navigate(int user,int book,Guid instance,Guid session,Guid manuscript,long revision,int start,bool requireSaved=false,Guid? navigationId=null)
{lock(gate){Prune();var key=(user,instance,session);if(!leases.TryGetValue(key,out var lease)||!lease.Position.WordAvailable||lease.Position.BookId!=book||lease.Position.ManuscriptId!=manuscript||lease.Position.Revision!=revision||(requireSaved&&lease.Position.WordSaved!=true)||start<0||(navigation.TryGetValue(key,out var queued)&&queued.Kind!="navigate"))return false;var id=navigationId??Guid.NewGuid();if(id==Guid.Empty)return false;var receipt=(user,instance,session,id);if(navigationReceipts.TryGetValue(receipt,out var prior))return prior.Revision==revision&&prior.Start==start;if(navigationReceipts.Count>=8192)return false;navigationReceipts[receipt]=(clock.GetUtcNow().AddMinutes(15),revision,start);navigation[key]=new(){Id=id,Kind="navigate",SessionId=session,Revision=revision,Chapter=new(){Start=start}};return true;}}
public void RequestCancellation(int user,NativeLease selected){lock(gate){var key=(user,selected.Instance,selected.Session);if(leases.TryGetValue(key,out var current)&&current.Grant==selected.Grant&&current.Position.Revision==selected.Position.Revision)navigation[key]=new(){Kind="cancel",SessionId=selected.Session,Revision=selected.Position.Revision};}}
private readonly Dictionary<Guid,(int User,int Book,Guid Instance,Guid Session,long Revision,DateTimeOffset Expires)> chapterRepairs=[];
private readonly Dictionary<Guid,(int User,int Book,Guid Instance,Guid Session,long Revision,string Grant,DateTimeOffset Expires)> chapterRepairs=[];private readonly HashSet<Guid> cancelledChapterRepairs=[];
private readonly Dictionary<(int User,int Book,Guid Instance,Guid Session,long Revision),PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress> chapterProgress=[];
private readonly Dictionary<(int User,int Book,Guid Instance,Guid Session,long Revision),HashSet<int>> repairedChapters=[];
public void RecordChapterRepair(int user,int book,Guid instance,Guid session,long revision,int chapter){lock(gate){if(repairedChapters.Count>=4096)repairedChapters.Clear();var key=(user,book,instance,session,revision);if(!repairedChapters.TryGetValue(key,out var chapters))repairedChapters[key]=chapters=[];chapters.Add(chapter);}}
public int RepairedChapters(int user,int book,Guid instance,Guid session,long revision){lock(gate)return repairedChapters.GetValueOrDefault((user,book,instance,session,revision))?.Count??0;}
public void RecordChapterProgress(int user,int book,Guid instance,Guid session,long revision,PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress progress){lock(gate){if(chapterProgress.Count>=4096)chapterProgress.Clear();chapterProgress[(user,book,instance,session,revision)]=progress;}}
public PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress? ChapterProgress(int user,int book,Guid instance,Guid session,long revision){lock(gate)return chapterProgress.GetValueOrDefault((user,book,instance,session,revision));}
public (Guid Id,string State,string Message,DateTimeOffset Created)? ChapterTransfer(int user,int book,Guid instance,Guid session)
{lock(gate){var operation=chapterRepairs.Where(p=>p.Value.User==user&&p.Value.Book==book&&p.Value.Instance==instance&&p.Value.Session==session&&p.Value.Expires>clock.GetUtcNow()).LastOrDefault();if(operation.Key==Guid.Empty)return null;if(cancelledChapterRepairs.Contains(operation.Key))return(operation.Key,"needs-review","Chapter repair cancelled. Successfully accepted checkpoints are retained.",operation.Value.Expires.AddMinutes(-30));var progress=ChapterProgress(user,book,instance,session,operation.Value.Revision);return(operation.Key,progress?.State=="Synchronised"?"accepted":progress?.State is "Needs review" or "Cancelled"?"needs-review":"pending",progress?.Message??"Checking chapters. Previously accepted checkpoints are preserved.",operation.Value.Expires.AddMinutes(-30));}}
public void CancelChapterRepairs(int user,int book){lock(gate){foreach(var item in chapterRepairs.Where(p=>p.Value.User==user&&p.Value.Book==book).ToArray()){var op=item.Value;var key=(user,op.Instance,op.Session);if(leases.TryGetValue(key,out var lease)&&lease.Position.Revision==op.Revision)navigation[key]=new(){Kind="cancel",SessionId=op.Session,Revision=op.Revision};RecordChapterProgress(user,book,op.Instance,op.Session,op.Revision,new(){State="Cancelled",Message="Chapter repair cancelled. Successfully accepted checkpoints are retained."});cancelledChapterRepairs.Add(item.Key);}}}
public bool RequestChapterRepair(int user,NativeLease selected,Guid id)
{lock(gate){Prune();foreach(var old in chapterRepairs.Where(p=>p.Value.Expires<=clock.GetUtcNow()).Select(p=>p.Key).ToArray())chapterRepairs.Remove(old);var key=(user,selected.Instance,selected.Session);if(chapterRepairs.Count>=128||!leases.TryGetValue(key,out var current)||current.Grant!=selected.Grant||!current.Position.CanChapterSync||current.Position.WordSaved!=true||current.Position.Revision!=selected.Position.Revision||navigation.ContainsKey(key))return false;chapterRepairs[id]=(user,selected.Position.BookId,selected.Instance,selected.Session,selected.Position.Revision,clock.GetUtcNow().AddMinutes(30));navigation[key]=new(){Id=id,Kind="chapter-repair",BookId=selected.Position.BookId,SessionId=selected.Session,Revision=selected.Position.Revision};return true;}}
public bool CanRepairChapter(int user,NativeLease lease,Guid id){lock(gate)return chapterRepairs.TryGetValue(id,out var repair)&&repair.User==user&&repair.Book==lease.Position.BookId&&repair.Instance==lease.Instance&&repair.Session==lease.Session&&repair.Revision==lease.Position.Revision&&repair.Expires>clock.GetUtcNow();}
{lock(gate){Prune();foreach(var old in chapterRepairs.Where(p=>p.Value.Expires<=clock.GetUtcNow()).Select(p=>p.Key).ToArray()){chapterRepairs.Remove(old);cancelledChapterRepairs.Remove(old);}var key=(user,selected.Instance,selected.Session);if(chapterRepairs.Count>=128||!leases.TryGetValue(key,out var current)||current.Grant!=selected.Grant||!current.Position.CanChapterSync||current.Position.WordSaved!=true||current.Position.Revision!=selected.Position.Revision||navigation.ContainsKey(key))return false;chapterRepairs[id]=(user,selected.Position.BookId,selected.Instance,selected.Session,selected.Position.Revision,selected.Grant,clock.GetUtcNow().AddMinutes(30));RecordChapterProgress(user,selected.Position.BookId,selected.Instance,selected.Session,selected.Position.Revision,new(){State="Checking",Message="Chapter repair requested; awaiting fresh server acceptance. Existing accepted checkpoints are retained."});navigation[key]=new(){Id=id,Kind="chapter-repair",BookId=selected.Position.BookId,SessionId=selected.Session,Revision=selected.Position.Revision};return true;}}
public bool CanRepairChapter(int user,NativeLease lease,Guid id){lock(gate)return !cancelledChapterRepairs.Contains(id)&&chapterRepairs.TryGetValue(id,out var repair)&&repair.Grant==lease.Grant&&repair.User==user&&repair.Book==lease.Position.BookId&&repair.Instance==lease.Instance&&repair.Session==lease.Session&&repair.Revision==lease.Position.Revision&&repair.Expires>clock.GetUtcNow();}
public bool RequestCapture(int user,NativeLease selected,Guid request,int book=0,bool paragraphs=false,bool synchronise=false,long baseRevision=0,string baseHash="")
{lock(gate){Prune();var key=(user,selected.Instance,selected.Session);if(!leases.TryGetValue(key,out var lease)||lease.Grant!=selected.Grant||lease.Position.Revision!=selected.Position.Revision||lease.Position.ManuscriptId!=selected.Position.ManuscriptId||(book>0&&lease.Position.BookId!=0&&lease.Position.BookId!=book)||!lease.Position.CanCapture||navigation.ContainsKey(key))return false;navigation[key]=new(){Id=request,BaseRevision=baseRevision,BaseSnapshotHash=baseHash,BookId=book,ParagraphTracking=paragraphs,Kind=synchronise?"paragraph-snapshot":"wizard-capture",SessionId=lease.Session,Revision=lease.Position.Revision};return true;}}
public AdapterCommand? TakeNavigation(int user,string grant,Guid instance,Guid session)

View File

@ -7,19 +7,31 @@ IF OBJECT_ID('dbo.BookChapterValidations','U') IS NULL
RequestID uniqueidentifier NOT NULL,ContentHash char(64) NOT NULL,IdentityHash char(64) NOT NULL,MappingHash char(64) NOT NULL,Positions nvarchar(max) NOT NULL,
SourceRevision bigint NOT NULL,ValidatedUtc datetime2 NOT NULL,ExpiresUtc datetime2 NOT NULL,
CONSTRAINT PK_BookChapterValidations PRIMARY KEY(BookID,ChapterID,UserID,SessionID),
CONSTRAINT FK_BookChapterValidations_Book FOREIGN KEY(BookID) REFERENCES dbo.Books(BookID) ON DELETE CASCADE,
CONSTRAINT FK_BookChapterValidations_Book FOREIGN KEY(BookID) REFERENCES dbo.BookParagraphManuscripts(BookID) ON DELETE CASCADE,
CONSTRAINT CK_BookChapterValidations_Json CHECK(ISJSON(Positions)=1));
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
@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
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 FROM dbo.BookChapterValidations WHERE BookID=@BookID AND UserID=@UserID AND SessionID=@SessionID AND WordRevision=@WordRevision AND ExpiresUtc>SYSUTCDATETIME();RETURN;END;
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
@ -34,9 +46,24 @@ BEGIN
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;
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 ISJSON(@Checkpoint)<>1 OR ISJSON(@Positions)<>1 OR ISJSON(@Bindings)<>1 OR DATALENGTH(@Positions)>4*1024*1024 OR DATALENGTH(@Checkpoint)>16384 OR @SessionID IS NULL OR @RequestID IS NULL OR @WordRevision<0 THROW 51000,'Invalid chapter validation',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;
@ -55,13 +82,18 @@ BEGIN
FETCH NEXT FROM bind INTO @Paragraph,@Native;
END;
CLOSE bind;DEALLOCATE bind;
IF EXISTS(SELECT 1 FROM OPENJSON(@Positions) WITH(ParagraphId uniqueidentifier,ChapterId int) p WHERE p.ChapterId<>@ChapterID OR NOT EXISTS(SELECT 1 FROM OPENJSON(@Payload,'$.Paragraphs') a WHERE TRY_CONVERT(uniqueidentifier,JSON_VALUE(a.value,'$.Occurrence.Id'))=p.ParagraphId)) THROW 51000,'Chapter position refers to an unknown paragraph',1;
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 OPENJSON(@Payload,'$.Paragraphs') a WHERE TRY_CONVERT(uniqueidentifier,JSON_VALUE(a.value,'$.Occurrence.Id'))=p.ParagraphId AND TRY_CONVERT(int,JSON_VALUE(a.value,'$.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));
IF EXISTS(SELECT 1 FROM dbo.BookChapterValidations WHERE BookID=@BookID AND ChapterID=@ChapterID AND UserID=@UserID AND SessionID=@SessionID AND WordRevision=@WordRevision AND (Positions<>@Positions OR ContentHash<>JSON_VALUE(@Checkpoint,'$.ContentHash') OR IdentityHash<>JSON_VALUE(@Checkpoint,'$.IdentityHash'))) THROW 51000,'Conflicting evidence for the same live Word revision',1;
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();

View File

@ -0,0 +1,98 @@
-- Forward repair: a duplicate or ambiguous live chapter cannot retain trusted positions.
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
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 @Native nvarchar(8),@Paragraph uniqueidentifier,@Index int,@Existing nvarchar(16);
DECLARE bind CURSOR LOCAL FAST_FORWARD FOR SELECT ParagraphId,NativeId FROM OPENJSON(@Bindings) WITH(ParagraphId uniqueidentifier,NativeId nvarchar(8));
OPEN bind;FETCH NEXT FROM bind INTO @Paragraph,@Native;
WHILE @@FETCH_STATUS=0
BEGIN
SET @Index=NULL;SET @Existing=NULL;
SELECT @Index=CONVERT(int,j.[key]),@Existing=JSON_VALUE(j.value,'$.Occurrence.NativeId') FROM OPENJSON(@Payload,'$.Paragraphs') j WHERE TRY_CONVERT(uniqueidentifier,JSON_VALUE(j.value,'$.Occurrence.Id'))=@Paragraph;
IF @Index IS NULL OR COALESCE(@Existing,'') NOT IN ('',@Native) OR LEN(@Native)<>8 OR @Native LIKE '%[^0-9A-F]%' THROW 51000,'Native identity adoption conflicts with existing evidence',1;
SET @Payload=JSON_MODIFY(@Payload,CONCAT('$.Paragraphs[',@Index,'].Occurrence.NativeId'),@Native);
FETCH NEXT FROM bind INTO @Paragraph,@Native;
END;
CLOSE bind;DEALLOCATE bind;
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 OPENJSON(@Payload,'$.Paragraphs') a WHERE TRY_CONVERT(uniqueidentifier,JSON_VALUE(a.value,'$.Occurrence.Id'))=p.ParagraphId AND TRY_CONVERT(int,JSON_VALUE(a.value,'$.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,102 @@
-- Forward repair: native-ID adoption also updates the existing full-snapshot digest.
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 @Native nvarchar(8),@Paragraph uniqueidentifier,@Index int,@Existing nvarchar(16);
DECLARE bind CURSOR LOCAL FAST_FORWARD FOR SELECT ParagraphId,NativeId FROM OPENJSON(@Bindings) WITH(ParagraphId uniqueidentifier,NativeId nvarchar(8));
OPEN bind;FETCH NEXT FROM bind INTO @Paragraph,@Native;
WHILE @@FETCH_STATUS=0
BEGIN
SET @Index=NULL;SET @Existing=NULL;
SELECT @Index=CONVERT(int,j.[key]),@Existing=JSON_VALUE(j.value,'$.Occurrence.NativeId') FROM OPENJSON(@Payload,'$.Paragraphs') j WHERE TRY_CONVERT(uniqueidentifier,JSON_VALUE(j.value,'$.Occurrence.Id'))=@Paragraph;
IF @Index IS NULL OR COALESCE(@Existing,'') NOT IN ('',@Native) OR LEN(@Native)<>8 OR @Native LIKE '%[^0-9A-F]%' THROW 51000,'Native identity adoption conflicts with existing evidence',1;
SET @Payload=JSON_MODIFY(@Payload,CONCAT('$.Paragraphs[',@Index,'].Occurrence.NativeId'),@Native);
FETCH NEXT FROM bind INTO @Paragraph,@Native;
END;
CLOSE bind;DEALLOCATE bind;
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 OPENJSON(@Payload,'$.Paragraphs') a WHERE TRY_CONVERT(uniqueidentifier,JSON_VALUE(a.value,'$.Occurrence.Id'))=p.ParagraphId AND TRY_CONVERT(int,JSON_VALUE(a.value,'$.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

@ -21,9 +21,14 @@
<form asp-action="Enable" method="post" class="d-flex flex-wrap gap-2 align-items-end"><input name="bookId" type="hidden" value="@state.BookId"/>
<label>Synchronisation <select name="mode" class="form-select"><option value="Manual" selected="@(state.Mode=="Manual")">Only when requested</option><option value="OnSave" selected="@(state.Mode=="OnSave")">After Word saves or reconnects</option><option value="Off" selected="@(state.Mode=="Off")">Off</option></select></label><button class="btn btn-outline-primary">Save preference</button></form>
<p class="small mt-2">Save/reconnect mode explicitly permits manuscript updates from this book's associated Word document. Only changed prose is transmitted when the agent has a matching snapshot. It never starts AI analysis.</p>
<div class="d-flex gap-2 flex-wrap"><form asp-action="Snapshot" method="post"><input name="bookId" type="hidden" value="@state.BookId"/><button class="btn btn-primary">Synchronise from Word</button></form><form asp-action="Cancel" method="post"><input name="bookId" type="hidden" value="@state.BookId"/><button class="btn btn-outline-secondary">Cancel pending snapshot</button></form><a class="btn btn-outline-secondary" asp-action="Index" asp-route-bookId="@state.BookId" asp-route-page="@currentPage">Refresh saved snapshot</a></div>
<div class="d-flex gap-2 flex-wrap"><form asp-action="Repair" method="post"><input name="bookId" type="hidden" value="@state.BookId"/><button class="btn btn-outline-primary">Repair Manuscript Synchronisation</button></form><form asp-action="Snapshot" method="post"><input name="bookId" type="hidden" value="@state.BookId"/><button class="btn btn-primary">Synchronise from Word</button></form><form asp-action="Cancel" method="post"><input name="bookId" type="hidden" value="@state.BookId"/><button class="btn btn-outline-secondary">Cancel pending snapshot</button></form><a class="btn btn-outline-secondary" asp-action="Index" asp-route-bookId="@state.BookId" asp-route-page="@currentPage">Refresh saved snapshot</a></div>
<details class="mt-2"><summary>Full snapshot fallback</summary><p class="small">For content which cannot be validated chapter by chapter, the existing bounded full reader is available. Large manuscripts can take substantially longer. It never reimports the book or reruns AI.</p><form asp-action="Snapshot" method="post"><input type="hidden" name="bookId" value="@state.BookId"/><input type="hidden" name="fullSnapshot" value="true"/><button class="btn btn-outline-secondary">Read full snapshot from Word</button></form></details>
<p class="small mt-2">A different Word manuscript must be imported into a separate book. This preview never guesses evidence identity across documents.</p>
</div>
<details class="card p-3 mb-3"><summary>Accepted chapter checkpoints</summary>
<p class="small">These are saved evidence checkpoints, not proof that the current Word session is connected. Live session validation appears in the Word connection dialog. Older imports acquire checkpoints through verified repair; they do not need to be reimported.</p>
@if(state.ChapterCheckpoints.Count==0){<p>No chapter checkpoints have been adopted yet.</p>}else{<div class="table-responsive"><table class="table"><thead><tr><th>Chapter</th><th>Paragraphs</th><th>Last accepted</th><th>State</th></tr></thead><tbody>@foreach(var checkpoint in state.ChapterCheckpoints.OrderBy(c=>c.Order)){<tr><td>@(state.Chapters.FirstOrDefault(c=>c.CanonicalId==checkpoint.ChapterId)?.Title??"Saved chapter")</td><td>@checkpoint.ParagraphCount</td><td>@(checkpoint.LastSuccessfulSyncUtc!=DateTime.MinValue?checkpoint.LastSuccessfulSyncUtc.ToString("u"):"Not yet accepted")</td><td>@checkpoint.Status<div class="small">@checkpoint.Message</div></td></tr>}</tbody></table></div>}
</details>
<div class="card p-3 mb-3"><h2>Scenes</h2><p>Split at a paragraph or move a boundary using the paragraph list. Move prose and reorder scenes in Word, then synchronise.</p>
<form asp-action="Change" method="post"><input name="bookId" type="hidden" value="@state.BookId"/><input name="revision" type="hidden" value="@state.Revision"/><input name="action" type="hidden" value="undo"/><button class="btn btn-outline-secondary" disabled="@(state.Undo.Count==0)">Undo last structure change</button></form>
@foreach(var scene in current){var sceneIndex=Array.IndexOf(current,scene);var adjacent=sceneIndex+1<current.Length?current[sceneIndex+1]:null;<details class="mt-2"><summary>@scene.Title @if(scene.NeedsRefinement){<span class="badge text-bg-warning">Needs refinement</span>}</summary><p>@state.Paragraphs.Count(p=>p.SceneId==scene.Id) paragraphs</p>

View File

@ -11,6 +11,7 @@
@Html.AntiForgeryToken()
<input type="hidden" name="bookId" data-word-sync-book />
<button type="submit" class="btn btn-primary" data-word-sync-button disabled>Synchronise from Word</button>
<button type="submit" class="btn btn-outline-primary mt-2" data-word-repair-button formaction="/manuscript/paragraphs/repair" disabled>Repair Manuscript Synchronisation</button>
<p class="small mt-2 mb-0" data-word-sync-feedback role="status">Select a connected, saved manuscript to refresh its paragraph positions. Word prose is never rewritten and AI analysis is not started.</p>
</form>
<p data-word-connection-diagnostics class="small text-muted"></p>

View File

@ -9,7 +9,7 @@
const selected=syncCurrent;syncPending={key:selected.instanceId+'/'+selected.sessionId,revision:selected.snapshotRevision||0,started:Date.now()};syncButton.disabled=true;
syncFeedback.textContent='Requesting a saved paragraph snapshot from Word…';
const body=new URLSearchParams(new FormData(syncForm));body.set('instanceId',selected.instanceId);body.set('sessionId',selected.sessionId);
try{const response=await fetch(syncForm.action,{method:'POST',body,headers:{'X-Requested-With':'XMLHttpRequest'},signal:AbortSignal.timeout(15000)});
try{const response=await fetch((event.submitter?.hasAttribute('formaction')?event.submitter.formAction:syncForm.action),{method:'POST',body,headers:{'X-Requested-With':'XMLHttpRequest'},signal:AbortSignal.timeout(15000)});
if(response.redirected||!response.headers.get('content-type')?.includes('application/json'))throw Error('Sign in to PlotDirector again before requesting synchronisation.');
const result=await response.json();if(!response.ok)throw Error(result.message||'Synchronisation could not be requested.');syncFeedback.textContent=result.message;if(syncPending)syncPending.requestId=result.requestId&&result.requestId!=='00000000-0000-0000-0000-000000000000'?result.requestId:null;if(!syncPending?.requestId){syncPending=null;syncButton.disabled=false;}void update();
}catch(error){syncPending=null;syncButton.disabled=false;syncFeedback.textContent=error.message||'Could not contact PlotDirector. Your saved manuscript is unchanged.';}
@ -30,14 +30,16 @@
details.querySelector('[data-word-document-picker]')?.toggleAttribute('hidden',!workspace);
const activeInScope=selectable.filter(l=>l.active),selection=documents.value?selectable.find(l=>l.instanceId+'/'+l.sessionId===documents.value):activeInScope.length===1?activeInScope[0]:selectable.length===1?selectable[0]:null;
const returnButton=details.querySelector('[data-word-return-to-current]');if(returnButton)returnButton.disabled=!selection?.sceneId||selection.wordSaved===false;
const repairButton=details.querySelector('[data-word-repair-button]');if(repairButton)repairButton.disabled=!!syncPending||!selection?.bookId||selection.wordSaved!==true||selection.canChapterSync!==true;
syncCurrent=selection;
if(syncForm){syncForm.querySelector('[data-word-sync-book]').value=selection?.bookId||'';syncButton.disabled=!!syncPending||!selection?.bookId||selection.wordSaved!==true||selection.canParagraphSync!==true;
if(syncPending){const observed=selectable.find(l=>l.instanceId+'/'+l.sessionId===syncPending.key);
if(observed?.mappingCurrent&&Number(observed.snapshotRevision)>syncPending.revision&&observed.paragraphTransfer?.requestId===syncPending.requestId&&observed.paragraphTransfer.state==='accepted'){syncPending=null;syncButton.disabled=!selection?.bookId||selection.wordSaved!==true||selection.canParagraphSync!==true;syncFeedback.textContent='Word snapshot accepted. This session’s paragraph positions are verified; current scene following can resume.';}
if(observed?.paragraphTransfer?.requestId===syncPending.requestId&&observed.paragraphTransfer.state==='accepted'&&(observed.paragraphTransfer.kind==='chapter'||observed.mappingCurrent&&Number(observed.snapshotRevision)>syncPending.revision)){syncPending=null;syncButton.disabled=!selection?.bookId||selection.wordSaved!==true||selection.canParagraphSync!==true;syncFeedback.textContent=observed.paragraphTransfer.message||'Word snapshot accepted. This session’s paragraph positions are verified; current scene following can resume.';}
else if(observed?.paragraphTransfer?.requestId===syncPending.requestId&&observed.paragraphTransfer.kind==='chapter'){syncFeedback.textContent=observed.paragraphTransfer.message;if(observed.paragraphTransfer.state==='needs-review'){syncPending=null;syncButton.disabled=false;}}
else if(syncPending.requestId&&(!observed||observed.paragraphTransfer?.requestId!==syncPending.requestId||observed.paragraphTransfer.state==='failed')){syncPending=null;syncButton.disabled=!selection?.bookId||selection.wordSaved!==true||selection.canParagraphSync!==true;syncFeedback.textContent='Word transfer ended without an accepted snapshot. Saved paragraphs are unchanged. Check Companion Troubleshooting, then retry.';}
else if(observed?.captureRequestId)syncFeedback.textContent='Reading Word: '+Math.max(0,Math.min(100,Number(observed.captureProgress)||0))+'%. Keep Word open until PlotDirector acknowledges the snapshot.';
else if(Date.now()-syncPending.started>120000){syncPending=null;syncButton.disabled=false;syncFeedback.textContent='No accepted snapshot has been confirmed. Open Manuscript structure and evidence below or Companion Troubleshooting before retrying.';}
}else if(!selection)syncFeedback.textContent='Open the intended manuscript in Word and select its current connection. Saved scene browsing remains available.';
}else if(selection?.chapterProgress){const progress=selection.chapterProgress;syncFeedback.textContent=progress.state+' · '+progress.matching+'/'+progress.total+' chapter mappings accepted. '+progress.message;}else if(!selection)syncFeedback.textContent='Open the intended manuscript in Word and select its current connection. Saved scene browsing remains available.';
else if(selection.wordSaved!==true)syncFeedback.textContent='Save the manuscript in Word before requesting synchronisation.';
else if(selection.canParagraphSync!==true)syncFeedback.textContent='The connected add-in has not advertised paragraph synchronisation. Check the installed Companion and Word connection.';
}