Integrate native workspace status, saved Context and Intent, and safe import preview

This commit is contained in:
Nick Beckley 2026-11-05 14:18:06 +00:00
parent 7df1552306
commit 0075bb5299
43 changed files with 1360 additions and 77 deletions

View File

@ -0,0 +1,83 @@
# Native Word Companion Phase 3.5 integration
## Outcome and boundaries
Developer build **1.0.0.6** extends Phase 3 on the same shared branch. Existing authenticated chapter AI, bounded extraction, local detection, named pipes and separate .NET 10 agent are retained. There is no replacement architecture, new UI framework, schema migration, native live SignalR protocol or manuscript rewriting.
The useful integrated path is: local detection → explicit chapter AI → source-labelled review → bounded cross-page chapter/scene selection → authenticated **read-only import preview**. Native commit is deliberately unavailable. This is the largest safe import portion delivered under the assignment's fallback; it must not be described as completed native importing.
## Architecture and ownership
```mermaid
flowchart LR
W[Word STA scheduler and ribbon] <-->|value-only bounded IPC| A[Per-user .NET 10 agent]
W --> R[Modeless review: per-document book binding]
A -->|bearer HTTPS| N[Existing native API plus workflow endpoints]
N --> P[Existing book ownership and subscription checks]
N --> C[Existing Context and chapter workflow services]
N --> I[Existing manuscript eligibility and validation]
N --> AI[Existing chapter AI service]
A -->|explicit open only| B[Pinned saved Context / Intent or book browser page]
L[Existing Office.js SignalR connection] --> V[Ordinary live browser Context / Intent]
```
No HTTP, credentials, parsing, database operations or AI execute in VSTO. New saved-data/preview responses use optional `workspace-review-v1` capability negotiation. Existing core IPC and `chapter-ai-v2` remain compatible. Existing Office.js routes, hub methods, event contracts and ordinary multi-screen live following are retained.
## Experience audit and repairs
| Finding | Repair / actual resulting behaviour |
|---|---|
| A previous successful sign-in string could look current after outages | Shared `ConnectionHealth` / `ConnectionPresentation`; IPC failure overrides cached server/auth/book state, server checks have a freshness limit, 401 rotates the authentication scope and clears access. |
| One book combo was not an authorised per-document context | `DocumentBinding` and `DocumentWorkspaceWork` bind exact session/revision/book/authentication/binding IDs. Switching clears prior saved data immediately; delayed replies are discarded. |
| Native Context / Intent had no useful saved-data integration | Read-only summaries from existing scene Context and chapter workflow/goals, with source labels, book/chapter/scene title and explicit missing-data messages. Foreign saved markers are rejected. |
| Opening a browser URL could start following the legacy latest Word connection | Explicit `pinned=true` snapshot mode suppresses live subscription, global story-position listeners and window registration for these views. Manual scene/tab navigation remains; ordinary live views are unchanged. |
| Review and import were disconnected | Checked rows survive page changes and document switching (80-row bound), target is authorised, metadata-only upload requires confirmation, existing validation/eligibility reports conflicts. No commit is implied. |
| Duplicate Analyse / Synchronise alias controls confused local detection with sync | Removed the duplicate ribbon action. Detect structure remains local; explicit chapter AI is separately labelled. |
| Ribbon Cancel could be active without work; save could leave an old preview loading | Cancel enabled only for active work; client cancellation invalidates request ID immediately, agent generation suppresses delayed completion. Save never waits or cancels Word's save. |
| Status text could be too wide; large selections lost across pages | Ribbon status split across two labels; modeless wrapping action layout, long book dropdown, hierarchical 40-row pages, full inspector, bounded selection shared across tabs. DPI/layout still requires Word qualification. |
### Connection semantics
- `Word loaded` is local host state; connected means successful local IPC, never server or AI health.
- `/api/native-companion/connection` is bearer-authenticated and verifies current entitlement/configuration. It does **not** submit a paid AI probe.
- Server/auth verification is considered current for 90 seconds. Status reads may initiate at most one health check per two minutes; an explicit Check connection initiates a check immediately. The deliberate intervening `unverified` state avoids a stale success claim without frequent network polling.
- Cached grants/books remain distinguishable from live verification. Known four-hour expiry and server 401 invalidate authentication scope; book data must be reselected/revalidated after sign-out/restart.
- AI `configured`, `not-configured`, `not-entitled`, `unknown`, `last-request-succeeded` and `request-failed` describe evidence, not a guarantee of provider availability. Local analysis remains available offline.
- Saved-data requests have 15-second timeouts, bounded 1MiB responses, four concurrent workspace fetches, 350ms position coalescing and replacement suppression. Preview has at most four in-flight requests, no automatic retries or commits. Cancelled read-only HTTP may finish within its timeout; its result cannot restore UI state.
- No diagnostics contain prose or credentials. Health explanatory text is available in the protocol; native status displays the distinct states and operation-specific result/error text.
### Document lifecycle
The existing persistent manuscript GUID and live session remain distinct. Word-derived positional scene/chapter markers are verified against the selected book through `GetBookStructureAsync`, not trusted as arbitrary database IDs. Book selection remains per open document; account/agent change invalidates it. Observed revision changes reset the saved binding and reauthorise the retained book. Document close/revision clearing releases agent workspace state. Existing limited same-length-edit detection remains: review results describe a captured snapshot, so re-detect after editing.
## Import: what works and what does not
`NativeImportPreview.Build` checks bounded current identity/selection, nonblank bounded titles, positive/nonoverlapping ranges, unique boundaries, parent chapters and at least one selected scene per selected chapter. It orders by Word positions, never invents placeholder scenes, and invokes the same `WordCompanionService.ValidImportStructure` validator used by the existing importer. The controller checks authenticated ownership and Import entitlement before the existing `AnalyseManuscriptAsync` eligibility operation. Linked manuscript counts, existing planned chapters/scenes and refusal reasons are returned. Metadata contains titles/positions and identity only; prose is not uploaded, and word counts are explicitly unknown/zero.
The old `WordCompanionService.ImportManuscriptAsync` and SQL import (migration 219) also own document binding/structure and planned-content decisions; its existing linked/planned checks precede its transaction. Canonical onboarding additionally owns prose sources, chapter AI review, resumable marker build and save acknowledgement. Calling that write path directly from the native preview would not provide safe idempotent prose/binding/recovery semantics. No unsafe direct database path, automatic replacement or new partial-import retry mechanism was added.
The UI always reports **Created: 0 / Replaced: 0**, `CommitAvailable=false`. Continue in PlotDirector opens the authorised book in the existing application. **Selections are not transferred**. Existing web importing remains the committing workflow, with its existing author confirmation. Repeated native previews are read-only and cannot create duplicates; they do not claim to solve transaction/idempotency guarantees for a future native commit. Full commit is a separate remaining capability, not a hidden success state.
## Context and Intent
Native tabs distinguish saved information from local structural/AI suggestions. Context uses saved scene summary, then chapter/book summary where applicable. Intent uses saved scene-purpose notes and chapter goal/emotional-goal/reader-takeaway/must-include fields. Neither generates AI information nor saves changes. Book-level absence is useful explicit guidance, not a fabricated writing objective.
Full browser views reuse existing rendering and access validation. Native links pin project/book/verified chapter/scene and opt out of legacy latest-connection follow. Multiple independently opened pinned views keep their scopes. This is **saved snapshot integration**, not native live multi-screen SignalR following. Existing Office.js live Context/Intent multi-screen behaviour is preserved for its ordinary views. A future native live protocol still requires session-aware routing and explicit follow policy.
## Main evidence references
- `Protocol/WorkflowContracts.cs`, `Protocol/Messages.cs`: optional capability and bounded value contracts.
- `Agent/CloudGateway.cs`: auth expiry, HTTP verification, status, scoped browser opening; `DocumentWorkspaceWork.cs`: per-session saved scope, coalescing and preview suppression; `SessionManager.cs`: current snapshot/identity checks and lifecycle.
- `Client/DocumentBinding.cs`, `ConnectionPresentation.cs`: shared presentation and stale-response guards.
- `Vsto/WordAdapter.cs`: UI-thread value exchange, exact-document commands, save/cancel safety; `AnalysisWindow.cs`, `NativeRibbon.cs`, `Ribbon.xml`: native experience.
- `PlotLine/Controllers/NativeCompanionWorkflowController.cs`: authenticated connection/workspace/preview; `Services/NativeCompanion/NativeImportPreview.cs`; existing `Services/WordCompanionService.cs` shared validation/eligibility.
- `WritingController.cs`, Context/Intent Razor views, `wwwroot/js/writing-follow.js`: pinned mode with preserved live mode.
- Existing investigation: `Docs/Investigations/2026-11-04-word-companion-investigation.md`; previous report: `2026-11-05-phase3-ai-integration.md`.
## Verification and remaining qualification
Evidence and exact final checks/deployment outcome are recorded alongside this report under `Evidence/2026-11-05-phase35/`. Automated checks exercise real controller/HTTP routes with synthetic authenticated principals/provider and fail-on-write repositories, agent lifecycle/state, browser response races, package tamper refusal and VSTO source syntax. They do not claim a live author's database import, provider availability or real Office execution.
There are no new database migrations or configuration secrets/settings. The server needs the existing desktop pairing/auth infrastructure, subscription entitlement and configured existing AI provider; the Phase 3 migration 230 prerequisite remains. Preparing Windows packages does not alter the working laptop installation.
Windows COM semantics, compilation against installed Office, signed manifests, installation, visual DPI/layout and actual typing/scroll/save responsiveness remain unverified on Atlas. Native import commit, native live SignalR following, full prose sync and a complete edit journal remain out of scope. [Windows steps and tonight's checklist](../../PlotDirector.NativeCompanion/WindowsValidation/Phase35-Integration.md) use the existing Update/Install scripts and version 1.0.0.6.

View File

@ -0,0 +1,408 @@
PASS Native saved workspace and established import eligibility remain scoped and read-only
PASS Native companion authentication, canonical AI mapping and isolated chapter retry
PASS Solver never discards a corroborated concern or exhausts navigation before verification
PASS Solver result evidence covers all reachable diagnoses without changing Stage 1 semantics
PASS Solver result copy follows actual answers, intention, variants and revision
PASS Solver workspace CTAs resolve authorised project/character context and real routes
PASS Stage 1 preserves all 60 strict conversations, corroboration, intent, reachability and adoption
PASS Stage 1 evidence gates, required follow-ups, bounded multi-select and neutral choices are enforced
PASS Neutral endpoints require explicit valid terminal declarations
PASS Neutral reassurance follows selected concerns without evidence and survives revision
PASS Scene navigation does not invent purpose evidence; genuine D05 witnesses survive
PASS D50 requires actual series evidence and preserves D50/D51 witnesses
PASS Curated V2 preserves 60 literal paths and enforces eight explicit Development review exceptions
PASS Curated V2 exhausts real-engine states and preserves revision/multi-select behaviour
PASS Curated V2 passes normal validation and invalid publication stays guarded
PASS Payoff covers all 52 diagnoses with seven archetypes and semantic uncertainty ordering without graph changes
PASS Development review observes every acceptance prefix without changing signals, results or graph; access and durable capture stay isolated
PASS All permanent writing problems have distinct editorial content, intent, metadata, links and real images
PASS Clean solver completion preserves private evidence and permanent indexable URLs
PASS Writing Solver anonymous state is protected, expires and rejects stale versions
PASS Writing Solver scoring, multi-select, revision, fallback and graph routes
PASS Writing Solver import rejects invalid graphs and editorial identities
PASS Project export and restore access gates enforce author and ownership boundaries
PASS Retired checklist bookmarks redirect without report access
PASS Ribbon operation identity and semantic icons stay consistent
PASS Maps Story projects canonical hierarchy, sequence, journeys and evidence without changing geography
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,5 @@
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 pinned context retains scoped saved content without SignalR/latest Word/window registration
PASS pinned intent retains scoped saved content without SignalR/latest Word/window registration
PASS fresh Writer launcher opens both missing role windows without undeclared currentRole

View File

@ -0,0 +1,183 @@
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
PASS review suggestion storage is bounded with explicit truncation
PASS analysis results are paginated
PASS review page fits bounded IPC frame
PASS analysis result contract round-trips over framing
PASS document-specific analysis returns structured results and progress
PASS document-specific analysis returns structured results and progress
PASS document-specific analysis returns structured results and progress
PASS another document's snapshot cannot retrieve results
PASS analysis acknowledges bounded partial progress before cancellation
PASS cancelled analysis cannot complete
PASS analysis waiting for Word scheduler is cancellable
PASS pending analysis cancellation does not require extraction
PASS review rejects results from a different document
PASS late results cannot replace cancellation
PASS new analysis rejects obsolete revision and snapshot
PASS review completes only matching analysis
PASS selection replies cannot regress completed review progress
PASS late page zero cannot replace requested later page
PASS agent restart releases document analysis state
PASS native connection rejects unsafe site root
PASS native connection rejects unsafe site root
PASS native connection rejects unsafe site root
PASS native connection rejects unsafe site root
PASS native connection rejects unsafe site root
PASS incompatible agent handshake enters recovery instead of killing the client worker
PASS browser-approved sign-in loads only authorised book choices
PASS sign-in and local work never upload chapter prose
PASS AI chapter capture starts only after an explicit command
PASS bounded chapter capture reports progress without submitting early
PASS duplicate submit uses one HTTP call and preserves exact chapter mapping
PASS worst-case bounded AI page fits IPC framing
PASS AI result contract round-trips on actual frame codec
PASS late cancellation cannot retire a replacement AI chapter
PASS another document cannot retrieve an AI result
PASS cancelled network chapter cannot reappear in review
PASS authorisation failure is isolated and actionable
PASS malformed AI fields fail safely instead of leaving a chapter spinning
PASS upload consent pins document snapshot and authentication context
PASS account/site change refuses old consent before any chapter HTTP upload
PASS sign-out forgets credential and book list
PASS local chapters supply explicit nonoverlapping AI extraction ranges
PASS duplicate live session identity cannot cross Word instances
PASS expired verification never presents cached sign-in/book as live
PASS IPC outage overrides previously successful server state
PASS book switch rejects late saved data
PASS late successful response cannot revive a cancelled client preview
PASS one parent chapter is retained across local and AI pages
PASS cross-page preview selection is bounded without silently dropping selected rows
PASS multiple document saved contexts remain isolated
PASS older workspace binding cannot fetch or overwrite a replacement
PASS cancelled import preview cannot reappear after delayed completion
PASS server loss clears a previously verified online indicator
PASS explicit connection check detects recovery
PASS authentication expiry rotates scope and removes verified authentication
PASS expired credentials cannot display an old authenticated workspace
Native foundation: 182 checks passed. Linux named-pipe API uses Unix domain sockets; Windows ACL/COM/Word responsiveness NOT verified.

View File

@ -0,0 +1,8 @@
PASS parse Build-Developer.ps1
PASS parse DeveloperPackage.ps1
PASS parse Generate-Fixtures.ps1
PASS parse Install-WordCompanion.ps1
PASS parse Measure-Processes.ps1
PASS parse Test-DeveloperPackage.ps1
PASS parse Update-WordCompanion.ps1
PASS portable package validation, tamper refusal and non-Windows fail-closed guards. Fixture signatures are placeholders; no Office trust/Windows installation validation claimed.

View File

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

View File

@ -0,0 +1 @@
PASS native saved workspace and safe import preview validation

View File

@ -20,6 +20,8 @@ public sealed class CloudGateway : IDisposable
private string? token;
private Guid authenticationContext=Guid.NewGuid();
private string state="Not signed in";
private ConnectionHealth health=new();
private int checking;private DateTime nextCheck;
private CompanionBook[] books=[];
private readonly string? settingsPath;
private static readonly JsonSerializerOptions Json=new(JsonSerializerDefaults.Web);
@ -34,12 +36,26 @@ public sealed class CloudGateway : IDisposable
return uri;
}
public Message Status()
{lock(gate)return new(){Status=state,Books=books,AuthenticationContext=authenticationContext,ServerUrl=origin?.AbsoluteUri??ReadOrigin()};}
{
bool refresh;Message answer;
lock(gate){Expire();refresh=token!=null&&DateTime.UtcNow>=nextCheck;answer=new(){Status=state,Books=books,AuthenticationContext=authenticationContext,ServerUrl=origin?.AbsoluteUri??ReadOrigin(),Health=CopyHealth()};}
if(refresh)_=CheckConnection();return answer;
}
private ConnectionHealth CopyHealth()=>new(){Server=health.Server,Authentication=health.Authentication,Ai=health.Ai,Explanation=health.Explanation,VerifiedUtc=health.VerifiedUtc,ExpiresUtc=health.ExpiresUtc};
private void Expire(){if(token!=null&&health.ExpiresUtc!=default&&DateTime.UtcNow>=health.ExpiresUtc){authenticationContext=Guid.NewGuid();token=null;books=[];state="Sign-in expired. Connect again.";health.Authentication="expired";health.Ai="unknown";}}
public async Task CheckConnection()
{
if(Interlocked.Exchange(ref checking,1)!=0)return;
Guid context;lock(gate){context=authenticationContext;nextCheck=DateTime.UtcNow.AddMinutes(2);health.Server="checking";}
try{var result=await Get<ConnectionHealth>("api/native-companion/connection",context);lock(gate)if(authenticationContext==context){result.VerifiedUtc=DateTime.UtcNow;health=result;state="Signed in (verified)";}}
catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException){lock(gate)if(authenticationContext==context){health.Server=token==null?"unknown":"offline";health.Explanation="Server verification failed. Check connection; local detection remains available.";}}
finally{Volatile.Write(ref checking,0);}
}
private string ReadOrigin(){try{return settingsPath!=null&&File.Exists(settingsPath)?File.ReadAllText(settingsPath):"";}catch(IOException){return "";}}
public void Connect(string address)
{
var uri=ValidateOrigin(address);CancellationTokenSource stop;
lock(gate){pairing?.Cancel();pairing=stop=new(TimeSpan.FromMinutes(5));origin=uri;authenticationContext=Guid.NewGuid();token=null;books=[];state="Starting browser sign-in…";}
lock(gate){pairing?.Cancel();pairing=stop=new(TimeSpan.FromMinutes(5));origin=uri;authenticationContext=Guid.NewGuid();token=null;books=[];health=new(){Server="connecting",Authentication="pending"};state="Starting browser sign-in…";}
_=Task.Run(async()=>{
try
{
@ -60,33 +76,65 @@ public sealed class CloudGateway : IDisposable
using var request=new HttpRequestMessage(HttpMethod.Get,new Uri(uri,"api/native-companion/books"));request.Headers.Authorization=new("Bearer",grant.AccessToken);
using var list=await http.SendAsync(request,stop.Token);list.EnsureSuccessStatusCode();
var available=await list.Content.ReadFromJsonAsync<CompanionBook[]>(Json,stop.Token)??[];
lock(gate)if(pairing==stop&&!stop.IsCancellationRequested){token=grant.AccessToken;books=available.Where(b=>b!=null&&b.BookId>0&&b.Title!=null).Take(200).Select(b=>new CompanionBook{BookId=b.BookId,Title=b.Title.Length>160?b.Title[..160]:b.Title}).ToArray();state="Signed in (four-hour grant)";}
lock(gate)if(pairing==stop&&!stop.IsCancellationRequested){token=grant.AccessToken;books=available.Where(b=>b!=null&&b.BookId>0&&b.Title!=null).Take(200).Select(b=>new CompanionBook{BookId=b.BookId,Title=b.Title.Length>160?b.Title[..160]:b.Title}).ToArray();state="Signed in (four-hour grant)";health=new(){Server="online",Authentication="verified",VerifiedUtc=DateTime.UtcNow,ExpiresUtc=DateTime.UtcNow.AddHours(4),Ai="unknown",Explanation="Book list verified; checking AI configuration."};nextCheck=DateTime.MinValue;}
return;
}
}
catch(Exception e)when(e is HttpRequestException or OperationCanceledException or IOException or InvalidDataException or JsonException or System.ComponentModel.Win32Exception or UnauthorizedAccessException or InvalidOperationException or ArgumentException)
{lock(gate)if(pairing==stop)state="Sign-in failed or expired. Check the site address and try Connect again.";}
{lock(gate)if(pairing==stop){state="Sign-in failed or expired. Check the site address and try Connect again.";health=new(){Server="unverified",Authentication="not-signed-in",Explanation=state};}}
});
}
public void SignOut(){lock(gate){pairing?.Cancel();pairing=null;authenticationContext=Guid.NewGuid();token=null;books=[];state="Not signed in";}}
public void SignOut(){lock(gate){pairing?.Cancel();pairing=null;authenticationContext=Guid.NewGuid();token=null;books=[];state="Not signed in";health=new();}}
public bool Allows(Guid context,int bookId)
{lock(gate)return token!=null&&context==authenticationContext&&books.Any(b=>b.BookId==bookId);}
{lock(gate){Expire();return token!=null&&context==authenticationContext&&books.Any(b=>b.BookId==bookId);}}
public async Task<AiChapterResult> Analyse(AiChapterRequest chapter,CancellationToken cancellation,Guid expectedContext)
{
Uri site;string access;
lock(gate){if(authenticationContext!=expectedContext)throw new InvalidOperationException("Connection/account changed. Confirm the chapter upload again.");site=origin??throw new InvalidOperationException("Connect to PlotDirector first.");access=token??throw new InvalidOperationException("Sign in first.");}
using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(site,"api/native-companion/analyse-chapter")){Content=JsonContent.Create(chapter,options:Json)};
request.Headers.Authorization=new AuthenticationHeaderValue("Bearer",access);
using var response=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,cancellation);
if(response.StatusCode==HttpStatusCode.Unauthorized){lock(gate)if(token==access){authenticationContext=Guid.NewGuid();token=null;books=[];state="Sign-in expired. Connect again.";}throw new InvalidOperationException("Sign-in expired. Connect again.");}
if(!response.IsSuccessStatusCode)throw new InvalidOperationException(response.StatusCode switch{HttpStatusCode.Forbidden=>"Book/subscription access denied.",HttpStatusCode.TooManyRequests=>"Server busy. Retry this chapter later.",HttpStatusCode.BadRequest=>"Chapter mapping or size was rejected. Check boundaries.",_=>"Server unavailable. Check the deployed native API."});
HttpResponseMessage responseValue;
try{responseValue=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,cancellation);}
catch(HttpRequestException){lock(gate)if(authenticationContext==expectedContext){health.Server="offline";health.Explanation="AI request could not reach the server.";}throw;}
using var response=responseValue;
if(response.StatusCode==HttpStatusCode.Unauthorized){lock(gate)if(token==access){authenticationContext=Guid.NewGuid();token=null;books=[];state="Sign-in expired. Connect again.";health.Authentication="expired";health.Server="online";health.Ai="unknown";}throw new InvalidOperationException("Sign-in expired. Connect again.");}
if(!response.IsSuccessStatusCode){lock(gate)if(authenticationContext==expectedContext){health.Server="degraded";health.Ai="request-failed";health.Explanation="AI request rejected or unavailable; see chapter results.";}throw new InvalidOperationException(response.StatusCode switch{HttpStatusCode.Forbidden=>"Book/subscription access denied.",HttpStatusCode.TooManyRequests=>"Server busy. Retry this chapter later.",HttpStatusCode.BadRequest=>"Chapter mapping or size was rejected. Check boundaries.",_=>"Server unavailable. Check the deployed native API."});}
// Bound server response before deserializing; never log a body/provider message.
await using var stream=await response.Content.ReadAsStreamAsync(cancellation);using var buffer=new MemoryStream();var bytes=new byte[8192];
int count;while((count=await stream.ReadAsync(bytes,cancellation))>0){if(buffer.Length+count>1024*1024)throw new InvalidDataException("AI response too large.");buffer.Write(bytes,0,count);}
buffer.Position=0;var result=await JsonSerializer.DeserializeAsync<AiChapterResult>(buffer,Json,cancellation)??throw new InvalidDataException();
if(result.RequestId!=chapter.RequestId||result.State is not ("complete" or "failed" or "cancelled")||result.Message==null||result.Message.Length>2048||result.Scenes==null||result.Scenes.Length>500||result.Scenes.Any(s=>s==null||s.Start<chapter.ChapterStart||s.End>chapter.ChapterEnd||s.End<=s.Start||s.Title==null||s.Reason==null||s.Confidence==null||s.Confidence.Length>32||s.Kind!="Scene"||s.Origin!="AI"||s.Title.Length>200||s.Reason.Length>600))throw new InvalidDataException("Invalid AI mapping.");
lock(gate)if(authenticationContext==expectedContext){health.Server="online";health.Authentication="verified";health.VerifiedUtc=DateTime.UtcNow;health.Ai=result.State=="complete"?"last-request-succeeded":"request-failed";health.Explanation=result.Message;}
return result;
}
public async Task<T> Get<T>(string path,Guid expectedContext)
=>await Send<T>(HttpMethod.Get,path,null,expectedContext);
public async Task<T> Post<T>(string path,object body,Guid expectedContext)
=>await Send<T>(HttpMethod.Post,path,body,expectedContext);
private async Task<T> Send<T>(HttpMethod method,string path,object? body,Guid context)
{
Uri site;string access;lock(gate){Expire();if(context!=authenticationContext||token==null)throw new InvalidOperationException("Sign in again and reselect the book.");site=origin!;access=token;}
using var stop=new CancellationTokenSource(TimeSpan.FromSeconds(15));using var request=new HttpRequestMessage(method,new Uri(site,path));request.Headers.Authorization=new("Bearer",access);if(body!=null)request.Content=JsonContent.Create(body,options:Json);
try
{
using var response=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,stop.Token);
if(response.StatusCode==HttpStatusCode.Unauthorized){lock(gate)if(authenticationContext==context){authenticationContext=Guid.NewGuid();token=null;books=[];state="Sign-in expired. Connect again.";health.Authentication="expired";}throw new InvalidOperationException("Sign-in expired. Connect again.");}
if(!response.IsSuccessStatusCode&&!(response.StatusCode==HttpStatusCode.BadRequest&&path=="api/native-companion/import-preview")){lock(gate)if(context==authenticationContext){health.Server=response.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.NotFound?"online":"degraded";health.VerifiedUtc=DateTime.UtcNow;health.Explanation="Server rejected the saved-data request. See the document result.";}throw new InvalidOperationException(response.StatusCode==HttpStatusCode.Forbidden?"Access denied or subscription unavailable.":response.StatusCode==HttpStatusCode.NotFound?"No saved chapter/scene matches this book and Word marker.":"Server request failed. Check connection or update the server.");}
await using var stream=await response.Content.ReadAsStreamAsync(stop.Token);using var buffer=new MemoryStream();var bytes=new byte[8192];int size;
while((size=await stream.ReadAsync(bytes,stop.Token))>0){if(buffer.Length+size>1024*1024)throw new InvalidDataException();buffer.Write(bytes,0,size);}buffer.Position=0;
var result=await JsonSerializer.DeserializeAsync<T>(buffer,Json,stop.Token);
lock(gate){if(context!=authenticationContext)throw new InvalidOperationException("Connection changed; discarded old response.");health.Server="online";health.Authentication="verified";health.VerifiedUtc=DateTime.UtcNow;}
return result??throw new InvalidDataException();
}
catch(OperationCanceledException){lock(gate)if(context==authenticationContext){health.Server="degraded";health.Explanation="Server verification timed out. Check connection before continuing.";}throw;}
catch(HttpRequestException){lock(gate)if(context==authenticationContext){health.Server="offline";health.Explanation="Server unreachable. Saved information is not current.";}throw;}
}
public void OpenSavedPage(string path,Guid context)
{
lock(gate){Expire();if(context!=authenticationContext||token==null||origin==null)throw new InvalidOperationException("Sign in first.");
if(!path.StartsWith("/Books/Details/",StringComparison.Ordinal)&&!path.StartsWith("/Writing/Context?",StringComparison.Ordinal)&&!path.StartsWith("/Writing/Intent?",StringComparison.Ordinal))throw new InvalidDataException();
var url=new Uri(origin,path);if(url.GetLeftPart(UriPartial.Authority)!=origin.GetLeftPart(UriPartial.Authority))throw new InvalidDataException();openBrowser(url.AbsoluteUri);}
}
public async Task CancelRemote(Guid id)
{
try

View File

@ -0,0 +1,78 @@
using PlotDirector.Companion.Protocol;
namespace PlotDirector.Companion.Agent;
// Bounded value-only per-document saved workspace/preview. No import commit operation exists.
public sealed class DocumentWorkspaceWork(CloudGateway cloud)
{
private readonly SemaphoreSlim requests=new(4);
private int previewJobs;
private readonly object gate=new();private readonly Dictionary<Guid,State> states=[];
public Message Handle(DocumentDescriptor descriptor,Message request,Message answer)
{
lock(gate)
{
if(request.Kind=="workspace-select")
{
Clear(descriptor.SessionId);
if(request.BookId==0){answer.Workspace=new();return answer;}
if(states.Count>=256||!cloud.Allows(request.AuthenticationContext,request.BookId)){answer.Status="authentication-changed";return answer;}
var state=new State(request.BookId,request.AuthenticationContext,descriptor.Revision,request.SnapshotId);states[descriptor.SessionId]=state;Refresh(descriptor.SessionId,state,request.ChapterId,request.SceneId);
}
if(!states.TryGetValue(descriptor.SessionId,out var current)){answer.Workspace=new();return answer;}
if(request.SnapshotId!=current.Binding){answer.Status="obsolete-workspace";return answer;}
answer.SnapshotId=current.Binding;answer.BookId=current.Book;answer.AuthenticationContext=current.Context;
if(!cloud.Allows(current.Context,current.Book)){Clear(descriptor.SessionId);answer.Status="authentication-changed";answer.Workspace=new();return answer;}
if(request.Kind=="workspace-refresh")Refresh(descriptor.SessionId,current,request.ChapterId,request.SceneId);
if(request.Kind=="workspace-preview")
{
var selection=request.ImportSelection;
if(selection==null||selection.BookId!=current.Book||selection.SessionId!=descriptor.SessionId||selection.SnapshotId==Guid.Empty||selection.Items==null||selection.Items.Length is <1 or >80){answer.Status="invalid-preview";return answer;}
if(previewJobs>=4||current.Preview?.State=="loading"){answer.ImportPreview=new(){RequestId=selection.RequestId,State="rejected",Message="Preview already running or server preview capacity is busy. Cancel or wait, then retry."};answer.Workspace=current.Workspace;return answer;}
previewJobs++;var generation=++current.PreviewGeneration;current.Preview=new(){RequestId=selection.RequestId,State="loading",Message="Validating selected structure with PlotDirector. No records are created."};
_=Task.Run(async()=>{
ImportPreview result;
try{result=await cloud.Post<ImportPreview>("api/native-companion/import-preview",selection,current.Context);}
catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or System.Text.Json.JsonException){result=new(){State="rejected",Message=e is InvalidOperationException?e.Message:"Preview unavailable. Check connection and retry; no import was committed."};}
lock(gate){previewJobs--;if(states.GetValueOrDefault(descriptor.SessionId)==current&&generation==current.PreviewGeneration){result.RequestId=selection.RequestId;current.Preview=result;}}
});
}
if(request.Kind=="workspace-cancel-preview"){current.PreviewGeneration++;current.Preview=null;}
if(request.Kind=="workspace-open")
{
if(!current.Workspace.State.StartsWith("saved-",StringComparison.Ordinal)){answer.Status="workspace-unavailable";return answer;}
var path=request.Action switch{"context"=>current.Workspace.ContextPath,"intent"=>current.Workspace.IntentPath,"book"=>current.Workspace.BookPath,_=>""};
_=Task.Run(()=>{try{cloud.OpenSavedPage(path,current.Context);}catch(Exception e)when(e is InvalidOperationException or IOException or InvalidDataException or System.ComponentModel.Win32Exception){ }});
}
answer.Workspace=current.Workspace;answer.ImportPreview=current.Preview;answer.BookId=current.Book;return answer;
}
}
public void Position(Guid session,int? chapter,int? scene)
{lock(gate)if(states.TryGetValue(session,out var state)&&(state.Chapter!=chapter||state.Scene!=scene))Refresh(session,state,chapter,scene);}
private void Refresh(Guid session,State state,int? chapter,int? scene)
{
state.Chapter=chapter;state.Scene=scene;state.Generation++;
state.Workspace=new(){BookId=state.Book,State="loading",Context="Loading saved book/position…",Intent="Loading saved objectives…"};
if(state.Running)return;state.Running=true;
_=Task.Run(async()=>{
while(true)
{
await Task.Delay(350);long generation;int? chapterId,sceneId;
lock(gate){if(states.GetValueOrDefault(session)!=state)return;generation=state.Generation;chapterId=state.Chapter;sceneId=state.Scene;}
SavedWorkspace result;
await requests.WaitAsync();
try
{
lock(gate){if(states.GetValueOrDefault(session)!=state)return;}
result=await cloud.Get<SavedWorkspace>($"api/native-companion/books/{state.Book}/workspace"+(chapterId.HasValue||sceneId.HasValue?$"?chapterId={chapterId}&sceneId={sceneId}":""),state.Context);
}
catch(Exception e){result=new(){BookId=state.Book,State="unavailable",Context=e is InvalidOperationException?e.Message:"Saved context could not be loaded. Check connection.",Intent="No saved intent is displayed. Refresh after reconnecting."};}
finally{requests.Release();}
lock(gate){if(states.GetValueOrDefault(session)!=state)return;if(state.Generation==generation){state.Workspace=result;state.Running=false;return;}}
}
});
}
public void Clear(Guid session){lock(gate)states.Remove(session);}
public void ClearAll(){lock(gate)states.Clear();}
private sealed class State(int book,Guid context,long revision,Guid binding)
{public Guid Binding=binding;public int Book=book;public Guid Context=context;public long Revision=revision;public bool Running;public long Generation,PreviewGeneration;public int? Chapter,Scene;public SavedWorkspace Workspace=new();public ImportPreview? Preview;}
}

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,Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability},cancellation);
await FrameCodec.WriteAsync(pipe,new Message {CorrelationId=hello.CorrelationId,Status="ready",WordInstanceId=instance,Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability},cancellation);
log?.Invoke("peer-connected");
while (!cancellation.IsCancellationRequested)
{

View File

@ -15,7 +15,7 @@ using(var shutdown = new CancellationTokenSource())
log.Write("agent-start protocol=1 authentication=browser-pairing publisher=Nick-Beckley");
using var cloud=new CloudGateway(settingsPath:Path.Combine(directory,"server-url.txt"));
using var ai=new ChapterAiWork(cloud);
var host=new PipeHost(AgentEndpoint.CurrentUserPipeName(),new SessionManager(cloud,ai),log.Write);
var host=new PipeHost(AgentEndpoint.CurrentUserPipeName(),new SessionManager(cloud,ai,new DocumentWorkspaceWork(cloud)),log.Write);
var serve=host.RunAsync(shutdown.Token);
var idle=Task.Run(async()=>{
var lastPeer=DateTime.UtcNow;

View File

@ -4,7 +4,7 @@ using PlotDirector.Companion.Protocol;
namespace PlotDirector.Companion.Agent;
public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai = null)
public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai = null,DocumentWorkspaceWork? workspace = null)
{
private readonly object gate = new();
private readonly Dictionary<Guid, WordInstance> instances = [];
@ -37,7 +37,7 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai
}
private void ClearDocument(DocumentState document)
{
ai?.Clear(document.Descriptor.SessionId);
ai?.Clear(document.Descriptor.SessionId);workspace?.Clear(document.Descriptor.SessionId);
totalSuggestions -= document.Analysis?.Count ?? 0;document.Analysis=null;
ClearPending(document);totalBoundaries -= document.Boundaries.Count;document.Boundaries=[];
}
@ -50,12 +50,12 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai
if (message.Sequence <= word.LastSequence) return Reject(answer,"stale-sequence");
word.LastSequence = message.Sequence;
if (message.Kind == "ping") return answer;
if(message.Kind is "cloud-status" or "cloud-connect" or "cloud-signout")
if(message.Kind is "cloud-status" or "cloud-check" or "cloud-connect" or "cloud-signout")
{
answer.Kind="cloud-status";if(cloud==null)return Reject(answer,"cloud-unavailable");
try{if(message.Kind=="cloud-connect"){ai?.Dispose();cloud.Connect(message.ServerUrl);}if(message.Kind=="cloud-signout"){ai?.Dispose();cloud.SignOut();}}
try{if(message.Kind=="cloud-check")_=cloud.CheckConnection();if(message.Kind=="cloud-connect"){ai?.Dispose();workspace?.ClearAll();cloud.Connect(message.ServerUrl);}if(message.Kind=="cloud-signout"){ai?.Dispose();workspace?.ClearAll();cloud.SignOut();}}
catch(ArgumentException){return Reject(answer,"invalid-server-url");}
var status=cloud.Status();answer.Kind="cloud-status";answer.Status=status.Status;answer.Books=status.Books;answer.AuthenticationContext=status.AuthenticationContext;answer.ServerUrl=status.ServerUrl;return answer;
var status=cloud.Status();answer.Kind="cloud-status";answer.Status=status.Status;answer.Books=status.Books;answer.Health=status.Health;answer.AuthenticationContext=status.AuthenticationContext;answer.ServerUrl=status.ServerUrl;return answer;
}
if (message.Kind is "document" or "reconcile")
{
@ -90,6 +90,10 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai
return answer;
}
if (message.Revision != document.Descriptor.Revision) return Reject(answer,"stale-revision");
if(message.Kind.StartsWith("workspace-",StringComparison.Ordinal)){answer.Kind="workspace-response";answer.BookId=message.BookId;answer.AuthenticationContext=message.AuthenticationContext;
if(message.Kind=="workspace-preview"&&(message.ImportSelection?.SnapshotId!=document.SnapshotId||message.ImportSelection?.ManuscriptId!=document.Descriptor.ManuscriptId)){answer.ImportPreview=new(){RequestId=message.ImportSelection?.RequestId??Guid.Empty,State="rejected",Message="Document snapshot changed. Detect structure and preview again."};return Reject(answer,"stale-preview");}
if(message.Kind is "workspace-select" or "workspace-refresh"){var position=new Message();Resolve(document,position);message.ChapterId=position.ChapterId;message.SceneId=position.SceneId;}
answer.Kind="workspace-response";return workspace?.Handle(document.Descriptor,message,answer)??Reject(answer,"workspace-unavailable");}
if(message.Kind.StartsWith("ai-",StringComparison.Ordinal))return ai?.Handle(document.Descriptor,message,answer)??Reject(answer,"ai-unavailable");
switch (message.Kind)
{
@ -97,7 +101,7 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai
case "active": word.ActiveSession = message.SessionId; break;
case "selection":
if (message.Start < 0 || message.End < message.Start) return Reject(answer,"invalid-position");
document.Cursor = message.Start; Resolve(document, answer); break;
document.Cursor = message.Start; Resolve(document, answer);workspace?.Position(message.SessionId,answer.ChapterId,answer.SceneId);break;
case "snapshot-begin":
if (message.SnapshotId == Guid.Empty || message.End < 0 || message.End > MaxSnapshotCharacters) return Reject(answer,"invalid-snapshot");
ClearPending(document);

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, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability }, stop.Token).ConfigureAwait(false);
await ExchangeAsync(pipe, new Message { Kind = "hello", WordInstanceId = instanceId, Capabilities=ProtocolVersion.Capabilities+","+ProtocolVersion.AnalysisCapability+","+ProtocolVersion.ChapterAiCapability+","+ProtocolVersion.WorkflowCapability }, 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,14 @@
using PlotDirector.Companion.Protocol;
namespace PlotDirector.Companion.Client;
public static class ConnectionPresentation
{
public static string Describe(string ipc,ConnectionHealth? health,int book,string workspace)
{
if(ipc!="connected")return "Word loaded · Local agent/IPC: "+ipc+" · Server/authentication: unverified";
if(health==null)return "Word loaded · Agent/IPC connected · Server/authentication: checking";
var server=health.VerifiedUtc==default||DateTime.UtcNow-health.VerifiedUtc>TimeSpan.FromSeconds(90)?(health.Server=="offline"?"offline":"unverified"):health.Server;
var authentication=server!="online"&&health.Authentication=="verified"?"cached grant; check connection":health.Authentication;
return "Agent/IPC connected · Server: "+server+" · Sign-in: "+authentication+" · Book: "+(book<=0?"not selected":server=="online"?workspace:"cached/unverified")+" · AI: "+health.Ai;
}
}

View File

@ -0,0 +1,33 @@
using PlotDirector.Companion.Protocol;
namespace PlotDirector.Companion.Client;
public sealed class DocumentBinding
{
public int BookId {get;private set;}
public Guid Id {get;private set;}
public Guid AuthenticationContext {get;private set;}
public SavedWorkspace Workspace {get;private set;}=new();
public Guid PendingPreview {get;private set;}
public void BeginPreview(Guid id){PendingPreview=id;Preview=new(){RequestId=id,State="loading",Message="Validating selected structure…"};}
public void CancelPreview(){PendingPreview=Guid.Empty;Preview=new(){State="cancelled",Message="Preview cancelled; nothing was imported."};}
public ImportPreview? Preview {get;private set;}
public void Select(int book,Guid authentication)
{BookId=book;AuthenticationContext=authentication;Id=Guid.NewGuid();Workspace=new(){BookId=book,State=book==0?"unselected":"loading"};Preview=null;PendingPreview=Guid.Empty;}
public void Reset()=>Select(0,Guid.Empty);
public bool Accept(Message response)
{
if(response.SnapshotId!=Id||response.AuthenticationContext!=AuthenticationContext||response.BookId!=BookId)return false;
if(response.Workspace!=null)Workspace=response.Workspace;
if(response.ImportPreview!=null&&response.ImportPreview.RequestId==PendingPreview&&PendingPreview!=Guid.Empty)Preview=response.ImportPreview;return true;
}
}
public sealed class StructureSelection
{
private readonly Dictionary<string,StructureSuggestion> rows=new();
public static string Key(StructureSuggestion item)=>item.Kind+":"+item.Start+(item.Kind=="Chapter"?"":":"+item.Origin);
public bool Contains(StructureSuggestion item)=>rows.ContainsKey(Key(item));
public bool Set(StructureSuggestion item,bool selected)
{var key=Key(item);if(!selected){rows.Remove(key);return true;}if(rows.Count>=80&&!rows.ContainsKey(key))return false;rows[key]=item;return true;}
public StructureSuggestion[] Items=>rows.Values.OrderBy(s=>s.Start).ThenBy(s=>s.Kind).ToArray();
public void Clear()=>rows.Clear();
}

View File

@ -1 +1 @@
<Project><PropertyGroup><ApplicationVersion>1.0.0.5</ApplicationVersion></PropertyGroup></Project>
<Project><PropertyGroup><ApplicationVersion>1.0.0.6</ApplicationVersion></PropertyGroup></Project>

View File

@ -5,6 +5,7 @@ namespace PlotDirector.Companion.Protocol;
public static class ProtocolVersion
{
public const int Current = 1;
public const string WorkflowCapability = "workspace-review-v1";
public const string ChapterAiCapability = "chapter-ai-v2";
public const string AnalysisCapability = "structure-review-v1";
public const int AnalysisPageSize = 40;
@ -43,6 +44,11 @@ public sealed class Message
[DataMember] public int? SceneId { get; set; }
[DataMember] public string ChapterTitle { get; set; } = "";
[DataMember] public string SceneTitle { get; set; } = "";
[DataMember] public ConnectionHealth? Health {get;set;}
[DataMember] public SavedWorkspace? Workspace {get;set;}
[DataMember] public ImportPreviewRequest? ImportSelection {get;set;}
[DataMember] public ImportPreview? ImportPreview {get;set;}
[DataMember] public string Action {get;set;}="";
[DataMember] public Guid AuthenticationContext { get; set; }
[DataMember] public string ServerUrl { get; set; } = "";
[DataMember] public AiChapterResult? Ai { get; set; }

View File

@ -0,0 +1,51 @@
using System.Runtime.Serialization;
namespace PlotDirector.Companion.Protocol;
[DataContract]
public sealed class ConnectionHealth
{
[DataMember] public string Server {get;set;}="unknown";
[DataMember] public string Authentication {get;set;}="signed-out";
[DataMember] public string Ai {get;set;}="unknown";
[DataMember] public string Explanation {get;set;}="Use Connect to sign in; local structure detection works offline.";
[DataMember] public DateTime VerifiedUtc {get;set;}
[DataMember] public DateTime ExpiresUtc {get;set;}
}
[DataContract]
public sealed class SavedWorkspace
{
[DataMember] public int BookId {get;set;}
[DataMember] public int ProjectId {get;set;}
[DataMember] public int? ChapterId {get;set;}
[DataMember] public int? SceneId {get;set;}
[DataMember] public string Title {get;set;}="";
[DataMember] public string Context {get;set;}="";
[DataMember] public string Intent {get;set;}="";
[DataMember] public string ContextPath {get;set;}="";
[DataMember] public string IntentPath {get;set;}="";
[DataMember] public string BookPath {get;set;}="";
[DataMember] public string State {get;set;}="unselected";
}
[DataContract]
public sealed class ImportPreviewRequest
{
[DataMember] public Guid RequestId {get;set;}
[DataMember] public Guid SessionId {get;set;}
[DataMember] public Guid SnapshotId {get;set;}
[DataMember] public Guid ManuscriptId {get;set;}
[DataMember] public int BookId {get;set;}
[DataMember] public StructureSuggestion[] Items {get;set;}=Array.Empty<StructureSuggestion>();
}
[DataContract]
public sealed class ImportPreview
{
[DataMember] public Guid RequestId {get;set;}
[DataMember] public string State {get;set;}="";
[DataMember] public string Message {get;set;}="";
[DataMember] public int Chapters {get;set;}
[DataMember] public int Scenes {get;set;}
[DataMember] public int ExistingChapters {get;set;}
[DataMember] public int ExistingScenes {get;set;}
[DataMember] public string BookPath {get;set;}="";
[DataMember] public bool CommitAvailable {get;set;}
}

View File

@ -1,3 +1,7 @@
# Current developer build: Phase 3.5
Version **1.0.0.6** adds per-document book binding, verified connection status, saved Context/Intent and read-only import preview. See [qualification](WindowsValidation/Phase35-Integration.md) and [implementation report](../Docs/WordCompanion/2026-11-05-phase35-integration.md). Native import commit and native live SignalR following remain unavailable.
# Native Word Companion — developer foundation, structure and AI review
Phase 3 adds explicit chapter-by-chapter AI review through the existing PlotDirector chapter service, browser-approved sign-in, a hierarchical native review and safe update/build plus explicit per-user installation scripts. See the [Phase 3 implementation report](../Docs/WordCompanion/2026-11-05-phase3-ai-integration.md) and [Windows workflow](WindowsValidation/Phase3-AI.md). The baseline implementation details below describe the foundation; Phase 3's native API does not provide prose synchronization or native Context/Intent/SignalR following.

View File

@ -70,6 +70,7 @@ internal static class ChapterAiTests
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellation)
{
var path=request.RequestUri!.AbsolutePath;
if(path.EndsWith("/connection"))return new(HttpStatusCode.OK){Content=JsonContent.Create(new ConnectionHealth{Server="online",Authentication="verified",Ai="configured",VerifiedUtc=DateTime.UtcNow,ExpiresUtc=DateTime.UtcNow.AddHours(4)})};
if(path.EndsWith("/pair"))return new(HttpStatusCode.OK){Content=JsonContent.Create(new{code=new string('A',24)})};
if(path.EndsWith("/token"))return new(HttpStatusCode.OK){Content=JsonContent.Create(new{accessToken="test-only-grant"})};
if(path.EndsWith("/books"))return new(HttpStatusCode.OK){Content=JsonContent.Create(new[]{new CompanionBook{BookId=11,Title="Synthetic test book"}})};

View File

@ -162,4 +162,5 @@ using(var stalledClient=new AgentLink(stalledName,Guid.NewGuid(),_=>true))
}
await AnalysisTests.Run(Check);
await ChapterAiTests.Run(Check);
await WorkflowTests.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,60 @@
using System.Net;
using System.Net.Http.Json;
using PlotDirector.Companion.Agent;
using PlotDirector.Companion.Client;
using PlotDirector.Companion.Protocol;
internal static class WorkflowTests
{
public static async Task Run(Action<bool,string> check)
{
var health=new ConnectionHealth{Server="online",Authentication="verified",Ai="configured",VerifiedUtc=DateTime.UtcNow.AddMinutes(-3)};
check(ConnectionPresentation.Describe("connected",health,11,"saved-book").Contains("unverified")&&ConnectionPresentation.Describe("connected",health,11,"saved-book").Contains("cached grant"),"expired verification never presents cached sign-in/book as live");
check(ConnectionPresentation.Describe("offline",health,11,"saved-book").Contains("Server/authentication: unverified"),"IPC outage overrides previously successful server state");
var binding=new DocumentBinding();var auth=Guid.NewGuid();binding.Select(11,auth);var old=binding.Id;binding.Select(12,auth);
check(!binding.Accept(new(){SnapshotId=old,AuthenticationContext=auth,BookId=11,Workspace=new(){Title="old"}})&&binding.Workspace.Title=="","book switch rejects late saved data");
var requestId=Guid.NewGuid();binding.BeginPreview(requestId);binding.CancelPreview();binding.Accept(new(){SnapshotId=binding.Id,AuthenticationContext=auth,BookId=12,ImportPreview=new(){RequestId=requestId,State="validated-preview"}});
check(binding.Preview?.State=="cancelled","late successful response cannot revive a cancelled client preview");
var selection=new StructureSelection();var parent=new StructureSuggestion{Kind="Chapter",Start=0,Origin="Existing marker"};selection.Set(parent,true);selection.Set(new(){Kind="Chapter",Start=0,Origin="Local structure"},true);
check(selection.Items.Length==1,"one parent chapter is retained across local and AI pages");
for(var i=1;i<80;i++)selection.Set(new(){Kind="Scene",Start=i,Origin="AI"},true);
check(!selection.Set(new(){Kind="Scene",Start=100,Origin="AI"},true)&&selection.Items.Length==80,"cross-page preview selection is bounded without silently dropping selected rows");
var handler=new Server();using var cloud=new CloudGateway(handler,_=>{});cloud.Connect("https://fixture.invalid/");await Wait(()=>cloud.Status().Status.StartsWith("Signed in"));await cloud.CheckConnection();
await Wait(()=>cloud.Status().Health?.Ai=="configured");var context=cloud.Status().AuthenticationContext;
var work=new DocumentWorkspaceWork(cloud);var one=new DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Revision=1};var two=new DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Revision=1};
var first=Guid.NewGuid();var second=Guid.NewGuid();
Message Send(DocumentDescriptor d,string kind,int book,Guid id,ImportPreviewRequest? plan=null)=>work.Handle(d,new(){Kind=kind,BookId=book,SnapshotId=id,AuthenticationContext=context,ImportSelection=plan},new(){Status="ok",SnapshotId=id});
Send(one,"workspace-select",11,first);Send(two,"workspace-select",12,second);
await Wait(()=>Send(one,"workspace-status",11,first).Workspace?.State=="saved-book"&&Send(two,"workspace-status",12,second).Workspace?.State=="saved-book");
check(Send(one,"workspace-status",11,first).Workspace?.BookId==11&&Send(two,"workspace-status",12,second).Workspace?.BookId==12,"multiple document saved contexts remain isolated");
var replacement=Guid.NewGuid();Send(one,"workspace-select",12,replacement);
check(Send(one,"workspace-status",11,first).Status=="obsolete-workspace","older workspace binding cannot fetch or overwrite a replacement");
Send(one,"workspace-preview",12,replacement,new(){BookId=12,SessionId=one.SessionId,SnapshotId=Guid.NewGuid(),RequestId=Guid.NewGuid(),Items=[new(){Kind="Chapter",Title="Chapter",Start=0,End=10}]});
await Wait(()=>Send(one,"workspace-status",12,replacement).ImportPreview!=null);
Send(one,"workspace-cancel-preview",12,replacement);await Task.Delay(100);
check(Send(one,"workspace-status",12,replacement).ImportPreview==null,"cancelled import preview cannot reappear after delayed completion");
handler.Offline=true;await cloud.CheckConnection();check(cloud.Status().Health?.Server=="offline","server loss clears a previously verified online indicator");
handler.Offline=false;await cloud.CheckConnection();check(cloud.Status().Health?.Server=="online","explicit connection check detects recovery");
handler.Expired=true;await cloud.CheckConnection();check(cloud.Status().AuthenticationContext!=context&&cloud.Status().Health?.Authentication=="expired","authentication expiry rotates scope and removes verified authentication");
check(Send(two,"workspace-status",12,second).Status=="authentication-changed","expired credentials cannot display an old authenticated workspace");
work.Clear(one.SessionId);work.Clear(two.SessionId);
}
private static async Task Wait(Func<bool> ready){using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(12));while(!ready())await Task.Delay(20,timeout.Token);}
private sealed class Server:HttpMessageHandler
{
public bool Offline,Expired;
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken token)
{
if(Offline)throw new HttpRequestException();var path=request.RequestUri!.AbsolutePath;
if(path.EndsWith("/pair"))return Ok(new{code=new string('A',24)});
if(path.EndsWith("/token"))return Ok(new{accessToken="test"});
if(Expired)return new(HttpStatusCode.Unauthorized);
if(path.EndsWith("/books"))return Ok(new[]{new CompanionBook{BookId=11,Title="One"},new CompanionBook{BookId=12,Title="Two"}});
if(path.EndsWith("/connection"))return Ok(new ConnectionHealth{Server="online",Authentication="verified",Ai="configured",VerifiedUtc=DateTime.UtcNow,ExpiresUtc=DateTime.UtcNow.AddHours(4)});
if(path.EndsWith("/workspace")){var id=int.Parse(path.Split('/')[4]);return Ok(new SavedWorkspace{BookId=id,State="saved-book",Title="Saved book "+id,Context="Saved context",Intent="Saved goals"});}
if(path.EndsWith("/import-preview")){await Task.Delay(80,token);return Ok(new ImportPreview{State="validated-preview",CommitAvailable=false});}
return new(HttpStatusCode.NotFound);
}
private static HttpResponseMessage Ok<T>(T value)=>new(HttpStatusCode.OK){Content=JsonContent.Create(value)};
}
}

