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

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

Final source and running Development

  • Foundation: e6e2a33; integrated pipeline: 59e17df43f470da64b91a90700e4c3703c76ddf7; final executable source: f171d8b1969b343eb1fbc28f9402acfd51624d21. The final boundary tests include a last chapter moved earlier and existing block content controls; the agent has at most two in-flight parse/network operations, with no waiting work queue. Final focused engine count is 31, agent protocol 110, paragraph/recovery/workflow 54, Context navigation 30, and actual Development repository/SP assertions 10. The full 455 application and 271 native foundation runs passed earlier in this sequence; final focused gates cover the subsequent edge-case changes.
  • Deployed Development release: /srv/apps/plotdirector-dev/releases/f171d8b-20261109T123348Z. Physical previous-current backup: /srv/apps/plotdirector-dev/current-before-f171d8b-20261109T123348Z. Normal protected-job idle guard passed before restart and afterwards. Production, Windows installation and configuration were untouched.
  • Published/deployed PlotLine.dll SHA-256 both 66380b81bc5beaf656d250662ff4978655bc05cac7d763c84bab1227f66ab309. Service active; actual local GET and public TLS-validated HTTPS GET both 200. Authenticated changed API and recovery routes were exercised, not just the homepage.
  • Actual Development bearer pairing/authorisation and presence test on disposable book 10159: new live session initially has no trusted scene; unchanged proofs for both chapters are committed, retries are idempotent, cursor positions resolve to the correct canonical scenes, no automatic full capture/navigation is issued, and finish reports server-confirmed synchronisation. Conflicting same-revision positions and stale snapshot revisions are refused.
  • Manual-mode changed chapter initially returns Changed with no prose permission. Explicit repair queues one existing exact-session command. Only the changed chapter body is submitted; the existing engine increments one coherent snapshot revision and preserves every original paragraph GUID. The unchanged later chapter accepts its shifted physical positions and resolves its own scene. Finish reports Synchronised with one repaired chapter.
  • Real author-facing backup download → upload → validation → preview → explicit confirmation → transactional restore into a new project → re-export passed. Actual restored records retain checkpoint text hashes, paragraph/native IDs, exact edited prose and scene GUIDs; local canonical chapter IDs are remapped, checkpoint status is Not yet checked and the live session GUID is empty. No restore-point replacement or author project was used.
  • Browser/chapter-sync-development.cjs and ChapterSyncDevelopmentTests.cs retain the repeatable guarded procedures. Both synthetic accounts, original fixture books (10158/10159), restored fixture and associated data were removed using normal cleanup. Private credential files were deleted. No test touched book 10151 or used 10152 as a mutation fixture.
  • Final read-only comparison confirms book 10152 still has the identical accepted payload SHA-256, revision and payload length, 48 chapters /290 scenes. Its paragraph identities, saved mappings/evidence and completed analysis were not rewritten or reimported by this task.

Remaining qualification and observed warning

Windows qualification is required before accepting performance or compatibility. Atlas did not compile/execute the Office VSTO host, measure real COM/UI occupancy, sign/package/install the candidate or test visual ribbon behaviour. .22 remains installed and uses the compatible existing full-reader path. The fast chapter path requires both .23 candidate components. Follow the exact Windows instructions, starting with synthetic documents and the read-only benchmark. No PowerShell runtime is installed on Atlas, so the COM benchmark script is prepared/reviewed, not claimed executed or parsed here.

Current conservative limitations: Heading 1 boundaries and exact supported XML/native IDs are required; headingless, oversized or complex content requires review/explicit full fallback. New/deleted/moved chapter structure is not silently applied to canonical chapter order. A validated chapter establishes its own physical ranges; full-book completion is withheld until the recognised chapter set/order is checked. Saved DOCX hashing is investigated but not used as a substitute for live evidence. Repair permissions are ephemeral; after a server restart changed-prose repair requires a fresh explicit request, while durable accepted chapters survive. Repaired counters describe the current server process/session; persisted checkpoint acceptance and timestamps remain authoritative after restart.

During the synthetic restore at 12:34:13 UTC, idle PersistedStoryIntelligenceWorker claim loops briefly logged SQL 650 (READPAST requires READ COMMITTED/REPEATABLE READ). The restore itself committed and passed record-level re-export verification. No author import/analysis was queued/running; normal idle guards passed afterwards. No further warning/error entries appeared after 12:34:20 UTC in the final observation window. The precise ambient/pooled isolation interaction is not established by this sprint and no Story Intelligence code/jobs were changed. This is a separate follow-up finding, not a passed SI runtime test or a reason to alter completed author analysis.