PlotDirector/Docs/Navigation/NarrativeFocusArchitecture.md

23 KiB
Raw Blame History

Narrative focus and Scene Explorer: audit, architecture and qualification

Follow-up: global stepping now lives in the shared Focus ribbon; see Focus ribbon consolidation for the navigation inventory and workspace adapters.

Status: implemented on the established development branch; final qualification and deployment results are recorded below. The first table preserves the initial audit; the completed classification follows it. The unrelated CanonicalManuscriptArchitectureAssessment.md is not part of this work.

Findings and evidence

Surface Current mechanism Classification and migration direction
Relationships RelationshipMapController.Index/State, relationship-workspace.js: range input, Initial/End endpoints, relationship-change markers; debounced state fetch with cancellation. The scene sequence comes from server-provided options. Local exploration. Preserve Initial/End snapshots and change markers as extensions; scene explorer must not write global focus. Verify ordering and book scope of the State request before replacement: the inspected refresh passes projectId/sceneId, not bookId.
Maps maps-story.js maintains scene, chapter, plot, character and time lenses. Scene scrubber uses filtered scene indices; Previous/Next changes to dated-event navigation in Time lens. Session storage key includes user/project/map. MapStoryService composes NarrativeOrder and can substitute scenario attribution order. Local exploration and local filters. Extract scene navigation without conflating Time events, map selection, scenario order or character journeys with global manuscript order.
Maps right panel renderDetails, sceneDetails, legDetails, feature/overview details: scene endpoints, repeated journeys, dates, location coverage and editable travel context. maps-workspace.js separately maintains map-edit undo/redo history. Retain and adapt the detail/history panel. It is not redundant with a scene dropdown. Neither journey history nor edit undo history is recent global-focus history.
Floor Plans FloorPlans/Edit.cshtml contains inline occupancy navigation: scene dropdown, Previous/Next by option index, initial-floor selection and occupancy trays. Scene_ListByFloorPlan is the data contract (082_FloorPlanOccupancySceneOrdering.sql). Local exploration plus specialised floor/occupancy editing. Preserve edit targets, floors and trays. Validate whether the eligible-scene subset can represent all book positions before attaching a full-book explorer.
Writer WriterObjectiveRepository, WriterController.SaveObjective, dbo.WriterObjective (280_WriterFocusIntention.sql) persist chapter/scene together with activity and intention. Review falls back to objective chapter. WriterContext explicitly separates Working, SavedObjective, Exploration, PinnedReference, Reader, Session and VerifiedWord. Existing persisted location is coupled to task data. Requires the decision below before introducing an authoritative global service.
Timeline Timeline/Index.cshtml exposes selectedSceneId links, jump-scene controls, scene inspectors and filter-selected scene fields. Provisional: explicit scene-opening navigation should commit focus; filter matches and inspection must be classified separately before wiring.
Plot Lines / Threads Plot Line workspace exposes scene-inspector controls and attribution/scenario projections. Provisional: inspection, scenario attribution, filtering and explicit opening are different actions. Do not treat every scene ID as navigation. Trace Thread handlers before consolidation.
At This Point StoryPoint/Index.cshtml has book/chapter/scene controls tied to its snapshot. Provisional: separate deliberate navigation from local reference snapshots before conversion.
Reader / Review _Reader.cshtml, manuscript-reader.js: chapter Previous/Next, reading mode, focus mode, accepted manuscript and paragraph selections. Explicit chapter navigation may commit global focus. Reading-mode toggles, scrolling, annotation selection and rendering must not. Preserve specialised manuscript controls where the header is hidden or insufficient.
Reflect / Calendar / planning Not yet fully traced. Inventory pending. Scheduling, recording-session binding, comparison and activity filters must not be converted by selector-name heuristics.
Word writer-word.js reacts to explicit focus-saved events but does not move Word automatically. Navigate/Availability use verified instance, document session, manuscript, revision and accepted paragraph identity; document-position adoption is explicit. Keep observed Word position separate. Global context may supply intended navigation targets, never manufacture verified paragraph or scene associations.

