PlotDirector/Docs/Writer/Unified-Context-Enhancements-20261122.md

19 KiB

Unified Context enhancement programme

22 November 2026. Development only. Production is outside scope. Existing untracked investigation/audit documents are preserved.

Existing-system audit and reuse decisions

  • WritingController, Context.cshtml, context-workspace.js: established two-pane shell, declared endpoints/scopes/lifecycle, shared native notification connection, HTTP partials, generation guards, dirty/busy deferral and independent local state. Extend these; do not add a second workspace or connection.
  • StoryPointContextService.GetAsync/Compose and StoryStateService.OrderScenes: canonical narrative ordering and bounded established knowledge/relationship state. ICharacterRepository.GetTimelineAsync already batches character appearances. A focused Context read projection can combine these for previous/next appearances without changing canonical story state. Future location records must remain explicitly author reference, never current viewpoint knowledge.
  • ICharacterService: canonical identity, alias, scene appearance and relationship-event reads/saves. Existing character editor supports name, aliases, importance, description and many unrelated fields. Focused modals must hydrate the canonical edit model, change only the chosen field, and reuse these saves rather than posting replacement editor models.
  • Classifications: manual create currently leaves importance null (timeline fallback). CharacterLanePriority can use role/count as display ranking; that must not be presented as explicit author classification. The core structural-import character INSERT in migration 162 sets new characters to 8 (Major); a forward-only correction for new records is needed. Existing classifications must not be bulk-updated.
  • NamesController / INameIntelligenceService: canonical Unicode normalization, reference recognition, related forms, locale/era/gender/used-name searches and full Names workspace already exist. Use them for suggestions. Canonical aliases have individual-character repository reads; a bounded batched project read is the only missing read shape needed for a responsive alias catalogue. No existing general project-name near-match engine has been established; do not substitute a new generator.
  • IRelationshipMapService.GetAsync / BuildAtScene: existing narrative-point projection, category, direction, reciprocal state, intensity and recorded event history. CharacterRelationship and RelationshipType retain family categories; family/narrative tracks must remain distinct. First meeting is displayed only when explicitly recorded, not inferred from co-occurrence.
  • RelationshipMapController.Save and ICharacterService.SaveInitialRelationshipAsync/AddRelationshipEventAsync/UpdateRelationshipEventAsync: focused existing relationship persistence. Context must validate scope, permitted edit access, entity IDs, lookups and existing relationship ownership before invoking them.
  • ProjectAccessService, ProjectAccessFilter, project collaboration: existing access checks and Owner/Collaborator membership. The new interaction registry is strictly per authenticated user/book, separate from project membership/collaboration. No cross-user command path is enabled. Focused writes will conservatively require owner permission where the existing model exposes no finer write permission, rather than inventing a read/write role.
  • Shared notifications: _WritingCompanionLayout owns _ToastHost, notifications.js and word-notifications.js outside replaceable content. Explicit save outcomes toast in the initiating window only; incoming invalidations remain quiet. Inline validation and recovery remain in the modal.

Phase 1: My Windows

The existing /hubs/native-companion connection additionally supports version-1 Context registration, discovery, targeted interaction and acknowledgements. ContextWindows is ephemeral presence/capability state, not another character/name/relationship service. It expires stale leases after 60 seconds, removes disconnects, and bounds registrations/pending commands. Registration and command methods independently authorize the book; canonical IDs are checked against its project and story point.

Only visible, loaded, clean panes advertise supported action names. Routing prefers an eligible pane in the originating connection, then another same-user/book connection. Explicit window/session/pane targets stay within that scope. No unrelated tool is switched. Missing, busy, expired or unavailable handlers return explicit outcomes. Receiver re-reads its authorized HTTP partial before tool-specific focus handling; it never sets the manuscript scene or calls Word navigation. Receipt acknowledgements are accepted only from the selected recipient.

