feat: add cancellable native manuscript structure analysis and review

This commit is contained in:
Nick Beckley 2026-11-04 22:33:46 +00:00
parent 726a3d5bc2
commit c1c6009844
23 changed files with 1095 additions and 33 deletions

View File

@ -0,0 +1,87 @@
# Native Word Companion Phase 2: local document analysis
4 November 2026. Shared branch: `codex/word-companion-native-phase1-20261104`.
## Baseline and scope
Started from a clean branch at `726a3d5`, matching the fetched remote tip, with Windows fixes `2f0f5a4`, `f0d1f6b`, `a0c2d25` and `726a3d5` present. The author identifies this as the successful Windows smoke-tested build `1.0.0.3`. The older [Windows qualification report](2026-11-04-windows-qualification.md) predates that smoke test; its pending-load wording is historical. The deployment/package version is not recorded in source (assembly version remains `0.1.0.0`); this work does not claim to have reproduced that package or assign a new published version.
The [Phase 1 report](2026-11-04-phase1-implementation.md) and component/protocol documentation supplied the baseline and remaining-work plan. There was no separate native Phase 2 implementation plan in the companion documentation. Existing extraction, session management, named pipes, lifecycle/scheduling, native ribbon and marker-based resolution were reused. The registration queue-loop and blank-document fixes are preserved. No new branch, transport, server endpoint, database operation or application deployment was introduced.
This phase implements an end-to-end **Word → local agent → Word review** workflow. It does not connect native documents to the authenticated PlotDirector website. Existing server chapter/scene analysis (`ManuscriptStructureAnalysisService.AnalyseChapterAsync`) depends on approved onboarding context, paragraph maps, configured prompts and the Story Intelligence client. It is not a standalone local parser and cannot safely be called without native authentication and binding. Those business services, import approval and scene identity ownership remain on the server. The smallest local extension provides structural evidence and suggestions, not an alternative onboarding or AI pipeline.
## Author workflow
1. Open a document and wait for the existing agent connection/session registration.
2. Choose **Analyse Document** on the native PlotDirector ribbon.
3. A small modeless review window shows extraction/analysis progress. Typing and Word operations retain priority; work waits for quiet periods.
4. Review approximate word count, paragraph count and potential chapter/scene boundaries. Rows show paragraph ordinal, title/separator, evidence and confidence. Results are paged, 40 rows at a time.
5. Use **Cancel** in the window or **Cancel Analysis** on the ribbon. Use **Analyse again** to acquire a fresh snapshot. Reopening review for the same valid analysis reuses its results instead of reading the manuscript again.
The window follows the active document session. Switching documents retains separate results/work; it never presents another document's results as the current manuscript. A request still waiting to start is stopped if its target has switched or is closing. A started extraction can continue for its exact document in bounded scheduled steps. Closing retires that session; cancelled close requires a new analysis. Save handlers do not delay saving: they stop analysis, invalidate its review and let Word proceed. Disconnect invalidates review/paging; after reconnect the author can analyse again. Closing the review window alone does not cancel work; the ribbon cancellation remains available.
No import, binding change, marker insertion, manuscript overwrite, automatic save, prose upload or AI request is performed by analysis. The separate existing Settings action still offers explicit native identity persistence.
## Implementation
```mermaid
sequenceDiagram
actor Author
participant UI as Native ribbon / modeless review
participant STA as Existing Word STA scheduler
participant Pipe as Existing AgentLink / pipe v1
participant Agent as .NET 10 session manager + analysis
Author->>UI: Analyse Document
UI->>STA: Schedule exact active document
STA->>Pipe: Descriptor, snapshot-begin(RequestAnalysis)
loop Bounded extraction with UI yields
STA->>STA: Existing <=2048-character range reads
STA->>Pipe: Ordered paragraph fragment
Pipe->>Agent: Values only; no COM objects
Agent->>Agent: Incremental counts / boundary evidence
Agent-->>Pipe: Progress acknowledgement
Pipe-->>UI: Bounded/coalesced progress, UI timer consumption
end
STA->>Pipe: snapshot-end
Pipe->>Agent: Validate session/revision/completeness
Agent-->>UI: First bounded results page
Author->>UI: Next / previous results
UI->>Agent: analysis-page(exact session/revision/snapshot)
Agent-->>UI: Requested page
opt Cancel, close, observed edit or disconnect
UI->>STA: Cancel/supersede extraction
STA->>Agent: Existing snapshot-cancel or session retirement
UI->>UI: Reject late results
end
```
- [DocumentAnalysis](../../PlotDirector.NativeCompanion/Agent/DocumentAnalysis.cs) processes each existing fragment on the agent, retaining only a bounded paragraph prefix and candidate rows in addition to Phase 1's temporary snapshot storage. It counts across fragment splits, uses existing `StructuralParser.MarkerId` semantics, outline levels, common English chapter/part/book labels, standalone numerals and visible separators. Candidate titles are capped at 200 characters. Markers/headings are evidence; text-only labels and separators are explicitly possible/uncertain suggestions.
- Existing trusted positional chapter/scene resolution remains separate. Guessed boundaries are never promoted to authorized server scene IDs or used for Context/Intent routing.
- [SessionManager](../../PlotDirector.NativeCompanion/Agent/SessionManager.cs) binds analysis to the current instance lease, document session, revision and snapshot. Invalid/incomplete/cancelled work cannot commit. Review requests have exact snapshot identity and bounded offsets. Snapshot fragments may not advance beyond the declared document end.
- [AnalysisReview](../../PlotDirector.NativeCompanion/Client/AnalysisReview.cs) holds per-document value-only review state and rejects another document, old revision, old snapshot, stale page and late post-cancellation results. Ordinary selection replies cannot regress a completed review.
- [WordAdapter](../../PlotDirector.NativeCompanion/Vsto/WordAdapter.cs) reuses the tested Word access path. All COM stays on the original STA. Preparation, extraction and author cancellation are scheduled without blocking IPC. Review progress is bounded to 32 session slots, drained at most four per UI tick and rendered at most every 250 ms. It does not queue a UI callback per paragraph. Existing cooperative four-fragment/~20 ms extraction batches and COM timing remain in place.
- [AnalysisWindow](../../PlotDirector.NativeCompanion/Vsto/AnalysisWindow.cs) is a small modeless Windows Forms review, with no COM references, embedded website, network calls or import controls.
## Compatibility, bounds and privacy
Protocol version remains 1. The optional `structure-review-v1` capability is advertised by new agents/clients; original required capabilities and endpoint remain unchanged. New VSTO enables analysis only after the agent advertises it. Old clients still request ordinary snapshots, and new agents keep their normal response behavior. Unknown optional DTO members are additive. Native components should nevertheless be rebuilt together for Windows qualification; an already-running old agent needs to be stopped/restarted to expose the new capability.
`RequestAnalysis` on `snapshot-begin` enables incremental analysis. Fragment responses carry `Progress`; successful `snapshot-end` returns `analysis-complete` and the first `AnalysisPage`. `analysis-page` uses `Start` as a zero-based result offset. Results contain counts, total, offset, truncation notice and at most 40 `StructureSuggestion` values. No prose body is returned. Additional contracts retain the existing 256 KiB frame bound, correlation IDs, timeouts, backpressure and reconnect behavior. No breaking Office.js or browser SignalR change was made.
Candidate storage is capped at 8,192 per document, with explicit truncation, and 32,768 retained candidates globally. Existing snapshot/global storage and fragment bounds remain. Disconnect/close/reconcile/revision replacement release the agent state. Temporary snapshot prose is released after commit; analysis retains only counts and bounded heading/separator excerpts. It is not persisted to disk or written to diagnostic logs. Existing metadata-only offline work queues remain disconnected from a prose sender.
## Verification and limits
Linux solution build passed with zero warnings/errors. Native harness passed **146 assertions**, including existing capacity-slot checks, not 146 independent end-to-end scenarios. Coverage includes blank documents, chapter labels, marker reuse, ambiguity explanations, split words/paragraphs, synthetic 250,000-word analysis, truncation, framed/paged results, three document sessions, cancellation before/during extraction, stale results/pages, actual named-pipe analysis replies and repeat analysis after actual pipe-host shutdown/restart. Application regression harness passed 406 checks; focused Chromium Context/Intent and Writer launcher regressions passed. All commands exited 0. Retained output and exact commands are in the [Phase 2 evidence directory](Evidence/2026-11-04-phase2/README.md).
VSTO C# syntax and XML were checked, but the VSTO host was **not built or executed on Linux**. Linux named pipes use Unix-domain sockets. No new Windows COM, modeless-window interaction, Office compatibility, cross-user security or Word responsiveness claim is made. Windows test instructions are [here](../../PlotDirector.NativeCompanion/WindowsValidation/Phase2-Analysis.md).
Limitations:
- Local deterministic suggestions only. No semantic scene detection, AI, authenticated server integration, import preview/commit or Context/Intent synchronization. Unmarked scenes can be missed; non-English chapter labels need markers/outline levels. Formatting and chapter/scene meaning need author review.
- Word count is approximate whitespace-based local counting, not Word's own statistics. Main document ranges are analyzed; other Word stories such as headers, footnotes and text boxes are not integrated.
- Phase 1 change detection remains positional/first-saved-to-dirty based. Same-length edits while already dirty are not fully detected. Results represent an observed snapshot, not a full edit journal; use Analyse again after edits. Concurrent edits that are not observed can require a repeat analysis. No manuscript import uses these results automatically.
- Single COM calls cannot be preempted. Batching is a cooperative target, not a guaranteed latency bound. Validate with real 190k/250k manuscripts, many short paragraphs and continuous interaction on Windows before acceptance.
- Signing, installation/update distribution, native authentication, server-authorized persistent binding and session-aware SignalR remain subsequent reviewed work. No installed Windows component was modified from Atlas.
Stop after review and Windows qualification. No Production deployment was performed.