Approved objective boundary

Saved Writer objectives remain independent task targets. The author approved this boundary before implementation. Activity, intention, chapter and scene remain unchanged until explicitly edited. The new focus is seeded once from a valid existing Writer location; later reads never use the objective as a fallback. Go to objective navigates without saving an objective. Objective editors retain explicitly selected targets while global focus changes.

Shared architecture

  1. A read-only, authorised narrative-position provider returns stable BookID/ChapterID/SceneID, display text and manuscript sequence. Use authoritative SortOrder with stable ID tie-breakers; audit existing ordering procedures before selecting one provider. Do not order by fictional timestamps. Scenario order remains an explicitly local alternative.
  2. A small Scene Explorer view/component plus JS controller accepts positions, selected ID and a local selection callback. It supplies scrubber, grouped chapter/scene dropdown, mirrored Previous/Next, boundary-disabled states and accessible current-position text. Optional slots retain relationship markers and workspace detail panels. No focus writes occur in its default callbacks.
  3. Each visual workspace retains an independent, user/book/workspace-scoped position. Floor-plan occupancy and map filters are not rewritten by header events. Initial/End relationship snapshots remain explicit non-scene positions and cannot be promoted as fabricated scene IDs.
  4. One narrative-focus repository/service/API persists current location and bounded deduplicated recency (proposed bound: 20) per authenticated user/project/book, using Dapper and stored procedures. Membership and scene/chapter/book relationships are checked server-side. Changes use a version token; stale multi-window writes are rejected rather than silently overwriting a newer selection.
  5. Header selection/search, explicit scene-opening links, global Previous/Next and the explorer's explicit Set Current Focus Here are deliberate commit paths. Global stepping uses the manuscript sequence; recent-history selection uses recency, never scene chronology.
  6. Deleted/moved scene identifiers are revalidated on read/commit. Prefer retaining a valid chapter-only focus when a scene disappears; do not jump into another book. Reordering changes neighbour calculations, not stable focus identity. Revalidate and prune invalid recent entries.
  7. Successful commits publish a scoped presentation event. Cross-window updates carry scope/version, trigger authorised refresh, and do not navigate the document. Workspace adapters update only safe dependent read-only regions; dirty editors retain their fields and offer explicit application of the new target. No blanket form replacement or synthetic change events.
  8. Reader and verified Word adapters keep accepted manuscript identity, paragraph revision checks and recording-session binding independent. A global scene ID is a navigation intention, not proof of a Word position. Scrolling and visualisation selection never invoke Word navigation.

Staged delivery and qualification

  • Stage 1: finish ordering/scope checks; implement the local Scene Explorer and adapters for Relationships, Maps scene lens and Floor Plans. Retain specialised panels and Time lens. Prove no focus writes on local events.
  • Stage 2: after resolving the objective boundary, implement focus persistence/history and the header; migrate current-location consumers atomically to one authority. Forward-only SQL after Development backup and live schema verification.
  • Stage 3: complete the page inventory, tracing every commit-capable selector. Remove only controls made genuinely redundant; keep local filters, comparisons, edit targets and focus-mode fallbacks.
  • Stage 4: integrate explicit Reader/Word navigation using existing verification gates. Retain unsaved editors and active session bindings.
  • Stage 5: SQL/service/controller tests for ownership, scope, neighbour order, deleted/reordered/moved scenes and concurrent versions; Chromium and installed PWA across workspaces, refresh, project/book switches, dirty editors, independent local positions and verified/unverified Word targets.

Only qualified changes may deploy to Development. Production is excluded. See the implementation and qualification record below.

Approved boundary and completed selector classification

The author approved independent saved objectives. The alternative that retargets objectives is rejected. Saving an objective does not commit global navigation; Go to objective does. Existing task editors retain their selected fields when the header changes. Recording, observed/verified Word positions and accepted paragraph references are separate bindings.

