PlotDirector/Docs/Writer/Writer-Phase3B-Word-Companion-Integration-Audit.md

54 KiB
Raw Blame History

Writer Phase 3B — Word Companion integration audit

Audit date: 20 November 2026 (Europe/London). Source baseline: 00f5b96, shared branch codex/word-companion-native-phase1-20261104. This is an investigation and implementation plan, not an implementation release.

1. Executive summary

The integration is substantially implemented. The shortest safe route is a small correctness pass followed by qualification of the existing system, rather than another integration build.

An important programme correction: the previous Phase3B report already records verified Writer status, chapter/scene handoff and native acknowledgements. Phase3C subsequently integrated the accepted Reader and paragraph handoff into Review. The current Global Focus correction supplies coordinated Review positioning. Historical statements that these capabilities are absent are superseded. This audit checks their current implementation and remaining gaps.

The current architecture correctly separates Word content, accepted server content, live position verification, Global Narrative Focus, saved objectives, sessions and local reading positions. Writer does not require a new editor, sync service, identity scheme or focus architecture. Saved objectives retain their own targets. Unsaved Word prose is deliberately not accepted or treated as a verified navigation map.

Two concrete correctness gaps merit attention:

  • F1, P1 (browser-reproduced): Review's same-chapter chapter-only/unmapped-scene focus fallback can retain the previously selected passage and its scene context. The visible fallback and the annotation/Word target can consequently disagree. This does not manufacture a verified association, but can leave the author acting on an unintended existing one.
  • F2, P1: The older native AI-review navigation route reuses stored numeric offsets without checking that the review was captured in the selected document session or revalidating its content. Reopened documents can reuse numeric Word revision values. Exact live command routing alone cannot prove that a historical offset still identifies the suggested passage. This is a confirmed missing guard; a physical wrong-passage incident is not established.

No confirmed lost edits, manuscript corruption, cross-author access or wrong-document execution was established. P0 consequences must not be presented as observed events. Additional P2 reliability risks concern stalled Word UI observations, multiple-document selection recovery and physical qualification. Existing freshness wording is appropriately cautious; a connection indicator is not proof of current prose.

Audit boundary: no application code, SQL, schema, author data, Word document, configuration or deployment changed. Only this report is committed. No live database was queried. SQL observations below describe checked-in procedure definitions, not the installed schema or runtime feature flags. The pre-existing untracked Docs/Investigations/CanonicalManuscriptArchitectureAssessment.md was left untouched.

2. Evidence method and vocabulary

Current source is the primary evidence. Existing reports support chronology and historical measurements. Automated managed/fixture checks establish their specific contracts; they do not establish physical Word behaviour. “Verified” below always states whether verification is automated or physical.

Classification Meaning here
Implemented and verified Current implementation plus automated evidence for the named contract; no implied physical acceptance
Implemented, insufficiently verified Source exists, but this environment cannot establish the required end-to-end result
Partial A useful path exists with a specific missing contract
Missing No implementation for the stated outcome was found on the traced path
Superseded Historical limitation/approach no longer describes the current path

Targeted inspection covered Writer routes/views/scripts, native status/presence/capture/chapter APIs, manuscript reader/reconciliation/persistence, native protocol/client/agent/VSTO execution, Focus and objective services, relevant SQL definitions, regression fixtures and Windows reports. No inference about current installed Windows binaries or Development freshness is made from source version alone.

3. Architecture, communication and authority

Component Current responsibility and persistence Evidence
Browser/PWA MVC/Razor Writer, planning, reading and annotations; cookie-authenticated requests, antiforgery writes, SignalR invalidations and status fallback. PWA installation adds no offline data store application shell, service worker
Writer workspace Composes independent working focus, objective, intention, session and review contexts. Word widget selects a live document and asks the server to resolve explicit targets WriterController, WriterContext, WriterWordService
VSTO add-in Owns Word COM access on its UI thread, ribbon, document observations and bounded reads. Executes explicit range selection after checking command identity/revision/expiry/saved state WordAdapter, WordChapterRead, scheduler
Windows agent Per-user process; account/server binding, async HTTPS, session routing, chapter work, fingerprint/reuse/reconciliation coordination, retries and diagnostics. Does not directly read Word COM TrayCoordinator, chapter coordinator, SessionManager
Manuscript synchronisation Server authorises exact leases, validates hashes/identities/boundaries and expected accepted revisions; reconciles authorised changed chapters through existing engine ChapterSyncService, ParagraphManuscriptService, NativeManuscriptCapture
Captured source Durable import preview/capture and associated source provenance. Capturing is not equivalent to completing the canonical build or accepting every later edit ManuscriptCaptureRepository, capture service
Canonical accepted manuscript BookParagraphManuscripts: manuscript GUID, accepted revision/request ID, JSON paragraph/chapter/scene/evidence/checkpoint payload, timestamp. Dapper/stored procedures preserve optimistic revisions and idempotency; activity append shares the save transaction ParagraphManuscriptRepository, foundation SQL
Live verification BookChapterValidations stores session/Word-revision-specific positions, hashes and expiry. Accepted durable checkpoints and live verification are separate; later SQL materialises position intervals chapter repository, current interval procedure, reuse proof guards
Global Narrative Focus Authorised, versioned author/book working context with recent history and canonical stepping, persisted through NarrativeFocus_* procedures service, focus SQL, client