View File

@ -14,16 +14,26 @@ namespace PlotDirector.WordAddIn
private readonly Label status=new Label{AutoSize=true,MaximumSize=new Size(1100,0),Margin=new Padding(8)};
private readonly ProgressBar progress=new ProgressBar{Dock=DockStyle.Fill,Height=6,Maximum=100};
private readonly TreeView local=new TreeView{Dock=DockStyle.Fill,CheckBoxes=true,HideSelection=false,ShowNodeToolTips=true};
private readonly TreeView ai=new TreeView{Dock=DockStyle.Fill,HideSelection=false,ShowNodeToolTips=true};
private readonly TreeView ai=new TreeView{CheckBoxes=true,Dock=DockStyle.Fill,HideSelection=false,ShowNodeToolTips=true};
private readonly TextBox details=new TextBox{Dock=DockStyle.Fill,Multiline=true,ReadOnly=true,ScrollBars=ScrollBars.Vertical};
private readonly ComboBox books=new ComboBox{DropDownStyle=ComboBoxStyle.DropDownList,Width=300,DisplayMember="Title",ValueMember="BookId"};
private readonly Label pages=new Label{AutoSize=true,Margin=new Padding(8)};
private readonly Button cancel=new Button{Text="Cancel",AutoSize=true};
private readonly Button next=new Button{Text="Next",AutoSize=true},previous=new Button{Text="Previous",AutoSize=true};
private readonly TabControl tabs=new TabControl{Dock=DockStyle.Fill};
private bool rebinding;
private readonly Dictionary<Guid,Guid> selectionSnapshots=new Dictionary<Guid,Guid>();
private readonly Dictionary<Guid,StructureSelection> choices=new Dictionary<Guid,StructureSelection>();
private StructureSelection selection=new StructureSelection();
private readonly TextBox savedContext=new TextBox{Dock=DockStyle.Fill,Multiline=true,ReadOnly=true,ScrollBars=ScrollBars.Vertical};
private readonly TextBox savedIntent=new TextBox{Dock=DockStyle.Fill,Multiline=true,ReadOnly=true,ScrollBars=ScrollBars.Vertical};
private readonly TextBox previewText=new TextBox{Dock=DockStyle.Fill,Multiline=true,ReadOnly=true,ScrollBars=ScrollBars.Vertical};
private readonly Button ask=new Button{Text="AI: analyse checked chapters",AutoSize=true};
private readonly Button previewButton=new Button{Text="Preview selected import",AutoSize=true};
private readonly Button openContext=new Button{Text="Open full saved Context",AutoSize=true},openIntent=new Button{Text="Open saved Intent",AutoSize=true},openBook=new Button{Text="Continue in PlotDirector",AutoSize=true};
private int aiOffset;private Guid session,authenticationContext,localSnapshot;private string renderKey="";private string bookKey="";private string aiRenderKey="";
private IList<StructureSuggestion> aiItems=new List<StructureSuggestion>();
public AnalysisWindow(Action analyse,Action stop,Action<int> page,Action<AiConsent> submit,Action<StructureSuggestion> navigate)
public AnalysisWindow(Action analyse,Action stop,Action<int> page,Action<AiConsent> submit,Action<StructureSuggestion> navigate,Action<int> selectBook,Action<AiConsent> previewImport,Action<string> open,Action checkConnection)
{
Text="PlotDirector — Manuscript review";Font=new Font("Segoe UI",9F);AutoScaleMode=AutoScaleMode.Dpi;MinimumSize=new Size(680,480);Width=980;Height=680;ShowInTaskbar=false;
status.MaximumSize=new Size(Math.Max(400,ClientSize.Width-40),0);
@ -33,18 +43,33 @@ namespace PlotDirector.WordAddIn
layout.RowStyles.Add(new RowStyle(SizeType.Percent,70));layout.RowStyles.Add(new RowStyle(SizeType.Percent,30));layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
var actions=new FlowLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,WrapContents=true,Padding=new Padding(0,6,0,6)};
var repeat=new Button{Text="Detect structure",AutoSize=true};repeat.Click+=(_,__)=>analyse();
var ask=new Button{Text="AI: analyse checked chapters",AutoSize=true};ask.Click+=(_,__)=>{
var chosen=local.Nodes.Cast<TreeNode>().Where(n=>n.Checked&&n.Tag is StructureSuggestion).Select(n=>(StructureSuggestion)n.Tag).ToArray();
ask.Click+=(_,__)=>{
var chosen=selection.Items.Where(item=>item.Kind=="Chapter").ToArray();
if(chosen.Length==0){MessageBox.Show("Check one or more chapter nodes in Local structure first.","PlotDirector");return;}
var consent=new AiConsent{SessionId=session,SnapshotId=localSnapshot,AuthenticationContext=authenticationContext,BookId=SelectedBook,Chapters=chosen};
if(consent.BookId<=0){MessageBox.Show("Connect, then select an authorised PlotDirector book.","PlotDirector");return;}
if(MessageBox.Show("Send "+chosen.Length+" selected chapter(s) for book "+(books.SelectedItem as CompanionBook)?.Title+" to PlotDirector's configured AI provider? This may incur AI costs. Existing markers and manuscript text will not change.","Confirm chapter upload",MessageBoxButtons.OKCancel)==DialogResult.OK)submit(consent);
};
cancel.Click+=(_,__)=>stop();actions.Controls.AddRange(new Control[]{repeat,books,ask,cancel});
var localTab=new TabPage("Local structure");localTab.Controls.Add(local);var aiTab=new TabPage("AI scene suggestions");aiTab.Controls.Add(ai);tabs.TabPages.AddRange(new[]{localTab,aiTab});
cancel.Click+=(_,__)=>{if(tabs.SelectedIndex==4)previewText.Text="Preview cancelled; no records changed.";stop();};
books.SelectedIndexChanged+=(_,__)=>{if(!rebinding){selectBook(SelectedBook);previewText.Clear();}};
var check=new Button{Text="Check connection",AutoSize=true};check.Click+=(_,__)=>checkConnection();
previewButton.Click+=(_,__)=>{
var chosen=selection.Items;if(chosen.Length==0){details.Text="Check chapter and scene rows to preview. Parent chapters are required; choose one local/AI interpretation at each position.";return;}
var consent=new AiConsent{SessionId=session,SnapshotId=localSnapshot,AuthenticationContext=authenticationContext,BookId=SelectedBook,Chapters=chosen};
if(MessageBox.Show("Send selected titles and structural positions to PlotDirector for a read-only import preview? No prose is uploaded and nothing is committed.","Preview import",MessageBoxButtons.OKCancel)==DialogResult.OK){previewImport(consent);tabs.SelectedIndex=4;previewText.Text="Preparing a read-only server preview…";}
};
var clear=new Button{Text="Clear selection",AutoSize=true};clear.Click+=(_,__)=>{selection.Clear();rebinding=true;foreach(TreeNode node in local.Nodes){node.Checked=false;foreach(TreeNode child in node.Nodes)child.Checked=false;}foreach(TreeNode node in ai.Nodes){node.Checked=false;foreach(TreeNode child in node.Nodes)child.Checked=false;}rebinding=false;};
actions.Controls.AddRange(new Control[]{repeat,books,ask,previewButton,clear,cancel,check});
var localTab=new TabPage("Local structure");localTab.Controls.Add(local);var aiTab=new TabPage("AI scene suggestions");aiTab.Controls.Add(ai);var contextTab=new TabPage("Context · saved data");var intentTab=new TabPage("Intent · saved objectives");var importTab=new TabPage("Import preview");
contextTab.Controls.Add(savedContext);openContext.Dock=DockStyle.Bottom;contextTab.Controls.Add(openContext);
intentTab.Controls.Add(savedIntent);openIntent.Dock=DockStyle.Bottom;intentTab.Controls.Add(openIntent);
importTab.Controls.Add(previewText);openBook.Dock=DockStyle.Bottom;importTab.Controls.Add(openBook);
openContext.Click+=(_,__)=>open("context");openIntent.Click+=(_,__)=>open("intent");openBook.Click+=(_,__)=>open("book");
tabs.TabPages.AddRange(new[]{localTab,aiTab,contextTab,intentTab,importTab});
local.AfterCheck+=Checked;ai.AfterCheck+=Checked;
var footer=new FlowLayoutPanel{Dock=DockStyle.Fill,AutoSize=true};footer.Controls.AddRange(new Control[]{previous,next,pages});
previous.Click+=(_,__)=>{if(tabs.SelectedIndex==0)page(-1);else{aiOffset=Math.Max(0,aiOffset-40);RenderAi();}};
next.Click+=(_,__)=>{if(tabs.SelectedIndex==0)page(1);else{aiOffset+=40;RenderAi();}};
previous.Click+=(_,__)=>{if(tabs.SelectedIndex==0)page(-1);else if(tabs.SelectedIndex==1){aiOffset=Math.Max(0,aiOffset-40);RenderAi();}};
next.Click+=(_,__)=>{if(tabs.SelectedIndex==0)page(1);else if(tabs.SelectedIndex==1){aiOffset+=40;RenderAi();}};
tabs.SelectedIndexChanged+=(_,__)=>{details.Text="Select a result to inspect its source and reasoning.";if(tabs.SelectedIndex==1)RenderAi();else UpdatePages();};
local.AfterSelect+=(_,e)=>Inspect(e.Node);ai.AfterSelect+=(_,e)=>Inspect(e.Node);
local.NodeMouseDoubleClick+=(_,e)=>{if(e.Node.Tag is StructureSuggestion item)navigate(item);};
@ -52,19 +77,32 @@ namespace PlotDirector.WordAddIn
layout.Controls.Add(status,0,0);layout.Controls.Add(progress,0,1);layout.Controls.Add(actions,0,2);layout.Controls.Add(tabs,0,3);layout.Controls.Add(details,0,4);layout.Controls.Add(footer,0,5);Controls.Add(layout);
Resize+=(_,__)=>status.MaximumSize=new Size(Math.Max(400,ClientSize.Width-40),0);
}
public void ForgetBookSelection(){books.SelectedIndex=-1;}
public void ForgetBookSelection(){rebinding=true;try{books.SelectedIndex=-1;}finally{rebinding=false;}}
public int SelectedBook=>books.SelectedItem is CompanionBook book?book.BookId:0;
private AnalysisPage current;
public void Render(AnalysisReview review,string connection,Guid document,string documentName,Guid authentication,CompanionBook[] available,string cloud,string aiStatus,IList<StructureSuggestion> results,bool running)
public void Render(AnalysisReview review,string connection,Guid document,string documentName,Guid authentication,CompanionBook[] available,string cloud,string aiStatus,IList<StructureSuggestion> results,bool running,DocumentBinding binding,ConnectionHealth health,bool workflowSupported)
{
if(session!=document){session=document;renderKey="";aiRenderKey="";books.SelectedIndex=-1;aiOffset=0;local.Nodes.Clear();ai.Nodes.Clear();details.Clear();}
if(session!=document){session=document;renderKey="";aiRenderKey="";ForgetBookSelection();aiOffset=0;local.Nodes.Clear();ai.Nodes.Clear();details.Clear();}
if(!choices.TryGetValue(document,out selection)){if(choices.Count>=32){choices.Clear();selectionSnapshots.Clear();}selection=new StructureSelection();choices[document]=selection;}
var snapshot=review?.SnapshotId??Guid.Empty;if(selectionSnapshots.TryGetValue(document,out var previousSnapshot)&&previousSnapshot!=snapshot)selection.Clear();selectionSnapshots[document]=snapshot;
authenticationContext=authentication;localSnapshot=review?.SnapshotId??Guid.Empty;
current=review?.Page;aiItems=results??new List<StructureSuggestion>();
status.Text=(documentName??"No active document")+" · Agent: "+connection+" · "+cloud+"\n"+(string.IsNullOrEmpty(aiStatus)?review?.Status:aiStatus);
status.Text=(documentName??"No active document")+" · Agent: "+connection+" · "+cloud+"\n"+(review?.Running==true?review.Status:string.IsNullOrEmpty(aiStatus)?review?.Status:aiStatus);
if(current!=null)status.Text+="\n"+current.WordCount.ToString("N0")+" approximate words · "+current.ChapterCount+" local chapter candidates · "+current.SceneCount+" local scene candidates. "+(current.Truncated?"Result limit reached. ":"")+"Double-click to navigate; select to inspect evidence.";
progress.Value=review?.Progress??0;cancel.Enabled=running||review?.Running==true;
progress.Value=review?.Progress??0;cancel.Enabled=running||review?.Running==true||binding?.Preview?.State=="loading";
var workspace=binding?.Workspace;
var verified=workspace?.State?.StartsWith("saved-",StringComparison.Ordinal)==true;
savedContext.Text=(workspace?.Title??"No book selected")+"\r\nSaved PlotDirector data · read-only · "+(workspace?.State??"unselected")+"\r\n\r\n"+(string.IsNullOrWhiteSpace(workspace?.Context)?"No saved context for this location. Select a book; recognised saved chapter/scene markers are verified against that book. Local/AI suggestions do not create saved context.":workspace.Context);
savedIntent.Text=(workspace?.Title??"No book selected")+"\r\nSaved writing objectives · read-only · "+(workspace?.State??"unselected")+"\r\n\r\n"+(string.IsNullOrWhiteSpace(workspace?.Intent)?"No saved writing objective at this location. Set chapter goals or scene purpose in PlotDirector; no intent is invented or silently saved here.":workspace.Intent);
openContext.Enabled=verified&&!string.IsNullOrEmpty(workspace.ContextPath);openIntent.Enabled=verified&&!string.IsNullOrEmpty(workspace.IntentPath);openBook.Enabled=verified;
var plan=binding?.Preview;
if(plan!=null)previewText.Text=plan.State+"\r\nSelected: "+plan.Chapters+" chapters / "+plan.Scenes+" scenes\r\nAlready saved: "+plan.ExistingChapters+" chapters / "+plan.ExistingScenes+" scenes\r\n\r\n"+plan.Message+"\r\n\r\nCreated: 0. Replaced: 0. Native commit is unavailable; use the established PlotDirector workflow.";
else previewText.Text="Select chapter and scene rows, then Preview selected import. This validates the target through PlotDirector's existing importer. Native commit is unavailable; selections are not silently transferred to onboarding.";
var fresh=health!=null&&DateTime.UtcNow-health.VerifiedUtc<TimeSpan.FromSeconds(90)&&health.Authentication=="verified"&&health.Server=="online";
ask.Enabled=fresh&&verified&&!running&&review?.Running!=true&&review?.Page!=null&&(health.Ai=="configured"||health.Ai=="last-request-succeeded");
previewButton.Enabled=workflowSupported&&fresh&&verified&&!running&&review?.Running!=true&&plan?.State!="loading"&&review?.Page!=null;
var key=string.Join("|",available.Select(b=>b.BookId+":"+b.Title));
if(bookKey!=key){var selected=SelectedBook;bookKey=key;books.DataSource=available;books.SelectedIndex=-1;if(available.Any(b=>b.BookId==selected))books.SelectedValue=selected;}
rebinding=true;try{if(bookKey!=key){bookKey=key;books.DataSource=available;books.DropDownWidth=650;}var selected=binding?.BookId??0;if(available.Any(b=>b.BookId==selected))books.SelectedValue=selected;else books.SelectedIndex=-1;}finally{rebinding=false;}
var newKey=(review?.SnapshotId.ToString()??"")+":"+(current?.Offset??-1);
if(renderKey!=newKey){renderKey=newKey;details.Text="Select a result to inspect its source and reasoning.";Fill(local,current?.Items??Array.Empty<StructureSuggestion>());}
if(tabs.SelectedIndex==1)RenderAi();else UpdatePages();
@ -73,22 +111,29 @@ namespace PlotDirector.WordAddIn
{if(node.Tag is StructureSuggestion item)details.Text=item.Title+Environment.NewLine+item.Origin+" · "+item.Confidence+Environment.NewLine+item.Reason+Environment.NewLine+"Word position "+item.Start+". Double-click to navigate without changing text.";}
private void Fill(TreeView tree,IEnumerable<StructureSuggestion> values)
{
tree.BeginUpdate();try{tree.Nodes.Clear();var parents=new Dictionary<int,TreeNode>();
rebinding=true;tree.BeginUpdate();try{tree.Nodes.Clear();var parents=new Dictionary<int,TreeNode>();
foreach(var item in values)
{
var chapterStart=item.Kind=="Chapter"?item.Start:item.ChapterStart;
if(!parents.TryGetValue(chapterStart,out var parent))
{
var chapter=item.Kind=="Chapter"?item:new StructureSuggestion{Kind="Chapter",Start=chapterStart,End=item.ChapterEnd,Title=string.IsNullOrEmpty(item.ChapterTitle)?"Before first chapter / unassigned":item.ChapterTitle,Origin="Local structure",Reason="Chapter context for this results page."};
parent=new TreeNode("Chapter · "+chapter.Title){Tag=chapterStart>=0?(object)chapter:null,ToolTipText=chapter.Title};parents.Add(chapterStart,parent);tree.Nodes.Add(parent);
parent=new TreeNode("Chapter · "+chapter.Title){Checked=selection.Contains(chapter),Tag=chapterStart>=0?(object)chapter:null,ToolTipText=chapter.Title};parents.Add(chapterStart,parent);tree.Nodes.Add(parent);
}
if(item.Kind!="Chapter")parent.Nodes.Add(new TreeNode(item.Title+" ["+item.Origin+"]"){Tag=item,ToolTipText=item.Title});
if(item.Kind!="Chapter")parent.Nodes.Add(new TreeNode(item.Title+" ["+item.Origin+"]"){Checked=selection.Contains(item),Tag=item,ToolTipText=item.Title});
}
tree.ExpandAll();}finally{tree.EndUpdate();}
tree.ExpandAll();}finally{tree.EndUpdate();rebinding=false;}
}
private void RenderAi(){if(aiOffset>=aiItems.Count)aiOffset=0;var key=aiOffset+":"+aiItems.Count+":"+session+string.Join("|",aiItems.Skip(aiOffset).Take(40).Select(s=>s.Start+":"+s.Title+":"+s.Reason));if(aiRenderKey!=key){aiRenderKey=key;Fill(ai,aiItems.Skip(aiOffset).Take(40));}UpdatePages();}
private void Checked(object sender,TreeViewEventArgs args)
{
if(rebinding||!(args.Node.Tag is StructureSuggestion item))return;
if(!selection.Set(item,args.Node.Checked)){rebinding=true;args.Node.Checked=false;rebinding=false;details.Text="Preview selection is limited to 80 rows. Use smaller batches.";}
if(args.Action!=TreeViewAction.Unknown)foreach(TreeNode child in args.Node.Nodes)child.Checked=args.Node.Checked;
}
private void UpdatePages()
{
if(tabs.SelectedIndex>1){previous.Enabled=false;next.Enabled=false;pages.Text="Read-only saved data / preview; no automatic changes";return;}
var offset=tabs.SelectedIndex==0?(current?.Offset??0):aiOffset;var total=tabs.SelectedIndex==0?(current?.Total??0):aiItems.Count;
pages.Text=total==0?"No results":"Showing "+(offset+1)+"–"+Math.Min(total,offset+40)+" of "+total;
previous.Enabled=offset>0;next.Enabled=offset+40<total;

View File

@ -1,5 +1,6 @@
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
@ -17,12 +18,14 @@ namespace PlotDirector.WordAddIn
{ using (var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("PlotDirector.WordAddIn.Ribbon.xml"))) return reader.ReadToEnd(); }
public void OnLoad(Office.IRibbonUI ribbonUI) { ui = ribbonUI; }
public void Invalidate() { try { ui?.Invalidate(); } catch(COMException) { } }
public string GetStatus(Office.IRibbonControl _) => "Agent: " + (getAdapter()?.ConnectionState ?? "Unavailable")+" · "+(getAdapter()?.CloudState??"Not signed in");
public bool CanSynchronize(Office.IRibbonControl _) => getAdapter()?.HasActiveDocument == true;
public string GetStatus(Office.IRibbonControl _) => string.Join(" · ",(getAdapter()?.StatusSummary??"Word add-in unavailable").Split('·').Take(3));
public string GetScopeStatus(Office.IRibbonControl _) => string.Join(" · ",(getAdapter()?.StatusSummary??"").Split('·').Skip(3));
public bool CanSynchronize(Office.IRibbonControl _) => getAdapter()?.HasActiveDocument == true&&getAdapter()?.ConnectionState=="connected";
public bool CanCancel(Office.IRibbonControl _) => getAdapter()?.HasActiveWork==true;
public void Connect(Office.IRibbonControl _) { var adapter=getAdapter();if(adapter!=null)new ConnectWindow(adapter).Show(); }
public void Analyse(Office.IRibbonControl _) { getAdapter()?.AnalyseDocument(); }
public void Cancel(Office.IRibbonControl _) { getAdapter()?.CancelAnalysis(); }
public void Synchronize(Office.IRibbonControl _) { getAdapter()?.RequestSnapshot(); }
public void Synchronize(Office.IRibbonControl _) { getAdapter()?.AnalyseDocument(); }
public void Settings(Office.IRibbonControl _)
{
if (getAdapter() == null) return;

View File

@ -3,6 +3,6 @@ using System.Runtime.InteropServices;
[assembly: AssemblyTitle("PlotDirector Word Companion — Native development")]
[assembly: AssemblyCompany("Nick Beckley")]
[assembly: AssemblyProduct("PlotDirector")]
[assembly: AssemblyVersion("1.0.0.5")]
[assembly: AssemblyFileVersion("1.0.0.5")]
[assembly: AssemblyVersion("1.0.0.6")]
[assembly: AssemblyFileVersion("1.0.0.6")]
[assembly: ComVisible(false)]

View File

@ -2,10 +2,10 @@
<ribbon><tabs><tab id="PlotDirectorTab" label="PlotDirector">
<group id="PlotDirectorConnection" label="Word Companion">
<labelControl id="PlotDirectorStatus" getLabel="GetStatus" />
<labelControl id="PlotDirectorScopeStatus" getLabel="GetScopeStatus" />
<button id="PlotDirectorConnect" label="Connect / Sign In" imageMso="ConnectToExternalData" onAction="Connect" screentip="Reconnect local agent" supertip="Approve a short-lived native connection in your browser. No passwords are stored in Word." />
<button id="PlotDirectorAnalyse" label="Analyse" imageMso="ReviewShowMarkup" onAction="Analyse" getEnabled="CanSynchronize" supertip="Detect local structure, then explicitly select chapters for AI scene analysis. 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="PlotDirectorCancelAnalysis" label="Cancel Analysis" imageMso="CancelRequest" onAction="Cancel" getEnabled="CanCancel" />
<button id="PlotDirectorSettings" label="Settings" imageMso="PropertySheet" onAction="Settings" />
<button id="PlotDirectorDiagnostics" label="Diagnostics" imageMso="Info" onAction="Diagnostics" />
</group>

View File

@ -50,6 +50,8 @@ namespace PlotDirector.WordAddIn
private double lastBatchMs;
private AnalysisWindow analysisWindow;
private Guid cloudContext;
private ConnectionHealth cloudHealth;
private bool workflowSupported;
private string cloudState="Not signed in",serverUrl="";
private CompanionBook[] cloudBooks=Array.Empty<CompanionBook>();
private bool analysisSupported,cloudSupported;
@ -60,6 +62,7 @@ namespace PlotDirector.WordAddIn
private string lastResult = "Waiting for local structural snapshot";
public string ConnectionState { get; private set; } = "Connecting";
public bool HasActiveDocument => active != null;
public bool HasActiveWork => active!=null&&(active.Review.Running||active.AiJob!=Guid.Empty||active.Binding.Preview?.State=="loading");
public string Diagnostics => "PlotDirector by Nick Beckley — Phase 3\nAgent: " + ConnectionState
+ "\nServer: "+cloudState+" · Prose sync: unavailable\nOpen sessions: " + documents.Count
+ "\nIPC queued: " + link.QueueDepth + "\nWord work queued: " + scheduler.Depth
@ -77,9 +80,10 @@ namespace PlotDirector.WordAddIn
ConnectionState = state;
if(state!="connected")
{
analysisSupported=false;cloudSupported=false;
analysisSupported=false;cloudSupported=false;workflowSupported=false;
foreach(var doc in documents.Values){StopAi(doc,"Agent disconnected. Successful AI suggestions retained; reconnect before retrying.");scheduler.Cancel("analyse:"+doc.Session);if(doc.Review.Running||doc.Review.SnapshotId!=Guid.Empty)doc.Review.Stop("Agent disconnected. Reconnect and analyse again.");}
}
foreach(var doc in documents.Values)doc.Binding.Reset();
reviewDirty=true;
if (state == "connected")
{
@ -90,8 +94,10 @@ namespace PlotDirector.WordAddIn
});
link.Received += message => {
if(message.Kind=="cloud-status")
{PostToUi(()=>{if(cloudContext!=message.AuthenticationContext){foreach(var doc in documents.Values)if(doc.AiJob!=Guid.Empty||doc.AiQueue.Count>0)StopAi(doc,"Connection/account changed. Review and confirm chapters again.");analysisWindow?.ForgetBookSelection();}cloudContext=message.AuthenticationContext;cloudState=message.Status;cloudBooks=message.Books;serverUrl=message.ServerUrl;reviewDirty=true;});return;}
if(message.Status=="ready")PostToUi(()=>{analysisSupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.AnalysisCapability);cloudSupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterAiCapability);});
{PostToUi(()=>{if(cloudContext!=message.AuthenticationContext){foreach(var doc in documents.Values)if(doc.AiJob!=Guid.Empty||doc.AiQueue.Count>0)StopAi(doc,"Connection/account changed. Review and confirm chapters again.");analysisWindow?.ForgetBookSelection();}if(cloudContext!=message.AuthenticationContext)foreach(var doc in documents.Values)doc.Binding.Reset();cloudContext=message.AuthenticationContext;cloudHealth=message.Health;cloudState=message.Status;cloudBooks=message.Books;serverUrl=message.ServerUrl;reviewDirty=true;invalidateRibbon();});return;}
if(message.Status=="ready")PostToUi(()=>{analysisSupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.AnalysisCapability);cloudSupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.ChapterAiCapability);workflowSupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.WorkflowCapability);});
if(message.Kind=="workspace-response")
{PostToUi(()=>{var doc=documents.Values.FirstOrDefault(d=>d.Session==message.SessionId&&d.Revision==message.Revision);if(doc!=null){if(message.Status=="authentication-changed")doc.Binding.Reset();else doc.Binding.Accept(message);reviewDirty=true;invalidateRibbon();}});return;}
// 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)
@ -183,7 +189,7 @@ namespace PlotDirector.WordAddIn
state.ProjectId = ReadPositiveProperty(document,"PlotDirector.Native.ProjectID");
state.BookId = ReadPositiveProperty(document,"PlotDirector.Native.BookID");
state.End = DocumentEnd(document); state.WasSaved = Com(() => document.Saved);
documents.Add(document,state); link.Register(Descriptor(state));
documents.Add(document,state); RegisterState(state);
ScheduleSelection();
})) pendingOpen.Remove(document);
}
@ -213,7 +219,7 @@ namespace PlotDirector.WordAddIn
StopAi(state,"Document changed. Detect structure again before AI analysis.");state.AiResults.Clear();
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));
CancelExtraction(state); RegisterState(state);
}
state.WasSaved = saved;
if(active!=state)reviewDirty=true;
@ -239,7 +245,7 @@ namespace PlotDirector.WordAddIn
{
if(active==null)return;
if(analysisWindow==null||analysisWindow.IsDisposed)
analysisWindow=new AnalysisWindow(()=>StartAnalysis(true),CancelAnalysis,RequestAnalysisPage,StartAi,Navigate);
analysisWindow=new AnalysisWindow(()=>StartAnalysis(true),CancelAnalysis,RequestAnalysisPage,StartAi,Navigate,SelectBook,PreviewImport,OpenWorkspace,CheckConnection);
analysisWindow.Show();analysisWindow.BringToFront();
if(active.Review.Page==null&&!active.Review.Running)StartAnalysis(false);
RenderReview();
@ -250,17 +256,18 @@ namespace PlotDirector.WordAddIn
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;}
StopAi(doc,"Detecting updated local structure.");doc.AiResults.Clear();CancelExtraction(doc);doc.Review.Prepare(doc.Session);reviewDirty=true;
StopAi(doc,"Detecting updated local structure.");doc.AiStatus=null;doc.AiResults.Clear();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();
RegisterState(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;
if(doc.Binding.Preview?.State=="loading"){doc.Binding.CancelPreview();reviewDirty=true;WorkspacePost(doc,"workspace-cancel-preview");return;}
if(doc.AiJob!=Guid.Empty||doc.AiQueue.Count>0){StopAi(doc,"AI analysis cancelled. Successful chapter results retained.");RenderReview();return;}
scheduler.Cancel("analyse:"+doc.Session);CancelExtraction(doc);doc.NeedsSnapshot=false;
doc.Review.Stop("Analysis cancelled. Nothing was imported or changed.");RenderReview();
@ -275,7 +282,7 @@ namespace PlotDirector.WordAddIn
lastResult="Agent queue busy. Try the results page again.";
}
private void RenderReview()
{if(analysisWindow!=null&&!analysisWindow.IsDisposed)analysisWindow.Render(active?.Review,ConnectionState,active?.Session??Guid.Empty,active?.DisplayName,cloudContext,cloudBooks,cloudState,active?.AiStatus,active?.AiResults,active!=null&&active.AiJob!=Guid.Empty);reviewDirty=false;}
{if(analysisWindow!=null&&!analysisWindow.IsDisposed)analysisWindow.Render(active?.Review,ConnectionState,active?.Session??Guid.Empty,active?.DisplayName,cloudContext,cloudBooks,StatusSummary,active?.AiStatus,active?.AiResults,active!=null&&active.AiJob!=Guid.Empty,active?.Binding,cloudHealth,workflowSupported);reviewDirty=false;}
public void RequestSnapshot()
{
if (active == null) return;
@ -284,7 +291,7 @@ namespace PlotDirector.WordAddIn
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);
RegisterState(active); ScheduleSnapshot(active);
}
private void ScheduleSnapshot(LocalDocument doc,bool analyse=false)
{
@ -428,7 +435,7 @@ 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)){StopAi(state,"Save or close interrupted AI analysis. Successful results retained.");scheduler.Cancel("analyse:"+state.Session);CancelExtraction(state);state.NeedsSnapshot=true;state.Review.Stop("Document saved or saving. Analyse again to refresh suggestions.");reviewDirty=true;}
if(documents.TryGetValue(document,out var state)){StopAi(state,"Save or close interrupted AI analysis. Successful results retained.");scheduler.Cancel("analyse:"+state.Session);CancelExtraction(state);state.NeedsSnapshot=true;state.Review.Stop("Document saved or saving. Analyse again to refresh suggestions.");state.Binding.CancelPreview();WorkspacePost(state,"workspace-cancel-preview");reviewDirty=true;}
}
private void BeforeClose(Word.Document document,ref bool cancel)
{
@ -477,6 +484,7 @@ namespace PlotDirector.WordAddIn
{
metricClock.Restart();
if(cloudSupported)link.TryPost(new Message{Kind="cloud-status"});
foreach(var doc in documents.Values)if(doc.Binding.BookId>0)WorkspacePost(doc,"workspace-status");
foreach(var doc in documents.Values)if(doc.AiJob!=Guid.Empty&&doc.Extraction==null)
link.TryPost(new Message{Kind="ai-status",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.AiJob,Start=doc.AiOffset});
link.TryPost(new Message{Kind="metrics",SessionId=active.Session,Revision=active.Revision,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth});
@ -486,7 +494,35 @@ namespace PlotDirector.WordAddIn
{foreach(var doc in documents.Values)if(doc.AiJob!=Guid.Empty||doc.AiQueue.Count>0)StopAi(doc,"Connecting a different account/site. Confirm chapters again.");if(!cloudSupported){MessageBox.Show("Connect the matching Phase 3 agent first.","PlotDirector");return;}link.TryPost(new Message{Kind="cloud-connect",ServerUrl=address});}
public string ServerUrl=>serverUrl;
public string CloudState=>cloudState;
public string StatusSummary=>ConnectionPresentation.Describe(ConnectionState,cloudHealth,active?.Binding.BookId??0,active?.Binding.Workspace.State??"unselected");
public void CheckConnection(){if(cloudSupported)link.TryPost(new Message{Kind="cloud-check"});if(active?.Binding.BookId>0)WorkspacePost(active,"workspace-refresh");}
public void SignOut(){foreach(var doc in documents.Values)StopAi(doc,"Signed out. Successful results retained.");link.TryPost(new Message{Kind="cloud-signout"});}
private void RegisterState(LocalDocument doc)
{
var book=doc.Binding.BookId;link.Register(Descriptor(doc));
if(book>0){doc.Binding.Select(book,cloudContext);WorkspacePost(doc,"workspace-select");}
}
private void SelectBook(int book)
{
var doc=active;if(doc==null)return;
if(doc.Binding.BookId==book&&doc.Binding.AuthenticationContext==cloudContext)return;
StopAi(doc,"Book selection changed; confirm AI chapters again.");doc.AiStatus=null;
doc.Binding.Select(book,cloudContext);WorkspacePost(doc,"workspace-select");reviewDirty=true;invalidateRibbon();
}
private void WorkspacePost(LocalDocument doc,string kind,ImportPreviewRequest selection=null,string action="")
{
if(!workflowSupported)return;
var accepted=link.TryPost(new Message{Kind=kind,SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.Binding.Id,BookId=doc.Binding.BookId,AuthenticationContext=doc.Binding.AuthenticationContext,ImportSelection=selection,Action=action});
if(!accepted){lastResult="Local queue busy. Check connection/refresh and try again.";if(kind=="workspace-preview")doc.Binding.CancelPreview();}
}
private void PreviewImport(AiConsent consent)
{
var doc=active;if(doc==null||!consent.Matches(doc.Session,doc.Review.SnapshotId,cloudContext)||consent.BookId!=doc.Binding.BookId)return;
var id=Guid.NewGuid();doc.Binding.BeginPreview(id);WorkspacePost(doc,"workspace-preview",new ImportPreviewRequest{RequestId=id,BookId=consent.BookId,SessionId=doc.Session,SnapshotId=consent.SnapshotId,ManuscriptId=doc.Identity,Items=consent.Chapters.Select(s=>new StructureSuggestion{Kind=s.Kind,Title=s.Title,Start=s.Start,End=s.End,Origin=s.Origin}).ToArray()});
reviewDirty=true;
}
private void OpenWorkspace(string action)
{if(active!=null)WorkspacePost(active,"workspace-open",action:action);}
private void StartAi(AiConsent consent)
{
var doc=active;if(doc==null||doc.Review.Page==null||doc.Review.Running)return;
@ -565,7 +601,7 @@ namespace PlotDirector.WordAddIn
dynamic properties=doc.Document.CustomDocumentProperties;
try{properties.Add("PlotDirector.Native.DocumentGuid",false,Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString,doc.Identity.ToString("D"));}
finally{Release(properties);}
doc.IdentityPersisted=true;link.Register(Descriptor(doc));
doc.IdentityPersisted=true;RegisterState(doc);
});
}
// Future marker writes are explicitly scoped to a known document and exact range.
@ -631,6 +667,7 @@ namespace PlotDirector.WordAddIn
private sealed class LocalDocument
{
public readonly Word.Document Document;public readonly Guid Session=Guid.NewGuid();public Guid Identity;public bool IdentityPersisted;
public readonly DocumentBinding Binding=new DocumentBinding();
public string DisplayName;
public readonly AnalysisReview Review=new AnalysisReview();
public readonly Queue<StructureSuggestion> AiQueue=new Queue<StructureSuggestion>();

View File

@ -1,6 +1,8 @@
# Phase 3: update, build, install and test
Use only `codex/word-companion-native-phase1-20261104`. Phase 2's working developer installation `1.0.0.4` is preserved by preparation. The new developer build identifier is `1.0.0.5`; it is not Windows-qualified until the steps below pass.
For current integration behaviour and tonight’s checks, see [Phase 3.5 qualification](Phase35-Integration.md).
Use only `codex/word-companion-native-phase1-20261104`. Phase 2's working developer installation `1.0.0.4` is preserved by preparation. The new developer build identifier is `1.0.0.6`; it is not Windows-qualified until the steps below pass.
## Update and prepare (no installation)
@ -21,7 +23,7 @@ Thereafter the single update/build command is:
It checks the branch/clean worktree, fetches and fast-forwards, refuses unpublished/divergent local history, finds existing Office-equipped command-line MSBuild, builds managed Release, runs native/server authentication/HTTP tests, builds signed VSTO manifests without Office registration, publishes the .NET 10 win-x64 agent and verifies a complete hash-inventoried package. If the script itself changed on fetch it re-enters the updated script. It never launches Visual Studio or its installer, changes workloads/PATH/IDE settings, closes Word, registers the add-in or alters the current installation.
The package is placed in your Windows Downloads known folder under `PlotDirectorWordCompanion\1.0.0.5-<short SHA>`. A successful rerun verifies/reports the existing package rather than overwriting it. A failed preparation can leave a clearly named `.preparing-<GUID>` directory; it is not installed or reported as ready.
The package is placed in your Windows Downloads known folder under `PlotDirectorWordCompanion\1.0.0.6-<short SHA>`. A successful rerun verifies/reports the existing package rather than overwriting it. A failed preparation can leave a clearly named `.preparing-<GUID>` directory; it is not installed or reported as ready.
The helper first reuses a remembered certificate thumbprint, then tries the signing certificate in the existing per-user PlotDirector manifest, then a single valid current-user code-signing certificate. If selection is ambiguous, run once with `-CertificateThumbprint <existing certificate thumbprint>`; that nonsecret choice is remembered outside Git. It never creates/trusts a certificate or exports a private key. Missing prerequisites stop with diagnostics rather than invoking Visual Studio Installer/Repair. Office still validates the manifest signatures/trust on load.
@ -64,6 +66,6 @@ Test normal login/2FA, browser refusal, expiry/sign-out, authorised and unauthor
Then test the author's manuscript and synthetic 190k/250k fixtures: three documents, repeated text, short/long paragraphs, rapid switching, edits, save/close/cancelled close, agent termination/restart and partial chapter failure. Check 100/150/200% DPI, resizing, modeless focus, full-title/evidence inspection, expansion state and both paginated tabs. Record COM/batch/tick timing, typing/scroll/save/close responsiveness, CPU/memory and queue depth versus add-in-disabled trials.
The current observed-revision model does not detect every same-length edit in an already dirty document. Results describe a captured snapshot; re-detect after editing. Chapter upload has a 120,000 Word-position/text-character bound, at most 10,000 paragraphs and 500 returned AI scenes; split/review an oversized chapter rather than uploading a whole novel. Up to 256 explicitly selected chapters can queue in one document; AI results are capped at 5,000 rows/document. No semantic editing, server-to-Word prose writing or Context/Intent migration is implemented.
The current observed-revision model does not detect every same-length edit in an already dirty document. Results describe a captured snapshot; re-detect after editing. Chapter upload has a 120,000 Word-position/text-character bound, at most 10,000 paragraphs and 500 returned AI scenes; split/review an oversized chapter rather than uploading a whole novel. Up to 256 explicitly selected chapters can queue in one document; AI results are capped at 5,000 rows/document. No semantic editing or server-to-Word prose writing is implemented. Phase 3.5 adds read-only saved Context/Intent integration and metadata import preview; see its qualification guide.
Commit Windows fixes and qualification evidence to the same shared branch and push. Do not create a Windows feature branch or alter Production.

View File

@ -0,0 +1,27 @@
# Phase 3.5: integration qualification (developer version 1.0.0.6)
Use the existing [update/build and explicit install workflow](Phase3-AI.md). The branch and scripts are unchanged; preparation does not alter the installed add-in. No additional installer or Windows profile is needed.
```powershell
# In the existing clean repository on the shared branch:
git pull --ff-only origin codex/word-companion-native-phase1-20261104
& .\PlotDirector.NativeCompanion\WindowsValidation\Update-WordCompanion.ps1
# Close Word normally, then use the package path printed above:
& .\PlotDirector.NativeCompanion\WindowsValidation\Install-WordCompanion.ps1 -PackagePath '<printed package path>' -StopAgent
```
Do not install if update/build/tests/package verification fail. Existing rollback uses the same Install script with `-Rollback -StopAgent`. Neither script launches or repairs Visual Studio. Atlas has not built or run the Office host.
## Tonight's acceptance checks
1. Record Git SHA, version **1.0.0.6**, Office build/bitness and Windows scaling. Confirm ribbon has one Analyse action, separate connection/scope text and a useful disabled Cancel state. Open review; resize at 100/150/200% DPI. Check long titles, inspector, pagination, chapter collapse/expansion and no clipped actions.
2. Connect with the Development HTTPS site root and approve in the normal browser. Check connection explains server/auth/book/AI separately. AI `configured` means configuration/entitlement checked, not provider health. Use **Check connection** after failures or the 90-second verification freshness window. Automatic checks are rate-limited to two minutes; expiry is also enforced locally and by the server.
3. Open three manuscripts and select a different authorised book in each. Switch repeatedly. Book, Context, Intent, preview and selected rows must remain scoped to that document. Sign-out/agent restart must invalidate old authenticated data and require re-selection after sign-in.
4. **Detect structure** remains local and does not upload prose. Check chapter/scene rows across result pages. **AI: analyse checked chapters** uploads only explicitly confirmed chapters; source labels distinguish local/existing/AI. Double-click mapped suggestions; document prose must remain unchanged.
5. Context/Intent tabs show **saved PlotDirector** summaries/goals, not AI-generated state. Saved markers resolve only within the selected authorised book. No marker means book-level empty/summary state. Full browser Context/Intent opens a **pinned snapshot**, with manual navigation and no automatic save. Existing ordinary browser windows must continue following the legacy live Word connection independently.
6. Check a parent chapter and its desired scenes, then **Preview selected import**. This explicitly uploads metadata (titles/positions), not prose. It validates via the existing importer and reports selected/existing counts, conflicts and duplicate/overlap/orphan errors. **Created: 0, Replaced: 0** is intentional. Cancel during loading; late results must not restore the cancelled preview. Save/switch books during preview and verify stale results do not appear.
7. **Continue in PlotDirector** opens the selected book's existing workflow. Native choices are **not transferred**; native commit is unavailable. Do not treat this as a completed manuscript import. The canonical onboarding/import remains responsible for prose, persistent bindings, marker/save acknowledgement and resumable recovery.
8. Disconnect network, use Check connection, restore it and recheck. No stale green/authenticated claim should remain. Terminate/restart only the Companion agent; Word typing/scroll/save/close must keep working and other documents must never receive stale results.
9. Repeat with 190k/250k fixtures, repeated text, many short paragraphs, rapid cursor movement, continuous typing and save/close during pending extraction/AI. Use the existing [measurement procedure](README.md). Record timings/CPU/memory/queues; portable tests do not prove real Word responsiveness.
No native SignalR redesign, prose synchronisation, automatic imports or server-to-Word text writing is included. Results still describe a captured snapshot; the existing same-length-edit detection limitation requires explicit re-detection after editing. Cross-page selection is bounded to 80 rows for a preview batch, retained per document; split larger selections. Successful AI results remain reviewable after individual chapter failures.

View File

@ -1,3 +1,5 @@
Current developer version **1.0.0.6**: [Phase 3.5 integration checklist](Phase35-Integration.md). The original Phase 1 qualification below is historical; use the current checklist for implemented authentication, AI and saved workspace behaviour.
For current Phase 3 development, use [Phase3-AI.md](Phase3-AI.md). It provides a same-user, command-line update/build and explicit reversible per-user install workflow. A VM/separate profile, IDE launch or IDE repair is not required. The earlier disposable-profile guidance below is historical qualification advice, not a prerequisite for the authorised Phase 3 developer update.
# Windows / real Word validation gate

View File

@ -39,6 +39,7 @@ try {
Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotDirector.NativeCompanion/Tests/PlotDirector.Companion.Tests.csproj')
Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-companion')
Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-companion-http')
Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-workflow')
# The qualified command-line target bypasses Office registration/F5 while generating signed manifests.
Invoke-Checked $msbuild @('PlotDirector.NativeCompanion\Vsto\PlotDirector.WordAddIn.csproj','/restore','/t:Clean;Build;VisualStudioForApplicationsBuild','/p:Configuration=Release','/p:PrepareForRunDependsOn=CopyFilesToOutputDirectory','/p:SignManifests=true',"/p:ManifestCertificateThumbprint=$CertificateThumbprint","/p:ApplicationVersion=$version")
$bin=Join-Path $repo 'PlotDirector.NativeCompanion\Vsto\bin\Release'

View File

@ -41,6 +41,15 @@ const scripts=path.join(__dirname,'../../PlotLine/wwwroot/js');
}
console.log('PASS '+role+' actual browser delayed responses, abort, current-scene return, old failure and chapter identity');await page.close();
}
for(const mode of ['context','intent']){
const pinned=await browser.newPage();await pinned.goto('about:blank');await pinned.setContent('<main id="pinned" data-follow-mode="snapshot" data-scope-project-id="1" data-scope-book-id="2"><div id="content"><section id="fragment" data-scene-id="7">saved scene</section></div><div id="status"></div></main>');
await pinned.addScriptTag({content:'window.signalR={HubConnectionBuilder:class{constructor(){throw new Error("Pinned view must not connect SignalR")}}};window.PlotDirectorWritingWorkspace={registerWindow(){throw new Error("Pinned view must not register latest-window routing")},roles:{context:"Context",intent:"Intent"}};'});
await pinned.addScriptTag({content:fs.readFileSync(path.join(scripts,'writing-follow.js'),'utf8')});
await pinned.evaluate(mode=>PlotDirectorWritingFollow.initialize({rootSelector:'#pinned',contentSelector:'#content',fragmentSelector:'#fragment',statusTextSelector:'#status',tabSelector:'.tab',panelSelector:'.panel',selectSelector:'.select',defaultEndpoint:'/fragment',source:mode==='context'?'WritingContext':'WritingIntent'}),mode);
await pinned.evaluate(()=>document.dispatchEvent(new CustomEvent('plotdirector:story-position-changed',{detail:{projectId:1,bookId:2,sceneId:99}})));
assert.equal(await pinned.locator('#fragment').textContent(),'saved scene');assert.match(await pinned.locator('#status').textContent(),/snapshot/);
console.log('PASS pinned '+mode+' retains scoped saved content without SignalR/latest Word/window registration');await pinned.close();
}
const page=await browser.newPage();await page.goto('about:blank');
await page.addScriptTag({content:`window.__opened=[];window.open=(url,name)=>{__opened.push(name);return{focus(){}}};const peer={on(){},onreconnected(){},onclose(){},start:async()=>{},invoke:async()=>({projectID:1,bookID:2,windows:[]})};window.signalR={HubConnectionBuilder:class{withUrl(){return this}withAutomaticReconnect(){return this}build(){return peer}}};`});
await page.addScriptTag({content:fs.readFileSync(path.join(scripts,'writing-workspace.js'),'utf8')});