Inventory was extended before removing any page selector. Classifications below describe semantics, not automatic conversion based on field names:

Surface / implementation Classification Retain / integrate
Timeline scene-card destination (SelectedSceneID, FocusType, FocusID) Explicit narrative navigation Commit when the author follows a scene card; filter restoration, scrolling, search, jump-to-visible-position and drag/reorder do not commit.
Timeline controls: BookID, SelectedSceneID, FocusType, FocusID, saved presets Local filter/highlight Retain; applying a preset is not narrative navigation.
PlotLineWorkspace scene inspector and scenario attribution Local inspection/comparison and scenario editing Retain; explicit Open Scene destinations commit through Scenes/Edit.
PlotThreads introduced/planned-resolution/actual-resolution scene fields Persisted entity editing Retain unchanged; never retarget on navigation.
StoryPoint/Index book/chapter/scene and Show state (story-point.js) Local snapshot exploration Retain and label as snapshot position, not current focus. Its AJAX updates do not write focus.
StoryCalendar book/month/date controls Local chronological filtering Retain; dates are fictional chronology, not manuscript ordering. Explicit Open Scene commits.
Writer Plan / WritingActivity chapter/scene destinations Explicit navigation from independent task/session records Retain useful links; preserve schedule/session target IDs.
Writer Reflect calendar, date, session and activity controls Historical filters Retain; never move recorded sessions.
Writer focus wizard and legacy objective form Independent objective editing Retain explicit target selectors. Do not subscribe form fields to header events.
Writer work toolbar chapter and activity fields / Audio Review New-session binding or specialised media operation Retain. Existing sessions keep original binding.
Writer authoring chapter/scene intent forms Explicit editing targets Retain while editing; header changes defer replacement and offer explicit application after Save/Cancel.
Reader chapter picker / Previous / Next Global chapter navigation Integrate explicit destinations. Retain in Focus Reading because the normal header is inert/hidden. Reading/focus-mode toggles, paragraph selection and automatic accepted-content refresh never commit focus.
Writing Context / Intent jump controls (writing-follow.js) Specialised pinned/snapshot/document-follow reference navigation Retain and distinguish from global focus. Existing explicit verified Word navigation is a separate operation; following observations is never authoritative global navigation.
NativeWorkspace Review scene index and Word-session picker Verified manuscript repair/navigation Retain; preserve exact live document/revision checks, no inferred scene mappings.
Warnings chapter filter; ContinuityExplorer chapter/start/end/selected scene Local diagnostic filters/ranges/comparison Retain; explicit scene-opening links commit independently.
Chapters/Edit IDs and nested SceneInspector dependency/character/note/attachment selects Entity editing Retain; identifiers bind edits, not global navigation.
Admin Story Intelligence chapter selectors Administrative test/analysis targets Retain; outside narrative navigation.
Scenarios timeline ordering and attribution selectors Alternative-order editing/comparison Retain. Never rewrite canonical focus order.
Relationships scene position Local Scene Explorer Shared controls; retain Initial/End and separately labelled relationship-change stepping.
Maps scene position, scene/chapter/character/plot/time lenses Local Scene Explorer + filters Shared scene controls; retain time-event navigation and journey/scene/travel-context panel.
Floor Plans occupancy scene Local Scene Explorer + occupancy edit target Shared controls; retain eligible-scene subset and floor/tray editing. Local events no longer publish to writing-window position bus.

No page-level selector has been removed on the assumption that a scene ID implies global navigation. Useful specialised controls remain; the header supplies the single normal-workspace global selector.