Contract: version, book ID, originating pane, action, canonical character/location/relationship ID as applicable, chapter/scene story point, optional target window/session/pane. Reserved target-user routing is rejected in version 1. Commands contain no manuscript text or display-name matching. Saved-data ContextInvalidated events remain separate from interaction commands.

My Windows shows current capabilities and offers a scene-focus demonstration. Overview and Characters are minimal non-destructive handlers; later phases extend them. Pinned snapshots retain their existing no-live-connection semantics and explicitly explain that My Windows requires a live Context window. Reconnect re-registers current visible capability state and recovers manuscript authority through the existing foundation mechanisms; missed commands are not replayed.

Qualification and deployment evidence will be appended as each phase completes. Physical cross-device/Word/installed-PWA acceptance is not implied by browser-session automation.

Phase 1 qualification

Commit 16c0505, Development release context-enhancement-phase1-16c0505-20261122T150659Z. Clean build; 13 routing assertions; actual SignalR transport in isolated host and two independently authenticated Development browser contexts passed targeted delivery, exactly one recipient read, no unrelated pane mutation/Word navigation, cross-user/book/story-point rejection, no-handler, reconnect. This qualifies separate authenticated sessions, not physical devices or Word.

Phase 2

Compact scene-first Characters explorer uses canonical timeline/appearance reads, existing story-point knowledge and Map location rules. Catalogue search, independent pane filters, POV/participation/classification, Previous→Now→Next, canonical-ID location interactions and focused classification/description/emotion/condition/location corrections. Correction facade hydrates existing models and uses existing save services; checks authenticated book, character project, scene membership and Owner/Collaborator role. Unknown/read-only roles denied. Fingerprints reject stale forms within a process; existing persistence has no cross-process atomic row version, so this does not establish fully transactional concurrent editing across main editors.

Manual creation defaults Supporting (6); import migration297 changes only the literal default for newly discovered characters from Major (8) to Minor (2). No existing row reclassification. Development backup context-enhancement-phase2-20261122.bak succeeded and was independently VERIFYONLY checked using administrator because application principal cannot perform VERIFYONLY. Migration applied with Development guard; pre/post existing CharacterID/classification set unchanged.

Qualification: clean solution build; 11 focused narrative/edit/permission assertions; actual compiled Razor browser with 12 long-name characters, independent same-tool panes, full/half/stacked/mobile and 125% zoom; focused modal existing values, rejected discard, cancelled persistence, inline failed-save draft retention and one success toast. Browser save responses isolated; canonical persistence tested at service boundary, live persistence acceptance continues in integration. Previous/next scoped to the selected book; future information explicitly author reference. No unsupported presence/location inferred. Existing unknown/unrecorded participation displayed explicitly.

Phase 2 deployed commit 6e6c7fd; archived context-enhancement-phase2-6e6c7fd-20261122T152545Z. Published/live assembly and assets SHA-256 matched; informational version matched commit; local and public TLS GET200; authenticated Characters canonical partial passed.

Phase 3

Names uses existing canonical characters, aliases, Unicode normalisation and INameIntelligenceService.BuildLibraryAsync (book locale/era defaults and related forms). New migration298 provides one authenticated project alias read instead of per-character catalogue reads. Shared normalized spellings across different IDs are explicitly review hints; aliases belonging to one character do not create false duplicate identities. No general near-name detector was found; existing related forms are offered as spelling hints, without a replacement generator or inferred identity merge.

Focused canonical rename retains the previous spelling as an alias through the existing character service. Individual alias add/correct/remove uses existing canonical repository saves after full book/project/role checks, fingerprint validation and alias ownership verification. Canonical alias cannot be deleted through alias correction; use the name action. Names→Characters sends structured character.focus and never switches an unrelated tab. Full Names and Character editors remain linked.

