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: replan — archive 17 shipped items, drop superseded pointer, refresh LOC counts

Adam Eivy3ec3d591ddbe
diff --git a/DONE.md b/DONE.md
index c7ffcea499..0c58eec0bb 100644
--- a/DONE.md
+++ b/DONE.md
@@ -6,6 +6,24 @@ Archive of completed work. For active roadmap, see [PLAN.md](./PLAN.md). For pro
## 2026-05-10
+- **CoS agent dedup race fix** — `spawnAgentForTask` released the `spawningTasks` guard before the agent was queued to the runner, so a concurrent `task:ready` could slip a duplicate past the has-check. Spawn call is now wrapped in `try { spawnViaRunner | spawnDirectly } finally { spawningTasks.delete(task.id) }` (`server/services/agentLifecycle.js:536-547`). New behavioral race-repro + source-text regression guard in `agentLifecycle.test.js`; 3831 tests green.
+- **Video Gen — FFLF keyframe-pair guidance** — `renderFramePanel` in `client/src/pages/VideoGen.jsx` gained a `hint` prop and an accent-coloured line under FFLF mode telling users to use keyframes that share scene geometry. Distinct styling from the experimental advisory.
+- **Deprecate notapalindrome LTX models** — `ltx2_unified`, `ltx23_unified`, `ltx23_distilled_q4` carry `deprecated: true` in `server/lib/mediaModels.js` + the `data.sample/media-models.json` seed; VideoGen + Creative Director dropdowns group them under a `Legacy` `<optgroup>` below the active dgrauet models. `defaultMacos` deliberately stays on `ltx23_distilled_q4` because dgrauet requires an opt-in `INSTALL_LTX2=1` venv install — fresh installs need a model that works out of the box.
+- **Step 4c — `useAsyncAction` hook** — `client/src/hooks/useAsyncAction.js` returns `[run, running]`. Migrated `ProseStage.jsx#handleExtract`, `TextStagePanel.jsx#handleSave` + `#handleGenerate`, and `EpisodeVideoStage.jsx#submit` onto the hook. `StoryboardsStage` stays on its keyed loading state pattern — boolean abstraction wouldn't fit.
+- **Step 2b — Shared zod bible schemas** — `server/lib/validation.js` re-exports `characterBibleCreateSchema` / `settingBibleCreateSchema` / `objectBibleCreateSchema` under kind-neutral names; pipeline routes extend those with back-compat fields + `.passthrough()`. The loose `bibleEntrySchema = z.record(z.string(), z.any())` is gone. Single sanitizer enforces shape for both writers-room + pipeline.
+- **Step 2a — `createBibleStore` factory** — `server/lib/storyBible.js#createBibleStore(...)` derives file paths and id regexes from `kind`; each writers-room domain file (characters / settings / objects) collapses to ~30 LOC. -281 LOC across the three files; 12 new factory tests in `storyBible.test.js`. Settings' slugline-aware dedup and "blank-both → reject" guard flow through the `dedupKey` callback and `validateAfterUpdate`.
+- **Step 4b — Parallel bible extraction** — `extractBibleSchema` accepts `parallel: true`; the three kinds fan out via `Promise.all` for ~3× wall-clock speedup on HTTP-API providers. Default stays sequential — safe for CLI providers that serialize at session level. Merge runs after all kinds complete; baseline read once at top of the route.
+- **Step 4a — `extractAndMergeIntoSeries`** — Bible extract → merge → patch orchestration lives in `server/services/pipeline/series.js`; the route shrinks to a single `seriesSvc.extractAndMergeIntoSeries(...)` call. `mergeExtractedBible` / `extractBible` no longer route-layer imports. Mirrors WR's `mergeExtractedCharacters(workId, extracted)`.
+- **Step 4 — Shared bible-extraction service** — `server/lib/bibleExtractor.js#extractBible({ kind, corpus, existing, context, providerOverride, source })` runs the staged LLM, pulls the `{ characters | settings | objects }` envelope, and routes through canonical `sanitizeBibleList`. Caller owns persistence (avoids the double-merge footgun). Writers-room evaluator's three bible SHAPERS (~75 LOC) deleted; new pipeline route `POST /api/pipeline/series/:id/extract-bible` + an "Extract bibles" button on the Pipeline ProseStage. 12 lib tests + 4 route tests.
+- **Step 3 — Shared staged-LLM runner** — `server/lib/stageRunner.js` exposes `runStagedLLM(stageName, variables, { providerOverride, modelOverride, returnsJson, source })` plus `resolveModel` (tier-aware) and `extractJson` (lenient code-fence stripper). Writers Room evaluator + Pipeline text stages both route through it; ~150 LOC of bespoke CLI-spawn drift deleted. WR analyses now persist transcripts to `data/runs/<runId>/` and pick up tier-name resolution for free. Per-stage temperature override dropped (toolkit's `executeApiRun` doesn't expose temp).
+- **Step 2 — Unified story-bible schema** — `server/lib/storyBible.js` owns canonical `Character` / `Setting` / `Object` shapes + `sanitizeBibleList` + `mergeExtractedBible` with per-kind key normalizers. Writers-room domain files (`characters.js` / `settings.js` / `objects.js`) collapsed onto shared helpers (-299 LOC). Pipeline gains `series.settings[]` + `series.objects[]`; legacy `description` auto-promotes to `physicalDescription`. `composeVisualPrompt` activates the slugline-matching plumbed in step 1 — pipeline storyboard scenes that reuse a setting slugline get the canonical baseline prepended automatically.
+- **Step 1b — `composeStyledPrompt` server mirror** — `server/lib/composeStyledPrompt.js` is the verbatim mirror of the client lib; World Builder's `compileBatchPrompts` now uses it for both variation + composite-sheet paths. Side effect: rendered prompts switch separator from `, ` to `. ` (the composeStyledPrompt convention) — semantically identical for diffusion models. 6 unit tests.
+- **Step 1a — Drop `sceneCardHelpers.js` shim** — Constants moved to new `client/src/lib/wrImageDefaults.js`; SceneCard.jsx + StoryboardPanel.jsx now import `buildScenePrompt` / `matchScene*` / `normCharKey` directly from `client/src/lib/scenePrompt`. Shim file deleted.
+- **Step 1 — Shared scene-prompt composer** — `server/lib/scenePrompt.js` + mirror `client/src/lib/scenePrompt.js` (Vite fs.allow doesn't reach across, follows the project's manual-mirror convention). Pipeline's `composeVisualPrompt` now routes through `buildScenePrompt` so series name + style + universal cast + scene visual all flow through one algorithm with PROMPT_MAX-budgeted truncation. Storyboards stage UI + route schema accept optional per-scene `slugline` so step 2's settings-bible match is plumbed end-to-end. 18 new unit tests.
+- **EpisodeVideoStage aspectRatio + quality picker** — Inline `aspectRatio` + `quality` dropdowns on EpisodeVideoStage's pre-kickoff toolbar, plumbed through to the CD-handoff route. modelId picker deferred until the video-model registry exposes a flagged-stable list.
+- **ScenePreview component + shared CD status helpers** — `client/src/components/creative-director/ScenePreview.jsx` owns the `<video controls poster>` + onError-missing-media + Retry + cache-bust idiom; `sceneStatus.js` exports `SCENE_STATUS*` constants + `getSceneStatusBadge()` + `PROJECT_STATUS_LABEL`. SegmentsTab + EpisodeVideoStage both consume the shared components — EpisodeVideoStage's final-video render gains the missing-onError fallback for free. Side fix: slim CD projection was returning `scene.id` but CD scenes are keyed by `sceneId`; projection + fixture corrected.
+- **Slim `GET /creative-director/:id?slim=1`** — Drops unbounded `runs[]` history + full treatment text; returns `{ id, status, updatedAt, finalVideoId, failureReason, treatment: { scenes: [{ id, order, status }] } }`. EpisodeVideoStage's 4s poll now passes `slim: true`. 2 new route tests.
+- **Pipeline auto-run resumption (demote on boot)** — `recoverStuckAutoRuns()` in `autoRunner.js` walks issues at boot and demotes any `status: 'running'` to `needs-review` (the same terminal state a normal completion lands on). Wired into `server/index.js` alongside brain / writers-room boot recovery. Actual resume deferred — re-attaching SSE + re-running missing stages needs the persisted runId + per-stage progress we don't write to disk. Falling back to `needs-review` is the safe, low-blast-radius fix.
- **Prompt template partials** — Step 7 of the Writers Room ↔ Pipeline DRY unification. PortOS's prompt engine now supports Mustache-style `{{> partial-name }}` includes via a new `server/lib/promptPartials.js` module. Implemented as a pre-processing pass: `buildPrompt` first calls `expandPartials` to inline `<promptsDir>/_partials/<name>.md` files (recursively, with a MAX_DEPTH=8 cycle guard and loud missing-partial throws), then hands the expanded text to the existing `applyTemplate` for the variable + section pass — so partials carry variable refs naturally and the existing engine stays sync + pure. First two partials shipped: `_partials/bible-deference.md` (character + setting bible deference preamble) and `_partials/scene-output-contract.md` (the canonical scenes[] JSON output shape). `writers-room-script.md` and `pipeline-extract-scenes.md` collapse onto these — bug-fixes to "use canonical character names" or "JSON output contract" logic now land in one place instead of N. 16 unit tests covering reference detection, sync + async expansion, cycle detection, missing-partial throws, and the no-partial fast path. Note: existing installs keep their customized stage prompts (`setup-data.js#ensureSampleContent` only copies missing files); to pick up the partial-using refactor on an existing install, manually re-copy from `data.sample/prompts/stages/`.
- **Writers Room ↔ Pipeline bridge — Promote to pipeline** — Step 6 of the DRY unification. New `server/services/writersRoom/promoteToPipeline.js#promoteWorkToPipeline(workId, { force })` lifts a WR work into the Pipeline in one call: copies the active draft body into `stages.prose.output` (status `edited`), the latest characters/settings/objects bibles into the new series (canonical sanitizer applied — wr-char-/wr-setting-/wr-object- ids preserved), and the latest succeeded `script` analysis scenes into `stages.storyboards.scenes` (with the same `visualPrompt → description` alias the storyboards-extractor route uses). Records the bidirectional link on both sides — `manifest.pipelineSeriesId` / `manifest.pipelineIssueId` on the WR work; `series.writersRoomWorkId` on the pipeline series — so the menu flips between "Promote to pipeline" and "Open in pipeline" without state. Idempotent: a second promote returns the existing pair (`reused: true`); pass `{ force: true }` for a fresh series. If either linked record is deleted out-of-band, the stale link is dropped and a fresh series is created. Route `POST /api/writers-room/works/:id/promote-to-pipeline`. UI: menu item on WR `WorkEditor`; "Writers Room" badge on PipelineSeries header when linked. Side fix: pipeline `series.js` + `issues.js` switched to lazy `statePath()` (matches writers-room/local.js convention) so the new tests' Proxy-based PATHS mocks load cleanly. 8 service tests + 4 route tests; full server pack 3777/3777.
- **Pipeline — Storyboards auto-fill from TV script or prose** — Step 5 of the Writers Room ↔ Pipeline DRY unification. New `server/lib/sceneExtractor.js#extractScenes({ source, sourceKind, characters, settings, objects, work, series, issue })` is the single LLM-driven scene-list extractor for both surfaces; mirrors the bibleExtractor pattern (extract→sanitize, caller persists). Two source modes: `prose` uses the existing `writers-room-script` prompt (paragraph-grain breakdown), `tvScript` uses the new `pipeline-extract-scenes` prompt (slugline-grain parse — one entry per teleplay slugline). Shared `sanitizeSceneList` owns the canonical scene shape; Writers Room evaluator's `script` kind now delegates here, deleting ~25 LOC of duplicated SHAPERS.script logic. Pipeline storyboards stage gains "From TV script" + "From prose" buttons via `POST /api/pipeline/issues/:id/stages/storyboards/extract-scenes` — disabled until the source stage has output, two-click-arm guard before replacing existing scenes. Extracted scenes alias `visualPrompt → description` for legacy storyboards-UI compat; rich fields (heading/summary/characters/action/dialogue/sourceSegmentIds) ride along untouched. **Side fix:** `issuePatchSchema.stages` z.union order swapped so visual-stage PATCH bodies (`scenes` / `pages` / `cdProjectId` / `videoPath`) no longer silently strip — the union evaluated the strict text-only schema first, hiding the visual fields. 14 unit tests + 4 route tests; full server pack 3765/3765.
diff --git a/PLAN.md b/PLAN.md
index cc954908ea..a461ecd594 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -7,8 +7,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
## Next Up
1. **Voice agent next power-ups** — `ui_read` (extract visible page text so "what does this say?" works without hand-navigation), destructive-action confirmation gate (pause and require spoken "confirm" when `ui_click` matches `/delete|remove|discard|reset|clear/i`), proactive CoS speech (server-pushed voice with quiet-hours policy + barge-in contract).
-2. **Chronotype-aware CoS scheduling** — M42 ships chronotype derivation (`identity.js#getChronotype` + `getEnergyZones`) but `taskSchedule.js` still routes round-robin. Add a `temporalPreference` field to CoS task schema (`focus` / `low-energy` / `any`) and shift priority by time-of-day from the identity chronotype profile. Targeted addition (~150 lines), no new deps.
-3. **God-file test coverage** — `cos.js` (3115 lines) and `agentLifecycle.js` (1435 lines) still have no test sibling. Add tests for `evaluateTasks` priority ordering + `dequeueNextTask` capacity guards (cos), and `spawnAgentForTask` + `handleAgentCompletion` error recovery (agentLifecycle). Both files are still growing — 44 LOC since last replan; add coverage before further surgery.
+2. **God-file test coverage** — `cos.js` (3115 lines) and `agentLifecycle.js` (1446 lines) still have no test sibling. Add tests for `evaluateTasks` priority ordering + `dequeueNextTask` capacity guards (cos), and `spawnAgentForTask` + `handleAgentCompletion` error recovery (agentLifecycle). Both files are still growing — `agentLifecycle.js` is +11 LOC since last replan; add coverage before further surgery.
## Backlog
@@ -22,7 +21,6 @@ The pipeline now has multi-frame evaluation, auto-accept watchdog, cheap smoke f
- **Stitch path change.** `server/services/creativeDirector/stitchRunner.js` after timeline render: strip per-clip audio (`-c:v copy -an`), then a second ffmpeg pass overlays the generated track. New project-level `audioMode: 'per-clip' | 'silent' | 'generated' | 'uploaded-track'`. PLAN today's `'per-clip'` stays the default so existing projects don't regress.
- **UX.** `EpisodeVideoStage.jsx` toolbar gets an "Audio" dropdown beside aspectRatio/quality. "Generated" kicks off the audio gen as part of the stitch pipeline; "Uploaded" opens a file picker.
- **Investigation needed first** — pick a generator. Suno has the cleanest UX (give it a vibe prompt + duration); MusicGen-MLX is local but needs sliding-window stitching to exceed 30s; AudioLDM2 is older. ~150 LOC for the stitcher change once the generator is picked; the bigger question is which model and how to prompt it from script-level arc metadata. Treat this as a new sub-brainstorm when we pick it up — not a same-PR fix.
-- [x] **Duplicate evaluator spawn dedup** — shipped (2026-05-10). Root cause: `spawningTasks.delete(task.id)` ran immediately after `updateTask(in_progress)` succeeded but BEFORE the spawn call queued the agent to the runner; a concurrent `task:ready` re-emission could race past the dedup-has-check and produce a duplicate spawn. Fix wraps the spawn call in `try { spawnViaRunner|spawnDirectly } finally { spawningTasks.delete(task.id) }` (`server/services/agentLifecycle.js:536-547`). New behavioral repro + source-text regression guard in `agentLifecycle.test.js`. Full server pack green (3831 tests). Pre-existing wider issue (any throw between `spawningTasks.add` and the inner try-block also leaks the guard) noted as a separate item below.
- [ ] **Render slowness on long sessions.** Per-scene render time degraded from ~3.5 min (early) to 10–30 min (late) within one project — likely accumulated listeners + queue races. Profile after sustained use; the round-22 dedup work probably already helps; verify.
### LTX-2.3 dgrauet runtime — wire native modes
@@ -30,12 +28,10 @@ The pipeline now has multi-frame evaluation, auto-accept watchdog, cheap smoke f
The dgrauet/ltx-2-mlx runtime ships with FFLF (true keyframe interpolation), audio-to-video, and native video Extend (see DONE.md 2026-05-06). Remaining gaps:
- [ ] **Native FFLF deeper test on real keyframe pairs.** FFLF wiring is verified on synthetic ball-motion keyframes (commit `ef5d9081`). Validate with REAL pairs: take last frame of clip A + first frame of clip B from the same scene/camera, render an interpolation, confirm temporally-coherent transition. If it looks weak even on similar keyframes, file a follow-up to expose more pipeline knobs in the UI (cfg-scale, stg-scale, stage1-steps).
-- [x] **Add UI hint under FFLF mode** — shipped (2026-05-10). `renderFramePanel` in `client/src/pages/VideoGen.jsx` gained a `hint` prop rendered as a subtle accent-coloured line below the existing experimental advisory ("Tip: use keyframes that share scene geometry — same camera, same subject…"). Visually distinct from the warning so the two categories of information don't blur.
-- [x] **Deprecate notapalindrome models** — shipped (2026-05-10). `ltx2_unified`, `ltx23_unified`, `ltx23_distilled_q4` carry `deprecated: true` in both `server/lib/mediaModels.js` and the `data.sample/media-models.json` seed. VideoGen and CreativeDirector dropdowns render them under a `<optgroup label="Legacy">` below the active dgrauet models. `defaultMacos` deliberately stays on `ltx23_distilled_q4` and `getDefaultVideoModelId` does NOT auto-roll forward — the dgrauet runtime requires an opt-in venv install (`INSTALL_LTX2=1 bash scripts/setup-image-video.sh`), so fresh installs need a model that works out of the box. Comment in `mediaModels.js#getDefaultVideoModelId` documents this. Eventual full removal of `runtime: 'mlx_video'` dispatch (~50 LOC in `videoGen/local.js`) deferred until dgrauet is the install-default.
### Other backlog
-- [ ] **Writers Room (Phase 4–5)** — Phases 1–3 shipped (authoring core, storyboard companion, character/world/objects bibles, per-stage LLM picker, paragraph-grain Adapt, auto-queue scene image gen, Read view + render dock). Remaining: Phase 4 synced prose/script/media review, Phase 5 realtime CD feedback. See [writers-room.md](./docs/features/writers-room.md). **Cross-cutting:** Phase 4 overlaps with the [Writers Room ↔ Pipeline DRY Unification](#writers-room--pipeline-dry-unification) work below — schedule them together so the synced-review surface lands on the unified bible/scene model rather than the parallel one.
+- [ ] **Writers Room (Phase 4–5)** — Phases 1–3 shipped (authoring core, storyboard companion, character/world/objects bibles, per-stage LLM picker, paragraph-grain Adapt, auto-queue scene image gen, Read view + render dock). Remaining: Phase 4 synced prose/script/media review, Phase 5 realtime CD feedback. See [writers-room.md](./docs/features/writers-room.md). Phase 4 now lands on the unified bible/scene model that the DRY-unification work (DONE.md 2026-05-10) brought in.
- [ ] **Voice CoS tool expansion** — `calendar_today` / `calendar_next` (Google Calendar via existing MCP), `meatspace_log_workout` (wraps `meatspaceHealth.js`), `weather_now` (needs API choice — OpenWeather / WeatherKit / NWS), `timer_set` (reuses `agentActionExecutor.js` scheduled actions).
- [ ] **Voice agent vision fallback** — `ui_describe_visually` tool: screenshot the current tab (or a named canvas/chart) and send to a vision-capable model so "what's on this chart?" works on non-DOM content (CyberCity, graph views). Depends on a vision provider in `portos-ai-toolkit`.
- [ ] **Voice agent — explicit long-term memory routing** — pipeline already routes capture verbs to `brain_capture`. Remaining: on retrieval-shaped voice turns, inject top-N relevant memories into the system prompt via `brain_search` so it's self-improving rather than ambient.
@@ -52,6 +48,7 @@ The dgrauet/ltx-2-mlx runtime ships with FFLF (true keyframe interpolation), aud
- [ ] **Extract `mockPathsDataRoot()` test helper** — `server/lib/storyBible.test.js`, `server/services/writersRoom/{characters,settings,objects,local,promoteToPipeline}.test.js` (6 files) all open with byte-identical setup: `let tempRoot; vi.mock('../../lib/fileUtils.js', async () => { const actual = await vi.importActual(...); return new Proxy(actual, { get(t,p){ if (p==='PATHS') return new Proxy(actual.PATHS,{get(tp,pp){ if(pp==='data') return tempRoot; ... }}); ... } }); }); beforeEach(() => { tempRoot = mkdtempSync(...) }); afterEach(() => rmSync(tempRoot, { recursive: true, force: true }))`. Extract into `server/test-utils/tempDataRoot.js` exposing `mockPathsDataRoot()` that returns a live tempRoot getter. ~20 LOC saved per file plus a single fix-point if PATHS mocking semantics ever change. Surfaced from the bibleStore-factory /simplify pass.
- [ ] **Widen `spawningTasks` try/finally in `agentLifecycle.js#spawnAgentForTask`** — pre-existing bug surfaced during /do:review. Today's try/finally (`server/services/agentLifecycle.js:536-547`) only wraps the spawn call itself. Between `spawningTasks.add(task.id)` (line 134) and the try-block, the function does ~400 lines of async work — `buildAgentPrompt`, `writeFile(prompt)`, `createAgentRun`, `registerAgent`, etc. — each of which can throw (ENOSPC, EACCES, network). A throw on any of those paths leaves `spawningTasks` registered FOREVER, permanently blocking future spawns of that task id. The detected-error paths call `cleanupOnError` which does delete, but an unhandled throw is the gap. Fix: hoist the try/finally up to wrap from line 134 (after `add`) through the spawn calls. `cleanupOnError`'s redundant `spawningTasks.delete` becomes a no-op (Set.delete on absent key) which is fine. Pre-existing bug, not introduced by the dedup-race fix.
- [ ] **`useAsyncAction` post-unmount setState guard** — the hook in `client/src/hooks/useAsyncAction.js` calls `setRunning(false)` after an awaited async fn resolves. If the owning component unmounts mid-action, React 18 silently warns; React 17 surfaces the warning. Add a `mountedRef` (set true in mount effect, false in cleanup) and gate `setRunning(false)` on `mountedRef.current`. YAGNI for current call sites (all stable parent components) but worth doing once the hook gains a 4th consumer or any consumer that unmounts during long-running ops. Surfaced from /do:review.
+- [ ] **Drop legacy `description` fallback in `sanitizeCharacter`** — `server/lib/storyBible.js:130` carries an inline `TODO(item-4): drop the description fallback once pipeline characters extract natively.` Item 4 (shared bible-extraction service) shipped 2026-05-10 — extraction now writes the canonical `physicalDescription` field directly. Plan: write a one-shot migration that rewrites every `series.characters[].description` → `physicalDescription` in `data/pipeline-series.json` (idempotent: skip entries that already have `physicalDescription`), drop the `|| raw.description` fallback at `storyBible.js:137`, and remove the TODO comment. Audit `data.sample/` + tests for any remaining `description` reads before merging.
### Civitai LoRA / Z-Image-Turbo follow-ups (from /simplify pass)
@@ -77,7 +74,7 @@ These were flagged by the post-merge code review pass on the Z-Image + Civitai L
### Deferred Architecture (human-led planning)
- `server/services/cos.js` (3115 LOC) — split into cosTaskStore / cosTaskGenerator / cosJobScheduler / cosHealthMonitor.
-- `server/services/agentLifecycle.js` (1435 LOC) — extract prepareAgentWorkspace / resolveProvider / processCompletion.
+- `server/services/agentLifecycle.js` (1446 LOC) — extract prepareAgentWorkspace / resolveProvider / processCompletion.
- `server/services/identity.js` (1917 LOC) — separate genomic markers + longevity + goals + todos.
- `server/services/taskSchedule.js` (2369 LOC) — extract prompt management to `taskPromptService.js`.
- `server/services/taskLearning.js` (1939 LOC) — separate metrics aggregation from heuristic routing.
@@ -88,8 +85,8 @@ These were flagged by the post-merge code review pass on the Z-Image + Civitai L
- `server/services/memory.js` (1049 LOC) — separate retrieval, classification, and persistence.
- `server/services/xcodeScripts.js` (1131 LOC) — collapse repeated AppleScript builders.
- `server/routes/apps.js` (1180 LOC) — extract `npm install` orchestration to `appBuilder.js`.
-- `client/src/pages/VideoGen.jsx` (1334 LOC) — extract mode-specific control panels (i2v / a2v / extend / FFLF) into siblings.
-- `client/src/pages/ImageGen.jsx` (1161 LOC) — extract preset picker + multi-reference uploader.
+- `client/src/pages/VideoGen.jsx` (1361 LOC) — extract mode-specific control panels (i2v / a2v / extend / FFLF) into siblings.
+- `client/src/pages/ImageGen.jsx` (1182 LOC) — extract preset picker + multi-reference uploader.
- `client/src/components/goals/GoalDetailPanel.jsx` (1252 LOC) — god component.
- `client/src/components/meatspace/tabs/CalendarTab.jsx` (1269 LOC) — extract grid renderer + goal-link panels.
- `client/src/components/cos/tabs/ScheduleTab.jsx` (1088 LOC) — extract schedule editor + run history table.
@@ -123,32 +120,7 @@ All dependencies audited and justified (2026-04-28). 0 removals. See [docs/DEPS.
## Writers Room ↔ Pipeline DRY Unification
-The Writers Room and the Pipeline grew up in parallel and now duplicate enough machinery that bug fixes (e.g. character-physical-description injection, stage prompt drift, JSON extraction quirks) have to be applied twice — and one side usually gets missed. Both systems do the same five things: (1) call an LLM via the active provider, (2) extract characters/settings/objects from prose, (3) hold a project-scoped "bible," (4) generate a scene list, (5) compose per-scene image prompts. They should share a single implementation for each.
-
-Items below are ordered by dependency: each later item builds on earlier ones. Land them as separate PRs — none is so large it can't ship standalone.
-
-- [x] **1a. Drop the `sceneCardHelpers.js` shim** — shipped. Constants moved to new `client/src/lib/wrImageDefaults.js`; SceneCard.jsx + StoryboardPanel.jsx now import `buildScenePrompt` / `matchScene*` / `normCharKey` etc. directly from `client/src/lib/scenePrompt`. Shim file deleted.
-- [x] **1b. Mirror `composeStyledPrompt` to `server/lib/`** — shipped. `server/lib/composeStyledPrompt.js` is the verbatim mirror of `client/src/lib/composeStyledPrompt.js`. World Builder's `compileBatchPrompts` now uses it for both the variation and composite-sheet code paths. Side effect: the rendered prompts switch separator from `, ` to `. ` (the composeStyledPrompt convention shared with `scenePrompt`); semantically identical for diffusion models, two pinned test assertions updated. 6 unit tests.
-- [x] **1. Shared scene-prompt composer** — shipped. Canonical `server/lib/scenePrompt.js` with mirror `client/src/lib/scenePrompt.js` (Vite fs.allow doesn't reach across to `server/lib`, so we follow the project's existing manual-mirror convention). `writersRoom/settings.js#normalizeSlugline` and `sceneCardHelpers.js` both re-export from the canonical home. Pipeline `composeVisualPrompt` now routes through `buildScenePrompt` so series name + style + universal cast (series.characters[]) + scene visual all flow through the same algorithm with PROMPT_MAX-budgeted truncation. Storyboards stage UI + route schema accept an optional per-scene `slugline` so the eventual settings-bible match (item 2) is plumbed end-to-end. 18 new unit tests in `server/lib/scenePrompt.test.js`; existing 119-test pipeline + writers-room pack stays green.
-
-- [x] **2a. `createBibleStore({...})` factory** — shipped (2026-05-10). Factory lives in `server/lib/storyBible.js` and derives `fileName`/`listKey`/`idSuffix` regex internally from `kind`; callers supply `idPrefix` + `dedupKey` + `primaryFields` + `editableFields` + `requireOnCreate` + optional `validateAfterUpdate` + error strings. Each writers-room domain file collapses to ~30 LOC. -281 LOC across the three files; 12 new factory tests in `storyBible.test.js`. Settings' slugline-aware dedup and "blank-both → reject" guard go through the `dedupKey` callback and `validateAfterUpdate` respectively.
-- [x] **2b. Share zod bible-entry schemas between writers-room + pipeline routes** — shipped (2026-05-10). `server/lib/validation.js` re-exports `characterBibleCreateSchema` / `settingBibleCreateSchema` / `objectBibleCreateSchema` under kind-neutral names (the writers-room name `writersRoomCharacterCreateSchema` etc. stay for the existing route's import). Pipeline `routes/pipeline.js` extends those with its own back-compat fields (`description` legacy alias, `imageRefs`, optional `id`) plus `.passthrough()` so sanitizer-emitted fields (evidence/firstAppearance/source/timestamps) round-trip without strict-mode rejection. The loose `bibleEntrySchema = z.record(z.string(), z.any())` is gone. `settingBibleCreateSchema` is the un-refined `ZodObject` (the refined `writersRoomSettingCreateSchema` is the route-layer enforcer for the WR endpoint only); the "name OR slugline" rule is enforced at the sanitizer/store layer (`storyBible.js#sanitizeSetting` drops blank-both entries) — single source of truth.
-- [x] **2. Unified story-bible schema** — shipped. `server/lib/storyBible.js` owns the canonical `Character` / `Setting` / `Object` shapes + `sanitizeBibleList` + `mergeExtractedBible` (with per-kind key normalizers — slugline collapsing for settings, name-key for characters/objects). Writers-room `characters.js` / `settings.js` / `objects.js` collapsed onto the shared helpers (-299 LOC of duplicated merge/sanitize logic). Pipeline `series.characters` migrates to the canonical shape via back-compat read (legacy `description` field auto-promotes to `physicalDescription`); `series.settings[]` and `series.objects[]` added with the same sanitizers. `composeVisualPrompt` now activates the slugline-matching plumbed in item 1 — pipeline storyboard scenes that reuse a setting slugline get the canonical setting baseline (description + palette + recurring details) prepended automatically. 30 new tests in `server/lib/storyBible.test.js`; full server pack 3716/3716 green.
-
-- [x] **3. Shared staged-LLM runner** — shipped. `server/lib/stageRunner.js` exposes `runStagedLLM(stageName, variables, { providerOverride, modelOverride, returnsJson, source })` plus `resolveModel` (tier-aware) and `extractJson` (lenient code-fence stripper). Both `writersRoom/evaluator.js#runAnalysis` and `pipeline/textStages.js#generateStage` route through it. Writers-room evaluator went 589 → 435 LOC; the bespoke `callApiProvider` + `callCliProvider` + `buildCliInvocation` (~150 LOC of CLI-spawn drift) deleted. Pipeline text stages went 180 → 118 LOC. Writers-room calls now persist transcripts to `data/runs/<runId>/` (which the bespoke fetch path was silently skipping) and pick up tier-name model resolution for free. Behavioral note: per-stage temperature override (format=0.2, others=0.4) was dropped — the toolkit's `executeApiRun` doesn't expose a temp parameter; if format-stage drift surfaces, plumb temperature through the toolkit. 18 new stageRunner tests; obsolete `evaluator.test.js` (only `buildCliInvocation` coverage, now redundant with `runner.test.js:48`) deleted. Server pack 3733/3733 green.
-
-- [x] **4a. `extractAndMergeIntoSeries(seriesId, { kinds, corpus, ... })`** — shipped. The bible extract → merge → patch orchestration now lives in `server/services/pipeline/series.js`; the route shrinks to a `seriesSvc.extractAndMergeIntoSeries(series.id, {...})` call and `mergeExtractedBible` / `extractBible` are no longer route-layer imports. Mirrors how writers-room exposes `mergeExtractedCharacters(workId, extracted)`. Forwards the `parallel` flag from 4b through to the service so the speedup stays available. Pure refactor — all 23 pipeline route tests green without modification.
-- [x] **4b. Opt-in `parallel: true` mode for `/extract-bible`** — shipped. `extractBibleSchema` accepts a `parallel: boolean`; when true the three kinds fan out via `Promise.all` (~3× wall-clock speedup on HTTP-API providers). Default stays sequential — safe for CLI providers that serialize at the provider session anyway. Merge always runs after all extractions complete; `series.<field>` is read once at the top of the route so the merge baseline doesn't race. 2 new route tests: one drives the parallel guarantee (every start fires before the first finish), one drives the sequential guarantee (events alternate start/finish/start/finish/...).
-- [x] **4c. `client/src/hooks/useAsyncAction.js`** — shipped (2026-05-10). Hook returns `[run, running]`. Migrated `ProseStage.jsx#handleExtract`, `TextStagePanel.jsx#handleSave` + `#handleGenerate` (the latter OR'd with externally-synced `serverGenerating` for auto-runs), and `EpisodeVideoStage.jsx#submit`. `StoryboardsStage.jsx` deliberately stays on its existing pattern — `savingIdx` and `extractingFrom` are keyed loading states, not booleans; a keyed variant would be a bigger abstraction. Post-unmount setState guard with `mountedRef` deferred to a future general DRY pass (YAGNI for the current stable parent components).
-- [x] **4. Shared bible-extraction service** — shipped. `server/lib/bibleExtractor.js#extractBible({ kind, corpus, existing, context, providerOverride, source })` runs the staged LLM, pulls the `{ characters | settings | objects }` envelope, and routes through the canonical `sanitizeBibleList`. Returns the sanitized list + run metadata; the caller owns persistence (writers-room → `mergeExtractedX(workId, ...)`, pipeline → `mergeExtractedBible(series.<field>, extracted, kind)`) — splitting extraction from merge avoids the double-merge footgun. Writers-room evaluator's three bible SHAPERS (~75 LOC of duplicated field-trim) deleted; analysis path now goes `runAnalysis → extractBible → mergeExtractedX`. New pipeline route `POST /api/pipeline/series/:id/extract-bible` accepts `{ kinds, issueId, corpus, providerOverride }` and merges results into the series. New "Extract bibles" button on the Pipeline ProseStage that calls it. 12 lib tests + 4 route tests; full server pack 3746/3746 green.
-
-- [x] **5. Shared scene-list extractor** — shipped. `server/lib/sceneExtractor.js#extractScenes({ source, sourceKind, characters, settings, objects, work, series, issue, providerOverride, tag })` mirrors the bibleExtractor.js pattern: caller owns persistence, extractor owns the LLM call + sanitization. Two source modes: `prose` routes through the existing `writers-room-script` prompt; `tvScript` routes through the new `pipeline-extract-scenes` prompt (parses already-present sluglines instead of inventing them). Shared `sanitizeSceneList` is the single source of truth for the canonical scene shape (`{ id, heading, slugline, summary, characters, action, dialogue, visualPrompt, sourceSegmentIds }`) — defensive, every field has a typed fallback so a partial LLM response never crashes downstream. Writers Room evaluator's `script` kind now delegates here (~25 LOC of duplicated SHAPERS.script logic deleted); Pipeline storyboards stage gains a "From TV script" + "From prose" button pair via `POST /api/pipeline/issues/:id/stages/storyboards/extract-scenes` (with a 409 + two-click-arm replace-confirm guard so an extraction can't silently obliterate hand-curated scenes). 14 unit tests + 4 route tests; full server pack 3765/3765 green. **Side fix:** `issuePatchSchema.stages` z.union order swapped so PATCH /issues/:id with a visual stage payload (`scenes` / `pages` / `cdProjectId` / `videoPath`) no longer silently strips those fields — the union picked the strict text-only schema first, hiding the visual fields.
-
-- [x] **6. Pipeline ↔ Writers Room bridge** — shipped (one-way promote). New `server/services/writersRoom/promoteToPipeline.js#promoteWorkToPipeline(workId, { force })` creates a pipeline series + first issue from a writers-room work, carrying over (a) the active draft body → `stages.prose.output` with status `edited`, (b) the latest characters/settings/objects bibles → `series.{characters,settings,objects}` via the canonical sanitizer, and (c) the latest `script` analysis scenes → `stages.storyboards.scenes` with the same `visualPrompt → description` UI-shape alias the storyboards extractor route uses. Records the bidirectional link on both sides (`manifest.pipelineSeriesId` / `manifest.pipelineIssueId` on the WR work; `series.writersRoomWorkId` on the pipeline series). Idempotent by default — re-promoting a linked work returns the existing pair (`reused: true`) unless `{ force: true }`. If either linked record was deleted out-of-band, the stale link is dropped and a fresh series is created. **Re-sync action (one-way writers-room → pipeline on demand) deferred** — promote-once covers the user-stated need; re-sync needs UX work to communicate which fields will overwrite. Route `POST /api/writers-room/works/:id/promote-to-pipeline`. UI: "Promote to pipeline" menu item on `WorkEditor` (flips to "Open in pipeline" once linked); "Writers Room" badge on the `PipelineSeries` page header when `writersRoomWorkId` is set. **Side fix:** pipeline `series.js` + `issues.js` switched to lazy `statePath()` resolution (matching writers-room/local.js) — the previous eager `const STATE_PATH = join(PATHS.data, ...)` crashed under Proxy-based `PATHS.data` mocks that the new promote tests need. 8 service tests + 4 route tests.
-
-- [x] **7. Shared prompt template partials** — shipped. New `server/lib/promptPartials.js` adds Mustache-style `{{> partial-name }}` include support as a pre-processing pass before `applyTemplate` — the existing engine stays sync + pure (`promptTemplate.js` unchanged); partial expansion lives in a sibling module that pre-loads referenced partials from `<promptsDir>/_partials/` via the buildPrompt shim. Recursive expansion with a MAX_DEPTH=8 cycle guard; missing partials throw loudly (typo in `{{> visual-grammr }}` doesn't silently drop the section). Two partials shipped: `_partials/bible-deference.md` (the character + setting bible deference blocks, identical across writers-room-script and pipeline-extract-scenes) and `_partials/scene-output-contract.md` (the canonical scenes[] JSON output shape). Both `writers-room-script.md` and `pipeline-extract-scenes.md` collapse onto these two includes — bug-fixes to bible-deference logic now land in one place. 16 unit tests covering listPartialReferences, sync resolver-based expansion, async fs-backed expansion, cycle detection, missing-partial throws, and the no-partial fast path. **Note for existing installs:** `scripts/setup-data.js`'s `ensureSampleContent` only copies missing files — a user who already has `data/prompts/stages/writers-room-script.md` from a prior install keeps their copy (which is the right default if they've customized it). To pick up the partial-using refactor, manually re-copy from `data.sample/prompts/stages/`.
-
-**Testing strategy:** items 1, 2, 3 each have unit-test siblings already (`scenePrompt.test.js` lives next to the helpers; bible sanitizer + LLM runner get new test files). Items 4 & 5 need both unit tests (the extractor against a fixture prose) AND a small integration test that runs the writers-room and pipeline calling sites against the same input and asserts the same output shape — the whole point is one implementation, so the test should prove it.
+Steps 1–7 shipped (see DONE.md 2026-05-10). The Writers Room and Pipeline now share one scene-prompt composer, one story-bible schema + sanitizer, one staged-LLM runner, one bible-extraction service, one scene-list extractor, a one-way promote bridge, and a partials-aware prompt template engine. Remaining follow-ups live in the dedicated items above (drop legacy `description` fallback; `mockPathsDataRoot()` test helper; `useAsyncAction` post-unmount guard).
---
@@ -281,13 +253,8 @@ Skeleton landed in `server/services/pipeline/` + `client/src/pages/Pipeline*.jsx
- [ ] **Rich-text editor for prose stage.** Currently a plain `<textarea>` in `client/src/components/pipeline/stages/ProseStage.jsx`. Either reuse `client/src/components/writers-room/` editor, or pick a minimal markdown editor.
- [ ] **Versioning / diff view per stage.** No history right now — regenerating overwrites. Could persist last N `lastRunId` snapshots and offer a diff modal.
- [ ] **Episode-video provider picker (RunwayML / third-party).** Stubs are commented in `server/services/videoGen/`. Once that abstraction lands, the `episodeVideo` handoff should expose a provider picker on the EpisodeVideoStage UI (local LTX vs Runway vs …).
-- [x] **Episode-video aspectRatio / quality picker on the UI** — shipped. Inline `aspectRatio` + `quality` dropdowns on EpisodeVideoStage's pre-kickoff toolbar, plumbed through to the existing route. modelId picker deferred until the video model registry exposes a flagged-stable list for the UI to read.
-- [x] **Extract `ScenePreview` + shared CD status helpers** — shipped. New `client/src/components/creative-director/ScenePreview.jsx` owns the `<video controls poster>` + onError-missing-media + Retry + cache-bust idiom; `sceneStatus.js` exports `SCENE_STATUS`, `SCENE_STATUS_BADGE`, `SCENE_STATUS_LABEL`, `getSceneStatusBadge()`, `PROJECT_STATUS_LABEL`. SegmentsTab + EpisodeVideoStage both consume the shared components — EpisodeVideoStage's final-video render now has the missing-onError fallback for free (was hand-rolled and missing it). Side fix: the slim `?slim=1` CD projection was returning `scene.id` but CD scenes are keyed by `sceneId`; corrected the projection + its test fixture.
-- [x] **Slim `GET /creative-director/:id?slim=1` endpoint** — shipped. Drops the unbounded `runs[]` history + full treatment text; returns just `{ id, status, updatedAt, finalVideoId, failureReason, treatment: { scenes: [{ id, order, status }] } }`. EpisodeVideoStage's 4s poll now passes `{ slim: true }` to the client API. 2 new route tests.
-- [ ] **Series-arc grouping (Series → Arc → Issue).** Superseded by the "Pipeline — Story Arc Planning + Series Page Redesign" section below. Drop this entry once that initiative ships its Phase 1.
- [ ] **Comic-book PDF export.** Once `stages.comicPages` carries enough panel data + rendered images, export a print-ready PDF.
- [ ] **Voice-controlled stage advancement.** "Next stage", "rerun comic script" via the existing voice agent. Register pipeline stage navigation actions in `server/services/voice/tools.js`.
- [ ] **Recent-issues dynamic children under the Pipeline sidebar entry.** Currently Pipeline is a single sidebar link; could mirror Apps' `dynamic: 'apps'` pattern in `client/src/components/Layout.jsx`. **Wrinkle:** Apps is a TOP-LEVEL nav entry; Pipeline lives 2 levels deep under Create. The existing `renderNavItem`'s child render is flat — it emits a NavLink per child and ignores `child.children`. Needs either (a) recursive child render (cleaner, but bigger UX questions: indentation/collapsibility/auto-expand-depth) or (b) promoting Pipeline to a top-level nav entry (changes IA; might be the right call once it has its own subnav anyway). Attempted in this PR, backed out as out-of-scope.
- [ ] **AI-assisted panel/scene prompt generation.** Reserve `pipeline-comic-panel-image-prompt.md` and `pipeline-storyboard-image-prompt.md` template files for a future "AI: turn the script fragment into N image-gen prompts" button on the ComicPages and Storyboards stages.
- [ ] **Per-panel/scene image progress in the Pipeline UI.** Right now ComicPages and Storyboards record `jobId` but don't subscribe to the media-job SSE for live preview. Tie into the existing per-job progress hook so each panel shows live render thumbnails.
-- [x] **Background auto-run resumption** — shipped as "demote on boot." New `recoverStuckAutoRuns()` in `autoRunner.js` walks issues at boot and demotes any `status: 'running'` to `needs-review` (the same terminal state a normal-completion path lands on). Wired into `server/index.js` next to the existing brain / writers-room boot recovery calls. 2 new tests. **Not implemented: actual resume** — re-attaching SSE and re-running the missing stages would need the persisted runId + per-stage progress, which we don't write to disk. Falling back to `needs-review` (the user clicks "Run again" if they want to retry) is the safe, low-blast-radius fix.