Separate information authorities

  1. Actual manuscript: Word's in-memory document, including unsaved edits; Word owns saving. PlotDirector is not a second prose editor.
  2. Captured canonical content: PlotDirector's last committed accepted snapshot, not a live mirror of every Word keystroke. Initial capture/preview is a separate earlier state.
  3. Accepted/verified content: Accepted prose remains readable when Word is absent. A currently verified physical position additionally needs live document/session/revision and checkpoint proof. Acceptance is not blanket literary approval of prose or every scene boundary.
  4. Global Focus: Author's selected working chapter/scene. Explicit actions update its version/history; passive Word presence does not.
  5. Word position: Actual cursor/range in a particular Word document, observed through VSTO. Server-resolved chapter/scene labels are conditional evidence, not Global Focus.
  6. Objectives/intentions: Objectives persist chapter, scene, activity and intention through dbo.WriterObjective; canonical chapter/scene intentions have their own authoring saves. Neither is rewritten by a focus change or Word heartbeat.
  7. Reader/Review: Displayed accepted chapter, selected paragraph/range and scroll/pause state are local. Focus-following can deliberately align them; pinned/exploration/session targets retain their own contracts.

Transport and identifiers

VSTO ↔ agent uses framed, bounded, value-only named-pipe messages. WordInstanceId identifies a process; SessionId identifies an open document lifetime; ManuscriptId identifies manuscript provenance. Sequence numbers and monotonic revisions reject stale traffic. Word revision is not a globally durable content version. Reopening creates another session and can restart its revision counter.

Document recognition reads owned properties including PlotDirector.Native.DocumentGuid, book/project/server values and the newer association property. DocumentBinding validates association values. Binding is also remembered in account/site-scoped agent state; a title or filename is not sufficient ownership evidence. Copies/Save As retaining properties remain a qualification case.

Agent ↔ server uses bearer-authenticated HTTPS under /api/native-companion: installation/pairing/renewal, books, per-instance/per-document presence, capture, and /books/{book}/chapter-sync manifest/validate/reuse/repair/finish. Persistent authorisation, CloudGateway authorisation and state store retain server/account isolation and protected Windows credential storage.

Browser status uses /native-companion/status?writerBookId=…&writerChapterId=…, /native-companion/connection-state and /hubs/native-companion. Metadata and verified positions extend the existing status response; legacy callers retain the array response. Browser handoff uses /WriterWord/Availability, POST /WriterWord/Navigate, then /WriterWord/Navigation. Navigation UUID, grant, book, manuscript, instance/session, Word revision and expiry correlate delivery and acknowledgement. Successful queueing is HTTP 202, not completion.

4. End-to-end connection lifecycle

Primary evidence: AgentLink, PipeHost, WordAdapter, TrayCoordinator, NativePresenceStore, NativePresenceController, browser status.

Event Current flow and safeguards Qualification/limitation
Browser before Word Browser displays disconnected/agent-only state. Native status is independent of page lifetime; later presence invalidates status Automated; physical startup order outstanding
Word before browser Add-in discovers open documents and agent publishes presence independently. Browser reads existing live leases when opened Automated session/reconcile contract
Manuscript opened Owned identity/association is read, fresh session registered, active selection observed. Association is checked against account/catalogue before cloud use Unknown/unlinked document is not proof of canonical ownership
Companion connects Capability handshake, authoritative document reconciliation, then authenticated cloud publication and chapter verification Connection alone does not accept prose
Agent starts/restarts Add-in retries off UI thread (bounded backoff up to 5s), may relaunch agent, reconciles authoritative descriptors and clears stale extraction mailbox. Agent restores eligible account/book binding and rechecks positions Restart/pipe fixtures; Windows process/COM acceptance still needed
Word closes Normal shutdown disposes link; document close is reconciled against actual open documents so cancelled close preserves the same session Closing one document does not retire another
Word crashes Broken pipe detaches instance, removes owned sessions and attempts cloud removal. If removal cannot arrive, server leases expire Crash-recovery managed fixtures; no crash injected into real Word
Word UI hangs Agent transport can remain alive while STA selection/timer observations stop. Heartbeat currently republishes cached document state; no per-document UI-observation age fence was found R1: real blocked-STA test needed; transport liveness is not UI responsiveness
Agent/cloud disconnects Session state is retired on pipe loss; cloud failure produces reconnecting/action-required/status-unavailable states. Server liveness is ephemeral No accepted data deletion. Failed clean removal may leave a bounded stale lease
Browser refresh/BFCache return Status re-reads and hub reconnects; pageshow resumes interval. Focus is read from authoritative server state; local Reader policy remains separate BFCache covered by fixtures; real installed Windows PWA outstanding
Book switch Access checked for book; Writer filters eligible leases by book and canonical manuscript identity. Other-book documents are explained, not silently associated Current account feature flags not measured
Multiple documents Separate instance/session identities; Writer provides a chooser and navigation requires one selected exact lease R2: pinned selection can fall back to sole remaining document after disappearance
Active document changes Native active observation is distinct from identity. Standalone Context/Intent may follow Word; Writer's intended global context does not automatically follow it Same-title and multiple-process physical acceptance needed