Qualification: clean build, 17 focused character/name assertions including Unicode-equivalent shared spelling and legitimate aliases; compiled Razor browser passes canonical/alias filtering, collision review, structured focus, focused alias form/cancel, independent same-tool panes and mobile widths. Migration298 applied/verified after context-enhancement-phase3-20261122.bak backup and VERIFYONLY. No character/name rows bulk changed.

Phase 3 deployed commit c63925c; release context-enhancement-phase3-c63925c-20261122T153035Z; assembly/asset hashes and informational commit verified; authenticated Characters/Names HTTP reads passed.

Phase 4

Relationships reuses the Story Point snapshot / existing RelationshipMapService.BuildAtScene: scene participants first, Family separately from other narrative categories, directional versus reciprocal connections, current established state/intensity, recorded notes and up to three developments on demand. Future and unverified events are excluded by the existing canonical projection. Catalogue scope and search are independent per pane. The existing knowledge flag combines initial-reader/event-other-character semantics; the UI explicitly avoids treating it as proof of POV knowledge. No structured first-meeting field exists; explicit meeting notes are displayed, with no co-occurrence inference or invented date.

One relationship modal supports adding an initial connection or a scene development, correcting existing initial state or the selected scene event. It reuses initial/event services and lookups, validates role/book/scene/character/relationship ownership and duplicates, protects stale drafts and preserves existing direction/type/pair. Ambiguous multiple or unverified same-scene events redirect the author to full-editor review. Existing initial save now hydrates the prior structural flags/start/end before saving, preserving those fields during a focused correction.

Qualification: clean build; 10 focused assertions cover canonical future exclusion, Family/direction, loaded values, exact event save, stale and invalid pair/direction guards, initial save, foreign relationship/scene and read-only denial. Compiled Razor browser covers category separation, directional display, evidence limitations, saved modal values/cancel, independent same-tool filters and full/half/stacked/mobile layouts. No schema migration needed.

Phase 4 deployed commit 3784599; release context-enhancement-phase4-3784599-20261122T153623Z; assembly/asset hashes and informational commit verified; local/public GET200 and all three authenticated tool reads passed. Actual Development persistence acceptance created two characters in the pre-existing disposable qualification project through the normal Character editor (Supporting default verified), attached them through the normal scene-participant save, and exercised Context description, alias and relationship saves. No author manuscript fixtures were modified.

Phase 5 integration qualification

  • Clean dotnet build PlotLine.slnx (zero warnings/errors), full executable regression harness via dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj passed, exit0; stored-procedure architecture guard passed. The first full run exposed an older native HTTP fixture missing the new presence-hub constructor dependencies; its isolated service registration was corrected and the full harness passed afterwards.
  • Focused coverage: 13 routing/lifecycle assertions, 17 character/name projection/edit assertions, 10 relationship state/edit assertions, plus existing narrative/permissions/native suites in the full harness.
  • Actual compiled Razor browser suites: Characters (12 long-name entries, Previous/Now/Next, canonical location command/no-handler link, saved-value modal, cancel/draft protection, inline failure and one success toast); Names (canonical/alias lookup, Unicode shared-spelling domain test, structured character focus, alias form, full-editor access); Relationships (Family/narrative separation, direction/evidence limits, focused modal, independent search). Full/half/stacked/390px widths, 125% zoom, two same-tool panes and touch-emulated Chromium passed. Screenshots inspected for narrow Characters. This is browser/emulation acceptance; physical touch hardware and installed PWA are not claimed.
  • Foundation suite passed including stale/race responses, dirty/busy deferral, reconnect, native/Office selection, cloned-window identity, denied-storage fallback, pinned snapshots, no inactive reload and unrelated-project invalidation isolation.
  • Real SignalR tests cover two independent authenticated sessions, exact scene and character recipient/pane, authoritative HTTP read only in recipient, explicit no-handler without tab replacement, cross-user/book/story-point rejection, disconnect/reconnect, one connection per Context and no Word navigation.
  • Actual Development editing on disposable records passed persisted description and alias, cancel without persistence, invalid blank-name inline draft retention, single local success toast and quiet second authenticated session, existing-service relationship create/correct and quiet remote refresh. Test is opt-in Browser/context-live-editing.cjs; it refuses identities not marked Development/disposable and requires an explicit synthetic scope.
  • Integration correction: identity/relationship changes notify the same authenticated account with a project ID so other books in that project can recover authoritative state; scene-appearance corrections stay book-scoped. Other projects ignore the hint. Inactive tabs remain stale until selected, rather than reloading. Current location now distinguishes explicitly Unknown and Off-screen from an unrecorded location.

