18 KiB
Native Companion integration correction — 6 November 2026
Scope and delivery
Shared branch: codex/word-companion-native-phase1-20261104. Clean Atlas checkout was fetched and fast-forwarded from bda826b to Windows handover dcaab6e before development. No alternate branch/worktree, Production change, Windows package build or installation. Existing Windows maintenance/installer fixes are preserved.
Managed/VSTO source version: 1.0.0.13. This is source awaiting Windows qualification, not an installed or qualified release. WindowsValidation/Setup/Release.json remains pinned to 1.0.0.12 deliberately; the unified installer must be aligned and qualified on Windows. The fetched maintenance report records an unresolved MSI payload-copy blocker; this work does not claim to fix it.
Implemented communication path
sequenceDiagram
participant W as Word STA scheduler
participant A as Existing per-user agent
participant P as PlotDirector presence
participant I as Existing manuscript wizard
participant D as SQL accepted-source store
participant S as Existing analysis/review services
A->>P: authenticated heartbeat (exact instance/session/manuscript/book/revision)
I->>P: explicit Import manuscript request
P-->>A: negotiated wizard-capture command on heartbeat
A->>W: existing bounded snapshot request with capture ID
W-->>A: validated paragraph fragments in scheduled batches
A->>I: authenticated complete capture (no AI inside Word)
I->>D: immutable source preview + hash
D-->>I: committed acceptance
I-->>A: acknowledgement of exact capture ID/revision
I-->>I: existing chapter review
Note over W,I: Word and agent may disconnect after acceptance
I->>S: explicit existing scene analysis and subsequent review stages
S->>D: existing canonical manuscript sources/build persistence
The new endpoint is an intake adapter, not another importer or AI engine. NativeManuscriptCapture.Build maps native fragments into existing ManuscriptScanPreview/source paragraphs. Wizard coordinates are one-based paragraph indices; actual Word character positions are kept separately. Existing chapter and scene marker IDs are reused only when they belong to the authorised book. Heading 1/marker detection is not labelled AI analysis. Character, location, asset, summary and existing review services are retained.
StartOnboardingManuscriptScan keeps its Office.js signature and fallback. Native capture is negotiated with wizard-capture-v1; old native installations receive an update-required explanation rather than an unsupported command. Routing requires one unambiguous active document for the wizard's book. It never selects an arbitrary latest Word connection.
Registration and save-state corrections
- Reconciliation preserves live document records, association and heartbeat sequence instead of unregistering/recreating every document.
- Short pipe reconnects can restore a verified session-only association for the same manuscript/session/authentication context for two minutes. This is not credential persistence across agent restarts.
- Process-wide monotonic sequences avoid per-document counter reset on reconnect. Sequence-conditioned removal prevents delayed disconnect requests deleting a newer registration.
- Invalid/foreign saved markers are cleared without rejecting otherwise authorised document liveness. Book authorisation remains mandatory. Cursor coordinates are retained in accepted leases.
- Presence success updates the local acknowledgement timestamp only after HTTP success. Failures retry at a bounded interval and identify registration/HTTP failure instead of calling everything a “saved-data request.”
- Website header and writing-workspace Hub status consume the native lease store, with Office.js compatibility fallback. Website connectivity is unchanged. The redundant strip below the ribbon is removed.
- Word selection observations include
Document.SavedwithBackgroundSavingStatus == 0, on the Word thread. BeforeSave never cancels, waits for network, forces a save or claims success. It invalidates the observation revision and pending extraction conservatively. - Word's saved-state observation is distinct from PlotDirector's exact capture acknowledgement. Checking connection does not upload prose. A fresh, explicitly requested wizard capture is the manual synchronisation fallback.
Durable acceptance and safety
Migration 237_DurableManuscriptCapture.sql adds OnboardingManuscriptCaptures and the Dapper-only OnboardingManuscriptCapture procedure. These are accepted onboarding staging sources, not a second canonical manuscript store. Canonical chapter/scene sources continue to be written by existing import services.
Persistence checks active project access, scopes source retrieval by author, validates JSON, hashes immutable payloads and rejects conflicting reuse of a preview ID. Book deletion cascades staging-source removal. Wizard reset clears the current pointer without destroying explicitly addressable accepted sources; starting a new scan cannot resurrect an older preview while the scan is running. No credentials or server-bound encrypted capture are put into Word or the source record.
Transfer requests expire after 20 minutes, or when their exact Word lease disappears before acceptance. Failures/cancellation notify the existing wizard. Once accepted, source retrieval does not depend on live presence and can recover after a server restart. Transfer instructions in progress are intentionally ephemeral and are not automatically replayed after restart.
The agent permits one pending extraction/upload at a time, uses the existing 16 Mi-character/fragment-budget limits and 200,000-fragment ceiling, and uses a 120-second HTTP intake timeout. Request bodies are bounded at 100 MiB; these are maxima, not a guarantee that every document below a word count fits. No prose enters diagnostics. Explicit browser wizard requests authorise only that exact transfer; the older optional retained-AI-capture permission is not silently expanded into a standing upload permission.
Repeated delivery of the same capture ID/content is idempotent; altered content is rejected. Acceptance failure cannot become a successful tray acknowledgement. Review and build are still explicit actions; capture completion alone does not create canonical story records or automatically start AI.
Normal Companion and writing windows
The normal tray UI now contains sign-in, connection checks, active document, authorised book association, settings and diagnostics. Chapter detection/selection/AI controls and Context/Intent launch controls are removed from the visible interface. Existing extraction, AI and historic review contracts remain for compatibility; they are not a competing normal author workflow.
Website launchers use one stable named window for Context and one for Intent across book changes. Repeated launches from the launcher reuse/focus the existing window without unnecessarily reloading an unchanged scope. Book scope stays in the URL. Dedicated windows reuse the existing theme-aware _WritingCompanionLayout, register their roles with existing writing-window infrastructure, and subscribe to native presence invalidations. The iframe fills remaining viewport height instead of a fixed vh panel.
Each workspace has independent manual scene selection and following. Manual selection pauses following; no unresolved scene is guessed from stale positions. Saved data remains available without Word. Context and Intent remain distinct; no new AI intent engine or planning records were introduced.
Material limitations — do not call this full native migration
- No real Word/VSTO execution or Windows visual/performance qualification on Atlas. The managed Windows target compiles; the VSTO host and packages have not been built here.
- Newly imported markers are not written back into Word by this change. Native server builds record
MarkerStatus=NotRequested, separately from completed canonical import. Office.js marker/save acknowledgement remains unchanged. - Scene mappings made from an approved native capture are valid only for its exact document session, manuscript, revision and saved state. Dirty/changed documents do not reuse positional evidence. Existing marks can be read through bounded snapshots; this is not proven continuous scene tracking while typing. Fresh capture/manual saved-scene navigation is required when no trustworthy mapping exists.
Document.Savedobservation is not an independently verified filesystem save-completion event. Native revision observation has the existing limitations for same-length edits between observations; BeforeSave invalidation and conservative dirty-state handling avoid treating that as acknowledged prose synchronisation.- Accepted source is durable. Existing later-stage review/job persistence semantics are retained, not rewritten; this is not a guarantee that every in-flight analysis resumes after an application-server crash. A small synthetic chapter was subsequently exercised through the live configured provider; this does not qualify VSTO extraction or server-crash recovery of every existing analysis stage.
- Browser popup/PWA focus is subject to browser policy. Actual installed-PWA window chrome and monitor placement need the normal Windows human pass.
- Setup's version12 maintenance/copy blocker and version13 installer alignment remain Windows work. Do not substitute direct
.vstoregistration or another installer.
Verification
dotnet build PlotLine.slnx --no-restore: zero warnings/errors.- Normal executable regression harness: 415 passed.
- Native portable harness: 217 passed, including actual named-pipe foundations, exact-document capture frames, reconciliation/reconnect association, background handoff and acknowledgement.
- Native intake tests: blank and 220,000-word fragmented source, exact prose, one-based paragraph/character mapping, incomplete input, wrong author/grant, persistence failure, immutable retries, disconnected Word, simulated server recovery and stale/dirty scene mapping.
- Actual loopback HTTP/WebSocket security regression passed with a synthetic provider: browser-approved pairing, antiforgery, bearer/security-stamp checks, book/subscription access, AI idempotency and presence invalidation. No live paid-provider call.
- Browser:
native-companion-workspace.cjsandword-companion-regressions.cjs: following/manual pause, disconnection, stale responses, scene scope, shared badge, distinct/reused role windows and book changes. - Guarded real SQL regression:
PlotLine.Tests/Sql/NativeManuscriptCapture.sqlon PlotDirector_Phase2_20261103_2305; exact recovered prose, duplicate safety, other-account denial, revoked-access denial, current-pointer reset, book-deletion cleanup and unauthorised write refusal. Fixtures rolled back. - Development migration applied only after idle-work gates and copy-only/checksummed backup with
RESTORE VERIFYONLY:/var/opt/mssql/backup/PlotDirector_Development_before_native_capture_20261106T220229Z.bak. - Development deployment and authenticated smoke results are recorded in the delivery addendum after deployment; nothing here claims live Windows integration.
Windows qualification pass
Keep the shared branch, inspect/preserve local work, identify the configured remote, fetch and fast-forward. Build the exact pushed source using the existing entry point:
.\PlotDirector.NativeCompanion\WindowsValidation\Update-WordCompanion.ps1 -CertificateThumbprint '<existing developer certificate thumbprint>'
It prepares a signed developer package, not an installation. Do not run installation unattended, launch Word, close applications or invoke Computer Use during the build pass. Preserve the actual qualified installation and settings. In the existing WindowsValidation/Setup architecture, align release/version/product identity to the newly qualified 1.0.0.13 payload, resolve/verify the already reported maintenance-copy blocker and exercise existing payload/package/upgrade tests. Do not bypass source/version guards or introduce another installer. Installer outputs must contain both VSTO and tray; inspect the real interactive user's installation rather than sandbox-local registry evidence.
Human Word checks on an isolated test book:
- Link a saved test manuscript; verify top-right website status and tray registration agree. Reconnect the pipe/agent and recheck association. Try three open books.
- From website Import manuscript, read the correct selected Word document; observe progress/cancellation, then accepted chapter review. Check exact prose and paragraph mapping. Do not confirm import against a populated primary book.
- Close Word/agent after acceptance; run existing scene/location/character/asset/summary review stages in the browser. Confirm import only into the isolated test book and test duplicate/conflict handling.
- Open Context and Intent twice each; verify separate reused windows, full-height layout, correct book and independent manual pause. Check saved information with Word disconnected.
- Observe saved/dirty Word state. Edit/save during extraction; verify interruption/retry and no false acknowledgement. Do not mistake marker-free snapshot mapping for continuous live following after edits.
- Inspect native COM timings, typing/scroll/save/close responsiveness on a 200,000+ word document. Confirm no unrequested manuscript edits or uploads.
Delivery addendum — deployed and live-tested
Web/server application commit 269bb324ca was pushed to the shared branch and deployed to Development. Later commits containing this addendum, the repeatable live test and VSTO assembly-version alignment descend from that application commit; the deployed web/server binaries are unchanged by those additions. Build the latest shared-branch HEAD on Windows and record that exact SHA rather than substituting the deployed web SHA for the package's actual source.
Release: /srv/apps/plotdirector-dev/releases/269bb32-20261106T221333Z. Prior application preserved at /srv/apps/plotdirector-dev/current-before-269bb32-20261106T221333Z. Published/deployed PlotLine.dll SHA-256 both edb6fb9c1281fc1cfc3e64aaa6bc0958283457572ca1ded3bda12ac56c090c61. Service active; local and public HTTPS GETs returned 200. Idle-work guards passed before replacement and after testing. SQL237 is applied; there are no Production changes or Windows installation/package operations.
The live Development pass used a freshly provisioned isolated author and normal application project/book creation. It verified:
- Normal login and browser-approved desktop pairing, without exporting cookies or logging credentials.
- Real native registration, saved state and the single top-right website indicator.
- The existing wizard's Import manuscript action delivered an exact-session capture request to a simulated native client. No actual Word/VSTO execution is implied.
- Authenticated capture acceptance, SQL persistence of exact synthetic source and existing chapter review after client disconnection.
- Explicit existing AI scene analysis after the desktop client had disconnected, resulting in a completed canonical server build and saved scene prose. A direct SQL SHA-256 comparison confirmed canonical prose matched the accepted body after paragraph-terminal CR trimming. No model-generated prose replaced the source.
- A subsequent heartbeat resolved the approved capture's actual saved chapter/scene IDs using the exact manuscript/session/revision mapping.
- Real Context/Intent Razor windows without application ribbon/navigation, separate names, reused launches and saved information with Word disconnected.
Normal regressions passed 415/415; native checks passed 217/217. The real HTTP/WebSocket security regression, browser workspace/stale-response checks, embedded-theme regression and guarded synthetic SQL checks passed. VSTO assembly/file versions were aligned to 1.0.0.13 in source; this static version correction is not a Windows build result.
Repeating the Development smoke test
PlotLine.Tests/Browser/native-integration-development.cjs is an explicit, serial, Development-only test. It refuses an ordinary author identity. Provision a fresh private fixture through the existing helper (which verifies the Development DB and backs it up):
dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj -- --dev-browser-identity create /tmp/pd-dev-browser-native-qualification.json
node PlotLine.Tests/Browser/native-integration-development.cjs /tmp/pd-dev-browser-native-qualification.json
Add --analyse only for an explicit small live-provider/canonical-import check on a fresh fixture account. Without that option, no AI or canonical import is requested. After the browser run, execute its generated /tmp/native-integration-live-check.sql using the verified Development database procedure to compare actual records/prose. Never run this test against a real author's account, primary manuscript or Production. It does not operate Windows or launch Word.
Separate finding encountered during fixture cleanup
The existing account-deletion procedure fails on FK_UserOnboardingState_AppUser after a user has completed onboarding steps. This predates the new capture table: project/book deletion had already removed native source correctly, but remaining onboarding state blocked AppUser deletion. It was not repaired as an unrelated application change in this sprint.
For these isolated fixtures only, an operator script verified Development, the fixture email/display-name namespace, ownership, expected synthetic project names and absence of collaborators; removed only that fixture's UserOnboardingState; then retried the normal authenticated account-deletion workflow. Both test identities/private credential files were removed and a SQL check confirmed no account/capture remained. Account-cleanup commands alone should not be reported as passing for an onboarded fixture until this existing FK issue is addressed or that guarded operator cleanup is performed. No real author records were touched.