Final implementation

  • INarrativeFocus / NarrativeFocus is the sole persistent current-location authority. All database calls use Dapper and stored procedures. WriterContext.Working, header display and Writer’s intended Word targets project this service; Review keeps its accepted Reader/paragraph target independently. Saved objectives occupy only SavedObjective.
  • Migration 292 creates NarrativeFocus and NarrativeFocusHistory, plus NarrativeFocus_Read, NarrativeFocus_Set and NarrativeFocus_Locate. It also changes WriterObjective reads to retain saved target metadata when its chapter/scene becomes unavailable, without modifying the objective. Migration 293 ensures position results follow NarrativeSceneOrder.BookSceneIndex, including tied chapter numbers/orders. Migration 294 inserts empty chapters at their chapter position and steps from them to real neighbouring scenes; a moved scene is never followed implicitly into another chapter.
  • Current records are keyed by authenticated user/book; every procedure validates the requested project/book against active user access and non-archived entities. A book belongs to one project. Chapter/scene identifiers are revalidated against that book. Deleting a book/user cascades only its focus/history; chapter/scene deletion is handled by read-time validation, retaining a valid chapter where possible. No story entity is modified by navigation.
  • Initialisation is locked and transactional. Only a missing focus row can be seeded from a valid Writer objective location. An explicitly empty focus remains empty on subsequent reads. Automatic invalidation increases the version. Commits use an expected version, so stale windows receive HTTP 409 and refresh before retrying. No-op navigation does not add history or write another version. Personal focus navigation remains available in read-only accounts without granting story-content editing.
  • History contains at most 20 distinct chapter/scene pairs, ordered by recency, separate from manuscript neighbours. Invalid/moved history entries are pruned. Reordering changes neighbours, not stable identities.
  • _NarrativeFocus and narrative-focus.js provide header selection, search, previous/next and recent focus. Scoped storage notifications and window-focus/disclosure refresh reconcile windows through the authorised service. Client storage never stores an authoritative chapter/scene fallback. Project-wide pages retain their all-books filters: their focus picker can select a focus book independently. Device storage remembers only that picker’s book scope, not narrative location. Background refreshes queue behind scope selections/commits, so a late disclosure or cross-window refresh cannot revert them.
  • NarrativeNavigationFilter commits only successful, deliberate chapter/scene destinations. Background fetches, AJAX inspection and prefetches do not commit. Timeline scene-card/scene-link destinations explicitly identify navigation; filters, presets, scrolling, entity back-links and edit cancellation do not. The one-use navigation marker is removed from the displayed URL after navigation.
  • Writer shows current narrative location separately from the saved objective and offers Go to objective. Its chapter-only Go to scene shortcut now navigates through the focus service; it no longer posts to SaveObjective and cannot clear an intention. The objective wizard and legacy form keep explicit target fields, including unavailable saved targets that require explicit replacement. Unsaved wizard edits protect full-page navigation; Cancel restores the last confirmed target. Post-edit return redirects retain the independently selected global focus.
  • scene-explorer.js composes shared native dropdown/range controls, matched chevrons, manuscript stepping, accessible output and an explicit promotion action. There are no implicit focus writes. Relationships retains Initial/End snapshots and change-marker navigation; scene buttons skip non-scene snapshots. Maps retains its six lenses, journey/scene/travel-context detail panel and separate dated-event navigation. Default/global scene order is canonical manuscript order; explicitly selected scenarios retain their existing local projected manuscript order, never fictional-event chronology. Floor Plans retains its eligible-scene subset, floors and occupancy editing; its sequence now follows manuscript sort order. Local positions remain independent and are retained using workspace-scoped session storage (Maps keeps its existing storage mechanism).
  • Promotion is available only for a real scene in the header’s current book. For another book, choose that focus book first. Initial/End snapshots cannot be promoted as fabricated scene IDs.
  • Writer’s inline editors defer content changes while open/dirty/busy. Review changes chapter within its stable three-column container and preserves divider elements, Word state objects and recording controls. Unsaved annotations retain their original chapter/reference; authors apply pending focus after saving or cancelling. Annotation filters and the existing Pause/Resume updates checkbox state survive the refresh; the label/icon use that same state immediately. A global scene can select an already accepted, mapped paragraph; missing mappings remain explicit and never create scene associations.
  • Verified Word observations, accepted paragraph identities and recording-session bindings remain independent. The verified Word-origin adoption action changes global focus, not objectives. A default Reader preview does not set global focus, and its Word target remains the displayed accepted chapter rather than an invented global location. Word navigation/synchronisation still uses the existing document/session/manuscript/revision and availability checks; global navigation never moves Word automatically.

