PlotDirector/Docs/Investigations/Writer2Audit/04-Architecture-Recommendations.md

18 KiB
Raw Blame History

Architecture Recommendations

Everything proposed here is design work for later approval. No schema or application implementation is included in this audit. Preserve ASP.NET Core MVC/Razor, Dapper, stored procedures, canonical manuscripts, current grants, existing imports and forward-only numbered migrations.

Ownership and components

  1. Existing manuscript acceptance remains authoritative. Extend ParagraphManuscriptService / repository save and selective chapter procedures; do not create a parallel live manuscript writer or import engine. BookParagraphManuscripts remains accepted source; SceneManuscriptSources remains its established scene projection for analysis consumers; Reader continues to read accepted state.
  2. Writing activity ingestion validates a versioned source-neutral envelope, current access, source capabilities, source sequence/identity and payload hash. It accepts session/declaration observations and attaches native observation metadata to server-accepted content changes. It does not trust client totals, actor IDs or book mappings without validation.
  3. Transactional activity append records one accepted content transition with its actual acceptance result. Persist the event and canonical change in one database transaction; if a later projection fails, retain the committed event and retry projection. If the append fails, do not acknowledge full activity capture. Publish SignalR only after commit. Where a reliable downstream bus is needed, use a database outbox in that same transaction, not a second independently committed insert from the controller.
  4. Deterministic projections aggregate bounded date/book/chapter/session/pass scopes, maintain version/checkpoints and expose drill-down. Replays must not change raw evidence. Initially incremental SQL processing with durable progress is sufficient; use existing hosting infrastructure, not an unnecessary external event platform.
  5. Plan service evolution adds availability, exceptions, independent passes and milestone/dependency proposals around existing personal plans. Distinguish plan templates, generated opportunities and author tasks from actual work. Use preview/apply and optimistic concurrency.
  6. Session service persists explicit state transitions and reconciles cross-device/native/browser contributions. Session timer state is distinct from observed document activity. Default to one foreground focus session per author unless explicit product behaviour permits overlap; document events can still arrive from other devices.
  7. Insight and report services consume the same projections and evidence qualification. Conventional statistics first; no external AI dependency. A separate signed-report boundary handles keys and public verification only in G6.

Proposed flow:

flowchart LR
  Word[Word add-in and protected agent outbox] --> Validate[Authenticated source-neutral validation]
  Editor[Future native PlotDirector Editor] --> Validate
  Manual[Author declarations and feedback imports] --> Validate
  Validate --> Commit[Existing acceptance transaction plus event append]
  Commit --> Canonical[Canonical manuscript and scene projections]
  Canonical --> Reader[Existing read-only Reader]
  Commit --> Ledger[Versioned activity ledger and optional retained snapshots]
  Ledger --> Projection[Rebuildable qualified projections]
  Projection --> Writer[Dashboard and Writing Journey]
  Projection --> Reports[Insights and evidence reports]
  Plans[Availability and versioned plan proposals] --> Writer
  Sessions[Explicit session lifecycle] --> Validate

Manual/import events cannot directly masquerade as accepted manuscript transitions. If a feedback import updates text, it goes through accepted source validation as an import-attributed transition.

Proposed schema (names provisional)