View File

@ -0,0 +1,16 @@
# Phase 2 Linux verification
4 November 2026. Tested source is the Phase 2 local document-analysis change on top of `726a3d5`, on the existing shared Phase 1 branch. No application/database deployment or Windows installation change.
Run serially from repository root:
```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
node PlotLine.Tests/Browser/word-companion-regressions.cjs
```
All exited 0. Managed build: zero warnings/errors. Native harness: 146 assertions, including capacity-slot assertions and 250,000-word agent-only synthetic analysis. Application harness: 406 PASS checks. Chromium regressions: Context, Intent and fresh Writer launcher passed. No live database ownership specialist test was run during this phase.
VSTO source was parsed by a temporary SDK Roslyn syntax checker; VSTO project/ribbon/host-item XML was parsed. These checks do not bind Office assemblies or compile/run the VSTO host. No VSTO build attempt on Linux. Windows qualification is required for all new Word UI/COM behavior and performance. Native test pipes use Unix-domain sockets on Linux.

View File

@ -0,0 +1,407 @@
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 13ms.
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

View File

@ -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

View File

@ -0,0 +1,15 @@
Determining projects to restore...
All projects are up-to-date for restore.
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.Protocol -> /srv/repos/PlotDirector/PlotDirector.NativeCompanion/Protocol/bin/Debug/netstandard2.0/PlotDirector.Companion.Protocol.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:07.13

View File