Server presence expires after 45 seconds; a server restart loses leases/commands and requires fresh publication. Acknowledged clients normally refresh every two seconds; older paths can use 15 seconds. Browser status has a 15-second fallback, plus debounced SignalR invalidation and visibility/pageshow recovery. These create a bounded delay after abrupt loss; they are not instantaneous disconnect detection. Navigation commands expire after 25 seconds, with browser confirmation bounded to about 30 seconds. Missing/late acknowledgement remains unconfirmed.

Monotonic sequence/revision and grant checks reject delayed heartbeats; lease ownership prevents an old disconnect retiring a replacement. Capacity limits bound sessions, queues, receipts and transfers. No duplicate-session defect was demonstrated, but copied identity, simultaneous documents for one book and server/agent restart together need physical qualification.

5. Manuscript capture, incremental synchronisation and freshness

Capture and acceptance flow

  1. Native import requests authorise one intended live document. Capture carries request/instance/session/manuscript/revision and paragraph capabilities; payloads and progress must match that authority.
  2. VSTO reads paragraph fragments in bounded UI turns. Word w14:paraId is a hint, not PlotDirector's durable paragraph GUID. Complete ordered fragments and physical bounds are validated before snapshot assembly.
  3. Durable capture/preview precedes canonical build. Paragraph tracking initialisation requires accepted import provenance and reversible chapter/scene mapping. Unassigned and excluded sections are not guessed into canonical scenes.
  4. Existing accepted paragraphs are reconciled, saved with expected revision/request ID and activity transaction, then exposed to Reader/Review. This is the authoritative accepted state; it does not write prose back to Word.

ParagraphIdentity uses unambiguous native IDs, unchanged sequences, recognised neighbour/content context and reviewable rewrite evidence. Duplicate/copy ambiguity does not simply attach identical text to the old occurrence. Inserts receive new occurrence identities; removed/moved content and evidence are evaluated by ParagraphManuscriptEngine. Invalid duplicate identities, incomplete paragraphs, ambiguous headings and stale base revisions reject rather than silently overwrite. Split/merge/move/boundary cases exist in chapter and paragraph fixtures; unusual real Word structures remain qualification cases.

Current chapter path

The modern path is not whole-book import on every save. It loads the accepted manifest, compares chapter-range text, verifies native identity/geometry where required, batches unchanged checkpoint proofs and submits changed-chapter prose through existing reconciliation. Text equality alone is insufficient proof of identity or physical position. Missing IDs, fields, drawings/floating anchors, revisions and other structural cases use detailed fallback.

Observed revision/saved-state transitions are debounced by about three seconds. After completion, approximately 60-second periodic range passes cover changes missed by length/saved-state observations. Word author-priority and busy handling can defer work. These intervals are opportunities, not a freshness SLA. Cursor location can prioritise checking; it is not evidence that other content is unchanged.

  • OnSave: saved changes may reconcile automatically under existing authority. Unsaved range observations can detect changes but do not upload accepted prose or establish verified positions.
  • Manual/Off: existing modes and explicit repair permits govern mutation authority; automatic checks must not be described as blanket authorisation to reconcile.
  • Manual web check: Writer POSTs /manuscript/paragraphs/snapshot with exact instance/session. For chapter-capable clients, RequestParagraphSnapshot delegates to existing chapter repair unless full snapshot was explicitly requested. The normal Writer action does not request full snapshot or force a save.
  • Legacy paragraph-capable clients: ObserveParagraphSave uses the existing throttled OnSave snapshot path; it is separate from modern chapter checks.

Native range synchronisation report accurately distinguishes selective prose reconciliation from verification. A one-chapter edit can still require range comparisons across all chapters. Do not promise that 47 unchanged chapters require zero Word reads. XML/native-identity fallback costs depend on actual Word data.

Interruption and recovery

Revision changes cancel/retire old work and queued commands. Saved-state, session, identity, grant and current accepted hash checks fence acceptance. Reconciliation is serialised per session; changed canonical revisions invalidate stale proofs. Retry counts/backoff and operation IDs bound recovery. Already accepted independent checkpoints survive cancellation or a later failure; partial success is not rolled back into an empty manuscript. Active import/analysis pauses synchronisation through existing repository status checks. Capture acceptance is idempotent and durable; ephemeral authorisation loss/server restart can require a new request without justifying reimporting the book.

No evidence was found that normal Writer status reads initiate manuscript capture, mint paragraph identities or accept scene associations. No automatic whole-book AI run is required for ordinary sync.

Freshness and Reader

Writer metadata SQL returns accepted snapshot and selected-chapter acceptance timestamps. writer-word.js distinguishes disconnected, mismatched identity, unsaved, checking, needs-attention and failed states. Its completed wording explicitly says later edits may still be pending. It does not claim “up to date” from presence.

ManuscriptReaderService reads accepted paragraphs, active accepted scene assignments and checkpoint timestamps. It bypasses manuscript workspace initialisation. It can display last accepted prose even when live Word positions have expired. Metadata-only accepted checks do not unnecessarily replace unchanged DOM. Content fingerprints include manuscript/paragraph identities, text, headings and scene mappings; remapping is a content-context change even if prose is equal.

