Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

docs([issue-2073]): rewrite four shipped feature docs from plan-tense to verified current-state

[._.]/ Adam Eivy3fd0234302d5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9242378643..662a5b2efa 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -34,6 +34,7 @@
## Internal
+- **[issue-2073] Docs editorial pass: four shipped feature docs rewritten from plan-tense to current-state.** `docs/features/digital-twin.md`, `openclaw-operator-chat.md`, `post.md`, and `writers-room.md` still read as pre-build plans/specs ("Planned Phases", "Proposed capabilities", phased roadmaps) despite describing shipped features. Each was rewritten as current-state documentation with every claim verified against the code, correcting stale details along the way: digital-twin's import list (Spotify/Letterboxd/iCal, not Last.fm; transcript/image analysis, not live voice/video capture), POST's undocumented sixth Cognitive domain plus Morse training, drill cache, training log, and adaptive difficulty, writers-room's PostgreSQL-primary storage, CD-bridge-instead-of-render-plans design, story bible, and storyboard surfaces, and OpenClaw's shipped endpoint/config/degradation surface (keeping the honest list of proposed-but-unbuilt endpoints). The three digital-twin-adjacent docs (`soul-system.md` / `digital-twin.md` / `identity-system.md`) now cross-link with a note explaining which angle each covers (#2073).
- Deflaked the `UpdateTab reconcile flow` tests, which intermittently failed CI with "Unable to find role=button and name 'Restarting...'" (#2065). The component mirrors `updating` into `updatingRef` via a passive effect, and the disconnect handler's guard reads that ref synchronously; since `runUpdate()` calls `setUpdating(true)` outside any `act` (after awaiting the pre-update health check), the "Reconciling..." button could commit — satisfying the test's `waitFor` — a scheduler tick before the ref-sync effect ran, leaving the ref stale-false when `disconnect` fired so the confirmation timer never armed. The test now flushes pending effects (`await act(async () => {})`) before firing `disconnect`, syncing the ref to the state production always reaches over real network time. Test-only change; no product behavior touched.
- Docs audit and reorganization: reclassified two non-feature docs out of `docs/features/` — the cross-domain insights design spike now lives at `docs/plans/2026-06-03-cross-domain-insights-engine.md` (it specs future work, it isn't feature documentation) and the OpenClaw pre-implementation extension-point audit at `docs/research/2026-03-31-openclaw-operator-chat-audit.md` (it's an explicitly-unmaintained investigation record). `docs/README.md` links updated. Also fixed `docs/PORTS.md` claiming the `PORTS` object is "re-exported at `server/lib/ports.js`" (it's a manually-synced mirror — the ESM server can't `require()` the CommonJS config), replaced a dead `#m7-app-templates` anchor in `docs/features/app-wizard.md` with a real pointer to `GET /api/scaffold/templates`, and refreshed the stale example model IDs in `docs/TROUBLESHOOTING.md`. The audit verified every other doc against the code: all 13 top-level guides are indexed and accurate, every feature doc's modules/routes/nav entries resolve, and plans/decisions/research/superpowers/themes/examples/media have zero orphans or broken links.
- Consolidated five component-local duration/uptime/time-until formatters onto the shared `utils/formatters.js` helpers (`formatDurationMs`, `timeUntil`), per the "do not re-define formatters inside components" convention (#2028). `formatDurationMs` gained a day bucket (`2d 3h`) so long uptimes no longer render as an unbounded hours count; ProcessesTab, CityHud, Shell session ages, the CoS QuickSummary "next job" countdown, and the Loops interval label now all route through the shared helpers, and a `console.log` in `memoryClassifier.js` was collapsed to a single interpolated line.
diff --git a/docs/features/digital-twin.md b/docs/features/digital-twin.md
index c69ae916d8..d822e38e3c 100644
--- a/docs/features/digital-twin.md
+++ b/docs/features/digital-twin.md
@@ -1,66 +1,22 @@
# Digital Twin Personality Enhancement
-Quantitative personality modeling and prediction system that accurately embodies a human's values, decision patterns, and communication style.
+Quantitative personality modeling and prediction on top of the [Soul System](./soul-system.md)'s document store: trait scoring, confidence measurement, behavioral testing, feedback-driven weighting, and personas.
-## Vision
-
-Transform the Digital Twin from a document capture system into a quantitative personality modeling and prediction system.
+This doc covers the quantitative-modeling layer. The document workflow (Documents/Enrich/Export tabs, soul markdown files) is documented in [Soul System](./soul-system.md); the broader identity architecture (genome, chronotype, taste, goals) in [Unified Identity System](./identity-system.md).
## Architecture
-- **Digital Twin Service** (`server/services/digital-twin.js`, with logic split across ~25 `digital-twin-*.js` modules): Trait analysis, confidence scoring, gap recommendations
-- **Digital Twin Routes** (`server/routes/digital-twin.js`): REST API endpoints
+- **Digital Twin Service** (`server/services/digital-twin.js`, with logic split across ~20 `digital-twin-*.js` modules plus `feedbackLoop.js`): trait analysis, confidence scoring, gap recommendations, testing suites, personas, imports
+- **Digital Twin Routes** (`server/routes/digital-twin.js`): REST API under `/api/digital-twin/*`
- **Digital Twin Validation** (`server/lib/digitalTwinValidation.js`): Zod schemas for trait data
-## Features
-
-### Phase 1: Quantitative Personality Modeling (Complete)
-
-**Big Five Trait Scoring**
-- Quantified OCEAN scores (Openness, Conscientiousness, Extraversion, Agreeableness, Neuroticism)
-- Infer scores from existing documents using LLM analysis
-- Allow manual override/adjustment
-- Store in `meta.json` under `traits.bigFive`
-
-**Values Hierarchy**
-- Extract explicit values from VALUES.md and NON_NEGOTIABLES.md
-- Create ranked values list with conflict resolution rules
-- Store in `meta.json` under `traits.valuesHierarchy`
-
-**Communication Fingerprint**
-- Quantify writing style: formality (1-10), verbosity (1-10), emoji usage, sentence length avg
-- Extract from WRITING_STYLE.md and writing samples
-- Store in `meta.json` under `traits.communicationProfile`
+## Quantitative Personality Modeling
-### Phase 2: Personality Confidence Scoring (Complete)
-
-**Coverage Metrics**
-- For each Big Five dimension: evidence count from documents
-- For each value: supporting document count + specificity score
-- For communication: sample diversity, consistency across samples
-
-**Confidence Algorithm**
-```
-confidence(aspect) = min(1.0,
- (evidence_count / required_evidence) *
- (consistency_score) *
- (recency_weight)
-)
-```
+**Big Five Trait Scoring** — quantified OCEAN scores (Openness, Conscientiousness, Extraversion, Agreeableness, Neuroticism), inferred from existing soul documents via LLM analysis, with manual override/adjustment. Stored in `meta.json` under `traits.bigFive`.
-**Gap Recommendations**
-- Identify lowest-confidence aspects
-- Generate specific questions to fill gaps
-- Prioritize enrichment categories by confidence gap
+**Values Hierarchy** — explicit values extracted from VALUES.md and NON_NEGOTIABLES.md into a ranked list. Stored under `traits.valuesHierarchy`.
-### Phase 4: External Data Integration (Complete)
-
-Import from external sources to reduce manual input:
-- Goodreads CSV import for reading preferences
-- Spotify/Last.fm for music profile
-- Calendar pattern analysis for routines
-
-## Data Structure
+**Communication Fingerprint** — quantified writing style (formality, verbosity, sentence length, emoji usage, tone), extracted from WRITING_STYLE.md and writing samples. Stored under `traits.communicationProfile`.
```javascript
traits: {
@@ -77,13 +33,60 @@ traits: {
}
```
+## Confidence Scoring & Gap Recommendations
+
+Per-dimension confidence is computed either by an AI pass (`calculateConfidence`) or a deterministic local fallback (`calculateLocalConfidence` in `server/services/digital-twin-analysis.js`) that scores each Big Five dimension plus communication from document evidence. Results persist at `meta.confidence`.
+
+Gap recommendations identify the lowest-confidence aspects, generate specific questions to fill them, and prioritize enrichment categories by confidence gap. They regenerate after enrichment answers and data imports.
+
+## Behavioral Feedback Loop
+
+`server/services/feedbackLoop.js` captures "sounds like me" / "doesn't sound like me" validations on twin responses, tracks feedback patterns, and adjusts per-document weights used in confidence scoring and context assembly. Feedback persists in `feedback.json` (peer-synced). Routes: `POST /feedback`, `GET /feedback/stats`, `POST /feedback/recalculate`, `GET /feedback/recent`.
+
+## External Data Import
+
+`server/services/digital-twin-import.js` reduces manual input by importing:
+
+- **Goodreads** CSV export (reading preferences)
+- **Spotify** extended streaming history JSON (music profile)
+- **Letterboxd** film export
+- **iCal** calendar files — event categorization and recurring-pattern analysis (routines)
+
+Routes: `GET /import/sources`, `POST /import/analyze`, `POST /import/save`.
+
+## Transcript & Image Analysis
+
+Multi-modal capture works on pasted/uploaded artifacts — there is no live audio or video capture infrastructure:
+
+- **Interview analysis** (`POST /interview/analyze`) — extracts traits from a pasted conversation transcript
+- **Spoken vs. written style comparison** (`POST /style/spoken-written`, `digital-twin-style-comparison.js`) — compares a pasted speech transcript against written samples; the output is qualitative (spoken/written profiles, differences, a suggested communication profile), not a numeric match score
+- **Image identity** (`POST /identity/image`, `digital-twin-image-identity.js`) — analyzes an uploaded image for identity/visual-spec content
+
+## Behavioral Testing Suites
+
+All run from the Test tab, graded by an LLM scorer with pass/partial/fail verdicts (`parseScorerVerdict`), with per-suite run history:
+
+- **Behavioral tests** — the base suite plus AI-generated dynamic tests (see [Soul System](./soul-system.md))
+- **Multi-turn conversation suite** (`MULTI_TURN_SUITE.md`, `digital-twin-multi-turn-testing.js`) — plays each scenario's user turns in order (the twin sees its own prior replies) and grades whether the twin stayed consistent across the whole conversation: not contradicting earlier turns, caving to repeated pushback, or forgetting a stated constraint
+- **Values-alignment suite** (`VALUES_ALIGNMENT_SUITE.md`, `digital-twin-values-testing.js`) — poses ethical dilemmas and grades each answer against the ranked values hierarchy
+- **Adversarial boundary suite** (`ADVERSARIAL_BOUNDARY_SUITE.md`, `digital-twin-adversarial-testing.js`) — tries to manipulate the embodied twin (authority pressure, flattery, guilt, incremental escalation, harmful reframing) into crossing a stated boundary; grades held / partial / breached
+
+Suite spec documents ship in `data.reference/digital-twin/`.
+
+## Personas & Context Switching
+
+`server/services/digital-twin-personas.js` provides named personas (e.g. Professional, Casual, Family) with full CRUD, stored in `meta.personas`. One persona is active at a time (`meta.settings.activePersonaId`); its `traitAdjustments` blend over the base twin's quantitative traits to produce a per-context communication calibration. Test runs (behavioral and multi-turn) can execute *as* a selected persona, and each run-history entry records which persona it embodied.
+
## UI Components
-- `PersonalityMap.jsx` - Radar chart of Big Five with confidence coloring
-- `ConfidenceGauge.jsx` - Per-dimension confidence indicator
-- `GapRecommendations.jsx` - Prioritized enrichment suggestions
+Page: `client/src/pages/DigitalTwin.jsx`. Quantitative-layer components in `client/src/components/digital-twin/`:
-## API Endpoints
+- `PersonalityMap.jsx` — radar chart of Big Five with confidence coloring
+- `ConfidenceGauge.jsx` — per-dimension confidence indicator
+- `GapRecommendations.jsx` — prioritized enrichment suggestions
+- `InterviewAnalysisCard.jsx`, `PersonaBadge.jsx`, `tabs/AdversarialBoundaryPanel.jsx`, and the tab panels under `tabs/`
+
+## API Endpoints (quantitative layer)
| Route | Description |
|-------|-------------|
@@ -93,41 +96,29 @@ traits: {
| GET /api/digital-twin/confidence | Get confidence scores |
| POST /api/digital-twin/confidence/calculate | Recalculate confidence |
| GET /api/digital-twin/gaps | Get gap recommendations |
+| POST /api/digital-twin/feedback | Submit "sounds like me" validation |
+| GET/POST /api/digital-twin/feedback/* | Feedback stats, recalculate weights, recent |
+| GET/POST /api/digital-twin/{values,adversarial,multi-turn}-tests[/run,/history] | Testing suites |
+| GET/POST/PUT/DELETE /api/digital-twin/personas[/:id,/active] | Persona CRUD + active selection |
+| GET/POST /api/digital-twin/import/* | External data import |
+| POST /api/digital-twin/interview/analyze | Transcript trait extraction |
+| POST /api/digital-twin/style/spoken-written | Spoken vs written comparison |
+| POST /api/digital-twin/identity/image[/save] | Image identity analysis |
+| GET/POST/DELETE /api/digital-twin/snapshots[/:id,/compare] | Twin snapshots and comparison |
-## Planned Phases
-
-### Phase 3: Behavioral Feedback Loop
-- Response validation: "sounds like me" / "not quite me" ratings
-- Feedback analysis and document improvement suggestions
-- Adaptive document weighting based on feedback patterns
-
-### Phase 5: Multi-Modal Personality Capture
-- Voice analysis for speech patterns
-- Video interview for facial expressions and gestures
-- Comparison of spoken vs written style
-
-### Phase 6: Advanced Behavioral Testing
-- Complex multi-turn conversation scenarios — **done**: the Test tab's multi-turn suite (`MULTI_TURN_SUITE.md`) plays each scenario's user turns in order (the twin sees its own prior replies) and grades whether the twin stayed consistent / partial / inconsistent across the whole conversation — not contradicting earlier turns, caving to repeated pushback, or forgetting a stated constraint
-- Ethical dilemma tests aligned with stated values — **done**: the Test tab's values-alignment suite poses dilemmas and grades each answer against the user's ranked values hierarchy
-- Quantitative scoring of communication style match
-- Adversarial testing of boundaries — **done**: the Test tab's adversarial-boundary suite (`ADVERSARIAL_BOUNDARY_SUITE.md`) tries to manipulate the embodied twin (authority pressure, flattery, guilt, incremental escalation, harmful reframing) into crossing a stated boundary, and grades each response held / partial / breached
+The document/test/enrich/export endpoints shared with the document workflow are listed in [Soul System](./soul-system.md).
-### Phase 7: Twin Personas & Context Switching
-- Named personas (Professional, Casual, Family, Creative)
-- Blending rules for trait variation per context
-- Per-persona testing — **done**: the Test tab can run the behavioral and values-alignment suites *as* a selected persona (or the base twin), and each run-history entry records which persona it embodied
+## Not Built
-## Success Metrics
+Kept as an honest record of the original roadmap's unshipped ideas:
-| Metric | Current | Target |
-|--------|---------|--------|
-| Behavioral test pass rate | ~70% | >90% |
-| Enrichment category coverage | Manual | Confidence-guided |
-| User feedback: "sounds like me" | N/A | >85% |
-| Time to usable twin | Hours | <30 min |
-| Trait confidence coverage | 0% | >80% across all dimensions |
+- Live voice-audio analysis and video-interview capture (only pasted transcripts and uploaded images are supported)
+- A numeric communication-style match score (style comparison is qualitative)
+- Multi-persona blending (one active persona overlays the base twin)
+- Last.fm import (music import is Spotify-only)
## Related Features
-- [Soul System](./soul-system.md) - Document-based identity management
-- [Chief of Staff](./chief-of-staff.md) - Uses twin context in agent prompts
+- [Soul System](./soul-system.md) — document-based identity management (the document workflow this layer builds on)
+- [Unified Identity System](./identity-system.md) — genome/chronotype/taste/goals identity architecture
+- [Chief of Staff](./chief-of-staff.md) — uses twin context in agent prompts
diff --git a/docs/features/identity-system.md b/docs/features/identity-system.md
index 7c7951d38e..2fdf487625 100644
--- a/docs/features/identity-system.md
+++ b/docs/features/identity-system.md
@@ -1,6 +1,8 @@
# Unified Digital Twin Identity System (M42)
> **Status:** design plan, since largely implemented (`server/services/identity.js`, `server/routes/identity.js`, `data/digital-twin/{identity,chronotype,goals}.json`). Kept here as the identity-architecture reference; phase/roadmap sections below are the original plan, and a few items (e.g. `aesthetics.json`) remain unbuilt. For current behavior, trust the code paths named in each section.
+>
+> Three docs cover the digital-twin subsystem from different angles: [Soul System](./soul-system.md) (the **document workflow**), [Digital Twin](./digital-twin.md) (the **quantitative modeling layer**), and this one (the **unified identity architecture**).
Connects Genome (117 markers, 32 categories), Chronotype (5 sleep markers + behavioral), Aesthetic Taste (P2 complete, P2.5 adds twin-aware prompting), and Mortality-Aware Goals into a single coherent Identity architecture with cross-insights engine.
diff --git a/docs/features/openclaw-operator-chat.md b/docs/features/openclaw-operator-chat.md
index 2c0fac9ce5..d3846dec93 100644
--- a/docs/features/openclaw-operator-chat.md
+++ b/docs/features/openclaw-operator-chat.md
@@ -1,446 +1,74 @@
# OpenClaw Operator Chat
-> **Status: implemented.** See `server/routes/openclaw.js`, `server/integrations/openclaw/api.js`, `client/src/pages/OpenClaw.jsx`, and the client service `client/src/services/apiOpenclaw.js` (not the proposed `openclaw.js`). The shipped endpoint surface differs from this proposal: `GET /api/openclaw/status`, `GET /api/openclaw/sessions`, `GET/POST /api/openclaw/sessions/:id/messages`, and streaming `POST /api/openclaw/sessions/:id/messages/stream`. The proposed `POST /sessions`, `GET /jobs`, `GET /subagents`, and `POST /context/compose` were not built.
-
-A generic, first-party operator chat surface inside PortOS that allows a user to communicate with a local or privately reachable OpenClaw runtime without relying on third-party messaging providers like Telegram.
+A generic, first-party operator chat surface inside PortOS for talking to a local or privately reachable [OpenClaw](https://github.com/openclaw/openclaw) runtime — without routing sensitive operator conversations through third-party messaging providers like Telegram.
## Why this exists
-PortOS is already reachable over Tailscale and is intended to be a secure, self-hosted operating surface. For sensitive operator work, routing chat through Telegram or another third-party messaging network adds avoidable privacy and security exposure.
-
-This feature adds a **generic** assistant/operator chat module to PortOS so users can:
-
-- chat with their assistant directly inside PortOS
-- inspect session state without leaving the app
-- keep sensitive machine/admin context off third-party transports
-- use PortOS as a first-party local operator console
-
-## Critical product constraint
-
-PortOS is a public open-source project used by many people.
-
-Therefore:
-
-- **do not bake any private assistant identity into product features**
-- **do not assume one specific assistant persona or relationship model**
-- **do not assume one specific machine/network topology**
-- **do not assume OpenClaw is always present**
-
-This feature must remain:
-
-- generic
-- optional
-- instance-configurable
-- safe for users running their own OpenClaw or no assistant at all
-
-Identity, assistant naming, local network details, and machine-specific behavior must live in local/private configuration or git-ignored instance data.
-
-## Product framing
-
-This should be presented as something like:
-
-- **Operator Chat**
-- **Assistant Console**
-- **OpenClaw**
-- **Runtime Chat**
-
-Not:
-
-- a hardcoded persona name
-- a product-level "Rowan" feature
-- a fixed Chief-of-Staff replacement
-
-## Goals
-
-1. Provide a first-party chat UI inside PortOS for talking to an assistant/runtime.
-2. Reduce reliance on Telegram for operator/admin conversations.
-3. Keep the feature generic enough for any PortOS instance to connect to its own OpenClaw deployment.
-4. Preserve clean boundaries between:
- - PortOS UI
- - assistant runtime
- - private instance config
-5. Make chat adjacent to PortOS state, apps, repos, tasks, and services.
-
-## Non-goals
-
-- replacing all external messaging integrations
-- embedding assistant identity into PortOS core
-- making PortOS depend on OpenClaw to function
-- exposing private machine details through public/open-source defaults
-- coupling this feature tightly to one user's workflow
-
-## Existing PortOS extension points that make this feasible
-
-PortOS already has several relevant building blocks:
-
-### UI patterns
-- `client/src/pages/ChiefOfStaff.jsx`
-- `client/src/components/cos/*`
-- existing tabbed operational UI patterns
-- event logs, terminal-style panels, status indicators
-
-### Networking and real-time
-- `client/src/services/socket.js` uses relative paths and is already Tailscale-friendly
-- `server/index.js` already mounts Socket.IO and API routes for local/private access
-
-### Agent/runtime patterns
-- CoS page and agent runner already model:
- - status
- - running jobs
- - event streams
- - agent outputs
-- `server/cos-runner/` already provides a process/runtime management pattern
-
-### Messaging patterns
-- `client/src/pages/Messages.jsx`
-- `server/routes/messages.js`
-- existing draft/message/thread models can inform UX, even if operator chat is a separate domain
-
-### Security assumptions
-- PortOS already assumes trusted-network/private access via Tailscale
-- this is compatible with a local-first assistant console
-
-## High-level architecture
-
-### Separation of concerns
-
-#### PortOS is responsible for:
-- operator UI
-- session list UI
-- message history UI
-- context attachment UX
-- runtime connection status
-- local authentication to PortOS itself
-- optional linking between chat and PortOS pages/apps/tasks
-
-#### OpenClaw is responsible for:
-- session runtime
-- message handling
-- tool execution
-- subagent/session orchestration
-- response generation
-- runtime-side security/policy enforcement
-
-### Integration model
-
-PortOS should talk to OpenClaw through a small adapter/integration layer, not by reimplementing assistant logic.
-
-Suggested shape:
-
-- **server integration module**
- - `server/integrations/openclaw/*`
-- **PortOS API routes**
- - `server/routes/openclaw.js`
-- **client service wrapper**
- - `client/src/services/openclaw.js`
-- **UI page**
- - `client/src/pages/OpenClaw.jsx` or `client/src/pages/OperatorChat.jsx`
-
-## Proposed capabilities
-
-### Phase 1 — MVP: first-party assistant chat
-
-A page inside PortOS where the user can:
-
-- see whether an OpenClaw runtime is configured/reachable
-- view available sessions or a default session
-- load recent message history
-- send a message
-- receive assistant replies
-- see timestamps and basic status
-
-Suggested features:
-
-- session selector
-- message timeline
-- input composer
-- connection status badge
-- send/receive loading states
-- optional "reply in current session" mode
-
-### Phase 2 — operator-aware context
-
-Allow the user to send a message with attached PortOS context such as:
-
-- current page/app
-- selected repo/app
-- active task
-- system status summary
-- current machine/app metadata
-
-Examples:
+PortOS is reachable over Tailscale and is intended to be a secure, self-hosted operating surface. For sensitive operator work, routing chat through Telegram or another third-party messaging network adds avoidable privacy and security exposure. Operator Chat keeps assistant conversations first-party: chat with your assistant directly inside PortOS, inspect session state without leaving the app, and keep machine/admin context off third-party transports.
-- "look at this app"
-- "review the current queue"
-- "inspect the service behind this page"
-- "summarize what changed here"
+## Product constraints
-This context should be explicit and user-controlled, not silently leaked.
+PortOS is a public open-source project used by many people, so this feature is:
-### Phase 3 — runtime visibility and controls
+- **Generic** — no assistant identity, persona, or relationship model is baked into product code.
+- **Optional** — PortOS works cleanly without OpenClaw; the page degrades gracefully when unconfigured.
+- **Instance-configurable** — identity, endpoints, tokens, and machine topology live in local, git-ignored config (`data/openclaw/config.json`) or environment variables, never in committed defaults.
-Expose runtime information such as:
+## Architecture
-- connected runtime endpoint
-- active sessions
-- spawned subagents/jobs
-- recent tool actions
-- execution status
-- reminders/cron job visibility if supported
+PortOS talks to the OpenClaw runtime through a thin adapter — it does not reimplement assistant logic:
-This should feel like an operator console, not just a basic chat box.
+- **Integration module** — `server/integrations/openclaw/api.js` is the entire runtime client: config loading, auth headers, upstream calls, session/message/status normalization, and error translation. It reaches the runtime through two upstream paths: a tool-invoke endpoint (`/tools/invoke`, for `sessions_list` / `sessions_history`) and an OpenAI-Responses-style endpoint (`/v1/responses`, for send + stream with `model: openclaw:<agentId>`).
+- **Routes** — `server/routes/openclaw.js`, mounted at `/api/openclaw`.
+- **Client service** — `client/src/services/apiOpenclaw.js` (status, sessions, messages, non-streaming send, SSE streaming send).
+- **Page** — `client/src/pages/OpenClaw.jsx` at `/openclaw` (registered in `App.jsx` and in `NAV_COMMANDS` under the Brain section, so it is reachable from ⌘K and voice nav).
-### Phase 4 — structured PortOS actions
+Responsibility split: PortOS owns the operator UI, session list, message history, attachment/context UX, and runtime connection status. OpenClaw owns the session runtime, message handling, tool execution, orchestration, response generation, and runtime-side policy enforcement.
-Optional future capabilities:
+## API surface
-- ask assistant to inspect a repo and open linked results
-- pass page context to assistant with one click
-- show inline approvals/review items
-- link assistant output to Review / Goals / Apps / Brain surfaces
+| Route | Description |
+|-------|-------------|
+| `GET /api/openclaw/status` | Configured? Reachable (live `sessions_list` probe)? Default session, label, runtime info (allowlisted fields only — never the raw upstream payload) |
+| `GET /api/openclaw/sessions` | List sessions discovered from the runtime |
+| `GET /api/openclaw/sessions/:id/messages` | Message history (`?limit=`, default 50, max 200) |
+| `POST /api/openclaw/sessions/:id/messages` | Send a message (non-streaming) |
+| `POST /api/openclaw/sessions/:id/messages/stream` | Send a message, stream the reply as SSE |
-## Privacy and security model
+Both send routes validate with a shared Zod schema: a required non-empty `message`, an optional `context` object (`appName`, `repoPath`, `directoryPath`, `extraInstructions` — flattened into prose server-side and prepended to the input), and optional `attachments` (max 8, image/file, base64 or URL, ~10 MB per attachment and 50 MB combined). Send routes return 503 `OPENCLAW_UNCONFIGURED` when not configured; the history route soft-fails to `{ configured: false, reachable: false, messages: [] }` instead.
-### Public/open-source code may contain
-- generic OpenClaw connector support
-- generic UI for assistant/runtime chat
-- generic settings for endpoint/auth/session behavior
-- generic local data storage hooks
+**Proposed but not built** (kept here as an honest record of the original proposal's larger surface): `POST /api/openclaw/sessions` (create/bind a session — sessions are discovery-only today; the client injects a synthetic "default" session but cannot create one), `GET /api/openclaw/jobs`, `GET /api/openclaw/subagents`, and `POST /api/openclaw/context/compose` (context is composed inline on the send payload instead of via a separate endpoint).
-### Private instance-local data must contain
-- assistant identity/persona
-- local machine topology
-- hostnames, ports, URLs, tokens
-- role preferences
-- private operator notes
-- machine-specific context mapping
+## UI
-### Rules
-- no private assistant identity in product defaults
-- no machine-specific hostnames or ports in committed code/docs beyond generic examples
-- no assumptions about Telegram or other third-party transports
-- no assumptions that all users want autonomous operator chat
-- fail gracefully when OpenClaw is unconfigured or unreachable
+Two-column layout on `/openclaw`:
-## Configuration model
+- **Left sidebar** — runtime status panel (label, configured, reachable, default session), session list with a "Show older chats" partition, and a refresh action.
+- **Main panel** — role-tagged message timeline with timestamps and per-message attachment chips, a streaming placeholder while the assistant replies, and a composer (⌘↵ to send, Stop button for in-flight streams).
-### Public-safe config surface
-PortOS can expose generic settings like:
+Context and attachments are explicit and user-controlled, not silently leaked: an app/repo picker (`AppContextPicker`), a directory-context input, an extra-instructions input, and file/image attachments via drag-and-drop, paste, or file picker (`useOpenClawAttachments`; streaming via `useOpenClawStream`).
-```json
-{
- "enabled": true,
- "provider": "openclaw",
- "transport": "http",
- "sessionMode": "default",
- "allowContextAttachments": true,
- "showRuntimeStatus": true
-}
-```
+## Configuration
-### Private instance-local config
-Actual endpoint/auth/session defaults should live in local, git-ignored config, for example:
+Config resolves in two layers — environment variables override the file:
-```json
-{
- "enabled": true,
- "baseUrl": "http://100.x.x.x:PORT",
- "authToken": "...",
- "defaultSession": "main",
- "label": "Local Operator Runtime",
- "paths": {
- "toolsInvoke": "/tools/invoke",
- "responses": "/v1/responses"
- }
-}
-```
+- **File**: `data/openclaw/config.json` (git-ignored; reference template at `data.reference/openclaw/config.json` ships with `enabled: false`). Fields: `enabled`, `baseUrl`, `authToken`, `defaultSession`, `label`, `paths` (upstream path overrides).
+- **Env**: `OPENCLAW_ENABLED`, `OPENCLAW_BASE_URL`, `OPENCLAW_AUTH_TOKEN`, `OPENCLAW_AUTH_HEADER` (default `Authorization`), `OPENCLAW_AUTH_SCHEME` (default `Bearer`; empty string = token-only), `OPENCLAW_LABEL`, `OPENCLAW_DEFAULT_SESSION`, `OPENCLAW_DEFAULT_AGENT_ID` (default `main`), `OPENCLAW_TIMEOUT_MS` (default 15000).
-The exact file/location should align with PortOS local config conventions, but must remain out of public repo defaults if it contains private topology or credentials.
-
-## Suggested API surface inside PortOS
-
-These would be PortOS routes that proxy or adapt to an OpenClaw runtime.
-
-### Status
-- `GET /api/openclaw/status`
- - runtime reachable?
- - configured?
- - default session?
-
-### Sessions
-- `GET /api/openclaw/sessions`
-- `GET /api/openclaw/sessions/:id/messages`
-- `POST /api/openclaw/sessions/:id/messages`
-- `POST /api/openclaw/sessions`
- - create or bind a new operator session if needed
-
-### Optional runtime actions
-- `GET /api/openclaw/jobs`
-- `GET /api/openclaw/subagents`
-- `POST /api/openclaw/context/compose`
- - build a safe context bundle from current PortOS state
-
-These should remain thin adapters where possible.
-
-## UI proposal
-
-### New page
-A new page such as:
-
-- `/openclaw`
-- `/operator-chat`
-- `/assistant`
-
-I recommend **`/openclaw`** or **`/operator-chat`**.
-
-### Page layout
-
-#### Left rail
-- runtime status
-- session list
-- quick actions
-- optional recent tasks/subagents
-
-#### Main panel
-- message timeline
-- streamed assistant replies
-- tool activity summaries (optional)
-- context chips
-
-#### Right rail (future)
-- current page/app context
-- recent system events
-- inspectable attachments
-
-### UX principles
-- chat should feel calm and operational, not social-media-like
-- context attachments should be explicit
-- runtime status should be visible
-- errors should be actionable
-- chat must not block normal PortOS use
-
-## Integration with existing PortOS surfaces
-
-### Chief of Staff
-Relationship:
-- CoS remains an autonomous/managed system surface
-- OpenClaw chat is a direct operator conversation surface
-
-Possible links:
-- "Ask about this CoS task"
-- "Open in Operator Chat"
-- "Send BTW / additional context"
-
-### Messages
-Relationship:
-- Messages page manages external communications/accounts
-- OpenClaw Operator Chat is an internal/local console
-
-This distinction should stay clear in the UI.
-
-### Review
-Assistant outputs that need human attention could eventually create Review items.
-
-### Apps / Instances / DevTools / Shell
-These are strong context sources for chat attachments and operator actions.
-
-## Failure modes to design for
-
-- OpenClaw unreachable
-- OpenClaw configured incorrectly
-- runtime session missing/expired
-- streaming disconnects
-- PortOS page context too large/noisy
-- user accidentally sharing more context than intended
-- partial feature deployment on instances without OpenClaw
+"Configured" requires `enabled` not false AND a well-formed `http:`/`https:` `baseUrl` (other schemes are rejected). There is no settings-page UI for this — it is deliberately file/env-only, keeping private topology out of synced app state.
## Graceful degradation
-If OpenClaw is not configured:
-- hide the page by default or show a setup screen
-- do not break PortOS navigation
-- do not throw noisy errors in unrelated pages
-
-If runtime is unavailable:
-- show disconnected status
-- preserve local UI state where possible
-- allow retry/reconnect
-
-## Suggested implementation order
-
-### Step 1 — Spec and extension-point audit
-- confirm PortOS route/page placement
-- confirm local config pattern
-- confirm whether proxying through PortOS server is preferable to direct browser calls
-
-### Step 2 — Thin server adapter
-- add OpenClaw integration module
-- add status/session/message proxy routes
-- keep adapter minimal
-
-### Step 3 — MVP UI page
-- session list
-- message timeline
-- composer
-- status badge
-
-### Step 4 — context attachments
-- current page/app/task context chips
-- explicit attach/send flow
-
-### Step 5 — runtime/operator extras
-- subagents
-- jobs
-- session status
-- linked review actions
-
-## Recommended design decisions
-
-1. **Keep the product generic**
- - no private assistant identity in public code
-
-2. **Use local/private config for identity and topology**
- - assistant name, endpoint, role, machine map stay local
-
-3. **Proxy through PortOS server first**
- - keeps auth/config simpler
- - avoids browser-side exposure of private runtime details
- - fits existing PortOS API patterns
-
-4. **Do not merge this into Messages**
- - operator chat is a different domain than email/SMS/Telegram messaging
-
-5. **Keep OpenClaw optional**
- - PortOS must still work cleanly without it
-
-## Open questions
-
-1. Should OpenClaw chat live as a top-level page or under Chief of Staff?
- - My recommendation: top-level page or top-level tool, not hidden under CoS
-
-2. Should PortOS support multiple runtimes or one default runtime first?
- - My recommendation: one default runtime first, design for future plurality
-
-3. Should chat sessions be created/managed by PortOS or discovered from OpenClaw?
- - My recommendation: discover existing sessions first, optionally allow PortOS to create a dedicated operator session
-
-4. Should tool activity be shown in the timeline from the start?
- - My recommendation: basic status first, detailed tool activity later
-
-## Initial deliverables
+- Unconfigured: the page stays visible with an "Unconfigured" badge, an empty-state prompt to add local config, a disabled composer, and no noisy errors elsewhere in the app.
+- Unreachable: status shows "Unavailable" with the probe's error message; `getRuntimeStatus`/`listSessions` return structured `{ configured, reachable, ... }` payloads rather than throwing.
+- The status endpoint's runtime info is allowlisted so upstream payloads and tokens never leak to the client.
-- this feature spec
-- PortOS extension-point audit
-- minimal server-side OpenClaw adapter
-- minimal `/openclaw` page
-- local private config example (git-ignored)
+## Relationship to other surfaces
-## Bottom line
+- **Chief of Staff** — CoS remains the autonomous/managed agent surface; Operator Chat is a direct conversation surface. They are separate domains.
+- **Messages** — the Messages page manages external communications/accounts; Operator Chat is an internal/local console. The distinction is deliberate.
-PortOS should gain a **generic, optional, first-party OpenClaw operator chat surface** so users can communicate with their assistant/runtime directly over their private network instead of depending on Telegram.
+## Tests
-That feature should be:
-- generic in product code
-- private in identity/config
-- optional per instance
-- aligned with existing PortOS CoS, socket, and Tailscale architecture
+- `server/routes/openclaw.test.js` — route coverage: status/sessions configured + unconfigured, history limits and clamping, send validation (missing message, attachment count/size caps), 503 guards, SSE content-type and event streaming.
+- `server/integrations/openclaw/api.test.js` — `getRuntimeStatus` field allowlisting, unreachable → `runtime: null`, unconfigured → no fetch.
diff --git a/docs/features/post.md b/docs/features/post.md
index d2f104532f..d08dcf68a8 100644
--- a/docs/features/post.md
+++ b/docs/features/post.md
@@ -1,190 +1,105 @@
# POST (Power On Self Test)
-## Overview
+POST is a daily cognitive self-test and training system within MeatSpace. Sessions take ~5 minutes and balance testing with active training — teaching techniques and building skills, not just measuring them.
-POST is a daily cognitive self-test and training system within MeatSpace. It covers five cognitive domains: **Math**, **Memory**, **Wordplay**, **Verbal Agility**, and **Imagination**. Sessions are designed to take ~5 minutes and balance testing with active training — teaching techniques and building skills, not just measuring them.
+> The POST overhaul epic (#1985) is actively evolving this area (responsive layouts, analytics, spaced repetition, adaptive difficulty). This doc describes the shipped state; expect churn.
## Cognitive Domains
-### 1. Mental Math (existing)
-- **Doubling Chain** — sequential doubling from a seed number
-- **Serial Subtraction** — countdown by a fixed subtrahend (e.g., 100 - 7 - 7 - 7...)
-- **Multiplication** — random N-digit multiplication problems
-- **Powers** — base^exponent calculations
-- **Estimation** — approximate large arithmetic within tolerance
+Six drill domains, each individually enable/disable-able (`client/src/components/meatspace/post/constants.js`):
-### 2. Memory (new: Memory Builder)
-Configurable memory training for songs, poems, sequences, speeches, or any ordered content.
+### Mental Math (~60s)
+`doubling-chain` (sequential doubling from a seed), `serial-subtraction` (countdown by a fixed subtrahend), `multiplication` (random N-digit problems), `powers` (base^exponent), `estimation` (approximate large arithmetic within tolerance).
-**Built-in Content:**
-- Tom Lehrer's "The Elements" — periodic table set to music, with interactive element identification
+### Memory (~90s)
+Memory Builder drills drawn from the user's memory items: `memory-sequence` and `memory-element-flash` inside scored sessions (`memory-fill-blank` exists for standalone practice). See Memory Builder below.
-**Custom Content:**
-- User adds any text/song/sequence they want to memorize
-- System breaks it into chunks and builds progressive recall exercises
+### Wordplay (~60s)
+`pun-wordplay` and `word-association`, plus the cacheable wordplay set: `compound-chain`, `bridge-word`, `double-meaning`, `idiom-twist`. All LLM-scored.
-**Training Modes:**
-- **Learn** — progressive reveal: show content line-by-line, then chunk-by-chunk, building from small to large
-- **Fill-in-the-Blank** — show partial content with blanks to fill; difficulty increases as more words are blanked
-- **Sequence Recall** — given a starting point, continue the sequence from memory
-- **Random Prompt** — given a random line/chunk, identify what comes before and after
-- **Speed Run** — recite the full sequence as fast as possible with accuracy tracking
+### Verbal Agility (~60s)
+`wit-comeback` (respond to scenarios with humor), `verbal-fluency` (name category items against the clock), `story-recall` (read a paragraph, answer detail questions). LLM-scored.
-**Spaced Repetition:**
-- Track per-chunk mastery (how often recalled correctly, average response time)
-- Focus training on weakest chunks
-- Graduated difficulty: new items start with heavy hints, mastered items tested with no hints
+### Imagination & Ideation (~60s)
+`what-if` (absurd hypotheticals), `alternative-uses` (divergent-thinking classic), `story-prompt` (micro-story from 3 random words), `invention-pitch`, `reframe` (recast a negative situation positively/humorously). LLM-scored for originality, elaboration, and feasibility.
-### 3. Wordplay (existing, enhanced)
-- **Pun/Wordplay** — create puns on given topics (LLM-scored)
-- **Word Association** — free-associate with prompt words (LLM-scored)
+### Cognitive (~90s)
+Classic psychometric drills, scored deterministically server-side (`server/services/meatspacePostCognitive.js`, runner `PostCognitiveDrillRunner.jsx`): `n-back`, `digit-span`, `stroop`, `schulte-table`, `mental-rotation`, `reaction-time`.
-### 4. Verbal Agility (existing)
-- **Wit Comeback** — respond to scenarios with humor (LLM-scored)
-- **Verbal Fluency** — name items in a category within time limit (LLM-scored)
-- **Story Recall** — read a paragraph, answer detail questions (LLM-scored)
+### Morse (training-only)
+`MorseTrainer.jsx` (`morse-copy`, `morse-head-copy`, `morse-send`, deep-linked at `/post/morse/:mode`) is deliberately excluded from scored sessions — Morse practice posts to the training log only.
-### 5. Imagination & Ideation (new)
-Creative thinking exercises scored by AI for originality, elaboration, and feasibility.
+## Session Structure
-- **What If** — respond to absurd hypothetical scenarios ("What if gravity reversed for 10 minutes every Tuesday?")
-- **Alternative Uses** — list creative uses for a common object (divergent thinking classic)
-- **Story Prompt** — given 3 random words, create a micro-story connecting them
-- **Invention Pitch** — given a problem, pitch an inventive solution in 2-3 sentences
-- **Reframe** — take a negative situation and reframe it positively/humorously
+A POST session pulls drills from each enabled domain against the per-domain time budgets above (~5.5 minutes total with transitions; `DrillTransition.jsx` handles the interstitials). The session state machine is `client/src/hooks/usePostSession.js`.
-## Session Structure (~5 minutes)
+## Training vs Testing
-A POST session pulls one drill from each enabled domain, time-budgeted:
+The session launcher (`PostSessionLauncher.jsx`) has a per-session Test/Train toggle:
-| Domain | Drill Count | Time Budget |
-|--------|-------------|-------------|
-| Math | 1 drill (e.g., 10 multiplication problems) | ~60s |
-| Memory | 1 memory item exercise | ~90s |
-| Wordplay | 1 drill (e.g., 3 pun challenges) | ~60s |
-| Verbal | 1 drill (e.g., 1 story recall) | ~60s |
-| Imagination | 1 drill (e.g., 2 what-if prompts) | ~60s |
+- **Test** — timed, scored, saved to session history (`POST /api/meatspace/post/sessions`).
+- **Train** — immediate feedback, hints on wrong answers, not scored; entries go to a separate training log (`POST /api/meatspace/post/training`) with its own stats, streaks, and entries endpoints (`server/services/meatspacePostTraining.js` → `data/meatspace/post-training-log.json`).
-Total: ~5.5 minutes with transitions. Users can enable/disable any domain.
+## Memory Builder
-## Training vs Testing
+Configurable memory training for songs, poems, sequences, speeches, or any ordered content (`server/services/meatspacePostMemory.js`; client `MemoryBuilder.jsx`, `MemoryPractice.jsx`).
-Each domain supports two modes:
-- **Train** — learning-focused: hints, progressive difficulty, immediate feedback, no final score
-- **Test** — performance-focused: timed, scored, saved to session history
-
-The session launcher lets users pick mode per-domain. Training sessions are tracked separately (practice count, streaks) but don't contribute to the scored POST history.
-
-## Elements Song Memory Builder
-
-### Content Structure
-The Tom Lehrer "Elements Song" is stored as structured data:
-- Full lyrics split into lines
-- Each element name mapped to its atomic number and symbol
-- Musical phrases grouped for chunked learning
-
-### Interactive Features
-- **Karaoke Mode** — lyrics scroll with timing, user fills in blanked element names
-- **Element Flash** — show atomic number or symbol, user names the element (and vice versa)
-- **Sequence Game** — "What element comes after Arsenic in the song?"
-- **Progress Map** — periodic table colored by mastery (green = solid, yellow = shaky, red = unlearned)
-- **Audio Reference** — link to the song for listening practice (user provides their own audio file)
-
-### Data Model
-```json
-{
- "memoryItems": [
- {
- "id": "elements-song",
- "title": "The Elements (Tom Lehrer)",
- "type": "song",
- "builtin": true,
- "content": {
- "lines": [
- { "text": "There's antimony, arsenic, aluminum, selenium", "elements": ["Sb", "As", "Al", "Se"] },
- { "text": "And hydrogen and oxygen and nitrogen and rhenium", "elements": ["H", "O", "N", "Re"] }
- ],
- "chunks": [
- { "id": "verse-1", "lineRange": [0, 3], "label": "Verse 1" }
- ]
- },
- "mastery": {
- "overallPct": 45,
- "chunks": { "verse-1": { "correct": 12, "attempts": 20, "lastPracticed": "2026-03-08" } },
- "elements": { "Sb": { "correct": 5, "attempts": 5 }, "As": { "correct": 3, "attempts": 5 } }
- }
- }
- ]
-}
-```
-
-### Custom Memory Items
-Users can add their own items via the Config page:
-```json
-{
- "id": "user-uuid",
- "title": "Gettysburg Address",
- "type": "speech",
- "builtin": false,
- "content": {
- "lines": [
- { "text": "Four score and seven years ago our fathers brought forth on this continent, a new nation" },
- { "text": "conceived in Liberty, and dedicated to the proposition that all men are created equal." }
- ],
- "chunks": [
- { "id": "opening", "lineRange": [0, 1], "label": "Opening" }
- ]
- },
- "mastery": {}
-}
-```
+- **Built-in content**: Tom Lehrer's "The Elements" (code-embedded, id `elements-song`, non-deletable) with per-line element mappings and a specialized `ElementsSong.jsx` UI with periodic-table visualization.
+- **Custom items**: users add any text/song/sequence; the system chunks it into progressive recall exercises.
+- **Practice modes** (`MemoryPractice.jsx`): `learn` (progressive reveal), `fill-blank`, `sequence` (continue from a starting point), `speed-run`, and `spaced` (spaced-repetition mode focusing the weakest chunks with graduated hints).
+- **Spaced repetition**: an SM-2-inspired scheduler tracks per-chunk `ease`/`intervalDays`/`nextReview` (ease clamped 1.3–5, intervals capped at 365 days, misses reset to relearn). `GET /post/memory-items/due` surfaces what's due; per-item and per-chunk mastery are queryable.
## Scoring
-- **Math**: accuracy (80%) + speed bonus (20%), server-rescored
-- **Memory**: chunk accuracy (70%) + sequence accuracy (20%) + speed (10%)
-- **Wordplay/Verbal/Imagination**: LLM-scored on quality criteria (80%) + speed bonus (20%)
-- **Session score**: weighted average across all completed drills
+- **Math**: server-rescored — the server strips client-provided correctness and re-derives expected answers (`meatspacePost.js`, "never trust client-provided expected"); estimation compares within tolerance. Accuracy plus speed bonus.
+- **Cognitive**: deterministic server-side rescoring per drill type.
+- **Wordplay/Verbal/Imagination**: LLM-scored against per-drill rubrics (e.g. wit-comeback: humor 40% / cleverness 30% / relevance 30%), blended as quality 80% + speed bonus 20% (`server/services/meatspacePostLlm.js`).
+- **Session score**: weighted average across completed drills.
+
+## Adaptive Difficulty
+
+Opt-in adaptive tuning for math drills (`server/lib/postAdaptive.js`): recent scored performance nudges drill parameters, with a transparent preview of what would change (`GET /api/meatspace/post/adaptive-preview`).
+
+## Drill Cache
+
+The four cacheable wordplay types are pre-generated so drills serve instantly (`server/services/meatspacePostDrillCache.js` → `data/meatspace/post-drill-cache.json`, seeded from `data.reference/`). Per the AI-provider policy, a cold cache is never filled silently: boot loads only what's on disk, and the bulk fill runs solely from `POST /api/meatspace/post/drill-cache/fill` behind a consent prompt in `WordplayTrainer.jsx` that names the provider/model. Incremental top-ups after the user has engaged are silent by design.
+
+## Daily Reminder
+
+`server/services/meatspacePostReminder.js` schedules an optional daily POST reminder, re-registered whenever the config changes.
## Data Files
-- `data/meatspace/post-config.json` — drill settings, enabled modules, time limits
+- `data/meatspace/post-config.json` — drill settings, enabled domains, time limits
- `data/meatspace/post-sessions.json` — scored test session history
-- `data/meatspace/post-memory-items.json` — memory builder content and mastery tracking
-- `data/meatspace/post-training-log.json` — practice session log (unscored training)
+- `data/meatspace/post-memory-items.json` — memory builder content and mastery
+- `data/meatspace/post-training-log.json` — unscored training/practice log
+- `data/meatspace/post-drill-cache.json` — pre-generated wordplay drills
## Routes
-### Existing
-- `GET/PUT /api/meatspace/post/config` — drill configuration
-- `GET/POST /api/meatspace/post/sessions` — session CRUD
-- `GET /api/meatspace/post/sessions/:id` — single session
-- `GET /api/meatspace/post/stats` — rolling averages
-- `POST /api/meatspace/post/drill` — generate math or LLM drill
-- `POST /api/meatspace/post/score-llm` — score LLM drill responses
-
-### New (M55)
-- `GET/POST/PUT/DELETE /api/meatspace/post/memory-items` — memory item CRUD
-- `POST /api/meatspace/post/memory-items/:id/practice` — submit practice result, update mastery
-- `GET /api/meatspace/post/memory-items/:id/mastery` — get mastery breakdown
-- `POST /api/meatspace/post/drill` — extended to support the `imagination` drill type
-- `POST /api/meatspace/post/memory-drill` — generate memory drills (separate endpoint)
+All under `/api/meatspace` (`server/routes/meatspacePostRoutes.js`):
+
+- `GET/PUT /post/config` — drill configuration
+- `GET/POST /post/sessions`, `GET /post/sessions/:id` — scored session history
+- `GET /post/stats` — rolling averages
+- `POST /post/drill` — generate a drill (dispatches math / LLM / memory / cognitive)
+- `GET /post/adaptive-preview` — adaptive-difficulty preview
+- `POST /post/score-llm` — score LLM drill responses
+- `GET /post/drill-cache/status`, `POST /post/drill-cache/fill` — wordplay cache
+- `POST /post/training`, `GET /post/training/{stats,entries}` — training log
+- `GET/POST /post/memory-items`, `GET/PUT/DELETE /post/memory-items/:id` — memory item CRUD
+- `GET /post/memory-items/due` — spaced-repetition due list
+- `POST /post/memory-items/:id/practice` — submit practice result, update mastery
+- `GET /post/memory-items/:id/{mastery,chunk-mastery}` — mastery breakdowns
+- `POST /post/memory-drill` — generate memory drills
## UI Components
-### Existing
-- `PostTab` — view router (launcher, running, results, history, config)
-- `PostSessionLauncher` — start screen with drill summary
-- `PostDrillRunner` — math drill UI with timer
-- `PostLlmDrillRunner` — LLM drill UIs (word-association, story-recall, etc.)
-- `PostSessionResults` — score breakdown and save
-- `PostHistory` — date-range analytics with charts
-- `PostDrillConfig` — per-drill settings
-
-### New (M55)
-- `MemoryBuilder` — main memory training interface
-- `MemoryItemList` — browse/add/edit memory items
-- `MemoryPractice` — interactive practice with mode selection
-- `ElementsSong` — specialized Elements Song UI with periodic table visualization
-- `MasteryMap` — visual mastery progress (periodic table for elements, progress bar for generic items)
-- `ImaginationDrillRunner` — UI for imagination/ideation drills
+Container: `client/src/components/meatspace/tabs/PostTab.jsx` (view router: launcher, running, results, history, config). In `client/src/components/meatspace/post/`:
+
+- `PostSessionLauncher` — start screen with Test/Train toggle and drill summary
+- `PostDrillRunner` — math drills; `PostLlmDrillRunner` — all LLM drills (wordplay/verbal/imagination); `PostCognitiveDrillRunner` — cognitive drills
+- `PostSessionResults`, `PostHistory` (date-range analytics), `PostDrillConfig`
+- `MemoryBuilder`, `MemoryPractice`, `ElementsSong`
+- `WordplayTrainer` (standalone wordplay practice + cache-fill consent), `WordplayDrillUI`, `MorseTrainer`, `DrillTransition`
diff --git a/docs/features/soul-system.md b/docs/features/soul-system.md
index 54747d969e..cb9396404b 100644
--- a/docs/features/soul-system.md
+++ b/docs/features/soul-system.md
@@ -2,6 +2,8 @@
Digital twin identity scaffold management for creating and testing aligned AI personas.
+> Three docs cover the digital-twin subsystem from different angles: this one (the **document workflow** — soul markdown files, enrichment, testing, export), [Digital Twin](./digital-twin.md) (the **quantitative modeling layer** — traits, confidence, feedback, personas), and [Unified Identity System](./identity-system.md) (the **identity architecture** — genome, chronotype, taste, goals).
+
## Overview
LLMs can embody specific personas, but creating comprehensive identity documents and testing alignment across different models is manual and error-prone. The Soul System provides a structured approach to capturing, validating, and deploying personality models.
@@ -108,5 +110,6 @@ data/digital-twin/
## Related Features
-- [Digital Twin](./digital-twin.md) - Quantitative personality modeling
+- [Digital Twin](./digital-twin.md) - Quantitative personality modeling built on these documents
+- [Unified Identity System](./identity-system.md) - Genome/chronotype/taste/goals identity architecture
- [Chief of Staff](./chief-of-staff.md) - Uses soul context in agent prompts
diff --git a/docs/features/writers-room.md b/docs/features/writers-room.md
index 0e43242468..c16f083054 100644
--- a/docs/features/writers-room.md
+++ b/docs/features/writers-room.md
@@ -1,634 +1,118 @@
# Writers Room
-## Intent
+Writers Room is the PortOS workspace for creating, organizing, editing, analyzing, and adapting literary works: a focused writing environment with manual AI passes, a story bible, storyboarding, and bridges into the Creative Director and comic-pipeline media systems.
-Writers Room is the PortOS workspace for creating, organizing, editing, analyzing,
-and adapting literary works. It starts as a focused writing environment with
-manual AI review actions, then grows into the story-to-media pipeline: prose to
-script, script to character sheets and scene plans, scene plans to reference
-images and video renders, and a synchronized review surface that keeps prose,
-script, and media aligned.
+Every AI evaluation and render action is user-initiated or explicitly opted into — nothing runs on keystrokes or draft saves without the per-work Live Director opt-in described below.
-The first version should support three jobs:
+## Navigation & Layout
-1. Manage writing projects: folders, works, drafts, versions, notes, and status.
-2. Help the writer produce words: a "write for 10" exercise with timer, live
- word count, and progress tracking.
-3. Run explicit AI passes over the current draft: summaries, character and scene
- extraction, expansion recommendations, prose-to-script adaptation, and media
- planning.
+Routes (registered in `App.jsx` and `server/lib/navManifest.js` — `nav.writers-room`, `nav.writers-room.guide`):
-Realtime Creative Director feedback and background live analysis are intentionally
-future work. In the first implementation, every AI evaluation and render action is
-started by a user click.
+- `/writers-room` — landing (library + editor)
+- `/writers-room/works/:workId` — active work editor
+- `/writers-room/guide` — writing guide (length targets, craft reference)
-## Baseline
-
-`main` now contains both FLUX.2-klein image generation and the full Creative
-Director / media-job-queue surface — `feat/creative-director` was squash-merged
-as PR #191 (`9b36b900`). Phase 0 of this plan is therefore complete; Writers
-Room implementation starts directly on `main`.
+The page lives in the sidebar's **Create** group. The main workspace is `client/src/pages/WritersRoom.jsx` with a library pane (`LibraryPane.jsx`), the Markdown work editor (`WorkEditor.jsx`), and tool panels. The editor is plain Markdown — stable text ranges, reliable word count, low corruption risk for long prose.
-Reuse — do not rebuild — the existing image/video gen systems:
+## Writing Exercise ("write for 10")
-- `server/services/imageGen/` and `scripts/flux2_macos.py` for image renders.
-- `server/services/videoGen/` for LTX/MLX video renders.
-- `server/services/mediaJobQueue/` for serializing local image/video jobs.
-- `server/services/creativeDirector/` for treatment/scene/run orchestration.
-- `server/lib/mediaModels.js` as the source of truth for image/video models
- (including FLUX.2-klein image variants).
-
-## Product Shape
-
-### Navigation
-
-Routes:
-
-- `/writers-room` — Writers Room landing (library + editor)
-- `/writers-room/works/:id` — Active work editor
-
-Sidebar placement: a new top-level **Create** group that contains both
-**Media Gen** (default landing for the group) and **Writers Room**. Creative
-Director continues to live under `/media/creative-director` and is reachable from
-Writers Room via the render-plan handoff. Configuration surfaces (Prompts,
-Providers) stay under the existing **AI** group.
-
-Add navigation entries in both places PortOS currently needs them:
-
-- `client/src/components/Layout.jsx`
-- `server/lib/navManifest.js`
-
-### Primary Layout
-
-The main Writers Room page should be a three-pane workspace:
-
-- Left: library tree with folders, works, tags, status filters, recent drafts,
- and exercise sessions.
-- Center: editor for the active draft, with title, metadata, save/version state,
- word count, and selected prose range.
-- Right: action sidebar with manual AI tools grouped as Analyze, Adapt, Render,
- and Review.
-
-The first editor can be a high-quality plain text or Markdown editor. Avoid a
-rich-text dependency until formatting requirements justify it. The core needs are
-stable text ranges, reliable word count, keyboard-friendly writing, and low risk
-of corrupting large prose drafts.
-
-### Writing Exercise
-
-The "write for 10" section can live as a tab in Writers Room and as a quick action
-from any work.
-
-MVP behavior (ships in **Phase 1**):
-
-- Configurable timer (5/10/15/25-min presets) with start, finish, and discard.
-- Live word count of the sprint buffer, words added since session start.
-- Session can start from a blank prompt or a selected work (free-write the
- current work's title appears as the implicit prompt).
-- On finish, save the exercise session with starting/ending word counts and
- the appended sprint text.
-- Track session history: date, duration, starting words, ending words, words
- added, linked work, and prompt.
-
-Deferred to **Phase 2+** (NOT in Phase 1):
-
-- Pause / resume mid-session (today's MVP is start/finish/discard only).
-- Promote / append the sprint text into the active work's draft on finish
- (today the appendedText is logged with the session but not merged into the
- work). The session metadata already carries everything needed to wire this
- up later — surface a "Promote to draft" button on the recent-sessions list.
-- Session can start from a selected prose segment (currently scopes to the
- whole work).
-
-Do not blend this into POST yet. POST has creative writing drills, but Writers
-Room needs an authoring-grade exercise log tied to works and drafts.
-
-## Data Model
-
-Use local, human-readable storage under `data/writers-room/`. Avoid one giant
-JSON file for all prose. Store metadata as JSON and draft bodies as Markdown/text
-files so long works remain manageable.
-
-Recommended layout:
-
-```text
-data/writers-room/
- folders.json
- exercises.json
- works/
- <workId>/
- manifest.json
- drafts/
- <draftVersionId>.md
- analysis/
- <analysisId>.json
- render-plans/
- <renderPlanId>.json
-```
-
-### Folder
-
-```json
-{
- "id": "wr-folder-...",
- "parentId": null,
- "name": "Novel Drafts",
- "sortOrder": 0,
- "createdAt": "iso",
- "updatedAt": "iso"
-}
-```
-
-### Work Manifest
-
-The shape that ships in **Phase 1** (matches the on-disk file written by
-`server/services/writersRoom/local.js`):
-
-```json
-{
- "id": "wr-work-...",
- "folderId": "wr-folder-..." or null,
- "title": "Working Title",
- "kind": "novel|short-story|screenplay|essay|treatment|other",
- "status": "idea|drafting|revision|adaptation|rendering|complete|archived",
- "activeDraftVersionId": "wr-draft-...",
- "drafts": [ /* see Draft Version */ ],
- "createdAt": "iso",
- "updatedAt": "iso"
-}
-```
-
-**Phase 2+ planned (NOT yet persisted)** — added when the phase that uses
-each field ships. Listed here so the data-model story stays continuous, but
-the writer/validator drops them as YAGNI today:
-
-```json
-{
- "tags": [],
- "collectionId": "media-collection-id",
- "creativeDirectorProjectIds": [],
- "settings": {
- "defaultAnalysisProviderId": null,
- "defaultAnalysisModel": null,
- "defaultImageModelId": null,
- "defaultVideoModelId": null,
- "renderAspectRatio": "16:9",
- "renderQuality": "draft"
- }
-}
-```
-
-### Draft Version
-
-Draft metadata should be stored in `manifest.json`, with body text in
-`drafts/<draftVersionId>.md`.
-
-```json
-{
- "id": "wr-draft-...",
- "label": "Draft 3",
- "contentFile": "drafts/wr-draft-....md",
- "contentHash": "sha256",
- "wordCount": 12842,
- "segmentIndex": [
- {
- "id": "seg-001",
- "kind": "chapter|scene|paragraph",
- "heading": "Chapter 1",
- "start": 0,
- "end": 1842,
- "wordCount": 312
- }
- ],
- "createdAt": "iso",
- "createdFromVersionId": null
-}
-```
-
-The segment index is the foundation for stale-analysis detection and synced
-prose/script/media review. AI outputs should attach to a draft version and to
-specific segment IDs or character offsets.
-
-### Analysis Snapshot
-
-AI evaluations are immutable snapshots tied to a draft version. If the draft
-changes later, show them as stale rather than mutating them silently.
-
-```json
-{
- "id": "wr-analysis-...",
- "workId": "wr-work-...",
- "draftVersionId": "wr-draft-...",
- "kind": "summary|characters|scenes|suggestions|expansion|script|media-plan",
- "sourceRange": { "start": 0, "end": 1842, "segmentIds": ["seg-001"] },
- "providerId": "openai",
- "model": "selected-model",
- "status": "queued|running|succeeded|failed",
- "result": {},
- "error": null,
- "createdAt": "iso",
- "completedAt": "iso"
-}
-```
-
-Expected result schemas:
-
-- Characters: `characters[]` with name, aliases, role, goals, traits,
- relationships, visual spec, first-seen segment, and evidence snippets.
-- Scenes: `scenes[]` with summary, location, time, characters, plot beats,
- emotional turn, adaptation notes, and suggested visual prompt.
-- Summary: logline, short summary, detailed synopsis, themes, open questions.
-- Suggestions: issue/recommendation list with target segment, rationale,
- severity, and optional replacement/continuation text.
-- Expansion: continuation options, missing-scene opportunities, character
- deepening notes, pacing recommendations.
-- Script: screenplay-style script segments mapped back to prose segment IDs.
-- Media plan: character reference prompts, scene reference prompts, shot list,
- video prompts, and Creative Director handoff metadata.
-
-## Backend Plan
-
-### Services
-
-Add `server/services/writersRoom/local.js` for file-backed CRUD and draft I/O.
-Keep it the only writer for `data/writers-room/`, matching the pattern used by
-Creative Director and Video Timeline.
-
-Responsibilities:
-
-- create/update/delete folders
-- create/update/archive works
-- read/write draft body files
-- create draft versions and compute word count/content hash
-- build/update segment indexes
-- save immutable analysis snapshots
-- save exercise sessions
-- create media collections for works when needed
-- link works to Creative Director projects, media collections, and timeline
- projects
-
-Add validation in `server/lib/validation.js` or a dedicated
-`server/lib/writersRoomValidation.js` if the schemas get large. Keep Zod schemas
-strict at the route boundary.
-
-### Routes
-
-Add `server/routes/writersRoom.js`.
-
-Suggested endpoints:
-
-| Method | Path | Purpose |
-|--------|------|---------|
-| GET | `/api/writers-room/folders` | List folders |
-| POST | `/api/writers-room/folders` | Create folder |
-| PATCH | `/api/writers-room/folders/:id` | Rename/move folder |
-| DELETE | `/api/writers-room/folders/:id` | Delete empty folder |
-| GET | `/api/writers-room/works` | List work summaries |
-| POST | `/api/writers-room/works` | Create work |
-| GET | `/api/writers-room/works/:id` | Get manifest, latest draft metadata, latest analysis summaries |
-| PATCH | `/api/writers-room/works/:id` | Update work metadata/status/settings |
-| DELETE | `/api/writers-room/works/:id` | Archive or delete work |
-| GET | `/api/writers-room/works/:id/draft` | Get active draft body |
-| PUT | `/api/writers-room/works/:id/draft` | Save active draft body and update segment index |
-| POST | `/api/writers-room/works/:id/versions` | Snapshot current draft as a new version |
-| GET | `/api/writers-room/works/:id/analysis` | List analysis snapshots |
-| POST | `/api/writers-room/works/:id/analysis` | Manually run an AI evaluation |
-| GET | `/api/writers-room/analysis/:analysisId` | Get full analysis result |
-| POST | `/api/writers-room/exercises` | Start or save exercise session |
-| PATCH | `/api/writers-room/exercises/:id` | Finish/discard/update session |
-| POST | `/api/writers-room/works/:id/render-plans` | Create media plan from script/scenes |
-| POST | `/api/writers-room/render-plans/:id/creative-director` | Create/link Creative Director project |
-
-Analysis can be synchronous for small drafts in v1, but the API should already
-carry `status` so it can move to queued/background execution without changing the
-UI contract.
-
-### AI Evaluation Service
-
-Add `server/services/writersRoom/evaluator.js`.
-
-Use existing provider and prompt infrastructure instead of hardcoding prompts in
-the route. Recommended prompt stages under `data.reference/prompts/stages/`:
-
-- `writers-room-summary.md`
-- `writers-room-characters.md`
-- `writers-room-scenes.md`
-- `writers-room-suggestions.md`
-- `writers-room-expansion.md`
-- `writers-room-script.md`
-- `writers-room-media-plan.md`
-
-Prompt outputs should be JSON-first and schema-validated before persistence. If
-validation fails, save the failed analysis snapshot with the raw error and do not
-modify the work.
-
-Manual trigger rule:
-
-- No automatic eval on every keystroke.
-- No background eval on draft save.
-- Buttons in the sidebar trigger exactly one analysis kind for the selected
- range or the active draft.
-
-## Creative Director And Media Integration
-
-### What To Reuse
-
-From `feat/creative-director`:
-
-- `server/services/creativeDirector/local.js` for project state.
-- `server/services/creativeDirector/orchestrator.js` for next-task decisions.
-- `server/services/creativeDirector/agentBridge.js` and
- `completionHook.js` for CoS task chaining.
-- `server/services/mediaJobQueue/index.js` for serializing local image/video
- jobs and avoiding GPU/Metal contention.
-- `server/routes/creativeDirector.js` and `server/routes/mediaJobs.js`.
-- Creative Director detail UI concepts: treatment, segments, runs.
-
-From latest `main`:
-
-- `server/lib/mediaModels.js` as the source of truth for image/video models,
- including FLUX.2-klein image models.
-- `scripts/flux2_macos.py` and `scripts/flux2_quantized.py`.
-- `/api/image-gen/models`, `/api/video-gen/models`, media collections, media
- history, and video timeline routes.
-
-### Merge Requirements
-
-When merging Creative Director onto latest main:
-
-- Preserve FLUX.2 model registry fields: `runner`, `quantization`, `repo`,
- `tokenizerRepo`, `basePipelineRepo`, and `isFlux2`.
-- Preserve the FLUX.2 setup/status route and HF token/license messaging.
-- Keep mediaJobQueue's `providedJobId` behavior for image/video generators so
- queued job IDs match SSE event IDs.
-- Re-run and update tests around `imageGen`, `videoGen`, `mediaModels`, and
- `mediaJobQueue`.
-
-### Writers Room Bridge
-
-Writers Room should not duplicate Creative Director. It should create inputs for
-Creative Director and link back to its outputs.
-
-Bridge behavior:
-
-1. User runs `media-plan` or `script` analysis on a work or selected range.
-2. Writers Room stores a render plan mapped to draft segment IDs.
-3. User clicks "Create Creative Director project".
-4. Server creates a Creative Director project with:
- - work title as project name
- - selected prose/script as `userStory`
- - work/render style as `styleSpec`
- - selected video model/aspect/quality
- - a media collection shared with the work
-5. Creative Director plans and renders only after the user starts it.
-6. Writers Room stores the returned `creativeDirectorProjectId` and displays
- Creative Director treatment/scenes/runs inline or through deep links.
-
-For character and scene reference images, use image generation directly through
-the existing image-gen route and media job queue. FLUX.2-klein is an image model,
-so it is best suited for character sheets, scene references, and mood frames.
-Scene videos still go through the configured video model pipeline.
+`ExercisePanel.jsx` runs timed free-write sprints (default 10 minutes, clamped 1–60): start, finish, or discard, with live word count. Sessions can start standalone or attached to a work, and history records date, duration, word deltas, linked work, and prompt. Finished sprint text is stored as `appendedText` on the exercise record.
-## Synchronized Review Surface
+Not built (deliberately deferred): pause/resume mid-session, and a "promote to draft" action that merges `appendedText` into the work — the session record carries everything needed to add it later.
+
+## Storage
+
+Metadata (folders, work manifests, decomposed draft versions, exercises) persists through the storage dispatcher `server/services/writersRoom/store.js`: **PostgreSQL on a normal install** (#1017), with the legacy on-disk JSON layout under `data/writers-room/` remaining only as a dev/test escape hatch. Draft **prose bodies always stay on disk** as Markdown files (`works/<workId>/drafts/<draftVersionId>.md`) regardless of backend — long works never live inside a database row or a giant JSON blob. `store.js` decomposes `drafts[]` into rows on PG and reassembles on read, so the manifest shape is backend-independent.
+
+`server/services/writersRoom/local.js` is the single owner of work/folder/draft/exercise storage; `db.js` is the PG backend.
+
+### Work manifest
+
+Persisted fields: `id`, `folderId`, `title`, `kind` (novel/short-story/screenplay/essay/treatment/other), `status` (idea/drafting/revision/adaptation/rendering/complete/archived), `activeDraftVersionId`, `drafts[]`, `createdAt`, `updatedAt`. Users can edit `title`, `folderId`, `kind`, `status`, `imageStyle`, and the partial-merged `liveMode` config. Server-owned link fields are stamped by their own flows, never by user PATCH: `mediaCollectionId` (auto-created media collection), `cdProjectId` (Creative Director link), `pipelineSeriesId`/`pipelineIssueId` (comic-pipeline promotion).
+
+### Draft versions
+
+Each draft version records `id`, `label`, `contentFile`, `contentHash`, `wordCount`, `segmentIndex`, `createdAt`, `createdFromVersionId`. The **segment index** (chapter/scene/paragraph ranges with character offsets) is the foundation for stale-analysis detection and the synced review surface — AI outputs attach to a draft version and to specific segment IDs.
+
+## Analysis (manual AI passes)
+
+`server/services/writersRoom/evaluator.js` runs user-clicked passes against the active draft, pinning the source draft's `contentHash` so the UI can flag stale results when the prose changes. Analysis kinds map to prompt stages in `data.reference/prompts/stages/`:
-Add this after core analysis and Creative Director handoff are stable.
+| Kind | Stage | Output |
+|------|-------|--------|
+| `evaluate` | `writers-room-evaluate.md` | Editorial evaluation of the draft |
+| `format` | `writers-room-format.md` | Formatting/structure pass |
+| `script` | `writers-room-script.md` | Screenplay-style scenes mapped back to prose segment IDs |
+| `characters` | `writers-room-characters.md` | Character extraction into the story bible |
+| `places` | `writers-room-places.md` | Place extraction |
+| `objects` | `writers-room-objects.md` | Object extraction |
-Goal: let the user see how a story maps across forms.
+(Two more stages back the live features: `writers-room-continue.md` and `writers-room-cd-bridge.md`.) Outputs are JSON-first and schema-validated before persistence. Client: `AnalysisHistory.jsx`. Scene images can be attached to script-analysis scenes (`POST .../analysis/:analysisId/scene-image`) and persist into the work's media collection.
-View modes:
+## Story Bible
-- Prose only
-- Script only
-- Media only
-- Prose + script
-- Script + media
-- Prose + script + media
+Characters, places, and objects extracted by analysis (or entered by hand) live as per-work bible entities with full CRUD (`characters.js` / `places.js` / `objects.js`; client `CharactersBible.jsx`, `PlacesBible.jsx`, `ObjectsBible.jsx`, `StoryboardBibleTab.jsx`). Extraction merges into existing entries rather than duplicating.
-Mapping model:
+## Storyboard & Media
-```json
-{
- "proseSegmentId": "seg-001",
- "scriptSegmentIds": ["script-001"],
- "mediaSegmentIds": ["media-001"],
- "creativeDirectorSceneIds": ["scene-1"],
- "mediaRefs": [
- { "kind": "image", "ref": "character-ref.png" },
- { "kind": "video", "ref": "video-history-id" }
- ]
-}
-```
+The storyboard suite (`StoryboardPanel.jsx`, `StoryboardScenesTab.jsx`, `StoryboardBoardsTab.jsx`, `StoryboardConfigTab.jsx`, `SceneCard.jsx`) turns script-analysis scenes into rendered boards through the existing image-gen pipeline and media job queue. Scene images ride the shared media-collection infrastructure — a work auto-creates its collection on first render.
-Behavior:
+There is no persisted "render plan" store (the originally planned `render-plans` endpoints were never built); scene→media mapping is derived on read (see Synchronized Review below) and Creative Director handoff goes through the CD bridge.
-- Selecting prose highlights the mapped script and media.
-- Selecting script scrolls prose and media to the mapped segments.
-- Media cards show provenance: source prose segment, script segment, prompt,
- model, render job, and Creative Director scene/run when applicable.
-- If the draft content hash differs from the analysis/render plan version, show
- stale badges and require a deliberate refresh.
+## Creative Director Bridge
+
+The live-mode sidebar can turn the prose around the cursor into a short Creative Director **treatment** — logline, synopsis, overall visual treatment, and 2–6 filmable scenes (beat + visual prompt + duration). The writer reviews the proposal in the CD Bridge panel (`CdBridgePanel.jsx`) and sends it into a **new** Creative Director project seeded with that treatment (`POST .../cd-bridge/suggest` + `.../cd-bridge/send`, backed by the `writers-room-cd-bridge` stage). The bridge is non-destructive — it always creates a fresh project — and the work links to it via `cdProjectId` with an "Open in Creative Director" jump.
+
+## Pipeline Promotion
+
+`POST /works/:id/promote-to-pipeline` (`promoteToPipeline.js`) promotes a work into the comic pipeline, creating a series and first issue and stamping `pipelineSeriesId`/`pipelineIssueId` on the manifest.
+
+## Live Director (opt-in realtime assistance)
+
+`server/services/writersRoom/liveDirector.js` powers the editor's per-work, off-by-default "Live Director" mode:
+
+- **Live continuation** — while the writer pauses, asks for 2–4 short continuation options (beats, insertable prose snippets, dialogue lines) from the prose around the cursor, surfaced in `LiveContinuationPanel.jsx`; `prose`/`dialogue` options insert at the caret. Backed by the `writers-room-continue` stage (quick tier).
+- **Live render previews** — on-demand scene render reservations (`LiveRenderPanel.jsx`), with a separate daily render budget.
+
+Controls are enforced server-side, not just in the UI: per-work opt-in toggle (requests 409 when off), a client debounce after typing stops (`liveMode.debounceMs`, default 2.5s), and daily budgets (`liveMode.dailyCallBudget`, default 100, `0` = unlimited; plus `dailyRenderBudget`) that roll over at UTC midnight and 429 when spent. Usage counters are server-owned and stripped from user updates.
+
+## Synchronized Review Surface
-## Frontend Plan
+`GET /works/:id/synced-review` (`server/services/writersRoom/syncedReview.js`, client `SyncedReview.jsx`) lets the user see how a story maps across forms — prose, script, and media side by side, with selection sync between panes.
-Add:
+The mapping model is a **relational read-model derived on request** rather than a persisted mapping store:
-- `client/src/pages/WritersRoom.jsx`
-- `client/src/services/apiWritersRoom.js`
-- `client/src/components/writers-room/LibraryPane.jsx`
-- `client/src/components/writers-room/WorkEditor.jsx`
-- `client/src/components/writers-room/ExercisePanel.jsx`
-- `client/src/components/writers-room/AiSidebar.jsx`
-- `client/src/components/writers-room/AnalysisPanel.jsx`
-- `client/src/components/writers-room/RenderPlanPanel.jsx`
-- `client/src/components/writers-room/SyncedReview.jsx`
+- Prose segments come from the active draft's `segmentIndex`.
+- Script scenes come from the latest `script` analysis, whose scenes carry `sourceSegmentIds` back-references.
+- Media comes from the analysis snapshot's scene-image map.
-MVP UI states:
+Selecting prose highlights the mapped script and media; media cards show provenance (source segments, prompt, model, render job). Staleness falls out of the pinned analysis `sourceContentHash` — when the draft's hash differs, the UI shows stale badges and requires a deliberate re-run. Media attached to scenes that no longer exist after re-extraction is surfaced explicitly as orphaned rather than silently dropped.
-- Empty library
-- Create folder/work
-- Save draft pending/saved/error
-- Unsaved changes
-- Exercise running/paused/complete
-- Analysis idle/running/succeeded/failed/stale
-- Render plan not created/ready/linked/rendering/complete
-- Creative Director linked project status
+## Federation
-Keep the UI dense and tool-like. This is an authoring workspace, not a marketing
-page. Use icons for manual actions, tabs for work surfaces, and fixed panes so
-the editor does not jump when analysis cards update.
+Writers Room content syncs across peers: record kinds `writersRoomWorks`, `writersRoomFolders`, and `writersRoomExercises` are registered in `server/lib/schemaVersions.js` with per-record peer-sync push (#1565/#1645). `local.js` emits record events through `sharing/recordEvents.js`; draft `.md` bodies and scene-image assets ride the peer-sync body/asset lanes, and conflict-restore handlers cover exercises and bodyless records.
-## Phased Implementation
+## API Surface
-### Phase 0 - Merge Foundation [DONE]
+All under `/api/writers-room` (`server/routes/writersRoom.js`, client wrapper `client/src/services/apiWritersRoom.js`):
-Completed by squash-merge of `feat/creative-director` (PR #191, commit
-`9b36b900`) and the FLUX.2 work that landed alongside it. Image/video routes,
-mediaJobQueue, FLUX.2 model registry, Creative Director routes/UI, and SSE
-progress all ship on `main` today.
+- **Folders** — `GET/POST /folders`, `DELETE /folders/:id`
+- **Works** — `GET/POST /works`, `GET/PATCH/DELETE /works/:id`, `POST /works/:id/promote-to-pipeline`
+- **Drafts/versions** — `PUT /works/:id/draft`, `POST /works/:id/versions`, `GET/PATCH /works/:id/versions/:draftId` (PATCH sets active)
+- **Exercises** — `GET/POST /exercises`, `POST /exercises/:id/finish`, `POST /exercises/:id/discard`
+- **Analysis** — `GET/POST /works/:id/analysis`, `GET /works/:id/analysis/:analysisId`, `POST .../scene-image`
+- **Live director** — `POST /works/:id/live-suggest`, `POST /works/:id/live-render-preview`, `POST /works/:id/cd-bridge/{suggest,send}`
+- **Synced review** — `GET /works/:id/synced-review`
+- **Story bible** — `GET/POST /works/:id/{characters,places,objects}`, `PATCH/DELETE /works/:id/{characters,places,objects}/:entityId`
-### Phase 1 - Writers Room Core
+Route inputs are Zod-validated at the boundary (`server/lib/validation.js`).
-Goal: works can be created, organized, edited, saved, versioned, and exercised.
+## Tests
-- Add storage service, validation, routes, and API client.
-- Add `/writers-room` route and nav entries.
-- Build library pane and editor.
-- Add autosave or explicit save with visible dirty/saved state. Prefer explicit
- save for the first version unless the editor proves stable.
-- Add "write for 10" exercise session flow.
-- Add word count, selected-range count, and draft version snapshots.
-
-Exit criteria:
-
-- User can create a folder, create a work, write prose, save it, snapshot a
- version, and complete a 10-minute exercise.
+Most services carry sibling `.test.js` suites (storage CRUD, draft save/version/content-hash behavior, segment indexing, analysis stale detection, exercise lifecycle, live-director gating/budgets, synced-review derivation, sync logic). `server/lib/navManifest.test.js` covers the nav entries; route validation is covered in the routes suite.
-### Phase 2 - Manual AI Analysis
+## Related Features
-Goal: the writer can trigger useful, reviewable AI passes against a draft or
-selected segment.
-
-- Add prompt stages and evaluator service.
-- Add analysis sidebar buttons for summary, characters, scenes, suggestions,
- expansion, and script.
-- Store immutable analysis snapshots tied to draft version/content hash.
-- Render structured analysis panels with evidence and stale badges.
-- Add "accept into notes" or "copy into draft" only as explicit actions.
-
-Exit criteria:
-
-- No AI pass runs without a click.
-- A changed draft marks old analysis as stale.
-- Character/scene/script outputs retain source segment mappings.
-
-### Phase 3 - Media Planning And Creative Director Handoff
-
-Goal: a work can become a media plan, reference images, and a Creative Director
-project.
-
-- Add media-plan analysis kind.
-- Add render plan storage and UI.
-- Generate character reference prompts and scene reference prompts.
-- Queue selected image previews using configured image model, including FLUX.2
- where available.
-- Create/link Creative Director projects from render plans.
-- Show Creative Director treatment/scenes/runs inside Writers Room as linked
- project state.
-
-Exit criteria:
-
-- User can select a scene or range, create a media plan, generate reference
- images, create a Creative Director project, and start rendering from a manual
- action.
-
-### Phase 4 - Synchronized Prose, Script, Media Review
-
-Goal: the user can inspect the adaptation chain and see what maps to what.
-
-- Build `SyncedReview` with prose/script/media panes.
-- Add segment mapping storage and stale-state detection.
-- Support scroll/selection sync between panes.
-- Link media items to collection, history, Creative Director scene, and source
- prose/script.
-
-Exit criteria:
-
-- User can open one work and review prose, script, and generated media with
- visible mappings and provenance.
-
-### Phase 5 - Realtime Creative Director Feedback
-
-Goal: evolve from manual passes to controlled live assistance.
-
-- Optional live story continuation suggestions while writing. **[shipped]**
-- Optional render previews on selected scenes. **[shipped]**
-- Creative Director can propose next beats, alternate scenes, and visual
- treatments from the active cursor context. **[shipped]**
-- Add throttling, debouncing, budget controls, and explicit opt-in per work. **[shipped]**
-
-This phase should wait until manual analysis quality, mapping, and render costs
-are proven.
-
-**Shipped (live continuation slice):** the editor has an opt-in "Live Director"
-mode (per work, off by default) that, while the writer pauses, asks for 2–4
-short continuation options from the prose around the cursor — beats to take,
-ready-to-insert prose snippets, or dialogue lines. Suggestions surface in a side
-panel; `prose`/`dialogue` options insert at the caret. Controls:
-
-- Per-work opt-in toggle (work menu → "Enable live director").
-- A client debounce after typing stops (`liveMode.debounceMs`, default 2.5s) so
- no call fires on every keystroke.
-- A server-enforced daily call budget (`liveMode.dailyCallBudget`, default 100,
- `0` = unlimited) that rolls over at UTC midnight. Opt-in and budget are
- enforced server-side, not just in the UI — the debounce is convenience only.
-
-Backed by the `writers-room-continue` prompt stage (quick tier) and
-`server/services/writersRoom/liveDirector.js`; per-work live config persists on
-the work manifest.
-
-**Shipped (Creative Director bridge slice):** alongside the inline prose
-continuations, the live-mode sidebar can turn the prose around the cursor into a
-short Creative Director **treatment** — a logline, synopsis, an overall visual
-treatment (palette/lighting/cinematography), and 2–6 filmable scenes (each a
-beat + a visual prompt + a duration). The writer reviews the proposal in the
-"CD Bridge" panel and, with one click, sends it into a **new Creative Director
-project** seeded with that treatment and visual style — then jumps straight to
-it via an "Open in Creative Director" link on the work menu. The bridge is
-non-destructive (it always creates a fresh project, never overwrites an existing
-one) and draws on the same per-work opt-in and daily suggestion budget as the
-continuation panel. Backed by the `writers-room-cd-bridge` prompt stage and the
-existing Creative Director treatment store.
-
-## Test Plan
-
-Backend:
-
-- Writers Room storage CRUD and atomic writes.
-- Draft save/version/content-hash behavior.
-- Segment index generation for headings, blank-line scenes, and paragraphs.
-- Analysis snapshot validation and stale detection.
-- Exercise session lifecycle.
-- Creative Director project linking.
-- Media job queue integration with image and video job owners.
-- Route validation and error shapes.
-
-Frontend:
-
-- Library create/select/delete flows.
-- Editor dirty/saved/error state.
-- Exercise timer and word-count deltas.
-- Analysis sidebar loading, success, failure, stale states.
-- Render plan and Creative Director linked-project states.
-- Mobile layout for the three-pane workspace.
-
-Regression:
-
-- `/media/image`, `/media/video`, `/media/creative-director`, `/media/timeline`,
- and `/media/collections` still work.
-- `server/lib/navManifest.test.js` still passes after adding Writers Room nav.
-- FLUX.2 setup/status remains visible and its unsupported LoRA constraints are
- still enforced.
-
-## Non-Goals For MVP
-
-- Realtime background evaluation while typing.
-- Multi-user collaboration.
-- Rich screenplay pagination/export.
-- Automatic rewrite of user prose.
-- Fully autonomous story-to-movie generation without manual gates.
-- Database migration for writing content.
-- Public sharing or publishing workflows.
-
-## Resolved Review Questions
-
-1. **Sidebar placement** — A new top-level `Create` group containing Media Gen
- (default landing) and Writers Room. Prompts and Providers stay under `AI`.
-2. **Editor** — Plain Markdown for v1. Revisit when screenplay formatting needs
- pagination.
-3. **"Write for 10" sessions** — Can start standalone or attached to a work.
- Default the new-session form to "attach to active work" when one is open.
-4. **First media milestone** — Character/scene reference images first, then
- video previews via Creative Director handoff.
-5. **Creative Director auto-continue** — Inherit Creative Director's existing
- behavior; do not add a Writers-Room-specific gate. The user already controls
- per-scene start/cancel from the CD detail page.
+- Creative Director (`server/services/creativeDirector/`, `/media/creative-director`) — treatment/scene/run orchestration the CD bridge feeds into
+- Comic pipeline — the promote-to-pipeline target
+- Media collections, image-gen, and the media job queue — shared render infrastructure