@ -0,0 +1,148 @@
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: 101ms (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
Native foundation: 146 checks passed. Linux named-pipe API uses Unix domain sockets; Windows ACL/COM/Word responsiveness NOT verified.

View File

@ -0,0 +1,7 @@
Syntax only PASS AnalysisWindow.cs
Syntax only PASS ThisAddIn.cs
Syntax only PASS AgentProcess.cs
Syntax only PASS WordAdapter.cs
Syntax only PASS NativeRibbon.cs
Syntax only PASS ThisAddIn.Designer.cs
Syntax only PASS AssemblyInfo.cs

View File

@ -0,0 +1,61 @@
using System.Text;
using System.Text.RegularExpressions;
using PlotDirector.Companion.Protocol;
namespace PlotDirector.Companion.Agent;
// Incremental, local structural review. No server identities, AI or import decisions.
// Keeps a bounded paragraph prefix and suggestions, not a second manuscript copy.
public sealed class DocumentAnalysis
{
private const int Limit = 8192;
private readonly List<StructureSuggestion> suggestions = [];
private readonly StringBuilder prefix = new(240);
private static readonly Regex ChapterLabel = new(@"^(chapter|part|book)\s+(\d+|[ivxlcdm]+|one|two|three|four|five|six|seven|eight|nine|ten)(\b|:)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(50));
private static readonly Regex NumberOnly = new(@"^(\d{1,3}|[IVXLCDM]{1,8})[.:]?$", RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(50));
private bool inWord;
private int words, paragraphs, paragraphStart, paragraphLength, outline;
private string[] tags = [];
private bool truncated;
public int Count => suggestions.Count;
public void Add(ParagraphFragment fragment)
{
if (paragraphLength == 0) { paragraphStart=fragment.Start; outline=fragment.OutlineLevel; tags=fragment.MarkerTags; }
if(prefix.Length<240)prefix.Append(fragment.Text.AsSpan(0,Math.Min(fragment.Text.Length,240-prefix.Length)));
paragraphLength += fragment.Text.Length;
foreach(var character in fragment.Text)
{
var next=!char.IsWhiteSpace(character) && character!='\a';
if(next&&!inWord)words++;
inWord=next;
}
if(!fragment.CompletesParagraph)return;
paragraphs++; inWord=false;
var text=prefix.ToString().Trim('\r','\n','\a',' ','\t');
var chapter=StructuralParser.MarkerId(tags,"PD-CHAPTER-").HasValue;
var scene=StructuralParser.MarkerId(tags,"PD-SCENE-").HasValue;
if(chapter||(outline==1&&text.Length>0))Suggest("Chapter",text,"Strong",chapter?"Existing PlotDirector chapter marker":"Word heading level 1");
if(scene||(outline==2&&text.Length>0))Suggest("Scene",text,"Strong",scene?"Existing PlotDirector scene marker":"Word heading level 2; review whether this is a scene");
if(!chapter&&!scene&&outline>2&&paragraphLength<=240&&text.Length>0)
{
if(ChapterLabel.IsMatch(text))Suggest("Chapter",text,"Possible","Chapter/part/book label; confirm hierarchy");
else if(NumberOnly.IsMatch(text))Suggest("Chapter",text,"Uncertain","Standalone number may be a heading or ordinary text");
else if(text.Replace(" ","") is "***" or "---" or "###" or "#" or "⁂")
Suggest("Scene",text,"Possible","Visible separator; may be decorative");
}
prefix.Clear();paragraphLength=0;tags=[];
}
private void Suggest(string kind,string text,string confidence,string reason)
{
if(suggestions.Count==Limit){truncated=true;return;}
suggestions.Add(new StructureSuggestion{Start=paragraphStart,Paragraph=paragraphs,Kind=kind,Title=text.Length>200?text[..200]:text,Confidence=confidence,Reason=reason});
}
public AnalysisPage Page(int offset)
{
if(offset<0||offset>suggestions.Count)throw new ArgumentOutOfRangeException(nameof(offset));
return new AnalysisPage{Offset=offset,Total=suggestions.Count,WordCount=words,ParagraphCount=paragraphs,
ChapterCount=suggestions.Count(s=>s.Kind=="Chapter"),SceneCount=suggestions.Count(s=>s.Kind=="Scene"),Truncated=truncated,
Notice=words==0?"No manuscript words found.":"Local suggestions only. Unmarked prose may contain undetected scenes. Nothing has been imported or changed.",
Items=suggestions.Skip(offset).Take(ProtocolVersion.AnalysisPageSize).ToArray()};
}
}

View File

@ -56,7 +56,7 @@ public sealed class PipeHost(string pipeName, SessionManager sessions, Action<st
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="unsupported-version"},cancellation); return;
}
instance = hello.WordInstanceId; sessions.Attach(instance,lease);
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="ready",WordInstanceId=instance},cancellation);
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="ready",WordInstanceId=instance,Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability},cancellation);
log?.Invoke("peer-connected");
while (!cancellation.IsCancellationRequested)
{

View File

@ -13,6 +13,7 @@ public sealed class SessionManager
private int totalCharacters;
private int totalFragments;
private int totalBoundaries;
private int totalSuggestions;
public int SessionCount { get { lock (gate) return instances.Values.Sum(i => i.Documents.Count); } }
public void Attach(Guid instance, Guid lease)
{
@ -36,6 +37,7 @@ public sealed class SessionManager
}
private void ClearDocument(DocumentState document)
{
totalSuggestions -= document.Analysis?.Count ?? 0;document.Analysis=null;
ClearPending(document);totalBoundaries -= document.Boundaries.Count;document.Boundaries=[];
}
public Message Apply(Guid lease, Message message)
@ -89,11 +91,11 @@ public sealed class SessionManager
case "snapshot-begin":
if (message.SnapshotId == Guid.Empty || message.End < 0 || message.End > MaxSnapshotCharacters) return Reject(answer,"invalid-snapshot");
ClearPending(document);
document.Pending = new Snapshot(message.SnapshotId,message.End); break;
document.Pending = new Snapshot(message.SnapshotId,message.End,message.RequestAnalysis); break;
case "snapshot-fragment":
var pending = document.Pending; var fragment = message.Fragment;
if (pending == null || pending.Id != message.SnapshotId) return Reject(answer,"obsolete-snapshot");
if (fragment == null || fragment.Text == null || fragment.Text.Length > ProtocolVersion.MaxParagraphCharacters || fragment.Start != pending.End || fragment.End <= fragment.Start || fragment.End-fragment.Start > ProtocolVersion.MaxParagraphCharacters || fragment.ParagraphIndex != pending.NextParagraph || fragment.OutlineLevel < 1 || fragment.OutlineLevel > 10
if (fragment == null || fragment.Text == null || fragment.Text.Length > ProtocolVersion.MaxParagraphCharacters || fragment.Start != pending.End || fragment.End <= fragment.Start || fragment.End>pending.ExpectedEnd || fragment.End-fragment.Start > ProtocolVersion.MaxParagraphCharacters || fragment.ParagraphIndex != pending.NextParagraph || fragment.OutlineLevel < 1 || fragment.OutlineLevel > 10
|| fragment.MarkerTags == null || fragment.MarkerTags.Length > 16 || fragment.MarkerTags.Any(t => t == null || t.Length > 128) || pending.Fragments.Count >= 200_000)
return Reject(answer,"invalid-fragment");
// Include marker text and a per-fragment metadata allowance so
@ -101,18 +103,29 @@ public sealed class SessionManager
var cost = fragment.Text.Length + fragment.MarkerTags.Sum(t=>t.Length) + 128;
if (pending.Characters + cost > MaxSnapshotCharacters || totalCharacters + cost > MaxTotalCharacters || totalFragments >= 200_000) return Reject(answer,"snapshot-capacity");
pending.Characters += cost; totalCharacters += cost; totalFragments++;
pending.End = fragment.End; pending.LastComplete = fragment.CompletesParagraph; if(fragment.CompletesParagraph)pending.NextParagraph++; pending.Fragments.Add(fragment); break;
pending.End = fragment.End; pending.LastComplete = fragment.CompletesParagraph; if(fragment.CompletesParagraph)pending.NextParagraph++; pending.Fragments.Add(fragment); pending.Analysis?.Add(fragment);
answer.Progress=pending.ExpectedEnd==0?100:(int)(100L*pending.End/pending.ExpectedEnd); break;
case "snapshot-end":
if (document.Pending == null || document.Pending.Id != message.SnapshotId) return Reject(answer,"obsolete-snapshot");
var snapshot = document.Pending;
if(snapshot.End != snapshot.ExpectedEnd || (snapshot.End > 0 && !snapshot.LastComplete)) return Reject(answer,"incomplete-snapshot");
var boundaries = StructuralParser.Parse(snapshot.Fragments);
if(boundaries.Count>8192 || totalBoundaries-document.Boundaries.Count+boundaries.Count>32768)return Reject(answer,"structure-capacity");
var suggestionCount = snapshot.Analysis?.Count ?? 0;
if(totalSuggestions-(document.Analysis?.Count??0)+suggestionCount>32768)return Reject(answer,"analysis-capacity");
totalSuggestions+=suggestionCount-(document.Analysis?.Count??0);
document.Analysis=snapshot.Analysis;
totalBoundaries += boundaries.Count-document.Boundaries.Count;
document.Boundaries = boundaries;
document.SnapshotId = snapshot.Id;
document.ContentFingerprint = StructuralParser.Fingerprint(snapshot.Fragments);
ClearPending(document); Resolve(document, answer); break;
ClearPending(document); Resolve(document, answer);
if(document.Analysis!=null){answer.Analysis=document.Analysis.Page(0);answer.Status="analysis-complete";answer.Progress=100;}
break;
case "analysis-page":
if(document.SnapshotId!=message.SnapshotId||document.Analysis==null)return Reject(answer,"analysis-unavailable");
if(message.Start<0||message.Start>document.Analysis.Count)return Reject(answer,"invalid-page");
answer.Analysis=document.Analysis.Page(message.Start);answer.Status="analysis-complete";answer.Progress=100;break;
case "snapshot-cancel":
if (document.Pending?.Id == message.SnapshotId) { ClearPending(document); }
break;
@ -133,8 +146,8 @@ public sealed class SessionManager
public Guid? ActiveSession(Guid instance) { lock(gate) return instances.GetValueOrDefault(instance)?.ActiveSession; }
public bool HasSession(Guid instance, Guid session) { lock(gate) return instances.TryGetValue(instance,out var word) && word.Documents.ContainsKey(session); }
private sealed class WordInstance(Guid lease) { public Guid Lease = lease; public long LastSequence; public Guid? ActiveSession; public Dictionary<Guid,DocumentState> Documents = []; }
private sealed class DocumentState(DocumentDescriptor descriptor) { public DocumentDescriptor Descriptor = descriptor; public int Cursor; public Snapshot? Pending; public Guid SnapshotId; public string ContentFingerprint=""; public List<StructuralBoundary> Boundaries = []; }
private sealed class Snapshot(Guid id,int expectedEnd) { public Guid Id = id; public int ExpectedEnd=expectedEnd; public bool LastComplete; public int End; public int NextParagraph=1; public int Characters; public List<ParagraphFragment> Fragments = []; }
private sealed class DocumentState(DocumentDescriptor descriptor) { public DocumentDescriptor Descriptor = descriptor; public int Cursor; public Snapshot? Pending; public Guid SnapshotId; public string ContentFingerprint=""; public List<StructuralBoundary> Boundaries = []; public DocumentAnalysis? Analysis; }
private sealed class Snapshot(Guid id,int expectedEnd,bool analyze) { public DocumentAnalysis? Analysis=analyze?new DocumentAnalysis():null; public Guid Id = id; public int ExpectedEnd=expectedEnd; public bool LastComplete; public int End; public int NextParagraph=1; public int Characters; public List<ParagraphFragment> Fragments = []; }
}
public sealed record StructuralBoundary(int Start, int? ChapterId, int? SceneId, string ChapterTitle, string SceneTitle);
@ -147,9 +160,7 @@ public static class StructuralParser
{
if (fragment.ParagraphIndex == previousParagraph) continue;
previousParagraph = fragment.ParagraphIndex;
int? Id(string prefix) => fragment.MarkerTags.Select(t => t.Replace("_", "-").TrimStart('-')).Where(t => t.StartsWith(prefix,StringComparison.OrdinalIgnoreCase))
.Select(t => int.TryParse(t[prefix.Length..],out var id) && id > 0 ? (int?)id : null).FirstOrDefault(id => id.HasValue);
var chapter = Id("PD-CHAPTER-"); var scene = Id("PD-SCENE-");
var chapter = MarkerId(fragment.MarkerTags,"PD-CHAPTER-"); var scene = MarkerId(fragment.MarkerTags,"PD-SCENE-");
if (fragment.OutlineLevel == 1 || chapter.HasValue)
{
chapterId = chapter; chapterTitle = Title(fragment.Text);
@ -160,6 +171,9 @@ public static class StructuralParser
}
return result;
}
public static int? MarkerId(IEnumerable<string> tags,string prefix) => tags.Select(t=>t.Replace("_","-").TrimStart('-'))
.Where(t=>t.StartsWith(prefix,StringComparison.OrdinalIgnoreCase))
.Select(t=>int.TryParse(t[prefix.Length..],out var id)&&id>0?(int?)id:null).FirstOrDefault(id=>id.HasValue);
private static string Title(string value) {var title=value.Trim();return title.Length>200?title[..200]:title;}
public static string Fingerprint(IReadOnlyList<ParagraphFragment> fragments)
{

View File

@ -97,7 +97,7 @@ public sealed class AgentLink : IDisposable
lock (gate) activePipe = pipe;
await pipe.ConnectAsync(700, stop.Token).ConfigureAwait(false);
if (!verifyServer(pipe)) throw new UnauthorizedAccessException("Unexpected agent owner.");
await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId }, stop.Token).ConfigureAwait(false);
await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability }, stop.Token).ConfigureAwait(false);
mailbox.Clear(); // Reconcile authoritative open documents; never replay stale extraction fragments.
await ExchangeAsync(pipe, Reconcile(), stop.Token).ConfigureAwait(false);
attempt = 0; StateChanged?.Invoke("connected");

View File

@ -0,0 +1,33 @@
using PlotDirector.Companion.Protocol;
namespace PlotDirector.Companion.Client;
// Value-only per-document review state; the Word adapter owns this on its UI thread.
public sealed class AnalysisReview
{
public Guid SessionId { get; private set; }
public long Revision { get; private set; }
public Guid SnapshotId { get; private set; }
public string Status { get; private set; } = "Choose Analyse Document to review structure.";
public bool Running { get; private set; }
public int Progress { get; private set; }
private int expectedOffset;
public void ExpectPage(int offset) {expectedOffset=offset;}
public AnalysisPage? Page { get; private set; }
public void Prepare(Guid session)
{SessionId=session;SnapshotId=Guid.Empty;Page=null;Running=true;Progress=0;Status="Waiting for a quiet moment to read the document…";}
public void Begin(Guid session,long revision,Guid snapshot)
{SessionId=session;Revision=revision;SnapshotId=snapshot;Page=null;expectedOffset=0;Progress=0;Running=true;Status="Reading document in short batches…";}
public void Stop(string reason)
{Running=false;SnapshotId=Guid.Empty;Page=null;Status=reason;}
public bool Accept(Message message)
{
if(SnapshotId==Guid.Empty||message.SessionId!=SessionId||message.Revision!=Revision||message.SnapshotId!=SnapshotId)return false;
if(message.Status=="analysis-complete"&&message.Analysis!=null&&message.Analysis.Offset==expectedOffset)
{Page=message.Analysis;Running=false;Progress=100;Status="Analysis complete — review suggestions below.";return true;}
if(!Running)return false;
if(message.Status is "ok" or "awaiting-structure")
{Progress=Math.Max(Progress,Math.Min(100,message.Progress));Status=Progress==100?"Finishing local analysis…":"Reading and analysing document: "+Progress+"%";return true;}
Stop("Analysis stopped: "+message.Status+". You can try again.");return true;
}
}