Reader client checks accepted changes, defers replacement around selection/editing/listening/pause, preserves paragraph scroll anchors and rejects stale responses. It communicates updates becoming available rather than forcing them into an active selection. Thus a reader can intentionally show an older accepted version; that is distinct from unsynchronised Word text.

6. Writer workflow integration matrix

Area Word required? Current implementation and freshness Offline/disconnected disposition and status
Writer Home No Navigation and saved context/objective entry; shell offers conditional Word controls Implemented/automated. No reason to require Word merely to choose work
Write Only for writing prose in Word Canonical chapter/scene intentions, saved objective, sessions and Word widget; explicit chapter/scene handoff and bounded check Implemented/automated. Planning/intentions remain available with server; unsaved Word changes honestly pending
Explore No Guided investigations and existing story tools; explicit destinations can set working focus Implemented/automated. Word availability should not gate diagnostic guidance
Plan No Planned activities/schedules are intended work, separate from measured manuscript changes or session completion Implemented/automated. No new Word coupling needed
Review No for accepted reading/notes; yes for handoff Three columns, accepted Reader, verified scene context, chapter/scene/passage annotations, Word chapter/scene/paragraph handoff Implemented with F1 correctness gap. Missing accepted text is explained; Word absence does not prevent existing accepted reading
Reflect No Calendar, sessions/activity and accepted-change measurements; capture lag limits manuscript progress totals Implemented/automated. Quiet/missing recorded progress does not prove no writing occurred
Writing Dashboard No Authorised book rollups, work/session/planning context; manuscript metrics are accepted observations Implemented/automated. Do not call metrics live Word word counts
Guided Investigations No Saved guidance and explicit story destinations use existing tools Implemented/automated. No integration gap merely because guidance does not open Word
Saved objectives No Explicit SaveObjective stores activity/chapter/scene/intention independently; “Go to objective” aligns focus, not the saved target Implemented/automated. Changing Focus/Word never automatically retargets objective
Standalone Context/Intent Optional live following Existing local follow/pin/document-selection contract; Writing/Context/Navigate uses accepted anchors Implemented; receipt consistency can improve. Its local following must not become Global Focus history

Evidence: Writer partials, WriterController, objective repository, objective client, planning, follow client, navigation inventory. The matrix describes traced implementation and portable evidence, not physical author acceptance of every workflow.

7. Global Focus and all Word navigation paths

Global Focus, recent history, Previous/Next and Go use the existing service and workspace adapters. Neither NativePresenceController nor the normal native status path writes Focus or objectives. writer-word.js listens to Focus to update the intended target, not to issue navigation. Word movement does not dispatch a Focus save. Verified-origin adoption is an explicit author action and updates Current Focus, not the objective. Native Return to Writer passes typed book/instance/session hints through a same-origin authenticated launcher; these hints do not establish accepted ownership or replace the current focus.

Navigation surface Resolution and outcome Audit result
Focus ribbon chapter in Word WriterWordService.Navigate: authorised chapter, single exact lease, matching manuscript, current live chapter start and final position/revision recheck Implemented/automated; physical cross-chapter activation pending
Focus ribbon scene in Word Accepted canonical scene's first story paragraph GUID, position verified, current scene-start proof and final matching chapter/scene Implemented/automated; no title/order heuristic
Review paragraph in Word Stable accepted paragraph GUID, chapter, expected accepted revision and WriterReview_ParagraphStart checkpoint join Implemented/automated; missing/stale reference refuses exact handoff
Standalone Context Open in Word WritingController.NavigateWord: same accepted paragraph/scene and current session/checkpoint principles Implemented; reports requested, not confirmed. Does not use Writer's acknowledgement receipt UX
Native AI-review “Locate a suggested scene” NativeWorkspaceController.Navigate: stored suggestion offset and numeric document revision passed directly to presence Partial, F2 missing source-session/fresh-content guard
Native tray/local chapter navigation Local selected document/session through coordinator and VSTO scheduler; UI-thread range/identity fences Implemented; detailed real Word activation remains outstanding
Retained Office.js host Separate host/manifest and marker/selection compatibility route; not the current VSTO/agent sync implementation Retained compatibility. Do not delete/redesign solely for consistency

The ribbon delegates to hidden legacy widget buttons; these are adapters, not necessarily redundant visible controls. Keep the ribbon layout. Consolidate destination verification and receipt semantics where useful, not every entry point into a replacement navigation subsystem.

Current Writer handoff rechecks on the server, agent and UI thread. It refuses uncertain/ambiguous targets and does not open, close, save or rewrite a document. Range.Select may affect the foreground through Word itself; correct activation and cursor landing are physical acceptance requirements. Chapter/scene/paragraph identity proof must be preserved if any endpoint is consolidated.

8. Review and paragraph-verification contracts

Review loads the chapter selected by explicit route/Global Focus through WriterController. Clean focus changes use one cancellable accepted-content/layout pipeline; dirty editors defer following with explanation. Scene positioning resolves the first accepted DOM paragraph bearing the stable canonical SceneID, never a scene-list index or paragraph-number approximation.

