82 lines
12 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Current architecture: Windows tray Companion (1.0.0.10)
Word now exposes only local status and Open Companion. Use the existing agent’s tray control centre and PlotDirector PWA for analysis/review, Context and Intent. [Implementation and limitations](../Docs/WordCompanion/2026-11-05-tray-companion.md) · [one Windows update/install/qualification procedure](WindowsValidation/Tray-Companion.md). Earlier phase notes below are historical and describe superseded native dialogs.
# Current developer build: Phase 3.5
Version **1.0.0.6** adds per-document book binding, verified connection status, saved Context/Intent and read-only import preview. See [qualification](WindowsValidation/Phase35-Integration.md) and [implementation report](../Docs/WordCompanion/2026-11-05-phase35-integration.md). Native import commit and native live SignalR following remain unavailable.
# Native Word Companion — developer foundation, structure and AI review
Phase 3 adds explicit chapter-by-chapter AI review through the existing PlotDirector chapter service, browser-approved sign-in, a hierarchical native review and safe update/build plus explicit per-user installation scripts. See the [Phase 3 implementation report](../Docs/WordCompanion/2026-11-05-phase3-ai-integration.md) and [Windows workflow](WindowsValidation/Phase3-AI.md). The baseline implementation details below describe the foundation; Phase 3's native API does not provide prose synchronization or native Context/Intent/SignalR following.
Phase 2 adds optional local structural analysis through the existing snapshot/pipe path, with a native modeless review, progress, cancellation and per-document results. See the [Phase 2 report](../Docs/WordCompanion/2026-11-04-phase2-document-analysis.md) and [Windows analysis checklist](WindowsValidation/Phase2-Analysis.md). The author's Phase 1 Windows smoke test is build `1.0.0.3` at `726a3d5`; the Linux limitations below describe the original foundation. New Phase 2 Word integration still requires Windows qualification.
Publisher: **Nick Beckley**. Architecture: minimal Windows VSTO adapter → per-user modern .NET agent → existing PlotDirector server (native browser-paired chapter preview implemented; session-aware SignalR deferred).
This is a development foundation, **not a publicly installable replacement**. Office.js, its manifest, onboarding, Context/Intent and multi-screen UI remain present. Nothing in this tree automatically deploys or installs a component. The .NET Framework VSTO host has not been built or run in Word on the Linux development host.
```mermaid
flowchart LR
Word[Word UI / STA: lifecycle, positional selection, bounded ranges] --> VSTO[VSTO native ribbon and bounded UI scheduler]
VSTO <-->|asynchronous bounded named-pipe protocol v1| Agent[Per-user .NET 10 agent]
Agent --> Sessions[Word instance + live session + persistent manuscript identity]
Agent --> Processing[Structure resolution, snapshots, diagnostics]
Agent --> Outbox[Bounded metadata-only durable scheduling foundation]
Agent -.->|future native authentication and explicit session contracts| Server[Existing PlotDirector HTTP / SignalR / domain services]
Server --> Screens[Existing browser Context / Intent / multi-screen workspace]
```
## Projects
- `Protocol` targets .NET Standard 2.0 for the VSTO/modern runtime boundary. Value-only data contracts; 256 KiB length-prefixed frames, protocol/capability handshake, correlation/instance/session/revision/snapshot identities. No Office or server-domain references.
- `Client` targets .NET Standard 2.0. Background pipe I/O/recovery; Word callback producers never wait for space or replies. A 64-message FIFO plus at most 32 coalesced selection slots and one latest active-session slot; 3s exchanges, cancellation closes hung I/O on a worker; idle keepalive every second, retry capped at 5s, launch attempts limited to once per 30s. Open-document descriptors are authoritative reconciliation state; stale snapshot fragments are discarded after reconnect. `WordAccessScheduler` is UI-thread-only, fair FIFO low-priority work, latest selection priority, 64 actions, author quiet windows and timings.
- `Agent` targets .NET 10. Windows interactive executable, one process per user/logon session using an exclusive local lock; named-pipe ACL restricts current user, add-in independently checks server process SID. Up to eight connected Word instances and 32 documents each; 16 Mi storage-budget units per assembling document snapshot / 64 Mi globally (text + marker text + per-fragment overhead allowance); 200k assembling fragments globally; 8,192 boundaries per document / 32,768 globally, with 200-character titles. Session routing always requires the connection's instance lease and exact session ID. No server command is routed to a “latest Word” connection. Idle exit after five minutes with no peers; no privileged service.
- `Vsto` is a classic .NET Framework 4.8 **Word VSTO** project, host-item/designer metadata and native ribbon. Requires Visual Studio Office tools/PIAs/runtime on Windows. It is intentionally excluded from the Linux/main managed build; `NativeCompanion.Windows.sln` and `WindowsValidation/Build-Developer.ps1` provide the Windows path. The host-item plumbing must be validated/regenerated against the installed VS Office template if toolchain generation differs; no Windows compile/load claim is made.
- `Tests` is a portable executable regression harness. It runs actual framed named-pipe traffic and managed production logic, including three synthetic book sessions and agent restart. Linux implements named pipes via Unix-domain sockets; these results do not establish Windows ACL, COM or Word performance.
## Identity and data ownership
`WordInstanceId` is generated once per add-in load. `SessionId` is generated per open document and is distinct from `ManuscriptId`. The latter reads `PlotDirector.Native.DocumentGuid` from custom properties or is provisionally generated for an uninitialized document. Settings explicitly offers to persist that native identity; no implicit save occurs. Until persisted, a provisional identity is **not** reopen-stable; diagnostics/protocol flag `IdentityPersisted=false`. `PlotDirector.Native.ProjectID/BookID` can be read from prepared test metadata, with `AssociationVerified=false`: local values never grant server authorization.
The Office.js settings bag is not reinterpreted as custom properties. Automatic migration/read-back of existing Office.js binding storage remains a documented follow-on compatibility dependency requiring real linked DOCX fixtures. Native metadata uses a separate namespace and never overwrites an existing Office.js binding. This phase is not a switchover for real linked manuscripts.
A descriptor carries an observation revision; snapshots carry a new snapshot ID and the exact revision. Agent refuses stale sequences, leases, revisions, retired sessions and cancelled snapshot commits. Word uses Range.Start/End, OutlineLevel and PD control/bookmark tags, not repeated paragraph text matching. Agent resolves structural positions from completed snapshots; no guessed server scene title is promoted into a trusted scene ID. Structural IDs originate from metadata; server authorization remains required before any future server update.
## Responsiveness and safe failure
Word events enqueue/coalesce work; all COM remains on the original thread, driven by a 25ms WinForms timer. The extractor reads at most 2,048 Word range characters per fragment, up to four fragments or a cooperative ~20ms batch, yielding between batches. A single COM call cannot be preempted; 20–30ms is a **measurement target**, not a guarantee. Every wrapped COM call and batch is timed; UI tick delay and queue depth are sent as bounded diagnostics. COM busy/errors back off, and unsupported marker density/ranges stop extraction instead of looping indefinitely.
Selection reads are prioritized and repeated events coalesced. A completed snapshot is reused on cursor movement. Length changes or the first Saved→dirty transition invalidate it; manual Synchronise Now explicitly rebuilds it. **Same-length structural edits while already dirty are not fully detected in Phase 1**; use manual refresh. This is a read-only structural proof, not a complete edit journal or safe prose-sync implementation. Save/close handlers never set Cancel, wait for IPC, read prose or force a save. Cancelled document close retains its session; actual close retires the exact session after a bounded UI-side reconciliation.
Under IPC backpressure the pending value is retained and the UI yields; it does not reread Word or wait for agent space. Disconnect cancels extraction and reconnect schedules new snapshots. Documents are not retained in an unbounded agent or UI queue. On shutdown the add-in requests worker cancellation without joining it. No HTTP/SignalR/authentication, database, AI, prose parser, entity detector or sync retry runs inside VSTO.
The ribbon has status, Connect / Sign In, Synchronise Now, Settings and Diagnostics. Native server sign-in is available through Connect; prose sync is unavailable; Synchronise Now means **local structure refresh only**. No large pane/embedded website. Native metadata/marker helpers do not expose a remote mutation operation in protocol v1; no Word prose writer exists. Interop marker removal uses `Delete(false)` to preserve text.
## Server and protocol boundaries
The agent is not connected to the old user-only Word presence hub. Native chapter preview now uses browser-approved, verifier-bound four-hour Data Protection grants with current security-stamp and book/subscription checks. No token or cookie crosses IPC or is saved in a Word document. Session-aware SignalR routing remains a subsequent phase. Browser cookie scraping, password storage and forged authentication are not implemented. Do not claim Context/Intent/native live synchronization; existing Office.js/browser coordination stays intact.
Server fixes in this branch independently retain hub signatures and event names. Migration 230 adds an atomic owned-build acknowledgement procedure. Old browser/Office.js callers may omit preview/document fields; the server still verifies authenticated build ownership, current access and the exact active manuscript/book/project association. Supplied identifiers must match. Completed acknowledgements are idempotent and cannot be regressed by a late failure. Code depends on migration 230 before any future server deployment; no live migration/deployment is performed by this prototype.
## Future prose synchronization contract
`ProseSynchronizationMode`: Automatic / OnSave / Manual. Word remains prose authority. Future agent work will compare scene-level snapshots/hashes, enqueue only changed scenes after the chosen trigger, submit expected server revision and idempotency key, and refuse stale acknowledgements. No full-novel upload, server-to-Word prose rewrite or automatic expensive AI reanalysis is implied. A save event must return immediately and only enqueue a later trigger; never wait for sync.
`DeferredWorkQueue` implements the bounded durable scheduling substrate for metadata-only intents: 128 scene slots, newer-revision supersession, mode/quiet-time gating, atomic file replacement and idempotency acknowledgement. It is deliberately **not wired to a prose sender or authenticated account** in Phase 1. Account/environment isolation, encrypted optional prose caching, expiry/retention policy, scene hash mapping and server revision API remain required before activating offline prose synchronization.
## Verification
From repository root, serially:
```sh
dotnet build PlotLine.slnx
dotnet run --no-build --project PlotDirector.NativeCompanion/Tests/PlotDirector.Companion.Tests.csproj
dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj
node PlotLine.Tests/Browser/word-companion-regressions.cjs
```
The explicit `--word-marker-security` specialist command applies migration 230 only to the hard-coded existing synthetic database `PlotDirector_Phase2_20261103_2305` after checking its synthetic-only marker, then rolls back all security fixture mutations. Never repoint it at Development or Production.
See [Windows validation](WindowsValidation/README.md) before any desktop acceptance or distribution. Phase 1 requires review; full migration is not authorized by this implementation.