20 KiB
Native Word Companion Phase 3: AI integration and Windows workflow
Outcome
The native Companion now has an implemented Word → per-user agent → authenticated PlotDirector chapter AI → native review path. It extends the existing VSTO/.NET 10/named-pipe architecture. The Development server API is deployed and its protected public routes were verified. A live call through the configured existing chapter provider (gpt-5-mini) returned two valid scenes for a short synthetic chapter, with correct native position mapping. No author manuscript was submitted by Atlas.
The new Windows developer build identifier is 1.0.0.5; VSTO assembly/file and application-manifest version inputs are aligned to that identifier. New VSTO compilation, signed-package generation, installation, native UI interaction and Word performance remain unverified until Windows qualification. Atlas did not alter the laptop or its working 1.0.0.4 installation. Source syntax/PowerShell parsing and portable package tests are not substitutes for those Windows checks.
Everything uses the shared branch codex/word-companion-native-phase1-20261104, fast-forwarded from the reported Windows checkpoint 76a92f9; Phase 1 smoke-test fixes at 726a3d5 remain ancestors. No additional branch/worktree was created. Implementation milestones were committed and pushed during work: af243d3 (server/pairing/agent), baa1326 (review/update workflow), cdc75a3 (stale cancellation/source-identity guards), 0a404d2 (registration-free legacy helper and review header layout), 718c996 (pairing body bounds and current-user process ownership). Final evidence/documentation follows those commits on the same branch.
Existing AI implementation reused
OnboardingService.AnalyseApprovedChaptersAsync already calls IManuscriptStructureAnalysisService.AnalyseChapterAsync one chapter at a time. That service:
- Loads the existing
Chapter-Structure-Prompt-V2.mdand prompt version. - Uses
IStoryIntelligenceClient/StoryIntelligenceClient, the existing OpenAI Responses transport, configuredEffectiveChapterStructureModel, output-token limit, timeout and provider retry/quota handling. Native code contains no provider key/model override. - Uses the canonical JSON parser, repair/retry, boundary normaliser and validator, then maps numbered structural paragraphs back to source Word paragraph indices.
- Returns scene ranges, suggested titles, confidence/reasoning and optional other chapter information. Invalid/ambiguous output can fail validation rather than becoming canonical scenes.
The new API wraps this service; it does not implement another AI parser, prompt or import engine. Native results map those paragraph indices to the captured Word Start/End spans. Web onboarding/import still follows its original path and persists/materialises through its existing services. Native previews do not create an onboarding build, import canonical records or trigger expensive subsequent scene/entity/whole-book analysis.
A shared StoryIntelligenceRequestLimiter now gates actual typed-client provider requests using MaxGlobalConcurrentAiRequests, including both existing web calls and native previews. Native preview jobs additionally allow at most two workers (no greater than configured global capacity), one active chapter per user, and the configured native-preview per-book concurrency. Provider-side quota failures and retries remain owned by the existing client. Background database claim limits remain on the existing runner; this work does not duplicate its job persistence.
Architecture and message flow
flowchart LR
Word[Word UI / STA] --> V[VSTO ribbon, bounded extraction, modeless review]
V <-->|existing named pipe v1, optional chapter-ai-v2; values only| A[Per-user .NET 10 agent]
A -->|launch normal sign-in/approval page| Browser[System browser]
Browser -->|existing cookie login / 2FA + antiforgery approval| Pair[PlotDirector pairing]
Pair -->|one-use verifier-bound exchange over TLS| A
A -->|explicit one-chapter HTTPS request + short-lived bearer| API[Native companion API]
API --> Auth[Current security stamp, book access and subscription]
API --> Cache[Bounded user/request deduplication and cancellation]
Cache --> Existing[Existing chapter analysis service / prompt / provider]
Existing -->|validated paragraph boundaries| API
API -->|bounded mapped results| A
A -->|40-result IPC pages / progress| V
V -->|author double-click; STA Range.Select only| Word
Local detection stays separate: existing chapter/scene markers and Word headings are recognised without upload, and their provenance is shown as Existing marker or Local structure. Each detected chapter has explicit Start/End limits; ambiguous candidates still require author review. AI scene rows are labelled AI, never counted as marker discoveries or assigned trusted server scene IDs.
Only explicit confirmed AI: analyse checked chapters starts chapter capture/upload. The author selects an authorised book and chapter nodes from the displayed local-results page. Selected chapters queue sequentially within that document, with chapter N/M and reading/AI progress. The agent buffers one bounded chapter and performs HTTP off Word's thread. Existing local structure is reused; this does not reread/upload the full novel for each chapter.
The API uses a process-local, user/request-keyed content-hash cache. Duplicate identical requests share the same provider task/result; a reused ID with different content is rejected. A failed chapter does not delete successful chapter results. Retry requires another explicit author action; there is no silent network replay after uncertainty or agent restart. Server cancellation is best effort and cannot undo provider costs already incurred. A network failure may leave an unknown outcome; the UI warns about potential retry charges.
Authentication and authorisation
There was no suitable existing desktop flow; the site used cookie authentication. The new lightweight pairing flow retains normal browser login/2FA:
- Agent generates a random verifier and sends its SHA-256 challenge to the HTTPS site root selected by the author.
- A short-lived random pairing code opens a browser approval page. The author compares the code suffix and explicitly approves. Approval requires an authenticated cookie and antiforgery token; GET never issues a grant.
- Only the original verifier can redeem the approved, one-use code. Pairings expire after five minutes and are globally bounded/rate limited, with a 4 KiB pairing body limit.
- A Data Protection grant contains the server-authenticated user/security stamp and a four-hour absolute expiry. The native-only bearer handler rechecks the current account, lockout and database security stamp on every authenticated request.
- Book access and Story Intelligence entitlement are checked server-side before work, including duplicate/cache-hit requests. Existing global edit-content subscription enforcement also remains in place. A book ID or local document GUID is never proof of access.
No password, API key, browser cookie or bearer token is embedded in the add-in, sent through IPC, written into Word or persisted by the agent. Only the configured site address is remembered. Disconnect forgets the in-memory grant; restarting the agent requires sign-in again. Native grants do not authorise unrelated cookie-only site endpoints. Password/security-stamp changes or lockout revoke access. Ordinary website logout does not revoke this independent grant; use Companion Disconnect or let its four-hour expiry elapse.
Upload confirmation pins the document session, local snapshot, book and a nonsecret authentication-context nonce. Account/site switching cancels active work and invalidates queued consent across Word instances; old consent is refused before HTTP upload. The IPC capability is chapter-ai-v2 for this scope protection. Credentials still never cross IPC.
All author-selected roots must be HTTPS with no embedded credentials, query, fragment or path. The agent does not bypass certificate validation or follow HTTP redirects for API requests. Browser approval uses the normal site account workflow; no developer impersonation/workaround was added.
Native chapter analysis sets private diagnostics mode so response JSON, narrative excerpts and POV evidence are not written to chapter-service logs. Provider-client error logs no longer include exception bodies that could contain raw provider responses. Agent/IPC diagnostics remain identifiers, timings, status and queue depth. Suggestions can contain bounded narrative titles/reasoning in the author-facing UI; that is review data, not telemetry.
Native review and responsiveness
The small modeless Windows Forms review now uses a resizable, DPI-aware layout with an automatically sized header, a thin progress strip, chapter trees, expand/collapse, separate local/AI tabs, a full evidence inspector and contextual “Showing X–Y of Z” paging. Repeated diagnostic evidence is removed from the main rows. It uses system UI components/Segoe UI and adds no UI dependency. Book selection resets on document switching to avoid silently applying another document's choice. File names stay in the Word UI and are not included in diagnostics or IPC.
Tree updates are bounded to 40 rows per view and avoid rebuilding unchanged pages. Results hold their exact document/session/revision/request identity; wrong-document, obsolete revision, cancelled and stale-page responses are refused. A late cancellation cannot cancel a replacement chapter. Backpressured AI cancellation forces asynchronous link reset/reconciliation instead of silently losing the cancel. Successful AI rows stay in Word memory after agent loss/cancellation; no automatic resubmission occurs.
All Word COM calls remain on the original STA with existing instrumentation and cooperative bounded extraction. There are no HTTP/SignalR/authentication calls, parser work, synchronous waits or worker-thread COM calls in VSTO. Navigation is an author-triggered, scheduled Range.Select at the captured position; it never writes prose. Save/close does not wait for AI and cancels affected work. A single COM call is not preemptible; the 20–30 ms target still requires Windows measurement.
Windows update/build/install
The complete procedure is WindowsValidation/Phase3-AI.md. No VM/profile change or IDE launch/repair is required.
After the initial clean fast-forward that brings the script onto the laptop, the repeatable update/build command is:
& .\PlotDirector.NativeCompanion\WindowsValidation\Update-WordCompanion.ps1
It verifies the existing shared branch, preserves/refuses local changes or unpublished/divergent history, fetches/fast-forwards, locates existing Office build tools, reuses the installed/current-user signing certificate, builds managed Release and signed VSTO without registration, runs relevant native and server/HTTP tests, publishes the separate agent, then verifies a complete version/SHA/hash-inventoried package under the Windows Downloads known folder. Source changes or a changing Git HEAD during build stop packaging. Preparation never installs, stops Word, changes the current registration, launches Visual Studio/Installer, modifies PATH/workloads or alters machine-wide configuration/trust.
Close Word normally and explicitly install using the path printed by the helper:
& .\PlotDirector.NativeCompanion\WindowsValidation\Install-WordCompanion.ps1 -PackagePath '<printed package path>' -StopAgent
It checks package hashes/manifest shape/dependencies, stops only the explicitly authorised current-user/session agent, uses the existing per-user PlotDirector registry key, stages immutable versioned files under LocalAppData and backs up the previous registration. The 1.0.0.4 files remain intact. A rerun does not replace the rollback backup. Office still validates signing/trust; the script never adds a certificate to a trust store. A separate explicit rollback restores the immediately previous registration:
& .\PlotDirector.NativeCompanion\WindowsValidation\Install-WordCompanion.ps1 -Rollback -StopAgent
The legacy Build-Developer helper also now omits Office registration. Its original output layout is retained; the preferred complete workflow is Update-WordCompanion.
Verification evidence
Retained evidence records commands and outcomes:
| Verification | Result |
|---|---|
| Linux managed solution | Passed, zero warnings/errors. VSTO deliberately excluded. |
| Full application executable harness | 407 checks passed, including native crypto/mapping/authorisation/cache tests and existing web AI/import coverage. |
| Native harness | 169 assertions passed, including existing capacity-slot assertions, 250k-word local workload, explicit upload, mapping, frame bounds, cancellation/replacement, authorisation failures, document isolation and existing real pipe/agent-host recovery. |
| Actual Kestrel HTTP fixture | Passed cookie login, approval view, antiforgery rejection/approval, verifier redemption, bearer/security-stamp enforcement, book/subscription refusal, canonical service mapping and duplicate-result reuse. Synthetic provider and repositories; no live database. |
| Live configured provider | Existing gpt-5-mini service returned two valid mapped scenes for a synthetic four-paragraph chapter. No author manuscript/database writes. This is provider/service proof, not Word desktop proof. |
| Chromium | Existing Context/Intent stale-response and Writer launcher regressions passed. These screens were not rewritten. |
| PowerShell | Every script parsed with official portable PowerShell 7.6.9. Portable package tests passed valid-fixture inventory, tamper refusal and non-Windows fail-closed guards. Placeholder fixture signatures do not establish real Office trust. |
| VSTO | C# syntax and XML checked. No Windows VSTO compilation/execution or real UI/performance measurements on Atlas. |
A new malformed-response regression exposed an uncaught InvalidDataException that could leave AI review waiting; the agent/client recovery paths were fixed, and the final native run passed all 169 assertions. Unknown IPC handshakes now enter recovery rather than faulting the worker. One initial Linux pipe-harness attempt failed with a broken pipe during handshake; a subsequent isolated serial run passed all 169 assertions. The cause was not conclusively established; the failed log is retained. A publish to /tmp hit a temporary-filesystem quota; the failed scratch output was removed and publishing succeeded in the disk-backed artifact directory. Neither event stopped the running Development service. No tests were weakened to hide these failures.
Development delivery and database state
The Development database was explicitly verified as PlotDirector_Development and background/import restart gates were idle. A unique COPY_ONLY/checksummed backup was made. The application's database login could create the backup but lacked permission for RESTORE VERIFYONLY; an administrative check verified that same backup valid. Existing forward-only migration 230 was then applied and its procedure presence/hash checked. No new Phase 3 migration was added and no manuscript rows were changed. Production was not contacted or altered.
The Development application was published/deployed with server source at 718c996 (later changes are agent/IPC/native UI/scripts/documentation; HTTP contracts remain compatible). Runtime configuration, environment, uploads and Data Protection keys were preserved. The immediately previous Development application remains backed up at (the pre-Phase 3 backup at current-before-native-word-phase3-cdc75a3-20261105111817 is also retained):
/srv/apps/plotdirector-dev/current-before-native-word-phase3-718c996-20261105114542
Release archive:
/srv/apps/plotdirector-dev/releases/native-word-phase3-718c996-20261105114542
Both PlotLine.dll and the shared protocol DLL hashes match the publish output. The service is active; local/public roots return 200. Verified public TLS probes confirm pairing start (200/no-store), oversized pairing refusal (413), unapproved redemption (202/no grant), normal login redirect for approval (302) and unauthenticated books/AI routes (401). No authenticated author upload was made against the live website. Post-deploy logs had no application errors and the existing local HTTPS redirect-port warning; public reverse-proxy TLS requests succeeded.
Limits and remaining Windows work
- AI suggestions are transient read-only previews, not canonical imported scenes, stored onboarding decisions, a scene/entity intelligence pipeline or native Context/Intent/SignalR following. Existing Office.js remains available.
- Native document/project binding is not automatically migrated from the Office.js settings bag. The author explicitly selects an authorised book for each document's AI request; this does not persist a new binding. Unpersisted native GUIDs remain provisional as in Phase 1.
- Chapter input is bounded to 120,000 Word positions/text characters and 10,000 paragraphs; the server default maximum is 120,000 configurable downward/upward to its bounded range, but the agent remains capped at 120,000. Up to 500 validated scenes/chapter are returned in 40-row IPC pages. Queue selection is capped at 256 chapters and review storage at 5,000 AI rows/document. Reaching the review limit is reported and stops remaining chapter uploads rather than silently paying for undisplayable results. First-page/visible-page selection is intentional; there is no silent whole-book upload.
- Provider request timeout/retry and model/output limits use existing configuration; native jobs have a five-minute server deadline and six-minute agent bound. Cache/credentials/jobs are process-local, not durable refresh/offline AI queues. Server restart loses request deduplication; automatic replay is disabled. Retrying an unknown outcome can charge again.
- Successful results survive individual failures and agent restart in the open Word session, not Word closure/reopening. No review content or credentials are saved into documents or an unencrypted prose cache.
- The existing observed-revision model does not catch every same-length edit while a document is already dirty. Results represent a captured snapshot, not a complete edit journal. Re-detect after edits; no automatic import relies on these positions. Main-document text only; other stories such as footnotes/text boxes are not integrated.
- Native previews use chapter text and the existing prompt's default optional context; they do not duplicate onboarding's full known-character/context preparation. This can affect POV/contextual interpretation; boundaries/confidence/reasons still use the canonical service and validator.
- Windows still must verify Office build/signing/manifest portability, certificate/registry discovery, per-user process-SID checks, upgrade/rollback, modeless focus/DPI/resizing, live author login and actual Word→AI→review/navigation. Measure typing, scrolling, save/close, queue depth and COM/batch latency with the working manuscript and 190k/250k fixtures across three documents. Do not accept syntax/provider results as Word performance evidence.
Short Windows Codex prompt
On the existing shared branch, preserve local work and fast-forward to the latest remote. Read
Docs/WordCompanion/2026-11-05-phase3-ai-integration.mdandPlotDirector.NativeCompanion/WindowsValidation/Phase3-AI.md. Run Update-WordCompanion.ps1 using existing tools/certificate, capture SHA/version and package results, and do not launch/repair the IDE. With author approval and Word closed, explicitly install the printed package with Install-WordCompanion.ps1 -StopAgent; retain rollback. Connect to the Development HTTPS site with normal browser login, locally detect structure, select an authorised book and a small synthetic chapter, explicitly request AI, verify AI provenance/positions and unchanged manuscript/markers. Then qualify multi-document cancellation/recovery, DPI/focus and 190k/250k responsiveness. Commit/push necessary Windows fixes/evidence to the same branch; no Production deployment.
Implementation stops at Phase 3 handover and Windows qualification. No public installer/updater or further migration phase was started.