PlotDirector/Docs/WordCompanion/2026-11-09-chapter-sync-implementation.md

12 KiB
Raw Blame History

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.

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, 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.

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.