Entity Minimum responsibility/fields Relationships, index and policy
WritingActivityEvent Event GUID; book/manuscript/stream epoch; stream sequence; type/version; source/producer; authenticated submitter; actor kind/contributor; source event key+payload hash; observed/received UTC; offset/timezone and clock/precision flags; correlation/causation; baseline/before/after revision+hash; provenance/coverage; optional session/pass; metric algorithm version; counts or structured minimal payload Unique producer-scoped idempotency key; unique accepted stream transition; (BookID, ReceivedUtc, EventID) and observation-date query indexes. Tenant/book checks in stored procedures. Append-only through normal APIs.
WritingActivityScope (optional child table) Affected paragraph GUID; chapter/scene at observation and acceptance; association confidence; old/new placement/movement kind Avoid multiplying book totals when joining many scopes. IDs may outlive archived/deleted structures; use governed tombstone/nullable links and immutable minimal historical references.
WritingActivityReceipt Original source identity/key/hash, accepted event IDs/result and receipt status Exact replay returns original result; same key/different payload rejected. Retain receipts at least as long as event replay risk. Can be merged with event table if one-to-one; needed when one batch maps to several events.
WritingSession + append-only session transitions Owner, objective, optional planned task/pass/document, planned duration; Start/Pause/Resume/Extend/Finish/Abandon; monotonic measured intervals, server receipts, declaration notes and confidence Optimistic version and transition idempotency. Derived elapsed/paused/observed activity separate. Native document session ID is a transport identity, never the focus-session PK.
ManuscriptSnapshot Immutable version identity, content/mapping hashes, accepted revision/epoch, capture/acceptance times, scope, algorithm, coverage; optional encrypted full/delta payload and parent reference Metadata + references mandatory for evidence; historical prose optional subject to policy. Existing canonical Payload is not rewritten as the entire archive. Content-addressed chunks/deltas reduce duplication. Periodic full checkpoints bound replay cost if reconstruction is offered.
ManuscriptPass Book, kind/custom name, optional parent/ordering, planned dates, explicit status and source Multiple simultaneous passes. Do not constrain to one active pass per book/chapter.
ChapterPassStatus + state events Chapter/pass, NotStarted/InProgress/Reviewed/Complete, actor/effective/receipt time, observed/declared/imported provenance Current state projection plus history. Unique chapter/pass current row; edits can be associated but cannot mark reviewed/complete.
WritingAvailability User/book-or-profile scope, regular/flexible mode, local timezone, recurrence/slot intervals, capacity, preferred session types and protected periods Version effective date; no mandatory fixed weekdays for flexible mode. Personal-time labels should not be exposed to collaborators.
ScheduleException Local-date/range/slot overrides, holidays, temporary reduced availability, reason visibility Applied after recurrence; test DST, crossing midnight and conflicts with protected time.
Plan/opportunity revisions Keep WritingPlans/WritingScheduleItems compatibility; add plan revision/proposal/approval metadata and opportunity/task identities Avoid destructive regeneration of historical Done/Skipped entries. Existing items can be linked as legacy declarations, not measured sessions.
WritingMilestone + dependencies Book/pass/external work, planned target/effective completion/status, actor/source; dependency edges Acyclic dependency validation; concurrent phases valid. Only declarations or integrated source states establish completion.
CollaboratorAssignment Author owner, scoped book/chapter/pass/task, contributor identity or external contact, capability grants, status/dates New scopes intersect existing project access but must not require granting all project data. Separate external contact from authenticated app principal.
WritingInsight Rule+version, sample interval/count, qualifying coverage, confidence/limitations, factual result, dismissal/cooldown Regenerable result separate from persistent author dismissal. No permanent personality identity.
ProvenanceReport Report GUID, owner/scope, query/projection/metric versions, generated time, coverage/redaction manifest, export digest; later signature/key/version and verification disclosure Issued report basis must remain identifiable even after retention expiry; disclose unavailable evidence. No public manuscript lookup.
Projection tables/checkpoints Book/day/session/chapter/pass aggregate, counts, coverage periods and source partitions; projection version and last processed stream/event Bounded reads, cursor pagination, deterministic rebuild/checksum and lag monitoring. Keep raw evidence and derived caches distinct.

Add explicit retention/deletion metadata and recovery format versions where needed. Exact column widths, next migration number and batch boundaries must be selected during implementation after current schema inspection, not invented in this audit. No EF or inline application SQL.

Idempotency and concurrency contract

  • A source producer creates immutable event identity before delivery, including server/account scope. Document switching and reauthentication must not redirect queued events to a different account/book. Keep stable IDs across retries and process restarts.
  • Enforce a durable unique receipt key, not only LastRequestId. A retry after newer changes still returns its original acceptance result. Same key with a different payload is a conflict; never reinterpret it as a new event.
  • Server-side canonical acceptance generates the content transition. Native observation and the resulting accepted transition are linked evidence, not two countable copies of the words. Unchanged validation is a distinct non-growth event or compact receipt; do not manufacture a writing day from repeated checks.
  • Lock/check expected book revision and stream epoch in the existing transaction. Concurrent producers based on the same old revision cannot both silently overwrite accepted state. Reject/review stale edits; generic business logic must not use manuscript-specific rules.
  • An append-only stream sequence reflects accepted order. Observed times may arrive out of order; maintain both axes. Quarantine future/skewed client times and expose precision rather than silently rewriting them as server times. Never infer elapsed duration by subtracting unreliable wall clocks.
  • Chapter-only changes must retain unrelated canonical GUIDs/assignments; old/new scope mappings live on the event. Full snapshots, identity adoption, layout edits, mode changes and validation must not all become content output.
  • Plan regeneration, book import/copy, restore and manuscript rebinding need a lineage/epoch decision. Restoring old content is a new present-day restoration event pointing to its source, never a rewind of the activity ledger or a replay of all old words as fresh drafting. Imports across book IDs retain original source references with scoped deduplication; they do not attach another author's private history by default.

Measurement and coverage

The first accepted existing state is a baseline. Record its word count and capture coverage beginning now; do not add its words to today's output. The immediate baseline can be server-side against the accepted current snapshot; distinguish this from when Word was last observed. An up-to-date Word baseline requires the existing authorised capture path.

Compute word changes with a deterministic versioned token diff over matched paragraphs, with a coherent book/scope total. Current manuscript statistics can inform the token contract, but private CountWords is not already a diff engine. For a fully comparable transition, enforce gross additions − gross deletions = current words − prior words. If scope/token rules differ, label the figures as incomparable until reconciled. Moves and structure-only split/merge should preserve book net; ambiguous matching must not inflate gross output as if new prose was certainly written.

