Compare commits

...

31 Commits

Author SHA1 Message Date
nick
898a97f730 Complete native shared-focus ribbon and reuse scoped Context windows 2026-11-23 14:45:36 +00:00
2d60e2a90a Record qualified shared-focus Development deployment 2026-11-23 14:23:47 +00:00
3b1491f1a4 Retain held Review references when accepted positioning is unavailable 2026-11-23 14:16:01 +00:00
d55206d8c3 Harden focus recovery and canonical chapter boundaries 2026-11-23 14:07:59 +00:00
a85d6ed532 Coordinate manuscript focus and independent Hold across workspaces 2026-11-23 13:38:09 +00:00
2fe1d85e95 Record authenticated Character refinement delivery checks 2026-11-23 11:33:41 +00:00
7fa095409c Refine Character ribbon, grouped relationships and canonical evolution history 2026-11-23 11:21:45 +00:00
5bc339bf9b Record Character workspace regression and Development acceptance evidence 2026-11-23 10:07:30 +00:00
ce51829512 Use the relationship dialog as the single removal confirmation 2026-11-23 10:05:33 +00:00
7ff5306c3b Redesign main Character workspace with bounded tabs and safe relationship management 2026-11-23 10:01:35 +00:00
0fc459a270 Record Family tree Development delivery and live qualification evidence 2026-11-22 20:24:44 +00:00
6ba409220a Retain family exploration when recentering and resolving character lookup 2026-11-22 20:09:38 +00:00
f357cbde81 Redesign Context Family as scene-indexed genealogical trees with branches 2026-11-22 20:04:52 +00:00
467861718f Record final Context refinement Development deployment evidence 2026-11-22 17:45:35 +00:00
d9559713a5 Qualify Context refinements across live editing, navigation and touch 2026-11-22 17:44:29 +00:00
01a7723c5a Add Family and Story Context visual lenses and canonical life status 2026-11-22 17:38:55 +00:00
48573298d8 Expose full Names Library discovery in Context and correct shared book usage scope 2026-11-22 16:41:40 +00:00
5de6e5f345 Refine Context correction forms and reuse authorised main application windows 2026-11-22 16:24:18 +00:00
2eede4e941 Record final Development Context acceptance and HTTP denial checks 2026-11-22 15:46:23 +00:00
504eccacd6 Qualify Context integration and scope cross-book refreshes to projects 2026-11-22 15:43:42 +00:00
37845993c8 Add story-point Context Relationships and focused relationship editing 2026-11-22 15:35:52 +00:00
c63925c648 Add Context Names lookup, reference suggestions and focused alias editing 2026-11-22 15:30:05 +00:00
6e6c7fdcd9 Build compact scene-aware Context character explorer and focused corrections 2026-11-22 15:25:06 +00:00
16c05055fa Add same-user book-scoped My Windows interactions to Context 2026-11-22 15:06:21 +00:00
bd3ebd0deb Record final Context foundation release and expanded browser acceptance 2026-11-21 22:41:57 +00:00
868099ec82 Preserve saved-scene reads during unavailable native Word observations 2026-11-21 22:39:45 +00:00
fcc81fb015 Validate Context fragments against each registered navigation scope 2026-11-21 22:36:21 +00:00
7c3c8f7f09 Restore Context document selection consistently in controls and reload routes 2026-11-21 22:33:29 +00:00
cf8a969196 Keep Context windows isolated when browser channel or storage is unavailable 2026-11-21 22:31:34 +00:00
28b074ca53 Record Context foundation Development deployment and acceptance evidence 2026-11-21 22:30:04 +00:00
218e2bd1d5 Replace Context and Intent windows with unified two-pane foundation 2026-11-21 22:27:01 +00:00
221 changed files with 6102 additions and 3702 deletions

View File

@ -0,0 +1,67 @@
# Character workspace refinement — 23 November 2026
## Scope and preservation
This is a focused change to the main Character Details workspace and existing dedicated Relationship Evolution route. The five tabs, profile/gallery/aliases, character-level Evolution, appearances/knowledge, canonical Family/Story engines, Context, existing main editor and Timeline remain available. No manuscript-specific production rules or automatic deduplication were introduced.
## Phase 1 — ribbon
The existing Characters navigation remains in the ribbon. The redundant Characters/Timeline/Edit/Actions header controls are removed; the header retains portrait, identity, classification and analysis status. Edit Character and Actions now live in a selected-character ribbon group. Merge, Reanalyse, normal HTML character export, Markdown-format character export and Archive use their original controllers and forms. Markdown remains `Exports.Character(format=markdown)`; it was not reinterpreted. Owner/Collaborator editing checks, anti-forgery and the established Archive confirmation are retained; Viewer has export actions only. Each full character navigation renders the canonical ID into the shared ribbon partial. The dropdown uses Bootstrap with a fixed body portal so the horizontally scrolling ribbon does not clip its menu.
## Phase 2 — grouped relationships
SQL filters before grouping and orders by the other participant display name using case-insensitive `Latin1_General_100_CI_AS`, then canonical character ID. This is independent of A/B direction. Definition order within a group is controlled type name, then canonical definition ID. Queries page 25 character groups. Each group initially reads at most three definitions (75 total); a focused group pages all of its definitions in batches of 25. No client-side full dataset is loaded for sorting. Two identical display names remain separate canonical identities. Reciprocal flags remain one record; separately authored reverse records remain distinct.
Collapsed summaries show name, count, a few recorded types and meaningful states. Expanded groups show distinct definitions, direction/category, selected-point state, notes, initial/scene-established status and start/end links. Family filtering mirrors the existing `ContextFamily_Structure` / `ContextRelationshipLenses.Family` predicate, including canonical partnerships, and never infers family membership from participants or prose. Story filtering selects the other definitions. The graph lenses remain the existing engines. Search, paging and narrative cutoff are retained. Expanded group IDs and selected definition survive ordinary refreshes; empty groups disappear after removal.
## Phase 3 — actions and safe quick editing
Each definition has Edit, History and Remove. Inspect Connection previously only selected/highlighted the diagram; clicking or keyboard-selecting the record now preserves that function, and diagram selection reveals its canonical record. One contextual link replaces repeated full-editor links. History links to the exact existing Dynamics Relationship route; Advanced Evolution and the complete in-page history have been removed.
The focused native dialog reuses the established operation partial/controller, canonical controlled types and `Relationship_Save`. It edits type within the existing category, reverses direction explicitly, changes safe non-Family-category reciprocal representation, permanent status, reader awareness, initial state/intensity/reader awareness, and optional notes. Category is a property of canonical type, not an independent field. The definition ID is retained: no delete/recreate or inverse-record rewriting occurs. Pair identities, narrative boundaries, book and initial/scene-established status remain unchanged.
Structural changes with dependent events, cross-category changes and Family-category reciprocity changes are rejected atomically with an inline explanation and focused route to the full editor. Those operations can reinterpret historical/family semantics and lack canonical coordinated validation here. Notes and supported initial properties remain editable. The full editor deep link selects the requested definition if established at its current point; otherwise it explains why it is unavailable there. The full editor itself was not redesigned.
Removal retains the existing versioned, authorised canonical archive/event-delete operations, explicit scope/dependency confirmation and source-provenance guards. SQL locks and the original definition/history hash protect concurrent changes. Shared toast feedback and existing lightweight Context invalidation are reused; no new SignalR connection is created.
## Phase 4 — dedicated history
Diagnosis: the old graphic was a fixed-height decorative bright gradient, with an unlabelled positional strip. It rendered even with zero/one event, clipped edge markers, and substituted intensity 3 when no intensity was recorded. It did not explain axes or missing data. This was principally sparse-data/rendering/theme design, not missing canonical events.
The existing Dynamics Relationship route is retained. It shows exact names/type/direction/definition ID, canonical book/chapter/scene-ordered events, actual state and optional intensity, notes, evidence/review status, source links and retained continuity warnings. Event editing/removal uses the existing protected operation workflow on this page. Data is paged at 25. Empty/single-event cases get concise explicit presentations. Multiple verified recorded intensities get a compact labelled point plot, with no synthetic intermediate states or values for missing intensity. Narrow charts scroll internally instead of shrinking text or overflowing the page. Theme surfaces and text use existing application tokens. The source of ordering is the established canonical scene-order function; same-scene events sort by canonical event ID. The return link identifies the originating character, selected definition and narrative point, restoring selection/expansion in Relationships. Character-level Evolution remains separate.
## Qualification and Development delivery
Evidence, final regression results and deployed commit are appended after verification. The two pre-existing untracked investigation documents are preserved. Tests use rollback SQL fixtures or explicitly disposable Development browser characters only; no actual manuscript relationship is corrected, merged or removed.
### Database qualification
Forward-only migrations 309–313 were applied only to the verified `PlotDirector_Development` database. Each uses `CREATE OR ALTER` routines; existing applied numbered scripts remain unchanged. The backup `/var/opt/mssql/backup/character-refinement-20261123T105440Z.bak` completed with COPY_ONLY/CHECKSUM and passed `RESTORE VERIFYONLY`; no restore/reset occurred. The quick-edit procedure initially failed compilation because SQL treats parameter/local variable names case-insensitively; the unapplied procedure was corrected before successful application. No dependent application build was deployed during that failure.
The opt-in disposable-scope SQL suite passed and rolled back every case: 28 globally ordered groups, matching/case-varied names with stable identity, direction-independent grouping, 28 definitions in a single group with 25+3 focused pages, combined search/category filters and no deduplication; same-ID family type/direction changes; one-row story reciprocity; rejection of incompatible category, family reciprocity and semantic rewrites with history; canonical archive/restore retaining dependent events and independent reverse facts; one-event editing/removal; stale-history and permission/confirmation checks; source-linked blocking; dedicated canonical history pagination at 25+3 and stable same-scene event order. The final test confirms no fixture character remains from any rollback case.
Read-only real-manuscript acceptance used the actual Dapper readers: bounded explorers, SQL/.NET ordering agreement, selected-point future-knowledge exclusion, canonical management preview mapping and a sparse single-event dedicated history. The real-project relationship checksum was identical before and after; no AI work or manuscript mutation occurred.
### Regression and visual acceptance
`dotnet build PlotLine.slnx -m:1 --disable-build-servers` passes with zero warnings/errors. Single-process compilation avoids an initial CLR/build-server crash on this host. The full executable harness reports **786 PASS** and exits successfully. The 15 focused Character workspace service checks also pass after the final form/ribbon integration adjustments.
The rendered main-workspace Playwright suite passes: lazy tabs and retained profile/gallery/navigation; sorted compact groups with two directional definitions together; Family/Story filters; controlled type modal, inline stale validation, unsaved/Escape handling and full-width controls; selection/expansion after saves and exact-history return; archive refresh; correct relocated ribbon IDs after character navigation, Markdown-format link and anti-forgery forms; unclipped Actions menu at desktop/laptop/tablet/mobile widths; actual touch pan/pinch; stable Native/SI connection counts and Viewer controls. Browser fixture pagination is complemented by actual SQL all-page ordering tests. The dedicated history suite passes empty/single/five-event cases, actual intensity omission rather than fabricated values, canonical order/source navigation, exact return identity, event modal protection and Viewer restrictions. The existing Relationships Editor browser suite passes after the minimal deep-link integration.
Widths 1366, 1024, 768 and 390 pass without page-wide horizontal overflow. The compact chart has a bounded internal scroller on narrow screens. Screenshots `/tmp/character-refinement-grouped-dark.png` and `/tmp/relationship-evolution-dark-desktop.png` were visually inspected in the actual warm-dark theme. The final scoped outline-button adjustment improves contrast without changing the shared application theme.
No additional per-tab/component SignalR connections or complete-dataset broadcasts were added. Physical device/touch and assistive-technology screen-reader acceptance remain manual recommendations; browser tests cover touch emulation, keyboard, modal focus and responsive geometry.
The final dedicated-history browser check also performs a successful event-form save, verifies that the shared success toast remains visible and that only the bounded content is fetched (no document reload), then checks protected-source removal. Main workspace saves restore focus to the selected definition and retain its group. The exact full-editor deep link is tested after saved story-position restoration, in addition to the original editor regression scenarios.
The database suite reports **26 passing checks in 16 fully rolled-back cases**. Build, focused service checks, main-workspace browser, dedicated-history browser and main Relationships Editor browser all pass for the delivered refinements. Deployment evidence follows.
### Verified Development release
Deployed application commit: **`7fa095409cea95994bb68850b8fb4574daff5730`** (`7fa0954`). Release archive: `/srv/apps/plotdirector-dev/releases/character-refinement-qualified-7fa0954-20261123T112320Z`; preserved prior installation: `/srv/apps/plotdirector-dev/current-before-character-refinement-qualified-7fa0954-20261123T112320Z`. The pre-stop import/SI/synthesis/enrichment guard passed. Deployment preserves live configuration, keys, uploads and logs. A verification-helper asset-prefix typo stopped the initial hash loop after installation; the paths were corrected and every intended DLL/CSS/JS hash was then verified without another installation. The service is active, normal-TLS public HTTPS GET and local GET return 200, and assembly informational version identifies this exact commit. Recent logs have only the existing HTTPS-redirection port warning, with no application failures.
Authenticated Development acceptance passed on an exclusively disposable account: Supporting creation default; current-character ribbon IDs through direct/cross-character back/forward/reload; all five tabs; canonical Parent creation; dedicated empty History and exact selected/expanded-group return; actual same-ID Child/type and explicit direction update; dirty navigation rejection; explicit removal preview; archive and Family/Story refresh; exactly one Context hint per add/edit/archive; final fixture character archive. Test-only async-modal and MVC hidden-checkbox selector errors were corrected; their isolated leftovers were safely soft-archived before rerunning. No application repair or redeployment was needed for those test errors.
A separate read-only authenticated check verifies Edit/Merge GETs, actual HTML and Markdown export responses, the correct reanalysis ID/anti-forgery form (without queuing AI work), and the relocated Archive confirmation opened and cancelled. The actual My Windows suite passes existing-main reuse for scene, character, Names and Relationships with unchanged Context scene and no Word navigation. Final SQL integrity smoke confirms no active qualification character or relationship remains in either direction, both baseline fixture characters remain active, and the final new fixture and its exact relationship are archived.
Production was untouched. Actual manuscript relationships, including those specifically protected in the brief, were never corrected, merged or removed by testing. The original two untracked investigation files remain untouched. The application release above is followed only by test/evidence updates; those do not change the deployed application.

View File

@ -0,0 +1,73 @@
# Context Family tree redesign — 22 November 2026
Requested base: deployed `d955971`; repository evidence-only HEAD was `4678617`. Scope is the Context Family lens. The Story lens, main Relationships editor, canonical relationship types and manuscript records are preserved. Production is outside scope.
## Family identification and scene index
The index starts from explicit physical participants under existing canonical presence rules, plus the POV independently of presence. Mentioned Only overrides a contradictory presence label. Names/surnames, scene co-occurrence, residence, friendship, hostility and professional partnerships never establish membership.
New `ContextFamilyTopology` builds connected components over supported canonical parent/child, biological/adoptive/step parentage, recorded marriages/family partnerships, siblings/half-siblings and explicit aunt/uncle/niece/nephew/cousin links. Parent direction must be unambiguous. Iterative strong-component analysis excludes ancestry-cycle edges; descendants of a cycle are not automatically branded as cycles. Reciprocal parent/child, self-links, unknown type semantics and guardianship alone do not establish genealogy. Known unverified primary evidence for a relationship's establishing scene is excluded by the reader. Other canonical author-established relationships retain their existing authority; no verification field or knowledge engine is invented.
One entry represents each eligible connected family structure. Its key is the smallest canonical character ID in the component, and its label uses up to two recognisable scene characters, with POV first. Other entries sort predictably by label and ID. Explicit marriage can connect ancestral branches into a broader navigable family; actual parentage remains separately recorded and drawn. An individual with no qualifying relatives gets their own entry. Three compact buttons plus More are used where needed; panes narrower than 560px use a labelled selector.
Initial/new-scene selection prefers the POV family. Same-scene manual exploration survives notifications. Each pane is independent. A scene change resets the default family choice without recalculating an unchanged layout; if the same POV remains focused, pan/zoom need not reset. No new pinning system.
## Genealogical layout
The existing small deterministic SVG layout is extended, without a new graph library. Explicit directional ancestry establishes vertical generations; partners and recorded siblings align only where ancestry permits. Reliable birth dates order known siblings. Separate parental rails retain biological, adoptive and step semantics. Children attach beneath their actual recorded parent, or beneath an explicit recorded partnership when compatible parentage exists for both partners. Co-parentage alone creates no partner or union marker.
Multiple partnerships have separate rails and children keep their exact recorded parent links; half-siblings do not acquire each other's second parent. Single parents remain single. Ended/former partnerships remain visible with dashed status. Deceased and archived relatives remain visible; archival does not imply death. Global life status retains its existing author-reference label.
Orthogonal generation-gap buses and outer corridors for skipped generations avoid unrelated cards. A connector halo distinguishes crossings, and junction dots identify explicit parental unions. Unknown relatives/ancestry are never fabricated. Explicit kinship without enough parentage to place generations is shown with an explanatory warning. Structural signatures exclude notes/state-only changes; unchanged structures keep their cached deterministic layout. The graph retains readable 180×66 cards, pan/zoom and fixed text sizes.
## Compact branches and retained state
Initial visibility includes the focus, recorded adjacent relatives, siblings supported by common recorded parentage and nearby recorded partners. It does not load all generations into the browser. A node's + appears only when additional recorded adjacent relatives exist. Its accessible title gives an exact count of hidden adjacent relatives, not a speculative total descendant count. Expanding adds recorded neighbours; − removes that expansion. No expansion creates people or relationships, and it cannot open an editing modal.
Each tree request reauthorises book, scene, project and focus. Expansion IDs must belong to the selected component. If a membership edit makes previously saved expansion IDs obsolete, the refreshed index/tree reconciles the component and retries a compact tree. Concurrently changed returned records are rechecked so disconnected physical participants cannot remain in the selected tree. Branch changes preserve the selected person's screen position where practical.
Each pane retains at most 12 recently used family view states: focus, selection, up to 64 expanded nodes, pan, zoom and layout. Only the current Family data response and existing Story response are cached. A book change discards the previous book's family state. State is in-window lifecycle state, not unlimited persisted diagrams or a new cross-window messaging system.
Family gestures permit drag/pinch from cards or connectors after a movement threshold, preserving taps for selection and protecting branch controls. This addresses mobile touch target adjustment near cards. Story gesture semantics remain unchanged. Branch controls support touch, Enter and Space; SVG keyboard pan/zoom and the shared correction modals remain available.
## Services, queries and safety
`ContextRelationshipLenses.Scope`, canonical characters, existing narrative ordering, `RelationshipMapService.BuildAtScene` projection, verified evidence projection, existing focused relationship editing, shared `PlotDirector.toast`, Context invalidation and My Windows remain authoritative. No additional SignalR connection, name inference, new relationship category, inline application SQL or bulk canonical migration.
Forward migration **305_ContextFamilyExploration.sql** adds two read-only stored procedures. Structure returns only eligible seed names and at most 8,193 relationship metadata rows (the 8,193rd is a rejection sentinel). The server identifies components; it never sends the project membership graph to the browser. Tree returns at most 128 requested identities and 256 requested canonical links, with existing minimal narrative ordering metadata (20,000-item limit) and at most three verified developments per visible link through the existing event reader. Additional character details are fetched when a branch is expanded. No complete manuscript or relationship history is fetched for the tree. Very large metadata requests fail explicitly and retain a full-editor route rather than silently declaring incomplete families unrelated.
Development-only backup `context-family-20261122T194552Z.bak` succeeded with CHECKSUM and VERIFYONLY. Effective database was verified as `PlotDirector_Development`; only migration305 was applied. No canonical rows were changed by the migration. Backup verification is not claimed as a restore test. Original untracked investigation documents were preserved.
## Verification evidence
Isolated canonical fixtures cover separate families in one scene; actual siblings sharing an entry; biological versus adoptive parentage; single parents; exact half-sibling parentage; multiple marriages; step relations; isolated individuals; cyclic/ambiguous records; membership merge/split after editing; independent POV inclusion and mentioned-only exclusion. Service tests cover Viewer access, project/book isolation, selected-component-only snapshots and foreign branch rejection.
Browser interaction acceptance covers one family at a time, POV bias, More and compact selectors, branch +/−, keyboard activation, preserved family zoom/selection through notifications, obsolete expansion recovery after a split, regrouping after a merge, independent panes, new scene POV defaults, and eviction after 12 retained families. Responsive cases include full-width, half-width columns, stacked panes, 390px mobile and two simultaneous Relationships tools. Existing Family/Story browser regression retains exact Story scene-state, direction, focus and editing checks.
Layout assertions cover four generations, biological/adoptive/step styles, multiple partners, exact parentage, known birth order, no invented union for co-parents, no overlapping cards and orthogonal paths avoiding unrelated cards. Large/deep metadata fixtures exercise the bounded server selection and iterative ancestry traversal. Touch-emulated Chromium covers branch taps without editing, card selection, real CDP drag and pinch, zoom, lens switching and no document horizontal overflow. Physical-device/PWA installation is not claimed.
Additional real-manuscript acceptance used existing authorised Development data read-only: one eligible scene identity and scene-family entry, plus two additional recorded family components. Three deidentified snapshots contained ten visible identities and eight recorded connections, with no overlapping cards or invented identities. Canonical relationship checksums were unchanged before/after. No real manuscript relationship was edited. This is structural data acceptance, not author editorial approval of every family.
Final qualification: solution build succeeded with **zero warnings/errors**; full executable regression harness completed with **770 PASS lines and exit0**. This includes 21 new Family domain/access/performance assertions, existing Family/Story and focused-editing regressions, and the wider application harness. Broad/deep 4,096-edge metadata fixtures completed in 72ms on this host (an observed fixture result, not a database latency guarantee). Actual SVG connector hit selection, membership merge/split recovery and the 12-family state bound passed in the Family browser. Existing shared modal acceptance passed all nine character/name variants plus relationship forms; My Windows real-SignalR isolation/reconnect passed; shared notification and touch/gesture checks passed. No forced browser clicks or modal/authorisation bypasses.
Predeployment evidence: `/tmp/context-family-final-build2.log`, `/tmp/context-family-final-regression.log`, `/tmp/context-family-final-browser.log`, `/tmp/context-family-final-story-browser.log`, `/tmp/context-family-final-shared-browser.log`, `/tmp/context-family-final-windows-browser.log`, `/tmp/context-family-final-touch.log`, `/tmp/context-family-notifications.log`, `/tmp/context-family-readonly-final.log`. Deployment and live endpoint/editing evidence are recorded below after installation.
## Limits / future manual acceptance
- Explicit cousin/aunt/uncle and similar kinship without parentage cannot reliably establish missing ancestors or precise generations. The interface labels this limitation rather than inventing them.
- Ambiguous or unsupported records require correction in the existing Relationships Editor; excluded records are not used to merge index entries.
- Membership metadata is bounded at 8,192 project family records, a visible tree at 128 people/256 links and retained state at 12 families/64 expansions. Larger structures require recentering or the full editor; metadata beyond the hard limit needs future incremental membership infrastructure.
- Author-reference truth is independent of POV knowledge. No new viewpoint-knowledge, biological inference or first-meeting logic is provided.
- Physical phones/tablets, installed PWA windowing and screen-reader review remain manual acceptance. Editorial review of representative author-owned complex families is recommended; those records were not modified for testing.
Final exploration-state acceptance also verified re-centring on a visible relative and searching back into a previously visited family: zoom and expanded branches are retained, with at most one bounded restoration retry after the server resolves the canonical component. Evidence: `/tmp/context-family-state-browser.log`, `/tmp/context-family-state-story.log`, `/tmp/context-family-state-touch.log`. The Story regression uses normal keyboard pan to reach an offscreen branch at the restored zoom. No .NET domain changes followed the 770-PASS run.
## Development delivery
Deployed source commit **`6ba409220aa3d8071d447c722e5ecdb7fc342427`** (implementation `f357cbd`, exploration-state follow-up `6ba4092`). Release: `/srv/apps/plotdirector-dev/releases/context-family-final-6ba4092-20261122T201055Z`. The active import/Story Intelligence/synthesis/enrichment guard passed immediately before restart. Service active; local/public HTTP200 with normal TLS verification; deployed assembly informational commit and all 12 published/live assembly/assets SHA-256 hashes matched. Deployment manifest: `/tmp/context-family-final-deployment.json`.
Actual authenticated API acceptance initially returned a useful empty index on the old qualification scene, which correctly had no POV and no explicitly physical participants. Only that disposable fixture was then prepared through the existing `SceneCharactersEditor`/`SaveSceneCharacters` form: its two known synthetic participants were marked Present, any Mentioned Only role was changed to an available ordinary role, and its first synthetic character became POV. Other submitted participation fields were preserved. No real manuscript participation or POV was modified.
Live focused Family acceptance then established a canonical family connection between those synthetic characters: two index entries became one. A further focused correction persisted, refreshed the selected connection in a second authenticated window and produced no receiving success toast. Each Context retained one SignalR connection and sent no Word navigation. The general live character/name/life-status/relationship edit regression passed as well; its Names step now waits for the already-queued originating-panel refresh before repeating an identity lookup. Actual main-window navigation passed Scene, Characters, Names and Relationships without an extra window or changed Context/Word position. The original main editors remain functional.
Postdeployment evidence: `/tmp/context-family-live-prepared.log`, `/tmp/context-family-presence-confirmed.log`, `/tmp/context-family-live-editing-final.log`, `/tmp/context-family-live-navigation.log`. Development journal had no error categories and only the pre-existing HTTPS-redirection warning. Production was not accessed or changed; the original two untracked investigation files were preserved. Existing Context windows should reload once to acquire the updated scripts. Physical-device/PWA and screen-reader/editorial acceptance remain the manual items listed above.

View File

@ -0,0 +1,70 @@
# Context UX refinement, Names Library and visual relationships
Development-only programme requested 22 November 2026. Base implementation: `504ecca`; evidence-only follow-up `2eede4e`. Existing untracked user investigations remain untouched. Production is outside scope.
## Stage 1: shared UI and main-window reuse
Shared correction form geometry gives all controls full available content width, consistent spacing, minimum textarea height and vertical resizing. The shell dialog responds to viewport width independently of its originating pane. Loaded forms expose one Save and one Cancel; the shell fallback Cancel appears only if loading fails. Nested labels, initial input focus, Escape, inline validation, dirty-draft confirmation and the shared toast service are retained.
Main navigation extends `ContextWindows` / the existing authenticated presence hub with `workspace.open` and a closed structured target `{tool, entityID}`. `ContextNavigationController` resolves permitted Characters, Names, Relationships and Scene targets from canonical IDs after book/project/entity checks. No caller-supplied URL is accepted. Main shells register on the existing native presence connection; a shell without that connection creates one shared connection, not one per feature. Context windows retain their one connection.
A user/browser-profile environment preference restricts automatic main navigation to the same browser environment. It is not an authentication credential: every command and destination is independently authorised. Normal reference focus commands retain their book isolation; main navigation is explicitly allowed to an authenticated same-user main shell currently showing another book, because it revalidates the requested book before navigating. Another environment/device is never selected automatically. Browser-private/storage-disabled environments cannot share this preference and use the named-window fallback.
Main recipients acknowledge navigation, attempt focus where permitted and protect unsaved ordinary forms; Maps uses its existing `requestLeave` guard. Busy/declined/unconfirmed requests do not automatically open another window. Missing recipients use one named main window and an account/environment-scoped ten-second launch reservation in the existing registry to suppress concurrent fallback opens. Blocked popups retain an explicit named link retry. Focus and named-window targeting remain subject to browser security and browsing-context isolation. Transient leases, reconnect registration, authenticated IDs and data-change notifications remain separate from navigation. No Word navigation is requested.
Context workspace links use `data-context-workspace-target` plus optional `data-context-entity` as the reusable standard; href remains an accessible fallback. Existing main editors are not redesigned.
Stage 1 qualification: clean solution build (zero warnings/errors), 19 registry/routing/lease assertions, real-SignalR isolated browser routing suite, existing Characters editing/responsive suite and expanded shared-refinement browser acceptance passed. Every existing character/name correction variant (classification, description, emotional state, physical condition, location, canonical name, alias add and alias correction/removal) and the relationship form was checked for full-width controls; desktop/mobile, one Save/Cancel and Escape passed. Existing-main reuse, repeated actions, unsaved-main cancellation and one named missing-main fallback passed. Browser fixture editor endpoints render the real application shell/views; canonical persistence is qualified separately. Relationship main-editor navigation retains the selected story point. No database migration was needed in this stage.
Stage 1 deployed at `5de6e5f`, archive `context-refine-stage1-5de6e5f-20261122T162449Z`. Published/live assembly and all changed navigation/form assets matched SHA-256; clean active-job guard before restart; service active. Actual Development acceptance reused one existing main window for the real Scene, Character, Names and Relationships editors, kept the Context scene unchanged and sent no Word navigation. Focus remains discretionary in the browser. No canonical edits were made by this navigation check.
## Stage 2: Names Library discovery
Names now opens with bounded reference-library candidates rather than an identity catalogue. It calls the same `INameIntelligenceService.BuildLibraryAsync` with the complete existing `NameSearchFilter`: search, locale, birth year, gender preference/threshold, type, minimum commonness, project/book/accessible-project usage scope, used/unused, page and page size. No replacement database, generation or matching engine. Profiles retain existing prior weights, era, confidence, source, related forms and usage summary. Copy uses the clipboard and shared toast. Additional filters collapse; layouts use pane containers. Search cancellation propagates to the existing library query. Pagination retains criteria; pane state is independent.
The tool is book-scoped, works without an active scene and does not reload just because the scene changes. Exact established-name/alias lookup and candidate project-use inspection reuse `GivenName_UsedDecorations`, now bounded to 100 distinct use records. Canonical identity/aliases load only after explicit selection, with existing focused name/alias modals and My Windows character focus. No automatic merge or rename. The obsolete alphabetical presentation and separate suggestion-only partial were removed.
Underlying shared-query correction (migration299): the existing Name Search book-usage CTE joined every character to every book in its project, so unused-in-this-book could be reported as used. It now uses the same canonical SceneCharacters→Scenes→Chapters→Books membership joins as existing usage details. Project scope still includes project identities without appearances; Book scope requires a recorded appearance. Mentioned-only participation can establish name use, which does not establish physical presence or POV knowledge. No manuscript text matching or invented name-use evidence. The main controller now interprets its existing book scope selector correctly; hidden scope/pagination metadata preserve explicit criteria. The main UI is not redesigned. Nonvisual result IDs/counts permit exact parity acceptance.
Both live procedure definitions were checked against the previous authoritative migration before applying the new forward-only definitions. Development backup `context-refine-stage2-20261122T163128Z.bak` succeeded and VERIFYONLY passed. Migration299 applied and its procedures were smoke-verified. No canonical data rows were changed by the migration. Disposable qualification added one empty book and one reference-name alias on the existing synthetic character; shared-query acceptance proved used in the character's appearance book and unused in the empty second book.
Stage 2 predeployment qualification: clean solution build, seven direct library/filter/bounded-identity/read-only assertions, 17 existing character/name-edit assertions, stored-procedure architecture guard, actual compiled Razor browser with all filters, 100 candidates, profile/related forms/copy, on-demand identity/correction, pagination, independent panes and full/half/stacked/mobile passed. Touch-emulated 390px browser checks passed. Full Development query-parity acceptance follows installation. Existing open application/Context windows should reload once to acquire the updated tool scripts; no Word navigation is part of that reload.
Stage 2 deployed at `4857329`, release `context-refine-stage2-4857329-20261122T164213Z`. Local/public GET200, informational commit and assembly/assets verified (including the new Names module). Ten actual Development main/Context searches matched exact ordered candidate IDs and used counts, covering empty/uncommon/near-prefix, aliases, used/unused, book/project/accessible-project scopes, all meaningful filters, two active locales and pagination. The alias was used in its appearance book and unused in the empty qualification book. Live focused editing with quiet second-session refresh and existing-main navigation passed again. No physical PWA/device acceptance is claimed.
## Stage 3: Family and Story visual lenses
The previous text list is replaced with two purpose-built SVG views. Both use the canonical relationship records, existing narrative ordering and `RelationshipMapService.BuildAtScene`, existing verified evidence projection, existing focused relationship editing/services, My Windows and shared notifications. No new graph framework or story-state engine. Family defaults to POV, represents author-established structure independently of POV knowledge, keeps historical/archived relatives, and never manufactures missing relatives. Explicit directional parent/child, biological/adoptive/step and ancestor links control generations; spouses/partners align, known siblings group with reliable birth dates, multiple unions and half-siblings are preserved. Ambiguous/cyclic records are labelled rather than guessed. Canonical professional partnerships are not family unions.
Story prioritises explicitly physical participants (a Mentioned Only role overrides a contradictory presence label), preserves direction/reciprocity, uses category colours and a legend, and excludes future starts, later changes and unverified primary evidence. Selected links show current state and at most three established changes. The interface expressly avoids inferred first meetings, mutual trust or viewpoint knowledge. Global death status is excluded from Story DTOs because it has no narrative timestamp. No optional viewpoint-knowledge filter is offered: the available canonical data cannot reliably provide one.
Readers use new authorised stored procedures, bounded at 128 characters, 256 links and three verified events per link. Only canonical ordering metadata is read across the project (20,000-item safety limit); no manuscript or complete relationship histories. Lookup is literal escaped name/alias matching, minimum two characters and 25 results. Family expansion is bounded to six connection steps, with boundary messages and recentering for further exploration. Nodes retain readable size and support mouse/touch pan, pinch/buttons/wheel zoom and keyboard exploration. Per-pane lens/focus/pan/layout state survives switching; structural signatures exclude state-only changes so manuscript notifications do not reposition unchanged families. Recorded-connections disclosure provides accessible disambiguation in complex graphs.
User explicitly approved a canonical deceased-status field in response to the data-model question. `Characters.IsDeceased` is nullable: NULL Unrecorded, false Living, true Deceased. No backfill or inference from archival/imported prose. Family and character reference views label it as global author reference, without death-date/scene/knowledge claims. An existing shared focused modal saves only this field with SQL permission checks and nullable original-value comparison. The main Character form exposes the same optional field; unchanged/legacy saves preserve it. Backup export, stored-field contracts, JSON roundtrip, canonical reads and timeline projections include the field; older backups remain compatible.
Database qualification: migration300 applied after verified backup `context-refine-stage3-20261122T170555Z.bak`. Life-status backup `context-refine-life-20261122T173415Z.bak` succeeded and VERIFYONLY passed. Migration301 installed the nullable field and save/read procedures, then stopped on differently formatted deployed projection headers. Migration302 stopped before projection changes because of a malformed comment. Both attempts are preserved unchanged. Forward303 completed projections, and standalone idempotent **304_CharacterLifeStatusCanonical.sql** consolidates the complete authorised definition for future environments. Use 304 directly for this field, not a blind replay of 301–303. Exact Character_Save preflight matched authoritative previous logic; all projection anchors were checked before applying. Final schema/procedure smoke passed. Transactional tests proved nullable CAS rejects stale saves, legacy full saves preserve status, explicit full-editor saves update it, and rollback leaves all canonical statuses unrecorded. No real manuscript records changed.
Stage 3 qualification: solution build zero warnings/errors; 10 visual-domain assertions, 12 focused relationship assertions and 21 character/name/life-status assertions passed. Layout tests cover four generations, multiple spouses, half-siblings, adoption/step/Child reversal, unknown/cyclic/cross-generation records, reliable birth order and 120 nonoverlapping nodes; Story sizes 1–128 are checked for nonoverlap. Actual compiled Razor browser passed SVG hit selection, source-specific modal, 120-node family, dense 45-edge network, scene changes, independent panes, full/half/stacked/mobile, keyboard pan/zoom, read-only controls, and zero family layout recalculations on state-only notification. Family death indicator and Story omission are tested. Full integration and actual Development persistence follow installation.
Stage 3 deployed at `01a7723`, archive `context-refine-stage3-01a7723-20261122T173935Z`. Clean active-job guard immediately before restart; local/public HTTP200; informational assembly commit and SHA-256 assembly/graph/form/navigation/CSS matches verified. Actual Development browser passed single-field life-status persistence, Family-only DTO status, Story omission and restoration of the original value on the disposable character. Relationship create/correction and selected-link refresh in a second authenticated browser session passed, with zero receiving success toasts, one native SignalR connection per Context and no Word navigation. Other real manuscript data was not edited.
## Stage 4: integrated qualification and final delivery
Full executable regression harness completed successfully with **748 PASS lines and exit0**. Final solution build passed with zero warnings/errors. Full harness includes the new Family/Story, character life-status and existing relationship/Names/routing/permissions/backup contracts. Compiled-browser acceptance passed all nine character/name modal variants plus relationship at desktop/mobile, one Save/Cancel, Escape, main-shell reuse/unsaved guard and bounded fallback. Names browser covered all criteria, 100 results, profiles/related forms/copy, usage/identity corrections, pagination, independent panes and full/half/stacked/narrow layouts. The live main/Context Names parity suite passed all ten equivalent queries again on this release, including unused-in-the-empty-other-book behaviour.
Real-SignalR My Windows acceptance passed exact recipient/pane-only reload, no-handler behaviour, cross-user/book/story-point rejection and reconnect recovery. Actual Development navigation passed all four main workspaces with no extra window, no Context scene change and no Word navigation. Browser test adjustments use SVG attachment for zero-width vertical edge groups and dismiss the existing navigation toast through its normal accessible button before a later footer click; no forced clicks or product guard bypasses. Actual Development editing passed description/alias persistence, cancel/unsaved handling, retained failed inline name draft, life status, relationship correction, quiet second-window refresh and one connection per Context.
Chromium touch emulation at 390px passed character/name disclosure taps, graph person selection, zoom buttons, real CDP touch drag and two-finger pinch, Family/Story switching and no document horizontal overflow. Full/half/stacked/mobile graph cases retain legible fixed node dimensions; complex family/network interactions were exercised rather than only HTML assertions. Visual review shortened graph captions and corrected selected-lens contrast using existing theme tokens. Physical phone/tablet, installed PWA/windowing differences and assistive-technology review remain manual acceptance items; no physical-device or PWA-installation claim is made.
Development journal since Stage3 restart had zero error categories and only the existing HTTPS-redirection warning. Final Stage4 release records its source commit, archive, pre-restart guard and published/live hashes in deployment evidence. Existing open windows should reload once to receive the new modules. Production was not accessed or modified. The two original untracked investigation documents were preserved.
### Practical limits / remaining manual acceptance
- Browser focus is discretionary. Private/storage-isolated profiles cannot locate another profile's main window and use one named fallback; physical devices are never selected automatically.
- Author-reference Family truth and global life status can reveal author knowledge. Story excludes global death status and later narrative developments; reliable death-at-scene/POV knowledge is not modelled or invented.
- Inspect a representative author-owned complex family and dense scene for editorial readability. Ambiguous canonical/cyclic types are labelled; very large views use explicit bounds and recenter/expand rather than loading every record.
- Physical-device touch, installed desktop/mobile PWA behaviour and screen-reader acceptance remain manual.
Key acceptance logs on this host: `/tmp/context-refine-stage4-regression.log`, `context-refine-stage4-build.log`, `context-refine-stage3-polish-browser.log`, `context-refine-stage3-shared-browser.log`, `context-refine-stage4-touch.log`, `context-refine-stage4-names-browser.log`, `context-refine-stage4-names-parity.log`, `context-refine-stage4-windows.log`, `context-refine-stage4-navigation-final.log`, `context-refine-stage4-live-editing-final.log`. These contain no credentials. SQL backup verification is not claimed as a restore test; life-status compatibility was checked by canonical JSON roundtrip, stored-field harness contracts and rollback-protected SQL save smoke.
Final Stage4 deployed source commit **`d9559713a5beef504f9ca595a8287693c8056256`**, release `/srv/apps/plotdirector-dev/releases/context-refine-stage4-d955971-20261122T174505Z`. Clean Development active-job guard, service active, public/local HTTP200, informational version and all twelve published/live assembly/assets hashes verified. Postdeployment authenticated Family/Story/lookup reads passed: authorised focus, bounded responses and no global life-status value in Story. Final deployment manifest: `/tmp/context-refine-stage4-deployment.json`; authenticated smoke: `/tmp/context-refine-stage4-final-health.log`. Implementation commits: Stage1 `5de6e5f`, Stage2 `4857329`, Stage3 `01a7723`, Stage4 `d955971`.

View File

@ -0,0 +1,96 @@
# Main Character workspace redesign — 23 November 2026
## Phase 1 audit / preservation contract
Audit starts at `CharactersController.Details` → `ICharacterService.GetCharacterDetailAsync` → `Views/Characters/Details.cshtml`. The current GET loads every project character, relationship lookups/books, this character's relationship containers/events, the whole project character timeline and story timeline, all appearances, attribute events, knowledge and gallery images. This work precedes even the profile render. Existing URLs `/Characters/Details/{id}` must stay valid.
| Existing capability | Current persistence / source | Workspace destination |
|---|---|---|
| Breadcrumbs, project ribbon, character/timeline return | Existing navigation and authorised IDs | Persistent shell/header |
| Portrait, thumbnail fallback, name | Canonical Characters / shared `_Avatar` | Compact persistent header |
| Major/supporting/minor importance | `CharacterImportance`, existing character create/edit/save | Header + Overview; explicit values preserved |
| Preferred name, aliases, set preferred | CharacterAliases; `SetPreferredName` service/action | Overview names dossier, same action |
| Description, sex, DOB, age/reference scene, height, eye colour, life status | Character edit/save; canonical age display service | Overview identity/profile; existing full edit |
| Generated summary, generated DOB/age/physical facts, status/message/last analysed | Character enrichment persisted status, existing reanalyse POST and SI hub | Overview analysis, separate from canonical profile; header reanalyse |
| Full character edit, merge | Existing Edit/Save and Merge services/actions | Header actions / Overview |
| Character export (normal/Markdown), archive/restore | Existing Exports and canonical archive operations | Header actions, archive retained |
| Gallery upload/caption, full image, crop/set avatar, remove avatar/image | Existing UploadImage/CropAvatar/DeleteImage/RemoveAvatar | Overview gallery disclosure and bounded page; same actions |
| Initial relationship add/edit; type, partner, state, intensity, reciprocity, reader awareness, initial book, notes | `SaveInitialRelationshipAsync` → canonical `Relationship_Save` | Relationships focused definition editor; advanced structural editing remains linked |
| Initial relationship removal/restore | `ArchiveRelationshipAsync` → `Relationship_Archive` → `Archive_Entity` | Direct confirmed Remove relationship on every related record |
| Current relationships, categories, direction, intensity/notes | Canonical relationship definitions + verified ordered events | Relationships Family/Story lenses + bounded records |
| Per-relationship initial/current state and event history | RelationshipEvents, canonical ordering/evidence projection | Selected relationship chronological history, bounded loading |
| All relationship events + related character/timeline links | `RelationshipEvent_ListByCharacter` | Relationship history filter and Evolution relationship category, preserving source links |
| Attribute history with values/descriptions/sources | CharacterAttributeEvents / canonical classifications | Evolution chronological explorer |
| Arc charts, scene metrics/markers, appearance/knowledge/relationship KPIs, continuity issues | Existing `Dynamics.Character`, dynamics services | Explicit Advanced arc / charts link in Evolution (existing endpoint retained) |
| Scene appearances, presence/role, outfit, condition/emotion, timeline/source | SceneCharacters + scenes/chapters/books | Appearances grouped, filtered, paged explorer |
| Canonical knowledge state, asset/thread, description, source point | CharacterKnowledge + canonical KnowledgeStates / evidence | Knowledge searchable/paged explorer with narrative cutoff |
| Existing knowledge timeline and continuity/review workflows | Dynamics.Knowledge, canonical Scene editor / Review Centre | Clear links in Knowledge; no generated prose reconstruction |
| Old fragment bookmarks `#character-overview`, `#character-gallery`, `#character-relationships`, `#character-appearances` | Existing anchor navigation | Mapped into the matching tab/disclosure by the workspace router |
### Removal audit
`IsReciprocal` is stored on one `CharacterRelationships` row. Canonical `Relationship_Save` updates/inserts that row; it does not manufacture a reverse row. Independently recorded reverse/different-type rows are separate authored facts and must be disclosed, not silently deleted. `Relationship_Archive` delegates to `Archive_Entity`, which marks only the definition archived with timestamps; dependent RelationshipEvents remain intact and restoration is available in Archived Items. This is the correct reversible removal operation for an erroneous parent/child definition, including one with historical events. The confirmation must name both characters, type, event count and separately recorded reverse/pair records retained.
`RelationshipEvent_Delete` is the existing single-event deletion operation. Event removal must stay distinct from definition archive. Dependencies/provenance must be checked before deletion and unsafe linked events must be blocked with their existing source/review route. New workspace management must wrap canonical operations with project permissions and original-record comparison under SQL locks, not introduce another delete implementation. No actual manuscript relationship is to be modified for testing.
### Classification audit
Main character creation already defaults to Supporting (importance6). Scene quick-create currently leaves importance unrecorded, rather than explicitly Major. Existing author values and classification thresholds must not be migrated. Header labels will use Major ≥8, Supporting ≥4, Minor ≥1 and Unclassified otherwise; edit choices remain available through the existing editor.
Implementation and phase validation evidence follows below.
## Implemented workspace and phase acceptance
The existing Character URL and ribbon now lead to a compact persistent identity header and five primary tabs. The shell reads identity, permissions, counts and age candidates; tab fragments fetch only their required bounded data. Tab, query, page and narrative point survive navigation; the remembered tab is scoped to the signed-in user and project. Existing fragment bookmarks map to their destination. Native dialog forms retain drafts on validation/concurrency failure, protect navigation and use the shared toast service. Existing presence and Story Intelligence connections are reused; tabs do not open connections.
- **Overview:** responsive dossier with all canonical profile/age/life-status fields, known names and preferred-name action; description disclosure; bounded canonical family/story definition summaries; counts and three recent changes. Persisted enrichment is separate from author profile. Gallery retains uploads, captions, full images, avatar crop/set/remove and image removal, paged at 25. Full edit retains all aliases beyond the 50-name overview bound.
- **Relationships:** reuses `ContextFamilyExploration`, its topology, project tree reader and the shared genealogical layout engine, including biological/adoptive/step links, partnerships, vertical generations and expandable recorded relatives. Family remains global author reference and works without a book/scene. Story reuses the canonical Context reader, relationship projection and selected-scene ordering. The diagram is bounded at 128 people/256 connections; re-centering explores further. Records are paged at 25 with selection synchronised to the diagram. Independently authored relative-to-relative links are managed from the appropriate relative's workspace.
- **Evolution:** narrative book/chapter/scene groups, expandable changes, previous attribute values, actual classifications, evidence flags, book/category/search filters and source links; 25 entries per page. Existing charts, metrics, continuity issues and scene markers remain in the clearly linked advanced Arc workspace.
- **Appearances:** 25-entry searchable/grouped pages retain role/presence, POV, appearance notes, outfit, condition, emotion and knowledge notes, plus direct scene/timeline links.
- **Knowledge:** uses actual canonical knowledge-state text, source/evidence and review flags; search, book/state filters and narrative cutoff. Author reference does not imply viewpoint knowledge. Existing knowledge timeline and review/source workflows remain linked.
### Focused relationship management
Definition editing deliberately preserves pair, type, direction, book and narrative boundaries. It supports notes and, for initial definitions, state/intensity/reader awareness. Structural edits remain one clear link away in the existing full Relationships Editor. Individual history events have their own focused state/intensity/awareness/description editor; event removal is explicitly distinct from definition removal.
Removal confirmation names both characters/type, identifies definition versus single event, reports dependent event count and independently authored pair records, and requires explicit confirmation. Definition removal calls canonical `Relationship_Archive`, retaining all events and Archived Items restoration. Single-event removal calls canonical `RelationshipEvent_Delete`. Evidence, review provenance or possible knowledge-source dependencies block direct event editing/removal and link to the source workflow. No second store or deletion implementation was introduced.
The new stored-procedure wrapper revalidates Owner/Collaborator access, relationship membership and SHA-256 definition/history version under SQL locks before invoking canonical save/archive/delete procedures. New history invalidates stale previews. Successful writes log canonical project activity and publish existing Context invalidation hints; the active list and diagram refresh without a page reload. Viewer controls are hidden and writes are independently rejected server-side.
### Database rollout
Forward-only migrations 306 (bounded reads), 307 (authorised/concurrency-safe canonical management) and 308 (bounded definition summaries) were applied only to the verified `PlotDirector_Development` database. Existing numbered files were not changed after application. Before application, unique COPY_ONLY/CHECKSUM backups completed and passed `RESTORE VERIFYONLY`:
- `/var/opt/mssql/backup/character-workspace-20261123T093043Z.bak`
The additional summary migration backup `/var/opt/mssql/backup/character-workspace-summary-20261123T095708Z.bak` also passed verification. These backups were verified, not restored. Migrations add/alter routines, with no bulk character or manuscript relationship mutation. Main create remains Supporting6; new scene quick-created characters explicitly use Minor2; existing values are unchanged.
### Integrity and regression evidence
`CharacterWorkspaceTests` adds 15 passing service cases covering a thin header, bounded data, canonical ordering and future-state exclusion, labels, invalid queries, dependency previews, confirmation, stale/protected records and permissions. The explicit `--character-workspace-database <disposable-scope>` mode validates effective Development plus the disposable account prefix before creating any fixture. Every case rolls back all newly created characters/relationships/events. It passed parent archive/restore with retained events, one-row reciprocal handling, independent reverse-record preservation, family/story edits, one-event removal, concurrent-history rejection, permission rejection, confirmation and source-linked blocking. Existing manuscript relationships were not changed.
The actual Dapper reader was exercised read-only against an existing manuscript character: 55 relationship definitions, 509 overview-source changes, 755 evolution entries, 246 appearances and 282 knowledge entries. Each explorer returned at most 25 rows; SQL and .NET canonical scene order agreed, selected-point knowledge excluded later records, the management preview mapped its version/dependencies correctly, and the relationship checksum was identical before and after. No AI reanalysis was requested.
The Playwright suite exercises the actual Razor shell/partials with isolated fixture responses: five lazy tabs, bounded histories/pages, cached page state, selected narrative position, back/forward, character links, old gallery fragment, keyboard tabs and modal focus/Escape/draft handling, full-width modal fields, explicit archive consequences, list/tree refresh, event controls and protected-source blocking. Widths 1366, 1024, 768 and 390 all pass without whole-page horizontal overflow. CDP touch events verify actual tablet pan and pinch transforms. Existing Context Family and Story browser suites also pass after the shared reader/tree extraction. Native/SI connection counts remain stable across tab switches.
Screenshots captured during acceptance: `/tmp/character-workspace-overview-desktop.png`, `/tmp/character-workspace-family-desktop.png`, `/tmp/character-workspace-tablet-family.png`, `/tmp/character-workspace-mobile.png`. The dossier and tablet diagram have been visually inspected.
### Preservation reconciliation and practical limits
All rows in the Phase 1 matrix remain in the workspace or have an explicit link to their existing editor/advanced view. The redesign does not remove chart/continuity capabilities. The canonical archive limitation is made visible: removal hides a definition and retains history; independently authored pair records remain. Source-linked events require their source/review workflow, rather than unsafe direct deletion. These are explicit supported safety boundaries, not missing author functionality.
Physical-device touch, assistive-technology screen-reader usability and author judgement of visual family complexity remain useful manual acceptance; automated tests cover touch emulation, keyboard, focus and responsive geometry. Family life status is labelled global author reference and does not invent a death scene. Ordering metadata is capped at 20,000 books/chapters/scenes per list; larger projects receive an explicit full-editor route instead of silent truncation. No production changes are authorised or performed.
Final build: `dotnet build PlotLine.slnx` passed with zero warnings/errors. Full executable regression harness passed **786** checks. The prior preferred-name/enrichment source assertions were updated to follow their moved profile partial; both capabilities are also exercised in the rendered browser workspace. The separate enrichment browser check proves initial/reconnect completed-run replay is silent and each later completed run refreshes the workspace exactly once, without AI work or page navigation.
## Development delivery verification
The first qualified release `7ff5306` passed service activity, local/public GET (normal TLS), assembly informational-version and DLL/changed-asset SHA-256 checks. Authenticated live acceptance created a new disposable Supporting character and successfully added/edited its initial Parent definition. The test's note-based locator was then corrected to retain the canonical relationship ID; its isolated leftover definition and character were soft-archived under explicit disposable-scope guards. This did not touch baseline fixture relationships or any manuscript relationship.
Final integration review also disabled the shared generic delete-confirmation handler for the bespoke relationship operation form: its own scope/dependency preview and checkbox are the sole removal confirmation. Build (zero warnings/errors), all 15 focused service cases and the full workspace browser suite passed again, including an explicit assertion that the generic confirmation stays closed. The complete 786-check regression run had already passed before this form-attribute-only integration fix.
The actual Context My Windows navigation suite passed on Development: existing main-window reuse for scene, character, Names and Relationships, no extra windows, no Word navigation, unchanged Context scene. Final release and authenticated create/edit/archive/peer-hint verification are recorded below.
Final deployed application commit: **`ce5182951298a9f31d095806b90e147c259a52c5`** (`ce51829`). Release archive: `/srv/apps/plotdirector-dev/releases/character-workspace-verified-ce51829-20261123T100632Z`; preserved previous installation: `/srv/apps/plotdirector-dev/current-before-character-workspace-verified-ce51829-20261123T100632Z`. The immediate pre-stop background-work guard passed. The service is active; local GET and public HTTPS GET both returned 200; DLL and all changed/reused assets matched publish SHA-256; assembly informational version identifies this commit. Recent logs contain only the existing HTTPS-redirection port warning and no application failures.
Authenticated live acceptance passed on this final build: new Supporting character, all five tabs/empty states, canonical initial Parent add, definition edit, rejected unsaved navigation, explicit dependency preview, direct archive, Family/Story refresh, and exactly **one** existing Context peer invalidation per add/edit/archive (three total). The Context scene remained unchanged. The newly created character was archived, and no baseline fixture or actual manuscript relationship was removed. The final fixture integrity smoke confirms no new qualification character or relationship remains active and both baseline fixture characters remain active. Production was untouched.

View File

@ -0,0 +1,93 @@
# 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.

View File

@ -0,0 +1,160 @@
# Unified Context Workspace — foundation
21 November 2026. This replaces the separate Context/Intent window framework. Only **Overview** and **Characters in Scene** are registered. Existing planning records, canonical data, full editors, map/plot/metric tools and explicit AI Evidence services remain intact for subsequent tab migrations.
## Architecture and routes
`WritingController.Context` serves `/Writing/Context`, always using `_WritingCompanionLayout`. The page is a viewport shell: connection indicator/dialog, shared manuscript navigation, layout controls, two pane slots and a divider. The shared toast host remains in the layout, outside partial replacement. No framework dependency or schema migration was introduced.
Each pane has its own tool chooser, scroll container, component records, request generation and dirty/busy state. Both panes use one manuscript position and one chosen native document session. Either tool can appear in either or both panes; server responses are parsed independently into different DOM nodes. The initial partials contain no repeated fixed IDs.
| Route | Ownership |
| --- | --- |
| GET `/Writing/Context` | Authorized window shell and saved-scene choices. Accepts project/book/chapter/scene, document GUID, pinned flag and complete native instance/session. |
| GET `/Writing/Context/Tabs/overview` | `ContextScene` → existing canonical context composition → `_ContextTab` / `_WritingContextOverview`. |
| GET `/Writing/Context/Tabs/characters` | `ContextCharacters` → canonical context composition → `_ContextTab` / `_WritingContextPeople`. |
| GET `/Writing/Context/Position` | Account-scoped authoritative Office presence recovery; book/project access checked independently. |
| POST `/Writing/Context/Navigate` | Existing antiforgery-protected, session/revision/accepted-position-verified native navigation; command behavior retained. |
| GET `/Writing/Intent` and `/Writing/Intent/Scene` | Compatibility redirects to Context, preserving scoped position, document/session and pinned parameters. There is no Intent shell behind them. |
| `/Writing/Intent/Assessment` and `/decision` | Existing explicit Evidence GET/POST/decision endpoints, retained; never invoked by the two initial tabs. |
Both tab endpoints independently validate model binding, project/book/scene relationships and project access. Native requests additionally verify the selected saved session mapping both before and after data loading. A changed mapping returns 409. Missing/unavailable saved scenes do not become authorized browser selections. An event or stored UI record never grants access.
## Registration and lifecycle contract
The small declarative registry lives in `Views/Writing/Context.cshtml`, serialized as JSON for `wwwroot/js/context-workspace.js`:
```text
id, displayName, endpoint
scope: None | Book | Chapter | Scene | Paragraph
contentRefresh: none | relevant-scope
lifecycle: name of a registered lifecycle implementation
refreshGuard: defer-while-dirty-or-busy
```
The two current registrations use Scene scope, relevant saved-content refresh and the reference lifecycle. Navigation scopes are hierarchical: project/book identity precedes chapter, scene and paragraph. Paragraph IDs remain null unless supplied by an authoritative future integration; no paragraph position is invented from a scene ID or cursor offset.
A future component can register lifecycle hooks through `window.PlotDirectorContextLifecycles` before controller initialization, or `root.contextController.registerLifecycle(name, hooks)` before mounting it. Hooks are `mount(node, {paneId, windowId, position})`, `dispose(node)` and optional `canRefresh(node, record)`. Hooks own component behavior; the window controller has no Overview/Characters business branches.
A pane dispatches `context-panel-state` with `{dirty, busy}` when interaction must defer replacement. While guarded, refresh marks the record stale and shows an inline notice; changing tools is deferred too. Clearing both flags loads the latest pending context. A future editor must retain its original record identity and implement server concurrency checks. This foundation adds no inline planning editor or automatic save.
On replacement the controller disposes the old component and mounts a fresh server fragment; it restores pane scroll and preserves equivalent link focus when possible. Shell controls and toasts are never replaced. Hidden records retain stale flags and presentation state, and load only when selected/visible. Lifecycle disposal also runs when a pane is hidden or the window closes.
## Connection ownership and accepted data
Each live Context window owns exactly one browser SignalR connection, to the existing cookie-authenticated `/hubs/native-companion` (`NativeCompanionPresenceHub`). The group remains server-derived per authenticated user; clients cannot select another account's group. Pinned snapshots start no Context connection.
The same connection carries:
- Existing `NativePresenceChanged` hints, causing the existing native status reader to recover current leases over ordinary HTTP.
- `ContextPositionChanged` hints from the Office current-scene API, registration/heartbeat/disconnection and stale-presence monitor. The window re-reads `/Writing/Context/Position`; it does not install arbitrary event payloads as current position.
- `ContextInvalidated` lightweight book/chapter/scene hints at existing accepted manuscript save and successful editor/API update boundaries. These mark saved reference content stale, including when scene ID is unchanged.
`ContextWorkspaceNotifications` publishes account-group hints and catches transport failures so a committed save is never reported as failed because a browser notification could not be sent. `ParagraphManuscriptService.Save` announces after accepted persistence and the existing derived-statistics step. `WordCompanionController` announces after successful existing scene/manuscript/link/progress update calls. `ContextReferenceInvalidationFilter` covers successful Scene editor POSTs and chapter-goal saves. It does not run capture, typing analysis or AI.
`native-companion-status.js` retains its HTTP recovery, document selection, connection dialog, synchronization controls, lease expiry, visibility handling and 15-second recovery polling. In a Context shell it does **not** create its own hub connection. Other application pages keep their existing status behavior. The Context controller supplies its native wake/reconnect events. Native leases take precedence over Office fallback; ambiguous, disconnected, unsaved or unverified sessions retain saved content with explicit persistent warnings. A selected document never silently falls back to another instance.
Existing Word/native observation sequence checks, chapter/paragraph acceptance, native-agent command connections, navigation receipts, typing debounce, batching, reconciliation and Story Intelligence pipeline are unchanged. Observing a new Word revision is not evidence that prose or canonical analysis completed. Accepted-data hints request fresh saved reads; they never claim analysis completion.
On reconnect the controller re-reads authoritative position/status and invalidates visible content even for unchanged scene IDs. Initial connection failures can retry on the existing recovery interval. Visibility recovery revalidates authority. Office recovery fetches are serialized and guarded against a newer native selection/observation. Full-page/login HTML and redirected partial responses are rejected rather than inserted.
## Refresh and request ordering
The controller tracks record staleness independently for each pane/tool. Relevant navigation or saved-data invalidation refreshes visible clean tools; inactive tools wait until next selection. Scope invalidation is conservative within the current book because established reference records may affect later scene context. Unknown-scope editor invalidations revalidate current saved reference, not manuscript analysis.
Equivalent concurrent requests from both panes share one HTTP response promise for the same endpoint/context/generation; each pane constructs and owns its own fragment. Navigation/invalidation cancels obsolete requests. Window generation plus pane revision, tab identity and visibility checks reject late results. Detached, superseded or guarded panels never receive a replacement. Persistent inline status explains missing mappings, access/session expiry, interrupted requests and retained stale content. Refresh saved data offers explicit retry; routine passive updates stay silent.
## Window and pane state
Versioned localStorage keys are `plotdirector.context.v1.<account>.<window UUID>`. sessionStorage records the current window identity; managed launches pass a fresh `contextWindow` UUID. Ordinary refresh/navigation restores that window's layout, ratio, both pane selections, selected document and per-tool scroll. No manuscript prose or unsaved form drafts are persisted.
New Context, Writer, native launcher and Office launches open independent windows with a fresh UUID/default single-pane arrangement. Role-wide popup names, role focus selection and global active-tab keys are gone. An opener check plus account-scoped BroadcastChannel identity claims (with a storage-event fallback) detects cloned/duplicated live tabs; the newcomer receives a new identity/default layout. Explicit native document parameters are retained during clone repair. Storage access, including a denied storage getter, is guarded. When persistent storage is unavailable, each document operates with fresh in-memory identity/state; otherwise storage events provide clone recovery when BroadcastChannel is unavailable.
Single mode retains pane two's tool and state. Layouts are Single, Side by side and Stacked. Pointer drag and arrow/Home/End keyboard controls resize the separator; orientation, value and controlled pane IDs are exposed for assistive technology. Ratios are bounded; pane-size constraints are clamped to the available viewport. On very small/zoomed displays users can select stacked or single layout rather than relying on operating-system snapping.
`context-workspace.css` makes pane content an inline-size container, uses independently scrollable flex/grid slots, wraps shell controls and reflows cards/facts by pane width. It removes page-height assumptions inside panes. The parent cannot develop horizontal overflow from the reference cards. Full map/floor/plot editor layout work is intentionally outside this two-tab phase.
## Removed legacy components
- Standalone `Views/Writing/Intent.cshtml` and aggregate `_WritingContextContent` / `_WritingIntentContent` shells.
- `writing-follow.js`, its `writing-context.js` / `writing-intent.js` initializers and `writing-context-components.js` page controller.
- Browser role registration, fixed popup names, multi-monitor Context-versus-Intent placement and global selected-tab persistence from `writing-workspace.js` / launcher. These files now contain only independent Context launch behavior.
- `WritingWorkspacePresenceService`, its role/window models and registration/watch/heartbeat/focus methods in `WordCompanionFollowHub`; obsolete background role-presence cleanup/broadcasts.
- Styles exclusive to the retired window/page/tab shells. Reusable cards, facts and dormant feature styles remain.
- Legacy browser/static tests asserting the removed architecture, replaced by the Context foundation suite and updated server integration tests.
`WordCompanionFollowHub` itself remains necessary for Office presence/onboarding/import. It is not loaded by Context. The native notification hub and native agent command connection remain operational for their existing responsibilities.
## Retained, deliberately dormant features
Relationships, floor plans, maps, Story/continuity, Plot Lines, Metrics, chapter/scene planning, Must Include, Notes, Threads, Checklist/workflow and AI Evidence implementation/data remain. Reusable feature partials and map/plot/assessment JavaScript are preserved but not registered or loaded by the new shell. Remaining standalone feature endpoints are not a second Context window architecture. Old helper-based map/plot browser fixtures will need their tab integration adapted when those features are migrated.
The Scene editor, Writer Chapter workflows, full Maps/Floor Plans/Relationships/Plot Lines/Calendar and Story Intelligence review workspaces remain available. Overview's saved source links and the full Scene editor are preserved. Character knowledge remains author reference with established source provenance, not an assertion that the viewpoint character knows another participant's information. AI Evidence hashes, decisions and explicit POST semantics are untouched.
## Verification and qualification
- Normal `dotnet build PlotLine.slnx`: clean build, zero warnings/errors at the recorded gate.
- Full executable regression harness: 673 PASS lines, exit 0; includes updated native session/access/ownership/reference-data checks and existing native command/authentication suites. Additional notification-boundary assertions are included in focused Writing integration qualification.
- `--writing-integration`: authoritative reference hydration, scope/access, exact native session, unsaved/stale mappings, during-load changes, chronology/provenance and request reuse.
- `Browser/context-workspace-foundation.cjs`: real compiled Razor shell and both partials in the isolated loopback host, with synthetic reference data and controllable HTTP/SignalR inputs. Covers layouts, pointer/keyboard divider, same/different tabs, shared reads, generic None/Book/Chapter/Scene/Paragraph hierarchy using test-only registration metadata, hidden staleness, same-scene invalidation, rapid chapter/scene races, dirty/busy deferral, access/session failures, reconnect, native ambiguity/document selection and reload persistence, delayed manual saved reads during unavailable native observations, Office fallback/native precedence, independent windows, cloned storage (BroadcastChannel and storage-event fallback), denied storage, persistence, pinned snapshots and Office/Intent launch compatibility.
- Browser sizes include 1366×768, 760×768, 683×384 and 480×700 at 125% CSS zoom; shell/card reflow and no document-wide horizontal overflow are checked. The 683×384 viewport approximates the CSS space at 200% on a 1366×768 display.
- Shared notifications browser checks pass in browser and simulated standalone presentation. Existing Evidence request/cancel/isolation checks remain applicable.
- Standalone presentation is simulated Chromium qualification. Physical installed-PWA, Windows Word/VSTO and OS-level zoom/assistive-technology acceptance remain manual; these are not claimed as automated physical tests.
Browser suite uses the existing isolated host:
```sh
dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj -- --toolbar-browser-host
node PlotLine.Tests/Browser/context-workspace-foundation.cjs
```
No real author manuscript was used. Development smoke uses a dedicated disposable account, a synthetic project/book/chapter created through normal authenticated forms, and a new synthetic scene saved through the existing SceneRepository after explicit disposable ownership checks; no import or AI run is needed. Deployment and authenticated smoke evidence are recorded below after execution.
## Development deployment evidence
**Deployed successfully to Development on 21 November 2026 at 22:40 UTC. Production was not accessed or changed.**
- Deployed implementation commit: `868099ec828b938d3c9a2c843b1d4be984073819`. This evidence is added in a documentation-only follow-up; application source remains the deployed implementation.
- Release: `/srv/apps/plotdirector-dev/releases/context-foundation-868099e-20261121T224027Z`.
- Rollback application backup: `/srv/apps/plotdirector-dev/current-before-context-foundation-868099e-20261121T224027Z`. Deployment preserves configured appsettings/environment files, data-protection state, uploads and logs.
- Active import/queued and processing intelligence/synthesis/enrichment/core-import/marker work guard: passed immediately before service stop; effective database verified as `PlotDirector_Development`. No migration was applied.
- `plotdirector-dev`: active/running after installation. Local HTTP GET and public HTTPS GET both returned 200; public TLS validation was enabled.
- Deployed assembly: version `1.0.0.0`, informational version `1.0.0+868099ec828b938d3c9a2c843b1d4be984073819`.
- Published/deployed DLL SHA-256: `fe41f6e131cc8a7152709d80f60064f8b1df47d10172e61e4ab5b638dcaeda27`. Context controller JS, Context CSS, native-status JS and Office hosted JS hashes also matched the release publish.
- Authenticated `context-workspace-development.cjs`: passed against the actual public Development application with no HTTP/SignalR mocks. Confirmed saved Overview and empty Characters data, exactly one real hub connection, two panes sharing one reference request, an actual Scene editor save invalidating both panes and a second independent Context window, persistence, snapshots with no Context hub connection, native-session mismatch 409, forbidden/mismatched scope rejection, anonymous denial and Intent redirect. The disposable scene title was restored.
- Journal review from deployment through smoke completion: zero application errors; one HTTPS-redirection middleware warning, “Failed to determine the https port for redirect.” Public reverse-proxy HTTPS and local GET both passed. No unrelated configuration change was made.
Full harness finished with 673 PASS results and exit 0; normal build and Release publish succeeded. Focused browser suites passed: Context foundation, shared notifications, actual Writer/native dialog toast paths (browser and simulated standalone), and explicit Intent Evidence cancellation/isolation. Additional focused Writing integration verified lightweight account-group invalidations and failure-safe notification delivery.
The new opt-in live smoke requires private disposable identity/scope files via `PD_CONTEXT_IDENTITY` and `PD_CONTEXT_SCOPE`. It checks the account/database/synthetic project and exact scene title before its bounded editor update; no real author manuscript is used. The existing manual Scene/Create page did not expose a creation form during fixture setup, so a new scene was provisioned through the existing SceneRepository under verified disposable ownership instead of changing unrelated creation UI.
## Known limitations
- Only Overview and Characters in Scene are available. The other eleven feature areas remain dormant pending their requested migrations; full application editors remain available.
- Context shows authoritative saved reference data. Accepted prose synchronization does not imply completed canonical Story Intelligence analysis, and no analysis is started by refresh.
- Paragraph scope is supported by the generic registry, but the current common position integration supplies no durable paragraph identity and no paragraph tool is shipped.
- Browser layout/zoom and standalone presentation were qualified in Chromium; physical Windows Word/VSTO, a genuinely installed PWA and OS/browser zoom plus assistive technology need the manual acceptance below. No physical Word performance claim is made.
- Managed new-window identities, BroadcastChannel and storage-event clone recovery, and denied-storage in-memory operation are tested. Settings cannot persist when storage is denied.
- Window/pane settings are local to the account/browser/window identity, not server-roaming preferences. Storage refusal falls back to usable in-memory operation.
## Adding a future tab
1. Reuse its canonical service/repository and introduce an independently authorized partial GET; keep business interpretation and access checks on the server. Do not initiate analysis on GET.
2. Return one `_ContextTab`-compatible fragment with authoritative scope attributes. Make IDs and presentation state instance-safe; avoid document-global component selectors/listeners.
3. Add registry metadata and, when needed, an instance lifecycle. Use pane container dimensions; dispose observers/listeners/requests on replacement.
4. Declare dirty/busy protection, explicit save actions and server concurrency checks. Place transient outcomes in the existing toast service; retain persistent validation/recovery inline.
5. Identify accepted-data invalidation boundaries and verify reconnect/same-scene refresh. Reuse existing sync acceptance; do not add a typing debounce or new analysis pipeline.
6. Qualify the same tab twice, both orientations, hidden staleness, response ordering, focus/scroll, narrow/zoom presentation and two independent windows.
## Manual acceptance steps
1. Sign into Development, open a book/scene, then choose **Context** from Writer or **Open Context** from Companion. Confirm Overview displays the saved scene and only two tools are offered.
2. Choose **Side by side** and **Characters in Scene** in pane two. Check saved participants, roles, physical/emotional state, location/movement and established knowledge/source links against the Scene editor.
3. Choose Overview in both panes, then Characters in both. Scroll each independently; change one chooser and verify the other is unchanged.
4. Drag the divider. Focus it and use the orientation-appropriate arrows plus Home/End. Switch to **Stacked**, then Single, then split again; verify pane two's selection survives.
5. Refresh the browser. Verify layout, proportion, selected tools, document selection and practical scroll state restore. Open **New Context window** and verify a fresh single-pane layout; alter it without affecting the first. Duplicate a live browser tab and verify its identity/layout becomes independent.
6. Move through chapters/scenes in a saved, correctly linked Word document. Confirm both panes follow the same verified scene. Select among two native documents via the connection indicator; ambiguous/unverified mappings must explain why following is unavailable, without guessing a scene or sending navigation.
7. Save an accepted manuscript update while staying in the same scene, or save a scene change in another PlotDirector window. Verify visible reference content refreshes without an AI request or routine toast; a hidden tool should refresh when selected.
8. Interrupt/reconnect the notification connection and restore Word. Verify authoritative scene recovery and same-scene revalidation. Try an unsaved/missing mapping and confirm saved browsing/recovery explanations remain available.
9. Open `?pinned=true&sceneId=<saved scene>&bookId=<book>` and verify Word movement does not retarget it. Manual scene navigation still works. Check an old Intent link redirects to Context with its scope/session intact.
10. At 1366×768, a narrow browser and 125–200% browser zoom, check both orientations, scroll, labels and keyboard focus. Repeat in the installed PWA and physical Word environment when available. Signing out/expiring a session must produce sign-in/access feedback rather than nesting a login page in a pane.

View File

@ -0,0 +1,64 @@
# Unified manuscript focus — implementation and qualification
Development only, 23 November 2026. Existing feature branch: `codex/word-companion-native-phase1-20261104`. The application commit, release directory, hashes and post-deployment results are recorded in the deployment evidence linked below.
## Audit and architectural choice
Previously, `NarrativeFocus` stored personal chapter/scene navigation, with browser storage/focus events supplying recovery. Review's chapter GET could change that state. Context principally followed native/Office presence and its navigation endpoint requested a Word command, which made it ineffective without Word. Review's paragraph selection updated review tools and the explicit Word target, but did not publish a common manuscript position.
Context already owned one native-presence SignalR connection per window, independent cached tabs, split panes, layout persistence, window identity and duplicate-window detection. Its invalidation handler already allowed an earlier-scene change to invalidate later-scene projections; it must remain independent of navigation. Snapshot windows previously skipped connection setup. The main application already had a shared native-presence connection, and the native tray Companion already had a validated command queue, asynchronous agent wake notifications, exact document sessions and acknowledgements.
The implementation extends these paths. It does not introduce another hub, Context connection, manuscript copy, editor owner, focus polling loop or Intent surface. Existing content/status checks remain. The current Windows VSTO/tray architecture is the Word implementation target; the older Office.js task-pane shell remains unchanged and is not advertised as a shared-focus client.
## Server contract
Forward-only migrations **314–317** extend the existing `NarrativeFocus` row with canonical manuscript/paragraph and originating-window IDs; add a per-origin sequence replay ledger; replace implicit objective seeding and read-time redirection; and resolve Word positions from exact-session verified chapter evidence. Backup `/var/opt/mssql/backup/shared-manuscript-focus-20261123T125506Z.bak` completed with COPY_ONLY/CHECKSUM and passed VERIFYONLY before the initial migrations. The chapter-only/empty-chapter boundary correction in 317 used a further verified backup, `/var/opt/mssql/backup/shared-focus-boundary-20261123T134529Z.bak`. VERIFYONLY is not a restore test.
`GET /NarrativeFocus/Shared?projectID=…&bookID=…` retrieves authoritative focus. Antiforgery-protected POSTs to `/NarrativeFocus/Shared/Publish`, `/Resolve` and `/Validate` accept existing identifiers. `Resolve` performs held local navigation; `Validate` checks a retained reference; neither publishes. Every operation verifies active authenticated access, project/book membership, canonical manuscript identity and chapter/scene/paragraph compatibility in stored procedures accessed through Dapper. Navigation remains available to read-only subscription accounts.
The packet contains `ProjectID`, `BookID`, `ManuscriptID`, `ChapterID`, optional `SceneID`/`ParagraphID`, `OriginWindowID`, `Version`, `IsValid` and `Changed`. It contains no prose, Word offsets or contextual datasets. The server locks the existing focus row and assigns increasing revisions atomically. Different clients are ordered by accepted server revisions, without client timestamps. Duplicate/older per-window sequences and unchanged effective targets do not create another revision. A stale stored reference is returned as invalid, without silently moving it. Clients process validity metadata even when the focus revision is unchanged, so Release never reuses a cached valid flag for a now-invalid shared point.
`ManuscriptFocusChanged` uses the existing authenticated `NativeCompanionPresenceHub.UserGroup`. `ManuscriptFocusDelivery` reports unavailable Word mapping without blocking other clients. Browser clients scope-filter messages, reject obsolete/duplicate revisions, serialize rapid local intent and recover on connect/reconnect. Ordinary GETs, refreshes, passive observations and received navigation do not publish. Existing explicit browser navigation delegates to the coordinator; server GET hooks no longer write focus.
A future editor can use the same identifier-only contract and existing authenticated transport without changing manuscript content ownership.
## Clients and Hold
Review publishes deliberate paragraph clicks, paragraph keyboard navigation and chapter/scene selectors, including when Word is closed. Accepted content remains authoritative. Incoming focus uses the existing partial chapter/scene positioning pipeline, preserves open editors and review tools, and explains missing precise paragraph/scene mapping before showing a deterministic scene/chapter fallback. A missing held passage stops positioning and offers local reselection/Release, without moving to another paragraph. Scrolling does not publish.
Context dropdown, Previous, Next and Go to Focus use shared focus directly, without a Word navigation request. Each window retains its panes, tools, divider, cached tab state and layout. Snapshot windows also keep data notifications. Focus changes only invalidate panels whose scope changed. Data invalidation is independent of Hold and conservatively refreshes affected visible relationship/character panels across scenes; hidden panels are marked stale until activated. Structural invalidation retains the held reference and offers another local selection or Release Hold.
Browser Hold is stored in session storage under authenticated-user/window identity, separately from global book preferences. An ordinary refresh retains Hold and local position. Existing Context identity arbitration plus browser identity claims prevent duplicated storage from sharing Hold. New windows default to Follow. Release obtains current authoritative focus, then follows it; it never publishes the held position. With no valid shared focus, it retains the local position and follows without creating one. Failed recovery retains Hold.
The static Hold control and status appear in Review/application ribbons and Context. Hold remains visible when the installed PWA compacts Previous/Go/Next into its existing menu. Labels explicitly say Following/Held and Release Hold; colour is supplementary.
Native Word adds Hold/Follow to the existing ribbon and uses a distinct state/identity for each actual Word window. The adapter distinguishes foreground mouse/navigation-key selection events from passive observations and suppresses incoming-navigation publication. Deliberate observations pass through existing framed IPC and native presence, then resolve canonical paragraph IDs using saved, fresh, exact-session verified chapter positions. Existing agent wake/command/receipt delivery supplies background following. Shared commands use `Window.ScrollIntoView`, not `Select`, `Activate` or a foreground-window call; editing selection/content ownership is retained. Unmapped, unsaved and busy states are explicit. Word Outline view cannot use this API and requires changing view before retrying ([Microsoft API contract](https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word.window.scrollintoview?view=word-pia)). Window state rejects old/duplicate deliveries and Release can catch the same window's own previously published shared position.
Explicit Open in Word controls are retained, including paragraph navigation: physical native replacement qualification is not complete, so removing these controls would be premature. They remain useful for unsupported/disconnected/held/unmapped Word sessions and opening the manuscript. Shared paragraph/Context selection never automatically launches Word.
## Verification
- Solution build: zero warnings/errors; full executable regression harness: **786 passing checks**.
- Native portable regression harness: **320 passing checks**, including the dedicated per-window Hold/revision cases. These exercise managed production logic and IPC, not Word COM.
- Development rollback-only SQL tests cover no initial publication, canonical paragraph resolution, monotonic revisions, unchanged-target suppression, replay rejection, held resolution without mutation, canonical cross-chapter stepping, chapter-only and empty-chapter boundaries, endpoint paragraph preservation, invalid references, verified Word offsets, exact-session isolation and authorisation. The updated historical six-phase SQL regression also passes with no implicit seed/redirection.
- Sixteen real concurrent SQL connections verify contiguous unique accepted revisions and a final durable read equal to the highest revision. Real coordinator/SQL/native-queue integration also verifies Word-only publication, browser-to-Word chapter crossing, passive suppression, Hold/release, failed receipts, unsaved documents, delivery renewal after a saved Word/snapshot revision, and exact-session isolation through a recording transport.
- Real authenticated Chromium and installed standalone Chromium PWA tests use the actual controllers, SQL and SignalR with a synthetic isolated project/manuscript. They cover Context alone; Review/Context without Word; local scrolling; exact paragraphs and chapter crossing; independent Hold; local held Review navigation; refresh and release without publication; rapid and obsolete ordering; new/duplicated-window isolation; reconnect; responsive widths; hidden tabs; a synthetic missing-accepted-passage resolver check that prevents held Review fallback navigation; and relationship edits in an earlier scene refreshing both held panes. The refreshed later-scene graph is checked for the new note, not just a refresh request.
- Actual loopback server restart passed: durable focus recovered, SignalR reconnected, and the held window detected an offline structural change without redirecting. Browser structural archival acceptance passed. Final public Development smoke results are recorded in deployment evidence. Browser fixtures are isolated and archived after testing; no real manuscript text or relationships are edited.
Reproducible entry points: `PlotLine.Tests --shared-focus-database <disposable-scope-file>` (rollback); `--shared-focus-browser-setup <disposable-scope-file>`; `--shared-focus-browser-host` (loopback only, real auth/SQL/hub, no hosted workers); `--shared-focus-concurrent`; `--shared-focus-cleanup`. Browser: `PlotLine.Tests/Browser/shared-manuscript-focus.cjs`, optionally `--installed`, `--structure`, or the externally coordinated `--restart` case, with private disposable identity supplied through `PD_CONTEXT_IDENTITY`. Portable native: `--shared-focus`. No credentials are in the report or repository.
## Windows qualification still required
This Linux host cannot compile/load the Office/VSTO project or run physical Word, Windows foreground handling or multiple monitors. The main .NET build deliberately excludes that project. Browser and portable native passes are **not physical Word acceptance**; no new Word binary has been installed or published by this task.
1. On an Office-equipped Windows development machine, use the existing shared branch and `PlotDirector.NativeCompanion/WindowsValidation/Update-WordCompanion.ps1` workflow at the recorded commit. Build/sign/verify the package, then use its existing explicit development installation procedure. Verify the loaded add-in/agent commit before testing.
2. Associate/save a disposable Development manuscript and complete chapter position verification. With Word alone, click and keyboard-select paragraphs across chapter/scene boundaries. Inspect shared revisions, then open Review/Context and verify initialization at the latest position without a new publication.
3. Exercise Word+Review, Word+Context and all three, with two Context windows (one Held) and split panes. Scroll Word and Review without changing shared focus. Select paragraphs/chapter/scene deliberately in each client and verify only followers move.
4. Keep Review foreground on another monitor. Select a paragraph there; verify Word reveals the exact target while the Windows foreground process, insertion point, selection and manuscript text remain unchanged. Repeat while Word has a dialog, protected view or editing activity; verify explicit busy/unmapped handling without activation.
5. Hold each Word window independently, including two windows on the same document. Navigate/edit locally; verify content synchronization continues and shared revision is unchanged. Release to the latest shared point, including one originally published by that same window. Close/reopen a window and verify new Follow identity.
6. Close each client in turn, including Word unexpectedly, and verify remaining pairs still navigate. Reconnect/restart the agent/service, rapidly alternate publications, and replay/delay notifications; verify newest accepted focus wins without an echo. Test saved/unsaved and stale/expired mapping transitions and independent manuscripts/accounts.
7. Repeat the earlier-scene relationship edit while a later-scene diagram is Held; verify data changes without movement. Archive a disposable held scene and verify explicit invalid-reference recovery. Confirm existing editing, synchronization, review tools, launch actions and ribbon layout.
Older native installations do not advertise the new capability. They retain editing, content synchronisation and explicit Word navigation, but must be updated before participating in shared focus; passive legacy cursor-following is replaced rather than promoted into deliberate focus. Existing connection details and Review status make that upgrade requirement explicit. Precise native following requires fresh verified saved chapter positions; legacy paragraph-only offsets are not guessed. Historical Office.js hosting requires separate host-specific implementation/qualification before shared-focus support can be claimed there.
Deployment evidence: [Unified-Manuscript-Focus-Deployment-20261123.md](Unified-Manuscript-Focus-Deployment-20261123.md).

View File

@ -0,0 +1,58 @@
# Unified manuscript focus — Development deployment evidence
Final application commit: **`3b1491f1a4f91a4118dc1efe366e9b1f50e987e6`** (`3b1491f`). Branch: `codex/word-companion-native-phase1-20261104`.
Implementation commits: `a85d6ed`, `d55206d`, `3b1491f`. [Implementation report and exact Windows acceptance checklist](Unified-Manuscript-Focus-20261123.md).
## Installed Development release
- Installed UTC: `2026-11-23T14:16:58.954976+00:00`.
- Release: `/srv/apps/plotdirector-dev/releases/shared-focus-complete-3b1491f-20261123T141655Z`.
- Previous live-directory backup: `/srv/apps/plotdirector-dev/current-before-shared-focus-complete-3b1491f-20261123T141655Z`.
- Service: `plotdirector-dev`, verified active after final acceptance and cleanup.
- Target: `https://dev.plotdirector.com/` and `PlotDirector_Development`.
- Published/deployed DLL and changed asset SHA-256 values matched. Deployed informational version contains `1.0.0+3b1491f1a4f91a4118dc1efe366e9b1f50e987e6`.
- Local and public GETs returned 200; public verification used normal TLS validation.
- Queued/running import, Story Intelligence, synthesis and enrichment guards passed immediately before every service stop. Existing settings, uploads, logs and data-protection keys were preserved by the deployment procedure.
Migrations 314–317 were applied to the verified Development database. Both backups completed with COPY_ONLY/CHECKSUM and passed VERIFYONLY:
- `/var/opt/mssql/backup/shared-manuscript-focus-20261123T125506Z.bak`
- `/var/opt/mssql/backup/shared-focus-boundary-20261123T134529Z.bak`
## Completed verification
- Solution build: zero warnings/errors. Final application Release publish succeeded.
- Application regression harness: **786 PASS**, exit 0.
- Portable native regression harness: **320 PASS**, exit 0. This is managed/IPC coverage, not Windows COM/Word qualification.
- Rollback-only shared-focus SQL checks passed, including authorisation, replay rejection, paragraph resolution, chapter-only/empty-chapter boundaries, endpoint precision and stale references. The existing six-phase narrative SQL and Dapper repository regressions also passed after updating the no-seeding/no-redirection expectations.
- Sixteen simultaneous real SQL connections produced contiguous unique accepted revisions and the correct durable latest focus.
- Real coordinator/SQL/native-queue integration passed Word-only publication, exact cross-chapter background delivery, passive suppression, Hold/release, failed receipts, unsaved state, session isolation, and renewed delivery identity after saved Word/snapshot revisions.
- Actual loopback application restart passed with live authenticated browsers: shared focus persisted, SignalR reconnected, the held window stayed in place, and an offline structural change was detected without redirection.
- Final **public Development browser and installed standalone Chromium PWA** suites passed against the deployed release. They used real authentication, controllers, SQL and SignalR. Coverage includes Review/Context without Word; scrolling local; deliberate paragraphs; chapter crossing; chapter-only and empty-chapter toolbar navigation; Context Previous/Next/Go; independent Hold; held local navigation; release without publication; refresh; new and duplicated windows; delayed/duplicate events; rapid intent; one active SignalR connection per Context window; split panes; responsive widths; and a previously cached hidden tab refreshed on activation.
- A real earlier-scene relationship save refreshed both visible later-scene held panes. The resulting Story graph contained the new note, while the held position remained unchanged.
- Structural archival tests passed: a held local reference remained explicit and recoverable; Release retained a valid local position when shared focus became invalid at the same revision; duplicate focus packets did not reverse authoritative invalidity. The synthetic missing-passage resolver check also verified that held Review did not navigate or retarget to a fallback paragraph.
- Public authenticated HTTP smoke passed: scoped read, foreign-scope rejection, required antiforgery, anonymous challenge, ignored client revision and unchanged-publication suppression.
- All committed synthetic fixture projects were archived after testing; transaction-only fixtures rolled back. The isolated loopback test host was stopped. No real manuscript or relationship was edited by acceptance testing.
## Remaining Windows work and support limits
The updated Windows add-in/agent **has not been installed or physically tested**. This Linux host cannot build/load VSTO, verify actual Word event ordering, Windows foreground behavior or multiple monitors. Existing Windows installations need the updated package before shared-focus participation; the website now makes that requirement explicit. Their existing editing/synchronisation and explicit Word actions remain available.
The older Office.js task-pane host remains outside the new shared-focus client implementation. Precise native navigation requires fresh, saved, verified exact-session chapter positions. Explicit Open in Word controls remain until the replacement has physical qualification. Follow the Windows checklist in the implementation report; browser or portable native results must not be reported as physical Word acceptance.
## Installed hashes
| File | SHA-256 |
| --- | --- |
| `PlotLine.dll` | `281c2e8d3329c691b7ed1b8e3ab78d3a7869ecac8071a45f500c4e8cfb14a09b` |
| `wwwroot/css/application-shell.css` | `17b5178477c108aba21dded63253621ab1e00baeceda86f6d145f6e80859dfb5` |
| `wwwroot/js/shared-manuscript-focus.js` | `b7786cbe7936f7ad1d0573765e1d2deadbaff1d04f0ec550fc3ba284391edc94` |
| `wwwroot/js/context-workspace.js` | `3ed08ef2f7a23c89e7c1283fae92a29632501e64a3ee0e7a557f48a24fc4c50e` |
| `wwwroot/js/narrative-focus.js` | `2c75d700cb2f09fb6f9ed4b85d1fd35c98393ac1ffd01a92376b43d19fa0cb6d` |
| `wwwroot/js/narrative-focus-review.js` | `101fa5586bb8866c395feaa85242eb7224d96d88b65effc9fd9ccdcce0652fd2` |
| `wwwroot/js/narrative-focus-workspaces.js` | `72c52c6408d68fb0827cf48aaf6277c7d43e90abfa0028c0f591fe6cc8cd92e2` |
| `wwwroot/js/manuscript-reader.js` | `490af79adfdb3dd02a40e4b71acdccec98f40b0cf12c4c63bccd9b76de3863e3` |
| `wwwroot/js/writer-review.js` | `f5fd829a4db72e8b33c16c85caf592ecc90ba0fc22259fa3cb43323d56e44294` |
| `wwwroot/js/writer-word.js` | `8324bfd5eef873926a2069aed37e838512a8c3657775a05aaf02ac659f1be592` |
| `wwwroot/js/native-companion-status.js` | `43f2967f9d7cd45fa1bc2bd944991abc04ebd53ffda808a6e7c9b39f2940ef91` |

View File

@ -109,7 +109,7 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai
if(message.Kind.StartsWith("ai-",StringComparison.Ordinal))return ai?.Handle(document.Descriptor,message,answer)??Reject(answer,"ai-unavailable");
switch (message.Kind)
{
case "tray-context":case "tray-intent":case "tray-workspace": break;
case "tray-context":case "tray-workspace": break;
case "tray-audio":
if(message.Action is not ("play" or "pause" or "back15" or "forward15"))return Reject(answer,"invalid-audio-operation");
break;

View File

@ -42,18 +42,19 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway
else{
doc.Observed=DateTime.UtcNow;
if(request.Kind=="active"){foreach(var d in documents.Values)d.Active=false;doc.Active=true;}
if(request.Kind=="selection"){doc.WordObservedUtc=request.WordObservedUtc.HasValue?(request.WordObservedUtc.Value.ToUniversalTime()<=ChapterNow?request.WordObservedUtc.Value.ToUniversalTime():null):ChapterNow;if(doc.WordSaved!=request.WordSaved&&request.WordSaved==true&&doc.NextChapterCheckUtc!=default)doc.NextChapterCheckUtc=ChapterNow.AddSeconds(3);if(ChapterCapable(instance)&&(doc.Cursor!=request.Start||doc.WordSaved!=request.WordSaved)){ChapterCursorEvidence.Invalidate(doc);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;}doc.Cursor=request.Start;doc.WordSaved=request.WordSaved;if(doc.WordSaved==true&&doc.RibbonNotice?.State=="Save required")doc.RibbonNotice=null;if(request.WordSaved==true&&doc.AssociationNeedsSave){doc.AssociationNeedsSave=false;doc.AssociationNotice="";}}
if(request.Kind=="selection"){if(doc.FocusWindowID!=request.FocusWindowID||doc.FocusModeRequest!=request.FocusModeRequest)doc.DeliberateFocusSequence=0;doc.CanSharedFocus=request.CanSharedFocus;doc.FocusHeld=request.FocusHeld;doc.AnyFollowingWindows=request.AnyFollowingWindows;doc.FocusWindowID=request.FocusWindowID;doc.FocusModeRequest=request.FocusModeRequest;if(request.DeliberateFocusSequence>0)doc.DeliberateFocusSequence=request.DeliberateFocusSequence;if(request.CanSharedFocus&&(request.DeliberateFocusSequence>0||doc.LastFocusModeRequest!=request.FocusModeRequest)){doc.PresenceRequested=true;doc.LastFocusModeRequest=request.FocusModeRequest;}doc.WordObservedUtc=request.WordObservedUtc.HasValue?(request.WordObservedUtc.Value.ToUniversalTime()<=ChapterNow?request.WordObservedUtc.Value.ToUniversalTime():null):ChapterNow;if(doc.WordSaved!=request.WordSaved&&request.WordSaved==true&&doc.NextChapterCheckUtc!=default)doc.NextChapterCheckUtc=ChapterNow.AddSeconds(3);if(ChapterCapable(instance)&&(doc.Cursor!=request.Start||doc.WordSaved!=request.WordSaved)){ChapterCursorEvidence.Invalidate(doc);doc.LastPresenceKey="";doc.LastPresenceUtc=DateTime.MinValue;}doc.Cursor=request.Start;doc.WordSaved=request.WordSaved;if(doc.WordSaved==true&&doc.RibbonNotice?.State=="Save required")doc.RibbonNotice=null;if(request.WordSaved==true&&doc.AssociationNeedsSave){doc.AssociationNeedsSave=false;doc.AssociationNotice="";}}
if(request.Kind=="selection"&&doc.LastPresenceKey!=""&&chapterWork.TryGetValue(doc.Session,out var localWork)&&CurrentChapterWork(doc,localWork)&&localWork.Supported)
PumpChapterWork(doc,localWork);
ChapterFrame(doc,request,answer);
if(request.Kind=="tray-audio"&&answer.Status=="ok"&&doc.Active&&doc.Book>0)
AudioRequested?.Invoke(doc.Session,request.Action);
if(request.Kind is "tray-sync" or "tray-repair")ReceiveChapterRibbonRequest(doc,request.Kind);
if ((request.Kind is "tray-context" or "tray-intent") && answer.Status == "ok")
_ = OpenRibbonWorkspace(doc.Session, request.Revision, request.Kind == "tray-context" ? "context" : "intent");
if (request.Kind == "tray-context" && answer.Status == "ok")
_ = OpenRibbonWorkspace(doc.Session, request.Revision, "context");
if (request.Kind == "tray-workspace" && answer.Status == "ok")
_ = OpenRibbonWorkspace(doc.Session, request.Revision, "book");
CaptureFrame(doc,request,answer);
answer.SharedFocusStatus=doc.SharedFocusStatus;
if((request.Kind=="selection"||request.Kind=="snapshot-end")&&!ChapterCapable(instance)){doc.ChapterId=answer.ChapterId;doc.SceneId=answer.SceneId;doc.ChapterTitle=answer.ChapterTitle;doc.SceneTitle=answer.SceneTitle;}
if(answer.WordCount.HasValue)doc.Words=answer.WordCount;
if(request.Kind.StartsWith("snapshot-",StringComparison.Ordinal)&&answer.Status is not ("ok" or "analysis-complete" or "awaiting-structure")){Cancel(doc);doc.Status="Local reading failed: "+answer.Status+". Detect chapters again.";}
@ -193,7 +194,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway
}
private async Task PublishPresence(TrayDocument doc,bool force,CancellationToken cancellation)
{
var freshObservation=FreshWordObservation(doc);if(!force&&doc.LastPresenceKey==""&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(2))return;var key=$"{freshObservation}:{doc.Capture?.RequestId}:{(doc.Capture!=null?doc.Progress/5:0)}:{doc.WordSaved}:{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}:{doc.NavigationAcknowledgedId}:{doc.NavigationResult}:{(ParagraphCapable(doc.Instance)||!doc.SceneId.HasValue?doc.Cursor:0)}";if(!force&&key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(acknowledgedNavigationInstances.Contains(doc.Instance)?2:15))return;try{var presenceClock=System.Diagnostics.Stopwatch.StartNew();Guid? publishedNavigation;long publishedAckTimestamp;string publishedResult;lock(gate){publishedNavigation=doc.NavigationAcknowledgedId;publishedAckTimestamp=doc.NavigationAckTimestamp;publishedResult=doc.NavigationResult;}var presenceStarted=System.Diagnostics.Stopwatch.GetTimestamp();var reply=await cloud.Presence(doc.Instance,doc.Session,new(){CanAcknowledgeNavigation=acknowledgedNavigationInstances.Contains(doc.Instance),NavigationAcknowledgedId=publishedNavigation,NavigationResult=publishedResult,CaptureRequestId=doc.Capture?.RequestId,CaptureProgress=doc.Progress,ChapterIssue=ChapterIssue(doc),CanChapterSync=ChapterCapable(doc.Instance),CanParagraphSync=ParagraphCapable(doc.Instance),CanCapture=captureInstances.Contains(doc.Instance),WordRunning=true,WordSaved=freshObservation?doc.WordSaved:null,CursorStart=freshObservation?doc.Cursor:null,ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=doc.PresenceSequence=Interlocked.Increment(ref presenceSequence),ChapterId=freshObservation?doc.ChapterId:null,SceneId=freshObservation?doc.SceneId:null,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication,cancellation);if(reply.Navigation?.Kind=="navigate")TraceNavigation(reply.Navigation.Id,"presence-acquisition-roundtrip",presenceClock.Elapsed.TotalMilliseconds);if(publishedNavigation.HasValue&&doc.LastTracedNavigationAck!=publishedNavigation.Value){if(publishedAckTimestamp!=0)TraceNavigation(publishedNavigation.Value,"adapter-result-to-ack-presence",System.Diagnostics.Stopwatch.GetElapsedTime(publishedAckTimestamp,presenceStarted).TotalMilliseconds);TraceNavigation(publishedNavigation.Value,"ack-presence-roundtrip",presenceClock.Elapsed.TotalMilliseconds);doc.LastTracedNavigationAck=publishedNavigation.Value;}lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc||(ChapterCapable(doc.Instance)&&reply.Revision!=doc.Revision)||doc.Authentication!=cloud.Status().AuthenticationContext)return;if(ChapterCapable(doc.Instance)&&chapterWork.TryGetValue(doc.Session,out var currentChapters)&&currentChapters.Manifest!=null&&reply.ParagraphRevision>0&&reply.ParagraphRevision<currentChapters.Manifest.Revision)return;doc.LastPresenceKey=key;doc.LastPresenceUtc=DateTime.UtcNow;doc.ChapterProgress=reply.ChapterProgress;if(ChapterCapable(doc.Instance))ChapterCursorEvidence.Apply(doc,reply);else{doc.ChapterTitle=reply.ChapterTitle;doc.SceneTitle=reply.SceneTitle;}ObserveChapterPresence(doc,reply);}
var freshObservation=FreshWordObservation(doc);if(!force&&doc.LastPresenceKey==""&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(2))return;var key=$"{freshObservation}:{doc.Capture?.RequestId}:{(doc.Capture!=null?doc.Progress/5:0)}:{doc.WordSaved}:{doc.Book}:{doc.Revision}:{doc.ChapterId}:{doc.SceneId}:{doc.Active}:{doc.NavigationAcknowledgedId}:{doc.NavigationResult}:{(ParagraphCapable(doc.Instance)||!doc.SceneId.HasValue?doc.Cursor:0)}";if(!force&&key==doc.LastPresenceKey&&DateTime.UtcNow-doc.LastPresenceUtc<TimeSpan.FromSeconds(acknowledgedNavigationInstances.Contains(doc.Instance)?2:15))return;try{var presenceClock=System.Diagnostics.Stopwatch.StartNew();Guid? publishedNavigation;long publishedAckTimestamp;string publishedResult;lock(gate){publishedNavigation=doc.NavigationAcknowledgedId;publishedAckTimestamp=doc.NavigationAckTimestamp;publishedResult=doc.NavigationResult;}var focusPublication=new NativePresence{CanSharedFocus=doc.CanSharedFocus,FocusHeld=doc.FocusHeld,AnyFollowingWindows=doc.AnyFollowingWindows,FocusWindowID=doc.FocusWindowID,FocusModeRequest=doc.FocusModeRequest,DeliberateFocusSequence=doc.DeliberateFocusSequence};var presenceStarted=System.Diagnostics.Stopwatch.GetTimestamp();var reply=await cloud.Presence(doc.Instance,doc.Session,new(){CanSharedFocus=focusPublication.CanSharedFocus,FocusHeld=focusPublication.FocusHeld,AnyFollowingWindows=focusPublication.AnyFollowingWindows,FocusWindowID=focusPublication.FocusWindowID,FocusModeRequest=focusPublication.FocusModeRequest,DeliberateFocusSequence=focusPublication.DeliberateFocusSequence,CanAcknowledgeNavigation=acknowledgedNavigationInstances.Contains(doc.Instance),NavigationAcknowledgedId=publishedNavigation,NavigationResult=publishedResult,CaptureRequestId=doc.Capture?.RequestId,CaptureProgress=doc.Progress,ChapterIssue=ChapterIssue(doc),CanChapterSync=ChapterCapable(doc.Instance),CanParagraphSync=ParagraphCapable(doc.Instance),CanCapture=captureInstances.Contains(doc.Instance),WordRunning=true,WordSaved=freshObservation?doc.WordSaved:null,CursorStart=freshObservation?doc.Cursor:null,ManuscriptId=doc.Manuscript,BookId=doc.Book,Revision=doc.Revision,Sequence=doc.PresenceSequence=Interlocked.Increment(ref presenceSequence),ChapterId=freshObservation?doc.ChapterId:null,SceneId=freshObservation?doc.SceneId:null,Active=doc.Active,DocumentTitle=doc.Title},doc.Authentication,cancellation);if(reply.Navigation?.Kind=="navigate")TraceNavigation(reply.Navigation.Id,"presence-acquisition-roundtrip",presenceClock.Elapsed.TotalMilliseconds);if(publishedNavigation.HasValue&&doc.LastTracedNavigationAck!=publishedNavigation.Value){if(publishedAckTimestamp!=0)TraceNavigation(publishedNavigation.Value,"adapter-result-to-ack-presence",System.Diagnostics.Stopwatch.GetElapsedTime(publishedAckTimestamp,presenceStarted).TotalMilliseconds);TraceNavigation(publishedNavigation.Value,"ack-presence-roundtrip",presenceClock.Elapsed.TotalMilliseconds);doc.LastTracedNavigationAck=publishedNavigation.Value;}lock(gate){if(documents.GetValueOrDefault(doc.Session)!=doc||(ChapterCapable(doc.Instance)&&reply.Revision!=doc.Revision)||doc.Authentication!=cloud.Status().AuthenticationContext)return;if(ChapterCapable(doc.Instance)&&chapterWork.TryGetValue(doc.Session,out var currentChapters)&&currentChapters.Manifest!=null&&reply.ParagraphRevision>0&&reply.ParagraphRevision<currentChapters.Manifest.Revision)return;if(doc.FocusWindowID==focusPublication.FocusWindowID&&doc.DeliberateFocusSequence==focusPublication.DeliberateFocusSequence)doc.DeliberateFocusSequence=0;doc.LastPresenceKey=key;doc.LastPresenceUtc=DateTime.UtcNow;if(!string.IsNullOrEmpty(reply.SharedFocusStatus))doc.SharedFocusStatus=reply.SharedFocusStatus;doc.ChapterProgress=reply.ChapterProgress;if(ChapterCapable(doc.Instance))ChapterCursorEvidence.Apply(doc,reply);else{doc.ChapterTitle=reply.ChapterTitle;doc.SceneTitle=reply.SceneTitle;}ObserveChapterPresence(doc,reply);}
if(reply.ParagraphRevision>0&&!ChapterCapable(doc.Instance))lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext){doc.ChapterId=reply.ChapterId;doc.SceneId=reply.SceneId;}
if(reply.Navigation is {Kind:"wizard-capture",BookId:>0} requested&&requested.SessionId==doc.Session&&requested.Revision==doc.Revision&&doc.Book==0){await cloud.CheckConnection();lock(gate){if(doc.Book==0&&requested.SessionId==doc.Session&&requested.Revision==doc.Revision&&doc.Authentication==cloud.Status().AuthenticationContext&&cloud.Allows(doc.Authentication,requested.BookId)&&documents.GetValueOrDefault(doc.Session)==doc){doc.Book=requested.BookId;cloud.RememberBinding(doc.Manuscript,doc.Book,doc.Authentication);doc.LastPresenceKey="";}}}
if(reply.Navigation!=null)lock(gate)if(documents.GetValueOrDefault(doc.Session)==doc&&reply.Navigation.SessionId==doc.Session&&reply.Navigation.Revision==doc.Revision){if((reply.Navigation.Kind is "wizard-capture" or "paragraph-snapshot")&&captureInstances.Contains(doc.Instance)&&(reply.Navigation.BookId==0||reply.Navigation.BookId==doc.Book)&&cloud.Allows(doc.Authentication,doc.Book)){if(uploading!=0||documents.Values.Any(d=>d.Capture!=null)){_=cloud.FailCapture(reply.Navigation.Id,doc.Authentication);return;}var retained=doc.RetryCapture;var reusable=retained!=null&&doc.RetryAuthentication==doc.Authentication&&doc.RetryBook==doc.Book&&retained.ManuscriptId==doc.Manuscript&&retained.Revision==doc.Revision&&retained.ParagraphTracking==reply.Navigation.ParagraphTracking;
@ -244,6 +245,7 @@ var freshObservation=FreshWordObservation(doc);if(!force&&doc.LastPresenceKey=="
}
public sealed class TrayDocument
{
public string SharedFocusStatus="";public bool CanSharedFocus,FocusHeld,AnyFollowingWindows;public Guid FocusWindowID,FocusModeRequest,LastFocusModeRequest;public long DeliberateFocusSequence;
internal long AudioTextChanges;
public PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress? ChapterProgress;
public long NavigationQueuedTimestamp,NavigationAckTimestamp;public Guid LastTracedNavigationAck;public Guid? NavigationAcknowledgedId;public string NavigationResult="";public Guid PendingNavigation;public long NavigationRevision;public DateTime NavigationExpires;public string LastPresenceKey="";public DateTime LastPresenceUtc;public Guid Instance,Session,Manuscript,Authentication,Job;public long Revision,PresenceSequence;public string Title="",AssociationSite="",ChapterTitle="",SceneTitle="",Status="Link this manuscript to a book, then use Import manuscript in PlotDirector.",ReviewPath="";

View File

@ -1 +1 @@
<Project><PropertyGroup><ApplicationVersion>1.0.0.44</ApplicationVersion></PropertyGroup></Project>
<Project><PropertyGroup><ApplicationVersion>1.0.0.45</ApplicationVersion></PropertyGroup></Project>

View File

@ -0,0 +1,10 @@
namespace PlotDirector.Companion.Protocol;
// Per actual editor window; independent of content synchronisation and document ownership.
public sealed class FocusWindowState
{
public Guid Id {get;}=Guid.NewGuid();public bool Held{get;private set;}public long Sequence{get;private set;}public long LastSharedRevision{get;private set;}public Guid ModeRequest{get;private set;}=Guid.NewGuid();
private int start=-1,end=-1;private long appliedRevision=-1;private bool catchup;
public void Hold(bool held){if(Held==held)return;Held=held;if(!held){appliedRevision=-1;catchup=true;}ModeRequest=Guid.NewGuid();}
public long Observe(int nextStart,int nextEnd,bool deliberate){var changed=start!=nextStart||end!=nextEnd;start=nextStart;end=nextEnd;return changed&&deliberate&&!Held?++Sequence:0;}
public bool Accept(long revision,Guid origin){if(revision<LastSharedRevision||revision<=appliedRevision)return false;LastSharedRevision=revision;if(Held)return false;appliedRevision=revision;var follow=catchup||origin!=Id;catchup=false;return follow;}
}

View File

@ -34,6 +34,13 @@ public static class ProtocolVersion
[DataContract]
public sealed class Message
{
[DataMember] public string SharedFocusStatus{get;set;}="";
[DataMember] public bool CanSharedFocus{get;set;}
[DataMember] public bool FocusHeld{get;set;}
[DataMember] public bool AnyFollowingWindows{get;set;}
[DataMember] public Guid FocusWindowID{get;set;}
[DataMember] public Guid FocusModeRequest{get;set;}
[DataMember] public long DeliberateFocusSequence{get;set;}
[DataMember] public bool ChapterStatusProvided {get;set;}
[DataMember(EmitDefaultValue=false)] public string? AudioState { get; set; }
[DataMember(EmitDefaultValue=false)] public string[]? AudioOperations { get; set; }

View File

@ -3,6 +3,9 @@ namespace PlotDirector.Companion.Protocol;
[DataContract]
public sealed class AdapterCommand
{
[DataMember] public bool BackgroundFocus{get;set;}
[DataMember] public long FocusVersion{get;set;}
[DataMember] public Guid FocusOriginWindowID{get;set;}
[DataMember] public PlotDirector.Companion.Protocol.Manuscript.ChapterManifestItem? RangeBaseline {get;set;}
[DataMember] public DateTime ExpiresUtc {get;set;}
[DataMember] public Guid ManuscriptId {get;set;}
@ -26,6 +29,13 @@ public sealed class AdapterCommand
[DataContract]
public sealed class NativePresence
{
[DataMember] public string SharedFocusStatus{get;set;}="";
[DataMember] public bool CanSharedFocus{get;set;}
[DataMember] public bool FocusHeld{get;set;}
[DataMember] public bool AnyFollowingWindows{get;set;}
[DataMember] public Guid FocusWindowID{get;set;}
[DataMember] public Guid FocusModeRequest{get;set;}
[DataMember] public long DeliberateFocusSequence{get;set;}
[DataMember] public bool CanAcknowledgeNavigation {get;set;}
[DataMember] public Guid? NavigationAcknowledgedId {get;set;}
[DataMember] public string NavigationResult {get;set;}="";

View File

@ -3,6 +3,7 @@ using PlotDirector.Companion.Agent;
using PlotDirector.Companion.Client;
using PlotDirector.Companion.Protocol;
if(args.Contains("--shared-focus")){SharedFocusTests.Run((ok,name)=>{if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);});return;}
if(args.Contains("--word-observation")){await WordObservationTests.Run((ok,name)=>{if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);});return;}
if(args.Contains("--chapter-sync")){ChapterRangeVerificationTests.Run();ChapterReopenTests.Run();await ChapterAgentTests.Run();await ChapterHandshakeTests.Run();await WordReopeningWorkTests.Run();return;}
if(args.Contains("--native-capture-upload")){await NativeCaptureUploadTests.Run();return;}
@ -28,6 +29,7 @@ void SchedulerChecks()
var rejected=false;var thread=new Thread(()=>{try{scheduler.Pump();}catch(InvalidOperationException){rejected=true;}});thread.Start();thread.Join();Check(rejected,"Word scheduler rejects wrong thread");
scheduler.PrioritizeAuthor(TimeSpan.FromMinutes(1));scheduler.Post("low",()=>value=0);Check(!scheduler.Pump()&&value==999,"author activity suspends low priority work");
}
SharedFocusTests.Run(Check);
SchedulerChecks();
var mailbox=new BoundedMailbox();var id=Guid.NewGuid();
for(var i=0;i<10000;i++)mailbox.TryPost(new Message{Kind="selection",SessionId=id,Start=i});

View File

@ -0,0 +1,22 @@
using PlotDirector.Companion.Protocol;
internal static class SharedFocusTests
{
public static void Run(Action<bool,string> check)
{
var a=new FocusWindowState();var b=new FocusWindowState();var origin=Guid.NewGuid();
check(!a.Held&&!b.Held&&a.Id!=b.Id,"new Word windows follow with independent identities");
check(a.Observe(10,10,false)==0&&a.Observe(20,20,false)==0,"passive Word observations never publish");
check(a.Observe(30,30,true)==1&&a.Observe(30,30,true)==0,"deliberate changed selection publishes once");
var mode=a.ModeRequest;a.Hold(true);
check(a.Held&&!b.Held&&a.ModeRequest!=mode,"holding Word affects only that window");
check(a.Observe(40,40,true)==0&&a.Sequence==1,"held selection remains local without consuming a publication");
check(!a.Accept(4,origin)&&a.LastSharedRevision==4,"held window records latest shared revision without navigation");
a.Hold(false);
check(a.Sequence==1&&a.Accept(4,origin),"release catches latest focus without publishing held position");
check(!a.Accept(4,origin)&&!a.Accept(3,origin),"duplicate and delayed Word focus deliveries cannot navigate again");
check(!a.Accept(5,a.Id)&&a.LastSharedRevision==5,"originating Word window does not echo its own selection");
a.Hold(true);a.Observe(50,50,true);a.Hold(false);check(a.Accept(5,a.Id),"release returns to shared reference even when this same Word window originally published it");
check(b.Accept(5,a.Id),"another following Word window can receive that selection");
}
}

View File

@ -39,6 +39,10 @@ internal static class TrayTests
bool staleLaunch=false;
try{control.OpenPage(Guid.NewGuid(),"writer");}catch(InvalidOperationException){staleLaunch=true;}
check(staleLaunch&&launched.Count==1,"Return to Writer rejects a stale document without launching a page");
var retired=Apply(new(){Kind="tray-intent",SessionId=first.SessionId,Revision=1});
check(retired.Status!="ok"&&launched.Count==1,"retired Intent ribbon IPC cannot launch a separate workspace");
control.OpenPage(first.SessionId,"context");
check(launched.Last().EndsWith("&view=context",StringComparison.Ordinal)&&launched.Last().Contains("sessionId="+first.SessionId),"Context launch retains authorised exact-session routing for browser window reuse");
bool refused=false;try{control.SelectBook(second.SessionId,999,false);}catch(InvalidOperationException){refused=true;}check(refused,"tray refuses unauthorised books before Word metadata command");
using(var heartbeatStop=new CancellationTokenSource()){
var heartbeat=control.Heartbeat(heartbeatStop.Token);await Until(()=>handler.Heartbeats==1);await Task.Delay(600);

View File

@ -37,6 +37,7 @@ namespace PlotDirector.WordAddIn
try
{
Refresh("PlotDirectorStatus", GetStatus(null));
Refresh("PlotDirectorHold",adapter()?.FocusWindowKey+GetFocusHeld(null));Refresh("PlotDirectorFocusState",adapter()?.FocusWindowKey+GetFocusState(null));
Refresh("PlotDirectorBook", GetBookTip(null));
Refresh("PlotDirectorChapter", GetChapterTip(null));
Refresh("PlotDirectorScene", GetSceneTip(null));
@ -44,7 +45,6 @@ namespace PlotDirector.WordAddIn
Refresh("PlotDirectorSyncProgress", GetSyncProgress(null));
var enabled = CanOpenBook(null).ToString();
Refresh("PlotDirectorContext", enabled);
Refresh("PlotDirectorIntent", enabled);
Refresh("PlotDirectorWeb", enabled);
Refresh("PlotDirectorSynchronise", enabled);
Refresh("PlotDirectorRepair", enabled);
@ -68,6 +68,11 @@ namespace PlotDirector.WordAddIn
ui?.InvalidateControl(control.Id);
}
public bool GetFocusHeld(Office.IRibbonControl control)=>adapter()?.WindowFocusHeld(control?.Context)==true;
public string GetFocusAction(Office.IRibbonControl control)=>GetFocusHeld(control)?"Release Hold":"Hold";
public string GetFocusState(Office.IRibbonControl control)=>adapter()?.WindowFocusState(control?.Context)??"Following";
public string GetFocusTip(Office.IRibbonControl control)=>GetFocusHeld(control)?"Release Hold: catch up to shared manuscript focus. Content synchronisation stays active.":"Hold this Word window at its local position. Other windows and content synchronisation continue.";
public void ToggleFocusHold(Office.IRibbonControl control,bool pressed){adapter()?.SetFocusHeld(pressed);Invalidate();}
public bool CanOpenBook(Office.IRibbonControl control) => adapter()?.HasRibbonBook == true;
public string GetBookTip(Office.IRibbonControl control) => adapter()?.RibbonBook ?? "No linked book";
public string GetChapterTip(Office.IRibbonControl control) => adapter()?.RibbonChapter ?? "Chapter unverified";
@ -77,7 +82,6 @@ namespace PlotDirector.WordAddIn
public string GetSyncTip(Office.IRibbonControl control) => adapter()?.ChapterStatusTip ?? "Open Companion to connect.";
public string GetStatus(Office.IRibbonControl control) => adapter()?.ConnectionState == "connected" ? "Companion connected" : "Companion offline";
public void OpenContext(Office.IRibbonControl control) => adapter()?.OpenWritingWorkspace("tray-context");
public void OpenIntent(Office.IRibbonControl control) => adapter()?.OpenWritingWorkspace("tray-intent");
public void OpenPlotDirector(Office.IRibbonControl control) => adapter()?.OpenWritingWorkspace("tray-workspace");
public void Synchronise(Office.IRibbonControl control) => adapter()?.RequestChapterSynchronisation(false);
public void Repair(Office.IRibbonControl control) => adapter()?.RequestChapterSynchronisation(true);

View File

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

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.44")]
[assembly: AssemblyFileVersion("1.0.0.44")]
[assembly: AssemblyVersion("1.0.0.45")]
[assembly: AssemblyFileVersion("1.0.0.45")]
[assembly: ComVisible(false)]

View File

@ -7,9 +7,9 @@
<editBox id="PlotDirectorChapter" label="Chapter" getText="GetChapterTip" getSupertip="GetChapterTip" onChange="RestoreTitle" sizeString="MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" />
<editBox id="PlotDirectorScene" label="Scene" getText="GetSceneTip" getSupertip="GetSceneTip" onChange="RestoreTitle" sizeString="MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" />
</group>
<group id="PlotDirectorSharedFocus" label="Manuscript focus"><toggleButton id="PlotDirectorHold" getLabel="GetFocusAction" imageMso="Lock" getPressed="GetFocusHeld" onAction="ToggleFocusHold" getSupertip="GetFocusTip"/><editBox id="PlotDirectorFocusState" label="State" getText="GetFocusState" onChange="RestoreTitle" sizeString="MMMMMMMMMMMMMMMMMMMMMMMM"/></group>
<group id="PlotDirectorWriting" label="Writing">
<button id="PlotDirectorContext" label="Writing Context" size="large" imageMso="ReadingMode" onAction="OpenContext" getEnabled="CanOpenBook" />
<button id="PlotDirectorIntent" label="Writing Intent" size="large" imageMso="ReviewNewComment" onAction="OpenIntent" getEnabled="CanOpenBook" />
<button id="PlotDirectorContext" label="Context" size="large" imageMso="ReadingMode" onAction="OpenContext" getEnabled="CanOpenBook" />
<button id="PlotDirectorWeb" label="PlotDirector" size="large" imageMso="HyperlinkInsert" onAction="OpenPlotDirector" getEnabled="CanOpenBook" />
</group>
<group id="PlotDirectorCompanion" label="Companion">

View File

@ -102,6 +102,7 @@ namespace PlotDirector.WordAddIn
invalidateRibbon();
});
link.Received += message => {
if(!string.IsNullOrEmpty(message.SharedFocusStatus))PostToUi(()=>{sharedFocusStatus=message.SharedFocusStatus;invalidateRibbon?.Invoke();});
if(message.Status=="ready")PostToUi(()=>{var capabilities=(message.Capabilities??"").Split(',');traySupported=capabilities.Contains(ProtocolVersion.TrayCapability);liveChapterTextSupported=capabilities.Contains(ProtocolVersion.LiveChapterTextCapability);nativeChapterTextSupported=capabilities.Contains(ProtocolVersion.NativeChapterTextCapability);nativeChapterPositionsSupported=capabilities.Contains(ProtocolVersion.NativeChapterPositionsCapability);});
if(message.ChapterStatusProvided&&message.SessionId!=Guid.Empty)PostToUi(()=>ReceiveChapterStatus(message));
if((message.Action=="tray-sync"||message.Action=="tray-repair")&&message.Status!="ok")PostToUi(()=>{
@ -189,7 +190,7 @@ namespace PlotDirector.WordAddIn
})) pendingOpen.Remove(document);
}
private void Activate(Word.Document document,Word.Window window) { activationPending=true;Open(document); ScheduleSelection(); }
private void SelectionChanged(Word.Selection selection) { selectionNotifications++;ScheduleSelection(); }
private void SelectionChanged(Word.Selection selection) { selectionNotifications++;MarkDeliberateFocus();ScheduleSelection(); }
private void ScheduleSelection()
{
if (disposed) return;
@ -226,7 +227,8 @@ namespace PlotDirector.WordAddIn
if(active!=state||activationPending){link.TryPost(new Message {Kind="active",SessionId=state.Session,Revision=state.Revision});activationPending=false;}
ChangeActiveDocument(state);
link.TryPost(new Message {Kind="selection",SessionId=state.Session,Revision=state.Revision,Start=start,End=end,WordSaved=saved&&Com(()=>application.BackgroundSavingStatus)==0,WordObservedUtc=observationStartedUtc,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth});
var focusObservation=FocusObservation(document,start,end);
link.TryPost(new Message {CanSharedFocus=focusObservation.CanSharedFocus,FocusHeld=focusObservation.FocusHeld,AnyFollowingWindows=focusObservation.AnyFollowingWindows,FocusWindowID=focusObservation.FocusWindowID,FocusModeRequest=focusObservation.FocusModeRequest,DeliberateFocusSequence=focusObservation.DeliberateFocusSequence,Kind="selection",SessionId=state.Session,Revision=state.Revision,Start=start,End=end,WordSaved=saved&&Com(()=>application.BackgroundSavingStatus)==0,WordObservedUtc=observationStartedUtc,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth});
// Prose is read only on an explicit Companion request; cursor observations never rescan it.
}
@ -283,7 +285,7 @@ namespace PlotDirector.WordAddIn
if(!NavigationPolicy.Current(command,doc.Session,doc.Revision,doc.Identity,DateTime.UtcNow,Com(()=>doc.Document.Saved)))throw new InvalidOperationException("Navigation expired or document changed.");
if(completedNavigationIds.Contains(command.Id)){Reply(command,"ok");return;}
var position=command.Chapter.Start;if(position<0||position>DocumentEnd(doc.Document))throw new InvalidOperationException("Position no longer exists.");
Metric("navigation-identity-and-target",navigationClock.Elapsed.TotalMilliseconds,command.Id);navigationClock.Restart();Word.Range range=null;try{range=Com(()=>doc.Document.Range(position,position));Com(()=>{range.Select();return true;});Metric("navigation-word-selection",navigationClock.Elapsed.TotalMilliseconds,command.Id);navigationExecutions++;lastNavigationId=command.Id;if(completedNavigationIds.Count==64)completedNavigationIds.Dequeue();completedNavigationIds.Enqueue(command.Id);}finally{Release(range);}
Metric("navigation-identity-and-target",navigationClock.Elapsed.TotalMilliseconds,command.Id);navigationClock.Restart();Word.Range range=null;try{range=Com(()=>doc.Document.Range(position,position));if(command.BackgroundFocus)FollowSharedFocus(doc.Document,command,range);else Com(()=>{range.Select();return true;});Metric("navigation-word-selection",navigationClock.Elapsed.TotalMilliseconds,command.Id);navigationExecutions++;lastNavigationId=command.Id;if(completedNavigationIds.Count==64)completedNavigationIds.Dequeue();completedNavigationIds.Enqueue(command.Id);}finally{Release(range);}
}
else if(command.Kind=="associate"){
if(command.Remember){

View File

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using PlotDirector.Companion.Protocol;
using Word=Microsoft.Office.Interop.Word;
namespace PlotDirector.WordAddIn
{
public sealed partial class WordAdapter
{
[DllImport("user32.dll")]private static extern short GetAsyncKeyState(int key);
[DllImport("user32.dll")]private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]private static extern uint GetWindowThreadProcessId(IntPtr window,out uint process);
private readonly Dictionary<int,FocusWindowState> focusWindows=new Dictionary<int,FocusWindowState>();
private readonly uint focusProcessId=(uint)Process.GetCurrentProcess().Id;private Guid deliberateFocusWindow;private bool deliberateFocusPending,applyingFocus;private string sharedFocusStatus="";
private FocusWindowState FocusWindow(Word.Window window){var handle=Com(()=>window.Hwnd);FocusWindowState state;if(!focusWindows.TryGetValue(handle,out state))focusWindows[handle]=state=new FocusWindowState();return state;}
private FocusWindowState ActiveFocusWindow(){Word.Window window=null;try{window=Com(()=>application.ActiveWindow);return window==null?null:FocusWindow(window);}catch(COMException){return null;}finally{Release(window);}}
public bool FocusHeld=>ActiveFocusWindow()?.Held==true;
public bool WindowFocusHeld(object context){var window=context as Word.Window;try{return window!=null?FocusWindow(window).Held:FocusHeld;}finally{Release(window);}}
public string FocusWindowKey=>ActiveFocusWindow()?.Id.ToString()??"";
private string FollowingFocusLabel=>sharedFocusStatus=="word-unmapped"?"Following · mapping unavailable":sharedFocusStatus=="save-required"?"Following · save Word first":sharedFocusStatus=="word-busy"?"Following · Word busy":"Following · Hold available";
public string FocusStateLabel=>FocusHeld?"Held · Release Hold":FollowingFocusLabel;
public string WindowFocusState(object context)=>WindowFocusHeld(context)?"Held · Release Hold":FollowingFocusLabel;
public void SetFocusHeld(bool held){var state=ActiveFocusWindow();if(state==null)return;state.Hold(held);deliberateFocusPending=false;scheduler.Post("selection",CaptureSelection);invalidateRibbon?.Invoke();}
private void MarkDeliberateFocus(){uint process;GetWindowThreadProcessId(GetForegroundWindow(),out process);if(applyingFocus||process!=focusProcessId)return;foreach(var key in new[]{1,37,38,39,40,33,34,35,36,9})if((GetAsyncKeyState(key)&0x8000)!=0){deliberateFocusPending=true;deliberateFocusWindow=ActiveFocusWindow()?.Id??Guid.Empty;break;}}
private Message FocusObservation(Word.Document document,int start,int end){var state=ActiveFocusWindow();var pending=deliberateFocusPending&&state?.Id==deliberateFocusWindow;deliberateFocusPending=false;bool any=false;Word.Windows windows=null;var alive=new HashSet<int>();try{windows=Com(()=>application.Windows);for(int i=1;i<=Com(()=>windows.Count);i++){Word.Window window=null;try{window=Com(()=>windows[i]);alive.Add(Com(()=>window.Hwnd));}finally{Release(window);}}foreach(var handle in focusWindows.Keys.Where(k=>!alive.Contains(k)).ToArray())focusWindows.Remove(handle);Release(windows);windows=Com(()=>document.Windows);for(int i=1;i<=Com(()=>windows.Count);i++){Word.Window window=null;try{window=Com(()=>windows[i]);if(!FocusWindow(window).Held)any=true;}finally{Release(window);}}}finally{Release(windows);}return new Message{CanSharedFocus=true,FocusWindowID=state?.Id??Guid.Empty,FocusHeld=state?.Held==true,AnyFollowingWindows=any,FocusModeRequest=state?.ModeRequest??Guid.Empty,DeliberateFocusSequence=state?.Observe(start,end,pending&&!applyingFocus)??0};}
private void FollowSharedFocus(Word.Document document,AdapterCommand command,Word.Range range)
{
Word.Windows windows=null;bool eligible=false,followed=false;applyingFocus=true;try{windows=Com(()=>document.Windows);for(int i=1;i<=Com(()=>windows.Count);i++){Word.Window window=null;try{window=Com(()=>windows[i]);var state=FocusWindow(window);if(!state.Accept(command.FocusVersion,command.FocusOriginWindowID))continue;eligible=true;Com(()=>{object atStart=true;window.ScrollIntoView(range,ref atStart);return true;});followed=true;}finally{Release(window);}}if(eligible&&!followed)throw new InvalidOperationException("Word could not follow in the background; its editing selection was retained.");}finally{applyingFocus=false;Release(windows);invalidateRibbon?.Invoke();}
}
}
}

View File

@ -1,7 +1,7 @@
{
"version": "1.0.0.44",
"msiVersion": "1.0.44",
"productCode": "{8245E12F-39A8-4FC3-B1A0-9FB6AEB62F1A}",
"version": "1.0.0.45",
"msiVersion": "1.0.45",
"productCode": "{C9797E15-A318-48BF-95B8-1769AEBCA565}",
"upgradeCode": "{641A087B-9779-458C-B290-BCBBAD49319A}",
"atlasBaseline": "9fed339879887964d526cff00772ffc4dc522c5d",
"baselineProductCode": "{98F46939-764D-407F-BD1F-1D88315D010A}",

View File

@ -0,0 +1,3 @@
// Read-only opt-in acceptance of relocated commands on the disposable Development account.
const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict');
(async()=>{assert(process.env.PD_CONTEXT_IDENTITY&&process.env.PD_CONTEXT_SCOPE);const who=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY)),s=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_SCOPE));assert.equal(who.Database,'PlotDirector_Development');assert.equal(who.UserID,s.user);assert(who.Email.startsWith('pwa-browser-'));const b=await chromium.launch();try{const c=await b.newContext(),p=await c.newPage();await p.addLocatorHandler(p.locator('[data-desktop-continue]'),async l=>l.click());await p.goto('https://dev.plotdirector.com/Account/Login');await p.locator('[name=Email]').fill(who.Email);await p.locator('[name=Password]').fill(who.Password);await Promise.all([p.waitForURL(u=>u.pathname!='/Account/Login'),p.locator('button[type=submit]').click()]);const id=s.characters[0];await p.goto('https://dev.plotdirector.com/Characters/Details/'+id+'?tab=overview');await p.locator('[data-character-ribbon="'+id+'"]').waitFor();assert.match(await p.locator('[data-character-ribbon-edit]').getAttribute('href'),new RegExp('/Characters/Edit/'+id+'$'));await p.locator('[data-character-ribbon] [data-bs-toggle=dropdown]').click();const menu=p.locator('[data-character-actions-for="'+id+'"]');assert.equal(await menu.locator('form[action*="Reanalyse"] [name=id]').inputValue(),String(id));assert((await menu.locator('form[action*="Reanalyse"] [name=__RequestVerificationToken]').inputValue()).length>0);for(const action of ['Edit','Merge']){const response=await c.request.get('https://dev.plotdirector.com/Characters/'+action+'/'+id);assert.equal(response.status(),200);}for(const format of ['html','markdown']){const response=await c.request.get('https://dev.plotdirector.com/Exports/Character/'+id+'?format='+format);assert.equal(response.status(),200);assert((await response.body()).length>0);if(format==='html')assert.match(response.headers()['content-type'],/text\/html/);else assert.match(response.headers()['content-disposition'],/attachment/);}await menu.locator('form[action*="Archive"] button').click();await p.locator('#plotlineConfirmModal.show').waitFor();await p.locator('#plotlineConfirmModal [data-bs-dismiss=modal]').first().click();console.log('PASS Development ribbon read-only acceptance: correct character Edit/Merge GETs, original HTML and Markdown export responses, scoped antiforgery reanalysis form, Archive confirmation opened and cancelled. No reanalysis queued or baseline character changed.');}finally{await b.close();}})().catch(e=>{console.error(e);process.exitCode=1});

View File

@ -0,0 +1,2 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),path=require('node:path');
(async()=>{const b=await chromium.launch();try{const p=await b.newPage();await p.setContent('<div data-character-workspace><header data-character-analysis-panel data-character-id="5" data-analysis-run-id="10" data-analysis-status="Completed"><span data-character-analysis-status>Completed</span><span data-character-analysis-message></span></header></div>');await p.evaluate(()=>{window.refreshes=0;document.querySelector('[data-character-workspace]').addEventListener('character-analysis-updated',()=>window.refreshes++);const connection={on(name,fn){window.snapshot=fn},onreconnected(fn){window.reconnect=fn},start:async()=>{},invoke:async()=>({characterId:5,characterEnrichmentRunID:10,status:'Completed'})};window.signalR={HubConnectionBuilder:class{withUrl(){return this}withAutomaticReconnect(){return this}build(){return connection}}};});await p.addScriptTag({path:path.resolve(__dirname,'../../PlotLine/wwwroot/js/character-enrichment-detail.js')});await p.waitForTimeout(750);assert.equal(await p.evaluate(()=>refreshes),0);await p.evaluate(()=>{snapshot({characterId:99,characterEnrichmentRunID:99,status:'Completed'});snapshot({characterId:5,characterEnrichmentRunID:11,status:'Running'});snapshot({characterId:5,characterEnrichmentRunID:11,status:'Completed'});snapshot({characterId:5,characterEnrichmentRunID:11,status:'Completed'});});await p.waitForFunction(()=>refreshes===1);await p.evaluate(()=>{reconnect();snapshot({characterId:5,characterEnrichmentRunID:12,status:'Completed'});});await p.waitForFunction(()=>refreshes===2);await p.waitForTimeout(750);assert.equal(await p.evaluate(()=>refreshes),2);assert.equal(await p.locator('[data-character-analysis-status]').innerText(),'Completed');console.log('PASS Character enrichment: completed replay is silent, unrelated/old runs ignored, each later completed run refreshes persisted workspace once; no full-page navigation or AI work.');}finally{await b.close();}})().catch(e=>{console.error(e);process.exitCode=1});

View File

@ -0,0 +1,14 @@
// Explicit Development-only opt-in. Creates its own disposable character and relationship.
const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict');
(async()=>{assert(process.env.PD_CONTEXT_IDENTITY&&process.env.PD_CONTEXT_SCOPE);const who=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY)),s=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_SCOPE));assert.equal(who.Database,'PlotDirector_Development');assert.equal(who.UserID,s.user);assert(who.Email.startsWith('pwa-browser-'));const b=await chromium.launch();let step='login';try{const c=await b.newContext({viewport:{width:1366,height:1000}}),p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.addLocatorHandler(p.locator('[data-desktop-continue]'),async l=>l.click());await p.goto('https://dev.plotdirector.com/Account/Login');await p.locator('[name=Email]').fill(who.Email);await p.locator('[name=Password]').fill(who.Password);await Promise.all([p.waitForURL(u=>u.pathname!='/Account/Login'),p.locator('button[type=submit]').click()]);
step='new isolated character and Supporting default';await p.goto('https://dev.plotdirector.com/Characters/Create?projectId='+s.project);assert.equal(await p.locator('[name=CharacterImportance]').inputValue(),'6');const fixtureName='Workspace qualification '+Date.now();await p.locator('[name=CharacterName]').fill(fixtureName);await Promise.all([p.waitForURL(/\/Characters\/Details\/\d+/),p.locator('button[type=submit]').filter({hasText:'Save character'}).click()]);const id=Number(new URL(p.url()).pathname.split('/').at(-1));assert(!s.characters.includes(id));fs.writeFileSync('/tmp/character-refinement-live-fixture.json',JSON.stringify({project:s.project,user:s.user,character:id}));await p.locator('[data-character-tab-content="overview"]').waitFor();
step='ribbon targets through character back/forward and refresh';await p.goto('https://dev.plotdirector.com/Characters/Details/'+s.characters[0]+'?tab=overview');await p.locator('[data-character-ribbon="'+s.characters[0]+'"]').waitFor();await p.goBack();await p.locator('[data-character-ribbon="'+id+'"]').waitFor();await p.goForward();await p.locator('[data-character-ribbon="'+s.characters[0]+'"]').waitFor();await p.goBack();await p.reload();await p.locator('[data-character-ribbon="'+id+'"]').waitFor();assert.match(await p.locator('[data-character-ribbon-edit]').getAttribute('href'),new RegExp('/Characters/Edit/'+id+'$'));
step='five live bounded tabs and empty states';for(const tab of ['relationships','evolution','appearances','knowledge','overview']){await p.click('[data-character-tab="'+tab+'"]');await p.locator('[data-character-tab-content="'+tab+'"]').waitFor();assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));}await p.click('[data-character-tab="relationships"]');await p.locator('[data-character-node="'+id+'"]').waitFor({state:'attached'});
step='existing Context peer notifications';const peer=await c.newPage();await peer.goto(`https://dev.plotdirector.com/Writing/Context?projectId=${s.project}&bookId=${s.book}&sceneId=${s.scene}`);await peer.waitForFunction(()=>document.querySelector('[data-context-workspace]')?.contextController.connection?.state==='Connected');await peer.evaluate(project=>{window.workspaceHints=0;document.querySelector('[data-context-workspace]').contextController.connection.on('ContextInvalidated',hint=>{if(Number(hint.projectId)===project)workspaceHints++});},s.project);
step='initial parent via canonical save';await p.locator('[data-workspace-add]').click();// Resolve the known fixture name from its authenticated shell, without printing it.
const targetShell=await c.request.get('https://dev.plotdirector.com/Characters/Details/'+s.characters[0]);const html=await targetShell.text();const name=await p.evaluate(text=>new DOMParser().parseFromString(text,'text/html').querySelector('h1')?.childNodes[0]?.textContent.trim(),html);assert(name);await p.locator('[data-workspace-target-search]').fill(name.slice(0,50));await p.locator('[data-workspace-target] option[value="'+s.characters[0]+'"]').waitFor({state:'attached'});await p.locator('[data-workspace-target]').selectOption(String(s.characters[0]));const type=await p.locator('[name=RelationshipTypeID] option').evaluateAll(ns=>ns.find(n=>/Family · Parent$/.test(n.textContent))?.value);assert(type);await p.selectOption('[name=RelationshipTypeID]',type);await p.locator('[name=Notes]').fill('Disposable workspace qualification definition');await p.locator('[data-workspace-operation-form] button[type=submit], [data-workspace-operation-form] button:not([type])').first().click();await p.waitForFunction(()=>!document.querySelector('[data-workspace-dialog]').open);await p.locator('[data-relationship-group] > summary').first().click();let row=p.locator('[data-workspace-relationship]').filter({hasText:'Disposable workspace qualification definition'});await row.waitFor();const rid=Number(await row.getAttribute('data-workspace-relationship'));row=p.locator('[data-workspace-relationship="'+rid+'"]');fs.writeFileSync('/tmp/character-refinement-live-fixture.json',JSON.stringify({project:s.project,user:s.user,character:id,relationship:rid}));await p.locator('[data-character-connection="'+rid+'"]').waitFor({state:'attached'});
step='dedicated empty history and exact return';await row.getByRole('link',{name:'History',exact:true}).click();await p.waitForURL(u=>u.pathname==='/Dynamics/Relationship/'+rid);assert.match(await p.locator('main').innerText(),/No recorded events/);assert.equal(await p.locator('.relationship-evolution-chart').count(),0);await p.getByRole('link',{name:'Return to character Relationships'}).click();await p.locator('[data-workspace-relationship="'+rid+'"].is-selected').waitFor();assert.equal(await row.evaluate(n=>n.closest('[data-relationship-group]').open),true);
step='live edit, dirty main navigation guard and archive preview';await row.locator('[data-workspace-operation="definition"]').click();await p.locator('[name=TypeID]').waitFor();const childType=await p.locator('[name=TypeID] option').evaluateAll(ns=>ns.find(n=>/Family · Child$/.test(n.textContent))?.value);assert(childType);await p.locator('[name=TypeID]').selectOption(childType);await p.locator('[name=ReverseDirection][type=checkbox]').check();await p.locator('[name=Notes]').fill('Disposable definition edited');p.once('dialog',d=>d.dismiss());assert.equal(await p.evaluate(()=>window.PlotDirectorCharacterWorkspace.requestLeave(()=>{window.unexpectedLeave=true})),false);assert.equal(await p.evaluate(()=>!!window.unexpectedLeave),false);await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-workspace-dialog]').open);await row.locator('[data-workspace-operation="archive"]').click();await p.locator('[name=Confirmed][type=checkbox]').waitFor();assert.match(await p.locator('[data-workspace-dialog]').innerText(),/0 dependent scene events will be retained/);assert.match(await p.locator('[data-workspace-dialog]').innerText(),/underlying relationship definition/);await p.locator('[name=Confirmed][type=checkbox]').check();await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(r=>!document.querySelector('[data-workspace-relationship="'+r+'"]'),rid);await p.locator('[data-character-connection="'+rid+'"]').waitFor({state:'detached'});assert.equal(await p.locator('#plotlineConfirmModal').evaluate(n=>n.classList.contains('show')),false);await p.click('[data-character-lens="story"]');await p.waitForFunction(()=>document.querySelector('[data-character-graph-status]').textContent!=='Loading recorded relationships…');
await peer.waitForFunction(()=>workspaceHints===3);await peer.waitForTimeout(400);assert.equal(await peer.evaluate(()=>workspaceHints),3);assert.equal(await peer.locator('[data-context-scene]').inputValue(),String(s.scene));
step='archive only this newly created fixture character';await p.locator('[data-character-ribbon] .dropdown-toggle').click();await p.locator('[data-character-actions-for] form[action*="Archive"] button').click();await p.locator('#plotlineConfirmModal [data-confirm-submit]').click();await p.waitForURL(u=>!u.pathname.endsWith('/Details/'+id));assert.deepEqual(errors,[]);console.log('PASS Development live Character workspace: new isolated Supporting fixture; all five tabs and exact dedicated History/return; canonical initial Parent add and same-ID Child/direction edit; dirty navigation rejection; explicit dependency preview; direct soft archive and Family/Story refresh; exactly one existing Context peer hint per add/edit/archive; newly created fixture character archived. Existing manuscript and baseline fixture relationships untouched.');
}catch(e){console.error('FAILED '+step+': '+e.message);process.exitCode=1;}finally{await b.close();}})();

View File

@ -0,0 +1,16 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
(async()=>{const b=await chromium.launch();let step='setup';try{const c=await b.newContext({viewport:{width:1366,height:1000}});await c.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));await c.route('**/native-companion/status',r=>r.fulfill({json:[]}));await c.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false}}));let removed=false,notes=null,fail=false,viewer=false,tabReads=[],familyReads=0;for(const [endpoint,fixture]of [['Tab','tab'],['Family','family'],['Operation','operation']])await c.route('**/Characters/Workspace/'+endpoint+'/*',async r=>{const u=new URL(r.request().url());if(endpoint==='Operation'&&r.request().method()==='POST'){if(fail){fail=false;await r.fulfill({response:await r.fetch({method:'GET',url:base+'/character-workspace-operation-fixture?operation=definition&relationshipId=9&invalid=true&notes='+encodeURIComponent('Draft retained')})});return;}if(r.request().postData()?.includes('archive'))removed=true;else notes='Saved fixture definition';await r.fulfill({json:{saved:true,message:removed?'Relationship archived; history retained.':'Relationship saved.'}});return;}if(endpoint==='Tab'){tabReads.push(u.searchParams.get('Tab'));u.searchParams.set('id',u.pathname.split('/').at(-1));}if(endpoint==='Family')familyReads++;u.searchParams.set('viewer',String(viewer));u.searchParams.set('removed',String(removed));if(notes)u.searchParams.set('notes',notes);await r.fulfill({response:await r.fetch({url:base+'/character-workspace-'+fixture+'-fixture'+u.search})});});await c.route('**/Characters/Workspace/Lookup/*',r=>r.fulfill({json:[{id:6,name:'Another established character'}]}));await c.route('**/Characters/Workspace/Story/*',r=>r.fulfill({json:{lens:'story',focusID:5,povID:null,sceneID:22,canEdit:!viewer,truncated:false,nodes:[{id:5,name:'Current character'},{id:7,name:'Recorded colleague'}],links:[{id:12,a:5,b:7,type:'Friend',category:'Friendship',state:'Earlier recorded state',reciprocal:false,initial:true,recent:[]}]}}));await c.route('**/Characters/Details/*',async r=>{const u=new URL(r.request().url());u.searchParams.set('id',u.pathname.split('/').at(-1));await r.fulfill({response:await r.fetch({url:base+'/character-workspace-fixture'+u.search})});});const p=await c.newPage(),errors=[];await p.addLocatorHandler(p.locator('[data-desktop-continue]'),async locator=>locator.click());let native=0,si=0;p.on('pageerror',e=>errors.push(e.message));p.on('request',r=>{if(r.url().includes('/hubs/native-companion/negotiate'))native++;if(r.url().includes('/hubs/story-intelligence/negotiate'))si++;});await p.goto(base+'/character-workspace-fixture');await p.waitForSelector('[data-character-tab-content="overview"]');
step='compact shell and lazy Overview';assert.deepEqual(tabReads,['overview']);assert.equal(await p.locator('[data-character-tab-content]').count(),1);assert.equal(await p.locator('[data-character-tab]').count(),5);assert.match(await p.locator('.character-workspace-header').innerText(),/Supporting/);assert.match(await p.locator('.character-dossier').innerText(),/Recorded variant/);assert(await p.locator('.character-workspace-header').evaluate(n=>n.getBoundingClientRect().height<260));assert.equal(await p.locator('[data-workspace-relationship]').count(),0);await p.screenshot({path:'/tmp/character-workspace-overview-desktop.png',fullPage:true});
step='relationships layout, branch and record selection';await p.click('[data-character-tab="relationships"]');await p.waitForSelector('[data-character-node="5"]');assert.equal(await p.locator('[data-workspace-relationship]').count(),4);assert.equal(await p.locator('[data-relationship-group]').count(),3);assert.equal(await p.locator('[data-relationship-group="6"]').evaluate(n=>n.open),false);await p.locator('[data-relationship-group="6"] > summary').click();assert.deepEqual(await p.locator('[data-relationship-group] > summary > strong').allTextContents(),['Recorded child','Recorded colleague','Recorded partner']);for(const [category,count]of [['family',2],['story',1],['',3]]){await p.locator('[data-workspace-filter] [name=Category]').selectOption(category);await p.locator('[data-workspace-filter]').getByRole('button',{name:'Apply filters'}).click();await p.waitForFunction(n=>document.querySelectorAll('[data-relationship-group]').length===n,count);}assert.equal(await p.locator('[data-relationship-group="6"]').evaluate(n=>n.open),true);await p.locator('[data-character-branch="3"]').click();await p.locator('[data-character-node="1"]').waitFor();await p.screenshot({path:'/tmp/character-workspace-family-desktop.png',fullPage:true});await p.locator('[data-workspace-relationship="9"] > p').first().click();assert(await p.locator('[data-workspace-relationship="9"]').evaluate(n=>n.classList.contains('is-selected')));await p.locator('[data-workspace-relationship="9"] [data-workspace-operation="definition"]').click();await p.waitForSelector('[data-workspace-operation-form]');assert(await p.locator('[data-workspace-operation-form]').evaluate(f=>[...f.querySelectorAll('textarea,select,input:not([type=hidden]):not([type=checkbox])')].every(n=>n.getBoundingClientRect().width>=f.clientWidth*.92)));assert.equal(await p.locator('[name=TypeID]').inputValue(),'1');await p.locator('[name=TypeID]').selectOption('2');await p.locator('[name=Notes]').fill('Saved fixture definition');await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-workspace-dialog]').open);await p.waitForFunction(()=>document.querySelector('[data-workspace-relationship="9"]')?.textContent.includes('Saved fixture definition'));
step='inline stale error, Escape and draft protection';await p.locator('[data-workspace-relationship="9"] [data-workspace-operation="definition"]').click();await p.locator('[name=Notes]').fill('Draft retained');fail=true;await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.locator('.validation-summary-errors').waitFor();assert.equal(await p.locator('[name=Notes]').inputValue(),'Draft retained');p.once('dialog',d=>d.dismiss());await p.keyboard.press('Escape');assert(await p.locator('[data-workspace-dialog]').evaluate(n=>n.open));p.once('dialog',d=>d.accept());await p.locator('[data-workspace-cancel]').click();
step='explicit underlying removal with retained dependent history';await p.locator('[data-workspace-relationship="9"] [data-workspace-operation="archive"]').click();await p.locator('[name=Confirmed][type=checkbox]').waitFor();assert.match(await p.locator('[data-workspace-dialog]').innerText(),/2 dependent scene events will be retained/);assert.match(await p.locator('[data-workspace-dialog]').innerText(),/1 separately recorded/);await p.locator('[name=Confirmed][type=checkbox]').check();await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-workspace-dialog]').open);await p.waitForFunction(()=>!document.querySelector('[data-workspace-relationship="9"]'));assert(familyReads>1);assert.equal(await p.locator('[data-relationship-group="6"]').evaluate(n=>n.open),true);assert.equal(await p.locator('#plotlineConfirmModal').evaluate(n=>n.classList.contains('show')),false);
step='bounded Evolution, Appearances and Knowledge and cached tabs';for(const tab of ['evolution','appearances','knowledge']){await p.click('[data-character-tab="'+tab+'"]');await p.locator('[data-character-tab-content="'+tab+'"]').waitFor();assert.equal(await p.locator('[data-workspace-entry]').count(),25);await p.locator('[data-workspace-entry] summary').first().click();assert(await p.locator('[data-workspace-entry] .character-record-detail').first().isVisible());}await p.locator('[data-workspace-page="2"]').click();await p.waitForSelector('[data-character-tab-content][data-page="2"]');assert.equal(await p.locator('[data-workspace-entry]').count(),25);const reads=tabReads.length;await p.click('[data-character-tab="overview"]');await p.waitForSelector('[data-character-tab-content="overview"]');await p.click('[data-character-tab="knowledge"]');await p.waitForSelector('[data-character-tab-content="knowledge"]');assert.equal(tabReads.length,reads+1); // Overview invalidated by the save; Knowledge restores its second page.
step='selected story point and back forward';await p.click('[data-workspace-position]');await p.locator('[data-workspace-dialog] [data-workspace-entry="22"] summary').click();await p.locator('[data-workspace-set-position="22"]').click();await p.waitForSelector('[data-character-tab-content="knowledge"][data-scene="22"]');assert.match(p.url(),/SceneID=22/);await p.goBack();await p.waitForSelector('[data-character-tab-content="knowledge"][data-page="2"]');await p.goForward();await p.waitForSelector('[data-character-tab-content="knowledge"][data-scene="22"]');
step='Story network uses selected point and filters';await p.click('[data-character-tab="relationships"]');await p.waitForSelector('[data-character-node]');await p.click('[data-character-lens="story"]');await p.locator('[data-character-connection="12"]').waitFor({state:'attached'});assert.match(await p.locator('[data-character-graph-selection]').innerText(),/Recorded identity|Current character/);
step='responsive and touch-size geometry';for(const width of [1366,1024,768,390]){await p.setViewportSize({width,height:1000});for(const tab of ['overview','relationships','evolution','appearances','knowledge']){await p.click('[data-character-tab="'+tab+'"]');await p.locator('[data-character-tab-content="'+tab+'"]').waitFor();assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),width+'/'+tab);}}await p.screenshot({path:'/tmp/character-workspace-mobile.png',fullPage:true});assert.equal(native,1);assert(si<=2,'existing global/detail SI connections do not grow per tab');
step='direct legacy fragment, remembered character tab and keyboard';await p.goto(base+'/Characters/Details/5#character-gallery');await p.locator('[data-workspace-gallery][open]').waitFor();await p.click('[data-character-tab="knowledge"]');await p.waitForSelector('[data-character-tab-content="knowledge"]');await p.locator('[data-character-switch]').fill('another');await p.locator('[data-character-matches] a').click();await p.waitForURL(/\/Characters\/Details\/6\?tab=knowledge/);await p.locator('[data-character-tab-content="knowledge"]').waitFor();await p.locator('[data-character-tab="knowledge"]').focus();await p.keyboard.press('Home');await p.waitForSelector('[data-character-tab-content="overview"]');
step='one exact history destination and ribbon targets';await p.setViewportSize({width:1024,height:1000});await p.click('[data-character-tab="relationships"]');assert.equal(await p.locator('[data-workspace-history]').count(),0);assert.equal(await p.locator('[data-character-history]').count(),0);assert.match(await p.locator('[data-workspace-relationship="12"] a').filter({hasText:'History'}).getAttribute('href'),/Dynamics\/Relationship\/12.*returnCharacterId=6/);assert.equal(await p.locator('.character-workspace-header .button-row,.character-workspace-header .dropdown,.character-workspace-header a.btn').count(),0);assert.match(await p.locator('[data-character-ribbon-edit]').getAttribute('href'),/Characters\/Edit\/6/);assert.equal(await p.locator('[data-character-ribbon] form[action*="Archive"] [name=id]').inputValue(),'6');await p.locator('[data-character-ribbon] [data-bs-toggle="dropdown"]').click();const menu=p.locator('[data-character-actions-for="6"]');await menu.waitFor({state:'visible'});assert.match(await menu.getByRole('link',{name:'Markdown',exact:true}).getAttribute('href'),/Exports\/Character\/6.*format=markdown/);assert(await menu.locator('form[action*="Archive"] button').evaluate(n=>{const r=n.getBoundingClientRect();return n.contains(document.elementFromPoint(r.x+r.width/2,r.y+r.height/2));}));await p.keyboard.press('Escape');
step='tablet touch pan and pinch';await p.setViewportSize({width:768,height:1000});await p.locator('[data-character-lens="family"]').click();await p.locator('[data-character-node]').first().waitFor({state:'attached'});await p.locator('[data-character-graph-reset]').click();const host=p.locator('[data-character-graph]');await host.scrollIntoViewIfNeeded();const box=await host.boundingBox(),x=box.x+box.width*.5,y=box.y+box.height*.5,cdp=await c.newCDPSession(p);await cdp.send('Emulation.setTouchEmulationEnabled',{enabled:true,maxTouchPoints:2});const world=p.locator('[data-character-graph] svg > g'),beforePan=await world.getAttribute('transform');await cdp.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[{x,y,id:1}]});await cdp.send('Input.dispatchTouchEvent',{type:'touchMove',touchPoints:[{x:x+70,y:y+30,id:1}]});await cdp.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});assert.notEqual(await world.getAttribute('transform'),beforePan);const beforePinch=await world.getAttribute('transform');await cdp.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[{x:x-35,y,id:1},{x:x+35,y,id:2}]});await cdp.send('Input.dispatchTouchEvent',{type:'touchMove',touchPoints:[{x:x-70,y,id:1},{x:x+70,y,id:2}]});await cdp.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});assert.notEqual(await world.getAttribute('transform'),beforePinch);await p.screenshot({path:'/tmp/character-workspace-tablet-family.png',fullPage:false});await cdp.send('Emulation.setTouchEmulationEnabled',{enabled:false});
step='return to exact definition and retained group';removed=false;await p.goto(base+'/Characters/Details/5?tab=relationships&relationshipId=9');await p.waitForSelector('[data-workspace-relationship="9"].is-selected');assert.equal(await p.locator('[data-relationship-group="6"]').evaluate(n=>n.open),true);for(const width of [1366,1024,768,390]){await p.setViewportSize({width,height:1000});await p.locator('[data-character-ribbon] [data-bs-toggle="dropdown"]').click();const menu=p.locator('[data-character-actions-for="5"]');await menu.waitFor({state:'visible'});const archive=menu.locator('form[action*="Archive"] button');assert(await archive.evaluate(n=>{const r=n.getBoundingClientRect();return n.contains(document.elementFromPoint(r.x+r.width/2,r.y+r.height/2));}));assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));await p.keyboard.press('Escape');}await p.setViewportSize({width:1366,height:1000});await p.evaluate(()=>{document.documentElement.dataset.appTheme='warm-dark';document.documentElement.dataset.theme='dark';document.documentElement.dataset.bsTheme='dark'});await p.screenshot({path:'/tmp/character-refinement-grouped-dark.png',fullPage:true});
step='read-only workspace';viewer=true;await p.goto(base+'/character-workspace-fixture?viewer=true&tab=relationships');await p.waitForSelector('[data-character-tab-content="relationships"]');assert.equal(await p.locator('[data-workspace-operation]').count(),0);assert.equal(await p.locator('[data-workspace-add]').count(),0);assert.deepEqual(errors,[]);console.log('PASS main Character browser: compact header, five lazy tabs, dossier/aliases/gallery, bounded explorers and pages, Family branches, Story and selected point, diagram/record selection, modal widths/inline error/Escape/unsaved protection, explicit archive consequences, refresh, cache, back/forward, character links, legacy hash, keyboard, desktop/laptop/tablet/mobile, touch pan/pinch, grouped/filterable records, exact History return, current-character ribbon targets and read-only; connection counts stable across tabs.');
}catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await b.close();}})();

View File

@ -0,0 +1,19 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');
const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
(async()=>{const browser=await chromium.launch();let step='setup';try{
const context=await browser.newContext({viewport:{width:1366,height:768}});let posts=0,fail=true;
await context.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));
for(const url of ['**/native-companion/status','**/native-companion/connection-state','**/Writing/Context/Position?*'])await context.route(url,r=>r.fulfill({json:url.endsWith('status')?[]:{connected:false,known:false}}));
await context.route('**/Writing/Context/Tabs/*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-tab-fixture/'+u.pathname.split('/').at(-1)+u.search})});});
await context.route('**/Writing/Context/EditCharacter*',async r=>{const post=r.request().method()==='POST';if(post)posts++;if(post&&!fail)return r.fulfill({json:{saved:true,bookId:12}});const response=await r.fetch({url:base+'/context-edit-fixture?field=description'+(post?'&invalid=true':''),method:'GET'});await r.fulfill({status:post?422:200,contentType:'text/html',body:await response.text()});});
const page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(base+'/Writing/Context');await page.selectOption('[data-context-tab]','characters');await page.waitForSelector('[data-character-explorer]');
step='scene-first compact long catalogue';assert.equal(await page.locator('[data-context-character]').count(),12);assert.match(await page.locator('[data-context-character="5"]').innerText(),/POV/);assert.match(await page.locator('[data-context-character="6"] summary').innerText(),/Mentioned only/);assert.match(await page.locator('[data-context-character="5"]').innerText(),/Earlier hall[\s\S]*Saved room[\s\S]*Following garden/);
step='location canonical command and no-handler fallback';await page.evaluate(()=>{window.locationCommands=[];document.querySelector('[data-context-workspace]').addEventListener('context-command',e=>locationCommands.push(e.detail));});await page.locator('[data-context-character="5"] [data-context-location="77"]').click();await page.waitForSelector('[data-context-interaction-status] a');assert.deepEqual(await page.evaluate(()=>locationCommands[0]),{action:'location.focusAtStoryPoint',locationID:77,storyPoint:{chapterID:10,sceneID:22}});assert.equal(await page.locator('[data-context-tab]').first().inputValue(),'characters');
step='independent same-tool panes';await page.selectOption('[data-context-layout]','columns');await page.selectOption('[data-context-pane="1"] [data-context-tab]','characters');await page.locator('[data-context-pane="1"] [data-character-filter]').fill('name 10');assert.equal(await page.locator('[data-context-pane="1"] [data-context-character]:visible').count(),1);assert.equal(await page.locator('[data-context-pane="0"] [data-context-character]:visible').count(),12);
step='container widths, stacked, mobile, zoom';for(const width of [1366,760,390]){await page.setViewportSize({width,height:800});for(const layout of ['single','columns','rows']){await page.selectOption('[data-context-layout]',layout);await page.waitForTimeout(60);assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),width+'/'+layout);}}
await page.evaluate(()=>document.documentElement.style.zoom='1.25');assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));await page.evaluate(()=>document.documentElement.style.zoom='1');
step='correct values, cancel and draft protection';await page.selectOption('[data-context-layout]','single');await page.locator('[data-context-pane="0"] [data-context-edit="description"]').first().click();await page.waitForSelector('[data-context-edit-form]');assert.equal(await page.locator('[name=Value]').inputValue(),'Saved value');await page.locator('[name=Value]').fill('Entered draft');page.once('dialog',d=>d.dismiss());await page.click('[data-context-edit-cancel]');assert(await page.locator('[data-context-edit-dialog]').isVisible());assert.equal(posts,0);
step='failed save retains modal and draft inline';await page.click('[data-context-edit-form] [type=submit]');await page.waitForSelector('[data-context-edit-form] .validation-summary-errors');assert.equal(await page.locator('[name=Value]').inputValue(),'Entered draft');assert(await page.locator('[data-context-edit-dialog]').isVisible());
step='successful save closes with one success toast';fail=false;await page.evaluate(()=>{window.successes=0;window.PlotDirector.toast.success=()=>successes++;});await page.click('[data-context-edit-form] [type=submit]');await page.waitForFunction(()=>!document.querySelector('[data-context-edit-dialog]').open);assert.equal(await page.evaluate(()=>successes),1);assert.equal(posts,2);
assert.deepEqual(errors,[]);console.log('PASS Characters browser: twelve characters, independent panes, container layouts/mobile/zoom, modal values/cancel/unsaved protection/inline failure/single success (isolated HTTP save fixture; canonical persistence separately tested)');
} catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await browser.close();}})();

View File

@ -0,0 +1,7 @@
const fs=require('node:fs'),vm=require('node:vm'),assert=require('node:assert/strict');const sandbox={window:{}};vm.runInNewContext(fs.readFileSync('PlotLine/wwwroot/js/context-relationship-layout.js','utf8'),sandbox);const engine=sandbox.window.PlotDirectorContextRelationshipLayout;
const nodes=Array.from({length:15},(_,i)=>({id:i+1,name:'Person '+(i+1),birthDate:i===6?'2000-01-01':i===7?'2002-01-01':null}));let seq=0;const links=[];function add(a,b,type,reciprocal=false){links.push({id:++seq,a,b,type,reciprocal});return seq;}
add(1,2,'Spouse',true);add(1,3,'Parent');add(2,3,'Parent');add(3,4,'Spouse',true);add(3,5,'Parent');add(4,5,'Parent');add(5,6,'Spouse',true);add(5,10,'Former spouse',true);add(5,7,'Biological Parent');add(6,7,'Biological Parent');add(5,8,'Parent');add(6,8,'Parent');add(5,9,'Parent');add(10,9,'Parent');add(11,7,'Adoptive Parent');add(12,7,'Step Parent');add(3,15,'Child');add(1,14,'Grandparent');add(13,14,'Cousin');
const layout=engine.family(nodes,links),p=layout.positions;assert(p[1].y<p[3].y&&p[3].y<p[5].y&&p[5].y<p[7].y);assert.equal(p[5].y,p[6].y);assert.equal(p[5].y,p[10].y);assert(p[7].x<p[8].x);assert(layout.junctions.length>0);assert(layout.routes.some(r=>r.kind==='adoptive'));assert(layout.routes.some(r=>r.kind==='step'));
// Orthogonal connectors may cross with a visual bridge, but must not enter an unrelated card.
for(const route of layout.routes){const edge=links.find(l=>l.id===route.id);let cursor={x:0,y:0};const parts=[...route.d.matchAll(/([MHV])\s*(-?[\d.]+)(?:\s+(-?[\d.]+))?/g)];for(const part of parts){const next=part[1]==='M'?{x:+part[2],y:+part[3]}:part[1]==='H'?{x:+part[2],y:cursor.y}:{x:cursor.x,y:+part[2]};if(part[1]!=='M')for(const n of nodes){if(n.id===edge.a||n.id===edge.b)continue;const rect=p[n.id],inside=cursor.x===next.x?cursor.x>rect.x+1&&cursor.x<rect.x+179&&Math.max(Math.min(cursor.y,next.y),rect.y+1)<Math.min(Math.max(cursor.y,next.y),rect.y+65):cursor.y>rect.y+1&&cursor.y<rect.y+65&&Math.max(Math.min(cursor.x,next.x),rect.x+1)<Math.min(Math.max(cursor.x,next.x),rect.x+179);assert(!inside,`edge ${edge.id} crosses unrelated card ${n.id}`);}cursor=next;}}
assert.equal(JSON.stringify(engine.family(nodes,links).positions),JSON.stringify(layout.positions));const lone=engine.family([{id:1,name:'One known parent'},{id:2,name:'Child'}],[{id:1,a:1,b:2,type:'Parent'}]);assert.equal(lone.junctions.length,0);const coParents=engine.family([{id:1},{id:2},{id:3}],[{id:1,a:1,b:3,type:'Biological Parent'},{id:2,a:2,b:3,type:'Adoptive Parent'}]);assert.equal(coParents.junctions.length,0);console.log('PASS genealogical layout: generations, recorded unions, exact half-sibling parentage, biological/adoptive/step styles, birth order, deterministic positions, single/co-parent records create no inferred union, orthogonal routes avoid unrelated cards.');

View File

@ -0,0 +1,8 @@
// Opt-in Development acceptance; only the explicitly disposable qualification characters may be edited.
const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict');
(async()=>{assert(process.env.PD_CONTEXT_IDENTITY&&process.env.PD_CONTEXT_SCOPE);const who=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY)),scope=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_SCOPE));assert.equal(who.Database,'PlotDirector_Development');assert.equal(who.UserID,scope.user);assert(who.Email.startsWith('pwa-browser-'));assert.equal(scope.characters.length,2);const b=await chromium.launch();let step='login';try{const pages=[],counts=[];for(let i=0;i<2;i++){const c=await b.newContext({viewport:{width:1366,height:1000}}),p=await c.newPage();await p.goto('https://dev.plotdirector.com/Account/Login');await p.locator('[name=Email]').fill(who.Email);await p.locator('[name=Password]').fill(who.Password);await Promise.all([p.waitForURL(u=>u.pathname!='/Account/Login'),p.locator('button[type=submit]').click()]);if(i===0&&process.env.PD_CONTEXT_PREPARE_FAMILY==='1'){step='prepare isolated physical-presence fixture';await p.goto('https://dev.plotdirector.com/Scenes/SceneCharactersEditor?sceneId='+scope.scene);const ids=await p.locator('input[name$=".CharacterID"]').evaluateAll(ns=>ns.map(n=>Number(n.value)));assert.deepEqual([...ids].sort((a,b)=>a-b),[...scope.characters].sort((a,b)=>a-b));assert.equal(Number(await p.locator('[name=SceneID]').inputValue()),scope.scene);for(let row=0;row<ids.length;row++){const presence=p.locator(`[name="Characters[${row}].PresenceTypeID"]`),present=await presence.locator('option').evaluateAll(ns=>ns.find(n=>n.textContent.trim()==='Present')?.value);assert(present);await presence.selectOption(present);const role=p.locator(`[name="Characters[${row}].RoleInSceneTypeID"]`);if((await role.locator('option:checked').innerText()).trim()==='Mentioned Only'){const physicalRole=await role.locator('option').evaluateAll(ns=>ns.find(n=>n.value&&n.textContent.trim()!=='Mentioned Only')?.value);assert(physicalRole);await role.selectOption(physicalRole);}}await p.locator(`[name=POVCharacterID][value="${scope.characters[0]}"]`).check();await Promise.all([p.waitForURL(u=>u.pathname==='/Scenes/SaveSceneCharacters'),p.locator('[data-scene-editor-save]').click()]);assert.equal(JSON.parse(await p.locator('body').innerText()).success,true);step='login';}const counter={hubs:0,word:0};counts.push(counter);p.on('request',r=>{if(r.url().includes('/hubs/native-companion/negotiate'))counter.hubs++;if(/\/(Writing\/Context|WriterWord)\/Navigate/.test(new URL(r.url()).pathname))counter.word++;});await p.goto('https://dev.plotdirector.com/Writing/Context?'+new URLSearchParams({projectId:scope.project,bookId:scope.book,sceneId:scope.scene}));await p.selectOption('[data-context-tab]','relationships');await p.locator('[data-family-key]').first().waitFor();await p.locator('[data-graph-node]').first().waitFor();await p.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection?.state==='Connected');await p.evaluate(()=>{window.successes=0;const before=PlotDirector.toast.success;PlotDirector.toast.success=(...a)=>{successes++;before(...a);};});pages.push(p);}
const [p,remote]=pages;async function index(page){return page.evaluate(async args=>{const response=await fetch('/Writing/Context/Relationships/FamilyIndex?'+new URLSearchParams(args));if(!response.ok)throw Error('Index read failed');return response.json();},{bookId:scope.book,sceneId:scope.scene});}let current=await index(p);assert(scope.characters.every(id=>current.groups.some(g=>g.sceneMembers.includes(id))),'both qualification characters must be explicitly eligible scene participants');const merged=()=>current.groups.some(g=>scope.characters.every(id=>g.sceneMembers.includes(id)));
async function save(){await p.locator('[data-context-edit-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-context-edit-dialog]').open);}
if(!merged()){step='focused family connection groups two scene entries';await p.locator('[data-relationship-add]').click();await p.waitForSelector('[data-context-edit-form]');await p.selectOption('[name=SourceID]',String(scope.characters[0]));await p.selectOption('[name=TargetID]',String(scope.characters[1]));const type=await p.locator('[name=TypeID] option').evaluateAll(ns=>ns.find(n=>n.value&&/Parent/.test(n.textContent))?.value);assert(type);await p.selectOption('[name=TypeID]',type);const state=await p.locator('[name=StateID] option').evaluateAll(ns=>ns.find(n=>n.value)?.value);if(state)await p.selectOption('[name=StateID]',state);await p.locator('[name=Notes]').fill('Synthetic family grouping qualification');await save();await remote.waitForFunction(()=>document.querySelectorAll('[data-family-key]').length===1);current=await index(p);assert(merged());}
step='focused family correction persists and refreshes quiet peer';for(const page of pages){await page.locator(`[data-graph-node="${scope.characters[0]}"]`).click();await page.locator('[data-relationship-details] details summary').click();await page.locator('[data-inspect-connection]').first().click();}await p.locator('[data-relationship-details] [data-context-relationship-edit]').click();await p.waitForSelector('[data-context-edit-form]');const note='Synthetic family source correction '+Date.now();await p.locator('[name=Notes]').fill(note);await save();await remote.waitForFunction(note=>document.querySelector('[data-relationship-details]').textContent.includes(note),note);assert.equal(await remote.evaluate(()=>successes),0);assert(await p.evaluate(()=>successes)>=1);assert(counts.every(c=>c.hubs===1&&c.word===0));assert.equal(await p.locator('[data-context-scene]').inputValue(),String(scope.scene));console.log('PASS Development Family editing: authorised scene index and one tree; focused canonical family add/inspection/correction, membership regrouping, persisted notes, quiet receiving window, one SignalR connection per Context, no Word navigation. Disposable qualification characters only.');
}catch(e){console.error('FAILED '+step+': '+e.message);process.exitCode=1;}finally{await b.close();}})();

View File

@ -0,0 +1,16 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
(async()=>{const b=await chromium.launch();let step='setup';try{const c=await b.newContext({viewport:{width:1366,height:1000}});await c.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));for(const url of ['**/native-companion/status','**/native-companion/connection-state','**/Writing/Context/Position?*'])await c.route(url,r=>r.fulfill({json:url.endsWith('status')?[]:{known:false,connected:false}}));await c.route('**/Writing/Context/Tabs/*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-tab-fixture/'+u.pathname.split('/').at(-1)+u.search})});});await c.route('**/Writing/Context/Relationships/Lookup?*',async r=>r.fulfill({response:await r.fetch({url:base+'/context-lenses-lookup-fixture'})}));let merged=false,split=false,many=false,trees=0;for(const [route,fixture]of [['FamilyIndex','index'],['FamilyTree','tree']])await c.route('**/Writing/Context/Relationships/'+route+'?*',async r=>{if(route==='FamilyTree')trees++;const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-family-'+fixture+'-fixture'+u.search+'&large=true&merge='+merged+'&many='+many+'&split='+split})});});const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.goto(base+'/Writing/Context');await p.selectOption('[data-context-tab]','relationships');const pane=p.locator('[data-context-pane="0"]');await pane.locator('[data-graph-node="5"]').waitFor();
const index=()=>pane.locator('[data-family-key]');const visibleIDs=()=>pane.locator('[data-graph-node]').evaluateAll(ns=>ns.map(n=>Number(n.dataset.graphNode)));
step='scene family index and one tree';assert.equal(await index().count(),5);assert.equal(await pane.locator('[data-family-key][aria-pressed=true]').getAttribute('data-family-key'),'1');assert((await visibleIDs()).includes(8));assert(!(await visibleIDs()).includes(22));assert(!(await visibleIDs()).includes(25));assert(!(await visibleIDs()).includes(30));assert.equal(await pane.locator('[data-family-index] details').count(),1);await p.screenshot({path:'/tmp/context-family-initial-desktop.png',fullPage:true});
step='real genealogical connector inspection';await pane.locator('[data-relationship-svg]').scrollIntoViewIfNeeded();const point=await pane.locator('[data-graph-connection="7"]').evaluate(n=>{const p=n.getPointAtLength(n.getTotalLength()-12),m=n.getScreenCTM();return{x:m.a*p.x+m.c*p.y+m.e,y:m.b*p.x+m.d*p.y+m.f};});await p.mouse.click(point.x,point.y);await pane.locator('[data-graph-edge="7"].is-selected').waitFor({state:'attached'});assert.match(await pane.locator('[data-relationship-details]').innerText(),/Recorded person 3/);await pane.locator('[data-graph-node="5"]').click();
step='per-family view and unrelated notification stability';await pane.locator('[data-graph-zoom=in]').click();const zoom=await pane.locator('[data-relationship-viewport]').getAttribute('transform');await pane.locator('[data-family-key="21"]').click();await pane.locator('[data-graph-node="22"]').waitFor();assert(!(await visibleIDs()).includes(5));const before=trees;await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({bookId:12}));await p.waitForFunction(()=>document.querySelector('[data-family-key="21"]')?.getAttribute('aria-pressed')==='true');await p.waitForTimeout(180);assert(trees>before);assert((await visibleIDs()).includes(22));await pane.locator('[data-family-key="1"]').click();await pane.locator('[data-graph-node="5"]').waitFor();assert.equal(await pane.locator('[data-relationship-viewport]').getAttribute('transform'),zoom);
step='branch expand/collapse, exact recorded relatives and no edit';await pane.locator('[data-family-branch="3"]').click();await pane.locator('[data-graph-node="1"]').waitFor();assert.equal(await p.locator('[data-context-edit-dialog][open]').count(),0);await pane.locator('[data-family-branch="7"]').click();await pane.locator('[data-graph-node="11"]').waitFor();assert((await visibleIDs()).includes(12));assert((await visibleIDs()).includes(16));assert(!(await visibleIDs()).includes(100));assert.equal(await pane.locator('[data-family-branch="7"]').getAttribute('aria-expanded'),'true');await pane.locator('[data-family-key="21"]').click();await pane.locator('[data-graph-node="22"]').waitFor();await pane.locator('[data-relationship-person]').fill('relative 7');await pane.locator('[data-relationship-matches] button').click();await pane.locator('[data-graph-node="7"].is-selected').waitFor();assert.equal(await pane.locator('[data-family-key="1"]').getAttribute('aria-pressed'),'true');assert.match(await pane.locator('[data-relationship-viewport]').getAttribute('transform'),/scale\(1.2\)/);for(const id of [7,5]){await pane.locator(`[data-graph-node="${id}"]`).click();await pane.getByRole('button',{name:'Centre tree / network on this person',exact:true}).click();await pane.locator(`[data-graph-node="${id}"].is-selected`).waitFor();assert.match(await pane.locator('[data-relationship-viewport]').getAttribute('transform'),/scale\(1.2\)/);}await pane.locator('[data-graph-node="1"]').waitFor();await pane.locator('[data-graph-node="11"]').waitFor();await pane.locator('[data-family-branch="7"]').click();await p.waitForFunction(()=>!document.querySelector('[data-graph-node="11"]'));await pane.locator('[data-family-branch="3"]').focus();await p.keyboard.press('Enter');await p.waitForFunction(()=>!document.querySelector('[data-graph-node="1"]'));
step='split membership prunes obsolete expansions';await pane.locator('[data-family-branch="3"]').click();await pane.locator('[data-graph-node="1"]').waitFor();split=true;await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({bookId:12}));await p.waitForFunction(()=>document.querySelector('[data-family-key="5"]')?.getAttribute('aria-pressed')==='true');assert(!(await visibleIDs()).includes(3));assert(!(await visibleIDs()).includes(15));split=false;await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({bookId:12}));await p.waitForFunction(()=>document.querySelector('[data-family-key="1"]')?.getAttribute('aria-pressed')==='true');
step='isolated and cyclic entries';await pane.locator('[data-family-index] details summary').click();await pane.locator('[data-family-key="40"]').click();await pane.locator('[data-graph-node="40"]').waitFor();assert.deepEqual(await visibleIDs(),[40]);assert.match(await pane.locator('[data-relationship-status]').innerText(),/cyclic/);await pane.locator('[data-family-key="30"]').click();await pane.locator('[data-graph-node="30"]').waitFor();assert.deepEqual(await visibleIDs(),[30]);
step='independent family selection in two panes';await p.selectOption('[data-context-layout]','columns');await p.locator('[data-context-pane="1"] [data-context-tab]').selectOption('relationships');await p.locator('[data-context-pane="1"] [data-graph-node="5"]').waitFor();assert((await visibleIDs()).includes(30));await pane.locator('[data-family-key="21"]').click();await pane.locator('[data-graph-node="22"]').waitFor();assert.equal(await p.locator('[data-context-pane="1"] [data-family-key="1"]').getAttribute('aria-pressed'),'true');
step='new scene chooses new POV family';await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:11,sceneId:23}));await p.locator('[data-context-pane="1"] [data-graph-node="22"]').waitFor();assert.equal(await p.locator('[data-context-pane="1"] [data-family-key="21"]').getAttribute('aria-pressed'),'true');
step='membership edit reconciles index';merged=true;await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({bookId:12}));await p.waitForFunction(()=>document.querySelectorAll('[data-context-pane="0"] [data-family-key]').length===4);assert.equal(await pane.locator('[data-family-key="1"]').getAttribute('aria-pressed'),'true');
step='full half stacked narrow compact selection';for(const width of [1366,760,390]){await p.setViewportSize({width,height:1000});for(const layout of ['single','columns','rows']){await p.selectOption('[data-context-layout]',layout);await p.waitForTimeout(60);assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),width+'/'+layout);}}await p.selectOption('[data-context-layout]','single');assert(await pane.locator('[data-family-select]').isVisible());assert.equal(await pane.locator('.context-family-tabs').isVisible(),false);await pane.locator('[data-family-select]').selectOption('30');await pane.locator('[data-graph-node="30"]').waitFor();await p.screenshot({path:'/tmp/context-family-mobile.png',fullPage:true});
step='bounded retained family views';await pane.locator('[data-graph-zoom=in]').click();assert.match(await pane.locator('[data-relationship-viewport]').getAttribute('transform'),/scale\(1.2\)/);many=true;await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({bookId:12}));await p.waitForFunction(()=>document.querySelectorAll('[data-context-pane="0"] [data-family-select] option').length>12);for(const id of [31,32,33,34,35,36,37,38,39,42,43,44,45,46]){await pane.locator('[data-family-select]').selectOption(String(id));await pane.locator(`[data-graph-node="${id}"]`).waitFor();}await pane.locator('[data-family-select]').selectOption('30');await pane.locator('[data-graph-node="30"]').waitFor();assert.match(await pane.locator('[data-relationship-viewport]').getAttribute('transform'),/scale\(1\)/);
assert.deepEqual(errors,[]);console.log('PASS Family browser: distinct scene groups, POV bias, one tree, individual/cycle safeguards, per-family zoom/selection, notifications, branch +/- and keyboard, exact ancestry/adoption/step nodes, independent panes, new scene POV, membership merge/split regrouping, real SVG connector inspection, More and compact selector, 12-family retained-state bound, full/half/stacked/mobile.');
}catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await b.close();}})();

View File

@ -0,0 +1,27 @@
// Opt-in Development-only canonical persistence acceptance. Requires an explicitly disposable identity and scope.
const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict');
(async()=>{assert(process.env.PD_CONTEXT_IDENTITY&&process.env.PD_CONTEXT_SCOPE,'Disposable Development inputs required');const who=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY)),s=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_SCOPE));assert.equal(who.Database,'PlotDirector_Development');assert.equal(who.UserID,s.user);assert(who.Email.startsWith('pwa-browser-'));assert(s.characters?.length===2);const browser=await chromium.launch();let step='login';try{
const pages=[],counts=[];
for(let i=0;i<2;i++){const c=await browser.newContext({viewport:{width:1280,height:900}}),p=await c.newPage();pages.push(p);await p.goto('https://dev.plotdirector.com/Account/Login');await p.locator('[name=Email]').fill(who.Email);await p.locator('[name=Password]').fill(who.Password);await Promise.all([p.waitForURL(u=>u.pathname!='/Account/Login'),p.locator('button[type=submit]').click()]);const count={hub:0,word:0,reads:0};counts.push(count);p.on('request',r=>{if(r.url().includes('/hubs/')&&r.url().includes('/negotiate'))count.hub++;if(r.url().includes('/Writing/Context/Navigate')||r.url().includes('/WriterWord/Navigate'))count.word++;if(r.url().includes('/Writing/Context/Tabs/'))count.reads++;});await p.goto(`https://dev.plotdirector.com/Writing/Context?projectId=${s.project}&bookId=${s.book}&sceneId=${s.scene}`);await p.waitForSelector('[data-context-tab-fragment]');await p.selectOption('[data-context-tab]','characters');await p.waitForSelector('[data-character-explorer]');await p.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection?.state==='Connected');await p.evaluate(()=>{window.successes=0;const prior=window.PlotDirector.toast.success;window.PlotDirector.toast.success=(...a)=>{successes++;prior(...a);};});}
const [p,remote]=pages,id=s.characters[0],row=`[data-context-character="${id}"]`,stamp='Synthetic Context correction '+Date.now();
async function open(field){if(!await p.locator(row).evaluate(n=>n.open))await p.locator(row+' summary').click();await p.locator(row+` [data-context-edit="${field}"]`).click();await p.waitForSelector('[data-context-edit-form]');}
async function save(){await p.locator('[data-context-edit-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-context-edit-dialog]').open);}
step='live canonical description and quiet remote refresh';await open('description');await p.locator('[name=Value]').fill(stamp);await save();await remote.waitForFunction(stamp=>document.querySelector('[data-character-explorer]').textContent.includes(stamp),stamp);assert.equal(await p.evaluate(()=>successes),1);assert.equal(await remote.evaluate(()=>successes),0);
step='canonical life-status persistence and lens separation';await open('life-status');const originalLife=await p.locator('[name=Value]').inputValue();await p.selectOption('[name=Value]','true');await save();await remote.waitForFunction(()=>document.querySelector('[data-character-explorer]').textContent.includes('Deceased'));
for(const lens of ['family','story']){const graph=await p.evaluate(async args=>{const response=await fetch('/Writing/Context/Relationships/'+(args.lens==='family'?'FamilyTree':'Graph')+'?'+new URLSearchParams(args));if(!response.ok)throw Error('Graph '+response.status);const data=await response.json();return data.graph||data;},{bookId:s.book,sceneId:s.scene,focusId:id,lens});assert.equal(graph.nodes.find(n=>n.id===id).isDeceased,lens==='family'?true:null);}
await open('life-status');assert.equal(await p.locator('[name=Value]').inputValue(),'true');await p.selectOption('[name=Value]',originalLife);await save();
step='cancel persists nothing';await open('description');assert.equal(await p.locator('[name=Value]').inputValue(),stamp);await p.locator('[name=Value]').fill('Discarded synthetic draft');p.once('dialog',d=>d.accept());await p.click('[data-context-edit-cancel]');await open('description');assert.equal(await p.locator('[name=Value]').inputValue(),stamp);await p.click('[data-context-edit-cancel]');
async function lookupIdentity(query){const details=p.locator('[data-established-names]');if(!await details.evaluate(n=>n.open))await details.locator('summary').first().click();await p.locator('[data-context-name-lookup] [name=search]').fill(query);await p.locator('[data-context-name-lookup] [type=submit]').click();await p.locator('[data-context-name-identities] [data-name-usage-fragment]').waitFor();await p.locator(`[data-context-name-identities] [data-name-identity="${id}"]`).click();await p.waitForSelector('[data-name-identity-fragment]');}
step='names alias add and persisted spelling';await p.selectOption('[data-context-tab]','names');await p.waitForSelector('[data-context-names]');await lookupIdentity('Synthetic Context person one');await p.locator(`[data-context-edit="alias-add"][data-character-id="${id}"]`).click();await p.waitForSelector('[data-context-edit-form]');const alias='Synthetic alias '+Date.now();await p.locator('[name=Value]').fill(alias);await save();await p.waitForSelector('[data-context-names]');await lookupIdentity(alias);assert.match(await p.locator('[data-name-identity-fragment]').innerText(),new RegExp(alias));
await p.waitForTimeout(350);await p.waitForFunction(()=>!document.querySelector('[data-context-pane="0"] [aria-busy="true"]'));await lookupIdentity(alias);
step='live inline validation retains failed draft';await p.locator(`[data-context-edit="name"][data-character-id="${id}"]`).click();await p.waitForSelector('[data-context-edit-form]');await p.locator('[name=Value]').fill('');await p.locator('[data-context-edit-form] [type=submit]').click();await p.waitForSelector('.validation-summary-errors');assert(await p.locator('[data-context-edit-dialog]').isVisible());assert.equal(await p.locator('[name=Value]').inputValue(),'');p.once('dialog',d=>d.accept());await p.click('[data-context-edit-cancel]');
if(process.env.PD_CONTEXT_RELATIONSHIPS==='1'){
step='live one-relationship create and correction';await p.selectOption('[data-context-tab]','relationships');await remote.selectOption('[data-context-tab]','relationships');await p.waitForSelector('[data-context-relationships]');await remote.waitForSelector('[data-context-relationships]');
await p.locator('[data-relationship-lens="story"]').click();await remote.locator('[data-relationship-lens="story"]').click();await p.waitForFunction(()=>document.querySelector('[data-relationship-caption]')?.textContent.includes('Later developments are excluded'));await remote.waitForFunction(()=>document.querySelector('[data-relationship-caption]')?.textContent.includes('Later developments are excluded'));
const existing=p.locator('[data-graph-edge]');if(await existing.count()===0){await p.locator('[data-relationship-add]').click();await p.waitForSelector('[data-context-edit-form]');await p.selectOption('[name=SourceID]',String(s.characters[0]));await p.selectOption('[name=TargetID]',String(s.characters[1]));const type=await p.locator('[name=TypeID] option').evaluateAll(ns=>ns.find(n=>n.value&&!n.textContent.includes('Family'))?.value);await p.selectOption('[name=TypeID]',type);const state=await p.locator('[name=StateID] option').evaluateAll(ns=>ns.find(n=>n.value)?.value);await p.selectOption('[name=StateID]',state);await p.locator('[name=Notes]').fill('Synthetic relationship evidence');await save();}
async function selectConnection(page){await page.locator(`[data-graph-node="${id}"]`).click();await page.locator('[data-relationship-details] details summary').click();await page.locator('[data-inspect-connection]').first().click();}
step='live relationship SVG ready';await p.waitForSelector('[data-graph-edge]',{state:'attached'});await remote.waitForSelector('[data-graph-edge]',{state:'attached'});await selectConnection(p);await selectConnection(remote);step='live relationship save modal';await p.locator('[data-relationship-details] [data-context-relationship-edit="scene"]').click();await p.waitForSelector('[data-context-edit-form]');const note='Synthetic relationship correction '+Date.now();await p.locator('[name=Notes]').fill(note);await save();step='live relationship remote update';await remote.waitForFunction(note=>document.querySelector('[data-context-relationships]').textContent.includes(note),note);assert.equal(await remote.evaluate(()=>successes),0);
}
assert(counts.every(c=>c.word===0&&c.hub===1));console.log('PASS Development canonical editing: focused persisted values, cancel/unsaved protection, alias add, failed inline name draft retained, one local success/quiet second authenticated session, one connection each, no Word navigation'+(process.env.PD_CONTEXT_RELATIONSHIPS==='1'?', relationship create/correct persisted through existing services':''));
} catch(e){console.error('FAILED '+step+': '+e.message);process.exitCode=1;}finally{await browser.close();}})();

View File

@ -0,0 +1,8 @@
// Read-only authenticated/antiforgery denial checks; Development disposable identity required.
const {chromium}=require('playwright'),fs=require('fs'),assert=require('assert/strict');
(async()=>{const b=await chromium.launch();try{assert(process.env.PD_CONTEXT_SCOPE&&process.env.PD_CONTEXT_IDENTITY,'Explicit disposable Development inputs required');const s=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_SCOPE)),who=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY));assert.equal(who.Database,'PlotDirector_Development');assert.equal(who.UserID,s.user);assert(who.Email.startsWith('pwa-browser-'));const base='https://dev.plotdirector.com',unauth=await b.newContext(),auth=await b.newContext();const login=await auth.newPage();await login.goto(base+'/Account/Login');await login.locator('[name=Email]').fill(who.Email);await login.locator('[name=Password]').fill(who.Password);await Promise.all([login.waitForURL(u=>u.pathname!='/Account/Login'),login.locator('button[type=submit]').click()]);const path=`/Writing/Context/EditCharacter?bookId=${s.book}&sceneId=${s.scene}&characterId=${s.characters[0]}&field=description`;
assert([302,401].includes((await unauth.request.get(base+path,{maxRedirects:0})).status()));
for(const [url,status] of [[path.replace('field=description','field=emotion').replace('sceneId='+s.scene,'sceneId=2147483647'),403],[path.replace('characterId='+s.characters[0],'characterId=2147483647'),403],[path.replace('bookId='+s.book,'bookId=2147483647'),403],[path.replace('&field=description',''),400],[`/Writing/Context/EditRelationship?bookId=${s.book}&sceneId=${s.scene}&relationshipId=2147483647`,403]]){const response=await auth.request.get(base+url,{maxRedirects:0});if(status===403&&response.status()===302)assert.equal(new URL(response.headers().location,base).pathname,"/Account/AccessDenied");else assert.equal(response.status(),status);}
assert.equal((await auth.request.post(base+'/Writing/Context/EditCharacter',{form:{BookID:s.book,SceneID:s.scene,CharacterID:s.characters[0],Field:'description',Value:'Must never persist'}})).status(),400);
assert.equal((await auth.request.post(base+'/Writing/Context/EditRelationship',{form:{BookID:s.book,SceneID:s.scene,Notes:'Must never persist'}})).status(),400);
console.log('PASS Development HTTP security: unauthenticated form denied; foreign book/scene/character/relationship IDs denied; missing field rejected; both mutation endpoints enforce antiforgery. No changes persisted.');}finally{await b.close();}})().catch(e=>{console.error(e.message);process.exitCode=1;});

View File

@ -0,0 +1,32 @@
// Real SignalR transport. Isolated loopback data by default; opt-in real Development uses disposable identity/scope.
const {chromium}=require('playwright'),fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict');
const live=!!process.env.PD_CONTEXT_IDENTITY,base=live?'https://dev.plotdirector.com':(process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238');
(async()=>{const browser=await chromium.launch();let step='setup';try{
const scope=live?JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_SCOPE)):{project:7,book:12,chapter:10,scene:22};
const who=live?JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY)):null;
if(live){assert.equal(who.Database,'PlotDirector_Development');assert.equal(who.UserID,scope.user);assert(who.Email.startsWith('pwa-browser-'));}
const contexts=[];const pages=[];const counts=[];
for(let i=0;i<2;i++){
const context=await browser.newContext({viewport:{width:1366,height:768}});contexts.push(context);
if(!live){await context.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));await context.route('**/native-companion/status',r=>r.fulfill({json:[]}));await context.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false,state:'Disconnected'}}));await context.route('**/Writing/Context/Position?*',r=>r.fulfill({json:{connected:false,position:null}}));await context.route('**/Writing/Context/Tabs/*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-tab-fixture/'+u.pathname.split('/').at(-1)+u.search})});});}
const page=await context.newPage();pages.push(page);const count={hub:0,word:0,reads:0};counts.push(count);page.on('request',r=>{if(r.url().includes('/hubs/')&&r.url().includes('/negotiate'))count.hub++;if(r.url().includes('/Writing/Context/Navigate')||r.url().includes('/WriterWord/Navigate'))count.word++;if(r.url().includes('/Writing/Context/Tabs/'))count.reads++;});
if(live){await page.goto(base+'/Account/Login');await page.locator('[name=Email]').fill(who.Email);await page.locator('[name=Password]').fill(who.Password);await Promise.all([page.waitForURL(u=>u.pathname!=='/Account/Login'),page.locator('button[type=submit]').click()]);}
count.hub=0;count.word=0;count.reads=0;
await page.goto(`${base}/Writing/Context?projectId=${scope.project}&bookId=${scope.book}&sceneId=${scope.scene}`);await page.waitForSelector('[data-context-tab-fragment]');await page.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection?.state==='Connected');
}
const [source,destination]=pages;
step='two independently authenticated browser sessions';await source.waitForFunction(book=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',book).then(w=>w.length===2&&w.every(x=>x.panes[0].available)),scope.book);
const target=await destination.evaluate(()=>({windowID:document.querySelector('[data-context-workspace]').contextController.windowId,connection:document.querySelector('[data-context-workspace]').contextController.connection.connectionId}));
const command={version:1,bookID:scope.book,originPaneID:'0',action:'scene.focus',storyPoint:{chapterID:scope.chapter,sceneID:scope.scene},targetWindowID:target.windowID,targetSessionID:target.connection,targetPaneID:'0'};
await source.evaluate(()=>{window.receipts=[];document.querySelector('[data-context-workspace]').contextController.connection.on('ContextInteractionResult',r=>receipts.push(r));});
const before=counts.map(x=>x.reads),position=await source.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position);
step='targeted command and authoritative recipient read';const result=await source.evaluate(c=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('SendContextInteraction',c),command);assert.equal(result.status,'delivered');await destination.waitForSelector('.context-reference-focus');await source.waitForFunction(()=>receipts.some(r=>r.status==='focused'));
assert.equal(counts[0].reads,before[0]);assert.equal(counts[1].reads,before[1]+1);assert.equal(await source.locator('.context-reference-focus').count(),0);assert.deepEqual(await source.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position),position);assert(counts.every(x=>x.word===0&&x.hub===1));
step='no-handler does not replace a tool';await destination.selectOption('[data-context-pane="0"] [data-context-tab]','characters');await destination.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',Number(document.querySelector('[data-context-workspace]').dataset.scopeBookId)).then(rows=>rows.find(r=>r.windowID===document.querySelector('[data-context-workspace]').contextController.windowId)?.panes[0].toolID==='characters'));
const absent=await source.evaluate(c=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('SendContextInteraction',c),command);assert.equal(absent.status,'no-handler');assert.equal(await destination.locator('[data-context-tab]').first().inputValue(),'characters');
step='character handler focuses only intended recipient';await destination.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.announcement.panes[0].available);await destination.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('RegisterContextWindow',document.querySelector('[data-context-workspace]').contextController.announcement));const charBefore=counts.map(x=>x.reads);const characterCommand={...command,action:'character.focus',characterID:live?scope.characters?.[0]:5};if(characterCommand.characterID){const focused=await source.evaluate(c=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('SendContextInteraction',c),characterCommand);assert.equal(focused.status,'delivered');await destination.waitForSelector(`[data-context-character="${characterCommand.characterID}"].context-reference-focus`);await source.waitForFunction(id=>receipts.some(r=>r.commandID===id&&r.status==='focused'),focused.commandID);assert.equal(counts[0].reads,charBefore[0]);assert.equal(counts[1].reads,charBefore[1]+1);assert.deepEqual(await destination.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position),position);}
step='cross-user and cross-book rejection';for(const change of [{targetUserID:999},{bookID:2147483647},{storyPoint:{chapterID:scope.chapter,sceneID:2147483647}}])assert(await source.evaluate(async c=>{try{await document.querySelector('[data-context-workspace]').contextController.connection.invoke('SendContextInteraction',c);return false}catch{return true}},{...command,...change}));
step='disconnect and reconnect registration';await destination.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.connection.stop());await source.waitForFunction(book=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',book).then(w=>w.length===1),scope.book);await destination.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await source.waitForFunction(book=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',book).then(w=>w.length===2),scope.book);
assert.equal(await destination.locator('[data-context-tab]').first().inputValue(),'characters');assert.equal(counts[1].word,0);
for(const context of contexts)await context.close();console.log('PASS My Windows real SignalR: two independent sessions, exact recipient and pane read, no unrelated mutation/Word navigation, no-handler, cross-user/book/story-point rejection and reconnect capability recovery'+(live?' on Development':' in isolated host'));
} catch(error){console.error('FAILED '+step+': '+error.message);process.exitCode=1;}finally{await browser.close();}})();

View File

@ -0,0 +1,12 @@
// Actual shared Names Library query parity, read-only on an explicitly disposable Development project.
const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict');
(async()=>{assert(process.env.PD_CONTEXT_IDENTITY&&process.env.PD_CONTEXT_SCOPE);const who=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY)),s=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_SCOPE));assert.equal(who.Database,'PlotDirector_Development');assert.equal(who.UserID,s.user);assert(who.Email.startsWith('pwa-browser-'));assert(s.libraryTestName&&s.unusedBook);const b=await chromium.launch();let step='login';try{const c=await b.newContext({viewport:{width:1280,height:900}}),main=await c.newPage();await main.goto('https://dev.plotdirector.com/Account/Login');await main.locator('[name=Email]').fill(who.Email);await main.locator('[name=Password]').fill(who.Password);await Promise.all([main.waitForURL(u=>u.pathname!='/Account/Login'),main.locator('button[type=submit]').click()]);const names=await c.newPage();
await main.goto(`https://dev.plotdirector.com/Names?ProjectID=${s.project}&BookID=${s.book}&Search=${encodeURIComponent(s.libraryTestName)}&UsedScope=Book`);const locales=await main.locator('[name=LocaleCode] option').evaluateAll(ns=>ns.filter(n=>n.value).map(n=>({code:n.value,label:n.textContent.trim()})));assert(locales.length>=2);let testLocale=s.libraryLocale;if(!testLocale){const row=main.locator('tbody tr').first(),label=(await row.locator('td').nth(1).locator('.muted').innerText()).split(' · usage')[0].trim();testLocale=locales.find(l=>l.label===label)?.code||locales[0].code;}
const common={ProjectID:String(s.project),BookID:String(s.book),UsedScope:'Book',LocaleCode:testLocale,BirthYear:s.libraryBirthYear||'',Page:'1',PageSize:'25'};
const cases=[{}, {Search:'zzxy-uncommon-qualification'}, {Search:s.libraryTestName,UsedOnly:'true'}, {Search:s.libraryTestName,BookID:String(s.unusedBook),UsedOnly:'false'}, {Search:s.libraryTestName,UsedScope:'Project',BookID:''}, {Search:'Jo',GenderPreference:'Female',GenderThreshold:'0.7',NameType:'Variant',MinimumUsage:'0.01'}, {LocaleCode:locales[0].code,Page:'2'}, {LocaleCode:locales[1].code,UsedOnly:'false'}, {Search:s.libraryTestName.slice(0,-1)}, {Search:s.libraryTestName,UsedScope:'Library',BookID:''}];let records=[];
for(let i=0;i<cases.length;i++){step='equivalent criteria '+i;const f={...common,...cases[i]},q=new URLSearchParams(f);await main.goto('https://dev.plotdirector.com/Names?'+q);const expected=await main.locator('[data-name-library-id]').evaluateAll(rows=>rows.map(r=>({id:Number(r.dataset.nameLibraryId),used:Number(r.dataset.nameUsedCount)})));await names.goto('https://dev.plotdirector.com/Writing/Context/Names/Search?contextBookId='+s.book+'&'+q);const actual=await names.locator('[data-context-name-id]').evaluateAll(rows=>rows.map(r=>({id:Number(r.dataset.contextNameId),used:Number(r.dataset.usedCount)})));assert.deepEqual(actual,expected);assert(actual.length<=25);records.push(actual);}
assert(records[0].length>0&&records[6].length>0,'default and pagination searches must exercise actual candidates');
assert(records[2].some(r=>r.used>0),'recorded alias must be used in its character appearance book');assert(records[3].every(r=>r.used===0)&&records[3].length>0,'same alias must be unused in empty second book');assert(records[4].some(r=>r.used>0),'project usage remains recorded');
step='exact canonical/alias usage query';const response=await c.request.get('https://dev.plotdirector.com/Writing/Context/Names/Usage?'+new URLSearchParams({contextBookId:s.book,search:s.libraryTestName,usedScope:'Project'}));assert(response.ok());assert((await response.text()).includes('data-name-identity="'+s.characters[0]+'"'));
console.log('PASS Development Names parity: ten equivalent main/Context searches match exact candidate IDs and usage counts; empty/uncommon/near search, aliases, used/unused, book/project scope, gender/type/commonness, multiple locales and pagination; current-book alias used, empty other-book unused; bounded 25 rows.');
}catch(e){console.error('FAILED '+step+': '+e.message);process.exitCode=1;}finally{await b.close();}})();

View File

@ -0,0 +1,8 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
(async()=>{const b=await chromium.launch();let step='setup';try{const c=await b.newContext({viewport:{width:1366,height:900},permissions:['clipboard-read','clipboard-write']});await c.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));for(const url of ['**/native-companion/status','**/native-companion/connection-state','**/Writing/Context/Position?*'])await c.route(url,r=>r.fulfill({json:url.endsWith('status')?[]:{connected:false,known:false}}));let queries=[];await c.route('**/Writing/Context/Tabs/*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-tab-fixture/'+u.pathname.split('/').at(-1)+u.search})});});await c.route('**/Writing/Context/Names/*',async r=>{const u=new URL(r.request().url()),part=u.pathname.split('/').at(-1).toLowerCase();if(part==='search')queries.push(u.searchParams);await r.fulfill({response:await r.fetch({url:base+'/context-names-fixture/'+part+u.search})});});await c.route('**/Writing/Context/EditCharacter?*',async r=>r.fulfill({response:await r.fetch({url:base+'/context-edit-fixture?field=name'})}));const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.goto(base+'/Writing/Context');await p.selectOption('[data-context-tab]','names');await p.waitForSelector('[data-context-name-id]');
step='discovery default and complete criteria';assert.equal(await p.locator('[data-context-name-id]').count(),25);assert.equal(await p.locator('[data-name-row]').count(),0);await p.locator('[name=Search]').fill('Uncommon');await p.selectOption('[name=LocaleCode]','fr-FR');await p.selectOption('[name=UsedOnly]','false');await p.click('[data-name-filters] summary');await p.locator('[name=BirthYear]').fill('1850');await p.selectOption('[data-name-gender]','Male:0.9');await p.selectOption('[name=NameType]','Variant');await p.selectOption('[name=MinimumUsage]','0.05');await p.selectOption('[name=UsedScope]','Book');await p.selectOption('[name=BookID]','13');await p.selectOption('[name=PageSize]','100');await p.locator('[data-context-name-search] [type=submit]').click();await p.waitForFunction(()=>document.querySelectorAll('[data-context-name-id]').length===100);for(const [key,value]of Object.entries({Search:'Uncommon',LocaleCode:'fr-FR',BirthYear:'1850',GenderPreference:'Male',GenderThreshold:'0.9',NameType:'Variant',MinimumUsage:'0.05',UsedScope:'Book',BookID:'13',UsedOnly:'false',Page:'1',PageSize:'100'}))assert.equal(queries.at(-1).get(key),value,key);
step='profile, copy, related forms and selected usage';const first=p.locator('[data-context-name-id]').first();await first.locator('[data-name-copy]').click();assert.equal(await p.evaluate(()=>navigator.clipboard.readText()),'Uncommon 1');await first.locator('summary').click();assert.match(await first.innerText(),/Known spelling variant/);await first.locator('[data-name-usage]').click();await first.locator('[data-name-usage-fragment]').waitFor();await first.locator('[data-name-identity]').click();await p.waitForSelector('[data-name-identity-fragment]');assert.match(await p.locator('[data-name-identity-fragment]').innerText(),/Known variant/);await p.locator('[data-context-edit="name"]').click();await p.waitForSelector('[data-context-edit-form]');await p.click('[data-context-edit-cancel]');
step='pagination preserves all criteria';await p.click('[data-name-page="2"]');await p.waitForSelector('[data-name-results-fragment][data-page="2"]');assert.equal(queries.at(-1).get('GenderThreshold'),'0.9');assert.equal(await p.locator('[data-context-name-id]').first().getAttribute('data-context-name-id'),'101');
step='independent same-tool panes and book scope';await p.selectOption('[data-context-layout]','columns');await p.selectOption('[data-context-pane="1"] [data-context-tab]','names');await p.locator('[data-context-pane="1"] [name=Search]').fill('Other lookup');assert.equal(await p.locator('[data-context-pane="0"] [name=Search]').inputValue(),'Uncommon');const before=queries.length;await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:11,sceneId:23}));await p.waitForTimeout(150);assert.equal(queries.length,before);
step='actual pane widths and substantial result set';for(const width of [1366,760,390]){await p.setViewportSize({width,height:900});for(const layout of ['single','columns','rows']){await p.selectOption('[data-context-layout]',layout);await p.waitForTimeout(60);assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),width+'/'+layout);}}assert.deepEqual(errors,[]);console.log('PASS Names discovery browser: all library criteria, 100 bounded candidates, profiles/related forms/copy, on-demand usage/identity/correction, pagination, book scope, independent panes and desktop/half/stacked/mobile widths (query parity qualified separately against Development).');
}catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await b.close();}})();

View File

@ -0,0 +1,7 @@
// Explicit Development-only read/navigation acceptance on disposable scope; no Word commands or edits.
const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict');
(async()=>{assert(process.env.PD_CONTEXT_IDENTITY&&process.env.PD_CONTEXT_SCOPE);const who=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY)),s=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_SCOPE));assert.equal(who.Database,'PlotDirector_Development');assert.equal(who.UserID,s.user);assert(who.Email.startsWith('pwa-browser-'));const b=await chromium.launch();let step='login';try{const c=await b.newContext({viewport:{width:1366,height:900}}),main=await c.newPage();await main.goto('https://dev.plotdirector.com/Account/Login');await main.locator('[name=Email]').fill(who.Email);await main.locator('[name=Password]').fill(who.Password);await Promise.all([main.waitForURL(u=>u.pathname!='/Account/Login'),main.locator('button[type=submit]').click()]);await main.goto('https://dev.plotdirector.com/Projects/Details/'+s.project);let word=0;c.on('request',r=>{if(/\/(Writing\/Context|WriterWord)\/Navigate/.test(new URL(r.url()).pathname))word++;});const p=await c.newPage();await p.goto(`https://dev.plotdirector.com/Writing/Context?projectId=${s.project}&bookId=${s.book}&sceneId=${s.scene}`);await p.waitForSelector('[data-context-tab-fragment]');await p.waitForFunction(book=>document.querySelector('[data-context-workspace]').contextController.connection?.state==='Connected'&&document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',book).then(rows=>rows.some(r=>r.kind==='main'&&r.environmentID===window.PlotDirectorContextEnvironment)),s.book);
const count=c.pages().length;step='scene editor in existing main';await p.click('[data-context-editor]');await main.waitForURL(u=>u.pathname==='/Scenes/Edit/'+s.scene);assert.equal(c.pages().length,count);
for(const [tool,button,path] of [['characters',`[data-context-workspace-target="characters"][data-context-entity="${s.characters[0]}"]`,'/Characters/Details/'+s.characters[0]],['names','[data-context-workspace-target="names"]','/Names'],['relationships','[data-context-workspace-target="relationships"]','/RelationshipMap']]){step=tool+' existing-main reuse';await p.selectOption('[data-context-tab]',tool);await p.waitForSelector('[data-context-tab-fragment]');if(tool==='characters'){const row=p.locator(`[data-context-character="${s.characters[0]}"]`);if(!await row.evaluate(n=>n.open))await row.locator('summary').click();}await p.waitForTimeout(600);for(const toast of await p.locator('.pd-toast button[aria-label^="Dismiss"]').all())await toast.click();await p.locator(button).last().click();await main.waitForURL(u=>u.pathname===path);assert.equal(c.pages().length,count);}
assert.equal(word,0);assert.equal(await p.locator('[data-context-scene]').inputValue(),String(s.scene));console.log('PASS Development main-window navigation: actual scene, character, Names and Relationships editors reused one existing main window; Context scene and Word position unchanged. Browser focus remains discretionary.');
} catch(e){console.error('FAILED '+step+': '+e.message);process.exitCode=1;}finally{await b.close();}})();

View File

@ -0,0 +1,13 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
(async()=>{const b=await chromium.launch();let step='setup';try{const c=await b.newContext({viewport:{width:1280,height:900}});await c.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));for(const url of ['**/native-companion/status','**/native-companion/connection-state','**/Writing/Context/Position?*'])await c.route(url,r=>r.fulfill({json:url.endsWith('status')?[]:{known:false,connected:false}}));await c.route('**/Writing/Context/Tabs/*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-tab-fixture/'+u.pathname.split('/').at(-1)+u.search})});});
await c.route('**/Writing/Context/EditCharacter?*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-edit-fixture?field='+u.searchParams.get('field')})});});await c.route('**/Writing/Context/EditRelationship?*',async r=>r.fulfill({response:await r.fetch({url:base+'/context-relationship-edit-fixture'})}));
await c.route('**/Writing/Context/Relationships/Graph?*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-lenses-fixture'+u.search})});});for(const [route,fixture] of [['FamilyIndex','index'],['FamilyTree','tree']])await c.route('**/Writing/Context/Relationships/'+route+'?*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-family-'+fixture+'-fixture'+u.search})});});const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.goto(base+'/Writing/Context');await p.selectOption('[data-context-tab]','characters');await p.waitForSelector('[data-character-explorer]');
step='all shared modal forms fill content';for(const width of [1280,390]){await p.setViewportSize({width,height:900});for(const field of ['life-status','classification','description','emotion','condition','location','name','alias-add','alias:11']){await p.evaluate(field=>{const host=document.querySelector('[data-character-explorer]'),button=document.createElement('button');button.dataset.contextEdit=field;button.dataset.characterId='5';host.append(button);button.click();button.remove();},field);await p.waitForSelector('[data-context-edit-form]');assert.equal(await p.locator('[data-context-edit-dialog] button:visible').count(),2);assert(await p.locator('[data-context-edit-form]').evaluate(f=>[...f.querySelectorAll('textarea,select,input:not([type=hidden]):not([type=checkbox])')].every(n=>n.getBoundingClientRect().width>=f.clientWidth*.92&&n.scrollWidth<=n.clientWidth+2)));await p.keyboard.press('Escape');await p.waitForFunction(()=>!document.querySelector('[data-context-edit-dialog]').open);}}
step='relationship modal shares full-width layout';await p.selectOption('[data-context-tab]','relationships');await p.waitForSelector('[data-context-relationships]');await p.locator('[data-graph-node="5"]').click();await p.locator('[data-relationship-details] details summary').click();await p.locator('[data-inspect-connection="10"]').click();await p.locator('[data-relationship-details] [data-context-relationship-edit]').click();await p.waitForSelector('[data-context-edit-form]');assert(await p.locator('[data-context-edit-form]').evaluate(f=>[...f.querySelectorAll('textarea,select,input:not([type=hidden]):not([type=checkbox])')].every(n=>n.getBoundingClientRect().width>=f.clientWidth*.92)));assert.equal(await p.locator('[data-context-edit-dialog] button:visible').count(),2);await p.keyboard.press('Escape');await p.selectOption('[data-context-tab]','characters');await p.waitForSelector('[data-character-explorer]');
step='main shell registers on existing native connection';const main=await c.newPage();let hubs=0;main.on('request',r=>{if(r.url().includes('/hubs/native-companion/negotiate'))hubs++;});await main.goto(base+'/fixture?layout=full');await p.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',12).then(rows=>rows.some(r=>r.kind==='main')));assert.equal(hubs,1);
step='scene editor reuses main window with no popup';const originalPages=c.pages().length;await p.click('[data-context-editor]');await main.waitForURL(/\/Scenes\/Edit\/22/);assert.equal(c.pages().length,originalPages);assert.equal(await p.locator('[data-context-tab]').first().inputValue(),'characters');
step='repeat navigation retains one main window';await p.waitForTimeout(550);await main.waitForFunction(()=>window.PlotDirectorPresenceConnection?.state==='Connected');await p.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',12).then(rows=>rows.some(r=>r.kind==='main')));await p.click('[data-context-editor]');await p.waitForTimeout(700);assert.equal(c.pages().length,originalPages);
step='unsaved main form can decline navigation';await main.waitForTimeout(500);const beforeDirty=main.url();await main.evaluate(()=>{const f=document.createElement('form');f.method='post';f.innerHTML='<input name="SyntheticDraft">';document.body.append(f);});await main.locator('[name=SyntheticDraft]').fill('Unsaved draft');main.once('dialog',d=>d.dismiss());await p.waitForTimeout(550);await p.locator('a[href="/Characters?projectId=7"]').click();await p.waitForTimeout(700);assert.equal(main.url(),beforeDirty);assert.equal(c.pages().length,originalPages);
step='missing main opens only one named fallback';await main.close();const popupPromise=p.waitForEvent('popup');await p.waitForTimeout(550);await p.locator('a[href="/Characters?projectId=7"]').click();const popup=await popupPromise;await popup.waitForURL(/Characters\?projectId=7/);await popup.waitForFunction(()=>window.PlotDirectorPresenceConnection?.state==='Connected',{},{timeout:7000}).catch(async e=>{const info=await popup.evaluate(()=>({user:document.body.dataset.pdUserId,books:document.body.dataset.pdBookIds,env:window.PlotDirectorContextEnvironment,state:window.PlotDirectorPresenceConnection?.state,ready:document.readyState,title:document.title}));throw Error(e.message+JSON.stringify(info));});await p.waitForTimeout(550);await p.locator('a[href="/Characters?projectId=7"]').click();await p.waitForTimeout(600);assert.equal(c.pages().length,originalPages);
assert.deepEqual(errors,[]);console.log('PASS shared Context refinement: all nine character/name modal variants full-width at desktop/mobile, one Save/Cancel, Escape; real registry/main shell reuses native connection and existing main window, repeated navigation creates no popup.');
} catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await b.close();}})();

View File

@ -0,0 +1,8 @@
const vm=require('node:vm'),fs=require('node:fs'),assert=require('node:assert/strict');const sandbox={window:{}};vm.runInNewContext(fs.readFileSync('PlotLine/wwwroot/js/context-relationship-layout.js','utf8'),sandbox);const L=sandbox.window.PlotDirectorContextRelationshipLayout;
const nodes=Array.from({length:16},(_,i)=>({id:i+1,name:'A deliberately long canonical relative name '+(i+1),birthDate:i===6?'2000-01-01':i===7?'2002-01-01':null,archived:i===5}));let id=0;const link=(a,b,type,reciprocal=false)=>({id:++id,a,b,type,reciprocal,category:'Family'});const links=[link(1,2,'Spouse',true),link(1,3,'Parent'),link(2,3,'Parent'),link(3,4,'Spouse',true),link(3,5,'Parent'),link(4,5,'Parent'),link(5,6,'Spouse',true),link(5,10,'Spouse',true),link(5,7,'Biological Parent'),link(6,7,'Biological Parent'),link(5,8,'Parent'),link(6,8,'Parent'),link(5,9,'Parent'),link(10,9,'Parent'),link(7,8,'Sibling',true),link(7,9,'Half-sibling',true),link(11,7,'Adoptive Parent'),link(12,7,'Step Parent'),link(13,14,'Child'),link(12,9,'Guardian'),link(15,16,'Parent',true)];
function noOverlap(layout,people){for(let i=0;i<people.length;i++)for(let j=i+1;j<people.length;j++){const a=layout.positions[people[i].id],b=layout.positions[people[j].id];assert(Math.abs(a.x-b.x)>=layout.nodeWidth||Math.abs(a.y-b.y)>=layout.nodeHeight,`nodes overlap ${people[i].id}/${people[j].id}`);}}
const f=L.family(nodes,links);assert.equal(Object.keys(f.positions).length,nodes.length);for(const l of links){const r=L.role(l);if(r.kind==='parent')assert(f.positions[r.from].y<f.positions[r.to].y,'ancestor above descendant');}for(const l of links.filter(l=>l.type==='Spouse'))assert.equal(f.positions[l.a].y,f.positions[l.b].y);assert.equal(f.positions[7].y-f.positions[11].y,145,'adoptive parent is aligned one generation above child');assert.equal(f.positions[7].y-f.positions[12].y,145,'step parent generation');assert(f.positions[7].x<f.positions[8].x,'recorded sibling birth order');assert(f.warnings.some(w=>w.includes('reciprocal')));noOverlap(f,nodes);assert.equal(L.signature(nodes,links),L.signature(nodes,links.map(l=>({...l,state:'Changed note',notes:'New note'}))));
const cycleNodes=[{id:1,name:'One'},{id:2,name:'Two'}],cycle=L.family(cycleNodes,[link(1,2,'Parent'),link(2,1,'Parent')]);assert(cycle.warnings.some(w=>w.includes('cycle')));noOverlap(cycle,cycleNodes);
const crossing=L.family(nodes,[...links,link(1,7,'Spouse')]);assert(crossing.positions[1].y<crossing.positions[7].y,'cross-generation partnership never flattens ancestry');
const big=Array.from({length:120},(_,i)=>({id:i+1,name:'Long canonical person '+i,birthDate:i%3?'1900-01-01':null,physical:i<12})),tree=[];for(let i=2;i<=120;i++)tree.push(link(Math.floor(i/2),i,'Parent'));const start=performance.now();const b=L.family(big,tree);noOverlap(b,big);assert.equal(Object.keys(b.positions).length,120);assert(performance.now()-start<1000,'bounded family layout performance');const dense=[];for(let i=1;i<24;i++)for(let j=i+1;j<=24;j++)dense.push(link(i,j,'Friend'));const story=L.story(big,dense,1);noOverlap(story,big);assert.equal(story.routes.length,dense.length);for(let count=1;count<=128;count++){const people=Array.from({length:count},(_,i)=>({id:i+1,name:'Person '+i,physical:i<12}));noOverlap(L.story(people,[],1),people);}
console.log('PASS family/network layout: four generations, multiple partners, half-siblings, adoptive/step/explicit Child reversal, archived identity retained, unknown relatives not invented, birth order, ambiguous/cyclic/cross-generation records, 120 nonoverlapping nodes and dense edges; stable signature ignores state-only changes.');

View File

@ -0,0 +1,11 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
(async()=>{const b=await chromium.launch();let step='setup';try{const c=await b.newContext({viewport:{width:1366,height:900}});await c.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));for(const url of ['**/native-companion/status','**/native-companion/connection-state','**/Writing/Context/Position?*'])await c.route(url,r=>r.fulfill({json:url.endsWith('status')?[]:{known:false,connected:false}}));await c.route('**/Writing/Context/Tabs/*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-tab-fixture/'+u.pathname.split('/').at(-1)+u.search})});});let graphReads=0,large=false,readOnly=false,editQuery;await c.route('**/Writing/Context/Relationships/Graph?*',async r=>{graphReads++;const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-lenses-fixture'+u.search+'&large='+large+'&readonly='+readOnly})});});await c.route('**/Writing/Context/Relationships/Lookup?*',async r=>r.fulfill({response:await r.fetch({url:base+'/context-lenses-lookup-fixture'})}));await c.route('**/Writing/Context/EditRelationship?*',async r=>{editQuery=new URL(r.request().url()).searchParams;await r.fulfill({response:await r.fetch({url:base+'/context-relationship-edit-fixture'})});});for(const [route,fixture] of [['FamilyIndex','index'],['FamilyTree','tree']])await c.route('**/Writing/Context/Relationships/'+route+'?*',async r=>{const u=new URL(r.request().url());graphReads++;await r.fulfill({response:await r.fetch({url:base+'/context-family-'+fixture+'-fixture'+u.search+'&large='+large+'&readonly='+readOnly})});});const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.goto(base+'/Writing/Context');await p.selectOption('[data-context-tab]','relationships');await p.waitForSelector('[data-graph-node="5"]');
async function selectEdge(id){await p.locator('[data-context-pane="0"] [data-relationship-svg]').scrollIntoViewIfNeeded();const hit=p.locator(`[data-context-pane="0"] [data-graph-connection="${id}"]`);const pt=await hit.evaluate(n=>{const p=n.getPointAtLength(n.getTotalLength()*.35),m=n.getScreenCTM();return {x:m.a*p.x+m.c*p.y+m.e,y:m.b*p.x+m.d*p.y+m.f};});await p.mouse.click(pt.x,pt.y);await p.locator(`[data-context-pane="0"] [data-graph-edge="${id}"].is-selected`).waitFor({state:'attached'});}
step='genealogical view and specific connection edit';assert.equal(await p.locator('[data-relationship-lens="family"]').getAttribute('aria-pressed'),'true');assert.equal(await p.locator('[data-graph-node]').count(),9);assert.match(await p.locator('[data-graph-node="6"]').getAttribute('aria-label'),/deceased; author reference/);assert.equal(await p.locator('[data-relationship-details] [data-context-edit="life-status"]').count(),1);assert.match(await p.locator('[data-relationship-caption]').innerText(),/Author-established/);await p.locator('[data-graph-node="5"]').click();await p.locator('[data-relationship-details] details summary').click();await p.locator('[data-inspect-connection="10"]').click();await p.waitForFunction(()=>document.querySelector('[data-relationship-details]').textContent.includes('Biological Parent'));await p.locator('[data-relationship-details] [data-context-relationship-edit]').click();await p.waitForSelector('[data-context-edit-form]');assert.equal(editQuery.get('referenceLens'),'family');assert.equal(editQuery.get('mode'),'initial');await p.click('[data-context-edit-cancel]');
step='pan zoom and unchanged-family notification stability';await p.click('[data-graph-zoom="in"]');await p.locator('[data-relationship-svg]').focus();await p.keyboard.press('ArrowRight');const transform=await p.locator('[data-relationship-viewport]').getAttribute('transform');await p.evaluate(()=>{window.familyLayouts=0;const original=window.PlotDirectorContextRelationshipLayout.family;window.PlotDirectorContextRelationshipLayout.family=(...a)=>{familyLayouts++;return original(...a);};});const before=graphReads;await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({bookId:12}));await p.waitForFunction(()=>document.querySelector('[data-graph-node="5"]'));await p.waitForTimeout(200);assert(graphReads>before);assert.equal(await p.evaluate(()=>familyLayouts),0);assert.equal(await p.locator('[data-relationship-viewport]').getAttribute('transform'),transform);
step='Story network and recorded point';await p.click('[data-relationship-lens="story"]');await p.waitForFunction(()=>document.querySelector('[data-relationship-caption]').textContent.includes('Later developments are excluded'));assert(await p.locator('[data-graph-edge]').count()>30);assert.equal(await p.locator('[data-graph-node] rect.is-physical').count(),2);assert.equal(await p.locator('[data-relationship-details] [data-context-edit="life-status"]').count(),0);assert.doesNotMatch(await p.locator('[data-graph-node="6"]').getAttribute('aria-label'),/deceased/);await selectEdge(1);await p.waitForFunction(()=>document.querySelector('[data-relationship-details]').textContent.includes('Rival'));assert.match(await p.locator('[data-relationship-details]').innerText(),/does not prove a first meeting/);await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:11,sceneId:23}));await p.waitForFunction(()=>document.querySelector('[data-relationship-details]')?.textContent.includes('Later established'));await p.click('[data-relationship-lens="family"]');await p.waitForFunction(()=>document.querySelector('[data-relationship-caption]').textContent.includes('Author-established'));assert.equal(await p.locator('[data-family-key="21"]').getAttribute('aria-pressed'),'true');
step='lookup and recenter';await p.locator('[data-relationship-person]').fill('relative 7');await p.locator('[data-relationship-matches] button').waitFor();await p.locator('[data-relationship-matches] button').click();await p.waitForFunction(()=>document.querySelector('[data-relationship-details]').textContent.includes('Recorded person 7'));
step='large family and independent panes';large=true;await p.locator('[data-relationship-svg]').focus();await p.keyboard.press('ArrowRight');await p.keyboard.press('ArrowRight');await p.locator('[data-family-branch="5"]').click();await p.waitForSelector('[data-graph-node="3"]');await p.selectOption('[data-context-layout]','columns');await p.selectOption('[data-context-pane="1"] [data-context-tab]','relationships');await p.locator('[data-context-pane="1"] [data-graph-node="22"]').waitFor();await p.locator('[data-context-pane="1"] [data-relationship-lens="story"]').click();await p.waitForTimeout(120);assert.equal(await p.locator('[data-context-pane="0"] [data-relationship-lens="family"]').getAttribute('aria-pressed'),'true');
step='container widths and keyboard navigation';for(const width of [1366,760,390]){await p.setViewportSize({width,height:900});for(const layout of ['single','columns','rows']){await p.selectOption('[data-context-layout]',layout);await p.waitForTimeout(50);assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),width+'/'+layout);}}await p.selectOption('[data-context-layout]','single');await p.locator('[data-context-pane="0"] [data-relationship-svg]').focus();await p.keyboard.press('Home');await p.keyboard.press('+');
step='read-only graph removes edit controls';readOnly=true;await p.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({bookId:12}));await p.waitForTimeout(350);assert.equal(await p.locator('[data-context-pane="0"] [data-relationship-add]:visible').count(),0);assert.deepEqual(errors,[]);console.log('PASS visual Relationships browser: Family and Story lenses, real SVG hit selection/edit, pan/zoom/keyboard, stable family layout through notifications, scene changes, lookup/recentre, compact family branches, dense Story network, independent panes, full/half/stacked/mobile and read-only controls.');
}catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await b.close();}})();

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,37 @@
// Opt-in Development smoke. Only edits a specifically named disposable synthetic scene.
const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict');
(async()=>{
const identity=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY));
const scope=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_SCOPE));
assert.equal(identity.Database,'PlotDirector_Development');assert.equal(identity.UserID,scope.user);
assert(identity.Email.startsWith('pwa-browser-')&&identity.Email.endsWith('@example.invalid'));
const base='https://dev.plotdirector.com',browser=await chromium.launch();let step='login',restore;
try {
const context=await browser.newContext({viewport:{width:1366,height:768}}),page=await context.newPage();
await page.goto(base+'/Account/Login');await page.locator('[name=Email]').fill(identity.Email);await page.locator('[name=Password]').fill(identity.Password);
await Promise.all([page.waitForURL(u=>u.pathname!=='/Account/Login'),page.locator('button[type=submit]').click()]);
step='ownership and synthetic identity';await page.goto(base+'/Projects/Details/'+scope.project);assert(await page.getByText('Context foundation disposable qualification',{exact:true}).count());
const url=`${base}/Writing/Context?projectId=${scope.project}&bookId=${scope.book}&sceneId=${scope.scene}`;
let connections=0,reads=0;const errors=[];page.on('pageerror',e=>errors.push(e.message));page.on('request',r=>{if(r.url().includes('/hubs/')&&r.url().includes('/negotiate'))connections++;if(r.url().includes('/Writing/Context/Tabs/overview'))reads++;});
step='real authorized Overview';await page.goto(url);await page.locator('[data-context-pane="0"] [data-context-tab-fragment]').waitFor();
const title=await page.locator('[data-context-pane="0"] [data-context-tab-fragment]>h2').innerText();assert.equal(title,'Synthetic foundation scene');
await page.waitForTimeout(500);assert.equal(connections,1,'one real browser SignalR connection');
step='Characters and split';await page.selectOption('[data-context-layout]','columns');await page.locator('[data-context-pane="1"] [data-context-tab-fragment]').waitFor();assert.match(await page.locator('[data-context-pane="1"]').innerText(),/No characters recorded/);
await page.selectOption('[data-context-pane="1"] [data-context-tab]','overview');await page.waitForFunction(()=>document.querySelectorAll('[data-context-tab-fragment]>h2').length===2);
step='independent window';const opened=page.waitForEvent('popup');await page.click('[data-context-new]');const popup=await opened;await popup.waitForSelector('[data-context-tab-fragment]');assert.equal(await popup.locator('[data-context-layout]').inputValue(),'single');
const editor=await context.newPage();await editor.goto(base+`/Scenes/Edit/${scope.scene}`);await editor.click('[data-scene-editor="scene-details"]');const form=editor.locator('[data-scene-editor-form]').filter({has:editor.locator('[name="SceneTitle"]')});await form.waitFor();
const saved=await form.evaluate(n=>({action:n.action,fields:Object.fromEntries([...new FormData(n)].filter(([,v])=>typeof v==='string'))}));assert.equal(saved.fields.SceneTitle,title);restore=async()=>{const response=await page.request.post(saved.action,{form:saved.fields});assert(response.ok(),'synthetic title restore failed');};
await page.waitForTimeout(300);const before=reads;
step='real cross-window invalidation';const response=await editor.request.post(saved.action,{form:{...saved.fields,SceneTitle:title+' updated through editor'}});assert(response.ok());
await page.waitForFunction(()=>[...document.querySelectorAll('[data-context-tab-fragment]>h2')].every(n=>n.textContent.includes('updated through editor')));
await popup.waitForFunction(()=>document.querySelector('[data-context-tab-fragment]>h2').textContent.includes('updated through editor'));
assert.equal(reads-before,1,'same tab in two panes shares one real refresh request');await restore();restore=null;await page.waitForFunction(()=>[...document.querySelectorAll('[data-context-tab-fragment]>h2')].every(n=>n.textContent==='Synthetic foundation scene'));
step='persistence';await page.selectOption('[data-context-layout]','rows');const id=await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.windowId);await page.reload();await page.waitForSelector('[data-context-tab-fragment]');assert.equal(await page.locator('[data-context-layout]').inputValue(),'rows');assert.equal(await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.windowId),id);
step='snapshot and real authorization';const pinned=await context.newPage();let snapshotConnections=0;pinned.on('request',r=>{if(r.url().includes('/hubs/')&&r.url().includes('/negotiate'))snapshotConnections++;});await pinned.goto(url+'&pinned=true');await pinned.waitForSelector('[data-context-tab-fragment]');assert.equal(snapshotConnections,0);
const native=await page.request.get(`${base}/Writing/Context/Tabs/overview?bookId=${scope.book}&sceneId=${scope.scene}&instanceId=11111111-1111-4111-8111-111111111111&sessionId=22222222-2222-4222-8222-222222222222`);assert.equal(native.status(),409);
const foreign=await page.request.get(`${base}/Writing/Context/Tabs/overview?bookId=2147483647&sceneId=${scope.scene}`);assert([403,404].includes(foreign.status()));
const old=await page.request.get(`${base}/Writing/Intent?projectId=${scope.project}&bookId=${scope.book}&sceneId=${scope.scene}`,{maxRedirects:0});assert.equal(old.status(),302);assert.match(old.headers().location,/Writing\/Context/);
const anonymous=await browser.newContext();const denied=await anonymous.request.get(`${base}/Writing/Context/Tabs/characters?sceneId=${scope.scene}`,{maxRedirects:0});assert([302,401].includes(denied.status()));await anonymous.close();
assert.deepEqual(errors,[]);await context.close();console.log('PASS Development actual saved Razor data, one real SignalR connection, two panes/shared read, cross-window editor invalidation, independent window, persistence, pinned snapshot, native session/access denial and Intent redirect; synthetic title restored');
} catch(error){console.error('FAILED at '+step+': '+error.message);process.exitCode=1;} finally{if(restore)await restore();await browser.close();}
})().catch(()=>{console.error('Development Context smoke could not complete');process.exitCode=1;});

View File

@ -0,0 +1,102 @@
// Actual compiled Razor shell and partials; isolated loopback fixture, no database or Word writes.
const {chromium}=require('playwright');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
const fakeSignalR=`window.contextConnections=[];window.signalR={HubConnectionBuilder:class{withUrl(url){this.url=url;return this}withAutomaticReconnect(){return this}build(){const c={url:this.url,state:'Disconnected',handlers:{},on(n,f){this.handlers[n]=f},onreconnecting(f){this.reconnecting=f},onreconnected(f){this.reconnected=f},onclose(f){this.closed=f},async start(){this.state='Connected'},async stop(){this.state='Disconnected'}};contextConnections.push(c);return c}}};`;
const lease=(extra={})=>({instanceId:'11111111-1111-4111-8111-111111111111',sessionId:'22222222-2222-4222-8222-222222222222',manuscriptId:'33333333-3333-4333-8333-333333333333',bookId:12,chapterId:10,sceneId:22,wordAvailable:true,wordSaved:true,active:true,positionVerified:true,mappingCurrent:true,snapshotRevision:1,revision:1,documentTitle:'Synthetic manuscript',updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString(),...extra});
(async()=>{
const browser=await chromium.launch();let step='setup';
try{
const context=await browser.newContext({viewport:{width:1366,height:768}});
let leases=[lease()],office={connected:false,position:null},revision=1,mode='ok',delayScene=null,requests=[];
await context.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fakeSignalR}));
await context.route('**/native-companion/status',r=>r.fulfill({json:leases}));
await context.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false,state:'Disconnected'}}));
await context.route('**/Writing/Context/Position?*',r=>r.fulfill({json:office}));
await context.route('**/Writing/Context/Navigate',r=>r.fulfill({status:409,json:{message:'No current Word mapping. Saved scene selected.'}}));
await context.route('**/Writing/Context/Tabs/*',async route=>{
const url=new URL(route.request().url());const tool=url.pathname.split('/').at(-1),scene=url.searchParams.get('sceneId');
requests.push({tool,scene,revision});const captured=revision;
if(mode==='expired')return route.fulfill({status:401,body:'Sign in'});
if(mode==='mapping')return route.fulfill({status:409,body:'Mapping pending'});
const response=await route.fetch({url:`${base}/context-tab-fixture/${tool}?sceneId=${scene}`});
const html=(await response.text()).replace('Saved scene summary and provenance',`Saved scene summary and provenance · revision ${captured}`);
if(delayScene===scene)await new Promise(resolve=>setTimeout(resolve,350));
try{await route.fulfill({contentType:'text/html',body:html});}catch{/* Navigation may abort an obsolete shared read. */}
});
const page=await context.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));
step='single-pane actual Razor';await page.goto(base+'/Writing/Context');
await page.locator('[data-context-pane="0"] [data-context-tab-fragment][data-scene-id="22"]').waitFor();
assert.equal(await page.evaluate(()=>contextConnections.length),1,'one shared connection, including native status shell');
assert.equal(await page.locator('[data-context-pane="1"]').isVisible(),false);
assert.match(await page.locator('[data-context-pane="0"]').innerText(),/viewpoint knowledge|POV/i);
step='columns, independent tools';await page.selectOption('[data-context-layout]','columns');
await page.locator('[data-context-pane="1"] [data-context-tab-fragment]').waitFor();
assert.match(await page.locator('[data-context-pane="1"]').innerText(),/Fixture participant/);
assert.match(await page.locator('[data-context-pane="1"]').innerText(),/Uncertain/);
assert.match(await page.locator('[data-context-pane="1"]').innerText(),/future record/);
if(process.env.PD_CONTEXT_EVIDENCE){fs.mkdirSync(process.env.PD_CONTEXT_EVIDENCE,{recursive:true});await page.screenshot({path:process.env.PD_CONTEXT_EVIDENCE+'/columns-1366.png'});}
step='same tab twice and shared HTTP request';requests=[];
await page.selectOption('[data-context-pane="1"] [data-context-tab]','overview');
await page.waitForFunction(()=>[...document.querySelectorAll('[data-context-pane-content]')].every(n=>n.textContent.includes('Saved scene summary')));
await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate());
await page.waitForTimeout(180);
assert.equal(requests.length,2,'one new pane initial read plus one shared invalidation read');
const ids=await page.locator('[id]').evaluateAll(nodes=>nodes.map(n=>n.id));assert.equal(ids.length,new Set(ids).size,'no duplicate IDs');
assert.equal(await page.locator('[data-context-pane="0"] [data-context-tab-fragment]').evaluate((n)=>n===document.querySelector('[data-context-pane="1"] [data-context-tab-fragment]')),false);
step='divider keyboard and drag';const divider=page.locator('[data-context-divider]');await divider.focus();const initial=Number(await divider.getAttribute('aria-valuenow'));await page.keyboard.press('ArrowRight');assert(Number(await divider.getAttribute('aria-valuenow'))>initial);
let box=await divider.boundingBox();await page.mouse.move(box.x+box.width/2,box.y+box.height/2);await page.mouse.down();await page.mouse.move(850,box.y+box.height/2);await page.mouse.up();assert(Number(await divider.getAttribute('aria-valuenow'))>55);
step='stacked layout';await page.selectOption('[data-context-layout]','rows');assert.equal(await divider.getAttribute('aria-orientation'),'horizontal');await divider.focus();await page.keyboard.press('ArrowUp');
const a=await page.locator('[data-context-pane="0"]').boundingBox(),b=await page.locator('[data-context-pane="1"]').boundingBox();assert(b.y>a.y+a.height);
step='single retains second pane selection';await page.selectOption('[data-context-pane="1"] [data-context-tab]','characters');await page.selectOption('[data-context-layout]','single');await page.selectOption('[data-context-layout]','columns');assert.equal(await page.locator('[data-context-pane="1"] [data-context-tab]').inputValue(),'characters');
step='unrelated-project notifications do not reload panes';const scopedReads=requests.length;await page.evaluate(()=>contextConnections[0].handlers.ContextInvalidated({projectId:999}));await page.waitForTimeout(80);assert.equal(requests.length,scopedReads);
step='same scene accepted content and inactive stale selection';revision=2;await page.evaluate(()=>contextConnections[0].handlers.ContextInvalidated({bookId:12}));await page.waitForFunction(()=>document.querySelector('[data-context-pane="0"]').textContent.includes('revision 2'));
await page.selectOption('[data-context-pane="0"] [data-context-tab]','characters');await page.selectOption('[data-context-pane="0"] [data-context-tab]','overview');await page.waitForFunction(()=>document.querySelector('[data-context-pane="0"]').textContent.includes('revision 2'));
step='rapid scene/chapter navigation and out of order responses';delayScene='23';await page.evaluate(()=>{const c=document.querySelector('[data-context-workspace]').contextController;c.setPosition({projectId:7,bookId:12,chapterId:11,sceneId:23});setTimeout(()=>c.setPosition({projectId:7,bookId:12,chapterId:10,sceneId:22}),30);});await page.waitForTimeout(550);assert.equal(await page.locator('[data-context-pane="0"] [data-context-tab-fragment]').getAttribute('data-scene-id'),'22');delayScene=null;
step='dirty/busy deferral';await page.evaluate(()=>document.querySelector('[data-context-pane="0"]').dispatchEvent(new CustomEvent('context-panel-state',{detail:{dirty:true}})));revision=3;await page.evaluate(()=>contextConnections[0].handlers.ContextInvalidated({bookId:12}));await page.waitForTimeout(160);assert.match(await page.locator('[data-context-pane="0"]').innerText(),/revision 2/);assert.match(await page.locator('[data-context-pane="0"] [data-context-pane-status]').innerText(),/editing|busy/);
await page.evaluate(()=>document.querySelector('[data-context-pane="0"]').dispatchEvent(new CustomEvent('context-panel-state',{detail:{dirty:false,busy:false}})));await page.waitForFunction(()=>document.querySelector('[data-context-pane="0"]').textContent.includes('revision 3'));
step='session expiry and mapping conflict';mode='expired';await page.click('[data-context-refresh]');await page.waitForFunction(()=>document.querySelector('[data-context-pane-status]').textContent.includes('Sign in'));assert.match(await page.locator('[data-context-pane="0"]').innerText(),/revision 3/);mode='mapping';await page.click('[data-context-refresh]');await page.waitForFunction(()=>document.querySelector('[data-context-pane-status]').textContent.includes('mapping'));mode='ok';
step='disconnect and unchanged-position reconnect';revision=4;await page.evaluate(()=>contextConnections[0].reconnecting());assert.match(await page.locator('[data-context-status]').innerText(),/reconnecting/);await page.evaluate(()=>contextConnections[0].reconnected());await page.waitForFunction(()=>document.querySelector('[data-context-pane="0"]').textContent.includes('revision 4'));
step='native ambiguity and missing mapping';leases=[lease(),lease({instanceId:'44444444-4444-4444-8444-444444444444',active:true})];await page.evaluate(()=>window.dispatchEvent(new CustomEvent('plotdirector:refresh-word-status')));await page.waitForFunction(()=>document.querySelector('[data-context-status]').textContent.includes('Choose a Word document'));
await page.click('#native-companion-status');await page.selectOption('#writing-word-document','44444444-4444-4444-8444-444444444444/22222222-2222-4222-8222-222222222222');await page.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.position.instanceId==='44444444-4444-4444-8444-444444444444');assert.equal(new URL(page.url()).searchParams.get('instanceId'),'44444444-4444-4444-8444-444444444444');await page.reload();await page.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.position.instanceId==='44444444-4444-4444-8444-444444444444');await page.click('#native-companion-status');assert.equal(await page.locator('#writing-word-document').inputValue(),'44444444-4444-4444-8444-444444444444/22222222-2222-4222-8222-222222222222');await page.selectOption('#writing-word-document','');await page.click('[data-close-word-details]');
leases=[lease({positionVerified:false,positionMessage:'Mapping pending'})];await page.evaluate(()=>window.dispatchEvent(new CustomEvent('plotdirector:refresh-word-status')));await page.waitForFunction(()=>document.querySelector('[data-context-status]').textContent.includes('Mapping pending'));
step='saved manual reads survive unavailable Word observations';delayScene='23';await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:11,sceneId:23}));await page.waitForTimeout(40);await page.evaluate(leases=>window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:leases})),leases);await page.waitForSelector('[data-context-pane=\"0\"] [data-context-tab-fragment][data-scene-id=\"23\"]');delayScene=null;
step='Office fallback and native precedence';leases=[];office={connected:true,position:{projectId:7,bookId:12,chapterId:11,sceneId:23}};await page.evaluate(()=>window.dispatchEvent(new CustomEvent('plotdirector:refresh-word-status')));await page.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId===23);
leases=[lease()];await page.evaluate(()=>window.dispatchEvent(new CustomEvent('plotdirector:refresh-word-status')));await page.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId===22);
step='persistence';await page.selectOption('[data-context-layout]','rows');const identity=await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.windowId);await page.reload();await page.waitForSelector('[data-context-tab-fragment]');assert.equal(await page.locator('[data-context-layout]').inputValue(),'rows');assert.equal(await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.windowId),identity);
step='cloned window storage';const storage=await page.evaluate(()=>({id:sessionStorage.getItem('plotdirector.context.window.v1')}));const clone=await context.newPage();await clone.addInitScript(s=>sessionStorage.setItem('plotdirector.context.window.v1',s.id),storage);await clone.goto(base+'/Writing/Context');await clone.waitForFunction(id=>document.querySelector('[data-context-workspace]')?.contextController?.windowId!==id,identity);assert.equal(await clone.locator('[data-context-layout]').inputValue(),'single');assert.equal(await page.locator('[data-context-layout]').inputValue(),'rows');await clone.close();
step='multiple windows';const popupPromise=page.waitForEvent('popup');await page.click('[data-context-new]');const popup=await popupPromise;await popup.waitForSelector('[data-context-tab-fragment]');assert.equal(await popup.locator('[data-context-layout]').inputValue(),'single');assert.notEqual(await popup.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.windowId),identity);assert.equal(await popup.evaluate(()=>contextConnections.length),1);await popup.close();
step='laptop, narrow pane, zoom and standalone presentation';for(const [width,height,zoom]of [[1366,768,1],[760,768,1],[683,384,1],[480,700,1.25]]){
await page.setViewportSize({width,height});await page.evaluate(zoom=>document.documentElement.style.zoom=zoom,zoom);
for(const layout of ['single','columns','rows']){await page.selectOption('[data-context-layout]',layout);await page.waitForTimeout(40);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false,`window overflow ${width}/${layout}/${zoom}`);assert(await page.locator('[data-context-pane="0"] [data-context-pane-content]').evaluate(n=>n.clientHeight>30));}
}
await page.evaluate(()=>{document.documentElement.style.zoom='1';Object.defineProperty(navigator,'standalone',{value:true});});
step='pinned snapshot';leases=[lease({sceneId:23,chapterId:11})];const pinned=await context.newPage();await pinned.goto(base+'/Writing/Context?pinned=true&sceneId=22');await pinned.waitForSelector('[data-context-tab-fragment]');assert.equal(await pinned.evaluate(()=>contextConnections.length),0);assert.equal(await pinned.locator('[data-context-tab-fragment]').getAttribute('data-scene-id'),'22');await pinned.selectOption('[data-context-scene]','23');await pinned.waitForSelector('[data-context-tab-fragment][data-scene-id="23"]');await pinned.close();
step='generic hierarchical registration scopes';
for(const declared of ['None','Book','Chapter','Scene','Paragraph']){
const generic=await context.newPage();let count=0;
await generic.route('**/Writing/Context?pinned=true*',async route=>{const response=await route.fetch();await route.fulfill({response,body:(await response.text()).replaceAll('"scope":"Scene"','"scope":"'+declared+'"')});});
await generic.route('**/Writing/Context/Tabs/*',async route=>{count++;const params=new URL(route.request().url()).searchParams,level=['None','Book','Chapter','Scene','Paragraph'].indexOf(declared),fields=['projectId','bookId','chapterId','sceneId','paragraphId'];const attributes=fields.slice(0,level===0?0:level+1).filter(f=>params.has(f)).map(f=>'data-'+f.replace(/[A-Z]/g,c=>'-'+c.toLowerCase())+'="'+params.get(f)+'"').join(' ');await route.fulfill({contentType:'text/html',body:'<div data-context-tab-fragment '+attributes+'><p>Generic reference</p></div>'});});
await generic.goto(base+'/Writing/Context?pinned=true');await generic.waitForSelector('[data-context-tab-fragment]');assert.equal(count,1);assert.equal(await generic.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.paragraphId),null);
const move=async(chapterId,sceneId,paragraphId=null)=>{const before=count;await generic.evaluate(p=>document.querySelector('[data-context-workspace]').contextController.setPosition(p),{projectId:7,bookId:12,chapterId,sceneId,paragraphId});await generic.waitForTimeout(70);return count-before;};
assert.equal(await move(10,23),['Scene','Paragraph'].includes(declared)?1:0,declared+' scene policy');
assert.equal(await move(11,24),['Chapter','Scene','Paragraph'].includes(declared)?1:0,declared+' chapter policy');
assert.equal(await move(11,24,'provided-paragraph'),declared==='Paragraph'?1:0,declared+' paragraph policy');await generic.close();
}
step='storage-event clone fallback';
const fallback=await context.newPage();await fallback.addInitScript(()=>Object.defineProperty(window,'BroadcastChannel',{value:undefined}));await fallback.goto(base+'/Writing/Context');await fallback.waitForSelector('[data-context-tab-fragment]');await fallback.selectOption('[data-context-layout]','rows');const fallbackId=await fallback.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.windowId);
const fallbackClone=await context.newPage();await fallbackClone.addInitScript(id=>{Object.defineProperty(window,'BroadcastChannel',{value:undefined});sessionStorage.setItem('plotdirector.context.window.v1',id);},fallbackId);await fallbackClone.goto(base+'/Writing/Context');await fallbackClone.waitForFunction(id=>document.querySelector('[data-context-workspace]')?.contextController?.windowId!==id,fallbackId);assert.equal(await fallbackClone.locator('[data-context-layout]').inputValue(),'single');await fallback.close();await fallbackClone.close();
step='denied storage in-memory fallback';
const noStorage=await context.newPage();await noStorage.addInitScript(()=>{Object.defineProperty(window,'BroadcastChannel',{value:undefined});for(const name of ['localStorage','sessionStorage'])Object.defineProperty(window,name,{get(){throw new DOMException('Storage unavailable','SecurityError');}});});await noStorage.goto(base+'/Writing/Context');await noStorage.waitForSelector('[data-context-tab-fragment]');await noStorage.selectOption('[data-context-layout]','rows');assert.equal(await noStorage.locator('[data-context-layout]').inputValue(),'rows');await noStorage.close();
step='Office launch URL contract';
const host=fs.readFileSync(require('node:path').join(__dirname,'../../PlotLine/wwwroot/js/word-companion-host.js'),'utf8');
const launch=host.slice(host.indexOf(' const writingWorkspaceUrl ='),host.indexOf(' const openWritingWindow ='));
const build=new Function('window','crypto','URL','writingWorkspaceScope','currentDocumentGuid','resolvedChapterId','resolvedSceneId','detectedChapterAnchorId','detectedSceneAnchorId',launch+';return writingWorkspaceUrl');
const launchUrl=build({location:{origin:base}},require('node:crypto').webcrypto,URL,()=>({projectId:7,bookId:12}),()=> '33333333-3333-4333-8333-333333333333',10,22,null,null);
const first=new URL(launchUrl('context'),base),second=new URL(launchUrl('workspace'),base);
assert.equal(first.pathname,'/Writing/Context');assert.equal(second.pathname,'/Writing/Context');assert.equal(first.searchParams.get('sceneId'),'22');assert.notEqual(first.searchParams.get('contextWindow'),second.searchParams.get('contextWindow'));
step='Intent compatibility';const redirected=await page.request.get(base+'/Writing/Intent?bookId=12&sceneId=23',{maxRedirects:0});assert.equal(redirected.status(),302);assert.match(redirected.headers().location,/Writing\/Context.*sceneId=23/);
assert.deepEqual(errors,[]);await context.close();console.log('PASS Context foundation: compiled Razor, two tabs, layouts/divider, shared requests, stale/race guards, dirty safety, native/Office/reconnect, windows/storage, auth failures, snapshot, narrow/zoom/standalone presentation');
}catch(error){console.error('FAILED at '+step);throw error;}finally{await browser.close();}
})().catch(error=>{console.error(error);process.exit(1);});

View File

@ -0,0 +1,37 @@
// Isolated production launch asset: no account, database, native process or manuscript.
const {chromium}=require('playwright');
const fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict');
const script=fs.readFileSync(path.join(__dirname,'../../PlotLine/wwwroot/js/native-context-launch.js'),'utf8');
(async()=>{
const browser=await chromium.launch();
try{
for(const outcome of ['open','reused','pending','failure','no-storage']){
const context=await browser.newContext(),page=await context.newPage();
await page.route('https://fixture.invalid/**',route=>route.fulfill({contentType:'text/html',body:'<p>Context destination</p>'}));
await page.goto('https://fixture.invalid/launch');
await page.setContent('<main data-native-context-launch data-book="12" data-project="3" data-instance="instance" data-session="session"><p data-context-launch-status></p><button data-context-launch-retry hidden>Retry</button></main>');
await page.evaluate(outcome=>{
window.calls=[];window.closedByLaunch=false;window.close=()=>{window.closedByLaunch=true;};
window.PlotDirectorContextEnvironment=outcome==='no-storage'?null:'browser-profile';
window.PlotDirectorPresenceConnection={state:'Connected',invoke:async(name,...args)=>{
window.calls.push([name,...args]);if(name==='OpenContextWindow'){if(outcome==='failure')throw new Error('offline');return outcome;}
}};
},outcome);
await page.addScriptTag({content:script});
if(outcome==='open'){
await page.waitForURL('**/Writing/Context?**');const url=new URL(page.url());
assert.equal(url.searchParams.get('bookId'),'12');assert.equal(url.searchParams.get('sessionId'),'session');
assert.equal(url.searchParams.has('sceneId'),false,'opening cannot force a scene selection');
}else{
await page.waitForFunction(()=>window.closedByLaunch||document.querySelector('[data-context-launch-status]').textContent.length>0);
const state=await page.evaluate(()=>({calls:window.calls,closed:window.closedByLaunch,retry:!document.querySelector('button').hidden,text:document.querySelector('p').textContent}));
assert.equal(state.closed,['reused','pending'].includes(outcome));
assert.equal(state.calls.some(c=>/Publish|Resolve|Navigate/.test(c[0])),false,'opening never publishes or redirects manuscript focus');
assert.equal(state.retry,outcome==='failure');
if(outcome==='no-storage')assert.equal(state.calls.length,0,'missing environment cannot target another device');
if(outcome==='reused')assert.match(state.text,/layout, tools, Hold and position were retained/);
}
console.log('PASS isolated native Context launch: '+outcome);await context.close();
}
}finally{await browser.close();}
})().catch(error=>{console.error(error);process.exitCode=1;});

View File

@ -23,7 +23,7 @@
"test:maps-story": "node maps-story-engine.cjs && node maps-story.cjs",
"test:writer": "node writer-workspace.cjs",
"test:writer-goals": "node writer-goal-navigation.cjs",
"test:word-companion": "node word-companion-regressions.cjs"
"test:word-companion": "node context-workspace-foundation.cjs"
},
"devDependencies": {
"@microsoft/signalr": "8.0.7",

View File

@ -0,0 +1,3 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
(async()=>{const b=await chromium.launch();try{const c=await b.newContext({viewport:{width:1366,height:1000}});await c.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));await c.route('**/native-companion/status',r=>r.fulfill({json:[]}));await c.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false}}));let protectedSource=false;await c.route('**/Characters/Workspace/Operation/*',async r=>{if(r.request().method()==='POST'){await r.fulfill({json:{saved:true,message:'One canonical event saved.'}});return;}const u=new URL(r.request().url());u.searchParams.set('protected',String(protectedSource));await r.fulfill({response:await r.fetch({url:base+'/character-workspace-operation-fixture'+u.search})});});const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.addLocatorHandler(p.locator('[data-desktop-continue]'),async l=>l.click());for(const count of [0,1,5]){await p.setViewportSize({width:1366,height:1000});await p.goto(base+'/relationship-evolution-fixture?count='+count);await p.locator('[data-relationship-evolution="9"]').waitFor();await p.evaluate(()=>{document.documentElement.dataset.appTheme='warm-dark';document.documentElement.dataset.theme='dark';document.documentElement.dataset.bsTheme='dark'});assert.equal(await p.locator('[data-evolution-event]').count(),count);assert.equal(await p.locator('.relationship-evolution-chart').count(),count>1?1:0);assert.equal(await p.locator('.dynamics-timeline').count(),0);if(count===0)assert.match(await p.locator('main').innerText(),/No recorded events/);if(count===1)assert.match(await p.locator('main').innerText(),/One recorded event/);if(count===5){assert.deepEqual(await p.locator('[data-evolution-event]').evaluateAll(ns=>ns.map(n=>Number(n.dataset.evolutionEvent))),[1,2,3,4,5]);assert.equal(await p.locator('.relationship-evolution-chart circle').count(),4);await p.locator('.relationship-evolution-chart a').first().click();assert.match(p.url(),/#event-1/);await p.screenshot({path:'/tmp/relationship-evolution-dark-desktop.png',fullPage:true});}for(const width of [1366,1024,768,390]){await p.setViewportSize({width,height:1000});assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));}assert.match(await p.getByRole('link',{name:'Return to character Relationships'}).getAttribute('href'),/Characters\/Details\/5.*relationshipId=9/);}
await p.locator('[data-history-operation="event-edit"]').first().click();await p.locator('[data-workspace-operation-form]').waitFor();assert.match(await p.locator('[data-history-dialog]').innerText(),/one recorded development/);await p.locator('[name=Notes]').fill('Unsaved event draft');p.once('dialog',d=>d.dismiss());await p.keyboard.press('Escape');assert(await p.locator('[data-history-dialog]').evaluate(n=>n.open));p.once('dialog',d=>d.accept());await p.locator('[data-workspace-cancel]').click();let refreshes=0,navigations=0;p.on('request',r=>{if(r.url().includes('/relationship-evolution-fixture'))refreshes++;});p.on('load',()=>navigations++);await p.locator('[data-history-operation="event-edit"]').first().click();await p.locator('[name=Notes]').fill('Saved event draft');await p.locator('[data-workspace-operation-form] [type=submit]').click();await p.waitForFunction(()=>!document.querySelector('[data-history-dialog]').open);await p.locator('.pd-toast').filter({hasText:'One canonical event saved.'}).waitFor();await p.waitForTimeout(150);assert(refreshes>0);assert.equal(navigations,0);protectedSource=true;await p.locator('[data-history-operation="event-remove"]').first().click();await p.locator('[data-workspace-operation-form]').waitFor();assert.match(await p.locator('[data-history-dialog]').innerText(),/Direct modification\/removal is blocked/);assert.equal(await p.locator('[data-workspace-operation-form] [type=submit]').count(),0);await p.locator('[data-workspace-cancel]').click();await p.goto(base+'/relationship-evolution-fixture?count=1&viewer=true');assert.equal(await p.locator('[data-history-operation]').count(),0);assert.deepEqual(errors,[]);console.log('PASS relationship Evolution: empty/single/multiple canonical histories, dark theme bounded intensity chart without invented missing values, chronological source links, exact return identity, desktop/laptop/tablet/mobile, event modal draft/Escape/source protection and Viewer permissions.');}finally{await b.close();}})().catch(e=>{console.error(e);process.exitCode=1});

View File

@ -174,7 +174,9 @@ const base = 'http://127.0.0.1:5238';
await app.locator('.pd-context-popup').waitFor();
assert.match(await app.locator('.pd-context-popup').innerText(), /Edit character|Add relationship/, 'map context actions remain available after focusing');
await app.keyboard.press('Escape');
await page.goto(base + '/fixture?page=relationships&relationshipId=1');
await page.waitForFunction(()=>window.PlotDirectorRelationshipWorkspace?.selectedRelationship?.characterRelationshipID===1);
assert.deepEqual(errors, []);
console.log('PASS Relationships workspace: 75 cast, 300 scenes, focus, search, drag/drop, editor, timeline, persistence, responsive layout and PWA menu');
console.log('PASS Relationships workspace: 75 cast, 300 scenes, focus, search, drag/drop, editor, timeline, persistence, responsive layout, exact definition deep link and PWA menu');
} finally { await browser.close(); }
})().catch(error => { console.error(error); process.exitCode = 1; });

View File

@ -0,0 +1,49 @@
// Real authenticated Development database + SignalR acceptance; synthetic fixture only.
const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict');
const base=process.env.PD_SHARED_FOCUS_URL||'http://127.0.0.1:5258';
(async()=>{
const who=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY)),s=JSON.parse(fs.readFileSync('/tmp/shared-focus-browser-scope.json'));
assert.equal(who.Database,'PlotDirector_Development');assert.equal(who.UserID,s.user);assert(who.Email.startsWith('pwa-browser-'));
const installed=process.argv.includes('--installed');const profile=installed?fs.mkdtempSync('/tmp/pd-shared-focus-pwa-'):null;const persistent=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1500,height:1000}}):null;const browser=persistent?.browser()||await chromium.launch();let step='login';const errors=[];
try{
const c=persistent||await browser.newContext({viewport:{width:1500,height:1000}});
await c.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8')}));
await c.addInitScript(user=>{try{localStorage.setItem('plotdirector.desktop.v1.'+user,JSON.stringify({dismissedAt:Date.now()}));}catch{}},who.UserID);
const sockets=new WeakMap();let wordCommands=0;c.on('request',r=>{if(/\/(WriterWord|Writing\/Context)\/Navigate/.test(new URL(r.url()).pathname))wordCommands++;});c.on('page',p=>{const rows=[];sockets.set(p,rows);p.on('websocket',socket=>{const row={url:socket.url(),closed:false};rows.push(row);socket.on('close',()=>row.closed=true);});p.on('pageerror',e=>{errors.push(e.message);console.error('Browser error: '+e.message);});});
const login=await c.newPage();await login.goto(base+'/Account/Login');await login.locator('[name=Email]').fill(who.Email);await login.locator('[name=Password]').fill(who.Password);await Promise.all([login.waitForURL(u=>u.pathname!='/Account/Login'),login.locator('button[type=submit]').click()]);
let desktop;if(installed){await login.goto(`${base}/Projects/Details/${s.project}`);desktop=await browser.newBrowserCDPSession();await desktop.send('PWA.install',{manifestId:base+'/Projects',installUrlOrBundleUrl:`${base}/Projects/Details/${s.project}`});await desktop.send('PWA.changeAppUserSettings',{manifestId:base+'/Projects',displayMode:'standalone'});}
async function surface(url){if(!installed){const p=await c.newPage();await p.goto(url);return p;}const opened=c.waitForEvent('page');await desktop.send('PWA.launch',{manifestId:base+'/Projects',url});const p=await opened;await p.waitForLoadState();assert(await p.evaluate(()=>matchMedia('(display-mode: standalone)').matches));return p;}
const contextURL=`${base}/Writing/Context?projectId=${s.project}&bookId=${s.book}&sceneId=${s.scene1}`;
const ready=async p=>{await p.waitForFunction(()=>window.PlotDirectorSharedFocus&&document.querySelector('[data-context-workspace]')?.contextController?.connection?.state==='Connected');await p.waitForSelector('[data-context-tab-fragment]');};
const scene=async(p,id)=>p.waitForFunction(id=>document.querySelector('[data-context-workspace]').contextController.position.sceneId===id,id);
const current=p=>p.evaluate(()=>window.PlotDirectorSharedFocus.shared);
const a=await surface(contextURL);await ready(a);
step='Context alone publishes without Word';await a.selectOption('[data-context-scene]',String(s.scene2));await a.waitForFunction(id=>window.PlotDirectorSharedFocus.shared?.sceneID===id,s.scene2);await a.selectOption('[data-context-scene]',String(s.scene1));await a.waitForFunction(id=>window.PlotDirectorSharedFocus.shared?.sceneID===id,s.scene1);
await a.click('[data-shared-focus-hold]');await a.selectOption('[data-context-scene]',String(s.scene2));await scene(a,s.scene2);assert.equal((await current(a)).sceneID,s.scene1);
const b=await surface(contextURL);await ready(b);await scene(b,s.scene1);assert.equal(await b.evaluate(()=>PlotDirectorSharedFocus.held),false);
assert.notEqual(await a.evaluate(()=>PlotDirectorSharedFocus.windowID),await b.evaluate(()=>PlotDirectorSharedFocus.windowID));
await a.waitForTimeout(450);let heldFocusFetches=0;a.on('request',r=>{if(new URL(r.url()).pathname.startsWith('/Writing/Context/Tabs/'))heldFocusFetches++;});step='Review alone/Context paragraph publication';const review=await surface(`${base}/Writer/Review?projectId=${s.project}&bookId=${s.book}&chapterId=${s.chapter1}`);await review.waitForFunction(()=>window.PlotDirectorSharedFocus?.shared?.chapterID);await review.waitForSelector(`.manuscript-reader [data-paragraph-id="${s.paragraph2}"]`);
const before=(await current(review)).version;await review.mouse.wheel(0,200);await review.waitForTimeout(300);assert.equal((await current(review)).version,before,'scroll is local');
await review.locator(`.manuscript-reader [data-paragraph-id="${s.paragraph2}"]`).click();await scene(b,s.scene2);await scene(a,s.scene2);assert.equal(await a.evaluate(()=>PlotDirectorSharedFocus.held),true);await review.waitForFunction(p=>PlotDirectorSharedFocus.shared.paragraphID===p,s.paragraph2);
step='Next crosses chapters without Word';await b.locator('[data-context-next]').click();await scene(b,s.scene3);await review.waitForSelector(`.manuscript-reader [data-paragraph-id="${s.paragraph3}"]`);await scene(a,s.scene2);
assert.equal(heldFocusFetches,0,'shared focus alone does not refetch a held pane');await b.click('[data-context-previous]');await scene(b,s.scene2);await b.click('[data-context-next]');await scene(b,s.scene3);const latest=(await current(b)).version;await a.click('[data-context-go-focus]');await scene(a,s.scene3);assert.equal(await a.evaluate(()=>PlotDirectorSharedFocus.held),true);assert.equal((await current(a)).version,latest);await a.selectOption('[data-context-scene]',String(s.scene2));await scene(a,s.scene2);await a.reload();await ready(a);await scene(a,s.scene2);assert.equal(await a.evaluate(()=>PlotDirectorSharedFocus.held),true);
step='release catches latest without publishing';await a.click('[data-shared-focus-hold]');await scene(a,s.scene3);assert.equal((await current(a)).version,latest);assert.equal((await current(b)).version,latest);
step='held Review local navigation';await review.locator('[data-shared-focus-hold]:visible').first().click();await review.evaluate(s=>PlotDirectorSharedFocus.navigate({chapterID:s.chapter1,paragraphID:s.paragraph1}),s);await review.waitForSelector(`.manuscript-reader [data-paragraph-id="${s.paragraph1}"]`);assert.equal((await current(review)).version,latest);await scene(b,s.scene3);await review.evaluate(()=>{const r=document.querySelector('.manuscript-reader'),resolve=r.readerResolveFocus,locate=r.readerLocateFocus;window.__heldFallbackMoves=0;r.readerResolveFocus=()=>({paragraph:r.querySelector('[data-paragraph-id]'),precise:false});r.readerLocateFocus=(...args)=>{window.__heldFallbackMoves++;return locate(...args);};window.__restoreHeldReader=()=>{r.readerResolveFocus=resolve;r.readerLocateFocus=locate;};document.dispatchEvent(new Event('reader:updated'));});await review.waitForFunction(()=>/held reference no longer/.test(document.querySelector('[data-review-focus-notice]').textContent));await review.waitForTimeout(120);assert.equal(await review.evaluate(()=>window.__heldFallbackMoves),0,'a missing held accepted passage cannot trigger fallback navigation');console.log('PASS held Review missing accepted-passage resolver: no fallback navigation or retarget.');await review.evaluate(()=>window.__restoreHeldReader());await review.locator('[data-shared-focus-hold]:visible').first().click();await review.waitForSelector(`.manuscript-reader [data-paragraph-id="${s.paragraph3}"]`);
step='rapid navigation serializes latest intent';await b.evaluate(async s=>{void PlotDirectorSharedFocus.navigate({sceneID:s.scene1});void PlotDirectorSharedFocus.navigate({sceneID:s.scene2});void PlotDirectorSharedFocus.navigate({sceneID:s.scene3});},s);await b.waitForFunction(s=>PlotDirectorSharedFocus.shared.sceneID===s.scene3&&PlotDirectorSharedFocus.shared.version>0,s);await b.waitForTimeout(700);assert.equal((await current(b)).sceneID,s.scene3);
step='duplicate/delayed events cannot overwrite';const stable=await current(b);await b.evaluate(p=>{const conn=document.querySelector('[data-context-workspace]').contextController.connection;const handlers=Object.values(conn).find(v=>Array.isArray(v?.manuscriptfocuschanged))?.manuscriptfocuschanged;if(!handlers)throw Error('Focus receiver was not registered');for(const handler of handlers)handler({...p,version:p.version-1,sceneID:1});},stable);assert.equal((await current(b)).sceneID,s.scene3);
step='held cross-scene relationship invalidation in split panes';await a.click('[data-shared-focus-hold]');await a.selectOption('[data-context-scene]',String(s.scene2));await scene(a,s.scene2);await a.selectOption('[data-context-layout]','columns');await a.selectOption('[data-context-pane="0"] [data-context-tab]','relationships');await a.selectOption('[data-context-pane="1"] [data-context-tab]','characters');await a.waitForSelector('[data-context-pane="0"] [data-context-tab-fragment]');await a.waitForSelector('[data-context-pane="1"] [data-context-tab-fragment]');
await a.click('[data-relationship-lens=story]');await a.waitForTimeout(400);let graphAfter=null;let invalidated=0,refreshed=new Set();a.on('response',async r=>{const u=new URL(r.url());if(u.pathname==='/Writing/Context/Relationships/Graph'&&r.ok())graphAfter=await r.json().catch(()=>null);if(u.pathname.startsWith('/Writing/Context/Tabs/')){invalidated++;refreshed.add(u.pathname);}});
const edit=await surface(`${base}/Characters/Workspace/Operation/${s.character1}?relationshipId=${s.relationship}&eventId=${s.relationshipEvent}&operation=event-edit`);const changeNote='Changed earlier-scene fixture '+Date.now();await edit.locator('[name=Notes]').fill(changeNote);await edit.locator('[name=Intensity]').fill('8');
const saved=await edit.evaluate(async()=>{const form=document.querySelector('form');const response=await fetch(form.action,{method:'POST',body:new FormData(form)});return {status:response.status,text:await response.text()};});assert.equal(saved.status,200,saved.text.slice(0,200));assert.match(saved.text,/saved/);
await a.waitForFunction(()=>window.PlotDirectorSharedFocus.held===true);await a.waitForTimeout(1800);assert(refreshed.has('/Writing/Context/Tabs/relationships')&&refreshed.has('/Writing/Context/Tabs/characters'),'both affected visible panes refreshed');assert.equal(graphAfter?.links?.find(l=>l.id===s.relationship)?.notes,changeNote,'held later-scene graph contains the new earlier-scene note');await scene(a,s.scene2);assert.equal((await current(a)).sceneID,s.scene3);
step='reconnect catches current shared reference';await b.evaluate(async()=>{const c=document.querySelector('[data-context-workspace]').contextController.connection;await c.stop();await c.start();await PlotDirectorSharedFocus.refresh(true);});await scene(b,s.scene3);
step='new window does not inherit Hold';const fresh=await surface(contextURL);await ready(fresh);await scene(fresh,s.scene3);assert.equal(await fresh.evaluate(()=>PlotDirectorSharedFocus.held),false);
if(s.emptyChapter){step='chapter-only and empty-chapter toolbar boundaries';const command=async name=>{const menu=review.locator('.pd-ribbon-panel:not([hidden]) .pd-ribbon-focus details[data-compact=true]');if(await menu.count()&&!await menu.evaluate(n=>n.open))await menu.locator('summary').click();await review.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus='+name+']').click();await review.waitForFunction(()=>document.querySelector('.pd-ribbon-panel:not([hidden]) [data-global-focus=previous]')?.disabled===false);};await review.evaluate(s=>PlotDirectorNarrativeFocus.set({chapterID:s.chapter2}),s);await review.waitForFunction(s=>PlotDirectorSharedFocus.local.chapterID===s.chapter2&&!PlotDirectorSharedFocus.local.sceneID,s);await command('next');await scene(b,s.scene3);await review.evaluate(s=>PlotDirectorNarrativeFocus.set({chapterID:s.emptyChapter}),s);await review.waitForFunction(s=>document.querySelector('.manuscript-reader').dataset.chapterId===String(s.emptyChapter),s);await command('next');await scene(b,s.scene3);await review.evaluate(s=>PlotDirectorNarrativeFocus.set({chapterID:s.emptyChapter}),s);await review.waitForFunction(s=>document.querySelector('.manuscript-reader').dataset.chapterId===String(s.emptyChapter),s);await command('previous');await scene(b,s.scene2);await scene(a,s.scene2);await review.evaluate(s=>PlotDirectorNarrativeFocus.set({chapterID:s.chapter2,sceneID:s.scene3}),s);await scene(b,s.scene3);console.log('PASS actual Review toolbar: chapter-only Next stays in its own chapter; empty-chapter Previous/Next reaches the canonical neighbor without moving held Context.');}
step='duplicated session state cannot inherit Hold';const clone=await c.newPage();const storage=await a.evaluate(()=>Object.fromEntries(Object.entries(sessionStorage).filter(([k])=>k.startsWith('pd.shared-focus')||k==='plotdirector.context.window.v1')));await clone.addInitScript(values=>{for(const[k,v]of Object.entries(values))sessionStorage.setItem(k,v);},storage);await clone.goto(contextURL);await ready(clone);await clone.waitForFunction(id=>!PlotDirectorSharedFocus.held&&PlotDirectorSharedFocus.windowID!==id,await a.evaluate(()=>PlotDirectorSharedFocus.windowID));await scene(clone,s.scene3);
step='hidden affected cached tab is fetched when activated';const beforeHidden=invalidated;await a.selectOption('[data-context-pane="0"] [data-context-tab]','overview');await a.waitForTimeout(600);assert(invalidated>beforeHidden);await scene(a,s.scene2);
step='responsive Hold control';for(const width of[1500,760,390]){await a.setViewportSize({width,height:900});assert(await a.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),'Context overflow at '+width);}await a.setViewportSize({width:1500,height:1000});
if(process.argv.includes('--restart')){step='actual server restart recovery';const revision=(await current(b)).version;await b.evaluate(()=>{const root=document.querySelector('[data-context-workspace]');root.contextController.connection.onreconnected(()=>window.__sharedFocusRestartRecovered=true);root.addEventListener('context-connection-ready',()=>window.__sharedFocusRestartRecovered=true,{once:true});});fs.writeFileSync('/tmp/shared-focus-restart-ready','ready');await b.waitForFunction(()=>window.__sharedFocusRestartRecovered,null,{timeout:55000});await scene(b,s.scene3);await a.waitForFunction(()=>[...document.querySelectorAll('[data-shared-focus-status]')].some(n=>/no longer valid/.test(n.textContent)));await scene(a,s.scene2);assert.equal(await a.evaluate(()=>PlotDirectorSharedFocus.held),true);assert.equal((await current(b)).version,revision);await a.selectOption('[data-context-scene]',String(s.scene1));await scene(a,s.scene1);assert.equal((await current(a)).version,revision);console.log('PASS actual loopback server restart: latest focus persisted, SignalR reconnected, held scene retained and an offline structural change was validated without redirect.');}
if(process.argv.includes('--structure')){step='structural archive retains held reference';const result=await edit.evaluate(async s=>{const token=document.querySelector('[name=__RequestVerificationToken]').value;const response=await fetch('/Scenes/Archive',{method:'POST',body:new URLSearchParams({id:s.scene2,chapterId:s.chapter1,__RequestVerificationToken:token})});return response.status;},s);assert.equal(result,200);await a.waitForFunction(()=>[...document.querySelectorAll('[data-shared-focus-status]')].some(n=>/no longer valid/.test(n.textContent)));await scene(a,s.scene2);assert.equal(await a.evaluate(()=>PlotDirectorSharedFocus.held),true);await a.selectOption('[data-context-scene]',String(s.scene1));await scene(a,s.scene1);assert.equal((await current(a)).sceneID,s.scene3);const version=(await current(a)).version;const archived=await edit.evaluate(async s=>{const token=document.querySelector('[name=__RequestVerificationToken]').value;return(await fetch('/Scenes/Archive',{method:'POST',body:new URLSearchParams({id:s.scene3,chapterId:s.chapter2,__RequestVerificationToken:token})})).status;},s);assert.equal(archived,200);await a.evaluate(()=>PlotDirectorSharedFocus.refresh());assert.equal((await current(a)).isValid,false);await a.evaluate(()=>{const conn=document.querySelector('[data-context-workspace]').contextController.connection;const handlers=Object.values(conn).find(v=>Array.isArray(v?.manuscriptfocuschanged))?.manuscriptfocuschanged;for(const handler of handlers||[])handler({...PlotDirectorSharedFocus.shared,isValid:true});});assert.equal((await current(a)).isValid,false,'duplicate focus packets cannot undo authoritative same-revision invalidity');await a.click('[data-shared-focus-hold]');await a.waitForFunction(()=>!PlotDirectorSharedFocus.held);await scene(a,s.scene1);assert.equal((await current(a)).version,version);assert.equal((await current(a)).isValid,false,'same-revision invalidity must replace cached validity before Release');await b.selectOption('[data-context-scene]',String(s.scene1));await b.waitForFunction(s=>PlotDirectorSharedFocus.shared.sceneID===s.scene1&&PlotDirectorSharedFocus.shared.isValid,s);console.log('PASS structural safety: local invalid reference retained; Release rejects an invalid shared point even at the same revision, retains valid local position, and does not publish.');}
assert.equal(wordCommands,0,'shared navigation never depends on or automatically invokes Word navigation');for(const p of[a,b,fresh,clone])assert.equal(sockets.get(p).filter(s=>!s.closed&&s.url.includes('/hubs/native-companion')).length,1,'one existing SignalR connection per Context window');assert.deepEqual(errors,[]);console.log('PASS real authenticated browser + SQL + SignalR: Context alone, Review↔Context without Word, scroll local, exact paragraphs/chapter crossing, per-window Hold, refresh/release, rapid/obsolete ordering, cross-scene relationship save refreshes both held panes, reconnect, new/duplicated-window isolation, Previous/Go without Word, hidden tabs and responsive Hold.');
}catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await persistent?.close();await browser.close();if(profile)fs.rmSync(profile,{recursive:true,force:true});}
})();

View File

@ -1,65 +0,0 @@
const {chromium}=require('playwright');
const fs=require('node:fs');
const path=require('node:path');
const assert=require('node:assert/strict');
const scripts=path.join(__dirname,'../../PlotLine/wwwroot/js');
(async()=>{
const browser=await chromium.launch();
try{
for(const role of ['context','intent']){
const page=await browser.newPage();
await page.goto('about:blank');
await page.setContent(`<main id="root" data-scope-project-id="1" data-scope-book-id="2"><div id="status"></div><div id="content"><section id="fragment" data-scene-id="5" data-chapter-id="1">initial</section></div></main>`);
await page.addScriptTag({content:`window.__requests=[];window.fetch=(url,options)=>new Promise((resolve,reject)=>__requests.push({url:String(url),signal:options.signal,resolve,reject}));`});
await page.addScriptTag({content:fs.readFileSync(path.join(scripts,'writing-follow.js'),'utf8')});
await page.evaluate(role=>{
// Override origin only in test URL construction; no network request is issued.
const OriginalURL=URL;window.URL=class extends OriginalURL{constructor(url,base){super(url,base==='null'?'https://fixture.invalid':base);}};
window.follow=PlotDirectorWritingFollow.initialize({rootSelector:'#root',contentSelector:'#content',fragmentSelector:'#fragment',statusTextSelector:'#status',tabSelector:'.tab',panelSelector:'.panel',selectSelector:'.scene-select',defaultEndpoint:'/fragment',allowChapterOnly:role==='intent'});
window.load=(sceneId,chapterId=1)=>follow.loadPosition({projectId:1,bookId:2,chapterId,sceneId});
window.finish=(index,sceneId,chapterId=1)=>__requests[index].resolve({ok:true,text:async()=>`<section id="fragment" ${sceneId?`data-scene-id="${sceneId}"`:''} data-chapter-id="${chapterId}">${sceneId||chapterId}</section>`});
},role);
await page.evaluate(()=>{window.first=load(11);window.second=load(12);});
await page.evaluate(async()=>{finish(1,12);await second;finish(0,11);await first;});
assert.equal(await page.locator('#fragment').getAttribute('data-scene-id'),'12',role+' late response cannot overwrite newer scene');
assert.equal(await page.evaluate(()=>__requests[0].signal.aborted),true);
await page.evaluate(()=>{window.pending=load(13);void load(12);});
await page.evaluate(async()=>{finish(2,13);await pending;});
assert.equal(await page.locator('#fragment').getAttribute('data-scene-id'),'12',role+' returning to displayed scene cancels obsolete request');
await page.evaluate(()=>{window.older=load(14);window.newer=load(15);});
await page.evaluate(async()=>{__requests[3].reject(new Error('old failure'));await older;});
assert.equal(await page.locator('#status').textContent(),'Updating',role+' old failure cannot replace newest loading state');
await page.evaluate(async()=>{finish(4,15);await newer;});
assert.equal(await page.locator('#fragment').getAttribute('data-scene-id'),'15');
if(role==='intent'){
await page.evaluate(()=>{window.chapter=load(null,2);});
await page.evaluate(async()=>{finish(5,null,2);await chapter;});
assert.equal(await page.locator('#fragment').getAttribute('data-scene-id'),null);
await page.evaluate(()=>{window.returnScene=load(15,2);});
await page.evaluate(async()=>{finish(6,15,2);await returnScene;});
assert.equal(await page.locator('#fragment').getAttribute('data-scene-id'),'15','chapter-only intent does not retain stale scene dedup identity');
}
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);const target=new URL(url,'https://fixture.invalid');return{location:{pathname:target.pathname,search:target.search,assign(value){const next=new URL(value,'https://fixture.invalid');this.pathname=next.pathname;this.search=next.search;}},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')});
await page.evaluate(async()=>{
const NativeURL=URL;window.URL=class extends NativeURL{constructor(url,base){super(url,base==='null'?'https://fixture.invalid':base);}};
await PlotDirectorWritingWorkspace.registerWindow({projectID:1,bookID:2,writingRole:'Launcher'});
window.__started=await PlotDirectorWritingWorkspace.startWorkspace({projectID:1,bookID:2});
});
assert.equal(await page.evaluate(()=>__started.ok),true);assert.deepEqual(await page.evaluate(()=>__opened),['PlotDirectorContext','PlotDirectorIntent']);
await page.evaluate(()=>{PlotDirectorWritingWorkspace.openRoleWindow('Context',{projectID:1,bookID:2});PlotDirectorWritingWorkspace.openRoleWindow('Context',{projectID:1,bookID:3});});assert.equal(await page.evaluate(()=>__opened.length),2,'Repeated launches and book changes reuse one Context window');
console.log('PASS fresh Writer launcher opens both missing role windows without undeclared currentRole');await page.close();
}finally{await browser.close();}
})().catch(error=>{console.error(error);process.exitCode=1});

View File

@ -1,48 +0,0 @@
// Explicit live Development protocol verification. Requires guarded synthetic account/snapshot files.
// No AI calls, manuscript imports, Windows automation or real Word COM operations.
const {chromium}=require('playwright');
const fs=require('node:fs'),crypto=require('node:crypto'),assert=require('node:assert/strict');
const base='https://dev.plotdirector.com';let step='validate fixture files';
(async()=>{
const [identityPath,scopePath]=process.argv.slice(2);
assert.ok(identityPath?.startsWith('/tmp/pd-dev-browser-')&&scopePath?.startsWith('/tmp/pd-context-'));
assert.equal(fs.statSync(identityPath).mode&0o077,0);
const identity=JSON.parse(fs.readFileSync(identityPath)),scope=JSON.parse(fs.readFileSync(scopePath));
assert.equal(identity.Database,'PlotDirector_Development');assert.equal(identity.UserID,scope.User);assert.match(identity.Email,/^pwa-browser-.*@example\.invalid$/);assert.equal(scope.SceneStarts.length,2);
const browser=await chromium.launch();let keepalive;
try{
const context=await browser.newContext();await context.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8')}));
const page=await context.newPage();let navigationForm;page.on('request',request=>{if(request.url().endsWith('/Writing/Context/Navigate')&&request.method()==='POST')navigationForm=request.postData();});step='normal login';await page.goto(base+'/Account/Login');await page.locator('[name=Email]').fill(identity.Email);await page.locator('[name=Password]').fill(identity.Password);await Promise.all([page.waitForURL(u=>u.pathname!='/Account/Login'),page.locator('form:has(input[name=Password]) button[type=submit]').click()]);
step='browser-approved persistent pairing';const verifier=crypto.randomBytes(32).toString('base64url'),connectionId=crypto.randomUUID();
let response=await page.request.post(base+'/api/native-companion/pair',{data:{challenge:crypto.createHash('sha256').update(verifier).digest('hex').toUpperCase(),persistent:true,connectionId,deviceName:'Atlas Context protocol verification'}});assert.equal(response.status(),200);const {code}=await response.json();
await page.goto(base+'/native-companion/authorize?code='+code);const csrf=await page.locator('[name=__RequestVerificationToken]').inputValue();response=await page.request.post(base+'/native-companion/authorize',{form:{code,retainImport:'true',__RequestVerificationToken:csrf}});assert.equal(response.status(),200);
response=await page.request.post(base+'/api/native-companion/token',{data:{code,verifier}});assert.equal(response.status(),200);const tokens=await response.json();const headers={Authorization:'Bearer '+tokens.accessToken};
let sequence=0,cursor=scope.SceneStarts[0],revision=1;const commands=[];
const presencePath=(instance=scope.Instance,session=scope.Session)=>base+`/api/native-companion/instances/${instance}/documents/${session}/presence`;
async function heartbeat(){const r=await page.request.post(presencePath(),{headers,data:{bookId:scope.Book,manuscriptId:scope.Manuscript,revision,sequence:++sequence,documentTitle:'Synthetic context manuscript.docx',wordRunning:true,wordAvailable:true,wordSaved:true,canCapture:true,canParagraphSync:true,active:true,cursorStart:cursor}});assert.equal(r.status(),200,'Native registration');const data=await r.json();if(data.navigation)commands.push(data.navigation);return data;}
step='live paragraph cursor resolution';let presence=await heartbeat();assert.equal(presence.sceneId,scope.Scenes[0]);assert.equal(presence.chapterId,scope.Chapters[0]);
keepalive=setInterval(()=>void heartbeat().catch(()=>{}),10000);
step='direct Context and compiled fragments';await page.goto(base+`/native-companion/workspace?bookId=${scope.Book}&instanceId=${scope.Instance}&sessionId=${scope.Session}&view=context`);await page.waitForURL(u=>u.pathname==='/Writing/Context');await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${scope.Scenes[0]}"]`);assert.equal(await page.locator('iframe').count(),0);assert.equal(await page.locator('.pd-ribbon,.pd-titlebar').count(),0);await page.evaluate(()=>window.originalContextShell=document.querySelector('[data-writing-context]'));
await page.click('[data-writing-context-tab=people]');
step='passive cursor following across chapters';for(const next of [scope.SceneStarts[1],scope.SceneStarts[0]]){cursor=next;await heartbeat();await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${next===scope.SceneStarts[0]?scope.Scenes[0]:scope.Scenes[1]}"]`);}for(let i=0;i<5;i++)await heartbeat();assert.equal(commands.length,0,'Passive presence and scene changes cannot queue Word selection');await page.locator('[data-writing-context-scene-select]').press('End');
await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${scope.Scenes[1]}"]`);await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('Navigation requested'));
step='existing native navigation command';await heartbeat();assert.equal(commands.length,1);assert.equal(commands[0].kind,'navigate');assert.equal(commands[0].sessionId.toLowerCase(),scope.Session.toLowerCase());assert.equal(commands[0].revision,1);assert.equal(commands[0].chapter.start,scope.SceneStarts[1]);
assert.equal(commands[0].id,new URLSearchParams(navigationForm).get('navigationId'));const acceptedNavigationForm=navigationForm;
cursor=commands[0].chapter.start;presence=await heartbeat();assert.equal(presence.sceneId,scope.Scenes[1]);assert.equal(presence.chapterId,scope.Chapters[1]);await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent==='Following Word');assert.equal(commands.length,1,'Following a cursor must not command Word back');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());
step='duplicate explicit request after acknowledgement';response=await page.request.post(base+'/Writing/Context/Navigate',{form:Object.fromEntries(new URLSearchParams(acceptedNavigationForm))});assert.equal(response.status(),200);assert.ok(!(await heartbeat()).navigation);assert.equal(commands.length,1,'Retried explicit navigation is not reexecuted');
step='stale Word revision refusal';revision=2;await heartbeat();const body={bookId:String(scope.Book),sceneId:String(scope.Scenes[0]),instanceId:scope.Instance,sessionId:scope.Session,__RequestVerificationToken:await page.locator('[data-writing-context] [name=__RequestVerificationToken]').inputValue()};response=await page.request.post(base+'/Writing/Context/Navigate',{form:body});assert.equal(response.status(),409);assert.match((await response.json()).message,/mapping|synchronise/i);assert.ok(!(await heartbeat()).navigation);
revision=1;await page.request.delete(presencePath(),{headers});sequence=0;await heartbeat();
step='actual saved metrics and empty plot data';await page.click('[data-writing-context-tab=metrics]');await page.waitForSelector('[data-writing-component=metrics][data-loaded=true]');assert.ok(await page.locator('[data-context-metric-select] option').count()>0);await page.click('[data-writing-context-tab=plots]');await page.waitForSelector('[data-writing-component=plots][data-loaded=true]');assert.ok(await page.getByText('No saved plot-line developments are available for this book.').isVisible());
step='disconnect and saved navigation';clearInterval(keepalive);keepalive=null;await page.request.delete(presencePath(),{headers});await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('disconnected'),null,{timeout:25000});await page.click('[data-writing-context-tab=people]');await page.locator('[data-writing-context-scene-select]').press('Home');await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${scope.Scenes[0]}"]`);
step='reconnect actual cursor wins';cursor=scope.SceneStarts[1];sequence=0;presence=await heartbeat();assert.equal(presence.sceneId,scope.Scenes[1]);await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${scope.Scenes[1]}"]`);assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());assert.ok(await page.evaluate(()=>originalContextShell===document.querySelector('[data-writing-context]')));assert.equal(commands.length,1,'Reconnect cannot manufacture navigation commands');
step='direct existing synchronisation action and exact document selection';const syncToken=await page.locator('[data-word-sync-form] [name=__RequestVerificationToken]').inputValue();
response=await page.request.post(base+'/manuscript/paragraphs/snapshot',{headers:{'X-Requested-With':'XMLHttpRequest'},form:{bookId:String(scope.Book),instanceId:scope.Instance,sessionId:crypto.randomUUID(),__RequestVerificationToken:syncToken}});assert.equal(response.status(),409);assert.match((await response.json()).message,/selected Word document/i);
await page.click('#native-companion-status');await page.locator('[data-word-sync-button]').waitFor({state:'visible'});await page.waitForFunction(()=>!document.querySelector('[data-word-sync-button]').disabled);
const submitted=page.waitForResponse(r=>r.url().endsWith('/manuscript/paragraphs/snapshot')&&r.request().method()==='POST');await page.click('[data-word-sync-button]');response=await submitted;assert.equal(response.status(),200);const requestedSnapshot=await response.json();assert.match(requestedSnapshot.requestId,/^[0-9a-f-]{36}$/i);
const snapshotCommand=(await heartbeat()).navigation;assert.equal(snapshotCommand.kind,'paragraph-snapshot');assert.equal(snapshotCommand.id,requestedSnapshot.requestId);assert.equal(snapshotCommand.sessionId,scope.Session);assert.equal(commands.filter(c=>c.kind==='navigate').length,1);assert.ok(!(await page.locator('[data-word-sync-feedback]').textContent()).includes('accepted.'),'request alone is not acceptance');
await page.request.delete(base+'/api/native-companion/manuscript-capture/'+snapshotCommand.id,{headers});await page.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('ended without an accepted snapshot'));await page.click('[data-close-word-details]');
step='anonymous and antiforgery refusal';const bare=await browser.newContext();const unauthorised=await bare.request.get(base+`/Writing/Context/Metrics?projectId=${scope.Project}&bookId=${scope.Book}`,{maxRedirects:0});assert.ok([302,401].includes(unauthorised.status()));await bare.close();response=await page.request.post(base+'/Writing/Context/Navigate',{form:{bookId:String(scope.Book),sceneId:String(scope.Scenes[0])}});assert.equal(response.status(),400);
step='sign out test installation';await page.request.post(base+'/api/native-companion/revoke',{data:{installationId:tokens.installationId,credential:tokens.deviceSecret,connectionId,nextCredential:'',rotationId:crypto.randomUUID()}});response=await page.request.get(base+'/api/native-companion/books',{headers});assert.equal(response.status(),401);
console.log('PASS live Development: normal browser approval, real native presence and persisted paragraph mapping, direct iframe-free Context, cross-chapter explicit command at exact saved position, cursor acknowledgement without loops, stable People tab/shell, stale revision refusal, read-only metrics/plots, disconnected browsing, reconnect precedence, authentication/antiforgery and revocation. Includes repeated passive cursor observations and duplicate explicit-request refusal after acknowledgement. Protocol client only; actual Word execution remains unverified.');
}finally{if(keepalive)clearInterval(keepalive);await browser.close();}
})().catch(error=>{fs.writeFileSync('/tmp/pd-context-development-error.log',String(error.stack),{mode:0o600});console.error('FAIL Development Context verification at '+step+'; private diagnostic saved.');process.exit(1);});

View File

@ -1,59 +0,0 @@
// Real scripts in Chromium with controlled native/legacy event interleavings. No Word automation.
const {chromium}=require('playwright'),fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict');
(async()=>{const browser=await chromium.launch();try{
const page=await browser.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));
const html=`<button id="native-companion-status"><span id="native-companion-status-text">Checking Word…</span></button><main data-writing-context data-scope-book-id="12" data-scope-project-id="7" data-context-url="/Writing/Context/Scene"><span data-writing-context-status-text></span><input name="__RequestVerificationToken" value="fixture"><section data-writing-context-content></section></main>`;
const fragment=(scene)=>`<article data-writing-context-fragment data-project-id="7" data-book-id="12" data-chapter-id="${scene===22?10:11}" data-scene-id="${scene}"><nav><button data-writing-context-tab="overview">Overview</button><button data-writing-context-tab="people">People</button></nav><select data-writing-context-scene-select><option value="22" ${scene===22?'selected':''}>First</option><option value="23" ${scene===23?'selected':''}>Second</option></select><button data-writing-scene-step="${scene===22?23:22}">Next</button><div data-writing-context-panel="overview">Overview saved data</div><div data-writing-context-panel="people">People saved data</div></article>`;
let current=22,wordSaved=true,verified=true,fragmentReads=0,failStatus=false,holdStatus=false,release,reads=0,commands=0,fragmentFailure=false,fragmentConflict=false,holdFragment=false,releaseFragment;
await page.route('https://context.test/**',async r=>{const u=new URL(r.request().url());
if(u.pathname==='/')return r.fulfill({contentType:'text/html',body:html});
if(u.pathname==='/native-companion/status'){
reads++;const snapshot=current;if(holdStatus){holdStatus=false;await new Promise(resolve=>release=resolve);}
return r.fulfill(failStatus?{status:503}:{json:[{instanceId:'instance',sessionId:'session',bookId:12,chapterId:snapshot===22?10:11,sceneId:snapshot,wordAvailable:true,wordSaved,positionVerified:verified,active:true,documentTitle:'Synthetic',expires:new Date(Date.now()+45000).toISOString()}]});}
if(u.pathname==='/Writing/Context/Scene'){
fragmentReads++;assert.equal(u.searchParams.get('instanceId')||'instance','instance');assert.equal(u.searchParams.get('sessionId')||'session','session');
if(holdFragment){holdFragment=false;await new Promise(resolve=>releaseFragment=resolve);}
return r.fulfill(fragmentConflict?{status:409}:fragmentFailure?{status:503}:{contentType:'text/html',body:fragment(Number(u.searchParams.get('sceneId')))});}
if(u.pathname==='/Writing/Context/Navigate'){commands++;assert.ok(new URLSearchParams(r.request().postData()).get('navigationId'));return r.fulfill({json:{message:'Navigation requested in Word.'}});}
return r.fulfill({json:{known:false}});
});
await page.goto('https://context.test/');await page.evaluate(fragment=>document.querySelector('[data-writing-context-content]').innerHTML=fragment,fragment(22));
await page.evaluate(()=>{window.hubHandlers={};window.focusCalls=0;window.focus=()=>focusCalls++;window.intervals=[];window.setInterval=f=>(intervals.push(f),intervals.length);window.signalR={HubConnectionBuilder:class{withUrl(){return this}withAutomaticReconnect(){return this}build(){return{state:'Disconnected',on:(name,fn)=>hubHandlers[name]=fn,onreconnected:()=>{},start:async()=>{},stop:async()=>{}}}}};window.PlotDirectorWritingWorkspace={watchWorkspace:async()=>null};});
for(const name of ['story-position','writing-follow','writing-context','native-companion-status']){
let script=fs.readFileSync(path.resolve(__dirname,'../../PlotLine/wwwroot/js/'+name+'.js'),'utf8');
if(process.env.PD_SCRIPT_BASE)script=await(await page.request.get(process.env.PD_SCRIPT_BASE+'/js/'+name+'.js')).text();
await page.addScriptTag({content:script});
}
const scene=async id=>page.waitForFunction(id=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId===String(id),id);
const pulse=()=>page.evaluate(()=>intervals[0]());await page.waitForFunction(()=>document.querySelector('#native-companion-status').dataset.connected==='true');
await page.click('[data-writing-context-tab=people]');await page.evaluate(()=>{window.elementFocusCalls=0;const original=HTMLElement.prototype.focus;HTMLElement.prototype.focus=function(...args){elementFocusCalls++;return original.apply(this,args);};});
current=23;await pulse();await scene(23);assert.equal(commands,0);assert.equal(await page.evaluate(()=>elementFocusCalls),0,'passive following must not refocus any browser control');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());
// A delayed legacy broadcast must not override a live native cursor scene.
await page.evaluate(()=>document.dispatchEvent(new CustomEvent('plotdirector:story-position-changed',{detail:{projectId:7,bookId:12,chapterId:10,sceneId:22,source:'WordCompanion'}})));
await page.waitForTimeout(120);assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'23','stale legacy position cannot replace live native scene');
const repeated=fragmentReads;
for(let i=0;i<8;i++)await pulse();await page.waitForTimeout(60);assert.equal(commands,0);assert.equal(await page.evaluate(()=>focusCalls),0);assert.equal(fragmentReads,repeated,'unchanged native scenes do not recompute context fragments');
// Status failure must dispatch disconnection, not throw ReferenceError for an out-of-scope leases variable.
failStatus=true;await pulse();await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('disconnected'));
failStatus=false;current=22;await pulse();await scene(22);assert.deepEqual(errors,[]);
// SignalR invalidation during an HTTP read must be drained, not discarded until a 15-second poll.
holdStatus=true;await pulse();await page.waitForFunction(()=>document.querySelector('#native-companion-status').dataset.connected==='true');while(!release)await page.waitForTimeout(10);
const before=reads;current=23;await page.evaluate(()=>hubHandlers.NativePresenceChanged());await page.waitForTimeout(300);release();await scene(23);assert.ok(reads>before,'pending invalidation triggers a trailing authoritative read');
// Failed fragment read can recover on an unchanged authoritative scene, without navigating Word.
fragmentFailure=true;current=22;await pulse();await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent==='Context unavailable');fragmentFailure=false;await pulse();await scene(22);assert.equal(commands,0);
// Programmatic scene changes can browse saved information but may not command Word.
await page.selectOption('[data-writing-context-scene-select]','23');await scene(23);assert.equal(commands,0);
// Genuine keyboard action requests exactly one command; its acknowledgement is passive.
await page.locator('[data-writing-context-scene-select]').press('Home');await scene(22);await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('Navigation requested'));assert.equal(commands,1);
current=22;for(let i=0;i<4;i++)await pulse();await page.waitForTimeout(60);assert.equal(commands,1);assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());assert.deepEqual(errors,[]);
// A pending/unsaved mapping must invalidate an older in-flight scene response.
holdFragment=true;current=23;await pulse();while(!releaseFragment)await page.waitForTimeout(10);
wordSaved=false;await pulse();await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('Save Word'));
releaseFragment();await page.waitForTimeout(150);assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'22','late fragment cannot restore an earlier cursor after native mapping becomes pending');
wordSaved=true;verified=false;await pulse();await page.waitForTimeout(60);assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'22','unverified claimed native scene cannot replace saved context');
verified=true;fragmentConflict=true;await pulse();await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('awaiting verification'));assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'22');fragmentConflict=false;await pulse();await scene(23);assert.equal(commands,1);
console.log('PASS pending native response cancellation, unverified mapping refusal, exact-session query parameters and no recomputation for repeated unchanged scenes');
console.log('PASS native/legacy race, cross-chapter cursor following, repeated presence without commands/focus, status failure recovery, in-flight invalidation, unchanged-scene fragment retry, trusted explicit navigation and acknowledgement without feedback; simulated Chromium protocol, not Word');
// Native safety source guard: ordinary polling must never invalidate the ribbon or select a range.
const adapter=fs.readFileSync(path.resolve(__dirname,'../../PlotDirector.NativeCompanion/Vsto/WordAdapter.cs'),'utf8');const observation=adapter.split('private void CaptureSelection()')[1].split('private int DocumentEnd')[0];assert.doesNotMatch(observation,/invalidateRibbon\(|\.Select\(/);assert.match(adapter,/command.Kind=="navigate"/);console.log('PASS native source invariant: selection observation contains no ribbon invalidation or range selection (not runtime Word proof)');
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);});

View File

@ -1,36 +0,0 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),path=require('node:path');
const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
(async()=>{const browser=await chromium.launch();try{
for(const width of [400,760,1600]) for(const theme of ['modern-light','modern-dark','warm-light','warm-dark']){
const page=await browser.newPage({viewport:{width,height:850}});let commands=0,fullPage=false;
await page.route('**/Writing/Context/Navigate',async route=>{commands++;assert.equal(route.request().method(),'POST');await route.fulfill({json:{message:'Navigation requested in Word. Cursor confirmation is still pending.'}});});
await page.route('**/Writing/Context/Scene?*',async route=>{
if(fullPage){await route.fulfill({contentType:'text/html',body:'<!doctype html><html><body><nav>Timeline shell must never appear here</nav></body></html>'});return;}
const id=new URL(route.request().url()).searchParams.get('sceneId');await new Promise(r=>setTimeout(r,80));
const response=await route.fetch({url:base+'/writing-desk-fixture/context?fragment=true&sceneId='+id});await route.fulfill({response});
});
await page.goto(base+'/writing-desk-fixture/context');
await page.evaluate(theme=>{
document.documentElement.dataset.appTheme=theme;document.documentElement.dataset.theme=theme.endsWith('dark')?'dark':'light';
const root=document.querySelector('main');root.dataset.writingContext='';root.dataset.contextUrl='/Writing/Context/Scene';root.dataset.scopeProjectId='7';root.dataset.scopeBookId='12';
const host=document.createElement('section');host.dataset.writingContextContent='';while(root.firstChild)host.append(root.firstChild);root.append(host);
const status=document.createElement('p');status.dataset.writingContextStatusText='';root.prepend(status);const input=document.createElement('input');input.type='hidden';input.name='__RequestVerificationToken';input.value='fixture';root.append(input);window.originalWritingShell=root;window.focusCalls=0;window.focus=()=>focusCalls++;
},theme);
for(const script of ['story-position','writing-follow','writing-context'])await page.addScriptTag({path:path.resolve(__dirname,'../../PlotLine/wwwroot/js/'+script+'.js')});
assert.equal(await page.locator('iframe').count(),0);
await page.click('[data-writing-context-tab=people]');await page.locator('[data-writing-context-tab=people]').press('ArrowRight');assert.ok(await page.locator('[data-writing-context-panel=relationships]').isVisible());await page.locator('[data-writing-context-tab=relationships]').press('ArrowLeft');await page.locator('[data-writing-context-scene-select]').press('End');
await page.waitForFunction(()=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId==='23');await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('Navigation requested'));
assert.equal(commands,1);assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-chapter-id'),'11');
assert.ok(await page.evaluate(()=>originalWritingShell===document.querySelector('[data-writing-context]')));
await page.click('[data-writing-scene-step="22"]');await page.waitForFunction(()=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId==='22');await page.waitForTimeout(30);assert.equal(commands,2);
const beat=async id=>page.evaluate(id=>window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:[{instanceId:'instance',sessionId:'document',bookId:12,chapterId:id===23?11:10,sceneId:id,active:true,wordAvailable:true,wordSaved:true,expires:new Date(Date.now()+45000).toISOString()}]})),id);
await page.evaluate(()=>{const spacer=document.createElement('div');spacer.style.height='1400px';document.body.append(spacer);window.scrollTo(0,150);});await page.waitForFunction(()=>Math.abs(scrollY-150)<=2);
await beat(23);await page.waitForFunction(()=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId==='23');assert.equal(commands,2,'Word follow must not command Word back');assert.ok(Math.abs(await page.evaluate(()=>scrollY)-150)<=2,`Word scene changes retain page scroll where space permits: ${width} ${theme}, actual ${await page.evaluate(()=>scrollY)}`);assert.equal(await page.evaluate(()=>focusCalls),0,'cursor following must not focus the browser window');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());
await page.evaluate(()=>window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:[]})));await page.click('[data-writing-scene-step="22"]');await page.waitForFunction(()=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId==='22');
await beat(23);await page.waitForFunction(()=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId==='23');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible(),'reconnection follows actual Word scene without resetting view');
const before=commands;fullPage=true;await page.locator('[data-writing-context-scene-select]').press('Home');await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent==='Context unavailable');assert.equal(await page.locator('nav').filter({hasText:'Timeline shell must never appear here'}).count(),0);assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'23');assert.equal(commands,before,'invalid fragments cannot trigger Word navigation');
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false,`overflow ${width} ${theme}`);
await page.close();
}
console.log('PASS actual Razor fragments, stable shell, cross-chapter Previous/Next and jump, tab persistence, Word follow without feedback, disconnect/reconnect and full-page response rejection at three widths in four themes');
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);});

View File

@ -1,11 +0,0 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),path=require('node:path');
(async()=>{const browser=await chromium.launch();try{const page=await browser.newPage({viewport:{width:1440,height:950}}),base='http://127.0.0.1:5238';let reads=0;
await page.route('**/Writing/Context/PlotLines?*',async r=>{reads++;await r.fulfill({response:await r.fetch({url:base+'/writing-context-component/plots?large=true'})});});
await page.route('**/Writing/Context/Scene?*',async r=>r.fulfill({response:await r.fetch({url:base+'/writing-desk-fixture/context?fragment=true&large=true&sceneId='+new URL(r.request().url()).searchParams.get('sceneId')})}));
await page.goto(base+'/writing-desk-fixture/context?large=true');await page.evaluate(()=>{const root=document.querySelector('main');root.dataset.writingContext='';root.dataset.contextUrl='/Writing/Context/Scene';root.dataset.scopeProjectId='7';root.dataset.scopeBookId='12';const host=document.createElement('section');host.dataset.writingContextContent='';while(root.firstChild)host.append(root.firstChild);root.append(host);});
for(const script of ['story-position','writing-follow','writing-context-plots','writing-context-components','writing-context'])await page.addScriptTag({path:path.resolve(__dirname,'../../PlotLine/wwwroot/js/'+script+'.js')});
const began=Date.now();await page.click('[data-writing-context-tab=plots]');await page.waitForSelector('[data-writing-component=plots][data-loaded=true]');const load=Date.now()-began;assert.ok(await page.locator('[data-plot-scene-strip] button').count()<=7);assert.equal(await page.locator('[data-plot-line]').count(),10);assert.equal(await page.locator('[data-context-chart-scene]').count(),0);await page.evaluate(()=>window.originalPlot=document.querySelector('[data-writing-component=plots]'));
const changes=Date.now();for(const scene of [100,200,300,421]){await page.evaluate(scene=>window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:[{instanceId:'large',sessionId:'large',bookId:12,chapterId:10+Math.floor((scene-22)/8),sceneId:scene,active:true,wordAvailable:true,wordSaved:true,expires:new Date(Date.now()+45000).toISOString()}]})),scene);await page.waitForFunction(scene=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId===String(scene),scene);}
assert.equal(reads,1);assert.ok(await page.evaluate(()=>originalPlot===document.querySelector('[data-writing-component=plots]')));assert.equal(await page.locator('[data-plot-scene="399"]').getAttribute('aria-current'),'location');assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false);
console.log(`PASS 400-scene, 10-line actual Razor browser fixture: initial chart ${load}ms; four scene changes ${Date.now()-changes}ms; one chart read, retained panel/compact scene strip and no page overflow. Chromium fixture measurements only, not Word performance.`);
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);});

View File

@ -1,22 +0,0 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs');
const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
(async()=>{const browser=await chromium.launch();try{
for(const embedded of [false,true])for(const installed of [false,true]){
const page=await browser.newPage({viewport:{width:1280,height:900}});await page.addInitScript(installed=>{if(installed){const match=window.matchMedia.bind(window);window.matchMedia=query=>query==='(display-mode: standalone)'?{matches:true,media:query,addEventListener(){},removeEventListener(){},addListener(){},removeListener(){}}:match(query);}},installed);
let snapshotRevision=1,syncFailure=false,syncRequests=0,repairRequests=0,modern=false,transferState='pending';
await page.route('**/manuscript/paragraphs/snapshot',async r=>{syncRequests++;const body=new URLSearchParams(r.request().postData());assert.equal(body.get('bookId'),'12');assert.equal(body.get('instanceId'),'fixture');assert.equal(body.get('sessionId'),'doc');assert.ok(body.get('__RequestVerificationToken'));await r.fulfill({status:syncFailure?409:200,json:{requestId:'11111111-1111-4111-8111-111111111111',message:syncFailure?'Word is unavailable; saved snapshot preserved.':'Word snapshot requested; awaiting acceptance.'}});});
await page.route('**/manuscript/paragraphs/repair',async r=>{repairRequests++;assert.equal(new URLSearchParams(r.request().postData()).get('bookId'),'12');await r.fulfill({json:{requestId:'22222222-2222-4222-8222-222222222222',message:'Chapter repair requested.'}});});
await page.route('**/native-companion/status',r=>r.fulfill({json:[{instanceId:'fixture',sessionId:'doc',bookId:12,chapterId:10,sceneId:22,active:true,wordAvailable:true,wordSaved:true,canParagraphSync:true,canChapterSync:modern,snapshotRevision,mappingCurrent:true,paragraphTransfer:repairRequests?{requestId:'22222222-2222-4222-8222-222222222222',state:transferState,kind:'chapter',message:'Chapter repair '+transferState}:syncRequests?{requestId:'11111111-1111-4111-8111-111111111111',state:transferState}:null,documentTitle:'Synthetic manuscript.docx',updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString()}]}));
await page.route('**/Writing/Context/Scene?*',async r=>r.fulfill({response:await r.fetch({url:base+'/writing-desk-fixture/context?fragment=true&sceneId='+new URL(r.request().url()).searchParams.get('sceneId')})}));
await page.route(/\/Writing\/Context\/(PlotLines|Metrics|Map)\?/,async r=>{const url=new URL(r.request().url()),kind=url.pathname.endsWith('PlotLines')?'plots':url.pathname.endsWith('Metrics')?'metrics':'map';await r.fulfill({response:await r.fetch({url:base+'/writing-context-component/'+kind+url.search})});});
const response=await page.goto(base+'/Writing/Context?bookId=12'+(embedded?'&embedded=true':''));assert.equal(response.status(),200);
await page.waitForSelector('[data-writing-context-fragment][data-scene-id="22"]');assert.equal(await page.locator('iframe').count(),0);assert.equal(await page.locator('#native-companion-status').count(),1);await page.click('#native-companion-status');assert.ok(await page.locator('#writing-connection-details').isVisible());assert.ok(await page.getByRole('option',{name:'Synthetic manuscript.docx · active in Word'}).count());await page.locator('[data-word-sync-button]').click();await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('requested'));assert.equal(syncRequests,1);assert.ok(await page.locator('[data-word-sync-button]').isDisabled(),'request is not completion');snapshotRevision=2;await page.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await page.waitForTimeout(100);assert.ok(!(await page.locator('[data-word-sync-feedback]').textContent()).includes('accepted'),'an unrelated revision is not snapshot acceptance');transferState='accepted';await page.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('accepted'));assert.ok(await page.locator('[data-word-sync-button]').isEnabled());syncFailure=true;await page.locator('[data-word-sync-button]').click();await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('unavailable'));assert.equal(syncRequests,2);assert.ok(await page.locator('[data-word-repair-button]').isDisabled(),'legacy add-in must not receive chapter commands');modern=true;transferState='pending';await page.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await page.waitForFunction(()=>!document.querySelector('[data-word-repair-button]').disabled);await page.locator('[data-word-repair-button]').click();await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('repair pending'));assert.equal(repairRequests,1);transferState='accepted';await page.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('repair accepted'));assert.equal(snapshotRevision,2,'metadata-only chapter acceptance does not need a new global prose revision');await page.click('[data-close-word-details]');
await page.click('[data-writing-context-tab=people]');await page.selectOption('[data-writing-context-scene-select]','23');await page.waitForSelector('[data-writing-context-fragment][data-scene-id="23"]');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());assert.equal(await page.locator('iframe').count(),0);
await page.click('#native-companion-status');await page.click('[data-word-return-to-current]');await page.waitForSelector('[data-writing-context-fragment][data-scene-id="22"]');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());
if(embedded)assert.equal(await page.locator('.pd-application-header').count(),0,'dedicated workspace has no normal ribbon');
await page.evaluate(()=>window.dispatchEvent(new StorageEvent('storage',{key:'plotdirector.applicationTheme',newValue:'warm-dark'})));await page.waitForFunction(()=>document.documentElement.dataset.appTheme==='warm-dark'&&document.documentElement.dataset.bsTheme==='dark');
if(process.env.PD_SCREENSHOT_DIR&&embedded&&!installed){fs.mkdirSync(process.env.PD_SCREENSHOT_DIR,{recursive:true});for(const tab of ['plots','metrics','maps']){await page.click('[data-writing-context-tab='+tab+']');await page.waitForFunction(tab=>document.querySelector('[data-writing-context-panel='+tab+'] [data-writing-component]').dataset.loaded==='true',tab);await page.screenshot({path:process.env.PD_SCREENSHOT_DIR+'/'+tab+'-warm-dark.png',fullPage:true});}}
await page.close();
}
console.log('PASS full compiled Context page, compact connection dialog/document selection, live native event path, fragment navigation and People tab in browser/PWA and dedicated-window layouts; no iframe');
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);});

View File

@ -1,2 +0,0 @@
const {chromium}=require('playwright'),assert=require('node:assert/strict'),path=require('path');
(async()=>{const browser=await chromium.launch();try{for(const role of ['context','intent'])for(const width of [400,760,1440])for(const theme of ['modern-light','modern-dark','warm-light','warm-dark']){const page=await browser.newPage({viewport:{width,height:1000}});const response=await page.goto(`http://127.0.0.1:5238/writing-desk-fixture/${role}`);assert.equal(response.status(),200);await page.evaluate(({role,theme})=>{document.documentElement.setAttribute('data-app-theme',theme);document.documentElement.setAttribute('data-theme',theme.endsWith('dark')?'dark':'light');const main=document.querySelector('main');main.setAttribute('data-writing-'+role,'');main.dataset.followMode='snapshot';const wrap=document.createElement('div');wrap.setAttribute('data-writing-'+role+'-content','');while(main.firstChild)wrap.append(main.firstChild);main.append(wrap);},{role,theme});await page.addScriptTag({path:path.resolve(__dirname,'../../PlotLine/wwwroot/js/writing-follow.js')});await page.addScriptTag({path:path.resolve(__dirname,`../../PlotLine/wwwroot/js/writing-${role}.js`)});assert.ok(await page.getByText('A deliberately long scene title for a narrow reference screen',{exact:true}).count());assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false,`${role} overflow ${width} ${theme}`);if(role==='context'){assert.ok(await page.getByText('People at this point',{exact:true}).isVisible());assert.ok(await page.getByText('No participants saved for this scene.',{exact:true}).isVisible());await page.click('[data-writing-context-tab="place"]');assert.equal(await page.locator('[data-writing-context-panel="place"]').isVisible(),true);}else{await page.click('[data-writing-intent-tab="evidence"]');assert.equal(await page.locator('[data-intent-assessment]').isVisible(),true);assert.ok(await page.getByText('Edit intentions and objective completion',{exact:true}).isVisible());}await page.close();}const empty=await browser.newPage();await empty.goto('http://127.0.0.1:5238/writing-desk-fixture/context?empty=true');assert.ok(await empty.getByText('No current Word scene',{exact:true}).isVisible());const evidence=await browser.newPage();await evidence.goto('http://127.0.0.1:5238/writing-desk-fixture/evidence');assert.ok(await evidence.getByText('Evidence matches the saved prose and plan.',{exact:false}).isVisible());assert.equal(await evidence.locator('[data-intent-decision]').count(),4);await evidence.goto('http://127.0.0.1:5238/writing-desk-fixture/evidence?stale=true');assert.ok(await evidence.getByText('Out of date',{exact:false}).isVisible());assert.equal(await evidence.locator('[data-intent-decision]').count(),0,'stale suggestions cannot be decided');console.log('PASS actual Context/Intent Razor, tab navigation, missing metadata, objective edit link, 400/760/1440 layouts and four light/dark/warm themes');}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);});

View File

@ -0,0 +1,21 @@
using Microsoft.AspNetCore.Mvc.Rendering;
using PlotLine.Models;
using PlotLine.Services.Context;
using PlotLine.ViewModels;
internal static class CharacterWorkspaceBrowserFixture
{
public static CharacterDetailViewModel Header(int id=5,bool viewer=false)=>new(){Project=new(){ProjectID=7,ProjectName="Character workspace qualification"},Character=new(){CharacterID=id,ProjectID=7,CharacterName=id==5?"A character with a long established canonical name":"Another established character",CharacterImportance=6,Sex="Recorded sex",BirthDate=new(1980,1,1),DefaultDescription=string.Join("\n",Enumerable.Repeat("A long canonical biography with details that must wrap naturally in the dossier.",12)),Height="Recorded height",EyeColour="Recorded eyes"},WorkspaceCanEdit=!viewer,WorkspaceCounts=new(){Relationships=3,Appearances=71,Attributes=44,Knowledge=66,Images=0,FirstSceneID=22},DisplayAge="40 years",AgeContext="At age reference scene",AgeReferenceScene=new(){SceneID=22,SceneTitle="Reference scene"},CharacterAnalysis=new(){CharacterID=id,Status="Completed",Summary="Existing persisted analysis, distinct from the author's profile."},Aliases=[new(){CharacterID=id,Alias="Recorded variant"}]};
public static CharacterRelationship Relationship(int id=9)=>new(){RelationshipTypeID=id==12?3:1,WorkspaceDefinitionCount=id==9?2:1,CharacterRelationshipID=id,ProjectID=7,CharacterAID=5,CharacterBID=id==12?7:id==10?8:6,CharacterAName="A character with a long established canonical name",CharacterBName=id==12?"Recorded colleague":id==10?"Recorded partner":"Recorded child",RelationshipTypeName=id==12?"Friend":id==10?"Spouse":"Parent",RelationshipCategoryName=id==12?"Friendship":id==10?"Romantic / Sexual":"Family",IsInitialRelationship=true,InitialRelationshipStateID=1,InitialRelationshipStateName="Established",Notes="Canonical definition notes",IsReciprocal=id==10};
public static CharacterWorkspacePage Page(int id,CharacterWorkspaceQuery q,bool viewer=false,bool removed=false,string? notes=null)
{
var p=Header(id,viewer);var page=new CharacterWorkspacePage{Profile=p,Query=q,Total=q.Tab=="overview"?0:71,Books=[new("First book","12"),new("Second book","13")],PointLabel=q.SceneID.HasValue?"First book · Ch 1 · Scene 2: Earlier point":null};
if(q.Tab=="relationships"){page.Total=3;page.Relationships=new[]{9,10,12,13}.Where(n=>!removed||n!=9).Where(n=>!q.RelationshipID.HasValue||n==q.RelationshipID).Select(n=>{var r=Relationship(n);if(n==13){r.CharacterAID=6;r.CharacterBID=5;r.CharacterAName="Recorded child";r.CharacterBName=p.Character.CharacterName;r.WorkspaceDefinitionCount=2;}if(notes!=null&&n==9)r.Notes=notes;return new CurrentRelationshipViewModel{Relationship=r,LatestEvent=q.SceneID.HasValue?new(){RelationshipStateName="Earlier recorded state",Description="Earlier canonical development"}:null};}).Where(x=>string.IsNullOrEmpty(q.Category)||(q.Category=="family")==ContextRelationshipLenses.Family(x.Relationship.RelationshipCategoryName,x.Relationship.RelationshipTypeName)).OrderBy(x=>x.Relationship.CharacterAID==id?x.Relationship.CharacterBName:x.Relationship.CharacterAName,StringComparer.OrdinalIgnoreCase).ThenBy(x=>x.Relationship.CharacterRelationshipID).ToArray();return page;}
page.Entries=q.Tab is "overview" or "gallery"?[]:Enumerable.Range((q.Page-1)*25+1,Math.Min(25,Math.Max(0,71-(q.Page-1)*25))).Select(i=>new CharacterWorkspaceEntry{ID=i,Kind=q.Tab=="appearances"?"appearances":q.Tab=="knowledge"?"knowledge":q.Tab=="history"?"relationships":q.Tab=="scenes"?"scenes":"attributes",RelationshipID=q.Tab=="history"?q.RelationshipID:null,SceneID=i,BookID=i>35?13:12,BookTitle=i>35?"Second book":"First book",ChapterNumber=(i-1)/10+1,SceneNumber=i,SceneTitle="Recorded source scene "+i,Ordinal=i,Heading=q.Tab=="scenes"?"Source scene "+i:q.Tab=="knowledge"?"Recorded asset or thread":"Recorded change "+i,State=q.Tab=="knowledge"?(i%2==0?"Knows":"Partially Knows"):"New recorded state",Previous=q.Tab=="evolution"?"Previous recorded state":null,Notes="Existing canonical detail and source. "+new string('x',220),EvidenceState=i%7==0?"Needs review":"Verified",IsPov=i%3==0}).Where(e=>string.IsNullOrEmpty(q.Search)||e.Heading!.Contains(q.Search,StringComparison.OrdinalIgnoreCase)).ToArray();return page;
}
public static CharacterWorkspaceOperation Operation(int id,string action,int relationship,int? eventId,bool protectedSource=false,string version="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")=>new(){CharacterID=id,RelationshipID=relationship,EventID=eventId,Action=action,Version=version,TypeID=1,Types=[new("Family · Parent","1"),new("Family · Child","2")],Reciprocal=false,Permanent=true,ReaderKnows=false,Record=new(){Relationship=Relationship(relationship),Version=version,EventCount=action=="definition"?0:2,OtherPairRecords=1},Event=eventId.HasValue?new(){Record=new(){RelationshipEventID=eventId.Value,CharacterRelationshipID=relationship,SceneID=22,RelationshipStateID=1,Description="One event description"},ProtectedSource=protectedSource}:null,Notes=eventId.HasValue?"One event description":"Canonical definition notes",StateID=1,Intensity=5,States=[new("Established","1"),new("Changed","2")]};
public static ContextFamilyTree Family(int focus,int[] expanded,bool removed=false)
{
var links=new List<CharacterRelationship>{Relationship(9),Relationship(10),new(){CharacterRelationshipID=1,CharacterAID=1,CharacterBID=3,RelationshipTypeName="Parent",RelationshipCategoryName="Family"},new(){CharacterRelationshipID=2,CharacterAID=3,CharacterBID=5,RelationshipTypeName="Parent",RelationshipCategoryName="Family"},new(){CharacterRelationshipID=3,CharacterAID=4,CharacterBID=5,RelationshipTypeName="Biological Parent",RelationshipCategoryName="Family"},new(){CharacterRelationshipID=4,CharacterAID=6,CharacterBID=11,RelationshipTypeName="Parent",RelationshipCategoryName="Family"},new(){CharacterRelationshipID=5,CharacterAID=12,CharacterBID=6,RelationshipTypeName="Adoptive Parent",RelationshipCategoryName="Family"},new(){CharacterRelationshipID=6,CharacterAID=13,CharacterBID=6,RelationshipTypeName="Step Parent",RelationshipCategoryName="Family"}}.Where(r=>!removed||r.CharacterRelationshipID!=9).ToArray();
var people=new[]{1,3,4,5,6,8,11,12,13}.Select(id=>new Character{CharacterID=id,ProjectID=7,CharacterName=id==5?"A character with a long established canonical name":id==6?"Recorded child":id==8?"Recorded partner":"Recorded relative "+id}).ToArray();var topology=new ContextFamilyTopology(links);var visible=topology.Visible(focus,expanded);var graph=new ContextLensGraph("family",focus,null,0,"Author reference",true,visible.Truncated,people.Where(c=>visible.People.Contains(c.CharacterID)).Select(c=>new ContextLensNode(c.CharacterID,c.CharacterName,c.BirthDate,c.IsArchived,false,null,c.IsDeceased)).ToArray(),links.Where(r=>visible.Links.Contains(r.CharacterRelationshipID)).Select(r=>new ContextLensLink(r.CharacterRelationshipID,r.CharacterAID,r.CharacterBID,r.RelationshipTypeName,r.RelationshipCategoryName,"Established",r.IsReciprocal,true,null,null,null,r.Notes,[])).ToArray());return new(topology.Key(focus),graph,visible.Branches,topology.Warnings(visible.People));
}
}

View File

@ -0,0 +1,46 @@
using PlotLine.Models;
using System.Data;using System.Text.Json;using Dapper;using Microsoft.Data.SqlClient;
internal static class CharacterWorkspaceDatabaseTests
{
public static async Task Run(string scopePath)
{
var settings=File.ReadLines("/etc/plotdirector/plotdirector.env").Single(s=>s.StartsWith("ConnectionStrings__DefaultConnection="));var builder=new SqlConnectionStringBuilder(settings[(settings.IndexOf('=')+1)..].Trim().Trim('"','\''));if(builder.InitialCatalog!="PlotDirector_Development")throw new Exception("Wrong configured database");await using var db=new SqlConnection(builder.ConnectionString);await db.OpenAsync();if(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()")!="PlotDirector_Development")throw new Exception("Wrong effective database");var scope=JsonDocument.Parse(File.ReadAllText(scopePath)).RootElement;int project=scope.GetProperty("project").GetInt32(),owner=scope.GetProperty("user").GetInt32(),scene=scope.GetProperty("scene").GetInt32(),book=scope.GetProperty("book").GetInt32(),actor=scope.GetProperty("characters")[0].GetInt32();
if(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.ProjectUserAccess a JOIN dbo.AppUser u ON u.UserID=a.UserID WHERE a.ProjectID=@project AND a.UserID=@owner AND a.IsActive=1 AND a.AccessRole=N'Owner' AND u.Email LIKE N'pwa-browser-%'",new{project,owner})!=1)throw new Exception("Explicitly disposable Development scope required");
int parent=await db.ExecuteScalarAsync<int>("SELECT TOP(1) RelationshipTypeID FROM dbo.RelationshipTypes WHERE TypeName=N'Parent'"),childType=await db.ExecuteScalarAsync<int>("SELECT TOP(1) RelationshipTypeID FROM dbo.RelationshipTypes WHERE TypeName=N'Child'"),friend=await db.ExecuteScalarAsync<int>("SELECT TOP(1) RelationshipTypeID FROM dbo.RelationshipTypes WHERE TypeName=N'Friend'"),state=await db.ExecuteScalarAsync<int>("SELECT TOP(1) RelationshipStateID FROM dbo.RelationshipStates ORDER BY SortOrder,RelationshipStateID");
void Check(bool ok,string text){if(!ok)throw new Exception(text);Console.WriteLine("PASS Development workspace SQL: "+text);}
async Task<int> NewCharacter(SqlTransaction tx)=>await db.QuerySingleAsync<int>("dbo.Character_Save",new{ProjectID=project,CharacterName="Isolated workspace regression "+Guid.NewGuid().ToString("N")},tx,commandType:CommandType.StoredProcedure);
async Task<int> Rel(SqlTransaction tx,int child,bool reciprocal=false,int? type=null,bool reverse=false)=>await db.QuerySingleAsync<int>("dbo.Relationship_Save",new{ProjectID=project,CharacterAID=reverse?child:actor,CharacterBID=reverse?actor:child,RelationshipTypeID=type??parent,IsPermanent=true,IsKnownToReader=false,IsInitialRelationship=true,InitialRelationshipStateID=state,IsReciprocal=reciprocal,Notes="Synthetic definition"},tx,commandType:CommandType.StoredProcedure);
async Task<int> Event(SqlTransaction tx,int r,string description="Synthetic event")=>await db.QuerySingleAsync<int>("dbo.RelationshipEvent_Save",new{CharacterRelationshipID=r,SceneID=scene,RelationshipStateID=state,Intensity=4,IsKnownToOtherCharacter=false,Description=description},tx,commandType:CommandType.StoredProcedure);
async Task<(string Version,int Events,int Other)> Frame(SqlTransaction tx,int r,int? e=null){using var rows=await db.QueryMultipleAsync("dbo.CharacterWorkspace_RelationshipFrame",new{CharacterID=actor,UserID=owner,RelationshipID=r,EventID=e},tx,commandType:CommandType.StoredProcedure);var row=(IDictionary<string,object>)(await rows.ReadAsync<dynamic>()).Single();await rows.ReadAsync<dynamic>();return((string)row["Version"],(int)row["EventCount"],(int)row["OtherPairRecords"]);}
async Task Change(SqlTransaction tx,int r,string version,string action,bool confirmed=true,int? e=null,string notes="Updated isolated definition",int? user=null)=>await db.ExecuteAsync("dbo.CharacterWorkspace_ChangeRelationship",new{CharacterID=actor,UserID=user??owner,RelationshipID=r,Version=version,Action=action,Confirmed=confirmed,EventID=e,Notes=notes,StateID=state,Intensity=6,Awareness=true},tx,commandType:CommandType.StoredProcedure);
async Task Case(string name,Func<SqlTransaction,Task> action){using var tx=db.BeginTransaction();try{await action(tx);}finally{try{tx.Rollback();}catch(InvalidOperationException){}}Console.WriteLine("PASS rolled back isolated case: "+name);}
await Case("parent archive retains history and restores",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);await Event(tx,r);await Event(tx,r);var frame=await Frame(tx,r);Check(frame.Events==2,"preview reports dependent scene events");await Change(tx,r,frame.Version,"archive");Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r AND IsArchived=1",new{r},tx)==1&&await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.RelationshipEvents WHERE CharacterRelationshipID=@r",new{r},tx)==2,"erroneous parent definition archives reversibly without cascading its two events");await db.ExecuteAsync("dbo.Archive_Restore",new{EntityType="Relationship",EntityID=r},tx,commandType:CommandType.StoredProcedure);Check(await db.ExecuteScalarAsync<int>("SELECT IsArchived FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r",new{r},tx)==0,"existing canonical restore reactivates the same definition and retained history");});
await Case("reciprocal single record and independent reverse",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c,true);Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE CharacterAID=@actor AND CharacterBID=@c OR CharacterAID=@c AND CharacterBID=@actor",new{actor,c},tx)==1,"canonical reciprocal flag does not create an extra reverse row");int reverse=await Rel(tx,c,false,childType,true);var frame=await Frame(tx,r);Check(frame.Other==1,"confirmation distinguishes a separately authored reverse fact");await Change(tx,r,frame.Version,"archive");Check(await db.ExecuteScalarAsync<int>("SELECT IsArchived FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@reverse",new{reverse},tx)==0,"independent reverse fact is retained, not silently cascaded");});
foreach(var type in new[]{parent,friend})await Case("definition edit "+type,async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c,false,type);var frame=await Frame(tx,r);await Change(tx,r,frame.Version,"definition");var row=await db.QuerySingleAsync<(int Type,int A,int B,bool Initial,string Notes)>("SELECT RelationshipTypeID,CharacterAID,CharacterBID,IsInitialRelationship,Notes FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r",new{r},tx);Check(row.Type==type&&row.A==actor&&row.B==c&&row.Initial&&row.Notes=="Updated isolated definition","focused definition edit preserves pair/type and family/story meaning");});
await Case("global grouped alphabetical pagination",async tx=>{
string token="Isolated workspace regression Group "+Guid.NewGuid().ToString("N");var expected=new List<(int ID,string Name)>();
for(int i=0;i<28;i++){string name=token+" "+(i==0?"alpha":i==1?"ALPHA":((char)('b'+i%22)).ToString()+i.ToString("00"));int c=await db.QuerySingleAsync<int>("dbo.Character_Save",new{ProjectID=project,CharacterName=name},tx,commandType:CommandType.StoredProcedure);expected.Add((c,name));await Rel(tx,c);}
int focus=expected[0].ID;await Rel(tx,focus,false,friend);await Rel(tx,focus,false,childType,true);for(int i=0;i<25;i++)await Rel(tx,focus);
async Task<(int Total,List<dynamic> Rows)> Read(int page=1,string? category=null,int? other=null,int definitionPage=1){using var grid=await db.QueryMultipleAsync("dbo.CharacterWorkspace_Relationships",new{CharacterID=actor,UserID=owner,Page=page,Search=token,Category=category,OtherCharacterID=other,DefinitionPage=definitionPage},tx,commandType:CommandType.StoredProcedure);int total=await grid.ReadSingleAsync<int>();await grid.ReadAsync<dynamic>();await grid.ReadAsync<dynamic>();await grid.ReadAsync<dynamic>();return(total,(await grid.ReadAsync<dynamic>()).ToList());}
var first=await Read();var second=await Read(2);var actual=first.Rows.Concat(second.Rows).Select(r=>(int)((int)r.CharacterAID==actor?r.CharacterBID:r.CharacterAID)).Distinct().ToArray();var sorted=expected.OrderBy(e=>e.Name,StringComparer.OrdinalIgnoreCase).ThenBy(e=>e.ID).Select(e=>e.ID).ToArray();Check(first.Total==28&&actual.SequenceEqual(sorted),"case-insensitive alphabetical groups span all pages, direction independent and duplicate names stable by identity");
var group=await Read(other:focus);var more=await Read(other:focus,definitionPage:2);Check(group.Total==1&&group.Rows.Count==25&&more.Rows.Count==3,"one character group retains 28 distinct definitions with bounded inner pagination");
var family=await Read(category:"family",other:focus);var story=await Read(category:"story",other:focus);Check(family.Total==1&&story.Total==1&&story.Rows.Count==1&&(string)story.Rows[0].RelationshipTypeName=="Friend","family/story filters classify individual definitions, including one pair in both categories");
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE ProjectID=@project AND (CharacterAID=@focus AND CharacterBID=@actor OR CharacterBID=@focus AND CharacterAID=@actor)",new{project,focus,actor},tx)==28,"grouping and pagination never merge or deduplicate canonical definitions");
});
async Task Structural(SqlTransaction tx,int r,string v,int type,bool reverse=false,bool? reciprocal=null)=>await db.ExecuteAsync("dbo.CharacterWorkspace_ChangeRelationship",new{CharacterID=actor,UserID=owner,RelationshipID=r,Version=v,Action="definition",Notes="Structural isolated edit",TypeID=type,ReverseDirection=reverse,Reciprocal=reciprocal},tx,commandType:CommandType.StoredProcedure);
await Case("canonical type and direction edits retain record",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);await Structural(tx,r,frame.Version,childType,true);var row=await db.QuerySingleAsync<(int Type,int A,int B)>("SELECT RelationshipTypeID,CharacterAID,CharacterBID FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r",new{r},tx);Check(row.Type==childType&&row.A==c&&row.B==actor,"canonical family type/direction edit retains exact definition ID without recreating records");});
await Case("story reciprocity edit retains one record",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c,false,friend);var frame=await Frame(tx,r);await Structural(tx,r,frame.Version,friend,reciprocal:true);Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r AND IsReciprocal=1",new{r},tx)==1,"story reciprocity is one flag on the same canonical definition");});
await Case("incompatible category rejected",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);try{await Structural(tx,r,frame.Version,friend);throw new Exception("Cross-category change accepted");}catch(SqlException ex)when(ex.Number==51022){Check(true,"cross-category type change requires full-editor review");}});
await Case("history prevents semantic rewrite",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);await Event(tx,r);var frame=await Frame(tx,r);try{await Structural(tx,r,frame.Version,childType);throw new Exception("History reinterpretation accepted");}catch(SqlException ex)when(ex.Number==51022){Check(true,"dependent history prevents unsafe structural reinterpretation");}});
await Case("family reciprocity cannot manufacture reverse parentage",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);try{await Structural(tx,r,frame.Version,parent,reciprocal:true);throw new Exception("Family reciprocity change accepted");}catch(SqlException ex)when(ex.Number==51022){Check(true,"family reciprocity changes require explicit full-editor review");}});
await Case("single event edit then remove",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);int e=await Event(tx,r),other=await Event(tx,r);var frame=await Frame(tx,r,e);await Change(tx,r,frame.Version,"event-edit",e:e,notes:"Updated one event");Check(await db.ExecuteScalarAsync<string>("SELECT Description FROM dbo.RelationshipEvents WHERE RelationshipEventID=@e",new{e},tx)=="Updated one event","one event changes without rewriting the definition");frame=await Frame(tx,r,e);await Change(tx,r,frame.Version,"event-remove",e:e);Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.RelationshipEvents WHERE RelationshipEventID=@other",new{other},tx)==1&&await db.ExecuteScalarAsync<int>("SELECT IsArchived FROM dbo.CharacterRelationships WHERE CharacterRelationshipID=@r",new{r},tx)==0,"single-event deletion leaves the other event and definition active");});
await Case("dedicated history canonical order and bounded pages",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);for(int i=0;i<28;i++)await Event(tx,r,"Recorded history "+i);async Task<List<RelationshipProgressionPoint>> Read(int page){using var grid=await db.QueryMultipleAsync("dbo.Dynamics_RelationshipEvolution",new{CharacterRelationshipID=r,Page=page},tx,commandType:CommandType.StoredProcedure);await grid.ReadAsync<CharacterRelationship>();var rows=(await grid.ReadAsync<RelationshipProgressionPoint>()).ToList();await grid.ReadAsync<dynamic>();return rows;}var first=await Read(1);var second=await Read(2);Check(first.Count==25&&second.Count==3&&first.All(e=>e.TotalRecords==28),"dedicated history pages 28 actual events as 25 + 3 with no synthetic transitions");Check(first.Concat(second).Select(e=>e.RelationshipEventID).SequenceEqual(first.Concat(second).Select(e=>e.RelationshipEventID).OrderBy(id=>id)),"same-scene developments retain stable canonical event order");});
await Case("stale dependent history",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);await Event(tx,r);try{await Change(tx,r,frame.Version,"archive");throw new Exception("Stale archive accepted");}catch(SqlException ex)when(ex.Number==51021){Check(true,"new dependent event invalidates the confirmation atomically");}});
await Case("permission enforcement",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);try{await Change(tx,r,frame.Version,"archive",user:-991);throw new Exception("Foreign user accepted");}catch(SqlException ex)when(ex.Number==51020){Check(true,"ungranted user cannot mutate a definition");}});
await Case("missing explicit confirmation",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c);var frame=await Frame(tx,r);try{await Change(tx,r,frame.Version,"archive",false);throw new Exception("Unconfirmed accepted");}catch(SqlException ex)when(ex.Number==51022){Check(true,"SQL enforces explicit destructive confirmation");}});
await Case("protected source event",async tx=>{int c=await NewCharacter(tx),r=await Rel(tx,c),e=await Event(tx,r);await db.ExecuteAsync("INSERT dbo.ManuscriptEvidenceIndex(BookID,EvidenceID,EventKind,EventID,IsPrimary,EvidenceState) VALUES(@book,NEWID(),'Relationship',@e,1,N'Verified')",new{book,e},tx);var frame=await Frame(tx,r,e);try{await Change(tx,r,frame.Version,"event-remove",e:e);throw new Exception("Protected deletion accepted");}catch(SqlException ex)when(ex.Number==51022){Check(true,"evidence-linked event is blocked before canonical deletion");}});
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Characters WHERE CharacterName LIKE N'Isolated workspace regression %'")==0,"all new character/relationship/event fixtures rolled back; no manuscript relationships changed");
}
}

View File

@ -0,0 +1,33 @@
using Microsoft.AspNetCore.SignalR;using Microsoft.Extensions.Logging.Abstractions;
using PlotLine.Data;using PlotLine.Hubs;using PlotLine.Models;using PlotLine.Services;using PlotLine.Services.Context;using PlotLine.ViewModels;
internal static class CharacterWorkspaceTests
{
public static async Task Run()
{
void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS main Character workspace: "+message);}
var role="Owner";int records=0,galleries=0,changes=0,aliases=0;bool protectedEvent=false;var version=new string('A',64);
var character=new Character{CharacterID=5,ProjectID=7,CharacterName="Canonical identity",CharacterImportance=6,AgeAtSeriesStart=25};
var definitions=new RelationshipMapData{Books=[new(){BookID=12,SortOrder=1}],Chapters=[new(){ChapterID=10,BookID=12,SortOrder=1}],Scenes=[new(){SceneID=90,ChapterID=10,SceneNumber=1},new(){SceneID=22,ChapterID=10,SceneNumber=2},new(){SceneID=2,ChapterID=10,SceneNumber=3}],Relationships=[new(){CharacterRelationshipID=9,ProjectID=7,CharacterAID=5,CharacterBID=6,RelationshipTypeName="Parent",RelationshipCategoryName="Family",IsInitialRelationship=true,InitialRelationshipStateName="Before"},new(){CharacterRelationshipID=11,ProjectID=7,CharacterAID=5,CharacterBID=7,RelationshipTypeName="Friend",RelationshipCategoryName="Friendship",StartSceneID=2}],RelationshipEvents=[new(){RelationshipEventID=1,CharacterRelationshipID=9,SceneID=22,RelationshipStateName="Now"},new(){RelationshipEventID=2,CharacterRelationshipID=9,SceneID=2,RelationshipStateName="Later",Description="Future notes"}]};
var reader=NativeWorkflowTests.Proxy<ICharacterWorkspaceReader>((name,a)=>name switch{
"Summary"=>Task.FromResult((new CharacterWorkspaceCounts{Relationships=2,Appearances=70},(IReadOnlyList<WorkspaceAgeRow>)Array.Empty<WorkspaceAgeRow>())),
"Records"=>Read((CharacterWorkspaceQuery)a![2]!),"Gallery"=>Gallery(),"Relationships"=>Task.FromResult((2,definitions)),
"Frame"=>Task.FromResult((new CharacterRelationshipFrame{Relationship=definitions.Relationships[0],Version=version,EventCount=3,OtherPairRecords=1},a![3] is int eid?new CharacterWorkspaceEvent{Record=new(){RelationshipEventID=eid,SceneID=22,CharacterRelationshipID=9},ProtectedSource=protectedEvent}:null)),
"Change"=>Changed(),_=>throw new Exception(name)});
Task<(int,IReadOnlyList<CharacterWorkspaceEntry>)> Read(CharacterWorkspaceQuery q){records++;return Task.FromResult((1,(IReadOnlyList<CharacterWorkspaceEntry>)new[]{new CharacterWorkspaceEntry{ID=1,SceneID=q.SceneID??22,Heading="Recorded source",BookTitle="Book",Kind=q.Tab}}));}
Task<(int,IReadOnlyList<CharacterImage>)> Gallery(){galleries++;return Task.FromResult((0,(IReadOnlyList<CharacterImage>)Array.Empty<CharacterImage>()));}Task Changed(){changes++;return Task.CompletedTask;}
var repo=NativeWorkflowTests.Proxy<ICharacterRepository>((n,a)=>n switch{"GetCharacterAsync"=>Task.FromResult<Character?>((int)a![0]! ==99?null:character),"GetReferenceCharacterAsync"=>Task.FromResult<Character?>(character),"ListAliasesAsync"=>Alias(),"GetLookupsAsync"=>Task.FromResult(new CharacterLookupData()),_=>throw new Exception("Unexpected eager read: "+n)});
Task<IReadOnlyList<CharacterAlias>> Alias(){aliases++;return Task.FromResult<IReadOnlyList<CharacterAlias>>(Enumerable.Range(1,75).Select(i=>new CharacterAlias{CharacterID=5,Alias="Alias "+i}).ToArray());}
var client=NativeWorkflowTests.Proxy<IClientProxy>((_,_)=>Task.CompletedTask);var clients=NativeWorkflowTests.Proxy<IHubClients>((_,_)=>client);var hub=NativeWorkflowTests.Proxy<IHubContext<NativeCompanionPresenceHub>>((_,_)=>clients);
var workspace=new CharacterWorkspace(repo,NativeWorkflowTests.Proxy<IProjectRepository>((n,_)=>n=="GetForUserAsync"?Task.FromResult<Project?>(new(){ProjectID=7,ProjectName="Author project",AccessRole=role}):throw new Exception("Unscoped project read")),NativeWorkflowTests.Proxy<IBookRepository>((_,_)=>Task.FromResult<IReadOnlyList<Book>>([])),NativeWorkflowTests.Proxy<ICurrentUserService>((_,_)=>4),NativeWorkflowTests.Proxy<ICharacterEnrichmentService>((_,_)=>Task.FromResult<CharacterEnrichmentCharacterStatus?>(null)),reader,NativeWorkflowTests.Proxy<IContextRelationshipReader>((_,_)=>throw new Exception("Unexpected graph/history read")),null!,new ContextWorkspaceNotifications(hub,NullLogger<ContextWorkspaceNotifications>.Instance),NativeWorkflowTests.Proxy<IProjectActivityService>((_,_)=>Task.CompletedTask),NativeWorkflowTests.Proxy<ICharacterService>((_,_)=>throw new Exception("Legacy full-detail service called")));
var header=await workspace.Header(5,null,CancellationToken.None);Check(records==0&&galleries==0&&aliases==0&&header.Character.CharacterName=="Canonical identity","shell loads only identity, scoped project, counts/age candidates and persisted enrichment status");
var overview=await workspace.Page(5,new(){Tab="overview"},CancellationToken.None);Check(records==1&&galleries==1&&aliases==1&&overview.Profile.Aliases.Count==50&&overview.Entries.Count<=3,"Overview is bounded; it does not load full character/project histories");
var page=await workspace.Page(5,new(){Tab="relationships",SceneID=22},CancellationToken.None);Check(page.Relationships.Single(r=>r.Relationship.CharacterRelationshipID==9).CurrentStateName=="Now"&&!page.Relationships[0].Events.Any(e=>e.SceneID==2),"selected-point relationship state and displayed history exclude future events using canonical ordering");Check(page.Relationships.Single(r=>r.Relationship.CharacterRelationshipID==11).CurrentStateName=="Not established / ended at this point","later definitions stay identifiable as author records without pretending to exist at the selected point");
Check(CharacterWorkspace.Classification(10)=="Major"&&CharacterWorkspace.Classification(6)=="Supporting"&&CharacterWorkspace.Classification(2)=="Minor"&&CharacterWorkspace.Classification(null)=="Unclassified"&&character.CharacterImportance==6,"classification labels preserve explicit values and do not reclassify existing records");
foreach(var q in new[]{new CharacterWorkspaceQuery{Tab="unknown"},new(){Tab="evolution",Page=0},new(){Tab="knowledge",Search=new string('x',121)}}){try{await workspace.Page(5,q,CancellationToken.None);throw new Exception("Invalid query accepted");}catch(ArgumentException){Check(true,"closed tabs and bounded query criteria reject invalid requests");}}
var op=await workspace.Operation(5,9,null,"archive",CancellationToken.None);Check(op.Record.EventCount==3&&op.Record.OtherPairRecords==1,"removal preview exposes retained dependencies and separate pair records");op.Confirmed=true;op.Version=new string('B',64);try{await workspace.Change(op,CancellationToken.None);throw new Exception("Stale accepted");}catch(InvalidOperationException){Check(changes==0,"stale form is rejected before canonical mutation");}
op.Version=version;op.Confirmed=false;try{await workspace.Change(op,CancellationToken.None);throw new Exception("Unconfirmed removal");}catch(ArgumentException){Check(changes==0,"destructive definition removal requires explicit confirmation");}
protectedEvent=true;var evt=await workspace.Operation(5,9,1,"event-remove",CancellationToken.None);evt.Confirmed=true;try{await workspace.Change(evt,CancellationToken.None);throw new Exception("Protected source accepted");}catch(ArgumentException){Check(changes==0,"source/review-linked event cannot be removed or orphaned by focused operations");}
role="Viewer";try{await workspace.Operation(5,9,null,"definition",CancellationToken.None);throw new Exception("Viewer edit accepted");}catch(UnauthorizedAccessException){Check(changes==0,"Viewer cannot open or execute an editing operation");}
var viewer=await workspace.Header(5,null,CancellationToken.None);Check(!viewer.WorkspaceCanEdit,"Viewer header stays read-only");try{await workspace.Header(99,null,CancellationToken.None);throw new Exception("Unknown accepted");}catch(UnauthorizedAccessException){Check(true,"unavailable character rejected before reading histories");}
}
}

View File

@ -0,0 +1,65 @@
using System.Text.Json;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging.Abstractions;
using PlotLine.Data;
using PlotLine.Hubs;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Services.Context;
using PlotLine.ViewModels;
internal static class ContextCharacterTests
{
private static void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS Context characters: "+message);}
public static async Task Run()
{
var scene=new SceneEditViewModel{SceneID=30,ChapterID=10,POVCharacterID=5,SceneTitle="Current",SceneCharacters=[new(){SceneID=30,CharacterID=5,PresenceTypeName="Present",LocationID=2},new(){SceneID=30,CharacterID=6,PresenceTypeName="Mentioned Only",LocationID=2}]};
var ordered=new[]{new Scene{SceneID=90,ChapterID=10,SceneTitle="Earlier different"},new Scene{SceneID=10,ChapterID=10,SceneTitle="Earlier duplicate"},new Scene{SceneID=30,ChapterID=10,SceneTitle="Current"},new Scene{SceneID=2,ChapterID=10,SceneTitle="Future"}};
SceneCharacter[] appearances=[new(){CharacterID=5,SceneID=90,PresenceTypeName="Present",LocationID=1},new(){CharacterID=5,SceneID=10,PresenceTypeName="Present",LocationID=2},..scene.SceneCharacters,new(){CharacterID=5,SceneID=2,PresenceTypeName="Present",LocationID=3,EmotionalState="Future emotion"}];
var model=new WritingContextDisplayViewModel{Context=new(){Position=new(7,12,10,30),Scene=scene,Narrative=new(){Chapters=[new(){ChapterID=10,BookID=12}],Scenes=ordered}}};
var projection=ContextCharacterPanels.Compose(model,[new(){CharacterID=5,CharacterName="Person",CharacterImportance=6},new(){CharacterID=6,CharacterName="Mentioned",CharacterImportance=10}],appearances,[new(){LocationID=1,LocationName="First"},new(){LocationID=2,LocationName="Now"},new(){LocationID=3,LocationName="Next"}],true);
var row=projection.Rows.Single(r=>r.Character.CharacterID==5);Check(row.Previous?.SceneID==90,"previous skips duplicate current locations using canonical order, not numeric IDs");Check(row.Now?.LocationID==2&&row.Next?.SceneID==2,"next is the nearest recorded following location, independently labelled by the view");Check(row.Emotion==null,"future emotional state never fills a current blank");Check(projection.Rows.Single(r=>r.Character.CharacterID==6).Now==null,"mentioned-only is never represented as physically present");Check(row.IsPov&&row.Classification=="Supporting","POV and canonical character importance remain independent");
Check(!ContextEditPolicy.CanEdit(new(){AccessRole="Viewer"})&&!ContextEditPolicy.CanEdit(null),"unknown/read-only access cannot edit");
var character=new CharacterEditViewModel{CharacterID=5,ProjectID=7,CharacterName="Preserve name",Aliases=["Kept alias"],CharacterImportance=8,DefaultDescription="Preserve description"};
var appearance=new SceneCharacter{SceneCharacterID=8,SceneID=22,CharacterID=5,RoleInSceneTypeID=1,PresenceTypeID=1,LocationID=2,PhysicalCondition="Preserve physical",EmotionalState="Before",KnowledgeNotes="Preserve knowledge"};
var role="Owner";var writes=0;SceneCharacterEditViewModel? savedAppearance=null;
var service=NativeWorkflowTests.Proxy<ICharacterService>((name,args)=>name switch{
"GetEditCharacterAsync"=>Task.FromResult<CharacterEditViewModel?>(JsonSerializer.Deserialize<CharacterEditViewModel>(JsonSerializer.Serialize(character))),
"GetReferenceCharacterAsync"=>Task.FromResult<Character?>(new(){CharacterID=5,ProjectID=7,CharacterName=character.CharacterName,IsDeceased=character.IsDeceased,IsArchived=true}),
"SaveLifeStatusAsync"=>SaveLife((bool?)args![1],(bool?)args[2]),
"SaveCharacterAsync"=>Save((CharacterEditViewModel)args![0]!),
"UpdateSceneCharacterAsync"=>SaveAppearance((SceneCharacterEditViewModel)args![0]!),_=>throw new Exception(name)});
Task<CharacterSaveResult> Save(CharacterEditViewModel input){writes++;character=input;return Task.FromResult(new CharacterSaveResult(5));}
Task SaveLife(bool? value,bool? expected){Check(expected==character.IsDeceased,"life-status correction passes the original canonical value for atomic comparison");writes++;character.IsDeceased=value;return Task.CompletedTask;}
Task<int> SaveAppearance(SceneCharacterEditViewModel input){writes++;savedAppearance=input;return Task.FromResult(8);}
var client=NativeWorkflowTests.Proxy<IClientProxy>((_,_)=>Task.CompletedTask);var clients=NativeWorkflowTests.Proxy<IHubClients>((_,_)=>client);var hub=NativeWorkflowTests.Proxy<IHubContext<NativeCompanionPresenceHub>>((_,_)=>clients);
var aliases=new List<CharacterAlias>{new(){CharacterAliasID=11,CharacterID=5,Alias="Kept alias",SortOrder=10}};
var repository=NativeWorkflowTests.Proxy<ICharacterRepository>((name,args)=>name switch{
"ListAliasesAsync"=>Task.FromResult<IReadOnlyList<CharacterAlias>>(aliases.ToList()),
"AddAliasAsync"=>AddAlias((string)args![1]!),
"UpdateAliasAsync"=>UpdateAlias((int)args![0]!, (string)args[1]!),
"DeleteAliasAsync"=>DeleteAlias((int)args![0]!),_=>throw new Exception(name)});
Task<int> AddAlias(string value){aliases.Add(new(){CharacterAliasID=12,CharacterID=5,Alias=value});return Task.FromResult(12);}
Task UpdateAlias(int id,string value){aliases.Single(a=>a.CharacterAliasID==id).Alias=value;return Task.CompletedTask;}
Task DeleteAlias(int id){aliases.RemoveAll(a=>a.CharacterAliasID==id);return Task.CompletedTask;}
var edit=new ContextCharacterEditing(service,
NativeWorkflowTests.Proxy<IStoryContextService>((_,_)=>Task.FromResult<StoryContextViewModel?>(new(){Position=new(7,12,10,22),Scene=new(){SceneID=22,SceneCharacters=[appearance]}})),
repository,
NativeWorkflowTests.Proxy<IWordCompanionRepository>((_,_)=>Task.FromResult<WordCompanionBookStructureResponse?>(new(){BookId=12,Chapters=[new(){ChapterId=10,Scenes=[new(){SceneId=22}]}]})),
NativeWorkflowTests.Proxy<IBookRepository>((_,_)=>Task.FromResult<Book?>(new(){BookID=12,ProjectID=7})),NativeWorkflowTests.Proxy<IProjectRepository>((_,_)=>Task.FromResult<Project?>(new(){ProjectID=7,AccessRole=role})),
NativeWorkflowTests.Proxy<ICurrentUserService>((_,_)=>7),new ContextWorkspaceNotifications(hub,NullLogger<ContextWorkspaceNotifications>.Instance));
var form=await edit.Read(12,22,5,"classification");Check(form.Value=="8"&&form.Options.Any(o=>o.Value=="8"),"existing deliberate classification survives form loading");
var old=form.Fingerprint;form.Value="6";await edit.Save(form);Check(character.CharacterImportance==6&&character.CharacterName=="Preserve name"&&character.Aliases.SequenceEqual(["Kept alias"]),"focused classification save preserves unrelated canonical identity fields");
try{form.Fingerprint=old;await edit.Save(form);throw new Exception("Stale save accepted");}catch(InvalidOperationException){Check(true,"stale drafts are rejected rather than overwriting a newer correction");}
var state=await edit.Read(12,22,5,"emotion");state.Value="After";await edit.Save(state);Check(savedAppearance?.EmotionalState=="After"&&savedAppearance.PhysicalCondition=="Preserve physical"&&savedAppearance.KnowledgeNotes=="Preserve knowledge"&&savedAppearance.LocationID==2,"focused scene-state save preserves the rest of the participation record");
var rename=await edit.Read(12,22,5,"name");rename.Value="New canonical";await edit.Save(rename);Check(character.CharacterName=="New canonical"&&character.Aliases.Contains("Preserve name"),"canonical rename retains the old spelling as an alias");
var add=await edit.Read(12,22,5,"alias-add");add.Value="New variant";await edit.Save(add);Check(aliases.Any(a=>a.Alias=="New variant"),"focused alias add reuses existing alias persistence");
var correction=await edit.Read(12,22,5,"alias:11");correction.Value="Corrected alias";await edit.Save(correction);Check(aliases.Single(a=>a.CharacterAliasID==11).Alias=="Corrected alias","individual alias correction preserves identity");
var remove=await edit.Read(12,22,5,"alias:11");remove.Value="";await edit.Save(remove);Check(aliases.All(a=>a.CharacterAliasID!=11),"explicit empty alias correction removes only the selected alias");
var nameRows=ContextNames.Compose([new(){CharacterID=5,CharacterName="Éva"},new(){CharacterID=6,CharacterName="Another"}],[new(){CharacterID=5,Alias="Éva"},new(){CharacterID=6,Alias="E\u0301VA"}]);
Check(nameRows.All(r=>r.SharedSpellings.Any()),"existing Unicode normalisation detects cross-character shared spellings including aliases");
Check(ContextNames.Compose([new(){CharacterID=5,CharacterName="Person"}],[new(){CharacterID=5,Alias="PERSON"}]).Single().SharedSpellings.Count==0,"legitimate aliases of one identity are not duplicate identities");
var life=await edit.Read(12,22,5,"life-status");Check(life.Value==null&&life.Options.Count==3,"archived relatives retain unrecorded life status and three explicit choices");life.Value="true";var beforeLife=writes;await edit.Save(life);Check(character.IsDeceased==true&&writes==beforeLife+1&&character.CharacterName=="New canonical","life-status uses a single-field save without a hydrated full-character write");
var encoded=JsonSerializer.Serialize(new Character{CharacterID=5,IsDeceased=true});Check(JsonSerializer.Deserialize<Character>(encoded)!.IsDeceased==true&&JsonSerializer.Deserialize<Character>("{\"CharacterID\":5}")!.IsDeceased==null,"canonical deceased status roundtrips and older backups remain unrecorded");
role="Viewer";var before=writes;try{await edit.Read(12,22,5,"description");throw new Exception("Viewer permitted");}catch(UnauthorizedAccessException){Check(writes==before,"read-only account cannot load an editing form or write");}
}
}

View File

@ -0,0 +1,58 @@
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services.Context;
using PlotLine.Services;
using PlotLine.ViewModels;
internal static class ContextFamilyTests
{
internal static (ContextFamilyStructure Structure,SceneEditViewModel Scene) Fixture(bool large=false,int sceneID=22,bool many=false)
{
var people=Enumerable.Range(1,80).Concat(Enumerable.Range(100,large?120:0)).Select(id=>new Character{CharacterID=id,ProjectID=7,CharacterName=id switch{5=>"Scene viewpoint",15=>"Scene sibling",22=>"Other family participant",30=>"An individual",_=>"Recorded person "+id},BirthDate=id is 7 or 8?new(2000+(id-7)*2,1,1):null,IsArchived=id==6,IsDeceased=id==6?true:null}).ToList();
var links=new List<CharacterRelationship>();int sequence=0;
void Add(int a,int b,string type,bool reciprocal=false,string category="Family")=>links.Add(new(){CharacterRelationshipID=++sequence,ProjectID=7,CharacterAID=a,CharacterBID=b,RelationshipTypeName=type,RelationshipCategoryName=category,IsReciprocal=reciprocal,IsInitialRelationship=true});
Add(1,2,"Spouse",true,"Romantic / Sexual");Add(1,3,"Parent");Add(2,3,"Parent");Add(3,4,"Spouse",true,"Romantic / Sexual");Add(3,5,"Parent");Add(4,5,"Parent");Add(3,15,"Parent");Add(5,6,"Spouse",true,"Romantic / Sexual");Add(5,10,"Former spouse",true,"Romantic / Sexual");Add(5,7,"Biological Parent");Add(6,7,"Biological Parent");Add(5,8,"Parent");Add(6,8,"Parent");Add(5,9,"Parent");Add(10,9,"Parent");Add(7,9,"Half-sibling",true);Add(11,7,"Adoptive Parent");Add(12,7,"Step Parent");Add(7,16,"Parent");Add(16,17,"Parent");
Add(21,22,"Parent");Add(21,23,"Spouse",true,"Romantic / Sexual");Add(24,21,"Parent");Add(24,25,"Parent");
Add(40,41,"Parent");Add(41,40,"Parent");Add(50,51,"Parent",true);Add(60,61,"Guardian");Add(5,22,"Friend",true,"Friendship");Add(5,30,"Partner",true,"Professional / Social");
if(large)for(int id=100;id<220;id++)Add(id==100?17:100+(id-101)/2,id,"Parent");
var scene=new SceneEditViewModel{SceneID=sceneID,ChapterID=10,SceneTitle="Family exploration fixture",POVCharacterID=sceneID==23?22:5,SceneCharacters=[..new[]{5,15,22,30,40,41}.Select(id=>new SceneCharacter{CharacterID=id,PresenceTypeName="Present"}),new(){CharacterID=25,PresenceTypeName="Present",RoleInSceneTypeName="Mentioned Only"}]};
if(many)scene.SceneCharacters=[..scene.SceneCharacters,..new[]{31,32,33,34,35,36,37,38,39,42,43,44,45,46}.Select(id=>new SceneCharacter{CharacterID=id,PresenceTypeName="Present"})];
return(new(people,links),scene);
}
public static void Run()
{
void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS Context family: "+message);}
var(data,scene)=Fixture(true);var topology=new ContextFamilyTopology(data.Links);var index=ContextFamilyExploration.Index(data,scene);
Check(index.Groups.First().IsPov&&index.DefaultKey==topology.Key(5),"POV family sorts first; scene co-occurrence does not group unrelated families");
Check(index.Groups.Single(g=>g.SceneMembers.Contains(5)).SceneMembers.Contains(15)&&topology.Key(5)!=topology.Key(22),"siblings and common recorded ancestry share one index entry; unrelated families remain separate");
Check(!index.Groups.Any(g=>g.SceneMembers.Contains(25))&&index.Groups.Single(g=>g.SceneMembers.Contains(30)).SceneMembers.Count==1,"mentioned-only is not physical; a person without genealogy remains an individual despite professional partnership");
Check(topology.Key(40)!=topology.Key(41)&&topology.Key(50)!=topology.Key(51)&&topology.Key(60)!=topology.Key(61)&&index.Warnings.Any(),"cyclic, reciprocal-parent and ambiguous guardianship records cannot merge families or establish ancestry");
var initial=topology.Visible(5,[]);Check(initial.People.Contains(15)&&!initial.People.Contains(1)&&!initial.People.Contains(100)&&!initial.People.Contains(22),"initial family is compact, includes recorded siblings, and excludes distant generations and other families");
var expand=topology.Visible(5,[3,7]);Check(expand.People.Contains(1)&&expand.People.Contains(2)&&expand.People.Contains(11)&&expand.People.Contains(12)&&expand.People.Contains(16),"node expansion reveals only recorded ancestors, adoption, step-parentage and descendants");
Check(topology.Visible(5,[]).People.SequenceEqual(initial.People)&&expand.Branches.Any(b=>b.ID==3&&b.Expanded),"collapse returns the compact tree and expansion state is explicit");
Check(data.Links.Single(r=>r.CharacterAID==11&&r.CharacterBID==7).RelationshipTypeName=="Adoptive Parent"&&data.Links.Single(r=>r.CharacterAID==6&&r.CharacterBID==7).RelationshipTypeName=="Biological Parent","adoptive and biological parentage retain separate canonical semantics");
Check(!data.Links.Any(r=>r.CharacterAID==11&&r.CharacterBID==12)&&topology.Visible(30,[]).People.SequenceEqual([30]),"no second parent or parental partnership is invented for an individual");
Check(data.Links.Any(r=>r.CharacterAID==5&&r.CharacterBID==9)&&data.Links.Any(r=>r.CharacterAID==10&&r.CharacterBID==9)&&!data.Links.Any(r=>r.CharacterAID==6&&r.CharacterBID==9),"multiple unions and half-siblings retain exact recorded parentage");
var changed=new ContextFamilyStructure(data.Seeds,data.Links.Append(new(){CharacterRelationshipID=500,CharacterAID=8,CharacterBID=22,RelationshipTypeName="Spouse",RelationshipCategoryName="Romantic / Sexual"}).ToList());Check(ContextFamilyExploration.Index(changed,scene).Groups.Count==index.Groups.Count-1,"a canonical connection correction recomputes family membership");
Check(ContextFamilyExploration.Index(data,Fixture(false,23).Scene).Groups.First().SceneMembers.Contains(22),"a new scene defaults to its new POV family independently of knowledge");
scene.POVCharacterID=25;Check(ContextFamilyExploration.Index(data,scene).Groups.First().SceneMembers.Contains(25),"POV is included independently of physical classification");
try{topology.Visible(5,[22]);throw new Exception("foreign branch accepted");}catch(ArgumentException){Check(true,"branch expansion cannot import a different family");}
var watch=System.Diagnostics.Stopwatch.StartNew();var broad=new ContextFamilyTopology(Enumerable.Range(2,4096).Select(id=>new CharacterRelationship{CharacterRelationshipID=id,CharacterAID=1,CharacterBID=id,RelationshipTypeName="Parent",RelationshipCategoryName="Family"}).ToList());var bounded=broad.Visible(1,[]);Check(bounded.Truncated&&bounded.People.Length==128&&bounded.Links.Length<=256,"a 4,097-person family remains bounded without sorting the focus neighbourhood per person");
var deep=new ContextFamilyTopology(Enumerable.Range(1,4096).Select(id=>new CharacterRelationship{CharacterRelationshipID=id,CharacterAID=id,CharacterBID=id+1,RelationshipTypeName="Parent",RelationshipCategoryName="Family"}).ToList());Check(deep.Key(4097)==1&&deep.Visible(1,[]).People.Length==2,"deep canonical ancestry uses iterative traversal and starts with only adjacent generations");Console.WriteLine($"Family 4096-edge broad/deep metadata qualification: {watch.ElapsedMilliseconds}ms");
RunAccess().GetAwaiter().GetResult();
}
static async Task RunAccess()
{
void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS Context family access: "+message);}
var(data,scene)=Fixture();var structures=0;var trees=0;int[] requested=[];var role="Viewer";
var reader=NativeWorkflowTests.Proxy<IContextFamilyReader>((name,args)=>{if(name=="Structure"){structures++;requested=((IReadOnlyList<int>)args![2]!).ToArray();return Task.FromResult(data);}trees++;var people=(IReadOnlyList<int>)args![2]!;var links=(IReadOnlyList<int>)args[3]!;return Task.FromResult(new RelationshipMapData{Books=[new(){BookID=12}],Chapters=[new(){ChapterID=10,BookID=12}],Scenes=[new(){SceneID=22,ChapterID=10}],Characters=data.Seeds.Where(c=>people.Contains(c.CharacterID)).ToList(),Relationships=data.Links.Where(r=>links.Contains(r.CharacterRelationshipID)).ToList()});});
var characters=NativeWorkflowTests.Proxy<ICharacterRepository>((_,a)=>Task.FromResult<Character?>(new(){CharacterID=(int)a![0]!,ProjectID=(int)a[0]! ==99?8:7}));var user=NativeWorkflowTests.Proxy<ICurrentUserService>((_,_)=>4);
var lenses=new ContextRelationshipLenses(NativeWorkflowTests.Proxy<IContextRelationshipReader>((_,_)=>throw new Exception("Story reader should not be used")),characters,NativeWorkflowTests.Proxy<IWordCompanionRepository>((_,_)=>Task.FromResult<WordCompanionBookStructureResponse?>(new(){BookId=12,Chapters=[new(){ChapterId=10,Scenes=[new(){SceneId=22}]}]})),NativeWorkflowTests.Proxy<IBookRepository>((_,_)=>Task.FromResult<Book?>(new(){BookID=12,ProjectID=7})),NativeWorkflowTests.Proxy<IProjectRepository>((_,_)=>Task.FromResult<Project?>(new(){ProjectID=7,AccessRole=role})),user,NativeWorkflowTests.Proxy<IStoryContextService>((_,_)=>Task.FromResult<StoryContextViewModel?>(new(){Position=new(7,12,10,22),Scene=scene})));
var service=new ContextFamilyExploration(lenses,reader,characters,user);await service.Index(12,22,CancellationToken.None);Check(requested.Contains(5)&&requested.Contains(15)&&!requested.Contains(25),"authorised index receives explicit physical seeds plus POV, not mentioned-only identities");
var tree=await service.Tree(12,22,5,[],CancellationToken.None);Check(!tree.Graph.CanEdit&&tree.Graph.Nodes.Count<=128&&tree.Graph.Nodes.All(n=>n.ID!=22),"viewer receives a bounded selected-family tree without unrelated physical participants");
var before=structures;try{await service.Tree(12,22,99,[],CancellationToken.None);throw new Exception("Foreign focus accepted");}catch(UnauthorizedAccessException){Check(before==structures,"foreign-project focus is rejected before reading family metadata");}
try{await service.Tree(12,999,5,[],CancellationToken.None);throw new Exception("Foreign scene accepted");}catch(UnauthorizedAccessException){Check(before==structures,"foreign-book scene is rejected before reading family metadata");}
var beforeTrees=trees;try{await service.Tree(12,22,5,[22],CancellationToken.None);throw new Exception("Foreign branch accepted");}catch(ArgumentException){Check(beforeTrees==trees,"branch IDs from another component cannot request a tree snapshot");}
}
}

View File

@ -0,0 +1,9 @@
using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Abstractions;using Microsoft.AspNetCore.Mvc.ModelBinding;using Microsoft.AspNetCore.Mvc.Rendering;using Microsoft.AspNetCore.Mvc.ViewEngines;using Microsoft.AspNetCore.Mvc.ViewFeatures;using Microsoft.AspNetCore.Routing;using Microsoft.Extensions.DependencyInjection;using PlotLine.Models;using PlotLine.ViewModels;using PlotLine.Services.Context;
internal static class ContextNamesBrowserFixture
{
public static ContextNamePanel Panel(NameSearchFilter? f=null){f??=new(){ProjectID=7,BookID=12,UsedScope="Book",PageSize=25};return new(7,12,true,[],new(){Project=new(){ProjectID=7,ProjectName="Fixture project"},Filter=f,Books=[new(){BookID=12,BookTitle="Current book"},new(){BookID=13,BookTitle="Other book"}],Locales=[new(){LocaleCode="en-GB",DisplayName="English (UK)"},new(){LocaleCode="fr-FR",DisplayName="French"}],Results=Enumerable.Range((Math.Max(1,f.Page)-1)*f.PageSize+1,f.PageSize).Select(i=>new NameSearchResult{GivenNameID=i,DisplayName=(f.Search??"Reference suggestion")+" "+i,NameType=f.NameType??"Canonical",LocaleDisplayName=f.LocaleCode??"English",RelatedForms="Known spelling variant",FemaleWeight=.7m,MaleWeight=.3m,UsageWeight=.5m,BirthYearFrom=1800,BirthYearTo=1900,UsedCount=f.UsedOnly==false?0:i%2,UsedSummary="Fixture participant · Current book",TotalRows=300}).ToList()});}
public static async Task Render(HttpContext context){var f=new NameSearchFilter{ProjectID=7,BookID=12,UsedScope="Book",PageSize=25};foreach(var p in typeof(NameSearchFilter).GetProperties()){var value=context.Request.Query[p.Name].ToString();if(!context.Request.Query.ContainsKey(p.Name))continue;var type=Nullable.GetUnderlyingType(p.PropertyType)??p.PropertyType;p.SetValue(f,string.IsNullOrWhiteSpace(value)&&type!=typeof(string)?null:Convert.ChangeType(value,type,System.Globalization.CultureInfo.InvariantCulture));}
var part=context.Request.RouteValues["part"]?.ToString();object model=part switch{"usage"=>new List<NameUsageDecoration>{new(){CharacterID=5,CharacterName="Fixture participant",ProjectID=7,ProjectName="Fixture project",BookID=12,BookTitle="Current book",MatchedName="Known variant",MatchType="Alias"}},"identity"=>new ContextNamePanel(7,12,true,[new(new(){CharacterID=5,ProjectID=7,CharacterName="Fixture participant"},[new(){CharacterAliasID=11,CharacterID=5,Alias="Known variant"}],[])],null),_=>Panel(f)};
var partial=part switch{"usage"=>"_ContextNameUsage","identity"=>"_ContextNameIdentity",_=>"_ContextNameResults"};var action=new ActionContext(context,new RouteData(),new ActionDescriptor());var view=context.RequestServices.GetRequiredService<ICompositeViewEngine>().GetView(null,"/Views/Writing/"+partial+".cshtml",false);using var writer=new StringWriter();await view.View!.RenderAsync(new ViewContext(action,view.View,new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model},new TempDataDictionary(context,context.RequestServices.GetRequiredService<ITempDataProvider>()),writer,new HtmlHelperOptions()));context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString());
}
}

View File

@ -0,0 +1,17 @@
using PlotLine.Data;using PlotLine.Models;using PlotLine.Services;using PlotLine.Services.Context;using PlotLine.ViewModels;
internal static class ContextNamesTests
{
public static async Task Run(){void Check(bool p,string m){if(!p)throw new Exception(m);Console.WriteLine("PASS Context Names Library: "+m);}
NameSearchFilter? observed=null;var results=new List<NameSearchResult>{new(){GivenNameID=8,DisplayName="Candidate",UsedCount=2,TotalRows=90}};
var service=NativeWorkflowTests.Proxy<INameIntelligenceService>((n,a)=>{if(n!="BuildLibraryAsync")throw new Exception(n);observed=(NameSearchFilter)a![0]!;return Task.FromResult<NamesLibraryViewModel?>(new(){Filter=observed,Results=results});});
var projectRole="Owner";var personProject=7;var normalised="";var scope="";
var panel=new ContextNames(NativeWorkflowTests.Proxy<ICharacterRepository>((n,a)=>n switch{"GetCharacterAsync"=>Task.FromResult<Character?>(new(){CharacterID=5,ProjectID=personProject,CharacterName="Canonical"}),"ListAliasesAsync"=>Task.FromResult<IReadOnlyList<CharacterAlias>>([new(){CharacterID=5,CharacterAliasID=1,Alias="Variant"}]),_=>throw new Exception("Unbounded catalogue read: "+n)}),NativeWorkflowTests.Proxy<IProjectRepository>((_,_)=>Task.FromResult<Project?>(new(){ProjectID=7,AccessRole=projectRole})),NativeWorkflowTests.Proxy<ICurrentUserService>((_,_)=>4),service,NativeWorkflowTests.Proxy<INameIntelligenceRepository>((n,a)=>{normalised=(string)a![3]!;scope=(string)a[4]!;return Task.FromResult<IReadOnlyList<NameUsageDecoration>>([]);}));
var filter=new NameSearchFilter{ProjectID=999,BookID=12,Search="Jo",LocaleCode="en-GB",BirthYear=1850,GenderPreference="Female",GenderThreshold=.7m,NameType="Variant",MinimumUsage=.05m,UsedScope="Book",UsedOnly=false,Page=2,PageSize=50};var value=await panel.Build(7,12,filter);
Check(ReferenceEquals(observed,filter)&&observed.ProjectID==7&&observed.LocaleCode=="en-GB"&&observed.BirthYear==1850&&observed.GenderThreshold==.7m&&observed.MinimumUsage==.05m&&observed.UsedOnly==false&&observed.Page==2&&observed.PageSize==50,"all library criteria pass directly to the existing query service; project is authorised");
Check(ReferenceEquals(value.Library!.Results,results)&&value.Entries.Count==0,"candidate rows/counts/usage are unchanged and no identity catalogue is loaded");
await panel.Build(7,12);Check(observed!.BookID==12&&observed.UsedScope=="Book"&&observed.PageSize==25,"discovery opens with bounded current-book criteria");
await panel.Usage(7,12,"e\u0301va","Book");Check(normalised=="ÉVA"&&scope=="Book","exact identity/alias usage reuses existing normalisation and scope query");
var identity=await panel.Identity(7,12,5);Check(identity.Entries.Single().Aliases.Single().Alias=="Variant"&&identity.CanEdit,"only explicitly selected canonical identity and aliases are loaded");
projectRole="Viewer";Check(!(await panel.Identity(7,12,5)).CanEdit,"read-only identity references expose no corrections");personProject=8;try{await panel.Identity(7,12,5);throw new Exception("Foreign identity accepted");}catch(UnauthorizedAccessException){Check(true,"foreign-project identity cannot be inspected for correction");}
}
}

View File

@ -0,0 +1,10 @@
using Microsoft.AspNetCore.Http;using PlotLine.Services.Context;using PlotLine.ViewModels;
internal static class ContextRelationshipBrowserFixture
{
public static ContextLensGraph Graph(HttpContext context){var family=context.Request.Query["lens"]!="story";var large=context.Request.Query["large"]=="true";var scene=int.TryParse(context.Request.Query["sceneId"],out var sid)?sid:22;var focus=int.TryParse(context.Request.Query["focusId"],out var fid)?fid:5;var nodes=Enumerable.Range(1,large?120:24).Select(i=>new ContextLensNode(i,i==5?"Fixture participant":"An established relative with a deliberately long name "+i,i is 7 or 8?new DateTime(2000+(i-7)*2,1,1):null,i==6,i is 5 or 6 or 7,null,family&&i==6?true:null)).ToList();var links=new List<ContextLensLink>();int id=0;
void Add(int a,int b,string type,string category="Family",bool mutual=false)=>links.Add(new(++id,a,b,type,category,scene==23?"Later established":"Established",mutual,true,null,null,scene,"Explicit recorded connection notes",[new(){SceneID=scene,Label="Source scene "+scene,StateName=scene==23?"Later established":"Established",Notes="Recorded development"}]));
if(family){Add(1,2,"Spouse","Romantic / Sexual",true);Add(1,3,"Parent");Add(2,3,"Parent");Add(3,4,"Spouse","Romantic / Sexual",true);Add(3,5,"Parent");Add(4,5,"Parent");Add(5,6,"Spouse","Romantic / Sexual",true);Add(5,10,"Spouse","Romantic / Sexual",true);Add(5,7,"Biological Parent");Add(6,7,"Biological Parent");Add(5,8,"Parent");Add(6,8,"Parent");Add(5,9,"Parent");Add(10,9,"Parent");Add(7,8,"Sibling","Family",true);Add(7,9,"Half-sibling","Family",true);Add(11,7,"Adoptive Parent");Add(12,7,"Step Parent");Add(13,14,"Child");Add(12,9,"Guardian");if(large)for(int i=25;i<=120;i++)Add(i/2,i,"Parent");}
else{nodes=nodes.Select(n=>n with{Physical=n.ID is 5 or 6}).ToList();for(int a=5;a<=14;a++)for(int b=a+1;b<=14;b++)Add(a,b,(a+b)%2==0?"Friend":"Rival",(a+b)%2==0?"Friendship":"Hostile / Conflict",(a+b)%3==0);}
return new(family?"family":"story",focus,5,scene,"Fixture scene "+scene,context.Request.Query["readonly"]!="true",false,nodes,links);
}
}

View File

@ -0,0 +1,22 @@
using PlotLine.Data;using PlotLine.Models;using PlotLine.Services;using PlotLine.Services.Context;using PlotLine.ViewModels;
internal static class ContextRelationshipLensTests
{
public static async Task Run(){void Check(bool p,string m){if(!p)throw new Exception(m);Console.WriteLine("PASS Context visual lenses: "+m);}
var scene=new SceneEditViewModel{SceneID=22,ChapterID=10,SceneTitle="Current point",POVCharacterID=5,SceneCharacters=[new(){CharacterID=5,PresenceTypeName="Present"},new(){CharacterID=7,PresenceTypeName="Present",RoleInSceneTypeName="Mentioned Only"}]};
var data=new RelationshipMapData{Books=[new(){BookID=12,SortOrder=1}],Chapters=[new(){ChapterID=10,BookID=12,SortOrder=1}],Scenes=[new(){SceneID=90,ChapterID=10,SceneNumber=1},new(){SceneID=22,ChapterID=10,SceneNumber=2},new(){SceneID=2,ChapterID=10,SceneNumber=3}],Characters=[new(){CharacterID=5,ProjectID=7,CharacterName="Focus",IsDeceased=true,BirthDate=new(1950,1,1)},new(){CharacterID=6,ProjectID=7,CharacterName="Archived relative",IsArchived=true},new(){CharacterID=7,ProjectID=7,CharacterName="Mentioned identity"}],Relationships=[new(){CharacterRelationshipID=9,ProjectID=7,CharacterAID=5,CharacterBID=6,RelationshipTypeName="Parent",RelationshipCategoryName="Family",IsInitialRelationship=true,InitialRelationshipStateName="Before"},new(){CharacterRelationshipID=10,ProjectID=7,CharacterAID=5,CharacterBID=7,RelationshipTypeName="Acquaintance",RelationshipCategoryName="Professional / Social",IsInitialRelationship=true,InitialRelationshipStateName="Known of"},new(){CharacterRelationshipID=11,ProjectID=7,CharacterAID=6,CharacterBID=7,RelationshipTypeName="Child",RelationshipCategoryName="Family",StartSceneID=2}],RelationshipEvents=[new(){RelationshipEventID=1,CharacterRelationshipID=9,SceneID=22,RelationshipStateName="Now",Description="Recorded present change"},new(){RelationshipEventID=2,CharacterRelationshipID=9,SceneID=2,RelationshipStateName="Later",Description="Future evidence"}]};
var read=new ContextLensRead(data,5,false);var story=ContextRelationshipLenses.Compose(read,"story",scene,true);
Check(story.Links.Single(r=>r.ID==9).State=="Now"&&!story.Links.Any(r=>r.ID==11),"Story uses canonical scene order and excludes future-start relationships");
Check(story.Links.Single(r=>r.ID==9).Recent.All(e=>e.SceneID!=2)&&story.Links.Single(r=>r.ID==9).Notes=="Recorded present change","future events cannot leak into current details or recent changes");
Check(!story.Nodes.Single(n=>n.ID==7).Physical&&story.Nodes.Single(n=>n.ID==5).Physical,"mentioned-only role overrides a contradictory physical presence label");
var family=ContextRelationshipLenses.Compose(read,"family",scene,false);Check(family.Links.Any(r=>r.ID==11)&&family.Nodes.Any(n=>n.ID==6&&n.Archived)&&!family.CanEdit,"Family author truth retains recorded future structure and archived identities, explicitly outside POV knowledge");
Check(family.Links.All(r=>r.Category=="Family")&&ContextRelationshipLenses.Family("Romantic / Sexual","Spouse")&&!ContextRelationshipLenses.Family("Professional / Social","Partner"),"family spouse semantics do not turn professional partners into kinship");
Check(story.Links.Single(r=>r.ID==10).State=="Known of"&&!story.Links.Single(r=>r.ID==9).Reciprocal,"explicit states and directional connections are preserved without inferred meeting or symmetry");
Check(family.Nodes.Single(n=>n.ID==5).IsDeceased==true&&family.Nodes.Single(n=>n.ID==6).IsDeceased==null&&story.Nodes.All(n=>n.IsDeceased==null),"canonical death status is Family author reference only; archival does not imply death and Story cannot leak a global future death");
int[]? observedPhysical=null;bool? narrative=null;var role="Viewer";
var reader=NativeWorkflowTests.Proxy<IContextRelationshipReader>((n,a)=>{observedPhysical=((IReadOnlyList<int>)a![6]!).ToArray();return Task.FromResult(read);});
var lens=new ContextRelationshipLenses(reader,NativeWorkflowTests.Proxy<ICharacterRepository>((n,a)=>Task.FromResult<Character?>(new(){CharacterID=(int)a![0]!,ProjectID=(int)a[0]! ==99?8:7})),NativeWorkflowTests.Proxy<IWordCompanionRepository>((n,a)=>Task.FromResult<WordCompanionBookStructureResponse?>((int)a![0]! ==12?new(){BookId=12,Chapters=[new(){ChapterId=10,Scenes=[new(){SceneId=22}]}]}:null)),NativeWorkflowTests.Proxy<IBookRepository>((_,_)=>Task.FromResult<Book?>(new(){BookID=12,ProjectID=7})),NativeWorkflowTests.Proxy<IProjectRepository>((_,_)=>Task.FromResult<Project?>(new(){ProjectID=7,AccessRole=role})),NativeWorkflowTests.Proxy<ICurrentUserService>((_,_)=>4),NativeWorkflowTests.Proxy<IStoryContextService>((n,a)=>{narrative=(bool)a![4]!;return Task.FromResult<StoryContextViewModel?>(new(){Position=new(7,12,10,22),Scene=scene});}));
var actual=await lens.Graph(12,22,"story",null,3);Check(observedPhysical!.SequenceEqual([5])&&narrative==false&&!actual.CanEdit,"visual reads use bounded reader and thin scene context without loading narrative histories; viewers remain read-only");
try{await lens.Graph(12,22,"family",99,3);throw new Exception("foreign focus accepted");}catch(UnauthorizedAccessException){Check(true,"cross-project focus rejected before graph read");}
try{await lens.Graph(12,999,"family",5,3);throw new Exception("foreign scene accepted");}catch(UnauthorizedAccessException){Check(true,"cross-book scene rejected");}
}
}

View File

@ -0,0 +1,29 @@
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging.Abstractions;
using PlotLine.Data;using PlotLine.Hubs;using PlotLine.Models;using PlotLine.Services;using PlotLine.Services.Context;using PlotLine.ViewModels;
internal static class ContextRelationshipTests
{
static void Check(bool pass,string message){if(!pass)throw new Exception(message);Console.WriteLine("PASS Context relationships: "+message);}
public static async Task Run()
{
var r=new CharacterRelationship{CharacterRelationshipID=9,ProjectID=7,CharacterAID=5,CharacterBID=6,CharacterAName="From",CharacterBName="To",RelationshipTypeID=1,RelationshipTypeName="Parent",RelationshipCategoryName="Family",IsInitialRelationship=true,InitialRelationshipStateID=1,InitialRelationshipStateName="Established",InitialIntensity=4};
var events=new List<RelationshipEvent>{new(){RelationshipEventID=10,CharacterRelationshipID=9,SceneID=22,RelationshipStateID=2,RelationshipStateName="Changed",Description="Explicit scene note"},new(){RelationshipEventID=11,CharacterRelationshipID=9,SceneID=23,RelationshipStateID=3,RelationshipStateName="Future"}};
RelationshipMapData Data()=>new(){Characters=[new(){CharacterID=5,CharacterName="From"},new(){CharacterID=6,CharacterName="To"}],Books=[new(){BookID=12}],Chapters=[new(){ChapterID=10,BookID=12}],Scenes=[new(){SceneID=22,ChapterID=10,SceneNumber=1},new(){SceneID=23,ChapterID=10,SceneNumber=2}],Relationships=[r],RelationshipEvents=events};
var point=RelationshipMapService.BuildAtScene(Data(),new Dictionary<int,int>{{22,0},{23,1}},22).Single();Check(point.CurrentStateName=="Changed"&&point.RelationshipCategoryName=="Family"&&!point.IsReciprocal,"canonical story-point state excludes future events, preserves Family and direction");
var role="Owner";RelationshipEventCreateViewModel? saved=null;InitialRelationshipEditViewModel? initial=null;
var repository=NativeWorkflowTests.Proxy<ICharacterRepository>((name,_)=>name switch{"GetRelationshipMapAsync"=>Task.FromResult(Data()),"GetLookupsAsync"=>Task.FromResult(new CharacterLookupData{RelationshipTypes=[new(){RelationshipTypeID=1,TypeName="Parent",RelationshipCategoryName="Family",IsActive=true}],RelationshipStates=[new(){RelationshipStateID=1,StateName="Established",IsActive=true},new(){RelationshipStateID=2,StateName="Changed",IsActive=true}]}),_=>throw new Exception(name)});
var service=NativeWorkflowTests.Proxy<ICharacterService>((name,args)=>{if(name=="UpdateRelationshipEventAsync"){saved=(RelationshipEventCreateViewModel)args![0]!;return Task.FromResult(10);}if(name=="SaveInitialRelationshipAsync"){initial=(InitialRelationshipEditViewModel)args![0]!;return Task.FromResult(9);}throw new Exception(name);});
var client=NativeWorkflowTests.Proxy<IClientProxy>((_,_)=>Task.CompletedTask);var clients=NativeWorkflowTests.Proxy<IHubClients>((_,_)=>client);var hub=NativeWorkflowTests.Proxy<IHubContext<NativeCompanionPresenceHub>>((_,_)=>clients);
var edit=new ContextRelationshipEditing(repository,service,NativeWorkflowTests.Proxy<IWordCompanionRepository>((_,_)=>Task.FromResult<WordCompanionBookStructureResponse?>(new(){BookId=12,Chapters=[new(){ChapterId=10,Scenes=[new(){SceneId=22}]}]})),NativeWorkflowTests.Proxy<IBookRepository>((_,_)=>Task.FromResult<Book?>(new(){BookID=12,ProjectID=7})),NativeWorkflowTests.Proxy<IProjectRepository>((_,_)=>Task.FromResult<Project?>(new(){ProjectID=7,AccessRole=role})),NativeWorkflowTests.Proxy<ICurrentUserService>((_,_)=>4),new ContextWorkspaceNotifications(hub,NullLogger<ContextWorkspaceNotifications>.Instance));
var form=await edit.Read(12,22,9,"scene");Check(form.StateID==2&&form.Notes=="Explicit scene note","focused form loads current scene event values");form.Notes="Corrected scene note";await edit.Save(form);Check(saved?.RelationshipEventID==10&&saved.CharacterRelationshipID==9&&saved.CharacterAID==5&&saved.CharacterBID==6&&saved.SceneID==22,"save corrects only selected event using existing service");
form.TargetID=5;try{await edit.Save(form);throw new Exception("invalid pair accepted");}catch(ArgumentException){Check(true,"invalid self-relationship rejected");}form.TargetID=6;
form.Mutual=true;try{await edit.Save(form);throw new Exception("direction changed");}catch(ArgumentException){Check(true,"existing directional relationship cannot silently become reciprocal");}form.Mutual=false;
events[0].Description="Changed elsewhere";try{await edit.Save(form);throw new Exception("stale accepted");}catch(InvalidOperationException){Check(true,"stale relationship drafts rejected");}
var start=await edit.Read(12,22,9,"initial");start.Notes="Initial correction";await edit.Save(start);Check(initial?.CharacterRelationshipID==9&&initial.InitialRelationshipStateID==1&&initial.CharacterID==5&&initial.RelatedCharacterID==6,"focused initial correction reuses existing initial relationship service");
try{await edit.Read(12,22,999,"scene");throw new Exception("foreign ID accepted");}catch(UnauthorizedAccessException){Check(true,"unowned relationship ID rejected");}
try{await edit.Read(12,999,9,"scene");throw new Exception("foreign scene accepted");}catch(UnauthorizedAccessException){Check(true,"cross-book scene rejected");}
r.StartSceneID=23;var author=await edit.Read(12,22,9,"initial","family");Check(author.ReferenceLens=="family"&&author.Types.Any(t=>t.Value=="1"),"Family initial corrections use explicit author truth without treating a future source as current POV knowledge");
r.RelationshipCategoryName="Professional / Social";r.RelationshipTypeName="Colleague";try{await edit.Read(12,22,9,"initial","family");throw new Exception("nonfamily accepted");}catch(ArgumentException){Check(true,"Family reference mode cannot relabel a nonfamily connection");}r.RelationshipCategoryName="Family";r.RelationshipTypeName="Parent";r.StartSceneID=null;
role="Viewer";try{await edit.Read(12,22,9,"scene");throw new Exception("viewer accepted");}catch(UnauthorizedAccessException){Check(true,"read-only relationship correction rejected");}
}
}

View File

@ -0,0 +1,46 @@
using PlotLine.Services.Context;
internal static class ContextWindowsTests
{
private sealed class Clock:TimeProvider {public DateTimeOffset Now=DateTimeOffset.UtcNow;public override DateTimeOffset GetUtcNow()=>Now;}
private static void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS My Windows: "+message);}
public static void Run()
{
var clock=new Clock();var store=new ContextWindows(clock);var first=Guid.NewGuid();var second=Guid.NewGuid();
ContextWindowRegistration Registration(Guid id,int book,string action,bool available=true)=>new(1,book,id,[new("0","reference",[action],available)]);
store.Register(7,"origin",Registration(first,12,"scene.focus"));store.Register(7,"remote-device",Registration(second,12,"scene.focus"));
store.Register(8,"other-user",Registration(Guid.NewGuid(),12,"scene.focus"));store.Register(7,"other-book",Registration(Guid.NewGuid(),13,"scene.focus"));
var command=new ContextInteraction(1,12,"0","scene.focus",StoryPoint:new(10,22));
Check(store.List(7,12).Length==2,"discovery is isolated by account and book");
var local=store.Route(7,"origin",command)!.Value;Check(local.Window.Connection=="origin","suitable local pane is preferred");
var remote=store.Route(7,"origin",command with{TargetWindowID=second})!.Value;Check(remote.Window.Connection=="remote-device","explicit recipient is targeted without broadcasting");
Check(store.Complete(7,"origin",remote.CommandID)==null,"another connection cannot acknowledge a recipient's command");
Check(store.Complete(7,"remote-device",remote.CommandID)=="origin","only the selected recipient acknowledges delivery");
Check(store.Route(7,"origin",command with{Action="location.focus",LocationID=20})==null,"no-handler is explicit and does not replace a tool");
try{store.Route(7,"origin",command with{TargetUserID=8});throw new Exception("Cross-user request accepted");}catch(ArgumentException){Check(true,"cross-user commands are disabled");}
try{store.Route(7,"origin",command with{BookID=13});throw new Exception("Cross-book request accepted");}catch(ArgumentException){Check(true,"origin registration cannot cross books");}
store.Register(7,"origin",Registration(first,12,"scene.focus",false));Check(store.Route(7,"origin",command)!.Value.Window.Connection=="remote-device","busy local pane is bypassed without mutation");
store.Remove("remote-device");Check(store.Route(7,"origin",command)==null,"disconnect removes eligible destinations");
clock.Now+=TimeSpan.FromSeconds(61);Check(store.List(7,12).Length==0,"missed disconnects expire on authoritative discovery");
store.Register(7,"reconnected",Registration(first,12,"scene.focus"));Check(store.List(7,12).Length==1,"reconnection registers current capability state");
var environment=Guid.NewGuid();store.Register(7,"reconnected",Registration(first,12,"scene.focus") with{EnvironmentID=environment});
store.Register(7,"main-remote",new(1,12,Guid.NewGuid(),[new("0","main",["workspace.open"])],Guid.NewGuid(),"main"));
var open=new ContextInteraction(1,12,"0","workspace.open",Workspace:new("characters",5));Check(store.Route(7,"reconnected",open)==null,"main navigation never targets another browser environment/device");
store.Register(7,"main-local",new(1,13,Guid.NewGuid(),[new("0","main",["workspace.open"])],environment,"main",[12,13]));
Check(store.Route(7,"reconnected",open)?.Window.Connection=="main-local","same-environment main shell can receive authorised navigation for its project books");
Check(store.Route(7,"reconnected",open with{TargetSessionID="main-remote"})==null,"explicit target cannot bypass same-environment restriction");
store.Remove("main-local");store.Remove("main-remote");Check(store.TryLaunch(7,"reconnected",12,environment),"one browser environment can reserve a missing main-window launch");Check(!store.TryLaunch(7,"reconnected",12,environment),"concurrent fallback launches are suppressed");clock.Now+=TimeSpan.FromSeconds(11);Check(store.TryLaunch(7,"reconnected",12,environment),"failed or blocked main launches can be retried after the short lease");
try{store.Register(7,"bad",new(1,12,Guid.NewGuid(),[new("0","fake",["word.navigate"])]));throw new Exception("Word action accepted");}catch(ArgumentException){Check(true,"interaction contract cannot invoke Word navigation");}
var launchStore=new ContextWindows(clock);var browser=Guid.NewGuid();
launchStore.Register(7,"launcher",new(1,12,Guid.NewGuid(),[],browser));
launchStore.Register(8,"foreign-user",Registration(Guid.NewGuid(),12,"scene.focus") with{EnvironmentID=browser});
launchStore.Register(7,"foreign-book",Registration(Guid.NewGuid(),13,"scene.focus") with{EnvironmentID=browser});
launchStore.Register(7,"foreign-browser",Registration(Guid.NewGuid(),12,"scene.focus") with{EnvironmentID=Guid.NewGuid()});
Check(launchStore.OpenContext(7,"launcher",12).Status=="open","ribbon launch cannot reuse a foreign account, book or browser window");
Check(launchStore.OpenContext(7,"launcher",12).Status=="pending","repeated ribbon launches reserve only one new Context window");
launchStore.Register(7,"held-context",Registration(Guid.NewGuid(),12,"scene.focus",false) with{EnvironmentID=browser});
Check(launchStore.OpenContext(7,"launcher",12)==("reused","held-context"),"existing Context is reused without replacing busy tools or its independent held position");
try{launchStore.OpenContext(8,"launcher",12);throw new Exception("Cross-user launch accepted");}catch(ArgumentException){Check(true,"Context launch validates its authenticated origin registration");}
launchStore.Remove("held-context");clock.Now+=TimeSpan.FromSeconds(11);
Check(launchStore.OpenContext(7,"launcher",12).Status=="open","failed launch reservations expire for an explicit retry");
}
}

View File

@ -25,7 +25,7 @@ internal static class NarrativeFocusDatabaseTests
var factory=new Factory(builder.ConnectionString);var focus=new NarrativeFocus(factory);var objectives=new WriterObjectiveRepository(factory);
var before=(await objectives.Read(fixture.UserID,fixture.BookID)).Objective!;
var state=await focus.Read(fixture.UserID,fixture.ProjectID,fixture.BookID);
if(state.SceneID!=fixture.SceneID||state.Positions.Count!=1||state.Recent.Single().SceneID!=fixture.SceneID)throw new Exception("Repository seed/position/history mapping failed");
if(state.SceneID!=null||state.ChapterID!=null||state.Version!=0||state.Positions.Count!=1||state.Recent.Count!=0)throw new Exception("Read must not manufacture focus from a working objective");
state=await focus.Set(fixture.UserID,fixture.ProjectID,fixture.BookID,fixture.ChapterID,null,state.Version);
if(state.SceneID!=null||state.ChapterID!=fixture.ChapterID)throw new Exception("Repository chapter navigation failed");
if(await focus.Open(fixture.UserID,null,fixture.SceneID,fixture.ProjectID,fixture.BookID+1)!=null)throw new Exception("Repository accepted an explicit destination in the wrong book");

View File

@ -26,23 +26,25 @@ internal static class NarrativeNavigationTests
var http=new DefaultHttpContext();http.Request.Method=item.Item3;http.Request.QueryString=new(item.Item4);
if(item.Item4=="?ajax")http.Request.Headers["Sec-Fetch-Mode"]="cors";if(item.Item4=="?prefetch")http.Request.Headers["Sec-Purpose"]="prefetch";
var route=new RouteData();route.Values["controller"]=item.Item1;route.Values["action"]=item.Item2;
var action=new ActionContext(http,route,new ActionDescriptor());var filter=new NarrativeNavigationFilter(focus,user);
var action=new ActionContext(http,route,new ActionDescriptor());var filter=new NarrativeNavigationFilter(user);
var executing=new ActionExecutingContext(action,[],new Dictionary<string,object?>{{"id",31}},new object());
var executed=new ActionExecutedContext(action,[],new object()){Result=item.Item5?new ViewResult():new NotFoundResult()};
var before=writes;await filter.OnActionExecutionAsync(executing,()=>Task.FromResult(executed));
if(writes-before!=(item.Item6?1:0))throw new Exception($"Narrative navigation classification failed: {item}");
if(writes-before!=0)throw new Exception($"Narrative navigation classification failed: {item}");
}
var savedContext=new DefaultHttpContext();savedContext.Request.Method="POST";var savedRoute=new RouteData();savedRoute.Values["controller"]="Scenes";
var saveAction=new ActionContext(savedContext,savedRoute,new ActionDescriptor());var redirect=new RedirectToActionResult("Edit","Scenes",new{id=31});
var savedResult=new ActionExecutedContext(saveAction,[],new object()){Result=redirect};
await new NarrativeNavigationFilter(focus,user).OnActionExecutionAsync(new(saveAction,[],new Dictionary<string,object?>(),new object()),()=>Task.FromResult(savedResult));
await new NarrativeNavigationFilter(user).OnActionExecutionAsync(new(saveAction,[],new Dictionary<string,object?>(),new object()),()=>Task.FromResult(savedResult));
if(redirect.RouteValues?["retainNarrativeFocus"] is not true)throw new Exception("Saving an editor must preserve independently navigated focus");
var navigationController=new PlotLine.Controllers.NarrativeFocusController(focus,user);
var navigationAction=new ActionExecutingContext(saveAction,[],new Dictionary<string,object?>(),navigationController);
bool allowedNavigation=false;
await new SubscriptionEnforcementFilter(user,NativeWorkflowTests.Proxy<ISubscriptionService>((_,_)=>throw new Exception("Narrative navigation must not require content-edit entitlement")))
.OnActionExecutionAsync(navigationAction,()=>{allowedNavigation=true;return Task.FromResult(new ActionExecutedContext(saveAction,[],navigationController));});
if(!allowedNavigation)throw new Exception("Read-only accounts must retain narrative navigation");
Console.WriteLine("PASS deliberate narrative destinations commit focus; local visualisation, filtering, failed opens and edits submitted by POST do not");
foreach(var navigationController in new Controller[]{new PlotLine.Controllers.NarrativeFocusController(focus,user),new PlotLine.Controllers.SharedFocusController(null!,user)})
{
var navigationAction=new ActionExecutingContext(saveAction,[],new Dictionary<string,object?>(),navigationController);
bool allowedNavigation=false;
await new SubscriptionEnforcementFilter(user,NativeWorkflowTests.Proxy<ISubscriptionService>((_,_)=>throw new Exception("Narrative navigation must not require content-edit entitlement")))
.OnActionExecutionAsync(navigationAction,()=>{allowedNavigation=true;return Task.FromResult(new ActionExecutedContext(saveAction,[],navigationController));});
if(!allowedNavigation)throw new Exception("Read-only accounts must retain narrative navigation");
}
Console.WriteLine("PASS page loads, refreshes, local inspection and editor return redirects never publish shared focus");
}
}

View File

@ -56,7 +56,9 @@ internal static class NativeCompanionHttpTests
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<INativeInstallationRepository>(new MemoryNativeInstallations(user));builder.Services.AddScoped<NativeInstallationService>();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.AddSingleton(NativeWorkflowTests.Proxy<INativeImportRepository>((n,a)=>n=="List"?Task.FromResult<IReadOnlyList<NativeImportedChapter>>([]):throw new Exception("Unexpected import write "+n)));builder.Services.AddScoped<NativeImportService>();builder.Services.AddSingleton<NativeCommandWakeQueue>();builder.Services.AddSingleton<NativeAgentConnections>();builder.Services.AddHostedService<NativeCommandNotificationDispatcher>();builder.Services.AddSingleton<NativePresenceStore>();builder.Services.AddSingleton<INativeReviewRepository>(new MemoryNativeReviews());
builder.Services.AddSingleton<IDataProtectionProvider>(new EphemeralDataProtectionProvider());builder.Services.AddSingleton(TimeProvider.System);builder.Services.AddSingleton<PlotLine.Services.Context.ContextWindows>();
builder.Services.AddSingleton(Proxy<ICharacterRepository>((n,a)=>throw new Exception("Unexpected character read "+n)));
builder.Services.AddSingleton(Proxy<ILocationRepository>((n,a)=>throw new Exception("Unexpected location read "+n)));builder.Services.AddSingleton<DesktopPairing>();builder.Services.AddSingleton<NativeAnalysisCache>();builder.Services.AddSingleton(NativeWorkflowTests.Proxy<INativeImportRepository>((n,a)=>n=="List"?Task.FromResult<IReadOnlyList<NativeImportedChapter>>([]):throw new Exception("Unexpected import write "+n)));builder.Services.AddScoped<NativeImportService>();builder.Services.AddSingleton<NativeCommandWakeQueue>();builder.Services.AddSingleton<NativeAgentConnections>();builder.Services.AddHostedService<NativeCommandNotificationDispatcher>();builder.Services.AddSingleton<NativePresenceStore>();builder.Services.AddSingleton<INativeReviewRepository>(new MemoryNativeReviews());
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options=>{options.LoginPath="/fixture-login";options.Cookie.SecurePolicy=Microsoft.AspNetCore.Http.CookieSecurePolicy.None;})
.AddScheme<AuthenticationSchemeOptions,DesktopAuthentication>(DesktopPairing.Scheme,_=>{});
builder.Services.AddRateLimiter(o=>o.AddPolicy("native-pair",_=>System.Threading.RateLimiting.RateLimitPartition.GetNoLimiter("fixture")));

View File

@ -15,6 +15,11 @@ using PlotLine.Models;
using PlotLine.Services;
using PlotLine.ViewModels;
if(args.Contains("--shared-focus-concurrent")){await SharedFocusDatabaseTests.Concurrent();return;}
if(args.Contains("--shared-focus-cleanup")){await SharedFocusDatabaseTests.Concurrent(true);return;}
if(args.Contains("--shared-focus-browser-host")){await SharedFocusBrowserHost.Run();return;}
if(args.Contains("--shared-focus-database")){await SharedFocusDatabaseTests.Run(args.Last());return;}
if(args.Contains("--shared-focus-browser-setup")){await SharedFocusDatabaseTests.Run(args.Last(),true);return;}
if(args.Contains("--narrative-focus-database")){await NarrativeFocusDatabaseTests.Run(args.Last());return;}
if(args.Contains("--production-investigation")){ProductionInvestigationTests.Run(args.Last());return;}
if(args.Contains("--writer-investigation-diagnostics")){if(args.Contains("--acceptance"))InvestigationDiagnosticTests.Run();InvestigationDiagnosticTests.Export(args[^2],args[^1]);return;}
@ -182,8 +187,24 @@ if(args.Contains("--sql-architecture-inventory")){Console.WriteLine(System.Text.
if(args.Contains("--native-review-navigation")){await NativeReviewNavigationTests.Run();Console.WriteLine("PASS historical review navigation session/content guards and acknowledgements");return;}
if(args.Contains("--character-workspace-database")){await CharacterWorkspaceDatabaseTests.Run(args.Last());return;}
if(args.Contains("--character-workspace")){await CharacterWorkspaceTests.Run();return;}
if(args.Contains("--context-family")){ContextFamilyTests.Run();return;}
if(args.Contains("--context-lenses")){await ContextRelationshipLensTests.Run();return;}
if(args.Contains("--context-names")){await ContextNamesTests.Run();return;}
if(args.Contains("--context-relationships")){await ContextRelationshipTests.Run();return;}
if(args.Contains("--context-characters")){await ContextCharacterTests.Run();return;}
if(args.Contains("--context-windows")){ContextWindowsTests.Run();return;}
var tests = new (string Name, Action Test)[]
{
("Main Character workspace lazy reads and safe management",()=>CharacterWorkspaceTests.Run().GetAwaiter().GetResult()),
("Scene family identification and branch exploration",ContextFamilyTests.Run),
("Context Family/Story projection and bounded reads",()=>ContextRelationshipLensTests.Run().GetAwaiter().GetResult()),
("Context Names Library query parity and bounded identities",()=>ContextNamesTests.Run().GetAwaiter().GetResult()),
("Context relationship state and focused editing",()=>ContextRelationshipTests.Run().GetAwaiter().GetResult()),
("Context character narrative projection and focused editing",()=>ContextCharacterTests.Run().GetAwaiter().GetResult()),
("Context My Windows routing and lifecycle",ContextWindowsTests.Run),
("Settlement boundaries preserve anchors, routes and backup/import contracts",MapSettlementTests.Run),
("Shared boundary topology preserves map and project contracts",MapTopologyTests.Run),
("Geographical roots, providers, queue outcomes and access", () => GeographyTests.Run().GetAwaiter().GetResult()),
@ -543,40 +564,24 @@ var tests = new (string Name, Action Test)[]
("Whole-book Plot Intelligence production code remains fixture agnostic", WholeBookPlotIntelligenceProductionCodeRemainsFixtureAgnostic),
("Story Intelligence narrative review creates canonical records via existing procs", StoryIntelligenceNarrativeReviewCreatesCanonicalRecordsViaExistingProcs),
("Story Intelligence narrative stage follows knowledge", StoryIntelligenceNarrativeStageFollowsKnowledge),
("Word Companion replays live current scene to writing panes", WordCompanionReplaysLiveCurrentSceneToWritingPanes),
("Scan review post supports full-book form submissions", ScanReviewPostSupportsFullBookFormSubmissions),
("StoryPosition rejects incomplete or invalid runtime scene positions", StoryPositionRejectsInvalidRuntimeScenePositions),
("StoryPosition builds canonical runtime scene navigation", StoryPositionBuildsCanonicalRuntimeSceneNavigation),
("StoryPosition derives canonical scene context identity", StoryPositionDerivesCanonicalSceneContextIdentity),
("Writing Context route uses canonical story context service", WritingContextRouteUsesCanonicalStoryContextService),
("Writing Context client follows canonical story position events", WritingContextClientFollowsCanonicalStoryPositionEvents),
("Writing Context preserves selected tab and avoids event loops", WritingContextPreservesSelectedTabAndAvoidsEventLoops),
("Writing Intent route uses canonical story context and planning data", WritingIntentRouteUsesCanonicalStoryContextAndPlanningData),
("Writing Intent client uses shared writing follow helper", WritingIntentClientUsesSharedWritingFollowHelper),
("Obsolete global Word navigation is removed while writing windows remain live", GlobalWordNavigationIsRemoved),
("Appearance preferences and ribbon destinations", AppearanceTests.RegistryAndPersistence),
("Toolbar preferences, authorisation and contextual routes", ToolbarTests.PreferencesAndRoutes),
("Application navigation resolves authorised project and book context", ApplicationNavigationTests.ContextAndPermissions),
("Writing pair shares canonical follow infrastructure", WritingPairSharesCanonicalFollowInfrastructure),
("Writing Context and Intent resolve native sessions, preserve decisions and reuse bounded chronological data", () => WritingIntegrationTests.Run().GetAwaiter().GetResult()),
("Writing Context Plot Lines preserves canonical associations, developments and book access", () => WritingContextPlotLinesTests.Run().GetAwaiter().GetResult()),
("Writing workspace presence scopes browser windows", WritingWorkspacePresenceScopesBrowserWindows),
("Writing workspace client uses session window identity and stable names", WritingWorkspaceClientUsesSessionIdentityAndStableNames),
("Writing workspace launcher uses progressive screen placement", WritingWorkspaceLauncherUsesProgressiveScreenPlacement),
("Writing workspace pages register roles without changing follow behavior", WritingWorkspacePagesRegisterRolesWithoutChangingFollowBehavior),
("Word marker client acknowledgements require authenticated ownership", WordMarkerSecurityTests.HubChecks),
("Word Companion exposes writing workspace launch actions", WordCompanionExposesWritingWorkspaceLaunchActions),
("Word Companion writing screens receive resolved context identifiers", WordCompanionWritingScreensReceiveResolvedContextIdentifiers),
("Word Companion canonical markers drive runtime follow", WordCompanionCanonicalMarkersDriveRuntimeFollow),
("Word Companion runtime follows multiple imported scene anchors", WordCompanionRuntimeFollowsMultipleImportedSceneAnchors),
("Word Companion existing project book linking remains available", WordCompanionExistingProjectBookLinkingRemainsAvailable),
("Word Companion document identity survives reconnect", WordCompanionDocumentIdentitySurvivesReconnect),
("Word Companion multiscreen launch and follow remain reachable", WordCompanionMultiscreenLaunchAndFollowRemainReachable),
("Word Companion modes remain distinct", WordCompanionModesRemainDistinct),
("Writing pages do not require Story Intelligence", WritingPagesDoNotRequireStoryIntelligence),
("Word Companion host script has valid tab mapping", WordCompanionHostScriptHasValidTabMapping),
("Writing screens show diagnostic empty states", WritingScreensShowDiagnosticEmptyStates),
("Word Companion three-screen flow logs connection identifiers", WordCompanionThreeScreenFlowLogsConnectionIdentifiers),
("Admin Story Intelligence reset returns to diagnostics with messages", AdminStoryIntelligenceResetReturnsToDiagnosticsWithMessages),
("Project hard delete clears Story Intelligence dependencies in transaction", ProjectHardDeleteClearsStoryIntelligenceDependenciesInTransaction),
("Permanent project delete keeps archive and name safety gates", PermanentProjectDeleteKeepsArchiveAndNameSafetyGates),
@ -1569,7 +1574,7 @@ static void CharacterDetailCanQueueSingleCharacterEnrichment()
var controller = File.ReadAllText(Path.Combine(root, "Controllers/CharactersController.cs"));
var characterService = File.ReadAllText(Path.Combine(root, "Services/CoreServices.cs"));
var enrichmentService = File.ReadAllText(Path.Combine(root, "Services/CharacterEnrichmentService.cs"));
var view = File.ReadAllText(Path.Combine(root, "Views/Characters/Details.cshtml"));
var view = File.ReadAllText(Path.Combine(root, "Views/Characters/Details.cshtml")) + File.ReadAllText(Path.Combine(root, "Views/Shared/_CharacterRibbonCommands.cshtml"));
Assert(view.Contains("Reanalyse character", StringComparison.Ordinal), "Character detail should expose a discreet reanalyse action.");
Assert(view.Contains("data-character-reanalyse-form", StringComparison.Ordinal), "Character reanalyse action should be script-addressable.");
@ -1608,7 +1613,8 @@ static void CharacterDetailEnrichmentStatusUsesScopedSignalR()
{
var root = PlotLineRoot();
var viewModel = File.ReadAllText(Path.Combine(root, "ViewModels/CoreViewModels.cs"));
var view = File.ReadAllText(Path.Combine(root, "Views/Characters/Details.cshtml"));
var view = File.ReadAllText(Path.Combine(root, "Views/Characters/Details.cshtml"))
+ File.ReadAllText(Path.Combine(root, "Views/Characters/_WorkspaceProfile.cshtml"));
var hub = File.ReadAllText(Path.Combine(root, "Hubs/StoryIntelligenceHub.cs"));
var script = File.ReadAllText(Path.Combine(root, "wwwroot/js/character-enrichment-detail.js"));
var models = File.ReadAllText(Path.Combine(root, "Models/CharacterEnrichmentModels.cs"));
@ -1622,7 +1628,7 @@ static void CharacterDetailEnrichmentStatusUsesScopedSignalR()
Assert(models.Contains("public int? CharacterID { get; init; }", StringComparison.Ordinal), "SignalR progress event should include character scope.");
Assert(script.Contains("CharacterEnrichmentProgressChanged", StringComparison.Ordinal)
&& script.Contains("Number(snapshot.characterID || snapshot.characterId || 0) !== characterId", StringComparison.Ordinal), "Character detail script should ignore unrelated enrichment events.");
Assert(script.Contains("window.location.reload()", StringComparison.Ordinal), "Character detail should refresh displayed generated details after completion.");
Assert(script.Contains("character-analysis-updated", StringComparison.Ordinal), "Character workspace should refresh persisted generated details after completion without reloading its shell.");
Assert(migration.Contains("LastAnalysedUtc = @LastAnalysedUtc", StringComparison.Ordinal), "Last analysed should come only from a successful completed enrichment run.");
Assert(migration.Contains("Status = COALESCE((SELECT TOP (1) Status FROM @Attempt)", StringComparison.Ordinal), "Failed latest attempts should remain visible and retryable.");
}
@ -2006,245 +2012,22 @@ static void WritingContextRouteUsesCanonicalStoryContextService()
Assert(controller.Contains("[Route(\"Writing\")", StringComparison.Ordinal), "Writing Context controller should expose the /Writing route prefix.");
Assert(controller.Contains("[HttpGet(\"Context\")", StringComparison.Ordinal), "Writing Context shell route is missing.");
Assert(controller.Contains("[HttpGet(\"Context/Scene\")", StringComparison.Ordinal), "Writing Context partial route is missing.");
Assert(controller.Contains("[HttpGet(\"Context/Tabs/overview\")", StringComparison.Ordinal), "Writing Context partial route is missing.");
Assert(controller.Contains("IStoryContextService storyContext", StringComparison.Ordinal), "Writing Context must consume IStoryContextService.");
Assert(controller.Contains("storyContext.GetForSceneAsync", StringComparison.Ordinal), "Writing Context scene requests must load canonical story context.");
Assert(!controller.Contains("ISceneService", StringComparison.Ordinal), "Writing Context should not bypass canonical story context with ISceneService.");
Assert(viewModel.Contains("StoryContextViewModel? Context", StringComparison.Ordinal), "Writing Context display model should carry canonical story context.");
}
static void WritingContextClientFollowsCanonicalStoryPositionEvents()
{
var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine");
var script = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js"));
var initializer = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-context.js"));
var view = File.ReadAllText(Path.Combine(root, "Views/Writing/Context.cshtml"));
Assert(view.Contains("data-writing-context", StringComparison.Ordinal), "Writing Context shell should expose a stable script root.");
Assert(view.Contains("data-writing-mode=\"context\"", StringComparison.Ordinal), "Writing Context should identify itself as a writing-mode page.");
Assert(view.Contains("~/js/writing-follow.js", StringComparison.Ordinal), "Writing Context should load the shared writing follow helper.");
Assert(initializer.Contains("window.PlotDirectorWritingFollow?.initialize", StringComparison.Ordinal), "Writing Context should initialize the shared writing follow helper.");
Assert(script.Contains("window.PlotDirectorStoryPosition?.eventName", StringComparison.Ordinal), "Writing Context must subscribe to canonical browser story-position events.");
Assert(script.Contains("connection.on(\"storyPositionChanged\"", StringComparison.Ordinal), "Writing Context must bridge SignalR story-position events.");
Assert(script.Contains("fetch(url", StringComparison.Ordinal), "Writing Context should refresh context content without full page navigation.");
Assert(initializer.Contains("[data-writing-context-scene-select]", StringComparison.Ordinal), "Writing Context manual fallback selector should be wired.");
Assert(script.Contains("publishChanged", StringComparison.Ordinal), "Manual scene selection should publish canonical story-position changes.");
}
static void WritingContextPreservesSelectedTabAndAvoidsEventLoops()
{
var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine");
var script = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js"));
var initializer = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-context.js"));
Assert(initializer.Contains("plotdirector.writingContext.activeTab", StringComparison.Ordinal), "Writing Context should remember the selected tab.");
Assert(script.Contains("activateTab(tab)", StringComparison.Ordinal), "Writing Context should restore the selected tab after content refresh.");
Assert(script.Contains("position.sceneId === currentSceneId", StringComparison.Ordinal), "Writing Context should ignore duplicate current-scene events.");
Assert(script.Contains("position.sceneId === loadingSceneId", StringComparison.Ordinal), "Writing Context should ignore duplicate in-flight scene events.");
Assert(!script.Contains("window.location.assign", StringComparison.Ordinal) && !script.Contains("window.location.href", StringComparison.Ordinal), "Writing Context must not navigate away when Word changes scene.");
}
static void WritingIntentRouteUsesCanonicalStoryContextAndPlanningData()
{
var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine");
var controller = File.ReadAllText(Path.Combine(root, "Controllers/WritingController.cs"));
var viewModel = File.ReadAllText(Path.Combine(root, "ViewModels/CoreViewModels.cs"));
var contentView = File.ReadAllText(Path.Combine(root, "Views/Writing/_WritingIntentContent.cshtml"));
Assert(controller.Contains("[HttpGet(\"Intent\")", StringComparison.Ordinal), "Writing Intent shell route is missing.");
Assert(controller.Contains("[HttpGet(\"Intent/Scene\")", StringComparison.Ordinal), "Writing Intent partial route is missing.");
Assert(controller.Contains("IStoryContextService storyContext", StringComparison.Ordinal), "Writing Intent must share canonical story context service injection.");
Assert(controller.Contains("storyContext.GetForSceneAsync", StringComparison.Ordinal), "Writing Intent scene requests must use canonical story context.");
Assert(controller.Contains("IWriterWorkspaceService writerWorkspace", StringComparison.Ordinal), "Writing Intent should reuse existing writer planning data.");
Assert(controller.Contains("writerWorkspace.GetChapterWorkflowAsync", StringComparison.Ordinal), "Writing Intent should load chapter workflow planning data.");
Assert(controller.Contains("projectId.HasValue && chapterWorkflow.Project.ProjectID != projectId.Value", StringComparison.Ordinal), "Writing Intent should reject mismatched project scope.");
Assert(controller.Contains("bookId.HasValue && chapterWorkflow.Book.BookID != bookId.Value", StringComparison.Ordinal), "Writing Intent should reject mismatched book scope.");
Assert(viewModel.Contains("public sealed class WritingIntentDisplayViewModel", StringComparison.Ordinal), "Writing Intent display model is missing.");
Assert(viewModel.Contains("StoryContextViewModel? Context", StringComparison.Ordinal), "Writing Intent display should carry canonical story context.");
Assert(viewModel.Contains("ChapterWorkflowViewModel? ChapterWorkflow", StringComparison.Ordinal), "Writing Intent display should carry chapter planning workflow.");
Assert(contentView.Contains("No current scene. Showing chapter intent.", StringComparison.Ordinal), "Writing Intent should support chapter-only fallback.");
Assert(contentView.Contains("No scene-specific plan. Showing chapter intent.", StringComparison.Ordinal), "Writing Intent should prefer chapter intent when scene planning is sparse.");
}
static void WritingIntentClientUsesSharedWritingFollowHelper()
{
var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine");
var helper = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js"));
var initializer = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-intent.js"));
var view = File.ReadAllText(Path.Combine(root, "Views/Writing/Intent.cshtml"));
var contentView = File.ReadAllText(Path.Combine(root, "Views/Writing/_WritingIntentContent.cshtml"));
Assert(view.Contains("data-writing-intent", StringComparison.Ordinal), "Writing Intent shell should expose a stable script root.");
Assert(view.Contains("data-writing-mode=\"intent\"", StringComparison.Ordinal), "Writing Intent should identify itself as a writing-mode page.");
Assert(view.Contains("~/js/writing-follow.js", StringComparison.Ordinal), "Writing Intent should load the shared writing follow helper.");
Assert(initializer.Contains("window.PlotDirectorWritingFollow?.initialize", StringComparison.Ordinal), "Writing Intent should initialize the shared helper.");
Assert(initializer.Contains("plotdirector.writingIntent.activeTab", StringComparison.Ordinal), "Writing Intent should remember the selected tab.");
Assert(initializer.Contains("defaultEndpoint: \"/Writing/Intent/Scene\"", StringComparison.Ordinal), "Writing Intent should refresh from its partial route.");
Assert(initializer.Contains("allowChapterOnly: true", StringComparison.Ordinal), "Writing Intent should accept canonical chapter-only positions.");
Assert(helper.Contains("window.PlotDirectorStoryPosition?.eventName", StringComparison.Ordinal), "Writing Intent should receive canonical story-position events through the shared helper.");
Assert(helper.Contains("fetch(url", StringComparison.Ordinal), "Writing Intent should update in place.");
Assert(helper.Contains("position.sceneId === currentSceneId", StringComparison.Ordinal), "Writing Intent should ignore duplicate current-scene events.");
Assert(helper.Contains("position.sceneId === loadingSceneId", StringComparison.Ordinal), "Writing Intent should ignore duplicate in-flight events.");
Assert(helper.Contains("position.bookId && position.bookId !== scopedBookId", StringComparison.Ordinal), "Writing Intent should ignore unrelated scoped book events.");
Assert(helper.Contains("publishChanged", StringComparison.Ordinal), "Writing Intent manual fallback should publish canonical story-position changes.");
Assert(contentView.Contains("data-writing-intent-scene-select", StringComparison.Ordinal), "Writing Intent manual scene selector should be wired.");
Assert(contentView.Contains("data-writing-intent-chapter-select", StringComparison.Ordinal), "Writing Intent manual chapter selector should be wired.");
Assert(!helper.Contains("window.location.assign", StringComparison.Ordinal) && !helper.Contains("window.location.href", StringComparison.Ordinal), "Writing Intent must not navigate away when Word changes scene.");
}
static void GlobalWordNavigationIsRemoved()
{
var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine");
var site = File.ReadAllText(Path.Combine(root, "wwwroot/js/site.js"));
var controller = File.ReadAllText(Path.Combine(root, "Controllers/WordCompanionController.cs"));
var follow = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js"));
Assert(!site.Contains("plotdirector.followWordCompanion", StringComparison.Ordinal), "Obsolete persisted global-follow preference must not control the browser.");
Assert(!site.Contains("data-word-companion-follow-toggle", StringComparison.Ordinal), "Obsolete global-follow toggle handler must be removed.");
Assert(!controller.Contains("wordCompanionSceneChanged", StringComparison.Ordinal) && !controller.Contains("wordCompanionCharactersCreated", StringComparison.Ordinal), "Broadcasts used only by global navigation must be removed.");
Assert(site.Contains("window.PlotDirectorStoryPosition", StringComparison.Ordinal), "Shared position event helper must remain for writing windows.");
var workspace = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-workspace.js"));
Assert(workspace.Contains("connection.on(\"storyPositionChanged\"", StringComparison.Ordinal), "The workspace launcher must retain its live canonical-position feed without global follow.");
Assert(controller.Contains("BroadcastToCurrentUserAsync(\"storyPositionChanged\"", StringComparison.Ordinal), "Current scene API must still notify the writing windows.");
Assert(follow.Contains("connection.on(\"storyPositionChanged\"", StringComparison.Ordinal), "Writing windows must still receive canonical positions directly.");
}
static void WritingPairSharesCanonicalFollowInfrastructure()
{
var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine");
var context = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-context.js"));
var intent = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-intent.js"));
var helper = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js"));
Assert(context.Contains("source: \"WritingContext\"", StringComparison.Ordinal), "Writing Context should identify its canonical event source.");
Assert(intent.Contains("source: \"WritingIntent\"", StringComparison.Ordinal), "Writing Intent should identify its canonical event source.");
Assert(context.Contains("window.PlotDirectorWritingFollow?.initialize", StringComparison.Ordinal), "Writing Context should use shared follow initialization.");
Assert(intent.Contains("window.PlotDirectorWritingFollow?.initialize", StringComparison.Ordinal), "Writing Intent should use shared follow initialization.");
Assert(helper.Contains("connection.on(\"storyPositionChanged\"", StringComparison.Ordinal), "The shared helper should bridge Word story-position events for both pages.");
Assert(helper.Contains("document.addEventListener(window.PlotDirectorStoryPosition?.eventName", StringComparison.Ordinal), "Both pages should react to the same canonical browser event.");
}
static void WritingWorkspacePresenceScopesBrowserWindows()
{
var service = new WritingWorkspacePresenceService();
var word = new WordCompanionPresenceStatus
{
UserID = 9,
IsConnected = true,
DocumentOpen = true,
LinkedProjectID = 10,
LinkedBookID = 20
};
service.RegisterAsync(9, "launcher-1", new WritingWindowRegistration
{
BrowserWindowID = "launcher",
ProjectID = 10,
BookID = 20,
WritingRole = WritingWorkspaceRoles.Launcher,
CurrentRoute = "/Writer"
}, word).GetAwaiter().GetResult();
service.RegisterAsync(9, "context-1", new WritingWindowRegistration
{
BrowserWindowID = "context",
ProjectID = 10,
BookID = 20,
WritingRole = WritingWorkspaceRoles.Context,
CurrentRoute = "/Writing/Context"
}, word).GetAwaiter().GetResult();
service.RegisterAsync(9, "intent-1", new WritingWindowRegistration
{
BrowserWindowID = "intent",
ProjectID = 10,
BookID = 20,
WritingRole = WritingWorkspaceRoles.Intent,
CurrentRoute = "/Writing/Intent"
}, word).GetAwaiter().GetResult();
service.RegisterAsync(9, "other-context", new WritingWindowRegistration
{
BrowserWindowID = "other-context",
ProjectID = 10,
BookID = 21,
WritingRole = WritingWorkspaceRoles.Context,
CurrentRoute = "/Writing/Context"
}, word).GetAwaiter().GetResult();
var status = service.GetStatusAsync(9, new WritingWorkspaceScope { ProjectID = 10, BookID = 20 }, word).GetAwaiter().GetResult();
Assert(status.WordCompanionConnected && status.WordDocumentOpen, "Writing workspace should include Word Companion presence.");
Assert(status.ContextOpen && status.IntentOpen, "Matching Context and Intent windows should be open.");
Assert(status.Context?.BrowserWindowID == "context", "Workspace status should choose the matching book's Context window.");
Assert(status.Windows.All(window => window.BookID == 20), "Workspace status should not include another book's windows.");
service.DisconnectAsync("context-1", word).GetAwaiter().GetResult();
status = service.GetStatusAsync(9, new WritingWorkspaceScope { ProjectID = 10, BookID = 20 }, word).GetAwaiter().GetResult();
Assert(!status.ContextOpen && status.IntentOpen, "Disconnected Context should be removed without affecting Intent.");
}
static void WritingWorkspaceClientUsesSessionIdentityAndStableNames()
{
var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine");
var script = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-workspace.js"));
var service = File.ReadAllText(Path.Combine(root, "Services/WritingWorkspacePresenceService.cs"));
Assert(script.Contains("sessionStorage.getItem(storageKeys.windowId)", StringComparison.Ordinal), "Browser window IDs must come from sessionStorage.");
Assert(script.Contains("sessionStorage.setItem(storageKeys.windowId", StringComparison.Ordinal), "Browser window IDs must be stored per tab/window.");
Assert(!script.Contains("localStorage.getItem(storageKeys.windowId)", StringComparison.Ordinal), "Browser window IDs must not be shared through localStorage.");
Assert(script.Contains("PlotDirector${role}", StringComparison.Ordinal), "Context and Intent windows should use stable named targets.");
Assert(script.Contains("url.searchParams.set(\"bookId\", bookId)", StringComparison.Ordinal), "Workspace URLs retain book scope while one named window is reused per role.");
Assert(script.Contains("windowRefs = new Map()", StringComparison.Ordinal), "Launcher-created window references should be retained for focus.");
Assert(script.Contains("RequestWritingWindowFocus", StringComparison.Ordinal), "Launcher should fall back to SignalR focus requests.");
Assert(script.Contains("connection.onreconnected", StringComparison.Ordinal), "Writing workspace windows should re-register after SignalR reconnect.");
Assert(service.Contains("ActiveTimeout = TimeSpan.FromSeconds(45)", StringComparison.Ordinal) && service.Contains("MarkStaleOfflineAsync", StringComparison.Ordinal), "Writing workspace presence should expire stale windows.");
}
static void WritingWorkspaceLauncherUsesProgressiveScreenPlacement()
{
var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine");
var script = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-workspace.js"));
var launcher = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-workspace-launcher.js"));
var view = File.ReadAllText(Path.Combine(root, "Views/Writer/Legacy.cshtml"));
Assert(script.Contains("getScreenDetails", StringComparison.Ordinal), "Workspace launcher should use the Window Management API when available.");
Assert(script.Contains("window-management", StringComparison.Ordinal), "Workspace launcher should check/request window-management permission.");
Assert(script.Contains("sort((a, b) => a.left - b.left", StringComparison.Ordinal), "Screen topology should be derived from physical coordinates.");
Assert(script.Contains("mode: \"three-screen\"", StringComparison.Ordinal), "Three-screen layout decision is missing.");
Assert(script.Contains("key: `screen-${index}`", StringComparison.Ordinal), "Detected displays should receive stable option keys.");
Assert(script.Contains("displayByPreference", StringComparison.Ordinal), "Launcher should resolve logical and physical display preferences.");
Assert(script.Contains("preferences.contextDisplay", StringComparison.Ordinal), "Context display preference is missing.");
Assert(script.Contains("preferences.intentDisplay", StringComparison.Ordinal), "Intent display preference is missing.");
Assert(script.Contains("mode: \"two-screen\"", StringComparison.Ordinal), "Two-screen fallback is missing.");
Assert(script.Contains("mode: \"single-screen\"", StringComparison.Ordinal), "One-screen fallback is missing.");
Assert(script.Contains("localStorage.setItem(storageKeys.preferences", StringComparison.Ordinal), "Remembered layout preferences are missing.");
Assert(script.Contains("window.open(url, name, popupFeatures(display))", StringComparison.Ordinal), "Writing windows should be opened from explicit launcher clicks with placement features.");
Assert(script.Contains("window.open(buildWritingUrl(role, scope), stableWindowName(role, scope), popupFeatures(display))", StringComparison.Ordinal), "Focus actions should open missing windows on the selected display.");
Assert(script.Contains("getScreenLayout(Boolean(options.requestScreens), options.displayPreferences || {})", StringComparison.Ordinal), "Start action should pass selected display preferences into layout detection.");
Assert(script.Contains("openRoleWindow(roles.intent, resolvedScope, layout.intentDisplay)", StringComparison.Ordinal), "Start should open Intent on the selected display instead of converting the launcher window.");
Assert(!script.Contains("window.location.assign(buildWritingUrl(roles.intent", StringComparison.Ordinal), "Start should leave the launcher visible while opening the selected writing windows.");
Assert(launcher.Contains("requestScreens: true", StringComparison.Ordinal), "Screen permission should be requested from the Start action.");
Assert(launcher.Contains("workspace.getScreenLayout(true, selectedDisplayPreferences())", StringComparison.Ordinal), "Detect displays action should request physical display details.");
Assert(launcher.Contains("workspace.focusRole(role, scope, targetDisplay)", StringComparison.Ordinal), "Direct open/focus actions should use the selected display.");
Assert(view.Contains("data-start-writing-workspace", StringComparison.Ordinal), "Writer dashboard launcher start button is missing.");
Assert(view.Contains("data-writing-context-display", StringComparison.Ordinal), "Context display selector is missing.");
Assert(view.Contains("data-writing-intent-display", StringComparison.Ordinal), "Intent display selector is missing.");
Assert(view.Contains("data-detect-writing-displays", StringComparison.Ordinal), "Detect displays button is missing.");
Assert(view.Contains("data-focus-writing-context", StringComparison.Ordinal), "Focus Context action is missing.");
Assert(view.Contains("data-focus-writing-intent", StringComparison.Ordinal), "Focus Intent action is missing.");
}
static void WritingWorkspacePagesRegisterRolesWithoutChangingFollowBehavior()
{
var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine");
var contextView = File.ReadAllText(Path.Combine(root, "Views/Writing/Context.cshtml"));
var intentView = File.ReadAllText(Path.Combine(root, "Views/Writing/Intent.cshtml"));
var follow = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js"));
Assert(contextView.Contains("writingRole: window.PlotDirectorWritingWorkspace.roles.context", StringComparison.Ordinal), "Writing Context should register its workspace role.");
Assert(intentView.Contains("writingRole: window.PlotDirectorWritingWorkspace.roles.intent", StringComparison.Ordinal), "Writing Intent should register its workspace role.");
Assert(contextView.Contains("data-writing-mode=\"context\"", StringComparison.Ordinal), "Writing Context should remain a writing-mode page.");
Assert(intentView.Contains("data-writing-mode=\"intent\"", StringComparison.Ordinal), "Writing Intent should remain a writing-mode page.");
Assert(follow.Contains("registerWorkspaceRole", StringComparison.Ordinal), "Writing follow should refresh presence scope after Word updates.");
Assert(follow.Contains("connection.on(\"storyPositionChanged\"", StringComparison.Ordinal), "Existing canonical Word follow should remain.");
Assert(!follow.Contains("window.location.assign", StringComparison.Ordinal) && !follow.Contains("window.location.href", StringComparison.Ordinal), "Writing pages must still update in place without navigation.");
}
static void WordCompanionExposesWritingWorkspaceLaunchActions()
{
@ -2254,31 +2037,13 @@ static void WordCompanionExposesWritingWorkspaceLaunchActions()
Assert(view.Contains("data-open-writing-workspace", StringComparison.Ordinal), "Word Companion should expose Open Workspace.");
Assert(view.Contains("data-open-writing-context", StringComparison.Ordinal), "Word Companion should expose Open Context.");
Assert(view.Contains("data-open-writing-intent", StringComparison.Ordinal), "Word Companion should expose Open Intent.");
Assert(script.Contains("writingWindowName", StringComparison.Ordinal), "Word Companion should use stable writing window names.");
Assert(script.Contains("PlotDirector${role}_${suffix}", StringComparison.Ordinal), "Word Companion writing window names should be scoped.");
Assert(!view.Contains("data-open-writing-intent", StringComparison.Ordinal), "Standalone Intent launcher is retired.");
Assert(script.Contains("window.open(url, \"_blank\")", StringComparison.Ordinal), "Word Companion opens independent Context windows.");
Assert(script.Contains("openWritingWorkspaceButton?.addEventListener", StringComparison.Ordinal), "Word Companion Open Workspace button should be wired.");
Assert(script.Contains("openWritingContextButton?.addEventListener", StringComparison.Ordinal), "Word Companion Open Context button should be wired.");
Assert(script.Contains("openWritingIntentButton?.addEventListener", StringComparison.Ordinal), "Word Companion Open Intent button should be wired.");
Assert(!script.Contains("openWritingIntentButton?.addEventListener", StringComparison.Ordinal), "Standalone Intent listener is retired.");
}
static void WordCompanionWritingScreensReceiveResolvedContextIdentifiers()
{
var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine");
var script = File.ReadAllText(Path.Combine(root, "wwwroot/js/word-companion-host.js"));
var controller = File.ReadAllText(Path.Combine(root, "Controllers/WritingController.cs"));
var contextView = File.ReadAllText(Path.Combine(root, "Views/Writing/Context.cshtml"));
var intentView = File.ReadAllText(Path.Combine(root, "Views/Writing/Intent.cshtml"));
Assert(script.Contains("const chapterId = Number.isInteger(resolvedChapterId)", StringComparison.Ordinal), "Word Companion should prefer resolved chapter IDs for writing screen URLs.");
Assert(script.Contains("const sceneId = Number.isInteger(resolvedSceneId)", StringComparison.Ordinal), "Word Companion should prefer resolved scene IDs for writing screen URLs.");
Assert(script.Contains("url.searchParams.set(\"chapterId\", chapterId)", StringComparison.Ordinal), "Writing screen URLs should include chapterId when available.");
Assert(script.Contains("url.searchParams.set(\"sceneId\", sceneId)", StringComparison.Ordinal), "Writing screen URLs should include sceneId when available.");
Assert(script.Contains("url.searchParams.set(\"documentGuid\", documentGuid)", StringComparison.Ordinal), "Writing screen URLs should include documentGuid for diagnostics.");
Assert(controller.Contains("Guid? documentGuid", StringComparison.Ordinal), "Writing routes should accept the Word document identifier.");
Assert(contextView.Contains("data-document-guid=\"@Model.DocumentGuid\"", StringComparison.Ordinal), "Writing Context should retain the document identifier.");
Assert(intentView.Contains("data-document-guid=\"@Model.DocumentGuid\"", StringComparison.Ordinal), "Writing Intent should retain the document identifier.");
}
static void WordCompanionCanonicalMarkersDriveRuntimeFollow()
{
@ -2373,28 +2138,6 @@ static void WordCompanionDocumentIdentitySurvivesReconnect()
Assert(repository.Contains("\"dbo.ManuscriptDocument_UpdateLastOpened\"", StringComparison.Ordinal), "Last-opened update must remain stored-procedure based.");
}
static void WordCompanionMultiscreenLaunchAndFollowRemainReachable()
{
var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine");
var view = File.ReadAllText(Path.Combine(root, "Views/WordCompanionHost/Index.cshtml"));
var hostScript = File.ReadAllText(Path.Combine(root, "wwwroot/js/word-companion-host.js"));
var follow = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js"));
var contextView = File.ReadAllText(Path.Combine(root, "Views/Writing/Context.cshtml"));
var intentView = File.ReadAllText(Path.Combine(root, "Views/Writing/Intent.cshtml"));
Assert(view.Contains("data-open-writing-workspace", StringComparison.Ordinal), "Word Companion should expose the workspace launch action.");
Assert(view.Contains("data-open-writing-context", StringComparison.Ordinal), "Word Companion should expose the Context launch action.");
Assert(view.Contains("data-open-writing-intent", StringComparison.Ordinal), "Word Companion should expose the Intent launch action.");
Assert(hostScript.Contains("openWritingWindow(\"context\")", StringComparison.Ordinal), "Context launch should call the writing window helper.");
Assert(hostScript.Contains("openWritingWindow(\"intent\")", StringComparison.Ordinal), "Intent launch should call the writing window helper.");
Assert(hostScript.Contains("new URL(target === \"workspace\" ? \"/Writer\" : `/Writing/${target}`", StringComparison.Ordinal), "Writing windows should target the dedicated Context, Intent, and Workspace routes.");
Assert(hostScript.Contains("url.searchParams.set(\"sceneId\", sceneId)", StringComparison.Ordinal), "Writing windows should receive the current canonical SceneID.");
Assert(follow.Contains("connection.invoke(\"WatchWritingWorkspace\"", StringComparison.Ordinal), "Writing panes should attach to the Word Companion follow hub.");
Assert(follow.Contains("connection.on(\"storyPositionChanged\"", StringComparison.Ordinal), "Writing panes should receive runtime scene changes.");
Assert(follow.Contains("registerWindow", StringComparison.Ordinal), "Writing panes should register their multiscreen role.");
Assert(contextView.Contains("~/js/writing-follow.js", StringComparison.Ordinal), "Context page should load shared follow script.");
Assert(intentView.Contains("~/js/writing-follow.js", StringComparison.Ordinal), "Intent page should load shared follow script.");
}
static void WordCompanionModesRemainDistinct()
{
@ -2414,22 +2157,6 @@ static void WordCompanionModesRemainDistinct()
Assert(script.Contains("setFirstRunMode(false)", StringComparison.Ordinal), "Linked documents should leave the bind/import mode.");
}
static void WritingPagesDoNotRequireStoryIntelligence()
{
var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine");
var controller = File.ReadAllText(Path.Combine(root, "Controllers/WritingController.cs"));
var contextPartial = File.ReadAllText(Path.Combine(root, "Views/Writing/_WritingContextContent.cshtml"));
var intentPartial = File.ReadAllText(Path.Combine(root, "Views/Writing/_WritingIntentContent.cshtml"));
var follow = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js"));
Assert(controller.Contains("IStoryContextService storyContext", StringComparison.Ordinal), "Writing pages should use canonical story context.");
Assert(controller.Contains("IWriterWorkspaceService writerWorkspace", StringComparison.Ordinal), "Writing Intent should use existing writer workspace planning data.");
Assert(!controller.Contains("IStoryIntelligence", StringComparison.Ordinal), "Writing routes should not depend on Story Intelligence services.");
Assert(!controller.Contains("Onboarding", StringComparison.Ordinal), "Writing routes should not depend on import onboarding.");
Assert(contextPartial.Contains("@Model.EmptyTitle", StringComparison.Ordinal), "Writing Context should render a normal empty state when context is unavailable.");
Assert(intentPartial.Contains("@Model.EmptyMessage", StringComparison.Ordinal), "Writing Intent should render a normal empty state when planning data is unavailable.");
Assert(follow.Contains("No current Word scene has been received", StringComparison.Ordinal), "Writing panes should tolerate no current Word scene without Story Intelligence.");
}
static void WordCompanionHostScriptHasValidTabMapping()
{
@ -2444,43 +2171,7 @@ static void WordCompanionHostScriptHasValidTabMapping()
Assert(view.Split("word-companion-review-group").Length - 1 == 3, "Review panel should contain exactly the three review groups.");
}
static void WritingScreensShowDiagnosticEmptyStates()
{
var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine");
var viewModel = File.ReadAllText(Path.Combine(root, "ViewModels/CoreViewModels.cs"));
var controller = File.ReadAllText(Path.Combine(root, "Controllers/WritingController.cs"));
var contextPartial = File.ReadAllText(Path.Combine(root, "Views/Writing/_WritingContextContent.cshtml"));
var intentPartial = File.ReadAllText(Path.Combine(root, "Views/Writing/_WritingIntentContent.cshtml"));
var follow = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js"));
Assert(viewModel.Contains("EmptyTitle", StringComparison.Ordinal), "Writing display models should carry an empty-state title.");
Assert(viewModel.Contains("EmptyMessage", StringComparison.Ordinal), "Writing display models should carry an empty-state message.");
Assert(controller.Contains("No current Word scene received", StringComparison.Ordinal), "Writing routes should not default to Waiting for Word forever.");
Assert(controller.Contains("No Story Intelligence context is available", StringComparison.Ordinal), "Writing Context should report missing context clearly.");
Assert(controller.Contains("No writing intent is available", StringComparison.Ordinal), "Writing Intent should report missing intent clearly.");
Assert(contextPartial.Contains("@Model.EmptyTitle", StringComparison.Ordinal), "Writing Context empty state should render the diagnostic title.");
Assert(intentPartial.Contains("@Model.EmptyMessage", StringComparison.Ordinal), "Writing Intent empty state should render the diagnostic message.");
Assert(follow.Contains("setEmptyState", StringComparison.Ordinal), "Writing follow should update empty states after connection/fetch failures.");
Assert(follow.Contains("No current Word scene has been received", StringComparison.Ordinal), "Writing follow should replace indefinite waiting with a diagnostic message.");
}
static void WordCompanionThreeScreenFlowLogsConnectionIdentifiers()
{
var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine");
var hostController = File.ReadAllText(Path.Combine(root, "Controllers/WordCompanionHostController.cs"));
var wordController = File.ReadAllText(Path.Combine(root, "Controllers/WordCompanionController.cs"));
var hub = File.ReadAllText(Path.Combine(root, "Hubs/WordCompanionFollowHub.cs"));
var hostScript = File.ReadAllText(Path.Combine(root, "wwwroot/js/word-companion-host.js"));
var follow = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js"));
Assert(hostController.Contains("Serving Word Companion host", StringComparison.Ordinal), "Word Companion host route should log which host page is served.");
Assert(wordController.Contains("Word Companion current scene received", StringComparison.Ordinal), "Current-scene API should log received identifiers.");
Assert(wordController.Contains("DocumentGuidPresent", StringComparison.Ordinal), "Current-scene API should log document identifier presence without exposing the value.");
Assert(hub.Contains("Word Companion registered", StringComparison.Ordinal), "Companion SignalR registration should be logged.");
Assert(hub.Contains("Writing window registered", StringComparison.Ordinal), "Context/Intent window registration should be logged.");
Assert(hostScript.Contains("[Word Companion] Opening writing screen.", StringComparison.Ordinal), "Host UI should log direct writing screen opens.");
Assert(follow.Contains("Loading writing position", StringComparison.Ordinal), "Context/Intent follow helper should log received positions.");
}
static void WordManuscriptCleanupClassifiesPlotDirectorMarkersByTagOnly()
{
@ -6550,7 +6241,7 @@ static void CharacterMergeIsReusableStoredProcedureWorkflow()
var repository = File.ReadAllText(Path.Combine(root, "Data/Repositories.cs"));
var services = File.ReadAllText(Path.Combine(root, "Services/CoreServices.cs"));
var controller = File.ReadAllText(Path.Combine(root, "Controllers/CharactersController.cs"));
var details = File.ReadAllText(Path.Combine(root, "Views/Characters/Details.cshtml"));
var details = File.ReadAllText(Path.Combine(root, "Views/Characters/Details.cshtml")) + File.ReadAllText(Path.Combine(root, "Views/Shared/_CharacterRibbonCommands.cshtml"));
var merge = File.ReadAllText(Path.Combine(root, "Views/Characters/Merge.cshtml"));
var siCharacters = File.ReadAllText(Path.Combine(root, "Services/StoryIntelligenceCharacterImportService.cs"));
var migration = File.ReadAllText(Path.Combine(root, "Sql/165_Phase26A_PovAndCharacterIdentityFoundation.sql"));
@ -6595,7 +6286,8 @@ static void EntityPreferredNamesArePeerAliases()
var services = File.ReadAllText(Path.Combine(root, "Services/CoreServices.cs"));
var characterController = File.ReadAllText(Path.Combine(root, "Controllers/CharactersController.cs"));
var locationController = File.ReadAllText(Path.Combine(root, "Controllers/LocationsController.cs"));
var characterDetails = File.ReadAllText(Path.Combine(root, "Views/Characters/Details.cshtml"));
var characterDetails = File.ReadAllText(Path.Combine(root, "Views/Characters/Details.cshtml"))
+ File.ReadAllText(Path.Combine(root, "Views/Characters/_WorkspaceProfile.cshtml"));
var characterEdit = File.ReadAllText(Path.Combine(root, "Views/Characters/Edit.cshtml"));
var locationDetails = File.ReadAllText(Path.Combine(root, "Views/Locations/Details.cshtml"));
var locationEdit = File.ReadAllText(Path.Combine(root, "Views/Locations/Edit.cshtml"));
@ -8157,20 +7849,6 @@ static void StoryIntelligenceNarrativeStageFollowsKnowledge()
Assert(controller.Contains("ImportStoryIntelligenceKnowledge", StringComparison.Ordinal) && controller.Contains("RedirectToAction(nameof(StoryIntelligenceReviewCentre)", StringComparison.Ordinal), "Knowledge completion should return to Review Centre instead of auto-advancing.");
}
static void WordCompanionReplaysLiveCurrentSceneToWritingPanes()
{
var root = Path.Combine(AppContext.BaseDirectory, "../../../../PlotLine");
var controller = File.ReadAllText(Path.Combine(root, "Controllers/WordCompanionController.cs"));
var presence = File.ReadAllText(Path.Combine(root, "Services/WordCompanionPresenceService.cs"));
var workspace = File.ReadAllText(Path.Combine(root, "Services/WritingWorkspacePresenceService.cs"));
var script = File.ReadAllText(Path.Combine(root, "wwwroot/js/writing-follow.js"));
Assert(controller.Contains("presence.UpdateCurrentStoryPositionAsync", StringComparison.Ordinal), "Word current-scene updates should update live presence.");
Assert(presence.Contains("CurrentStoryPosition = connected ? record.CurrentStoryPosition : null", StringComparison.Ordinal), "Presence should only replay current scene while Word is live.");
Assert(workspace.Contains("CurrentStoryPosition = wordStatus.CurrentStoryPosition", StringComparison.Ordinal), "Workspace status should carry Word's current scene.");
Assert(script.Contains("storyPositionFromWorkspaceStatus", StringComparison.Ordinal), "Writing panes should read the current scene from workspace status.");
Assert(script.Contains("WatchWritingWorkspace", StringComparison.Ordinal), "Writing panes should request scoped workspace status on startup.");
}
static int CountCsvRows(string path)
=> File.ReadLines(path).Skip(1).Count(line => !string.IsNullOrWhiteSpace(line));

View File

@ -0,0 +1,25 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
// Real authentication, controllers, stored procedures and SignalR, loopback only.
// Never starts import, mail, AI, retention or other background workers.
internal static class SharedFocusBrowserHost
{
public static async Task Run()
{
var line=File.ReadLines("/etc/plotdirector/plotdirector.env").Single(s=>s.StartsWith("ConnectionStrings__DefaultConnection="));
var value=line[(line.IndexOf('=')+1)..].Trim().Trim('"','\'');
var sql=new SqlConnectionStringBuilder(value);
if(sql.InitialCatalog!="PlotDirector_Development")throw new Exception("Development only");
await using(var db=new SqlConnection(value)){await db.OpenAsync();using var command=db.CreateCommand();command.CommandText="SELECT DB_NAME()";if((string?)await command.ExecuteScalarAsync()!="PlotDirector_Development")throw new Exception("Wrong effective database");}
Environment.SetEnvironmentVariable("ConnectionStrings__DefaultConnection",value);
var app=PlotLine.Program.BuildApplication(["--environment=Development","--applicationName=PlotLine","--contentRoot="+Path.GetFullPath("PlotLine"),"--DataProtection:KeysPath=/tmp/shared-focus-test-keys"],builder=>{
foreach(var item in builder.Services.Where(s=>s.ServiceType==typeof(IHostedService)).ToArray())builder.Services.Remove(item);
builder.Configuration["SqlDiagnostics:Enabled"]="false";
});
app.Urls.Clear();app.Urls.Add("http://127.0.0.1:5258");await app.RunAsync();
}
}

View File

@ -0,0 +1,88 @@
using System.Data;
using System.Text.Json;
using Dapper;
using Microsoft.Data.SqlClient;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Services.Manuscript;
using PlotDirector.Companion.Protocol.Manuscript;
internal static class SharedFocusDatabaseTests
{
internal sealed record Fixture(int user,int project,int book,int chapter1,int chapter2,int scene1,int scene2,int scene3,Guid paragraph1,Guid paragraph2,Guid paragraph3,Guid manuscript,Guid session,int character1,int character2,int relationship,int relationshipEvent,int emptyChapter=0);
public static async Task Concurrent(bool cleanup=false)
{
var fixture=JsonSerializer.Deserialize<Fixture>(File.ReadAllText("/tmp/shared-focus-browser-scope.json"))!;
var line=File.ReadLines("/etc/plotdirector/plotdirector.env").Single(s=>s.StartsWith("ConnectionStrings__DefaultConnection="));
var connection=new SqlConnectionStringBuilder(line[(line.IndexOf('=')+1)..].Trim().Trim('"','\''));
if(connection.InitialCatalog!="PlotDirector_Development")throw new Exception("Development only");
await using var db=new SqlConnection(connection.ConnectionString);await db.OpenAsync();
if(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()")!="PlotDirector_Development")throw new Exception("Wrong effective database");
if(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID JOIN dbo.AppUser u ON u.UserID=a.UserID WHERE p.ProjectID=@project AND p.ProjectName=N'Disposable shared-focus integration' AND a.UserID=@user AND u.Email LIKE N'pwa-browser-%'",fixture)!=1)throw new Exception("Disposable fixture scope required");
if(cleanup){await db.ExecuteAsync("UPDATE dbo.Books SET IsArchived=1 WHERE BookID=@book AND ProjectID=@project;UPDATE dbo.Characters SET IsArchived=1 WHERE ProjectID=@project;UPDATE dbo.Projects SET IsArchived=1 WHERE ProjectID=@project;",fixture);Console.WriteLine("PASS isolated browser fixture archived; no real project/content changed.");return;}
async Task<SharedFocusPosition> Run(SqlConnection sql,string action,Guid window,int scene)=>await sql.QuerySingleAsync<SharedFocusPosition>("dbo.NarrativeFocus_Coordinate",new{Action=action,UserID=fixture.user,ProjectID=fixture.project,BookID=fixture.book,WindowID=window,Sequence=1,SceneID=scene},commandType:CommandType.StoredProcedure);
var before=await Run(db,"read",Guid.NewGuid(),fixture.scene1);
var pending=Enumerable.Range(0,16).Select(async index=>{await using var sql=new SqlConnection(connection.ConnectionString);await sql.OpenAsync();return await Run(sql,"publish",Guid.NewGuid(),index%2==0?fixture.scene1:fixture.scene3);}).ToArray();
var results=await Task.WhenAll(pending);var after=await Run(db,"read",Guid.NewGuid(),fixture.scene1);var changed=results.Where(r=>r.Changed).Select(r=>r.Version).Order().ToArray();
if(changed.Length<2||!changed.SequenceEqual(Enumerable.Range(1,changed.Length).Select(n=>before.Version+n))||after.Version!=changed.Last())throw new Exception("Concurrent publications lost/duplicated revision order");
Console.WriteLine("PASS sixteen real concurrent SQL connections: accepted changes receive contiguous unique revisions, final durable read equals highest accepted revision.");
await SharedFocusNativeDeliveryTests.Run(connection.ConnectionString,fixture);
}
public static async Task Run(string scopePath,bool persist=false)
{
var line=File.ReadLines("/etc/plotdirector/plotdirector.env").Single(s=>s.StartsWith("ConnectionStrings__DefaultConnection="));var builder=new SqlConnectionStringBuilder(line[(line.IndexOf('=')+1)..].Trim().Trim('"','\''));if(builder.InitialCatalog!="PlotDirector_Development")throw new Exception("Development only");await using var db=new SqlConnection(builder.ConnectionString);await db.OpenAsync();if(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()")!="PlotDirector_Development")throw new Exception("Wrong effective database");var scope=JsonDocument.Parse(File.ReadAllText(scopePath)).RootElement;int project=scope.GetProperty("project").GetInt32(),user=scope.GetProperty("user").GetInt32();if(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.ProjectUserAccess a JOIN dbo.AppUser u ON u.UserID=a.UserID WHERE a.ProjectID=@project AND a.UserID=@user AND a.AccessRole=N'Owner' AND a.IsActive=1 AND u.Email LIKE N'pwa-browser-%'",new{project,user})!=1)throw new Exception("Explicit disposable account required");
using var tx=db.BeginTransaction();
try{
// Isolated collaborator fixture: no existing project/content or subscription is modified.
project=await db.QuerySingleAsync<int>("INSERT dbo.Projects(ProjectName) VALUES(N'Disposable shared-focus integration');SELECT CAST(SCOPE_IDENTITY() AS int)",transaction:tx);
await db.ExecuteAsync("INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole) VALUES(@project,@user,N'Collaborator')",new{project,user},tx);
var ids=await db.QuerySingleAsync<(int Book,int C1,int C2,int S1,int S2,int S3)>("""
DECLARE @revision int=(SELECT TOP(1) RevisionStatusID FROM dbo.RevisionStatuses ORDER BY RevisionStatusID),@time int=(SELECT TOP(1) TimeModeID FROM dbo.TimeModes),@confidence int=(SELECT TOP(1) TimeConfidenceID FROM dbo.TimeConfidences);
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@project,N'Shared focus disposable fixture',999999,999999);DECLARE @book int=SCOPE_IDENTITY();
INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) VALUES(@book,2,N'Focus fixture first',10,@revision);DECLARE @c1 int=SCOPE_IDENTITY();
INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) VALUES(@book,1,N'Focus fixture second',20,@revision);DECLARE @c2 int=SCOPE_IDENTITY();
INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID) VALUES(@c1,200,N'Focus fixture early',10,@time,@confidence,@revision);DECLARE @s1 int=SCOPE_IDENTITY();
INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID) VALUES(@c1,1,N'Focus fixture late',20,@time,@confidence,@revision);DECLARE @s2 int=SCOPE_IDENTITY();
INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID) VALUES(@c2,1,N'Focus fixture next chapter',10,@time,@confidence,@revision);DECLARE @s3 int=SCOPE_IDENTITY();
SELECT @book Book,@c1 C1,@c2 C2,@s1 S1,@s2 S2,@s3 S3;
""",new{project},tx);
int emptyChapter=await db.QuerySingleAsync<int>("DECLARE @revision int=(SELECT RevisionStatusID FROM dbo.Chapters WHERE ChapterID=@chapter);INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) VALUES(@book,100,N'Focus fixture empty boundary',15,@revision);SELECT CAST(SCOPE_IDENTITY() AS int);",new{book=ids.Book,chapter=ids.C1},tx);
Guid manuscript=Guid.NewGuid(),session=Guid.NewGuid(),p1=Guid.NewGuid(),p2=Guid.NewGuid(),p3=Guid.NewGuid(),sk1=Guid.NewGuid(),sk2=Guid.NewGuid(),sk3=Guid.NewGuid();string hash=new('A',64);
var state=new ParagraphManuscript{BookId=ids.Book,ProjectId=project,ManuscriptId=manuscript,SessionId=session,WordRevision=1,Revision=1,LastRequestId=Guid.NewGuid(),UpdatedUtc=DateTime.UtcNow,Paragraphs=[new(){ChapterId=ids.C1,SceneId=sk1,Story=true,PositionVerified=true,Occurrence=new(){Id=p1,Start=10,End=20,Text="Isolated focus paragraph one."}},new(){ChapterId=ids.C1,SceneId=sk2,Story=true,PositionVerified=true,Occurrence=new(){Id=p2,Start=20,End=30,Text="Isolated focus paragraph two."}},new(){ChapterId=ids.C2,SceneId=sk3,Story=true,PositionVerified=true,Occurrence=new(){Id=p3,Start=40,End=50,Text="Isolated focus paragraph three."}}],Scenes=[new(){Id=sk1,CanonicalId=ids.S1,ChapterId=ids.C1},new(){Id=sk2,CanonicalId=ids.S2,ChapterId=ids.C1},new(){Id=sk3,CanonicalId=ids.S3,ChapterId=ids.C2}],ChapterCheckpoints=[new(){ChapterId=ids.C1,ContentHash=hash,IdentityHash=hash,MappingHash=hash},new(){ChapterId=ids.C2,ContentHash=hash,IdentityHash=hash,MappingHash=hash}]};
await db.ExecuteAsync("INSERT dbo.BookParagraphManuscripts(BookID,ManuscriptID,Revision,RequestID,Payload) VALUES(@book,@manuscript,1,NEWID(),@payload)",new{book=ids.Book,manuscript,payload=JsonSerializer.Serialize(state)},tx);
foreach(var chapter in new[]{ids.C1,ids.C2})await db.ExecuteAsync("""
INSERT dbo.BookChapterValidations(BookID,ChapterID,UserID,SessionID,ManuscriptID,WordRevision,RequestID,ContentHash,IdentityHash,MappingHash,Positions,SourceRevision,ValidatedUtc,ExpiresUtc)
VALUES(@book,@chapter,@user,@session,@manuscript,1,NEWID(),@hash,@hash,@hash,@positions,1,SYSUTCDATETIME(),DATEADD(hour,2,SYSUTCDATETIME()));
""",new{book=ids.Book,chapter,user,session,manuscript,hash,positions=JsonSerializer.Serialize(state.Paragraphs.Where(p=>p.ChapterId==chapter).Select(p=>new ChapterPosition(p.Occurrence.Id,p.Occurrence.Start,p.Occurrence.End,chapter,state.Scenes.Single(s=>s.Id==p.SceneId).CanonicalId,true)))},tx);
int ca=await db.QuerySingleAsync<int>("dbo.Character_Save",new{ProjectID=project,CharacterName="Shared focus fixture A "+ids.Book},tx,commandType:CommandType.StoredProcedure),cb=await db.QuerySingleAsync<int>("dbo.Character_Save",new{ProjectID=project,CharacterName="Shared focus fixture B "+ids.Book},tx,commandType:CommandType.StoredProcedure);
int type=await db.ExecuteScalarAsync<int>("SELECT TOP(1) RelationshipTypeID FROM dbo.RelationshipTypes WHERE TypeName=N'Friend'",transaction:tx),rs=await db.ExecuteScalarAsync<int>("SELECT TOP(1) RelationshipStateID FROM dbo.RelationshipStates ORDER BY SortOrder,RelationshipStateID",transaction:tx);
int rel=await db.QuerySingleAsync<int>("dbo.Relationship_Save",new{ProjectID=project,CharacterAID=ca,CharacterBID=cb,RelationshipTypeID=type,IsPermanent=true,IsKnownToReader=false,IsInitialRelationship=true,InitialBookID=ids.Book,InitialRelationshipStateID=rs,Notes="Disposable shared focus fixture"},tx,commandType:CommandType.StoredProcedure);
int ev=await db.QuerySingleAsync<int>("dbo.RelationshipEvent_Save",new{CharacterRelationshipID=rel,SceneID=ids.S1,RelationshipStateID=rs,Intensity=3,IsKnownToOtherCharacter=true,Description="Disposable earlier-scene event"},tx,commandType:CommandType.StoredProcedure);
await db.ExecuteAsync("""
DECLARE @role int=(SELECT TOP(1) CharacterRoleInSceneTypeID FROM dbo.CharacterRoleInSceneTypes ORDER BY CharacterRoleInSceneTypeID),@presence int=(SELECT TOP(1) PresenceTypeID FROM dbo.PresenceTypes WHERE TypeName=N'Present');
INSERT dbo.SceneCharacters(SceneID,CharacterID,RoleInSceneTypeID,PresenceTypeID) SELECT s.ID,c.ID,@role,@presence FROM (VALUES(@s1),(@s2),(@s3))s(ID) CROSS JOIN(VALUES(@ca),(@cb))c(ID);
""",new{s1=ids.S1,s2=ids.S2,s3=ids.S3,ca,cb},tx);
var fixture=new Fixture(user,project,ids.Book,ids.C1,ids.C2,ids.S1,ids.S2,ids.S3,p1,p2,p3,manuscript,session,ca,cb,rel,ev,emptyChapter);
if(persist){await db.ExecuteAsync("DECLARE @revision int,@time int,@confidence int;SELECT @revision=RevisionStatusID,@time=TimeModeID,@confidence=TimeConfidenceID FROM dbo.Scenes WHERE SceneID=@scene;INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID) VALUES(@chapter,2,N'Focus fixture archive guard',20,@time,@confidence,@revision);",new{scene=ids.S3,chapter=ids.C2},tx);tx.Commit();File.WriteAllText("/tmp/shared-focus-browser-scope.json",JsonSerializer.Serialize(fixture));Console.WriteLine("PASS isolated shared-focus browser fixture prepared; no real manuscript used.");return;}
void Check(bool condition,string name){if(!condition)throw new Exception(name);Console.WriteLine("PASS shared focus SQL: "+name);}
async Task<SharedFocusPosition> Run(string action,Guid? window=null,long sequence=0,int? chapter=null,int? scene=null,Guid? paragraph=null,int direction=0)=>await db.QuerySingleAsync<SharedFocusPosition>("dbo.NarrativeFocus_Coordinate",new{Action=action,UserID=user,ProjectID=project,BookID=ids.Book,WindowID=window,Sequence=sequence,ChapterID=chapter,SceneID=scene,ParagraphID=paragraph,Direction=direction},tx,commandType:CommandType.StoredProcedure);
var a=Guid.NewGuid();var b=Guid.NewGuid();var empty=await Run("read");Check(empty.Version==0&&!empty.IsValid,"new clients do not manufacture or publish initial focus");
var first=await Run("publish",a,1,scene:ids.S1);Check(first.Version==1&&first.Changed&&first.ChapterID==ids.C1,"scene resolves its canonical chapter and receives atomic revision one");
var same=await Run("publish",a,2,scene:ids.S1);Check(!same.Changed&&same.Version==1,"unchanged effective focus does not broadcast or increment revision");
var second=await Run("publish",b,1,paragraph:p2);Check(second.Version==2&&second.ParagraphID==p2&&second.SceneID==ids.S2,"accepted paragraph resolves canonical chapter and scene without text in the packet");
var duplicate=await Run("publish",a,1,scene:ids.S1);Check(duplicate.Version==2&&duplicate.ParagraphID==p2&&!duplicate.Changed,"replayed older client sequence cannot overwrite a newer window");
var held=await Run("resolve",a,3,scene:ids.S3);var still=await Run("read");Check(held.ChapterID==ids.C2&&still.Version==2&&still.ParagraphID==p2,"held local navigation validates without changing shared state");
Check((await Run("resolve",chapter:ids.C2,direction:1)).SceneID==ids.S3,"chapter-only Next remains within its own nonempty chapter");
Check((await Run("resolve",chapter:ids.C1,direction:-1)).SceneID==ids.S2,"chapter-only Previous selects the last scene of its chapter");
Check((await Run("resolve",chapter:emptyChapter,direction:1)).SceneID==ids.S3&&(await Run("resolve",chapter:emptyChapter,direction:-1)).SceneID==ids.S2,"empty chapter boundaries use canonical neighboring chapters rather than book endpoints");
Check((await Run("resolve",chapter:ids.C2,scene:ids.S3,paragraph:p3,direction:1)).ParagraphID==p3,"stepping beyond the final scene preserves the precise held paragraph");
var next=await Run("publish",b,2,direction:1);Check(next.SceneID==ids.S3&&next.Version==3,"scene stepping uses canonical sort order across chapter boundaries");
var precise=await Run("publish",b,3,paragraph:p3);var endpoint=await Run("publish",b,4,direction:1);Check(!endpoint.Changed&&endpoint.Version==precise.Version&&endpoint.ParagraphID==p3,"publishing Next at the final scene does not drop paragraph precision or increment revision");
await db.ExecuteAsync("UPDATE dbo.Scenes SET IsArchived=1 WHERE SceneID=@id",new{id=ids.S3},tx);var invalid=await Run("validate",scene:ids.S3,chapter:ids.C2);Check(!invalid.IsValid&&(await Run("read")).Version==precise.Version,"structural invalidation is explicit and never redirects a held reference");
var mapped=await db.QuerySingleAsync<FocusWordPosition>("dbo.NarrativeFocus_WordPosition",new{Action="position",UserID=user,BookID=ids.Book,ManuscriptID=manuscript,SessionID=session,WordRevision=1,Cursor=12},tx,commandType:CommandType.StoredProcedure);Check(mapped.ParagraphID==p1,"native deliberate selection maps only through exact verified live evidence");
var missing=await db.QueryAsync<FocusWordPosition>("dbo.NarrativeFocus_WordPosition",new{Action="target",UserID=user,BookID=ids.Book,ManuscriptID=manuscript,SessionID=Guid.NewGuid(),WordRevision=1,ParagraphID=p1},tx,commandType:CommandType.StoredProcedure);Check(!missing.Any(),"a different Word session never receives another session's offsets");
var bad=await Run("validate",chapter:ids.C2,paragraph:p1);Check(!bad.IsValid,"incompatible paragraph/chapter references are rejected");
try{await db.QuerySingleAsync<SharedFocusPosition>("dbo.NarrativeFocus_Coordinate",new{Action="read",UserID=-99,ProjectID=project,BookID=ids.Book},tx,commandType:CommandType.StoredProcedure);throw new Exception("Unauthorized scope accepted");}catch(SqlException e)when(e.Number==51000){Check(true,"ownership enforced for every focus read/write");}
}finally{try{tx.Rollback();}catch(InvalidOperationException){}}
Console.WriteLine("PASS shared focus fixture completely rolled back.");
}
}

View File

@ -0,0 +1,60 @@
using System.Data;
using Dapper;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Logging.Abstractions;
using PlotDirector.Companion.Protocol;
using PlotLine.Data;
using PlotLine.Hubs;
using PlotLine.Services;
using PlotLine.Services.NativeCompanion;
// Real coordinator/SQL and the existing native queue, with a recording transport instead of Word.
internal static class SharedFocusNativeDeliveryTests
{
private sealed class Factory(string value):ISqlConnectionFactory
{public IDbConnection CreateConnection()=>new SqlConnection(value);}
public static async Task Run(string value,SharedFocusDatabaseTests.Fixture f)
{
void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS shared native delivery: "+name);}
var packets=new List<(string Name,object? Packet)>();
var client=NativeWorkflowTests.Proxy<IClientProxy>((_,args)=>{packets.Add(((string)args![0]!,((object?[])args[1]!)[0]));return Task.CompletedTask;});
var clients=NativeWorkflowTests.Proxy<IHubClients>((_,args)=>{Check((string)args![0]! ==NativeCompanionPresenceHub.UserGroup(f.user),"notifications use only the authenticated author group");return client;});
var hub=NativeWorkflowTests.Proxy<IHubContext<NativeCompanionPresenceHub>>((_,_)=>clients);
var store=new NativePresenceStore(TimeProvider.System);var instance=Guid.NewGuid();var window=Guid.NewGuid();var mode=Guid.NewGuid();
var service=new SharedManuscriptFocus(new Factory(value),hub,store,NullLogger<SharedManuscriptFocus>.Instance);
NativePresence Position(long sequence,bool held=false,bool saved=true)=>new(){BookId=f.book,ManuscriptId=f.manuscript,Revision=1,Sequence=sequence,WordSaved=saved,WordAvailable=true,WordRunning=true,CanAcknowledgeNavigation=true,CanSharedFocus=true,FocusHeld=held,AnyFollowingWindows=!held,FocusWindowID=window,FocusModeRequest=mode,CursorStart=12,DocumentTitle="Synthetic shared-focus fixture"};
NativeLease Put(NativePresence position){Check(store.Put(f.user,"synthetic-focus-grant",DateTimeOffset.UtcNow.AddMinutes(10),instance,f.session,position),"exact native lease accepted");return store.Read(f.user,f.book).Single(l=>l.Instance==instance&&l.Session==f.session);}
AdapterCommand? Take()=>store.TakeNavigation(f.user,"synthetic-focus-grant",instance,f.session);
var first=Position(1);first.DeliberateFocusSequence=1;
await service.NativeObservation(f.user,f.project,Put(first),false);
var current=await service.Run(f.user,new(){ProjectID=f.project,BookID=f.book},"read");
Check(current.ParagraphID==f.paragraph1&&current.OriginWindowID==window,"Word alone publishes the verified canonical paragraph");
var command=Take();Check(command?.BackgroundFocus==true&&command.Chapter?.Start==10&&command.FocusVersion==current.Version,"shared navigation uses the existing exact-session background command");
var ack=Position(2);ack.NavigationAcknowledgedId=command!.Id;ack.NavigationResult="completed";Put(ack);
var count=packets.Count;
await service.NativeObservation(f.user,f.project,Put(Position(3)),false);
Check(packets.Count==count&&(await service.Run(f.user,new(){ProjectID=f.project,BookID=f.book},"read")).Version==current.Version,"passive native presence neither publishes nor polls shared focus");
var browserWindow=Guid.NewGuid();
var next=await service.Run(f.user,new(){ProjectID=f.project,BookID=f.book,WindowID=browserWindow,Sequence=1,ParagraphID=f.paragraph3},"publish");
command=Take();Check(command?.BackgroundFocus==true&&command.Chapter?.Start==40&&command.FocusVersion==next.Version&&command.FocusOriginWindowID==browserWindow,"browser focus queues the exact verified paragraph across chapters without activation semantics");
ack=Position(4);ack.NavigationAcknowledgedId=command!.Id;ack.NavigationResult="completed";Put(ack);
mode=Guid.NewGuid();var held=await service.NativeObservation(f.user,f.project,Put(Position(5,true)),true);
Check(held=="held"&&Take()==null,"held Word consumes no shared navigation command");
mode=Guid.NewGuid();await service.NativeObservation(f.user,f.project,Put(Position(6)),true);command=Take();
Check(command?.BackgroundFocus==true&&command.FocusVersion==next.Version&&(await service.Run(f.user,new(){ProjectID=f.project,BookID=f.book},"read")).Version==next.Version,"Word release queues latest revision without publishing its old cursor");
var failed=Position(7);failed.NavigationAcknowledgedId=command!.Id;failed.NavigationResult="failed";Check(await service.NativeObservation(f.user,f.project,Put(failed),true)=="word-busy"&&Take()==null,"failed background receipt is reported as busy rather than successful following");
Check(await service.NativeObservation(f.user,f.project,Put(Position(8,saved:false)),true)=="save-required","unsaved Word reports its limitation while the coordinator stays available");
var otherInstance=Guid.NewGuid();var otherSession=Guid.NewGuid();var other=Position(1);other.Sequence=1;
Check(store.Put(f.user,"synthetic-other-session",DateTimeOffset.UtcNow.AddMinutes(10),otherInstance,otherSession,other),"independent native session accepted");
var unmapped=await service.NativeObservation(f.user,f.project,store.Read(f.user,f.book).Single(l=>l.Instance==otherInstance),true);
Check(unmapped=="word-unmapped"&&store.TakeNavigation(f.user,"synthetic-other-session",otherInstance,otherSession)==null,"unmapped sessions receive an explicit limitation and never another session's offsets");
await using var validation=new SqlConnection(value);await validation.OpenAsync();
try{
await validation.ExecuteAsync("UPDATE dbo.BookChapterValidations SET WordRevision=2 WHERE BookID=@book AND UserID=@user AND SessionID=@session",new{book=f.book,user=f.user,session=f.session});
var saved=Position(9);saved.Revision=2;saved.ParagraphRevision=2;
await service.NativeObservation(f.user,f.project,Put(saved),true);var renewed=Take();
Check(renewed?.Revision==2&&renewed.Id!=command!.Id&&renewed.FocusVersion==next.Version,"saved Word revision and accepted snapshot receive a fresh delivery identity without manufacturing shared focus");
}finally{await validation.ExecuteAsync("UPDATE dbo.BookChapterValidations SET WordRevision=1 WHERE BookID=@book AND UserID=@user AND SessionID=@session AND WordRevision=2",new{book=f.book,user=f.user,session=f.session});}
}
}

View File

@ -11,6 +11,8 @@ BEGIN
DECLARE @book int,@otherBook int,@chapter int,@otherChapter int,@empty int,@tail int,@first int,@last int,@version bigint,@i int=1;
BEGIN TRY
BEGIN TRANSACTION;
INSERT dbo.Projects(ProjectName) VALUES(N'Disposable narrative focus regression');SET @project=SCOPE_IDENTITY();
INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole) VALUES(@project,@user,N'Collaborator');
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@project,N'Disposable narrative focus fixture',99999,99999);SET @book=SCOPE_IDENTITY();
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@project,N'Disposable other scope',99999,99999);SET @otherBook=SCOPE_IDENTITY();
INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) VALUES(@book,1,N'Fixture first chapter',1,@revision);SET @chapter=SCOPE_IDENTITY();
@ -26,12 +28,13 @@ BEGIN
END;
INSERT dbo.WriterWorkingObjectives(UserID,BookID,ChapterID,SceneID,Activity,Intention) VALUES(@user,@book,@chapter,@first,N'Revising',N'Independent original objective');
EXEC dbo.NarrativeFocus_Read @UserID=@user,@ProjectID=@project,@BookID=@book;
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID=@chapter AND SceneID=@first) THROW 51999,'Initial valid objective was not seeded',1;
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID IS NULL AND SceneID IS NULL AND Version=0) THROW 51999,'Initial read manufactured focus from an objective',1;
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@SceneID=@first,@ExpectedVersion=0;
EXEC dbo.NarrativeFocus_Read @UserID=@user,@ProjectID=@project,@BookID=@otherBook;
IF @phase IN(1,2,3)
BEGIN
DECLARE @wrongUser int=CASE WHEN @phase=1 THEN -1 ELSE @user END,@wrongProject int=CASE WHEN @phase=2 THEN -1 ELSE @project END,@wrongBook int=CASE WHEN @phase=3 THEN @otherBook ELSE @book END;
EXEC dbo.NarrativeFocus_Set @UserID=@wrongUser,@ProjectID=@wrongProject,@BookID=@wrongBook,@SceneID=@first,@ExpectedVersion=1;
DECLARE @wrongUser int=CASE WHEN @phase=1 THEN -1 ELSE @user END,@wrongProject int=CASE WHEN @phase=2 THEN -1 ELSE @project END,@wrongBook int=CASE WHEN @phase=3 THEN @otherBook ELSE @book END,@wrongVersion bigint=CASE WHEN @phase=3 THEN 0 ELSE 1 END;
EXEC dbo.NarrativeFocus_Set @UserID=@wrongUser,@ProjectID=@wrongProject,@BookID=@wrongBook,@SceneID=@first,@ExpectedVersion=@wrongVersion;
THROW 51999,'Unauthorised focus accepted',1;
END;
IF @phase=4
@ -80,18 +83,18 @@ BEGIN
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@SceneID=@first,@ExpectedVersion=@version;
UPDATE dbo.Scenes SET ChapterID=@otherChapter WHERE SceneID=@first;
EXEC dbo.NarrativeFocus_Read @UserID=@user,@ProjectID=@project,@BookID=@book;
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID=@chapter AND SceneID IS NULL) THROW 51999,'Moved scene was silently followed',1;
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID=@chapter AND SceneID=@first) THROW 51999,'Read redirected an invalid moved scene',1;
IF EXISTS(SELECT 1 FROM dbo.NarrativeFocusHistory WHERE UserID=@user AND BookID=@book AND ChapterID=@chapter AND SceneID=@first) THROW 51999,'Invalid history survived',1;
SELECT @version=Version FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book;
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@SceneID=@last,@ExpectedVersion=@version;
DELETE dbo.Scenes WHERE SceneID=@last;
EXEC dbo.NarrativeFocus_Read @UserID=@user,@ProjectID=@project,@BookID=@book;
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID=@otherChapter AND SceneID IS NULL) THROW 51999,'Deleted scene retained or silently retargeted',1;
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID=@otherChapter AND SceneID=@last) THROW 51999,'Read redirected a deleted scene reference',1;
SELECT @version=Version FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book;
EXEC dbo.NarrativeFocus_Set @UserID=@user,@ProjectID=@project,@BookID=@book,@ChapterID=@chapter,@ExpectedVersion=@version;
UPDATE dbo.Chapters SET IsArchived=1 WHERE ChapterID=@chapter;
EXEC dbo.NarrativeFocus_Read @UserID=@user,@ProjectID=@project,@BookID=@book;
IF EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID IS NOT NULL) THROW 51999,'Archived chapter retained',1;
IF NOT EXISTS(SELECT 1 FROM dbo.NarrativeFocus WHERE UserID=@user AND BookID=@book AND ChapterID=@chapter) THROW 51999,'Read redirected an archived chapter reference',1;
EXEC dbo.WriterObjective @UserID=@user,@BookID=@book;
IF NOT EXISTS(SELECT 1 FROM dbo.WriterWorkingObjectives WHERE UserID=@user AND BookID=@book AND SceneID=@first AND ChapterID=@chapter) THROW 51999,'Invalid objective target mutated',1;
ROLLBACK;

View File

@ -10,6 +10,8 @@ DECLARE @user int,@project int,@book int,@chapter int,@scene int,@revision int,@
SELECT TOP(1) @user=a.UserID,@project=p.ProjectID FROM dbo.Projects p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID AND a.IsActive=1 WHERE p.IsArchived=0 ORDER BY p.ProjectID;
SELECT TOP(1) @revision=RevisionStatusID,@time=TimeModeID,@confidence=TimeConfidenceID FROM dbo.Scenes;
IF @user IS NULL OR @revision IS NULL THROW 51999,'No fixture scope',1;
INSERT dbo.Projects(ProjectName) VALUES(N'Disposable focus repository regression');SET @project=SCOPE_IDENTITY();
INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole) VALUES(@project,@user,N'Collaborator');
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder) VALUES(@project,N'Disposable repository focus fixture',99999,99999);SET @book=SCOPE_IDENTITY();
INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) VALUES(@book,1,N'Repository fixture chapter',1,@revision);SET @chapter=SCOPE_IDENTITY();
INSERT dbo.Scenes(ChapterID,SceneNumber,SceneTitle,SortOrder,TimeModeID,TimeConfidenceID,RevisionStatusID) VALUES(@chapter,1,N'Repository fixture scene',1,@time,@confidence,@revision);SET @scene=SCOPE_IDENTITY();

View File

@ -112,7 +112,7 @@ internal static class ToolbarBrowserHost
return model;
}
private static async Task RenderFullAsync(HttpContext context, string controller, string actionName, object model)
private static async Task RenderFullAsync(HttpContext context, string controller, string actionName, object model, Dictionary<string,object?>? extras=null)
{
context.Request.RouteValues["controller"] = controller;
context.Request.RouteValues["action"] = actionName;
@ -120,8 +120,10 @@ internal static class ToolbarBrowserHost
var view = context.RequestServices.GetRequiredService<ICompositeViewEngine>().GetView(null, $"/Views/{controller}/{actionName}.cshtml", true);
if (!view.Success) throw new Exception(string.Join(",", view.SearchedLocations));
using var writer = new StringWriter();
var fullData=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model,["WritingEmbedded"]=true};
if(extras!=null)foreach(var item in extras)fullData[item.Key]=item.Value;
await view.View.RenderAsync(new ViewContext(action, view.View,
new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model, ["WritingEmbedded"] = context.Request.Query["embedded"] == "true" },
fullData,
new TempDataDictionary(context, context.RequestServices.GetRequiredService<ITempDataProvider>()), writer, new HtmlHelperOptions()));
context.Response.ContentType = "text/html; charset=utf-8";
await context.Response.WriteAsync(writer.ToString());
@ -139,8 +141,12 @@ internal static class ToolbarBrowserHost
builder.Services.AddScoped<PlotLine.Services.Investigations.InvestigationGuidanceService>();
builder.Services.AddScoped<PlotLine.Services.Investigations.InvestigationService>();
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton<PlotLine.Services.Context.ContextWindows>();
builder.Services.AddSingleton(FixtureProxy<IWordCompanionRepository>((name,args)=>Task.FromResult<WordCompanionBookStructureResponse?>((int)args![0]! is 12 or 13?new(){BookId=(int)args[0]!,Chapters=[new(){ChapterId=10,Scenes=[new(){SceneId=22}]},new(){ChapterId=11,Scenes=[new(){SceneId=23}]}]}:null)));
builder.Services.AddSingleton(FixtureProxy<ICharacterRepository>((name,args)=>name switch{"GetCharacterAsync"=>Task.FromResult<Character?>((int)args![0]! is >=1 and <=120?new(){CharacterID=(int)args[0]!,ProjectID=7,CharacterName="Fixture participant"}:null),"GetRelationshipAsync"=>Task.FromResult<CharacterRelationship?>((int)args![0]! is >=1 and <=300?new(){CharacterRelationshipID=(int)args[0]!,ProjectID=7}:null),_=>throw new NotSupportedException(name)}));
builder.Services.AddSingleton(FixtureProxy<ILocationRepository>((name,args)=>name=="GetAsync"?Task.FromResult<LocationItem?>((int)args![0]! ==77?new(){LocationID=77,ProjectID=7,LocationName="Saved room"}:null):throw new NotSupportedException(name)));
builder.Services.AddSingleton<IWordCompanionPresenceService, WordCompanionPresenceService>();
builder.Services.AddSingleton<IWritingWorkspacePresenceService, WritingWorkspacePresenceService>();
builder.Services.AddSingleton(FixtureProxy<IOnboardingRepository>((name, args) => throw new NotSupportedException(name)));
builder.Services.AddSingleton(FixtureProxy<IOnboardingBuildRepository>((name, args) => throw new NotSupportedException(name)));
builder.Services.AddSingleton(FixtureProxy<IManuscriptScanPreviewStore>((name, args) => throw new NotSupportedException(name)));
@ -200,6 +206,10 @@ internal static class ToolbarBrowserHost
builder.Services.AddSingleton(FixtureProxy<IFeatureRequestService>((name, args) => name == "CountAttentionForUserAsync" ? Task.FromResult(0) : throw new NotSupportedException(name)));
builder.Services.AddSingleton(FixtureProxy<IOnboardingService>((name, args) => name == "ShouldShowWordCompanionHeaderAsync" ? Task.FromResult(false) : throw new NotSupportedException(name)));
builder.Services.AddSingleton(FixtureProxy<IStoryIntelligenceGlobalProgressService>((name, args) => name == "GetForCurrentUserAsync" ? Task.FromResult(new StoryIntelligenceGlobalProgressViewModel()) : throw new NotSupportedException(name)));
builder.Services.AddSingleton(FixtureProxy<IStoryIntelligenceService>((_,_)=>throw new NotSupportedException()));
builder.Services.AddSingleton(FixtureProxy<IStoryIntelligenceResultRepository>((_,_)=>throw new NotSupportedException()));
builder.Services.AddSingleton(FixtureProxy<IOnboardingStoryIntelligenceService>((_,_)=>throw new NotSupportedException()));
builder.Services.AddSingleton(FixtureProxy<ICharacterEnrichmentService>((name,_)=>name=="GetCurrentForCharacterAsync"?Task.FromResult<CharacterEnrichmentRun?>(null):throw new NotSupportedException(name)));
builder.Services.AddSingleton<IHelpService, HelpService>();
builder.Services.AddSingleton<IWritingSolverRepository, WritingSolverFixtureRepository>();
builder.Services.AddSingleton<IWritingSolverWorkspaceContext, SolverWorkspaceFixture>();
@ -254,10 +264,11 @@ internal static class ToolbarBrowserHost
model.SceneID=id;model.ChapterID=id==32?22:21;model.SceneNumber=id==101?2:1;
model.SceneTitle=$"Fixture scene {id}";
model.Chapter!.ChapterID=model.ChapterID;model.Chapter.ChapterNumber=id==32?2:1;
if(context.Request.Query["retainNarrativeFocus"]!="true")
if(context.Request.Query["retainNarrativeFocus"]!="true"&&id is not (22 or 23))
await context.RequestServices.GetRequiredService<INarrativeFocus>().Open(context.RequestServices.GetRequiredService<ICurrentUserService>().UserId!.Value,null,id);
await RenderFullAsync(context,"Scenes","Edit",model);
}).WithOrder(-1);
app.MapGet("/Characters",async (HttpContext context)=>await RenderFullAsync(context,"Characters","Index",new CharacterListViewModel{Project=new(){ProjectID=7,ProjectName="Fixture project",AccessRole="Owner"},Characters=[new(){CharacterID=5,ProjectID=7,CharacterName="Fixture participant",CharacterImportance=6}]})).WithOrder(-1);
app.MapGet("/Projects", () => Results.Redirect("/fixture"));
app.MapGet("/map-story-fixture", () => {
var projection = MapStoryComposer.Compose(MapStoryTests.Fixture(), MapStoryTests.Plots(), 1);
@ -331,7 +342,7 @@ internal static class ToolbarBrowserHost
scene.PrimaryLocationID=77;scene.FloorPlanID=1;scene.InitialFloorPlanFloorID=8;
((WritingContextDisplayViewModel)model).FloorPlan=new(){FloorPlan=new(){FloorPlanID=1,Name="The inn"},Floors=[new(){FloorPlanFloorID=8,Name="Upper floor",GridWidth=20,GridHeight=10}],Blocks=[new(){FloorPlanFloorID=8,FloorPlanBlockID=9,LocationID=77,LocationName="Guest room",X=2,Y=2,WidthCells=4,HeightCells=3}]};
}
var writingRoute=new RouteData();writingRoute.Values["controller"]="Writing";var action=new ActionContext(context,writingRoute,new ActionDescriptor());var path=role=="evidence"?"/Views/Writing/_IntentAssessment.cshtml":role=="context"?"/Views/Writing/_WritingContextContent.cshtml":"/Views/Writing/_WritingIntentContent.cshtml";
var writingRoute=new RouteData();writingRoute.Values["controller"]="Writing";var action=new ActionContext(context,writingRoute,new ActionDescriptor());var path=role=="evidence"?"/Views/Writing/_IntentAssessment.cshtml":role=="context"?"/Views/Writing/_WritingContextOverview.cshtml":"/Views/Writing/_WritingIntentPlan.cshtml";
var view=context.RequestServices.GetRequiredService<ICompositeViewEngine>().GetView(null,path,false);using var writer=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model};
await view.View!.RenderAsync(new ViewContext(action,view.View,data,new TempDataDictionary(context,context.RequestServices.GetRequiredService<ITempDataProvider>()),writer,new HtmlHelperOptions()));
if(context.Request.Query["fragment"]=="true"){context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString());return;}
@ -378,8 +389,86 @@ internal static class ToolbarBrowserHost
if(step=="Preview")model.Preview=new(new(upload,[12,13],0,"Recovered harbour","",Guid.NewGuid(),DateTime.UtcNow.AddMinutes(20)),"fixture-confirmation",snapshot,12,5,context.Request.Query.ContainsKey("full")?0:4,package.Warnings);
await RenderFullAsync(context,"BookRecovery",step,step=="Complete"?new BookRecoveryReceipt{ProjectID=7,BooksCreated=2}:model);
});
app.MapGet("/Writing/Context", context => RenderFullAsync(context, "Writing", "Context", new WritingContextPageViewModel { ProjectID = 7, BookID = int.TryParse(context.Request.Query["bookId"].ToString(), out var bookId) ? bookId : 12 })).WithOrder(-1);
app.MapGet("/Writing/Intent", context => RenderFullAsync(context, "Writing", "Intent", new WritingIntentPageViewModel { ProjectID = 7, BookID = int.TryParse(context.Request.Query["bookId"].ToString(), out var bookId) ? bookId : 12 })).WithOrder(-1);
app.MapGet("/Writing/Context", async context =>
{
context.Request.RouteValues["controller"] = "Writing";
var pinned=context.Request.Query["pinned"]=="true";
var sceneId=int.TryParse(context.Request.Query["sceneId"],out var selected)?selected:22;
var page=new WritingContextPageViewModel { ProjectID=7, BookID=12, ChapterID=10, SceneID=sceneId,
Display=new(){SceneOptions=[new("Chapter one · scene one","22",sceneId==22),new("Chapter two · scene two","23",sceneId==23)]} };
await RenderFullAsync(context,"Writing","Context",page,new Dictionary<string,object?> { ["NativeSnapshot"]=pinned });
}).WithOrder(-1);
app.MapGet("/Writing/Intent",context=>{context.Response.Redirect("/Writing/Context"+context.Request.QueryString);return Task.CompletedTask;}).WithOrder(-1);
app.MapGet("/context-family-index-fixture",context=>{
var fixture=ContextFamilyTests.Fixture(context.Request.Query["large"]=="true",int.TryParse(context.Request.Query["sceneId"],out var scene)?scene:22,context.Request.Query["many"]=="true");
if(context.Request.Query["split"]=="true")fixture.Structure=new(fixture.Structure.Seeds,fixture.Structure.Links.Where(r=>!(r.CharacterAID is 3 or 4 && r.CharacterBID==5)).ToList());
if(context.Request.Query["merge"]=="true")fixture.Structure=new(fixture.Structure.Seeds,fixture.Structure.Links.Append(new(){CharacterRelationshipID=500,CharacterAID=8,CharacterBID=22,RelationshipTypeName="Spouse",RelationshipCategoryName="Romantic / Sexual"}).ToList());
return context.Response.WriteAsJsonAsync(PlotLine.Services.Context.ContextFamilyExploration.Index(fixture.Structure,fixture.Scene));
});
app.MapGet("/context-family-tree-fixture",context=>{
var fixture=ContextFamilyTests.Fixture(context.Request.Query["large"]=="true",int.TryParse(context.Request.Query["sceneId"],out var scene)?scene:22,context.Request.Query["many"]=="true");var focus=int.TryParse(context.Request.Query["focusId"],out var fid)?fid:5;
if(context.Request.Query["split"]=="true")fixture.Structure=new(fixture.Structure.Seeds,fixture.Structure.Links.Where(r=>!(r.CharacterAID is 3 or 4 && r.CharacterBID==5)).ToList());
if(context.Request.Query["merge"]=="true")fixture.Structure=new(fixture.Structure.Seeds,fixture.Structure.Links.Append(new(){CharacterRelationshipID=500,CharacterAID=8,CharacterBID=22,RelationshipTypeName="Spouse",RelationshipCategoryName="Romantic / Sexual"}).ToList());
var expanded=context.Request.Query["expanded"].Select(s=>int.Parse(s!)).ToArray();var topology=new PlotLine.Services.Context.ContextFamilyTopology(fixture.Structure.Links);(int[] People,int[] Links,IReadOnlyList<PlotLine.Services.Context.ContextFamilyBranch> Branches,bool Truncated) visible;
try{visible=topology.Visible(focus,expanded);}catch(ArgumentException){context.Response.StatusCode=400;return context.Response.WriteAsJsonAsync(new{message="Choose branches within the selected family."});}
var graph=PlotLine.Services.Context.ContextRelationshipLenses.Compose(new(new(){Books=[new(){BookID=12}],Chapters=[new(){ChapterID=10,BookID=12}],Scenes=[new(){SceneID=fixture.Scene.SceneID,ChapterID=10}],Characters=fixture.Structure.Seeds.Where(c=>visible.People.Contains(c.CharacterID)).ToList(),Relationships=fixture.Structure.Links.Where(r=>visible.Links.Contains(r.CharacterRelationshipID)).ToList()},focus,visible.Truncated),"family",fixture.Scene,context.Request.Query["readonly"]!="true");
return context.Response.WriteAsJsonAsync(new PlotLine.Services.Context.ContextFamilyTree(topology.Key(focus),graph,visible.Branches,topology.Warnings(visible.People)));
});
app.MapGet("/relationship-evolution-fixture",async context=>{int count=int.TryParse(context.Request.Query["count"],out var n)?n:1;var model=new RelationshipEvolutionViewModel{Project=new(){ProjectID=7,ProjectName="Evolution fixture"},Relationship=CharacterWorkspaceBrowserFixture.Relationship(),ReturnCharacterID=5,CanEdit=context.Request.Query["viewer"]!="true",Events=Enumerable.Range(1,count).Select(i=>new PlotLine.Models.RelationshipProgressionPoint{RelationshipEventID=i,CharacterRelationshipID=9,SceneID=i,SceneNumber=i,BookTitle="Recorded book",ChapterNumber=1,SceneTitle="Canonical scene "+i,GlobalSceneIndex=i*3,Intensity=i==2?null:Math.Min(10,i+2),RelationshipStateName="Recorded state "+i,Description="Canonical event description",TotalRecords=count}).ToArray()};await RenderFullAsync(context,"Dynamics","Relationship",model);});
app.MapGet("/character-workspace-fixture",async context=>{
var id=int.TryParse(context.Request.Query["id"],out var cid)?cid:5;var profile=CharacterWorkspaceBrowserFixture.Header(id,context.Request.Query["viewer"]=="true");profile.WorkspaceTab=context.Request.Query["tab"].FirstOrDefault();if(profile.WorkspaceTab!=null)profile.WorkspacePage=CharacterWorkspaceBrowserFixture.Page(id,new(){Tab=profile.WorkspaceTab},context.Request.Query["viewer"]=="true");await RenderFullAsync(context,"Characters","Details",profile);
});
app.MapGet("/character-workspace-tab-fixture",async context=>{
int? Number(string key)=>int.TryParse(context.Request.Query[key],out var value)?value:null;var q=new CharacterWorkspaceQuery{Tab=context.Request.Query["Tab"].FirstOrDefault()??"overview",Page=Number("Page")??1,SceneID=Number("SceneID"),BookID=Number("BookID"),RelationshipID=Number("RelationshipID"),Search=context.Request.Query["Search"],Category=context.Request.Query["Category"]};var model=CharacterWorkspaceBrowserFixture.Page(Number("id")??5,q,context.Request.Query["viewer"]=="true",context.Request.Query["removed"]=="true",context.Request.Query["notes"].FirstOrDefault());await WorkspacePartial(context,"_WorkspaceTab",model);
});
app.MapGet("/character-workspace-operation-fixture",async context=>{
var action=context.Request.Query["operation"].FirstOrDefault()??"definition";var model=CharacterWorkspaceBrowserFixture.Operation(5,action,int.TryParse(context.Request.Query["relationshipId"],out var r)?r:9,int.TryParse(context.Request.Query["eventId"],out var e)?e:null,context.Request.Query["protected"]=="true");if(context.Request.Query["invalid"]=="true"){context.Response.StatusCode=400;model.Notes=context.Request.Query["notes"].FirstOrDefault()??model.Notes;context.Items["WorkspaceValidation"]="The record changed. Your draft is retained.";}await WorkspacePartial(context,"_WorkspaceOperation",model);
});
app.MapGet("/character-workspace-family-fixture",context=>{var expanded=context.Request.Query["expanded"].Select(v=>int.Parse(v!)).ToArray();return context.Response.WriteAsJsonAsync(CharacterWorkspaceBrowserFixture.Family(int.TryParse(context.Request.Query["focusId"],out var f)?f:5,expanded,context.Request.Query["removed"]=="true"));});
static async Task WorkspacePartial(HttpContext context,string partial,object model){var action=new ActionContext(context,new RouteData(),new ActionDescriptor());var view=context.RequestServices.GetRequiredService<ICompositeViewEngine>().GetView(null,"/Views/Characters/"+partial+".cshtml",false);using var writer=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model};if(context.Items["WorkspaceValidation"] is string error)data.ModelState.AddModelError("",error);await view.View!.RenderAsync(new ViewContext(action,view.View,data,new TempDataDictionary(context,context.RequestServices.GetRequiredService<ITempDataProvider>()),writer,new HtmlHelperOptions()));context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString());}
app.MapGet("/context-edit-fixture",async context=>{
var action=new ActionContext(context,new RouteData(),new ActionDescriptor());var view=context.RequestServices.GetRequiredService<ICompositeViewEngine>().GetView(null,"/Views/Writing/_ContextCharacterEdit.cshtml",false);
var model=new PlotLine.Services.Context.ContextCharacterEditForm{BookID=12,SceneID=22,CharacterID=5,Field=context.Request.Query["field"].ToString(),CharacterName="Fixture participant",Label="Focused correction",Value="Saved value",Fingerprint="fixture-fingerprint"};
if(model.Field=="life-status"){model.Value=null;model.Options=[new("Unrecorded",""),new("Living","false"),new("Deceased","true")];}
if(model.Field is "classification" or "location")model.Options=[new("Recorded option","Saved value"),new("Other option","Other")];
using var writer=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model};
if(context.Request.Query["invalid"]=="true"){data.ModelState.AddModelError("Value","Synthetic validation: draft retained.");model.Value="Entered draft";}
await view.View!.RenderAsync(new ViewContext(action,view.View,data,new TempDataDictionary(context,context.RequestServices.GetRequiredService<ITempDataProvider>()),writer,new HtmlHelperOptions()));context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString());
});
app.MapGet("/context-relationship-edit-fixture",async context=>{
var action=new ActionContext(context,new RouteData(),new ActionDescriptor());var view=context.RequestServices.GetRequiredService<ICompositeViewEngine>().GetView(null,"/Views/Writing/_ContextRelationshipEdit.cshtml",false);
var model=new PlotLine.Services.Context.ContextRelationshipForm{BookID=12,SceneID=22,RelationshipID=9,Mode="scene",SourceID=5,TargetID=6,TypeID=1,StateID=1,Label="Relationship development at selected scene",Notes="Saved scene note",Fingerprint="fixture",Characters=[new("Fixture participant","5"),new("Other character","6")],Types=[new("Family · Parent","1")],States=[new("Established","1")]};
using var writer=new StringWriter();await view.View!.RenderAsync(new ViewContext(action,view.View,new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model},new TempDataDictionary(context,context.RequestServices.GetRequiredService<ITempDataProvider>()),writer,new HtmlHelperOptions()));context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString());
});
app.MapGet("/context-lenses-fixture",(HttpContext context)=>Results.Json(ContextRelationshipBrowserFixture.Graph(context)));
app.MapGet("/context-lenses-lookup-fixture",()=>Results.Json(new[]{new{id=7,name="An established relative with a deliberately long name 7",archived=false}}));
app.MapGet("/context-names-fixture/{part}",ContextNamesBrowserFixture.Render);
app.MapGet("/context-tab-fixture/{tool}",async context=>
{
var sceneId=int.TryParse(context.Request.Query["sceneId"],out var id)?id:22;
var scene=new SceneEditViewModel { SceneID=sceneId, ChapterID=sceneId==23?11:10,
SceneTitle="Scene "+sceneId+" · A deliberately long scene title for a narrow reference screen", Summary="Saved scene summary and provenance",ScenePurposeNotes="Reveal the letter",SceneOutcomeNotes="A decision changes the plan",
Project=new(){ProjectID=7,ProjectName="Fixture project"},Book=new(){BookID=12,BookTitle="Fixture book"},Chapter=new(){ChapterID=10,ChapterNumber=1,ChapterTitle="Opening"},
SceneCharacters=[new(){CharacterID=5,CharacterName="Fixture participant",RoleInSceneTypeName="Observer",EmotionalState="Uncertain",PhysicalCondition="Tired",LocationName="Saved room",EntryLocationName="Hall",ExitLocationName="Garden"}] };
var model=new WritingContextDisplayViewModel { Context=new(){Position=new(7,12,scene.ChapterID,sceneId),Scene=scene} };
scene.POVCharacterID=5;
var catalogue=Enumerable.Range(5,12).Select(id=>new Character{CharacterID=id,ProjectID=7,CharacterName=id==5?"Fixture participant":"A long established character name "+id,CharacterImportance=id==5?6:2}).ToList();
scene.SceneCharacters=catalogue.Select(c=>new SceneCharacter{SceneCharacterID=c.CharacterID,CharacterID=c.CharacterID,SceneID=sceneId,CharacterName=c.CharacterName,PresenceTypeName=c.CharacterID==6?"Mentioned Only":"Present",RoleInSceneTypeName="Observer",EmotionalState=c.CharacterID==5?"Uncertain":null,PhysicalCondition="Tired",LocationID=77}).ToList();
model=new WritingContextDisplayViewModel { Context=new(){Position=new(7,12,scene.ChapterID,sceneId),Scene=scene,Narrative=new(){Chapters=[new(){ChapterID=10,BookID=12},new(){ChapterID=11,BookID=12}],Scenes=[new(){SceneID=21,ChapterID=10,SceneTitle="Earlier"},new(){SceneID=22,ChapterID=10,SceneTitle="Current"},new(){SceneID=23,ChapterID=11,SceneTitle="Following"}]}} };
var appearances=scene.SceneCharacters.Concat(new SceneCharacter[]{new(){CharacterID=5,SceneID=21,PresenceTypeName="Present",LocationID=78},new(){CharacterID=5,SceneID=23,PresenceTypeName="Present",LocationID=79}}).ToList();
model.CharacterExplorer=PlotLine.Services.Context.ContextCharacterPanels.Compose(model,catalogue,appearances,[new(){LocationID=77,LocationName="Saved room"},new(){LocationID=78,LocationName="Earlier hall"},new(){LocationID=79,LocationName="Following garden"}],true);
model.ContextRelationshipCanEdit=true;
model.RelationshipMap=new(){Relationships=[new(){CharacterRelationshipID=9,CharacterAID=5,CharacterBID=6,CharacterAName="Fixture participant",CharacterBName="A long established character name 6",RelationshipCategoryName="Family",RelationshipTypeName="Parent",CurrentStateName="Established",InitialStateEditable=true,Notes="Explicit recorded family note",History=[new(){SceneID=22,Label="Current scene",StateName="Established",Notes="An explicit development"}]},new(){CharacterRelationshipID=10,CharacterAID=5,CharacterBID=7,CharacterAName="Fixture participant",CharacterBName="Another character",RelationshipCategoryName="Social",RelationshipTypeName="Friend",CurrentStateName="Trusting",IsReciprocal=true}]};
model.NamePanel=ContextNamesBrowserFixture.Panel();
var action=new ActionContext(context,new RouteData(),new ActionDescriptor());
var view=context.RequestServices.GetRequiredService<ICompositeViewEngine>().GetView(null,"/Views/Writing/_ContextTab.cshtml",false);
using var writer=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model};
data["ContextTabPartial"]=context.Request.RouteValues["tool"]?.ToString()switch{"characters"=>"_WritingContextPeople","names"=>"_ContextNames","relationships"=>"_ContextRelationships",_=>"_WritingContextOverview"};
await view.View!.RenderAsync(new ViewContext(action,view.View,data,new TempDataDictionary(context,context.RequestServices.GetRequiredService<ITempDataProvider>()),writer,new HtmlHelperOptions()));
context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString());
});
app.MapGet("/scenario-fixture/{view}", async (HttpContext context, string view) =>
{
var project = new Project { ProjectID = 7, ProjectName = "Scenario visual qualification" };
@ -677,6 +766,8 @@ internal static class ToolbarBrowserHost
context.Response.ContentType = "text/html; charset=utf-8";
await context.Response.WriteAsync("<!doctype html><html lang='en' data-app-theme='" + initialTheme + "' data-theme='" + (initialTheme.EndsWith("dark") ? "dark" : "light") + "'><head><script src='/js/application-display-mode.js'></script><link rel='manifest' href='/site.webmanifest'><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><link rel='stylesheet' href='/lib/bootstrap/dist/css/bootstrap.min.css'><link rel='stylesheet' href='/css/site.css'><link rel='stylesheet' href='/css/plotline-theme.css'><link rel='stylesheet' href='/css/application-navigation.css'><link rel='stylesheet' href='/css/application-shell.css'><link rel='stylesheet' href='/css/record-workspace.css'><link rel='stylesheet' href='/css/application-context-menu.css'><link rel='stylesheet' href='/css/plot-line-workspace.css'><link rel='stylesheet' href='/css/onboarding.css'></head><body data-pd-user-id='" + context.User.FindFirstValue(ClaimTypes.NameIdentifier) + "' data-pd-project-id='7' class='app-layout'><header class='pd-application-header'>" + menu + toolbar + "</header><template data-pwa-initial-contributions>" + contributions + "</template><link rel='stylesheet' href='/css/scene-explorer.css'><script src='/js/scene-explorer.js'></script><script src='/js/narrative-focus.js' defer></script><script src='/js/narrative-focus-workspaces.js' defer></script><script src='/js/application-page-context.js'></script><div class='plotline-help-main'><div class='container-fluid plotline-shell " + (recordLayout is null ? "pd-dashboard-shell" : $"pd-record-canvas pd-record-canvas--{recordLayout}") + "'><main data-pwa-page-content class='pb-3'>" + surface + "</main><script>window.PlotDirectorPageContext?.activate();</script></div></div><script src='/lib/bootstrap/dist/js/bootstrap.bundle.min.js'></script><script src='/js/application-navigation.js'></script><script src='/js/application-toolbar.js'></script>" + appearanceScript + "<script src='/js/application-shell.js'></script><script src='/js/application-theme-sync.js'></script><script src='/js/site.js'></script><script src='/js/application-pwa.js'></script><script src='/js/application-context-menu.js'></script>" + writerScripts + "</body></html>");
});
app.MapHub<PlotLine.Hubs.StoryIntelligenceHub>("/hubs/story-intelligence");
app.MapHub<PlotLine.Hubs.NativeCompanionPresenceHub>("/hubs/native-companion");
app.MapHub<PlotLine.Hubs.WordCompanionFollowHub>("/hubs/word-companion-follow");
await app.RunAsync();
}

View File

@ -27,7 +27,7 @@ internal static class WordMarkerSecurityTests
});
var client=Proxy<IClientProxy>((name,args)=>{sends++;return Task.CompletedTask;});
var clients=Proxy<IHubCallerClients>((name,args)=>client);
var hub=new WordCompanionFollowHub(null!,null!,null!,null!,null!,repository,NullLogger<WordCompanionFollowHub>.Instance)
var hub=new WordCompanionFollowHub(null!,null!,null!,null!,repository,NullLogger<WordCompanionFollowHub>.Instance)
{Context=new Caller(),Clients=clients};
foreach(var action in new Func<Task>[]{()=>hub.CompleteOnboardingBuildMarkerSync(99),()=>hub.RequireOnboardingBuildManualSave(99,"save"),()=>hub.FailOnboardingBuildMarkerSync(99,"failed")})
{
@ -45,7 +45,7 @@ internal static class WordMarkerSecurityTests
var legacy=new PlotLine.Services.WordCompanionPresenceService();
var books=Proxy<IBookRepository>((_,_)=>Task.FromResult<PlotLine.Models.Book?>(new(){BookID=3,ProjectID=1}));
var access=Proxy<IWordCompanionRepository>((_,_)=>Task.FromResult<PlotLine.Models.WordCompanionBookStructureResponse?>(new(){BookId=3}));
var combined=new WordCompanionFollowHub(legacy,null!,null!,null!,null!,repository,NullLogger<WordCompanionFollowHub>.Instance,nativePresence:native,nativeBooks:books,nativeAccess:access){Context=new Caller(),Groups=Proxy<IGroupManager>((_,_)=>Task.CompletedTask)};
var combined=new WordCompanionFollowHub(legacy,null!,null!,null!,repository,NullLogger<WordCompanionFollowHub>.Instance,nativePresence:native,nativeBooks:books,nativeAccess:access){Context=new Caller(),Groups=Proxy<IGroupManager>((_,_)=>Task.CompletedTask)};
var status=await combined.WatchCompanionPresence();Check(status.IsConnected&&status.CompanionVersion=="Native"&&status.LinkedBookID==3&&status.CurrentStoryPosition?.SceneId==20,"Existing website status must use the authoritative native session");
native.Remove(4,"grant",instance,session);Check(!(await combined.WatchCompanionPresence()).IsConnected,"Website status cannot keep a native session green after disconnect");
}

View File

@ -55,9 +55,8 @@ internal static class WriterFoundationTests
Check(scopes.Count == 0, "inaccessible project never reaches a queue repository");
var missingStory = Proxy<IStoryContextService>((n,a) => Task.FromResult<StoryContextViewModel?>(null));
var references = new WritingController(missingStory, null!, null!, Proxy<IWriterWorkspaceService>((n,a)=>throw new Exception(n)), Microsoft.Extensions.Logging.Abstractions.NullLogger<WritingController>.Instance);
var missing = (ViewResult)await references.Context(1,2,null,999,null,pinned:true);
Check(((WritingContextPageViewModel)missing.Model!).WorkingContext == null, "unresolved route scene never becomes a pinned authorised selection");
var references = new WritingController(missingStory, null!, null!, Microsoft.Extensions.Logging.Abstractions.NullLogger<WritingController>.Instance);
Check(await references.Context(1,2,null,999,null,pinned:true) is ForbidResult, "unresolved or unauthorized scope cannot become a pinned selection");
var plans = new WritingPlanSummary[] { new(){WritingPlanID=1,ProjectID=1,BookID=2}, new(){WritingPlanID=2,ProjectID=1,BookID=3}, new(){WritingPlanID=3,ProjectID=1,BookID=null}, new(){WritingPlanID=4,ProjectID=9,BookID=99} };
var scheduleRepo = Proxy<IWritingScheduleRepository>((n,a) => n switch

View File

@ -27,7 +27,7 @@ internal static class WritingContextNavigationTests
var native=new NativeWorkspaceController(access,NativeWorkflowTests.Proxy<IBookRepository>((n,a)=>Task.FromResult<Book?>(new(){BookID=12,ProjectID=7,BookTitle="Fixture book"})),NativeWorkflowTests.Proxy<INativeReviewRepository>((n,a)=>throw new Exception("Context launch must not load old review/iframe shell")),presence){ControllerContext=new(){HttpContext=new DefaultHttpContext{User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7")],"fixture"))}}};
var direct=await native.Workspace(12,instance,session,"context") as RedirectToActionResult;
Check(direct?.ActionName=="Context"&&direct.ControllerName=="Writing"&&Equals(direct.RouteValues!["instanceId"],instance),"Native Context opens the existing Writing workspace directly and preserves document selection, with no iframe");
var controller=new WritingController(null!,null!,null!,null!,NullLogger<WritingController>.Instance){ControllerContext=new(){HttpContext=new DefaultHttpContext{User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7")],"fixture"))}}};
var controller=new WritingController(null!,null!,null!,NullLogger<WritingController>.Instance){ControllerContext=new(){HttpContext=new DefaultHttpContext{User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7")],"fixture"))}}};
Task<IActionResult> Navigate(Guid? document=null)=>controller.NavigateWord(12,23,document??instance,session,access,paragraphs,presence);
Check(await Navigate() is OkObjectResult,"Explicit cross-chapter navigation accepts an owned scene and current verified paragraph start");
var command=presence.TakeNavigation(7,"installation",instance,session);Check(command?.Kind=="navigate"&&command.Chapter?.Start==100&&command.Revision==3,"Existing positional command routes to exact session/revision without writing prose or markers");

View File

@ -30,7 +30,7 @@ internal static class WritingContextPlotLinesTests
var permissions=NativeWorkflowTests.Proxy<IProjectAccessService>((n,a)=>Task.FromResult(allowed));
var book= new Book{BookID=12,ProjectID=7};
var books=NativeWorkflowTests.Proxy<IBookRepository>((n,a)=>Task.FromResult<Book?>(book));
var controller=new WritingController(null!,null!,null!,null!,NullLogger<WritingController>.Instance);
var controller=new WritingController(null!,null!,null!,NullLogger<WritingController>.Instance);
Check(await controller.ContextPlotLines(7,12,repository,permissions,books) is NotFoundResult&&reads==0,"Unauthorised requests must not read saved plot data");
allowed=true;book.ProjectID=8;
Check(await controller.ContextPlotLines(7,12,repository,permissions,books) is NotFoundResult&&reads==0,"A book in another project must not leak saved developments");

View File

@ -1,3 +1,5 @@
using Microsoft.AspNetCore.SignalR;
using PlotLine.Hubs;
using System.Diagnostics;
using System.Reflection;
using System.Security.Claims;
@ -34,6 +36,23 @@ internal static class WritingIntegrationTests
await ReadOnlyScene();
await ResolutionAndIntent();
await ChronologyAndReuse();
await NotificationBoundary();
}
private static async Task NotificationBoundary()
{
string? group=null,eventName=null,payload=null;var fail=false;
var client=Stub<IClientProxy>((name,args)=>{if(fail)throw new InvalidOperationException("Synthetic disconnected transport");eventName=(string)args![0]!;payload=JsonSerializer.Serialize(args[1]);return Task.CompletedTask;});
var clients=Stub<IHubClients>((name,args)=>{group=(string)args![0]!;return client;});
var hub=Stub<IHubContext<NativeCompanionPresenceHub>>((name,args)=>clients);
var notifications=new ContextWorkspaceNotifications(hub,NullLogger<ContextWorkspaceNotifications>.Instance);
await notifications.Invalidate(7,2,3,20);
Check(group==NativeCompanionPresenceHub.UserGroup(7)&&eventName=="ContextInvalidated"&&payload!.Contains("bookId"),"Accepted-data invalidations use the authenticated account's existing hub group and lightweight scope");
await notifications.Invalidate(7,projectId:1);
Check(payload!.Contains("\"projectId\":1")&&payload.Contains("\"bookId\":null"),"Project identity changes invalidate relevant windows across books using only IDs");
await notifications.Position(7);
Check(eventName=="ContextPositionChanged"&&!payload!.Contains("sceneId"),"Office notifications are hints, not invented authoritative cursor payloads");
fail=true;await notifications.Invalidate(7,2);
Check(true,"Notification transport failure cannot turn a committed manuscript save into failure");
}
private static async Task ReadOnlyScene()
{
@ -102,7 +121,7 @@ internal static class WritingIntegrationTests
var goal=new ChapterGoal{GoalSummary="An author's objective",EmotionalGoal="Doubt → commitment",MustInclude="An unresolved promise",ReaderTakeaway="A possibility, not canon"};
var workflow=new ChapterWorkflowViewModel{Project=scene.Project!,Book=scene.Book!,Chapter=scene.Chapter!,Goal=goal};
var writer=Stub<IWriterWorkspaceService>((n,a)=>n=="GetChapterWorkflowAsync"?Task.FromResult<ChapterWorkflowViewModel?>(workflow):throw new Exception("Intent read attempted a write"));
var controller=new WritingController(story,null!,null!,writer,NullLogger<WritingController>.Instance,companion,presence,Stub<IProjectAccessService>((n,a)=>Task.FromResult(allowed)),
var controller=new WritingController(story,null!,null!,NullLogger<WritingController>.Instance,companion,presence,Stub<IProjectAccessService>((n,a)=>Task.FromResult(allowed)),
Stub<IChapterSyncRepository>((n,a)=>n=="Position"?Task.FromResult<ParagraphPosition?>(mapping?new(){Revision=3,ChapterID=2,SceneID=presence.Read(7,2).Single().Position.SceneId}:null):throw new Exception("Context must not synchronise or reconcile")))
{ControllerContext=new(){HttpContext=new DefaultHttpContext{User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7")],"fixture"))}}};
Beat();
@ -110,9 +129,12 @@ internal static class WritingIntegrationTests
Check(page.WorkingContext?.VerifiedWord?.Selection.SceneID==20 && page.WorkingContext.Working==null,"Verified native projection leaves working focus independent");
Check(page.SceneID==20&&page.Display!.HasScene&&page.Display.FollowStatus=="Following Word","Native launch opens its exact verified scene rather than the book's first scene");
var before=JsonSerializer.Serialize(new{scene.ScenePurposeNotes,scene.SceneOutcomeNotes,goal});
var intent=(WritingIntentPageViewModel)((ViewResult)await controller.Intent(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!;
Check(intent.SceneID==20&&intent.Display!.ChapterWorkflow!.Goal==goal&&intent.Display.Context!.Scene!.ScenePurposeNotes==scene.ScenePurposeNotes,"Native Intent retrieves the selected scene's existing purpose and chapter objectives");
Check(JsonSerializer.Serialize(new{scene.ScenePurposeNotes,scene.SceneOutcomeNotes,goal})==before,"Opening Context and Intent preserves all author-entered decisions verbatim");
var redirect=(RedirectToActionResult)controller.Intent(1,2,2,20,null,instanceId:instance,sessionId:session);
Check(redirect.ActionName=="Context" && (Guid)redirect.RouteValues!["sessionId"]! == session,"Intent compatibility preserves native session and routes only to Context");
Check(JsonSerializer.Serialize(new{scene.ScenePurposeNotes,scene.SceneOutcomeNotes,goal})==before,"Opening Context preserves all author-entered decisions verbatim");
Check(await controller.ContextCharacters(1,2,2,20,instance,session) is PartialViewResult characters && characters.ViewName=="_ContextTab","Characters has its own authorized partial endpoint");
Check(await controller.ContextCharacters(1,2,2,99,instance,session) is ConflictObjectResult,"Partial endpoint refuses a claimed scene different from the current session");
Check(await controller.ContextCharacters(1,2,2,20,instance,null) is BadRequestResult,"Partial endpoint rejects incomplete native document identity");
Beat(saved:false);var oldReads=reads;
page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!;
Check(!page.Display!.HasScene&&reads==oldReads,"Unsaved native mapping waits without loading an unrelated saved scene");
@ -120,15 +142,16 @@ internal static class WritingIntegrationTests
Check(!page.Display!.HasScene&&reads==oldReads,"A stale database checkpoint cannot launch a scene merely claimed by the last heartbeat");mapping=true;
Beat(paragraph:0);page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!;
Check(!page.Display!.HasScene&&reads==oldReads,"Chapter-capable sessions without accepted position evidence cannot launch claimed scene IDs");
Beat(current:null);intent=(WritingIntentPageViewModel)((ViewResult)await controller.Intent(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!;
Check(intent.Display!.IsChapterOnly&&intent.Display.ChapterWorkflow!.Goal==goal,"A verified chapter with no mapped scene can show its own saved chapter intent");
Beat(current:null);page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!;
Check(!page.Display!.HasScene,"A chapter without a mapped scene does not invent scene reference data");
Beat();onRead=()=>{revision++;Beat(current:99);};
page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session)).Model!;
Check(!page.Display!.HasScene,"A Word cursor/revision change during server loading cannot render the earlier cursor as current");
Beat();Check(await controller.ContextScene(1,2,2,20,instance,session) is ConflictObjectResult,"Native partial requests reject mappings that change during data loading");onRead=null;
Beat();allowed=false;
Check(await controller.Context(1,2,null,null,null,instanceId:instance,sessionId:session) is ForbidResult,"Native Context launch authorises the book before resolving or displaying its scene");allowed=true;
Check(await controller.Intent(1,2,null,null,null,instanceId:Guid.NewGuid(),sessionId:session) is ViewResult missing&&((WritingIntentPageViewModel)missing.Model!).Display!.HasScene==false,"Exact document selection cannot fall back to another connected Word instance");
page=(WritingContextPageViewModel)((ViewResult)await controller.Context(1,2,null,null,null,instanceId:Guid.NewGuid(),sessionId:session)).Model!;
Check(!page.Display!.HasScene,"Exact document selection cannot fall back to another connected Word instance");
Check(await controller.Context(1,2,null,null,null,instanceId:instance) is BadRequestObjectResult,"Incomplete native session identity is rejected");
}
}

View File

@ -0,0 +1,37 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using PlotLine.Services;
using PlotLine.ViewModels;
namespace PlotLine.Controllers;
[Authorize,Route("Characters/Workspace"),ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
public sealed class CharacterWorkspaceController(CharacterWorkspace workspace):Controller
{
[HttpGet("Tab/{id:int}")]
public async Task<IActionResult> Tab(int id,[FromQuery]CharacterWorkspaceQuery query,CancellationToken ct)
{try{return PartialView("~/Views/Characters/_WorkspaceTab.cshtml",await workspace.Page(id,query,ct));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(new{message=e.Message});}catch(SqlException e)when(e.Number is 51020 or 51022){return BadRequest(new{message="This character or story point is unavailable."});}}
[HttpGet("Family/{id:int}")]
public async Task<IActionResult> Family(int id,int? focusId,[FromQuery]int[]? expanded,CancellationToken ct)
{try{return Ok(await workspace.Family(id,focusId,expanded??[],ct));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(new{message=e.Message});}}
[HttpGet("Story/{id:int}")]
public async Task<IActionResult> Story(int id,int? sceneId,CancellationToken ct)
{try{return Ok(await workspace.Story(id,sceneId,ct));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(new{message=e.Message});}}
[HttpGet("Lookup/{id:int}")]
public async Task<IActionResult> Lookup(int id,string? search,CancellationToken ct)
{try{return Ok(await workspace.Lookup(id,search??"",ct));}catch(UnauthorizedAccessException){return Forbid();}}
[HttpGet("Operation/{id:int}")]
public async Task<IActionResult> Operation(int id,int relationshipId,int? eventId,string operation="definition",CancellationToken ct=default)
{try{return PartialView("~/Views/Characters/_WorkspaceOperation.cshtml",await workspace.Operation(id,relationshipId,eventId,operation,ct));}catch(UnauthorizedAccessException){return Forbid();}catch(SqlException e)when(e.Number==51020){return Forbid();}catch(ArgumentException e){return BadRequest(new{message=e.Message});}}
[HttpPost("Operation/{id:int}"),ValidateAntiForgeryToken]
public async Task<IActionResult> Operation(int id,CharacterWorkspaceOperation input,CancellationToken ct)
{
if(input.CharacterID!=id)return Forbid();try{if(!ModelState.IsValid)throw new ArgumentException("Check the fields below.");await workspace.Change(input,ct);return Ok(new{saved=true,message=input.Action=="archive"?"Relationship removed from active views. History retained; restore is available in Archived Items.":input.Action=="event-remove"?"One relationship event removed.":"Relationship changes saved."});}
catch(UnauthorizedAccessException){return Forbid();}catch(Exception e)when(e is ArgumentException or InvalidOperationException){CharacterWorkspaceOperation frame;try{frame=await workspace.Operation(id,input.RelationshipID,input.EventID,input.Action,ct);}catch(UnauthorizedAccessException){return Forbid();}frame.TypeID=input.TypeID??frame.TypeID;frame.ReverseDirection=input.ReverseDirection;frame.Reciprocal=input.Reciprocal??frame.Reciprocal;frame.Permanent=input.Permanent;frame.ReaderKnows=input.ReaderKnows;frame.Version=input.Version;frame.Notes=input.Notes;frame.StateID=input.StateID;frame.Intensity=input.Intensity;frame.Awareness=input.Awareness;frame.Confirmed=input.Confirmed;ModelState.AddModelError("",e.Message);Response.StatusCode=400;return PartialView("~/Views/Characters/_WorkspaceOperation.cshtml",frame);}
}
[HttpGet("Add/{id:int}")]
public async Task<IActionResult> Add(int id,CancellationToken ct)
{try{return PartialView("~/Views/Characters/_WorkspaceAdd.cshtml",await workspace.AddForm(id,ct));}catch(UnauthorizedAccessException){return Forbid();}}
[HttpPost("Add/{id:int}"),ValidateAntiForgeryToken]
public async Task<IActionResult> Add(int id,InitialRelationshipEditViewModel input,CancellationToken ct)
{try{if(!ModelState.IsValid)throw new ArgumentException("Check the relationship fields.");await workspace.Add(id,input,ct);return Ok(new{saved=true,message="Initial relationship added."});}catch(UnauthorizedAccessException){return Forbid();}catch(Exception e)when(e is ArgumentException or InvalidOperationException){var model=await workspace.AddForm(id,ct,input);ModelState.AddModelError("",e.Message);Response.StatusCode=400;return PartialView("~/Views/Characters/_WorkspaceAdd.cshtml",model);}}
}

View File

@ -26,10 +26,9 @@ public sealed class CharactersController(ICharacterService characters) : Control
return model is null ? NotFound() : View(model);
}
public async Task<IActionResult> Details(int id)
public async Task<IActionResult> Details(int id,[FromServices] CharacterWorkspace workspace,string? tab=null,int? sceneId=null,CancellationToken cancellationToken=default)
{
var model = await characters.GetCharacterDetailAsync(id);
return model is null ? NotFound() : View(model);
try{var model=await workspace.Header(id,tab,cancellationToken);if(tab!=null)model.WorkspacePage=await workspace.Page(id,new(){Tab=tab,SceneID=sceneId},cancellationToken);return View(model);}catch(UnauthorizedAccessException){return NotFound();}catch(ArgumentException e){return BadRequest(e.Message);}
}
public async Task<IActionResult> Merge(int id)
@ -68,6 +67,7 @@ public sealed class CharactersController(ICharacterService characters) : Control
{
saveResult = await characters.SaveCharacterAsync(model);
}
catch(UnauthorizedAccessException){return Forbid();}
catch (SubscriptionLimitException ex) when (model.CharacterID == 0)
{
ModelState.AddModelError(string.Empty, ex.Message);
@ -216,6 +216,7 @@ public sealed class CharactersController(ICharacterService characters) : Control
target.Sex = source.Sex;
target.CustomSex = source.CustomSex;
target.BirthDate = source.BirthDate;
target.IsDeceased=source.IsDeceased;target.OriginalIsDeceased=source.OriginalIsDeceased;target.LifeStatusProvided=source.LifeStatusProvided;
target.AgeAtSeriesStart = source.AgeAtSeriesStart;
target.Height = source.Height;
target.EyeColour = source.EyeColour;
@ -290,10 +291,9 @@ public sealed class CharactersController(ICharacterService characters) : Control
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ArchiveRelationship(int id, int characterId)
public IActionResult ArchiveRelationship(int id, int characterId)
{
await characters.ArchiveRelationshipAsync(id);
TempData["ArchiveMessage"] = "Relationship archived. You can restore it from Archived Items.";
return RedirectToAction(nameof(Details), new { id = characterId });
// Old bookmarked/forms enter the new explicit preview; no removal bypass.
return RedirectToAction(nameof(Details), new { id = characterId,tab="relationships",relationshipId=id,operation="archive" });
}
}

View File

@ -0,0 +1,26 @@
using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Mvc;using PlotLine.Data;using PlotLine.Models;using PlotLine.Services;using PlotLine.Services.Context;
namespace PlotLine.Controllers;
[Authorize,Route("Writing/Context/Names"),ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
public sealed class ContextNamesController(ContextNames names,IWordCompanionRepository access,IBookRepository books,ICurrentUserService user):Controller
{
private async Task<Book> Book(int id){if(!user.UserId.HasValue||await access.GetBookStructureAsync(id,user.UserId.Value)==null)throw new UnauthorizedAccessException();return await books.GetAsync(id)??throw new UnauthorizedAccessException();}
[HttpGet("Search")]
public async Task<IActionResult> Search(int contextBookId,[FromQuery] NameSearchFilter filter,CancellationToken cancellationToken)
{
if(!ModelState.IsValid||filter.Search?.Length>120)return BadRequest();
try{var book=await Book(contextBookId);if(filter.BookID.HasValue&&(await books.GetAsync(filter.BookID.Value))?.ProjectID!=book.ProjectID)return Forbid();
var panel=await names.Build(book.ProjectID,contextBookId,filter,cancellationToken);return PartialView("~/Views/Writing/_ContextNameResults.cshtml",panel);
}catch(UnauthorizedAccessException){return Forbid();}
}
[HttpGet("Usage")]
public async Task<IActionResult> Usage(int contextBookId,string search,int? bookId,string usedScope="Project",CancellationToken cancellationToken=default)
{
if(string.IsNullOrWhiteSpace(search)||search.Length>120||usedScope is not ("Project" or "Book" or "Library"))return BadRequest();
try{var book=await Book(contextBookId);if(bookId.HasValue&&(await books.GetAsync(bookId.Value))?.ProjectID!=book.ProjectID)return Forbid();
ViewData["ContextBookID"]=contextBookId;return PartialView("~/Views/Writing/_ContextNameUsage.cshtml",await names.Usage(book.ProjectID,bookId,search,usedScope,cancellationToken));
}catch(UnauthorizedAccessException){return Forbid();}
}
[HttpGet("Identity")]
public async Task<IActionResult> Identity(int contextBookId,int characterId)
{try{var book=await Book(contextBookId);return PartialView("~/Views/Writing/_ContextNameIdentity.cshtml",await names.Identity(book.ProjectID,contextBookId,characterId));}catch(UnauthorizedAccessException){return Forbid();}}
}

View File

@ -0,0 +1,26 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PlotLine.Data;
using PlotLine.Services;
namespace PlotLine.Controllers;
[Authorize,Route("Writing/Context"),ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
public sealed class ContextNavigationController(IWordCompanionRepository companion,ICurrentUserService currentUser):Controller
{
[HttpGet("OpenWorkspace")]
public async Task<IActionResult> OpenWorkspace(int bookId,string tool,int? entityId,[FromServices] IBookRepository books,[FromServices] ICharacterRepository characters,bool resolve=false,int? sceneId=null)
{
var structure=currentUser.UserId.HasValue?await companion.GetBookStructureAsync(bookId,currentUser.UserId.Value):null;if(structure==null)return Forbid();
var book=await books.GetAsync(bookId);if(book==null)return NotFound();
if(sceneId.HasValue&&!structure.Chapters.Any(c=>c.Scenes.Any(s=>s.SceneId==sceneId)))return BadRequest();
string? url=null;
if(tool=="characters"&&(!entityId.HasValue||(await characters.GetCharacterAsync(entityId.Value))?.ProjectID==book.ProjectID))url=entityId.HasValue?$"/Characters/Details/{entityId}":$"/Characters?projectId={book.ProjectID}";
if(tool=="names"&&!entityId.HasValue)url=$"/Names?projectId={book.ProjectID}&bookId={bookId}";
if(tool=="relationships"){
var relation=entityId.HasValue?await characters.GetRelationshipAsync(entityId.Value):null;
if(!entityId.HasValue||relation?.ProjectID==book.ProjectID)url=$"/RelationshipMap?projectId={book.ProjectID}&bookId={bookId}"+(relation==null?"":$"&focusCharacterId={relation.CharacterAID}");
}
if(tool=="scene"&&entityId.HasValue&&structure.Chapters.Any(c=>c.Scenes.Any(s=>s.SceneId==entityId)))url=$"/Scenes/Edit/{entityId}";
if(url==null)return BadRequest();if(tool=="relationships"&&sceneId.HasValue)url+=$"&sceneId={sceneId}";return resolve?Ok(new{url}):Redirect(url);
}
}

View File

@ -0,0 +1,18 @@
using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Mvc;using PlotLine.Services.Context;
namespace PlotLine.Controllers;
[Authorize,Route("Writing/Context/Relationships"),ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
public sealed class ContextRelationshipLensesController(ContextRelationshipLenses lenses,ContextFamilyExploration families):Controller
{
[HttpGet("Graph")]
public async Task<IActionResult> Graph(int bookId,int sceneId,string lens="family",int? focusId=null,int depth=3,CancellationToken cancellationToken=default)
{try{return Ok(await lenses.Graph(bookId,sceneId,lens,focusId,depth,cancellationToken));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(new{message=e.Message});}}
[HttpGet("FamilyIndex")]
public async Task<IActionResult> FamilyIndex(int bookId,int sceneId,CancellationToken cancellationToken)
{try{return Ok(await families.Index(bookId,sceneId,cancellationToken));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(new{message=e.Message});}}
[HttpGet("FamilyTree")]
public async Task<IActionResult> FamilyTree(int bookId,int sceneId,int focusId,[FromQuery] int[]? expanded,CancellationToken cancellationToken)
{try{return Ok(await families.Tree(bookId,sceneId,focusId,expanded??[],cancellationToken));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(new{message=e.Message});}}
[HttpGet("Lookup")]
public async Task<IActionResult> Lookup(int bookId,int sceneId,string search,CancellationToken cancellationToken)
{if(string.IsNullOrWhiteSpace(search)||search.Length>120)return BadRequest();try{return Ok((await lenses.Lookup(bookId,sceneId,search,cancellationToken)).Select(c=>new{id=c.CharacterID,name=c.CharacterName,archived=c.IsArchived}));}catch(UnauthorizedAccessException){return Forbid();}}
}

View File

@ -0,0 +1,47 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PlotLine.Services.Context;
namespace PlotLine.Controllers;
[Authorize,Route("Writing/Context"),ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
public sealed class ContextToolsController(ContextCharacterEditing editing,ContextRelationshipEditing relationships):Controller
{
[HttpGet("EditCharacter")]
public async Task<IActionResult> EditCharacter(int bookId,int sceneId,int characterId,string field)
{try{return PartialView("~/Views/Writing/_ContextCharacterEdit.cshtml",await editing.Read(bookId,sceneId,characterId,field));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException){return BadRequest();}}
[HttpPost("EditCharacter"),ValidateAntiForgeryToken]
public async Task<IActionResult> SaveCharacter(ContextCharacterEditForm model)
{
try{
if(ModelState.IsValid){await editing.Save(model);return Ok(new{saved=true,bookId=model.BookID});}
return await Invalid(model,"Check the correction below.");
}catch(UnauthorizedAccessException){return Forbid();}
catch(Exception e)when(e is ArgumentException or InvalidOperationException){return await Invalid(model,e.Message);}
catch(Microsoft.Data.SqlClient.SqlException){return await Invalid(model,"The correction could not be saved. Your draft is retained; retry when the connection recovers.");}
}
[HttpGet("EditRelationship")]
public async Task<IActionResult> EditRelationship(int bookId,int sceneId,int relationshipId=0,string mode="scene",string referenceLens="story")
{try{return PartialView("~/Views/Writing/_ContextRelationshipEdit.cshtml",await relationships.Read(bookId,sceneId,relationshipId,mode,referenceLens));}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(e.Message);}}
[HttpPost("EditRelationship"),ValidateAntiForgeryToken]
public async Task<IActionResult> SaveRelationship(ContextRelationshipForm model)
{
try{if(ModelState.IsValid){await relationships.Save(model);return Ok(new{saved=true,bookId=model.BookID});}return await InvalidRelationship(model,"Check the correction below.");}
catch(UnauthorizedAccessException){return Forbid();}
catch(Exception e)when(e is ArgumentException or InvalidOperationException){return await InvalidRelationship(model,e.Message);}
catch(Microsoft.Data.SqlClient.SqlException){return await InvalidRelationship(model,"Save unavailable. Your draft is retained; retry when the connection recovers.");}
}
private async Task<IActionResult> InvalidRelationship(ContextRelationshipForm input,string error)
{
ContextRelationshipForm frame;
try{frame=await relationships.Read(input.BookID,input.SceneID,input.RelationshipID,input.Mode,input.ReferenceLens);}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(e.Message);}
frame.SourceID=input.SourceID;frame.TargetID=input.TargetID;frame.TypeID=input.TypeID;frame.StateID=input.StateID;frame.Intensity=input.Intensity;frame.Mutual=input.Mutual;frame.Known=input.Known;frame.Notes=input.Notes;frame.Fingerprint=input.Fingerprint;
ModelState.AddModelError("",error);Response.StatusCode=422;return PartialView("~/Views/Writing/_ContextRelationshipEdit.cshtml",frame);
}
private async Task<IActionResult> Invalid(ContextCharacterEditForm input,string error)
{
ContextCharacterEditForm frame;
try{frame=await editing.Read(input.BookID,input.SceneID,input.CharacterID,input.Field);}catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException){return BadRequest();}
frame.Value=input.Value;frame.Fingerprint=input.Fingerprint;ModelState.AddModelError(nameof(input.Value),error);Response.StatusCode=422;
return PartialView("~/Views/Writing/_ContextCharacterEdit.cshtml",frame);
}
}

View File

@ -19,10 +19,14 @@ public sealed class DynamicsController(IDynamicsService dynamics) : Controller
return model is null ? NotFound() : View(model);
}
public async Task<IActionResult> Relationship(int id)
public async Task<IActionResult> Relationship(int id,[FromServices]CharacterWorkspace workspace,int? returnCharacterId=null,int? returnSceneId=null,int page=1,CancellationToken ct=default)
{
var model = await dynamics.GetRelationshipEvolutionAsync(id);
return model is null ? NotFound() : View(model);
if(page is <1 or >100000)return BadRequest();
var model=await dynamics.GetRelationshipEvolutionAsync(id,page);if(model is null)return NotFound();
var r=model.Relationship;var anchor=returnCharacterId==r.CharacterBID?r.CharacterBID:r.CharacterAID;
try{var scope=await workspace.Scope(anchor);if(scope.Project.ProjectID!=r.ProjectID)return NotFound();model.CanEdit=scope.CanEdit;}catch(UnauthorizedAccessException){return NotFound();}
if(page>1&&model.Events.Count==0){model=await dynamics.GetRelationshipEvolutionAsync(id,1);if(model is null)return NotFound();model.CanEdit=(await workspace.Scope(anchor)).CanEdit;page=1;}
model.ReturnCharacterID=anchor;model.ReturnSceneID=returnSceneId;model.Page=page;return View(model);
}
public async Task<IActionResult> Knowledge(int id)

View File

@ -15,6 +15,7 @@ public sealed class NamesController(INameIntelligenceService names) : Controller
return BadRequest("ProjectID is required.");
}
if(!Request.Query.ContainsKey("UsedScope")&&filter.BookID.HasValue)filter.UsedScope="Book";
var model = await names.BuildLibraryAsync(filter, cancellationToken);
return model is null ? NotFound() : View(model);
}

View File

@ -4,13 +4,13 @@ using Microsoft.Data.SqlClient;
using PlotLine.Services;
namespace PlotLine.Controllers;
[Authorize,ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
public sealed class NarrativeFocusController(INarrativeFocus focus,ICurrentUserService currentUser) : Controller
public sealed class NarrativeFocusController(INarrativeFocus focus,ICurrentUserService currentUser,SharedManuscriptFocus? shared=null) : Controller
{
[HttpGet]
public Task<IActionResult> Read(int projectId,int bookId) => Execute(() => focus.Read(currentUser.UserId!.Value,projectId,bookId));
[HttpPost,ValidateAntiForgeryToken]
public Task<IActionResult> Set(int projectId,int bookId,int? chapterId,int? sceneId,long version,int direction=0) =>
Execute(() => focus.Set(currentUser.UserId!.Value,projectId,bookId,chapterId,sceneId,version,direction));
Execute(async () => {var state=await focus.Set(currentUser.UserId!.Value,projectId,bookId,chapterId,sceneId,version,direction);if(shared!=null)await shared.Announce(currentUser.UserId.Value,projectId,bookId);return state;});
private async Task<IActionResult> Execute(Func<Task<NarrativeFocusState>> operation)
{
if(currentUser.UserId is null)return Challenge();

View File

@ -8,7 +8,7 @@ using PlotLine.Data;
using PlotLine.Services.NativeCompanion;
namespace PlotLine.Controllers;
[ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion")]
public sealed class NativePresenceController(NativePresenceStore presence,IWordCompanionRepository access,IHubContext<NativeCompanionPresenceHub>? live=null,INativePositionRepository? positions=null,NativeManuscriptCapture? capture=null,IHubContext<WordCompanionFollowHub>? wizard=null,ILogger<NativePresenceController>? logger=null,IChapterSyncRepository? chapterPositions=null):ControllerBase
public sealed class NativePresenceController(NativePresenceStore presence,IWordCompanionRepository access,IHubContext<NativeCompanionPresenceHub>? live=null,INativePositionRepository? positions=null,NativeManuscriptCapture? capture=null,IHubContext<WordCompanionFollowHub>? wizard=null,ILogger<NativePresenceController>? logger=null,IChapterSyncRepository? chapterPositions=null,PlotLine.Services.SharedManuscriptFocus? sharedFocus=null,IBookRepository? focusBooks=null):ControllerBase
{
private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
private string Grant=>User.FindFirstValue("NativeCompanion.Grant")??throw new InvalidOperationException();
@ -45,6 +45,7 @@ public sealed class NativePresenceController(NativePresenceStore presence,IWordC
// ChapterIssue is the agent's current reading failure, not server chapter acceptance.
// Do not overwrite accepted/checking progress with a sticky synthetic Needs review state.
input.ChapterProgress=presence.ChapterProgress(Author,input.BookId,instance,session,input.Revision);
if(sharedFocus!=null&&focusBooks!=null&&input.CanSharedFocus&&input.BookId>0){var scopedBook=await focusBooks.GetAsync(input.BookId);var lease=presence.Read(Author,input.BookId).FirstOrDefault(l=>l.Instance==instance&&l.Session==session);if(scopedBook!=null&&lease!=null)try{input.SharedFocusStatus=await sharedFocus.NativeObservation(Author,scopedBook.ProjectID,lease,before==null||before.Position.FocusModeRequest!=input.FocusModeRequest||before.Position.FocusWindowID!=input.FocusWindowID||before.Position.WordSaved!=input.WordSaved||before.Position.ParagraphRevision!=input.ParagraphRevision||before.Position.NavigationAcknowledgedId!=input.NavigationAcknowledgedId);}catch(Exception e){input.SharedFocusStatus="word-unmapped";logger?.LogWarning("Shared focus observation unavailable ({Type}); manuscript synchronisation retained.",e.GetType().Name);}}
input.CatalogVersion=presence.CatalogVersion(Author);input.Navigation=presence.TakeNavigation(Author,Grant,instance,session);
if(input.Navigation is {Kind:"navigate"} command)logger?.LogInformation("Deliver explicit Word navigation Id={NavigationId} User={User} Book={Book} Instance={Instance} Session={Session} Revision={Revision} Position={Position}",command.Id,Author,input.BookId,instance,session,command.Revision,command.Chapter?.Start);
return Ok(input);

View File

@ -15,7 +15,8 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB
public async Task<IActionResult> Workspace(int bookId,Guid? instanceId,Guid? sessionId,string view="book")
{
var structure=await access.GetBookStructureAsync(bookId,Author);if(structure==null)return Forbid();var book=await books.GetAsync(bookId);if(book==null)return NotFound();
if(view is "context" or "intent") return RedirectToAction(view=="context"?"Context":"Intent","Writing",new{projectId=book.ProjectID,bookId,instanceId,sessionId,embedded=true});
if(view=="context") return View("ContextLaunch",new NativeWorkspaceModel(bookId,book.ProjectID,book.BookDisplayTitle,instanceId,sessionId,"context",[],structure.Chapters));
if(view=="intent") return RedirectToAction("Context","Writing",new{projectId=book.ProjectID,bookId,instanceId,sessionId,embedded=true});
return View(new NativeWorkspaceModel(bookId,book.ProjectID,book.BookDisplayTitle,instanceId,sessionId,view is "context" or "intent"?view:"book",await reviews.List(Author,bookId),structure.Chapters));
}
[HttpGet("presence")]
@ -37,7 +38,7 @@ public sealed class NativeWorkspaceController(IWordCompanionRepository access,IB
foreach(var book in leases.Select(l=>l.Position.BookId).Where(b=>b>0).Distinct())if(await access.GetBookStructureAsync(book,Author)!=null)allowed.Add(book);
var snapshots=new Dictionary<int,ParagraphSyncStatus?>();
if(paragraphs!=null)foreach(var book in leases.Where(l=>l.Position.WordAvailable&&allowed.Contains(l.Position.BookId)&&l.Position.BookId>0).Select(l=>l.Position.BookId).Distinct())snapshots[book]=await paragraphs.Status(Author,book);
var result=leases.Where(l=>allowed.Contains(l.Position.BookId)).Select(l=>new{l.Position.CanAcknowledgeNavigation,chapterTitle=l.Position.ChapterTitle,sceneTitle=l.Position.SceneTitle,instanceId=l.Instance,sessionId=l.Session,l.Position.BookId,l.Position.DocumentTitle,l.Position.Revision,l.Position.ManuscriptId,l.Position.ChapterId,l.Position.SceneId,l.Position.Active,l.Position.WordAvailable,l.Position.WordRunning,l.Position.WordSaved,l.Position.CanCapture,l.Position.ChapterIssue,l.Position.CanChapterSync,chapterProgress=presence.ChapterProgress(Author,l.Position.BookId,l.Instance,l.Session,l.Position.Revision),l.Position.CanParagraphSync,l.Position.CaptureRequestId,l.Position.CaptureProgress,
var result=leases.Where(l=>allowed.Contains(l.Position.BookId)).Select(l=>new{l.Position.CanSharedFocus,l.Position.FocusHeld,l.Position.SharedFocusStatus,l.Position.CanAcknowledgeNavigation,chapterTitle=l.Position.ChapterTitle,sceneTitle=l.Position.SceneTitle,instanceId=l.Instance,sessionId=l.Session,l.Position.BookId,l.Position.DocumentTitle,l.Position.Revision,l.Position.ManuscriptId,l.Position.ChapterId,l.Position.SceneId,l.Position.Active,l.Position.WordAvailable,l.Position.WordRunning,l.Position.WordSaved,l.Position.CanCapture,l.Position.ChapterIssue,l.Position.CanChapterSync,chapterProgress=presence.ChapterProgress(Author,l.Position.BookId,l.Instance,l.Session,l.Position.Revision),l.Position.CanParagraphSync,l.Position.CaptureRequestId,l.Position.CaptureProgress,
paragraphTransfer=capture?.ParagraphTransferStatus(Author,l.Position.BookId,l.Instance,l.Session),
positionVerified=l.Position.WordSaved==true&&(!(l.Position.CanChapterSync||l.Position.CanParagraphSync)||l.Position.ParagraphRevision>0)&&l.Position.ChapterId.HasValue,
snapshotRevision=snapshots.GetValueOrDefault(l.Position.BookId)?.Revision,

View File

@ -0,0 +1,14 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using PlotLine.Services;
namespace PlotLine.Controllers;
[Authorize,Route("NarrativeFocus/Shared"),ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
public sealed class SharedFocusController(SharedManuscriptFocus focus,ICurrentUserService user):Controller
{
[HttpGet]public Task<IActionResult> Read(int projectID,int bookID)=>Run(new(){ProjectID=projectID,BookID=bookID},"read");
[HttpPost("Publish"),ValidateAntiForgeryToken]public Task<IActionResult> Publish(SharedFocusRequest request)=>Run(request,"publish");
[HttpPost("Resolve"),ValidateAntiForgeryToken]public Task<IActionResult> Resolve(SharedFocusRequest request)=>Run(request,"resolve");
[HttpPost("Validate"),ValidateAntiForgeryToken]public Task<IActionResult> Validate(SharedFocusRequest request)=>Run(request,"validate");
private async Task<IActionResult> Run(SharedFocusRequest request,string action){if(user.UserId is not int author)return Challenge();if(!ModelState.IsValid)return BadRequest(new{message="Choose valid manuscript identifiers."});try{return Ok(await focus.Run(author,request,action));}catch(SqlException e)when(e.Number==51000){return NotFound(new{message="This manuscript reference is unavailable. Choose another position."});}}
}

View File

@ -16,7 +16,7 @@ public sealed class WordCompanionController(
IWordCompanionService wordCompanion,
IWordCompanionPresenceService presence,
IHubContext<WordCompanionFollowHub> followHub,
ILogger<WordCompanionController> logger) : ControllerBase
ILogger<WordCompanionController> logger, ContextWorkspaceNotifications? contextNotifications = null) : ControllerBase
{
[HttpGet("projects")]
public Task<WordCompanionProjectsResponse> GetProjects() => wordCompanion.ListProjectsAsync();
@ -86,6 +86,7 @@ public sealed class WordCompanionController(
public async Task<IActionResult> SyncScene(int bookId, WordCompanionSyncSceneRequest request)
{
var response = await wordCompanion.SyncSceneAsync(bookId, request);
if (response != null && contextNotifications != null) await contextNotifications.Invalidate(RequireUserId(), bookId);
return response is null ? BadRequest() : Ok(response);
}
@ -93,6 +94,7 @@ public sealed class WordCompanionController(
public async Task<IActionResult> SyncManuscript(int bookId, WordCompanionSyncManuscriptRequest request)
{
var response = await wordCompanion.SyncManuscriptAsync(bookId, request);
if (response != null && contextNotifications != null) await contextNotifications.Invalidate(RequireUserId(), bookId);
return response is null ? BadRequest() : Ok(response);
}
@ -100,6 +102,7 @@ public sealed class WordCompanionController(
public async Task<IActionResult> UpdateSceneLinks(int sceneId, WordCompanionUpdateSceneLinksRequest request)
{
var response = await wordCompanion.UpdateSceneLinksAsync(sceneId, request);
if (response != null && contextNotifications != null) await contextNotifications.Invalidate(RequireUserId(), null);
return response is null ? BadRequest() : Ok(response);
}
@ -107,6 +110,7 @@ public sealed class WordCompanionController(
public async Task<IActionResult> UpdateWordCount(int sceneId, WordCompanionUpdateWordCountRequest request)
{
var response = await wordCompanion.UpdateWordCountAsync(sceneId, request);
if (response != null && contextNotifications != null) await contextNotifications.Invalidate(RequireUserId(), null);
return response is null ? BadRequest() : Ok(response);
}
@ -121,6 +125,7 @@ public sealed class WordCompanionController(
public async Task<IActionResult> UpdateRuntimeSceneWordCount(WordCompanionRuntimeSceneWordCountRequest request)
{
var response = await wordCompanion.UpdateRuntimeSceneWordCountAsync(request);
if (response != null && contextNotifications != null) await contextNotifications.Invalidate(RequireUserId(), null);
return response is null ? BadRequest() : Ok(response);
}
@ -167,6 +172,7 @@ public sealed class WordCompanionController(
response.Position
});
if (contextNotifications != null) await contextNotifications.Position(RequireUserId());
return Ok(response);
}

View File

@ -31,11 +31,7 @@ public sealed class WriterController(
var result=await LoadDestination("Review",projectId,bookId);
if(result is ViewResult {Model:WriterDashboardViewModel model}&&model.BookID.HasValue&&reader!=null){
try{
if(chapterId.HasValue && narrativeFocus != null && model.ProjectID is int project && int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier),out var author))
{
var current=model.NarrativeFocus!;
if(current.ChapterID!=chapterId) {model.NarrativeFocus=await narrativeFocus.Set(author,project,model.BookID.Value,chapterId,null,current.Version);if(model.WorkingContext!=null)model.WorkingContext=model.WorkingContext.Select(PlotLine.Services.Writer.WriterFocusRole.Working,new(project,model.BookID.Value,model.NarrativeFocus.ChapterID,model.NarrativeFocus.SceneID));}
}
// Initial/deep-link chapter loading is local; deliberate navigation publishes through SharedFocus.
chapterId ??= model.NarrativeFocus?.ChapterID;
model.ReviewReader=await reader.Read(int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!),model.BookID.Value,chapterId);if(model.ReviewReader==null)return NotFound();model.ReviewReader.FocusReading=focus;model.ReviewReader.IntegratedReview=true;model.ReviewReader.ReadingMode=reading;}
catch(UnauthorizedAccessException){return NotFound();}
@ -46,12 +42,12 @@ public sealed class WriterController(
return result;
}
[HttpGet,ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
public async Task<IActionResult> ReviewContent(int projectId,int bookId,long version,bool focus=false,bool reading=false,[FromServices] PlotLine.Services.Manuscript.ManuscriptReaderService? reader=null)
public async Task<IActionResult> ReviewContent(int projectId,int bookId,long version,bool focus=false,bool reading=false,int? chapterId=null,bool localFocus=false,[FromServices] PlotLine.Services.Manuscript.ManuscriptReaderService? reader=null)
{
var result=await Review(projectId,bookId,null,focus,reading,reader);
var result=await Review(projectId,bookId,chapterId,focus,reading,reader);
if(result is ViewResult {Model:WriterDashboardViewModel model})
{
if(model.NarrativeFocus?.Version!=version)return Conflict(new{message="Current focus changed. Retry the current location."});
if(!localFocus&&model.NarrativeFocus?.Version!=version)return Conflict(new{message="Current focus changed. Retry the current location."});
return PartialView("_WriterReview",model);
}
return result;

View File

@ -18,8 +18,7 @@ public sealed class WritingController(
IStoryContextService storyContext,
IRelationshipMapService relationshipMap,
IFloorPlanService floorPlans,
IWriterWorkspaceService writerWorkspace,
ILogger<WritingController> logger,IWordCompanionRepository? companion=null,NativePresenceStore? nativePresence=null,IProjectAccessService? projectAccess=null,IChapterSyncRepository? chapterPositions=null) : Controller
ILogger<WritingController> logger,IWordCompanionRepository? companion=null,NativePresenceStore? nativePresence=null,IProjectAccessService? projectAccess=null,IChapterSyncRepository? chapterPositions=null,PlotLine.Services.Context.ContextCharacterPanels? characterPanels=null,PlotLine.Services.Context.ContextNames? contextNames=null,PlotLine.Services.Context.ContextRelationshipLenses? relationshipLenses=null) : Controller
{
[HttpGet("Context")]
public async Task<IActionResult> Context(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? documentGuid, bool pinned = false,bool embedded=false,Guid? instanceId=null,Guid? sessionId=null)
@ -34,63 +33,8 @@ public sealed class WritingController(
documentGuid.HasValue);
if(!ModelState.IsValid||InvalidNativeSelection(instanceId,sessionId))return BadRequest("Choose one complete Word document session.");
var nativeLaunch=!pinned&&(instanceId.HasValue||sessionId.HasValue);
NativeWritingTarget? target=null;
if(nativeLaunch)
{
if(!bookId.HasValue||companion==null)return BadRequest("A linked book is required.");
var structure=await companion.GetBookStructureAsync(bookId.Value,WritingUser);
if(structure==null)return Forbid();
target=await NativeTarget(bookId,instanceId,sessionId);
var chapter=structure.Chapters.FirstOrDefault(c=>c.ChapterId==target?.ChapterId);
if(target?.SceneId is int current&&chapter?.Scenes.Any(x=>x.SceneId==current)!=true)target=null;
if(target?.ChapterId!=null&&chapter==null)target=null;
chapterId=target?.ChapterId;sceneId=target?.SceneId;
}
if(!nativeLaunch&&!sceneId.HasValue&&bookId.HasValue&&companion!=null) {
var structure=await companion.GetBookStructureAsync(bookId.Value,int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!));
sceneId=structure?.Chapters.SelectMany(c=>c.Scenes).FirstOrDefault()?.SceneId;
}
var display = sceneId.HasValue
? await BuildDisplayAsync(projectId, bookId, chapterId, sceneId, "Manual context")
: WaitingContextDisplay(projectId, bookId, documentGuid);
if(nativeLaunch&&!SameNativeTarget(target,await NativeTarget(bookId,instanceId,sessionId)))
{
sceneId=null;chapterId=null;target=null;
display=WaitingContextDisplay(projectId,bookId,documentGuid);
}
if(nativeLaunch&&display!=null)display.FollowStatus=target!=null&&sceneId.HasValue?"Following Word":"Word mapping pending · choose a saved scene to browse manually";
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 = display?.Context?.Position.ProjectId ?? projectId,
BookID = display?.Context?.Position.BookId ?? bookId,
ChapterID = chapterId,
SceneID = sceneId,
DocumentGuid = documentGuid,
Display = display ?? MissingContextDisplay(projectId, bookId, sceneId)
};
model.WorkingContext = ReferenceContext(model.ProjectID, model.BookID,
model.Display?.Context?.Position.ChapterId,
model.Display?.Context?.Position.SceneId, pinned, nativeLaunch ? target : null);
return View(model);
}
[HttpGet("Intent")]
public async Task<IActionResult> Intent(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? documentGuid, bool pinned = false,bool embedded=false,Guid? instanceId=null,Guid? sessionId=null)
{
ViewData["NativeSnapshot"] = pinned;ViewData["WritingEmbedded"]=embedded;ViewData["WordInstance"]=instanceId;ViewData["WordSession"]=sessionId;
logger.LogInformation(
"Opening Writing Intent. ProjectID={ProjectID} BookID={BookID} ChapterID={ChapterID} SceneID={SceneID} DocumentGuidPresent={DocumentGuidPresent}",
projectId,
bookId,
chapterId,
sceneId,
documentGuid.HasValue);
if(!ModelState.IsValid||InvalidNativeSelection(instanceId,sessionId))return BadRequest("Choose one complete Word document session.");
if (projectId.HasValue && (projectAccess == null || !await projectAccess.CanAccessProjectAsync(projectId.Value))) return Forbid();
if (bookId.HasValue && (companion == null || await companion.GetBookStructureAsync(bookId.Value, WritingUser) == null)) return Forbid();
var nativeLaunch=!pinned&&(instanceId.HasValue||sessionId.HasValue);
NativeWritingTarget? target=null;
if(nativeLaunch)
@ -106,82 +50,116 @@ public sealed class WritingController(
}
if(!nativeLaunch&&!sceneId.HasValue&&!chapterId.HasValue&&bookId.HasValue&&companion!=null) {
var structure=await companion.GetBookStructureAsync(bookId.Value,int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!));
var first=structure?.Chapters.FirstOrDefault(c=>c.Scenes.Count>0)??structure?.Chapters.FirstOrDefault();
chapterId=first?.ChapterId;sceneId=first?.Scenes.FirstOrDefault()?.SceneId;
sceneId=structure?.Chapters.SelectMany(c=>c.Scenes).FirstOrDefault()?.SceneId;
}
var display = sceneId.HasValue || chapterId.HasValue
? await BuildIntentDisplayAsync(projectId, bookId, chapterId, sceneId, "Manual intent")
: WaitingIntentDisplay(projectId, bookId, documentGuid);
var display = sceneId.HasValue
? await BuildDisplayAsync(projectId, bookId, chapterId, sceneId, "Manual context")
: WaitingContextDisplay(projectId, bookId, documentGuid);
if(nativeLaunch&&!SameNativeTarget(target,await NativeTarget(bookId,instanceId,sessionId)))
{
sceneId=null;chapterId=null;target=null;
display=WaitingIntentDisplay(projectId,bookId,documentGuid);
display=WaitingContextDisplay(projectId,bookId,documentGuid);
}
if(nativeLaunch&&display!=null)display.FollowStatus=target!=null&&(sceneId.HasValue||chapterId.HasValue)?"Following Word":"Word mapping pending · choose a saved scene to browse manually";
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
if(nativeLaunch&&display!=null)display.FollowStatus=target!=null&&sceneId.HasValue?"Following Word":"Word mapping pending · choose a saved scene to browse manually";
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.";}}
if (sceneId.HasValue && display?.HasScene != true && !nativeLaunch) return NotFound();
var model = new WritingContextPageViewModel
{
ProjectID = display?.Context?.Position.ProjectId ?? display?.ChapterWorkflow?.Project.ProjectID ?? projectId,
BookID = display?.Context?.Position.BookId ?? display?.ChapterWorkflow?.Book.BookID ?? bookId,
ProjectID = display?.Context?.Position.ProjectId ?? projectId,
BookID = display?.Context?.Position.BookId ?? bookId,
ChapterID = chapterId,
SceneID = sceneId,
DocumentGuid = documentGuid,
Display = display ?? MissingIntentDisplay(projectId, bookId, chapterId, sceneId)
Display = display ?? MissingContextDisplay(projectId, bookId, sceneId)
};
if (model.BookID.HasValue && companion != null && model.Display != null && model.Display.SceneOptions.Count == 0)
{
var structure = await companion.GetBookStructureAsync(model.BookID.Value, WritingUser);
model.Display.SceneOptions = structure?.Chapters.SelectMany(chapter => chapter.Scenes.Select(scene =>
new SelectListItem($"{chapter.Title} / {scene.Title}", scene.SceneId.ToString(), scene.SceneId == model.SceneID))).ToList() ?? [];
}
model.WorkingContext = ReferenceContext(model.ProjectID, model.BookID,
model.Display?.Context?.Position.ChapterId ?? model.Display?.ChapterWorkflow?.Chapter.ChapterID,
model.Display?.Context?.Position.ChapterId,
model.Display?.Context?.Position.SceneId, pinned, nativeLaunch ? target : null);
return View(model);
}
[HttpGet("Context/Scene")]
public async Task<IActionResult> ContextScene(int? projectId, int? bookId, int? chapterId, int? sceneId,Guid? instanceId=null,Guid? sessionId=null)
// Compatibility only: no Intent shell, registration or follow controller remains.
[HttpGet("Intent"), HttpGet("Intent/Scene")]
public IActionResult Intent(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? documentGuid,
bool pinned = false, bool embedded = false, Guid? instanceId = null, Guid? sessionId = null)
{
if(!ModelState.IsValid||InvalidNativeSelection(instanceId,sessionId))return BadRequest();
var nativeRequest=instanceId.HasValue||sessionId.HasValue;
var target=nativeRequest?await NativeTarget(bookId,instanceId,sessionId):null;
if(nativeRequest&&(target==null||target.SceneId!=sceneId||(chapterId.HasValue&&target.ChapterId!=chapterId)))return Conflict(new{message="Word position changed or is awaiting verification."});
if (!sceneId.HasValue)
{
logger.LogWarning("Writing Context partial requested without SceneID. ProjectID={ProjectID} BookID={BookID} ChapterID={ChapterID}", projectId, bookId, chapterId);
return PartialView("~/Views/Writing/_WritingContextContent.cshtml", WaitingContextDisplay(projectId, bookId, null));
}
var model = await BuildDisplayAsync(projectId, bookId, chapterId, sceneId, "Saved scene");
if(nativeRequest&&!SameNativeTarget(target,await NativeTarget(bookId,instanceId,sessionId)))return Conflict(new{message="Word position changed while context was loading."});
if (model?.HasScene == true)
{
return PartialView("~/Views/Writing/_WritingContextContent.cshtml", model);
}
logger.LogWarning("Writing Context could not resolve scene. ProjectID={ProjectID} BookID={BookID} ChapterID={ChapterID} SceneID={SceneID}", projectId, bookId, chapterId, sceneId);
return PartialView("~/Views/Writing/_WritingContextContent.cshtml", MissingContextDisplay(projectId, bookId, sceneId));
if (!ModelState.IsValid || InvalidNativeSelection(instanceId, sessionId)) return BadRequest();
return RedirectToAction(nameof(Context), new { projectId, bookId, chapterId, sceneId, documentGuid, pinned, embedded, instanceId, sessionId });
}
[HttpGet("Intent/Scene")]
public async Task<IActionResult> IntentScene(int? projectId, int? bookId, int? chapterId, int? sceneId,Guid? instanceId=null,Guid? sessionId=null)
[HttpGet("Context/Tabs/overview")]
public Task<IActionResult> ContextScene(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? instanceId = null, Guid? sessionId = null)
=> RenderContextTab("_WritingContextOverview", projectId, bookId, chapterId, sceneId, instanceId, sessionId);
[HttpGet("Context/Tabs/characters")]
public Task<IActionResult> ContextCharacters(int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? instanceId = null, Guid? sessionId = null)
=> RenderContextTab("_WritingContextPeople", projectId, bookId, chapterId, sceneId, instanceId, sessionId);
[HttpGet("Context/Tabs/relationships")]
public Task<IActionResult> ContextRelationships(int? projectId,int? bookId,int? chapterId,int? sceneId,Guid? instanceId=null,Guid? sessionId=null)
=>RenderContextTab("_ContextRelationships",projectId,bookId,chapterId,sceneId,instanceId,sessionId);
[HttpGet("Context/Tabs/names")]
public async Task<IActionResult> ContextNamesTab(int? projectId,int? bookId,int? chapterId,int? sceneId,[FromServices] IBookRepository books,Guid? instanceId=null,Guid? sessionId=null)
{
if(!ModelState.IsValid||InvalidNativeSelection(instanceId,sessionId))return BadRequest();
var nativeRequest=instanceId.HasValue||sessionId.HasValue;
var target=nativeRequest?await NativeTarget(bookId,instanceId,sessionId):null;
if(nativeRequest&&(target==null||target.SceneId!=sceneId||(chapterId.HasValue&&target.ChapterId!=chapterId)))return Conflict(new{message="Word position changed or is awaiting verification."});
if (!sceneId.HasValue && !chapterId.HasValue)
{
logger.LogWarning("Writing Intent partial requested without ChapterID or SceneID. ProjectID={ProjectID} BookID={BookID}", projectId, bookId);
return PartialView("~/Views/Writing/_WritingIntentContent.cshtml", WaitingIntentDisplay(projectId, bookId, null));
}
if(!ModelState.IsValid||bookId is not >0||InvalidNativeSelection(instanceId,sessionId)||contextNames==null||companion==null)return BadRequest();
var structure=await companion.GetBookStructureAsync(bookId.Value,WritingUser);var book=await books.GetAsync(bookId.Value);
if(structure==null||book==null||projectId.HasValue&&projectId!=book.ProjectID)return Forbid();
var chapter=sceneId.HasValue?structure.Chapters.FirstOrDefault(c=>c.Scenes.Any(s=>s.SceneId==sceneId)):null;
if(sceneId.HasValue&&chapter==null)return BadRequest();
var model=new WritingContextDisplayViewModel{Context=new(){Position=new(book.ProjectID,book.BookID,chapter?.ChapterId,sceneId)},NamePanel=await contextNames.Build(book.ProjectID,book.BookID)};
ViewData["ContextTabPartial"]="_ContextNames";return PartialView("_ContextTab",model);
}
var model = await BuildIntentDisplayAsync(projectId, bookId, chapterId, sceneId, "Saved scene");
if(nativeRequest&&!SameNativeTarget(target,await NativeTarget(bookId,instanceId,sessionId)))return Conflict(new{message="Word position changed while context was loading."});
if (model is not null && (model.HasScene || model.HasChapter))
{
return PartialView("~/Views/Writing/_WritingIntentContent.cshtml", model);
}
private async Task<IActionResult> RenderContextTab(string partial, int? projectId, int? bookId, int? chapterId, int? sceneId, Guid? instanceId, Guid? sessionId)
{
if (!ModelState.IsValid || sceneId is not > 0 || InvalidNativeSelection(instanceId, sessionId)) return BadRequest();
var nativeRequest = instanceId.HasValue;
var target = nativeRequest ? await NativeTarget(bookId, instanceId, sessionId) : null;
if (nativeRequest && (target == null || target.SceneId != sceneId || (chapterId.HasValue && target.ChapterId != chapterId)))
return Conflict(new { message = "Word position changed or is awaiting verification." });
WritingContextDisplayViewModel? model;
if(partial=="_ContextRelationships"&&relationshipLenses!=null&&bookId.HasValue){
try{var scope=await relationshipLenses.Scope(bookId.Value,sceneId.Value);if(projectId.HasValue&&projectId!=scope.Book.ProjectID||chapterId.HasValue&&chapterId!=scope.Scene.ChapterID)return BadRequest();
model=new(){Context=new(){Position=new(scope.Book.ProjectID,scope.Book.BookID,scope.Scene.ChapterID,sceneId),Scene=scope.Scene},ContextRelationshipCanEdit=scope.CanEdit};
}catch(UnauthorizedAccessException){return Forbid();}
}else model=await BuildDisplayAsync(projectId,bookId,chapterId,sceneId,"Saved scene");
if (nativeRequest && !SameNativeTarget(target, await NativeTarget(bookId, instanceId, sessionId)))
return Conflict(new { message = "Word position changed while context was loading." });
if (model?.HasScene != true) return NotFound();
if (projectAccess == null || !await projectAccess.CanAccessProjectAsync(model.Context!.Position.ProjectId)) return Forbid();
if(partial=="_WritingContextPeople"&&characterPanels!=null)model.CharacterExplorer=await characterPanels.Build(model);
ViewData["ContextTabPartial"] = partial;
return PartialView("_ContextTab", model);
}
logger.LogWarning("Writing Intent could not resolve chapter/scene. ProjectID={ProjectID} BookID={BookID} ChapterID={ChapterID} SceneID={SceneID}", projectId, bookId, chapterId, sceneId);
return PartialView("~/Views/Writing/_WritingIntentContent.cshtml", MissingIntentDisplay(projectId, bookId, chapterId, sceneId));
[HttpGet("Context/CharacterReference")]
public async Task<IActionResult> CharacterReference(int bookId,int sceneId,int characterId)
{
if(!ModelState.IsValid||characterPanels==null)return BadRequest();
var display=await BuildDisplayAsync(null,bookId,null,sceneId,"Saved reference");
if(display?.HasScene!=true||projectAccess==null||!await projectAccess.CanAccessProjectAsync(display.Context!.Position.ProjectId))return NotFound();
var explorer=await characterPanels.Build(display);var row=explorer.Rows.SingleOrDefault(r=>r.Character.CharacterID==characterId);
return row==null?NotFound():PartialView("_ContextCharacterReference",(explorer,row));
}
[HttpGet("Context/Position")]
public async Task<IActionResult> ContextPosition([FromServices] IWordCompanionPresenceService office, int? bookId, int? projectId)
{
if (!ModelState.IsValid) return BadRequest();
if (bookId.HasValue && (companion == null || await companion.GetBookStructureAsync(bookId.Value, WritingUser) == null)) return Forbid();
if (projectId.HasValue && (projectAccess == null || !await projectAccess.CanAccessProjectAsync(projectId.Value))) return Forbid();
var status = await office.GetStatusAsync(WritingUser);
var position = status.IsConnected && status.DocumentOpen ? status.CurrentStoryPosition : null;
return Ok(new { connected = status.IsConnected && status.DocumentOpen, position });
}
private static WriterContext? ReferenceContext(int? project, int? book, int? chapter, int? scene, bool pinned, NativeWritingTarget? native)
@ -256,53 +234,6 @@ public sealed class WritingController(
};
}
private async Task<WritingIntentDisplayViewModel?> BuildIntentDisplayAsync(int? projectId, int? bookId, int? chapterId, int? sceneId, string followStatus)
{
StoryContextViewModel? context = null;
if (sceneId.HasValue)
{
context = await storyContext.GetForSceneAsync(sceneId.Value, projectId, bookId,forWriting:true,includeNarrative:false);
if (context?.Scene is null||chapterId.HasValue&&context.Position.ChapterId!=chapterId)
{
return null;
}
}
var resolvedChapterId = context?.Position.ChapterId ?? chapterId;
var chapterWorkflow = resolvedChapterId.HasValue
? await writerWorkspace.GetChapterWorkflowAsync(resolvedChapterId.Value)
: null;
if (chapterWorkflow is not null)
{
if(projectAccess==null||!await projectAccess.CanAccessProjectAsync(chapterWorkflow.Project.ProjectID))return null;
if (projectId.HasValue && chapterWorkflow.Project.ProjectID != projectId.Value)
{
return null;
}
if (bookId.HasValue && chapterWorkflow.Book.BookID != bookId.Value)
{
return null;
}
}
if (context is null && chapterWorkflow is null)
{
return null;
}
return new WritingIntentDisplayViewModel
{
Context = context,
ChapterWorkflow = chapterWorkflow,
FollowStatus = followStatus,
SceneOptions = context?.Scene is not null
? await ContextSceneOptions(context.Scene)
: BuildSceneOptions(chapterWorkflow)
};
}
[HttpGet("Context/Map")]
public async Task<IActionResult> ContextMap(int projectId,int bookId,int sceneId,int? mapId,[FromServices] MapRepository maps,[FromServices] IMapStoryService storyMaps,[FromServices] IProjectAccessService permissions,[FromServices] IBookRepository books)
{
@ -396,17 +327,6 @@ public sealed class WritingController(
.ToList();
}
private static IReadOnlyList<SelectListItem> BuildSceneOptions(ChapterWorkflowViewModel? chapterWorkflow)
{
return chapterWorkflow?.Scenes
.Select(x => new SelectListItem(
$"Scene {x.SceneNumber:g}: {x.SceneTitle}",
x.SceneID.ToString()))
.OrderBy(x => x.Text)
.ToList()
?? [];
}
private static WritingContextDisplayViewModel WaitingContextDisplay(int? projectId, int? bookId, Guid? documentGuid) => new()
{
FollowStatus = "No current Word scene received",
@ -414,13 +334,6 @@ public sealed class WritingController(
EmptyMessage = MissingScopeMessage(projectId, bookId, documentGuid, "Context")
};
private static WritingIntentDisplayViewModel WaitingIntentDisplay(int? projectId, int? bookId, Guid? documentGuid) => new()
{
FollowStatus = "No current Word scene received",
EmptyTitle = "No current Word scene received",
EmptyMessage = MissingScopeMessage(projectId, bookId, documentGuid, "Intent")
};
private static WritingContextDisplayViewModel MissingContextDisplay(int? projectId, int? bookId, int? sceneId) => new()
{
FollowStatus = "Context unavailable",
@ -428,13 +341,6 @@ public sealed class WritingController(
EmptyMessage = $"PlotDirector could not load context for scene {sceneId?.ToString() ?? "unknown"} in project {projectId?.ToString() ?? "unknown"}, book {bookId?.ToString() ?? "unknown"}."
};
private static WritingIntentDisplayViewModel MissingIntentDisplay(int? projectId, int? bookId, int? chapterId, int? sceneId) => new()
{
FollowStatus = "Intent unavailable",
EmptyTitle = "No writing intent is available",
EmptyMessage = $"PlotDirector could not load writing intent for chapter {chapterId?.ToString() ?? "unknown"}, scene {sceneId?.ToString() ?? "none"} in project {projectId?.ToString() ?? "unknown"}, book {bookId?.ToString() ?? "unknown"}."
};
private static string MissingScopeMessage(int? projectId, int? bookId, Guid? documentGuid, string screen)
{
if (bookId.HasValue)

View File

@ -0,0 +1,48 @@
using System.Data;
using System.Text.Json;
using Dapper;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.ViewModels;
namespace PlotLine.Data;
public sealed class WorkspaceAgeRow
{
public int SceneID{get;set;}public int ChapterID{get;set;}public string SceneTitle{get;set;}="";public DateTime? StartDateTime{get;set;}public string? TimeModeName{get;set;}public bool IsAppearance{get;set;}
public Scene Scene=>new(){SceneID=SceneID,ChapterID=ChapterID,SceneTitle=SceneTitle,StartDateTime=StartDateTime,TimeModeName=TimeModeName??""};
}
public interface ICharacterWorkspaceReader
{
Task<(CharacterWorkspaceCounts Counts,IReadOnlyList<WorkspaceAgeRow> Ages)> Summary(int character,int user,CancellationToken ct);
Task<(int Total,IReadOnlyList<CharacterWorkspaceEntry> Rows)> Records(int character,int user,CharacterWorkspaceQuery query,CancellationToken ct);
Task<(int Total,RelationshipMapData Data)> Relationships(int character,int project,int user,CharacterWorkspaceQuery query,CancellationToken ct);
Task<(int Total,IReadOnlyList<CharacterImage> Images)> Gallery(int character,int user,int page,CancellationToken ct);
Task<(CharacterRelationshipFrame Relationship,CharacterWorkspaceEvent? Event)> Frame(int character,int user,int relationship,int? eventID,CancellationToken ct);
Task Change(CharacterWorkspaceOperation input,int user,CancellationToken ct);
}
public sealed class CharacterWorkspaceReader(ISqlConnectionFactory connections,IConfiguration configuration):ICharacterWorkspaceReader
{
private sealed class Count{public int Total{get;set;}}
public async Task<(CharacterWorkspaceCounts,IReadOnlyList<WorkspaceAgeRow>)> Summary(int character,int user,CancellationToken ct)
{using var db=connections.CreateConnection();using var grid=await db.QueryMultipleAsync(new CommandDefinition("dbo.CharacterWorkspace_Summary",new{CharacterID=character,UserID=user},commandType:CommandType.StoredProcedure,cancellationToken:ct));return(await grid.ReadSingleAsync<CharacterWorkspaceCounts>(),(await grid.ReadAsync<WorkspaceAgeRow>()).ToList());}
public async Task<(int,IReadOnlyList<CharacterWorkspaceEntry>)> Records(int character,int user,CharacterWorkspaceQuery q,CancellationToken ct)
{using var db=connections.CreateConnection();using var grid=await db.QueryMultipleAsync(new CommandDefinition("dbo.CharacterWorkspace_Records",new{CharacterID=character,UserID=user,q.Tab,q.Page,Search=q.Search??"",q.BookID,q.Category,q.SceneID,q.RelationshipID},commandType:CommandType.StoredProcedure,cancellationToken:ct));return((await grid.ReadSingleAsync<Count>()).Total,(await grid.ReadAsync<CharacterWorkspaceEntry>()).ToList());}
public async Task<(int,RelationshipMapData)> Relationships(int character,int project,int user,CharacterWorkspaceQuery q,CancellationToken ct)
{
using var db=connections.CreateConnection();int total;RelationshipMapData data;
using(var grid=await db.QueryMultipleAsync(new CommandDefinition("dbo.CharacterWorkspace_Relationships",new{CharacterID=character,UserID=user,q.Page,Search=q.Search??"",q.RelationshipID,q.Category,q.OtherCharacterID,q.DefinitionPage},commandType:CommandType.StoredProcedure,cancellationToken:ct))){total=(await grid.ReadSingleAsync<Count>()).Total;data=new(){Books=(await grid.ReadAsync<Book>()).ToList(),Chapters=(await grid.ReadAsync<Chapter>()).ToList(),Scenes=(await grid.ReadAsync<Scene>()).ToList(),Relationships=(await grid.ReadAsync<CharacterRelationship>()).ToList()};}
if(data.Books.Count>20000||data.Chapters.Count>20000||data.Scenes.Count>20000)throw new ArgumentException("Use the full Relationships Editor for a project beyond the workspace ordering limit.");
var order=StoryStateService.OrderScenes(new(){Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes}).Select((s,i)=>new{s.SceneID,Ordinal=i}).ToList();var maximum=q.SceneID.HasValue?order.SingleOrDefault(s=>s.SceneID==q.SceneID)?.Ordinal??throw new UnauthorizedAccessException():order.Count-1;
var events=(await db.QueryAsync<RelationshipEvent>(new CommandDefinition("dbo.ContextRelationshipLens_Events",new{ProjectID=project,UserID=user,RelationshipIDs=JsonSerializer.Serialize(data.Relationships.Select(r=>r.CharacterRelationshipID)),SceneOrder=JsonSerializer.Serialize(order),AtOrdinal=maximum},commandType:CommandType.StoredProcedure,cancellationToken:ct))).ToList();await ParagraphEvidenceProjection.Apply(db,configuration,events);
return(total,new(){Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes,Relationships=data.Relationships,RelationshipEvents=events});
}
public async Task<(int,IReadOnlyList<CharacterImage>)> Gallery(int character,int user,int page,CancellationToken ct)
{using var db=connections.CreateConnection();using var grid=await db.QueryMultipleAsync(new CommandDefinition("dbo.CharacterWorkspace_Gallery",new{CharacterID=character,UserID=user,Page=page},commandType:CommandType.StoredProcedure,cancellationToken:ct));return((await grid.ReadSingleAsync<Count>()).Total,(await grid.ReadAsync<CharacterImage>()).ToList());}
public async Task<(CharacterRelationshipFrame,CharacterWorkspaceEvent?)> Frame(int character,int user,int relationship,int? eventID,CancellationToken ct)
{
using var db=connections.CreateConnection();using var grid=await db.QueryMultipleAsync(new CommandDefinition("dbo.CharacterWorkspace_RelationshipFrame",new{CharacterID=character,UserID=user,RelationshipID=relationship,EventID=eventID},commandType:CommandType.StoredProcedure,cancellationToken:ct));
var definition=(await grid.ReadAsync<dynamic>()).Single();var json=JsonSerializer.Serialize((object)definition);var options=new JsonSerializerOptions{PropertyNameCaseInsensitive=true};var frame=JsonSerializer.Deserialize<CharacterRelationshipFrame>(json,options)!;frame.Relationship=JsonSerializer.Deserialize<CharacterRelationship>(json,options)!;
var item=(await grid.ReadAsync<dynamic>()).SingleOrDefault();if(item==null)return(frame,null);json=JsonSerializer.Serialize((object)item);var eventFrame=JsonSerializer.Deserialize<CharacterWorkspaceEvent>(json,options)!;eventFrame.Record=JsonSerializer.Deserialize<RelationshipEvent>(json,options)!;return(frame,eventFrame);
}
public async Task Change(CharacterWorkspaceOperation input,int user,CancellationToken ct)
{using var db=connections.CreateConnection();await db.ExecuteAsync(new CommandDefinition("dbo.CharacterWorkspace_ChangeRelationship",new{CharacterID=input.CharacterID,UserID=user,RelationshipID=input.RelationshipID,input.Version,input.Action,input.Confirmed,EventID=input.EventID,input.Notes,input.StateID,input.Intensity,input.Awareness,input.TypeID,input.ReverseDirection,input.Reciprocal,input.Permanent,input.ReaderKnows},commandType:CommandType.StoredProcedure,cancellationToken:ct));}
}

View File

@ -0,0 +1,32 @@
using System.Data;
using System.Text.Json;
using Dapper;
using PlotLine.Models;
using PlotLine.Services;
namespace PlotLine.Data;
public sealed record ContextFamilyStructure(IReadOnlyList<Character> Seeds,IReadOnlyList<CharacterRelationship> Links);
public interface IContextFamilyReader
{
Task<ContextFamilyStructure> Structure(int project,int user,IReadOnlyList<int> seeds,CancellationToken cancellationToken);
Task<RelationshipMapData> Tree(int project,int user,IReadOnlyList<int> people,IReadOnlyList<int> links,CancellationToken cancellationToken);
}
public sealed class ContextFamilyReader(ISqlConnectionFactory connections,IConfiguration configuration):IContextFamilyReader
{
public async Task<ContextFamilyStructure> Structure(int project,int user,IReadOnlyList<int> seeds,CancellationToken cancellationToken)
{
using var db=connections.CreateConnection();using var rows=await db.QueryMultipleAsync(new CommandDefinition("dbo.ContextFamily_Structure",new{ProjectID=project,UserID=user,Seeds=JsonSerializer.Serialize(seeds)},commandType:CommandType.StoredProcedure,cancellationToken:cancellationToken));
var names=(await rows.ReadAsync<Character>()).ToList();var links=(await rows.ReadAsync<CharacterRelationship>()).ToList();
if(links.Count>8192)throw new ArgumentException("Family membership exceeds the Context limit. Use the full Relationships Editor.");
return new(names,links);
}
public async Task<RelationshipMapData> Tree(int project,int user,IReadOnlyList<int> people,IReadOnlyList<int> links,CancellationToken cancellationToken)
{
using var db=connections.CreateConnection();RelationshipMapData data;
using(var rows=await db.QueryMultipleAsync(new CommandDefinition("dbo.ContextFamily_Tree",new{ProjectID=project,UserID=user,CharacterIDs=JsonSerializer.Serialize(people),RelationshipIDs=JsonSerializer.Serialize(links)},commandType:CommandType.StoredProcedure,cancellationToken:cancellationToken)))
data=new(){Books=(await rows.ReadAsync<Book>()).ToList(),Chapters=(await rows.ReadAsync<Chapter>()).ToList(),Scenes=(await rows.ReadAsync<Scene>()).ToList(),Characters=(await rows.ReadAsync<Character>()).ToList(),Relationships=(await rows.ReadAsync<CharacterRelationship>()).ToList()};
if(data.Books.Count>20000||data.Chapters.Count>20000||data.Scenes.Count>20000)throw new ArgumentException("Narrative ordering exceeds the Context limit. Use the full Relationships Editor.");
var order=StoryStateService.OrderScenes(new(){Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes}).Select((s,i)=>new{s.SceneID,Ordinal=i}).ToList();
var changes=(await db.QueryAsync<RelationshipEvent>(new CommandDefinition("dbo.ContextRelationshipLens_Events",new{ProjectID=project,UserID=user,RelationshipIDs=JsonSerializer.Serialize(data.Relationships.Select(r=>r.CharacterRelationshipID)),SceneOrder=JsonSerializer.Serialize(order),AtOrdinal=order.Count-1},commandType:CommandType.StoredProcedure,cancellationToken:cancellationToken))).ToList();
await ParagraphEvidenceProjection.Apply(db,configuration,changes);return new(){Books=data.Books,Chapters=data.Chapters,Scenes=data.Scenes,Characters=data.Characters,Relationships=data.Relationships,RelationshipEvents=changes};
}
}

View File

@ -0,0 +1,24 @@
using System.Data;using System.Text.Json;using Dapper;using PlotLine.Models;using PlotLine.Services;
namespace PlotLine.Data;
public sealed record ContextLensRead(RelationshipMapData Data,int? FocusCharacterID,bool Truncated);
public interface IContextRelationshipReader
{
Task<ContextLensRead> Read(int project,int user,int scene,int? focus,string lens,int depth,IReadOnlyList<int> physical,CancellationToken cancellationToken=default);
Task<IReadOnlyList<Character>> Lookup(int project,int user,string search,CancellationToken cancellationToken=default);
}
public sealed class ContextRelationshipReader(ISqlConnectionFactory connectionFactory,IConfiguration configuration):IContextRelationshipReader
{
private sealed record Boundary(int? FocusCharacterID,bool Truncated);
public async Task<ContextLensRead> Read(int project,int user,int scene,int? focus,string lens,int depth,IReadOnlyList<int> physical,CancellationToken cancellationToken=default)
{
using var db=connectionFactory.CreateConnection();IReadOnlyList<Book> books;IReadOnlyList<Chapter> chapters;IReadOnlyList<Scene> scenes;IReadOnlyList<Character> people;IReadOnlyList<CharacterRelationship> links;Boundary boundary;
using(var grid=await db.QueryMultipleAsync(new CommandDefinition("dbo.ContextRelationshipLens_Read",new{ProjectID=project,UserID=user,FocusCharacterID=focus,Lens=lens,Depth=depth,PhysicalIDs=JsonSerializer.Serialize(physical)},commandType:CommandType.StoredProcedure,cancellationToken:cancellationToken))){books=(await grid.ReadAsync<Book>()).ToList();chapters=(await grid.ReadAsync<Chapter>()).ToList();scenes=(await grid.ReadAsync<Scene>()).ToList();people=(await grid.ReadAsync<Character>()).ToList();links=(await grid.ReadAsync<CharacterRelationship>()).ToList();boundary=await grid.ReadSingleAsync<Boundary>();}
if(books.Count>20000||chapters.Count>20000||scenes.Count>20000)throw new ArgumentException("This project exceeds the Context narrative-order limit. Use the full Relationships Editor.");
var order=StoryStateService.OrderScenes(new(){Books=books,Chapters=chapters,Scenes=scenes}).Select((s,i)=>new{s.SceneID,Ordinal=i}).ToList();var at=lens=="family"||scene==0?order.Count-1:order.FirstOrDefault(s=>s.SceneID==scene)?.Ordinal??-1;
var changes=(await db.QueryAsync<RelationshipEvent>(new CommandDefinition("dbo.ContextRelationshipLens_Events",new{ProjectID=project,UserID=user,RelationshipIDs=JsonSerializer.Serialize(links.Select(r=>r.CharacterRelationshipID)),SceneOrder=JsonSerializer.Serialize(order),AtOrdinal=at},commandType:CommandType.StoredProcedure,cancellationToken:cancellationToken))).ToList();
await ParagraphEvidenceProjection.Apply(db,configuration,changes);
return new(new(){Books=books,Chapters=chapters,Scenes=scenes,Characters=people,Relationships=links,RelationshipEvents=changes},boundary.FocusCharacterID,boundary.Truncated);
}
public async Task<IReadOnlyList<Character>> Lookup(int project,int user,string search,CancellationToken cancellationToken=default)
{using var db=connectionFactory.CreateConnection();return (await db.QueryAsync<Character>(new CommandDefinition("dbo.ContextCharacter_Lookup",new{ProjectID=project,UserID=user,Search=search},commandType:CommandType.StoredProcedure,cancellationToken:cancellationToken))).ToList();}
}

Some files were not shown because too many files have changed in this diff Show More