43 KiB
Phase 3B.4 Windows/Word execution handover
Prepared on Atlas, 20 November 2026. Preparation only: no Windows build, installation or physical acceptance was performed. Run the acceptance matrix in order using the Windows Codex prompt. All repository paths below are relative to the checkout root. Windows paths containing placeholders must be resolved locally; none identifies an available package by assertion.
1. Exact source and server baseline
- Shared branch:
codex/word-companion-native-phase1-20261104. Atlas preparation started at5b7eb27; fetch its documentation descendants. The exact handover commit is the commit containing these documents. Record the full actual build SHA; do not hardcode a future documentation commit into package metadata. - Required application ancestry:
bcef86e1cc47764ae2165e4d9d1232fd666bbe13(3B.1),80f7cb516b52bcf1a0d42493700f0bde85ac776c(3B.2/3B.3).5b7eb27contains its completion evidence. Later application/native/script changes require review before using this baseline; documentation-only descendants are expected. - Required matched add-in/agent 1.0.0.41, MSI 1.0.41.
PlotDirector.NativeCompanion/DeveloperVersion.props,Vsto/Properties/AssemblyInfo.csandWindowsValidation/Setup/Release.jsonagree. ProductCode{EF24354B-9ADC-4C69-9F8C-9BD261CB0291}; UpgradeCode{641A087B-9779-458C-B290-BCBBAD49319A}. Source metadata does not establish an existing .41 package or installed version. - Server: https://dev.plotdirector.com/ only. At 2026-11-20 23:51 UTC: service active since 22:45:45 UTC; deployed informational version
1.0.0+80f7cb516b52bcf1a0d42493700f0bde85ac776c. DLL SHA-2565d7f9b4db127f89a7fb866a932b2c14af5d5b7b96cae4b1bd25fc43e10d3c16d;writer-word.jsSHA-25658123f11f50145323db3c086768c0dd77e3442d16fe8b1d9d8720c7f9b130d54, matching Phase 3B.3 deployment evidence. No discrepancy found. Read-only recheck at 2026-11-21 00:04 UTC returned the same version/hashes. Atlas readiness evidence and static command/path qualification are retained separately from future physical runs. - TLS-validated anonymous GET
/and/Account/Login: 200. Native GET/api/native-companion/connection,/api/native-companion/books,/api/native-companion/books/0/chapter-sync: 401 as expected; website status/connection/Writer GETs redirect to login. Source confirms protected endpoint definitions. This is route/version readiness, not authenticated API or book qualification. Atlas created no account, authenticated no author, sent no write request, queried no database and restarted/deployed nothing for this task. - No new migration or configuration delta is required by .41: changes from the preceding deployed implementation introduce only native/UI safeguards and tests; no SQL/Program/appsettings delta. Existing installed schema/feature configuration was not re-audited by direct DB access. Earlier actual Development fixture acceptance is in
Docs/Writer/Writer-Phase3B2-3B3-Completion.md. Windows must still establish its authorised account/book, runtime feature eligibility and native connection before importing.
Authority reconciliation: Docs/Writer/Writer-Phase3B-Word-Companion-Integration-Audit.md identifies F1/F2/R1/R2; 3B.1 fixes F1/F2; 3B.2/3B.3 fixes the reproduced R1/R2 software paths. Current code supersedes old version pins, migration instructions, memory-only-auth claims and standalone investigation/popover layouts in historical README files. Do not replay old migrations or redesign the present three-column Review. The setup README's version21 heading is historical; current Release.json is authoritative.
Contracts to carry into execution:
| Contract | Current authority / qualification implication |
|---|---|
| Pipe protocol | PlotDirector.NativeCompanion/Protocol/Messages.cs: protocol 1; required sessions-v1,positional-selection-v1,batched-snapshot-v1; unchanged handshake. Client/AgentLink.cs offers acknowledged-navigation, chapter-range/live-text/native-position, chapter-sync, paragraph, capture and existing workflow capabilities. Verify negotiated capabilities, not just a version label. |
| R1 | Vsto/WordAdapter.cs timestamps selection before COM reads with optional Message.WordObservedUtc. Agent/TrayCoordinator.cs withholds saved/cursor/chapter/scene proof at age >=45s, while preserving document transport. It rejects stale navigation at queueing and delivery. Old frames can fall back to receipt time; matched .41 is required. No new polling subsystem. An inactive document can become ineligible until observed again. |
| Navigation | Browser /WriterWord/Availability, POST /WriterWord/Navigate, GET /WriterWord/Navigation; native /api/native-companion/instances/{instance}/documents/{session}/presence. Exact grant/book/manuscript/instance/session/revision, saved-state proof and capability checks remain. Commands expire after 25s in PlotLine/Services/NativeCompanion/NativePresenceStore.cs. 202 means requested; only matching actual adapter result establishes completion. |
| R2 | PlotLine/wwwroot/js/writer-word.js retains explicit instance/session choice in account/book-scoped tab sessionStorage; disappeared choice stays disconnected, never silently becomes another copy. Same-session recovery differs from a new-session reopen. Storage-unavailable fallback retains choice in page memory only; record storage policy and test refresh in normal supported storage conditions. Separate tabs/windows need independent explicit selection. |
| Authentication / association | Docs/WordCompanion/Persistent-Authorisation.md, Client/DocumentBinding.cs: existing PKCE browser approval, same-user DPAPI-protected installation state, rotating renewal and account/site-scoped bindings. Restart does not require resetting approval. Website logout can revoke installations. Never copy installation-state.dat or bearer credentials to evidence. |
| Synchronisation | Word unsaved content, accepted canonical prose and current verified positions are separate. Docs/WordCompanion/2026-11-12-vsto-range-synchronisation.md and WindowsHandover/2026-11-12-v1.0.0.33-post-edit-synchronisation.md explain saved-state fencing, selective reconciliation, reuse and periodic range checks. No forced save, no guessed association. |
| Writer / Review | Global Focus is independent of Word cursor and saved objective. Docs/Navigation/FocusSynchronisationCorrection.md, Phase 3B.1 report: chapter-only/unmapped fallback clears obsolete precise targets, dirty editors defer; historical reviews need original live source/content proof. Context/Intent I1 is optional and is not added to this qualification implementation scope. |
2. Windows prerequisites
Inspect and record rather than install/repair anything automatically:
- Normal authorised Windows desktop user with the existing checkout and desktop session. Current package requires x64 Windows; agent target is
net10.0-windows10.0.19041.0, framework-dependentwin-x64. Target build 19041 is a compile target, not proof of Microsoft's current OS support. Record actual OS edition/build, architecture, hardware, power plan and free disk space; verify the machine supports its installed .NET 10 runtime. ARM64/x86 Windows are not qualified by this package. - Licensed desktop Microsoft Word with VSTO (not Word web/macOS/mobile). Actual edition/build/channel and 32/64-bit architecture must be read from Word About. VSTO is AnyCPU/.NET Framework 4.8; project OfficeVersion 15.0 and Office 16.0 debug registry configuration are not a guarantee covering every Office version. Qualify the actual installed Word; if both Office bitnesses are claimed, separate runs are needed.
- Existing Visual Studio Office/VSTO workload (
Microsoft.VisualStudio.Workload.Office), Office PIAs, Framework 4.8 developer pack, VSTO runtime, .NET 10 SDK and x64 Windows Desktop 10 runtime.vswhere.exe, VS MSBuild, NETFX 4.8mage.exe, Framework64csc.exe, Windowsmakecab.exeand Windows Installer COM must exist. No IDE launch/F5/Clean is necessary; Office Clean can unregister the installed add-in. - Existing PowerShell 7 x64 for the packaging commands: current setup scripts use modern .NET APIs (
SHA256.HashData,Convert.ToHexString) unavailable in Windows PowerShell 5.1. Record$PSVersionTable. Use Windows PowerShellpowershell.exe -STAonly for the optional chapter COM measurement script, which uses FrameworkMarshal.GetActiveObject. - Existing approved developer signing certificate with accessible private key in
Cert:\CurrentUser\My, correct Code Signing usage, valid dates and approved signer identity. Inspect public metadata only. Never export keys, invent a thumbprint, create a certificate, alter trust stores or disable security. The script can discover the installed/remembered certificate; obtain human confirmation of the selected signer if uncertain. - Existing Chromium browser (Edge/Chrome/etc.), normal website login and an actually installed Development PWA, version/installation scope recorded. If PWA/browser/runtime/workload is missing, stop for human provision approval; Linux simulated standalone acceptance does not cover it.
- Human-approved disposable Development account or permission to create one through normal UI; authorised empty project/books and import/synchronisation/annotation/session/AI costs. No credentials in chat/Git. This preparation provisioned nothing. Never use Production account data or an existing author's books as a shortcut.
- DNS/TLS access to Development, normal browser approval for Companion, correct server and eligible book shown in Companion. Existing
%LOCALAPPDATA%\PlotDirector\Companion\installation-state.datandserver-url.txtare private; do not dump/reset them. If binding is wrong, ask the human before switching an existing account. - Existing diagnostic tools: Word/Companion Troubleshooting,
WindowsValidation/Measure-Processes.ps1, Task Manager; WPR/VS debugger only if already available and explicitly authorised. Do not enable system-wide tracing or attach/suspend Word merely to manufacture a stall.
3. Build and package commands
Run from the repository root in an existing x64 PowerShell 7 session. Stop on any nonzero native exit code; PowerShell does not automatically throw for git/dotnet. Do not use an execution-policy bypass. Keep raw staging/evidence outside the repository until the update/build gates finish: Update-WordCompanion.ps1 refuses any dirty/untracked worktree.
$ErrorActionPreference = 'Stop'
function Check-Exit { if ($LASTEXITCODE -ne 0) { throw "Native command failed: $LASTEXITCODE" } }
$branch = 'codex/word-companion-native-phase1-20261104'
git status --short --branch; Check-Exit
# If any local changes or another branch: preserve them and stop; do not reset/stash/switch automatically.
if ((git branch --show-current).Trim() -ne $branch) { throw 'Wrong shared branch' }
if (git status --porcelain=v1) { throw 'Preserve local changes before building' }
git fetch origin; Check-Exit
git pull --ff-only; Check-Exit
$source = (git rev-parse HEAD).Trim(); Check-Exit
git merge-base --is-ancestor 80f7cb516b52bcf1a0d42493700f0bde85ac776c HEAD; Check-Exit
git merge-base --is-ancestor 5b7eb27 HEAD; Check-Exit
git diff --name-only 80f7cb5..HEAD -- PlotLine PlotDirector.NativeCompanion PlotLine.Tests
# Expected: no application/native/test changes at this handover baseline. Stop/reconcile unexpected changes.
$native = 'PlotDirector.NativeCompanion'
$wv = "$native/WindowsValidation"
$release = Get-Content "$wv/Setup/Release.json" -Raw | ConvertFrom-Json
$version = ([xml](Get-Content "$native/DeveloperVersion.props" -Raw)).Project.PropertyGroup.ApplicationVersion
if ($version -ne '1.0.0.41' -or $release.version -ne $version -or $release.msiVersion -ne '1.0.41') { throw 'Wrong native release' }
Get-Content "$native/Vsto/Properties/AssemblyInfo.cs" | Select-String 'AssemblyVersion|AssemblyFileVersion'
. "$wv/DeveloperPackage.ps1"
$runId = [DateTime]::UtcNow.ToString('yyyyMMddTHHmmssZ') + '-windows-' + $source.Substring(0,8)
$stage = Join-Path (Get-DownloadsFolder) ("PlotDirectorQualification/" + $runId)
if (Test-Path -LiteralPath $stage) { throw 'Run staging directory already exists' }
New-Item -ItemType Directory -Path $stage -Force | Out-Null
$PSVersionTable
dotnet --info; Check-Exit
dotnet --list-runtimes; Check-Exit
$vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio/Installer/vswhere.exe'
& $vswhere -latest -requires Microsoft.VisualStudio.Workload.Office -property installationVersion; Check-Exit
The supported complete pipeline is PlotDirector.NativeCompanion/WindowsValidation/Update-WordCompanion.ps1. Set $thumbprint to the locally verified approved existing certificate's thumbprint (public identifier, no key material). Run once:
& "$wv/Update-WordCompanion.ps1" -CertificateThumbprint $thumbprint -NoSync
# Script throws on checked failures. It builds/tests/signs a developer payload; NEVER installs.
-NoSync is valid only after the explicit safe fetch/fast-forward above; script requires the tracked remote tip to be an ancestor. It verifies source cleanliness and ancestry, discovers Office-equipped MSBuild and Desktop runtime, then executes:
dotnet build PlotLine.slnx -c Release --disable-build-servers -m:1 /p:UseSharedCompilation=false(implicit restore).- Release native foundation and six focused application native suites (
--native-companion,--native-companion-http,--native-workflow,--native-tray,--native-import,--intent-assessment). These are disposable tests, not live Word acceptance. - VS MSBuild
PlotDirector.NativeCompanion\Vsto\PlotDirector.WordAddIn.csproj /restore '/t:Build;VisualStudioForApplicationsBuild' /p:Configuration=Release /p:PrepareForRunDependsOn=CopyFilesToOutputDirectory /p:SignManifests=true /p:ManifestCertificateThumbprint=$thumbprint /p:ApplicationVersion=1.0.0.41. - Installed NETFX 4.8
mage.exeupdates the publisher/application digest and signs the VSTO deployment manifest with SHA256RSA. dotnet publish PlotDirector.NativeCompanion/Agent/PlotDirector.Companion.Agent.csproj -f net10.0-windows10.0.19041.0 -c Release -r win-x64 --self-contained false -o <staging>/Agent.- Inventories hashes, source SHA and signer into
package.json, validates and atomically promotes the developer package. An existing package at the computed path is validated and returned without rebuilding/rerunning tests. Record whether this occurred; rerun the explicit managed checks below and verify the package SHA matches$source. Do not silently delete/relabel the existing package to force a pass.
The ordinary solution excludes classic Office build dependencies; NativeCompanion.Windows.sln is the native Windows solution. Do not replace the VS MSBuild step with dotnet build of VSTO, use the legacy Build-Developer.ps1/direct-registration install path, or run Office Clean/F5.
Additional required managed checks not supplied by the update script:
dotnet run --no-build -c Release --project "$native/Tests/PlotDirector.Companion.Tests.csproj"; Check-Exit
dotnet run --no-build -c Release --project "$native/Tests/PlotDirector.Companion.Tests.csproj" -- --word-observation; Check-Exit
dotnet run --no-build -c Release --project "$native/Tests/PlotDirector.Companion.Tests.csproj" -- --chapter-sync; Check-Exit
dotnet run --no-build -c Release --project PlotLine.Tests/PlotLine.Tests.csproj; Check-Exit
Expected Atlas reference counts are 304 foundation, 453 chapter and 633 application PASS checks, not fixed Windows performance targets. Investigate a failure; never edit production logic just to satisfy a count. If the update script reused a package, run its six named focused native application suites explicitly using the same dotnet run --no-build -c Release --project PlotLine.Tests/PlotLine.Tests.csproj -- <switch> syntax. No dotnet test substitute.
Package and inspect using actual script parameters:
. "$wv/DeveloperPackage.ps1"
$package = Join-Path (Get-DownloadsFolder) "PlotDirectorWordCompanion/$version-$($source.Substring(0,8))"
$inventory = Test-DeveloperPackage $package
if ($inventory.commit -ne $source -or $inventory.version -ne '1.0.0.41') { throw 'Wrong payload source/version' }
# $stage: a NEW private directory outside the repo; never an existing baseline/package directory.
$setup = Join-Path $stage 'setup'
& "$wv/Setup/Test-DeveloperPayload.ps1" -PackagePath $package -ReportPath (Join-Path $stage 'payload.json')
& "$wv/Setup/Build-Setup.ps1" -PackagePath $package -ExpectedSourceCommit $source -OutputDirectory $setup -CertificateThumbprint $thumbprint
# $baselineMsi: locate and verify a preserved signed older-family MSI. No path is assumed to exist.
& "$wv/Setup/Test-SetupPackage.ps1" -PackagePath $package -SetupDirectory $setup -BaselineMsi $baselineMsi -ReportPath (Join-Path $stage 'package.json')
# Optional artefact input: set to a locally verified historical failed-setup directory if available.
$failedSetup = $null
if ($failedSetup) {
& "$wv/Setup/Test-UpgradeRegression.ps1" -FailedSetupDirectory $failedSetup -CorrectedSetupDirectory $setup -ReportPath (Join-Path $stage 'upgrade-regression.json')
} else {
'BLOCKED historical failed-setup negative control: artefact unavailable' | Set-Content (Join-Path $stage 'upgrade-regression-blocked.txt')
}
Get-FileHash (Join-Path $setup 'PlotDirectorCompanionSetup.exe') -Algorithm SHA256
Get-FileHash (Join-Path $setup 'PlotDirectorCompanion.msi') -Algorithm SHA256
Get-AuthenticodeSignature (Join-Path $setup 'PlotDirectorCompanionSetup.exe') | Select-Object Status,StatusMessage,SignerCertificate
Get-AuthenticodeSignature (Join-Path $setup 'PlotDirectorCompanion.msi') | Select-Object Status,StatusMessage,SignerCertificate
Do not execute the conditional upgrade command with undefined/fabricated paths. If the baseline MSI is unavailable, package/CAB upgrade qualification is BLOCKED, not waived; ask for the preserved artefact. Build-Setup verifies both manifests with the SDK mage.exe -Verify, exact application file versions, source ancestry and product/upgrade codes, then creates/signs the embedded MSI/EXE with existing tools. It writes setup-evidence.json. The independent package test verifies MSI/CAB, every payload hash, upgrade range, component GUIDs, per-user/asInvoker registration and embedded MSI.
Signing policy: a matching hash alone is insufficient. Record mage verification, approved signer thumbprint, certificate validity and Authenticode status/message. The repository permits developer trust-only NotTrusted/UnknownError statuses; Test-SetupPackage.ps1 restricts these to a message indicating untrusted developer chain. This is not public distribution trust or permission to alter trust stores. Any changed signer, invalid digest, expiry, missing private key or other UnknownError stops packaging/installation. Have the human explicitly review the existing developer trust prompt when needed; never recommend disabling signing/security.
4. Installation and verification procedure
Stop after producing a reviewable package and preflight report. Obtain the human's scheduled interactive installation/physical-test authorisation, identify package path/hash/signer, account and disposable fixture scope. Have the human save and close all Word windows normally and resolve save prompts. Do not terminate Word, other users' agents or Visual Studio.
Before and after installation, in the actual normal user's context:
& "$wv/Setup/Inspect-UserInstallation.ps1" -OutputPath (Join-Path $stage 'installation-before-private.json')
This uses supported native MSI inventory/context/SID APIs; raw output contains identity/profile information and stays private. Do not use Win32_Product (may trigger repairs). Capture a sanitised summary of version, MSI feature state, registration target, file hashes and same-user context.
Have the human run PlotDirectorCompanionSetup.exe from normal File Explorer. Do not run --install to evade its review prompt; it is an internal supported relaunch argument, not an unattended/silent acceptance command. Bootstrapper installs per-user under %LOCALAPPDATA%\Programs\PlotDirector Companion, preserves application state, checks Word is closed, stops only the exact same-session installed agent, exports registration/VSTA metadata, and starts the tray after a successful upgrade. It does not install prerequisites or establish certificate trust. A packaged Codex child can relaunch through WMI into the normal user context; the initial process returning zero is not proof installation finished.
Re-run Inspect-UserInstallation.ps1 to a new private filename. Verify through supported inventory:
- Correct current user, per-user unmanaged context 2, ProductCode .41, MSI version 1.0.41, Complete feature Local=3, not Advertised.
- Installed
PlotDirector.WordAddIn.dll,Agent\PlotDirector.Companion.Agent.exeandAgent\PlotDirector.Companion.Agent.dllfile versions 1.0.0.41; SHA-256s equal the signed .41 package. Client/Protocol may retain stable assembly versions: compare exact package hashes, do not demand .41 library versions. - Exactly the intended Word add-in registration; Manifest targets the installed
.vsto|vstolocal, LoadBehavior 3. Inspect Word File → Options → Add-ins/COM Add-ins and actual loaded ribbon/Diagnostics after human opens the disposable document. Registration alone does not establish load. - Actual running agent executable belongs to the installed path and current session, not a checkout/debug folder. Confirm PID/start time,
.41diagnostics, visible Open Companion and IPC. Window X hides the tray; it does not prove exit. - Existing Startup shortcut points to that installed tray. Launch/inspect it only during the authorised window. No reboot is required/authorised by this handover.
- Companion server is Development, author/account and eligible disposable book are correct, browser approval completes if needed, protected reconnection works. Do not reset existing approval/preferences to force success.
Read-only installed-byte checks (keep raw user paths private):
$installRoot = Join-Path $env:LOCALAPPDATA 'Programs/PlotDirector Companion'
foreach ($relative in @('PlotDirector.WordAddIn.dll','Agent/PlotDirector.Companion.Agent.exe','Agent/PlotDirector.Companion.Agent.dll')) {
$installedFile = Join-Path $installRoot $relative
$fileVersion = [Diagnostics.FileVersionInfo]::GetVersionInfo($installedFile).FileVersion
if ($fileVersion -ne '1.0.0.41') { throw "Installed version mismatch: $relative" }
if ((Get-FileHash $installedFile).Hash -ne (Get-FileHash (Join-Path $package $relative)).Hash) { throw "Installed bytes differ: $relative" }
}
Get-ItemProperty 'HKCU:\Software\Microsoft\Office\Word\Addins\PlotDirector.WordAddIn' | Select-Object Manifest,LoadBehavior
Get-CimInstance Win32_Process -Filter "Name='PlotDirector.Companion.Agent.exe'" | Select-Object ProcessId,SessionId,ExecutablePath
Logs: %LOCALAPPDATA%\PlotDirector\InstallerBackup\<timestamp>\setup.log, windows-installer.log (and optional local-feature log); agent %LOCALAPPDATA%\PlotDirector\Companion\agent.jsonl and .previous; Word Tools → Diagnostics and Companion Troubleshooting. Retain private raw logs, publish only sanitised extracts. Never restore registry exports blindly.
5. Fixture preparation
Create fixtures only after explicit permission for disposable local files and Development test data; use a new run directory, never real author files. Keep originals, per-test working copies and file hashes. Word must open them without repair before measurements count.
Existing pure-OOXML generator (no Word/server calls):
& "$wv/Generate-Fixtures.ps1" -OutputDirectory (Join-Path $stage 'raw-generated')
It creates Discovery-190k.docx (190,000 prose words/60-word paragraphs), Reckoning-250k.docx (250,000/60), two optional stress variants and fixtures.json. Word totals include headings. It embeds arbitrary legacy project/book IDs 1/101–104 and PD tags. Do not open raw outputs while connected and assume these IDs are safe. Create neutral working copies first, removing legacy bindings/tags. The following documented helper only edits new copies of these generated files; never feed it an author file:
Add-Type -AssemblyName System.IO.Compression.FileSystem
$raw = (Resolve-Path (Join-Path $stage 'raw-generated')).Path
$fixtures = Join-Path $stage 'fixtures'
New-Item -ItemType Directory -Path $fixtures -ErrorAction Stop | Out-Null
function New-NeutralFixture([string]$rawName,[string]$name,[int]$limit=0) {
if ($rawName -notin @('Discovery-190k.docx','Reckoning-250k.docx')) { throw 'Only generator outputs allowed' }
$src = Join-Path $raw $rawName; $dst = Join-Path $fixtures $name
if (Test-Path -LiteralPath $dst) { throw 'Never overwrite a fixture' }
Copy-Item -LiteralPath $src -Destination $dst -ErrorAction Stop
$zip = [IO.Compression.ZipFile]::Open($dst,[IO.Compression.ZipArchiveMode]::Update)
try {
foreach ($entryName in @('docProps/custom.xml','word/document.xml')) {
$entry = $zip.GetEntry($entryName); $reader = [IO.StreamReader]::new($entry.Open())
try { [xml]$xml = $reader.ReadToEnd() } finally { $reader.Dispose() }
if ($entryName -eq 'docProps/custom.xml') {
foreach ($node in @($xml.DocumentElement.ChildNodes)) {
if ($node.GetAttribute('name').StartsWith('PlotDirector.')) { [void]$node.ParentNode.RemoveChild($node) }
}
} else {
$ns = [Xml.XmlNamespaceManager]::new($xml.NameTable); $ns.AddNamespace('w','http://schemas.openxmlformats.org/wordprocessingml/2006/main')
foreach ($tag in @($xml.SelectNodes('//w:tag',$ns))) {
if ($tag.GetAttribute('val',$ns.LookupNamespace('w')) -match '^PD-(CHAPTER|SCENE)-') { [void]$tag.ParentNode.RemoveChild($tag) }
}
if ($limit -gt 0) {
$body = $xml.SelectSingleNode('/w:document/w:body',$ns); $count = 0
foreach ($node in @($body.ChildNodes)) {
if ($node.LocalName -eq 'sectPr') { continue }
if ($count -ge $limit) { [void]$body.RemoveChild($node); continue }
if ($node.LocalName -eq 'p') { $count++ }
}
}
}
$entry.Delete(); $replacement = $zip.CreateEntry($entryName)
$writer = [IO.StreamWriter]::new($replacement.Open(),[Text.UTF8Encoding]::new($false))
try { $writer.Write($xml.OuterXml) } finally { $writer.Dispose() }
}
} finally { $zip.Dispose() }
Get-FileHash -LiteralPath $dst -Algorithm SHA256
}
New-NeutralFixture 'Discovery-190k.docx' 'Small.docx' 30
New-NeutralFixture 'Discovery-190k.docx' 'Medium.docx' 500
New-NeutralFixture 'Discovery-190k.docx' 'Large-190k.docx'
New-NeutralFixture 'Reckoning-250k.docx' 'Large-250k.docx'
This helper is documentation-only and not Windows-executed on Atlas. Verify XML/property removal and Word opening before importing. If it fails, retain generated files and stop fixture preparation; do not repair Office or switch to author documents. Small has ~1,800 prose words; in Word insert two additional Heading 1 paragraphs before plain paragraphs 11 and 21 to make three clearly named chapters. Medium has ~30,000 prose words and five original chapter headings; verify actual structure/counts in Word. Add distinctive synthetic sentinel text at each chapter's first/middle/last paragraph, including one same-length replacement pair, then save and hash working baselines. No real names/content needed.
Use a new owned disposable project and distinct books for small, medium, 190k and 250k. Associate through Companion/import wizard and normal saved metadata only after inspecting the correct Development account/site/book; preview import/chapter mapping before confirmation. Never trust numeric legacy tags, filename or word count as association proof. Record actual assigned IDs locally; evidence may use stable aliases. Establish mapped and deliberately unmapped scenes through supported UI without assigning every paragraph by guesswork.
F2 fixture prerequisite: identify an existing authorised synthetic native AI review and its original captured saved document/session, or a locally verified supported UI path to create it with approved AI cost. The current compact tray does not justify inventing an old analyser button; this handover has not established a new review-seeding UI procedure. The known review/decision route is /native-companion/reviews/{reviewId}. If no genuine disposable fixture can be supplied, F13 is BLOCKED; do not seed SQL, use a private author's historical review, or treat the existing managed source-provenance fixture as physical evidence.
For B tests: make a new copy of the associated small working fixture in a separate directory under the same filename so it retains properties; record GUID equality and distinct live sessions. Do not strip this intentional copy. Also open the independent neutral medium fixture. Keep closed originals for recovery. For boundary tests use per-case working copies of the accepted small/medium baselines; record starting revision/paragraph IDs and expected topology, then insert/split/merge/reorder in Word. No real-author backups, Production import, bulk account reset or direct SQL fixture forging.
6. Ordered acceptance checklist
Execute matrix groups A → B → C → D → E → F → G. Stop on unsafe/wrong-document execution, corruption, identity substitution, unexpected source/server, invalid signature or material Word responsiveness loss. Preserve drafts/logs before recovery. A missing physical control/hook is BLOCKED, not PASS. Dependency-blocked later rows must still be recorded.
A build/package gate can finish unattended. Installation/Word/PWA interaction and synthetic Development mutations require the concrete interactive authorisation described above. That authorisation may cover the scheduled matrix once; do not request it again for each already approved ordinary test. Additional debugger/network fault injection, trust changes, account switching, uninstallation/rollback or terminating a process outside normal UI needs its own explicit scope. No uncontrolled hangs, debugger suspension, crash tests, global firewall rules or author-app closure.
No safe dedicated production observation-stall hook was found in Vsto, Client or Agent. The Tests/WordObservationTests.cs controlled clock is managed fixture coverage, not a physical hook. C04–C06 and fault-dependent D rows have explicit blocked paths. An inactive-document observation gap is a safe separate physical case, not proof of blocked COM. Do not add a runtime test switch or improvise a risky stall during this acceptance task.
Performance sources: WindowsValidation/README.md historical initial practical UI slices ~20–30ms and investigate >100ms COM calls; current Client/WordAccessScheduler.cs defaults 16 steps/15ms, nominal Word timer 25ms. These are scheduling budgets, not preemptible COM guarantees. WindowsHandover/2026-11-12-v1.0.0.33-post-edit-synchronisation.md records ~16s historical 48-chapter opening, an unmet 5–10s target and 19.615s recovered pass; these used another manuscript/device/version, not acceptance guarantees for synthetic 190k/250k.
Proposed thresholds needing approval before G (record APPROVED / DECLINED / NOT AGREED): no typing/scroll/ribbon p95 regression >20% and >50ms over matched add-in-disabled baseline; no unresponsive episode >1s; investigate every measured COM call >100ms; recovery to useful fresh context <=10s after work can safely resume; initial full verification <=60s on 190k and <=90s on 250k; saved one-chapter edit accepted <=15s after save/quiescence. These are proposed engineering gates, not historical promises. Report actual distributions even if no threshold is approved; mark performance acceptance NOT AGREED, not green. R1's 45s evidence policy and server's 25s command expiry are correctness contracts, not proposals.
7. Evidence recording instructions
Run ID: <UTC-yyyyMMddTHHmmssZ>-windows-<shortSHA>; never reuse a directory. Stage privately outside Git during clean builds; publish sanitised results under Docs/Writer/Evidence/Phase3B4/<run-id>/ after packaging. Atlas preparation evidence is separately under 20261120T235104Z-atlas-preparation and proves no physical run.
Suggested layout: environment.json, package.json (sanitised inventory metadata), readiness.json, results.jsonl, performance.csv, thresholds.json, report.md, cleanup.json, plus logs/, screenshots/, failures/. A JSONL row for every stable matrix ID:
{"id":"B04","startUtc":"<ISO8601>","endUtc":"<ISO8601>","result":"PASS|FAIL|BLOCKED|NOT_RUN","mode":"physical|managed-only","fixture":"small-copy-A","source":"<40-char SHA>","expected":"explicit A retained disconnected","actual":"<observation>","evidence":["screenshots/B04.png"],"blocker":null,"cleanup":"<result>"}
Record environment: Windows edition/build/architecture, CPU/RAM/storage/power, Word product/build/bitness/channel, VS/MSBuild/tool versions, SDK/Desktop/Framework/VSTO versions, PowerShell version, browser/PWA product/version/scope, loaded add-in/actual agent versions and paths (sanitised), actual source SHA, package filenames/SHA-256, signer/status/manifest verification, server URL and version/hash or Atlas attestation with time. Record test start/end UTC and local/UTC clock offset; correctness evidence relies on timestamps.
Capture native operation/queue metrics through Diagnostics/Troubleshooting and rotated agent logs before/after each case. Measure-Processes.ps1 -OutputFile <new.csv> -Seconds 600 samples Word/agent process CPU totals, memory and handles once/sec without COM; compute CPU utilisation from delta total CPU / elapsed / logical processors, retain raw totals and PID changes. It buffers until complete: let it finish normally. No author process tracing.
Optional real selected-chapter measurement, only after the human has closed other disposable Word windows normally, verified a single intended Word process/document, selected a complete saved synthetic chapter and authorised read-only COM instrumentation:
powershell.exe -STA -File "$wv/Measure-ChapterSync.ps1" -ProtocolAssembly (Join-Path $package 'PlotDirector.Companion.Protocol.dll') -OutputFile (Join-Path $stage 'selected-chapter.json')
Do not use -IncludeLegacyParagraphXml for ordinary acceptance. This attaches to running Word, does not select/save/close, and measures cross-process COM wall times; it is not typing responsiveness. For UI COM p50/p95/p99 only use complete measured samples from already-approved diagnostics; current aggregates provide counts/total/max and over-threshold counts, so record percentiles unavailable if samples are absent. Do not infer p95 from a maximum or timestamp after a stall.
Performance CSV fields: run,id,fixture,trial,coldWarm,startUtc,endUtc,openMs,addinMs,firstContextMs,verifyMs,saveToAcceptMs,typingP95Ms,scrollP95Ms,ribbonP95Ms,comP95Ms,comMaxMs,cpuDeltaSeconds,wordPrivatePeak,agentPrivatePeak,queuePeak,chapterRequests,transferredBytes,reuses,reconciliations,cancelMs,recoveryMs,result,evidence. Use at least three comparable trials for each size/action, add-in-disabled baseline then enabled; record unavailable counters explicitly. Obtain agent transferred bytes only from a verified existing native counter or an approved agent-specific network trace. Browser DevTools/HAR measures browser traffic, not the agent HTTPS channel; it cannot establish agent upload bytes. No ready per-agent byte-capture script was established by this preparation. Record UNAVAILABLE/BLOCKED for that metric if safe instrumentation is absent; do not install an interception proxy or change TLS trust. If browser HAR is used for UI traffic, keep it private and export only redacted counts/timings, never headers/tokens/request prose. Hashing-only fixtures never substitute for physical timing.
Never commit credentials, cookies, pairing codes/URLs, DPAPI state, private keys, registry exports, full raw installation identity, author paths/content, unsanitised HAR or system traces. Local fixture prose can remain outside Git; commit fixture metadata/hashes, not large DOCX files. Record failure reproduction, last safe state, session/revision aliases, expected/actual, missing prerequisite and cleanup outcome. Commit evidence/results documentation only on the shared branch, normal push; no force push or application changes.
8. Troubleshooting and rollback
| Failure | Safe supported response |
|---|---|
| Build/dependency restore | Retain command/tool/source/error output. Check existing SDK/Office workload/mage paths. No IDE repair/install/Clean, source regeneration or silent dependency upgrade. Stop for provision approval if absent. |
| Signing | Stop before installation; inspect public certificate validity/usage/identity, mage result and exact digest. Missing key or trust failure is not permission to export keys/change trust/disable checks. |
| Package inspection | Preserve .41 output and baseline separately. Missing older MSI/failed setup artefact is BLOCKED; do not fake a baseline or relabel a file. |
| Failed installation | Preserve InstallerBackup logs/export privately and native MSI inventory. Do not rerun in loops, kill Word or edit ACLs/registry. After diagnosis and explicit approval, re-running the same valid unified EXE uses supported repair/recache. Verify files and Complete=3, not just exit code. |
| Add-in not loading | Human checks Word COM Add-ins/Disabled Items; record load error, registration Manifest and actual file hashes, duplicate registrations and existing trust. No automatic re-enable/reset/LoadBehavior edits, ClickOnce purge or broad registry import. Use normal VSTO trust UI only with approval. |
| Agent not starting | Verify installed exe/DLL hashes, Desktop 10 x64 runtime, current-session PID, Startup shortcut, private agent logs and paused state through diagnostics. Open Companion normally with approval; do not delete paused/auth files or kill another session. |
| Pairing/server failure | Verify clock, TLS, Development URL, normal website login/account and approved installation status. Use normal browser approval/retry only in authorised scope. Website logout/revocation has real effects; never reset binding/token state merely to pass. |
| Word unresponsive | Stop generating input/tests; note last action/elapsed time, retain existing private logs and allow natural recovery. Ask human to save/recover normally. No forced termination, debugger suspension or crash induction. A dump/trace/termination requires separate explicit approval; mark dependent cases BLOCKED. |
| Synchronisation failure | Leave accepted Reader/provenance intact; record current saved/accepted/verified revisions. Retry existing Synchronise, or explicit Repair Synchronisation on the disposable fixture only after checking diagnostics and authorisation; never erase accepted data/reimport over an author's book. Compare with closed pristine fixture copy. |
| Development incompatibility | Stop connected tests; record exact server version/status/source discrepancy. Do not deploy, change flags/schema, restart services or apply historical migrations from Windows. Request Atlas investigation separately. |
Rollback is an explicitly authorised installation operation, not a build step. Current unified MSI uninstall is Windows Settings → Apps → PlotDirector Companion → Uninstall; it removes installed components/registration/shortcuts, not author manuscripts/application state. Current installer refuses a downgrade over a newer family product, so do not invoke an old MSI directly to bypass it. With human approval, close Word normally, preserve private state/backups, uninstall current product through Settings, then use a locally verified known-good signed unified installer and recheck inventory/load/connection. Never delete document properties or account state as rollback.
Historical evidence identifies version10 EXE SHA-256 9526E3781EB2EF9936132786E1E2242633349933A553E93E7A7D0B038160A7FF (WindowsValidation/Setup/Qualification-2026-11-05.md). The .33 handover records EXE 1DB75F88DB540367542CDF6015EA204FB3DAB9B581AB5D25CEDF3D23136C2525 and MSI 4320A4A67FB779F164F97156F818FDFCD1F35986F8AC44E82EFA4097C2089D54, installed then, with live post-edit acceptance pending. Atlas has verified neither present availability nor suitability of either as today's rollback package. Locate the human's current known-good preserved package and verify signer/hash/version/source locally before installation. If none exists, installation rollback readiness is BLOCKED. Legacy Install-WordCompanion.ps1 -Rollback restores a different developer-registration workflow and is not the current MSI rollback procedure.
9. Completion criteria
A–G each have individual results/evidence/cleanup; prerequisites, source, package/signatures, installed matching bytes, actual Word/agent/PWA and server binding established. R2, F1/F2 and navigation exact-target contracts must pass physically where executable; managed-only and blocked fault cases remain explicit. R1 genuine stalled-UI coverage cannot be claimed without a safe authorised mechanism. No missing performance measure or unapproved threshold may be converted to PASS. A run with blocked required physical cases is a partial qualification, not full Phase 3B.4 completion. Submit concise results and blockers for review; no release/distribution or Production approval is implied.
Clean up only the run's owned local copies/test records through normal supported UI after human confirms evidence retained. Resolve active session/drafts, close disposable documents normally, restore approved test-only network/diagnostic settings, remove only authorised synthetic project/account data, confirm real author data/state untouched. Do not delete a shared test account or retained known-good packages. Leave failed fixture/evidence private if needed for investigation and record why.
10. Outstanding assumptions requiring Windows confirmation
- Actual OS/Word/VS/runtime/PowerShell/signing/tool availability and architecture; installed Companion version/normal-user registry context.
- Presence and integrity of older-family MSI/static upgrade fixtures and a suitable human-approved rollback installer. Source history is evidence of past packages, not availability.
- Authorised disposable Development account/books/import/AI use, current authenticated native capability negotiation and feature eligibility; Atlas readiness is anonymous/read-only.
- Safe dedicated stalled-observation/late-command mechanism: none found in current runtime. Do not improvise. Inactive-document and managed-clock cases qualify different facts.
- Actual installed PWA/sessionStorage policy, physical safe return behaviour, performance instrumentation and approval of proposed thresholds.
- Documentation fixture neutralisation helper and OOXML opening on the actual Word build; no Windows fixture helper execution claimed on Atlas.