Counts reflect sampled accepted state differences. Text typed and removed between observations is invisible; do not call snapshot counts all keystrokes or all revision effort. Formatting-only activity may be declared/observed as non-growth without claiming formatting details unavailable in capture. Deliberate deletion counts as work even when net is negative. Calendar projections use the author's local timezone and actual recorded opportunities, not the server date. Store timezone/offset context at observation so travel and DST do not retroactively shift history unexpectedly.

Store coverage windows/gaps explicitly: baseline only, accepted-transition coverage, optional native observation coverage, offline uncertain interval, unavailable retained text, imported source and declarations. Insights require qualifying windows and disclose denominators. A connected heartbeat and timer state are separate evidence, neither proves concentration. Non-document work is declared unless another supported integration directly observes it.

Offline and native compatibility

Add a production agent outbox using existing protected state conventions, but do not repurpose the coalescing metadata queue as an exact history journal. Use bounded encrypted atomic files or a suitable embedded store, per-account/site producer identity, monotonic source sequence, acknowledgements, expiry/backpressure, retry with jitter and diagnostics without prose. Preserve observations until acknowledged or explicitly resolved. If storage/permission/capacity fails, show a coverage gap; never acknowledge capture that was not durably queued.

Minimum capture can retain a before/after hash/count and timestamps without prose; exact independently recomputable gross changes need retained comparable text/diff under policy. If the application only observes a final offline state, honestly record an uncertain interval and final difference. Closing/crashing before capture cannot be made complete retrospectively.

Negotiate new capabilities; older installed add-ins retain current endpoints and behaviours. Server acceptance events provide a safe initial coverage level. Do not send unknown sprint/focus/window commands to old VSTO clients. Reuse validated chapter navigation, manuscript identities, lease/grant checks, authentication renewal and duplicate-position guards. Opening/focusing a closed document or placing Word on a display is additional native work requiring explicit author intent, safe local identity/path handling and Windows qualification; never send arbitrary server-supplied executable paths.

The future PlotDirector Editor should submit semantic accepted transactions with the same manuscript/paragraph identities and contract. Its richer operation stream may increase coverage but should not create a competing definition of output. Preserve source fidelity rather than downgrading Editor events or overstating Word telemetry as equivalent.

Security, privacy and retention

Reuse current authentication, project access and entitlement services. Add explicit book/chapter/pass capability authorisation at service and procedure boundaries, SignalR groups, drill-down and export; owner-owned reports do not imply collaborator access to private notes/research. Client actor IDs are claims to validate, not authority. Imported external editor activity stays imported/declaration evidence until independently captured and attributed.

Define retention, export and deletion before production capture. Append-only means ordinary corrections append superseding events; it does not prohibit authorised erasure/redaction. Separate immutable minimal event identity/digests from removable encrypted text and private notes. After erasure/expiry, record that evidence is unavailable, rebuild affected projections and prevent backups/exports/restores from resurrecting deleted private data. A hash of sensitive short text may itself leak information; hashes are not automatic anonymisation.

Snapshot text retention, event/receipt retention, external feedback, session notes, generated reports and public verification metadata need distinct policies. Do not default to retaining every full manuscript at every heartbeat. Quotas/backpressure, archival cost and deletion of book/project/user require explicit handling; avoid new cascading foreign keys that erase evidence accidentally or prevent legitimate deletion indefinitely.

Keep exports available under current inactive-subscription policy. Define what happens to queued ingestion after expiry/revocation: return explicit blocked status, keep locally pending under policy, offer resolution/export; never silently reassign or drop it. A malicious/new client cannot bypass existing entitlement checks using a telemetry endpoint to modify manuscript state.

Signed provenance boundary

First implement an unsigned report with reproducible scope, coverage, metric versions, redaction manifest and limitations. Later issue a PDF with report ID, timestamp, cryptographic signature over the exact issued document and approved verification metadata. Server-generated SHA-256 or a seal image alone is not a document signature.

G6 needs a chosen signature standard/provider, protected signing key/certificate custody, key rotation and compromise/revocation response, timestamp/long-term validation requirements, deterministic verification, redacted public status and rate limiting. QR should resolve to a random report verification identifier and reveal only approved metadata. Verification establishes that PlotDirector issued an unaltered report; it does not certify authorship, exclusive human work or absence of AI. Signed reports must disclose when underlying evidence later expires/is deleted and how verification is affected.

Performance and operations

Avoid reading a whole-book JSON blob for each dashboard chart. Introduce bounded stored procedures for daily aggregates and event pages, with user/book scope, time ranges and cursor limits. Reader can continue its existing retrieval initially; optimise its server aggregate read separately when measured. Cap processing of large paragraph diffs without silently truncating counts; classify unavailable/partial if exact calculation cannot complete.

Monitor ingestion lag, blocked outbox age/capacity, duplicate/conflict rates, accepted-vs-projected sequence, snapshot/metric hashes and rebuild discrepancies. Repair tools should replay projections, diagnose scope/lineage problems and append corrections, not rewrite author history to fit charts. No import or Story Intelligence rerun for ordinary activity projection or Writer GETs.