WriterReviewService resolves scene context from paragraphs of the current accepted fingerprint. Cross-scene ranges have no single verified scene. Unassigned paragraphs keep chapter context. The reader may fall back to the chapter when an accepted scene mapping is unavailable; navigation does not create such a mapping. F1 concerns retained local selection during that fallback, not acceptance of a new association.

Annotation creation validates displayed content version, exact paragraph IDs, range order/offsets and supported scope. Scene scope requires an accepted paragraph assignment. Passage hash covers paragraph IDs and text. Current observation procedure locks/rechecks accepted revision/manuscript within the create transaction; an intervening accepted commit produces conflict. Update changes annotation text/decision/classification/status under optimistic version, retaining original reference and scope. Retry IDs are idempotent. No save silently reanchors to similar prose.

An accepted Word change can preserve a paragraph GUID while changing text, remove a GUID, or replace manuscript provenance. AnchorState reports Current, Changed, Missing or changed, or Different manuscript. Old manuscript revision/content fingerprint and original paragraph IDs remain recorded. Changed/missing references refuse precise Word handoff and offer explicit chapter fallback. Reader updates and navigation are guarded while annotation edits are dirty; network/unconfirmed-save messages retain the in-memory draft. These are substantial existing protections against wrong-passage notes.

A scope nuance: stored SceneID on a passage observation is historical context; AnchorState hashes identities/text, not current scene assignment. A remap can leave a passage text anchor Current while scene context has changed. That does not move the annotation's passage and is not evidence of corruption. Qualification should ensure historical/current scene labels are unambiguous rather than rewriting old references.

9. Native reliability and performance evidence

The native design already bounds UI work: selection bursts coalesce, author activity takes priority, IPC/extraction queues have capacity/backpressure, COM stays on the owner thread, network/processing runs in the agent, and revision/close cancels obsolete work. Chapter comparison processing is bounded separately; retry exhaustion leads to Needs review, preserving accepted content. Long single COM calls still cannot be preempted by a managed queue budget.

Historical evidence must be interpreted by date/version:

Evidence Established result Not established
Phase1, Windows foundation qualification Separate agent/protocol/session foundation; Windows build and managed/pipe tests Initial desktop loading and author responsiveness were outstanding
Phase2, Phase3, Phase3.5 Detection/AI/review/preview progression Their original “native commit unavailable” limit is superseded by later import work
Import correction, paragraph foundation, chapter contract Existing capture, canonical identity, accepted mapping and chapter proof progression Documentation alone does not prove installed server/native compatibility
1.0.0.33 post-edit fix Historical initial verification about 16s; recovered pass 19.615s; saved-state/command-order corrections; installed package integrity recorded New-code physical post-edit acceptance remained pending
Incremental investigation Historical edited cycle about 259.444s, one reconciliation plus broad verification; explained checkpoint retention issue Not 48 prose reconciliations; not current performance
Range implementation Three-second/periodic scheduling; synthetic 48-chapter, one-edit selective reconciliation; fallback safeguards; historical disposable SQL evidence 30.5ms preallocated hashing is not Word extraction latency; no blanket one-detailed-read guarantee
Writer Phase3B/Windows appendices, Phase3C baseline Acknowledged handoff, matched capability, Windows package/build progression through source 1.0.0.40; returned-to-Writer route correction Earlier .39 report explicitly had no physical Word run. Later user-confirmed restored integration is not a complete instrumented acceptance matrix

Current source version is 1.0.0.40 in DeveloperVersion.props. This audit did not inspect installed Windows versions, package signatures, COM load, typing latency, actual Word cursor landing or physical PWA launching. It does not change historical Windows full-harness failures into passes: the .39 appendix records source assertions sensitive to LF/CRLF and an incomplete full Windows run.

Large manuscripts need both correctness and responsiveness evidence: 190k/250k-word authorised disposable fixtures, same-length edits/Undo, cross-chapter moves, fields/revisions/floating anchors, document switching and cancellation. Measure first useful verified context separately from whole-manuscript completion; record UI tick/COM p50/p95/max, typing/scroll/ribbon responsiveness, CPU/memory, queue depth, bytes and reconciliation/reuse counts. An existing 5–10s goal is not an achieved acceptance result.

10. Offline and disconnected behaviour

Condition What remains usable What is unavailable/uncertain
Word closed With server connectivity: accepted Reader/Review, notes, intentions, Explore, Plan, Reflect, saved objectives and schedules Word handoff, new Word capture, current cursor
Companion/agent unavailable Same persisted browser workflows Live position and new synchronisation; old accepted prose remains valid as historical content
Browser loses server connectivity Already rendered content and unsaved text may remain in memory; controls report failures No guaranteed new reads or durable writes; no offline queue/cache/background sync in service worker
Canonical content stale relative to Word Last accepted content and original annotation provenance Cannot claim latest Word edits are visible or navigate using expired/unverified offsets
Accepted update deliberately paused Displayed accepted text and selected passage remain stable Newer accepted version waits for safe/explicit refresh

Recommend retaining the existing compact distinction: connection, uncertain/unsaved/checking/failure message, and last chapter acceptance when useful. Do not add six permanent badges. “Synchronised” means a completed check for a particular saved revision, not continuous currentness. Server connectivity loss is separate from Word absence. Draft retention is in-memory protection, not durable offline authoring.