View File

@ -5,6 +5,8 @@ namespace PlotDirector.Companion.Protocol;
public static class ProtocolVersion
{
public const int Current = 1;
public const string AnalysisCapability = "structure-review-v1";
public const int AnalysisPageSize = 40;
public const int MaxFrameBytes = 256 * 1024;
public const int MaxDocuments = 32;
public const int MaxParagraphCharacters = 2048;
@ -40,6 +42,9 @@ public sealed class Message
[DataMember] public int? SceneId { get; set; }
[DataMember] public string ChapterTitle { get; set; } = "";
[DataMember] public string SceneTitle { get; set; } = "";
[DataMember] public bool RequestAnalysis { get; set; }
[DataMember] public AnalysisPage? Analysis { get; set; }
[DataMember] public int Progress { get; set; }
}
[DataContract]
@ -75,3 +80,29 @@ public sealed class UiMetric
[DataMember] public string Operation { get; set; } = "";
[DataMember] public double Milliseconds { get; set; }
}
// Optional v1 capability: pages contain suggestions, never authorized server identities.
[DataContract]
public sealed class AnalysisPage
{
[DataMember] public int Offset { get; set; }
[DataMember] public int Total { get; set; }
[DataMember] public int WordCount { get; set; }
[DataMember] public int ParagraphCount { get; set; }
[DataMember] public int ChapterCount { get; set; }
[DataMember] public int SceneCount { get; set; }
[DataMember] public bool Truncated { get; set; }
[DataMember] public string Notice { get; set; } = "";
[DataMember] public StructureSuggestion[] Items { get; set; } = Array.Empty<StructureSuggestion>();
}
[DataContract]
public sealed class StructureSuggestion
{
[DataMember] public int Start { get; set; }
[DataMember] public int Paragraph { get; set; }
[DataMember] public string Kind { get; set; } = "";
[DataMember] public string Title { get; set; } = "";
[DataMember] public string Confidence { get; set; } = "";
[DataMember] public string Reason { get; set; } = "";
}

View File

@ -28,3 +28,12 @@ Resource bounds: eight Word connections, 32 documents per instance, 64 FIFO fram
Disconnect detaches only the connection's current instance lease. Old disconnect callbacks cannot retire a replacement lease. Client reconnect discards stale transport backlog, reconciles still-open documents and requests fresh extraction on the UI scheduler. A pending snapshot frame under backpressure is retained as a value; Word is not reread or blocked. Lifecycle backpressure forces reconciliation rather than silently forgetting a closed/open document.
Protocol v1 exposes **no remote Word mutation operation** and no server integration. Native marker helper code is UI-only and not callable through IPC. Any future command requires explicit target instance/session, document binding, expected revision, bounded ranges, authorization and acknowledgement states. Existing Office.js markers/settings and server business rules remain authoritative for the legacy path until a reviewed migration exists.
## Optional Phase 2 structural review
`structure-review-v1` is additive to v1's required capabilities. New agents advertise it in `ready`; a new add-in must check it before setting `RequestAnalysis` on `snapshot-begin`. Old clients send ordinary snapshots and keep original behavior. The existing endpoint/version is retained; deploy native add-in/client/protocol and agent developer outputs together for qualification.
Analysis uses the same bounded paragraph stream. `snapshot-fragment` acknowledgements include progress percentage. A successful requested `snapshot-end` replies `analysis-complete`, `Progress=100` and the first `AnalysisPage`. `analysis-page` requires exact session/revision/snapshot and uses `Start` as zero-based row offset; it returns at most 40 rows. Candidate rows are suggestions (kind, Word position, paragraph ordinal, bounded title, confidence, evidence), never authorization to import or navigate a server scene. Summary includes approximate words, paragraphs, candidate totals and truncation notice. See Phase 2 report for heuristics and limits.
Analysis is incremental in the agent; no COM object crosses IPC and no analysis operation mutates Word. Candidate counts are bounded to 8,192/document and 32,768 globally. Cancellation uses existing `snapshot-cancel`; late replies are refused by the review's session/revision/snapshot guard. Disconnect invalidates the cache: reanalyse after reconnect. Native Context/Intent/server authentication is still deferred.

View File

@ -1,4 +1,6 @@
# Native Word Companion — Phase 1
# Native Word Companion — Phase 1 foundation and Phase 2 analysis
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.
Publisher: **Nick Beckley**. Architecture: minimal Windows VSTO adapter → per-user modern .NET agent → existing PlotDirector server (native authentication/session-aware server integration deferred).

View File

@ -0,0 +1,67 @@
using System.Diagnostics;
using PlotDirector.Companion.Agent;
using PlotDirector.Companion.Client;
using PlotDirector.Companion.Protocol;
internal static class AnalysisTests
{
public static async Task Run(Action<bool,string> check)
{
ParagraphFragment Fragment(string text,int index=1,int start=0,int outline=10,string[]? tags=null) => new(){Text=text,Start=start,End=start+text.Length,ParagraphIndex=index,OutlineLevel=outline,MarkerTags=tags??[],CompletesParagraph=true};
var blank=new DocumentAnalysis();blank.Add(Fragment("\r"));
check(blank.Page(0).WordCount==0&&blank.Page(0).Total==0&&blank.Page(0).Notice.Contains("No manuscript"),"blank document has an explicit empty analysis");
var ordinary=new DocumentAnalysis();var position=0;var index=0;
foreach(var text in new[]{"Chapter One\r","Ordinary manuscript prose.\r","* * *\r","Another scene.\r","Chapter 2: Return\r","More prose.\r"})
{ordinary.Add(Fragment(text,++index,position));position+=text.Length;}
check(ordinary.Page(0).ChapterCount==2&&ordinary.Page(0).SceneCount==1,"plain chapter labels and separators become review suggestions");
var ambiguous=new DocumentAnalysis();
ambiguous.Add(Fragment("12\r"));ambiguous.Add(Fragment("Chapter One was what she called it.\r",2,3));
ambiguous.Add(Fragment("A scene\r",3,40,2));
check(ambiguous.Page(0).Items[0].Confidence=="Uncertain"&&ambiguous.Page(0).Items[1].Confidence=="Possible"&&ambiguous.Page(0).Items[2].Reason.Contains("review"),"ambiguous text and heading levels explain uncertainty instead of approving import");
var marked=new DocumentAnalysis();marked.Add(Fragment("Tagged chapter\r",1,0,10,["PD_CHAPTER_42"]));marked.Add(Fragment("Tagged scene\r",2,15,10,["PD_SCENE_77"]));
check(marked.Page(0).Items.All(i=>i.Confidence=="Strong")&&marked.Page(0).ChapterCount==1&&marked.Page(0).SceneCount==1,"analysis reuses existing PlotDirector marker interpretation");
var fragmented=new DocumentAnalysis();fragmented.Add(new(){Text="hel",Start=0,End=3,ParagraphIndex=1,OutlineLevel=10,CompletesParagraph=false});
fragmented.Add(new(){Text="lo world\r",Start=3,End=12,ParagraphIndex=1,OutlineLevel=10,CompletesParagraph=true});
check(fragmented.Page(0).WordCount==2&&fragmented.Page(0).ParagraphCount==1,"fragment splits do not inflate word or paragraph counts");
var large=new DocumentAnalysis();var clock=Stopwatch.StartNew();
for(var i=0;i<25000;i++)large.Add(Fragment("one two three four five six seven eight nine ten\r",i+1,i*48,i%1000==0?1:10));
check(large.Page(0).WordCount==250000&&large.Page(0).ParagraphCount==25000&&large.Page(0).ChapterCount==25,"250000-word many-paragraph manuscript analysed incrementally");
Console.WriteLine($"Agent synthetic 250000-word analysis: {clock.ElapsedMilliseconds}ms (not Word extraction/UI timing).");
var dense=new DocumentAnalysis();for(var i=0;i<9000;i++)dense.Add(Fragment("Heading\r",i+1,i*8,1));
check(dense.Page(0).Truncated&&dense.Page(0).Total==8192,"review suggestion storage is bounded with explicit truncation");
var page=dense.Page(40);check(page.Offset==40&&page.Items.Length==ProtocolVersion.AnalysisPageSize,"analysis results are paginated");
using(var stream=new MemoryStream())
{await FrameCodec.WriteAsync(stream,new(){Analysis=page},CancellationToken.None);check(stream.Length<ProtocolVersion.MaxFrameBytes,"review page fits bounded IPC frame");stream.Position=0;check((await FrameCodec.ReadAsync(stream,CancellationToken.None)).Analysis?.Total==8192,"analysis result contract round-trips over framing");}
var sessions=new SessionManager();var instance=Guid.NewGuid();var lease=Guid.NewGuid();sessions.Attach(instance,lease);long sequence=0;
Message Send(Message m){m.WordInstanceId=instance;m.Sequence=++sequence;return sessions.Apply(lease,m);}
var docs=Enumerable.Range(0,3).Select(_=>new DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Revision=1}).ToArray();
Send(new(){Kind="reconcile",Documents=docs});
var snapshots=new List<Guid>();
foreach(var doc in docs)
{
var snapshot=Guid.NewGuid();snapshots.Add(snapshot);var fragment=Fragment("Chapter One\r");
Send(new(){Kind="snapshot-begin",SessionId=doc.SessionId,Revision=1,SnapshotId=snapshot,End=fragment.End,RequestAnalysis=true});
var progress=Send(new(){Kind="snapshot-fragment",SessionId=doc.SessionId,Revision=1,SnapshotId=snapshot,Fragment=fragment});
var result=Send(new(){Kind="snapshot-end",SessionId=doc.SessionId,Revision=1,SnapshotId=snapshot});
check(progress.Progress==100&&result.Status=="analysis-complete"&&result.Analysis?.ChapterCount==1,"document-specific analysis returns structured results and progress");
}
check(Send(new(){Kind="analysis-page",SessionId=docs[0].SessionId,Revision=1,SnapshotId=snapshots[1]}).Status=="analysis-unavailable","another document's snapshot cannot retrieve results");
var cancelled=Guid.NewGuid();Send(new(){Kind="snapshot-begin",SessionId=docs[0].SessionId,Revision=1,SnapshotId=cancelled,End=20,RequestAnalysis=true});
var partial=Send(new(){Kind="snapshot-fragment",SessionId=docs[0].SessionId,Revision=1,SnapshotId=cancelled,Fragment=Fragment("first\r")});
check(partial.Progress==30,"analysis acknowledges bounded partial progress before cancellation");
Send(new(){Kind="snapshot-cancel",SessionId=docs[0].SessionId,Revision=1,SnapshotId=cancelled});
check(Send(new(){Kind="snapshot-end",SessionId=docs[0].SessionId,Revision=1,SnapshotId=cancelled}).Status=="obsolete-snapshot","cancelled analysis cannot complete");
var review=new AnalysisReview();review.Prepare(docs[0].SessionId);
check(review.Running&&review.SnapshotId==Guid.Empty,"analysis waiting for Word scheduler is cancellable");review.Stop("Cancelled before extraction");check(!review.Running,"pending analysis cancellation does not require extraction");review.Begin(docs[0].SessionId,1,snapshots[0]);
check(!review.Accept(new(){SessionId=docs[1].SessionId,Revision=1,SnapshotId=snapshots[0],Status="analysis-complete",Analysis=page}),"review rejects results from a different document");
review.Stop("Cancelled");check(!review.Accept(new(){SessionId=docs[0].SessionId,Revision=1,SnapshotId=snapshots[0],Status="analysis-complete",Analysis=page}),"late results cannot replace cancellation");
review.Begin(docs[0].SessionId,2,Guid.NewGuid());
check(!review.Accept(new(){SessionId=docs[0].SessionId,Revision=1,SnapshotId=snapshots[0],Status="analysis-complete",Analysis=page}),"new analysis rejects obsolete revision and snapshot");
var complete=new Message{SessionId=review.SessionId,Revision=review.Revision,SnapshotId=review.SnapshotId,Status="analysis-complete",Analysis=ordinary.Page(0)};
check(review.Accept(complete)&&!review.Running&&review.Page?.ChapterCount==2,"review completes only matching analysis");
check(!review.Accept(new(){SessionId=review.SessionId,Revision=review.Revision,SnapshotId=review.SnapshotId,Status="ok"})&&review.Status.Contains("complete"),"selection replies cannot regress completed review progress");
review.ExpectPage(40);check(!review.Accept(complete),"late page zero cannot replace requested later page");
sessions.Detach(instance,lease);sessions.Attach(instance,Guid.NewGuid());
check(sessions.SessionCount==0,"agent restart releases document analysis state");
}
}

