diff --git a/Docs/WordCompanion/2026-11-07-native-import-synchronisation-fix.md b/Docs/WordCompanion/2026-11-07-native-import-synchronisation-fix.md new file mode 100644 index 00000000..8023f059 --- /dev/null +++ b/Docs/WordCompanion/2026-11-07-native-import-synchronisation-fix.md @@ -0,0 +1,90 @@ +# Native manuscript import and synchronisation correction — 7 November 2026 + +Application source: `e4ce822b0bf5700eed1f043178d7c0a674bd056a`, shared branch `codex/word-companion-native-phase1-20261104`. Safely fast-forwarded the clean Atlas worktree from `1ccb6c4` to Windows commit `25c75ad` before editing. Windows version16 association/save fixes and qualified installer metadata are preserved. Application source is now **1.0.0.17**; no Windows packages were built or installed on Atlas. + +## Confirmed causes + +### Failed scene analysis + +The historical fixes `794606f` (structural Word paragraph mapping) and `845b42e` (trailing boundary normalisation) were inspected first. The established onboarding importer extracts through Office.js (`word-companion-host.js`); the native intake builds the same `ManuscriptScanParagraphMap` / `ManuscriptScanSourceParagraph` contracts and calls the same `ManuscriptStructureAnalysisService`. There is no separate DOCX-upload parser in the current onboarding controller/service path. + +The actual Development failure at 16:19:29 and 16:19:37 was a JSON numeric syntax error at `$.sceneBoundaries[3].confidence`: the provider returned `"confidence": 0. Nine` and then `0. nine`. Both attempts failed parsing before scene-coordinate validation. An earlier chapter showed the same defect but succeeded on retry. + +A private read-only probe of the actual failed chapter's durable capture found **97 contiguous structural paragraphs and 99 source paragraphs**, with monotonically increasing Word paragraph identities. It passed the canonical analysis/mapping service with a synthetic response containing the observed malformed confidence token. This probe made no provider call, saved no invented scene, printed no manuscript prose and removed its temporary protected source file. It verifies the actual input mapping, not the narrative quality or complete contents of the original failed AI response. The complete original failed response was not persisted by the previous implementation; the precise parser path/excerpts are recorded in service logs. + +Two additional defects were confirmed: successful chapter analyses existed only in a local list and were discarded when a later chapter failed; the native intake inserted leading material as a numbered, included chapter instead of applying the original importer's front-matter behaviour. + +### Stale book list and disconnected wizard + +- The chooser bound a snapshot of the book list when opened and did not request a fresh list or update the open chooser as the catalogue changed. +- Connection checks used an interlocked early return, so callers could finish without waiting for an already running refresh. +- The agent published only documents with `Book > 0`; the server rejected `BookId == 0`; the wizard filtered live presence to the selected book. A first-time manuscript could therefore be visible locally but invisible to the server/wizard until an association already existed. +- The wizard reduced the resulting states to connected/disconnected and could not explain authenticated-without-Word, Word-without-document or an unassociated manuscript. + +## Corrections + +### Canonical analysis and retry + +`StoryIntelligenceJsonRepair.cs` now performs a narrowly scoped, reported repair for an unambiguous spelled fractional digit in a **Chapter Structure confidence** field, such as `0. Nine` → `0.9`. It scans JSON strings safely; prose strings are untouched. Scene ordinals and paragraph coordinates are never repaired by this new rule. Unknown malformed responses still use the existing single retry and then fail explicitly; the existing validator and boundary normaliser remain authoritative. + +`OnboardingService.AnalyseApprovedChaptersAsync` checkpoints chapter results using a SHA-256 of the full canonical request: preview/book/chapter identity, reviewed title/number, prose, original paragraph mapping and story context. Identical successful chapters are reused; failures are retried; changed requests do not reuse stale results. The same canonical AI service still performs all analysis. Existing location, character, asset, summary and review stages are retained. + +Migration **239_ManuscriptAnalysisCheckpoints.sql** adds a bounded JSON sidecar column and `dbo.OnboardingManuscriptChapterAnalysis` to the existing durable capture table. Dapper repository calls enforce user ownership and current project access. Accepted `Payload` and `PayloadHash` are never rewritten. Checkpoints are server-owned, not trusted from client preview JSON. No credentials, consent, active jobs or Word sessions are recreated. + +Native front matter is preserved separately for review, excluded by default in the canonical preview store, labelled **Front matter**, and does not shift numbered story chapters. Initial known front-matter headings use the established Office.js vocabulary. Plain documents without chapter headings still retain the existing single-manuscript fallback. Existing explicit author inclusion decisions are not silently changed. + +### Live connection and book selection + +- The chooser awaits a coalesced connection/book check on opening and updates its options when authorised book data changes. +- Book creation/editing through the established `BookService` changes a bounded, account-specific catalogue nonce in the existing presence store. Existing presence/installation heartbeat responses carry it. The agent refreshes authorised books when it changes; an invalidation during an in-flight check is not lost. No extra polling loop or authentication mechanism was introduced. Background updates arrive on the existing heartbeat cadence; chooser opening requests a fresh check immediately. +- Authenticated unassociated documents publish metadata under `BookId = 0`. Such leases cannot claim saved chapter/scene data. Word-running/no-document is reported separately from Word unavailable. +- The existing wizard's explicit Import manuscript request can select one trustworthy active/unique unassociated capture-capable session. It carries the authorised destination book on the existing exact-session command. The agent refreshes book access and associates locally before requesting extraction. An existing book association takes priority. An inactive unassociated document is never substituted for an active document belonging to another book; ambiguous or stale sessions fail safely. +- Wizard labels distinguish disconnected, authenticated/no Word, Word/no manuscript, unassociated manuscript, wrong book and ready-to-import. An unassociated eligible manuscript can start an explicit first import. Office.js remains a supported fallback. +- No opening, heartbeat, reconnect, catalogue refresh or association automatically uploads prose. + +### Marker messaging + +Native Detect Scenes and build/recovery messages now state that accepted text is processed on the server and **Word markers are not rewritten**. The original Office.js marker/save instructions remain conditional for that implementation. No marker-write-back subsystem was added. Existing native saved-position mapping remains limited to trustworthy unchanged session/revision data. + +## Verification + +| Check | Result | +|---|---| +| Managed solution build, including Windows-targeted agent | Passed, zero warnings/errors; VSTO host not built | +| Full application executable harness | 416 checks passed | +| Native portable executable harness | 265 checks passed, including lost-invalidation race, new-book refresh, unassociated presence and explicit wizard association | +| `--native-import-corrections` | 13 checks passed: observed confidence defect, strict malformed-coordinate refusal, source mapping/duplicates/manual breaks/blanks/front matter, checkpoint resume/invalidation | +| `--native-companion-http` | Passed actual loopback authentication, own unassociated presence, cleared foreign scene claims, ownership and existing import/security behaviour | +| `--native-tray` | Passed durable capture, first-time import, refusal to reassign another book, disconnection/restart and existing saved mapping | +| Guarded synthetic SQL regression | Passed real checkpoint JSON/prose round-trip, immutable source/hash, idempotency, changed request isolation, populated cross-account read/write refusal, revoked membership and rollback cleanup | +| Headless browser connection regression | Passed all wizard states, stale lease handling, explicit-only transfer and Office.js fallback | +| Existing native workspace browser regression | Passed Context/Intent following/disconnection and status clearing | +| Live Development, fresh synthetic author/book | Passed normal browser approval **before book creation**, catalogue invalidation/new book visibility without restart, unassociated first capture, durable intake, disconnected review, explicit configured AI scene analysis with no connected Word client, saved scene mapping and two reused workspace windows | +| Final Development capture follow-up | Final `e4ce822` deployment repeated the normal new-book/unassociated capture, durable source and workspace flow successfully without another AI call | +| Live SQL assertions | Exact accepted synthetic prose and canonical saved scene prose matched; native build Complete/NotRequested; successful chapter checkpoint present | + +The live test used a scripted HTTP native client and Linux headless browser, not Microsoft Word or the Windows tray. Its AI request contained only the isolated synthetic test chapter. A database-backed retry test and service-level failure injection establish resume behaviour; no real author's failed import was automatically rerun. + +The live synthetic account, project, book, captured source and generated scenes were removed. The existing normal account cleanup hit its pre-existing onboarding-state FK issue; only the explicitly verified fixture's onboarding state was removed, then normal account cleanup succeeded. Private fixture credentials were deleted. This unrelated product deletion defect was not refactored. + +## Development delivery + +- Both databases were backed up with COPY_ONLY/CHECKSUM and passed `RESTORE VERIFYONLY`: + - `/var/opt/mssql/backup/PlotDirector_Development_before_native_import_20261107T164506Z.bak` + - `/var/opt/mssql/backup/PlotDirector_Synthetic_before_native_import_20261107T164506Z.bak` +- Migration239 applied to the guarded synthetic database first, then to **PlotDirector_Development**, through the verified application principal. No existing numbered migration was edited. +- Active-work guards passed before migration/deployment. Release: `/srv/apps/plotdirector-dev/releases/e4ce822-20261107T172533Z`. +- Previous deployment preserved: `/srv/apps/plotdirector-dev/current-before-e4ce822-20261107T172533Z`. +- Published and deployed `PlotLine.dll` SHA-256: `2c87f960e4efb5445e83423b5a2b5377ab0b53b9ec8a23e95b50283012a9665d`. +- The live configured-AI run used the initial `a0cee0d` deployment; its analysis implementation is unchanged in the final document-selection safety follow-up. The final deployment repeated capture/workspace tests without a second AI call. +- Service active; public Development GET200; authenticated live workflow and SQL evidence passed. Production unchanged. + +## Boundaries and author recovery + +The accepted failed manuscript remains durable and can be reviewed/retried without another Word capture. The previous implementation did not checkpoint its earlier successful chapter analyses, so those pre-fix results cannot be recovered retroactively and may need one reanalysis. New successful results survive a later failure and server restart. + +The existing wizard stores review selections in memory. Following this Development restart, an already open pre-update import may require its chapter review to be confirmed again; the captured manuscript is not lost. This correction does not silently recreate author approval or redesign the entire review-persistence system. + +The wizard's automatic association does not silently write Word metadata. The existing Remember-in-document option and a normal Word save remain the path for a durable file association when the document has no persistent identity. The qualified version16 metadata/save behaviour is retained. + +Actual Windows extraction, chooser behaviour, tray recovery and author-owned manuscript acceptance require the version17 Windows qualification in [the handover](WindowsHandover/2026-11-07-native-import-correction.md). Do not test confirmed import against a populated primary book without a disposable copy/destination. No new native scene marker write-back is claimed. diff --git a/Docs/WordCompanion/WindowsHandover/2026-11-07-native-import-correction.md b/Docs/WordCompanion/WindowsHandover/2026-11-07-native-import-correction.md new file mode 100644 index 00000000..93ca233a --- /dev/null +++ b/Docs/WordCompanion/WindowsHandover/2026-11-07-native-import-correction.md @@ -0,0 +1,26 @@ +# Windows handover — native import correction, 1.0.0.17 + +Shared branch: `codex/word-companion-native-phase1-20261104`. +Application commit: **e4ce822b0bf5700eed1f043178d7c0a674bd056a**; subsequent handover commits change documentation only. + +1. Preserve the Windows worktree, discover the configured tracking remote, fetch and fast-forward this branch. Stop on divergence; no rebase, force push, new branch or worktree. Verify the application commit is an ancestor of HEAD. +2. Preserve the qualified **1.0.0.16** installation, signed installer, settings and approved device identity. Do not clear protected storage or repeat browser approval as an update procedure. Source version is **1.0.0.17**. `WindowsValidation/Setup/Release.json` intentionally remains version16: align the existing unified installer's version/ProductCode for17 on Windows, retain UpgradeCode and qualify the16→17 upgrade. Do not introduce another installation mechanism. +3. Use the existing `PlotDirector.NativeCompanion/WindowsValidation/Update-WordCompanion.ps1` to build the clean shared source and developer payload. Then use the existing `WindowsValidation/Setup/Build-Setup.ps1` with that validated `-PackagePath`, exact `-ExpectedSourceCommit`, a new `-OutputDirectory` and existing `-CertificateThumbprint`. Run existing package/upgrade checks. No automatic installation, Word launch, desktop control, trust bypass, IDE repair or unrelated refactoring during unattended qualification. Distinguish Codex's execution profile/registry from the real interactive installation. +4. The changed native components are the **managed agent**: book chooser refresh/coalescing, catalogue invalidation, unassociated presence, Word-running status and explicit wizard book association. Protocol additions are optional JSON metadata (`WordRunning`, `CatalogVersion`) and the existing `AdapterCommand.BookId` destination. Existing Word extraction and required IPC capabilities are retained; VSTO interop source was not changed in this correction, only its version metadata. Build both components as one coherent signed unified payload. + +Development already has the matching server/API changes and migration239. Existing version16 bound-document transfers remain supported; version17 is needed for the corrected chooser and unassociated-session workflow. No new configuration or sign-in flow is required. + +Atlas evidence: managed Windows-targeted build passed; 416 application checks, 265 native checks, 13 focused corrections, guarded SQL ownership/round-trip/rollback tests, HTTP/browser regressions and a live synthetic configured-AI Development import passed. The live test used scripted native HTTP rather than Word COM. See [the report](../2026-11-07-native-import-synchronisation-fix.md). + +## Scheduled human checks + +- Upgrade through the unified installer with Word closed by the author. Confirm existing approval/settings survive and reconnect automatically. +- Start Companion first, open a disposable manuscript in Word with **no book association**, then create a fresh test book in the existing PlotDirector import wizard. Open Change book: the new book must appear without restarting. Leave the chooser open during another book creation and verify it updates on the normal heartbeat cadence. +- Check the wizard distinguishes Companion off, approved/no Word, Word/no manuscript, manuscript unassociated, wrong-book association and correct-book ready. Activate/switch documents, disconnect/reconnect, and confirm there is no arbitrary cross-book selection. +- Request Import manuscript explicitly. Verify it selects the intended unassociated document and destination book, shows progress and durably accepts text. No prose upload should occur before this request. +- Review front matter: preserved, labelled, unchecked by default; story chapter numbering starts correctly. Check repeated paragraphs, blanks, manual line breaks and page/section breaks in the source review. +- After acceptance, close/disconnect Word and run Detect Scenes in the website. It must continue server-side and must not claim to write Word scene markers. Review exact saved prose before confirming anything against an important book. +- Retry a failed chapter on the same capture; completed unchanged chapters should be reused, not sent to AI again. The already failed pre-fix capture may need review reconfirmation and one repeat of previously uncheckpointed work; it does not require a fresh Word capture. +- Preserve the existing Remember-in-Word option and normal save confirmation for persistent file associations. New automatic wizard association does not silently modify Word metadata or prose. + +Do not import into a populated primary author book for qualification. Commit/push only validated Windows fixes to this same branch and report the exact source SHA, signed installer location/hash, automated results and genuinely completed interactive tests. diff --git a/Docs/WordCompanion/WindowsHandover/README.md b/Docs/WordCompanion/WindowsHandover/README.md index ad928d89..b0196547 100644 --- a/Docs/WordCompanion/WindowsHandover/README.md +++ b/Docs/WordCompanion/WindowsHandover/README.md @@ -1,3 +1,9 @@ +# Current handover — native import correction, version17 + +Use [the version17 correction handover](2026-11-07-native-import-correction.md) first. It supersedes version15 build pins and preserves the subsequently qualified version16 installer baseline. Development now includes the matching server and migration239. Windows work is the existing unified installer build and focused native qualification, without redesigning the interface or authentication. + +--- + # Current handover — compact Companion UI, version15 Use [the version15 UI handover](2026-11-07-UI-Redesign.md) first. It identifies the final application source commit, actual changed projects, Atlas test evidence, Development cover API deployment and focused Windows acceptance requirements. The managed interface is implemented; Windows owns native qualification and preparing the existing signed unified installer. **The qualified version14 installer baseline is preserved**, and its release pins must be deliberately advanced on Windows for version15. Do not install or drive Word during unattended qualification.