11. Prioritised findings and outstanding risks

F1 — P1 confirmed: Review fallback retains a previous passage

  • Workflow/trigger: within one accepted chapter, select a mapped passage, then choose chapter-only Focus or an unmapped scene. No editor need be dirty.
  • Evidence/root cause: manuscript-reader.js:readerResolveFocus returns a non-precise result with null paragraph; narrative-focus-review.js:apply passes null to selectNarrativeParagraph. In writer-review.js:selectNarrativeParagraph, only the non-null branch updates selected, anchor and wordReference; the null path reloads the previous selection. The old panel's verified SceneID can therefore remain the Word scene target. Existing missing-map browser coverage exercises cross-chapter replacement, which resets the closure, rather than this same-chapter transition.
  • Impact: chapter fallback can show notes or create a new passage/scene annotation against an earlier selection. Server guards correctly validate that earlier passage; they cannot infer the author's newly intended context. No wrong annotation save was executed in this audit.
  • Correction: explicitly clear local passage/scene/Word target on non-precise focus application, retain chapter context and precision-unavailable message, and keep dirty-edit deferral. Do not create a scene mapping or change the saved objective.
  • Complexity: small, roughly 0.5–1 day including regression.
  • Acceptance: same-chapter mapped→unmapped, mapped→chapter-only and accepted mapping removal; assert no previous passage/scene target survives and no write occurs until explicit author action. Repeat with dirty annotation/note editors, delayed requests and browser/PWA return.

F2 — P1 confirmed missing guard: historical native-review offsets lack session/content proof

  • Workflow/trigger: open /native-companion/reviews/{id}, select a live reopened manuscript session and locate an old AI suggestion.
  • Evidence/root cause: NativeWorkspaceController.Review filters by manuscript GUID and ResultJson.DocumentRevision, not source session. Navigate passes result.Scenes[index].Start directly to presence.Navigate using the selected session and that numeric revision. VSTO's LocalDocument creates a fresh session and starts its revision counter again. The downstream command correctly matches the new selected session; it has no proof the historical offset was derived from that session/content. Source session is optional persisted provenance and cannot simply be assumed present.
  • Impact: stale offsets may land at another passage in the same manuscript after reopening or external editing. Exact process routing still prevents arbitrary other-document delivery. This is not a demonstrated real-author corruption or wrong-document incident.
  • Correction: fail closed without trustworthy provenance; require original session/revision and/or fresh content-bound target proof before allowing historical numeric offsets. Suggestions may not yet have accepted paragraph GUIDs, so do not guess a canonical anchor. Preserve read/approve/reject without navigation. Reuse common command/receipt handling after target validation.
  • Complexity: medium, 1–2 days depending on usable existing provenance; no identity rewrite necessary.
  • Acceptance: fake server/coordinator tests for reopen with equal numeric revision but changed prefix text, copied properties, absent source session, valid current session and content mismatch; zero commands for stale targets. Physical Windows reopen test on disposable copy.

R1 — P2 risk: agent liveness can outlive fresh Word UI observations

  • Evidence: AgentLink pings from a background loop. TrayCoordinator.Exchange records document Observed, but Heartbeat republishes cached cursor/saved values without an observation-age gate. A responsive agent/pipe can survive a blocked Word STA. Server's 45s lease then proves agent publication, not recent UI observation.
  • Impact: connected/verified-position labels may look fresh during a Word UI stall; navigation should time out rather than claim completion. No physical hang was induced, so the duration and exact UI effect remain unverified.
  • Correction: first qualify an intentionally blocked STA in a disposable harness. If confirmed, expose/fence stale observation age separately from healthy agent transport, without deleting accepted content or flooding status UI.
  • Complexity/acceptance: 0.5 day investigation, then 1–2 days if needed; fake-clock stale observation tests plus Windows stall/recovery, ensuring no stale completion or forced save.

R2 — P2 risk: document selection recovery may change the intended manuscript

  • Evidence: writer-word.js:render preserves a selected session while present, but auto-selects the sole eligible remaining lease when it disappears. It also accepts an origin hint then falls back to one document. Canonical GUID checks and server proof still apply.
  • Impact: with copies sharing manuscript properties, author intent may be less clear than the live chooser suggests. No unsafe destination was demonstrated; do not label this a confirmed wrong-document defect.
  • Correction: test selected-document disappearance first; if confusing, keep a disconnected explicit selection until the author chooses another document. Preserve convenient single-document initial selection.
  • Complexity/acceptance: small, 0.5–1 day if needed; two-document close/reopen/active-switch, same-title/copy tests, no silent handoff to the other copy.

R3 — P2 qualification gap: full current physical acceptance is incomplete

  • Evidence: historical reports explicitly distinguish managed/Windows build and package checks from physical Word. No current complete matrix was found for all Writer/Review/Focus changes, large manuscripts, real installed PWA and reconnect/cancel.
  • Impact: source and fixture correctness cannot establish cursor landing, responsiveness, activation or installed compatibility.
  • Correction/complexity: execute Stage 3B.4; roughly 2–4 tester days plus defect-dependent retest.
  • Acceptance: exact package/source/OS/Word/PWA identity, disposable documents, measured results and explicit outstanding items. No install or author-document tests authorised by this audit.