View File

@ -110,22 +110,34 @@ using(var compatible=new NamedPipeClientStream(".",pipeName,PipeDirection.InOut,
{
await compatible.ConnectAsync(3000);var hello=new Message{Kind="hello",WordInstanceId=Guid.NewGuid(),Capabilities=ProtocolVersion.Capabilities+",future-optional"};
await FrameCodec.WriteAsync(compatible,hello,CancellationToken.None);
Check((await FrameCodec.ReadAsync(compatible,CancellationToken.None)).Status=="ready","same-version optional capabilities remain compatible");
var ready=await FrameCodec.ReadAsync(compatible,CancellationToken.None);
Check(ready.Status=="ready","same-version optional capabilities remain compatible");
Check(ready.Capabilities.Split(',').Contains(ProtocolVersion.AnalysisCapability),"agent advertises optional structural review capability");
}
var connected=0;var replies=0;var offline=0;
var analysisReplies=new System.Collections.Concurrent.ConcurrentQueue<Message>();
using(var link=new AgentLink(pipeName,Guid.NewGuid(),_=>true)) // Windows SID peer validation is exercised by the desktop procedure, not faked as proved here.
{
link.StateChanged+=state=>{if(state=="connected")Interlocked.Increment(ref connected);else if(state=="offline")Interlocked.Increment(ref offline);};
link.Received+=_=>Interlocked.Increment(ref replies);
link.Received+=message=>{Interlocked.Increment(ref replies);if(message.Analysis!=null)analysisReplies.Enqueue(message);};
foreach(var descriptor in descriptors)link.Register(descriptor);
link.Start();await Until(()=>Volatile.Read(ref connected)==1&&serverSessions.SessionCount==3,"real named-pipe handshake reconciles three documents");
link.TryPost(new Message{Kind="active",SessionId=descriptors[1].SessionId,Revision=1});
link.TryPost(new Message{Kind="selection",SessionId=descriptors[1].SessionId,Revision=1,Start=30,End=30});
await Until(()=>Volatile.Read(ref replies)>=4,"agent receives actual asynchronous positional/lifecycle traffic");
var analysisSnapshot=Guid.NewGuid();
link.TryPost(new Message{Kind="snapshot-begin",SessionId=descriptors[0].SessionId,Revision=1,SnapshotId=analysisSnapshot,End=12,RequestAnalysis=true});
link.TryPost(new Message{Kind="snapshot-fragment",SessionId=descriptors[0].SessionId,Revision=1,SnapshotId=analysisSnapshot,Fragment=new(){ParagraphIndex=1,Start=0,End=12,Text="Chapter One\r",OutlineLevel=10,CompletesParagraph=true}});
link.TryPost(new Message{Kind="snapshot-end",SessionId=descriptors[0].SessionId,Revision=1,SnapshotId=analysisSnapshot});
await Until(()=>analysisReplies.Any(m=>m.SnapshotId==analysisSnapshot&&m.Analysis?.ChapterCount==1),"real pipe returns document analysis results");
stopHost.Cancel();await host;await Until(()=>serverSessions.SessionCount==0,"agent shutdown retires peer sessions");
await Until(()=>Volatile.Read(ref offline)>0,"idle keepalive detects agent loss without a Word event");
stopHost.Dispose();stopHost=new CancellationTokenSource();host=StartHost(stopHost.Token);
await Until(()=>Volatile.Read(ref connected)>=2&&serverSessions.SessionCount==3,"agent restart reconnects and reconciles without UI waits");
var recoveredSnapshot=Guid.NewGuid();
link.TryPost(new Message{Kind="snapshot-begin",SessionId=descriptors[1].SessionId,Revision=1,SnapshotId=recoveredSnapshot,End=0,RequestAnalysis=true});
link.TryPost(new Message{Kind="snapshot-end",SessionId=descriptors[1].SessionId,Revision=1,SnapshotId=recoveredSnapshot});
await Until(()=>analysisReplies.Any(m=>m.SnapshotId==recoveredSnapshot&&m.Analysis?.WordCount==0),"analysis can be repeated after actual pipe host restart");
link.Retire(descriptors[2].SessionId);await Until(()=>serverSessions.SessionCount==2,"real pipe document close is isolated");
link.Dispose();await link.Completion.WaitAsync(TimeSpan.FromSeconds(5));
Check(true,"link shutdown cancels background worker promptly");
@ -148,4 +160,5 @@ using(var stalledClient=new AgentLink(stalledName,Guid.NewGuid(),_=>true))
await Until(()=>timedOut,"unresponsive agent handshake times out off producer thread");
stalledClient.Dispose();await stalledClient.Completion.WaitAsync(TimeSpan.FromSeconds(5));
}
await AnalysisTests.Run(Check);
Console.WriteLine($"Native foundation: {passed} checks passed. Linux named-pipe API uses Unix domain sockets; Windows ACL/COM/Word responsiveness NOT verified.");

View File

@ -0,0 +1,40 @@
using System;
using System.Drawing;
using System.Windows.Forms;
using PlotDirector.Companion.Client;
using PlotDirector.Companion.Protocol;
namespace PlotDirector.WordAddIn
{
// Small modeless review window. No Word references and no network activity.
public sealed class AnalysisWindow : Form
{
private readonly Label status=new Label{Dock=DockStyle.Top,Height=76,Padding=new Padding(8)};
private readonly ProgressBar progress=new ProgressBar{Dock=DockStyle.Top,Height=16};
private readonly ListView rows=new ListView{Dock=DockStyle.Fill,View=View.Details,FullRowSelect=true};
private readonly Button cancel=new Button{Text="Cancel",AutoSize=true};
private readonly Button next=new Button{Text="Next results",AutoSize=true};
private readonly Button previous=new Button{Text="Previous results",AutoSize=true};
public AnalysisWindow(Action analyse,Action stop,Action<int> page)
{
Text="PlotDirector — Document structure review";Width=880;Height=500;ShowInTaskbar=false;
rows.Columns.Add("Type",70);rows.Columns.Add("Paragraph",75);rows.Columns.Add("Title / separator",240);rows.Columns.Add("Evidence",320);
var buttons=new FlowLayoutPanel{Dock=DockStyle.Bottom,Height=42,Padding=new Padding(5)};
var repeat=new Button{Text="Analyse again",AutoSize=true};repeat.Click+=(_,__)=>analyse();
cancel.Click+=(_,__)=>stop();next.Click+=(_,__)=>page(1);previous.Click+=(_,__)=>page(-1);
buttons.Controls.AddRange(new Control[]{repeat,cancel,previous,next});
Controls.Add(rows);Controls.Add(progress);Controls.Add(status);Controls.Add(buttons);
}
public void Render(AnalysisReview review,string connection,Guid session)
{
var page=review?.Page;
status.Text="Document session "+session.ToString("N").Substring(0,8)+" · Agent: "+connection+"\n"+(review?.Status??"No active document.");
if(page!=null)status.Text+="\n"+page.WordCount.ToString("N0")+" approximate words · "+page.ParagraphCount.ToString("N0")+" paragraphs · "+page.ChapterCount+" chapter / "+page.SceneCount+" scene suggestions. "+(page.Truncated?"Result limit reached. ":"")+page.Notice;
progress.Value=review?.Progress??0;cancel.Enabled=review?.Running==true;
previous.Enabled=page!=null&&page.Offset>0;next.Enabled=page!=null&&page.Offset+page.Items.Length<page.Total;
rows.BeginUpdate();rows.Items.Clear();
if(page!=null)foreach(var item in page.Items)rows.Items.Add(new ListViewItem(new[]{item.Kind,item.Paragraph.ToString(),item.Title,item.Confidence+": "+item.Reason}));
rows.EndUpdate();
}
}
}

View File

@ -19,12 +19,14 @@ namespace PlotDirector.WordAddIn
public void Invalidate() { try { ui?.Invalidate(); } catch(COMException) { } }
public string GetStatus(Office.IRibbonControl _) => "Agent: " + (getAdapter()?.ConnectionState ?? "Unavailable") + " · Server: unavailable";
public bool CanSynchronize(Office.IRibbonControl _) => getAdapter()?.HasActiveDocument == true;
public void Connect(Office.IRibbonControl _) { getAdapter()?.Reconnect(); MessageBox.Show("The local agent reconnects in the background. Native server sign-in is not implemented in Phase 1; no browser credentials are reused.","PlotDirector — Nick Beckley"); }
public void Connect(Office.IRibbonControl _) { getAdapter()?.Reconnect(); MessageBox.Show("The local agent reconnects in the background. Native server sign-in is not available yet; no browser credentials are reused.","PlotDirector — Nick Beckley"); }
public void Analyse(Office.IRibbonControl _) { getAdapter()?.AnalyseDocument(); }
public void Cancel(Office.IRibbonControl _) { getAdapter()?.CancelAnalysis(); }
public void Synchronize(Office.IRibbonControl _) { getAdapter()?.RequestSnapshot(); }
public void Settings(Office.IRibbonControl _)
{
if (getAdapter() == null) return;
var choice = MessageBox.Show("Phase 1 uses Manual local snapshot refresh. Automatic / On Save prose synchronization is not available.\n\nPersist a native identity in this document's metadata? This will mark the document modified; it will not save or change prose. Existing Office.js bindings are untouched.","PlotDirector Settings",MessageBoxButtons.YesNo);
var choice = MessageBox.Show("Local analysis and Manual structural refresh are available. Automatic / On Save prose synchronization is not available.\n\nPersist a native identity in this document's metadata? This will mark the document modified; it will not save or change prose. Existing Office.js bindings are untouched.","PlotDirector Settings",MessageBoxButtons.YesNo);
if (choice == DialogResult.Yes) getAdapter().PersistNativeIdentity();
}
public void Diagnostics(Office.IRibbonControl _) => MessageBox.Show(getAdapter()?.Diagnostics ?? "Companion did not initialize. Word remains usable. Check the Windows validation prerequisites.","PlotDirector Diagnostics — Nick Beckley");

View File

@ -22,7 +22,7 @@
<ProjectReference Include="..\Protocol\PlotDirector.Companion.Protocol.csproj"><Name>PlotDirector.Companion.Protocol</Name></ProjectReference>
<ProjectReference Include="..\Client\PlotDirector.Companion.Client.csproj"><Name>PlotDirector.Companion.Client</Name></ProjectReference>
<Compile Include="ThisAddIn.cs" /><Compile Include="ThisAddIn.Designer.cs"><DependentUpon>ThisAddIn.cs</DependentUpon></Compile>
<Compile Include="WordAdapter.cs" /><Compile Include="NativeRibbon.cs" /><Compile Include="AgentProcess.cs" /><Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="WordAdapter.cs" /><Compile Include="AnalysisWindow.cs" /><Compile Include="NativeRibbon.cs" /><Compile Include="AgentProcess.cs" /><Compile Include="Properties\AssemblyInfo.cs" />
<None Include="ThisAddIn.Designer.xml"><DependentUpon>ThisAddIn.cs</DependentUpon></None>
<EmbeddedResource Include="Ribbon.xml" />
</ItemGroup>

View File

@ -1,9 +1,11 @@
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="OnLoad">
<ribbon><tabs><tab id="PlotDirectorTab" label="PlotDirector">
<group id="PlotDirectorConnection" label="Word Companion · Phase 1">
<group id="PlotDirectorConnection" label="Word Companion">
<labelControl id="PlotDirectorStatus" getLabel="GetStatus" />
<button id="PlotDirectorConnect" label="Connect / Sign In" imageMso="ConnectToExternalData" onAction="Connect" screentip="Reconnect local agent" supertip="Native server sign-in is not yet available. Existing Office.js sign-in remains unchanged." />
<button id="PlotDirectorSync" label="Synchronise Now" imageMso="RefreshAll" onAction="Synchronize" getEnabled="CanSynchronize" supertip="Refresh local structural snapshot only. Server/prose sync is unavailable in Phase 1." />
<button id="PlotDirectorAnalyse" label="Analyse Document" imageMso="ReviewShowMarkup" onAction="Analyse" getEnabled="CanSynchronize" supertip="Review local chapter and scene suggestions. No import or manuscript changes." />
<button id="PlotDirectorCancelAnalysis" label="Cancel Analysis" imageMso="CancelRequest" onAction="Cancel" getEnabled="CanSynchronize" />
<button id="PlotDirectorSync" label="Synchronise Now" imageMso="RefreshAll" onAction="Synchronize" getEnabled="CanSynchronize" supertip="Refresh local structural snapshot only. Server/prose sync is not yet available." />
<button id="PlotDirectorSettings" label="Settings" imageMso="PropertySheet" onAction="Settings" />
<button id="PlotDirectorDiagnostics" label="Diagnostics" imageMso="Info" onAction="Diagnostics" />
</group>

View File

@ -48,10 +48,16 @@ namespace PlotDirector.WordAddIn
private string lastWordError;
private int documentCollectionGeneration;
private double lastBatchMs;
private AnalysisWindow analysisWindow;
private bool analysisSupported;
private readonly Stopwatch reviewClock=Stopwatch.StartNew();
private bool reviewDirty;
private readonly object reviewGate=new object();
private readonly Dictionary<Guid,Message> reviewReplies=new Dictionary<Guid,Message>();
private string lastResult = "Waiting for local structural snapshot";
public string ConnectionState { get; private set; } = "Connecting";
public bool HasActiveDocument => active != null;
public string Diagnostics => "PlotDirector by Nick Beckley — Phase 1\nAgent: " + ConnectionState
public string Diagnostics => "PlotDirector by Nick Beckley — Phase 2\nAgent: " + ConnectionState
+ "\nServer authentication / prose sync: unavailable\nOpen sessions: " + documents.Count
+ "\nIPC queued: " + link.QueueDepth + "\nWord work queued: " + scheduler.Depth
+ "\nLast UI batch ms: " + lastBatchMs.ToString("F2") + "\nMax recorded COM call ms: " + (operationTimes.Count == 0 ? 0 : operationTimes.Max()).ToString("F2")
@ -66,6 +72,12 @@ namespace PlotDirector.WordAddIn
link = new AgentLink(AgentProcess.PipeName(), Guid.NewGuid(), AgentProcess.VerifyOwner, AgentProcess.Start);
link.StateChanged += state => PostToUi(() => {
ConnectionState = state;
if(state!="connected")
{
analysisSupported=false;
foreach(var doc in documents.Values){scheduler.Cancel("analyse:"+doc.Session);if(doc.Review.Running||doc.Review.SnapshotId!=Guid.Empty)doc.Review.Stop("Agent disconnected. Reconnect and analyse again.");}
}
reviewDirty=true;
if (state == "connected")
{
foreach (var doc in documents.Values) { CancelExtraction(doc); doc.NeedsSnapshot = true; }
@ -74,13 +86,25 @@ namespace PlotDirector.WordAddIn
invalidateRibbon();
});
link.Received += message => {
if(message.Status=="ready")PostToUi(()=>{analysisSupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.AnalysisCapability);});
// Bound/coalesce progress independently of the Word message pump.
// Never accumulate one BeginInvoke callback per manuscript fragment.
if(message.SessionId!=Guid.Empty&&message.SnapshotId!=Guid.Empty)
lock(reviewGate)
{
if(reviewReplies.TryGetValue(message.SessionId,out var prior))
{
if(message.Revision>=prior.Revision&&(prior.Analysis==null||message.Analysis!=null||message.Revision>prior.Revision))reviewReplies[message.SessionId]=message;
}
else if(reviewReplies.Count<ProtocolVersion.MaxDocuments)reviewReplies.Add(message.SessionId,message);
}
var description = message.Status + (string.IsNullOrEmpty(message.ChapterTitle) ? "" : " · " + message.ChapterTitle)
+ (string.IsNullOrEmpty(message.SceneTitle) ? "" : " / " + message.SceneTitle);
if (message.Status == "awaiting-structure" && message.SnapshotId == Guid.Empty) return;
if (message.Status != "ok" || !string.IsNullOrEmpty(message.ChapterTitle)) PostToUi(() => {
if (message.Status == "awaiting-structure")
description = "Local structure refreshed. No chapter or scene found at the cursor.";
if(message.Status!="ok"&&message.Status!="ready"&&message.Status!="awaiting-structure")
if(message.Status!="ok"&&message.Status!="ready"&&message.Status!="awaiting-structure"&&message.Status!="analysis-complete")
{
var failed=documents.Values.FirstOrDefault(d=>d.Session==message.SessionId&&d.Revision==message.Revision);
if(failed!=null){CancelExtraction(failed);failed.NeedsSnapshot=false;}
@ -92,6 +116,9 @@ namespace PlotDirector.WordAddIn
scheduler.Failed += error => {
busyFailures++;
lastWordError = error.GetType().Name + " 0x" + error.HResult.ToString("X8");
foreach(var doc in documents.Values)if(doc.Review.Running)
{CancelExtraction(doc);doc.NeedsSnapshot=false;doc.Review.Stop("Word could not finish this operation. Try analysis again; see Diagnostics.");}
reviewDirty=true;
scheduler.PrioritizeAuthor(TimeSpan.FromSeconds(1));
};
events = (Word.ApplicationEvents4_Event)application;
@ -177,10 +204,12 @@ namespace PlotDirector.WordAddIn
var documentEnd = DocumentEnd(document); var saved = Com(() => document.Saved);
if (documentEnd != state.End || (state.WasSaved && !saved))
{
state.Review.Stop("Document changed. Analyse again to refresh suggestions.");reviewDirty=true;
state.End = documentEnd; state.Revision++; state.NeedsSnapshot = true;
CancelExtraction(state); link.Register(Descriptor(state));
}
state.WasSaved = saved;
if(active!=state)reviewDirty=true;
active = state;
link.TryPost(new Message {Kind="active",SessionId=state.Session,Revision=state.Revision});
link.TryPost(new Message {Kind="selection",SessionId=state.Session,Revision=state.Revision,Start=start,End=end,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth});
@ -199,18 +228,62 @@ namespace PlotDirector.WordAddIn
SessionId=doc.Session,ManuscriptId=doc.Identity,ProjectId=doc.ProjectId,BookId=doc.BookId,
Revision=doc.Revision,IdentityPersisted=doc.IdentityPersisted,AssociationVerified=false
};
public void AnalyseDocument()
{
if(active==null)return;
if(analysisWindow==null||analysisWindow.IsDisposed)
analysisWindow=new AnalysisWindow(()=>StartAnalysis(true),CancelAnalysis,RequestAnalysisPage);
analysisWindow.Show();analysisWindow.BringToFront();
if(active.Review.Page==null&&!active.Review.Running)StartAnalysis(false);
RenderReview();
}
private void StartAnalysis(bool refresh)
{
var doc=active;if(doc==null)return;
if(ConnectionState!="connected"||!analysisSupported)
{doc.Review.Stop("Connect an updated local agent to analyse this document.");RenderReview();return;}
if(!refresh&&doc.Review.Page!=null){RenderReview();return;}
CancelExtraction(doc);doc.Review.Prepare(doc.Session);reviewDirty=true;
// Refresh the descriptor on the Word scheduler, never from a background callback.
if(!scheduler.Post("analyse:"+doc.Session,()=>{
if(active!=doc||closing.Contains(doc.Document)){doc.Review.Stop("Document switched or closing. Analyse again when ready.");reviewDirty=true;return;}
doc.End=DocumentEnd(doc.Document);doc.Revision++;doc.NeedsSnapshot=true;
link.Register(Descriptor(doc));ScheduleSnapshot(doc,true);RenderReview();
})){doc.Review.Stop("Word queue busy. Try analysis again.");RenderReview();}
}
public void CancelAnalysis()
{
var doc=active;if(doc==null)return;
scheduler.Cancel("analyse:"+doc.Session);CancelExtraction(doc);doc.NeedsSnapshot=false;
doc.Review.Stop("Analysis cancelled. Nothing was imported or changed.");RenderReview();
}
private void RequestAnalysisPage(int direction)
{
var doc=active;var page=doc?.Review.Page;if(page==null)return;
var offset=page.Offset+direction*ProtocolVersion.AnalysisPageSize;
if(offset<0||offset>=page.Total)return;
doc.Review.ExpectPage(offset);
if(!link.TryPost(new Message{Kind="analysis-page",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.Review.SnapshotId,Start=offset}))
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);reviewDirty=false;}
public void RequestSnapshot()
{
if (active == null) return;
scheduler.Cancel("analyse:"+active.Session);
active.Review.Stop("Structure refreshed. Analyse again to review updated suggestions.");reviewDirty=true;
lastResult = ConnectionState == "connected" ? "Refreshing local structure…" : "Waiting for the local agent";
active.Revision++; active.NeedsSnapshot = true; CancelExtraction(active);
link.Register(Descriptor(active)); ScheduleSnapshot(active);
}
private void ScheduleSnapshot(LocalDocument doc)
private void ScheduleSnapshot(LocalDocument doc,bool analyse=false)
{
if (doc.Extraction != null || ConnectionState != "connected") return;
doc.Extraction = new Extraction { Snapshot = Guid.NewGuid(), Revision=doc.Revision };
if (!scheduler.Post("extract:"+doc.Session,() => ExtractBatch(doc))) doc.Extraction = null;
doc.Extraction = new Extraction { Snapshot = Guid.NewGuid(), Revision=doc.Revision,Analyse=analyse };
if(analyse)doc.Review.Begin(doc.Session,doc.Revision,doc.Extraction.Snapshot);
if (!scheduler.Post("extract:"+doc.Session,() => ExtractBatch(doc)))
{doc.Extraction=null;doc.Review.Stop("Word queue busy. Try analysis again.");}
}
private void ExtractBatch(LocalDocument doc)
{
@ -222,7 +295,7 @@ namespace PlotDirector.WordAddIn
{
if(!extraction.Begun)
{
if(!link.TryPost(new Message{Kind="snapshot-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,End=doc.End}))return;
if(!link.TryPost(new Message{Kind="snapshot-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,End=doc.End,RequestAnalysis=extraction.Analyse}))return;
extraction.Begun=true;
}
// At most four <=2048-character fragments and a cooperative ~20ms budget.
@ -246,11 +319,11 @@ namespace PlotDirector.WordAddIn
}
}
catch(COMException)
{ busyFailures++;CancelExtraction(doc);doc.NeedsSnapshot=true;scheduler.PrioritizeAuthor(TimeSpan.FromSeconds(1)); }
{ doc.Review.Stop("Word was busy. Try analysis again after editing stops.");reviewDirty=true;busyFailures++;CancelExtraction(doc);doc.NeedsSnapshot=true;scheduler.PrioritizeAuthor(TimeSpan.FromSeconds(1)); }
catch(InvalidOperationException error)
{ CancelExtraction(doc);doc.NeedsSnapshot=false;lastResult="Snapshot stopped: " + error.Message; }
{ CancelExtraction(doc);doc.NeedsSnapshot=false;lastResult="Snapshot stopped: " + error.Message;doc.Review.Stop(lastResult);reviewDirty=true; }
catch(NullReferenceException)
{ CancelExtraction(doc);doc.NeedsSnapshot=false;lastResult="Snapshot stopped while reading Word.";throw; }
{ CancelExtraction(doc);doc.NeedsSnapshot=false;lastResult="Snapshot stopped while reading Word.";doc.Review.Stop(lastResult);reviewDirty=true;throw; }
finally
{
lastBatchMs=watch.Elapsed.TotalMilliseconds;Metric("snapshot-batch",lastBatchMs);
@ -346,13 +419,13 @@ namespace PlotDirector.WordAddIn
{
// Never set Cancel, wait for IPC, read prose or force a document save.
scheduler.PrioritizeAuthor(TimeSpan.FromMilliseconds(500));
if(documents.TryGetValue(document,out var state)){CancelExtraction(state);state.NeedsSnapshot=true;}
if(documents.TryGetValue(document,out var state)){scheduler.Cancel("analyse:"+state.Session);CancelExtraction(state);state.NeedsSnapshot=true;state.Review.Stop("Document saved or saving. Analyse again to refresh suggestions.");reviewDirty=true;}
}
private void BeforeClose(Word.Document document,ref bool cancel)
{
scheduler.PrioritizeAuthor(TimeSpan.FromMilliseconds(250));
if(!documents.TryGetValue(document,out var state))return;
CancelExtraction(state);
scheduler.Cancel("analyse:"+state.Session);CancelExtraction(state);state.Review.Stop("Document closing. Analyse again if close is cancelled.");reviewDirty=true;
documentCollectionGeneration++;
closing.Add(document);
scheduler.Post("retire",ReconcileClosedDocuments);
@ -376,7 +449,7 @@ namespace PlotDirector.WordAddIn
foreach(var doc in closing.ToArray())
{
if(!present.Contains(doc)&&documents.TryGetValue(doc,out var state))
{CancelExtraction(state);documents.Remove(doc);link.Retire(state.Session);if(active==state)active=null;}
{CancelExtraction(state);documents.Remove(doc);link.Retire(state.Session);if(active==state)active=null;reviewDirty=true;}
closing.Remove(doc);
}
}
@ -386,6 +459,11 @@ namespace PlotDirector.WordAddIn
{
Metric("ui-tick-delay",Math.Max(0,tickClock.Elapsed.TotalMilliseconds-25));tickClock.Restart();
if(!disposed)scheduler.Pump();
Message[] responses;
lock(reviewGate){responses=reviewReplies.Values.Take(4).ToArray();foreach(var response in responses)reviewReplies.Remove(response.SessionId);}
foreach(var response in responses)
{var doc=documents.Values.FirstOrDefault(d=>d.Session==response.SessionId);if(doc!=null&&doc.Review.Accept(response))reviewDirty=true;}
if(reviewDirty&&reviewClock.ElapsedMilliseconds>=250){reviewClock.Restart();RenderReview();}
if(!disposed&&active!=null&&ConnectionState=="connected"&&metricClock.ElapsedMilliseconds>=1000)
{
metricClock.Restart();
@ -461,15 +539,16 @@ namespace PlotDirector.WordAddIn
if(disposed)return;disposed=true;timer.Stop();timer.Dispose();scheduler.Clear();
events.DocumentOpen-=Open;events.NewDocument-=Open;events.DocumentChange-=ScheduleSelection;events.WindowActivate-=Activate;
events.WindowSelectionChange-=SelectionChanged;events.DocumentBeforeClose-=BeforeClose;events.DocumentBeforeSave-=BeforeSave;
link.Dispose();documents.Clear();pendingOpen.Clear();closing.Clear();dispatch.Dispose();
analysisWindow?.Dispose();link.Dispose();documents.Clear();pendingOpen.Clear();closing.Clear();dispatch.Dispose();
}
private sealed class LocalDocument
{
public readonly Word.Document Document;public readonly Guid Session=Guid.NewGuid();public Guid Identity;public bool IdentityPersisted;
public readonly AnalysisReview Review=new AnalysisReview();
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;}
}
private sealed class Extraction
{public Guid Snapshot;public long Revision;public int Position,ParagraphEnd,ParagraphIndex;public int OutlineLevel;public bool Begun;public Message Pending;}
{public Guid Snapshot;public long Revision;public int Position,ParagraphEnd,ParagraphIndex;public int OutlineLevel;public bool Begun,Analyse;public Message Pending;}
}
}

View File

@ -0,0 +1,26 @@
# Phase 2 analysis: Windows Codex handover
Use the existing shared branch `codex/word-companion-native-phase1-20261104`. Fetch and fast-forward only with a clean worktree; stop on divergence. Baseline Windows fixes at `726a3d5` (author-tested package `1.0.0.3`) must remain ancestors. Do not create a branch or deploy server changes.
Read `Docs/WordCompanion/2026-11-04-phase2-document-analysis.md` and the existing Windows validation README. Build the managed solution and run the native harness, then build the VSTO host with the existing Office-equipped MSBuild/developer-signing procedure. The Linux managed build excludes VSTO. Do not treat the Linux syntax check as a Windows build. Qualify a new controlled developer build with the author-approved installation procedure; do not overwrite the tested installation without authorization. Record the new package/developer build identifier, exact Git SHA, Office/toolchain details and signing method. No version `1.0.0.4` or other package number is asserted by Atlas.
The old agent may already be running. For an authorized developer trial, stop the test agent and launch the newly built adjacent agent; verify it advertises `structure-review-v1`. A new add-in talking to an old agent should show an updated-agent-required message, not pretend analysis succeeded. No native website sign-in or authenticated Context/Intent flow is part of this phase.
## Functional acceptance
1. Blank unsaved Word document: Analyse Document opens a small modeless review, reaches an explicit no-words result, reports no fabricated boundaries. Confirm the Phase 1 missing-custom-property registration fix still works.
2. Prepare a synthetic manuscript with Heading 1 chapters, Heading 2 scenes, unformatted “Chapter One” / “Chapter 2”, ordinary prose and `***` / `#` separators. Analyse; confirm paragraph positions, counts and evidence/confidence. Do not expect local IDs to authorize server operations. Test native `PD_CHAPTER_` / `PD_SCENE_` fixtures as well.
3. Ambiguity: standalone numeric paragraphs, a prose sentence beginning “Chapter One…”, decorative separators and Heading 2 subdivisions. Results must remain review suggestions. Ordinary prose must not be rewritten. Check file content/control/bookmark counts before/after (account for normal Word save behavior separately).
4. Produce more than 40 candidates; verify previous/next paging, first/last page and rapid navigation. Reopen the review: reuse valid results with no new extraction. Analyse again explicitly refreshes. Confirm current results cannot be replaced by an obsolete analysis/page.
5. Cancel while waiting for typing to pause, while extracting and near completion. Late replies must not resurrect cancelled results. Repeat must work. Closing the review window alone may leave work running; ribbon Cancel Analysis must still work.
6. Open Discovery, Reckoning and Redemption as separate documents; analyse each, switch rapidly and check the session suffix/results track the active document. Test in one and multiple Word processes. Close an analyzed document, cancel a close, save while analysis is running, close all Word documents and reopen one. No abandoned/foreign results should appear. Save/close must not wait for synchronization.
7. Terminate the agent during analysis and after completion. Word stays usable; review shows interruption and stale paging is invalidated. Restart/reconnect; Analyse Document/Analyse again must succeed with new snapshot state. Exercise busy Word dialogs/COM failures and unsupported ranges; show an actionable stopped state, never an endless spinner.
8. Run with an old Phase 1 agent and the new add-in, then with the new agent and old add-in in controlled test profiles. No incompatible operation should be silently interpreted as a completed analysis. Existing Office.js/browser behavior remains independent.
## Responsiveness measurements
Use the existing fixture generator and process measurement script. First validate fixtures open without repair. Compare add-in-disabled and enabled trials on 190k, 250k, many-short/repeated-paragraph and 250k single-paragraph fixtures. Include continuous typing, scrolling, rapid selection movement, saving, closing and three concurrent analyses. Record COM-call/batch duration distributions, UI tick delay and external typing/scroll/save/close latency; agent CPU/private memory, FIFO/coalesced queue depth, total extraction/analysis time and recovery time. Note that continuous input intentionally postpones low-priority extraction; progress may pause without Word being frozen.
Do not use the agent-only synthetic analysis timing as Word responsiveness evidence. Investigate any noticeable typing, scrolling or save regression before declaring acceptance. Inspect modeless window sizing, DPI, keyboard/focus behavior and Word activation: it must allow continuing to edit Word and clearly follow the active document.
Commit Windows-specific fixes and qualification evidence to the same shared branch, push, and report the exact tested SHA/build. Do not start another migration phase, install an updater or deploy Production.