diff --git a/Docs/Investigations/CanonicalManuscriptArchitectureAssessment.md b/Docs/Investigations/CanonicalManuscriptArchitectureAssessment.md new file mode 100644 index 00000000..fb412226 --- /dev/null +++ b/Docs/Investigations/CanonicalManuscriptArchitectureAssessment.md @@ -0,0 +1,591 @@ +# Canonical Manuscript Architecture Assessment + +**Investigation date:** 13 November 2026.\ +**Source baseline:** `ec5cf67` on `codex/word-companion-native-phase1-20261104`.\ +**Scope:** architecture investigation and recommendations only. No editor implementation is authorised by this document. + +> **Historical assessment — retained on 29 November 2026.** Findings and the Development +> census below describe the investigation date and source baseline above, not current +> implementation or deployment status. Repository reconciliation checked source-reference +> availability and document integrity; it did not repeat the database census or Word +> qualification. Recommendations remain proposals requiring separately authorised work. + +## 1. Executive summary + +PlotDirector already has a substantial **plain-text manuscript and reconciliation foundation**, considerably more than scene summaries or transient analysis input. Paragraph-tracked books persist complete captured paragraph text and PlotDirector-generated GUIDs in `dbo.BookParagraphManuscripts.Payload`. The model separates occurrence identity from order, maintains chapter/scene assignments, reconciles Word identifiers conservatively, preserves passage evidence, checks expected revisions, and projects accepted prose into the existing `SceneManuscriptSources` interface. + +The live Development database confirms that these structures are populated, not merely proposed. At the read-only census, its 14 books had 14 paragraph manuscript records containing 118,399 paragraph occurrences. None had null paragraph text, missing/null GUIDs, duplicate GUIDs within a book, or ordinals inconsistent with their JSON array positions in the checks performed. These are aggregate snapshot checks, **not proof that every original DOCX component was captured**, nor a Production census or an audit of every historical import. + +**The database can reconstruct the captured main-document plain-text stream for a complete tracked snapshot. It cannot reconstruct the original DOCX or a semantically complete illustrated/formatted manuscript.** Bold/italics, paragraph style beyond outline level, manuscript image binaries and placements, headers/footers, page layout, and other Word objects are not represented as canonical content. Older scene-source imports preserve actual prose but normalise or omit structural material; they cannot universally reconstruct the original paragraph stream. A scene summary, analysis quotation or paragraph index is not a substitute for full paragraph text. + +This foundation is **not yet a complete shared editing model**. There is no durable paragraph operation journal or full revision history, no general paragraph-to-entity reference index, no authoritative-editor fence, and no genuine offline manuscript store. The existing book JSON aggregate is appropriate to preserve while completing the Companion, but whole-book serialization and embedded Word coordinates should not become a long-term per-keystroke Writer API. + +A single percentage would imply a denominator that does not exist. Qualitatively, **most of the difficult Word capture/reconciliation and existing story-domain foundation is present; the editor-independent content/history/reference contract is partial; the offline editing foundation is largely absent**. It would be inaccurate to call the future Writer “nearly finished”, and equally inaccurate to start manuscript identity, import, Context or intelligence again from scratch. Section 8 provides a capability-by-capability assessment instead of invented numerical precision. + +### Immediate go/no-go + +- **GO:** finish and qualify the current VSTO Companion, including real Word Context/Intent launch and pending-to-verified following. Preserve its existing chapter/checkpoint and paragraph reconciliation contracts. +- **GO:** retain these findings and explicit authority/completeness contracts as design inputs; address demonstrated Companion correctness or recovery defects through its normal focused development process. +- **NO-GO now:** introduce a new paragraph schema, convert live books, add a native editor mutation path, or build offline/publishing infrastructure as a prerequisite to Companion completion. No absent-text emergency was found that justifies that diversion. +- **GO after the Companion milestone, under a separate authorised task:** establish the shared content/revision contract and a compatibility-preserving storage migration before Writer begins making edits. + +## 2. Evidence, scope and limits + +### 2.1 Investigation method + +Reviewed existing operational and architectural documentation first, then traced the actual models, services, repositories, stored procedures, native protocol and VSTO reader. Relevant existing documents include: + +- [Paragraph synchronisation foundation](../WordCompanion/2026-11-07-paragraph-sync-foundation.md), whose initial rollout restrictions are explicitly superseded by later delivery reports. +- [Chapter synchronisation contract](../WordCompanion/2026-11-09-chapter-sync-contract.md), [implementation](../WordCompanion/2026-11-09-chapter-sync-implementation.md) and [VSTO range verification](../WordCompanion/2026-11-12-vsto-range-synchronisation.md). +- [Context/Intent delivery evidence](../WordCompanion/2026-11-12-context-intent-integration.md). +- [Single-system Story Intelligence runtime](../../docs/story-intelligence/single-system-runtime.md) and [exception review policy](../StoryIntelligence_ExceptionReview.md). +- [Earlier backup/import/export audit](2026-11-06-backup-import-export-audit.md); its historical gaps are not assumed current where paragraph recovery has subsequently changed the implementation. + +Read-only SQL used the effective Development connection configuration parsed as data, verified both configured catalog and `SELECT DB_NAME()` as `PlotDirector_Development`, and executed only metadata/aggregate SELECTs. Queries inspected table columns, selected foreign keys, temporal-table status, relevant procedure definitions/hashes, and aggregate manuscript coverage. No author prose, account credentials or entity names are reproduced here. No rows, schema, migrations, feature settings or services were changed. The only repository change for this investigation is this assessment. No branches were created/switched, no deployment occurred, and no application/full regression suite was run. A small temporary external metadata-reader utility was compiled; it is not application code or a new repository component. + +Labels used below: + +- **Verified — source:** directly supported by the current checked-in implementation. +- **Verified — live:** directly observed metadata or aggregate data in Development during this investigation. +- **Recommendation:** future design advice, not existing functionality or an approved implementation. +- **Unverified:** evidence not available or behaviour not exercised in this read-only investigation. + +Existing test code and prior qualification reports were inspected as supporting evidence; their tests were not rerun. No Word runtime was available on Atlas. No claim is made about Production schema/data, every Word document feature, exact reconstruction of the protected Discovery DOCX, or current real-Word latency. + +### 2.2 Live census and schema confirmation + +| Read-only observation | Result | Meaning / limitation | +|---|---:|---| +| Books / paragraph manuscript rows | 14 / 14 | Current Development coverage, including whatever synthetic fixtures are retained; not a deployment-wide adoption guarantee | +| Paragraph occurrences | 118,399 | Count from `OPENJSON(Payload, '$.Paragraphs')` | +| Null text / null GUIDs / duplicate GUID groups per book / ordinal mismatches | 0 / 0 / 0 / 0 | Text read as `nvarchar(max)`, avoiding `JSON_VALUE`'s scalar-size limit; does not establish original-document completeness | +| Aggregate paragraph text bytes | 77,012,588 | SQL `DATALENGTH`, UTF-16 storage measure, not words or network bytes | +| Aggregate manuscript payload bytes | 234,800,062 | Includes metadata, prior text and other embedded state; demonstrates actual whole-book payload cost, not a benchmark | +| Books with scene source prose / scene-source rows | 14 / 868 | Real prose exists outside analysis JSON too | +| Structural chapter-source rows / retained onboarding captures | 48 / 1 | Different stores have different coverage; do not assume every book has every source layer | +| `ManuscriptEvidenceIndex` rows | 0 | Passage anchoring exists in code/schema; no live usage was demonstrated by this census | +| Temporal status of manuscript, source, Books and Scenes tables | Non-temporal | Their revision/timestamp fields are not automatic SQL history | + +Live tables and relevant procedures listed in sections 4–5 were present. The current `ParagraphManuscript` definition includes expected-revision locking, selective chapter scope and scene-source projection. It is not just the original migration 240 implementation. Migrations 241/243/249/250 and 245–252 are material to current behaviour. + +For reproducible identification, live procedure SHA-256 hashes over their SQL module definitions were: + +| Procedure | Definition hash | +|---|---| +| `dbo.ParagraphManuscript` | `1D147F6B7D0DDB360236F9A962574D1AECA47A68E3DF4777E96136DE1D6E0B31` | +| `dbo.BookChapterSync` | `8DB3D7FFDE54C70E250CE061044AF4C951AB2712E786BA2A4C42CB779C113757` | +| `dbo.OnboardingManuscriptCapture` | `D6871F72DB002449B92DC3C20668ED0FB899F3D9BCC07E619CB237FD026CD758` | +| `dbo.SceneManuscriptSource_Save` | `CC1F8B78E51A8C5F5FDA99CBDC95EE8E129C1FD8932CDBCC9F7E291CC20AFD70` | + +These identify what was inspected; they do not imply that only one historical migration defines each procedure. + +## 3. Existing architecture and data flows + +### 3.1 Current manuscript import and synchronisation + +```mermaid +flowchart TD + W[DOCX or other manuscript open in Word] --> V[VSTO WordAdapter: bounded main-document reads] + V -->|Value fragments: text, outline, positions, native hints| A[Existing Windows agent] + A -->|Authorised native capture API| C[NativeManuscriptCapture] + C --> CAP[(OnboardingManuscriptCaptures: immutable accepted preview)] + CAP --> O[OnboardingService: approved chapters and structural analysis] + O --> B[(Books / Chapters / Scenes / build maps)] + O --> SRC[(ManuscriptStructuralChapterSources / SceneManuscriptSources)] + O -->|Opt-in or eligible adoption| P[ParagraphManuscriptService / ParagraphManuscriptEngine] + A -->|Chapter fingerprints, evidence or authorised changed text| CS[ChapterSyncService / ChapterCheckpointEngine] + CS -->|Changed chapter only when authorised| P + P --> PM[(BookParagraphManuscripts: GUIDs and full captured paragraph text)] + P -->|Existing transactional projection| SRC + CS --> CV[(BookChapterValidations: exact-session accepted position evidence)] + PM --> POS[(BookParagraphPositions / ManuscriptEvidenceIndex)] + SRC --> SI[Existing Scene Intelligence and entity review] + SI --> ENT[(Canonical story entities and scene events)] + CV --> CTX[Native presence to existing Writing Context / Intent] + ENT --> CTX + SRC --> INT[Explicit Intent assessment] +``` + +The local structural preview and the separately approved chapter-review import also exist. They are not additional canonical manuscript engines; section 6 distinguishes their capabilities and source retention. + +**Important DOCX terminology:** the inspected current manuscript import is a **Word-mediated import**, normally from a DOCX already open in Word. `WordAdapter` reads COM ranges, not the DOCX ZIP package from an ASP.NET file upload. The `/Imports` service handles legacy structured JSON and project backup packages, not `.docx`. No independent server DOCX package parser was located in the traced application path. DOCX-specific work is currently largely delegated to Word. A future direct DOCX-upload option would be a new input adapter, not something this assessment assumes already exists. + +### 3.2 Existing intelligence and review flow + +```mermaid +flowchart LR + T[(SceneManuscriptSources)] --> X[Scene Intelligence request with saved scene context] + X --> R[(StoryIntelligenceSceneResults: raw and parsed audit JSON)] + R --> PREP[Deliberate deterministic candidate preparation] + PREP --> Q[(Review generations / candidates / evidence / priorities)] + Q --> DEC[Author decisions or conservative autoacceptance] + DEC --> CAN[(Characters / Locations / knowledge / relationships / thread events)] + CAN --> SP[Story Point chronology and verified knowledge] + SP --> WC[Writing Context] + PLAN[(Saved chapter goals / scene purpose / checklist)] --> WI[Writing Intent] + T --> AS[Explicit Intent assessment] + PLAN --> AS + AS --> E[(WritingIntentAssessments: input hash, results, decisions)] +``` + +Normal review GETs use persisted candidate pages. They must not rebuild candidates or run AI from raw scene JSON. A future Writer should enter the existing source/revision contracts, not bypass this rule. + +## 4. What is actually stored + +### 4.1 Structural and manuscript inventory + +Column lists below identify relevant fields rather than every audit column. Table/column existence in this table was checked live; model and write-path behaviour was checked in source. + +| Concern | Physical persistence | Meaning and writer | +|---|---|---| +| Project | `Projects(ProjectID, ProjectName, Description, IsArchived, …)`; `ProjectUserAccess(ProjectID, UserID, AccessRole, IsActive, …)` | Story/project scope and access; normal repositories and import/build procedures. Not manuscript prose. | +| Book | `Books(BookID, ProjectID, BookTitle, BookNumber, SortOrder, UsesExplicitScenes, …)` | Book identity and order. No authoritative-editor field was found. `Description` is not full book text. | +| Chapter | `Chapters(ChapterID, BookID, ChapterNumber decimal, SortOrder, ChapterTitle, Summary, POVCharacterID, ManuscriptDocumentID, ExternalReference, …)` | Chapter identity/order/planning. `Summary` is not chapter prose. Current narrative ordering uses existing story-order helpers; do not replace it with ID or title order. | +| Scene | `Scenes(SceneID, ChapterID, SceneNumber decimal, SortOrder, SceneTitle, Summary, StructuralSummary, StructuralSetting, SourceStartParagraph, SourceEndParagraph, POVCharacterID, PrimaryLocationID, StartDateTime, EndDateTime, RelativeTimeText, ScenePurposeNotes, SceneOutcomeNotes, …)` | Structural identity, chronology, scene setting and author planning. Paragraph numbers here are source provenance, not permanent paragraph IDs. | +| Imported chapter source | `ManuscriptStructuralChapterSources(ChapterID, ProjectID, BookID, SourceText nvarchar(max), SourceWordCount, SourceCharacterCount, ParagraphMapJson, StructuralParsedJson, DefaultPovName, ExplicitNarratorName, CreatedUtc, UpdatedUtc)` | `OnboardingService.SaveStructuralChapterSourcesAsync` → `OnboardingBuildRepository`. Retains actual chapter input and mapping/structural result, not a universally current editable chapter master. | +| Analysis-facing scene prose | `SceneManuscriptSources(SceneID, ProjectID, BookID, ChapterID, SourceText nvarchar(max), SourceWordCount, SourceCharacterCount, SourceStartParagraph, SourceEndParagraph, WordStartParagraphIndex, WordEndParagraphIndex, SourceKind, CreatedUtc, UpdatedUtc)` | Import writes accepted scene text; paragraph sync writes verified prose projections through `SceneManuscriptSource_Save`. Existing analysis/Intent read this interface. Normalised import prose and later exact paragraph projections can differ in whitespace. | +| Paragraph manuscript aggregate | `BookParagraphManuscripts(BookID PK/FK, ManuscriptID uniqueidentifier, Revision bigint, RequestID uniqueidentifier, Payload nvarchar(max), UpdatedUtc)` | One current JSON aggregate per book, not one relational row per paragraph. `ParagraphManuscriptRepository` and `dbo.ParagraphManuscript` persist it. | +| Paragraph payload | `Payload.Paragraphs[].Occurrence.{Id, NativeId, Fingerprint, Text, PreviousText, Ordinal, Start, End, Outline, PreviousId, NextId, Change, WasMoved, Resolution}`; wrapper `{ChapterId, SceneId, Story, PositionVerified}` | `Text` is complete captured text for the occurrence, not an excerpt. GUID identity differs from ordinal, fingerprint and Word hint. `SceneId` here is a grouping GUID; `ParagraphScene.CanonicalId` maps it to integer `Scenes.SceneID`. | +| Paragraph scene/chapter groups | `Payload.Scenes[]{Id, CanonicalId, ChapterId, Title, Retired, MergedInto, NeedsRefinement}`; `Payload.Chapters[]{CanonicalId, HeadingId, Title}` | Engine-owned mapping to existing canonical chapters/scenes. Includes excluded-section boundaries; not all stored paragraphs are `Story=true`. | +| Current position projection | `BookParagraphPositions(BookID, StartPosition, EndPosition, ChapterID, SceneID, Verified)` | Derived lookup for a snapshot. No paragraph GUID/text columns. It is not the paragraph content store or durable edit history. | +| Chapter session validation | `BookChapterValidations(BookID, ChapterID, UserID, SessionID, ManuscriptID, WordRevision, RequestID, ContentHash, IdentityHash, MappingHash, Positions nvarchar(max), SourceRevision, ValidatedUtc, ExpiresUtc)` | Durable but expiring validation of physical Word positions. `Positions` contains per-paragraph GUIDs and ranges. It is not authoritative content and must not be reused as offline revision history. | +| Document binding | `ManuscriptDocuments(ManuscriptDocumentID, BookID, ProjectID, DocumentGuid, BindingVersion, CreatedUtc, LastSyncUtc, LastOpenedUtc, IsActive, CreatedByUserID)` | Association/provenance; not a stored DOCX binary. Native session identity and manuscript GUID also travel in current protocol state. | +| Accepted onboarding source | `OnboardingManuscriptCaptures(PreviewID, UserID, OnboardingID, BookID, Payload nvarchar(max), PayloadHash varbinary(32), CreatedUtc, IsCurrent, AnalysisCheckpoints nvarchar(max))` | `ManuscriptCaptureRepository` persists a `ManuscriptScanPreview`. Contains chapter/source paragraph text and optional `NativeParagraphs`. Accepted payload is hash-checked and immutable for that capture identity. `IsCurrent` changes eligibility; capture is not the live manuscript master. | +| Build provenance | `OnboardingManuscriptBuilds`, `OnboardingManuscriptBuildChapterMap`, `OnboardingManuscriptBuildSceneMap`, `OnboardingManuscriptBuildCharacterMap` | Canonical ID maps and idempotent import recovery. Their existence does not mean all later manuscript revisions were recorded. | + +### 4.2 Reconstructability: four different questions + +1. **Can current captured plain text be rebuilt for a tracked book? — Yes, conditional on a valid complete snapshot.** Order `Payload.Paragraphs` by validated `Occurrence.Ordinal` and concatenate **all** `Occurrence.Text`, not only `Story=true`. This retains captured headings, blank paragraphs and excluded/front material. The initial complete native stream is validated for contiguous fragments and document end; legacy adoption refuses missing original paragraph positions. It reconstructs what Word exposed as captured main-document text, not independently verified original ZIP bytes. +2. **Can an arbitrary historical/import-only book's original plain text be rebuilt from scenes alone? — Not reliably.** Structural analysis uses approved body paragraphs, excludes headings/separators, trims paragraph text, removes outer blank lines and joins with double platform newlines. Scene splits/source ranges are not permanent paragraph identities. Chapter source/capture layers may improve recovery, but coverage must be checked per book. The live 14/14 tracked census does not change that compatibility limitation. +3. **Can the exact original DOCX be rebuilt from database content? — No.** No DOCX package archive, document relationships/media parts, complete run formatting, section/page layout, headers/footers, footnote/endnote structures, fields, tables, text boxes, comments or tracked-change history is preserved as a canonical Word document. Main-story text can include object/control characters without enough information to reconstruct their objects. Word-specific XML is read for verification in some paths; that does not make the XML or its media a persistent canonical document. +4. **Can a complete future semantic publishing manuscript be rebuilt now? — Not for all requested features.** A plain-text book with headings is possible in principle; reliable emphasis, explicit first-paragraph style and manuscript illustrations require additional content metadata. No publishing output implementation or quality guarantee follows from reconstructing plain text. + +### 4.3 Persisted, reconstructed, cached and Word-only data + +| Category | Examples | Consequence | +|---|---|---| +| Persisted current manuscript | Paragraph JSON text/GUIDs; verified scene prose; chapter/scene structure | Reusable foundation; physical storage is already real | +| Persisted import/audit evidence | Accepted capture payload; structural mapping; analysis checkpoints; Scene Intelligence raw/parsed JSON; review decisions | Useful provenance/recovery, but not interchangeable with latest text | +| Reconstructed during processing | Numbered structural paragraphs, accepted scene prose from source ranges, Story Point state at a scene, current evidence validity | Derived results should identify their source revision rather than become competing masters | +| Process-local caches | Agent `ParagraphSnapshotCache`; `NativeAnalysisCache`; ephemeral `NativePresenceStore`; request-scoped StoryContext task memoization | Restart loses these; none is an offline manuscript database | +| Retained only in Word / not captured as semantic content | Inline styling, actual manuscript image objects, full layout, headers/footers and Word editing apparatus | Requires deliberate later extraction/migration if Writer must retain it; cannot be inferred from plain text | + +### 4.4 Images and non-text content + +`CharacterImages` stores character-illustration file paths/thumbnails/captions; `MapReferenceImages` stores map-reference binary data and metadata (`ImageID`, `ImageData`, `ContentType`, `Width`, `Height`, `ContentHash`). Book cover paths and other uploaded resources also exist. These are **story/product assets**, not a manuscript illustration-placement model. + +The native chapter protocol has `ChapterPictureAnchor` information for correct physical position handling. `ChapterWordPositions` hashes/validates anchor offsets, shape IDs/types and Word lengths; `WordChapterRead` uses conservative native/XML fallbacks for pictures, tables, fields, revisions and notes. **Position safeguards are not media ingestion.** `ParagraphOccurrence` has no asset reference, caption, alt text, inline run structure or binary image field. No manuscript-image extraction/persistence path was found in the traced import/sync contracts. Image-only paragraphs or shape markers must not be advertised as a recoverable illustration. + +## 5. Paragraph identity and lifecycle + +### 5.1 Identity layers + +| Identity | Scope and role | Stability conclusion | +|---|---|---| +| `Books.BookID`, `Chapters.ChapterID`, `Scenes.SceneID` | Server canonical integer domain IDs | Reuse existing entities; chapter/scene order is separate | +| `ManuscriptId` / document GUID | Associated manuscript/document namespace | Distinct from Word session; cross-document capture is refused rather than guessed | +| `ParagraphOccurrence.Id` | PlotDirector-generated GUID for an occurrence | Already exists. Intended to survive confidently reconciled edits/moves; not a content hash and not guaranteed through every ambiguous Word transformation | +| `ParagraphOccurrence.NativeId` | Word `w14:paraId` hint / native `Paragraph.ParaID` | Candidate evidence, never the canonical identity | +| `Ordinal`, `PreviousId`, `NextId` | Current order and adjacent occurrence context | Mutable when content moves or paragraphs are inserted/deleted | +| `Start`, `End` and `WordRevision` | Word range coordinates and observed document revision | Session/revision-dependent; not identity and not future Writer ordering | +| Paragraph scene grouping `Id` versus `CanonicalId` | GUID grouping mapped to integer SceneID | Preserve both mapping and evidence lineage; do not conflate them | + +Microsoft specifies `paraId` uniqueness within a document part, not permanent authoring identity across edits/copies/sessions. The implementation correctly treats it conservatively. See [Microsoft's paraId specification](https://learn.microsoft.com/en-us/openspecs/office_standards/ms-docx/a0e7d2e2-2246-44c6-96e8-1cf009823615). + +Initial VSTO capture reads optional hints from first-character `WordOpenXML`; current chapter verification can read `Paragraph.ParaID` directly and uses XML/native positions where necessary. It does not stamp a PlotDirector GUID into every Word paragraph. A persistent document association is not per-paragraph permanent identity. + +### 5.2 Actual reconciliation rules + +Verified in `Protocol/Manuscript/ParagraphIdentity.cs` and the server engines: + +- An unchanged text sequence without contradictory native identity preserves occurrence IDs, even if Word regenerates hints. +- Unique matching native IDs preserve occurrences across ordinary text changes and moves. +- Unique contextual content pairs and already recognised neighbours provide fallback. A hash alone is not sufficient identity evidence. +- Duplicate content/native IDs are resolved only when neighbours identify a single original. New copies receive separate IDs; unresolved competition remains ambiguous. +- One rewrite between independently recognised neighbours can retain an occurrence with a reviewable resolution. Its old text must not have moved elsewhere. +- A longest-increasing-subsequence comparison distinguishes matched moves from ordinal shifts caused by additions/deletions. +- Unmatched incoming occurrences receive new GUIDs. `Compare` reports unmatched prior rows as `Removed`. +- `ParagraphManuscriptEngine` adds chapter-heading windows and chapter-local refinement, and rejects duplicate final identities. It protects excluded boundaries and chapter-scene containment instead of extending a neighbouring scene across uncertain structure. +- The agent adopts canonical IDs from server acknowledgements. Matching content or locally proposed IDs cannot transfer another occurrence's evidence. + +Current guards include a 100,000-paragraph / 16 Mi-character capture/reconciliation bound, a 128 MiB serialized SQL manuscript payload ceiling, bounded chapter requests, and bounded evidence/undo state. These are existing safety limits, not a capacity guarantee for future rich books. A 196,000-word input must be evaluated by actual characters, paragraphs, media and payload size rather than word count alone; a future native contract must retain explicit bounded validation. + +### 5.3 Lifecycle findings and limitations + +| Operation | Existing behaviour | Future Writer implication | +|---|---|---| +| Add paragraph | Fresh occurrence GUID and current ordinal; insertion is distinct from shifting later ordinals | Reuse GUID concept; allocate locally for offline creation and validate server-side | +| Modify paragraph | Retains ID when native/context evidence is sufficient; stores previous text and change reason | Writer knows the addressed GUID and should apply an explicit revision-checked edit, not rediscover identity from text | +| Delete paragraph | Prior row is absent from current paragraph list; affected passage evidence becomes Missing; canonical story events are not automatically deleted | Add durable tombstones/revision history before offline sync; current `Removed` output is not a permanent deletion ledger | +| Move within chapter | Confident matched occurrences can retain IDs; LIS marks movement; scene starts/grouping have separate safeguards | Explicit move should retain ID and change order; do not use delete-plus-insert as the native operation | +| Copy | Context-confirmed original may retain its ID; new copy receives a new ID; uncertain duplicates are not guessed | Native copy must always mint new IDs, optionally record origin lineage, and never duplicate confirmed event evidence automatically | +| Split/merge paragraph text | No explicit persistent split/merge paragraph operation or lineage model; native hint/context may preserve one surviving occurrence, but ambiguity is possible | Define one survivor/new-ID policy and lineage/tombstones; offset references require revalidation. Existing `Split`/`Merge` engine methods split/merge **scene groupings**, not text paragraphs | +| Move across chapters | Current selective `MergeChapter` rejects native IDs owned outside the chapter, changed next-heading boundaries and uncertain structural moves. Whole-snapshot engine has scene-movement logic but also chapter-local reidentification | **No general guaranteed cross-chapter paragraph identity contract exists.** Do not claim a native paragraph can simply be fed through chapter repair and keep its ID. A future explicit move API must preserve it directly | +| Restructure chapter headings | Existing accepted heading identities delimit chapter scope; lost/excluded headings or unknown structural boundaries can refuse updates or require review | Preserve Companion safeguards; separate deliberate native structural operations from externally observed Word restructuring | +| Restart/reopen | Persisted server GUIDs survive; physical live positions require fresh exact-session validation. Agent memory cache is disposable | Reuse durable identity, not cached Word coordinates | +| Restore/transfer | `ParagraphRecovery` validates/remaps canonical integer references while preserving occurrence/group/evidence GUIDs, detaches live session/Word revision and returns eligible modes to Manual | Useful migration/portable-format precedent; restore is not proof that old live Word positions remain valid | + +The future native identity requirement is compatible with the existing GUID model, but **not implemented by the existing heuristic reconciliation API**. `Compare` deliberately does not trust an incoming old GUID as proof of Word identity. A Writer must submit validated explicit operations against known GUIDs/revisions. Keep Word reconciliation as an adapter into that model. + +### 5.4 Revisions and history: what is missing + +`BookParagraphManuscripts.Revision`, `ExpectedRevision`, request identity and SQL locking provide optimistic concurrency and transactional acceptance. Mode changes can increment revision too. Chapter metadata adoption/reuse can update validation/checkpoint metadata without a new prose revision. Thus neither Word revision nor manuscript revision is currently a clean immutable content-history identifier for all purposes. + +`PreviousText` stores an immediate comparison value, not all previous versions. `Undo` holds bounded grouping/layout snapshots (one to twelve depending on paragraph count), tied to a snapshot hash; a changed manuscript snapshot clears incompatible undo. It does not undo arbitrary text edits. Raw analysis runs and accepted captures retain some earlier evidence; restore points/project backups preserve selected snapshots. None provides a complete append-only paragraph edit log, arbitrary revision retrieval, author/device provenance for each edit, or durable deletion lineage. + +## 6. DOCX/Word import pipeline and reuse + +### 6.1 Complete traced current path + +1. **Selection and authorisation.** Existing onboarding associates project/book and chooses the connected Word document. The native browser approval/token/agent session contract scopes transfer; paragraph tracking requires the existing feature/consent path. It is not an unsolicited whole-book upload on opening Context. +2. **Read the open Word manuscript.** `WordAdapter.DocumentEnd` reads `Document.Content.End`. Bounded STA steps read paragraph ranges, `OutlineLevel`, tags and optional native hints, then value-only `ParagraphFragment`s. COM references are released; no COM object crosses IPC. Main-document text is the scope, not a walk of every DOCX part. +3. **Transport and preview.** The existing Windows agent carries authorised fragments to `NativeManuscriptCapture`. It validates monotonic contiguous starts/ends, paragraph completion, document/session/revision, limits and retries. Local `DocumentAnalysis` supplies bounded structural suggestions from heading/marker/prefix cues; those are not server identities or full persisted manuscript content. +4. **Chapter/source assembly.** Native capture constructs chapters using existing chapter tags or outline level 1, detects opening/front material, uses outline level 2/scene markers and separators as cues, and retains `SourceParagraphs` with original indices/text and inclusion flags. The body `ChapterText` excludes structural headings/separators. Optional `NativeParagraphs` retain the complete raw occurrence stream. +5. **Durable capture.** `ManuscriptCaptureRepository` writes immutable accepted preview JSON plus payload hash to `OnboardingManuscriptCaptures`. Request-hashed structural results go into its `AnalysisCheckpoints` sidecar, not into the immutable accepted payload. This supports recovery without silently re-requesting analysis. +6. **Author-approved structural analysis.** `OnboardingService.BuildApprovedStructureAsync` validates review choices, analyses selected chapters through `ManuscriptStructureAnalysisService`, verifies paragraph-map coverage and accepted scene boundaries, and handles invalid proposals conservatively. A structural fallback retains accepted source with a refinement warning rather than inventing a valid-looking range or summary. Scene text is derived from original source entries; it is not generated prose. +7. **Canonical structure/prose.** `OnboardingBuildRepository` and build stored procedures create/reuse project/book chapter/scene mappings. The service saves `ManuscriptStructuralChapterSources` and `SceneManuscriptSources`, chronology/POV provenance and deterministic scene-character mentions. Core location/character review and scene title handling remain existing responsibilities. +8. **Paragraph initialisation.** Eligible tracked captures go to `ParagraphManuscriptService.Initialise`, using accepted scene-source maps and complete raw/legacy reconstructable paragraph provenance. Missing/non-reversible provenance is refused. Existing paragraph state is returned rather than overwritten by a second initialisation. Unapproved/excluded material remains distinct from canonical story prose. +9. **Story analysis and links.** Canonical scene prose feeds the existing Story Intelligence pipeline: saved raw/parsed result, candidate preparation, persisted review, conservative automatic/manual canonical materialisation. This is separate from structural scene detection and from background Word fingerprint checking. +10. **Later edits.** Existing paragraph/changed-chapter reconciliation updates accepted paragraph state and verified scene-source projections. It does not automatically rerun whole-book AI. Current Word mappings are refreshed only with appropriate revision/structure evidence. + +### 6.2 Other import paths and subsequent import handling + +- **Approved native chapter reviews:** `NativeImportService` can import explicitly approved chapter/scene decisions using retained, protected source from `NativeChapterReviews`. Missing encrypted source refuses import; source hashes, review versions, manuscript/book/range identity and confirmation tickets are checked. `NativeReviewImports`/`NativeImportOperations` provide receipts/idempotency. Same content/decisions can be skipped; different content/decisions for an imported chapter, overlaps or duplicate existing chapter titles are conflicts, not an automatic overwrite. This path is **not** a universal full-document/paragraph capture. +- **Existing build resume:** `OnboardingService` reuses completed build maps and repairs missing scene sources from retained source/checkpoints when possible. It is not an unbounded fresh reimport that replaces all existing author structure. +- **Legacy structured JSON/project backup:** `/Imports` (`ImportService`) supports structured story packages and full project backup restore/copy with ID remapping. It is not the Word manuscript parser. Paragraph-enabled backups use format 1.5 recovery; older backups may have only scene text/structure. +- **Changed manuscript after import:** use the current Companion synchronisation/reconciliation mechanism, not repeated initial imports. A different manuscript GUID is rejected by paragraph snapshot sync; it is not assumed to be a newer version of the same book. + +### 6.3 Reuse boundaries + +| Reuse as shared manuscript/domain capability | Keep Word/DOCX-specific | +|---|---| +| GUID occurrence identities, content fingerprints as change evidence, evidence validation and canonical scene mapping concepts | COM range extraction, native `ParaID`/XML hints, Word outline/marker interpretation | +| Validated scene-source interface and existing story repositories/stored procedures | Word session/revision, saved/background-save state, physical offsets and picture-coordinate safeguards | +| Structural analysis of numbered text plus explicit provenance, candidate review and import receipts | External-document identity reconciliation, Word-specific chapter recognition/fallbacks | +| Story Point chronology, recognition/alias policy, canonical materialisation, Context/Intent and continuity | STA scheduling, RCW lifetime, ribbon/selection handling, IPC and Word-specific synchronisation commands | +| Project backup graph validation/remapping/recovery; current access/feature policies | DOCX media/formatting extraction if a future adapter is added | + +Retain the importer. A future direct DOCX reader could emit the same content/import contract, with unsupported-feature reporting and explicit style/media conversion, while preserving Word-mediated import for current users. There is no reason to replace working review/intelligence pipelines merely because the input editor changes. + +## 7. Story entities, references and recognition + +### 7.1 Existing canonical association levels + +| Domain | Persisted canonical association | Paragraph-level status | +|---|---|---| +| Characters | `Characters`, `CharacterAliases`; `SceneCharacters(SceneCharacterID, SceneID, CharacterID, RoleInSceneTypeID, PresenceTypeID, LocationID, EntryLocationID, ExitLocationID, …)` | Scene-level link. Deterministic fields `MatchSource, MatchedText, OccurrenceCount, FirstOccurrenceIndex` describe detection, not a durable list of all GUID-anchored occurrences | +| Character knowledge | `CharacterKnowledge(CharacterKnowledgeID, CharacterID, StoryAssetID, PlotThreadID, SceneID, KnowledgeStateID, SourceEventID, Description, SourceReviewKey)` | Optional paragraph `StoryEvidence` links via event ID, with primary/supporting ranges and offsets. Not every knowledge fact is paragraph-anchored | +| Relationships | `CharacterRelationships` identifies directed/reciprocal pairs, type, initial state, reader-awareness and initial book; `RelationshipEvents(RelationshipEventID, CharacterRelationshipID, SceneID, RelationshipStateID, Intensity, IsKnownToOtherCharacter, Description, SourceReviewKey)` | Optional paragraph evidence for events; relationship identity itself is not a name match | +| Locations | `Locations(LocationID, ProjectID, ParentLocationID, …)`, `LocationAliases`; `Scenes.PrimaryLocationID` and character/asset locations | Primary scene setting is separate from mention evidence. `WordCompanionSceneLocations` and suggestion records are other scene association surfaces, not a complete passage index | +| Assets and state/events | `StoryAssets`, `AssetEvents`, `AssetCustodyEvents`, `SceneAssetLocations`, related character custody records | Scene/event-level state; no general asset-occurrence paragraph index in the inspected model | +| Plot lines/threads | `PlotLines(PlotLineID, ProjectID, BookID, …)`, `PlotThreads(PlotThreadID, PlotLineID, IntroducedSceneID, PlannedResolutionSceneID, ActualResolutionSceneID, …)`, `ThreadEvents(ThreadEventID, PlotThreadID, SceneID, EventTypeID, Source, SourceKey, Confidence, …)` | Canonical scene events plus synthesis evidence; no equivalent universal paragraph occurrence link | +| Timeline | Scene date/time/duration/relative chronology plus domain events, temporal clues and existing timeline projections | Not one independent chronological Event table for every action described in prose; scene order and story time must remain distinct | +| Planning/continuity | `SceneDependencies`, `ChapterGoals`, `SceneNotes`, `SceneWorkflow`, checklist and warning/acknowledgement records | Author planning is not automatically manuscript evidence or character knowledge | +| Extracted observations/review | `StoryIntelligenceSceneResults`; `StoryIntelligenceReviewCandidates`, `StoryIntelligenceReviewCandidateEvidence`; narrative candidate evidence/events | Scene IDs, excerpts, confidence, generation/decision provenance. Source paragraph numbers or quotation text are not confirmed permanent paragraph anchors | + +`ManuscriptEvidenceIndex` indexes only `Knowledge` and `Relationship` kinds, with `EvidenceID, EventID, IsPrimary, EvidenceState, DerivedSceneID`. The detailed payload stores start/end paragraph GUIDs, optional offsets, original/confirmed/current text and positions. A changed/deleted passage can become Needs review/Missing without deleting the event. Only verified primary evidence can derive its canonical scene and participate as verified evidence in relevant knowledge/relationship projections. + +The live index count was zero, so broad automatic anchoring must not be described as already deployed and populated. + +### 7.2 Semantic distinctions already supported + +**Mention versus physical appearance.** Core deterministic name/alias matching stores **Mentioned Only** scene association, occurrence count and first source-text index, rather than claiming physical presence. `BuildMatchIndex` rejects generic/ambiguous terms and uses canonical character IDs. However, the implementation falls back to other lookup values if the Mentioned Only vocabulary is absent. Preserving that vocabulary and provenance is important; its deterministic fallback is not proof of presence. + +Scene Intelligence separately represents `mentionedOnly`, roles, actions and confidence. Prompt V2 explicitly handles remembered, imagined, discussed or speculated-about people as mentioned-only. Canonical import maps that evidence to existing role/presence lookups. Appearance facts have evidence kind and confidence; describing someone's appearance does not itself establish that they are physically present. + +**Mentioned location versus actual setting.** `SceneIntelligenceLocation` has `PresentInScene` and `MentionedOnly`; scene `setting` is separate. Location import carries contextual parent/setting/significance evidence and only links a present setting under its rules, preserving an already recorded primary location. The current model does not turn every named road, room or recalled place into the current scene location. + +**Observed fact versus belief/hearsay/knowledge.** Knowledge extraction keeps source/acquisition/change signals and confidence. `StoryIntelligenceReviewPolicy` does not automatically equate belief, inference, suspicion or hearsay with established knowledge. It requires canonical identity, appropriate state, scene and supporting provenance for automatic canonical materialisation. Relationship policy preserves direction, reciprocity and awareness; confidence alone is insufficient. + +**Event now versus recalled/discussed/anticipated event.** Existing temporal clues, scene chronology, extraction evidence, notes and narrative contribution/event types retain some distinctions. However, the inspected schema/model does **not** establish a general paragraph-anchored event ontology with a mandatory occurrence mode such as `happening / recalled / reported / anticipated`, independent event time and narrated-at scene. Prompt instructions and free-text evidence are not equivalent to that structured guarantee. Treat this as a genuine future gap, not as proof that every described event can be safely placed on the current timeline. + +**Reader / viewpoint / author.** Relationship records have some reader-awareness fields, but there is no complete independent reader-knowledge ledger. Current Context explicitly says reader knowledge is not independently recorded, uses verified viewpoint knowledge through the narrative point, and labels other participant knowledge/planning as author reference. Do not generalise relationship reader flags into a complete reader model. + +### 7.3 Automatic reference association without thousands of manual tasks + +There are strong reusable pieces: canonical integer entity IDs, aliases, exclusion/priority controls, deterministic character matching, extraction confidence/evidence, persisted candidate generations, automatic existing-identity resolution, source-key idempotency, conservative exception review, and canonical materialisation. A future Writer need not ask an author to approve each clear occurrence in a 196,000-word book. + +What is missing is a **general, revision-aware occurrence index** connecting paragraph GUIDs/offsets to those canonical entities and semantic roles. Existing `SceneCharacters` counts/first index and scene evidence excerpts are not that index; offsets can become stale after text changes, and scene splitting changes their coordinate scope. Recognition also does not currently run as a general cheap incremental Writer paragraph service on every accepted edit. + +Recommendation: later index high-confidence, uniquely resolved **references** automatically, scoped to the book/project and accepted content revision; record entity ID, reference kind, span, confidence, recogniser/version, source revision, resolution reason and review state. Review ambiguous identity groups or consequential semantic assertions, not thousands of routine exact mentions. Keep separate operations for mention indexing, participant/setting decisions, event interpretation and canon materialisation. A name occurrence must not automatically create a scene participant, new location identity, learned fact, relationship state or timeline event. Preserve author decisions across new analyses and revalidate spans when text changes. + +## 8. Current capability versus the proposed foundation + +| Required capability | Position | Reuse / gap | +|---|---|---| +| Permanent paragraph identity separate from order | Substantial | GUIDs exist; native explicit lifecycle contract and cross-chapter guarantees are missing | +| Complete current paragraph text | Present for complete tracked captures | Do not add a second text store merely to solve a nonexistent general absence; coverage/completeness still needs per-book qualification | +| Chapter/scene structure and ordering | Substantial | Existing canonical IDs, sort fields and grouping safeguards; Word coordinates must become adapter metadata | +| Change detection and external identity reconciliation | Substantial | Preserve current protocol/engines; native Writer must use explicit operations instead of heuristics | +| Revision concurrency | Present | Expected-revision/CAS exists; metadata/prose revision semantics and durable operation history need separation | +| Full edit history, deletion/split/merge lineage | Missing as a manuscript capability | Prior text/layout undo/backup snapshots are insufficient | +| Semantic paragraph styles | Partial | Outline identifies headings; no explicit Normal versus First Paragraph semantic style | +| Bold/italic and lightweight inline formatting | Missing from content model | Add a small versioned, validated mark representation later | +| Manuscript images and placements | Missing | Existing map/character images and Word shape anchors are not this capability | +| Story domain and analysis/review | Substantial | Reuse existing canon, extraction, exception review and Story Point | +| General paragraph-to-entity reference index | Partial/narrow | Knowledge/Relationship evidence exists; broad typed entity/reference occurrence links do not | +| Context/Intent shared intelligence | Substantial | Already server/domain based; only position selection adapter is Word-specific | +| Authoritative editor and migration fence | Missing | Sync mode does not prohibit every Word write path | +| Genuine offline books and edit journal | Missing | Current PWA worker explicitly has no offline fetch/cache/sync | +| Portable backup | Useful existing foundation | Project backup/recovery supports paragraphs and GUID remapping; not yet a purpose-built offline manuscript/media package | +| Format-independent publishing content | Partial | Plain text/headings usable; semantic marks/media and publishing profiles/renderers missing | + +## 9. Context and Intent: preserve and reuse now + +### 9.1 Current integration + +The native agent opens `/native-companion/workspace` with book, instance/session and requested view. It redirects to established `/Writing/Context` or `/Writing/Intent` browser/PWA pages. `WritingController.NativeTarget` verifies the user/book/session, saved state and, for chapter-capable sessions, accepted chapter-position evidence. It checks the target again after data loading. Missing/stale positions wait instead of silently selecting another scene. Native fragment requests carry the exact session; a mapping race returns 409. `writing-follow.js` cancels stale native requests and retains saved browsing with explicit status. + +This is a position-resolution adapter. It does not make Context dependent on reading Word text on demand or require a second synchronisation to open it. + +### 9.2 Data dependencies + +- `SceneService.GetWritingContextAsync` reads saved scene/workflow/participant/event records using an authorised read-only hydration path, avoiding the full scene editor's storage/statistics/choice loading and old per-entity state traversal. +- `StoryContextService` reuses request-scoped scene and Story Point tasks. `StoryPointContextService` batches existing histories and projects knowledge, relationships, state, unresolved threads and continuity through **canonical narrative order**, not simply through earlier calendar dates. +- `WritingContextRelevance` limits initial neighbouring scenes and ranks relevant threads. Other author-reference charts remain explorable and labelled. +- Saved Intent reads scene purpose/outcome, purpose types, chapter goals/emotional direction/reader takeaway/requirements, notes and checklist. Opening it does not replace saved author intentions with an analysis-derived plan. +- `IntentAssessmentService.Read` explicitly reads current saved `SceneManuscriptSources.SourceText`, not the scene summary. Explicit `Analyse` checks feature access, bounded input and a fingerprint over prose/objectives, validates quoted evidence, and stores results/author decisions in `WritingIntentAssessments(UserID, SceneID, InputHash, ResultsJson, DecisionsJson, Model, CreatedUtc)`. Stale evidence cannot simply be treated as current. + +### 9.3 Eventual identical use from Writer + +A Writer selection already knows book/chapter/scene/paragraph GUID. Supply that accepted position to the same writing workspaces/domain services. Keep the Word exact-session adapter for Companion; add a Writer selection adapter only when Writer exists. Context, author planning, chronology, continuity and assessment remain shared. + +Future read models should identify the accepted manuscript/projection revision so local dirty text is not presented as server-verified canon. Offline Writer can show locally saved plan/context snapshots with explicit age/revision; it cannot claim fresh server AI or newly verified story state while disconnected. Reconnection can refresh the same services. None of this is a reason to delay current Context/Intent Windows qualification. + +## 10. Proposed canonical manuscript model — recommendation, not implementation + +### 10.1 Ownership and authority + +Use the principle: **PlotDirector owns manuscript content, identities and story relationships; the editor owns interaction; publishing profiles/renderers own output presentation.** + +For Word-owned books during the current phase, Word remains the authoring environment and layout source; accepted PlotDirector snapshots/projections feed stored intelligence. That is different from claiming the current server can fully replace a DOCX. A future shared canonical model should make the accepted content revision authoritative without requiring it to reproduce Word presentation. + +| Information | Recommended authority | Other representation | +|---|---|---| +| Paragraph text, semantic style/marks, image placements and paragraph order | One canonical manuscript content revision | Editor buffers/local replicas are revisioned working copies; scene text is a projection | +| Book/chapter/scene identity and domain metadata | Existing Books/Chapters/Scenes and their governed manuscript associations | Preserve integer IDs and grouping GUID compatibility | +| Chapter heading text | Canonical heading paragraph when present | Chapter display title can be a projection/explicitly distinct planning label; current copies need a defined migration rule | +| Scene/chapter summaries, purpose and goals | Existing saved author/structural/analysis fields with provenance | Never replace these with concatenated prose or automatically rewrite them on a text save | +| Character/location/asset/thread identity and state | Existing canonical story tables and accepted event records | Occurrence index links to IDs; names are labels, not identity | +| Inferred associations and extraction evidence | Revisioned reference/candidate records with provenance and decision state | Raw AI results remain audit, not unreviewed canon | +| Word native IDs, physical ranges, session proof | Word adapter bindings/validation metadata | Never primary keys or intrinsic canonical order | +| Print layout, page furniture and output styling | Publishing profile/version | No page numbers/margins embedded in body text | + +### 10.2 Natural extension versus a new content structure + +**Do not add another independent `ChapterText` or `SceneText` editing master.** `BookParagraphManuscripts` already embodies the right occurrence concept. Extend that logical model and reuse existing GUIDs and scene mappings. + +For eventual frequent Writer/offline edits, a **normalised content structure behind a compatibility facade is justified**, rather than indefinitely expanding the current whole-book JSON blob. This is an evolution of the existing manuscript store, not a parallel manuscript system. There must be one write authority and a controlled cutover; do not maintain independent authoritative JSON and row text with casual dual writes. + +Reasons: existing payload size/serialization, no relational paragraph foreign keys, whole-book write/CAS contention, lack of operation history and tombstones, and the need for incremental offline reconciliation. JSON can remain a compatibility/recovery snapshot and serialization format. A smaller book could initially work with a versioned JSON schema, but that does not remove the durable history/reference requirements. No measured native editing workload exists yet to justify a database tuning claim or immediate migration. + +### 10.3 Logical structures needed + +Names below are **illustrative proposed structures**, not existing tables or migration instructions. Changes would use the repository’s Dapper/stored-procedure approach, with explicit transactional validation rather than introducing an ORM or inline application SQL. + +| Structure | Minimum meaning | +|---|---| +| Manuscript aggregate/version | Existing BookID + ManuscriptID; schema version, accepted content revision, editor authority epoch and head revision; keep existing sync mode separately | +| Paragraph content | Permanent ParagraphID, manuscript scope, complete text, semantic style, validated inline marks, created/last-changed revision, deleted/tombstone state | +| Paragraph placement | ParagraphID, independent order key, chapter association and optional scene association; uniqueness/order invariants. Dense ordinals are a read projection, not identity | +| Manuscript revision/operation journal | Immutable operation ID, base/accepted revision, actor/device/editor epoch, operation type/payload or reconstructable version data, provenance; periodic validated snapshots for recovery | +| Word binding sidecar | Manuscript/paragraph ID to external hint and exact-session physical validation; preserve current content/identity/mapping/position safeguards | +| Media/placement | Immutable asset ID/hash, actual bytes or durable object reference, media type/dimensions, paragraph/block placement, caption/alt text and inline/block semantic mode | +| Entity-reference/evidence index | Paragraph range/span and source revision → canonical entity/event ID; semantic role, confidence, provenance, decision/validity state. Preserve Knowledge/Relationship evidence IDs and primary/supporting semantics | + +Do not require a story scene for every content block: front/back matter, chapter headings and excluded import material exist already. Keep scene contiguity/chapter containment rules for story prose. Avoid independently maintained chapter and paragraph order that can disagree: placement must have a defined ordering rule and chapter membership validation. + +```mermaid +flowchart LR + Word[Existing Word adapter and reconciliation] --> API[Shared accepted manuscript transaction contract] + Writer[Future Writer explicit GUID operations] --> API + API --> Content[(One canonical content and placement store)] + API --> History[(Revision and operation history)] + Content --> Compat[Existing scene-text and paragraph compatibility projections] + Compat --> Intelligence[Existing intelligence / review / Context / Intent] + Content --> Refs[Revision-aware reference and evidence indexing] + Refs --> Canon[(Existing story entities and accepted events)] + Content --> Publish[Future publishing profiles and renderers] + Writer <--> Local[(Future offline replica and durable journal)] +``` + +### 10.4 Minimal semantic formatting + +Support exactly the initial semantics requested: **Normal**, **First Paragraph** and **Heading 1**. Normal and First Paragraph differ semantically in body indentation; the actual indent dimension belongs to editor/publishing styling. Preserve an explicit author choice rather than deriving it solely from current scene position. Heading 1 identifies a chapter heading and participates in structural validation. + +Use a small versioned mark model for bold/italic rather than arbitrary stored editor HTML or Word run properties. Define character-offset encoding, newline/paragraph terminator rules, Unicode handling and permitted overlaps. Current Word text includes paragraph/control characters and evidence offsets use .NET string positions; silently normalising them would invalidate fingerprints and anchors. A later conversion must map old offsets explicitly, preserving original evidence. + +Image placement needs semantic position and accessible description, not Word shape IDs or fixed page coordinates. Word-owned books need not send all Word formatting during ordinary synchronisation. A deliberate Word→Writer migration must extract supported styles/emphasis/media or explicitly disclose their loss. Missing formatting cannot be reconstructed from an existing plain-text snapshot. + +## 11. Minimum viable changes and migration implications + +### 11.1 What is essential versus optional + +There are two different milestones: + +**A. Current complete plain-text snapshot foundation:** already substantially implemented. A universal completeness claim still needs per-book validation of captured scope and source provenance. No blanket new text column is required. Do not backfill historical books by splitting summaries, analysis excerpts or normalised scene strings and pretending they are original paragraphs. + +**B. Safe shared editable canonical model:** before Writer edits live books, the following are essential: + +1. Formalise one versioned content/placement/identity contract, independent of Word offsets. Preserve existing paragraph GUIDs; add explicit move/copy/split/merge/delete semantics. +2. Add durable revision/operation history and tombstones with revision-checked, idempotent transactions. Current whole-book request/revision guards can inform this but are insufficient for offline edits and old retry receipts. +3. Add the minimum semantic styles/marks/media fields needed to preserve the supported manuscript. At least explicit completeness/unsupported-content metadata is needed before migration promises. +4. Establish editor authority/epoch checks on every content-writing route, including manual Word sync and import/recovery paths. A preference-only UI field is not enough. +5. Keep `SceneManuscriptSources` and existing story services as compatible projections; distinguish content revision from projection/analysis version. Verified last-accepted scene prose must not be silently replaced by ambiguous assignments. +6. Migrate current paragraph payloads transactionally into the chosen persistent form, with counts, IDs, text hashes, ordering, grouping, evidence and recovery invariants checked before cutover. Dapper/stored procedures and forward-only migrations remain the repository constraints. + +A general automatic reference index is essential to the eventual large-book Writer experience, but not a prerequisite for completing Companion or proving a plain-text content store. Image/emphasis support is essential before promising lossless migration of those features; it can be staged behind explicit supported-content boundaries. + +**Optional/later improvements:** richer semantic blocks, reference suggestions for complex event interpretation, advanced automatic conflict merges, per-paragraph concurrency for unrelated edits, elaborate multi-device collaboration, granular history UI and extra publishing variants. None is necessary to invent a two-way live Word/Writer system. + +### 11.2 Compatibility strategy + +- Keep existing stored procedure/repository contracts available to the Companion. Introduce a compatibility facade/projection rather than forcing a Windows upgrade for a future storage migration. +- Preserve paragraph GUIDs, manuscript GUID scope, canonical integer chapter/scene IDs, event IDs and evidence primary/supporting states. Do not mint new IDs just because storage changes. +- For older books without complete snapshots, use an explicitly approved complete Word capture/adapter import. Retained original source may help where complete; normalised scene text alone does not prove fidelity. Never silently overwrite existing prose/planning to create a “canonical” book. +- Preserve old source/audit records as provenance, not active competing masters. Existing Scene Intelligence should continue consuming accepted scene-source projections and persisted candidate generations. +- Unknown new payload fields can be lost by older typed deserialize/serialize writers. Version/capability-gate new formats; do not assume adding JSON fields is automatically backward safe. +- Extend existing backup/restore validation and ID remapping alongside any content schema. Existing format 1.5 and `ParagraphRecovery` are a strong basis, but do not currently include future semantic media/history. +- Preserve manuscript/event deletion protection, access/owner authority, active-import/analysis guards and explicit author decisions. Do not turn a migration into automatic AI reanalysis or candidate acceptance. + +## 12. Editor ownership and deliberate migration + +### 12.1 Book-level authority + +Record both an author-facing preference and an enforceable manuscript editing mode if/when Writer exists: `Word Companion` or `Native PlotDirector Writer`, plus an authority generation/epoch. Existing `Mode=Manual/OnSave/Off` is a **Word synchronisation preference**, not editing authority; Off still permits explicit author-requested snapshots. Reusing it as a lock would be unsafe. + +Server write validation should enforce current mode/epoch and base revision regardless of stale clients, old tokens or apparent session liveness. Normal domain planning edits can remain independent under existing permissions. Word presence/navigation may remain useful in read-only form, but an old Companion must not write manuscript content after Writer authority is established. + +### 12.2 Deliberate Word→Writer migration + +Recommendation, after foundations exist: + +1. Complete and explicitly accept a final supported-scope Word snapshot; resolve or preserve flagged boundaries/evidence visibly. Take an independent validated backup. Identify formatting/media not represented in existing paragraph state. +2. Capture supported semantic formatting and actual images through an explicit conversion step if required. Report unsupported Word features rather than imply a lossless DOCX conversion. +3. Freeze a specific accepted source revision and source-editor epoch. Preserve paragraph GUIDs/order, chapter/scene mappings, event references and existing available history/provenance. Historical revisions that were never recorded cannot be manufactured; the migration snapshot becomes an honest baseline. +4. Validate canonical content and derived scene projections, then atomically switch editor authority and increment its epoch. Stop **all** Word content mutations, not only automatic OnSave transfers. +5. Writer starts from that exact revision. Retain the original Word document as an independent source/backup, not an automatically synchronised second editable master. + +Offline devices holding an older epoch must be refused on reconnect. Preserve their journal for explicit recovery/export or a deliberate fork; do not replay it into the new authority. Rollback/migration back must be an explicit operation with the same safeguards. A continuously bidirectional Word/Writer live synchronisation system is unnecessary for the stated author workflow. + +## 13. Future offline requirements — no implementation proposed now + +The current service worker expressly implements **no fetch handler, Cache Storage, offline page or background synchronisation**. Browser/PWA presentation and the agent's disposable memory cache are not offline Writer support. Word already owns its own offline document; that does not give PlotDirector a local complete book. + +A future native browser editor needs: + +| Area | Requirement / risk | +|---|---| +| Complete local book | Download a revision-consistent manifest, structure, every paragraph and required media; verify hashes/counts before declaring Offline Ready. Lazy browser cache entries are insufficient | +| Local persistence | Transactional IndexedDB or an evaluated alternative for content, order, journal and acknowledgements; media as durable blobs/files with integrity metadata; separate local accepted base from pending edits | +| Permanent identities | Locally generated GUIDs within manuscript scope; movement keeps ID, copy creates a new ID; stable operation/device IDs and explicit split/merge lineage | +| Durable journal | Atomically persist the edit and its operation record before displaying a durable-save claim; recover interrupted batches on startup; never depend on closing/unload to save | +| Reconnect | Send idempotent operations with base revision and authority epoch, preserve acknowledgements durably, and retry safely after uncertain responses | +| Conflicts | Detect divergent content/order/structure and stale authority. Start with explicit conflict resolution or whole-book single-editor rejection; do not silently last-write-win. Same-editor multiple tabs/devices can still conflict | +| Crash recovery | Transaction boundaries, checkpoints, schema migration recovery, unacknowledged operation replay and interrupted media staging; test browser/OS termination and quota exhaustion | +| Authentication/privacy | Existing server membership/subscription checks still govern server operations; define offline access and account-switch behaviour without deleting unsynced work silently. Local manuscript storage needs an explicit privacy/security design | +| Independent backup | User-exportable versioned package containing content, placement, media, metadata and integrity manifest, recoverable without the original site/session. Export both accepted base and pending work or state clearly which is included | +| Portable import | Validate package version, paths/sizes/hashes, IDs, entity scope and references before acceptance. Preserve manuscript identities on migration; define deliberate copy/fork namespace semantics separately | + +IndexedDB supplies transactions and durability hints, but durability must be tested on target platforms; the storage standard distinguishes best-effort versus persistent storage and provides quota/persistence APIs. Neither is a substitute for an independent backup or protection against user deletion/device loss. See [IndexedDB specification](https://www.w3.org/TR/IndexedDB/) and [WHATWG Storage standard](https://storage.spec.whatwg.org/). + +Do not choose CRDTs, collaborative editing protocols or a new background service merely to satisfy single-editor offline writing. Start with durable local operations, base revisions, server idempotency and visible conflicts. Any later merge sophistication must earn its complexity. + +## 14. Publishing separation + +The proposed text/style/mark/media/structure contract can support the stated outputs without encoding Word layout. **The current snapshot alone cannot preserve all requested publishing semantics.** + +| Output | Content required | Presentation/output responsibility | +|---|---|---| +| KDP PDF interior | Ordered chapters/text, supported semantic styles, emphasis, actual images and captions | Profile/render engine chooses trim, margins/gutter, bleed, typography, fonts, running headers/footers and generated page numbers; validates retailer output requirements | +| IngramSpark PDF interior | Same canonical content; suitable media assets | Separate output profile/preflight; do not assume a PDF acceptable to one service is automatically qualified for another | +| Reflowable EPUB | Semantic headings/paragraphs/emphasis/images, reading order, navigation and book metadata | XHTML/CSS/package generation and validation; fixed print pagination/page furniture is not body content | +| Compatibility DOCX | Supported semantic styles/marks/media and chapter structure | Export adapter maps semantics to DOCX constructs. It does not round-trip unsupported original Word layout/features | + +KDP documents trim/bleed/margin and PDF preparation separately from manuscript text; EPUB defines content documents and resource packaging rather than a single fixed print layout. IngramSpark publishes its own file requirements. These support the separation, not a claim that a renderer already exists or that a three-style model handles every future book genre. Sources: [KDP file preparation](https://kdp.amazon.com/en_US/help/topic/G202145060), [KDP trim/bleed/margins](https://kdp.amazon.com/en_US/help/topic/GVBQ3CMEQW3W2VL6), [EPUB 3.3](https://www.w3.org/TR/epub-33/), [IngramSpark file guide resources](https://www.ingramspark.com/lp/author-resources). + +Running-header text rules, chapter-opening pagination, numbering schemes and output-specific image sizing belong to versioned publishing profiles. Actual captions, alternative text, intentional emphasis, reading order and meaningful section/chapter breaks belong to manuscript semantics. If future requirements include footnotes, tables, lists, poetry or deliberate line breaks, add explicit semantic support or declared limitations; do not hide them in a generic Word-formatting blob. + +## 15. Risk assessment + +| Risk | Evidence / impact | Recommended control | +|---|---|---| +| Calling normalised scene text original manuscript | Import trims/rejoins and excludes structural paragraphs | Explicit per-book completeness/scope; prefer accepted raw snapshot; retain original DOCX for unsupported content | +| Losing identity during a schema rewrite | GUIDs/evidence already carry meaning; integer scene IDs are consumed widely | Preserve IDs and validated mappings; compare hashes/counts/order/evidence before cutover | +| Treating cross-chapter movement as supported repair | `MergeChapter` explicitly rejects cross-boundary/native ownership conflicts | Keep current refusal; future native moves are explicit operations with independent placement | +| Duplicate text/name mistaken for identity | Existing reconciliation/alias policy deliberately rejects ambiguity | Keep canonical GUID/entity IDs; never hash- or name-only identity | +| Conflicting editors/offline devices | Sync mode is not a write fence; stale revisions only cover some cases | Book editor authority + epoch on all content write paths; explicit migration and conflict recovery | +| Whole-book payload performance | 234.8 MB aggregate payload census; whole-book JSON serialization/read/write | No per-keystroke use; measure realistic workloads later; compatible row/history model and bounded operations | +| Silent formatting/media loss | No canonical style/marks/media placement | Explicit supported-feature conversion report; retain original; no lossless migration claim | +| Incomplete history/deletion recovery | Single current snapshot; bounded layout undo and immediate previous text | Durable operations/tombstones/snapshots before offline/native editing | +| Evidence falsely considered current | Text/scene boundary changes invalidate passage assumptions | Retain existing Verified/Needs review/Missing semantics; revision-tag references and derived projections | +| Canon polluted by mention indexing | Mention does not mean presence, setting, learned fact or actual event | Typed references separate from canonical assertion policy; preserve review/author decisions | +| Backward typed JSON writer drops new fields | Current clients/services serialize fixed models | Schema/capability gates and compatibility facade; recovery format versioning | +| Stale derived scene text/analysis | Ambiguous mappings intentionally preserve last accepted scene source; AI results are revision-specific evidence | Explicit projection revision/state; never present dirty/unverified content as accepted canon | +| Backup mistaken for live sync/history | Format 1.5 preserves paragraph recovery but detaches live proof | Reuse backup validation; define journal/media package contract separately | +| Content mutation during active analysis/import | Current SQL/services protect active work | Preserve guards; schedule a separately authorised migration, no automatic reanalysis | +| Browser storage loss or partial offline book | Current PWA has no local book; browser storage has quota/persistence limits | Offline readiness checks, durable journal, failure tests and independent portable backup | + +## 16. Recommended sequence and immediate decisions + +### Phase 0 — finish the Companion; necessary now + +Complete real Word qualification of synchronisation, exact-session navigation, Context and Intent using the installed qualified Companion. Preserve accepted checkpoints and current read-only writing integration. Only repair demonstrated correctness/recovery defects with focused regressions. No manuscript schema redesign or Writer code is necessary for this milestone. + +Small possible improvements must first be scoped against a real issue: + +- **Not needed as a blanket fix:** “start persisting full paragraphs” and “add permanent GUIDs”; these already exist for tracked books. +- **Potentially low risk:** clarify capture completeness/scope and snapshot versus projection revision in existing diagnostics/documentation; add focused future regressions for accidental ID/text loss through already-supported import/sync/recovery paths. Even these should be scheduled, not silently implemented by this investigation. +- **Not small by assumption:** new relational paragraph tables, cross-chapter native moves, split/merge text history, formatting/media capture or a general reference index. They affect existing persistence, fingerprints, evidence, backups and compatibility. + +### Phase 1 — define and qualify the shared foundation; defer until Companion milestone + +Under a separate authorised task, specify authority, identity/lifecycle, revision versus validation semantics, supported content and per-book completeness. Establish fixtures for old/import-only books, duplicate paragraphs, cross-chapter moves, pictures and lossless raw-text recovery. Existing paragraph GUIDs and source interfaces are the starting point. Make the storage choice from measured workloads, not from a future-editor assumption. + +### Phase 2 — evolve storage safely; defer + +Add the minimum canonical content/placement/history/authority structures with forward-only stored-procedure migrations, compatibility adapters, atomic writes and recovery validation. Migrate only eligible books with verified snapshots; require approved recapture/conversion where provenance is insufficient. Maintain the DOCX/Word importer and existing `SceneManuscriptSources` consumer contract. Do not introduce a second intelligence stack. + +### Phase 3 — build Writer and genuine offline support; defer + +Create the editor interaction layer, explicit GUID operations, local complete-book replica/journal, conflict recovery and portable package using the shared server contracts. Add revision-aware automatic reference indexing and exception review, reusing existing recognition/canonical materialisation rules. Word→Writer migration remains deliberate and fenced. + +### Phase 4 — publishing profiles/renderers; defer + +Use accepted semantic content to generate/preflight PDF interiors, EPUB and compatibility DOCX. Keep output presentation/versioning separate from manuscript identity and story data. No publishing engine is a prerequisite to operational Companion Context/Intent. + +**Decision:** preserve the current investment. There is sufficient existing foundation to justify later evolution into a canonical manuscript engine, but no evidence that a large immediate architecture diversion is needed to make the Companion operational. Authorise foundational implementation only after its current milestone, with explicit compatibility and recovery acceptance criteria. + +## 17. Source reference index + +Paths are repository-relative; symbol locations describe the inspected baseline and can move with subsequent work. + +| Area | Actual source and principal symbols | +|---|---| +| Paragraph payload | [ParagraphManuscriptModels.cs](../../PlotLine/Models/ParagraphManuscriptModels.cs): `ParagraphManuscript`, `StoryParagraph`, `StoryEvidence`, `ParagraphLayout` | +| Shared identity | [ParagraphIdentity.cs](../../PlotDirector.NativeCompanion/Protocol/Manuscript/ParagraphIdentity.cs): `ParagraphOccurrence`, `WordParagraphIdentity`, `ParagraphReconciliation.Compare`, `Assemble`; [ParagraphDelta.cs](../../PlotDirector.NativeCompanion/Protocol/Manuscript/ParagraphDelta.cs) | +| Engine/group/evidence lifecycle | [ParagraphManuscriptEngine.cs](../../PlotLine/Services/Manuscript/ParagraphManuscriptEngine.cs): Bootstrap 8, Reconcile 26, chapter refinement 80, grouping/scene split/merge 114–145, evidence 147–181, Validate 182 | +| Service/repository persistence | [ParagraphManuscriptService.cs](../../PlotLine/Services/Manuscript/ParagraphManuscriptService.cs): Initialise, Snapshot, ReconcileChapter, Change, Save; [ParagraphManuscriptRepository.cs](../../PlotLine/Data/ParagraphManuscriptRepository.cs): Get/Save/SaveChapter/Position | +| Current SQL evolution | [240](../../PlotLine/Sql/240_ParagraphManuscripts.sql), [241](../../PlotLine/Sql/241_ParagraphRecovery.sql), [243](../../PlotLine/Sql/243_ParagraphChapterBoundaries.sql), [249](../../PlotLine/Sql/249_SelectiveChapterProjections.sql), [250](../../PlotLine/Sql/250_SelectiveChapterShiftedSourceBounds.sql): `dbo.ParagraphManuscript`, projections and recovery | +| Chapter reconciliation/validation | [ChapterCheckpointEngine.cs](../../PlotLine/Services/Manuscript/ChapterCheckpointEngine.cs): Build, Validate, MergeChapter 77; [ChapterSyncService.cs](../../PlotLine/Services/Manuscript/ChapterSyncService.cs); [ChapterSyncRepository.cs](../../PlotLine/Data/ChapterSyncRepository.cs); SQL [245](../../PlotLine/Sql/245_ChapterSynchronisation.sql), [246](../../PlotLine/Sql/246_ChapterReviewInvalidatesLivePositions.sql), [247](../../PlotLine/Sql/247_ChapterAdoptionSnapshotDigest.sql), [248](../../PlotLine/Sql/248_ChapterAcceptanceSetBasedAdoption.sql), [251](../../PlotLine/Sql/251_ChapterCheckpointReuse.sql), [252](../../PlotLine/Sql/252_ChapterReuseStrictPositionRows.sql) | +| Chapter protocol/shape positions | [ChapterFingerprint.cs](../../PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterFingerprint.cs), [ChapterWordPositions.cs](../../PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterWordPositions.cs), [ChapterRangeVerification.cs](../../PlotDirector.NativeCompanion/Protocol/Manuscript/ChapterRangeVerification.cs) | +| VSTO reader | [WordAdapter.cs](../../PlotDirector.NativeCompanion/Vsto/WordAdapter.cs): DocumentEnd 231, ReadFragment 459; [WordChapterRead.cs](../../PlotDirector.NativeCompanion/Vsto/WordChapterRead.cs): IsPlainChapter 150, chapter-range text read 257, native/XML fallbacks; [WordChapterPositions.cs](../../PlotDirector.NativeCompanion/Vsto/WordChapterPositions.cs) | +| Agent and value transport | [DocumentAnalysis.cs](../../PlotDirector.NativeCompanion/Agent/DocumentAnalysis.cs), [ParagraphSnapshotCache.cs](../../PlotDirector.NativeCompanion/Agent/ParagraphSnapshotCache.cs), [Messages.cs](../../PlotDirector.NativeCompanion/Protocol/Messages.cs): `ParagraphFragment`; [ManuscriptCapture.cs](../../PlotDirector.NativeCompanion/Protocol/ManuscriptCapture.cs) | +| Capture/preview retention | [NativeManuscriptCapture.cs](../../PlotLine/Services/NativeCompanion/NativeManuscriptCapture.cs): stream/preview assembly 183–206; [ManuscriptScanModels.cs](../../PlotLine/Models/ManuscriptScanModels.cs); [ManuscriptCaptureRepository.cs](../../PlotLine/Data/ManuscriptCaptureRepository.cs); SQL [237](../../PlotLine/Sql/237_DurableManuscriptCapture.sql), [239](../../PlotLine/Sql/239_ManuscriptAnalysisCheckpoints.sql) | +| Core import | [OnboardingService.cs](../../PlotLine/Services/OnboardingService.cs): BuildApprovedStructureAsync 310, InitialiseParagraphsAsync 472, analysis checkpoint lookup 531, chapter/scene source saves 1305/1339; [OnboardingBuildRepository.cs](../../PlotLine/Data/OnboardingBuildRepository.cs); [ManuscriptStructureAnalysisService.cs](../../PlotLine/Services/ManuscriptStructureAnalysisService.cs): BuildSourceText 327, fallback validation | +| Source schema/projections | SQL [149 structural source](../../PlotLine/Sql/149_Phase24_StructuralImportMarkerSync.sql), [150 scene source](../../PlotLine/Sql/150_Phase24B_SceneManuscriptSources.sql), [219 current scene import](../../PlotLine/Sql/219_WordManuscriptImportCurrentSceneModel.sql) | +| Approved review import | [NativeImportService.cs](../../PlotLine/Services/NativeCompanion/NativeImportService.cs): Preview/Commit; [NativeChapterMapping.cs](../../PlotLine/Services/NativeCompanion/NativeChapterMapping.cs); [NativeImportRepository.cs](../../PlotLine/Data/NativeImportRepository.cs); [232](../../PlotLine/Sql/232_NativeApprovedImport.sql) | +| Recognition/review | [CoreImportCharacterMappingService.cs](../../PlotLine/Services/CoreImportCharacterMappingService.cs): MapBookAsync/BuildMatchIndex; [CoreImportBasicLocationDetector.cs](../../PlotLine/Services/CoreImportBasicLocationDetector.cs); [StoryIntelligenceCharacterImportService.cs](../../PlotLine/Services/StoryIntelligenceCharacterImportService.cs): MatchPresence 844; [StoryIntelligenceLocationImportService.cs](../../PlotLine/Services/StoryIntelligenceLocationImportService.cs): LinkSceneLocationsAsync 1170; [StoryIntelligenceReviewPolicy.cs](../../PlotLine/Services/StoryIntelligenceReviewPolicy.cs) | +| Semantic extraction | [SceneIntelligenceModels.cs](../../PlotLine/Models/SceneIntelligenceModels.cs): character 92, location 135, relationships 164, knowledge 183, temporal 197–225; [Scene Prompt V2](../../PlotLine/Docs/AI/Scene-Prompt-V2.md): character presence/mentions, contextual setting, knowledge evidence; [StoryIntelligenceImportCommitService.cs](../../PlotLine/Services/StoryIntelligenceImportCommitService.cs) | +| Context/Intent | [WritingController.cs](../../PlotLine/Controllers/WritingController.cs): NativeTarget 183, BuildDisplayAsync 200, BuildIntentDisplayAsync 238; [NativeWorkspaceController.cs](../../PlotLine/Controllers/NativeWorkspaceController.cs); [CoreServices.cs](../../PlotLine/Services/CoreServices.cs): GetWritingContextAsync 1958, PopulateWritingDataAsync 2119, StoryContextService 2498; [StoryPointContextService.cs](../../PlotLine/Services/StoryPointContextService.cs): GetAsync 29, Compose 60; [WritingContextRelevance.cs](../../PlotLine/Services/WritingContextRelevance.cs); [IntentAssessmentService.cs](../../PlotLine/Services/IntentAssessmentService.cs): Read 19, Analyse 29; `PlotLine/wwwroot/js/writing-follow.js` (historical source: `git show ec5cf67:PlotLine/wwwroot/js/writing-follow.js`); [Writing views](../../PlotLine/Views/Writing) | +| Backup and portability | [ProjectBackupRepository.cs](../../PlotLine/Data/ProjectBackupRepository.cs): recovery/format selection 308–309; [ProjectExportService.cs](../../PlotLine/Services/ProjectExportService.cs); [ParagraphRecovery.cs](../../PlotLine/Services/Manuscript/ParagraphRecovery.cs): Validate, Remap 31, Detach 52; [ImportServices.cs](../../PlotLine/Services/ImportServices.cs): backup validation/remapping | +| Offline baseline | [service-worker.js](../../PlotLine/wwwroot/service-worker.js): explicit absence of offline fetch/cache/background sync | +| Existing focused test evidence, not rerun | [WritingIntegrationTests.cs](../../PlotLine.Tests/WritingIntegrationTests.cs), [StoryPointTests.cs](../../PlotLine.Tests/StoryPointTests.cs), [WritingContextNavigationTests.cs](../../PlotLine.Tests/WritingContextNavigationTests.cs); paragraph/chapter protocol and recovery tests under [native tests](../../PlotDirector.NativeCompanion/Tests) and [application tests](../../PlotLine.Tests) | + +### Remaining evidence required before a future implementation decision + +- A supported-feature DOCX fidelity inventory on representative real manuscripts, including images, tables, fields, footnotes and tracked changes; no such fidelity proof was produced here. +- Per-book initial-capture completeness and original-DOCX comparison where a lossless migration is promised. Aggregate database counts cannot prove that. +- Focused lifecycle qualification for cross-chapter moves, copy/split/merge lineage and backward-compatible payload round trips; current chapter repair intentionally declines some of these cases. +- Actual native editing/offline performance, storage durability and crash/quota recovery on target devices; prior browser projection timings are not these measurements. +- A separate authorised migration rehearsal/backup restore round trip before any schema/content conversion. No migration or restore test was run against Development during this investigation. diff --git a/Docs/Writer/Unified-Context-Workspace-Audit-20261121.md b/Docs/Writer/Unified-Context-Workspace-Audit-20261121.md new file mode 100644 index 00000000..72715a0f --- /dev/null +++ b/Docs/Writer/Unified-Context-Workspace-Audit-20261121.md @@ -0,0 +1,335 @@ +# Unified Context Workspace — Phase 1 audit + +Date: 21 November 2026. Source baseline: `3af856a` plus the existing working tree. + +> **Historical audit — retained on 29 November 2026.** Findings describe the dated +> source inspection above, including its stated working-tree scope, not current +> implementation or deployment status. Repository reconciliation checked document +> integrity and baseline availability; it did not rerun the original feature audit, +> browser checks or physical Word acceptance. Open design decisions remain proposals, +> not authority to implement them. + +## 1. Executive summary + +**Verified:** Context and Intent are two authenticated MVC reference windows, already sharing a configurable JavaScript follow controller, Razor card layouts, scene navigation and workspace presence. Context has eight tabs; Intent has six. Most content is saved canonical author data. Intent additionally supports explicit saved-prose AI assessment and persisted evidence decisions. Retiring its window must preserve all six feature areas, especially the distinction between author checklist completion and AI evidence. + +The proposed unified workspace is a practical evolution, but is **not already implemented**. There is no generic two-pane host, per-pane tab selection, declarative refresh registry or persisted split layout. Current follow refresh replaces an entire scene fragment; three Context tools have separate lazy HTTP endpoints. Same-scene short-circuiting prevents reliable content refresh, including after reconnect. + +The most important integration obstacle is connection ownership: the embedded window normally starts both the Office/workspace hub connection and a separate native presence hub connection. Strictly one connection per new Context window requires a browser/server notification subscription change; it cannot be achieved merely by combining the existing views. Preserve the existing native/Office capture, batching, acceptance, revision and analysis mechanisms. + +The shared toast prerequisite is implemented in source, documented, and loaded by the application, embedded writing and Office shells. No replacement notification service is needed. + +**Recommended:** first migrate the existing reference tools into an instance-safe tab host; retain explicit AI assessment and existing full editors; add splitting and persistence; then qualify refresh/reconnect behavior using accepted saved-data changes. Do not add paragraph tools, a new analysis pipeline or automatic objective completion as incidental migration work. + +### Audit method and limits + +This was source inspection only. No application code, SQL, schema, migration, Word component, service or deployment was changed. No database was opened, no live manuscript was inspected, and no build or regression suite was run. Repository documentation is corroborating evidence, not proof of currently deployed behavior or physical Word acceptance. Runtime layout/latency findings below are source-derived risks, not measured failures. The requested report is the only new task artifact; the pre-existing untracked `Docs/Investigations/CanonicalManuscriptArchitectureAssessment.md` was preserved and not used as authority. + +Paths below are repository-relative. Line references identify the audited revision and may move. `Docs/Writer` already contains dated Writer investigations, so the requested destination follows actual conventions. + +## 2. Current Context architecture + +### Routes and rendering + +`PlotLine/Controllers/WritingController.cs:15–25` defines `[Authorize]`, route prefix `/Writing` and no-store responses. + +| Route / action | Current purpose | +| --- | --- | +| GET `/Writing/Context` — `Context`, line 25 | Full Context page; accepts project/book/chapter/scene, document GUID, pinned/embedded and native instance/session identifiers. | +| GET `/Writing/Context/Scene` — `ContextScene`, line 140 | Returns `_WritingContextContent`; waiting/missing states are fragments too. Native requests validate current target mapping. | +| GET `/Writing/Context/Map` — `ContextMap`, line 307 | Authorized map selection, saved document and story projection for the scene. | +| GET `/Writing/Context/PlotLines` — `ContextPlotLines`, line 325 | Authorized book plot workspace data transformed for reference cards. | +| GET `/Writing/Context/Metrics` — `ContextMetrics`, line 333 | Timeline structure plus recorded scene metrics, transformed for graphs. | +| POST `/Writing/Context/Navigate` — line 350 | Explicit native Word navigation, with antiforgery and current saved mapping/session/revision checks. Not a generic position broadcast. | + +`Views/Writing/Context.cshtml` chooses ordinary `_Layout` or `_WritingCompanionLayout` for embedded mode. Its root owns scope, native document identifiers, follow mode, status and a replaceable content section. `_WritingContextContent.cshtml` contains the scene header, selectors, tab buttons and all ordinary tab panels; Maps, Plot Lines and Metrics start as lazy placeholders. Ordinary tabs are rendered together even while hidden. + +`BuildDisplayAsync` (`WritingController.cs:221`) calls `IStoryContextService.GetForSceneAsync(...forWriting:true)`, obtains narrative/Story Point data, relationships, optional floor-plan editor data and scene options. Relationship snapshots are reused when available; otherwise `IRelationshipMapService` supplies them. Floor plans are checked against project ownership. This is reusable domain composition, but it currently prepares several tools in one request rather than allowing every tab endpoint to retrieve only its own data. + +### Browser components and management + +- `wwwroot/js/writing-context.js:1` supplies selectors/defaults to `PlotDirectorWritingFollow.initialize`; `writing-intent.js` does the same for Intent. +- `writing-follow.js:32` selects one root with `document.querySelector`. It owns tabs, navigation, status, fragment fetching, cancellation, view restoration and native/Office follow arbitration. +- `writing-context-components.js` mounts one Context root, lazily loads visible components, validates fragment responses, rejects detached/changed-URL results, offers retry and restores view state. +- `writing-context-map.js` and `maps-engine.js` supply SVG map behavior; `writing-context-plots.js` supplies plot exploration. `writing-context-plots.css` and `site.css` supply presentation; shell/theme/Bootstrap styles are dependencies too. +- `writing-workspace.js` manages role registration, window references, monitor preferences, popup sizing and focus. `stableWindowName` returns `PlotDirectorContext` or `PlotDirectorIntent` independent of scope. `startWorkspace` tries to open/focus both roles, not multiple generic Context instances. Popup blocking and browser focus restrictions are explicitly tolerated. +- `writing-workspace-launcher.js`, `native-companion-workspace.js` and Office `word-companion-host.js:1403` are launch integration points. The native launcher opens the existing writing routes directly and supplies selected document identifiers. + +### Current context levels + +| Level | What actually exists | +| --- | --- | +| Book/project | Scope and access boundaries, manuscript-wide scene options, book plot/metric datasets, project maps and established history. These are not a standalone book overview tab. | +| Chapter | Header/navigation identity and chapter-derived context; Intent can render chapter-only planning. Context itself requires a scene to render its normal tools. | +| Scene | Primary reference unit: summary, purpose/outcome, people, relationships, time/place, established knowledge, threads, dependencies, assets, warnings and floor/map position. | +| Paragraph | No paragraph-specific Context/Intent panel or paragraph scope in `story-position.js`. Native infrastructure has cursor/paragraph mapping and accepted paragraph revisions, but current writing views reduce those to chapter/scene. | + +Manual scene selection and previous/next buttons load saved data; trusted explicit scene selection can also POST native navigation. Programmatic follow does not automatically send a navigation command. Pinned snapshots disable automatic follow and role registration, preserving a saved-data browsing distinction. Native live following requires a suitable selected/unique document, saved Word state and verified mapping; ambiguous/unavailable mapping leaves saved content usable with persistent explanatory status. + +## 3. Current Intent architecture + +GET `/Writing/Intent` (`WritingController.cs:82`) and GET `/Writing/Intent/Scene` (`:164`) mirror Context page/fragment behavior, with chapter-only support. `BuildIntentDisplayAsync` (`:259`) obtains scene context without narrative history and `IWriterWorkspaceService.GetChapterWorkflowAsync`. It validates project/book scope and access before returning `WritingIntentDisplayViewModel`. + +`Views/Writing/Intent.cshtml` loads workspace/follow scripts plus `intent-assessment.js`; `_WritingIntentContent.cshtml` owns six panels. There is no separate inline chapter/scene plan editor in these panels. Links open the existing Scene or Writer Chapter editing workflows. The chapter selector currently renders only the current chapter option; it is not a complete book chapter chooser. Scene options exist for the scene/chapter context. + +### Completion, edits and saving + +- Plan, Must Include, Notes, Threads and Checklist display saved author data. Opening them does not save, generate intent or tick objectives. +- Checklist progress derives from persisted `SceneChecklistItem.IsCompleted`. `ScenesController.SaveChecklistItem` (`:1387`) and the existing scene edit POST persist author changes through `IWriterWorkspaceService`; `WriterController.SaveChapterGoal` (`:484`) persists chapter goals. +- `IntentAssessmentController` is independently authorized at `/Writing/Intent/Assessment`: GET `Read` retrieves saved evidence; POST `Analyse` explicitly invokes AI; POST `/decision` saves acknowledged/dismissed/deferred/pending decisions with antiforgery. Decisions reject changed input hashes with HTTP 409. +- `IntentAssessmentService.Read/Analyse/Validate` fingerprints saved prose plus objectives, reuses matching assessments, bounds input/output, verifies supporting quotations and rechecks the fingerprint after AI returns. Subscription checks, striped in-process locks and a three-minute timeout apply. Assessment reads saved manuscript source text, not unsaved Word text. +- Evidence statuses are achieved, partial, not-evidenced, contradicted and cannot-assess. These do **not** set checklist completion. “Keep evidence” is acknowledgment, not completion. +- `intent-assessment.js` uses panel-keyed pending requests, disables action buttons, supports cancel and aborts detached panels. Inline status/recovery messages remain important. Browser cancellation does not prove a server save was rolled back; the next read must recover authoritative evidence. + +No separate beats editor or automatically evaluated beat-completion system was found in the audited Intent implementation. Do not rename checklist rows “beats” and imply a richer existing model. + +## 4. Complete existing window feature inventory + +All partial names in this section live in `PlotLine/Views/Writing/`. + +| Existing feature | Behavior and implementation | Reuse assessment | +| --- | --- | --- | +| Context Overview | `_WritingContextOverview`: scene summary, POV, date/time or relative time, location, revision status, purpose types/notes, outcome, canonical/age/Story Point warnings; earlier established scenes near saved story date, people/thread/place summaries, tool links, viewpoint knowledge and relevant thread provenance. | Preserve; extract tab endpoint and retain source links/limits. | +| People | `_WritingContextPeople`: saved participants, role/presence, location and last recorded location, emotional/physical state, outfit, entry/exit movement and knowledge/source records. | Reuse presentation and canonical interpretation; isolate instance. | +| Relationships | `_WritingContextRelationships`: scene relationship events plus established relationships involving participants (first 12), state/category/intensity. Explicitly author reference, not proof of viewpoint knowledge. | Preserve distinctions and bounded list. | +| Maps | `_WritingContextMap`, `ContextMap`: map chooser; scene/people/plot/all-place lenses; fit, focus, zoom and pan; feature inspection, saved story position and full Maps link; explicit unmapped state. | Existing independent endpoint; adapt lifecycle/size. | +| Floor Plans | `_WritingContextPlace`: selected floor, saved plan blocks and room/participant reference, current-room emphasis, zoom and scroll. | Reuse; separate endpoint and pane-sized viewport. | +| Story | `_WritingContextStory`: scene thread events, verified viewpoint knowledge, author dependency references (may mention future plans), asset events/custody and continuity/age warnings. | Preserve every subsection, whether kept together or split later. | +| Plot Lines | `_WritingContextPlotLines`, `WritingContextPlotLines`, `writing-context-plots.js`: saved developments in manuscript order; Active here/Nearby/Elsewhere, show-all, scene strip/scrubber/steps, return to current and explicit go-to-scene. | Existing independent endpoint; preserve exploration independently per pane. | +| Metrics | `_WritingContextMetrics`, `WritingContextMetrics`: recorded metric selector, scale-aware graph and missing-value display, scene exploration/cards, current marker, return/go-to-scene. | Existing independent book-data endpoint; marker also needs scene sensitivity. | +| Intent Plan | `_WritingIntentPlan`: chapter summary/purpose/goal, scene summary/purpose selections/notes, expected outcome, chapter emotional goal and reader takeaway. | Reuse; chapter and scene views may share subpartials. | +| Must Include | `_WritingIntentMustInclude`: chapter requirements, scene checklist Done/Planned, goal and reader reminders. | Preserve alongside planning/objectives; avoid losing chapter requirements in consolidation. | +| Notes | `_WritingIntentNotes`: chapter risks/concerns and scene notes, ordered by pinned/resolved/updated status with labels and body. | Reuse as reference; editing stays in existing editor initially. | +| Threads | `_WritingIntentThreads`: scene plot/thread events and titles/descriptions. | Overlaps Context Story; consolidate while retaining descriptions and labels. | +| Evidence | `_WritingIntentContent`, `_IntentAssessment`: read/explicit AI assess/cancel, saved timestamp and stale state, verified excerpts, per-objective evidence and author decisions, edit link. | Preserve as a separate explicit-action tool. No automatic reassessment on refresh. | +| Checklist | `_WritingIntentChecklist`: saved objective progress and rows; revision status, priority, estimate/actual words, blocked reason; explanation of author authority. | Preserve workflow fields as well as objectives; initially reference-only. | +| Shared commands | Scene selectors, Context previous/next across chapters, Scene/Chapter editor links, scoped saved snapshots, full calendar/maps/plot/relationship workspace links, persistent follow state and missing-content explanations. | Move common navigation/status into shell; retain explicit versus passive navigation semantics. | + +Duplication exists in purpose/outcome, scene summaries, thread events, checklist rows and several overview snippets. Consolidate display composition, not underlying author records. The two Intent checklist presentations serve different reminder/workflow purposes; migration must retain their information even if tab count is reduced. + +## 5. Word Companion, synchronisation and SignalR + +### Office.js path + +`PlotDirector.WordCompanion/` contains manifest/config/render tooling; the actual hosted taskpane behavior is in `PlotLine/Views/WordCompanionHost/Index.cshtml` and `wwwroot/js/word-companion-host.js`. + +The Office script detects document/chapter/scene anchors and resolves saved IDs. `word-companion-host.js:4298` posts `/api/word-companion/runtime/current-scene`. `WordCompanionController.UpdateRuntimeCurrentScene` (`:128`) validates via `IWordCompanionService`, updates presence and broadcasts `storyPositionChanged` to the authenticated user with project/book/chapter/scene, canonical URL and position. This payload does not provide a durable paragraph identifier or ordered content-change version. + +Existing scheduling must be retained: the Office runtime waits 1,200 ms after activity (`:237`, `:6119–6230`), tracks a runtime generation/snapshot freshness, coalesces another pass while a refresh is running, and schedules scene progress/word-count synchronization after 4,000 ms (`:5474`). In-flight/pending guards and separate character-suggestion scheduling already exist. Presence heartbeat is 25 seconds. Import scanning chunks are 128 KiB. These are different responsibilities, not one universal typing debounce. + +The API also exposes structure/scene synchronization, links, word-count updates, manuscript linking/import and explicit analysis (`WordCompanionController.cs`). `WordCompanionService` validates associations and delegates persisted work to repositories. Do not treat automatic scene progress/word-count sync as proof that all Word prose was accepted or all intelligence was updated. + +### Native Windows path + +The current repository also contains `PlotDirector.NativeCompanion`, so an Office-only audit would miss the supported native integration. + +`Agent/TrayCoordinator.cs` publishes book/manuscript, instance/session, monotonic sequence, Word revision, cursor offset, saved state, active state and capabilities. `PlotLine/Controllers/NativePresenceController.cs:16–49` receives authenticated presence, resolves paragraph/chapter/scene mappings using accepted data and current session/revision, and emits lightweight `NativePresenceChanged` hints. Native navigation is delivered through the existing command machinery; observation itself does not request navigation. + +`NativePresenceStore.Put` rejects non-increasing sequences and backward revisions for an existing lease. Leases expire after 45 seconds; this is ephemeral liveness, not durable manuscript association. Different document sessions remain independent. Server restart loses those leases; current agent observations restore them. + +`NativeManuscriptCapture.ResolveParagraphPosition` (`:41`) uses the existing paragraph repository. `ObserveParagraphSave` (`:70`) gates legacy paragraph-capable, non-chapter sync checks with a 15-second per-document limit. Snapshot acceptance validates requests and serializes acceptance. Chapter-capable clients use `NativeChapterSyncController` at `/api/native-companion/books/{book}/chapter-sync` (manifest GET, validate/reuse/repair/finish POSTs) and `Services/Manuscript/ChapterSyncService` for revision/identity/hash verification, checkpoints and existing reconciliation. + +`TrayCoordinator.Chapters.cs` maintains current-work identity/revision checks, dirty chapters, timeout/retry state and accepted checkpoints. It batches reuse proofs with bounds of 64 chapters / 20,000 paragraphs and polls finished chapter validation at 60 seconds when applicable. It sends changed chapter text through existing reconciliation when authorized; it does not require a new Context analysis mechanism. These intervals are existing transport/checking policy, not instructions for new UI timers. + +### Connections, handlers and recovery + +| Owner | Connection/events and recovery | +| --- | --- | +| `writing-workspace.js:213–300` | One module-level `/hubs/word-companion-follow` connection; `storyPositionChanged`, `WritingWorkspacePresenceChanged`, `WordCompanionPresenceChanged`, `WritingWorkspaceFocusRequested`. Automatic reconnect; re-registers and re-watches to recover position. Failed initial start clears its promise for a later command retry. Registration heartbeat every 15 seconds. | +| `WordCompanionFollowHub` | `WatchWritingWorkspace`, `RegisterWritingWindow`, heartbeat and focus methods; authenticated user presence group; current status derives from Office presence or suitable native presence. Routes mapped in `Program.cs:432–435`. | +| `native-companion-status.js:58–69` | Separate `/hubs/native-companion` connection; `NativePresenceChanged` is coalesced for 250 ms, then HTTP `/native-companion/status` and connection state supply authority. Serialized update/pending-again guards, 15-second recovery polling, visibility/pageshow handling and reconnect refresh. Dispatches `native-companion-presence` and Writer state events. | +| `NativeCompanionPresenceHub` | Authenticated invalidation only, server-chosen user group. No Word command or navigation methods. | +| `writing-follow.js:351–439` | Consumes native browser events or Office story-position events; selected/native live documents take precedence. Normal route reuses `watchWorkspace`; direct SignalR fallback exists if workspace module is absent. Snapshot mode does not start this follow subscription. | + +The embedded layout loads native status plus page workspace scripts. Thus a normal live embedded Context or Intent window can have **two** relevant SignalR connections, despite the workspace module itself being a singleton. The native agent's command connection is separate again and must not be confused with the new browser-window connection budget. Existing snapshots still load shell status facilities even though their content follow is disabled. + +### Ordering and freshness limits + +- HTTP fragment requests can finish out of order. `writing-follow.js` already uses AbortController plus `requestGeneration`; both are necessary because abort alone is insufficient. It validates a single expected fragment and rejects redirects/full-page HTML, avoiding shell/login injection. +- Lazy components check connectivity and requested URL before replacement; map/plot instances have host-oriented state. Extend this with pane/tab generations, particularly same-URL forced refresh races. +- Native sequence/revision checks protect accepted presence, and serialized browser status fetches avoid parallel status replacements. These do not create one total ordering across Office events, native hints, accepted prose, canonical edits and AI evidence. +- `story-position.js` normalizes project/book/chapter/scene and URL only. It does not retain paragraph, revision or event ordering metadata. +- `loadPosition` skips the current/loading scene (or same chapter-only target). Native revision changes can trigger a call which still returns immediately for the same scene. Reconnect therefore recovers location more reliably than content freshness. +- Plot and metric hosts are retained by book key during scene replacement; maps are invalidated when their URL changes. This preserves interaction well but can leave book-data panels stale until explicit refresh. There is no generic saved-content invalidation policy in the current writing controller. + +**Recommendation:** normalize existing notifications into position versus saved-data invalidation in the browser integration layer; read authoritative accepted state over HTTP. Define saved-content/canonical-edit invalidation coverage before promising live updates. If existing accepted-data events lack scope/version, add a lightweight announcement at the existing acceptance/write boundary in a later phase, without another capture, debounce or analysis pipeline. Event arrival is a hint to re-read, never proof of successful chapter acceptance or new canonical intelligence. + +## 6. Reusable components and data access + +| Component | Reuse and boundary | +| --- | --- | +| `IStoryContextService` / `StoryContextService`, `Services/CoreServices.cs:2498` | Authorized scene composition; request-scoped memoization, scope validation and optional narrative loading. Keep authorization in every endpoint. | +| `ISceneService.GetWritingContextAsync`, `CoreServices.cs:1958` | Existing saved scene reference model; writing mode avoids editor-only text statistics. Do not duplicate scene interpretation in JavaScript. | +| `StoryPointContextService`, `Data/StoryPointRepository.cs:27` | Established narrative snapshots/provenance through `dbo.StoryPoint_GetHistory`; preserve distinction between author reference and viewpoint knowledge. | +| `IWriterWorkspaceService`, `WriterWorkspaceService:6140` | Chapter workflow/goals, notes, checklist and workflow data; existing editor save semantics. | +| `WriterWorkspaceRepository`, `Data/Repositories.cs:1210–1341` | Dapper stored procedures including `SceneWorkflow_Get/Save`, `SceneNote_ListByScene/Save`, `SceneChecklist_ListByScene/Save`, `ChapterGoal_Get/Save`, `ChapterWorkflow_Summary`. No schema replacement needed for basic hosting. | +| Map/relationship/floor/plot/timeline repositories and services | Current authoritative reference queries and projections; use existing access checks rather than passing trusted-looking IDs through blindly. | +| `WritingContextMetrics`, `WritingContextPlotLines`, `WritingContextRelevance` | Server transformations, recorded-value semantics, nearby/established relevance and scene options. | +| `IntentAssessmentService` / `IntentAssessmentRepository` | Existing explicit assessment, fingerprint validation and stored decisions via `dbo.WritingIntentAssessment`. Reuse, do not create a second AI assessor. | +| `PlotDirectorWritingFollow.fragmentFromHtml`, generation guards, view-state events | Useful mechanisms to extract into generic host lifecycle; existing initializer cannot simply be run twice. | +| Toast/theme/connection detail shells | Keep once per window, outside partial replacement. Preserve substantial inline states. | + +Story Intelligence contracts in `docs/story-intelligence/single-system-runtime.md` and `Docs/StoryIntelligence_ExceptionReview.md` remain authoritative: saved scene sources/canonical records and persisted candidates are distinct; normal reads must not silently regenerate review candidates from raw analysis JSON. A new tab GET must remain a read and never launch analysis/materialization as a side effect. + +## 7. Refresh-policy design recommendations + +### Assessment against the agreed architecture + +| Agreed requirement | Existing equivalent / required change | +| --- | --- | +| One connection per independent window | Singleton workspace connection exists, but native shell adds another. Consolidate browser subscriptions via one authenticated server event surface while retaining existing sync producers. | +| One JavaScript window controller | Shared configurable follow module exists, but assumes one legacy root and one content fragment. Introduce window controller plus pane/tab instance records. | +| Declarative endpoint and policy per tab | Only page-level follow configuration and three lazy component URLs exist. Add a small registry. | +| Refresh only visible tabs | Lazy tools approximate this; ordinary hidden tabs are rebuilt with the scene fragment. Separate their endpoints. | +| Lightweight notices, normal HTTP partials | Native invalidation/status and current fragment GETs already demonstrate the pattern. Preserve it. | +| Inactive tabs refresh on selection | Lazy initial load exists; a generic stale flag/version is missing. | +| Tabs own business queries/interpretation | Services and individual Map/Plot/Metrics actions are reusable; main scene builders bundle multiple tabs. Extract authorized tab actions, not client business branches. | +| Reconnect restores position and stale panels | Position watch/status recovery exists; force visible saved-data revalidation even if scene ID is unchanged. | +| Stale responses cannot overwrite newer ones | Whole-fragment generations/cancellation exist. Apply independently to each pane/tab/context/selection generation. | + +### Suggested registration contract (design only) + +```text +id, displayName, endpoint +scope: none | book | chapter | scene | paragraph +contentRefresh: none | relevant-scope +editing: read-only | defer-while-dirty +``` + +The endpoint is an ordinary authenticated partial GET. Scope determines which navigation identity fields form its cache key; hierarchy includes project/book changes above the declared scope. `relevant-scope` responds to accepted saved-data invalidations intersecting that scope; it must not mean every keystroke. Treat unknown invalidation scope conservatively as current-book stale, not as a reason to analyse. + +Generic per-instance runtime state: latest context key, dirty/loading flag, stale generation, rendered generation, abort controller and scroll/view state. Hooks such as mount/dispose/canRefresh allow map sizing or explicit assessment without parent feature-name branches. A tab may expose local position handling for a current-scene marker over a retained book dataset; alternatively declare Scene scope and use server-side caching later if measured need justifies it. Choose one consistent contract before implementation. + +On navigation/invalidation: update authoritative context, mark affected instances stale, load visible clean instances, and leave hidden instances stale. On selection: fetch if missing/stale. On reconnect: recover the chosen document's accepted position and mark visible content stale regardless of equal scene IDs. On completion: install only if pane identity, tab identity, context key and generation all still match. Use no-store behavior and handle sign-in/access loss without installing a full HTML page. Keep old content and retry affordance on transient failure, visibly labelled with its original scope. + +A Razor partial renders data; its endpoint/service performs authoritative retrieval. “Each partial retrieves its own data” should mean this MVC ownership, not SQL inside Razor. The parent controller handles layout/refresh only. Explicit Evidence POSTs remain feature-owned user actions; selecting or refreshing that tab may read evidence but must not invoke AI. + +## 8. Split-pane and responsive-layout findings + +**Verified source constraints:** + +- `site.css:67–71` starts scene actions at an 18rem minimum. Overview uses a 20rem side column (`:114`), Place an 18rem column (`:118`); facts reserve 7rem labels. Cards spanning two columns need resetting in narrow panes. +- Later `site.css:7706` rules reduce grids at **viewport** width 900px; plot cards use viewport breakpoints at 1100/700px (`writing-context-plots.css`). A wide browser with two narrow panes bypasses those intended mobile adaptations. +- `site.css:7729–7736` contains deliberately wide, locally scrollable story charts (160px label gutter plus scene widths), floor grids and maps with `clamp(18rem,55dvh,50rem)` height. Floor scrolling uses 65dvh. These are usable reference tools but viewport sizing is unsuitable for a short stacked pane. +- Page/empty layouts use viewport minimum heights; embedded page sets `min-height:100vh`. Reusing these inside panes would create excess scrolling. Tabs are sticky with z-index 3 and must stick within their pane. +- `writing-follow.js`, component initialization and several component helpers query the first legacy root. Whole-fragment tab activation hides all panels below that root. One root hosting two legacy fragments would couple both panes. +- IDs `writing-context-scene-select`, `writing-intent-scene-select`, `writing-intent-chapter-select` and `intent-progress` repeat if the corresponding feature is instantiated twice. Labels/ARIA references must use instance-prefixed IDs. State keys such as `context-metric`, `metric-scroll` and `context-map-lens` also need pane/tab identity. +- Evidence's delegated document listener is panel-oriented and its pending map supports different panels, but loading the script repeatedly would duplicate listeners/observers. Map mounting uses host-keyed state; retain that approach and add disposal/resize handling. +- Current Context cards mainly use text, lists and definition lists rather than wide editable tables. Plot strips and graphs deliberately scroll horizontally; constrain that scroll to the component rather than the entire workspace. +- Connection details are a shell dialog (`_WritingConnectionDetails`) referenced by shell IDs. Current Context partials do not define a separate general modal system. Do not clone the shell dialog/toast host into panes. Help/popover behavior and focus restoration require later browser qualification when partials are removed during interaction. + +**Recommendation:** two fixed pane slots only, using grid/flex with `min-width:0; min-height:0`, independent `overflow:auto`, container-size rules and bounded component canvases. Switch card grids/toolbars by pane width, not window width; wrap selects/buttons, allow label/value stacking and retain chart-local horizontal scroll. Use container height or ResizeObserver for maps/floors. Support keyboard-operable divider, focus-visible controls and meaningful pane/tab labels. Clamp proportions to practical minimums and offer single-pane/stacked mode on laptop displays. Do not introduce a docking framework or silently discard a pane's selection on resize. + +## 9. State persistence and editing safety + +### Existing state + +`writing-follow.js` stores selected tab under origin-wide `plotdirector.writingContext.activeTab` / `plotdirector.writingIntent.activeTab`. These keys survive refresh/reopen but are shared between windows. In-memory `viewState` preserves marked control values/checks, scroll and SVG viewBox across fragment refreshes only. Window scroll/focus are restored opportunistically. Stable book panels retain actual DOM nodes. None constitutes persisted pane layout or per-window scroll restoration. + +`writing-workspace.js:25–45` already provides a sessionStorage browser-window UUID and detects cloned opener storage for named popups. Preferences under `plotdirector.writingWorkspace.preferences` retain display choices/last layout mode, not a split workspace. Native selected-document choice is held in the current controller/root, not a comprehensive durable workspace record. + +### Recommended state model + +Use a versioned, account-scoped workspace record keyed by an explicit independent workspace UUID. Store two pane slots with active tab, layout (single/split), orientation, clamped proportion and optional pane/tab scroll state. Reuse browser-window identity for a live instance, while distinguishing a durable saved workspace identity if reopening must restore the same arrangement. sessionStorage naturally survives same-tab navigation/refresh; localStorage keyed by workspace UUID can support explicit reopen. Never use one global active-tab key for every window. + +New-window launch must generate a fresh identity; “reopen this workspace” should reuse its explicit identity. Browser duplicated-tab/session cloning needs qualification as well as ordinary window.open cloning. Only shared defaults should propagate between windows; independent layout writes must not overwrite each other. Persist at layout/tab/scroll boundaries with modest throttling, not on manuscript typing. Handle blocked storage and schema upgrades safely. Persist UI identifiers only, not manuscript prose or form drafts by default. + +Preserve pinned versus live mode and selected-document semantics deliberately. Unknown chapter/scene must clear or label subordinate stale content rather than attaching a former scene to a new chapter. Scroll restoration should occur after the right tab instance mounts, be clamped, and not move keyboard focus on passive Word updates. Browser window geometry is best-effort and subject to browser permissions; it is distinct from pane proportions. + +### Editing safety + +Most current panels are reference-only, but explicit evidence requests/decisions are interactive and must not be destroyed by automatic refresh. Future embedded planning forms make this more consequential. A pane must report dirty/busy state; the host marks it stale and displays a compact “Updates available” affordance while preserving the original record identity. Save/Cancel/Reload resolve that state through the tab's own logic. Never retarget an unsaved form to a new scene because Word moved. + +On scope changes, keep the dirty panel visibly bound to its old scene with a pending destination, or require an explicit keep/discard decision when leaving. Do not automatically submit or discard. Before replacement, run canRefresh/dispose hooks; after save re-read authority and honor the latest destination. Use server concurrency tokens/input hashes for conflicting saves from two windows; disabling a local button is not concurrency control. Reuse Evidence hash checks. Keep persistent validation/progress/recovery inline; use shared toasts for appropriate completed/failed explicit actions. + +## 10. Shared toast prerequisite status + +**Implemented in the audited source.** Evidence: + +- `wwwroot/js/notifications.js` guards singleton initialization (`if (pd.toast) return`), consumes one shell host and exposes `PlotDirector.toast`; `css/notifications.css` and `Views/Shared/_ToastHost.cshtml` provide presentation. +- `_Layout.cshtml:118,341`, `_WritingCompanionLayout.cshtml` and `Views/WordCompanionHost/Index.cshtml:16,625–626` load the shared service; the embedded shell renders its host after `RenderBody`, outside the refreshable writing section. +- `word-notifications.js` is loaded in all three shells; native status and Office setters feed it. Office host lines 617–619 use the adapter for sync failure/accepted presentation. +- `Docs/Codex/Notifications.md` records bounded page migrations, all-three-shell Word cleanup, correlated manual outcomes, persistent-state exclusions and focused checks. It documents subsequent position preference and incident lifecycle work too. This is beyond a merely proposed prerequisite. + +The document records passing build/regression/browser checks on 21 November; this audit did not rerun them or establish deployed status. Existing focused fixtures include `shared-notifications.cjs`, `word-toast-outcomes.cjs`, `word-toast-paths.cjs`, `writer-word-notifications.cjs`, `toast-position.cjs` and `word-state-lifecycle.cjs` under `PlotLine.Tests/Browser`. + +Future Context must use `PlotDirector.toast` with one shell host. Routine navigation/background sync stays silent; meaningful explicit outcomes can toast. Follow status, unavailable-content explanations, validation, AI progress and recovery instructions remain inline. Preserve user-scoped toast preference and Word incident deduplication across windows; do not create pane-specific notification hosts or competing listeners. + +## 11. Proposed initial tab catalogue + +Classification concerns migration effort, not whether underlying data is new. Every registered tab still needs instance lifecycle/refresh metadata. + +### 1. Existing functionality with direct endpoint reuse + +| Tab | Current endpoint | Suggested policy | +| --- | --- | --- | +| Maps | `/Writing/Context/Map` | Scene navigation + relevant saved-data changes. Retain lens/pan state when possible. | +| Plot Lines | `/Writing/Context/PlotLines` | Book dataset invalidation plus Scene position presentation; preserve explored position until Return to current. | +| Metrics | `/Writing/Context/Metrics` | Book dataset invalidation plus Scene marker; no inferred values or AI on GET. | +| Evidence | GET `/Writing/Intent/Assessment` | Scene + saved prose/intent staleness; retain explicit POST Analyze/decision controls through an adapted wrapper. | + +These are the closest to direct reuse; Evidence's existing read endpoint alone does not include its outer action/status wrapper. + +### 2. Existing functionality requiring adaptation + +Recommended initial additional tabs: + +| Tab | Source and preservation requirement | Scope | +| --- | --- | --- | +| Overview | Existing Context Overview and common saved scene header. | Scene | +| Characters in Scene | People, including knowledge/provenance and saved state. | Scene | +| Relationships | Current relationship events and established reference. | Scene | +| Floor Plans | Existing Place tool, room/occupancy/zoom. Keep separate from Maps initially. | Scene | +| Chapter Planning | Chapter fields from Plan, Must Include and Notes: summary/purpose/goals, emotional goal, takeaway, must include and risks. | Chapter | +| Scene Planning | Scene summary, purpose selections/notes and expected outcome. | Scene | +| Objectives and Workflow | Saved checklist/progress plus revision, blocked, priority and word estimates/actuals. | Scene | +| Notes | Existing saved scene notes and pinned/resolved ordering; chapter risks also available through Chapter Planning. | Scene | +| Story and Continuity | Existing Story sections, Intent Threads descriptions, canonical/age/Story Point warnings and provenance. | Scene | + +Together with the four above this is a 13-tab preservation catalogue, not 13 always-visible toolbar buttons. Use an accessible compact chooser/overflow on narrow panes. Grouping can be simplified after approval, but do not omit Notes, Metrics, Floor Plans, author workflow fields or evidence to fit a shorter example list. Most reference tabs should refresh on relevant canonical-data changes; Evidence additionally depends on saved prose and goal/checklist changes. Chapter changes can invalidate scene assessment inputs even when scene ID is constant. + +### 3. Proposed new functionality + +A standalone book overview, dedicated beats editor, paragraph-sensitive reference tool, richer unified continuity investigation and a separate combined Locations tab are **new or expanded UI work**, not functionality demonstrated by the existing windows. Existing canonical data/services may support portions, but defer specification. No None-scope or Paragraph-scope tool is required for initial parity; the registry can reserve those capabilities without manufacturing data support. + +### 4. Keep full application workspaces + +Retain Scene editor, Writer Chapter editing/queues, Story Intelligence Review Centre, full Maps editing, Floor Plan editor, Relationship Map editor, Plot Line workspace and Story Calendar as full workspaces linked from reference tabs. Large editing/review workflows should not be copied into narrow panes in the first migration. Existing saved-data links are a useful boundary, not missing functionality to fill automatically. + +## 12. Technical risks and dependencies + +1. **Connection consolidation:** strict single browser connection requires carrying both native invalidations and Office/workspace events through one authenticated subscription. Reuse producers and user isolation; do not remove native recovery until equivalent recovery exists. This is a UI notification integration change, not a Word sync redesign. +2. **Accepted data versus observed Word revision:** Word movement/save, paragraph acceptance, chapter verification and canonical intelligence readiness are separate. Display what the server can verify; do not refresh into guessed identities or use unrelated chapter progress as current-scene authority. +3. **Content invalidation coverage:** current same-scene suppression and retained lazy panels miss updates; canonical edits from another window also need invalidation or an explicit stale/revalidation strategy. Reconnection must force stale reads. +4. **Instance isolation:** singleton roots, fixed IDs, shared active-tab storage and role-wide popup names prevent direct two-pane/multiple-window reuse. +5. **Read cost:** separate tab endpoints improve visibility-based work but can duplicate scene model reads across two HTTP requests. Request memoization does not cross requests. Measure before introducing shared caches that might hide author changes. +6. **Editing/concurrency:** AI calls and author decisions need stable panel ownership; later inline editors need explicit dirty/conflict handling across windows. +7. **Responsive/accessibility:** container size, short stacked panes, divider keyboard behavior, focus and component cleanup need actual browser checks. Source inspection cannot qualify these. +8. **Launch compatibility:** Office taskpane, native launcher, Writer launcher, named popup/focus roles, saved links and old `/Writing/Intent` URLs need a coordinated retirement plan. Redirecting too early would drop scope/native document parameters or break older entry points. +9. **Authority/access:** all tab endpoints must independently validate account/project/book/scene and native verification where applicable; a persisted UI record is never authorization. Basic hosting needs no new domain schema. +10. **Toast/prior behavior:** shell services must remain once per window, with Word scoping/deduplication and current appearance settings intact. + +## 13. Recommended implementation sequence + +1. Approve the preservation catalogue, initial reference-only editing boundary, independent-window identity/reopen policy and single-connection integration approach. Specify accepted-content invalidation and unknown-position behavior. +2. Introduce a generic Context shell/registry and one-pane controller behind a controlled migration entry point. Keep existing routes/launchers working during parity qualification. Reuse current services and existing independent endpoints. +3. Extract remaining authorized tab actions/partials from aggregate fragments; preserve every inventory item and existing explicit assessment/save behavior. Make DOM IDs, component lifecycle and state per instance; add dirty/busy deferral before automatic replacement. +4. Consolidate browser event ownership, normalize existing notifications, and implement per-instance generation/stale handling plus authoritative reconnect recovery. Do not alter native/Office typing/capture/analysis schedules. +5. Add the second pane, side-by-side/stacked divider and per-pane selection/scroll. Use container-based responsive rules and versioned workspace persistence; qualify multiple independent windows and cloned/blocked-storage cases. +6. Exercise focused browser scenarios: fast A→B→A and same-scene content changes, two visible instances, hidden stale tabs, reconnect/initial failure, selected-document ambiguity, unsaved Word/mapping changes, detached/dirty/busy Evidence, access expiry, cross-window edits, 1366×768 and smaller/zoomed laptop displays, short stacked panes, keyboard-only divider/tab/focus and map/plot resize/scroll. Use existing Word regression fixtures and later physical Windows acceptance for changed launch/notification paths. Run build then appropriate tests serially during implementation, not during this source-only audit. +7. Only after parity, update launchers/focus roles and retire standalone Intent presentation, preserving compatible scoped URLs/redirects and explicit AI actions. Keep rollback possible. Deployment requires its own authorized phase. + +## 14. Open design decisions requiring approval + +- Approve the initial catalogue/grouping: 13 preservation tabs, or a smaller set with explicitly identified combined subpanels? Keep Floor Plans and Maps separate initially? +- Reference-only planning/checklists at first, retaining existing full editors, or require inline editing in phase one? Inline editing materially expands dirty/conflict handling. +- Can both panes select the same tab? Recommended yes, with independent view state and instance IDs; no shared live DOM node. +- Does a window have one shared manuscript position/document selection with independent tabs (recommended), or independently pinned positions per pane? Existing pinned-window behavior must remain available either way. +- Define “reopening”: restore a particular workspace UUID, restore a default template, or restore the last closed window? Define new-window versus focus-existing controls and old Intent launch compatibility. +- Confirm strict one browser SignalR connection and choose the common event surface. Approve forwarding existing lightweight native notifications while retaining sync producers and recovery semantics. +- Define content freshness guarantees: accepted prose changes, canonical entity/planning edits, metrics/maps and explicit assessment results. Which existing boundaries must announce missing invalidations, and what is the fallback when no version is available? +- On Word moving while a panel is dirty/busy, retain that panel at its labelled old scope with pending navigation (recommended), or prompt immediately? Do not infer permission to save/discard. +- Set minimum pane dimensions and laptop fallback: offer stacked/single layout, retain remembered proportions and require accessible divider behavior. +- Reserve Paragraph scope without shipping paragraph tabs (recommended), or explicitly authorize a separate paragraph identity/payload specification? Current common position payload is insufficient. + +No implementation has begun. This report is the design-support deliverable for the next specification.