diff --git a/Docs/WordCompanion/2026-11-05-phase3-ai-integration.md b/Docs/WordCompanion/2026-11-05-phase3-ai-integration.md new file mode 100644 index 00000000..83e21ae4 --- /dev/null +++ b/Docs/WordCompanion/2026-11-05-phase3-ai-integration.md @@ -0,0 +1,147 @@ +# 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.md` and prompt version. +- Uses `IStoryIntelligenceClient` / `StoryIntelligenceClient`, the existing OpenAI Responses transport, configured `EffectiveChapterStructureModel`, 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 + +```mermaid +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: + +1. Agent generates a random verifier and sends its SHA-256 challenge to the HTTPS site root selected by the author. +2. 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. +3. 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. +4. 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. +5. 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](../../PlotDirector.NativeCompanion/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: + +```powershell +& .\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: + +```powershell +& .\PlotDirector.NativeCompanion\WindowsValidation\Install-WordCompanion.ps1 -PackagePath '' -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: + +```powershell +& .\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](Evidence/2026-11-05-phase3/README.md) 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.md` and `PlotDirector.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. diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase3/README.md b/Docs/WordCompanion/Evidence/2026-11-05-phase3/README.md new file mode 100644 index 00000000..dfd2a71f --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase3/README.md @@ -0,0 +1,21 @@ +# Phase 3 verification evidence + +Tests were run serially from the shared repository. Commands: + +```sh +dotnet build PlotLine.slnx --disable-build-servers -m:1 /p:UseSharedCompilation=false +dotnet run --no-build --project PlotDirector.NativeCompanion/Tests/PlotDirector.Companion.Tests.csproj +dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj +dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj -- --native-companion-http +node PlotLine.Tests/Browser/word-companion-regressions.cjs +``` + +Results: managed build zero warnings/errors; native harness 169 assertions (includes capacity-slot assertions), application harness 407 checks, focused HTTP integration and Chromium regressions passed. HTTP fixtures use a synthetic provider/repositories with actual ASP.NET routing/authentication/antiforgery and the canonical chapter service. No database fixtures were written by these tests. + +The live-provider smoke was separate: a temporary protected Atlas runner loaded existing Development provider configuration without displaying secrets, used the real StoryPromptRepository/StoryPromptVersionService/StoryIntelligenceClient/ManuscriptStructureAnalysisService and NativeChapterMapping, and submitted one invented four-paragraph chapter. The configured gpt-5-mini stage returned two valid mapped scenes. The runner did not connect to the database or submit author manuscripts. This does not prove Word desktop execution or an authenticated author's live website upload. + +VSTO sources were parsed by an SDK Roslyn syntax checker; VSTO/project/version XML parsed. No Office semantic compile on Linux. Official portable PowerShell 7.6.9 parsed every Windows helper. `pwsh -NoProfile -File PlotDirector.NativeCompanion/WindowsValidation/Test-DeveloperPackage.ps1` validated a synthetic package, tamper refusal and non-Windows fail-closed guards. Fake signature elements test metadata shape only, not authentic signatures or trust. No Windows build/registry/CIM/certificate operation was executed on Atlas. + +Development deployment logs show idle gates, migration 230 and matching deployed/published DLL hashes. Public probes use verified TLS with no certificate bypass. No grant or author data appears in retained logs; the unapproved public pairing proof expires without yielding credentials. Production and the laptop installation were not changed. + +Initial failures: one native handshake attempt ended in a broken pipe (log retained); its isolated serial rerun passed. An initial `/tmp` publish hit quota and was replaced by a successful disk-backed publish. Application DB credentials could create the checksum backup but not execute RESTORE VERIFYONLY; an administrator verified the same backup before migration. No failure was resolved by weakening tests, discarding user work or disabling TLS/security. diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase3/application-regressions.log b/Docs/WordCompanion/Evidence/2026-11-05-phase3/application-regressions.log new file mode 100644 index 00000000..641381b4 --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase3/application-regressions.log @@ -0,0 +1,408 @@ +PASS Native companion authentication, canonical AI mapping and isolated chapter retry +PASS Solver never discards a corroborated concern or exhausts navigation before verification +PASS Solver result evidence covers all reachable diagnoses without changing Stage 1 semantics +PASS Solver result copy follows actual answers, intention, variants and revision +PASS Solver workspace CTAs resolve authorised project/character context and real routes +PASS Stage 1 preserves all 60 strict conversations, corroboration, intent, reachability and adoption +PASS Stage 1 evidence gates, required follow-ups, bounded multi-select and neutral choices are enforced +PASS Neutral endpoints require explicit valid terminal declarations +PASS Neutral reassurance follows selected concerns without evidence and survives revision +PASS Scene navigation does not invent purpose evidence; genuine D05 witnesses survive +PASS D50 requires actual series evidence and preserves D50/D51 witnesses +PASS Curated V2 preserves 60 literal paths and enforces eight explicit Development review exceptions +PASS Curated V2 exhausts real-engine states and preserves revision/multi-select behaviour +PASS Curated V2 passes normal validation and invalid publication stays guarded +PASS Payoff covers all 52 diagnoses with seven archetypes and semantic uncertainty ordering without graph changes +PASS Development review observes every acceptance prefix without changing signals, results or graph; access and durable capture stay isolated +PASS All permanent writing problems have distinct editorial content, intent, metadata, links and real images +PASS Clean solver completion preserves private evidence and permanent indexable URLs +PASS Writing Solver anonymous state is protected, expires and rejects stale versions +PASS Writing Solver scoring, multi-select, revision, fallback and graph routes +PASS Writing Solver import rejects invalid graphs and editorial identities +PASS Project export and restore access gates enforce author and ownership boundaries +PASS Retired checklist bookmarks redirect without report access +PASS Ribbon operation identity and semantic icons stay consistent +PASS Maps Story projects canonical hierarchy, sequence, journeys and evidence without changing geography +Maps Story scale: 500 scenes, 30 characters, 5,000 appearances in 15ms. +PASS Maps Story scales to 500 scenes and 5,000 appearances +PASS Maps Story enforces access and uses bounded repository batches +PASS Maps appearance validates colours, normalized raster images and portable backups +PASS Maps reference assets enforce access +PASS Maps validate rough geometry, relationships, Location intent and access boundaries +PASS Subscription entitlement evaluates trials, paid access, overrides and real plan limits +PASS Subscription overrides control access and dashboard presentation without trial contradictions +PASS Subscription enforcement is concurrent, audited and admin-authorised +PASS Plot Health stays scene-based with 12,000 contributions +PASS Plot Health preserves Discovery planning and boundary contradictions +PASS Plot Health separates stored status and meaningful-progress clocks +PASS Plot Health explains question, payoff, closure and boundary evidence +PASS Plot Health evaluates explicit targets and scoped line rollups +PASS Plot Health respects scenario coverage and ordered chapter identities +PASS Plot Lines Focus and Weave preserve gaps and shared-scene identity +PASS Plot Lines thread, enrichment and Timeline inspector contracts hold +PASS Plot Lines composition remains bounded with a large generated weave +PASS Exception review uses evidence, identity, consequence and directional conflicts +PASS Exception assessment preserves author decisions and scene history +PASS Character card widths reflect displayed text without changing character data +PASS Relationships workspace large cast, temporal states and canonical edits +PASS Scene relationship proposals preserve direction and validate acceptance +PASS Location and asset merges require confirmation and distinct records +PASS Location persisted analysis preserves contextual bedrooms and setting provenance +PASS Location consequence outranks capped recurrence +PASS Location scene significance is attributed only to actual settings +PASS Location significance preserves hierarchy and independent uncertainty +PASS Character profile age uses canonical reference chronology +PASS Character detail and date-only save retain canonical DOB +PASS Story Point presence, previous appearances and age cross book boundaries +PASS Story Point knowledge stops at selected narrative position +PASS Story Point relationships and independent asset state are historical +PASS Story Point threads and continuity warnings respect future evidence +PASS Story Point ownership, AJAX and bounded batch loading require no AI +PASS Story Point narrative tie breakers match canonical order +PASS Malformed confidence 0. is repaired to 0.0 +PASS Markdown fences are stripped +PASS Unescaped backslash in evidence is repaired +PASS Truncated JSON is rejected +PASS Repaired JSON deserialises into SceneIntelligenceScene +PASS Chapter Structure confidence 0. repairs and deserialises +PASS Chapter Structure confidence 0. 8 repairs and deserialises +PASS Chapter Structure confidence 7 .5 repairs when unambiguous +PASS JSON repair leaves decimal-looking prose unchanged +PASS Chapter Structure semantic validation still rejects out-of-range repaired confidence +PASS Structural scene detection parser failure uses friendly diagnostics and retry +PASS Chapter Structure boundary normaliser repairs gaps and overlaps +PASS Chapter Structure boundary normaliser preserves valid coverage +PASS Chapter Structure boundary normaliser handles terminal ghost paragraph +PASS Chapter Structure boundary normaliser discards multiple terminal ghost paragraphs +PASS Chapter Structure boundary normaliser replays full book terminal empty failure +PASS Chapter Structure boundary normaliser keeps meaningful end overflow repair +PASS Chapter Structure boundary normaliser preserves genuine inverted ranges for validation +PASS Structural Word mapping uses paragraph map as authoritative text +PASS Structural Word mapping includes filtered Word paragraphs in source coverage +PASS Structural Word mapping fails precisely when map metadata is incomplete +PASS Structural Word mapping keeps trailing empty normalisation mapped +PASS Shared parser reports raw chapter output on unrecoverable JSON +PASS Character filtering rejects generic groups +PASS Character filtering preserves titled names +PASS Location filtering rejects merged phrases +PASS Location filtering preserves story locations +PASS Location canonical keys merge trivial variants +PASS Location contextual names use POV and structural setting +PASS Location canonical keys merge punctuation and safe plurals +PASS Location candidate consolidation handles generic review variants +PASS Location candidate identity is parent-aware for generic sub-locations +PASS Locations page uses hierarchical sort order +PASS Location review UX supports large candidate sets +PASS Story Intelligence auto resolves exact known locations before review +PASS Story Intelligence location review uses single identity decision +PASS Asset filtering rejects generic objects +PASS Asset filtering preserves story assets +PASS Asset canonical keys merge trivial variants +PASS Asset canonical keys merge contextual vehicle variants +PASS Asset canonical keys keep unrelated owned cars distinct +PASS Asset candidate keys attach unique unowned variants +PASS Asset filtering rejects relationship facts +PASS Asset contextual names resolve POV ownership +PASS Asset structural phrases trim neighbouring nouns +PASS Asset significance is generic and not fixture-specific +PASS Story Intelligence asset review applies current identity rules +PASS Relationship review requires pair evidence and distinguishes social types +PASS Relationship signals map to broad lookup types +PASS Relationship signals infer friendship without romance +PASS Relationship events preserve chronological story order +PASS Relationship progression keeps chronological state +PASS Relationship observations do not create event spam +PASS Relationship review orders by first story appearance +PASS Relationship evidence priority preserves explicit semantics +PASS Relationship evidence handles retained hostile and incidental examples +PASS Knowledge signals map to existing knowledge states +PASS Knowledge recipient resolves narrator through POV +PASS Knowledge identity reveal preserves subjective timing +PASS Knowledge duplicate statements share canonical keys +PASS Knowledge suspicion and certainty remain distinct +PASS Illustration prompt builder separates spec and prompt +PASS Illustration prompt builder uses realistic image direction +PASS Illustration specification validation catches missing typed fields +PASS Illustration category validation rejects unknown values +PASS Illustration status transitions protect approval flow +PASS Illustration status transitions support archive flow +PASS Illustration metadata flags fallback location labels +PASS Illustration location matching rejects vehicle living room reuse +PASS Illustration automatic generation policy blocks vague fallbacks +PASS Story Memory import image generation defaults are safe +PASS Illustration storage codes are normalised safely +PASS Illustration starter batch has required category counts +PASS Illustration starter generation plan skips successful items +PASS Story Intelligence visualisation archive is preserved +PASS Story Intelligence visualisation runtime is removed +PASS Story Intelligence does not retry exhausted billing quota +PASS Illustration bulk retry result reports counts +PASS Illustration bulk retry skips blocking duplicate stable codes +PASS Illustration provider reports missing image model +PASS Illustration provider omits GPT image response format +PASS Illustration matching rejects adult masculine unknown art for Beth +PASS Illustration matching treats Mrs title as hard feminine evidence +PASS Illustration matching infers mother and aunt as mature feminine +PASS Illustration matching rejects duplicate named portrait allocation +PASS Illustration semantic types prevent bathroom office and ambulance car mismatches +PASS Illustration demand archetypes stay broad and use active template +PASS Story Intelligence evidence extraction prevents observed attribute leakage +PASS Story Intelligence scene call uses strict structured output +PASS Story Intelligence scene schema constrains confidence numbers +PASS Story Intelligence scene schema constrains evidence strings +PASS Story Intelligence temporal resolves chapter anchor and afternoon +PASS Story Intelligence temporal rolls over after midnight +PASS Story Intelligence temporal resolves following morning +PASS Story Intelligence temporal resolves exact day offsets +PASS Story Intelligence temporal resolves following weekday +PASS Story Intelligence temporal resolves evening clock time +PASS Story Intelligence temporal rejects unanchored clock time +PASS Story Intelligence temporal preserves yearless calendar date clues +PASS Story Intelligence temporal resolves yearless calendar dates from context +PASS Story Intelligence temporal inherits previous morning when extraction is empty +PASS Story Intelligence temporal inherits previous evening when extraction is empty +PASS Story Intelligence temporal inherits previous night when extraction is empty +PASS Story Intelligence temporal inherits after midnight advancement +PASS Story Intelligence temporal inherits chapter anchor when extraction is empty +PASS Story Intelligence temporal stays unknown without context or extraction +PASS Story Intelligence temporal explicit date overrides previous context +PASS Story Intelligence temporal preserves vague few days +PASS Core import applies structural chronology to canonical scenes +PASS Story Intelligence temporal importer preserves manual chronology +PASS Story Intelligence temporal materialisation saves canonical chronology +PASS Story Intelligence temporal malformed values are discarded +PASS Story Calendar useful months and sparse navigation +PASS Story Calendar places dated scenes on Monday-first month grid +PASS Story Calendar separates unplaced scenes without guessing +PASS Story Calendar book filter and all books scope work +PASS Story Calendar month navigation uses story dates across years +PASS Story Calendar month dropdown follows displayed month +PASS Story Calendar handles no dated scenes +PASS Story Calendar day details endpoint returns partial +PASS Story Calendar day details endpoint respects book filter +PASS Story Calendar day details endpoint handles empty story date +PASS Story Calendar day details endpoint rejects invalid project +PASS Story Calendar index returns surface partial for AJAX +PASS Story Calendar day selection uses progressive AJAX hooks +PASS Story Intelligence structured metric values validate and import +PASS Story Intelligence structured schema covers complete response model +PASS Story Intelligence structured schema remains fixture agnostic +PASS Illustration assignment repair enforces explicit evidence groups and strict subtypes +PASS Lean import removes replay links while retaining progress +PASS Story Intelligence progress does not prematurely report safe close +PASS Structural import creates scenes before Word sync +PASS Structural import creates first scene without placeholder +PASS Structural import persists paragraph mapping and source text +PASS Structural import persists canonical scene source text +PASS Structural import adds summaries without extra scene AI calls +PASS Core import scan stage defers scenes and characters +PASS Core import basic location detector is conservative +PASS Core import basic location detector consolidates and skips existing matches +PASS Core import basic location detector supports pending parent candidates +PASS Core import character discovery protects accepted locations +PASS Core import gates characters behind basic location review +PASS Core import hides exact existing character names from review +PASS Core import hides exact existing character aliases from review +PASS Core import keeps suspected unknown aliases in review +PASS Core import keeps ambiguous existing character matches in review +PASS Core import keeps new characters in review +PASS Core import auto resolved character evidence is preserved +PASS Core import character evidence is candidate specific +PASS Core import deterministically maps known characters +PASS Core import wizard orders scenes before characters +PASS Core import remaps characters after review +PASS Scan review separates known matches from unresolved names +PASS Story Intelligence uses persisted scene source after restart +PASS Story Intelligence canonical mode bypasses duplicate boundary analysis +PASS Story Intelligence progress uses canonical scene summaries +PASS Story Intelligence downstream imports prefer canonical SceneIDs +PASS Story Intelligence scene prompt no longer asks for duplicate factual summary +PASS Story Intelligence review uses canonical structural summaries and counts +PASS Story Intelligence review centre completion is category scoped +PASS Word sync requires save acknowledgement +PASS Word sync retry resumes existing structure +PASS Story Intelligence enriches existing structural scenes +PASS Core import scene titles ride existing structural AI call +PASS Core import scene title preference is review scoped +PASS Core import scene title preference moved to Detect Scenes +PASS Core import Review Chapters is compact and chapter only +PASS Core import Detect Scenes is compact and owns title option +PASS Book context is canonical import metadata +PASS Names defaults from selected book context +PASS Story Intelligence starts from core import complete +PASS Generated scene titles persist with provenance +PASS Scene title display keeps scene numbers visible +PASS Manuscript text statistics handles pure prose +PASS Manuscript text statistics handles pure dialogue +PASS Manuscript text statistics splits narrative before dialogue +PASS Manuscript text statistics splits dialogue before narrative +PASS Manuscript text statistics handles multiple dialogue passages +PASS Manuscript text statistics supports smart quotes +PASS Manuscript text statistics supports straight quotes +PASS Manuscript text statistics carries multi-paragraph dialogue +PASS Manuscript text statistics returns to prose after continued dialogue +PASS Manuscript text statistics ignores empty paragraphs +PASS Manuscript text statistics reconciles scene totals +PASS Manuscript text statistics aggregates chapter scenes +PASS Manuscript text statistics recalculates existing scene sources +PASS Manuscript text statistics does not invoke AI +PASS Phase 21T repairs durable character understanding +PASS Phase 21U extracts mandatory character appearance fixtures +PASS Character sex hints are conservative and reviewable +PASS Character discovery does not truncate scan review candidates +PASS Character discovery rejects sentence-start words +PASS Character discovery rejects fragments and location names +PASS Manuscript scan preview keeps only auto-selected character candidates +PASS Word Companion scan completion uses chunked transport +PASS Word Companion scan chunks assemble full novel payloads +PASS Word Companion scan chunks reject partial and conflicting payloads +PASS Onboarding wizard keeps character pages inside one main step +PASS Scan review aliases feed Story Intelligence known character context +PASS Name Intelligence package contract is present +PASS Name Intelligence reference data is copied on publish +PASS Name Intelligence repository uses stored procedures +PASS Name Intelligence review warning is wired +PASS Name Intelligence library defaults to all locales +PASS Story Intelligence new-format context uses canonical characters +PASS Story Intelligence character defaults link proposed existing matches +PASS Story Intelligence character defaults ignore generic references +PASS Story Intelligence character defaults keep descriptive identities +PASS Story Intelligence character review uses single identity decision +PASS Story Intelligence auto resolves exact known identities before review +PASS Story Intelligence character matching keeps ambiguous known names visible +PASS Story Intelligence descriptive references consolidate articles +PASS Story Intelligence review omits character metrics dashboard +PASS Story Intelligence resumed chapters use canonical labels +PASS Story Intelligence character review posts selected existing match +PASS Story Intelligence character default changes preserve persisted results +PASS Structural POV rides existing chapter analysis +PASS Structural POV persists through import resolution +PASS Chapter POV derives from canonical scenes +PASS Permanent Analyse My Book starts from saved book +PASS Story Intelligence canonical context carries provenance +PASS Scene prompt protects canonical scene context +PASS Structural setting rides existing chapter analysis +PASS Explicit narrator labels detect deterministic POV +PASS AI POV JSON parses into structural models +PASS Post character review resolves persisted structural POV +PASS Normal scene and chapter saves persist POV +PASS Character merge is a reusable stored procedure workflow +PASS Story Intelligence character review suppresses resolved narrator POV +PASS Story Intelligence character review reuses structured appearance aliases +PASS Entity preferred names are peer aliases +PASS Story Intelligence review evidence includes chapter scene labels +PASS Story Intelligence import enables project metric defaults before save +PASS Project metrics add defaults backfills scene values +PASS Story Intelligence scene prompt uses configured metrics +PASS Story Intelligence scene prompt uses scene characters terminology +PASS Story Intelligence downstream imports support canonical scene results +PASS Story Intelligence runner supplies metrics and Plot Lines +PASS Story Intelligence metric persistence uses configured keys +PASS Story Intelligence stabilisation gate materialises strict and legacy metrics +PASS Story Intelligence modern materialisation owns finalisation boundary +PASS Story Intelligence narrative materialisation reads strict scene results +PASS Story Intelligence stabilisation routes normal users to book +PASS Story Intelligence narrative candidates require review +PASS Story Intelligence discovers Plot Lines without preconfiguration +PASS Story Intelligence matches existing Plot Lines without duplicates +PASS Narrative research prototype fixture builds hierarchy +PASS Narrative sibling hotel fixture generalises hierarchy +PASS Narrative trivial one-scene question is suppressed +PASS Narrative short significant thread survives +PASS Narrative semantic evolution consolidates by continuity +PASS Narrative existing thread matching is supported +PASS Narrative candidate merge and parent fields are persisted +PASS Narrative prompt uses one scene call with compact schema +PASS Narrative production code remains fixture agnostic +PASS Whole-book Plot Intelligence prompt carries full manuscript context +PASS Whole-book Plot Intelligence schema requires timeline event types +PASS Whole-book Plot Intelligence author seed inputs persist safely +PASS Whole-book Plot Intelligence structured author seed match survives +PASS Whole-book Plot Intelligence unmatched seeds become review candidates +PASS Whole-book Plot Intelligence uses dedicated output token headroom +PASS Story Intelligence narrative review displays author seed provenance +PASS Story Intelligence narrative review avoids raw author-facing IDs +PASS Story Intelligence author seed decisions are preserved +PASS Whole-book Plot Intelligence production code remains fixture agnostic +PASS Story Intelligence narrative review creates canonical records via existing procs +PASS Story Intelligence narrative stage follows knowledge +PASS Word Companion replays live current scene to writing panes +PASS Scan review post supports full-book form submissions +PASS StoryPosition rejects incomplete or invalid runtime scene positions +PASS StoryPosition builds canonical runtime scene navigation +PASS StoryPosition derives canonical scene context identity +PASS Writing Context route uses canonical story context service +PASS Writing Context client follows canonical story position events +PASS Writing Context preserves selected tab and avoids event loops +PASS Writing Intent route uses canonical story context and planning data +PASS Writing Intent client uses shared writing follow helper +PASS Obsolete global Word navigation is removed while writing windows remain live +PASS Appearance preferences and ribbon destinations +PASS Toolbar preferences, authorisation and contextual routes +PASS Application navigation resolves authorised project and book context +PASS Writing pair shares canonical follow infrastructure +PASS Writing workspace presence scopes browser windows +PASS Writing workspace client uses session window identity and stable names +PASS Writing workspace launcher uses progressive screen placement +PASS Writing workspace pages register roles without changing follow behavior +PASS Word marker client acknowledgements require authenticated ownership +PASS Word Companion exposes writing workspace launch actions +PASS Word Companion writing screens receive resolved context identifiers +PASS Word Companion canonical markers drive runtime follow +PASS Word Companion runtime follows multiple imported scene anchors +PASS Word Companion existing project book linking remains available +PASS Word Companion document identity survives reconnect +PASS Word Companion multiscreen launch and follow remain reachable +PASS Word Companion modes remain distinct +PASS Writing pages do not require Story Intelligence +PASS Word Companion host script has valid tab mapping +PASS Writing screens show diagnostic empty states +PASS Word Companion three-screen flow logs connection identifiers +PASS Admin Story Intelligence reset returns to diagnostics with messages +PASS Project hard delete clears Story Intelligence dependencies in transaction +PASS Permanent project delete keeps archive and name safety gates +PASS Word manuscript cleanup classifies PlotDirector markers by tag only +PASS Word manuscript cleanup preserves content controls content +PASS Word manuscript cleanup UI separates unlink from clean unlink +PASS Word manuscript unlink keeps Story Intelligence data untouched +PASS Word manuscript cleanup remains relinkable and idempotent +PASS Story Intelligence Review Centre route replaces linear review resume +PASS Story Intelligence obsolete create scene workflow is removed +PASS Story Intelligence Review Centre counts only needs-attention categories +PASS Story Intelligence Review Centre uses independent tile grid +PASS Story Intelligence Review Centre opens with character gate +PASS Story Intelligence review modules are independent after character gate +PASS Story Intelligence review module completion is durable and independent +PASS Story Intelligence review module pages omit wizard chrome +PASS Story Intelligence downstream review uses completed scene analysis +PASS Story Intelligence review posts do not use success interstitials +PASS Story Intelligence legacy review completion routes are deleted +PASS Story Intelligence review forms share busy submit guard +PASS Story Intelligence heavy review modules offer bounded rendering +PASS Story Intelligence Review Centre adds no AI calls +PASS Story Intelligence Review Centre uses bounded summary query +PASS Story Intelligence character review queues enrichment beside plot synthesis +PASS Story Intelligence character enrichment uses persisted SignalR progress +PASS Story Intelligence character enrichment preserves author fields +PASS Story Intelligence character enrichment batches by prompt size +PASS Story Intelligence character enrichment promotes structured facts +PASS Character detail can queue single-character enrichment +PASS Single-character enrichment is persisted and duplicate safe +PASS Character detail enrichment status uses scoped SignalR +PASS Story Intelligence detailed review GETs use selected module paths +PASS Story Intelligence completed Character review remains inspectable +PASS Story Intelligence Review Centre completed modules use canonical destinations +PASS Story Intelligence detailed reviews read persisted candidate pages +PASS Story Intelligence module completion lifecycle uses persisted candidates +PASS Story Intelligence Job 6 uses bounded concurrent chapter execution +PASS Story Intelligence global progress uses whole run scene totals +PASS Story Intelligence recovered provider failures stay operational +PASS Story Intelligence recovered JSON repair stays operational +PASS Story Intelligence terminal failures remain user visible +PASS Story Intelligence global banner remains visible through finalising gaps +PASS Story Intelligence global banner rejects stale live snapshots +PASS Story Intelligence live global progress publishes authoritative scene aggregates +PASS Story Intelligence global progress survives initial SignalR start races +PASS Story Intelligence scene analysis completion barrier releases review +PASS Story Intelligence active progress only appears in global strip +PASS Story Intelligence book actions do not open review centre while running diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase3/browser-regressions.log b/Docs/WordCompanion/Evidence/2026-11-05-phase3/browser-regressions.log new file mode 100644 index 00000000..38734d22 --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase3/browser-regressions.log @@ -0,0 +1,3 @@ +PASS context actual browser delayed responses, abort, current-scene return, old failure and chapter identity +PASS intent actual browser delayed responses, abort, current-scene return, old failure and chapter identity +PASS fresh Writer launcher opens both missing role windows without undeclared currentRole diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase3/development-backup-verification.log b/Docs/WordCompanion/Evidence/2026-11-05-phase3/development-backup-verification.log new file mode 100644 index 00000000..b8e7d6f8 --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase3/development-backup-verification.log @@ -0,0 +1,6 @@ +The backup set on file 1 is valid. +database_name backup_finish_date has_backup_checksums +-------------------------------------------------------------------------------------------------------------------------------- ----------------------- -------------------- +PlotDirector_Development 2026-11-05 11:01:52.000 1 + +(1 rows affected) diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase3/development-deploy.log b/Docs/WordCompanion/Evidence/2026-11-05-phase3/development-deploy.log new file mode 100644 index 00000000..5c8a7690 --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase3/development-deploy.log @@ -0,0 +1,13 @@ +Verified database: PlotDirector_Development +SQL file: plotdirector-phase2-restart-authorised-gate.sql +Development deployment gate: idle +SQL file completed: plotdirector-phase2-restart-authorised-gate.sql +SQL file: p3-readiness.sql +Ownership procedure present | 1 +Ownership procedure hash | F393C358F4D1315984F06F1ECED164940A8879D36DD8B78DB07751EBFF5F51E0 +SQL file completed: p3-readiness.sql +active +Development server release: /srv/apps/plotdirector-dev/releases/native-word-phase3-718c996-20261105114542 +Previous application backup: /srv/apps/plotdirector-dev/current-before-native-word-phase3-718c996-20261105114542 +PlotLine.dll publish/deployed SHA256 matches: c89d1346d34e75d7953890f54c553910462a0e425d5e09747d4e94043f791727 +PlotDirector.Companion.Protocol.dll publish/deployed SHA256 matches: 6645fd9d49441a8a248acc28470fcf4fba886c32e272f403db9fa3a64f806c03 diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase3/development-migration230.log b/Docs/WordCompanion/Evidence/2026-11-05-phase3/development-migration230.log new file mode 100644 index 00000000..515819bd --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase3/development-migration230.log @@ -0,0 +1,10 @@ +Verified database: PlotDirector_Development +SQL file: plotdirector-phase2-restart-authorised-gate.sql +Development deployment gate: idle +SQL file completed: plotdirector-phase2-restart-authorised-gate.sql +SQL file: 230_WordMarkerAcknowledgementOwnership.sql +SQL file completed: 230_WordMarkerAcknowledgementOwnership.sql +SQL file: p3-readiness.sql +Ownership procedure present | 1 +Ownership procedure hash | F393C358F4D1315984F06F1ECED164940A8879D36DD8B78DB07751EBFF5F51E0 +SQL file completed: p3-readiness.sql diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase3/development-public-probes.log b/Docs/WordCompanion/Evidence/2026-11-05-phase3/development-public-probes.log new file mode 100644 index 00000000..365bc2ed --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase3/development-public-probes.log @@ -0,0 +1,10 @@ +Local root: HTTP 200 +Public TLS root: HTTP 200 +Native books without grant: HTTP 401 +Oversized public pairing body: rejected HTTP 413 +Public pairing: HTTP 200; code shape valid; no-store +Unapproved/incorrect-proof redemption: HTTP 202; no grant issued +Unauthenticated AI POST: HTTP 401; no provider request +Browser approval without login: HTTP 302 to normal Account login +Development service: active +Production and laptop installation unchanged. diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase3/development-publish.log b/Docs/WordCompanion/Evidence/2026-11-05-phase3/development-publish.log new file mode 100644 index 00000000..9bba0657 --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase3/development-publish.log @@ -0,0 +1,5 @@ + Determining projects to restore... + All projects are up-to-date for restore. + PlotDirector.Companion.Protocol -> /srv/repos/PlotDirector/PlotDirector.NativeCompanion/Protocol/bin/Release/netstandard2.0/PlotDirector.Companion.Protocol.dll + PlotLine -> /srv/repos/PlotDirector/PlotLine/bin/Release/net10.0/PlotLine.dll + PlotLine -> /srv/repos/plotdirector-native-phase3-artifacts/publish-718c996-20261105114235/ diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase3/live-provider-smoke.log b/Docs/WordCompanion/Evidence/2026-11-05-phase3/live-provider-smoke.log new file mode 100644 index 00000000..1da4a51f --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase3/live-provider-smoke.log @@ -0,0 +1,3 @@ +LIVE AI configured stage model: gpt-5-mini +LIVE AI state=complete sceneCount=2 mappedPositionsValid=True +LIVE AI PASS: synthetic chapter through the existing configured provider, prompt, JSON validation and native Word-position mapping. No database writes; no author manuscript submitted. diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase3/managed-build.log b/Docs/WordCompanion/Evidence/2026-11-05-phase3/managed-build.log new file mode 100644 index 00000000..001813c2 --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase3/managed-build.log @@ -0,0 +1,15 @@ + Determining projects to restore... + All projects are up-to-date for restore. + PlotDirector.Companion.Protocol -> /srv/repos/PlotDirector/PlotDirector.NativeCompanion/Protocol/bin/Debug/netstandard2.0/PlotDirector.Companion.Protocol.dll + PlotLine -> /srv/repos/PlotDirector/PlotLine/bin/Debug/net10.0/PlotLine.dll + PlotLine.Tests -> /srv/repos/PlotDirector/PlotLine.Tests/bin/Debug/net10.0/PlotLine.Tests.dll + PlotDirector.Companion.Agent -> /srv/repos/PlotDirector/PlotDirector.NativeCompanion/Agent/bin/Debug/net10.0/PlotDirector.Companion.Agent.dll + PlotDirector.Companion.Client -> /srv/repos/PlotDirector/PlotDirector.NativeCompanion/Client/bin/Debug/netstandard2.0/PlotDirector.Companion.Client.dll + PlotDirector.Companion.Tests -> /srv/repos/PlotDirector/PlotDirector.NativeCompanion/Tests/bin/Debug/net10.0/PlotDirector.Companion.Tests.dll + WritingSolver -> /srv/repos/PlotDirector/Tools/WritingSolver/bin/Debug/net10.0/WritingSolver.dll + +Build succeeded. + 0 Warning(s) + 0 Error(s) + +Time Elapsed 00:00:49.19 diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase3/native-http.log b/Docs/WordCompanion/Evidence/2026-11-05-phase3/native-http.log new file mode 100644 index 00000000..520b21ba --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase3/native-http.log @@ -0,0 +1 @@ +PASS actual HTTP native pairing, antiforgery, bearer/stamp, book/subscription access, canonical AI and idempotency (synthetic provider, no database) diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase3/native-initial-broken-pipe.log b/Docs/WordCompanion/Evidence/2026-11-05-phase3/native-initial-broken-pipe.log new file mode 100644 index 00000000..ef746c5e --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase3/native-initial-broken-pipe.log @@ -0,0 +1,136 @@ +PASS selection scheduler coalesces bursts +PASS Word operation timing recorded +PASS only latest selection executes on owner +PASS obsolete Word work cancelled +PASS bounded Word queue accepts capacity slot 0 +PASS bounded Word queue accepts capacity slot 1 +PASS bounded Word queue accepts capacity slot 2 +PASS bounded Word queue accepts capacity slot 3 +PASS bounded Word queue accepts capacity slot 4 +PASS bounded Word queue accepts capacity slot 5 +PASS bounded Word queue accepts capacity slot 6 +PASS bounded Word queue accepts capacity slot 7 +PASS bounded Word queue accepts capacity slot 8 +PASS bounded Word queue accepts capacity slot 9 +PASS bounded Word queue accepts capacity slot 10 +PASS bounded Word queue accepts capacity slot 11 +PASS bounded Word queue accepts capacity slot 12 +PASS bounded Word queue accepts capacity slot 13 +PASS bounded Word queue accepts capacity slot 14 +PASS bounded Word queue accepts capacity slot 15 +PASS bounded Word queue accepts capacity slot 16 +PASS bounded Word queue accepts capacity slot 17 +PASS bounded Word queue accepts capacity slot 18 +PASS bounded Word queue accepts capacity slot 19 +PASS bounded Word queue accepts capacity slot 20 +PASS bounded Word queue accepts capacity slot 21 +PASS bounded Word queue accepts capacity slot 22 +PASS bounded Word queue accepts capacity slot 23 +PASS bounded Word queue accepts capacity slot 24 +PASS bounded Word queue accepts capacity slot 25 +PASS bounded Word queue accepts capacity slot 26 +PASS bounded Word queue accepts capacity slot 27 +PASS bounded Word queue accepts capacity slot 28 +PASS bounded Word queue accepts capacity slot 29 +PASS bounded Word queue accepts capacity slot 30 +PASS bounded Word queue accepts capacity slot 31 +PASS bounded Word queue accepts capacity slot 32 +PASS bounded Word queue accepts capacity slot 33 +PASS bounded Word queue accepts capacity slot 34 +PASS bounded Word queue accepts capacity slot 35 +PASS bounded Word queue accepts capacity slot 36 +PASS bounded Word queue accepts capacity slot 37 +PASS bounded Word queue accepts capacity slot 38 +PASS bounded Word queue accepts capacity slot 39 +PASS bounded Word queue accepts capacity slot 40 +PASS bounded Word queue accepts capacity slot 41 +PASS bounded Word queue accepts capacity slot 42 +PASS bounded Word queue accepts capacity slot 43 +PASS bounded Word queue accepts capacity slot 44 +PASS bounded Word queue accepts capacity slot 45 +PASS bounded Word queue accepts capacity slot 46 +PASS bounded Word queue accepts capacity slot 47 +PASS bounded Word queue accepts capacity slot 48 +PASS bounded Word queue accepts capacity slot 49 +PASS bounded Word queue accepts capacity slot 50 +PASS bounded Word queue accepts capacity slot 51 +PASS bounded Word queue accepts capacity slot 52 +PASS bounded Word queue accepts capacity slot 53 +PASS bounded Word queue accepts capacity slot 54 +PASS bounded Word queue accepts capacity slot 55 +PASS bounded Word queue accepts capacity slot 56 +PASS bounded Word queue accepts capacity slot 57 +PASS bounded Word queue accepts capacity slot 58 +PASS bounded Word queue accepts capacity slot 59 +PASS bounded Word queue accepts capacity slot 60 +PASS bounded Word queue accepts capacity slot 61 +PASS bounded Word queue accepts capacity slot 62 +PASS bounded Word queue accepts capacity slot 63 +PASS Word queue rejects overflow without waiting +PASS Word scheduler rejects wrong thread +PASS author activity suspends low priority work +PASS IPC coalesces selection storm to latest value +PASS coalesced position is latest +PASS IPC snapshot queue backpressure bounded +PASS IPC selection session slots bounded +PASS missing required protocol capabilities refused +PASS three books have independent live sessions +PASS commit structural snapshot Discovery +PASS positional scene resolution independent of repeated text Discovery +PASS commit structural snapshot Reckoning +PASS positional scene resolution independent of repeated text Reckoning +PASS commit structural snapshot Redemption +PASS positional scene resolution independent of repeated text Redemption +PASS rapid three-document switching preserves active identity +PASS cancelled snapshot cannot commit +PASS partial snapshot cannot masquerade as complete +PASS oversized extraction fragment refused +PASS stale revision refused +PASS peer cannot address another instance lease +PASS duplicate/out-of-order sequence refused +PASS closing one document retires only its state +PASS old disconnect cannot retire replacement lease +PASS disconnect releases all owned sessions and snapshots +PASS one Word process cannot route into another process document +PASS terminating one Word process preserves another instance +PASS new observation revision invalidates in-flight old extraction +PASS malformed null document cannot crash agent session processing +PASS oversized frame rejected before allocation +PASS versioned frame round-trip retains identity +PASS offline work persisted without manuscript prose +PASS On Save mode cannot be triggered by automatic quiet period +PASS offline work survives agent restart +PASS new scene revision supersedes queued older work +PASS stale offline revision cannot replace newer work +PASS old acknowledgement cannot remove newer work +PASS matching idempotency acknowledgement retires work +PASS durable queue rejects capacity overflow +PASS real pipe rejects incompatible handshake +Unhandled exception. System.IO.IOException: Broken pipe + ---> System.Net.Sockets.SocketException (32): Broken pipe + at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.CreateException(SocketError error, Boolean forAsyncThrow) + at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.SendAsync(Socket socket, CancellationToken cancellationToken) + at System.Net.Sockets.Socket.SendAsync(ReadOnlyMemory`1 buffer, SocketFlags socketFlags, CancellationToken cancellationToken) + at System.IO.Pipes.PipeStream.WriteAsyncCore(ReadOnlyMemory`1 source, CancellationToken cancellationToken) + at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine) + at System.IO.Pipes.PipeStream.WriteAsyncCore(ReadOnlyMemory`1 source, CancellationToken cancellationToken) + at System.IO.Pipes.PipeStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) + at PlotDirector.Companion.Protocol.FrameCodec.WriteAsync(Stream stream, Message message, CancellationToken cancellation) in /srv/repos/PlotDirector/PlotDirector.NativeCompanion/Protocol/FrameCodec.cs:line 21 + at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine) + at PlotDirector.Companion.Protocol.FrameCodec.WriteAsync(Stream stream, Message message, CancellationToken cancellation) + at Program.
$(String[] args) in /srv/repos/PlotDirector/PlotDirector.NativeCompanion/Tests/Program.cs:line 112 + at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) + at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.MoveNext(Thread threadPoolThread) + at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(IAsyncStateMachineBox box, Boolean allowInlining) + at System.Threading.Tasks.Task.RunContinuations(Object continuationObject) + at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread) + at System.Threading.ThreadPoolWorkQueue.Dispatch() + at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart() + at System.Threading.Thread.StartCallback() +--- End of stack trace from previous location --- + at System.IO.Pipes.PipeStream.WriteAsyncCore(ReadOnlyMemory`1 source, CancellationToken cancellationToken) + --- End of inner exception stack trace --- + at System.IO.Pipes.PipeStream.WriteAsyncCore(ReadOnlyMemory`1 source, CancellationToken cancellationToken) + at PlotDirector.Companion.Protocol.FrameCodec.WriteAsync(Stream stream, Message message, CancellationToken cancellation) in /srv/repos/PlotDirector/PlotDirector.NativeCompanion/Protocol/FrameCodec.cs:line 21 + at Program.
$(String[] args) in /srv/repos/PlotDirector/PlotDirector.NativeCompanion/Tests/Program.cs:line 112 + at Program.
(String[] args) diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase3/native-malformed-before-fix.log b/Docs/WordCompanion/Evidence/2026-11-05-phase3/native-malformed-before-fix.log new file mode 100644 index 00000000..a9609e15 --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase3/native-malformed-before-fix.log @@ -0,0 +1,168 @@ +PASS selection scheduler coalesces bursts +PASS Word operation timing recorded +PASS only latest selection executes on owner +PASS obsolete Word work cancelled +PASS bounded Word queue accepts capacity slot 0 +PASS bounded Word queue accepts capacity slot 1 +PASS bounded Word queue accepts capacity slot 2 +PASS bounded Word queue accepts capacity slot 3 +PASS bounded Word queue accepts capacity slot 4 +PASS bounded Word queue accepts capacity slot 5 +PASS bounded Word queue accepts capacity slot 6 +PASS bounded Word queue accepts capacity slot 7 +PASS bounded Word queue accepts capacity slot 8 +PASS bounded Word queue accepts capacity slot 9 +PASS bounded Word queue accepts capacity slot 10 +PASS bounded Word queue accepts capacity slot 11 +PASS bounded Word queue accepts capacity slot 12 +PASS bounded Word queue accepts capacity slot 13 +PASS bounded Word queue accepts capacity slot 14 +PASS bounded Word queue accepts capacity slot 15 +PASS bounded Word queue accepts capacity slot 16 +PASS bounded Word queue accepts capacity slot 17 +PASS bounded Word queue accepts capacity slot 18 +PASS bounded Word queue accepts capacity slot 19 +PASS bounded Word queue accepts capacity slot 20 +PASS bounded Word queue accepts capacity slot 21 +PASS bounded Word queue accepts capacity slot 22 +PASS bounded Word queue accepts capacity slot 23 +PASS bounded Word queue accepts capacity slot 24 +PASS bounded Word queue accepts capacity slot 25 +PASS bounded Word queue accepts capacity slot 26 +PASS bounded Word queue accepts capacity slot 27 +PASS bounded Word queue accepts capacity slot 28 +PASS bounded Word queue accepts capacity slot 29 +PASS bounded Word queue accepts capacity slot 30 +PASS bounded Word queue accepts capacity slot 31 +PASS bounded Word queue accepts capacity slot 32 +PASS bounded Word queue accepts capacity slot 33 +PASS bounded Word queue accepts capacity slot 34 +PASS bounded Word queue accepts capacity slot 35 +PASS bounded Word queue accepts capacity slot 36 +PASS bounded Word queue accepts capacity slot 37 +PASS bounded Word queue accepts capacity slot 38 +PASS bounded Word queue accepts capacity slot 39 +PASS bounded Word queue accepts capacity slot 40 +PASS bounded Word queue accepts capacity slot 41 +PASS bounded Word queue accepts capacity slot 42 +PASS bounded Word queue accepts capacity slot 43 +PASS bounded Word queue accepts capacity slot 44 +PASS bounded Word queue accepts capacity slot 45 +PASS bounded Word queue accepts capacity slot 46 +PASS bounded Word queue accepts capacity slot 47 +PASS bounded Word queue accepts capacity slot 48 +PASS bounded Word queue accepts capacity slot 49 +PASS bounded Word queue accepts capacity slot 50 +PASS bounded Word queue accepts capacity slot 51 +PASS bounded Word queue accepts capacity slot 52 +PASS bounded Word queue accepts capacity slot 53 +PASS bounded Word queue accepts capacity slot 54 +PASS bounded Word queue accepts capacity slot 55 +PASS bounded Word queue accepts capacity slot 56 +PASS bounded Word queue accepts capacity slot 57 +PASS bounded Word queue accepts capacity slot 58 +PASS bounded Word queue accepts capacity slot 59 +PASS bounded Word queue accepts capacity slot 60 +PASS bounded Word queue accepts capacity slot 61 +PASS bounded Word queue accepts capacity slot 62 +PASS bounded Word queue accepts capacity slot 63 +PASS Word queue rejects overflow without waiting +PASS Word scheduler rejects wrong thread +PASS author activity suspends low priority work +PASS IPC coalesces selection storm to latest value +PASS coalesced position is latest +PASS IPC snapshot queue backpressure bounded +PASS IPC selection session slots bounded +PASS missing required protocol capabilities refused +PASS three books have independent live sessions +PASS commit structural snapshot Discovery +PASS positional scene resolution independent of repeated text Discovery +PASS commit structural snapshot Reckoning +PASS positional scene resolution independent of repeated text Reckoning +PASS commit structural snapshot Redemption +PASS positional scene resolution independent of repeated text Redemption +PASS rapid three-document switching preserves active identity +PASS cancelled snapshot cannot commit +PASS partial snapshot cannot masquerade as complete +PASS oversized extraction fragment refused +PASS stale revision refused +PASS peer cannot address another instance lease +PASS duplicate/out-of-order sequence refused +PASS closing one document retires only its state +PASS old disconnect cannot retire replacement lease +PASS disconnect releases all owned sessions and snapshots +PASS one Word process cannot route into another process document +PASS terminating one Word process preserves another instance +PASS new observation revision invalidates in-flight old extraction +PASS malformed null document cannot crash agent session processing +PASS oversized frame rejected before allocation +PASS versioned frame round-trip retains identity +PASS offline work persisted without manuscript prose +PASS On Save mode cannot be triggered by automatic quiet period +PASS offline work survives agent restart +PASS new scene revision supersedes queued older work +PASS stale offline revision cannot replace newer work +PASS old acknowledgement cannot remove newer work +PASS matching idempotency acknowledgement retires work +PASS durable queue rejects capacity overflow +PASS real pipe rejects incompatible handshake +PASS same-version optional capabilities remain compatible +PASS agent advertises optional structural review capability +PASS real named-pipe handshake reconciles three documents +PASS agent receives actual asynchronous positional/lifecycle traffic +PASS real pipe returns document analysis results +PASS agent shutdown retires peer sessions +PASS idle keepalive detects agent loss without a Word event +PASS agent restart reconnects and reconciles without UI waits +PASS analysis can be repeated after actual pipe host restart +PASS real pipe document close is isolated +PASS link shutdown cancels background worker promptly +PASS untrusted agent owner callback rejects connection before handshake +PASS unresponsive agent handshake times out off producer thread +PASS blank document has an explicit empty analysis +PASS plain chapter labels and separators become review suggestions +PASS ambiguous text and heading levels explain uncertainty instead of approving import +PASS analysis reuses existing PlotDirector marker interpretation +PASS fragment splits do not inflate word or paragraph counts +PASS 250000-word many-paragraph manuscript analysed incrementally +Agent synthetic 250000-word analysis: 104ms (not Word extraction/UI timing). +PASS review suggestion storage is bounded with explicit truncation +PASS analysis results are paginated +PASS review page fits bounded IPC frame +PASS analysis result contract round-trips over framing +PASS document-specific analysis returns structured results and progress +PASS document-specific analysis returns structured results and progress +PASS document-specific analysis returns structured results and progress +PASS another document's snapshot cannot retrieve results +PASS analysis acknowledges bounded partial progress before cancellation +PASS cancelled analysis cannot complete +PASS analysis waiting for Word scheduler is cancellable +PASS pending analysis cancellation does not require extraction +PASS review rejects results from a different document +PASS late results cannot replace cancellation +PASS new analysis rejects obsolete revision and snapshot +PASS review completes only matching analysis +PASS selection replies cannot regress completed review progress +PASS late page zero cannot replace requested later page +PASS agent restart releases document analysis state +PASS native connection rejects unsafe site root +PASS native connection rejects unsafe site root +PASS native connection rejects unsafe site root +PASS native connection rejects unsafe site root +PASS native connection rejects unsafe site root +PASS browser-approved sign-in loads only authorised book choices +PASS sign-in and local work never upload chapter prose +PASS AI chapter capture starts only after an explicit command +PASS bounded chapter capture reports progress without submitting early +PASS duplicate submit uses one HTTP call and preserves exact chapter mapping +PASS worst-case bounded AI page fits IPC framing +PASS AI result contract round-trips on actual frame codec +PASS late cancellation cannot retire a replacement AI chapter +PASS another document cannot retrieve an AI result +PASS cancelled network chapter cannot reappear in review +PASS authorisation failure is isolated and actionable +Unhandled exception. System.Threading.Tasks.TaskCanceledException: A task was canceled. + at ChapterAiTests.Wait(Func`1 ready) in /srv/repos/PlotDirector/PlotDirector.NativeCompanion/Tests/ChapterAiTests.cs:line 52 + at ChapterAiTests.Run(Action`2 check) in /srv/repos/PlotDirector/PlotDirector.NativeCompanion/Tests/ChapterAiTests.cs:line 44 + at Program.
$(String[] args) in /srv/repos/PlotDirector/PlotDirector.NativeCompanion/Tests/Program.cs:line 164 + at Program.
(String[] args) diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase3/native-tests.log b/Docs/WordCompanion/Evidence/2026-11-05-phase3/native-tests.log new file mode 100644 index 00000000..2e5be751 --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase3/native-tests.log @@ -0,0 +1,171 @@ +PASS selection scheduler coalesces bursts +PASS Word operation timing recorded +PASS only latest selection executes on owner +PASS obsolete Word work cancelled +PASS bounded Word queue accepts capacity slot 0 +PASS bounded Word queue accepts capacity slot 1 +PASS bounded Word queue accepts capacity slot 2 +PASS bounded Word queue accepts capacity slot 3 +PASS bounded Word queue accepts capacity slot 4 +PASS bounded Word queue accepts capacity slot 5 +PASS bounded Word queue accepts capacity slot 6 +PASS bounded Word queue accepts capacity slot 7 +PASS bounded Word queue accepts capacity slot 8 +PASS bounded Word queue accepts capacity slot 9 +PASS bounded Word queue accepts capacity slot 10 +PASS bounded Word queue accepts capacity slot 11 +PASS bounded Word queue accepts capacity slot 12 +PASS bounded Word queue accepts capacity slot 13 +PASS bounded Word queue accepts capacity slot 14 +PASS bounded Word queue accepts capacity slot 15 +PASS bounded Word queue accepts capacity slot 16 +PASS bounded Word queue accepts capacity slot 17 +PASS bounded Word queue accepts capacity slot 18 +PASS bounded Word queue accepts capacity slot 19 +PASS bounded Word queue accepts capacity slot 20 +PASS bounded Word queue accepts capacity slot 21 +PASS bounded Word queue accepts capacity slot 22 +PASS bounded Word queue accepts capacity slot 23 +PASS bounded Word queue accepts capacity slot 24 +PASS bounded Word queue accepts capacity slot 25 +PASS bounded Word queue accepts capacity slot 26 +PASS bounded Word queue accepts capacity slot 27 +PASS bounded Word queue accepts capacity slot 28 +PASS bounded Word queue accepts capacity slot 29 +PASS bounded Word queue accepts capacity slot 30 +PASS bounded Word queue accepts capacity slot 31 +PASS bounded Word queue accepts capacity slot 32 +PASS bounded Word queue accepts capacity slot 33 +PASS bounded Word queue accepts capacity slot 34 +PASS bounded Word queue accepts capacity slot 35 +PASS bounded Word queue accepts capacity slot 36 +PASS bounded Word queue accepts capacity slot 37 +PASS bounded Word queue accepts capacity slot 38 +PASS bounded Word queue accepts capacity slot 39 +PASS bounded Word queue accepts capacity slot 40 +PASS bounded Word queue accepts capacity slot 41 +PASS bounded Word queue accepts capacity slot 42 +PASS bounded Word queue accepts capacity slot 43 +PASS bounded Word queue accepts capacity slot 44 +PASS bounded Word queue accepts capacity slot 45 +PASS bounded Word queue accepts capacity slot 46 +PASS bounded Word queue accepts capacity slot 47 +PASS bounded Word queue accepts capacity slot 48 +PASS bounded Word queue accepts capacity slot 49 +PASS bounded Word queue accepts capacity slot 50 +PASS bounded Word queue accepts capacity slot 51 +PASS bounded Word queue accepts capacity slot 52 +PASS bounded Word queue accepts capacity slot 53 +PASS bounded Word queue accepts capacity slot 54 +PASS bounded Word queue accepts capacity slot 55 +PASS bounded Word queue accepts capacity slot 56 +PASS bounded Word queue accepts capacity slot 57 +PASS bounded Word queue accepts capacity slot 58 +PASS bounded Word queue accepts capacity slot 59 +PASS bounded Word queue accepts capacity slot 60 +PASS bounded Word queue accepts capacity slot 61 +PASS bounded Word queue accepts capacity slot 62 +PASS bounded Word queue accepts capacity slot 63 +PASS Word queue rejects overflow without waiting +PASS Word scheduler rejects wrong thread +PASS author activity suspends low priority work +PASS IPC coalesces selection storm to latest value +PASS coalesced position is latest +PASS IPC snapshot queue backpressure bounded +PASS IPC selection session slots bounded +PASS missing required protocol capabilities refused +PASS three books have independent live sessions +PASS commit structural snapshot Discovery +PASS positional scene resolution independent of repeated text Discovery +PASS commit structural snapshot Reckoning +PASS positional scene resolution independent of repeated text Reckoning +PASS commit structural snapshot Redemption +PASS positional scene resolution independent of repeated text Redemption +PASS rapid three-document switching preserves active identity +PASS cancelled snapshot cannot commit +PASS partial snapshot cannot masquerade as complete +PASS oversized extraction fragment refused +PASS stale revision refused +PASS peer cannot address another instance lease +PASS duplicate/out-of-order sequence refused +PASS closing one document retires only its state +PASS old disconnect cannot retire replacement lease +PASS disconnect releases all owned sessions and snapshots +PASS one Word process cannot route into another process document +PASS terminating one Word process preserves another instance +PASS new observation revision invalidates in-flight old extraction +PASS malformed null document cannot crash agent session processing +PASS oversized frame rejected before allocation +PASS versioned frame round-trip retains identity +PASS offline work persisted without manuscript prose +PASS On Save mode cannot be triggered by automatic quiet period +PASS offline work survives agent restart +PASS new scene revision supersedes queued older work +PASS stale offline revision cannot replace newer work +PASS old acknowledgement cannot remove newer work +PASS matching idempotency acknowledgement retires work +PASS durable queue rejects capacity overflow +PASS real pipe rejects incompatible handshake +PASS same-version optional capabilities remain compatible +PASS agent advertises optional structural review capability +PASS real named-pipe handshake reconciles three documents +PASS agent receives actual asynchronous positional/lifecycle traffic +PASS real pipe returns document analysis results +PASS agent shutdown retires peer sessions +PASS idle keepalive detects agent loss without a Word event +PASS agent restart reconnects and reconciles without UI waits +PASS analysis can be repeated after actual pipe host restart +PASS real pipe document close is isolated +PASS link shutdown cancels background worker promptly +PASS untrusted agent owner callback rejects connection before handshake +PASS unresponsive agent handshake times out off producer thread +PASS blank document has an explicit empty analysis +PASS plain chapter labels and separators become review suggestions +PASS ambiguous text and heading levels explain uncertainty instead of approving import +PASS analysis reuses existing PlotDirector marker interpretation +PASS fragment splits do not inflate word or paragraph counts +PASS 250000-word many-paragraph manuscript analysed incrementally +Agent synthetic 250000-word analysis: 104ms (not Word extraction/UI timing). +PASS review suggestion storage is bounded with explicit truncation +PASS analysis results are paginated +PASS review page fits bounded IPC frame +PASS analysis result contract round-trips over framing +PASS document-specific analysis returns structured results and progress +PASS document-specific analysis returns structured results and progress +PASS document-specific analysis returns structured results and progress +PASS another document's snapshot cannot retrieve results +PASS analysis acknowledges bounded partial progress before cancellation +PASS cancelled analysis cannot complete +PASS analysis waiting for Word scheduler is cancellable +PASS pending analysis cancellation does not require extraction +PASS review rejects results from a different document +PASS late results cannot replace cancellation +PASS new analysis rejects obsolete revision and snapshot +PASS review completes only matching analysis +PASS selection replies cannot regress completed review progress +PASS late page zero cannot replace requested later page +PASS agent restart releases document analysis state +PASS native connection rejects unsafe site root +PASS native connection rejects unsafe site root +PASS native connection rejects unsafe site root +PASS native connection rejects unsafe site root +PASS native connection rejects unsafe site root +PASS incompatible agent handshake enters recovery instead of killing the client worker +PASS browser-approved sign-in loads only authorised book choices +PASS sign-in and local work never upload chapter prose +PASS AI chapter capture starts only after an explicit command +PASS bounded chapter capture reports progress without submitting early +PASS duplicate submit uses one HTTP call and preserves exact chapter mapping +PASS worst-case bounded AI page fits IPC framing +PASS AI result contract round-trips on actual frame codec +PASS late cancellation cannot retire a replacement AI chapter +PASS another document cannot retrieve an AI result +PASS cancelled network chapter cannot reappear in review +PASS authorisation failure is isolated and actionable +PASS malformed AI fields fail safely instead of leaving a chapter spinning +PASS upload consent pins document snapshot and authentication context +PASS account/site change refuses old consent before any chapter HTTP upload +PASS sign-out forgets credential and book list +PASS local chapters supply explicit nonoverlapping AI extraction ranges +PASS duplicate live session identity cannot cross Word instances +Native foundation: 169 checks passed. Linux named-pipe API uses Unix domain sockets; Windows ACL/COM/Word responsiveness NOT verified. diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase3/powershell-parse.log b/Docs/WordCompanion/Evidence/2026-11-05-phase3/powershell-parse.log new file mode 100644 index 00000000..dedff1fc --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase3/powershell-parse.log @@ -0,0 +1,7 @@ +PARSE PASS Build-Developer.ps1 +PARSE PASS DeveloperPackage.ps1 +PARSE PASS Generate-Fixtures.ps1 +PARSE PASS Install-WordCompanion.ps1 +PARSE PASS Measure-Processes.ps1 +PARSE PASS Test-DeveloperPackage.ps1 +PARSE PASS Update-WordCompanion.ps1 diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase3/powershell-portable-tests.log b/Docs/WordCompanion/Evidence/2026-11-05-phase3/powershell-portable-tests.log new file mode 100644 index 00000000..172c66bd --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase3/powershell-portable-tests.log @@ -0,0 +1 @@ +PASS portable package validation, tamper refusal and non-Windows fail-closed guards. Fixture signatures are placeholders; no Office trust/Windows installation validation claimed. diff --git a/Docs/WordCompanion/Evidence/2026-11-05-phase3/vsto-syntax-only.log b/Docs/WordCompanion/Evidence/2026-11-05-phase3/vsto-syntax-only.log new file mode 100644 index 00000000..2c0b6546 --- /dev/null +++ b/Docs/WordCompanion/Evidence/2026-11-05-phase3/vsto-syntax-only.log @@ -0,0 +1,8 @@ +Syntax only PASS AnalysisWindow.cs +Syntax only PASS ThisAddIn.cs +Syntax only PASS AgentProcess.cs +Syntax only PASS ConnectWindow.cs +Syntax only PASS WordAdapter.cs +Syntax only PASS NativeRibbon.cs +Syntax only PASS ThisAddIn.Designer.cs +Syntax only PASS AssemblyInfo.cs diff --git a/PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs b/PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs index 2e0ec49e..c4f56f87 100644 --- a/PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs +++ b/PlotDirector.NativeCompanion/Agent/ChapterAiWork.cs @@ -13,13 +13,15 @@ public sealed class ChapterAiWork(CloudGateway cloud):IDisposable { if(request.Kind=="ai-begin") { + if(!cloud.Allows(request.AuthenticationContext,request.BookId)){answer.Status="authentication-changed";return answer;} if(request.SnapshotId==Guid.Empty||request.BookId<=0||request.Start<0||request.End<=request.Start||request.End-request.Start>120000){answer.Status="invalid-ai-chapter";return answer;} if(!jobs.ContainsKey(descriptor.SessionId)&&jobs.Count>=32){answer.Status="ai-capacity";return answer;} Clear(descriptor.SessionId); var chapter=new AiChapterRequest{RequestId=request.SnapshotId,BookId=request.BookId,SessionId=descriptor.SessionId,ManuscriptId=descriptor.ManuscriptId,Revision=descriptor.Revision,ChapterStart=request.Start,ChapterEnd=request.End}; - jobs[descriptor.SessionId]=new(chapter);return answer; + jobs[descriptor.SessionId]=new(chapter,request.AuthenticationContext);return answer; } if(!jobs.TryGetValue(descriptor.SessionId,out var job)||job.Chapter.RequestId!=request.SnapshotId){answer.Status="obsolete-ai-request";return answer;} + if(!cloud.Allows(job.AuthenticationContext,job.Chapter.BookId)){Clear(descriptor.SessionId);answer.Status="authentication-changed";return answer;} switch(request.Kind) { case "ai-fragment": @@ -36,9 +38,9 @@ public sealed class ChapterAiWork(CloudGateway cloud):IDisposable job.Submitted=true;job.Chapter.Paragraphs=job.Paragraphs.ToArray();job.Result.State="analysing"; _=Task.Run(async()=>{ AiChapterResult result; - try{result=await cloud.Analyse(job.Chapter,job.Token);} + try{result=await cloud.Analyse(job.Chapter,job.Token,job.AuthenticationContext);} catch(OperationCanceledException){result=new(){RequestId=job.Chapter.RequestId,State="cancelled",Message="AI analysis cancelled."};} - catch(Exception e)when(e is HttpRequestException or IOException or InvalidOperationException or System.Text.Json.JsonException) + catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or System.Text.Json.JsonException) {result=new(){RequestId=job.Chapter.RequestId,State="failed",Message=e is InvalidOperationException?e.Message:"Connection failed. Outcome may be unknown; explicit retry may incur another AI charge."};} lock(gate){job.Result=result;job.Chapter.Paragraphs=[];job.Paragraphs.Clear();job.Finished=true;job.Stop.Dispose();} });break; @@ -58,8 +60,8 @@ public sealed class ChapterAiWork(CloudGateway cloud):IDisposable public void Dispose(){lock(gate)foreach(var session in jobs.Keys.ToArray())Clear(session);} private sealed class Job { - public Job(AiChapterRequest chapter){Chapter=chapter;Position=chapter.ChapterStart;Token=Stop.Token;Result.RequestId=chapter.RequestId;} - public AiChapterRequest Chapter;public CancellationTokenSource Stop=new(TimeSpan.FromMinutes(6));public CancellationToken Token {get;}public bool Submitted,Finished; + public Job(AiChapterRequest chapter,Guid context){AuthenticationContext=context;Chapter=chapter;Position=chapter.ChapterStart;Token=Stop.Token;Result.RequestId=chapter.RequestId;} + public Guid AuthenticationContext;public AiChapterRequest Chapter;public CancellationTokenSource Stop=new(TimeSpan.FromMinutes(6));public CancellationToken Token {get;}public bool Submitted,Finished; public int Characters;public int Position,NextParagraph=1,ParagraphStart; public StringBuilder Text=new();public List Paragraphs=[]; public AiChapterResult Result=new(){State="reading"}; diff --git a/PlotDirector.NativeCompanion/Agent/CloudGateway.cs b/PlotDirector.NativeCompanion/Agent/CloudGateway.cs index 1af64c07..57bf3974 100644 --- a/PlotDirector.NativeCompanion/Agent/CloudGateway.cs +++ b/PlotDirector.NativeCompanion/Agent/CloudGateway.cs @@ -18,6 +18,7 @@ public sealed class CloudGateway : IDisposable private CancellationTokenSource? pairing; private Uri? origin; private string? token; + private Guid authenticationContext=Guid.NewGuid(); private string state="Not signed in"; private CompanionBook[] books=[]; private readonly string? settingsPath; @@ -33,12 +34,12 @@ public sealed class CloudGateway : IDisposable return uri; } public Message Status() - {lock(gate)return new(){Status=state,Books=books,ServerUrl=origin?.AbsoluteUri??ReadOrigin()};} + {lock(gate)return new(){Status=state,Books=books,AuthenticationContext=authenticationContext,ServerUrl=origin?.AbsoluteUri??ReadOrigin()};} private string ReadOrigin(){try{return settingsPath!=null&&File.Exists(settingsPath)?File.ReadAllText(settingsPath):"";}catch(IOException){return "";}} public void Connect(string address) { var uri=ValidateOrigin(address);CancellationTokenSource stop; - lock(gate){pairing?.Cancel();pairing=stop=new(TimeSpan.FromMinutes(5));origin=uri;token=null;books=[];state="Starting browser sign-in…";} + lock(gate){pairing?.Cancel();pairing=stop=new(TimeSpan.FromMinutes(5));origin=uri;authenticationContext=Guid.NewGuid();token=null;books=[];state="Starting browser sign-in…";} _=Task.Run(async()=>{ try { @@ -63,25 +64,27 @@ public sealed class CloudGateway : IDisposable return; } } - catch(Exception e)when(e is HttpRequestException or OperationCanceledException or IOException or JsonException or System.ComponentModel.Win32Exception or UnauthorizedAccessException or InvalidOperationException or ArgumentException) + catch(Exception e)when(e is HttpRequestException or OperationCanceledException or IOException or InvalidDataException or JsonException or System.ComponentModel.Win32Exception or UnauthorizedAccessException or InvalidOperationException or ArgumentException) {lock(gate)if(pairing==stop)state="Sign-in failed or expired. Check the site address and try Connect again.";} }); } - public void SignOut(){lock(gate){pairing?.Cancel();pairing=null;token=null;books=[];state="Not signed in";}} - public async Task Analyse(AiChapterRequest chapter,CancellationToken cancellation) + public void SignOut(){lock(gate){pairing?.Cancel();pairing=null;authenticationContext=Guid.NewGuid();token=null;books=[];state="Not signed in";}} + public bool Allows(Guid context,int bookId) + {lock(gate)return token!=null&&context==authenticationContext&&books.Any(b=>b.BookId==bookId);} + public async Task Analyse(AiChapterRequest chapter,CancellationToken cancellation,Guid expectedContext) { Uri site;string access; - lock(gate){site=origin??throw new InvalidOperationException("Connect to PlotDirector first.");access=token??throw new InvalidOperationException("Sign in first.");} + lock(gate){if(authenticationContext!=expectedContext)throw new InvalidOperationException("Connection/account changed. Confirm the chapter upload again.");site=origin??throw new InvalidOperationException("Connect to PlotDirector first.");access=token??throw new InvalidOperationException("Sign in first.");} using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(site,"api/native-companion/analyse-chapter")){Content=JsonContent.Create(chapter,options:Json)}; request.Headers.Authorization=new AuthenticationHeaderValue("Bearer",access); using var response=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,cancellation); - if(response.StatusCode==HttpStatusCode.Unauthorized){lock(gate)if(token==access){token=null;books=[];state="Sign-in expired. Connect again.";}throw new InvalidOperationException("Sign-in expired. Connect again.");} + if(response.StatusCode==HttpStatusCode.Unauthorized){lock(gate)if(token==access){authenticationContext=Guid.NewGuid();token=null;books=[];state="Sign-in expired. Connect again.";}throw new InvalidOperationException("Sign-in expired. Connect again.");} if(!response.IsSuccessStatusCode)throw new InvalidOperationException(response.StatusCode switch{HttpStatusCode.Forbidden=>"Book/subscription access denied.",HttpStatusCode.TooManyRequests=>"Server busy. Retry this chapter later.",HttpStatusCode.BadRequest=>"Chapter mapping or size was rejected. Check boundaries.",_=>"Server unavailable. Check the deployed native API."}); // Bound server response before deserializing; never log a body/provider message. await using var stream=await response.Content.ReadAsStreamAsync(cancellation);using var buffer=new MemoryStream();var bytes=new byte[8192]; int count;while((count=await stream.ReadAsync(bytes,cancellation))>0){if(buffer.Length+count>1024*1024)throw new InvalidDataException("AI response too large.");buffer.Write(bytes,0,count);} buffer.Position=0;var result=await JsonSerializer.DeserializeAsync(buffer,Json,cancellation)??throw new InvalidDataException(); - if(result.RequestId!=chapter.RequestId||result.Scenes==null||result.Scenes.Length>500||result.Scenes.Any(s=>s==null||s.Startchapter.ChapterEnd||s.End<=s.Start||s.Title.Length>200||s.Reason.Length>600))throw new InvalidDataException("Invalid AI mapping."); + if(result.RequestId!=chapter.RequestId||result.State is not ("complete" or "failed" or "cancelled")||result.Message==null||result.Message.Length>2048||result.Scenes==null||result.Scenes.Length>500||result.Scenes.Any(s=>s==null||s.Startchapter.ChapterEnd||s.End<=s.Start||s.Title==null||s.Reason==null||s.Confidence==null||s.Confidence.Length>32||s.Kind!="Scene"||s.Origin!="AI"||s.Title.Length>200||s.Reason.Length>600))throw new InvalidDataException("Invalid AI mapping."); return result; } public async Task CancelRemote(Guid id) diff --git a/PlotDirector.NativeCompanion/Agent/SessionManager.cs b/PlotDirector.NativeCompanion/Agent/SessionManager.cs index 812128c4..59bfd709 100644 --- a/PlotDirector.NativeCompanion/Agent/SessionManager.cs +++ b/PlotDirector.NativeCompanion/Agent/SessionManager.cs @@ -53,9 +53,9 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai if(message.Kind is "cloud-status" or "cloud-connect" or "cloud-signout") { answer.Kind="cloud-status";if(cloud==null)return Reject(answer,"cloud-unavailable"); - try{if(message.Kind=="cloud-connect")cloud.Connect(message.ServerUrl);if(message.Kind=="cloud-signout"){ai?.Dispose();cloud.SignOut();}} + try{if(message.Kind=="cloud-connect"){ai?.Dispose();cloud.Connect(message.ServerUrl);}if(message.Kind=="cloud-signout"){ai?.Dispose();cloud.SignOut();}} catch(ArgumentException){return Reject(answer,"invalid-server-url");} - var status=cloud.Status();answer.Kind="cloud-status";answer.Status=status.Status;answer.Books=status.Books;answer.ServerUrl=status.ServerUrl;return answer; + var status=cloud.Status();answer.Kind="cloud-status";answer.Status=status.Status;answer.Books=status.Books;answer.AuthenticationContext=status.AuthenticationContext;answer.ServerUrl=status.ServerUrl;return answer; } if (message.Kind is "document" or "reconcile") { diff --git a/PlotDirector.NativeCompanion/Client/AgentLink.cs b/PlotDirector.NativeCompanion/Client/AgentLink.cs index 6c978c48..704d1446 100644 --- a/PlotDirector.NativeCompanion/Client/AgentLink.cs +++ b/PlotDirector.NativeCompanion/Client/AgentLink.cs @@ -118,7 +118,7 @@ public sealed class AgentLink : IDisposable } } } - catch (Exception ex) when (ex is IOException || ex is TimeoutException || ex is OperationCanceledException || ex is UnauthorizedAccessException || ex is ObjectDisposedException || ex is System.Runtime.Serialization.SerializationException) + catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is TimeoutException || ex is OperationCanceledException || ex is UnauthorizedAccessException || ex is ObjectDisposedException || ex is System.Runtime.Serialization.SerializationException) { if (stop.IsCancellationRequested) break; StateChanged?.Invoke("offline"); diff --git a/PlotDirector.NativeCompanion/Client/AiConsent.cs b/PlotDirector.NativeCompanion/Client/AiConsent.cs new file mode 100644 index 00000000..c07e45df --- /dev/null +++ b/PlotDirector.NativeCompanion/Client/AiConsent.cs @@ -0,0 +1,13 @@ +using PlotDirector.Companion.Protocol; +namespace PlotDirector.Companion.Client; + +// Pinned before the upload confirmation dialog; never read a different target after consent. +public sealed class AiConsent +{ + public Guid SessionId {get;set;} + public Guid SnapshotId {get;set;} + public Guid AuthenticationContext {get;set;} + public int BookId {get;set;} + public StructureSuggestion[] Chapters {get;set;}=Array.Empty(); + public bool Matches(Guid session,Guid snapshot,Guid authentication) => SessionId!=Guid.Empty&&SnapshotId!=Guid.Empty&&AuthenticationContext!=Guid.Empty&&SessionId==session&&SnapshotId==snapshot&&AuthenticationContext==authentication; +} diff --git a/PlotDirector.NativeCompanion/Protocol/Messages.cs b/PlotDirector.NativeCompanion/Protocol/Messages.cs index 2442ff21..b5e4fc0b 100644 --- a/PlotDirector.NativeCompanion/Protocol/Messages.cs +++ b/PlotDirector.NativeCompanion/Protocol/Messages.cs @@ -5,7 +5,7 @@ namespace PlotDirector.Companion.Protocol; public static class ProtocolVersion { public const int Current = 1; - public const string ChapterAiCapability = "chapter-ai-v1"; + public const string ChapterAiCapability = "chapter-ai-v2"; public const string AnalysisCapability = "structure-review-v1"; public const int AnalysisPageSize = 40; public const int MaxFrameBytes = 256 * 1024; @@ -43,6 +43,7 @@ public sealed class Message [DataMember] public int? SceneId { get; set; } [DataMember] public string ChapterTitle { get; set; } = ""; [DataMember] public string SceneTitle { get; set; } = ""; + [DataMember] public Guid AuthenticationContext { get; set; } [DataMember] public string ServerUrl { get; set; } = ""; [DataMember] public AiChapterResult? Ai { get; set; } [DataMember] public CompanionBook[] Books { get; set; } = Array.Empty(); diff --git a/PlotDirector.NativeCompanion/Protocol/README.md b/PlotDirector.NativeCompanion/Protocol/README.md index 533ae9b6..b9c8f1ed 100644 --- a/PlotDirector.NativeCompanion/Protocol/README.md +++ b/PlotDirector.NativeCompanion/Protocol/README.md @@ -41,8 +41,10 @@ Analysis is incremental in the agent; no COM object crosses IPC and no analysis ## Optional Phase 3 chapter AI -`chapter-ai-v1` advertises the additive native feature. `cloud-connect` sends only an author-selected HTTPS root; `cloud-status` returns sign-in status and at most 200 authorized book choices; `cloud-signout` discards the agent's memory-only grant and cancels native AI jobs. Credentials never enter IPC. The agent performs verifier-bound browser pairing over HTTPS; the browser uses normal PlotDirector cookie login and antiforgery approval. +`chapter-ai-v2` advertises the additive native feature. `cloud-connect` sends only an author-selected HTTPS root; `cloud-status` returns sign-in status and at most 200 authorized book choices; `cloud-signout` discards the agent's memory-only grant and cancels native AI jobs. Credentials never enter IPC. The agent performs verifier-bound browser pairing over HTTPS; the browser uses normal PlotDirector cookie login and antiforgery approval. After explicit author upload confirmation, `ai-begin` specifies one chapter's Start/End, book and request SnapshotId under the exact existing document session/revision. `ai-fragment` reuses the bounded paragraph DTO and chapter-local paragraph ordinals. `ai-submit` starts asynchronous agent HTTP processing and returns promptly; duplicate submits do not create another call. `ai-status` polls that request and pages results using Start as zero-based result offset (40 rows). `ai-cancel` cancels the exact job and best-effort server request. Lifecycle/revision retirement also cancels the job. The live session ID must be unique across Word instances; a foreign duplicate is refused. Chapter capture is limited to 120,000 positions/text characters and 10,000 paragraphs. The server returns at most 500 validated AI scenes per chapter; the agent frames only 40 at a time. Suggested boundaries retain actual Word positions, provenance `AI`, confidence and bounded reasoning. Local/marker suggestions remain separate; their chapter ranges provide the upload bounds. No API or IPC operation imports scenes, rewrites text or inserts markers. Network uncertainty is not auto-replayed; explicit author retry is required and may incur a charge. Server deduplication is bounded to its process lifetime and a 30-minute cache. + +The `chapter-ai-v2` capability pins author consent to a nonsecret AuthenticationContext nonce in addition to document session, local snapshot and book. The agent rotates the context on connect/sign-out/expiry and cancels jobs on account/site change. `ai-begin` and submission refuse old context before HTTP upload; Word invalidates queued consent and book selection across instances. This nonce is not a bearer credential. HTTP chapter DTOs remain unchanged. diff --git a/PlotDirector.NativeCompanion/README.md b/PlotDirector.NativeCompanion/README.md index 76c393ff..19fd3241 100644 --- a/PlotDirector.NativeCompanion/README.md +++ b/PlotDirector.NativeCompanion/README.md @@ -1,6 +1,6 @@ # Native Word Companion — developer foundation, structure and AI review -Phase 3 adds explicit chapter-by-chapter AI review through the existing PlotDirector chapter service, browser-approved sign-in, a hierarchical native review and safe update/build plus explicit per-user installation scripts. See [Phase 3 Windows workflow](WindowsValidation/Phase3-AI.md). The baseline implementation details below describe the foundation; Phase 3's native API does not provide prose synchronization or native Context/Intent/SignalR following. +Phase 3 adds explicit chapter-by-chapter AI review through the existing PlotDirector chapter service, browser-approved sign-in, a hierarchical native review and safe update/build plus explicit per-user installation scripts. See the [Phase 3 implementation report](../Docs/WordCompanion/2026-11-05-phase3-ai-integration.md) and [Windows workflow](WindowsValidation/Phase3-AI.md). The baseline implementation details below describe the foundation; Phase 3's native API does not provide prose synchronization or native Context/Intent/SignalR following. Phase 2 adds optional local structural analysis through the existing snapshot/pipe path, with a native modeless review, progress, cancellation and per-document results. See the [Phase 2 report](../Docs/WordCompanion/2026-11-04-phase2-document-analysis.md) and [Windows analysis checklist](WindowsValidation/Phase2-Analysis.md). The author's Phase 1 Windows smoke test is build `1.0.0.3` at `726a3d5`; the Linux limitations below describe the original foundation. New Phase 2 Word integration still requires Windows qualification. diff --git a/PlotDirector.NativeCompanion/Tests/ChapterAiTests.cs b/PlotDirector.NativeCompanion/Tests/ChapterAiTests.cs index e3b15e02..0d24ec47 100644 --- a/PlotDirector.NativeCompanion/Tests/ChapterAiTests.cs +++ b/PlotDirector.NativeCompanion/Tests/ChapterAiTests.cs @@ -10,14 +10,24 @@ internal static class ChapterAiTests { foreach(var bad in new[]{"http://example.invalid/","file:///tmp/site","https://user:password@example.invalid/","https://example.invalid/path","https://example.invalid/?query=1"}) {try{CloudGateway.ValidateOrigin(bad);throw new Exception("Accepted unsafe origin");}catch(ArgumentException){check(true,"native connection rejects unsafe site root");}} + var incompatibleName="pd-incompatible-"+Guid.NewGuid().ToString("N"); + using(var incompatible=new System.IO.Pipes.NamedPipeServerStream(incompatibleName,System.IO.Pipes.PipeDirection.InOut,1,System.IO.Pipes.PipeTransmissionMode.Byte,System.IO.Pipes.PipeOptions.Asynchronous|System.IO.Pipes.PipeOptions.CurrentUserOnly)) + using(var link=new PlotDirector.Companion.Client.AgentLink(incompatibleName,Guid.NewGuid(),_=>true)) + { + var offline=0;link.StateChanged+=s=>{if(s=="offline")Interlocked.Exchange(ref offline,1);};link.Start();await incompatible.WaitForConnectionAsync(); + var hello=await FrameCodec.ReadAsync(incompatible,CancellationToken.None);await FrameCodec.WriteAsync(incompatible,new(){CorrelationId=hello.CorrelationId,Status="unsupported-version"},CancellationToken.None); + await Wait(()=>Volatile.Read(ref offline)==1);check(!link.Completion.IsCompleted,"incompatible agent handshake enters recovery instead of killing the client worker"); + link.Dispose();await link.Completion.WaitAsync(TimeSpan.FromSeconds(5)); + } var handler=new Provider();string browser="";using var cloud=new CloudGateway(handler,url=>browser=url); cloud.Connect("https://example.invalid/"); await Wait(()=>cloud.Status().Status.StartsWith("Signed in")); check(browser.StartsWith("https://example.invalid/native-companion/authorize?code=")&&cloud.Status().Books.Single().BookId==11,"browser-approved sign-in loads only authorised book choices"); check(handler.Submissions==0,"sign-in and local work never upload chapter prose"); + var approvedContext=cloud.Status().AuthenticationContext; using var jobs=new ChapterAiWork(cloud);var descriptor=new DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Revision=4}; var id=Guid.NewGuid(); - Message Send(string kind,ParagraphFragment? f=null,int offset=0)=>jobs.Handle(descriptor,new(){Kind=kind,SnapshotId=id,BookId=11,Start=kind=="ai-begin"?100:offset,End=120,Fragment=f},new(){Status="ok"}); + Message Send(string kind,ParagraphFragment? f=null,int offset=0)=>jobs.Handle(descriptor,new(){Kind=kind,SnapshotId=id,BookId=11,AuthenticationContext=approvedContext,Start=kind=="ai-begin"?100:offset,End=120,Fragment=f},new(){Status="ok"}); check(Send("ai-begin").Status=="ok","AI chapter capture starts only after an explicit command"); var progress=Send("ai-fragment",new(){ParagraphIndex=1,Start=100,End=120,Text="One chapter paragraph.",CompletesParagraph=true}); check(progress.Progress==100&&handler.Submissions==0,"bounded chapter capture reports progress without submitting early"); @@ -40,7 +50,13 @@ internal static class ChapterAiTests check(Send("ai-status").Status=="obsolete-ai-request","cancelled network chapter cannot reappear in review"); handler.Stall=false;handler.Deny=true;id=Guid.NewGuid();Send("ai-begin");Send("ai-fragment",new(){ParagraphIndex=1,Start=100,End=120,Text="Paragraph.",CompletesParagraph=true});Send("ai-submit"); await Wait(()=>Send("ai-status").Ai?.State=="failed");check(Send("ai-status").Ai!.Message.Contains("denied"),"authorisation failure is isolated and actionable"); - cloud.SignOut();check(cloud.Status().Books.Length==0&&!cloud.Status().Status.StartsWith("Signed in"),"sign-out forgets credential and book list"); + handler.Deny=false;handler.Malformed=true;id=Guid.NewGuid();Send("ai-begin");Send("ai-fragment",new(){ParagraphIndex=1,Start=100,End=120,Text="Paragraph.",CompletesParagraph=true});Send("ai-submit"); + await Wait(()=>Send("ai-status").Ai?.State=="failed");check(Send("ai-status").Ai?.State=="failed","malformed AI fields fail safely instead of leaving a chapter spinning"); + var consent=new PlotDirector.Companion.Client.AiConsent{SessionId=descriptor.SessionId,SnapshotId=Guid.NewGuid(),AuthenticationContext=approvedContext,BookId=11}; + check(consent.Matches(descriptor.SessionId,consent.SnapshotId,approvedContext)&&!consent.Matches(Guid.NewGuid(),consent.SnapshotId,approvedContext)&&!consent.Matches(descriptor.SessionId,consent.SnapshotId,Guid.NewGuid()),"upload consent pins document snapshot and authentication context"); + id=Guid.NewGuid();Send("ai-begin");Send("ai-fragment",new(){ParagraphIndex=1,Start=100,End=120,Text="Consented text.",CompletesParagraph=true});var submissionsBeforeSwitch=handler.Submissions; + cloud.SignOut();check(Send("ai-submit").Status=="authentication-changed"&&handler.Submissions==submissionsBeforeSwitch,"account/site change refuses old consent before any chapter HTTP upload"); + check(cloud.Status().Books.Length==0&&!cloud.Status().Status.StartsWith("Signed in"),"sign-out forgets credential and book list"); var analysis=new DocumentAnalysis();analysis.Add(new(){ParagraphIndex=1,Start=0,End=12,Text="Chapter One\r",OutlineLevel=1,CompletesParagraph=true});analysis.Add(new(){ParagraphIndex=2,Start=12,End=17,Text="Body\r",OutlineLevel=10,CompletesParagraph=true});analysis.Add(new(){ParagraphIndex=3,Start=17,End=29,Text="Chapter Two\r",OutlineLevel=1,CompletesParagraph=true}); var chapters=analysis.Page(0).Items.Where(i=>i.Kind=="Chapter").ToArray();check(chapters[0].End==17&&chapters[1].End==29,"local chapters supply explicit nonoverlapping AI extraction ranges"); var manager=new SessionManager();var a=Guid.NewGuid();var b=Guid.NewGuid();var la=Guid.NewGuid();var lb=Guid.NewGuid();manager.Attach(a,la);manager.Attach(b,lb); @@ -50,7 +66,7 @@ internal static class ChapterAiTests private static async Task Wait(Func ready){using var stop=new CancellationTokenSource(TimeSpan.FromSeconds(12));while(!ready())await Task.Delay(20,stop.Token);} private sealed class Provider:HttpMessageHandler { - public int Submissions;public AiChapterRequest? Last;public bool Stall,Deny; + public int Submissions;public AiChapterRequest? Last;public bool Stall,Deny,Malformed; protected override async Task SendAsync(HttpRequestMessage request,CancellationToken cancellation) { var path=request.RequestUri!.AbsolutePath; @@ -61,7 +77,7 @@ internal static class ChapterAiTests Last=await request.Content!.ReadFromJsonAsync(cancellation);Interlocked.Increment(ref Submissions); if(Stall)await Task.Delay(Timeout.Infinite,cancellation); if(Deny)return new(HttpStatusCode.Forbidden); - return new(HttpStatusCode.OK){Content=JsonContent.Create(new AiChapterResult{RequestId=Last!.RequestId,State="complete",Scenes=[new(){Start=100,End=120,Kind="Scene",Origin="AI",Title="Narrative interpretation",Reason="A change in narrative focus."}]})}; + return new(HttpStatusCode.OK){Content=JsonContent.Create(new AiChapterResult{RequestId=Last!.RequestId,State="complete",Scenes=[new(){Start=100,End=120,Kind="Scene",Origin="AI",Title=Malformed?null!:"Narrative interpretation",Reason="A change in narrative focus."}]})}; } } } diff --git a/PlotDirector.NativeCompanion/Vsto/AnalysisWindow.cs b/PlotDirector.NativeCompanion/Vsto/AnalysisWindow.cs index 61c78308..e483a5fc 100644 --- a/PlotDirector.NativeCompanion/Vsto/AnalysisWindow.cs +++ b/PlotDirector.NativeCompanion/Vsto/AnalysisWindow.cs @@ -21,9 +21,9 @@ namespace PlotDirector.WordAddIn private readonly Button cancel=new Button{Text="Cancel",AutoSize=true}; private readonly Button next=new Button{Text="Next",AutoSize=true},previous=new Button{Text="Previous",AutoSize=true}; private readonly TabControl tabs=new TabControl{Dock=DockStyle.Fill}; - private int aiOffset;private Guid session;private string renderKey="";private string bookKey="";private string aiRenderKey=""; + private int aiOffset;private Guid session,authenticationContext,localSnapshot;private string renderKey="";private string bookKey="";private string aiRenderKey=""; private IList aiItems=new List(); - public AnalysisWindow(Action analyse,Action stop,Action page,Action submit,Action navigate) + public AnalysisWindow(Action analyse,Action stop,Action page,Action submit,Action navigate) { Text="PlotDirector — Manuscript review";Font=new Font("Segoe UI",9F);AutoScaleMode=AutoScaleMode.Dpi;MinimumSize=new Size(680,480);Width=980;Height=680;ShowInTaskbar=false; status.MaximumSize=new Size(Math.Max(400,ClientSize.Width-40),0); @@ -36,8 +36,9 @@ namespace PlotDirector.WordAddIn var ask=new Button{Text="AI: analyse checked chapters",AutoSize=true};ask.Click+=(_,__)=>{ var chosen=local.Nodes.Cast().Where(n=>n.Checked&&n.Tag is StructureSuggestion).Select(n=>(StructureSuggestion)n.Tag).ToArray(); if(chosen.Length==0){MessageBox.Show("Check one or more chapter nodes in Local structure first.","PlotDirector");return;} - if(SelectedBook<=0){MessageBox.Show("Connect, then select an authorised PlotDirector book.","PlotDirector");return;} - if(MessageBox.Show("Send "+chosen.Length+" selected chapter(s) for book "+(books.SelectedItem as CompanionBook)?.Title+" to PlotDirector's configured AI provider? This may incur AI costs. Existing markers and manuscript text will not change.","Confirm chapter upload",MessageBoxButtons.OKCancel)==DialogResult.OK)submit(chosen); + var consent=new AiConsent{SessionId=session,SnapshotId=localSnapshot,AuthenticationContext=authenticationContext,BookId=SelectedBook,Chapters=chosen}; + if(consent.BookId<=0){MessageBox.Show("Connect, then select an authorised PlotDirector book.","PlotDirector");return;} + if(MessageBox.Show("Send "+chosen.Length+" selected chapter(s) for book "+(books.SelectedItem as CompanionBook)?.Title+" to PlotDirector's configured AI provider? This may incur AI costs. Existing markers and manuscript text will not change.","Confirm chapter upload",MessageBoxButtons.OKCancel)==DialogResult.OK)submit(consent); }; cancel.Click+=(_,__)=>stop();actions.Controls.AddRange(new Control[]{repeat,books,ask,cancel}); var localTab=new TabPage("Local structure");localTab.Controls.Add(local);var aiTab=new TabPage("AI scene suggestions");aiTab.Controls.Add(ai);tabs.TabPages.AddRange(new[]{localTab,aiTab}); @@ -51,11 +52,13 @@ namespace PlotDirector.WordAddIn layout.Controls.Add(status,0,0);layout.Controls.Add(progress,0,1);layout.Controls.Add(actions,0,2);layout.Controls.Add(tabs,0,3);layout.Controls.Add(details,0,4);layout.Controls.Add(footer,0,5);Controls.Add(layout); Resize+=(_,__)=>status.MaximumSize=new Size(Math.Max(400,ClientSize.Width-40),0); } + public void ForgetBookSelection(){books.SelectedIndex=-1;} public int SelectedBook=>books.SelectedItem is CompanionBook book?book.BookId:0; private AnalysisPage current; - public void Render(AnalysisReview review,string connection,Guid document,string documentName,CompanionBook[] available,string cloud,string aiStatus,IList results,bool running) + public void Render(AnalysisReview review,string connection,Guid document,string documentName,Guid authentication,CompanionBook[] available,string cloud,string aiStatus,IList results,bool running) { if(session!=document){session=document;renderKey="";aiRenderKey="";books.SelectedIndex=-1;aiOffset=0;local.Nodes.Clear();ai.Nodes.Clear();details.Clear();} + authenticationContext=authentication;localSnapshot=review?.SnapshotId??Guid.Empty; current=review?.Page;aiItems=results??new List(); status.Text=(documentName??"No active document")+" · Agent: "+connection+" · "+cloud+"\n"+(string.IsNullOrEmpty(aiStatus)?review?.Status:aiStatus); if(current!=null)status.Text+="\n"+current.WordCount.ToString("N0")+" approximate words · "+current.ChapterCount+" local chapter candidates · "+current.SceneCount+" local scene candidates. "+(current.Truncated?"Result limit reached. ":"")+"Double-click to navigate; select to inspect evidence."; diff --git a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs index 6f637e04..9e8fe54d 100644 --- a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs +++ b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs @@ -3,6 +3,6 @@ using System.Runtime.InteropServices; [assembly: AssemblyTitle("PlotDirector Word Companion — Native development")] [assembly: AssemblyCompany("Nick Beckley")] [assembly: AssemblyProduct("PlotDirector")] -[assembly: AssemblyVersion("0.1.0.0")] +[assembly: AssemblyVersion("1.0.0.5")] [assembly: AssemblyFileVersion("1.0.0.5")] [assembly: ComVisible(false)] diff --git a/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs b/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs index 6d4c06d7..5e4ec1a6 100644 --- a/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs +++ b/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs @@ -49,6 +49,7 @@ namespace PlotDirector.WordAddIn private int documentCollectionGeneration; private double lastBatchMs; private AnalysisWindow analysisWindow; + private Guid cloudContext; private string cloudState="Not signed in",serverUrl=""; private CompanionBook[] cloudBooks=Array.Empty(); private bool analysisSupported,cloudSupported; @@ -89,7 +90,7 @@ namespace PlotDirector.WordAddIn }); link.Received += message => { if(message.Kind=="cloud-status") - {PostToUi(()=>{cloudState=message.Status;cloudBooks=message.Books;serverUrl=message.ServerUrl;reviewDirty=true;});return;} + {PostToUi(()=>{if(cloudContext!=message.AuthenticationContext){foreach(var doc in documents.Values)if(doc.AiJob!=Guid.Empty||doc.AiQueue.Count>0)StopAi(doc,"Connection/account changed. Review and confirm chapters again.");analysisWindow?.ForgetBookSelection();}cloudContext=message.AuthenticationContext;cloudState=message.Status;cloudBooks=message.Books;serverUrl=message.ServerUrl;reviewDirty=true;});return;} if(message.Status=="ready")PostToUi(()=>{analysisSupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.AnalysisCapability);cloudSupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterAiCapability);}); // Bound/coalesce progress independently of the Word message pump. // Never accumulate one BeginInvoke callback per manuscript fragment. @@ -274,7 +275,7 @@ namespace PlotDirector.WordAddIn lastResult="Agent queue busy. Try the results page again."; } private void RenderReview() - {if(analysisWindow!=null&&!analysisWindow.IsDisposed)analysisWindow.Render(active?.Review,ConnectionState,active?.Session??Guid.Empty,active?.DisplayName,cloudBooks,cloudState,active?.AiStatus,active?.AiResults,active!=null&&active.AiJob!=Guid.Empty);reviewDirty=false;} + {if(analysisWindow!=null&&!analysisWindow.IsDisposed)analysisWindow.Render(active?.Review,ConnectionState,active?.Session??Guid.Empty,active?.DisplayName,cloudContext,cloudBooks,cloudState,active?.AiStatus,active?.AiResults,active!=null&&active.AiJob!=Guid.Empty);reviewDirty=false;} public void RequestSnapshot() { if (active == null) return; @@ -303,7 +304,7 @@ namespace PlotDirector.WordAddIn { if(!extraction.Begun) { - if(!link.TryPost(new Message{Kind=extraction.IsAi?"ai-begin":"snapshot-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,Start=extraction.Position,End=extraction.Limit,BookId=doc.AiBook,RequestAnalysis=extraction.Analyse}))return; + if(!link.TryPost(new Message{Kind=extraction.IsAi?"ai-begin":"snapshot-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,Start=extraction.Position,End=extraction.Limit,BookId=doc.AiBook,AuthenticationContext=doc.AiAuthenticationContext,RequestAnalysis=extraction.Analyse}))return; extraction.Begun=true; } // At most four <=2048-character fragments and a cooperative ~20ms budget. @@ -482,23 +483,25 @@ namespace PlotDirector.WordAddIn } } public void ConnectToServer(string address) - {if(!cloudSupported){MessageBox.Show("Connect the matching Phase 3 agent first.","PlotDirector");return;}link.TryPost(new Message{Kind="cloud-connect",ServerUrl=address});} + {foreach(var doc in documents.Values)if(doc.AiJob!=Guid.Empty||doc.AiQueue.Count>0)StopAi(doc,"Connecting a different account/site. Confirm chapters again.");if(!cloudSupported){MessageBox.Show("Connect the matching Phase 3 agent first.","PlotDirector");return;}link.TryPost(new Message{Kind="cloud-connect",ServerUrl=address});} public string ServerUrl=>serverUrl; public string CloudState=>cloudState; public void SignOut(){foreach(var doc in documents.Values)StopAi(doc,"Signed out. Successful results retained.");link.TryPost(new Message{Kind="cloud-signout"});} - private void StartAi(StructureSuggestion[] chapters) + private void StartAi(AiConsent consent) { var doc=active;if(doc==null||doc.Review.Page==null||doc.Review.Running)return; + if(!consent.Matches(doc.Session,doc.Review.SnapshotId,cloudContext)||!cloudBooks.Any(b=>b.BookId==consent.BookId)){MessageBox.Show("Document, connection or book changed during confirmation. Review the target and confirm again.","PlotDirector");return;} if(!cloudState.StartsWith("Signed in",StringComparison.Ordinal)){MessageBox.Show("Use Connect / Sign In first.","PlotDirector");return;} if(doc.AiJob!=Guid.Empty){MessageBox.Show("Cancel the current chapter batch before starting another.","PlotDirector");return;} - doc.AiBook=analysisWindow.SelectedBook;doc.AiCompleted=0;doc.AiFailures.Clear();doc.AiQueue.Clear(); - foreach(var chapter in chapters.Where(c=>c.Kind=="Chapter"&&c.Start>=0&&c.End>c.Start).GroupBy(c=>c.Start).Select(g=>g.First()).Take(256))doc.AiQueue.Enqueue(chapter); + doc.AiBook=consent.BookId;doc.AiAuthenticationContext=consent.AuthenticationContext;doc.AiCompleted=0;doc.AiFailures.Clear();doc.AiQueue.Clear(); + foreach(var chapter in consent.Chapters.Where(c=>c.Kind=="Chapter"&&c.Start>=0&&c.End>c.Start).GroupBy(c=>c.Start).Select(g=>g.First()).Take(256))doc.AiQueue.Enqueue(chapter); doc.AiTotal=doc.AiQueue.Count;if(doc.AiTotal==0){doc.AiStatus="No valid chapter ranges selected. Detect structure again.";reviewDirty=true;return;}NextAi(doc); } private void NextAi(LocalDocument doc) { doc.AiJob=Guid.Empty;doc.AiOffset=0;doc.AiPartial.Clear(); - if(doc.AiQueue.Count==0){doc.AiStatus="AI batch finished: "+doc.AiCompleted+" / "+doc.AiTotal+" chapters processed. Review AI suggestions; failed chapters can be explicitly retried."+(doc.AiFailures.Count>0?" "+doc.AiFailures.Count+" chapter(s) failed; inspect AI suggestions for details.":"");reviewDirty=true;return;} + if(doc.AiQueue.Count==0){doc.AiStatus="AI batch finished: "+doc.AiCompleted+" / "+doc.AiTotal+" chapters processed. Review AI suggestions; failed chapters can be explicitly retried."+(doc.AiResults.Count>=5000?" Review limit reached; additional suggestions were not retained.":"")+(doc.AiFailures.Count>0?" "+doc.AiFailures.Count+" chapter(s) failed; inspect AI suggestions for details.":"");reviewDirty=true;return;} + if(doc.AiResults.Count>=5000){StopAi(doc,"Review limit reached (5,000 rows). Remaining selected chapters were not uploaded.");return;} var chapter=doc.AiQueue.Dequeue();doc.AiChapter=chapter; if(chapter.End-chapter.Start>120000){AiFailure(doc,"Chapter exceeds the 120,000-character upload limit. Review its boundaries.");doc.AiCompleted++;NextAi(doc);return;} doc.AiJob=Guid.NewGuid(); @@ -514,6 +517,7 @@ namespace PlotDirector.WordAddIn private void AcceptAi(LocalDocument doc,Message message) { if(message.Revision!=doc.Revision)return; + if(message.Status=="authentication-changed"){StopAi(doc,"Connection/account changed. Confirm the upload again after signing in.");return;} if(message.Status!="ok"){doc.AiStatus="Chapter failed: "+message.Status;doc.AiCompleted++;AiFailure(doc,message.Status);NextAi(doc);return;} var result=message.Ai; if(result==null)return; @@ -632,7 +636,7 @@ namespace PlotDirector.WordAddIn public readonly Queue AiQueue=new Queue(); public readonly List AiResults=new List(); public readonly List AiFailures=new List(); - public Guid AiJob;public int AiBook,AiOffset,AiCompleted,AiTotal;public string AiStatus; + public Guid AiAuthenticationContext;public Guid AiJob;public int AiBook,AiOffset,AiCompleted,AiTotal;public string AiStatus; public StructureSuggestion AiChapter;public readonly List AiPartial=new List(); public int? ProjectId,BookId;public long Revision;public int End;public bool WasSaved;public bool NeedsSnapshot=true;public Extraction Extraction; public LocalDocument(Word.Document document){Document=document;}