View File

@ -42,6 +42,11 @@ internal static class NativeCompanionHttpTests
var json="""{"schemaVersion":"1.0","chapterSummary":"A fictional chapter.","sceneBoundaries":[{"sceneNumber":1,"startParagraph":1,"endParagraph":1,"suggestedTitle":"A narrative scene","structuralSummary":"The characters encounter a new problem and make a decision to resolve the immediate situation.","confidence":0.8,"reason":"A coherent dramatic unit."}]}""";
var provider=new FakeStoryIntelligenceClient(JsonSerializer.Serialize(new{output=new[]{new{content=new[]{new{type="output_text",text=json}}}}}));
var builder=WebApplication.CreateBuilder(new WebApplicationOptions{EnvironmentName="Development"});builder.Logging.ClearProviders();builder.WebHost.UseUrls("http://127.0.0.1:0");
builder.Services.AddSingleton<IStoryIntelligenceClient>(provider);
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IBookRepository>((n,a)=>Task.FromResult<Book?>(new(){BookID=3,ProjectID=1,BookTitle="Fixture book"})));
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IWordCompanionService>((n,a)=>n=="AnalyseManuscriptAsync"?Task.FromResult<WordCompanionManuscriptAnalyseResponse?>(new(){CanImport=true,Message="Preview eligible"}):throw new Exception("Unexpected write "+n)));
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IStoryContextService>((n,a)=>Task.FromResult<StoryContextViewModel?>(null)));
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IWriterWorkspaceService>((n,a)=>Task.FromResult<PlotLine.ViewModels.ChapterWorkflowViewModel?>(null)));
builder.Services.AddSingleton(users);builder.Services.AddSingleton(repo);builder.Services.AddSingleton(subscriptions);
builder.Services.AddSingleton<IDataProtectionProvider>(new EphemeralDataProtectionProvider());builder.Services.AddSingleton(TimeProvider.System);builder.Services.AddSingleton<DesktopPairing>();builder.Services.AddSingleton<NativeAnalysisCache>();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options=>{options.LoginPath="/fixture-login";options.Cookie.SecurePolicy=Microsoft.AspNetCore.Http.CookieSecurePolicy.None;})
@ -72,6 +77,9 @@ internal static class NativeCompanionHttpTests
var redeemed=await agent.PostAsJsonAsync("/api/native-companion/token",new{code,verifier});Check(redeemed.IsSuccessStatusCode,"Agent redeems approved pairing");
var token=(await redeemed.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("accessToken").GetString();agent.DefaultRequestHeaders.Authorization=new AuthenticationHeaderValue("Bearer",token);
Check((await agent.GetFromJsonAsync<CompanionBook[]>("/api/native-companion/books"))!.Single().BookId==3,"Grant loads authorized books through actual routing");
Check((await agent.GetFromJsonAsync<ConnectionHealth>("/api/native-companion/connection"))?.Authentication=="verified","Authenticated health verifies current session and configuration without paid AI request");
Check((await agent.GetFromJsonAsync<SavedWorkspace>("/api/native-companion/books/3/workspace"))?.State=="saved-book","Saved workspace is scoped to accessible book over actual HTTP");
var preview=await agent.PostAsJsonAsync("/api/native-companion/import-preview",NativeWorkflowTests.Selection());Check(preview.IsSuccessStatusCode&&(await preview.Content.ReadFromJsonAsync<PlotDirector.Companion.Protocol.ImportPreview>())?.CommitAvailable==false,"HTTP import preview is read-only with commit explicitly unavailable");
var request=new AiChapterRequest{BookId=3,ManuscriptId=Guid.NewGuid(),SessionId=Guid.NewGuid(),RequestId=Guid.NewGuid(),ChapterStart=20,ChapterEnd=40,Paragraphs=[new(){Index=1,Start=20,End=40,Text="A fictional narrative paragraph."}]};
var response=await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request);Check(response.IsSuccessStatusCode,"Authenticated chapter API calls canonical service");
var result=await response.Content.ReadFromJsonAsync<AiChapterResult>();Check(result?.State=="complete"&&result.Scenes.Single().Start==20&&provider.Prompts.Count==1,"Actual HTTP response maps scene to Word position");