Remaining limitations and acceptance

No Production changes. No physical Word Companion, genuine cross-device hardware, separate browser engine or installed-PWA acceptance has been performed. Two authenticated browser contexts using the actual Development transport have been qualified. Those physical-client checks remain manual acceptance items, not claimed passes.

Underlying gaps: no structured first-meeting marker; no established general near-name detector (existing related forms are used); initial-reader versus event-other-character knowledge flags have different semantics; canonical saves have no atomic cross-process row version. Focused fingerprints and process locks prevent common stale Context saves but cannot guarantee atomicity against simultaneous saves from every legacy editor. Presence/capability leases are in-memory on the current single application instance; multi-instance hosting would require shared discovery/backplane coordination.

Map/Location/Floor Plan capability handlers are not added by this programme: location commands return an explicit non-disruptive full-location-editor fallback until a suitable tool advertises the contract. Previous/next appearances are scoped to the selected book. Existing ambiguous/unverified relationship events and structural pair/type/direction changes require the full editor.

No known Development build/regression blockers remain. Physical-client acceptance and the above underlying-system gaps should be considered explicitly before broader launch claims.

Final Development installation and acceptance

Deployed source commit 504eccacd6a9f2b86cf496e51f025ccd107520c7 (phase5), installed 22 November 2026 at 15:44:23 UTC. Archive /srv/apps/plotdirector-dev/releases/context-enhancement-phase5-504ecca-20261122T154413Z; reversible application backup /srv/apps/plotdirector-dev/current-before-context-enhancement-phase5-504ecca-20261122T154413Z. Active-job guard passed immediately before restart. Service active; local HTTP/public TLS GET200. Deployed informational version matches commit. Published/live SHA-256 matched for assembly, workspace, windows, tools, focused-editing JavaScript and CSS. Assembly SHA-256: 7b65808ca757394693ae94b839008d7b1d7b4cdf73d886110a87ccb7d19213b3.

Post-installation actual Development checks passed again: authenticated Characters/Names/Relationships reads; two separately logged-in browser contexts receiving precisely targeted scene and character commands; only recipient pane HTTP reload, no Word navigation, no-handler, cross-user/book/story-point rejection and reconnect registration; persisted focused description/alias/relationship corrections, failed inline draft retention, cancel without persistence, one initiating success and quiet second session. Both windows retained exactly one Context SignalR connection.

Browser/context-live-security.cjs independently verified unauthenticated denial, foreign book/scene/character/relationship denial, malformed missing-field rejection and antiforgery on both save routes. Established cookie authentication redirects forbidden requests to /Account/AccessDenied; this is treated as denial, not a raw403 assertion. No mutation requests without a valid antiforgery token persisted.

Post-installation journal review: one pre-existing HTTPS-redirection configuration warning; three expected SignalR dispatcher error entries from deliberate Unsupported interaction / Book unavailable / Invalid story point rejection tests. No unexpected application exceptions found. Production remains unchanged. Validation-only follow-up documentation/tests do not change the deployed source hash above.

Implementation commits, in phase order: 16c0505 → 6e6c7fd → c63925c → 3784599 → 504ecca. All qualified phases were deployed separately to Development. The two pre-existing untracked audit/investigation documents were preserved.