I1 — P3 optional: shared acknowledgement UX for standalone Context

  • Evidence: WritingController.NavigateWord performs substantial target validation but calls presence.Navigate without Writer's requireAcknowledgement:true; it honestly says requested. Writer already has a correlated completed/failed/timed-out receipt contract.
  • Impact: inconsistent confidence/feedback and duplicate resolver maintenance, not a false completion claim.
  • Correction/complexity: optionally share validated target/receipt plumbing while retaining Context's independent target; 1–2 days. Do not redesign ribbon or merge local follow with Global Focus.
  • Acceptance: existing Context pin/follow/multiple-document behaviour, exact scene proof, old-client capability fallback and requested-versus-confirmed browser tests.

No P0 defect is asserted. F1/F2 are confirmed code-path gaps with possible safety consequences requiring tests; R1/R2/R3 remain risks/gates, not fabricated incidents. True offline editing and continuous unsaved verified navigation are absent by deliberate contract, not missing Phase3B requirements.

12. Proposed Phase 3B completion stages

Estimates are engineering/test days, not calendar promises. They assume the existing branch and services; they exclude unrelated editor/export work and any defect-dependent redesign. Existing delivered Phase3B/3C capabilities are prerequisites to preserve, not new scope to rebuild.

Stage Scope and implementation approach Dependencies/risks Acceptance and Windows need Effort
3B.1 Integration correctness Fix F1 local selection reset; fail closed for F2 historical offsets using existing provenance/current proof. Preserve paragraph GUIDs, accepted revision fences, Focus/objective/session separation First reproduce transitions; optional source-session fields may make old suggestion navigation unavailable. No automatic migration/identity adoption Focus fallback clears exact handoff; stale historical offsets issue zero commands; valid current chapter/scene/paragraph path still acknowledged. Managed/browser tests first; Windows reopen/cursor check required before physical sign-off 2–3 days
3B.2 Writer workflow completion Re-run all delivered Write/Review flows against 3B.1; clarify historical/current annotation context only if tests show ambiguity. Optionally share Context receipt contract (I1) if authorised scope warrants it Depends 3B.1. Risk of accidentally retargeting objective, pinned Context or active session; avoid general workspace redesign Home/Explore/Plan/Reflect work without Word; Review reads accepted content while disconnected; explicit handoff preserves objective/activity/intention/session/note/reader state. Browser automated; Windows for actual handoff 1–2 days; optional I1 +1–2
3B.3 Reliability and focused UX Qualify R1/R2; implement only demonstrated observation-age/selection recovery fixes. Reuse current status stream, retry/expiry and inline feedback No new poller or blanket “current” badge. Hung COM call cannot be made preemptible by UI wording Agent restart/server loss/BFCache recovery; stale observations never imply fresh cursor proof; explicit selected copy remains understood; errors retain drafts and accepted content. Windows stall/switch testing required 1–3 days, conditional
3B.4 Qualification Exact matched native/web baseline; portable regression plus isolated browser/PWA, then authorised Windows/Word functional/performance/security matrix Suitable Windows environment, approved package installation if necessary, disposable documents/account. Historical package reports are not acceptance of current HEAD All safety/workflow gates below pass; measured large-manuscript result and known limitations signed off; no pending critical navigation/reference defects 2–4 tester days, plus retest

Core residual work is approximately 6–12 days, with risks and optional work separately bounded. If R1/R2 fail to reproduce, document the result and omit speculative changes. No new database schema appears necessary for F1; F2 should first use existing provenance and refuse unsafe legacy targets. Any proven need for additive persistence must be proposed as a new forward-only migration, not editing numbered files.

13. Acceptance and qualification requirements

Use existing assertion suites and disposable fixture documents. Keep physical acceptance separate from source/build/managed reports.

  1. Authority invariants: changing Focus/Recent/Next/Previous/Go never selects Word without explicit handoff; passive Word movement never saves Focus/history/objective. Saved objective retains chapter/scene/activity/intention through every workflow and return path.
  2. Connection matrix: both startup orders, agent-only, browser refresh/BFCache, server/network loss, agent restart, Word close/cancel-close/crash/hang, sign-out/account change and multiple Word processes. Verify state delay/expiry and ownership; connection must not imply accepted freshness.
  3. Content: initial import into disposable book; OnSave/manual/off, same-length edit while dirty, Undo/Redo, paragraph insertion/deletion/copy/move/split/merge, chapter rename/reorder/boundary edits and drawings/fields/revisions. Assert canonical GUID preservation only where justified, ambiguity needs review, accepted checkpoints survive interruption and final Reader shows only committed prose.
  4. Navigation: exact chapter/scene/paragraph, wrong author/book/instance/session/manuscript/revision, old capability, stale/missing accepted anchor, duplicate clicks, another in-flight request, timeout, delayed acknowledgement, another edit before UI execution, cross-chapter and same-title/copy documents. Explicitly test F2 equal revision after reopen. Confirm correct activated document/range and single selection; no forced save or text mutation.
  5. Review: three-column target consistency; mapped/unmapped/mixed selections; F1 same-chapter fallback; Focus Reading and dirty-note deferral; accepted update during passage selection/create; concurrent save conflict; changed/missing/replaced paragraph; immutable original annotation provenance and safe chapter fallback. No automatic annotation or scene association from navigation.
  6. Workflow preservation: Writer Home, Write, Explore, Plan, Review, Reflect, Dashboard, investigations, saved objective, standalone pinned/follow Context and Intent, and active session/unsaved return note. Word absence must not disable independent work. Actual media playback only where already part of an explicitly approved fixture.
  7. Performance: 190k/250k disposable manuscripts; unchanged reopen, one-edit and multi-edit saved cycles, periodic check, switching during work, cancellation and recovery. Record UI latency and first useful context/completion separately, detailed/native fallbacks, reuse/reconciliation counts, requests/bytes and bounded memory/queues. Compare matched before/after trials; do not substitute preallocated hashing times.
  8. Browser/PWA/accessibility: browser and genuinely installed Windows PWA, refresh/return, narrow width, themes/high DPI/keyboard/status announcements, transport failure retaining drafts, and explicit acknowledgement wording. Simulated navigator.standalone is not installed-PWA evidence.

