diff --git a/Docs/Investigations/Writer2Audit/01-Existing-System-Inventory.md b/Docs/Investigations/Writer2Audit/01-Existing-System-Inventory.md new file mode 100644 index 00000000..fa644fdf --- /dev/null +++ b/Docs/Investigations/Writer2Audit/01-Existing-System-Inventory.md @@ -0,0 +1,62 @@ +# Existing System Inventory + +Evidence labels and audit scope are defined in [README](README.md). Paths below are repository-relative. “Implemented” describes inspected code, not a new end-to-end runtime certification. + +## Writer and planning + +| Component / status | Actual implementation and reusable behaviour | Limit relevant to Writer 2.0 | +|---|---|---| +| Writer dashboard — implemented; SQL objects present in Development | `PlotLine/Controllers/WriterController.cs`: `Index`, `Chapter`; `PlotLine/Services/CoreServices.cs`: `WriterWorkspaceService.GetDashboardAsync`, `GetChapterWorkflowAsync`; `PlotLine/Views/Writer/Index.cshtml`, `Chapter.cshtml`, `_WriterSceneQueue.cshtml`; `PlotLine/Data/Repositories.cs`: `WriterWorkspaceRepository` | Dashboard selects projects, not a book-specific workspace. `Index(int? projectId)` does not consume `bookId` although shell links carry it. Queries are repeated for accessible projects and four queues. Avoid expanding this fan-out for historical charts. | +| Workflow queues — implemented | `dbo.WriterDashboard_Scenes`, `dbo.WriterDashboard_Reminders`; `PlotLine/Sql/015_Phase1P_WriterWorkspace.sql`, `052_RevisionStatusWriterWorkflow.sql`. Outlined → Write Next; Drafted → Continue Writing; Needs Work → Revision; Revised → Polishing. Scene links, priorities, blockers, warnings, outstanding notes and checklist counts already exist. | Single scene revision status cannot describe multiple independent chapter passes. Old DraftStatus/readiness fields remain in model/storage for compatibility; `SaveSceneWorkflowAsync` preserves them rather than using them as queue authority. | +| Chapter/scene planning — implemented | `ChapterGoal_Get/Save`, `ChapterGoals`, `SceneWorkflow`, notes, checklists and attachments; `IWriterWorkspaceRepository`; `WriterWorkspaceService.SaveChapterGoalAsync`, `SaveSceneWorkflowAsync`, note/checklist/attachment methods. | Goals are author-entered narrative objectives, not time-series milestone completions or observed edit events. Preserve these distinctions. | +| Book targets/progress — implemented | `Book` in `Models/CoreModels.cs`: `TargetWordCount`, `CurrentWordCount`, `WritingStartDate`, `TargetCompletionDate`, calculated `ProgressPercentage`; book/project dashboard services | Existing explicit targets are useful wizard prefill/milestone inputs. Word-count ratio is current length versus target, capped at 100%; it is not percentage of revision/editorial work complete or historical output. | +| Writing plans — implemented and populated in Development | `WriterController.WritingPlans`, `EditWritingPlan`, activate/deactivate/delete/regenerate actions; `WritingScheduleService`; `WritingPlan` / `WritingScheduleItem` in `PlotLine/Models/CoreModels.cs`; `PlotLine/Views/Writer/{WritingPlans,EditWritingPlan,ScheduleSetup,SchedulePreview}.cshtml`. | Personal plan owner, project, optional book, start/deadline, JSON days/capacity, session minutes, blocked inclusion, rebalance mode. No separate time-of-day slots, exceptions, protected time, flexible unscheduled mode or versioned schedule history. | +| Schedule persistence — implemented | `PlotLine/Sql/056_Phase9B_WritingScheduleFoundation.sql` and procedure refactor `088_InlineSqlStoredProcedureRefactor.sql`; `WritingPlans`, `WritingScheduleItems`; `CreateWritingPlan`, `UpdateWritingPlan`, `GetWritingPlansByUser`, `WritingPlan_ListForManagement`, `WritingScheduleScene_ListForPlanning`, `WritingSchedulePreview_ListByPlan`, `WritingScheduleDashboard_ListActive`, `WritingScheduleItem_UpdatePlannedStatusForUser`, `WritingPlanSummary_ListRequiringRebalance`, date-update/delete procedures. Dapper calls specify stored-procedure command type. | Dates and capacity are plans, not measured sessions. Status Done is a user action, not observed manuscript completion. Deletion/regeneration can remove records. | +| Schedule engine — implemented | `WritingScheduleService.GenerateSchedule`, `BuildGeneratedScheduleItems`, `CreateTaskEstimate`, `PreviewRebalanceAsync`, `ApplyRebalanceAsync`. Draft estimates use estimated words / 750 words per hour, or 90 minutes; revision 45, polish 30. Large tasks split across dates and word allocations reconcile across parts. | Generation consumes a new available date per task/part; unused daily capacity is not shared between successive scenes. GoalType is stored but does not select a different task-estimation pipeline in `GenerateSchedule`. Insufficient capacity throws. No dependency graph or overlapping pass planning. Daily boundaries use server `DateTime.Today`. | +| Rebalance modes — partly implemented | Ask/Automatic/Never values are persisted and editable; rebalance preview and explicit apply exist. | The inspected service has no automatic rebalance execution path driven by the Automatic setting. Treat the value as configuration, not proof of a running scheduler. Specification requires approval of suggestions; retire incompatible automatic behaviour rather than adding it. | +| Measured sessions / sprints / rhythm / provenance — new work | `Exports.WritingSession` and `ExportWriterSessionBriefAsync` render a scene writing guide. Account onboarding has `WritingJourney` / writing software answers (`OnboardingController`, `UserOnboardingState`). | Neither is a measured focus session or the Writer 2.0 journey timeline. Targeted source and Development schema inspection found no implemented Writer 2.0 ledger/session/pass/insight/report subsystem. | + +## Shell, workspaces and displays + +| Component / status | Evidence and reusable behaviour | Limitation | +|---|---|---| +| Application shell/ribbon — implemented | `PlotLine/Services/ApplicationNavigation.cs`, `ApplicationRibbon.cs`, `ToolbarCommands.cs`, `RibbonPresentation.cs`; `Views/Shared/_ApplicationShell.cshtml`, `_ApplicationNavigation.cshtml`, `_ApplicationSectionMenus.cshtml`; ribbon contribution tag helpers | Writer is already a direct navigation destination. `ActiveCategory` returns `writer`, but the static category list does not define the six-destination Writer ribbon. Do not diagnose this as absence of all ribbon integration. | +| Theme/PWA/maximise — implemented | `wwwroot/css/plotline-theme.css`, application-navigation assets, `wwwroot/js/application-pwa.js`, workspace maximise browser tests; four application themes | Reuse existing tokens and controls. `wwwroot/service-worker.js` explicitly has no fetch handler, offline cache or background sync; installing the PWA does not provide offline manuscript history. | +| Context/Intent writing desks — implemented | `WritingController` routes `/Writing/Context`, `/Writing/Intent`, partials, maps/plots/metrics; `Views/Writing/`; `wwwroot/js/writing-workspace.js`; `WritingWorkspacePresenceService`, `WordCompanionFollowHub`, `Models/WritingWorkspacePresenceModels.cs` | These are contextual working windows, not duplicate Writer dashboards to remove. Native-target checks include saved state, session, revision and accepted positions. Preserve those checks and deep links. | +| Companion state/presence — implemented, ephemeral | `WordCompanionPresenceService` uses concurrent dictionaries with 55-second heartbeat timeout; `Services/NativeCompanion/NativePresenceStore.cs` has 45-second live leases; `WordCompanionPresenceMonitor` hosted service; native presence hub, `_WritingConnectionDetails.cshtml` and shell status button | Heartbeat time is connection evidence, not focus duration. “Not installed” cannot be established from a missing heartbeat alone. | +| Display discovery — partially meets specification | `writing-workspace.js`: `getScreenLayout`, `sortScreens`, `chooseLayout`, `popupFeatures`, `openRoleWindow`, `focusRole`. Permission-aware `getScreenDetails`, manual fallbacks, browser-window registration/focus, localStorage preference persistence. | >=3 monitors use a `three-screen` layout: outer Context/Intent and middle Word. Discovery can enumerate more screens, but semantic roles/profiles/research/spare/topology lifecycle are missing. Word display is a calculated preference, not an implemented OS Word-window placement command. | +| Charts/drill-down — reuse outside Writer | `Views/Analytics/Index.cshtml` has navigable scene metric charts and raw-row fallback; `Views/Timeline/Index.cshtml` uses story-position navigation and scene selection | Story chronology/narrative order is not writing-calendar history. Reuse interaction/theme patterns without substituting story events for author activity. | + +## Manuscript and native integration + +| Component / status | Evidence / responsibilities | Retention and compatibility limits | +|---|---|---| +| Office task-pane shell — existing separate integration | `PlotDirector.WordCompanion/README.md`, manifest/template, `/word-companion` host and `wwwroot/js/word-companion-host.js`; `WordCompanionController`, `WordCompanionService` | This is not the native VSTO source. Keep legacy routes/contracts compatible and explicitly identify which source captured evidence. | +| VSTO Word add-in — source implemented; Windows qualification separate | `PlotDirector.NativeCompanion/Vsto/WordAdapter.cs`, `WordChapterRead.cs`, `WordChapterPositions.cs`, `ThisAddIn.cs`, native ribbon. Word UI-thread COM work, bounded reads, document properties/association, selection/save/close observations and session/revision guards. | Revision counter is a local lifecycle/change signal, not Word Track Changes or a complete edit count. Linux cannot certify COM, installer, responsiveness or OS window focus. | +| Background Windows agent — source implemented | `PlotDirector.NativeCompanion/Agent/{Program,PipeHost,SessionManager,TrayCoordinator,TrayCoordinator.Chapters,TrayCoordinator.Reuse,CloudGateway,CloudGateway.Authorization,ParagraphSnapshotCache,CompanionStateStore}.cs` | Pipe sequences, authentication contexts, per-document sessions, bounded caches, captured transfer and retry coordination. Persistent protected state stores installation credentials/preferences/bindings; not an activity log. | +| Offline queue foundation — unused by production sender | `Agent/DeferredWorkQueue.cs`; only constructor/use references outside its class are in `PlotDirector.NativeCompanion/Tests/Program.cs` | Contains bounded durable scheduling metadata, coalesced per manuscript/scene; no prose. Source comment explicitly says not attached to a server sender. Does not preserve all offline edits or event order. | +| Native pairing/access — implemented | `NativeCompanionAuthController`, `Services/NativeCompanion/{DesktopPairing,NativeInstallationService}.cs`; `CloudGateway.Authorization`; Windows user DPAPI in `CompanionStateStore` | Existing server/account scope, grant renewal/revocation, capability negotiation and security stamp should be extended rather than bypassed. | +| Import capture — implemented and retained | `NativeManuscriptCaptureController`; `Services/NativeCompanion/NativeManuscriptCapture.cs`; `OnboardingManuscriptCaptures`, `OnboardingManuscriptCapture` procedure; SQL 237 and 239 | Original accepted preview payload/hash/time can survive beyond import. Analysis checkpoints are mutable and are not manuscript versions. Only one capture retained in current Development. | +| Canonical accepted manuscript — implemented and populated | `Models/ParagraphManuscriptModels.cs`; `Services/Manuscript/ParagraphManuscriptService.cs`, `ParagraphManuscriptEngine.cs`; `Data/ParagraphManuscriptRepository.cs`; `BookParagraphManuscripts`, `dbo.ParagraphManuscript`; SQL 240 and later replacements 249–250 | One accepted JSON payload per book. Full snapshot and selective chapter changes use expected revision/request identity. Scene projections and statistics remain existing authoritative consumer stores; do not introduce a second live manuscript. | +| Paragraph identities/reconciliation — implemented | `Protocol/Manuscript/ParagraphIdentity.cs`, `ParagraphDelta.cs`; GUID occurrences, Word native paraId hints, text fingerprints, neighbour/context matching, moves, ambiguity, removals and retained evidence anchors | Native paraId is a hint, not permanent identity. PreviousText is a latest-comparison aid; removed paragraphs are not a durable tombstone stream. Layout Undo stores assignments, not old prose. | +| Chapter detection and acceptance — implemented | `ChapterCheckpointEngine.{Build,Validate,MergeChapter}`, `ChapterSyncService.{Manifest,Accept,Reuse,Finish,Repair}`; `BookChapterSync`, `BookChapterReuse`; SQL 243, 245–251; `BookChapterValidations` | Durable checkpoint ≠ live position validation ≠ writing-pass completion. Explicit review for cross-boundary structural uncertainty. Validations expire after 12 hours and are updated/pruned, not immutable audit events. | +| Scene source/statistics — implemented | `SceneManuscriptSources`, source projections in `ParagraphManuscript`, `ManuscriptTextStatisticsService` and deterministic recalculation | Latest text/counts support current metrics and Story Intelligence; no gross historical addition/deletion ledger. Formatting absent from plain-text capture cannot be reconstructed. | +| Reader — implemented; documented Development delivery | `ManuscriptReaderController`, `ManuscriptReaderService.{Read,Check,Project}`, `Views/ManuscriptReader/`; `Docs/ManuscriptReader/{Phase1,LiveUpdates}.md` | GET-only, accepted source only, chapter navigation, focus reading, encoded selectable prose, refresh without reimport. Whole-book JSON still read server-side. Sync and capture timestamps are explicitly different. No native editor yet. | + +## History, relationships, access and background work + +- `Projects → Books → Chapters → Scenes` remains the relational hierarchy. Canonical paragraph state also stores document/manuscript identity, paragraph GUIDs, chapter heading GUIDs, scene GUIDs and scene canonical IDs. Captured paragraph ordinals and physical Word offsets are not durable entity identity. Document renames must preserve manuscript identity; copied documents with identical IDs need conflict treatment. +- `ProjectActivity` / `ProjectAudit_Record` / `ProjectActivity_Create` record selected entity operations with user, project, type, entity and receipt timestamp. `ProjectActivityService.RecordAsync` and explicit callers in `CoreServices.cs` establish coverage. This is not a universal SQL change log; native sync does not automatically become a recorded writing event. Source migration 046 has later extensions (e.g. merge/export activity); inspect current constraints rather than treating its original type list as exhaustive. +- `ProjectRestorePointService` stores complete project backup JSON through `IProjectExportService`. Manual creation is limited to 10 existing points; pre-restore safety backups also exist. Deletion/download are available. `Services/Manuscript/ParagraphRecovery.cs` validates and carries paragraph manuscripts through recovery. These are discrete recovery states, not periodic writing history. Book/project restore and transfer must be updated deliberately for a future ledger. +- `ProjectCollaboratorsController`, `ProjectCollaborationService` in `CoreServices.cs`, `ProjectAccessServices.cs`, `ProjectAccessFilter.cs`, SQL 045: owner-managed invitations and project-wide `Owner`/`Collaborator` access. All 14 Development access rows were Owner; no live collaboration journey was verified. Existing collaborators are not automatically restricted to assigned chapters or private-note exclusions. +- `SubscriptionService.GetEffectiveEntitlementAsync`, `SubscriptionEnforcementFilter`, `SubscriptionFeature`, `SubscriptionRepository`, SQL `201_SubscriptionEntitlementEnforcement.sql` and `docs/subscription-entitlements.md` are the central entitlement path. Inactive accounts retain reading/export but unsafe requests are blocked. Future ingestion must define denied-write/offline recovery semantics and avoid silently losing queued activity. Do not hard-code tier names. +- `UserOnboardingState`, application toolbar/bar preferences, browser-local display settings and native protected `CompanionPreferences` are different preference scopes. None is a versioned Writing Rhythm profile. Use the existing account/theme preferences; add writing-specific settings with explicit account/book/device scope. +- Hosted presence monitoring and the native agent's periodic polling are operational coordination. Existing import/analysis workers are not focus-session processors. Story Health should consume persisted warnings/metrics/review summaries under `docs/story-intelligence/single-system-runtime.md` and `Docs/StoryIntelligence_ExceptionReview.md`; no raw-analysis reconstruction or AI re-run on dashboard GETs. + +## Tests and operational evidence + +Existing relevant tests: `PlotLine.Tests/Paragraph{Manuscript,Workflow,Chapter,Backup,View}Tests.cs`, `ChapterSynchronisationTests.cs`, `ChapterStructuralContentTests.cs`, `ManuscriptReaderTests.cs`, `WritingIntegrationTests.cs`, `Native{Companion,Workflow,TrayIntegration,Installation,ManuscriptCapture,CaptureLifetime}Tests.cs`, `SubscriptionEntitlementTests.cs`, native portable tests, SQL tests and browser suites listed in the implementation plan. Existing tests include source-contract assertions; these are not substitutes for runtime/native acceptance. + +`Docs/WordCompanion/WindowsHandover/` distinguishes source candidates, Atlas qualification and Windows results. `Docs/ManuscriptReader/Phase1.md` explicitly leaves real Word-to-Reader and Windows installed-PWA acceptance unverified. Those limitations remain here; historical reports are not a new test run. + +Gate/deployment procedure was inspected in `Docs/Codex/Deployment.md` solely for the requested delivery-flow assessment. Future Development rollout requires idle import/analysis guard, verified migration prerequisites, build identity, service/HTTPS/authenticated smoke checks and an application rollback compatible with forward-only schema additions. No deployment took place in this audit. diff --git a/Docs/Investigations/Writer2Audit/02-Requirements-Traceability.md b/Docs/Investigations/Writer2Audit/02-Requirements-Traceability.md new file mode 100644 index 00000000..8512c2f6 --- /dev/null +++ b/Docs/Investigations/Writer2Audit/02-Requirements-Traceability.md @@ -0,0 +1,109 @@ +# Requirements Traceability Matrix + +Baseline: [Writer2_Spec.md](Writer2_Spec.md). IDs below are audit IDs, grouped by specification section; they do not change requirements. **R** = reuse, **M** = modify/extend, **N** = new capability, **U** = unverified acceptance/design input. Evidence aliases refer to exact repository paths/classes in [inventory](01-Existing-System-Inventory.md): **W** WriterController/WriterWorkspaceService/views; **P** WritingScheduleService/repository/SQL 056 and 088; **S** ApplicationNavigation/ApplicationRibbon/shared shell/themes/PWA; **D** WritingController/writing-workspace.js/presence; **C** native capture, paragraph and chapter services/protocol/SQL; **H** ProjectActivity/captures/recovery; **A** access/collaboration/subscription; **V** Reader/Analytics/Timeline. Each row identifies the dependency or principal risk and proposed approach. Phases G1–G6 refer to [implementation plan](06-Phased-Implementation-Plan.md). + +## Product, navigation and dashboard (§1–3) + +| ID / requirement | Existing and disposition | Gap, dependency/risk and approach | +|---|---|---| +| 1.1 Writing first; show achievement and next work; no duplicate records | R W queues, P tasks | M Overview should project current work + opportunities + evidence. G1 coverage before activity indicators. | +| 1.2 No chatty AI, artificial praise or guilt; UK English | R non-chat Writer; M copy | Remove “control room”/setup-heavy emphasis; factual labels, no streak penalties. No external AI dependency. G2. | +| 1.3 Drafting, deletion, revision, research, editorial and publication all count | R scene states/notes; N event categories | Distinguish observed edits from declared non-document work; never translate research minutes into invented words. G1/G4/G5. | +| 1.4 Author schedule control, accessible theme/ribbon | R S; M P | All proposals preview/approve/dismiss; accessible controls and non-colour meaning. G2/G3. | +| 2.1 Full-width Writer with contextual ribbon | R S; M W/ApplicationRibbon | Add Overview/Journey/Plan/Focus Sessions/Workspaces/Reports destinations; preserve shell/maximise. G2. | +| 2.2 Remove duplicate Write/Writer destinations; preserve deep links/redirects | R direct Writer nav; M route review | No separate `WriteController` was found in the audited path. Inventory legacy URLs before redirecting; Context/Intent remain independent desks. Preserve query scope. G2. | +| 2.3 Five workspace tabs | R four W queues + reminders; M | Map to Write Next/In Progress/Revision/Final Pass/Story Health; keep status semantics and completed work reachable. G2. | +| 2.4 Chapter/scene/issues navigate; common shell book/project selection | R V scene links/S selection; M W | Current dashboard ignores bookId and shows local project selector. Add authorised book scope; link issue targets explicitly. G2. | +| 2.5 Companion/Display Setup contextual actions | R D discovery/status; M | Compact menu; hide irrelevant document actions when no linked document. Installation state requires evidence, not heartbeat absence. G2. | +| 3.1 First viewport: selected book/current work/next opportunity/compact state/indicators | R W/P/D; M | Remove permanent workstation panel and long tables from first viewport; small data-backed cards. G2. | +| 3.2 Activity days relative to chosen opportunities | R planned dates P; N observed projection | Need G1 capture and local-day/coverage semantics; unscheduled days neutral, flexible mode has no invented missed days. G2/G3. | +| 3.3 Gross added/deleted/net manuscript change | R C current text/counts; N versioned differencing/history | Counts between accepted states only; moves/format-only changes separated. No summing current word counts as output. G1/G2. | +| 3.4 Pass/milestone progress; optional compact journey | R P Done and W revision status; N parallel passes/milestones | Author declarations labelled; edits never imply complete. G4; placeholder withheld before data. | +| 3.5 Progressive disclosure; charts/cards drillable | R V chart links/raw fallback; M W | Bounded aggregates → dates/events/scene/reader destinations. Keyboard/table equivalents. G2/G4. | +| 3.6 Green observed/amber risk/red blocker/grey unscheduled; provenance labels | R S tokens; M visual semantics | Labels/icons/patterns accompany colour. Risk is a forecast, pass completion may be declared, not green observed output by implication. G2. | + +## Rhythm wizard and focus (§4–5) + +| ID / requirement | Existing and disposition | Gap, dependency/risk and approach | +|---|---|---| +| 4.1 Visual conversational/skippable/resumable setup; four lifestyle choices | R onboarding patterns; N Writer setup state | No chatbot persona or full-/part-time identities. Save optional wizard draft without forcing a plan. G3. | +| 4.2 Paint weekly time slots/protected time/session types/rough milestones | R P day capacity; N intervals/exceptions | Add timezone-aware intervals + protected/excluded periods; touch/keyboard alternative to painting. G3. | +| 4.3 Write whenever possible; no fixed weekdays or mandatory daily targets | R nullable target words P; M validation/model | Current controller/service require a day. Separate flexible availability from zero opportunity; no fabricated daily obligations. G3. | +| 4.4 Detect manuscript/progress and reliably prefill | R C accepted state/W revision states | Use coverage-labelled current baseline and declared state; never infer historic effort or phase completion. G1/G3. | +| 4.5 Proposed plan preview before saving | R P rebalance preview; M create flow | Existing setup saves then generates. Introduce side-effect-free proposal before durable plan activation; revision token on approval. G3. | +| 4.6 Changes/holidays/exceptions, suggestions approved/ignored/dismissed | R P preview/apply; N exceptions/dismissals | Preserve past plan versions, no silent auto-rebalance; handle DST/travel. G3. | +| 5.1 Start sessions from dashboard/timeline/Word/future Editor | R D/C channels; N session contract/entry points | Shared session ID with source-neutral events, capability-gated native commands. G4. | +| 5.2 20/30/45/60/custom durations; six objective types | R P estimated minutes only; N session settings | Do not reuse planned schedule item as actual timer. Draft/revise/plan/editorial/publication/promotion selectable. G4. | +| 5.3 Optional five-minute recharge/reflection and next note | R W note conventions; N session breaks/note | Private-by-default note; break duration separate; no mandatory interruption. G4. | +| 5.4 Focus mode with discreet timer/pause/extend/finish; no mid-sentence modal | R PWA maximise patterns; N lifecycle UI | Monotonic duration accounting, browser sleep/reload recovery, non-modal expiry. G4. | +| 5.5 Focus/open linked Word and navigate chapter when permitted | R C validated navigate; N opening/OS focus contract | Current range selection is not a general safe open/focus/placement API. Author intent, identity and capability checks; Windows acceptance. G4. | +| 5.6 Notifications respect browser/OS/consent | N permission-aware delivery | Progressive enhancement; silent timer remains usable if denied/unsupported. G4. | +| 5.7 Planned/elapsed/observed activity/interruptions recorded separately; no attention claim | R ephemeral presence; N durable session transitions | Manual interruptions vs inferred inactivity distinct. Timer running ≠ continuous concentration. G1/G4. | + +## Journey and manuscript integration (§6–7) + +| ID / requirement | Existing and disposition | Gap, dependency/risk and approach | +|---|---|---| +| 6.1 Full-width zoomable history-left/Today/future-right, day/week/month/book | R V interaction patterns; N real-time calendar | Narrative Timeline data is unsuitable as author time. Bounded date-range projections and accessible list view. G4. | +| 6.2 Interactive days/milestones/chapter/scene drill-down | R V routes; N activity/milestone aggregation | Drill to coverage-qualified events and accepted manuscript version where retained; no unsupported past Reader reconstruction. G4. | +| 6.3 Editable future targets/dependency preview/optional reforecast | R P preview/apply; N dependency planning | Preview changes against plan version; approval before application. G3/G4. | +| 6.4 Parallel tracks: draft/structural/line/proof/editorial/publish/marketing/custom | R single revision status; N independent ManuscriptPass | Multiple passes can touch same chapter; statuses explicit and separate from scene workflow. G4. | +| 6.5 Chapter-pass matrix four states with provenance; iterative and sequential authors | N pass state/history model | No inference of reviewed/complete from edits; maintain declaration actor/time/source. G4. | +| 7.1 One ingestion contract for Companion and future Editor | R C stable IDs/reconciliation; N ledger adapter | Server appends accepted transitions; future Editor calls same acceptance boundary. Preserve existing wire contracts. G1. | +| 7.2 Audit GUIDs/Reader/checkpoints/reconciliation before alteration | R completed in this audit | Maintain canonical source and conservative structural review. No replacement import or second manuscript store. G0/G1. | +| 7.3 Idempotent events with session/document/chapter/scene/actor/source/times/counts/snapshot refs | R C request/revision/session IDs; N durable event receipts | Latest request check is not permanent idempotency. Unique scoped event key + payload hash, transactional acceptance; server stamps actor/receipt. G1. | +| 7.4 Offline queue/retries/clock skew/repeated sync | R C retry guards; queue class unused; N production outbox | Persist protected bounded observations before send; exact retries; preserve capture time uncertainty and interval gaps. G1. | +| 7.5 Switching/renames/moves/conflicts | R C manuscript/session IDs/native hints/move detection | M immutable old/new associations; don't attribute a moved paragraph as new writing; copied IDs/multiple devices must conflict safely. G1. | +| 7.6 Immediate baseline, no fabricated history; preserve native compatibility | R C current accepted source; M baseline onboarding | Snapshot present-day state; historic imports separate evidence class. Server-only acceptance capture can benefit legacy clients first. G1. | +| 7.7 Compact seven states and relevant actions | R S/D presence/details; M state reducer | Not installed / disconnected / connected-unlinked / syncing / ready / stale / error, with explicit capability/installation uncertainty. G2. | + +## Displays, insights and collaboration (§8–10) + +| ID / requirement | Existing and disposition | Gap, dependency/risk and approach | +|---|---|---| +| 8.1 Prominent permission-aware Detect Displays | R D getScreenLayout; M placement | Promote to Display Setup; user gesture requests permission; no automatic prompt on page open. G2. | +| 8.2 Visual geometry and Word/PlotDirector/reference/spare roles; 1–4+ | R screen enumeration and bounds; M chooseLayout | Replace >=3 “three-screen” policy with arbitrary role mapping; geometry display and manual editor. G2. | +| 8.3 Saved laptop/docked profiles/topology changes/manual fallback | R one local preference object; N profiles/lifecycle | Device-local profile keys, match/check topology, repair vanished targets; do not assume screen index stable. G2. | +| 8.4 Explain permissions/window restrictions; no irrelevant actions without document | R browser fallback/error handling; M UI | Never claim browser positions Word; separate browser window placement from native capabilities. G2/G4. | +| 9.1 Conventional statistics; independent schedule/session/workflow/mix/time dimensions | R current statistics; N historical projections | Availability vs preference distinct; explicit objective vs inferred edit pattern distinct. No AI narration. G5. | +| 9.2 Enough-quality data, sample size/uncertainty/factual wording | N qualification rules | Versioned eligibility, gaps, minimum sample window; suppress unsupported averages. G1/G5. | +| 9.3 Optional descriptors, no diagnoses/identities | N profile controls | Author can disable; no fixed labels based on availability. G5. | +| 9.4 Infrequent explainable/dismissible suggestions; no automatic schedule change | R P preview; N insight state/dismissal | Persist dismissal/cooldown and data basis; no unrequested plan mutation. G5. | +| 10.1 Author-owned contributor assignments, overlapping phases/status/milestones | R A invitations; N scoped assignments | Chapter/book/pass grants and external-contact records; do not grant project-wide collaborator as shortcut. G5. | +| 10.2 Manual reports distinct from captured edits | R P Done declarations; N actor/provenance model | Attribute imports/system/author/collaborator separately; an authenticated account does not prove who typed in Word. G1/G5. | +| 10.3 External milestones/feedback import first; integrated edit attribution later | R attachments/notes; N editorial import workflow | Preview/import with source, effective/receipt dates and idempotency; no collaborator adoption requirement. G5. | +| 10.4 No unrelated books/private notes/research access | R A project isolation; N granular authorisation | Endpoint/procedure/SignalR/export tests for chapter/book restrictions; default deny. G5. | + +## Reporting, architecture and acceptance (§11–16) + +| ID / requirement | Existing and disposition | Gap, dependency/risk and approach | +|---|---|---| +| 11.1 Date/chapter/pass/contributor report filters | R export infrastructure; N activity reporting | Same authorised bounded projections as dashboard; link reproducible query/version basis. G5. | +| 11.2 Days/qualified durations/gross/net/version growth/chapter/milestone/editorial/coverage | R current state and sparse H; N historical report | Separate planned/observed/inferred/declared/imported sections and incomparable scopes. G1/G5. | +| 11.3 Concise overview/detailed evidence report | R export patterns; N report composition | Redactable preview, explicit exclusions, evidence references and coverage warnings. G5. | +| 11.4 Future sealed PDF: ID/time/scope/quality/cryptographic signature/optional QR | N report registry/signing/verification | Separate security review, key custody/rotation/revocation and privacy-preserving verification. Not a logo/hash-only substitute. G6. | +| 11.5 Integrity ≠ human-only authorship; no AI-free certification | N evidence/report language controls | Enforce in templates/tests; imports/declarations visibly separate. G5/G6. | +| 11.6 Redaction/privacy/retention/export/deletion before production capture | R account/export patterns; N activity policy | Decide data minimisation, snapshot retention, report verification disclosure and erasure handling before G1 production use. | +| 12.1 Append-only versioned records + rebuildable derived read models | R SQL/Dapper; N event/projection store | Transactional append at acceptance; replay/versioned aggregation; do not mutate source events to fix statistics. G1. | +| 12.2 Candidate entities and stable keys/source/actors/UTC/local metadata/correlation/version | R IDs in C; N schema additions | Proposed schema in architecture; no migrations created/executed. G1/G3–G6. | +| 12.3 Minimal text, policy-governed diffs/snapshots | R current accepted manuscript; N optional immutable history | Counts-only cannot reconstruct prose; minimise duplicate text and disclose coverage lost after expiry. G1. | +| 12.4 Efficient bounded queries/aggregation/audit/repair | R procedures; N projection/checkpoint/repair controls | Book+time index, cursor paging, revision hashes, rebuild comparison; no whole-book JSON per dashboard card. G1/G2. | +| 13.A New author journey | R onboarding/plan forms; M | Skip/setup draft/proposal approval → usable dashboard → session. G2–G4. | +| 13.B Existing author journey | R accepted source/native/Reader; M/N session | Current baseline with coverage note → start → Word best effort → finish → event-backed summary. G1/G2/G4. | +| 13.C Irregular author journey | N flexible plan mode | No fixed weekday validation or empty-week failure display. G3. | +| 13.D Iterative author journey | N parallel passes | Independent Chapter 35 drafting and Chapter 8 revision with no status collision. G4. | +| 13.E Editor journey | R A only project-wide; N scoped editorial | Assignment/report first, integrated edits later; no private-note access. G5. | +| 13.F Provenance journey | N report scope/preview/export | Accurate evidence levels first; signed export only G6. | +| 13.G Display journey | R D detection; M | Detect/grant/assign/save/fallback across arbitrary monitor counts. G2. | +| 14.1 Ribbon/theme/responsive/PWA/routes/no-document controls | R S/D; M W | Browser acceptance matrix in G2; preserve legacy and Context/Intent URLs. | +| 14.2 No daily targets/available opportunities only | R nullable targets; M validation/P | Flexible and regular plans tested including holidays and no availability. G3. | +| 14.3 30-minute session pause/extend/complete, honest time | N lifecycle | Fake monotonic-clock and real browser recovery tests; non-modal expiration. G4. | +| 14.4 Parallel passes/no edit-induced completion | N pass transitions | Assert independent status and explicit actor/source. G4. | +| 14.5 Offline/duplicate no inflation; gross/deletion/net fixtures/format-only | R conservative C; N durable ledger/outbox | Retry across restart, old-key replay, conflict, moves, split/merge and tokenisation fixtures. G1. | +| 14.6 Coverage/source/navigation/display 1–4+/denied permission | R routes/discovery; M/N history | Cross-device coverage and permission-denied/browser unavailable tests. G1/G2. | +| 14.7 Insight thresholds/dismissal; no AI-free claim | N | Deterministic qualification/dismissal/report tests. G5/G6. | +| 14.8 Existing Word/Writer regressions | R existing harness/browser/native suites | Serial build/harness plus bounded feature and Windows acceptance at each affected gate. | +| 15 Gates 0–6 and per-gate testing/rollback/Development approval | R repository operational procedures | Phase plan below follows baseline sequence; no production authorisation and no gate automatically deploys. | +| 16 Historical capture, maps, permissions, displays, retention, components, milestones/imports | R this investigation | Findings in inventory/activity/UX; genuine product questions isolated in decisions document. Unknowns are not invented features. | + +The proposed architecture remains provisional as required by the baseline. Existing implemented functions are reusable foundations, not blanket acceptance of their unchanged UI, evidence meaning or access model. diff --git a/Docs/Investigations/Writer2Audit/03-Activity-Capture-Assessment.md b/Docs/Investigations/Writer2Audit/03-Activity-Capture-Assessment.md new file mode 100644 index 00000000..8ba1ea4e --- /dev/null +++ b/Docs/Investigations/Writer2Audit/03-Activity-Capture-Assessment.md @@ -0,0 +1,84 @@ +# Activity Capture Assessment + +## Conclusion + +The application can establish **what accepted manuscript state it holds now**, how paragraph/scene/chapter identities were reconciled at the latest transition, and when particular captures, validations or selected application operations were recorded. It cannot establish a complete past sequence of writing, continuous focus time, every added/deleted word, or the human origin of the prose. Authentication attributes an operation to an account/installation; it does not prove who physically typed it. + +These limits must be visible in dashboards and reports. An import baseline is pre-existing manuscript content, not newly written output. “Last synchronised” and “last changed” are different claims. + +## Four evidence categories + +**Recorded** means retained by the inspected current system, subject to overwrite/deletion below. **Transient** means available during operation but not retained as a historical activity record. **Inferred** means a limited conclusion derivable from evidence with a stated interval/scope. **Unavailable** means the current records cannot substantiate the claim. + +| Question | Recorded and retained | Transient operational evidence | Reasonable inference | Cannot currently establish | +|---|---|---|---|---| +| Current manuscript and timing | `BookParagraphManuscripts.Payload`, revision, last request, snapshot hash, payload `UpdatedUtc`; current `SceneManuscriptSources` text/counts and row dates | Incoming snapshot/chapter payload before overwrite | Accepted state existed by server acceptance/capture time | Actual sentence creation time; all intervening manuscript states | +| Paragraph changes and identity | Current `ParagraphOccurrence` GUID, NativeId, Text, PreviousText, Change, WasMoved, Resolution, neighbours/ordinal/positions; latest evidence anchor states | `ParagraphComparison.Removed` and old state in reconciliation | A matched paragraph differs between the two compared observations; movement is a reconciliation result | Durable timestamped per-paragraph edit history; previous states of deleted paragraphs after overwrite | +| Words added/removed/net | Current word statistics and some previous paragraph text; no retained gross-count ledger | Before/after accepted text available in full/chapter reconciliation | Net difference between two known, comparable retained snapshots; snapshot-diff additions/deletions if both full states and a stated algorithm exist | Total typing/deletion activity, edits undone before sync, all historic gross additions/deletions | +| Chapter/scene activity | Latest paragraph assignment, chapter headings/checkpoints; scene latest source, workflow actual words/LastWorkedOn | Live cursor and current validated chapter/scene, old/new mapping during reconciliation | Change interval can be associated with a chapter/scene if mappings are valid; current cursor means location, not editing | Time spent editing every chapter; current mappings as proof of historical ownership | +| Writing session boundaries/time | Schedule items store planned date/estimated minutes and declaration of Done/CompletedDateUtc | Word open/close, activation, heartbeat, native session/revision, browser window connection times; agent diagnostic stopwatches | At most a connected/observed interval while telemetry exists | Retained actual session duration; continuous concentration; precise pauses, interruptions or offline work time | +| Drafting versus revision | Current revision status; author-entered plan task type | Nature of a compared content change | A replacement/deletion-heavy change pattern can be labelled inferred revision-like activity with caveats | Intent, definitive drafting/revision classification or automatic phase completion | +| Offline changes | Latest Word file may later supply an accepted state | In-memory capture/retry/cache while processes survive; Word's own saved file | Changes occurred between last accepted state and later observation; exact event time may be unknown | Every offline action, offline sessions, guaranteed restart-safe delivery of all observations | +| Duplicate events | Latest request identity / revision checks; onboarding capture identity+payload hash; current chapter validations | Pipe sequence rejection, pending request acknowledgements and retry state | Current paths guard many repeated/stale submissions | A permanent globally deduplicated writing-event history, particularly old-key replay after later changes/restarts | +| Prior manuscript versions | Original retained import capture, discrete backup/restore-point payloads, latest accepted state; latest previous-text fields | Full prior state loaded for save; comparison removed rows | Some discrete earlier accepted/import states may be recoverable where complete snapshots exist | Arbitrary historical date reconstruction or continuous provenance from sparse backups | +| Author/editor/system attribution | ProjectActivity user on selected app actions; capture user; native grant/installation/account context | Authenticated request user and source, active session | Account submitted/accepted a particular operation | Sole physical authorship, AI-free text, external editor identity from an unlabelled imported file | + +## What the implementation actually observes + +`PlotDirector.NativeCompanion/Vsto/WordAdapter.cs` subscribes to document open/change/activation, selection, before-save and before-close. `CaptureSelection` samples cursor range, document length and Saved state. It increments a local revision on length changes or saved→dirty transitions; `BeforeSave` also invalidates affected work. A periodic probe covers some edits that do not raise selection changes. Later bounded chapter reads/fingerprints detect content differences, including same-length edits. + +These are deliberately coalesced lifecycle observations. They are not per-keystroke notifications or a durable Word Track Changes stream. A revision increment can reflect a save/lifecycle event and cannot be counted as one prose edit. The timer in the add-in schedules responsive COM work; it is not a writing-focus timer. Chapter timing metrics measure synchronisation performance, not time spent writing. + +`Agent/SessionManager.cs` keeps instances/documents in memory, rejects stale sequence/revision, and clears document work on detach/change. `ParagraphSnapshotCache` is in memory, bounded to eight entries / approximately 32 MiB of text and scoped to authentication/manuscript. It optimises deltas; it is not a local snapshot archive. `CompanionStateStore` persists DPAPI-protected account credentials/preferences/bindings; it does not persist a writing-event journal. + +`DeferredWorkQueue` is a durable metadata foundation with capacity 128. It coalesces newer work for a manuscript/scene and stores no prose. The source explicitly says it is not attached to a sender; production code has no construction/use reference. Its portable queue tests do not establish end-to-end offline activity capture. A later sync can reconcile final offline edits, but cannot recover deleted/undone intermediate work or session timing that was never observed and saved. + +## Identity and reconciliation limits + +`Protocol/Manuscript/ParagraphIdentity.cs` explicitly treats Word `w14:paraId` as a document-part hint. PlotDirector occurrence GUIDs are the canonical identity. Matching uses native IDs, unchanged sequence, unique text/context and neighbour checks; copy/paste duplicates, splits/merges and uncertain rewrites can remain ambiguous. `WasMoved` uses order analysis to distinguish moves from simple insertion-induced index shifts. + +`ParagraphManuscriptEngine.Reconcile` applies current rows, retains/reviews evidence and assignments conservatively, and updates snapshot capture time. PreviousText belongs to the latest comparison and may equal current text for unchanged matched rows. A high count of PreviousText fields does not imply that many edits. Removed rows returned by comparison are not an append-only tombstone list in `ParagraphManuscript`. + +The `Undo` collection is bounded layout history (roughly 1–12 layouts depending on manuscript size). It stores assignments, scene/chapter layout and event positions under a matching snapshot hash, not all old paragraph prose. It is cleared when content hash changes and for certain evidence actions. It cannot reconstruct old manuscript text. + +Chapter assignments use canonical IDs plus heading occurrence GUIDs and accepted heading windows, including excluded/canonical-zero sections. Changed-chapter merging requires a recognised heading, complete evidence, correct base revision and coherent adjacent boundaries. Cross-chapter moves, new/deleted headings and ambiguous identity require structural review. Store old and new associations in future activity; joining old events solely to today's chapter/scene layout would rewrite their meaning. + +## Timestamp and retention semantics + +| Field/store | Meaning | Retention/claim limit | +|---|---|---| +| `ParagraphManuscript.UpdatedUtc` inside Payload | Engine bootstrap/reconciliation snapshot capture time | Book-level accepted capture, not per-paragraph creation. Structure-only saves can advance revision without a new prose change. | +| `BookParagraphManuscripts.UpdatedUtc` column | Latest database row save, including mode preferences | Not a reliable prose change time. Metadata checkpoint updates can change Payload without advancing the content revision. | +| `ChapterCheckpoint.LastSuccessfulSyncUtc` | Successful acceptance/validation, including unchanged text | One latest durable checkpoint, not the date the author wrote that chapter. | +| `BookChapterValidations.ValidatedUtc/ExpiresUtc` | Server acceptance and current-session physical position lease | Updated per book/chapter/user/session; expiry is 12 hours, expired rows pruned on relevant acceptance/reuse. A retained expired row is not valid live evidence. | +| `OnboardingManuscriptCaptures.CreatedUtc` + PayloadHash | Server receipt/retention of a preview capture | `IsCurrent` changes; older captures can remain. Not a version at each subsequent sync. PayloadHash is an integrity digest, not an external signature. | +| `ManuscriptDocuments.LastOpenedUtc/LastSyncUtc` | Latest binding operation times | Latest values only, not a session/open history. | +| `SceneWorkflow.LastWorkedOn`, DraftedDate | Editable workflow dates; legacy companion word-count procedures can write date values | Date precision; can be author-entered or set on sync. Cannot treat as measured activity days or duration. | +| `WritingScheduleItems.CompletedDateUtc` | Server time an authorised user marks planned task Done | Declared task completion, no measured session duration. Regeneration/deletion can remove it. | +| `ProjectActivity.CreatedDateUTC` | Time selected app action was recorded, with optional user/entity | No before/after prose, coverage contract or writing idempotency key. Not every database path calls it. | +| `ProjectRestorePoints.CreatedDateUtc/JsonData` | A discrete recovery export and its creation time | Manually/safety-created, deletable, limited manual capacity; no guaranteed cadence or continuous chain. | +| App/native diagnostic logs | Operational troubleshooting, correlation and timings | No audited long-term retention or complete event contract. Do not use as provenance of all work. | + +`WordCompanion_Scene_UpdateWordCount` (SQL 059) overwrites current actual word count and a date-valued LastWorkedOn; runtime word-count update (097) uses the server UTC date. Neither preserves deltas. `ManuscriptTextStatisticsService` computes current deterministic counts; no additions/deletions are retained by that calculation. Word and server token counts must not be assumed identical. + +## Development evidence, without historical overclaim + +SELECT-only results are preserved alongside this assessment. The relevant stores are non-temporal; canonical paragraph state, scene sources, schedule items and project activity are not tracked by CDC. At inspection: + +- 14 current manuscript rows; 118,399 current paragraphs; 50,743 PreviousText fields and three latest Modified annotations. These are aggregate current annotations, not a count of past edits or distinct real books. Development fixture origin was not inferred. +- 467 retained chapter-validation rows, all expired. Retention here demonstrates rows remain until pruning, not a historical activity archive. Last retained validation was 13 November 2026, 22:09:15 UTC. +- One onboarding capture dated 8 November 2026, 21:05:14 UTC; one restore point dated 9 November 2026, 14:57:07 UTC, containing one paragraph manuscript snapshot. These establish discrete source states only. No full reconstruction of author prose was attempted or exported. +- 54 project activity rows, dominated by location create/update actions, plus project/book/export/merge records. No evidence in those aggregates establishes a complete sequence of native writing edits. +- One active writing plan, no schedule items, Owner-only current access rows. The absence of schedule items is not proof schedule generation is unimplemented; it exists in code/procedures. + +No arbitrary-date manuscript reconstruction is warranted. With author approval in a future feature, a specific retained import or restore point could be offered as a labelled historical source. Comparing two such states establishes a difference over their observation interval; it does not establish when or by whom each intermediate change occurred. Database backups outside the app were not restored/inspected and are not assumed available to authors. + +## Shared append-only activity: recommended measurement contract + +Capture accepted manuscript transitions on the server once, for Word and the future Editor. Native telemetry supplies optional observation/session information; server acceptance supplies authoritative receipt, actor context and accepted revision. Legacy clients can benefit from server acceptance events without a forced upgrade; they simply have lower temporal coverage. + +Each event must identify provenance class, source, authenticated submitter and claimed contributor separately, document/manuscript/book, old/new revision and snapshot hashes, affected paragraph GUIDs and historical chapter/scene links, observed time and precision/clock quality, received UTC, schema/metric version, optional focus session, immutable idempotency key and correlation/causation IDs. Baseline, content transition, mapping change, validation, import/declaration and session transition are different event types. + +Gross counts should mean **token insertions/deletions between accepted observed states under algorithm X**, not keystrokes. Define tokenisation once and version it. For comparable scope, `added - deleted = after words - before words`. Replacements count both sides; stable paragraph moves do not become drafting; split/merge and punctuation/whitespace cases need explicit fixtures. Formatting-only changes do not count as growth. Ambiguous identity or missing baseline produces partial/unknown coverage, never invented zeros. Imported baseline content is excluded from “words written this period”. + +Keep observed text change, timer elapsed, declared objective and inferred workflow pattern separate. A document can be edited while several passes exist; do not allocate all output to every pass or simultaneous session. If linkage is uncertain, leave it unassigned and offer declaration rather than silently doubling totals. Rebuild statistics from retained raw events; snapshot/diff text retention determines whether those counts remain independently recomputable. Full history/reconstruction is an optional policy-governed capability, not a consequence of append-only counts alone. diff --git a/Docs/Investigations/Writer2Audit/04-Architecture-Recommendations.md b/Docs/Investigations/Writer2Audit/04-Architecture-Recommendations.md new file mode 100644 index 00000000..5e48d738 --- /dev/null +++ b/Docs/Investigations/Writer2Audit/04-Architecture-Recommendations.md @@ -0,0 +1,107 @@ +# 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: + +```mermaid +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. diff --git a/Docs/Investigations/Writer2Audit/05-UX-Gap-Analysis.md b/Docs/Investigations/Writer2Audit/05-UX-Gap-Analysis.md new file mode 100644 index 00000000..0c700614 --- /dev/null +++ b/Docs/Investigations/Writer2Audit/05-UX-Gap-Analysis.md @@ -0,0 +1,49 @@ +# UX Gap Analysis + +The written specification is the approved design direction. No accompanying approved mockup images were supplied. This assessment uses current Razor/JavaScript/CSS, a rendered isolated synthetic Writer fixture at 1440×1000 and 390×844, and the existing theme/navigation browser suite. It is not a claim of reviewing an unseen mockup or the current authenticated Development author's private screen. + +Evidence: [desktop viewport](CurrentWriter-Desktop-Fixture.png), [small viewport](CurrentWriter-Small-Fixture.png). All titles/content are synthetic fixture data. These screenshots illustrate current UI only; they are not proposed Writer 2.0 designs. + +## Current experience and reusable visual language + +The current Writer inherits the established warm surface, typography, rounded buttons/cards, project/book selectors and direct Writer navigation in the shell. Existing themes, outlined/primary action conventions and state pills already fit a calm author-facing direction. Do not replace these with a generic admin template, new colour system or chatbot panel. + +At desktop width, the first viewport is dominated by the heading, plan links/local project selector, the large “Context | Word | Intent” launcher and no-schedule prompt. Actual writing work begins low in the viewport. At phone width, the three schedule actions and duplicated selection controls stack; the workstation panel starts below them and continues beyond the viewport. The layout wraps, but wrapping alone does not meet the first-viewport information contract. + +Scene queues and links already provide practical work destinations. The issue is that all queues, task tables, status cells and reminders remain concurrently expanded. The Writer ribbon is selected but has no dedicated command category in `ApplicationRibbon.Categories`. Overview/Journey/Plan/Focus/Workspaces/Reports need a coherent contextual navigation model. + +## Required changes + +| Area | Verified current behaviour | Proposed direction and acceptance | +|---|---|---| +| Common selection | Shell project/book selection plus local project dropdown in Writer; dashboard service only project-scoped | One authorised selection context in shell; consume bookId end-to-end. Never seed the displayed book from the first queued scene when the author selected another book. Book change updates cards, queues, presence and chart scope consistently. | +| Ribbon | Direct Writer navigation already exists; general project/book/story categories and contribution helpers | Add the six Writer destinations using existing ribbon contribution/category conventions. Maintain keyboard focus, active state, mobile overflow/collapse and PWA maximise. Preserve legacy route parameters and browser back navigation. | +| Overview | Large setup/workstation block and long task/queue sections | Full-width Overview: book context, current task/scene, next available opportunity, compact Companion state, then a small set of useful indicators. If no plan, offer a quiet optional setup/skip action while leaving work accessible. | +| Workspaces | Four simultaneously rendered queues + reminders | Five tabs: Write Next / In Progress / Revision / Final Pass / Story Health. Render active tab efficiently; retain counts, filters, blocker/priority states and direct scene links. Include Finished work as a filter/destination so renaming Polish does not hide completed scenes. | +| Story Health | Reminder rows; existing warnings/metrics/review pages elsewhere | Actionable grouped issues with a real destination. Show summary and reason on demand, not raw intelligence JSON or a forced review process. Respect persisted review priority and optional-review semantics. | +| Activity indicators | Task completion counts and projected finish date; no history ledger | Show opportunity-relative days, gross additions/deletions/net, declared pass progress, milestone forecast, optional compact journey only where supported. Distinguish baseline/unobserved interval from zero output. Do not render a decorative graph with invented history. | +| Charts | Current Writer lacks rich historical charts; Analytics has clickable scene charts/table fallback | Reuse theme and drill-down patterns for activity calendars, word-change bars, chapter-pass matrix and timeline. Every meaningful datum opens its date/scope/evidence or chapter/scene. Include data table/list, axis units, samples/coverage, text labels and keyboard targets. | +| Status meaning | Generic presence plus detailed launcher values | One compact state reducer with not-installed evidence, disconnected, linked/unlinked, syncing, ready, stale/error. “No live connection detected” when installation cannot be known. Expand details on action; no diagnostics wall in first viewport. | +| Companion actions | Start/Reapply/Open Context/Open Intent and layout controls remain prominent while disconnected | Display relevant actions only; an unlinked connection offers linking, a stale state offers refresh/details, a ready document offers focus/navigate/session. Context/Intent manual access may remain available as reference work but must not imply Word is linked. | +| Display Setup | Small Detect Displays alongside left/primary/right selectors; >=3 special layout | Prominent setup action opens a visual geometry/role assignment surface. Arbitrary monitor counts, laptop/docked profiles, research/spare roles, lost-display correction, permission-denied and manual choices. Explain that browser popups may be blocked and Word placement requires native support. | +| Rhythm wizard | Single substantial form, weekday/capacity/deadline validation; save then generate | Short optional visual steps, progress/resume/skip, keyboard-editable weekly grid and flexible-mode choice. Prefill known current state with evidence label. Show proposal before applying, capacity/risk facts and holiday exceptions. No mandatory daily target. | +| Focus Sessions | Session brief export, no timer/lifecycle | Non-modal discreet timer with objective, pause/resume/extend/finish, optional break and note. Desktop focus hides nonessential chrome while preserving exit/Escape and accessibility. Never say “30 minutes focused” merely because the timer ran. | +| Writing Journey | Narrative story Timeline exists; no real writing calendar | Separate author-calendar workspace with Today, observed history and planned future. Zoom/scroll with virtualised bounded data, accessible list alternative, editable future proposal preview and independent pass tracks. Never reuse fictional story dates as writing dates. | +| Pass state | Single scene revision status | Chapter/pass matrix with actor/source and explicit four-state transitions. Distinguish declared reviewed/complete from observed change. Drafting a late chapter and revising an early one remain visible concurrently. | +| Insights | Current story metrics; no qualified writing-pattern analysis | Small optional factual insight cards with denominator/window/uncertainty, dismiss and no auto-plan action. Show availability constraints separately from stated preferences. With insufficient data, omit the insight rather than producing encouragement. | +| Collaboration | Project-wide collaborator management | Author assignment/status and external milestones first; granular contributor view later. Private author notes remain private. Use named attribution only when supported by the evidence and consent. | +| Reports | Existing exports and writing guide | Scope/preview/export with short overview and expandable evidence/limitations. Redaction before generation. Separate imported history and declarations. Later signature verification explains integrity without AI-free language. | + +## Responsive, PWA and accessibility contract + +Use existing application theme tokens in modern-light, modern-dark, warm-light and warm-dark. Progress colours have functional meaning: observed progress green, forecast risk amber, actionable blocker red, unscheduled/not started grey. Keep explicit labels/icons/patterns and sufficient contrast; author-declared completion must not be presented as directly observed work solely through colour. + +On desktop, use available width for meaningful work and compact indicators, not an expanded administrative control grid. On laptop, reduce secondary detail before compressing charts into illegibility. On small screens, prioritise current work/start session/next opportunity; use horizontally navigable accessible workspace tabs and a list alternative for the journey. Do not require precision dragging for slots or milestones. Provide keyboard editing, visible focus, screen-reader names, reduced-motion support and large touch targets. Avoid unexpected auto-scroll while the author is reading or selecting text. + +Preserve the installed-PWA shell and maximise conventions. Existing service worker deliberately supplies no offline manuscript caching; do not imply offline editing/history because the app is installed. Timer completion must not seize focus from Word or introduce a modal. Notifications and cross-window focus are permission/capability-bound enhancements with an always-usable in-app fallback. + +## Design and validation limits + +The theme/navigation browser suite exercises synthetic Context/Intent content, four themes, full/embedded windows, browser/simulated PWA and small/desktop widths. It supports reuse of those conventions; it does not certify the proposed dashboard, OS notifications, real monitor placement or native Word focus. Further acceptance must include real Windows/Word, real installed PWA, denied permissions, single/laptop/docked/4+ monitor topology, keyboard/screen-reader use and populated long-book datasets. + +No new UI, CSS, controls, mockups or application assets were implemented during this audit. diff --git a/Docs/Investigations/Writer2Audit/06-Phased-Implementation-Plan.md b/Docs/Investigations/Writer2Audit/06-Phased-Implementation-Plan.md new file mode 100644 index 00000000..911d4c93 --- /dev/null +++ b/Docs/Investigations/Writer2Audit/06-Phased-Implementation-Plan.md @@ -0,0 +1,130 @@ +# Phased Implementation Plan + +This is a proposal, not authorisation to implement or deploy. Gate numbers follow specification §15. Use independent feature flags/capability negotiation so useful increments ship without replacing all Writer functions in one release. No production changes are authorised. + +## Common gate requirements + +- Build `dotnet build PlotLine.slnx`, then run `dotnet run --project PlotLine.Tests/PlotLine.Tests.csproj` serially. The executable harness is the gate; `dotnet test` is not a substitute. +- Add behaviour-level tests for new durable contracts and risks; do not rely solely on string assertions or add tests that merely mirror a UI implementation. Revise existing source-contract assertions when deliberately superseding old layout, keeping functional coverage. +- Run focused browser/PWA checks for changed journeys; include four themes, keyboard/touch, small/laptop/desktop, slow/failed requests and no-data/partial-data states. Simulated PWA is not Windows installed-PWA acceptance. +- For native changes: portable protocol/agent tests plus actual Windows VSTO compile/package/upgrade and real Word responsiveness/capture/focus qualification. Old capability profiles remain supported. Linux tests cannot certify COM or OS window restrictions. +- SQL integration uses a disposable verified test database with synthetic fixtures. Read relevant scripts before running them; tests that roll back still write and are outside this audit. Never run them on Production. Recheck repository `Docs/Codex/Testing.md` and `Database.md` during implementation. +- Proposed schema changes become new forward-only migrations only after implementation approval. Verify effective Development target, back up before applying, apply narrowly in order and verify object/permission compatibility. Document old-application compatibility; application rollback does not undo SQL. +- Before a Development rollout follow `Docs/Codex/Deployment.md`: no active imports/analysis, deliberate commit/build identity, release backup and authenticated smoke. Preserve existing manuscripts and user work. Log acceptance results per gate. Production requires separate explicit authorisation. +- Feature rollback must preserve accepted data, events/receipts and pending outbox entries. If old code cannot capture activity, mark the resulting coverage gap; never present rollback time as fully observed history. + +## G0 — audit and decisions + +**Objective/deliverables:** the seven documents, full requirements mapping, schema/retention recommendation, evidence limits and current regression record in this directory. + +**Acceptance:** product owner can distinguish working reusable capabilities, new development and unverified Windows requirements; no fabricated historical provenance; no code/data changes, migration or deployment. Resolve blocking retention/privacy/scope decisions before production capture. No schedule or report claims based on old state that cannot support them. + +**Current result:** audit delivered; see Verification.md for actual commands and results. This gate ends here. + +## G1 — reliable capture foundation + +### G1a: server acceptance, baseline and read-only evidence view + +**Dependencies:** retention policy and scope/actor semantics; inventory of latest accepted procedures and all full/selective acceptance paths; existing entitlement/access decisions. + +**Deliverables:** versioned event envelope; durable scoped receipt uniqueness; atomic canonical-save/event append; baseline event for current accepted state; separate unchanged-validation/mapping/declaration events; versioned word diff; coverage metadata; minimal bounded evidence query; projection checkpoints/replay. Optional retained snapshot/diff store only within approved policy. Extend backup/restore/delete format and permissions deliberately. Supply an administrative reconciliation/read tool with no manuscript-specific logic. + +**Acceptance criteria:** + +- Existing accepted manuscript and scene/evidence GUIDs survive; first baseline contributes zero new writing output. No automatic reimport/reanalysis. +- Exact retry before/after restart and after newer events returns the original receipt; same key/different payload rejected. Parallel accepted transitions cannot double-count. +- Canonical save + event are atomic under injected failure. Downstream notification/projection failure is recoverable without lost accepted events or duplicate totals. +- Gross additions/deletions/net reconcile with declared token fixtures; formatting-only unchanged text yields no word growth; zero net revision may have positive additions/deletions; moves and split/merge do not invent book growth. Ambiguity yields honest coverage. +- UTC receipt, observed precision/skew and author-local day are distinct. Old clients produce acceptance-time coverage without invented observation times. +- Rebuild produces the same aggregates/checksum; read queries are book-scoped, bounded and authorised. No dashboard GET writes or schedules AI work. +- Restore/import/copy/archive/delete/erasure scenarios preserve lineage and privacy without replaying historical content as new writing. Expired/inactive subscription and revoked native grant cases are explicit. + +**Tests:** synthetic full/chapter/no-op/mapping change; deleted/duplicate/moved/copied paragraphs, cross-chapter structure review, stale base and concurrent devices; replay/payload collision; tokenisation/control characters/Unicode/large chapter; transactional failure injection; report coverage classes; projection replay; tenant/book isolation; restore and deletion safety. Reuse `ParagraphManuscriptTests`, `ParagraphWorkflowTests`, `ParagraphChapterTests`, `ParagraphBackupTests`, `ChapterSynchronisationTests`, `ManuscriptReaderTests` and relevant SQL fixtures. + +**Risk/rollback:** new accepted-state hooks can damage the most important path. Additive schema and flag capture readers separately; preserve old endpoint responses. Keep old server compatible with added columns/tables. If capture is disabled, record a coverage boundary rather than silently resuming a complete-history claim. + +### G1b: native durable observations and offline delivery + +**Dependencies:** G1a event/receipt protocol; protected storage and negotiated native capabilities; decided offline retention/capacity handling. + +**Deliverables:** production protected outbox, acknowledgements/retry/backpressure, account/document-scoped producer identity, offline uncertain intervals and durable diagnostics. Do not claim the existing standalone coalescing queue already satisfies this. + +**Acceptance:** disconnect/edit/reconnect and restart/crash never inflate events, words or sessions; captured observations survive as designed; uncaptured intervals are labelled. Sign out/revoke/change account cannot deliver prose to a different scope. Clock skew does not reorder accepted state or manufacture duration. Old add-ins remain usable at lower coverage. Word typing/save remains responsive. + +**Tests:** native portable restart/outbox capacity/corrupt file/account switch; HTTP retries/timeouts/ack loss; real Windows offline, Word close, cancelled close, document rename/Save As, copied IDs, multiple documents/instances, same-length edits and large manuscripts. Existing native qualification fixtures must continue to pass. + +**Risk/rollback:** protected data loss or false completeness. Stop new capture if storage unsafe, retain pending entries, expose gap and manual resolution/export. Roll back agent with compatible outbox format; never discard outstanding events in an installer upgrade. + +G1a provides useful honest capture to legacy clients before G1b; acceptance-time history must remain visibly different from native observation history. + +## G2 — navigation, dashboard, workspaces and display setup + +**Dependencies:** G1a for observed indicators; existing S/D/V components. Navigation/display work can be implemented independently, but cannot display unbacked historical figures. + +**Deliverables:** contextual Writer ribbon and canonical route map; common shell book selection; progressive Overview; five queue tabs; compact Companion state/actions; bounded drillable cards/charts; Display Setup with arbitrary screen-role profiles and fallback. Keep current plan forms and Context/Intent links accessible. + +**Acceptance:** + +- Selected book consistently scopes queues/charts/status. Legacy Writer URLs resolve without losing context; no removal of legitimate `/Writing/Context` and `/Writing/Intent` deep links. +- First viewport prioritises current work, next opportunity and compact state at desktop/laptop/small sizes. No permanent setup wall; skip/no-plan remains useful. +- No linked document shows no misleading linked-Word layout/session actions. Absence of heartbeat is not labelled definitively not installed. +- Every available chart/issue/chapter/scene target navigates correctly, supports keyboard access and has non-colour/table equivalents. Partial history is explicit. +- Display discovery handles 1/2/3/4+ screens, negative coordinates, denied/unavailable permission, popup blocking, docking/topology changes and manual fallback. Word placement is not falsely claimed before native support. + +**Tests:** `Browser/writer-workspace.cjs`, `writer-navigation-themes.cjs`, `writer-goal-navigation.cjs`, `workspace-maximise.cjs`, `writing-context-navigation.cjs`, `writing-context-components.cjs`, `writing-desks.cjs`, `native-companion-workspace.cjs`; actual installed PWA and monitor matrix. Existing browser tests are reusable starting points, not coverage of all proposed features. + +**Risk/rollback:** UI/scope regressions and inaccessible charts. Feature-flag new routes/dashboard and restore old landing links independently; no data conversion required merely for tab/ribbon delivery. Preserve any new local profile format for safe downgrade. + +## G3 — Writing Rhythm and plan engine + +**Dependencies:** G2 navigation/selection; approved flexible-mode and calendar semantics; G1 baseline for reliable prefill; plan-version/availability/exception schema. + +**Deliverables:** skippable/resumable wizard, four schedule-fit choices, accessible weekly availability painting/manual entry, flexible mode, protected time, holidays/exceptions, milestone proposals, preview-before-save/apply and dismissal; capacity-aware scheduling and explicit timezone. + +**Acceptance:** create a plan with no daily word target and no fixed weekdays; protect personal time; save/resume/skip setup; detect existing manuscript without inventing historical work; approve a proposal before activation. Only available opportunities appear by default; holidays/unavailable days are neutral. Suggestions never mutate plan automatically. Multiple small scenes can share capacity deliberately; over-capacity/dependency conflicts are explained. Reforecast preserves historical Done/Skipped declarations and original plan versions. + +**Tests:** fixed/flexible/zero availability, crossing midnight, DST/travel, holidays and protected slots; no word target; custom session capacity; plan proposal stale-version rejection; insufficient capacity; task split accounting; completed-item preservation during regeneration; permissions and account isolation. Existing schedule service/repository tests/source contracts need behaviour-level extensions; don't assume persisted Automatic setting is a running engine. + +**Risk/rollback:** reforecast overwriting history, incompatible JSON availability and wrong local days. Keep legacy format read-compatible via adapter; version new structures, preserve original plans/items; disable new planner while old plan views remain available. No destructive conversion. + +## G4 — Focus Sessions, passes and Writing Journey + +**Dependencies:** G1 captured history/receipt semantics; G3 opportunities; independent pass/milestone/session schema; capability-gated Word commands. + +**Deliverables:** 20/30/45/60/custom sessions with objectives, pause/resume/extend/finish, optional break/note, non-modal focus mode; explicit lifecycle and qualified durations; chapter-pass matrix; zoomable calendar Journey with observed past, Today and future proposals; links from dashboard/Journey/Word and future Editor contract. + +**Acceptance:** 30-minute sprint pauses/extends/completes without interrupting typing; browser sleep/reload/crash yields honest time, not fictitious continuous concentration. Separate elapsed/pause/declared interruption/document-activity evidence. Finish is idempotent. Concurrent devices do not create duplicate sessions. Draft Chapter 35 and revise Chapter 8 concurrently with separate pass states; document edits never mark a pass reviewed/complete. Day/week/month/book views and chapter/scene drill-down work. Word navigate/open/focus is best effort and author-authorised; unsupported clients retain working fallback. + +**Tests:** fake monotonic clock/state machine, duplicate/stale transitions, background throttling/sleep/timezone changes, multiple tabs/native/browser recovery, no document/non-document sessions, optional break/reflection note privacy, dismiss/deny notifications; overlap and pass-state provenance; large timeline paging and keyboard/list access; Windows Word mid-sentence/focus/save scenarios and older client compatibility. + +**Risk/rollback:** attention overclaims, session double-counting, distracting timers, pass status colliding with scene status. Keep elapsed and evidence partitions immutable, disable session UI without erasing transitions, keep explicit pass states readable; old Writer can continue through original scene workflow. + +## G5 — insights, editorial collaboration and evidence reports + +**Dependencies:** sufficient qualifying G1/G4 data; approved retention/privacy/export rules; granular assignment permissions before collaborator login; projections and plan history. + +**Deliverables:** factual statistics and optional explainable/dismissible insights; independent behavioural dimensions; author-owned external milestones/feedback imports first; scoped integrated contributor views later; report scope/preview/redaction/export, concise overview and detailed evidence coverage. + +**Acceptance:** show sample size/window/limitations; suppress insufficient-data insights; observed availability never becomes natural preference by itself. Dismissal/cooldown persists and no insight changes a schedule. External editor updates remain declared/imported; directly captured collaborator changes are separately attributed. Assigned contributors cannot see unrelated books/private notes/research through routes, APIs, SignalR, exports or charts. Reports reconcile counts with ledger/projection version; missing/expired evidence is disclosed. No AI-free/human-only certification wording. + +**Tests:** insufficient sample/partial coverage/bias examples, deterministic statistic versions, dismissal/reappearance, actor attribution/import retry/redaction, assignment revocation, cross-book/chapter negative authorisation and export tests; selected-date/pass/contributor totals without join multiplication; expired subscription read/export access; retention expiry/deletion and restore privacy regression. + +**Risk/rollback:** privacy leakage, misleading inference and over-broad collaboration. External-report-first delivery avoids granting project-wide access prematurely. Disable integrated contributor routes until scope tests pass. Insights/read projections can be disabled/rebuilt; retain author declarations/dismissals and report audit basis. + +## G6 — signed provenance PDF and optional verification + +**Dependencies:** G5 accurate reports; approved report purpose/disclosure, signing/verification security design and explicit separate sign-off. + +**Deliverables:** report identity/timestamp/scope/evidence manifest, cryptographic PDF signature and verification; protected keys, rotation/revocation/compromise procedure, optional privacy-preserving QR endpoint, verification help text and retention policy. + +**Acceptance:** modifying issued bytes fails verification; correct issued reports validate with intended tools and appropriate certificate lifecycle rules. Public verification reveals only approved metadata, no manuscript/contributor identities by default. Redacted export and signature agree. Verification claims issuance/integrity only and explicitly excludes AI-free certification. Reports clearly state evidence gaps/imports/declarations and expired backing evidence. + +**Tests:** independent signature verification, tampering, wrong key, expired/revoked/rotated key, timestamp validation, disclosure/redaction, enumeration/rate limits, deleted/private reports, backup/key recovery and incident drill. Security review is mandatory; a logo or digest is insufficient acceptance. + +**Risk/rollback:** compromised keys or overstated assurance. Disable issuance independently of access to existing reports; publish accurate revocation/status where applicable, retain issued artifacts and key identifiers per policy. Never silently re-sign an old report as if it were originally issued under a new key. + +## Milestones and sequencing + +G1a → G1b establishes reliable evidence before dependent analysis. G2 can ship navigation, queues and display setup in small increments while showing only supported metrics. G3 produces opportunities and plan proposals. G4 adds sessions/passes/Journey. G5 needs both sufficient data and access controls; split external editorial reporting from integrated collaboration. G6 is independently optional and security-gated. + +Do not commit a calendar delivery estimate before sizing native offline work, retention/storage and scoped collaboration. These are the largest uncertainty drivers. Each milestone is independently reviewable and testable; no single deployment must replace the entire Writer interface. diff --git a/Docs/Investigations/Writer2Audit/07-Decisions-Required.md b/Docs/Investigations/Writer2Audit/07-Decisions-Required.md new file mode 100644 index 00000000..fce22e33 --- /dev/null +++ b/Docs/Investigations/Writer2Audit/07-Decisions-Required.md @@ -0,0 +1,23 @@ +# Decisions Required + +Only product/privacy/security choices that implementation cannot settle from existing requirements are listed here. Technical investigation questions from specification §16 are answered in the inventory/activity/architecture documents or explicitly marked unverified. No decision here authorises implementation. + +| Decision | Why owner input is needed | Recommended starting position / affected gate | +|---|---|---| +| Retention and consent for activity, prose snapshots/diffs, offline observations, notes and reports | Specification requires a policy before production capture but gives no durations/defaults or reconstruction guarantee. Storage/privacy and ability to recompute history differ substantially. | Minimal structured events and explicit coverage by default; detailed historical prose only under an explicit policy/author control. Decide retention duration, quotas, export/deletion and whether historical text reconstruction is a promised feature. Blocks production G1 capture. | +| Granularity and transparency of native observation | Accepted sync differences are less intrusive but cannot measure all edits; more frequent durable native observations improve intervals while increasing local data/telemetry. Requirements do not decide sampling/privacy defaults. | Start with accepted transitions, explicit focus sessions and declared interruptions. Explain offline gaps and source coverage. Approve additional observations and controls before G1b; no keystroke or continuous-attention claims. | +| Collaboration first-release scope and visibility | External milestones first is explicitly permitted; integrated collaborators require new chapter/book permissions. Existing project collaborators receive broader access. Product must choose launch commitment and what attributed activity contributors may see. | Author-entered external assignments/milestones/feedback first. Integrated contributors only after scoped authorisation; private notes/research excluded. Approve visibility of contributor identity and reports before G5. | +| Historical import/declaration policy | Existing sparse captures/backups cannot supply a complete past. Owners may want to enter previous sessions/editorial work; imported claims need visible provenance and potential evidence attachments. | Permit explicitly labelled author declarations/imports with effective and receipt dates; never merge them into observed totals without separate breakdown. Decide supported first-release import formats and correction controls in G5. | +| Session note and non-document-work privacy in shared books | Session notes may contain private creative/personal information; contributors must not gain access simply because work concerns a shared book. | Author-private notes by default; share only intentionally. Decide which aggregate activity summaries are shared, separately from manuscript access, before collaboration/report rollout. | +| Commercial packaging of new Writer features and historical storage | Existing central entitlement system supports tier decisions, but the baseline does not allocate new features/quotas. Capture blocked by expiry also affects evidence continuity. | Keep policy in SubscriptionService/SubscriptionFeature; preserve read/export access. Decide plan availability/quotas and pending-offline handling before G1 production/G5 packaging; never silently drop queued history. | +| Signed report assurance and optional public verification | Specification makes signing a later separate sign-off; no signature standard, legal/commercial assurance, public disclosure or retention promise has been chosen. | First deliver unsigned accurate evidence. Before G6 choose security-reviewed signing/certificate/key custody, verification lifetime and QR disclosure. Claim issued-report integrity only. | + +## Items that do not need another product decision + +- Writer remains in the established shell/ribbon/theme, with the six specified destinations and five specified workspace tabs. +- Flexible schedules, no mandatory daily targets, permission-aware display fallback, non-modal timers and overlapping passes are requirements, not optional questions. +- Existing accepted manuscripts/identities and legacy native endpoints must be preserved. Dapper/stored procedures and forward-only migrations are repository rules. +- Gross additions/deletions/net need versioned deterministic definitions and fixture-based validation; implementation should propose and review this technical contract rather than asking the owner to design the diff algorithm. +- “Not installed” cannot be inferred from missing heartbeat; timers cannot certify continuous concentration; sync times cannot certify when text was written; no AI-free provenance claim is allowed. +- Insight eligibility thresholds, query bounds, index design and projection cadence are technical choices to validate with representative fixtures/measurements. They must be disclosed and reviewed where they affect the product, but are not reasons to defer the read-only audit. +- Approved mockup images were not supplied. Their availability affects later visual design review, not completion of this technical audit against the written baseline. diff --git a/Docs/Investigations/Writer2Audit/CurrentWriter-Desktop-Fixture.png b/Docs/Investigations/Writer2Audit/CurrentWriter-Desktop-Fixture.png new file mode 100644 index 00000000..16928f39 Binary files /dev/null and b/Docs/Investigations/Writer2Audit/CurrentWriter-Desktop-Fixture.png differ diff --git a/Docs/Investigations/Writer2Audit/CurrentWriter-Small-Fixture.png b/Docs/Investigations/Writer2Audit/CurrentWriter-Small-Fixture.png new file mode 100644 index 00000000..b7eaf88c Binary files /dev/null and b/Docs/Investigations/Writer2Audit/CurrentWriter-Small-Fixture.png differ diff --git a/Docs/Investigations/Writer2Audit/DatabaseInventory.readonly.sql b/Docs/Investigations/Writer2Audit/DatabaseInventory.readonly.sql new file mode 100644 index 00000000..e6333cf3 --- /dev/null +++ b/Docs/Investigations/Writer2Audit/DatabaseInventory.readonly.sql @@ -0,0 +1,4 @@ +SET NOCOUNT ON; +SELECT t.name, t.temporal_type_desc, (SELECT SUM(p.rows) FROM sys.partitions p WHERE p.object_id=t.object_id AND p.index_id IN(0,1)) AS ApproximateRows FROM sys.tables t WHERE t.name LIKE '%Writ%' OR t.name LIKE '%Manuscript%' OR t.name LIKE '%ChapterValid%' OR t.name LIKE '%Activity%' OR t.name LIKE '%RestorePoint%' OR t.name LIKE '%ProjectUserAccess%' ORDER BY t.name; +SELECT t.name AS TableName,c.name AS ColumnName,ty.name AS DataType FROM sys.tables t JOIN sys.columns c ON c.object_id=t.object_id JOIN sys.types ty ON ty.user_type_id=c.user_type_id WHERE t.name IN('WritingPlans','WritingScheduleItems','BookChapterValidations','BookParagraphManuscripts','OnboardingManuscriptCaptures','ProjectActivity') ORDER BY t.name,c.column_id; +SELECT name,type_desc FROM sys.objects WHERE type IN('P','TR') AND (name LIKE '%Writing%' OR name LIKE '%ParagraphManuscript%' OR name LIKE '%BookChapter%' OR name LIKE '%Activity%' OR name LIKE '%ManuscriptCapture%') ORDER BY name; diff --git a/Docs/Investigations/Writer2Audit/DatabaseInventory.txt b/Docs/Investigations/Writer2Audit/DatabaseInventory.txt new file mode 100644 index 00000000..46917096 --- /dev/null +++ b/Docs/Investigations/Writer2Audit/DatabaseInventory.txt @@ -0,0 +1,114 @@ +Verified database: PlotDirector_Development +name | temporal_type_desc | ApproximateRows +BookChapterValidations | NON_TEMPORAL_TABLE | 467 +BookParagraphManuscripts | NON_TEMPORAL_TABLE | 14 +ManuscriptDocuments | NON_TEMPORAL_TABLE | 1 +ManuscriptEvidenceIndex | NON_TEMPORAL_TABLE | 0 +ManuscriptStructuralChapterSources | NON_TEMPORAL_TABLE | 48 +OnboardingManuscriptBuildChapterMap | NON_TEMPORAL_TABLE | 48 +OnboardingManuscriptBuildCharacterMap | NON_TEMPORAL_TABLE | 0 +OnboardingManuscriptBuilds | NON_TEMPORAL_TABLE | 1 +OnboardingManuscriptBuildSceneMap | NON_TEMPORAL_TABLE | 290 +OnboardingManuscriptCaptures | NON_TEMPORAL_TABLE | 1 +ProjectActivity | NON_TEMPORAL_TABLE | 54 +ProjectRestorePoints | NON_TEMPORAL_TABLE | 1 +ProjectUserAccess | NON_TEMPORAL_TABLE | 14 +SceneManuscriptSources | NON_TEMPORAL_TABLE | 868 +WritingIntentAssessments | NON_TEMPORAL_TABLE | 0 +WritingPlans | NON_TEMPORAL_TABLE | 1 +WritingScheduleItems | NON_TEMPORAL_TABLE | 0 +WritingSolverVersions | NON_TEMPORAL_TABLE | 4 +TableName | ColumnName | DataType +BookChapterValidations | BookID | int +BookChapterValidations | ChapterID | int +BookChapterValidations | UserID | int +BookChapterValidations | SessionID | uniqueidentifier +BookChapterValidations | ManuscriptID | uniqueidentifier +BookChapterValidations | WordRevision | bigint +BookChapterValidations | RequestID | uniqueidentifier +BookChapterValidations | ContentHash | char +BookChapterValidations | IdentityHash | char +BookChapterValidations | MappingHash | char +BookChapterValidations | Positions | nvarchar +BookChapterValidations | SourceRevision | bigint +BookChapterValidations | ValidatedUtc | datetime2 +BookChapterValidations | ExpiresUtc | datetime2 +BookParagraphManuscripts | BookID | int +BookParagraphManuscripts | ManuscriptID | uniqueidentifier +BookParagraphManuscripts | Revision | bigint +BookParagraphManuscripts | RequestID | uniqueidentifier +BookParagraphManuscripts | Payload | nvarchar +BookParagraphManuscripts | UpdatedUtc | datetime2 +OnboardingManuscriptCaptures | PreviewID | uniqueidentifier +OnboardingManuscriptCaptures | UserID | int +OnboardingManuscriptCaptures | OnboardingID | int +OnboardingManuscriptCaptures | BookID | int +OnboardingManuscriptCaptures | Payload | nvarchar +OnboardingManuscriptCaptures | PayloadHash | varbinary +OnboardingManuscriptCaptures | CreatedUtc | datetime2 +OnboardingManuscriptCaptures | IsCurrent | bit +OnboardingManuscriptCaptures | AnalysisCheckpoints | nvarchar +ProjectActivity | ProjectActivityID | bigint +ProjectActivity | ProjectID | int +ProjectActivity | UserID | int +ProjectActivity | ActivityType | nvarchar +ProjectActivity | EntityType | nvarchar +ProjectActivity | EntityID | int +ProjectActivity | EntityName | nvarchar +ProjectActivity | Description | nvarchar +ProjectActivity | CreatedDateUTC | datetime2 +WritingPlans | WritingPlanID | int +WritingPlans | UserID | int +WritingPlans | ProjectID | int +WritingPlans | BookID | int +WritingPlans | PlanName | nvarchar +WritingPlans | GoalType | nvarchar +WritingPlans | StartDate | date +WritingPlans | DeadlineDate | date +WritingPlans | AvailableDaysJson | nvarchar +WritingPlans | SessionLengthMinutes | int +WritingPlans | IncludeBlockedScenes | bit +WritingPlans | RebalanceMode | nvarchar +WritingPlans | IsActive | bit +WritingPlans | CreatedDateUtc | datetime2 +WritingPlans | ModifiedDateUtc | datetime2 +WritingScheduleItems | WritingScheduleItemID | int +WritingScheduleItems | WritingPlanID | int +WritingScheduleItems | SceneID | int +WritingScheduleItems | ScheduledDate | date +WritingScheduleItems | TaskType | nvarchar +WritingScheduleItems | EstimatedMinutes | int +WritingScheduleItems | TargetWords | int +WritingScheduleItems | ScheduleStatus | nvarchar +WritingScheduleItems | CompletedDateUtc | datetime2 +WritingScheduleItems | Notes | nvarchar +WritingScheduleItems | CreatedDateUtc | datetime2 +WritingScheduleItems | ModifiedDateUtc | datetime2 +name | type_desc +BookChapterReuse | SQL_STORED_PROCEDURE +BookChapterSync | SQL_STORED_PROCEDURE +CreateWritingPlan | SQL_STORED_PROCEDURE +DeleteWritingPlan | SQL_STORED_PROCEDURE +GetWritingPlanByID | SQL_STORED_PROCEDURE +GetWritingPlansByUser | SQL_STORED_PROCEDURE +OnboardingManuscriptCapture | SQL_STORED_PROCEDURE +ParagraphManuscript | SQL_STORED_PROCEDURE +ProjectActivity_Create | SQL_STORED_PROCEDURE +ProjectActivity_ListForProject | SQL_STORED_PROCEDURE +ProjectActivity_ListRecent | SQL_STORED_PROCEDURE +SetWritingPlanActive | SQL_STORED_PROCEDURE +UpdateWritingPlan | SQL_STORED_PROCEDURE +UserOnboarding_SaveWritingJourney | SQL_STORED_PROCEDURE +UserOnboarding_SaveWritingSoftware | SQL_STORED_PROCEDURE +WritingIntentAssessment | SQL_STORED_PROCEDURE +WritingPlan_ListForManagement | SQL_STORED_PROCEDURE +WritingPlanSummary_ListByUser | SQL_STORED_PROCEDURE +WritingPlanSummary_ListRequiringRebalance | SQL_STORED_PROCEDURE +WritingScheduleDashboard_ListActive | SQL_STORED_PROCEDURE +WritingScheduleItem_DeleteByPlan | SQL_STORED_PROCEDURE +WritingScheduleItem_UpdatePlannedDate | SQL_STORED_PROCEDURE +WritingScheduleItem_UpdatePlannedStatusForUser | SQL_STORED_PROCEDURE +WritingSchedulePreview_ListByPlan | SQL_STORED_PROCEDURE +WritingScheduleScene_ListForPlanning | SQL_STORED_PROCEDURE +WritingSolver_Get | SQL_STORED_PROCEDURE +WritingSolver_Publish | SQL_STORED_PROCEDURE diff --git a/Docs/Investigations/Writer2Audit/HistoricalCoverage.readonly.sql b/Docs/Investigations/Writer2Audit/HistoricalCoverage.readonly.sql new file mode 100644 index 00000000..fdb45db1 --- /dev/null +++ b/Docs/Investigations/Writer2Audit/HistoricalCoverage.readonly.sql @@ -0,0 +1,9 @@ +SET NOCOUNT ON; +SELECT COUNT_BIG(*) AS AcceptedBooks,MIN(UpdatedUtc) AS EarliestRowUpdateUtc,MAX(UpdatedUtc) AS LatestRowUpdateUtc,SUM(CASE WHEN TRY_CONVERT(bigint,JSON_VALUE(Payload,'$.Revision'))=Revision THEN 1 ELSE 0 END) AS MatchingJsonRevisions FROM dbo.BookParagraphManuscripts; +SELECT COUNT_BIG(*) AS CurrentParagraphs,SUM(CASE WHEN NULLIF(JSON_VALUE(j.value,'$.Occurrence.PreviousText'),'') IS NOT NULL THEN 1 ELSE 0 END) AS WithPreviousText,SUM(CASE WHEN JSON_VALUE(j.value,'$.Occurrence.Change')='Modified' THEN 1 ELSE 0 END) AS LatestModifiedAnnotations FROM dbo.BookParagraphManuscripts b CROSS APPLY OPENJSON(b.Payload,'$.Paragraphs') j; +SELECT COUNT_BIG(*) AS Validations,MIN(ValidatedUtc) AS FirstRetainedValidationUtc,MAX(ValidatedUtc) AS LastRetainedValidationUtc,SUM(CASE WHEN ExpiresUtc<=SYSUTCDATETIME() THEN 1 ELSE 0 END) AS ExpiredRows FROM dbo.BookChapterValidations; +SELECT COUNT_BIG(*) AS Captures,SUM(CASE WHEN IsCurrent=1 THEN 1 ELSE 0 END) AS CurrentCaptures,MIN(CreatedUtc) AS FirstCaptureUtc,MAX(CreatedUtc) AS LastCaptureUtc FROM dbo.OnboardingManuscriptCaptures; +SELECT ActivityType,EntityType,COUNT_BIG(*) AS Events,MIN(CreatedDateUTC) AS FirstUtc,MAX(CreatedDateUTC) AS LastUtc FROM dbo.ProjectActivity GROUP BY ActivityType,EntityType ORDER BY ActivityType,EntityType; +SELECT t.name,c.name AS ColumnName,ty.name AS DataType FROM sys.tables t JOIN sys.columns c ON c.object_id=t.object_id JOIN sys.types ty ON ty.user_type_id=c.user_type_id WHERE t.name IN('ProjectRestorePoints','SceneManuscriptSources','ManuscriptDocuments','ProjectUserAccess') ORDER BY t.name,c.column_id; +SELECT name,is_tracked_by_cdc,temporal_type_desc FROM sys.tables WHERE name IN('BookParagraphManuscripts','SceneManuscriptSources','WritingScheduleItems','ProjectActivity'); +SELECT t.name AS TableName FROM sys.tables t WHERE t.name LIKE '%Session%' OR t.name LIKE '%Snapshot%' OR t.name LIKE '%Milestone%' OR t.name LIKE '%PassStatus%' OR t.name LIKE '%WritingActivity%' OR t.name LIKE '%Availability%' OR t.name LIKE '%Provenance%' OR t.name LIKE '%Insight%'; diff --git a/Docs/Investigations/Writer2Audit/HistoricalCoverage.txt b/Docs/Investigations/Writer2Audit/HistoricalCoverage.txt new file mode 100644 index 00000000..ddf0d6ab --- /dev/null +++ b/Docs/Investigations/Writer2Audit/HistoricalCoverage.txt @@ -0,0 +1,64 @@ +Verified database: PlotDirector_Development +AcceptedBooks | EarliestRowUpdateUtc | LatestRowUpdateUtc | MatchingJsonRevisions +14 | 11/09/2026 15:47:45 | 11/13/2026 22:08:28 | 14 +CurrentParagraphs | WithPreviousText | LatestModifiedAnnotations +118399 | 50743 | 3 +Validations | FirstRetainedValidationUtc | LastRetainedValidationUtc | ExpiredRows +467 | 11/09/2026 15:48:35 | 11/13/2026 22:09:15 | 467 +Captures | CurrentCaptures | FirstCaptureUtc | LastCaptureUtc +1 | 1 | 11/08/2026 21:05:14 | 11/08/2026 21:05:14 +ActivityType | EntityType | Events | FirstUtc | LastUtc +Created | Book | 1 | 11/08/2026 18:11:00 | 11/08/2026 18:11:00 +Created | Location | 13 | 11/13/2026 15:07:54 | 11/14/2026 15:40:51 +Created | Project | 1 | 11/08/2026 18:10:43 | 11/08/2026 18:10:43 +Exported | Project | 1 | 11/09/2026 14:57:05 | 11/09/2026 14:57:05 +Merged | Character | 1 | 11/09/2026 21:51:44 | 11/09/2026 21:51:44 +Updated | Book | 1 | 11/08/2026 18:23:34 | 11/08/2026 18:23:34 +Updated | Location | 36 | 11/13/2026 15:09:49 | 11/13/2026 19:33:43 +name | ColumnName | DataType +ManuscriptDocuments | ManuscriptDocumentID | int +ManuscriptDocuments | BookID | int +ManuscriptDocuments | ProjectID | int +ManuscriptDocuments | DocumentGuid | uniqueidentifier +ManuscriptDocuments | BindingVersion | int +ManuscriptDocuments | CreatedUtc | datetime2 +ManuscriptDocuments | LastSyncUtc | datetime2 +ManuscriptDocuments | LastOpenedUtc | datetime2 +ManuscriptDocuments | IsActive | bit +ManuscriptDocuments | CreatedByUserID | int +ProjectRestorePoints | ProjectRestorePointID | int +ProjectRestorePoints | ProjectID | int +ProjectRestorePoints | RestorePointName | nvarchar +ProjectRestorePoints | RestorePointType | nvarchar +ProjectRestorePoints | CreatedDateUtc | datetime2 +ProjectRestorePoints | JsonData | nvarchar +ProjectRestorePoints | JsonSizeBytes | bigint +ProjectRestorePoints | Notes | nvarchar +ProjectUserAccess | ProjectUserAccessID | int +ProjectUserAccess | ProjectID | int +ProjectUserAccess | UserID | int +ProjectUserAccess | AccessRole | nvarchar +ProjectUserAccess | InvitedByUserID | int +ProjectUserAccess | InvitedDateUTC | datetime2 +ProjectUserAccess | AcceptedDateUTC | datetime2 +ProjectUserAccess | IsActive | bit +SceneManuscriptSources | SceneID | int +SceneManuscriptSources | ProjectID | int +SceneManuscriptSources | BookID | int +SceneManuscriptSources | ChapterID | int +SceneManuscriptSources | SourceText | nvarchar +SceneManuscriptSources | SourceWordCount | int +SceneManuscriptSources | SourceCharacterCount | int +SceneManuscriptSources | SourceStartParagraph | int +SceneManuscriptSources | SourceEndParagraph | int +SceneManuscriptSources | WordStartParagraphIndex | int +SceneManuscriptSources | WordEndParagraphIndex | int +SceneManuscriptSources | SourceKind | nvarchar +SceneManuscriptSources | CreatedUtc | datetime2 +SceneManuscriptSources | UpdatedUtc | datetime2 +name | is_tracked_by_cdc | temporal_type_desc +BookParagraphManuscripts | False | NON_TEMPORAL_TABLE +ProjectActivity | False | NON_TEMPORAL_TABLE +SceneManuscriptSources | False | NON_TEMPORAL_TABLE +WritingScheduleItems | False | NON_TEMPORAL_TABLE +TableName diff --git a/Docs/Investigations/Writer2Audit/README.md b/Docs/Investigations/Writer2Audit/README.md new file mode 100644 index 00000000..e834aeef --- /dev/null +++ b/Docs/Investigations/Writer2Audit/README.md @@ -0,0 +1,51 @@ +# Writer 2.0 technical audit + +Audit date: 14 November 2026 (Europe/London). Requirements baseline: [the supplied specification](Writer2_Spec.md), read in full before implementation investigation. Repository HEAD at investigation start: `05327c3ddd2468de7cee2ef02c3a9e7d41c165c4`. + +Status: Gate 0 audit and recommendations only. No implementation approval is implied. + +## Executive assessment + +Writer 2.0 can build on substantial working infrastructure. Writer already has revision-driven scene queues, chapter goals, notes/checklists, personal writing plans, generated scene tasks, completion/skip actions and a rebalance preview. The PWA shell, themes, Context/Intent windows, native Word transport, accepted paragraph manuscript, chapter checkpoints, read-only Reader and navigable story charts should be retained. + +The critical missing foundation is a durable, source-neutral history of accepted writing activity. Current synchronisation is designed to preserve the latest accepted manuscript and validate live Word positions. It is not a record of every edit, writing session or author contribution. Latest paragraph comparison metadata, import captures and occasional restore points provide limited evidence; they do not establish continuous historical provenance. A successful chapter validation can involve no text change whatsoever. + +Development inspection found 14 latest manuscript rows, one retained onboarding capture, one restore point containing one paragraph snapshot, one active writing plan, no schedule items, and 467 retained chapter validations, all expired at inspection. Counts include any development fixtures; they are not counts of real authors or complete user journeys. No candidate Writer 2.0 session/activity/pass/availability/insight/provenance tables were found. Existing project collaboration is project-wide and cannot safely supply the proposed chapter/book-scoped editorial permissions unchanged. + +The largest new capabilities are the activity ledger and retention policy, durable offline activity delivery, explicit sessions, independent overlapping passes, flexible availability and exceptions, journey projections, confidence-qualified insights and privacy-aware reports. Signed provenance is a separate security project. None requires generative AI to function. + +## Deliverables + +1. [Existing System Inventory](01-Existing-System-Inventory.md) +2. [Requirements Traceability Matrix](02-Requirements-Traceability.md) +3. [Activity Capture Assessment](03-Activity-Capture-Assessment.md) +4. [Architecture Recommendations](04-Architecture-Recommendations.md) +5. [UX Gap Analysis](05-UX-Gap-Analysis.md) +6. [Phased Implementation Plan](06-Phased-Implementation-Plan.md) +7. [Decisions Required](07-Decisions-Required.md) + +## Evidence and limits + +**Verified source** means a route, class, method, SQL definition or test was inspected. **Verified Development** means SELECT-only inspection of the effective configured `PlotDirector_Development`, after checking both the connection's database setting and `SELECT DB_NAME()`. **Recommendation** means proposed work, not existing behaviour. **Unverified** marks a runtime or design point not established here. Source implementation, historical deployment reports and actual present-day end-to-end operation are deliberately distinguished. + +The following evidence contains schema metadata and aggregates only; no manuscript prose, credentials, personal names, connection strings or reportable author identities were exported: + +- [Database inventory query](DatabaseInventory.readonly.sql) and [results](DatabaseInventory.txt). +- [Historical coverage query](HistoricalCoverage.readonly.sql) and [results](HistoricalCoverage.txt). +- [Recovery coverage query](RecoveryCoverage.readonly.sql) and [results](RecoveryCoverage.txt). Backup JSON uses camelCase; this query checks both casings. One retained paragraph snapshot is present, not zero. +- [Verification record](Verification.md). + +Queries were ordinary reads, not a transactionally consistent multi-query snapshot. Aggregate counts are point-in-time observations and are not a usage study. No database write procedures, synthetic fixture imports, repair actions, migrations, restores, deployment or service restarts were executed. SQL files here are audit evidence, not migrations. The connection helper ran outside the repository and refused any configured/effective database other than Development. + +The existing untracked `Docs/Investigations/CanonicalManuscriptArchitectureAssessment.md` was preserved and was not treated as verified evidence. No branch was created. No mockup image was supplied with the baseline; visual conclusions compare inspected UI/source and existing design conventions to the written visual contract, not an unseen approved image. Native Windows/Word/monitor behaviour and real installed-PWA behaviour require Windows acceptance. No production host or database was inspected. + +## Recommended sequence + +1. Approve retention, evidence semantics and the event contract; capture a truthful present-day baseline. +2. Deliver the ribbon/dashboard/workspace improvements progressively, with explicit history coverage. +3. Add flexible rhythm setup and an opportunity-based plan engine. +4. Add explicit focus sessions, parallel passes and the Writing Journey. +5. Add qualified insights, scoped editorial work and unsigned evidence reports. +6. Deliver signed PDFs/verification only after a separate security review and sign-off. + +Stop at this audit. Implementation and deployment require subsequent explicit approval. diff --git a/Docs/Investigations/Writer2Audit/RecoveryCoverage.readonly.sql b/Docs/Investigations/Writer2Audit/RecoveryCoverage.readonly.sql new file mode 100644 index 00000000..28b0463d --- /dev/null +++ b/Docs/Investigations/Writer2Audit/RecoveryCoverage.readonly.sql @@ -0,0 +1,4 @@ +SET NOCOUNT ON; +SELECT COUNT_BIG(*) AS RestorePoints,SUM(CASE WHEN COALESCE(JSON_QUERY(JsonData,'$.recovery.paragraphManuscripts'),JSON_QUERY(JsonData,'$.Recovery.ParagraphManuscripts')) IS NOT NULL THEN 1 ELSE 0 END) AS WithParagraphCollection FROM dbo.ProjectRestorePoints; +SELECT COUNT_BIG(*) AS ParagraphSnapshotsInRestorePoints FROM dbo.ProjectRestorePoints p CROSS APPLY OPENJSON(COALESCE(JSON_QUERY(p.JsonData,'$.recovery.paragraphManuscripts'),JSON_QUERY(p.JsonData,'$.Recovery.ParagraphManuscripts'))) j; +SELECT COUNT_BIG(*) AS RestorePointsWithSceneSourceCollection FROM dbo.ProjectRestorePoints WHERE COALESCE(JSON_QUERY(JsonData,'$.recovery.sceneManuscriptSources'),JSON_QUERY(JsonData,'$.Recovery.SceneManuscriptSources')) IS NOT NULL; diff --git a/Docs/Investigations/Writer2Audit/RecoveryCoverage.txt b/Docs/Investigations/Writer2Audit/RecoveryCoverage.txt new file mode 100644 index 00000000..b38c0629 --- /dev/null +++ b/Docs/Investigations/Writer2Audit/RecoveryCoverage.txt @@ -0,0 +1,7 @@ +Verified database: PlotDirector_Development +RestorePoints | WithParagraphCollection +1 | 1 +ParagraphSnapshotsInRestorePoints +1 +RestorePointsWithSceneSourceCollection +0 diff --git a/Docs/Investigations/Writer2Audit/Verification.md b/Docs/Investigations/Writer2Audit/Verification.md new file mode 100644 index 00000000..9b882f95 --- /dev/null +++ b/Docs/Investigations/Writer2Audit/Verification.md @@ -0,0 +1,30 @@ +# Audit verification record + +Date: 14 November 2026. Scope: source inspection, SELECT-only Development metadata/aggregates, existing portable regression suites and isolated synthetic browser rendering. No new tests or application implementation were written. + +## Executed checks + +| Check | Actual invocation / environment | Result | +|---|---|---| +| Initial/final worktree | `git status --short`; initial HEAD `05327c3ddd2468de7cee2ef02c3a9e7d41c165c4` | Existing untracked `Docs/Investigations/CanonicalManuscriptArchitectureAssessment.md` preserved. Only new audit documentation/assets under `Docs/Investigations/Writer2Audit/`. No branch or commit created. | +| Solution build | `dotnet build PlotLine.slnx --no-restore --nologo -v quiet`, with an external temporary directory | Exit 0; zero warnings, zero errors; 39.00 seconds. Uses already-restored dependencies. | +| Normal executable regression harness | `dotnet run --no-build --no-restore --project PlotLine.Tests/PlotLine.Tests.csproj` after build | Exit 0; 492 PASS lines, zero FAIL lines. Includes Reader and existing Writer/native/paragraph source/behaviour checks registered in the normal harness. | +| Focused portable chapter suite | Same runner with `-- --chapter-sync` | Exit 0; 71 PASS lines, zero FAIL lines. Includes structure safety, identity/lineage, selective reconciliation and cancellation. Portable hash timing is not Word/COM performance. | +| Browser navigation/theme suite | `node PlotLine.Tests/Browser/writer-navigation-themes.cjs` against the existing `--toolbar-browser-host` fixture at loopback port 5238 | Exit 0. Writer direct navigation/active context; Context/Intent full/embedded, four themes, browser/simulated PWA and 390/1440 widths. Synthetic repositories; no database connection. | +| Visual inspection | Existing synthetic Writer Razor fixture, screenshots at 1440×1000 and 390×844 | Both inspected. Copies retained as `CurrentWriter-Desktop-Fixture.png` and `CurrentWriter-Small-Fixture.png`. Not author data or Writer 2.0 mockups. | +| Development schema/history | Credential-safe external SqlClient helper consumed effective service environment as data, verified configured database, opened connection and verified `SELECT DB_NAME()` = `PlotDirector_Development` before each query | SELECT-only inventory/history/recovery results retained. No credentials or manuscript prose exported. Relevant live procedures also checked for latest-snapshot update and expired-validation/schedule deletion patterns. | + +Build and regression execution were serial. The fixture process started for this audit was terminated after browser checks. No development application service was restarted. A temporary-directory quota issue affected initial external helper setup; the helper was built outside the repository in a writable home directory instead. No existing temporary data was deleted to work around it. + +Database observations were not wrapped in a multi-query snapshot transaction. The schema row counts are labelled approximate where they come from `sys.partitions`; content counts are explicit aggregates. The recovery check uses both camelCase and PascalCase JSON paths and verifies one paragraph snapshot is present in the retained restore point. + +## Not executed / not claimed + +- No SQL regression scripts, database fixture setup, capture/repair/enable actions, migration, schema changes, restores, import or database write procedures. +- No service deployment, Production access, release packaging or signing. +- No new Writer 2.0 UI or feature acceptance: the features have not been implemented. +- No real Windows Word COM/add-in/agent installation, offline editing/restart qualification, OS notification/focus/window placement, physical monitor topology or Windows installed-PWA acceptance. Existing qualification reports are historical evidence only. +- No continuous historical reconstruction or inspection/export of author prose. Sparse retained states and metadata cannot justify that claim. +- No approved visual mockup review, because no mockup was attached. + +The executable regression harness uses synthetic/mocked paths by default; specialist Development-writing tests are separate flags and were not invoked. Existing tests include source-shape assertions, so passing them supports compatibility but is not proof of every end-to-end native or UI behaviour described by the specification. diff --git a/Docs/Investigations/Writer2Audit/Writer2_Spec.md b/Docs/Investigations/Writer2Audit/Writer2_Spec.md new file mode 100644 index 00000000..bdac4f6e --- /dev/null +++ b/Docs/Investigations/Writer2Audit/Writer2_Spec.md @@ -0,0 +1,85 @@ +# PlotDirector Writer 2.0 — Functional & Technical Specification + +Status: Product requirements baseline for Codex audit; technical implementation provisional. +Date: 14 November 2026 +Scope: PlotDirector PWA Writer, Word Companion, future Editor, planning, activity tracking, reporting and provenance. +Primary user outcome: “I can see what I have achieved with the writing time available to me, and I know what to do next.” + +## 1. Purpose and product principles + +Writer 2.0 is the author-facing planning, focus, progress and creative-history workspace within PlotDirector. Its primary purpose is to help authors use their available writing time and see meaningful progress without maintaining duplicate records. Manuscript provenance is a downstream reporting capability, not the primary interface. +Requirements: writing comes first; show rather than praise; no chatty AI persona; progress includes drafting, deletion, revision, research, editorial and publication work; no guilt for unavailable days; author controls schedule; accessible and consistent with existing PlotDirector PWA ribbon/theme; UK English. + +## 2. Information architecture and navigation + +Replace the legacy Writer landing experience with a full-width dashboard and contextual Writer ribbon consistent with other PlotDirector workspaces. Remove duplicate Writer/Write navigation routes while preserving deep links and backwards-compatible redirects. Ribbon destinations: Overview, Writing Journey, Writing Plan, Focus Sessions, Workspaces, Reports; Word Companion status and Display Setup are contextual actions. Keep project/book selection in the common shell, not floating in the page. Workspaces have five tabs: Write Next, In Progress, Revision, Final Pass, Story Health. All displayed chapter, scene and issue references should navigate to the corresponding destination where supported. In PWA mode preserve ribbon and maximise behaviour. + +## 3. Dashboard visual contract + +First viewport: selected book, current meaningful work, next writing opportunity, compact Word Companion state and a small set of useful indicators. Show activity days relative to chosen opportunities, manuscript change (gross additions, deletions, net), pass progress, milestone progress and an optional compact writing journey. Use progressive disclosure; no wall of text or permanent setup wizard. Make every relevant chart/card drillable. Green = observed progress; amber = potential schedule risk; red = actionable blocker; grey = not scheduled/not started. Never imply a missed session is a moral failure. Distinguish planned, observed, inferred and author-declared figures. Provide accessible non-colour equivalents. + +## 4. Writing Rhythm setup wizard + +Conversational, visual, skippable and resumable wizard. Ask how writing fits into life: around other commitments, regular dedicated periods, flexible availability, or still exploring. Do not label users full-time/part-time. Let authors paint available time slots on a weekly grid, optionally protect personal time, select preferred session types and rough milestones. Support “write whenever I can” with no fixed weekdays. Detect existing manuscript and progress to prefill where reliable. Preview a proposed plan before saving. Offer change/holiday/exception handling without penalising author. Never require daily word targets. Scheduling suggestions require approval and can be ignored or dismissed. + +## 5. Focus Sessions and sprints + +Start from dashboard, timeline, Word Companion and eventually native Editor. Presets such as 20/30/45/60 minutes and custom; objectives for drafting, revision, planning, editorial, publication or promotion. Optional 5-minute recharge or reflection break. Focus mode hides nonessential UI and offers a discreet timer, pause, extend, finish and optional next-session note. Do not interrupt mid-sentence with modal alerts. Word Companion may focus/open linked Word document and navigate to chapter where permitted; notification controls must respect OS/browser capabilities and user consent. Never claim a timer proves continuous concentration. Record planned duration, elapsed time, observed document activity and interruptions separately. + +## 6. Writing Journey and timeline + +Dedicated full-width, zoomable timeline with actual past activity to the left of Today and planned future work to the right. Support day/week/month/book scales, interactive days, milestones, chapter and scene drill-down, editable future targets, dependency previews and optional reforecasting. Multiple parallel tracks and passes: drafting, structural revision, line editing, proofing, editorial, publishing, marketing and user-defined phases. Allow iterative authors to edit early chapters while drafting later ones; allow phase-by-phase workflows equally. A chapter-pass matrix shows not started/in progress/reviewed/complete with explicit state provenance. Avoid deriving “complete” merely from document edits. + +## 7. Word Companion and future Editor integration + +One source-neutral activity ingestion contract shared by Word Companion and future PlotDirector Editor. Audit existing paragraph GUIDs, manuscript reader, checkpoints, sync reconciliation, timestamps and change detection before altering. Record idempotent change events, session linkage, document identity, chapter/scene association, actor/source, observed timestamp, receipt timestamp, additions/deletions and snapshot references when available. Handle offline queue, retries, clock skew, repeated sync, document switching, renames, paragraph moves and conflicts. Capture baseline immediately; never fabricate past history. Preserve current Word Companion functionality and compatibility. Compact status states: not installed, disconnected, connected/no linked document, syncing, ready, stale/error; show only relevant actions. + +## 8. Display discovery and layouts + +Make Detect Displays a prominent, permission-aware setup action. When supported, display discovered monitor geometry visually and permit role assignment for Word, PlotDirector, reference/research and spare displays. Support one, two, three, four or more monitors, saved profiles (e.g. laptop/docked), changing topology and manual fallback. Explain browser permission and window placement limitations. Never hard-code a three-monitor arrangement or show irrelevant layout actions when no linked document is active. + +## 9. Writing insights and profiles + +Use conventional statistics first, not generative AI narration. Track dimensions separately: regular/flexible schedule, short/long sessions, iterative/phase-oriented work, drafting/revision mix, and time-of-day patterns. Do not infer natural preference solely from observed availability. Only display insights with enough quality data; show sample size, uncertainty and plain factual phrasing. Examples: “14 of 18 sessions began after 7pm”; “Your recent drafting sessions average 38 minutes.” Profiles are optional internal descriptors, never fixed identities or diagnoses. Suggestions are infrequent, explainable, dismissible and never auto-change schedules. + +## 10. Collaboration and editorial work + +Support author-owned assignments to editors, proofreaders and other contributors, with overlapping phases, status and milestone dates. Separate manually reported progress from directly captured edits. First release may support external milestones and feedback imports without requiring collaborators to adopt PlotDirector. Later integrated editor work may record attributed changes. Role-scoped permissions: no default access to unrelated books, private notes or research. Activity history must distinguish author, collaborator, import and system actors. + +## 11. Reporting and manuscript provenance + +Reports cover selected dates, chapters, passes and collaborators. Include writing days, session durations (qualified), additions, deletions, net count, version growth, chapter changes, milestones, editorial contributions and evidence coverage. Offer concise overview and detailed evidence report. Future PlotDirector-sealed PDF: report ID, generation time, scope, evidence quality/coverage, cryptographic document signature and optional privacy-preserving verification endpoint/QR. Signing proves issued report integrity, not human-only authorship; do not market as proof that AI was never used. Separate observed evidence, imported history and author declarations. Allow redaction/privacy controls. Define retention, export and deletion policy before production capture. + +## 12. Proposed data architecture (subject to audit) + +Prefer append-only, versioned activity records and derived read models. Candidate entities: WritingActivityEvent, WritingSession, ManuscriptSnapshot, ManuscriptPass, ChapterPassStatus, WritingAvailability, ScheduleException, WritingMilestone, CollaboratorAssignment, WritingInsight, ProvenanceReport. Events require stable idempotency keys, source/actor IDs, UTC times and local-time display metadata, provenance class, correlation IDs and schema version. Store minimal necessary text; retain detailed diffs/snapshots only under explicit retention and privacy rules. Rebuild dashboard projections from events. Provide efficient bounded querying, aggregation, audit and repair tools. Actual schema and migration choices follow repository audit. + +## 13. Key user journeys + +A. New author: open Writer → choose book → wizard or skip → optional availability → proposed plan → dashboard and first session. +B. Existing author: open Writer → see detected manuscript baseline and coverage note → current work → start sprint → Word opens/focuses where possible → work → finish → activity summary and timeline update. +C. Irregular author: no fixed sessions → flexible weekly opportunities → observed activity visible without empty-week guilt. +D. Iterative author: draft Chapter 35 and revise Chapter 8 concurrently → separate tracks and accurate per-pass status. +E. Editor: assigned chapters → report or integrated updates → author sees editorial progress with permission boundaries. +F. Provenance: select period and evidence level → preview → export verifiable report with explicit limitations. +G. Display setup: grant permission → detect screens → assign roles → save profile → graceful single-screen fallback. + +## 14. Acceptance criteria + +Dashboard uses existing PlotDirector ribbon, theme and responsive/PWA conventions; duplicate Write/Writer paths resolve consistently. No linked Word document means no irrelevant controls. Plans can be created without daily targets and show only available writing opportunities by default. A 30-minute sprint can be paused/extended/completed without modal interruption; recorded time is not misrepresented as continuous focus. Multiple passes may overlap on the same chapter; edits alone never mark a pass complete. Duplicate/offline Word sync never inflates words or sessions. Gross added/deleted and net counts reconcile with known fixtures; formatting-only changes do not masquerade as word growth. Activity records indicate coverage and source. Charts and chapter issues navigate meaningfully. Display setup handles 1–4+ screens and denied permission. Insights require sample-size thresholds and can be dismissed. Provenance export never asserts AI-free certification. Existing Word Companion and Writer functions pass regression tests. + +## 15. Delivery and audit gates + +Gate 0 — read-only audit: inventory routes/views/ribbon, Writer data, scheduling, Word Companion native and agent components, paragraph/snapshot history, author permissions, tests, deployment flow. Produce reuse/gap/risk matrix and proposed schema; no implementation or deployment. +Gate 1 — capture foundation: event contract, deduplication, baseline, retention and integration tests; deploy to Development only after approval. +Gate 2 — navigation/dashboard/workspaces: accessible UI, compact Companion states, interactive charts. +Gate 3 — rhythm wizard and plan engine: availability, protected time, exceptions and milestone forecast. +Gate 4 — focus sessions and journey timeline: sprints, breaks, overlapping passes and drill-down. +Gate 5 — insights, collaboration and reports: confidence, permissions, evidence and privacy. +Gate 6 — signed provenance PDF and verification: separate security review and explicit sign-off. +For every gate: build, regression, PWA/browser verification, native Word tests where applicable, migration rollback and documented Development acceptance. No production changes without explicit approval. + +## 16. Open design questions for audit + +What historical activity is truly retained versus only latest manuscript state? Which Word events are reliably observed versus inferred? What are the current Writer schedule tables and permissions? How are chapters/scenes and paragraph IDs mapped across reorganisations? Which browser APIs and agent capabilities are available for multi-display and focus behaviour? What retention and privacy defaults are acceptable? Which existing UI components can be reused? Which milestones are explicit versus inferred? How should publication and external editor progress be entered or imported? These are investigation items, not permission to invent functionality. +