View File

@ -0,0 +1,51 @@
using System.Reflection;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PlotDirector.Companion.Protocol;
using PlotLine.Controllers;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Services.NativeCompanion;
using PlotLine.ViewModels;
using ImportPreview=PlotDirector.Companion.Protocol.ImportPreview;
internal static class NativeWorkflowTests
{
internal static T Proxy<T>(Func<string,object?[]?,object?> handler)where T:class{var item=DispatchProxy.Create<T,StoryPointProxy>();((StoryPointProxy)(object)item).Handler=handler;return item;}
public static ImportPreviewRequest Selection()=>new(){BookId=3,SessionId=Guid.NewGuid(),SnapshotId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Items=[new(){Kind="Chapter",Title="Second",Start=100,End=200},new(){Kind="Scene",Title="Last",Start=150,End=200,Origin="AI"},new(){Kind="Scene",Title="First",Start=100,End=150,Origin="Existing marker"}]};
public static async Task Run()
{
void Check(bool value,string message){if(!value)throw new Exception(message);}
var input=Selection();var plan=NativeImportPreview.Build(input,1);
Check(WordCompanionService.ValidImportStructure(plan)&&plan.Chapters[0].Scenes[0].Title=="First"&&plan.Chapters[0].Scenes[1].SortOrder==2&&!plan.ReplacePlanned,"Preview reuses existing importer validation and source-position ordering without replacement");
void Refuse(ImportPreviewRequest request){try{NativeImportPreview.Build(request,1);throw new Exception("Unsafe preview accepted");}catch(ArgumentException){}}
var duplicate=Selection();duplicate.Items=[..duplicate.Items,duplicate.Items[1]];Refuse(duplicate);
var overlap=Selection();overlap.Items[2].End=190;Refuse(overlap);
var backwards=Selection();backwards.Items[1].End=149;Refuse(backwards);
var orphan=Selection();orphan.Items=orphan.Items.Where(i=>i.Kind=="Scene").ToArray();Refuse(orphan);
var empty=Selection();empty.Items=[empty.Items[0]];Refuse(empty);
var linked=0;var planned=false;var allow=true;var calls=0;
var access=Proxy<IWordCompanionRepository>((name,args)=>{
if(name!="GetBookStructureAsync")throw new Exception("Unexpected access/write: "+name);
Check((int)args![1]! ==7,"Authenticated subject owns access check");return Task.FromResult((int)args[0]! ==3?new WordCompanionBookStructureResponse{BookId=3,Chapters=[new(){ChapterId=10,Title="Saved chapter",Scenes=[new(){SceneId=20,Title="Saved scene"}]}]}:null);
});
var books=Proxy<IBookRepository>((n,a)=>n=="GetAsync"?Task.FromResult<Book?>(new(){BookID=3,ProjectID=1,BookTitle="Saved book",Description="Saved book description"}):throw new Exception(n));
var companion=Proxy<IWordCompanionService>((n,a)=>{
if(n!="AnalyseManuscriptAsync")throw new Exception("Native preview attempted an import/write: "+n);calls++;
return Task.FromResult<WordCompanionManuscriptAnalyseResponse?>(new(){CanImport=linked==0,LinkedChapterCount=linked,RequiresReplaceConfirmation=planned,ExistingChapterCount=linked+ (planned?1:0),Message="Existing import eligibility check"});
});
var context=Proxy<IStoryContextService>((n,a)=>Task.FromResult<StoryContextViewModel?>(new(){Position=new(1,3,10,20),Scene=new(){SceneID=20,SceneTitle="Saved scene",Summary="Saved context, not AI",ScenePurposeNotes="Saved scene intent"}}));
var writer=Proxy<IWriterWorkspaceService>((n,a)=>Task.FromResult<ChapterWorkflowViewModel?>(new(){Project=new(){ProjectID=1},Book=new(){BookID=3,ProjectID=1},Chapter=new(){ChapterID=10,BookID=3,Summary="Saved chapter summary"},Goal=new(){GoalSummary="Saved chapter goal"}}));
var subscriptions=Proxy<ISubscriptionService>((n,a)=>Task.FromResult(new EntitlementDecision{Allowed=allow}));
var api=new NativeCompanionWorkflowController(access,books,companion,context,writer,new FakeStoryIntelligenceClient(""),subscriptions){ControllerContext=new(){HttpContext=new DefaultHttpContext{User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7")],DesktopPairing.Scheme))}}};
var saved=(SavedWorkspace)((OkObjectResult)await api.Workspace(3,10,20)).Value!;
Check(saved.Context=="Saved context, not AI"&&saved.Intent.Contains("Saved chapter goal")&&saved.ContextPath.Contains("pinned=true"),"Context/Intent reuse saved scene and chapter objective with pinned browser navigation");
Check(await api.Workspace(3,999,20) is NotFoundResult&&await api.Workspace(99,null,null) is ForbidResult,"Foreign book and mismatched marker cannot display saved context");
var result=(ImportPreview)((OkObjectResult)await api.Preview(input)).Value!;Check(!result.CommitAvailable&&result.State=="validated-preview"&&calls==1,"Validated preview never commits or creates canonical records");
linked=1;result=(ImportPreview)((OkObjectResult)await api.Preview(input)).Value!;Check(result.State=="already-linked","Duplicate manuscript import is blocked by existing linked state");
linked=0;planned=true;result=(ImportPreview)((OkObjectResult)await api.Preview(input)).Value!;Check(result.State=="existing-content"&&!result.CommitAvailable,"Planned content is never silently replaced");
allow=false;var before=calls;Check(await api.Preview(input) is ForbidResult&&before==calls,"Import entitlement denies before preview service call");
}
}

View File

@ -122,11 +122,13 @@ if (args.Contains("--plot-lines"))
return;
}
if(args.Contains("--native-workflow")){await NativeWorkflowTests.Run();Console.WriteLine("PASS native saved workspace and safe import preview validation");return;}
if(args.Contains("--native-companion-http")){await NativeCompanionHttpTests.Run();return;}
if(args.Contains("--native-companion")){await NativeCompanionTests.Run();Console.WriteLine("PASS native desktop pairing, canonical chapter AI/mapping, idempotency and cancellation");return;}
var tests = new (string Name, Action Test)[]
{
("Native saved workspace and established import eligibility remain scoped and read-only", () => NativeWorkflowTests.Run().GetAwaiter().GetResult()),
("Native companion authentication, canonical AI mapping and isolated chapter retry", () => NativeCompanionTests.Run().GetAwaiter().GetResult()),
("Solver never discards a corroborated concern or exhausts navigation before verification", WritingSolverDeadEndTests.Regression),
("Solver result evidence covers all reachable diagnoses without changing Stage 1 semantics", WritingSolverResultTests.EditorialCoverage),

View File

@ -0,0 +1,58 @@
using System.Security.Claims;
using ImportPreview = PlotDirector.Companion.Protocol.ImportPreview;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PlotDirector.Companion.Protocol;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Services.NativeCompanion;
namespace PlotLine.Controllers;
[ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion")]
public sealed class NativeCompanionWorkflowController(IWordCompanionRepository access,IBookRepository books,IWordCompanionService companion,IStoryContextService context,IWriterWorkspaceService writer,IStoryIntelligenceClient ai,ISubscriptionService subscriptions):ControllerBase
{
private int UserId=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
[HttpGet("connection")]
public async Task<IActionResult> Connection()
{
var entitled=(await subscriptions.CanUseFeatureAsync(UserId,SubscriptionFeature.StoryIntelligence)).Allowed;
var config=ai.GetConfigurationStatus();DateTime.TryParse(User.FindFirstValue("NativeCompanion.Expires"),null,System.Globalization.DateTimeStyles.AdjustToUniversal,out var expiry);
return Ok(new ConnectionHealth{Server="online",Authentication="verified",VerifiedUtc=DateTime.UtcNow,ExpiresUtc=expiry,Ai=!entitled?"not-entitled":config.ApiKeyConfigured&&!string.IsNullOrWhiteSpace(config.ChapterStructureModel)?"configured":"not-configured",Explanation="Authenticated server check. AI configuration is known; provider availability is only proven by an explicit analysis request."});
}
[HttpGet("books/{bookId:int}/workspace")]
public async Task<IActionResult> Workspace(int bookId,int? chapterId,int? sceneId)
{
var structure=await access.GetBookStructureAsync(bookId,UserId);if(structure==null)return Forbid();
var book=await books.GetAsync(bookId);if(book==null)return NotFound();
var parent=sceneId.HasValue?structure.Chapters.FirstOrDefault(c=>c.Scenes.Any(s=>s.SceneId==sceneId)):chapterId.HasValue?structure.Chapters.FirstOrDefault(c=>c.ChapterId==chapterId):null;
if((sceneId.HasValue||chapterId.HasValue)&&(parent==null||(chapterId.HasValue&&parent.ChapterId!=chapterId)))return NotFound();
var saved=sceneId.HasValue?await context.GetForSceneAsync(sceneId.Value,book.ProjectID,bookId):null;
if(sceneId.HasValue&&saved?.Scene==null)return NotFound();
var workflow=parent!=null?await writer.GetChapterWorkflowAsync(parent.ChapterId):null;
if(workflow!=null&&(workflow.Book.BookID!=bookId||workflow.Project.ProjectID!=book.ProjectID))return Forbid();
string Cut(string? s,int max=2000)=>string.IsNullOrWhiteSpace(s)?"":s.Length>max?s[..max]:s;
var goal=workflow?.Goal;
var scope=$"projectId={book.ProjectID}&bookId={bookId}"+(parent!=null?$"&chapterId={parent.ChapterId}":"")+(sceneId.HasValue?$"&sceneId={sceneId}":"")+"&pinned=true";
return Ok(new SavedWorkspace{BookId=bookId,ProjectId=book.ProjectID,ChapterId=parent?.ChapterId,SceneId=sceneId,Title=Cut(book.BookDisplayTitle,200)+(parent!=null?" / "+Cut(parent.Title,200):"")+(saved?.Scene!=null?" / "+Cut(saved.Scene.SceneTitle,200):""),
Context=Cut(saved?.Scene?.Summary??workflow?.Chapter?.Summary??book.ShortDescription??book.Description),
Intent=Cut(string.Join("\n",new[]{saved?.Scene?.ScenePurposeNotes,goal?.GoalSummary,goal?.EmotionalGoal,goal?.ReaderTakeaway,goal?.MustInclude}.Where(s=>!string.IsNullOrWhiteSpace(s)))),
State=sceneId.HasValue?"saved-scene":parent!=null?"saved-chapter":"saved-book",BookPath=$"/Books/Details/{bookId}",ContextPath="/Writing/Context?"+scope,IntentPath="/Writing/Intent?"+scope});
}
[HttpPost("import-preview"),RequestSizeLimit(160*1024)]
public async Task<IActionResult> Preview(ImportPreviewRequest input)
{
if(!(await subscriptions.CanUseFeatureAsync(UserId,SubscriptionFeature.Import)).Allowed)return Forbid();
if(await access.GetBookStructureAsync(input.BookId,UserId)==null)return Forbid();
var book=await books.GetAsync(input.BookId);if(book==null)return NotFound();
try
{
var plan=NativeImportPreview.Build(input,book.ProjectID);
var check=await companion.AnalyseManuscriptAsync(new(){ProjectId=book.ProjectID,BookId=input.BookId,DocumentGuid=input.ManuscriptId,ChapterCount=plan.Chapters.Count,SceneCount=plan.Chapters.Sum(c=>c.Scenes.Count),WordCount=0});
if(check==null)return Forbid();
return Ok(new ImportPreview{RequestId=input.RequestId,State=check.LinkedChapterCount>0?"already-linked":check.RequiresReplaceConfirmation?"existing-content":check.CanImport?"validated-preview":"rejected",Chapters=plan.Chapters.Count,Scenes=plan.Chapters.Sum(c=>c.Scenes.Count),ExistingChapters=check.ExistingChapterCount,ExistingScenes=check.ExistingSceneCount,
Message=check.Message+" Native commit is unavailable: the established import also owns prose sources, persistent binding, marker/save acknowledgement and partial-build recovery. This preview creates or replaces nothing. Selected counts are structural; prose word counts are not uploaded. Continue the established book import in PlotDirector; these native choices are not automatically transferred.",BookPath=$"/Books/Details/{input.BookId}",CommitAvailable=false});
}
catch(ArgumentException e){return BadRequest(new ImportPreview{RequestId=input.RequestId,State="rejected",Message=e.Message});}
}
}

View File

@ -17,8 +17,9 @@ public sealed class WritingController(
ILogger<WritingController> logger) : Controller
{
[HttpGet("Context")]
public async Task<IActionResult> Context(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? documentGuid)
public async Task<IActionResult> Context(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? documentGuid, bool pinned = false)
{
ViewData["NativeSnapshot"] = pinned;
logger.LogInformation(
"Opening Writing Context. ProjectID={ProjectID} BookID={BookID} ChapterID={ChapterID} SceneID={SceneID} DocumentGuidPresent={DocumentGuidPresent}",
projectId,
@ -31,6 +32,7 @@ public sealed class WritingController(
? await BuildDisplayAsync(projectId, bookId, chapterId, sceneId, "Manual context")
: WaitingContextDisplay(projectId, bookId, documentGuid);
if(pinned&&display!=null){display.FollowStatus="Saved PlotDirector snapshot";if(!sceneId.HasValue){display.EmptyTitle="No saved scene selected";display.EmptyMessage="This is a scoped saved-data view, not live Word following. Select a saved scene in PlotDirector; local markers or AI suggestions do not create saved context.";}}
var model = new WritingContextPageViewModel
{
ProjectID = projectId,
@ -45,8 +47,9 @@ public sealed class WritingController(
}
[HttpGet("Intent")]
public async Task<IActionResult> Intent(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? documentGuid)
public async Task<IActionResult> Intent(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? documentGuid, bool pinned = false)
{
ViewData["NativeSnapshot"] = pinned;
logger.LogInformation(
"Opening Writing Intent. ProjectID={ProjectID} BookID={BookID} ChapterID={ChapterID} SceneID={SceneID} DocumentGuidPresent={DocumentGuidPresent}",
projectId,
@ -59,6 +62,7 @@ public sealed class WritingController(
? await BuildIntentDisplayAsync(projectId, bookId, chapterId, sceneId, "Manual intent")
: WaitingIntentDisplay(projectId, bookId, documentGuid);
if(pinned&&display!=null){display.FollowStatus="Saved PlotDirector snapshot";if(!sceneId.HasValue&&!chapterId.HasValue){display.EmptyTitle="No saved writing objective selected";display.EmptyMessage="Choose a saved chapter or scene in PlotDirector. Set its goal/purpose explicitly; this view does not invent or automatically save intent.";}}
var model = new WritingIntentPageViewModel
{
ProjectID = projectId,

View File

@ -62,7 +62,7 @@ public sealed class DesktopAuthentication(IOptionsMonitor<AuthenticationSchemeOp
var grant=pairing.Read(header[7..]);if(grant==null)return AuthenticateResult.Fail("Sign in again.");
var user=await users.GetByIdAsync(grant.UserId);
if(user==null||user.SecurityStamp!=grant.Stamp||(user.IsLocked&&(!user.LockoutEndUtc.HasValue||user.LockoutEndUtc>DateTime.UtcNow)))return AuthenticateResult.Fail("Sign in again.");
var identity=new ClaimsIdentity([new(ClaimTypes.NameIdentifier,grant.UserId.ToString()),new("PlotLine.SecurityStamp",grant.Stamp.ToString())],DesktopPairing.Scheme);
var identity=new ClaimsIdentity([new(ClaimTypes.NameIdentifier,grant.UserId.ToString()),new("PlotLine.SecurityStamp",grant.Stamp.ToString()),new("NativeCompanion.Expires",grant.Expires.UtcDateTime.ToString("O"))],DesktopPairing.Scheme);
return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity),DesktopPairing.Scheme));
}
}

View File

@ -0,0 +1,30 @@
using PlotDirector.Companion.Protocol;
using PlotLine.Models;
namespace PlotLine.Services.NativeCompanion;
// Only constructs a read-only plan. Canonical import remains owned by the existing application.
public static class NativeImportPreview
{
public static WordCompanionManuscriptImportRequest Build(ImportPreviewRequest input,int project)
{
if(input.SessionId==Guid.Empty||input.SnapshotId==Guid.Empty||input.ManuscriptId==Guid.Empty||input.Items==null||input.Items.Length is <1 or >80)throw new ArgumentException("Select a bounded set of chapter/scene rows from one current snapshot.");
if(input.Items.Any(s=>s==null||s.Kind is not ("Chapter" or "Scene")||s.Start<0||string.IsNullOrWhiteSpace(s.Title)||s.Title.Length>200||s.Reason?.Length>600))throw new ArgumentException("A selected row has no valid title/range or is an error row.");
if(input.Items.GroupBy(s=>(s.Kind,s.Start)).Any(g=>g.Count()>1))throw new ArgumentException("Duplicate or competing boundaries selected. Choose one local/AI boundary at each position.");
var chapters=input.Items.Where(s=>s.Kind=="Chapter").OrderBy(s=>s.Start).ToArray();
if(chapters.Length==0||chapters.Any(c=>c.End<=c.Start)||chapters.Zip(chapters.Skip(1)).Any(pair=>pair.First.End>pair.Second.Start))throw new ArgumentException("Select nonoverlapping chapter ranges.");
var selectedScenes=input.Items.Where(s=>s.Kind=="Scene").OrderBy(s=>s.Start).ToArray();
if(selectedScenes.Any(s=>s.End<=s.Start))throw new ArgumentException("Scene ranges must have a positive length.");
if(selectedScenes.Any(s=>chapters.Count(c=>s.Start>=c.Start&&s.Start<c.End)!=1))throw new ArgumentException("Each scene needs its selected parent chapter.");
foreach(var chapter in chapters)
{
var scenes=selectedScenes.Where(s=>s.Start>=chapter.Start&&s.Start<chapter.End).ToArray();
if(scenes.Length==0)throw new ArgumentException("Choose scenes for every selected chapter; no placeholder scene is invented.");
for(var i=0;i<scenes.Length;i++)if(scenes[i].End>chapter.End||(i+1<scenes.Length&&scenes[i].End>scenes[i+1].Start))throw new ArgumentException("Scene ranges overlap or extend outside their chapter. Review competing local/AI choices.");
}
var request=new WordCompanionManuscriptImportRequest{ProjectId=project,BookId=input.BookId,DocumentGuid=input.ManuscriptId,ReplacePlanned=false,
Chapters=chapters.Select((c,i)=>new WordCompanionManuscriptImportChapterRequest{Title=c.Title,SortOrder=i+1,WordCount=0,
Scenes=selectedScenes.Where(s=>s.Start>=c.Start&&s.Start<c.End).Select((s,j)=>new WordCompanionManuscriptImportSceneRequest{Title=s.Title,SortOrder=j+1,WordCount=0}).ToArray()}).ToArray()};
if(!WordCompanionService.ValidImportStructure(request))throw new ArgumentException("The existing importer rejected this structure.");
return request;
}
}

View File

@ -542,9 +542,8 @@ public sealed class WordCompanionService(
private static bool ValidStructureTitle(string? title)=>!string.IsNullOrWhiteSpace(title) && title.Trim().Length<=200;
public Task<WordCompanionManuscriptImportResponse?> ImportManuscriptAsync(WordCompanionManuscriptImportRequest request)
{
if (request.ProjectId <= 0
public static bool ValidImportStructure(WordCompanionManuscriptImportRequest request)
=> !( request.ProjectId <= 0
|| request.BookId <= 0
|| request.BindingVersion <= 0
|| request.Chapters is null || request.Chapters.Count == 0
@ -553,7 +552,11 @@ public sealed class WordCompanionService(
|| chapter.SortOrder is null or <= 0
|| chapter.WordCount < 0
|| chapter.Scenes is null || chapter.Scenes.Count == 0
|| chapter.Scenes.Any(scene => scene is null || !ValidStructureTitle(scene.Title) || scene.SortOrder is null or <= 0 || scene.WordCount < 0)))
|| chapter.Scenes.Any(scene => scene is null || !ValidStructureTitle(scene.Title) || scene.SortOrder is null or <= 0 || scene.WordCount < 0)) );
public Task<WordCompanionManuscriptImportResponse?> ImportManuscriptAsync(WordCompanionManuscriptImportRequest request)
{
if (!ValidImportStructure(request))
{
return Task.FromResult<WordCompanionManuscriptImportResponse?>(null);
}

View File

@ -5,6 +5,7 @@
}
<main class="writing-context-page"
data-follow-mode="@(ViewData["NativeSnapshot"] is true ? "snapshot" : "live")"
data-writing-mode="context"
data-writing-context
data-context-url="@Url.Action("ContextScene", "Writing")"
@ -17,12 +18,12 @@
<h1>Writing Context</h1>
</div>
<div class="writing-context-status" data-writing-context-status>
<span class="writing-context-status-dot" aria-hidden="true"></span>
@if (ViewData["NativeSnapshot"] is not true) { <span class="writing-context-status-dot" aria-hidden="true"></span> }
<span data-writing-context-status-text>@(Model.Display?.FollowStatus ?? "Connected, waiting for scene")</span>
</div>
<div class="writing-workspace-role-indicator">
<span class="writing-context-status-dot" aria-hidden="true"></span>
<span>Writing Workspace</span>
@if (ViewData["NativeSnapshot"] is not true) { <span class="writing-context-status-dot" aria-hidden="true"></span> }
<span>@(ViewData["NativeSnapshot"] is true ? "Saved PlotDirector snapshot · manual navigation · no automatic save" : "Writing Workspace")</span>
</div>
</header>
@ -36,7 +37,7 @@
<script src="~/js/writing-follow.js" asp-append-version="true"></script>
<script src="~/js/writing-context.js" asp-append-version="true"></script>
<script>
window.PlotDirectorWritingWorkspace?.registerWindow({
if (document.querySelector('[data-follow-mode="snapshot"]') === null) window.PlotDirectorWritingWorkspace?.registerWindow({
projectID: "@Model.ProjectID",
bookID: "@Model.BookID",
writingRole: window.PlotDirectorWritingWorkspace.roles.context,

View File

@ -5,6 +5,7 @@
}
<main class="writing-context-page"
data-follow-mode="@(ViewData["NativeSnapshot"] is true ? "snapshot" : "live")"
data-writing-mode="intent"
data-writing-intent
data-context-url="@Url.Action("IntentScene", "Writing")"
@ -17,12 +18,12 @@
<h1>Writing Intent</h1>
</div>
<div class="writing-context-status" data-writing-intent-status>
<span class="writing-context-status-dot" aria-hidden="true"></span>
@if (ViewData["NativeSnapshot"] is not true) { <span class="writing-context-status-dot" aria-hidden="true"></span> }
<span data-writing-intent-status-text>@(Model.Display?.FollowStatus ?? "Connected, waiting for scene")</span>
</div>
<div class="writing-workspace-role-indicator">
<span class="writing-context-status-dot" aria-hidden="true"></span>
<span>Writing Workspace</span>
@if (ViewData["NativeSnapshot"] is not true) { <span class="writing-context-status-dot" aria-hidden="true"></span> }
<span>@(ViewData["NativeSnapshot"] is true ? "Saved PlotDirector snapshot · manual navigation · no automatic save" : "Writing Workspace")</span>
</div>
</header>
@ -36,7 +37,7 @@
<script src="~/js/writing-follow.js" asp-append-version="true"></script>
<script src="~/js/writing-intent.js" asp-append-version="true"></script>
<script>
window.PlotDirectorWritingWorkspace?.registerWindow({
if (document.querySelector('[data-follow-mode="snapshot"]') === null) window.PlotDirectorWritingWorkspace?.registerWindow({
projectID: "@Model.ProjectID",
bookID: "@Model.BookID",
writingRole: window.PlotDirectorWritingWorkspace.roles.intent,

View File

@ -71,6 +71,7 @@
};
const registerWorkspaceRole = () => {
if (root.dataset.followMode === "snapshot") return;
const role = config.source === "WritingContext"
? window.PlotDirectorWritingWorkspace?.roles?.context
: config.source === "WritingIntent"
@ -135,7 +136,7 @@
const fragment = contentHost?.querySelector(config.fragmentSelector);
const fragmentStatus = fragment?.dataset.followStatus;
if (fragmentStatus) {
setStatus(fragmentStatus);
setStatus(root.dataset.followMode === "snapshot" ? "Saved PlotDirector snapshot — manual selection" : fragmentStatus);
}
registerWorkspaceRole();
@ -206,11 +207,11 @@
if (hasScene && position.sceneId === currentSceneId && (loadingChapterId !== null || (loadingSceneId !== null && position.sceneId !== loadingSceneId))) {
++requestGeneration; pendingRequest?.abort(); pendingRequest = null;
loadingSceneId = null; loadingChapterId = null; setStatus("Following Word"); return;
loadingSceneId = null; loadingChapterId = null; setStatus(root.dataset.followMode === "snapshot" ? "Saved PlotDirector snapshot — manual selection" : "Following Word"); return;
}
if (!hasScene && currentSceneId === null && position.chapterId === currentChapterId && (loadingChapterId !== null || loadingSceneId !== null)) {
++requestGeneration; pendingRequest?.abort(); pendingRequest = null;
loadingSceneId = null; loadingChapterId = null; setStatus("Following Word"); return;
loadingSceneId = null; loadingChapterId = null; setStatus(root.dataset.followMode === "snapshot" ? "Saved PlotDirector snapshot — manual selection" : "Following Word"); return;
}
if (hasScene && (position.sceneId === currentSceneId || position.sceneId === loadingSceneId)) {
return;
@ -267,6 +268,8 @@
}
};
if (root.dataset.followMode === "snapshot") { wireFragment(); setStatus("Saved PlotDirector snapshot — manual selection"); return { loadPosition, activateTab }; }
document.addEventListener(window.PlotDirectorStoryPosition?.eventName || "plotdirector:story-position-changed", (event) => {
void loadPosition(event.detail);
});