Existing test evidence and this audit's execution

Current test entry points include WriterWordTests, WriterReviewTests, WriterPhase21Tests, ChapterSynchronisationTests, ManuscriptReaderTests, and native executable suites. Browser coverage includes Writer Word, Review, continuous Review, focus synchronisation and Reader live updates.

Audit execution results are recorded below. Tests run serially. No database regression, live site acceptance, author manuscript mutation, deployment, Windows installation or real Word test was run. Relevant SQL was inspected as source only; no SQL was applied, including rollback fixtures.

Gate executed on audit baseline Result and boundary
dotnet build PlotLine.slnx --no-restore PASS, 0 warnings, 0 errors, 40.89s. Managed and Windows-targeted agent compilation; not classic VSTO/Office build
dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj PASS, exit 0, 632 PASS records; includes Writer navigation/Review anchors, Focus, Reader, paragraph/capture/presence and isolation checks
dotnet run --no-build --project PlotDirector.NativeCompanion/Tests/PlotDirector.Companion.Tests.csproj -- --chapter-sync PASS, exit 0, 453 PASS records. Managed coordinator/range/reopen/handshake/real Linux pipe fixtures; measured handoff 112.7ms/2 polls, not Windows/Word performance
Same native project without arguments PASS, exit 0, 292 foundation checks. Linux pipe, scheduler, persistence/authentication and routing fixtures; no Windows ACL/COM responsiveness claim
node PlotLine.Tests/Browser/writer3-word.cjs PASS, exit 0. Chromium browser/simulated PWA covers status, exact document selection, explicit handoff/acknowledgement, timeout, repeated actions, bounded check, disconnect, retained session/note, origin adoption and narrow ribbon. Native events/transport simulated; not installed Windows PWA
Read-only Chromium F1 reproduction REPRODUCED against compiled MVC and production scripts with --toolbar-browser-host, in-memory repositories and fixture-focus-reader=mapped. No annotation save, SQL or Word command

Reproduction detail: open fixture /Writer/Review?projectId=7&bookId=12, wait for accepted SceneID 31 to position, then explicitly set the same chapter (21) with sceneID:null. Before: global scene 31, accepted focus paragraph P, review panel scene 31, Word scene 31 and paragraph P. After: global scene null and reader focus paragraph empty, but review panel scene 31, Word scene 31 and paragraph P remain. P is the same synthetic stable paragraph GUID, not a guessed index. This establishes the chapter-only branch of F1 in a real browser; the unmapped same-chapter branch follows the same null resolver path and must be added to regression coverage. The reproduction read current targets only and made no author-data writes. Fixture Focus updates were in-memory only.

Temporary command logs and the one-off reproduction were kept under /tmp/plotdirector-phase3b-audit-* and /tmp/plotdirector-phase3b-review-repro.cjs; they are local diagnostic artifacts, not committed tests or durable qualification files. The report records their results so it does not depend on temporary-file retention. Existing regression source and historical evidence remain linked above.

14. Decisions genuinely requiring author approval

No architectural decision or permission is needed to finish this audit/report commit. No implementation has been performed.

Before future physical qualification, arrange an approved Windows test session, authorised disposable manuscript copies/account and any required matched package installation. Permission to install, close Word, interrupt an active author session or modify real manuscripts is not implied by this audit. Record supported Word/Windows versions and agree a measurable responsiveness/completion target; existing historical timings do not supply a current guarantee.

The optional I1 Context acknowledgement polish is a scope choice, not a prerequisite for preserving existing safe requested-only behaviour. If Stage 3B.1 cannot safely prove an old AI suggestion's target using existing provenance, the recommended default is to disable only that stale navigation and retain review decisions, rather than infer a new identity. Broader compatibility retirement or unsaved-position acceptance would be separate product decisions and are not proposed here.

The future native manuscript editor and publishing export engines remain outside Phase 3B. Keep the existing Dapper/stored-procedure, canonical-manuscript, native-agent and Global Focus architecture. Implement the two demonstrated guard corrections, investigate the bounded risks, then qualify what already exists.