Qualification record

Development database backup: COPY_ONLY, checksum, compression and RESTORE VERIFYONLY succeeded before migrations. Only Development was used. SQL regressions create disposable synthetic books/scenes and roll back every fixture; existing author story/objective records are not edited by the tests.

Qualification commands and results follow. The deployment identifier is recorded in the task completion report and the Development release archive. Screenshots are generated under /tmp/pd-narrative-* by PlotLine.Tests/Browser/narrative-focus.cjs. The browser host renders real compiled Razor and production JavaScript using isolated fixture repositories; Word transport is simulated. No physical Word Companion acceptance is implied.

  • dotnet build PlotLine.slnx: successful, zero warnings/errors.
  • dotnet run --no-build --project PlotLine.Tests: full executable regression harness, 632 PASS checks.
  • PlotLine.Tests/Sql/NarrativeFocus.sql: six rollback-only phases passed as both Development administrator and application principal. Covers one-time seed/no fallback, author/project/book scope, CAS, canonical order across chapters, empty chapters, bounded/deduplicated history, reordered/moved/deleted/archived targets, objective preservation and fixture cleanup.
  • sudo -n dotnet PlotLine.Tests/bin/Debug/net10.0/PlotLine.Tests.dll --narrative-focus-database /etc/plotdirector/plotdirector.env: actual Dapper repository integration passed. Verifies multi-result DTO mapping, Read/Set/Open, expected book scope, history, independent objective fields and complete ambient-transaction rollback. Connections close before chained repository operations to avoid pool starvation.
  • node PlotLine.Tests/Browser/narrative-focus.cjs and xvfb-run -a node PlotLine.Tests/Browser/narrative-focus.cjs --installed: real compiled MVC/Razor/JavaScript passed in Chromium and installed Chromium PWA (CDP-installed app; standalone display mode asserted). Includes Timeline → Writer, header scene stepping/search/recency, independent objective fields and editors, explicit Go actions, stale-window conflict, account/book isolation, antiforgery, full book-switch cancellation with unsaved work, stable Review updates, Pause/Resume preservation, local exploration/promotion, local position persistence, project-wide focus-book selection, reopen, light/dark and narrower widths. A synthetic 5,000-scene header search/render took under 60 ms in measured runs.
  • Existing Maps Story browser/PWA suite passed: six lenses, canonical navigation, repeated journeys, travel context, stable canvas and 500 scenes/5,000 appearances; 50 scene changes took about one second.
  • Existing Relationships suite passed: 75 characters/300 scenes, local timeline, change markers, editing, layout and PWA controls. Visual inspection found and fixed clipping by replacing the fixed timeline-row height with content sizing; all controls are visible at 1666, 950 and 650 px.
  • Floor Plan save regression passed: failed/redirected/invalid saves, retained blocks, overlapping edits and navigation protection in browser/PWA.
  • Writer Word, Writer authoring and Manuscript Reader suites passed. Word transport/receipts are simulated. Authoring covers save/cancel, concurrent edits, retained unsaved text and scoped fields; obsolete test selectors were updated to the existing ribbon command and current labels. Reader covers real Razor/controllers, private responses, chapter navigation/empty chapters, focus mode and three widths × four themes × browser/PWA.

Reader’s chapter picker and chapter-level shortcuts remain for Focus Reading, native GET/no-script navigation and chapter-level operations; the central scene navigator does not duplicate those specialised contracts. Reference-window selectors, calendar/history filters, diagnostic comparisons and persisted editing targets remain local. No physical Word device was available: live hardware acceptance remains outside these fixture-based checks. No other implementation limitation is known.