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

Creative pipeline: WR↔Pipeline DRY unification + episode video + follow-ups (#215)

[._.]/ Adam Eivy2efdc9fafec0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c95adc8341..a212eb3c4c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,7 +2,10 @@
## Added
-- **Pipeline page** under Create — a series-production workflow that chains a rough idea seed through prose → comic-book script + TV teleplay (parallel) → comic pages + storyboards (image gen) → episode video. Each Series carries a shared bible (logline, premise, characters, optional World Builder ref, style notes) that every issue/episode inherits into its stage prompts so identity stays consistent across the run. The "Auto-run text stages" button kicks off the LLM chain end-to-end with SSE progress; the visual stages (comic pages, storyboards) hand off to the existing image-gen queue. Episode-video stitching via Creative Director is staged out — see `PLAN.md` → *Pipeline — Deferred*.
+- **Prompt template partials** — PortOS prompts now support Mustache-style `{{> partial-name }}` includes. Files in `data/prompts/_partials/` get inlined into stage templates at render time (recursive, with cycle detection + loud missing-partial errors). First two partials cover the duplicated bible-deference preamble and the scenes-JSON output contract that were copy-pasted across `writers-room-script.md` and `pipeline-extract-scenes.md`. Both prompts now reference the shared partials — future tweaks to "defer to canonical character names" or "this is the scenes[] JSON shape" land in one place. Step 7 of the Writers Room ↔ Pipeline DRY unification.
+- **Writers Room ↔ Pipeline bridge.** A "Promote to pipeline" action on a Writers Room work creates a Pipeline series + first issue in one call, carrying over the active draft prose, all three bibles (characters/settings/objects), and the latest script-analysis scenes as fully-populated storyboards. The two systems record each other's ids so the menu flips to "Open in pipeline" on subsequent visits, and the Pipeline series page surfaces a "Writers Room" badge linking back. Idempotent — re-promoting a linked work returns the existing pair instead of duplicating. Backed by `server/services/writersRoom/promoteToPipeline.js` and `POST /api/writers-room/works/:id/promote-to-pipeline`. Step 6 of the Writers Room ↔ Pipeline DRY unification.
+- **Pipeline page** under Create — a series-production workflow that chains a rough idea seed through prose → comic-book script + TV teleplay (parallel) → comic pages + storyboards (image gen) → episode video. Each Series carries a shared bible (logline, premise, characters, optional World Builder ref, style notes) that every issue/episode inherits into its stage prompts so identity stays consistent across the run. The "Auto-run text" button kicks off the LLM chain end-to-end with SSE progress; the visual stages (comic pages, storyboards) hand off to the existing image-gen queue.
+- **Pipeline episode video** now wired end-to-end to Creative Director. The Episode Video stage on a Pipeline issue creates a CD project from the storyboards scenes (series style notes auto-prepended, i2v continuation from scene 2 onward, audio disabled, scenes auto-accepted — no LLM evaluator round-trip since the human already vetted storyboards), persists the `cdProjectId` on the stage, polls render progress, and renders the final stitched mp4 inline when complete. A second "Run everything (incl. video)" button on the issue page extends auto-run past the text stages — text chain → episode-video kickoff in one click.
- Codex image gen: hi-res resolution presets (1024×1536, 1536×1024, 1536×1536) — gpt-image-2's native hi-res tier. Picking any ≥1536 size automatically appends a `(high quality)` hint to the codex prompt so the model renders at full fidelity instead of its 1024 default.
- Image Gen batch mode: a `× N` count input next to the Generate button (async modes only — local + codex) queues N renders of the same prompt+resolution in a single submit. The first job streams its progress live; the remaining N-1 land in the server queue and surface as `+N queued`. Each job gets a fresh random seed by default so the batch produces variations, not duplicates.
- Media Lightbox full-screen mode (`F` key or top-right toggle): drops the modal's rounding and padding and lets the image fill the viewport. Swipe left/right (or arrow keys) navigates between gallery items; tap reveals the settings as a slide-in drawer. Layered Escape closes drawer → exits full-screen → closes the lightbox. The Seed row in the settings pane is now copyable for easy reuse in a remix.
@@ -10,9 +13,18 @@
## Changed
+- Pipeline `POST /api/pipeline/series/:id/extract-bible` accepts a `parallel: true` flag that fans out the three bible kinds concurrently (~3× wall-clock speedup on HTTP-API providers like OpenAI / Anthropic / LM Studio HTTP). Default stays sequential so CLI-only providers (codex, claude-code, gemini-cli) — which serialize at the provider session anyway — aren't penalized.
+- Creative Director `GET /api/creative-director/:id` accepts a `?slim=1` query param that drops the unbounded `runs[]` history and the heavy treatment fields, returning only what a polling UI needs (`status`, `updatedAt`, per-scene `{ id, order, status }`, `finalVideoId`, `failureReason`). Pipeline EpisodeVideoStage's 4s poll now uses slim mode — keeps the UI responsive without pulling the entire render history on every tick.
+- Pipeline Storyboards stage gains "From TV script" + "From prose" auto-fill buttons. Once the upstream stage has output, one click runs the new shared `extractScenes()` LLM pass (sluglines parsed from the teleplay, or paragraph-grain beats lifted from the prose) and replaces `stages.storyboards.scenes[]` with the result. A two-click-arm replace guard surfaces a warning toast before clobbering hand-curated scenes. Backed by `POST /api/pipeline/issues/:id/stages/storyboards/extract-scenes` and the new `server/lib/sceneExtractor.js`, which both Pipeline AND the Writers Room evaluator's `script` analysis now route through — deleting ~25 LOC of duplicated SHAPERS.script logic and giving the Pipeline a one-click path from "TV script ready" to "all storyboards primed for image gen." Step 5 of the Writers Room ↔ Pipeline DRY unification. Side fix: the issue PATCH schema's `stages` z.union order was swapped so visual-stage payloads (`scenes` / `pages` / `cdProjectId` / `videoPath`) no longer silently strip on the way through — the union evaluated the text-only schema first, hiding the visual fields.
+- Pipeline ProseStage gains an "Extract bibles" button. Once you've drafted (or auto-run) the prose for an issue, one click fans out three LLM passes (characters / settings / objects) against the prose, sanitizes them through the canonical bible shape, and merges the result into the series-scoped bibles — fills only blank user-editable fields on existing entries (so your hand-edits survive) and inserts new entries with `source: 'ai'`. Backed by the new `POST /api/pipeline/series/:id/extract-bible` route + a single shared `server/lib/bibleExtractor.js` that the Writers Room analysis path also routes through; Writers Room's three bible SHAPERS (one per kind, ~75 LOC of duplicated field-trim) collapsed onto the canonical sanitizer. Step 4 of the Writers Room ↔ Pipeline DRY unification.
+- Writers Room and Pipeline now share one staged-LLM runner (`server/lib/stageRunner.js`). The Writers Room evaluator's bespoke `callApiProvider` (direct fetch) + `callCliProvider` (direct spawn) + `buildCliInvocation` (codex/gemini-cli/claude-code per-CLI quirk handling) are gone; both the Writers Room analyses and the Pipeline text stages now go through `runner.js`'s `executeApiRun`/`executeCliRun`. Writers Room transcripts now persist to `data/runs/<runId>/` so analyses are replayable from the runs UI. Stage tier-name model resolution (`model: 'heavy'` etc) extends to the Pipeline for free. Behavioral note: per-stage temperature override (format=0.2, others=0.4) was dropped because the toolkit's API runner doesn't expose temperature — sampling now follows the provider's defaults. Step 3 of the Writers Room ↔ Pipeline DRY unification.
+- Pipeline series gain settings + objects bibles (alongside the existing characters bible). All three writers-room bible kinds (characters, settings, objects) and the pipeline-side equivalent now share one canonical shape + extraction-merge implementation in `server/lib/storyBible.js`, deleting ~300 lines of near-identical per-kind code. Pipeline characters' legacy `description` field auto-migrates to `physicalDescription` on read so old series.json continues to load. The slugline plumbed in the previous unification step now activates: pipeline storyboard scenes that share a slugline with a setting bible entry get its description + palette + recurring details prepended to every render — visual continuity for free across an entire issue. Step 2 of the Writers Room ↔ Pipeline DRY unification.
+- Pipeline visual stages (Storyboards, Episode Video) and Writers Room SceneCard now share one image-prompt composer (`server/lib/scenePrompt.js` + `client/src/lib/scenePrompt.js` mirror). Pipeline previously concatenated `series.styleNotes + description` with no character or setting context — every render re-improvised the cast. The shared composer prepends style → series name → setting baseline (when matched) → "Featuring — name: physical description" for the universal cast → the scene's visual prompt, with budget-managed truncation at 1900 chars. First step of the Writers Room ↔ Pipeline DRY unification (PLAN.md).
- World Builder is now a standalone Create page at `/world-builder` with its own sidebar entry, instead of being buried under Media Gen's tab strip. The old path `/media/world-builder` still renders the same component so existing bookmarks and `⌘K` / voice references keep working. Sets the stage for the upcoming Pipeline page, which will deep-link to World Builder without having to traverse the Media nav.
- Image Gen resolution dropdown now filters by the selected backend. Flux-bucketed sizes (832×1216 / 1216×832) only appear for Flux 1/2 and external; the new 1536 hi-res tier only appears for codex and Flux 2. Z-Image-Turbo and ERNIE (trained at 1024²) now hide both groups to prevent users from picking sizes the model can't handle. A stale incompatible selection falls through to a `(custom)` option so the value stays visible until the user picks a supported one.
## Fixed
+- Pipeline issues no longer get stuck in `status: 'running'` after a server restart mid auto-run. Boot now walks every issue and demotes any `running` to `needs-review` (the same terminal state a normal completion lands on) — the UI shows the issue as needing attention instead of spinning forever waiting for SSE that will never arrive.
+- Pipeline EpisodeVideoStage final-video render no longer breaks when the underlying mp4 is missing — both surfaces (Creative Director SegmentsTab + Pipeline EpisodeVideoStage) now route through a shared `ScenePreview` component with the onError-missing-media fallback + Retry + cache-bust pattern.
- Render Queue UI now lists jobs in execution order (running first, then queue position ascending) instead of mixing a long-running job into the middle of newer queued batches. The route was sorting all jobs by `startedAt || queuedAt` DESC, which slotted an active job below a fresher batch.
diff --git a/DONE.md b/DONE.md
index ff56b9ee30..c7ffcea499 100644
--- a/DONE.md
+++ b/DONE.md
@@ -4,6 +4,13 @@ Archive of completed work. For active roadmap, see [PLAN.md](./PLAN.md). For pro
---
+## 2026-05-10
+
+- **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.
+- **Pipeline — episodeVideo wired end-to-end to Creative Director** — `POST /api/pipeline/issues/:id/stages/episodeVideo/visual` no longer returns 501. New `server/services/pipeline/episodeVideo.js#startEpisodeVideoForIssue` builds a CD treatment from the issue's storyboards scenes (series styleNotes prepended to each scene description, i2v continuation auto-enabled from scene 2 onward), creates a CD project with `autoAcceptScenes: true` + `disableAudio: true` (skips the LLM evaluator round-trip since the human already vetted the storyboards), persists `cdProjectId` on `stages.episodeVideo`, and kicks the CD orchestrator. Idempotent: re-POSTing returns the existing `cdProjectId` unless `force: true`. `EpisodeVideoStage.jsx` swapped its placeholder for a real UI that generates / restarts / polls the CD project (`getCreativeDirectorProject` on a 4s interval until terminal), surfaces per-scene render badges + a progress bar, and renders the final stitched `.mp4` inline when `cdProject.status === 'complete'`. `autoRunner.js` gained an optional `includeVideo` flag that fires the same handoff after text stages complete; a second "Run everything (incl. video)" button on the issue page opts users into it. Errors route through standard middleware (`ERR_NO_STORYBOARDS` → 400). 9 new tests + 1 rewritten (covers buildTreatmentFromStoryboards prompt composition, idempotency, force-restart, missing-storyboards rejection, includeVideo auto-run gating).
+
## 2026-05-09
- **Creative Director — i2v continuity fidelity (per-scene `imageStrength`)** — Added `imageStrength` (0..1, nullable) to `creativeDirectorSceneSchema` + `creativeDirectorSceneUpdateSchema`; `sceneRunner.resolveImageStrength` defaults continuation scenes (`useContinuationFromPrior=true`) to 0.85 and lets the evaluator override on retry. Already threaded through `videoGen/local.js#generateVideo` → mediaJobQueue. `creativeDirectorPrompts.js` surfaces the current setting on the evaluate view; `cd-treatment.md` / `cd-evaluate.md` document the knob; `TreatmentTab.jsx` shows "str X" on the scene chip. (PR #208)
diff --git a/PLAN.md b/PLAN.md
index 261f6679a0..dd4f4ba316 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -30,7 +30,7 @@ The dgrauet/ltx-2-mlx runtime ships with FFLF (true keyframe interpolation), aud
### 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).
+- [ ] **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.
- [ ] **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.
@@ -112,20 +112,173 @@ 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.
+
+- [ ] **2a. `bibleStore({ kind, idPrefix, idRegex, fileName, ... })` factory.** After items 1+2, the three writers-room files (`characters.js`/`settings.js`/`objects.js`) still share ~70% structurally — `loadFile`/`saveFile`/`listX`/`getX`/`createX`/`updateX`/`deleteX`/`mergeExtractedX` are byte-similar except for filename + idRegex + the setting-specific "name OR slugline" identifier rule + the post-update "blank-both → reject" guard. Extract into a `createBibleStore({ kind, idPrefix, idRegex, fileName, listKey, dedupKey, validateAfter })` factory in `server/lib/storyBible.js`. Each domain file shrinks to ~15 lines: `export const { list, get, create, update, delete, mergeExtracted } = createBibleStore({...})`. Setting's slugline-aware dedup goes in via the `dedupKey` callback. Estimated -250 LOC.
+- [ ] **2b. Share zod bible-entry schemas between writers-room + pipeline routes.** `server/lib/validation.js` already defines `writersRoomCharacterCreateSchema` / `writersRoomSettingCreateSchema` / `writersRoomObjectCreateSchema` mirroring `BIBLE_LIMITS` shape. Pipeline `routes/pipeline.js#bibleEntrySchema = z.record(z.string(), z.any())` is strictly looser — accepts arbitrary keys, no length caps. Re-export the writers-room schemas under generic names (`characterBibleSchema` / `settingBibleSchema` / `objectBibleSchema`) and have pipeline `routes/pipeline.js` extend them with its own back-compat `description` + `imageRefs` overrides.
+- [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/...).
+- [ ] **4c. `client/src/hooks/useAsyncAction.js`** — collapse the `setLoading(true) → await ... .catch(toast) → setLoading(false)` pattern that now duplicates across `ProseStage.jsx`, `TextStagePanel.jsx#handleGenerate`, `StoryboardsStage.jsx#handleGenerate`, `EpisodeVideoStage.jsx#handle*`. Returns `[run, running]`. Cross-cutting client cleanup, not WR↔Pipeline-specific — schedule with the next general DRY pass.
+- [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.
+
+---
+
+## Pipeline — Story Arc Planning + Series Page Redesign
+
+Today the PipelineSeries page (`client/src/pages/PipelineSeries.jsx`) is constrained to `max-w-5xl` and presents a single vertical scroll: bible metadata → characters → "Issues / Episodes" list with a one-line "New issue" input at the bottom. On a wide screen most of the viewport is wasted whitespace, and the only way to seed an issue is "type a title, click New, repeat." For a 24-episode show with a 3-season arc this is the wrong primitive — users want to plan the *whole arc* first, decide on the season/volume count, and only then drill into per-episode work.
+
+This initiative adds a structural Arc → Season(s) → Issue hierarchy and the LLM scaffolding to plan top-down. Supersedes the prior "Series-arc grouping" backlog item. Ship in phases so each phase is independently reviewable.
+
+### Phase 1 — Series page layout redesign (no schema change)
+
+The bible/style/world panels move to a left sidebar; the right side becomes the structural canvas. Drop the `max-w-5xl` cap; use a responsive 2-column grid (`grid-cols-1 lg:grid-cols-[360px_minmax(0,1fr)]`) so the page actually uses the viewport at wider widths.
+
+- Left sidebar (sticky, scroll-internal): NAME / TARGET FORMAT / LOGLINE / TARGET ISSUE COUNT / PREMISE / STYLE NOTES / LINKED WORLD / CHARACTERS. This is the "bible" — high-density inputs the user references but doesn't edit constantly.
+- Right canvas: Today this is just "Issues / Episodes" — Phase 2 fills it with the Arc tree. For Phase 1 it gets a card-grid view of existing issues (each card showing number / title / status / last-updated / a thumbnail of the most-recent storyboards image) instead of the current text list.
+- Collapsible left sidebar (so the canvas can expand to full width when the user is deep in episode work). Persists in localStorage like the existing Layout sidebar collapse.
+- Mobile: stays single-column, sidebar reflows above the canvas.
+
+Files: `client/src/pages/PipelineSeries.jsx`. No new server work.
+
+### Phase 2 — Arc + Season schema (Series → Arc → Season → Issue)
+
+Three new shapes; both stored on the existing `data/pipeline-series.json` (no new files — the arc is part of the series bible).
+
+```js
+// series.arc — overall multi-season story spine, optional
+{
+ logline: string, // one-sentence arc pitch
+ summary: string, // ~500 words: act structure, season-by-season turning points
+ themes: string[],
+ protagonistArc: string, // character growth across all seasons
+ status: 'draft' | 'verified',
+}
+// series.seasons[] — ordered list of seasons/volumes
+{
+ id: 'sea-<uuid>',
+ number: 1,
+ title: string,
+ logline: string,
+ synopsis: string, // ~200 words
+ episodeCountTarget: 8, // user-set target; actual issues may differ
+ themes: string[],
+ endingHook: string, // the line/image that pulls into season N+1
+ status: 'draft' | 'verified' | 'in-production' | 'complete',
+}
+// issue.seasonId (existing issue schema gains an optional pointer)
+{
+ ...existing fields,
+ seasonId: 'sea-...' | null, // null for ungrouped issues (back-compat)
+ arcPosition: number | null, // ordinal within the season — drives auto-sort
+}
+```
+
+- New `seasons` field on the series sanitizer with `sanitizeSeasonList()` in a new `server/lib/storyArc.js` (mirrors `storyBible.js` — canonical shape + sanitization + merge helpers).
+- Issue sanitizer gains `seasonId` + `arcPosition` (back-compat: existing un-grouped issues keep `seasonId: null`).
+- Service helpers: `listSeasons(seriesId)`, `createSeason(seriesId, input)`, `updateSeason(seriesId, seasonId, patch)`, `deleteSeason(seriesId, seasonId, { reassignTo: seasonId | null })` (reassigns child issues to a sibling or to null on delete).
+- No DB migration needed — JSON files take additive fields cleanly.
+
+Files: `server/lib/storyArc.js` (new), `server/services/pipeline/series.js`, `server/services/pipeline/issues.js`, `server/services/pipeline/seasons.js` (new), `server/routes/pipeline.js`. Route additions: `POST/PATCH/DELETE /api/pipeline/series/:id/seasons[/:seasonId]`. Tests follow the same pattern as `seriesService.test.js`.
+
+### Phase 3 — LLM-assisted arc generation (new stage prompts)
+
+Three new staged-LLM prompts in `data.sample/prompts/stages/`:
+
+- **`pipeline-arc-overview`** (returns JSON `{ logline, summary, themes, protagonistArc, seasonOutlines: [{ number, title, logline, endingHook, episodeCountTarget }] }`). Inputs: series bible (name, logline, premise, characters, target format, target issue count). The model proposes a top-level arc + season breakdown. Default `model: 'heavy'` since this is the most expensive single call in the pipeline (reasoning over the full series scope).
+- **`pipeline-season-episodes`** (returns JSON `{ episodes: [{ number, title, logline, synopsis, primaryCharacters, arcRole }] }`). Inputs: series bible + chosen season's outline + prior seasons' synopses (for continuity context). Generates the per-episode breakdown for one season. Called per-season so a user can revise season N's outline without re-generating earlier seasons.
+- **`pipeline-arc-verify`** (returns JSON `{ issues: [{ severity, location, problem, suggestion }] }`). Inputs: full arc + all seasons + all issues. Sanity-checks for: character arcs that contradict across seasons, dropped subplots, episode-count mismatch vs. arc weight, unresolved hooks at the series finale.
+
+Reuses the shared `stageRunner.js` so each call is replayable from `/runs`. All three stages register in `stage-config.json` and get the `_partials` treatment for the bible-deference block (same as `pipeline-extract-scenes.md`).
+
+Service: `server/services/pipeline/arcPlanner.js` exposing `generateArcOverview(seriesId)`, `generateSeasonEpisodes(seriesId, seasonId, { force })`, `verifyArc(seriesId)`. Each returns `{ result, runId, providerId, model }` and the caller persists via `updateSeries`/`createSeason`/`createIssue` chains.
+
+Routes: `POST /api/pipeline/series/:id/arc/generate`, `POST /api/pipeline/series/:id/seasons/:seasonId/episodes/generate`, `POST /api/pipeline/series/:id/arc/verify`.
+
+### Phase 4 — Arc canvas UI (right-side replacement)
+
+The Phase 1 card-grid evolves into a vertical Arc → Season → Episode tree:
+
+```
+┌─ Arc ──────────────────────────────────────┐
+│ Logline: "..." │
+│ Themes: [betrayal] [legacy] │
+│ [Edit arc] [Verify arc] [Regenerate] │
+└────────────────────────────────────────────┘
+
+▶ Season 1 — "The Choir Awakens" [12 episodes]
+ Episode 1 — "First Light" [draft]
+ Episode 2 — "Hollow Bones" [ready]
+ ...
+ [+ Add episode] [Generate episodes (LLM)]
+
+▶ Season 2 — "Diaspora" [8 episodes]
+ ...
+
+[+ Add season] [Generate arc (LLM)]
+```
+
+- Each season collapsible (`<details>` semantics) — collapsed seasons show season # + title + episode count badge; expanded seasons show the issue rows + the "generate season" action.
+- "Generate arc" runs `pipeline-arc-overview` and seeds `series.arc` + `series.seasons[]` after a preview/confirm modal (same two-click-arm pattern as the storyboards extractor).
+- "Generate episodes" on a season runs `pipeline-season-episodes` and creates the issue records with `seasonId` set + `arcPosition` numbered sequentially.
+- "Verify arc" surfaces findings inline as a sidebar list with severity badges, click-through to the offending season/episode.
+- Drag-and-drop to reorder episodes within a season + move between seasons (updates `arcPosition` + `seasonId`). Deferrable to Phase 4b.
+
+Files: `client/src/components/pipeline/ArcCanvas.jsx` (new), per-season `<SeasonRow>` + per-issue `<IssueRow>` subcomponents. Replaces today's flat "Issues / Episodes" list at the bottom of PipelineSeries.
+
+### Phase 5 — Cross-season continuity hooks (deferrable)
+
+Once seasons exist, the per-episode prose/script stages can inject "previous episode arc state" + "where we are in this season" into the prompt context automatically — the LLM stops re-inventing where the characters left off. New variable on issue prompts: `seasonContext` = the season's synopsis + the last 1–3 episodes' loglines. Plumbed through the existing `series` / `issue` prompt context object in textStages.js. Small once Phases 2–4 land; the work is mostly prompt-template edits.
+
+### Out of scope / explicitly not doing
+
+- Per-season independent media collections (one folder per season). The collection model is already per-series; per-season splits add UX complexity without clear value.
+- Multi-series arcs (a season that spans two related series). Single-series scope keeps the data model flat and the LLM context bounded.
+- Auto-promoting an existing flat list of issues into seasons. Users opt in via the "Generate arc" action; existing issues stay un-grouped (`seasonId: null`) until the user moves them.
+
+### Suggested PR sequence
+
+1. **Phase 1** standalone — pure UI refactor, no schema change. Easy review.
+2. **Phase 2** standalone — schema + service + route + tests. No UI yet.
+3. **Phase 3 + Phase 4 together** — the LLM prompts only have user value once the canvas surfaces them.
+4. **Phase 5** standalone — small prompt-context follow-up.
+
+---
+
## Pipeline — Deferred
-Skeleton landed in `server/services/pipeline/` + `client/src/pages/Pipeline*.jsx`. Items below were scoped out of MVP and live here so they don't evaporate:
+Skeleton landed in `server/services/pipeline/` + `client/src/pages/Pipeline*.jsx`. The core text-to-video creative pipeline is now wired end-to-end (idea → prose → scripts → storyboards → episode video via CD handoff). Items below were scoped out and live here so they don't evaporate:
-- [ ] **Wire `episodeVideo` stage to Creative Director.** `POST /api/pipeline/issues/:id/stages/episodeVideo/visual` currently returns 501. Refactor `server/services/creativeDirector/sceneRunner.js` + `orchestrator.js` to expose a `runSceneForExternalCaller(projectId, sceneId)` helper, then have `visualStages.js` use it for per-scene video + stitch. Persist `cdProjectId` + `videoPath` into `stages.episodeVideo`.
-- [ ] **Wire `storyboards` scene-video rendering** through the same CD handoff once episodeVideo lands. Each scene already records `imageJobId`; add optional `sceneVideoJobId`.
+- [ ] **Wire `storyboards` scene-video rendering** as a separate path from the episode-video handoff. Currently storyboards records `imageJobId` per scene; add optional `sceneVideoJobId` so a user can render an individual scene's video without committing the full episode-video stitch.
- [ ] **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.
-- [ ] **"Auto-run everything including video" button.** MVP auto-run stops after the text stages (idea → prose → comic+TV scripts) to avoid burning GPU minutes on un-reviewed content. Add this once `episodeVideo` is wired.
-- [ ] **RunwayML / third-party video provider integration.** Stubs are commented in `server/services/videoGen/`. Once that abstraction lands, the Pipeline's episodeVideo stage should expose a provider picker (local LTX vs Runway vs …).
-- [ ] **Series-arc grouping (Series → Arc → Issue).** MVP collapses arc into series; some narratives want a 3-issue arc that nests inside the series and shares its own arc-bible. Add an `arc` field on issues or a parallel `data/pipeline-arcs.json`.
+- [ ] **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`.
+- [ ] **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.
-- [ ] **Background auto-run resumption.** If the server restarts mid auto-run, the in-memory `runs` map in `autoRunner.js` is lost — the issue is left in `status: running` with no SSE attachable. Add a startup hook that scans for issues in `running` state and either clears them to `needs-review` or resumes them.
+- [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.
diff --git a/client/src/components/creative-director/ScenePreview.jsx b/client/src/components/creative-director/ScenePreview.jsx
new file mode 100644
index 0000000000..24f22b2e33
--- /dev/null
+++ b/client/src/components/creative-director/ScenePreview.jsx
@@ -0,0 +1,73 @@
+import { useState, useEffect } from 'react';
+import { ExternalLink } from 'lucide-react';
+
+/**
+ * Inline <video> preview for a single rendered scene. Used by SegmentsTab
+ * (CD detail page) and by EpisodeVideoStage (Pipeline issue page).
+ *
+ * Behavior notes:
+ * - `renderedJobId` survives even after the underlying mp4 is deleted from
+ * history, so the <video> can fail to load. We track that with onError
+ * and fall back to a "missing media" placeholder + Retry button.
+ * - `attempt` bumps via the Retry button and via the `jobId` reset effect
+ * (a re-render with the same jobId would otherwise leave a transient
+ * load error stuck for the rest of the session). The `?retry=N` cache
+ * buster forces the browser to re-fetch instead of using the cached
+ * error response.
+ * - `controls` + `preload="none"` keeps the thumbnail-driven idle state
+ * without ever fetching the full mp4 until the user hits Play.
+ */
+export default function ScenePreview({ jobId, label }) {
+ const [missing, setMissing] = useState(false);
+ const [attempt, setAttempt] = useState(0);
+ useEffect(() => {
+ setMissing(false);
+ setAttempt(0);
+ }, [jobId]);
+
+ if (!jobId) {
+ return <div className="bg-port-bg aspect-video flex items-center justify-center text-port-text-muted text-xs">no render yet</div>;
+ }
+ const cacheBust = attempt > 0 ? `?retry=${attempt}` : '';
+ const videoSrc = `/data/videos/${jobId}.mp4${cacheBust}`;
+ const posterSrc = `/data/video-thumbnails/${jobId}.jpg${cacheBust}`;
+ if (missing) {
+ return (
+ <div className="bg-port-bg aspect-video flex flex-col items-center justify-center text-port-text-muted text-xs gap-2">
+ <span>media missing</span>
+ <button
+ type="button"
+ onClick={() => { setMissing(false); setAttempt((a) => a + 1); }}
+ className="px-2 py-0.5 rounded border border-port-border hover:bg-port-card text-port-text"
+ >
+ Retry
+ </button>
+ </div>
+ );
+ }
+ return (
+ <div className="relative bg-port-bg aspect-video">
+ <video
+ key={attempt}
+ src={videoSrc}
+ poster={posterSrc}
+ controls
+ preload="none"
+ playsInline
+ aria-label={label}
+ onError={() => setMissing(true)}
+ className="w-full h-full object-cover"
+ />
+ <a
+ href={videoSrc}
+ target="_blank"
+ rel="noopener noreferrer"
+ aria-label={`Open ${label} in new tab`}
+ title="Open video in new tab"
+ className="absolute top-1 right-1 p-1 rounded bg-black/50 text-white hover:bg-black/80"
+ >
+ <ExternalLink className="w-3 h-3" />
+ </a>
+ </div>
+ );
+}
diff --git a/client/src/components/creative-director/SegmentsTab.jsx b/client/src/components/creative-director/SegmentsTab.jsx
index 1e337ef465..660ee05ff5 100644
--- a/client/src/components/creative-director/SegmentsTab.jsx
+++ b/client/src/components/creative-director/SegmentsTab.jsx
@@ -1,85 +1,8 @@
-import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
-import { Bot, ExternalLink } from 'lucide-react';
+import { Bot } from 'lucide-react';
import { extractKind } from './ActiveAgentsBanner.jsx';
-
-const STATUS_BADGE = {
- pending: 'bg-port-border text-port-text-muted',
- rendering: 'bg-port-accent/30 text-port-accent',
- evaluating: 'bg-port-warning/30 text-port-warning',
- accepted: 'bg-port-success/30 text-port-success',
- failed: 'bg-port-error/30 text-port-error',
-};
-
-// Renders the preview area for a scene that has a rendered video.
-// Uses <video controls poster> so the thumbnail is shown when idle and the
-// user can play the clip in-tab without leaving the page. The browser handles
-// a missing poster (ffmpeg/thumbnail not generated) by showing its own blank
-// poster — controls remain fully accessible either way.
-//
-// `renderedJobId` survives even after the underlying mp4 is deleted from
-// history, so the <video> can fail to load. We track that with onError and
-// fall back to a "missing media" placeholder (matches the prior <a><img>
-// onError-hides-tile behavior) instead of leaving a broken control.
-function ScenePreview({ jobId, label }) {
- const [missing, setMissing] = useState(false);
- // `attempt` is bumped manually by the user-clickable Retry button below
- // (and indirectly by the jobId reset effect — a re-render with the same
- // jobId would otherwise leave a transient load error stuck for the rest
- // of the session). Each bump remounts <video> via the keyed `?retry=N`
- // suffix so the browser re-fetches instead of using its cached error.
- const [attempt, setAttempt] = useState(0);
- // Reset the missing flag when jobId changes so a re-rendered scene gets
- // a fresh load attempt instead of inheriting the prior scene's "media
- // missing" state. attempt resets too so the cache-busting param starts
- // fresh per scene.
- useEffect(() => {
- setMissing(false);
- setAttempt(0);
- }, [jobId]);
- const cacheBust = attempt > 0 ? `?retry=${attempt}` : '';
- const videoSrc = `/data/videos/${jobId}.mp4${cacheBust}`;
- const posterSrc = `/data/video-thumbnails/${jobId}.jpg${cacheBust}`;
- if (missing) {
- return (
- <div className="bg-port-bg aspect-video flex flex-col items-center justify-center text-port-text-muted text-xs gap-2">
- <span>media missing</span>
- <button
- type="button"
- onClick={() => { setMissing(false); setAttempt((a) => a + 1); }}
- className="px-2 py-0.5 rounded border border-port-border hover:bg-port-card text-port-text"
- >
- Retry
- </button>
- </div>
- );
- }
- return (
- <div className="relative bg-port-bg aspect-video">
- <video
- key={attempt}
- src={videoSrc}
- poster={posterSrc}
- controls
- preload="none"
- playsInline
- aria-label={label}
- onError={() => setMissing(true)}
- className="w-full h-full object-cover"
- />
- <a
- href={videoSrc}
- target="_blank"
- rel="noopener noreferrer"
- aria-label={`Open ${label} in new tab`}
- title="Open video in new tab"
- className="absolute top-1 right-1 p-1 rounded bg-black/50 text-white hover:bg-black/80"
- >
- <ExternalLink className="w-3 h-3" />
- </a>
- </div>
- );
-}
+import ScenePreview from './ScenePreview.jsx';
+import { SCENE_STATUS_BADGE } from './sceneStatus.js';
export default function SegmentsTab({ project, activeAgents = [] }) {
const scenes = project.treatment?.scenes;
@@ -139,7 +62,7 @@ export default function SegmentsTab({ project, activeAgents = [] }) {
<div className="p-2 space-y-1">
<div className="flex items-center justify-between gap-2">
<div className="text-sm font-medium">Scene {s.order + 1}</div>
- <span className={`text-xs px-2 py-0.5 rounded ${STATUS_BADGE[decoratedStatus] || ''}`}>{decoratedStatus}</span>
+ <span className={`text-xs px-2 py-0.5 rounded ${SCENE_STATUS_BADGE[decoratedStatus] || ''}`}>{decoratedStatus}</span>
</div>
<div className="text-xs text-port-text-muted truncate" title={s.intent}>{s.intent}</div>
<div className="text-xs text-port-text-muted">
diff --git a/client/src/components/creative-director/sceneStatus.js b/client/src/components/creative-director/sceneStatus.js
new file mode 100644
index 0000000000..b9e8177b1d
--- /dev/null
+++ b/client/src/components/creative-director/sceneStatus.js
@@ -0,0 +1,59 @@
+/**
+ * Shared scene-status presentation helpers for the Creative Director scene
+ * runner and any consumer that polls it (Pipeline EpisodeVideoStage).
+ *
+ * The CD scene runner uses ~five terminal scene statuses (`pending`,
+ * `rendering`, `evaluating`, `accepted`, `failed`). Lifting them into a
+ * shared module keeps the badge palette in sync between the CD detail page
+ * and the Pipeline issue page so a "rendering" badge looks identical in
+ * both surfaces.
+ */
+
+export const SCENE_STATUS = Object.freeze({
+ PENDING: 'pending',
+ RENDERING: 'rendering',
+ EVALUATING: 'evaluating',
+ ACCEPTED: 'accepted',
+ FAILED: 'failed',
+});
+
+// Tailwind class map keyed by scene.status. `evaluating` reuses warning
+// because the runner is waiting on the evaluator's accept/reject decision;
+// it's not yet "done" but not actively rendering either.
+export const SCENE_STATUS_BADGE = Object.freeze({
+ pending: 'bg-port-border text-port-text-muted',
+ rendering: 'bg-port-accent/30 text-port-accent',
+ evaluating: 'bg-port-warning/30 text-port-warning',
+ accepted: 'bg-port-success/30 text-port-success',
+ failed: 'bg-port-error/30 text-port-error',
+});
+
+// Short user-facing label per scene status. Pipeline EpisodeVideoStage
+// previously rolled its own ('done', 'checking') — collapsed here so
+// terminology stays consistent across the two surfaces.
+export const SCENE_STATUS_LABEL = Object.freeze({
+ pending: 'pending',
+ rendering: 'rendering',
+ evaluating: 'checking',
+ accepted: 'done',
+ failed: 'failed',
+});
+
+export function getSceneStatusBadge(status) {
+ return {
+ cls: SCENE_STATUS_BADGE[status] || SCENE_STATUS_BADGE.pending,
+ text: SCENE_STATUS_LABEL[status] || status || 'pending',
+ };
+}
+
+// Top-level CD project statuses. Used by EpisodeVideoStage to render a
+// "Preparing / Rendering / Complete / Failed" pill on the issue page.
+export const PROJECT_STATUS_LABEL = Object.freeze({
+ draft: 'Preparing',
+ pending: 'Preparing',
+ treatment_ready: 'Ready',
+ rendering: 'Rendering',
+ evaluating: 'Reviewing',
+ complete: 'Complete',
+ failed: 'Failed',
+});
diff --git a/client/src/components/pipeline/stages/EpisodeVideoStage.jsx b/client/src/components/pipeline/stages/EpisodeVideoStage.jsx
index 29dab9cc79..096bfc0bc8 100644
--- a/client/src/components/pipeline/stages/EpisodeVideoStage.jsx
+++ b/client/src/components/pipeline/stages/EpisodeVideoStage.jsx
@@ -1,35 +1,313 @@
+import { useEffect, useMemo, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
-import { Film, ExternalLink } from 'lucide-react';
-
-/**
- * Episode Video stage — deferred to a follow-up PR. For MVP we expose the
- * placeholder + link to Creative Director, which still has the full
- * scene→render→stitch flow under its own page.
- */
-export default function EpisodeVideoStage() {
+import { Film, ExternalLink, Loader2, Sparkles, AlertCircle, CheckCircle2 } from 'lucide-react';
+import toast from '../../ui/Toast';
+import { generatePipelineVisualImage } from '../../../services/api';
+import { getCreativeDirectorProject } from '../../../services/apiCreativeDirector';
+import { getSceneStatusBadge, PROJECT_STATUS_LABEL } from '../../creative-director/sceneStatus';
+import ScenePreview from '../../creative-director/ScenePreview';
+
+const POLL_INTERVAL_MS = 4000;
+
+const isTerminalProjectStatus = (s) => s === 'complete' || s === 'failed';
+
+// Extra labels EpisodeVideoStage uses beyond the shared scene-status map —
+// these are CD project statuses specific to the long-form pipeline (planning,
+// stitching, paused). Fall through to PROJECT_STATUS_LABEL for the shared ones.
+const STATUS_LABEL = {
+ ...PROJECT_STATUS_LABEL,
+ planning: 'Planning',
+ stitching: 'Stitching final cut',
+ paused: 'Paused',
+};
+
+export default function EpisodeVideoStage({ issue, onStageUpdate }) {
+ const stage = issue.stages?.episodeVideo || {};
+ const cdProjectId = stage.cdProjectId || null;
+ const storyboardScenes = issue.stages?.storyboards?.scenes || [];
+ const usableScenes = storyboardScenes.filter((s) => (s?.description || '').trim().length > 0);
+
+ const [cdProject, setCdProject] = useState(null);
+ const [submitting, setSubmitting] = useState(false);
+ const [confirmRestart, setConfirmRestart] = useState(false);
+ // Initialize from the persisted stage values so a page reload (or a fresh
+ // tab) doesn't lose the user's previous picks. Falls through to defaults
+ // for an unstarted episodeVideo stage.
+ const [aspectRatio, setAspectRatio] = useState(stage.aspectRatio || '16:9');
+ const [quality, setQuality] = useState(stage.quality || 'standard');
+ const intervalRef = useRef(null);
+
+ // Single polling effect keyed only on cdProjectId so a status flip doesn't
+ // tear down and rebuild the interval (each tear-down fired an immediate
+ // fetch → setState → effect re-run, producing a fetch storm at every
+ // transition). The interval clears itself once status becomes terminal.
+ useEffect(() => {
+ if (!cdProjectId) {
+ setCdProject(null);
+ return undefined;
+ }
+ let cancelled = false;
+ const stop = () => {
+ if (intervalRef.current) {
+ clearInterval(intervalRef.current);
+ intervalRef.current = null;
+ }
+ };
+ const fetchOnce = async () => {
+ if (document.hidden) return;
+ const p = await getCreativeDirectorProject(cdProjectId, { slim: true }).catch((err) => {
+ if (!cancelled) console.log(`pipeline:episode poll error ${err.message}`);
+ return null;
+ });
+ if (cancelled || !p) return;
+ // Skip the setState (and downstream re-render + scene re-sort) when the
+ // poll returns the same monotonic snapshot we already hold.
+ setCdProject((prev) => (
+ prev && prev.updatedAt === p.updatedAt && prev.status === p.status ? prev : p
+ ));
+ if (isTerminalProjectStatus(p.status)) stop();
+ };
+ fetchOnce();
+ intervalRef.current = setInterval(fetchOnce, POLL_INTERVAL_MS);
+ return () => {
+ cancelled = true;
+ stop();
+ };
+ }, [cdProjectId]);
+
+ const submit = async ({ force }) => {
+ if (!force && !usableScenes.length) {
+ toast.error('Add storyboard scenes with descriptions first');
+ return;
+ }
+ setConfirmRestart(false);
+ setSubmitting(true);
+ const payload = { aspectRatio, quality };
+ if (force) payload.force = true;
+ const result = await generatePipelineVisualImage(issue.id, 'episodeVideo', payload).catch((err) => {
+ toast.error(err.message || (force ? 'Failed to restart episode render' : 'Failed to start episode render'));
+ return null;
+ });
+ setSubmitting(false);
+ if (!result) return;
+ if (force) {
+ // Only clear the prior project view AFTER the restart kickoff succeeds.
+ // Clearing pre-flight (which we used to do) meant a failed restart
+ // tore the in-flight progress UI off the page even though the
+ // previous CD project was still rendering.
+ setCdProject(null);
+ toast.success(`Restarted: ${result.cdProjectId.slice(0, 8)}`);
+ } else if (result.reused) {
+ toast.success(`Reusing in-flight CD project ${result.cdProjectId.slice(0, 8)}`);
+ } else {
+ toast.success(`Queued ${result.scenes} scene${result.scenes === 1 ? '' : 's'}`);
+ }
+ onStageUpdate?.('episodeVideo', {
+ ...stage,
+ status: 'generating',
+ cdProjectId: result.cdProjectId,
+ // Mirror the server's persisted render settings on the client-side
+ // issue model so a same-session navigate-away-and-back doesn't reset
+ // the restart pickers to defaults before a full refetch lands.
+ aspectRatio,
+ quality,
+ });
+ };
+
+ const sortedScenes = useMemo(
+ () => [...(cdProject?.treatment?.scenes || [])].sort((a, b) => a.order - b.order),
+ [cdProject?.treatment?.scenes],
+ );
+ const accepted = sortedScenes.filter((s) => s.status === 'accepted').length;
+ const total = sortedScenes.length;
+ const finalVideoId = cdProject?.finalVideoId || null;
+ const isComplete = cdProject?.status === 'complete' && finalVideoId;
+ const isFailed = cdProject?.status === 'failed';
+ const polling = cdProject && !isTerminalProjectStatus(cdProject.status);
+
return (
<div className="space-y-4">
- <div className="flex items-center gap-3">
- <Film className="w-5 h-5 text-port-accent" />
- <h2 className="text-lg font-semibold text-white">Episode Video</h2>
- </div>
- <div className="p-4 bg-port-card border border-port-border rounded-lg space-y-3">
- <p className="text-sm text-gray-300">
- Episode-video stitching directly from the storyboards isn't wired through the Pipeline yet. For
- now, drive per-scene video and final stitch from Creative Director, which already has the full
- treatment → scene render → stitch loop.
- </p>
- <p className="text-xs text-gray-500">
- The follow-up here is documented in <code className="text-port-accent">PLAN.md</code> under
- {' '}<em>Pipeline — Deferred</em>.
- </p>
- <Link
- to="/media/creative-director"
- className="inline-flex items-center gap-1 text-sm text-port-accent hover:underline"
- >
- Open Creative Director <ExternalLink size={12} />
- </Link>
+ <div className="flex items-center justify-between flex-wrap gap-3">
+ <div className="flex items-center gap-3">
+ <Film className="w-5 h-5 text-port-accent" />
+ <div>
+ <h2 className="text-lg font-semibold text-white">Episode Video</h2>
+ <p className="text-xs text-gray-500 mt-0.5">
+ Renders each storyboard scene as a video clip, then stitches them into a final episode.
+ </p>
+ </div>
+ </div>
+ {!cdProjectId ? (
+ <div className="flex items-center gap-2 flex-wrap">
+ <select
+ value={aspectRatio}
+ onChange={(e) => setAspectRatio(e.target.value)}
+ disabled={submitting}
+ aria-label="Aspect ratio"
+ title="Aspect ratio for the rendered scenes"
+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-gray-300"
+ >
+ <option value="16:9">16:9</option>
+ <option value="9:16">9:16</option>
+ <option value="1:1">1:1</option>
+ </select>
+ <select
+ value={quality}
+ onChange={(e) => setQuality(e.target.value)}
+ disabled={submitting}
+ aria-label="Render quality"
+ title="Render quality — higher = slower + more GPU time"
+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-gray-300"
+ >
+ <option value="draft">draft</option>
+ <option value="standard">standard</option>
+ <option value="high">high</option>
+ </select>
+ <button
+ type="button"
+ onClick={() => submit({ force: false })}
+ disabled={submitting || !usableScenes.length}
+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent text-white text-sm disabled:opacity-50"
+ title={!usableScenes.length ? 'Add storyboard scenes with descriptions first' : ''}
+ >
+ {submitting ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
+ Generate Episode ({usableScenes.length} scene{usableScenes.length === 1 ? '' : 's'})
+ </button>
+ </div>
+ ) : confirmRestart ? (
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-xs text-port-warning">Start a new CD project?</span>
+ <select
+ value={aspectRatio}
+ onChange={(e) => setAspectRatio(e.target.value)}
+ disabled={submitting}
+ aria-label="Aspect ratio"
+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-gray-300"
+ >
+ <option value="16:9">16:9</option>
+ <option value="9:16">9:16</option>
+ <option value="1:1">1:1</option>
+ </select>
+ <select
+ value={quality}
+ onChange={(e) => setQuality(e.target.value)}
+ disabled={submitting}
+ aria-label="Render quality"
+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-gray-300"
+ >
+ <option value="draft">draft</option>
+ <option value="standard">standard</option>
+ <option value="high">high</option>
+ </select>
+ <button
+ type="button"
+ onClick={() => submit({ force: true })}
+ disabled={submitting}
+ className="px-2 py-1 rounded bg-port-error text-white text-xs disabled:opacity-50"
+ >
+ {submitting ? <Loader2 size={12} className="animate-spin" /> : 'Yes, restart'}
+ </button>
+ <button
+ type="button"
+ onClick={() => setConfirmRestart(false)}
+ className="px-2 py-1 rounded bg-port-card border border-port-border text-white text-xs"
+ >
+ Cancel
+ </button>
+ </div>
+ ) : (
+ <button
+ type="button"
+ onClick={() => setConfirmRestart(true)}
+ disabled={submitting}
+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-card border border-port-border text-white text-sm hover:border-port-accent/50 disabled:opacity-50"
+ >
+ <Sparkles size={14} />
+ Restart
+ </button>
+ )}
</div>
+
+ {!cdProjectId ? (
+ <div className="p-4 bg-port-card border border-port-border rounded-lg space-y-2">
+ {usableScenes.length === 0 ? (
+ <p className="text-sm text-gray-400 flex items-center gap-2">
+ <AlertCircle size={14} className="text-port-warning" />
+ No storyboard scenes with descriptions yet. Fill in the Storyboards stage first.
+ </p>
+ ) : (
+ <p className="text-sm text-gray-300">
+ Ready to render {usableScenes.length} scene{usableScenes.length === 1 ? '' : 's'}. Each one becomes a short video clip; the first is text-to-video and every subsequent scene chains from the prior scene's last frame for visual continuity. Audio is disabled and scenes are auto-accepted (no LLM evaluator round-trip).
+ </p>
+ )}
+ </div>
+ ) : (
+ <div className="p-4 bg-port-card border border-port-border rounded-lg space-y-3">
+ <div className="flex items-center justify-between text-sm">
+ <div className="flex items-center gap-2">
+ {isComplete ? (
+ <CheckCircle2 size={16} className="text-port-success" />
+ ) : isFailed ? (
+ <AlertCircle size={16} className="text-port-error" />
+ ) : (
+ <Loader2 size={16} className={polling ? 'animate-spin text-port-accent' : 'text-gray-500'} />
+ )}
+ <span className="text-white">
+ {STATUS_LABEL[cdProject?.status || 'draft'] || cdProject?.status || 'Preparing'}
+ </span>
+ {total > 0 && (
+ <span className="text-xs text-gray-500">— {accepted}/{total} scenes</span>
+ )}
+ </div>
+ <Link
+ to={`/media/creative-director/${cdProjectId}`}
+ className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline"
+ >
+ Open in Creative Director <ExternalLink size={11} />
+ </Link>
+ </div>
+
+ {isFailed && cdProject?.failureReason && (
+ <p className="text-xs text-port-error bg-port-error/10 border border-port-error/30 rounded p-2">
+ {cdProject.failureReason}
+ </p>
+ )}
+
+ {total > 0 && (
+ <div className="space-y-1">
+ <div className="h-1.5 w-full bg-port-bg rounded-full overflow-hidden">
+ <div
+ className="h-full bg-port-accent transition-all"
+ style={{ width: `${total ? (accepted / total) * 100 : 0}%` }}
+ />
+ </div>
+ <ul className="flex flex-wrap gap-1.5 pt-1">
+ {sortedScenes.map((s) => {
+ const badge = getSceneStatusBadge(s.status);
+ return (
+ <li
+ key={s.sceneId}
+ className={`text-[10px] px-1.5 py-0.5 rounded font-mono ${badge.cls}`}
+ title={s.intent || s.sceneId}
+ >
+ #{s.order + 1} {badge.text}
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ )}
+
+ {isComplete && finalVideoId && (
+ <div className="space-y-2 pt-1">
+ <ScenePreview jobId={finalVideoId} label="Final episode video" />
+ <div className="text-xs text-gray-500">
+ <span className="font-mono">final {finalVideoId.slice(0, 8)}</span>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
</div>
);
}
diff --git a/client/src/components/pipeline/stages/ProseStage.jsx b/client/src/components/pipeline/stages/ProseStage.jsx
index ab4fc7ef4e..2905a1e4d7 100644
--- a/client/src/components/pipeline/stages/ProseStage.jsx
+++ b/client/src/components/pipeline/stages/ProseStage.jsx
@@ -1,12 +1,48 @@
+import { useState } from 'react';
+import { Library, Loader2 } from 'lucide-react';
+import toast from '../../ui/Toast';
+import { extractPipelineBibles } from '../../../services/api';
import TextStagePanel from './TextStagePanel';
-export default function ProseStage(props) {
+export default function ProseStage({ issue, series, onStageUpdate, onSeriesUpdate }) {
+ const [extracting, setExtracting] = useState(false);
+ const proseReady = (issue.stages?.prose?.output || '').trim().length > 0;
+
+ const handleExtract = async () => {
+ if (!series) return;
+ setExtracting(true);
+ const result = await extractPipelineBibles(series.id, { issueId: issue.id }).catch((err) => {
+ toast.error(err.message || 'Extraction failed');
+ return null;
+ });
+ setExtracting(false);
+ if (!result) return;
+ onSeriesUpdate?.(result.series);
+ const counts = ['characters', 'settings', 'objects'].map(
+ (k) => `${result.series[k]?.length ?? 0} ${k}`,
+ ).join(', ');
+ toast.success(`Bibles updated — ${counts}`);
+ };
+
return (
<TextStagePanel
- {...props}
+ issue={issue}
stageId="prose"
+ onStageUpdate={onStageUpdate}
generateLabel="Draft prose"
outputPlaceholder="An 800–1500 word short-story draft for this issue. Will be lightly structured with `## Scene N — Slugline` H2 markers so the comic and TV script stages have stable anchors."
+ extraActions={(
+ <button
+ type="button"
+ onClick={handleExtract}
+ disabled={extracting || !proseReady}
+ title={proseReady ? 'Extract characters, settings, and objects from the prose into the series bibles' : 'Generate prose first'}
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-card border border-port-border text-white text-sm hover:border-port-accent/50 disabled:opacity-40"
+ >
+ {extracting ? <Loader2 size={14} className="animate-spin" /> : <Library size={14} />}
+ Extract bibles
+ </button>
+ )}
/>
);
}
diff --git a/client/src/components/pipeline/stages/StoryboardsStage.jsx b/client/src/components/pipeline/stages/StoryboardsStage.jsx
index 4cd965ca46..21832b9787 100644
--- a/client/src/components/pipeline/stages/StoryboardsStage.jsx
+++ b/client/src/components/pipeline/stages/StoryboardsStage.jsx
@@ -7,15 +7,34 @@
* is deferred — see PLAN.md "Pipeline — Deferred".
*/
-import { useState } from 'react';
-import { Plus, Trash2, Sparkles, Loader2 } from 'lucide-react';
+import { useEffect, useRef, useState } from 'react';
+import { Plus, Trash2, Sparkles, Loader2, Wand2 } from 'lucide-react';
import toast from '../../ui/Toast';
-import { generatePipelineVisualImage, updatePipelineIssue } from '../../../services/api';
+import {
+ generatePipelineVisualImage,
+ updatePipelineIssue,
+ extractPipelineStoryboardScenes,
+} from '../../../services/api';
export default function StoryboardsStage({ issue, onStageUpdate }) {
const stage = issue.stages?.storyboards || { status: 'empty', scenes: [] };
const [scenes, setScenes] = useState(stage.scenes || []);
const [savingIdx, setSavingIdx] = useState(null);
+ const [extractingFrom, setExtractingFrom] = useState(null);
+ // Holds the active arm-timer id so an unmount or a fresh arm clears the
+ // pending disarm — otherwise the 5s callback fires setExtractingFrom on
+ // an unmounted component (React warning + small leak).
+ const armTimerRef = useRef(null);
+ useEffect(() => () => {
+ if (armTimerRef.current) clearTimeout(armTimerRef.current);
+ }, []);
+
+ const tvScriptReady = !!(issue.stages?.tvScript?.output || '').trim();
+ const proseReady = !!(issue.stages?.prose?.output || '').trim();
+ // Any non-null, non-arm value means an extract POST is in flight — both
+ // buttons must lock out concurrent submits so racing requests can't
+ // overwrite each other's results (last-write-wins).
+ const extractInFlight = !!extractingFrom && !extractingFrom.startsWith('arm:');
const persist = async (nextScenes) => {
setScenes(nextScenes);
@@ -35,6 +54,44 @@ export default function StoryboardsStage({ issue, onStageUpdate }) {
setScenes(next);
};
+ // Replace-existing confirm uses a two-click arm pattern (no window.confirm
+ // per CLAUDE.md, no shared confirm-modal primitive in the pipeline yet).
+ // First click on a button when scenes is non-empty arms it (label flips to
+ // "Click again to replace"). Second click within 5s fires the extract.
+ const onExtractClick = async (from) => {
+ const armKey = `arm:${from}`;
+ const needsConfirm = scenes.length > 0;
+
+ if (needsConfirm && extractingFrom !== armKey) {
+ setExtractingFrom(armKey);
+ toast.warning(`This will replace ${scenes.length} existing scene${scenes.length === 1 ? '' : 's'}. Click again to confirm.`);
+ if (armTimerRef.current) clearTimeout(armTimerRef.current);
+ armTimerRef.current = setTimeout(() => {
+ armTimerRef.current = null;
+ setExtractingFrom((cur) => (cur === armKey ? null : cur));
+ }, 5000);
+ return;
+ }
+ // Second click landed within the arm window — cancel the pending disarm
+ // so the post-await `setExtractingFrom(null)` is the only state flip.
+ if (armTimerRef.current) {
+ clearTimeout(armTimerRef.current);
+ armTimerRef.current = null;
+ }
+
+ setExtractingFrom(from);
+ const result = await extractPipelineStoryboardScenes(issue.id, { from, force: true }).catch((err) => {
+ toast.error(err.message || 'Scene extraction failed');
+ return null;
+ });
+ setExtractingFrom(null);
+ if (!result) return;
+ const next = result.stage?.scenes || [];
+ setScenes(next);
+ onStageUpdate?.('storyboards', result.stage, result.issue);
+ toast.success(`Extracted ${result.sceneCount} scene${result.sceneCount === 1 ? '' : 's'}`);
+ };
+
const handleGenerate = async (i) => {
const scene = scenes[i];
if (!scene.description?.trim()) {
@@ -44,6 +101,7 @@ export default function StoryboardsStage({ issue, onStageUpdate }) {
setSavingIdx(i);
const result = await generatePipelineVisualImage(issue.id, 'storyboards', {
description: scene.description,
+ slugline: scene.slugline || '',
}).catch((err) => {
toast.error(err.message || 'Failed to enqueue image');
return null;
@@ -61,16 +119,42 @@ export default function StoryboardsStage({ issue, onStageUpdate }) {
<div>
<h2 className="text-lg font-semibold text-white">Storyboards</h2>
<p className="text-xs text-gray-500 mt-1">
- One image per scene, fed by the TV script. Use sluglines to keep parity with the teleplay. Scene-video rendering through Creative Director is deferred.
+ One image per scene, fed by the TV script. Use sluglines to keep parity with the teleplay. Stitch the final episode in the Episode Video stage once the storyboards are ready.
</p>
</div>
- <button
- type="button"
- onClick={addScene}
- className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-card border border-port-border text-white text-sm hover:border-port-accent/50"
- >
- <Plus size={14} /> Add scene
- </button>
+ <div className="flex items-center gap-2 flex-wrap">
+ <button
+ type="button"
+ onClick={() => onExtractClick('tvScript')}
+ disabled={!tvScriptReady || extractInFlight}
+ title={tvScriptReady ? 'Parse the teleplay sluglines into structured scenes' : 'Generate the TV script first'}
+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-card border border-port-border text-white text-sm hover:border-port-accent/50 disabled:opacity-40 disabled:cursor-not-allowed"
+ >
+ {extractingFrom === 'tvScript'
+ ? <Loader2 size={14} className="animate-spin" />
+ : <Wand2 size={14} />}
+ {extractingFrom === 'arm:tvScript' ? 'Click again to replace' : 'From TV script'}
+ </button>
+ <button
+ type="button"
+ onClick={() => onExtractClick('prose')}
+ disabled={!proseReady || extractInFlight}
+ title={proseReady ? 'Break the prose into paragraph-grain scenes' : 'Generate the prose first'}
+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-card border border-port-border text-white text-sm hover:border-port-accent/50 disabled:opacity-40 disabled:cursor-not-allowed"
+ >
+ {extractingFrom === 'prose'
+ ? <Loader2 size={14} className="animate-spin" />
+ : <Wand2 size={14} />}
+ {extractingFrom === 'arm:prose' ? 'Click again to replace' : 'From prose'}
+ </button>
+ <button
+ type="button"
+ onClick={addScene}
+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-card border border-port-border text-white text-sm hover:border-port-accent/50"
+ >
+ <Plus size={14} /> Add scene
+ </button>
+ </div>
</div>
{scenes.length === 0 ? (
diff --git a/client/src/components/pipeline/stages/TextStagePanel.jsx b/client/src/components/pipeline/stages/TextStagePanel.jsx
index 3fec4dac33..093760dad8 100644
--- a/client/src/components/pipeline/stages/TextStagePanel.jsx
+++ b/client/src/components/pipeline/stages/TextStagePanel.jsx
@@ -35,6 +35,7 @@ export default function TextStagePanel({
seedPlaceholder,
outputPlaceholder,
generateLabel = 'Generate',
+ extraActions = null,
}) {
const stage = issue.stages?.[stageId] || { status: 'empty', input: '', output: '' };
const [draftOutput, setDraftOutput] = useState(stage.output || '');
@@ -98,6 +99,7 @@ export default function TextStagePanel({
) : null}
</div>
<div className="flex items-center gap-2">
+ {extraActions}
<button
type="button"
onClick={handleSave}
diff --git a/client/src/components/ui/Toast.jsx b/client/src/components/ui/Toast.jsx
index 261cd73c3b..895d494d80 100644
--- a/client/src/components/ui/Toast.jsx
+++ b/client/src/components/ui/Toast.jsx
@@ -69,14 +69,15 @@ export const toast = Object.assign(
success: (content, opts = {}) => add(content, opts, 'success'),
error: (content, opts = {}) => add(content, opts, 'error'),
loading: (content, opts = {}) => add(content, opts, 'loading'),
+ warning: (content, opts = {}) => add(content, opts, 'warning'),
dismiss,
}
);
export default toast;
-const TYPE_ICON = { success: '✓', error: '✕', loading: '⟳' };
-const TYPE_CLASS = { success: 'text-green-400', error: 'text-red-400', loading: 'text-gray-400 animate-spin' };
+const TYPE_ICON = { success: '✓', error: '✕', loading: '⟳', warning: '⚠' };
+const TYPE_CLASS = { success: 'text-green-400', error: 'text-red-400', loading: 'text-gray-400 animate-spin', warning: 'text-yellow-400' };
export function Toaster({ position = 'bottom-right', toastOptions = {} }) {
const [items, setItems] = useState([]);
diff --git a/client/src/components/writers-room/SceneCard.jsx b/client/src/components/writers-room/SceneCard.jsx
index c0ca5bf289..bc3d8bc618 100644
--- a/client/src/components/writers-room/SceneCard.jsx
+++ b/client/src/components/writers-room/SceneCard.jsx
@@ -15,13 +15,13 @@ import {
} from '../../services/apiWritersRoom';
import socket from '../../services/socket';
import useClickOutside from '../../hooks/useClickOutside';
+import { WR_IMAGE_DEFAULTS } from '../../lib/wrImageDefaults';
import {
- WR_IMAGE_DEFAULTS,
buildScenePrompt,
matchSceneCharacters,
matchSceneSetting,
normCharKey,
-} from './sceneCardHelpers';
+} from '../../lib/scenePrompt';
const SceneCard = forwardRef(function SceneCard({
scene,
diff --git a/client/src/components/writers-room/StoryboardPanel.jsx b/client/src/components/writers-room/StoryboardPanel.jsx
index 5a4f110c52..67720ff317 100644
--- a/client/src/components/writers-room/StoryboardPanel.jsx
+++ b/client/src/components/writers-room/StoryboardPanel.jsx
@@ -24,14 +24,8 @@ import StagePromptModelPicker from './StagePromptModelPicker';
import CharactersBible from './CharactersBible';
import SettingsBible from './SettingsBible';
import ObjectsBible from './ObjectsBible';
-import {
- WR_IMAGE_DEFAULTS,
- buildCharByKey,
- buildSettingByKey,
- readWrImageSettings,
- STYLE_ID,
- EMPTY_IMAGE_STYLE,
-} from './sceneCardHelpers';
+import { WR_IMAGE_DEFAULTS, readWrImageSettings, STYLE_ID, EMPTY_IMAGE_STYLE } from '../../lib/wrImageDefaults';
+import { buildCharByKey, buildSettingByKey } from '../../lib/scenePrompt';
const SCRIPT_STAGE = 'writers-room-script';
diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsx
index d19de6cc5f..0af64dc190 100644
--- a/client/src/components/writers-room/WorkEditor.jsx
+++ b/client/src/components/writers-room/WorkEditor.jsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { useSearchParams } from 'react-router-dom';
+import { useSearchParams, useNavigate } from 'react-router-dom';
import {
Save,
GitCommit,
@@ -19,6 +19,8 @@ import {
Loader2,
BookOpen,
Pencil,
+ Film,
+ ExternalLink,
} from 'lucide-react';
import toast from '../ui/Toast';
import Drawer from '../Drawer';
@@ -33,6 +35,7 @@ import {
listWritersRoomCharacters,
listWritersRoomSettings,
listWritersRoomObjects,
+ promoteWritersRoomWorkToPipeline,
} from '../../services/apiWritersRoom';
import { STATUS_LABELS } from './labels';
import { countWords } from '../../utils/formatters';
@@ -86,8 +89,10 @@ function readSidebarTab() {
}
export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOpen }) {
+ const navigate = useNavigate();
const [body, setBody] = useState(work.activeDraftBody || '');
const [title, setTitle] = useState(work.title);
+ const [promoting, setPromoting] = useState(false);
// Optimistic mirror of work.status so the dropdown changes show immediately
// before the PATCH round-trip resolves. Re-synced from the prop when it changes.
const [status, setStatus] = useState(work.status);
@@ -378,6 +383,31 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
toast.success(`Created ${updated.drafts[updated.drafts.length - 1].label}`);
};
+ const handlePromoteToPipeline = async () => {
+ if (dirty) {
+ toast('Save before promoting', { icon: '⚠️' });
+ return;
+ }
+ setPromoting(true);
+ const result = await promoteWritersRoomWorkToPipeline(work.id).catch((err) => {
+ if (mountedRef.current) toast.error(err.message || 'Promote failed');
+ return null;
+ });
+ if (mountedRef.current) setPromoting(false);
+ if (!result) return;
+ toast.success(result.reused ? 'Opening existing pipeline issue' : 'Pipeline series + issue created');
+ // Optimistic update so the menu flips to "Open in pipeline" instantly.
+ // The server route returns the full manifest (including the link fields)
+ // on the next GET, so a return-visit to this work will also see the link.
+ onChange?.({ ...work, pipelineSeriesId: result.series.id, pipelineIssueId: result.issue.id });
+ navigate(`/pipeline/issues/${encodeURIComponent(result.issue.id)}/prose`);
+ };
+
+ const handleOpenInPipeline = () => {
+ if (!work.pipelineIssueId) return;
+ navigate(`/pipeline/issues/${encodeURIComponent(work.pipelineIssueId)}/prose`);
+ };
+
const commitTitle = async () => {
if (title === work.title) return;
const updated = await updateWritersRoomWork(work.id, { title }).catch((err) => {
@@ -695,6 +725,11 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
<MenuSection label="Open">
<MenuItem icon={Clock} label="Versions" onClick={closeOverflowAnd(() => setDrawer(DRAWER.VERSIONS))} />
<MenuItem icon={History} label="Analysis history" onClick={closeOverflowAnd(() => setDrawer(DRAWER.HISTORY))} />
+ {work.pipelineSeriesId ? (
+ <MenuItem icon={ExternalLink} label="Open in pipeline" onClick={closeOverflowAnd(handleOpenInPipeline)} />
+ ) : (
+ <MenuItem icon={Film} label={promoting ? 'Promoting…' : 'Promote to pipeline'} running={promoting} onClick={closeOverflowAnd(handlePromoteToPipeline)} />
+ )}
</MenuSection>
<MenuSection label="View">
<MenuItem
diff --git a/client/src/lib/scenePrompt.js b/client/src/lib/scenePrompt.js
new file mode 100644
index 0000000000..4da7309b0c
--- /dev/null
+++ b/client/src/lib/scenePrompt.js
@@ -0,0 +1,100 @@
+// Mirror of server/lib/scenePrompt.js — keep byte-for-byte in sync.
+// The shape-invariant tests in server/lib/scenePrompt.test.js are the contract.
+
+const PROMPT_MAX = 1900;
+
+export const normalizeSlugline = (s) => String(s || '')
+ .toUpperCase()
+ .replace(/[—–-]/g, ' ')
+ .replace(/[.,:;]/g, '')
+ .replace(/\s+/g, ' ')
+ .trim();
+
+export const normCharKey = (s) => String(s || '').trim().toLowerCase().replace(/^the\s+/, '');
+
+export function buildCharByKey(allCharacters) {
+ const map = new Map();
+ for (const profile of allCharacters || []) {
+ map.set(normCharKey(profile.name), profile);
+ for (const alias of profile.aliases || []) map.set(normCharKey(alias), profile);
+ }
+ return map;
+}
+
+export function matchSceneCharacters(sceneCharacterNames = [], charByKey) {
+ if (!Array.isArray(sceneCharacterNames) || !sceneCharacterNames.length) return [];
+ const matched = [];
+ const seen = new Set();
+ for (const name of sceneCharacterNames) {
+ const profile = charByKey?.get(normCharKey(name));
+ if (profile && !seen.has(profile.id || profile.name)) {
+ matched.push(profile);
+ seen.add(profile.id || profile.name);
+ }
+ }
+ return matched;
+}
+
+export function buildSettingByKey(allSettings) {
+ const map = new Map();
+ for (const setting of allSettings || []) {
+ const key = normalizeSlugline(setting.slugline || setting.name);
+ if (!key) continue;
+ map.set(key, setting);
+ }
+ return map;
+}
+
+export function matchSceneSetting(sceneSlugline, settingByKey) {
+ if (!sceneSlugline) return null;
+ return settingByKey?.get(normalizeSlugline(sceneSlugline)) || null;
+}
+
+export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyle = '', matchedSetting = null) {
+ const stylePart = worldStyle && worldStyle.trim() ? `${worldStyle.trim()}. ` : '';
+ const titlePart = workTitle ? `${workTitle}. ` : '';
+ const visual = scene?.visualPrompt || scene?.description || '';
+
+ const settingFrags = matchedSetting ? [
+ matchedSetting.description?.trim() || '',
+ matchedSetting.palette ? `Palette: ${matchedSetting.palette.trim()}.` : '',
+ matchedSetting.recurringDetails?.trim() || '',
+ ].filter(Boolean) : [];
+
+ // Accept either `physicalDescription` (writers-room shape) or
+ // `description` (pipeline shape) — the composer doesn't care which
+ // field carries the visual descriptor.
+ const featuringFragments = (matchedCharacters || [])
+ .map((c) => ({ name: c.name, desc: (c.physicalDescription || c.description || '').trim() }))
+ .filter((c) => c.desc)
+ .map((c) => `${c.name}: ${c.desc}`);
+
+ const PREFIX = 'Featuring — ';
+ const reserveCore = stylePart.length + titlePart.length + visual.length + 4;
+ let budget = PROMPT_MAX - reserveCore;
+
+ const settingFit = [];
+ for (const frag of settingFrags) {
+ const cost = (settingFit.length === 0 ? 0 : 1) + frag.length;
+ if (cost > budget) break;
+ settingFit.push(frag);
+ budget -= cost;
+ }
+
+ budget -= PREFIX.length;
+ const charFit = [];
+ for (const frag of featuringFragments) {
+ const cost = (charFit.length === 0 ? 0 : 1) + frag.length;
+ if (cost > budget) break;
+ charFit.push(frag);
+ budget -= cost;
+ }
+
+ const segs = [];
+ if (stylePart) segs.push(stylePart.trim());
+ if (titlePart) segs.push(titlePart.trim());
+ if (settingFit.length > 0) segs.push(settingFit.join(' '));
+ if (charFit.length > 0) segs.push(`${PREFIX}${charFit.join(' ')}`);
+ if (visual) segs.push(visual);
+ return segs.filter(Boolean).join(' ').slice(0, PROMPT_MAX);
+}
diff --git a/client/src/lib/wrImageDefaults.js b/client/src/lib/wrImageDefaults.js
new file mode 100644
index 0000000000..98a12d68c6
--- /dev/null
+++ b/client/src/lib/wrImageDefaults.js
@@ -0,0 +1,35 @@
+// Writers Room per-scene image-gen defaults + style discriminators.
+//
+// Mirror of server/lib/writersRoomStylePresets.js — kept in sync manually
+// since client and server are separate bundles. Curated preset ids come from
+// the /api/image-gen/style-presets endpoint at runtime; only the two
+// special discriminators live here.
+
+export const STYLE_ID = Object.freeze({ NONE: 'none', CUSTOM: 'custom' });
+export const EMPTY_IMAGE_STYLE = Object.freeze({ presetId: STYLE_ID.NONE, prompt: '', negativePrompt: '' });
+
+// Defaults for the per-scene image gen pipe. Klein-4B is the fastest FLUX.2
+// variant on Apple Silicon, and 768×512 is a 3:2 aspect that suits scene work.
+// steps + seed are stored as strings (or empty) so the form inputs can bind
+// directly. Empty string = "use model default" for steps, "random per render"
+// for seed. Parsed to numbers at the generateImage boundary in SceneCard.
+export const WR_IMAGE_DEFAULTS = Object.freeze({
+ modelId: 'flux2-klein-4b',
+ mode: 'local',
+ width: 768,
+ height: 512,
+ steps: '',
+ seed: '',
+});
+
+export function readWrImageSettings(settings) {
+ const stored = settings?.writersRoom?.imageGen || {};
+ return {
+ modelId: stored.modelId || WR_IMAGE_DEFAULTS.modelId,
+ mode: stored.mode || WR_IMAGE_DEFAULTS.mode,
+ width: Number.isFinite(stored.width) ? stored.width : WR_IMAGE_DEFAULTS.width,
+ height: Number.isFinite(stored.height) ? stored.height : WR_IMAGE_DEFAULTS.height,
+ steps: stored.steps != null && stored.steps !== '' ? String(stored.steps) : '',
+ seed: stored.seed != null && stored.seed !== '' ? String(stored.seed) : '',
+ };
+}
diff --git a/client/src/pages/PipelineIssue.jsx b/client/src/pages/PipelineIssue.jsx
index e40dc9429c..4ee895763e 100644
--- a/client/src/pages/PipelineIssue.jsx
+++ b/client/src/pages/PipelineIssue.jsx
@@ -99,16 +99,18 @@ export default function PipelineIssue() {
}
}, [latest, issueId]);
- const handleAutoRun = async () => {
+ const handleAutoRun = async (opts = {}) => {
setAutoRunStarting(true);
- const res = await startPipelineAutoRunText(issueId, {}).catch((err) => {
+ const res = await startPipelineAutoRunText(issueId, opts).catch((err) => {
toast.error(err.message || 'Failed to start auto-run');
return null;
});
setAutoRunStarting(false);
if (!res) return;
setAutoRunActive(true);
- toast.success(res.alreadyRunning ? 'Auto-run already in progress' : 'Auto-run started');
+ toast.success(res.alreadyRunning
+ ? 'Auto-run already in progress'
+ : (opts.includeVideo ? 'Auto-run started (with video)' : 'Auto-run started'));
};
const handleCancelAutoRun = async () => {
@@ -174,13 +176,23 @@ export default function PipelineIssue() {
)}
<button
type="button"
- onClick={handleAutoRun}
+ onClick={() => handleAutoRun({})}
disabled={autoRunStarting || autoRunActive}
className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"
title="Run idea → prose → (comic script + TV script) end to end"
>
{autoRunStarting || autoRunActive ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
- Auto-run text stages
+ Auto-run text
+ </button>
+ <button
+ type="button"
+ onClick={() => handleAutoRun({ includeVideo: true })}
+ disabled={autoRunStarting || autoRunActive}
+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-card border border-port-accent/40 text-white text-sm font-medium disabled:opacity-50 hover:bg-port-accent/10"
+ title="Run text stages and then kick off episode video via Creative Director (burns GPU)"
+ >
+ {autoRunStarting || autoRunActive ? <Loader2 size={14} className="animate-spin" /> : <Clapperboard size={14} />}
+ Run everything (incl. video)
</button>
</div>
</div>
@@ -188,7 +200,9 @@ export default function PipelineIssue() {
{autoRunActive && latest ? (
<div className="text-xs text-gray-400">
{latest.type === 'stage:start' && <>Generating <span className="text-white">{PIPELINE_STAGE_LABELS[latest.stage]}</span>…</>}
- {latest.type === 'stage:complete' && <>{PIPELINE_STAGE_LABELS[latest.stage]} ready ({latest.length} chars)</>}
+ {latest.type === 'stage:complete' && latest.stage === 'episodeVideo' && <>{PIPELINE_STAGE_LABELS[latest.stage]} kicked off — {latest.scenes} scene{latest.scenes === 1 ? '' : 's'} queued in Creative Director</>}
+ {latest.type === 'stage:complete' && latest.stage !== 'episodeVideo' && <>{PIPELINE_STAGE_LABELS[latest.stage]} ready ({latest.length} chars)</>}
+ {latest.type === 'stage:error' && <>{PIPELINE_STAGE_LABELS[latest.stage]} error — {latest.error}</>}
{latest.type === 'skip' && <>{PIPELINE_STAGE_LABELS[latest.stage]} skipped — {latest.reason}</>}
{latest.type === 'start' && <>Starting auto-run…</>}
</div>
@@ -222,7 +236,7 @@ export default function PipelineIssue() {
{/* Active stage panel */}
<div className="flex-1 overflow-auto p-4 md:p-6">
{StageComponent ? (
- <StageComponent issue={issue} series={series} onStageUpdate={handleStageUpdate} />
+ <StageComponent issue={issue} series={series} onStageUpdate={handleStageUpdate} onSeriesUpdate={setSeries} />
) : (
<div className="text-gray-500 text-sm">Unknown stage.</div>
)}
diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsx
index 4c3d3d6e45..eba115aaa3 100644
--- a/client/src/pages/PipelineSeries.jsx
+++ b/client/src/pages/PipelineSeries.jsx
@@ -8,7 +8,7 @@
import { useEffect, useState } from 'react';
import { Link, useParams, useNavigate } from 'react-router-dom';
import {
- ArrowLeft, Plus, Save, Trash2, Loader2, ChevronRight, Workflow as WorkflowIcon, Globe,
+ ArrowLeft, Plus, Save, Trash2, Loader2, ChevronRight, Workflow as WorkflowIcon, Globe, NotebookPen,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import {
@@ -135,6 +135,15 @@ export default function PipelineSeries() {
</Link>
<WorkflowIcon className="w-5 h-5 text-port-accent ml-2" />
<h1 className="text-xl font-bold text-white truncate">{series.name || 'Untitled series'}</h1>
+ {series.writersRoomWorkId ? (
+ <Link
+ to={`/writers-room/works/${encodeURIComponent(series.writersRoomWorkId)}`}
+ className="ml-2 inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-white border border-port-border bg-port-card"
+ title="Open the Writers Room draft this series was promoted from"
+ >
+ <NotebookPen size={12} /> Writers Room
+ </Link>
+ ) : null}
<button
type="button"
onClick={handleSave}
diff --git a/client/src/services/apiCreativeDirector.js b/client/src/services/apiCreativeDirector.js
index 45cf48b6c7..1179e5e1b0 100644
--- a/client/src/services/apiCreativeDirector.js
+++ b/client/src/services/apiCreativeDirector.js
@@ -1,7 +1,12 @@
import { request } from './apiCore.js';
export const listCreativeDirectorProjects = () => request('/creative-director');
-export const getCreativeDirectorProject = (id) => request(`/creative-director/${encodeURIComponent(id)}`);
+// Pass `{ slim: true }` to receive only the fields a polling consumer needs
+// (status / per-scene status / finalVideoId / failureReason / updatedAt) —
+// drops the unbounded `runs[]` history and the full treatment text. Useful
+// for 4s-poll surfaces like the Pipeline EpisodeVideoStage.
+export const getCreativeDirectorProject = (id, { slim = false } = {}) =>
+ request(`/creative-director/${encodeURIComponent(id)}${slim ? '?slim=1' : ''}`);
export const createCreativeDirectorProject = (data) => request('/creative-director', {
method: 'POST',
body: JSON.stringify(data),
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index ec8d1f8c1e..00bb7e5c9a 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -32,6 +32,19 @@ export const deletePipelineSeries = (id) => request(`/pipeline/series/${encodeUR
method: 'DELETE',
});
+// Extract bibles (characters / settings / objects) from an issue's prose
+// stage and merge them into the series. `kinds` defaults server-side to all
+// three. Pass `parallel: true` to fan out the kinds concurrently — ~3×
+// wall-clock speedup on HTTP-API providers (OpenAI / Anthropic / LM Studio
+// HTTP). Safe to leave off for CLI-only providers (codex / claude-code /
+// gemini-cli) which serialize at the provider session anyway.
+// Returns { series, results } where results is keyed by field name.
+export const extractPipelineBibles = (seriesId, { issueId, corpus, kinds, providerOverride, parallel } = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/extract-bible`, {
+ method: 'POST',
+ body: JSON.stringify({ issueId, corpus, kinds, providerOverride, parallel }),
+ });
+
// ---- Issues ----
export const listPipelineIssues = (seriesId) =>
request(`/pipeline/series/${encodeURIComponent(seriesId)}/issues`);
@@ -66,6 +79,15 @@ export const generatePipelineVisualImage = (issueId, stageId, opts) =>
body: JSON.stringify(opts),
});
+// Auto-fill the storyboards stage's scenes[] from the issue's prose or
+// tvScript text stage. `from` defaults server-side to 'tvScript'. Pass
+// `force: true` to replace existing hand-curated scenes.
+export const extractPipelineStoryboardScenes = (issueId, { from, providerOverride, force } = {}) =>
+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/storyboards/extract-scenes`, {
+ method: 'POST',
+ body: JSON.stringify({ from, providerOverride, force }),
+ });
+
// ---- Auto-run text chain ----
export const startPipelineAutoRunText = (issueId, opts = {}) =>
request(`/pipeline/issues/${encodeURIComponent(issueId)}/auto-run-text`, {
diff --git a/client/src/services/apiWritersRoom.js b/client/src/services/apiWritersRoom.js
index 542a3a7d95..728d92d277 100644
--- a/client/src/services/apiWritersRoom.js
+++ b/client/src/services/apiWritersRoom.js
@@ -27,6 +27,16 @@ export const deleteWritersRoomWork = (id) => request(`/writers-room/works/${enc(
method: 'DELETE',
});
+// Pipeline bridge: create a pipeline series + first issue from this work
+// (transfers prose, bibles, and the latest script-analysis scenes). Idempotent
+// — if the work is already linked, returns the existing series + issue
+// (reused=true) unless { force: true } is passed.
+export const promoteWritersRoomWorkToPipeline = (id, { force } = {}) =>
+ request(`/writers-room/works/${enc(id)}/promote-to-pipeline`, {
+ method: 'POST',
+ body: JSON.stringify({ force }),
+ });
+
// Drafts
export const saveWritersRoomDraft = (id, body) => request(`/writers-room/works/${enc(id)}/draft`, {
method: 'PUT',
diff --git a/data.sample/prompts/_partials/bible-deference.md b/data.sample/prompts/_partials/bible-deference.md
new file mode 100644
index 0000000000..f43013f350
--- /dev/null
+++ b/data.sample/prompts/_partials/bible-deference.md
@@ -0,0 +1,18 @@
+## Character bible (canonical descriptions — defer to these)
+
+Each scene's image-gen prompt has to describe characters physically (image models don't know your story). When the source names a character that has an entry below, write `visualPrompt` to match the bible's `physicalDescription` rather than re-improvising. If the bible is empty, fall back to the source. Do **not** invent contradictory details.
+
+```json
+{{existingCharactersJson}}
+```
+
+## Setting bible (canonical locations — defer to these)
+
+When a scene's slugline matches a `slugline` below (case-insensitive, ignoring punctuation), the storyboard pipeline auto-injects the entry's `description` / `palette` / `recurringDetails` into the final image prompt. So:
+
+- **Reuse the same slugline string** from the bible verbatim when the scene takes place in that location — even minor wording drift breaks the match.
+- Don't restate the setting's baseline description inside `visualPrompt`; the pipeline will prepend it. Use `visualPrompt` for what's *new this beat* (blocking, lighting *changes* from the room's baseline, character action, time-of-day shifts).
+
+```json
+{{existingSettingsJson}}
+```
diff --git a/data.sample/prompts/_partials/scene-output-contract.md b/data.sample/prompts/_partials/scene-output-contract.md
new file mode 100644
index 0000000000..a55358e13a
--- /dev/null
+++ b/data.sample/prompts/_partials/scene-output-contract.md
@@ -0,0 +1,25 @@
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
+
+```json
+{
+ "title": "string (the work or episode title)",
+ "logline": "string (one-sentence pitch)",
+ "scenes": [
+ {
+ "id": "scene-01",
+ "heading": "Scene 1 — Title",
+ "slugline": "INT. KITCHEN — NIGHT",
+ "summary": "string",
+ "characters": ["NAME", ...],
+ "action": "string",
+ "dialogue": [
+ { "character": "NAME", "line": "string" }
+ ],
+ "visualPrompt": "string",
+ "sourceSegmentIds": []
+ }
+ ]
+}
+```
diff --git a/data.sample/prompts/stage-config.json b/data.sample/prompts/stage-config.json
index 0bbf9daee4..c263825f96 100644
--- a/data.sample/prompts/stage-config.json
+++ b/data.sample/prompts/stage-config.json
@@ -213,6 +213,13 @@
"model": "default",
"returnsJson": false,
"variables": []
+ },
+ "pipeline-extract-scenes": {
+ "name": "Pipeline — Extract Scenes from TV Teleplay",
+ "description": "Parse an already-formatted TV teleplay into a structured scenes[] list (one entry per slugline) the storyboards stage can render. Defers to character / setting bibles for canonical names and slugline reuse.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
}
}
}
diff --git a/data.sample/prompts/stages/pipeline-extract-scenes.md b/data.sample/prompts/stages/pipeline-extract-scenes.md
new file mode 100644
index 0000000000..f0d7777aad
--- /dev/null
+++ b/data.sample/prompts/stages/pipeline-extract-scenes.md
@@ -0,0 +1,40 @@
+# Pipeline — Extract Scenes from TV Teleplay
+
+You are a script supervisor parsing an already-broken-out TV teleplay into a structured scene list the storyboard pipeline can render. The teleplay has sluglines and dialogue **already in place** — you are not re-imagining the structure, you are translating screenplay format into JSON. Each scene becomes one storyboard image.
+
+## Series
+
+- **Title:** {{series.name}}
+- **Tone / style:** {{series.styleNotes}}
+
+## Episode
+
+- **Number:** {{issue.number}}
+- **Title:** {{issue.title}}
+
+{{> bible-deference }}
+
+## Source — TV teleplay (markdown)
+
+```
+{{teleplay}}
+```
+
+## Granularity — read carefully
+
+The teleplay's sluglines (`**INT./EXT. LOCATION — TIME**`) define scene boundaries. **Produce one entry per slugline.** Do NOT split a screenplay scene into multiple panels even if it's long; do NOT merge two screenplay scenes into one. The writer chose those breaks intentionally for episode pacing.
+
+If the teleplay uses act headers (`## TEASER`, `## ACT ONE`, `## ACT TWO`, ...) treat them as structural markers — do not produce a scene for the act header itself; carry the act name on the next scene's `heading` so the storyboard order preserves it.
+
+## For each scene, write
+
+- **`heading`** — short noun phrase summarizing the visual moment (e.g. `Scene 12 — Squid Arm Rises`). If the teleplay opens the scene with an evocative action line, mine that; otherwise distill the slugline + first action paragraph.
+- **`slugline`** — verbatim from the teleplay (`INT. KITCHEN — NIGHT`), uppercase, no markdown bold.
+- **`summary`** — 1–2 sentences naming what's *visible* in this scene. Lift from the action lines.
+- **`characters`** — list of CAPS character names that have dialogue in this scene + named characters in the action lines.
+- **`action`** — ≤ 3 sentences in present tense. Trim the action paragraphs down to the visual essentials.
+- **`dialogue`** — `[{ "character": "NAME", "line": "..." }]` for every spoken line in the scene, in order. Empty array if the scene is silent.
+- **`visualPrompt`** — a self-contained image-gen prompt (~30–60 words) describing the scene as a still frame: subjects, location, lighting, mood, camera framing, time of day. Bake in genre/era cues from the series style notes. Do NOT reference characters by name — describe them physically so an image model with no story context can render them.
+- **`sourceSegmentIds`** — keep empty.
+
+{{> scene-output-contract }}
diff --git a/data.sample/prompts/stages/writers-room-script.md b/data.sample/prompts/stages/writers-room-script.md
index 74420d8d79..7f134d9a63 100644
--- a/data.sample/prompts/stages/writers-room-script.md
+++ b/data.sample/prompts/stages/writers-room-script.md
@@ -8,24 +8,7 @@ You are a script supervisor breaking a piece of prose into the smallest visualiz
- Kind: {{work.kind}}
- Word count: {{work.wordCount}}
-## Character bible (canonical descriptions — defer to these)
-
-Each scene's image-gen prompt has to describe characters physically (image models don't know your story). When the prose names a character that has an entry below, write `visualPrompt` to match the bible's `physicalDescription` rather than re-improvising. If the bible is empty, fall back to the prose. Do **not** invent contradictory details.
-
-```json
-{{existingCharactersJson}}
-```
-
-## Setting bible (canonical locations — defer to these)
-
-When a scene's slugline matches a `slugline` below (case-insensitive, ignoring punctuation), the storyboard pipeline auto-injects the entry's `description` / `palette` / `recurringDetails` into the final image prompt. So:
-
-- **Reuse the same slugline string** from the bible verbatim when the scene takes place in that location — even minor wording drift breaks the match.
-- Don't restate the setting's baseline description inside `visualPrompt`; the pipeline will prepend it. Use `visualPrompt` for what's *new this beat* (blocking, lighting *changes* from the room's baseline, character action, time-of-day shifts).
-
-```json
-{{existingSettingsJson}}
-```
+{{> bible-deference }}
## Source prose
@@ -59,28 +42,4 @@ Do NOT merge to "tighten the arc" or "avoid padding." More cards is better — t
- **`visualPrompt`** — a self-contained image-gen prompt (~30–60 words) describing the scene as a still frame: subjects, location, lighting, mood, camera framing, time of day. Bake in genre/era cues from the prose. Do NOT reference characters by name — describe them physically so an image model with no story context can render them.
- **`sourceSegmentIds`** — keep empty unless the prose uses explicit `# Chapter` / `## Scene` markdown headings, in which case attribute each generated scene to the heading id like `seg-001`.
-## Output contract
-
-Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
-
-```json
-{
- "title": "string (the work title or your suggested screenplay title)",
- "logline": "string (one-sentence pitch)",
- "scenes": [
- {
- "id": "scene-01",
- "heading": "Scene 1 — Title",
- "slugline": "INT. KITCHEN — NIGHT",
- "summary": "string",
- "characters": ["NAME", ...],
- "action": "string",
- "dialogue": [
- { "character": "NAME", "line": "string" }
- ],
- "visualPrompt": "string",
- "sourceSegmentIds": ["seg-001"]
- }
- ]
-}
-```
+{{> scene-output-contract }}
diff --git a/server/index.js b/server/index.js
index 670aae7d4c..4714b09620 100644
--- a/server/index.js
+++ b/server/index.js
@@ -120,6 +120,7 @@ import { restoreLoops } from './services/loops.js';
import { startBrainScheduler } from './services/brainScheduler.js';
import { recoverStuckClassifications } from './services/brain.js';
import { recoverStuckAnalyses } from './services/writersRoom/evaluator.js';
+import { recoverStuckAutoRuns } from './services/pipeline/autoRunner.js';
import { initBridge as initBrainMemoryBridge } from './services/brainMemoryBridge.js';
import { initDrillCache } from './services/meatspacePostDrillCache.js';
import { createAIToolkit } from 'portos-ai-toolkit/server';
@@ -358,6 +359,7 @@ try {
// Recover any inbox entries stuck in 'classifying' from a previous crash/restart
recoverStuckClassifications().catch(err => console.error(`❌ Brain recovery failed: ${err.message}`));
recoverStuckAnalyses().catch(err => console.error(`❌ Writers Room recovery failed: ${err.message}`));
+recoverStuckAutoRuns().catch(err => console.error(`❌ Pipeline auto-run recovery failed: ${err.message}`));
// Initialize brain scheduler for daily digests and weekly reviews
startBrainScheduler();
// Initialize brain→memory bridge (mirrors brain data into CoS memory for semantic search)
diff --git a/server/lib/bibleExtractor.js b/server/lib/bibleExtractor.js
new file mode 100644
index 0000000000..de5b602e7f
--- /dev/null
+++ b/server/lib/bibleExtractor.js
@@ -0,0 +1,65 @@
+// Run an LLM bible-extraction stage and sanitize the response through the
+// canonical bible shape. Caller owns persistence.
+
+import { runStagedLLM } from './stageRunner.js';
+import { sanitizeBibleList, BIBLE_KIND, BIBLE_FIELD, pickPromptFields } from './storyBible.js';
+
+const KIND_STAGE = Object.freeze({
+ [BIBLE_KIND.CHARACTER]: 'writers-room-characters',
+ [BIBLE_KIND.SETTING]: 'writers-room-settings',
+ [BIBLE_KIND.OBJECT]: 'writers-room-objects',
+});
+
+const EXISTING_VAR = Object.freeze({
+ [BIBLE_KIND.CHARACTER]: 'existingCharactersJson',
+ [BIBLE_KIND.SETTING]: 'existingSettingsJson',
+ [BIBLE_KIND.OBJECT]: 'existingObjectsJson',
+});
+
+/**
+ * @param {object} args
+ * @param {string} args.kind BIBLE_KIND value
+ * @param {string} args.corpus prose to extract from
+ * @param {Array} [args.existing] current bible (sent to the prompt for deference)
+ * @param {object} [args.context] extra prompt variables (work, series, issue, ...)
+ * @param {string} [args.providerOverride]
+ * @param {string} [args.source] run-tracking source tag
+ */
+export async function extractBible({
+ kind,
+ corpus,
+ existing = [],
+ context = {},
+ providerOverride,
+ source,
+}) {
+ const stage = KIND_STAGE[kind];
+ if (!stage) throw new Error(`extractBible: unknown kind "${kind}"`);
+ if (typeof corpus !== 'string' || !corpus.trim()) {
+ throw new Error('extractBible: corpus is required');
+ }
+
+ const variables = {
+ ...context,
+ draftBody: corpus,
+ returnsJson: true,
+ [EXISTING_VAR[kind]]: JSON.stringify((existing || []).map((e) => pickPromptFields(kind, e))),
+ };
+
+ const result = await runStagedLLM(stage, variables, {
+ providerOverride,
+ returnsJson: true,
+ source: source || `bible-extract-${kind}`,
+ });
+
+ const envelopeKey = BIBLE_FIELD[kind];
+ const rawList = Array.isArray(result.content?.[envelopeKey]) ? result.content[envelopeKey] : [];
+ const extracted = sanitizeBibleList(rawList, kind);
+
+ return {
+ extracted,
+ runId: result.runId,
+ providerId: result.providerId,
+ model: result.model,
+ };
+}
diff --git a/server/lib/bibleExtractor.test.js b/server/lib/bibleExtractor.test.js
new file mode 100644
index 0000000000..921dfbeeea
--- /dev/null
+++ b/server/lib/bibleExtractor.test.js
@@ -0,0 +1,111 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./stageRunner.js', () => ({
+ runStagedLLM: vi.fn(),
+}));
+
+const stageRunner = await import('./stageRunner.js');
+const { extractBible } = await import('./bibleExtractor.js');
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('bibleExtractor — extractBible (characters)', () => {
+ it('passes draftBody + trimmed existingCharactersJson into the stage prompt', async () => {
+ stageRunner.runStagedLLM.mockResolvedValue({
+ content: { characters: [{ name: 'Aria', physicalDescription: 'tall' }] },
+ runId: 'r1', providerId: 'p1', model: 'm1',
+ });
+ const existing = [{ id: 'c1', name: 'Aria', aliases: [], role: 'lead', physicalDescription: 'tall', personality: '', background: '', notes: 'private', createdAt: 't', updatedAt: 't' }];
+ await extractBible({ kind: 'character', corpus: 'long prose...', existing, context: { work: { id: 'w1' } } });
+
+ const [stageName, variables] = stageRunner.runStagedLLM.mock.calls[0];
+ expect(stageName).toBe('writers-room-characters');
+ expect(variables.draftBody).toBe('long prose...');
+ expect(variables.work).toEqual({ id: 'w1' });
+ const trimmed = JSON.parse(variables.existingCharactersJson);
+ // notes/createdAt/updatedAt stripped before the prompt sees them
+ expect(trimmed[0]).not.toHaveProperty('notes');
+ expect(trimmed[0]).not.toHaveProperty('createdAt');
+ expect(trimmed[0].name).toBe('Aria');
+ expect(trimmed[0].role).toBe('lead');
+ });
+
+ it('routes the response through sanitizeBibleList — caps fields and drops malformed rows', async () => {
+ stageRunner.runStagedLLM.mockResolvedValue({
+ content: {
+ characters: [
+ { name: 'Aria', physicalDescription: 'X'.repeat(5000) },
+ { name: '' }, // dropped (blank name)
+ null, // dropped (non-object)
+ { name: 'Marcus', aliases: ['Marc'], personality: 'taciturn' },
+ ],
+ },
+ runId: 'r2', providerId: 'p2', model: 'm2',
+ });
+ const out = await extractBible({ kind: 'character', corpus: 'prose' });
+ expect(out.extracted).toHaveLength(2);
+ expect(out.extracted[0].physicalDescription.length).toBeLessThanOrEqual(2000);
+ expect(out.extracted[1].name).toBe('Marcus');
+ expect(out.extracted[1].aliases).toEqual(['Marc']);
+ });
+
+ it('returns runId/providerId/model from the stage runner', async () => {
+ stageRunner.runStagedLLM.mockResolvedValue({
+ content: { characters: [] }, runId: 'r3', providerId: 'p3', model: 'm3',
+ });
+ const out = await extractBible({ kind: 'character', corpus: 'prose' });
+ expect(out).toMatchObject({ runId: 'r3', providerId: 'p3', model: 'm3' });
+ });
+
+ it('forwards source + providerOverride to runStagedLLM', async () => {
+ stageRunner.runStagedLLM.mockResolvedValue({ content: { characters: [] }, runId: '', providerId: '', model: '' });
+ await extractBible({ kind: 'character', corpus: 'prose', source: 'pipeline-bible-character', providerOverride: 'override-id' });
+ const opts = stageRunner.runStagedLLM.mock.calls[0][2];
+ expect(opts.source).toBe('pipeline-bible-character');
+ expect(opts.providerOverride).toBe('override-id');
+ expect(opts.returnsJson).toBe(true);
+ });
+
+ it('returns empty array when LLM envelope is missing the expected key', async () => {
+ stageRunner.runStagedLLM.mockResolvedValue({ content: { totally: 'wrong shape' }, runId: '', providerId: '', model: '' });
+ const out = await extractBible({ kind: 'character', corpus: 'prose' });
+ expect(out.extracted).toEqual([]);
+ });
+});
+
+describe('bibleExtractor — extractBible (settings + objects)', () => {
+ it('settings: pulls inner array, sanitizes via setting shape', async () => {
+ stageRunner.runStagedLLM.mockResolvedValue({
+ content: { settings: [{ slugline: 'INT. BAR — NIGHT', description: 'cramped chrome bar', palette: 'amber' }] },
+ runId: '', providerId: '', model: '',
+ });
+ const out = await extractBible({ kind: 'setting', corpus: 'prose' });
+ expect(out.extracted).toHaveLength(1);
+ expect(out.extracted[0].slugline).toBe('INT. BAR — NIGHT');
+ expect(out.extracted[0].palette).toBe('amber');
+ });
+
+ it('objects: pulls inner array, sanitizes via object shape', async () => {
+ stageRunner.runStagedLLM.mockResolvedValue({
+ content: { objects: [{ name: 'The Locket', significance: "mother's" }] },
+ runId: '', providerId: '', model: '',
+ });
+ const out = await extractBible({ kind: 'object', corpus: 'prose' });
+ expect(out.extracted[0].name).toBe('The Locket');
+ expect(out.extracted[0].significance).toBe("mother's");
+ });
+});
+
+describe('bibleExtractor — guards', () => {
+ it('rejects unknown kinds', async () => {
+ await expect(extractBible({ kind: 'cheese', corpus: 'prose' })).rejects.toThrow(/unknown kind/);
+ });
+
+ it('rejects empty corpus', async () => {
+ await expect(extractBible({ kind: 'character', corpus: '' })).rejects.toThrow(/corpus is required/);
+ await expect(extractBible({ kind: 'character', corpus: ' ' })).rejects.toThrow(/corpus is required/);
+ await expect(extractBible({ kind: 'character', corpus: null })).rejects.toThrow(/corpus is required/);
+ });
+});
diff --git a/server/lib/composeStyledPrompt.js b/server/lib/composeStyledPrompt.js
new file mode 100644
index 0000000000..ca2456cea8
--- /dev/null
+++ b/server/lib/composeStyledPrompt.js
@@ -0,0 +1,30 @@
+/**
+ * Compose a user prompt + negative with an optional style preset.
+ *
+ * Mirror of `client/src/lib/composeStyledPrompt.js` — kept in sync manually
+ * since client and server are separate bundles (same convention as
+ * `server/lib/scenePrompt.js` ↔ `client/src/lib/scenePrompt.js`).
+ *
+ * Preset prompt prefixes the user prompt — diffusion models weight earlier
+ * tokens heaviest, so the broad aesthetic carries over the user's content.
+ * Preset negative appends to user negative so user-specified avoids stay
+ * first-class.
+ *
+ * Used by World Builder's batch-prompt compiler and any future server-side
+ * caller that needs the same style-prefix convention.
+ */
+export function composeStyledPrompt(userPrompt, userNegative, preset) {
+ const prompt = (userPrompt || '').trim();
+ const negative = (userNegative || '').trim();
+ if (!preset) return { prompt, negativePrompt: negative };
+ const stylePart = (preset.prompt || '').trim();
+ const styleNeg = (preset.negativePrompt || '').trim();
+ // Avoid trailing ". " when only one of the two parts is non-empty so the
+ // composed prompt is clean and deterministic regardless of which input
+ // is missing.
+ const composedPrompt = stylePart && prompt ? `${stylePart}. ${prompt}` : (stylePart || prompt);
+ return {
+ prompt: composedPrompt,
+ negativePrompt: [negative, styleNeg].filter(Boolean).join(', '),
+ };
+}
diff --git a/server/lib/composeStyledPrompt.test.js b/server/lib/composeStyledPrompt.test.js
new file mode 100644
index 0000000000..68c8006a9a
--- /dev/null
+++ b/server/lib/composeStyledPrompt.test.js
@@ -0,0 +1,43 @@
+import { describe, it, expect } from 'vitest';
+import { composeStyledPrompt } from './composeStyledPrompt.js';
+
+describe('composeStyledPrompt', () => {
+ it('returns the bare prompt + negative when no preset is supplied', () => {
+ expect(composeStyledPrompt(' a vault ', ' blur ', null)).toEqual({
+ prompt: 'a vault',
+ negativePrompt: 'blur',
+ });
+ expect(composeStyledPrompt('a vault', '', undefined)).toEqual({
+ prompt: 'a vault', negativePrompt: '',
+ });
+ });
+
+ it('prefixes the preset prompt with `. ` separator (deterministic)', () => {
+ const r = composeStyledPrompt('a vault', '', { prompt: 'cinematic noir' });
+ expect(r.prompt).toBe('cinematic noir. a vault');
+ });
+
+ it('appends preset negative after user negative with `, ` separator', () => {
+ const r = composeStyledPrompt('x', 'blur', { prompt: '', negativePrompt: 'text, watermark' });
+ expect(r.negativePrompt).toBe('blur, text, watermark');
+ });
+
+ it('handles missing user prompt — returns just the style part (no trailing `. `)', () => {
+ expect(composeStyledPrompt('', '', { prompt: 'cinematic noir' }))
+ .toEqual({ prompt: 'cinematic noir', negativePrompt: '' });
+ });
+
+ it('handles missing style part — returns just the user prompt', () => {
+ expect(composeStyledPrompt('a vault', '', { prompt: '' }))
+ .toEqual({ prompt: 'a vault', negativePrompt: '' });
+ });
+
+ it('drops empty negatives so the join never produces a leading or trailing `, `', () => {
+ expect(composeStyledPrompt('x', '', { prompt: 's', negativePrompt: '' })).toEqual({
+ prompt: 's. x', negativePrompt: '',
+ });
+ expect(composeStyledPrompt('x', '', { prompt: 's', negativePrompt: 'bad' })).toEqual({
+ prompt: 's. x', negativePrompt: 'bad',
+ });
+ });
+});
diff --git a/server/lib/promptPartials.js b/server/lib/promptPartials.js
new file mode 100644
index 0000000000..1cae5ac6d7
--- /dev/null
+++ b/server/lib/promptPartials.js
@@ -0,0 +1,121 @@
+/**
+ * Mustache-style partial expansion for PortOS prompt templates.
+ *
+ * `applyTemplate` (server/lib/promptTemplate.js) is intentionally sync + pure
+ * — it doesn't read the filesystem. Partial support lives here as a separate
+ * pre-processing pass so `buildPrompt` can expand `{{> partial-name }}`
+ * references into inline text before handing the result to `applyTemplate`
+ * for variable + section substitution.
+ *
+ * Convention: partials live at `<promptsDir>/_partials/<name>.md`. The leading
+ * underscore makes the directory clearly non-stage (the toolkit's stage
+ * loader scans `<promptsDir>/stages/`, so partials don't pollute the
+ * stage list). Partial names accept `[A-Za-z0-9_-]+`; no slashes — partials
+ * are flat, one directory.
+ *
+ * Recursion: a partial may itself include another partial. The expander runs
+ * to a fixed point with a depth guard (default 8 levels) so a self-referencing
+ * partial fails loudly instead of looping forever.
+ */
+
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+
+const PARTIAL_RE = /\{\{>\s*([A-Za-z0-9_-]+)\s*\}\}/g;
+const MAX_DEPTH = 8;
+
+/**
+ * Find every `{{> name }}` reference in a template and return the unique
+ * partial names. Used to pre-load partials before `applyTemplate` (so the
+ * expansion step doesn't need to be async at every call site).
+ */
+export function listPartialReferences(template) {
+ if (typeof template !== 'string' || !template) return [];
+ const names = new Set();
+ let m;
+ PARTIAL_RE.lastIndex = 0;
+ while ((m = PARTIAL_RE.exec(template)) !== null) names.add(m[1]);
+ return [...names];
+}
+
+/**
+ * Synchronous expander: takes a `(name) => string|null` resolver and rewrites
+ * every `{{> name }}` reference to the partial body. Recurses to MAX_DEPTH —
+ * a deeper chain throws so a partial cycle can't loop forever.
+ */
+export function expandPartialsWithResolver(template, resolve, depth = 0) {
+ if (typeof template !== 'string') return '';
+ if (!template.includes('{{>')) return template;
+ if (depth >= MAX_DEPTH) {
+ throw new Error(`Prompt partial expansion exceeded MAX_DEPTH=${MAX_DEPTH} — likely a cyclic partial`);
+ }
+ let changed = false;
+ const next = template.replace(PARTIAL_RE, (_match, name) => {
+ const body = resolve(name);
+ if (body == null) {
+ // A missing partial should fail loudly, not silently render an empty
+ // block — otherwise a typo in `{{> visual-grammr }}` evaporates the
+ // entire intended instruction without any signal at preview time.
+ throw new Error(`Prompt partial not found: "${name}"`);
+ }
+ changed = true;
+ return body;
+ });
+ return changed ? expandPartialsWithResolver(next, resolve, depth + 1) : next;
+}
+
+/**
+ * Convenience async wrapper: pre-load every partial referenced in the
+ * template (including transitively-referenced ones) from disk, build a
+ * synchronous resolver, then expand.
+ *
+ * @param {string} template — raw stage template text
+ * @param {object} opts
+ * @param {string} opts.partialsDir — absolute path to `<promptsDir>/_partials/`
+ */
+export async function expandPartials(template, { partialsDir } = {}) {
+ if (typeof template !== 'string' || !template.includes('{{>')) return template;
+ if (!partialsDir) throw new Error('expandPartials: partialsDir is required');
+
+ const cache = new Map();
+ async function loadOne(name) {
+ if (cache.has(name)) return cache.get(name);
+ const path = join(partialsDir, `${name}.md`);
+ // Try-read-catch-ENOENT keeps the whole expansion async — a sync
+ // existsSync here would block the event loop on every partial in a
+ // hot prompt-render path. Any non-ENOENT error (EACCES etc) escalates;
+ // a missing partial is a normal "no such name" signal handled by the
+ // sync expander's loud-throw path.
+ try {
+ const body = await readFile(path, 'utf-8');
+ cache.set(name, body);
+ return body;
+ } catch (err) {
+ if (err.code === 'ENOENT') {
+ cache.set(name, null);
+ return null;
+ }
+ throw err;
+ }
+ }
+
+ // Walk the include graph breadth-first so every referenced partial is
+ // cached before the synchronous expander runs. Without this pre-walk we'd
+ // have to make the resolver async, which means making applyTemplate async,
+ // which ripples into every caller.
+ const queue = listPartialReferences(template);
+ const visited = new Set();
+ while (queue.length) {
+ const name = queue.shift();
+ if (visited.has(name)) continue;
+ visited.add(name);
+ const body = await loadOne(name);
+ if (body) {
+ for (const ref of listPartialReferences(body)) {
+ if (!visited.has(ref)) queue.push(ref);
+ }
+ }
+ }
+
+ return expandPartialsWithResolver(template, (name) => cache.get(name) ?? null);
+}
diff --git a/server/lib/promptPartials.test.js b/server/lib/promptPartials.test.js
new file mode 100644
index 0000000000..d44f287fd7
--- /dev/null
+++ b/server/lib/promptPartials.test.js
@@ -0,0 +1,130 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import {
+ listPartialReferences,
+ expandPartialsWithResolver,
+ expandPartials,
+} from './promptPartials.js';
+
+let partialsDir;
+
+beforeEach(() => {
+ partialsDir = mkdtempSync(join(tmpdir(), 'pp-test-'));
+});
+
+afterEach(() => {
+ if (partialsDir && existsSync(partialsDir)) rmSync(partialsDir, { recursive: true, force: true });
+});
+
+function writePartial(name, body) {
+ writeFileSync(join(partialsDir, `${name}.md`), body);
+}
+
+describe('listPartialReferences', () => {
+ it('finds all unique partial names in a template', () => {
+ const tmpl = 'before {{> alpha }} mid {{>beta}} more {{>alpha}} end';
+ expect(listPartialReferences(tmpl)).toEqual(['alpha', 'beta']);
+ });
+
+ it('tolerates whitespace variations inside the include', () => {
+ expect(listPartialReferences('{{>foo}}{{> foo }}{{> foo }}')).toEqual(['foo']);
+ });
+
+ it('returns [] for empty / non-string / no-references input', () => {
+ expect(listPartialReferences('')).toEqual([]);
+ expect(listPartialReferences(null)).toEqual([]);
+ expect(listPartialReferences('no partials here {{var}} {{#section}}body{{/section}}')).toEqual([]);
+ });
+});
+
+describe('expandPartialsWithResolver (sync)', () => {
+ it('rewrites every {{> name }} to the resolver-returned body', () => {
+ const out = expandPartialsWithResolver(
+ 'A {{> x }} B {{> y }} C',
+ (name) => (name === 'x' ? '[X]' : '[Y]'),
+ );
+ expect(out).toBe('A [X] B [Y] C');
+ });
+
+ it('recurses through nested partials', () => {
+ const resolver = (name) => {
+ if (name === 'outer') return 'outer-open {{> inner }} outer-close';
+ if (name === 'inner') return 'INNER';
+ return null;
+ };
+ expect(expandPartialsWithResolver('top {{> outer }} bot', resolver))
+ .toBe('top outer-open INNER outer-close bot');
+ });
+
+ it('throws on a self-referencing partial (cycle guard)', () => {
+ const resolver = (name) => (name === 'loop' ? 'a {{> loop }} z' : null);
+ expect(() => expandPartialsWithResolver('{{> loop }}', resolver))
+ .toThrow(/MAX_DEPTH|cyclic/i);
+ });
+
+ it('throws on a missing partial rather than silently emptying it', () => {
+ expect(() => expandPartialsWithResolver('{{> missing }}', () => null))
+ .toThrow(/Prompt partial not found: "missing"/);
+ });
+
+ it('returns identical input when no partials are referenced (no-op fast path)', () => {
+ const input = 'plain text {{var}} {{#s}}body{{/s}}';
+ expect(expandPartialsWithResolver(input, () => '???')).toBe(input);
+ });
+
+ it('returns "" for non-string input', () => {
+ expect(expandPartialsWithResolver(null, () => '')).toBe('');
+ expect(expandPartialsWithResolver(undefined, () => '')).toBe('');
+ });
+});
+
+describe('expandPartials (async, fs-backed)', () => {
+ it('reads partials from disk and inlines them', async () => {
+ writePartial('alpha', 'ALPHA-BODY');
+ writePartial('beta', 'BETA-BODY');
+ const out = await expandPartials('1 {{> alpha }} 2 {{> beta }} 3', { partialsDir });
+ expect(out).toBe('1 ALPHA-BODY 2 BETA-BODY 3');
+ });
+
+ it('handles transitively-referenced partials (a → b → c)', async () => {
+ writePartial('a', 'a-open {{> b }} a-close');
+ writePartial('b', 'b-open {{> c }} b-close');
+ writePartial('c', 'C-BODY');
+ const out = await expandPartials('{{> a }}', { partialsDir });
+ expect(out).toBe('a-open b-open C-BODY b-close a-close');
+ });
+
+ it('throws on a missing partial file', async () => {
+ await expect(expandPartials('{{> ghost }}', { partialsDir }))
+ .rejects.toThrow(/Prompt partial not found: "ghost"/);
+ });
+
+ it('short-circuits when the template references no partials (no fs reads)', async () => {
+ const input = 'just plain prose {{var}}';
+ const out = await expandPartials(input, { partialsDir });
+ expect(out).toBe(input);
+ });
+
+ it('detects a cyclic include chain and throws', async () => {
+ writePartial('p', '{{> q }}');
+ writePartial('q', '{{> p }}');
+ await expect(expandPartials('{{> p }}', { partialsDir }))
+ .rejects.toThrow(/MAX_DEPTH|cyclic/i);
+ });
+
+ it('rejects when partialsDir is missing', async () => {
+ await expect(expandPartials('{{> x }}', {}))
+ .rejects.toThrow(/partialsDir is required/);
+ });
+
+ it('passes Mustache variables through the partial body verbatim (the var pass runs later)', async () => {
+ // Partials don't render variables themselves — they just emit body text
+ // that the downstream applyTemplate pass interpolates against the
+ // shared context. Round-trip check.
+ writePartial('greet', 'Hello {{name}}, welcome to {{place}}.');
+ const out = await expandPartials('-- {{> greet }} --', { partialsDir });
+ expect(out).toBe('-- Hello {{name}}, welcome to {{place}}. --');
+ });
+});
diff --git a/server/lib/sceneExtractor.js b/server/lib/sceneExtractor.js
new file mode 100644
index 0000000000..96bdfec5e2
--- /dev/null
+++ b/server/lib/sceneExtractor.js
@@ -0,0 +1,164 @@
+/**
+ * Scene-list extraction — split a prose draft OR a TV teleplay into a
+ * structured `scenes[]` shape both Writers Room and Pipeline can consume.
+ *
+ * Mirrors the bibleExtractor.js pattern: this module owns the LLM call +
+ * sanitization, the caller owns persistence. Returns the same scene shape
+ * the writers-room evaluator's `script` analysis produces, so a writers-room
+ * scene array and a pipeline-extracted scene array are byte-for-byte the
+ * same shape (the Pipeline UI then reads `description` ← `visualPrompt`
+ * for legacy field-name compat — see `extractedScenesToStoryboards` below).
+ *
+ * Two source modes:
+ *
+ * - `prose` → uses the existing `writers-room-script` stage prompt
+ * (prose-paragraph granularity, sluglines invented).
+ * - `tvScript`→ uses the new `pipeline-extract-scenes` stage prompt
+ * (sluglines already present in the teleplay markdown,
+ * parse them rather than invent).
+ */
+
+import { runStagedLLM } from './stageRunner.js';
+import { BIBLE_KIND, pickPromptFields, isStr, trimTo } from './storyBible.js';
+
+export const SOURCE_KIND = Object.freeze({ PROSE: 'prose', TV_SCRIPT: 'tvScript' });
+
+const STAGE_FOR_SOURCE = Object.freeze({
+ [SOURCE_KIND.PROSE]: 'writers-room-script',
+ [SOURCE_KIND.TV_SCRIPT]: 'pipeline-extract-scenes',
+});
+
+// Per-field caps. Match the BIBLE_LIMITS pattern: bound every LLM-sourced
+// string so a runaway scene list can't push stages.storyboards past
+// STAGE_OUTPUT_MAX (400kB) on the issue-persist round-trip.
+const SCENE_LIMITS = Object.freeze({
+ ID_MAX: 80,
+ HEADING_MAX: 200,
+ SLUGLINE_MAX: 200,
+ SUMMARY_MAX: 2000,
+ CHARACTER_NAME_MAX: 100,
+ CHARACTERS_PER_SCENE_MAX: 24,
+ ACTION_MAX: 2000,
+ DIALOGUE_LINE_MAX: 1000,
+ DIALOGUE_ENTRIES_MAX: 60,
+ VISUAL_PROMPT_MAX: 4000,
+ SOURCE_SEG_ID_MAX: 80,
+ SOURCE_SEG_IDS_MAX: 32,
+});
+
+// ---------- canonical scene shape (single source of truth) ----------
+
+function sanitizeScene(s, i) {
+ if (!s || typeof s !== 'object') return null;
+ const id = trimTo(s.id, SCENE_LIMITS.ID_MAX) || `scene-${String(i + 1).padStart(2, '0')}`;
+ const heading = trimTo(s.heading, SCENE_LIMITS.HEADING_MAX) || `Scene ${i + 1}`;
+ const slugline = trimTo(s.slugline, SCENE_LIMITS.SLUGLINE_MAX);
+ return {
+ id,
+ heading,
+ slugline: slugline || null,
+ summary: trimTo(s.summary, SCENE_LIMITS.SUMMARY_MAX),
+ characters: Array.isArray(s.characters)
+ ? s.characters.map((c) => trimTo(c, SCENE_LIMITS.CHARACTER_NAME_MAX)).filter(Boolean).slice(0, SCENE_LIMITS.CHARACTERS_PER_SCENE_MAX)
+ : [],
+ action: trimTo(s.action, SCENE_LIMITS.ACTION_MAX),
+ dialogue: Array.isArray(s.dialogue)
+ ? s.dialogue
+ .filter((d) => d && typeof d === 'object' && (isStr(d.character) || isStr(d.line)))
+ .slice(0, SCENE_LIMITS.DIALOGUE_ENTRIES_MAX)
+ .map((d) => ({
+ character: trimTo(d.character, SCENE_LIMITS.CHARACTER_NAME_MAX),
+ line: trimTo(d.line, SCENE_LIMITS.DIALOGUE_LINE_MAX),
+ }))
+ : [],
+ visualPrompt: trimTo(s.visualPrompt, SCENE_LIMITS.VISUAL_PROMPT_MAX),
+ sourceSegmentIds: Array.isArray(s.sourceSegmentIds)
+ ? s.sourceSegmentIds.map((segId) => trimTo(segId, SCENE_LIMITS.SOURCE_SEG_ID_MAX)).filter(Boolean).slice(0, SCENE_LIMITS.SOURCE_SEG_IDS_MAX)
+ : [],
+ };
+}
+
+/**
+ * Sanitize the full LLM envelope: `{ title, logline, scenes: [...] }`.
+ * Cap at 200 scenes to match the visual-stage `scenes` cap in
+ * `pipeline/issues.js#sanitizeVisualStage` so an over-eager extraction
+ * can't silently lose entries to a downstream slice.
+ */
+export function sanitizeSceneList(raw, { maxScenes = 200 } = {}) {
+ const obj = raw && typeof raw === 'object' ? raw : {};
+ const list = Array.isArray(obj.scenes) ? obj.scenes : [];
+ return {
+ title: isStr(obj.title) ? obj.title.trim() : null,
+ logline: isStr(obj.logline) ? obj.logline.trim() : null,
+ scenes: list.slice(0, maxScenes).map(sanitizeScene).filter(Boolean),
+ };
+}
+
+// ---------- LLM driver ----------
+
+/**
+ * @param {object} args
+ * @param {string} args.source prose body OR teleplay markdown
+ * @param {string} args.sourceKind 'prose' | 'tvScript'
+ * @param {Array} [args.characters] bible entries (for deference)
+ * @param {Array} [args.settings] bible entries (for deference)
+ * @param {Array} [args.objects] bible entries (for deference)
+ * @param {object} [args.work] variables consumed by writers-room-script (`work.title`, `work.kind`, `work.wordCount`)
+ * @param {object} [args.series] variables consumed by pipeline-extract-scenes (`series.name`, `series.styleNotes`)
+ * @param {object} [args.issue] variables consumed by pipeline-extract-scenes (`issue.number`, `issue.title`)
+ * @param {string} [args.providerOverride]
+ * @param {string} [args.tag] override the run-tracking source tag
+ * @returns {Promise<{ extracted: { title, logline, scenes }, runId, providerId, model }>}
+ */
+export async function extractScenes({
+ source,
+ sourceKind = SOURCE_KIND.PROSE,
+ characters = [],
+ settings = [],
+ objects = [],
+ work,
+ series,
+ issue,
+ providerOverride,
+ tag,
+}) {
+ const stage = STAGE_FOR_SOURCE[sourceKind];
+ if (!stage) throw new Error(`extractScenes: unknown sourceKind "${sourceKind}"`);
+ if (!isStr(source) || !source.trim()) {
+ throw new Error('extractScenes: source is required');
+ }
+
+ // Both prompts read the same `existing<X>Json` envelope so the model can
+ // defer to canonical character/setting names instead of re-improvising.
+ // Pipeline's series.characters and Writers Room's per-work characters both
+ // sanitize through `pickPromptFields` to strip ids/timestamps/source/notes.
+ const variables = {
+ returnsJson: true,
+ sourceKind,
+ existingCharactersJson: JSON.stringify((characters || []).map((c) => pickPromptFields(BIBLE_KIND.CHARACTER, c))),
+ existingSettingsJson: JSON.stringify((settings || []).map((s) => pickPromptFields(BIBLE_KIND.SETTING, s))),
+ existingObjectsJson: JSON.stringify((objects || []).map((o) => pickPromptFields(BIBLE_KIND.OBJECT, o))),
+ };
+ // Variable-shape compat: writers-room-script.md reads `{{draftBody}}` +
+ // `{{work.*}}`; pipeline-extract-scenes.md reads `{{teleplay}}` +
+ // `{{series.*}}` / `{{issue.*}}`. Populate both — Mustache silently drops
+ // unbound names.
+ variables.draftBody = source;
+ variables.teleplay = source;
+ if (work) variables.work = work;
+ if (series) variables.series = series;
+ if (issue) variables.issue = issue;
+
+ const result = await runStagedLLM(stage, variables, {
+ providerOverride,
+ returnsJson: true,
+ source: tag || `scene-extract-${sourceKind}`,
+ });
+
+ return {
+ extracted: sanitizeSceneList(result.content),
+ runId: result.runId,
+ providerId: result.providerId,
+ model: result.model,
+ };
+}
diff --git a/server/lib/sceneExtractor.test.js b/server/lib/sceneExtractor.test.js
new file mode 100644
index 0000000000..847f9634fc
--- /dev/null
+++ b/server/lib/sceneExtractor.test.js
@@ -0,0 +1,216 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./stageRunner.js', () => ({
+ runStagedLLM: vi.fn(),
+}));
+
+import {
+ extractScenes,
+ sanitizeSceneList,
+ SOURCE_KIND,
+} from './sceneExtractor.js';
+import { runStagedLLM } from './stageRunner.js';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('sanitizeSceneList', () => {
+ it('returns title/logline strings + scenes array from a fully-shaped envelope', () => {
+ const out = sanitizeSceneList({
+ title: ' The Pilot ',
+ logline: 'A heist gone wrong.',
+ scenes: [
+ {
+ id: 'scene-01',
+ heading: 'Scene 1 — Entry',
+ slugline: 'INT. VAULT — NIGHT',
+ summary: 'They break in.',
+ characters: ['ALICE', 'BOB'],
+ action: 'A drill bites into the lock.',
+ dialogue: [{ character: 'ALICE', line: 'Quiet.' }],
+ visualPrompt: 'a high-tech vault interior, two figures in black tactical gear, dim red emergency light',
+ sourceSegmentIds: ['seg-001'],
+ },
+ ],
+ });
+ expect(out.title).toBe('The Pilot');
+ expect(out.logline).toBe('A heist gone wrong.');
+ expect(out.scenes).toHaveLength(1);
+ expect(out.scenes[0]).toMatchObject({
+ id: 'scene-01',
+ heading: 'Scene 1 — Entry',
+ slugline: 'INT. VAULT — NIGHT',
+ characters: ['ALICE', 'BOB'],
+ dialogue: [{ character: 'ALICE', line: 'Quiet.' }],
+ });
+ });
+
+ it('synthesizes id/heading when LLM omits them', () => {
+ const out = sanitizeSceneList({
+ scenes: [{ visualPrompt: 'a' }, { visualPrompt: 'b' }, { visualPrompt: 'c' }],
+ });
+ expect(out.scenes.map((s) => s.id)).toEqual(['scene-01', 'scene-02', 'scene-03']);
+ expect(out.scenes.map((s) => s.heading)).toEqual(['Scene 1', 'Scene 2', 'Scene 3']);
+ });
+
+ it('coerces missing/non-array fields to safe defaults (no crash on partial LLM output)', () => {
+ const out = sanitizeSceneList({
+ scenes: [{ id: 's1', characters: 'NOT_AN_ARRAY', dialogue: null, sourceSegmentIds: undefined }],
+ });
+ expect(out.scenes[0].characters).toEqual([]);
+ expect(out.scenes[0].dialogue).toEqual([]);
+ expect(out.scenes[0].sourceSegmentIds).toEqual([]);
+ expect(out.scenes[0].visualPrompt).toBe('');
+ expect(out.scenes[0].slugline).toBeNull();
+ });
+
+ it('drops dialogue entries that lack both character and line, trims the rest', () => {
+ const out = sanitizeSceneList({
+ scenes: [{
+ dialogue: [
+ { character: ' ALICE ', line: ' Quiet. ' },
+ {}, // both missing → dropped
+ { character: 'BOB' }, // line missing but char present → kept
+ { line: '...' }, // char missing but line present → kept
+ 'not an object', // wrong type → dropped
+ ],
+ }],
+ });
+ expect(out.scenes[0].dialogue).toEqual([
+ { character: 'ALICE', line: 'Quiet.' },
+ { character: 'BOB', line: '' },
+ { character: '', line: '...' },
+ ]);
+ });
+
+ it('caps scenes at maxScenes', () => {
+ const huge = { scenes: Array.from({ length: 250 }, (_, i) => ({ id: `s${i}` })) };
+ const out = sanitizeSceneList(huge, { maxScenes: 10 });
+ expect(out.scenes).toHaveLength(10);
+ });
+
+ it('returns an empty list shape on garbage input rather than throwing', () => {
+ expect(sanitizeSceneList(null)).toEqual({ title: null, logline: null, scenes: [] });
+ expect(sanitizeSceneList('not-an-object')).toEqual({ title: null, logline: null, scenes: [] });
+ expect(sanitizeSceneList({ scenes: 'oops' })).toEqual({ title: null, logline: null, scenes: [] });
+ });
+
+ it('drops non-string character names and trims survivors', () => {
+ const out = sanitizeSceneList({ scenes: [{ characters: [' ALICE ', 42, null, 'BOB', ''] }] });
+ expect(out.scenes[0].characters).toEqual(['ALICE', 'BOB']);
+ });
+
+ it('clamps unbounded LLM string fields to per-field limits (no runaway payloads)', () => {
+ const huge = 'a'.repeat(10_000);
+ const out = sanitizeSceneList({
+ scenes: [{
+ summary: huge, action: huge, visualPrompt: huge, slugline: huge, heading: huge,
+ dialogue: [{ character: 'X'.repeat(500), line: huge }],
+ characters: Array.from({ length: 100 }, (_, i) => `CHAR_${i}`),
+ sourceSegmentIds: Array.from({ length: 100 }, (_, i) => `seg-${i}`),
+ }],
+ });
+ const s = out.scenes[0];
+ expect(s.summary.length).toBe(2000);
+ expect(s.action.length).toBe(2000);
+ expect(s.visualPrompt.length).toBe(4000);
+ expect(s.slugline.length).toBe(200);
+ expect(s.heading.length).toBe(200);
+ expect(s.dialogue[0].character.length).toBe(100);
+ expect(s.dialogue[0].line.length).toBe(1000);
+ expect(s.characters.length).toBe(24);
+ expect(s.sourceSegmentIds.length).toBe(32);
+ });
+});
+
+describe('extractScenes', () => {
+ it('routes prose source through the writers-room-script stage', async () => {
+ runStagedLLM.mockResolvedValue({
+ content: { title: 'X', logline: 'L', scenes: [{ visualPrompt: 'a vault' }] },
+ runId: 'run-1', providerId: 'lmstudio', model: 'gpt-oss-120b',
+ });
+
+ const result = await extractScenes({
+ source: 'Some prose body.',
+ sourceKind: SOURCE_KIND.PROSE,
+ characters: [{ id: 'c1', name: 'Alice', physicalDescription: 'tall, freckles' }],
+ settings: [],
+ work: { title: 'My Work', kind: 'short-story', wordCount: 1234 },
+ });
+
+ expect(runStagedLLM).toHaveBeenCalledTimes(1);
+ const [stage, vars, opts] = runStagedLLM.mock.calls[0];
+ expect(stage).toBe('writers-room-script');
+ expect(vars.draftBody).toBe('Some prose body.');
+ expect(vars.teleplay).toBe('Some prose body.');
+ expect(vars.sourceKind).toBe('prose');
+ expect(vars.work).toEqual({ title: 'My Work', kind: 'short-story', wordCount: 1234 });
+ // existing<X>Json strings are populated through pickPromptFields (id stripped)
+ const existingChars = JSON.parse(vars.existingCharactersJson);
+ expect(existingChars[0]).toMatchObject({ name: 'Alice', physicalDescription: 'tall, freckles' });
+ expect(existingChars[0].id).toBeUndefined();
+ expect(opts.returnsJson).toBe(true);
+ expect(opts.source).toBe('scene-extract-prose');
+
+ expect(result.extracted.scenes).toHaveLength(1);
+ expect(result.runId).toBe('run-1');
+ expect(result.providerId).toBe('lmstudio');
+ expect(result.model).toBe('gpt-oss-120b');
+ });
+
+ it('routes tvScript source through the pipeline-extract-scenes stage with series + issue context', async () => {
+ runStagedLLM.mockResolvedValue({
+ content: { title: 'X', logline: 'L', scenes: [{ slugline: 'INT. ROOM' }] },
+ runId: 'run-2', providerId: 'lmstudio', model: 'gpt-oss-120b',
+ });
+
+ await extractScenes({
+ source: '## TEASER\n\n### Scene 1\n\n**INT. ROOM — NIGHT**\n\nAction.',
+ sourceKind: SOURCE_KIND.TV_SCRIPT,
+ series: { name: 'Show', styleNotes: 'noir' },
+ issue: { number: 3, title: 'The Pilot' },
+ });
+
+ const [stage, vars, opts] = runStagedLLM.mock.calls[0];
+ expect(stage).toBe('pipeline-extract-scenes');
+ expect(vars.series).toEqual({ name: 'Show', styleNotes: 'noir' });
+ expect(vars.issue).toEqual({ number: 3, title: 'The Pilot' });
+ expect(opts.source).toBe('scene-extract-tvScript');
+ });
+
+ it('forwards providerOverride + custom run-tracking tag', async () => {
+ runStagedLLM.mockResolvedValue({
+ content: { scenes: [] }, runId: 'r', providerId: 'p', model: 'm',
+ });
+ await extractScenes({
+ source: 'x',
+ sourceKind: SOURCE_KIND.PROSE,
+ providerOverride: 'lmstudio',
+ tag: 'pipeline-storyboards',
+ });
+ const opts = runStagedLLM.mock.calls[0][2];
+ expect(opts.providerOverride).toBe('lmstudio');
+ expect(opts.source).toBe('pipeline-storyboards');
+ });
+
+ it('rejects unknown sourceKind', async () => {
+ await expect(extractScenes({ source: 'x', sourceKind: 'unknown' }))
+ .rejects.toThrow(/unknown sourceKind/);
+ });
+
+ it('rejects empty source', async () => {
+ await expect(extractScenes({ source: ' ', sourceKind: SOURCE_KIND.PROSE }))
+ .rejects.toThrow(/source is required/);
+ await expect(extractScenes({ source: null, sourceKind: SOURCE_KIND.PROSE }))
+ .rejects.toThrow(/source is required/);
+ });
+
+ it('still returns a valid envelope when the LLM emits scenes:[] (no crash)', async () => {
+ runStagedLLM.mockResolvedValue({ content: {}, runId: 'r', providerId: 'p', model: 'm' });
+ const result = await extractScenes({ source: 'x', sourceKind: SOURCE_KIND.PROSE });
+ expect(result.extracted.scenes).toEqual([]);
+ expect(result.extracted.title).toBeNull();
+ expect(result.extracted.logline).toBeNull();
+ });
+});
diff --git a/client/src/components/writers-room/sceneCardHelpers.js b/server/lib/scenePrompt.js
similarity index 50%
rename from client/src/components/writers-room/sceneCardHelpers.js
rename to server/lib/scenePrompt.js
index 0e35fc39ef..4bc509a312 100644
--- a/client/src/components/writers-room/sceneCardHelpers.js
+++ b/server/lib/scenePrompt.js
@@ -1,43 +1,21 @@
-// Shared scene/character helpers used by both the storyboard sidebar and the
-// (legacy) inline script result. Lives in its own module so SceneCard can be
-// imported wherever scenes are rendered without dragging the whole AI panel.
+/**
+ * Shared scene-prompt composer + bible matchers. Pure ESM, no Node-only
+ * deps — mirrored to `client/src/lib/scenePrompt.js` for the client bundle.
+ */
-// Mirror of server/lib/writersRoomStylePresets.js — kept in sync manually
-// since client and server are separate bundles. Curated preset ids come from
-// the /api/image-gen/style-presets endpoint at runtime; only the two
-// special discriminators live here.
-export const STYLE_ID = { NONE: 'none', CUSTOM: 'custom' };
-export const EMPTY_IMAGE_STYLE = { presetId: STYLE_ID.NONE, prompt: '', negativePrompt: '' };
-
-// Defaults for the per-scene image gen pipe. Klein-4B is the fastest FLUX.2
-// variant on Apple Silicon, and 768×512 is a 3:2 aspect that suits scene work.
-// steps + seed are stored as strings (or empty) so the form inputs can bind
-// directly. Empty string = "use model default" for steps, "random per render"
-// for seed. Parsed to numbers at the generateImage boundary in SceneCard.
-export const WR_IMAGE_DEFAULTS = {
- modelId: 'flux2-klein-4b',
- mode: 'local',
- width: 768,
- height: 512,
- steps: '',
- seed: '',
-};
+const PROMPT_MAX = 1900;
-export function readWrImageSettings(settings) {
- const stored = settings?.writersRoom?.imageGen || {};
- return {
- modelId: stored.modelId || WR_IMAGE_DEFAULTS.modelId,
- mode: stored.mode || WR_IMAGE_DEFAULTS.mode,
- width: Number.isFinite(stored.width) ? stored.width : WR_IMAGE_DEFAULTS.width,
- height: Number.isFinite(stored.height) ? stored.height : WR_IMAGE_DEFAULTS.height,
- steps: stored.steps != null && stored.steps !== '' ? String(stored.steps) : '',
- seed: stored.seed != null && stored.seed !== '' ? String(stored.seed) : '',
- };
-}
+// Normalize a screenplay slugline so case/punctuation/dash variants collapse:
+// `INT. KITCHEN — NIGHT` and `INT KITCHEN - NIGHT` both become `INT KITCHEN NIGHT`.
+export const normalizeSlugline = (s) => String(s || '')
+ .toUpperCase()
+ .replace(/[—–-]/g, ' ')
+ .replace(/[.,:;]/g, '')
+ .replace(/\s+/g, ' ')
+ .trim();
-// LLM scene lists use bare names ("ARIA"), profiles may use full names
-// ("Aria Reyes") or "the bartender" — strip leading "the " and lowercase so
-// either side resolves to the same key.
+// LLM scenes name characters bare ("ARIA"); profiles may use full names
+// ("Aria Reyes") or "the bartender". Strip leading "the " and lowercase.
export const normCharKey = (s) => String(s || '').trim().toLowerCase().replace(/^the\s+/, '');
export function buildCharByKey(allCharacters) {
@@ -55,24 +33,14 @@ export function matchSceneCharacters(sceneCharacterNames = [], charByKey) {
const seen = new Set();
for (const name of sceneCharacterNames) {
const profile = charByKey?.get(normCharKey(name));
- if (profile && !seen.has(profile.id)) {
+ if (profile && !seen.has(profile.id || profile.name)) {
matched.push(profile);
- seen.add(profile.id);
+ seen.add(profile.id || profile.name);
}
}
return matched;
}
-// Match server's normalizeSlugline in services/writersRoom/settings.js — the
-// pair has to agree byte-for-byte or the bible's match keys won't line up
-// with the live scene matching here.
-export const normalizeSlugline = (s) => String(s || '')
- .toUpperCase()
- .replace(/[—–-]/g, ' ')
- .replace(/[.,:;]/g, '')
- .replace(/\s+/g, ' ')
- .trim();
-
export function buildSettingByKey(allSettings) {
const map = new Map();
for (const setting of allSettings || []) {
@@ -88,24 +56,27 @@ export function matchSceneSetting(sceneSlugline, settingByKey) {
return settingByKey?.get(normalizeSlugline(sceneSlugline)) || null;
}
-const PROMPT_MAX = 1900;
-
-// Build the final image-gen prompt with priority order (diffusion models
-// weight earlier tokens heaviest):
-// 1. worldStyle preset (cinematic / film-noir / etc.) — broadest aesthetic
-// 2. workTitle — gives the model story-context cues
-// 3. setting baseline (description / palette / recurring details) — the place
-// 4. Featuring — char1: desc, char2: desc — the subjects
-// 5. scene.visualPrompt — what's NEW this beat
-//
-// Truncation priority is the inverse: visualPrompt survives unconditionally,
-// then setting baseline, then characters. Style + title are short so they're
-// always kept. Featuring drops characters one-by-one to fit; setting drops
-// secondary fields (palette, recurring) before description.
+/**
+ * Compose the final image-gen prompt with priority order (diffusion models
+ * weight earlier tokens heaviest):
+ * 1. worldStyle preset (cinematic / film-noir / etc.) — broadest aesthetic
+ * 2. workTitle — gives the model story-context cues
+ * 3. setting baseline (description / palette / recurring details) — the place
+ * 4. Featuring — char1: desc, char2: desc — the subjects
+ * 5. scene.visualPrompt — what's NEW this beat
+ *
+ * Truncation priority is the inverse: visualPrompt survives unconditionally,
+ * then setting baseline, then characters. Style + title are short so they're
+ * always kept. Featuring drops characters one-by-one to fit; setting drops
+ * secondary fields (palette, recurring) before description.
+ *
+ * Positional API kept for parity with the long-running Writers Room caller
+ * (`SceneCard.jsx`) — adding new optional kwargs at the tail is fine.
+ */
export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyle = '', matchedSetting = null) {
const stylePart = worldStyle && worldStyle.trim() ? `${worldStyle.trim()}. ` : '';
const titlePart = workTitle ? `${workTitle}. ` : '';
- const visual = scene.visualPrompt || '';
+ const visual = scene?.visualPrompt || scene?.description || '';
const settingFrags = matchedSetting ? [
matchedSetting.description?.trim() || '',
@@ -113,9 +84,13 @@ export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyle
matchedSetting.recurringDetails?.trim() || '',
].filter(Boolean) : [];
+ // Accept either `physicalDescription` (writers-room shape) or
+ // `description` (pipeline shape) — the composer doesn't care which
+ // field carries the visual descriptor.
const featuringFragments = (matchedCharacters || [])
- .filter((c) => c.physicalDescription && c.physicalDescription.trim())
- .map((c) => `${c.name}: ${c.physicalDescription.trim()}`);
+ .map((c) => ({ name: c.name, desc: (c.physicalDescription || c.description || '').trim() }))
+ .filter((c) => c.desc)
+ .map((c) => `${c.name}: ${c.desc}`);
const PREFIX = 'Featuring — ';
const reserveCore = stylePart.length + titlePart.length + visual.length + 4;
@@ -149,3 +124,5 @@ export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyle
if (visual) segs.push(visual);
return segs.filter(Boolean).join(' ').slice(0, PROMPT_MAX);
}
+
+export const __testing = { PROMPT_MAX };
diff --git a/server/lib/scenePrompt.test.js b/server/lib/scenePrompt.test.js
new file mode 100644
index 0000000000..24a0a5125a
--- /dev/null
+++ b/server/lib/scenePrompt.test.js
@@ -0,0 +1,180 @@
+import { describe, it, expect } from 'vitest';
+import {
+ normalizeSlugline,
+ normCharKey,
+ buildCharByKey,
+ matchSceneCharacters,
+ buildSettingByKey,
+ matchSceneSetting,
+ buildScenePrompt,
+ __testing,
+} from './scenePrompt.js';
+
+describe('scenePrompt — normalizeSlugline', () => {
+ it('collapses em/en/hyphen + punctuation + spaces so equivalent sluglines match', () => {
+ const a = normalizeSlugline('INT. KITCHEN — NIGHT');
+ const b = normalizeSlugline('INT. KITCHEN – NIGHT');
+ const c = normalizeSlugline('INT. KITCHEN - NIGHT');
+ const d = normalizeSlugline('INT KITCHEN NIGHT');
+ expect(a).toBe('INT KITCHEN NIGHT');
+ expect(b).toBe('INT KITCHEN NIGHT');
+ expect(c).toBe('INT KITCHEN NIGHT');
+ expect(d).toBe('INT KITCHEN NIGHT');
+ });
+
+ it('uppercases and collapses whitespace', () => {
+ expect(normalizeSlugline('int. kitchen — night')).toBe(normalizeSlugline('INT. KITCHEN — NIGHT'));
+ });
+
+ it('handles falsy input', () => {
+ expect(normalizeSlugline('')).toBe('');
+ expect(normalizeSlugline(null)).toBe('');
+ expect(normalizeSlugline(undefined)).toBe('');
+ });
+});
+
+describe('scenePrompt — normCharKey', () => {
+ it('strips leading "the " and lowercases', () => {
+ expect(normCharKey('The Bartender')).toBe('bartender');
+ expect(normCharKey('ARIA')).toBe('aria');
+ expect(normCharKey(' Aria Reyes ')).toBe('aria reyes');
+ });
+});
+
+describe('scenePrompt — buildCharByKey + matchSceneCharacters', () => {
+ const cast = [
+ { id: 'c1', name: 'Aria Reyes', aliases: ['Aria', 'The Bartender'], physicalDescription: 'tall, dark hair' },
+ { id: 'c2', name: 'Marcus', aliases: [], physicalDescription: 'broad shoulders' },
+ ];
+
+ it('indexes by name AND aliases', () => {
+ const map = buildCharByKey(cast);
+ expect(map.get('aria reyes')?.id).toBe('c1');
+ expect(map.get('aria')?.id).toBe('c1');
+ expect(map.get('bartender')?.id).toBe('c1'); // alias lookup also strips "the "
+ expect(map.get('marcus')?.id).toBe('c2');
+ });
+
+ it('matches LLM scene names via either canonical name or alias, dedupes, preserves order', () => {
+ const map = buildCharByKey(cast);
+ const matched = matchSceneCharacters(['ARIA', 'Marcus', 'aria'], map);
+ expect(matched.map((c) => c.id)).toEqual(['c1', 'c2']);
+ });
+
+ it('returns [] for empty / non-array input', () => {
+ expect(matchSceneCharacters([], new Map())).toEqual([]);
+ expect(matchSceneCharacters(null, new Map())).toEqual([]);
+ expect(matchSceneCharacters(undefined, new Map())).toEqual([]);
+ });
+});
+
+describe('scenePrompt — buildSettingByKey + matchSceneSetting', () => {
+ const settings = [
+ { id: 's1', slugline: 'INT. KITCHEN — NIGHT', description: 'cramped tile', palette: 'amber' },
+ { id: 's2', name: 'EXT. ROOFTOP', slugline: '', description: 'wind-swept' },
+ ];
+
+ it('keys by slugline (preferred) then name (fallback)', () => {
+ const map = buildSettingByKey(settings);
+ expect(map.get(normalizeSlugline('INT. KITCHEN — NIGHT'))?.id).toBe('s1');
+ expect(map.get(normalizeSlugline('EXT. ROOFTOP'))?.id).toBe('s2');
+ });
+
+ it('matches with em-dash / hyphen drift', () => {
+ const map = buildSettingByKey(settings);
+ expect(matchSceneSetting('INT KITCHEN - NIGHT', map)?.id).toBe('s1');
+ expect(matchSceneSetting('int kitchen — night', map)?.id).toBe('s1');
+ });
+
+ it('returns null when slugline is empty or unmatched', () => {
+ const map = buildSettingByKey(settings);
+ expect(matchSceneSetting('', map)).toBeNull();
+ expect(matchSceneSetting('INT. SUBMARINE — DAWN', map)).toBeNull();
+ });
+});
+
+describe('scenePrompt — buildScenePrompt', () => {
+ const baseScene = { visualPrompt: 'wide shot of two figures squaring up across the bar' };
+
+ it('emits style → title → setting → featuring → visual in order', () => {
+ const out = buildScenePrompt(
+ 'Neon Saints',
+ baseScene,
+ [{ name: 'Aria', physicalDescription: 'tall, dark hair' }],
+ 'noir, rain-soaked, sodium street lights',
+ { description: 'cramped chrome bar', palette: 'amber', recurringDetails: 'broken jukebox in corner' },
+ );
+ expect(out.indexOf('noir, rain-soaked, sodium street lights'))
+ .toBeLessThan(out.indexOf('Neon Saints'));
+ expect(out.indexOf('Neon Saints'))
+ .toBeLessThan(out.indexOf('cramped chrome bar'));
+ expect(out.indexOf('cramped chrome bar'))
+ .toBeLessThan(out.indexOf('Featuring — Aria'));
+ expect(out.indexOf('Featuring — Aria'))
+ .toBeLessThan(out.indexOf('wide shot of two figures'));
+ });
+
+ it('accepts pipeline-flavored characters (description in lieu of physicalDescription)', () => {
+ const out = buildScenePrompt(
+ 'Series',
+ baseScene,
+ [{ name: 'Aria', description: 'tall, dark hair' }],
+ '',
+ null,
+ );
+ expect(out).toContain('Featuring — Aria: tall, dark hair');
+ });
+
+ it('skips characters with no visual descriptor (avoids "Aria: " junk fragments)', () => {
+ const out = buildScenePrompt('S', baseScene, [{ name: 'Aria' }], '', null);
+ expect(out).not.toContain('Featuring');
+ });
+
+ it('drops palette + recurringDetails before description when budget runs out', () => {
+ // Reserve space for `description` (20) + a separator + the prefix-less
+ // setting baseline, but NOT enough for `Palette: AMBER.` (15) on top.
+ const huge = 'X'.repeat(__testing.PROMPT_MAX - 30);
+ const out = buildScenePrompt(
+ '',
+ { visualPrompt: huge },
+ [],
+ '',
+ { description: 'baseline description', palette: 'AMBER', recurringDetails: 'broken jukebox' },
+ );
+ expect(out).toContain(huge);
+ expect(out).toContain('baseline description');
+ expect(out).not.toContain('Palette');
+ expect(out).not.toContain('broken jukebox');
+ });
+
+ it('drops characters one-by-one to fit budget, in order', () => {
+ const cast = [
+ { name: 'A', physicalDescription: 'X'.repeat(800) },
+ { name: 'B', physicalDescription: 'short' },
+ ];
+ const out = buildScenePrompt('', baseScene, cast, '', null);
+ expect(out).toContain('A: ');
+ // 'B: short' is small enough to fit alongside A, so both should appear.
+ expect(out).toContain('B: short');
+ });
+
+ it('caps total length at PROMPT_MAX', () => {
+ const out = buildScenePrompt(
+ 'X'.repeat(500),
+ { visualPrompt: 'Y'.repeat(3000) },
+ [],
+ 'Z'.repeat(500),
+ null,
+ );
+ expect(out.length).toBeLessThanOrEqual(__testing.PROMPT_MAX);
+ });
+
+ it('falls back to scene.description when visualPrompt is missing (pipeline call shape)', () => {
+ const out = buildScenePrompt('S', { description: 'a dim room' }, [], '', null);
+ expect(out).toContain('a dim room');
+ });
+
+ it('returns empty string for fully empty inputs', () => {
+ expect(buildScenePrompt('', {}, [], '', null)).toBe('');
+ });
+});
diff --git a/server/lib/stageRunner.js b/server/lib/stageRunner.js
new file mode 100644
index 0000000000..b0a2a50d78
--- /dev/null
+++ b/server/lib/stageRunner.js
@@ -0,0 +1,180 @@
+/**
+ * Shared staged-LLM runner.
+ *
+ * Single entry point for "run a named stage from `data/prompts/stages/` against
+ * the active (or stage-pinned) provider, with tier-aware model resolution and
+ * runner.js-tracked transcripts." Replaces two parallel implementations:
+ *
+ * - server/services/writersRoom/evaluator.js (callApiProvider + callCliProvider
+ * + buildCliInvocation — bypassed runner.js, lost transcript persistence)
+ * - server/services/pipeline/textStages.js#callLLM (already used runner.js but
+ * lacked tier-name resolution and stage.provider pinning)
+ *
+ * Both call paths now route here so a single CLI-spawn fix applies once and
+ * every stage call lands in `data/runs/<runId>/` for replay.
+ */
+
+import { ServerError } from './errorHandler.js';
+import { stripCodeFences } from './aiProvider.js';
+import { getActiveProvider, getProviderById } from '../services/providers.js';
+import { buildPrompt, getStage } from '../services/promptService.js';
+import { createRun, executeApiRun, executeCliRun } from '../services/runner.js';
+
+// Stage configs name a model by tier (PromptManager UI). Map each tier name
+// to the provider's per-tier model field; an unset tier falls through to
+// `defaultModel`.
+const TIER_TO_MODEL_KEY = Object.freeze({
+ default: 'defaultModel',
+ quick: 'lightModel',
+ coding: 'mediumModel',
+ heavy: 'heavyModel',
+});
+
+const isTierName = (m) => typeof m === 'string' && m in TIER_TO_MODEL_KEY;
+
+// First-element fallback when defaultModel is unset on a provider that
+// exposes a `models` array (some toolkit-configured providers ship a model
+// list but no explicit default). Without this, API-side runners that require
+// an explicit model would receive `null` and 400. Mirrors the older pipeline
+// fallback that the shared runner replaced.
+const providerFallbackModel = (provider) =>
+ provider.defaultModel
+ || (Array.isArray(provider.models) && provider.models[0])
+ || null;
+
+export function resolveModel(provider, modelHint) {
+ if (!modelHint) return providerFallbackModel(provider);
+ if (isTierName(modelHint)) {
+ return provider[TIER_TO_MODEL_KEY[modelHint]] || providerFallbackModel(provider);
+ }
+ return modelHint;
+}
+
+// Stage config can pin a specific provider via `stage.provider`. If set we
+// must use it (or fail) — falling back to the active provider would route
+// silently through whatever's currently selected, defeating the override.
+async function resolveProviderForStage(stage, { providerOverride } = {}) {
+ if (providerOverride) {
+ const pinned = await getProviderById(providerOverride).catch(() => null);
+ if (pinned?.enabled) return pinned;
+ throw new ServerError(
+ `Requested provider "${providerOverride}" is not available`,
+ { status: 503, code: 'PROVIDER_OVERRIDE_UNAVAILABLE' }
+ );
+ }
+ if (stage?.provider) {
+ const pinned = await getProviderById(stage.provider).catch(() => null);
+ if (pinned?.enabled) return pinned;
+ throw new ServerError(
+ `Stage provider "${stage.provider}" is not available — re-pick a provider in Prompts or the stage settings`,
+ { status: 503, code: 'STAGE_PROVIDER_UNAVAILABLE' }
+ );
+ }
+ const active = await getActiveProvider().catch(() => null);
+ if (active?.enabled) return active;
+ throw new ServerError('No AI provider available', { status: 503, code: 'NO_PROVIDER' });
+}
+
+// Wraps executeApiRun / executeCliRun as a Promise so callers can await one
+// completion. Mirrors the pattern in worldBuilderExpand.js#callLLM — both
+// runner entry points are async and can reject before onComplete fires, so
+// we forward those rejections through the outer Promise instead of letting
+// them surface as unhandledRejection (Node ≥15 process-killer).
+function awaitRunnerCall({ provider, model, prompt, runId, source }) {
+ return new Promise((resolve, reject) => {
+ let text = '';
+ if (provider.type === 'cli') {
+ // executeCliRun reads `provider.defaultModel` for both the CLI args
+ // (`buildCliArgs(provider)`) and the run-started metadata hook. The
+ // toolkit's CLI entry doesn't accept a separate model param, so to
+ // honor a stage-level model override (or a tier-name resolution like
+ // `model: 'heavy'`) we hand it a shallow clone with the resolved
+ // model in `defaultModel`. Without this, `runStagedLLM(..., { modelOverride: 'codex-mini' })`
+ // would silently fall back to the provider's stock default AND the
+ // run record would log the wrong model.
+ const providerForCli = model && model !== provider.defaultModel
+ ? { ...provider, defaultModel: model }
+ : provider;
+ executeCliRun(
+ runId,
+ providerForCli,
+ prompt,
+ process.cwd(),
+ (chunk) => { text += chunk; },
+ (result) => {
+ if (result?.error || result?.success === false) {
+ reject(new Error(result?.error || 'CLI execution failed'));
+ } else {
+ resolve(text);
+ }
+ },
+ providerForCli.timeout ?? 300000,
+ ).catch(reject);
+ } else if (provider.type === 'api') {
+ executeApiRun(
+ runId,
+ provider,
+ model,
+ prompt,
+ process.cwd(),
+ [],
+ (data) => { text += typeof data === 'string' ? data : (data?.text || ''); },
+ (result) => {
+ if (result?.error) reject(new Error(result.error));
+ else resolve(text);
+ },
+ ).catch(reject);
+ } else {
+ reject(new Error(`Unsupported provider type: ${provider.type}`));
+ }
+ });
+}
+
+/**
+ * Extract the first balanced object/array from an LLM response. Some
+ * providers prepend explanation prose; the prompt asks for JSON only but
+ * we have to be defensive. Lifted from the writers-room evaluator so the
+ * pipeline gets the same lenient parser when it eventually requests JSON.
+ */
+export function extractJson(text) {
+ if (!text || typeof text !== 'string') throw new Error('Empty AI response');
+ let str = stripCodeFences(text);
+ const objMatch = str.match(/[{[][\s\S]*[\]}]/);
+ if (objMatch) str = objMatch[0];
+ return JSON.parse(str);
+}
+
+/**
+ * Run a named stage end-to-end. Returns `{ content, model, providerId, runId }`
+ * (or the parsed JSON in the `content` field when `returnsJson` is true).
+ *
+ * Options:
+ * - providerOverride: explicit provider id, beats stage.provider
+ * - modelOverride: explicit model id, beats stage.model
+ * - returnsJson: parse `content` via `extractJson` before returning
+ * - source: free-form tag persisted on the run record (e.g. 'pipeline-text-stage',
+ * 'writers-room-evaluate') so /runs is filterable
+ */
+export async function runStagedLLM(stageName, variables, options = {}) {
+ const stage = getStage(stageName);
+ const provider = await resolveProviderForStage(stage, options);
+ const prompt = await buildPrompt(stageName, variables);
+ let model = resolveModel(provider, options.modelOverride || stage?.model);
+ // Special case: gemini-cli requires an explicit model — toolkit defaults
+ // to `auto` which can resolve to a slow reasoning model (LM Studio gotcha).
+ if (provider.id === 'gemini-cli' && !model) {
+ model = provider.lightModel || 'gemini-2.5-flash';
+ }
+
+ const { runId } = await createRun({
+ providerId: provider.id,
+ model,
+ prompt,
+ source: options.source || 'staged-llm',
+ });
+ console.log(`📝 stage: ${provider.id} / ${model || '(default)'} / ${stageName} → ${runId.slice(0, 8)}`);
+
+ const text = await awaitRunnerCall({ provider, model, prompt, runId, source: options.source });
+ const content = options.returnsJson ? extractJson(text) : text;
+ return { content, model: model || null, providerId: provider.id, runId };
+}
diff --git a/server/lib/stageRunner.test.js b/server/lib/stageRunner.test.js
new file mode 100644
index 0000000000..1270181094
--- /dev/null
+++ b/server/lib/stageRunner.test.js
@@ -0,0 +1,200 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('../services/providers.js', () => ({
+ getActiveProvider: vi.fn(),
+ getProviderById: vi.fn(),
+}));
+
+vi.mock('../services/promptService.js', () => ({
+ buildPrompt: vi.fn().mockResolvedValue('rendered-prompt'),
+ getStage: vi.fn(),
+}));
+
+vi.mock('../services/runner.js', () => ({
+ createRun: vi.fn(async () => ({ runId: 'run-abc12345' })),
+ executeApiRun: vi.fn(),
+ executeCliRun: vi.fn(),
+}));
+
+const providers = await import('../services/providers.js');
+const prompts = await import('../services/promptService.js');
+const runner = await import('../services/runner.js');
+const { runStagedLLM, resolveModel, extractJson } = await import('./stageRunner.js');
+
+const apiProvider = (extra = {}) => ({
+ id: 'mock-api', name: 'Mock', type: 'api', enabled: true, defaultModel: 'm-default', ...extra,
+});
+const cliProvider = (extra = {}) => ({
+ id: 'codex', name: 'Codex', type: 'cli', enabled: true, defaultModel: 'm-default', timeout: 5000, ...extra,
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('stageRunner — resolveModel', () => {
+ it('returns provider.defaultModel when no hint', () => {
+ expect(resolveModel({ defaultModel: 'd' }, null)).toBe('d');
+ expect(resolveModel({ defaultModel: 'd' }, undefined)).toBe('d');
+ });
+
+ it('maps tier names to per-tier provider keys, falls back to defaultModel when missing', () => {
+ const p = { defaultModel: 'd', lightModel: 'l', mediumModel: 'm', heavyModel: 'h' };
+ expect(resolveModel(p, 'quick')).toBe('l');
+ expect(resolveModel(p, 'coding')).toBe('m');
+ expect(resolveModel(p, 'heavy')).toBe('h');
+ expect(resolveModel(p, 'default')).toBe('d');
+ expect(resolveModel({ defaultModel: 'd' }, 'heavy')).toBe('d'); // tier missing → fall back
+ });
+
+ it('returns explicit model id verbatim when not a tier name', () => {
+ expect(resolveModel({ defaultModel: 'd' }, 'gpt-5-explicit')).toBe('gpt-5-explicit');
+ });
+
+ it('falls back to provider.models[0] when defaultModel is unset (no hint)', () => {
+ expect(resolveModel({ models: ['m0', 'm1'] }, null)).toBe('m0');
+ expect(resolveModel({ models: ['m0'], defaultModel: '' }, null)).toBe('m0');
+ });
+
+ it('falls back to provider.models[0] when both tier slot and defaultModel are unset', () => {
+ expect(resolveModel({ models: ['m0', 'm1'] }, 'heavy')).toBe('m0');
+ });
+
+ it('returns null when neither defaultModel nor models[] is available', () => {
+ expect(resolveModel({}, null)).toBeNull();
+ expect(resolveModel({ models: [] }, null)).toBeNull();
+ expect(resolveModel({}, 'heavy')).toBeNull();
+ });
+});
+
+describe('stageRunner — extractJson', () => {
+ it('parses JSON inside markdown code fences', () => {
+ expect(extractJson('```json\n{"a":1}\n```')).toEqual({ a: 1 });
+ });
+ it('extracts the first balanced object even when prose is prepended', () => {
+ expect(extractJson('Sure! Here is the data: {"a":1,"b":2} cheers.')).toEqual({ a: 1, b: 2 });
+ });
+ it('parses an array', () => {
+ expect(extractJson('[1,2,3]')).toEqual([1, 2, 3]);
+ });
+ it('throws on empty or non-string input', () => {
+ expect(() => extractJson('')).toThrow(/Empty AI response/);
+ expect(() => extractJson(null)).toThrow(/Empty AI response/);
+ });
+});
+
+describe('stageRunner — runStagedLLM provider resolution', () => {
+ it('uses the active provider when stage and overrides leave it unspecified', async () => {
+ prompts.getStage.mockReturnValue(null);
+ providers.getActiveProvider.mockResolvedValue(apiProvider());
+ runner.executeApiRun.mockImplementation(async (_id, _p, _m, _pr, _cwd, _shots, onData, onComplete) => {
+ onData('hello');
+ onComplete({ success: true });
+ });
+ const out = await runStagedLLM('any-stage', {});
+ expect(out.providerId).toBe('mock-api');
+ expect(out.content).toBe('hello');
+ expect(runner.createRun).toHaveBeenCalledTimes(1);
+ expect(runner.executeApiRun).toHaveBeenCalledTimes(1);
+ });
+
+ it('honors providerOverride beating stage.provider', async () => {
+ prompts.getStage.mockReturnValue({ provider: 'should-not-use' });
+ providers.getProviderById.mockImplementation(async (id) => (
+ id === 'override-id' ? apiProvider({ id: 'override-id' }) : null
+ ));
+ runner.executeApiRun.mockImplementation(async (_id, _p, _m, _pr, _cwd, _shots, onData, onComplete) => {
+ onData('override-content');
+ onComplete({ success: true });
+ });
+ const out = await runStagedLLM('s', {}, { providerOverride: 'override-id' });
+ expect(out.providerId).toBe('override-id');
+ expect(providers.getActiveProvider).not.toHaveBeenCalled();
+ });
+
+ it('uses stage.provider when set and no override', async () => {
+ prompts.getStage.mockReturnValue({ provider: 'stage-pinned' });
+ providers.getProviderById.mockImplementation(async (id) => (
+ id === 'stage-pinned' ? apiProvider({ id: 'stage-pinned' }) : null
+ ));
+ runner.executeApiRun.mockImplementation(async (_id, _p, _m, _pr, _cwd, _shots, onData, onComplete) => {
+ onData('pinned');
+ onComplete({ success: true });
+ });
+ const out = await runStagedLLM('s', {});
+ expect(out.providerId).toBe('stage-pinned');
+ });
+
+ it('throws STAGE_PROVIDER_UNAVAILABLE when stage.provider is set but disabled', async () => {
+ prompts.getStage.mockReturnValue({ provider: 'pinned-but-gone' });
+ providers.getProviderById.mockResolvedValue(null);
+ await expect(runStagedLLM('s', {})).rejects.toMatchObject({ code: 'STAGE_PROVIDER_UNAVAILABLE' });
+ });
+
+ it('throws PROVIDER_OVERRIDE_UNAVAILABLE when override is unknown', async () => {
+ prompts.getStage.mockReturnValue(null);
+ providers.getProviderById.mockResolvedValue(null);
+ await expect(runStagedLLM('s', {}, { providerOverride: 'nope' })).rejects.toMatchObject({ code: 'PROVIDER_OVERRIDE_UNAVAILABLE' });
+ });
+
+ it('throws NO_PROVIDER when no active provider is available', async () => {
+ prompts.getStage.mockReturnValue(null);
+ providers.getActiveProvider.mockResolvedValue(null);
+ await expect(runStagedLLM('s', {})).rejects.toMatchObject({ code: 'NO_PROVIDER' });
+ });
+});
+
+describe('stageRunner — runStagedLLM dispatch', () => {
+ it('routes CLI providers through executeCliRun', async () => {
+ prompts.getStage.mockReturnValue(null);
+ providers.getActiveProvider.mockResolvedValue(cliProvider());
+ runner.executeCliRun.mockImplementation(async (_id, _p, _pr, _cwd, onData, onComplete, _t) => {
+ onData('cli-output');
+ onComplete({ success: true });
+ });
+ const out = await runStagedLLM('s', {});
+ expect(out.content).toBe('cli-output');
+ expect(runner.executeCliRun).toHaveBeenCalledTimes(1);
+ expect(runner.executeApiRun).not.toHaveBeenCalled();
+ });
+
+ it('rejects when executeApiRun reports an error', async () => {
+ prompts.getStage.mockReturnValue(null);
+ providers.getActiveProvider.mockResolvedValue(apiProvider());
+ runner.executeApiRun.mockImplementation(async (_id, _p, _m, _pr, _cwd, _shots, _onData, onComplete) => {
+ onComplete({ error: 'simulated 500' });
+ });
+ await expect(runStagedLLM('s', {})).rejects.toThrow(/simulated 500/);
+ });
+
+ it('rejects when executeCliRun reports success: false', async () => {
+ prompts.getStage.mockReturnValue(null);
+ providers.getActiveProvider.mockResolvedValue(cliProvider());
+ runner.executeCliRun.mockImplementation(async (_id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: false, error: 'cli failed' });
+ });
+ await expect(runStagedLLM('s', {})).rejects.toThrow(/cli failed/);
+ });
+
+ it('parses JSON when returnsJson is true', async () => {
+ prompts.getStage.mockReturnValue(null);
+ providers.getActiveProvider.mockResolvedValue(apiProvider());
+ runner.executeApiRun.mockImplementation(async (_id, _p, _m, _pr, _cwd, _shots, onData, onComplete) => {
+ onData('```json\n{"x":1}\n```');
+ onComplete({ success: true });
+ });
+ const out = await runStagedLLM('s', {}, { returnsJson: true });
+ expect(out.content).toEqual({ x: 1 });
+ });
+
+ it('forwards source to createRun for transcript filtering', async () => {
+ prompts.getStage.mockReturnValue(null);
+ providers.getActiveProvider.mockResolvedValue(apiProvider());
+ runner.executeApiRun.mockImplementation(async (_id, _p, _m, _pr, _cwd, _shots, onData, onComplete) => {
+ onData('out');
+ onComplete({ success: true });
+ });
+ await runStagedLLM('s', {}, { source: 'pipeline-text-stage' });
+ expect(runner.createRun).toHaveBeenCalledWith(expect.objectContaining({ source: 'pipeline-text-stage' }));
+ });
+});
diff --git a/server/lib/storyBible.js b/server/lib/storyBible.js
new file mode 100644
index 0000000000..f0e2034a63
--- /dev/null
+++ b/server/lib/storyBible.js
@@ -0,0 +1,371 @@
+/**
+ * Canonical story-bible shapes (Character / Setting / Object) shared by the
+ * Writers Room (per-work bibles) and the Pipeline (per-series bibles).
+ *
+ * Both surfaces persist their own JSON; this module just owns the shape +
+ * sanitization + the merge-extracted-entries algorithm. Per-domain concerns
+ * (id prefix, file path, route exposure) stay with the caller.
+ */
+
+import { randomUUID } from 'crypto';
+import { normalizeSlugline } from './scenePrompt.js';
+
+export const BIBLE_LIMITS = Object.freeze({
+ NAME_MAX: 200,
+ ROLE_MAX: 200,
+ ALIAS_MAX: 100,
+ ALIASES_PER_ENTRY_MAX: 12,
+ PHYSICAL_DESCRIPTION_MAX: 2000,
+ PERSONALITY_MAX: 2000,
+ BACKGROUND_MAX: 2000,
+ NOTES_MAX: 4000,
+ IMAGE_REF_MAX: 500,
+ IMAGE_REFS_PER_ENTRY_MAX: 12,
+ EVIDENCE_ITEM_MAX: 500,
+ EVIDENCE_PER_ENTRY_MAX: 20,
+ // Settings
+ SLUGLINE_MAX: 200,
+ PALETTE_MAX: 200,
+ ERA_MAX: 200,
+ WEATHER_MAX: 200,
+ RECURRING_DETAILS_MAX: 1000,
+ SETTING_DESCRIPTION_MAX: 2000,
+ // Objects
+ OBJECT_DESCRIPTION_MAX: 2000,
+ SIGNIFICANCE_MAX: 1000,
+ // Per-bible cap (universal — protects against runaway extraction)
+ ENTRIES_PER_BIBLE_MAX: 200,
+});
+
+const SOURCES = new Set(['user', 'ai', 'imported']);
+
+export const BIBLE_KIND = Object.freeze({
+ CHARACTER: 'character',
+ SETTING: 'setting',
+ OBJECT: 'object',
+});
+
+// Canonical pluralization: pipeline series.<field>, evaluator analysis kind,
+// extractor LLM envelope key — all the same string, consolidated here.
+export const BIBLE_FIELD = Object.freeze({
+ [BIBLE_KIND.CHARACTER]: 'characters',
+ [BIBLE_KIND.SETTING]: 'settings',
+ [BIBLE_KIND.OBJECT]: 'objects',
+});
+
+// Fields the bible-extraction prompt cares about. Routed both into the
+// `existing<X>Json` prompt variable (bibleExtractor) and into the script
+// stage's bibles context (evaluator). Excludes ids/timestamps/source/notes.
+export const PROMPT_FIELDS = Object.freeze({
+ [BIBLE_KIND.CHARACTER]: ['name', 'aliases', 'role', 'physicalDescription', 'personality', 'background'],
+ [BIBLE_KIND.SETTING]: ['name', 'slugline', 'description', 'palette', 'era', 'weather', 'recurringDetails'],
+ [BIBLE_KIND.OBJECT]: ['name', 'aliases', 'description', 'significance'],
+});
+
+export function pickPromptFields(kind, entry) {
+ const fields = PROMPT_FIELDS[kind];
+ if (!fields || !entry) return {};
+ const out = {};
+ for (const f of fields) out[f] = entry[f];
+ return out;
+}
+
+// Default id prefix per kind. Pipeline accepts these defaults; writers-room
+// passes its own `wr-char-` / `wr-setting-` / `wr-object-` prefixes via the
+// sanitizer options.
+const DEFAULT_ID_PREFIX = Object.freeze({
+ character: 'chr-',
+ setting: 'set-',
+ object: 'obj-',
+});
+
+// Tiny string helpers — exported so adjacent server modules (pipeline
+// series.js, issues.js, etc.) stop redefining the same one-liners.
+export const isStr = (v) => typeof v === 'string';
+export const trimTo = (v, max) => (isStr(v) ? v.trim().slice(0, max) : '');
+const cleanStringArray = (raw, itemMax, listMax) => {
+ if (!Array.isArray(raw)) return [];
+ const out = [];
+ for (const v of raw) {
+ const s = trimTo(v, itemMax);
+ if (s) out.push(s);
+ if (out.length >= listMax) break;
+ }
+ return out;
+};
+
+export const isBlank = (v) => {
+ if (v == null) return true;
+ if (Array.isArray(v)) return v.length === 0;
+ if (isStr(v)) return v.trim() === '';
+ return false;
+};
+
+export const normalizeBibleName = (name) => String(name || '').trim().toLowerCase();
+
+const nowIso = () => new Date().toISOString();
+
+function ensureId(raw, idPrefix) {
+ if (isStr(raw) && raw) return raw;
+ return `${idPrefix}${randomUUID()}`;
+}
+
+function ensureSource(raw) {
+ return SOURCES.has(raw) ? raw : 'user';
+}
+
+function ensureFirstAppearance(raw) {
+ return isStr(raw) && raw.trim() ? raw.trim().slice(0, 200) : null;
+}
+
+// Accepts the writers-room shape natively; legacy pipeline `description`
+// is treated as `physicalDescription` when the latter is empty so old
+// series.json migrates forward on first save. TODO(item-4): drop the
+// `description` fallback once pipeline characters extract natively.
+export function sanitizeCharacter(raw, { idPrefix = DEFAULT_ID_PREFIX.character, preserveTimestamps = true } = {}) {
+ if (!raw || typeof raw !== 'object') return null;
+ const name = trimTo(raw.name, BIBLE_LIMITS.NAME_MAX);
+ if (!name) return null;
+ const physicalDescription = trimTo(
+ raw.physicalDescription || raw.description || '',
+ BIBLE_LIMITS.PHYSICAL_DESCRIPTION_MAX,
+ );
+ const created = preserveTimestamps && isStr(raw.createdAt) ? raw.createdAt : nowIso();
+ return {
+ id: ensureId(raw.id, idPrefix),
+ name,
+ aliases: cleanStringArray(raw.aliases, BIBLE_LIMITS.ALIAS_MAX, BIBLE_LIMITS.ALIASES_PER_ENTRY_MAX),
+ role: trimTo(raw.role, BIBLE_LIMITS.ROLE_MAX),
+ physicalDescription,
+ personality: trimTo(raw.personality, BIBLE_LIMITS.PERSONALITY_MAX),
+ background: trimTo(raw.background, BIBLE_LIMITS.BACKGROUND_MAX),
+ notes: trimTo(raw.notes, BIBLE_LIMITS.NOTES_MAX),
+ imageRefs: cleanStringArray(raw.imageRefs, BIBLE_LIMITS.IMAGE_REF_MAX, BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX),
+ firstAppearance: ensureFirstAppearance(raw.firstAppearance),
+ evidence: cleanStringArray(raw.evidence, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),
+ missingFromProse: cleanStringArray(raw.missingFromProse, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),
+ source: ensureSource(raw.source),
+ createdAt: created,
+ updatedAt: preserveTimestamps && isStr(raw.updatedAt) ? raw.updatedAt : nowIso(),
+ };
+}
+
+export function sanitizeSetting(raw, { idPrefix = DEFAULT_ID_PREFIX.setting, preserveTimestamps = true } = {}) {
+ if (!raw || typeof raw !== 'object') return null;
+ const name = trimTo(raw.name, BIBLE_LIMITS.NAME_MAX);
+ const slugline = trimTo(raw.slugline, BIBLE_LIMITS.SLUGLINE_MAX);
+ // A setting needs at least one identifier (name OR slugline). Without
+ // either there's nothing for a scene matcher to key on.
+ if (!name && !slugline) return null;
+ const created = preserveTimestamps && isStr(raw.createdAt) ? raw.createdAt : nowIso();
+ return {
+ id: ensureId(raw.id, idPrefix),
+ name,
+ slugline,
+ description: trimTo(raw.description, BIBLE_LIMITS.SETTING_DESCRIPTION_MAX),
+ palette: trimTo(raw.palette, BIBLE_LIMITS.PALETTE_MAX),
+ era: trimTo(raw.era, BIBLE_LIMITS.ERA_MAX),
+ weather: trimTo(raw.weather, BIBLE_LIMITS.WEATHER_MAX),
+ recurringDetails: trimTo(raw.recurringDetails, BIBLE_LIMITS.RECURRING_DETAILS_MAX),
+ notes: trimTo(raw.notes, BIBLE_LIMITS.NOTES_MAX),
+ firstAppearance: ensureFirstAppearance(raw.firstAppearance),
+ evidence: cleanStringArray(raw.evidence, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),
+ missingFromProse: cleanStringArray(raw.missingFromProse, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),
+ source: ensureSource(raw.source),
+ createdAt: created,
+ updatedAt: preserveTimestamps && isStr(raw.updatedAt) ? raw.updatedAt : nowIso(),
+ };
+}
+
+export function sanitizeObject(raw, { idPrefix = DEFAULT_ID_PREFIX.object, preserveTimestamps = true } = {}) {
+ if (!raw || typeof raw !== 'object') return null;
+ const name = trimTo(raw.name, BIBLE_LIMITS.NAME_MAX);
+ if (!name) return null;
+ const created = preserveTimestamps && isStr(raw.createdAt) ? raw.createdAt : nowIso();
+ return {
+ id: ensureId(raw.id, idPrefix),
+ name,
+ aliases: cleanStringArray(raw.aliases, BIBLE_LIMITS.ALIAS_MAX, BIBLE_LIMITS.ALIASES_PER_ENTRY_MAX),
+ description: trimTo(raw.description, BIBLE_LIMITS.OBJECT_DESCRIPTION_MAX),
+ significance: trimTo(raw.significance, BIBLE_LIMITS.SIGNIFICANCE_MAX),
+ notes: trimTo(raw.notes, BIBLE_LIMITS.NOTES_MAX),
+ firstAppearance: ensureFirstAppearance(raw.firstAppearance),
+ evidence: cleanStringArray(raw.evidence, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),
+ missingFromProse: cleanStringArray(raw.missingFromProse, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),
+ source: ensureSource(raw.source),
+ createdAt: created,
+ updatedAt: preserveTimestamps && isStr(raw.updatedAt) ? raw.updatedAt : nowIso(),
+ };
+}
+
+/**
+ * Apply the per-kind sanitizer to a raw array, dropping rejected entries
+ * and capping at ENTRIES_PER_BIBLE_MAX. Used by the pipeline series-state
+ * loader and (eventually) by the writers-room file loaders so both sides
+ * agree on what an on-disk bible looks like.
+ */
+export function sanitizeBibleList(rawList, kind, opts = {}) {
+ if (!Array.isArray(rawList)) return [];
+ const sanitizer = SANITIZERS[kind];
+ if (!sanitizer) return [];
+ const out = [];
+ for (const raw of rawList) {
+ const s = sanitizer(raw, opts);
+ if (!s) continue;
+ out.push(s);
+ if (out.length >= BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX) break;
+ }
+ return out;
+}
+
+const SANITIZERS = Object.freeze({
+ character: sanitizeCharacter,
+ setting: sanitizeSetting,
+ object: sanitizeObject,
+});
+
+// Per-kind merge config:
+// userEditable — fields filled only when blank on the existing entry
+// keyFields — which fields contribute to the dedup lookup map, paired
+// with the normalizer to use for each (sluglines need em-dash/hyphen
+// collapsing; names just need lowercase+trim)
+// Blank key fields are also backfilled from incoming and trigger re-index
+// so a later entry in the same batch resolves to the canonical record.
+const MERGE_CONFIG = Object.freeze({
+ character: {
+ userEditable: ['role', 'physicalDescription', 'personality', 'background'],
+ keyFields: [
+ { field: 'name', normalize: normalizeBibleName },
+ { field: 'aliases', normalize: normalizeBibleName },
+ ],
+ },
+ setting: {
+ userEditable: ['description', 'palette', 'era', 'weather', 'recurringDetails'],
+ keyFields: [
+ { field: 'slugline', normalize: normalizeSlugline },
+ { field: 'name', normalize: normalizeSlugline },
+ ],
+ },
+ object: {
+ userEditable: ['description', 'significance'],
+ keyFields: [
+ { field: 'name', normalize: normalizeBibleName },
+ { field: 'aliases', normalize: normalizeBibleName },
+ ],
+ },
+});
+
+function indexEntry(map, entry, keyFields) {
+ for (const { field, normalize } of keyFields) {
+ const val = entry[field];
+ if (Array.isArray(val)) {
+ for (const v of val) {
+ const k = normalize(v);
+ if (k) map.set(k, entry);
+ }
+ } else {
+ const k = normalize(val);
+ if (k) map.set(k, entry);
+ }
+ }
+}
+
+function lookupExisting(map, incoming, keyFields) {
+ for (const { field, normalize } of keyFields) {
+ const val = incoming[field];
+ if (!val) continue;
+ if (Array.isArray(val)) {
+ for (const v of val) {
+ const found = map.get(normalize(v));
+ if (found) return found;
+ }
+ } else {
+ const found = map.get(normalize(val));
+ if (found) return found;
+ }
+ }
+ return null;
+}
+
+// Sort key per kind. Settings can legitimately have an empty `name` while
+// `slugline` is the primary identifier (scene-matcher keys on it), so a
+// pure name-sort drifts all slugline-only entries to the top of the list
+// AND diverges from `writersRoom/settings.js#listSettings` which uses
+// `slugline || name`. Characters / objects always have a name; key on it.
+const sortKey = (kind) => (entry) => {
+ if (kind === BIBLE_KIND.SETTING) return (entry.slugline || entry.name || '').toLowerCase();
+ return (entry.name || '').toLowerCase();
+};
+
+/**
+ * Merge AI-extracted entries into a bible array. Mutates and returns
+ * `existing`, sorted by the kind-specific key (`slugline || name` for
+ * settings, `name` for characters/objects — matches the per-kind list
+ * helpers so callers don't observe an ordering flip after a merge).
+ * Per-kind rules in `MERGE_CONFIG`:
+ * - match by case-insensitive name/alias/slugline
+ * - user-editable fields fill only when blank on the existing entry
+ * - prose-derived fields (firstAppearance/evidence/missingFromProse)
+ * refresh verbatim including explicit nulls
+ * - blank key fields backfill from incoming + re-index
+ */
+export function mergeExtractedBible(existing, incoming, kind, { idPrefix = DEFAULT_ID_PREFIX[kind] } = {}) {
+ if (!Array.isArray(existing)) existing = [];
+ const keyOf = sortKey(kind);
+ if (!Array.isArray(incoming)) {
+ return [...existing].sort((a, b) => keyOf(a).localeCompare(keyOf(b)));
+ }
+ const cfg = MERGE_CONFIG[kind];
+ if (!cfg) throw new Error(`mergeExtractedBible: unknown kind "${kind}"`);
+ const sanitizer = SANITIZERS[kind];
+ const map = new Map();
+ for (const e of existing) indexEntry(map, e, cfg.keyFields);
+
+ for (const rawIncoming of incoming) {
+ if (!rawIncoming || typeof rawIncoming !== 'object') continue;
+ // Sanitize the incoming entry through the same shape the existing
+ // entries went through. Drops malformed rows and gives downstream code
+ // a consistent shape to merge into.
+ const sane = sanitizer(rawIncoming, { idPrefix, preserveTimestamps: false });
+ if (!sane) continue;
+ const found = lookupExisting(map, sane, cfg.keyFields);
+ if (found) {
+ for (const field of cfg.userEditable) {
+ if (isBlank(found[field]) && !isBlank(sane[field])) {
+ found[field] = sane[field];
+ }
+ }
+ // Backfill any blank key field (slugline, name, aliases) and re-index
+ // so a later entry in the same batch keyed by the just-filled value
+ // resolves to this canonical record instead of inserting a duplicate.
+ let reindex = false;
+ for (const { field } of cfg.keyFields) {
+ if (isBlank(found[field]) && !isBlank(sane[field])) {
+ found[field] = sane[field];
+ reindex = true;
+ }
+ }
+ if (reindex) indexEntry(map, found, cfg.keyFields);
+ // Prose-derived fields refresh verbatim — but only when the extractor
+ // actually emitted them. A partial LLM response that omits these keys
+ // entirely would otherwise clear prior data, since the sanitizer
+ // normalizes missing keys to null/[]. Explicit null/[] in rawIncoming
+ // still wins (the "refresh verbatim including explicit nulls" rule).
+ if ('firstAppearance' in rawIncoming) found.firstAppearance = sane.firstAppearance;
+ if ('evidence' in rawIncoming) found.evidence = sane.evidence;
+ if ('missingFromProse' in rawIncoming) found.missingFromProse = sane.missingFromProse;
+ found.updatedAt = nowIso();
+ } else {
+ // Refuse new inserts past the per-bible cap so a runaway extraction
+ // can't grow `existing` past what `sanitizeBibleList` would re-load.
+ // Without this, the merged entries would silently truncate on next
+ // read.
+ if (existing.length >= BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX) continue;
+ const inserted = { ...sane, source: 'ai' };
+ existing.push(inserted);
+ indexEntry(map, inserted, cfg.keyFields);
+ }
+ }
+
+ return existing.sort((a, b) => keyOf(a).localeCompare(keyOf(b)));
+}
diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.js
new file mode 100644
index 0000000000..70e1f48710
--- /dev/null
+++ b/server/lib/storyBible.test.js
@@ -0,0 +1,281 @@
+import { describe, it, expect } from 'vitest';
+import {
+ sanitizeCharacter,
+ sanitizeSetting,
+ sanitizeObject,
+ sanitizeBibleList,
+ mergeExtractedBible,
+ isBlank,
+ normalizeBibleName,
+ BIBLE_LIMITS,
+} from './storyBible.js';
+
+describe('storyBible — sanitizeCharacter', () => {
+ it('returns null when name is blank or input is not an object', () => {
+ expect(sanitizeCharacter(null)).toBeNull();
+ expect(sanitizeCharacter('string')).toBeNull();
+ expect(sanitizeCharacter({ name: '' })).toBeNull();
+ expect(sanitizeCharacter({ name: ' ' })).toBeNull();
+ });
+
+ it('back-compat: accepts pipeline-shape `description` and migrates to `physicalDescription`', () => {
+ const out = sanitizeCharacter({ name: 'Aria', description: 'tall, dark hair' });
+ expect(out.physicalDescription).toBe('tall, dark hair');
+ });
+
+ it('prefers explicit `physicalDescription` over legacy `description` when both present', () => {
+ const out = sanitizeCharacter({ name: 'Aria', description: 'old', physicalDescription: 'new' });
+ expect(out.physicalDescription).toBe('new');
+ });
+
+ it('preserves writers-room-shape rich fields', () => {
+ const out = sanitizeCharacter({
+ name: 'Marcus',
+ aliases: ['Marc', 'Big M'],
+ role: 'antagonist',
+ physicalDescription: 'broad shoulders, scar',
+ personality: 'taciturn',
+ background: 'ex-military',
+ notes: 'do not kill',
+ evidence: ['ch1: enters bar'],
+ missingFromProse: ['ever named'],
+ firstAppearance: 'seg-003',
+ source: 'ai',
+ });
+ expect(out.role).toBe('antagonist');
+ expect(out.aliases).toEqual(['Marc', 'Big M']);
+ expect(out.evidence).toEqual(['ch1: enters bar']);
+ expect(out.firstAppearance).toBe('seg-003');
+ expect(out.source).toBe('ai');
+ });
+
+ it('caps long fields and array sizes', () => {
+ const long = 'x'.repeat(BIBLE_LIMITS.PHYSICAL_DESCRIPTION_MAX + 100);
+ const tooMany = Array.from({ length: 30 }, (_, i) => `alias${i}`);
+ const out = sanitizeCharacter({ name: 'A', physicalDescription: long, aliases: tooMany });
+ expect(out.physicalDescription.length).toBe(BIBLE_LIMITS.PHYSICAL_DESCRIPTION_MAX);
+ expect(out.aliases.length).toBe(BIBLE_LIMITS.ALIASES_PER_ENTRY_MAX);
+ });
+
+ it('generates an id with the requested prefix when missing, preserves explicit id', () => {
+ const generated = sanitizeCharacter({ name: 'A' }, { idPrefix: 'chr-' });
+ expect(generated.id).toMatch(/^chr-/);
+ const preserved = sanitizeCharacter({ id: 'wr-char-existing', name: 'A' });
+ expect(preserved.id).toBe('wr-char-existing');
+ });
+
+ it('coerces invalid source to `user`', () => {
+ expect(sanitizeCharacter({ name: 'A', source: 'evil' }).source).toBe('user');
+ });
+
+ it('drops empty / non-string aliases', () => {
+ const out = sanitizeCharacter({ name: 'A', aliases: ['', ' ', null, 42, 'real'] });
+ expect(out.aliases).toEqual(['real']);
+ });
+});
+
+describe('storyBible — sanitizeSetting', () => {
+ it('requires either name or slugline', () => {
+ expect(sanitizeSetting({ description: 'x' })).toBeNull();
+ expect(sanitizeSetting({ name: 'A bar' }).name).toBe('A bar');
+ expect(sanitizeSetting({ slugline: 'INT. BAR — NIGHT' }).slugline).toBe('INT. BAR — NIGHT');
+ });
+
+ it('preserves all fields and caps lengths', () => {
+ const out = sanitizeSetting({
+ slugline: 'INT. BAR — NIGHT',
+ name: 'The Foundry',
+ description: 'cramped chrome bar',
+ palette: 'amber, neon-red',
+ era: '2049',
+ weather: 'persistent rain outside',
+ recurringDetails: 'broken jukebox',
+ notes: 'returns in arc 2',
+ evidence: ['ch1: opens here'],
+ });
+ expect(out.slugline).toBe('INT. BAR — NIGHT');
+ expect(out.palette).toBe('amber, neon-red');
+ expect(out.evidence).toEqual(['ch1: opens here']);
+ });
+});
+
+describe('storyBible — sanitizeObject', () => {
+ it('requires name', () => {
+ expect(sanitizeObject({ description: 'x' })).toBeNull();
+ });
+
+ it('preserves significance + aliases', () => {
+ const out = sanitizeObject({ name: 'The Locket', aliases: ['locket'], description: 'silver, dented', significance: 'mother\'s' });
+ expect(out.name).toBe('The Locket');
+ expect(out.significance).toBe("mother's");
+ expect(out.aliases).toEqual(['locket']);
+ });
+});
+
+describe('storyBible — sanitizeBibleList', () => {
+ it('drops malformed entries and caps to ENTRIES_PER_BIBLE_MAX', () => {
+ const list = [
+ { name: 'A' },
+ { name: '' }, // dropped (blank name)
+ null, // dropped (non-object)
+ { name: 'B', description: 'tall' },
+ ...Array.from({ length: BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX + 50 }, (_, i) => ({ name: `pad-${i}` })),
+ ];
+ const out = sanitizeBibleList(list, 'character');
+ expect(out.length).toBe(BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX);
+ expect(out[0].name).toBe('A');
+ expect(out[1].name).toBe('B');
+ });
+
+ it('returns [] for non-array input or unknown kind', () => {
+ expect(sanitizeBibleList(null, 'character')).toEqual([]);
+ expect(sanitizeBibleList([{ name: 'A' }], 'noSuchKind')).toEqual([]);
+ });
+});
+
+describe('storyBible — mergeExtractedBible (characters)', () => {
+ const baseExisting = () => [
+ sanitizeCharacter({ id: 'c1', name: 'Aria', physicalDescription: 'tall, dark hair', source: 'user' }),
+ ];
+
+ it('fills only blank user-editable fields on an existing entry, keeping non-blank user content', () => {
+ const existing = baseExisting();
+ const incoming = [
+ { name: 'Aria', physicalDescription: 'short, redhead', personality: 'guarded', background: 'ex-bartender' },
+ ];
+ const merged = mergeExtractedBible(existing, incoming, 'character');
+ const aria = merged.find((c) => c.name === 'Aria');
+ expect(aria.physicalDescription).toBe('tall, dark hair'); // user wins
+ expect(aria.personality).toBe('guarded'); // was blank → filled
+ expect(aria.background).toBe('ex-bartender');
+ });
+
+ it('inserts new characters with source=ai', () => {
+ const merged = mergeExtractedBible(baseExisting(), [{ name: 'Marcus', physicalDescription: 'broad shoulders' }], 'character');
+ const marcus = merged.find((c) => c.name === 'Marcus');
+ expect(marcus.source).toBe('ai');
+ expect(marcus.physicalDescription).toBe('broad shoulders');
+ });
+
+ it('matches by alias on the incoming side and dedupes within a batch', () => {
+ const existing = [sanitizeCharacter({ id: 'c1', name: 'Aria Reyes', aliases: ['Aria', 'The Bartender'], physicalDescription: 'tall' })];
+ const merged = mergeExtractedBible(existing, [
+ { name: 'Aria', personality: 'guarded' }, // matches alias
+ { name: 'the bartender', background: 'ex-marine' }, // also matches alias
+ ], 'character');
+ expect(merged.length).toBe(1);
+ expect(merged[0].personality).toBe('guarded');
+ expect(merged[0].background).toBe('ex-marine');
+ });
+
+ it('refreshes prose-derived fields verbatim, including null firstAppearance', () => {
+ const existing = [sanitizeCharacter({ id: 'c1', name: 'Aria', physicalDescription: 'tall', firstAppearance: 'seg-001', evidence: ['old'], missingFromProse: ['old gap'] })];
+ const merged = mergeExtractedBible(existing, [{ name: 'Aria', firstAppearance: null, evidence: ['new'], missingFromProse: [] }], 'character');
+ expect(merged[0].firstAppearance).toBeNull();
+ expect(merged[0].evidence).toEqual(['new']);
+ expect(merged[0].missingFromProse).toEqual([]);
+ });
+
+ it('backfills aliases on an entry that previously had none, then reindexes', () => {
+ const existing = [sanitizeCharacter({ id: 'c1', name: 'Aria', physicalDescription: 'tall' })];
+ const merged = mergeExtractedBible(existing, [
+ { name: 'Aria', aliases: ['Reyes'] },
+ { name: 'Reyes', personality: 'sharp' }, // should resolve to Aria via the just-backfilled alias
+ ], 'character');
+ expect(merged.length).toBe(1);
+ expect(merged[0].aliases).toEqual(['Reyes']);
+ expect(merged[0].personality).toBe('sharp');
+ });
+
+ it('skips malformed incoming rows', () => {
+ const merged = mergeExtractedBible([], [null, { /* no name */ }, { name: 'A' }], 'character');
+ expect(merged.length).toBe(1);
+ expect(merged[0].name).toBe('A');
+ });
+
+ it('refuses inserts past ENTRIES_PER_BIBLE_MAX so merged data does not silently truncate on next read', () => {
+ const existing = Array.from({ length: BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX }, (_, i) => sanitizeCharacter({ name: `seed-${i}` }));
+ const incoming = Array.from({ length: 5 }, (_, i) => ({ name: `new-${i}` }));
+ const merged = mergeExtractedBible(existing, incoming, 'character');
+ expect(merged.length).toBe(BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX);
+ });
+});
+
+describe('storyBible — mergeExtractedBible (settings)', () => {
+ it('matches by slugline, fills blank fields only', () => {
+ const existing = [sanitizeSetting({ id: 's1', slugline: 'INT. BAR — NIGHT', description: 'cramped chrome bar', palette: '', recurringDetails: '' })];
+ const merged = mergeExtractedBible(existing, [
+ { slugline: 'INT. BAR — NIGHT', description: 'overwrite attempt', palette: 'amber', recurringDetails: 'jukebox' },
+ ], 'setting');
+ expect(merged[0].description).toBe('cramped chrome bar'); // user wins
+ expect(merged[0].palette).toBe('amber');
+ expect(merged[0].recurringDetails).toBe('jukebox');
+ });
+
+ it('matches with em-dash / hyphen drift on the slugline', () => {
+ const existing = [sanitizeSetting({ id: 's1', slugline: 'INT. BAR — NIGHT', description: 'cramped' })];
+ const merged = mergeExtractedBible(existing, [{ slugline: 'INT BAR - NIGHT', recurringDetails: 'jukebox' }], 'setting');
+ expect(merged.length).toBe(1);
+ expect(merged[0].recurringDetails).toBe('jukebox');
+ });
+
+ // Settings can legitimately have an empty `name` (slugline is the primary
+ // identifier). Sorting by `name` would float every slugline-only entry to
+ // the top AND diverge from `writersRoom/settings.js#listSettings`'s
+ // `slugline || name` order. Keep the merge sort kind-aware so the API is
+ // consistent and callers don't observe an ordering flip after a merge.
+ it('sorts settings by slugline (or name as fallback), not by name alone', () => {
+ const existing = [
+ sanitizeSetting({ id: 's1', slugline: 'INT. ZINC FOUNDRY — NIGHT' }),
+ sanitizeSetting({ id: 's2', name: 'Alpha Lab' }), // name-only
+ sanitizeSetting({ id: 's3', slugline: 'EXT. BEACH — DAWN' }),
+ ];
+ const merged = mergeExtractedBible(existing, [], 'setting');
+ // Keys (slugline || name) → 'alpha lab', 'ext. beach — dawn', 'int. zinc foundry — night'
+ expect(merged.map((e) => e.slugline || e.name)).toEqual([
+ 'Alpha Lab',
+ 'EXT. BEACH — DAWN',
+ 'INT. ZINC FOUNDRY — NIGHT',
+ ]);
+ });
+
+ it('character/object merges still sort by name (regression guard)', () => {
+ const chars = [
+ sanitizeCharacter({ id: 'c1', name: 'Zara', physicalDescription: 'tall' }),
+ sanitizeCharacter({ id: 'c2', name: 'Alice', physicalDescription: 'short' }),
+ ];
+ const mergedChars = mergeExtractedBible(chars, [], 'character');
+ expect(mergedChars.map((e) => e.name)).toEqual(['Alice', 'Zara']);
+
+ const objs = [
+ sanitizeObject({ id: 'o1', name: 'Zenith Coin' }),
+ sanitizeObject({ id: 'o2', name: 'Amulet' }),
+ ];
+ const mergedObjs = mergeExtractedBible(objs, [], 'object');
+ expect(mergedObjs.map((e) => e.name)).toEqual(['Amulet', 'Zenith Coin']);
+ });
+});
+
+describe('storyBible — mergeExtractedBible (objects)', () => {
+ it('fills description + significance only when blank', () => {
+ const existing = [sanitizeObject({ id: 'o1', name: 'The Locket', description: 'silver dented', significance: '' })];
+ const merged = mergeExtractedBible(existing, [{ name: 'The Locket', description: 'try overwrite', significance: 'mother\'s' }], 'object');
+ expect(merged[0].description).toBe('silver dented');
+ expect(merged[0].significance).toBe("mother's");
+ });
+});
+
+describe('storyBible — helpers', () => {
+ it('isBlank covers null, empty array, whitespace string', () => {
+ expect(isBlank(null)).toBe(true);
+ expect(isBlank(' ')).toBe(true);
+ expect(isBlank([])).toBe(true);
+ expect(isBlank('x')).toBe(false);
+ expect(isBlank(['x'])).toBe(false);
+ });
+
+ it('normalizeBibleName lowercases + trims', () => {
+ expect(normalizeBibleName(' Aria Reyes ')).toBe('aria reyes');
+ expect(normalizeBibleName(null)).toBe('');
+ });
+});
diff --git a/server/routes/creativeDirector.js b/server/routes/creativeDirector.js
index a741bca13b..4fde32eecf 100644
--- a/server/routes/creativeDirector.js
+++ b/server/routes/creativeDirector.js
@@ -34,10 +34,33 @@ router.get('/', asyncHandler(async (_req, res) => {
res.json(await listProjects());
}));
+// Slim projection of a project for polling consumers (pipeline EpisodeVideoStage
+// polls every 4s; the full project carries an unbounded `runs[]` history that
+// grows with every render operation). The shape covers exactly what the
+// polling UI consumes: status, updatedAt (change-detect key), per-scene
+// sceneId/order/status, finalVideoId, failureReason. `sceneId` (not `id`) is
+// the canonical scene identifier per services/creativeDirector/local.js.
+function slimProject(p) {
+ return {
+ id: p.id,
+ status: p.status,
+ updatedAt: p.updatedAt,
+ finalVideoId: p.finalVideoId || null,
+ failureReason: p.failureReason || null,
+ treatment: {
+ scenes: (p.treatment?.scenes || []).map((s) => ({
+ sceneId: s.sceneId,
+ order: s.order,
+ status: s.status,
+ })),
+ },
+ };
+}
+
router.get('/:id', asyncHandler(async (req, res) => {
const p = await getProject(req.params.id);
if (!p) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
- res.json(p);
+ res.json(req.query.slim === '1' ? slimProject(p) : p);
}));
router.post('/', asyncHandler(async (req, res) => {
diff --git a/server/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.js
index 203aeeca12..fb043ea5f7 100644
--- a/server/routes/creativeDirector.test.js
+++ b/server/routes/creativeDirector.test.js
@@ -52,6 +52,53 @@ describe('creativeDirector routes', () => {
expect(r.status).toBe(200);
expect(r.body.id).toBe('cd-1');
});
+
+ it('with ?slim=1 drops runs[] + full treatment, keeps poll-essential fields', async () => {
+ cdService.getProject.mockResolvedValue({
+ id: 'cd-1', name: 'A', status: 'rendering', updatedAt: '2026-05-10T10:00:00Z',
+ finalVideoId: null, failureReason: null,
+ styleSpec: 'big blob of style notes that polling consumers do not need',
+ runs: Array.from({ length: 50 }, (_, i) => ({ id: `run-${i}`, prompt: 'big payload' })),
+ treatment: {
+ logline: 'big logline text',
+ synopsis: 'big synopsis text',
+ scenes: [
+ { sceneId: 's1', order: 0, status: 'accepted', intent: 'long intent text', visualPrompt: 'long prompt' },
+ { sceneId: 's2', order: 1, status: 'rendering', intent: 'longer text', visualPrompt: 'longer prompt' },
+ ],
+ },
+ });
+ const r = await request(app).get('/api/creative-director/cd-1?slim=1');
+ expect(r.status).toBe(200);
+ expect(r.body).toEqual({
+ id: 'cd-1',
+ status: 'rendering',
+ updatedAt: '2026-05-10T10:00:00Z',
+ finalVideoId: null,
+ failureReason: null,
+ treatment: {
+ scenes: [
+ { sceneId: 's1', order: 0, status: 'accepted' },
+ { sceneId: 's2', order: 1, status: 'rendering' },
+ ],
+ },
+ });
+ expect(r.body.runs).toBeUndefined();
+ expect(r.body.styleSpec).toBeUndefined();
+ expect(r.body.treatment.logline).toBeUndefined();
+ expect(r.body.treatment.scenes[0].intent).toBeUndefined();
+ });
+
+ it('slim mode tolerates a project with no treatment (empty scenes array)', async () => {
+ cdService.getProject.mockResolvedValue({
+ id: 'cd-2', status: 'draft', updatedAt: 'now',
+ });
+ const r = await request(app).get('/api/creative-director/cd-2?slim=1');
+ expect(r.status).toBe(200);
+ expect(r.body.treatment).toEqual({ scenes: [] });
+ expect(r.body.finalVideoId).toBeNull();
+ expect(r.body.failureReason).toBeNull();
+ });
});
describe('POST /', () => {
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index cd94646861..b92d66b8f9 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -31,6 +31,10 @@ import * as issuesSvc from '../services/pipeline/issues.js';
import { generateStage } from '../services/pipeline/textStages.js';
import * as autoRunner from '../services/pipeline/autoRunner.js';
import { enqueueVisualImage } from '../services/pipeline/visualStages.js';
+import { startEpisodeVideoForIssue, ERR_NO_STORYBOARDS } from '../services/pipeline/episodeVideo.js';
+import { ASPECT_RATIOS, QUALITIES } from '../lib/creativeDirectorPresets.js';
+import { extractScenes, SOURCE_KIND } from '../lib/sceneExtractor.js';
+import { BIBLE_KIND } from '../lib/storyBible.js';
const router = Router();
@@ -39,6 +43,7 @@ const SERVICE_ERROR_STATUS = {
[seriesSvc.ERR_VALIDATION]: 400,
[issuesSvc.ERR_NOT_FOUND]: 404,
[issuesSvc.ERR_VALIDATION]: 400,
+ [ERR_NO_STORYBOARDS]: 400,
};
const mapServiceError = (err) => {
@@ -49,10 +54,23 @@ const mapServiceError = (err) => {
// ---- Series schemas ----
+// Bible entries are sanitized server-side via the canonical shape in
+// `server/lib/storyBible.js`; the route schema is intentionally permissive
+// (max length only) so additive fields don't require a schema migration.
+const bibleEntrySchema = z.record(z.string(), z.any());
+
const characterSchema = z.object({
id: z.string().trim().max(80).optional(),
name: z.string().trim().min(1).max(seriesSvc.CHARACTER_NAME_MAX),
- description: z.string().trim().max(seriesSvc.CHARACTER_DESCRIPTION_MAX).optional().default(''),
+ // Back-compat: pre-DRY shape used `description`. Both fields are accepted
+ // and the canonical sanitizer normalizes them to `physicalDescription`.
+ description: z.string().trim().max(seriesSvc.CHARACTER_DESCRIPTION_MAX).optional(),
+ physicalDescription: z.string().trim().max(seriesSvc.CHARACTER_DESCRIPTION_MAX).optional(),
+ aliases: z.array(z.string().trim().min(1).max(100)).max(12).optional(),
+ role: z.string().trim().max(200).optional(),
+ personality: z.string().trim().max(2000).optional(),
+ background: z.string().trim().max(2000).optional(),
+ notes: z.string().trim().max(4000).optional(),
imageRefs: z.array(z.string().trim().min(1).max(seriesSvc.IMAGE_REF_MAX))
.max(seriesSvc.IMAGE_REFS_PER_CHARACTER_MAX).optional(),
});
@@ -62,7 +80,10 @@ const seriesCreateSchema = z.object({
logline: z.string().trim().max(seriesSvc.LOGLINE_MAX).optional().default(''),
premise: z.string().trim().max(seriesSvc.PREMISE_MAX).optional().default(''),
worldId: z.string().trim().max(seriesSvc.WORLD_ID_MAX).nullable().optional(),
- characters: z.array(characterSchema).max(seriesSvc.CHARACTERS_PER_SERIES_MAX).optional(),
+ writersRoomWorkId: z.string().trim().max(seriesSvc.WRITERS_ROOM_WORK_ID_MAX).nullable().optional(),
+ characters: z.array(characterSchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
+ settings: z.array(bibleEntrySchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
+ objects: z.array(bibleEntrySchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
styleNotes: z.string().trim().max(seriesSvc.STYLE_NOTES_MAX).optional().default(''),
targetFormat: z.enum(seriesSvc.TARGET_FORMATS).optional(),
issueCountTarget: z.number().int().min(0).max(seriesSvc.ISSUE_COUNT_TARGET_MAX).optional(),
@@ -73,7 +94,10 @@ const seriesPatchSchema = z.object({
logline: z.string().trim().max(seriesSvc.LOGLINE_MAX).optional(),
premise: z.string().trim().max(seriesSvc.PREMISE_MAX).optional(),
worldId: z.string().trim().max(seriesSvc.WORLD_ID_MAX).nullable().optional(),
- characters: z.array(characterSchema).max(seriesSvc.CHARACTERS_PER_SERIES_MAX).optional(),
+ writersRoomWorkId: z.string().trim().max(seriesSvc.WRITERS_ROOM_WORK_ID_MAX).nullable().optional(),
+ characters: z.array(characterSchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
+ settings: z.array(bibleEntrySchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
+ objects: z.array(bibleEntrySchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
styleNotes: z.string().trim().max(seriesSvc.STYLE_NOTES_MAX).optional(),
targetFormat: z.enum(seriesSvc.TARGET_FORMATS).optional(),
issueCountTarget: z.number().int().min(0).max(seriesSvc.ISSUE_COUNT_TARGET_MAX).optional(),
@@ -102,13 +126,20 @@ const visualStageInputSchema = stageInputSchema.extend({
scenes: z.array(z.any()).max(200).optional(),
cdProjectId: z.string().trim().max(64).nullable().optional(),
videoPath: z.string().trim().max(1000).nullable().optional(),
+ aspectRatio: z.enum(ASPECT_RATIOS).nullable().optional(),
+ quality: z.enum(QUALITIES).nullable().optional(),
});
const issuePatchSchema = z.object({
title: z.string().trim().min(1).max(issuesSvc.TITLE_MAX).optional(),
number: z.number().int().min(1).max(9999).optional(),
status: z.enum(issuesSvc.ISSUE_STATUSES).optional(),
- stages: z.record(z.string(), z.union([stageInputSchema, visualStageInputSchema])).optional(),
+ // Use visualStageInputSchema as the union arm so visual-stage payloads keep
+ // their `scenes` / `pages` / `cdProjectId` / `videoPath` fields. The schema
+ // is a superset of stageInputSchema (those four are optional additions), so
+ // text-stage patches still validate. Z.union picks the first schema that
+ // succeeds — stageInputSchema first would silently strip the visual fields.
+ stages: z.record(z.string(), z.union([visualStageInputSchema, stageInputSchema])).optional(),
}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });
const generateSchema = z.object({
@@ -119,6 +150,8 @@ const generateSchema = z.object({
const visualGenerateSchema = z.object({
description: z.string().trim().min(1).max(8000),
+ // Matched against the series settings bible when present.
+ slugline: z.string().trim().max(200).optional(),
negativePrompt: z.string().trim().max(2000).optional(),
extraStyle: z.string().trim().max(2000).optional(),
mode: z.enum(['local', 'codex']).optional(),
@@ -130,10 +163,51 @@ const visualGenerateSchema = z.object({
guidance: z.number().min(0).max(30).optional(),
});
+const episodeVideoSchema = z.object({
+ aspectRatio: z.enum(ASPECT_RATIOS).optional(),
+ quality: z.enum(QUALITIES).optional(),
+ modelId: z.string().trim().max(64).optional(),
+ force: z.boolean().optional(),
+});
+
+// Source for scene extraction: which text stage to read from (`prose` →
+// granular paragraph-grain breakdown via `writers-room-script`; `tvScript`
+// → slugline-grain parse via `pipeline-extract-scenes`). `force` overrides
+// the "you have N hand-curated scenes already" guard.
+// Enum values match `SOURCE_KIND` verbatim so the route forwards `body.from`
+// straight through — same string also names the issue's text stage.
+const extractScenesSchema = z.object({
+ from: z.enum([SOURCE_KIND.PROSE, SOURCE_KIND.TV_SCRIPT]).optional().default(SOURCE_KIND.TV_SCRIPT),
+ providerOverride: z.string().trim().max(80).optional(),
+ force: z.boolean().optional(),
+});
+
+// Source: `issueId` (pulls `stages.prose.output`) OR explicit `corpus` text.
+// `parallel: true` runs the three bible kinds concurrently (~3× wall-clock
+// speedup on HTTP-API providers like OpenAI/Anthropic/LM Studio HTTP).
+// Default stays sequential — safe for CLI providers that serialize at the
+// session anyway (codex / claude-code / gemini-cli).
+const extractBibleSchema = z.object({
+ kinds: z.array(z.enum([BIBLE_KIND.CHARACTER, BIBLE_KIND.SETTING, BIBLE_KIND.OBJECT]))
+ .min(1).max(3).optional()
+ .default([BIBLE_KIND.CHARACTER, BIBLE_KIND.SETTING, BIBLE_KIND.OBJECT]),
+ issueId: z.string().trim().max(64).optional(),
+ corpus: z.string().min(1).max(issuesSvc.STAGE_OUTPUT_MAX).optional(),
+ providerOverride: z.string().trim().max(80).optional(),
+ parallel: z.boolean().optional(),
+}).refine((p) => p.issueId || p.corpus, { message: 'extract requires either `issueId` or `corpus`' });
+
const autoRunSchema = z.object({
providerId: z.string().trim().max(80).optional(),
model: z.string().trim().max(200).optional(),
force: z.boolean().optional(),
+ // Optional opt-in to extend the auto-run past text stages: kicks off the
+ // episodeVideo handoff to Creative Director once scripts are done. Burns
+ // GPU minutes, so default is off.
+ includeVideo: z.boolean().optional(),
+ aspectRatio: z.enum(ASPECT_RATIOS).optional(),
+ quality: z.enum(QUALITIES).optional(),
+ modelId: z.string().trim().max(64).optional(),
});
// =====================
@@ -160,6 +234,37 @@ router.patch('/series/:id', asyncHandler(async (req, res) => {
res.json(s);
}));
+router.post('/series/:id/extract-bible', asyncHandler(async (req, res) => {
+ const body = validateRequest(extractBibleSchema, req.body ?? {});
+ // Validate series exists up front so a typo returns 404 instead of bubbling
+ // out of the service-layer call below.
+ const series = await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+
+ let corpus = (body.corpus || '').trim();
+ if (!corpus) {
+ const issue = await issuesSvc.getIssue(body.issueId).catch((err) => { throw mapServiceError(err); });
+ if (issue.seriesId !== series.id) {
+ throw new ServerError('Issue does not belong to this series', { status: 400, code: 'PIPELINE_ISSUE_SERIES_MISMATCH' });
+ }
+ corpus = (issue.stages?.prose?.output || '').trim();
+ if (!corpus) {
+ throw new ServerError('Issue has no prose to extract from — generate the prose stage first', {
+ status: 400, code: 'PIPELINE_NO_PROSE_FOR_EXTRACTION',
+ });
+ }
+ }
+
+ // Delegate the extract → merge → patch chain to the service layer so
+ // mergeExtractedBible stays a service-internal concern.
+ const result = await seriesSvc.extractAndMergeIntoSeries(series.id, {
+ kinds: body.kinds,
+ corpus,
+ parallel: body.parallel,
+ providerOverride: body.providerOverride,
+ }).catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
router.delete('/series/:id', asyncHandler(async (req, res) => {
const r = await seriesSvc.deleteSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
res.json(r);
@@ -216,6 +321,72 @@ router.post('/issues/:id/stages/:stageId/generate', asyncHandler(async (req, res
res.json(result);
}));
+// Auto-fill stages.storyboards.scenes[] from a text stage. Reads the issue's
+// prose (paragraph-grain) or tvScript (slugline-grain) output, runs the
+// shared scene extractor, and replaces stages.storyboards.scenes with the
+// result mapped to the storyboards UI shape (visualPrompt → description).
+router.post('/issues/:id/stages/storyboards/extract-scenes', asyncHandler(async (req, res) => {
+ const body = validateRequest(extractScenesSchema, req.body ?? {});
+ const issue = await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const series = await seriesSvc.getSeries(issue.seriesId).catch((err) => { throw mapServiceError(err); });
+
+ const sourceKind = body.from;
+ const source = (issue.stages?.[sourceKind]?.output || '').trim();
+ if (!source) {
+ throw new ServerError(
+ `Cannot extract scenes — issue's ${sourceKind} stage is empty`,
+ { status: 400, code: 'PIPELINE_NO_SOURCE_FOR_SCENE_EXTRACT' },
+ );
+ }
+
+ const existing = Array.isArray(issue.stages?.storyboards?.scenes) ? issue.stages.storyboards.scenes : [];
+ if (existing.length > 0 && !body.force) {
+ throw new ServerError(
+ `Storyboards already has ${existing.length} scene${existing.length === 1 ? '' : 's'} — pass { force: true } to replace`,
+ { status: 409, code: 'PIPELINE_STORYBOARDS_NOT_EMPTY' },
+ );
+ }
+
+ const result = await extractScenes({
+ source,
+ sourceKind,
+ characters: series.characters || [],
+ settings: series.settings || [],
+ objects: series.objects || [],
+ work: { title: issue.title, kind: 'tv-episode' },
+ series: { name: series.name, styleNotes: series.styleNotes },
+ issue: { number: issue.number, title: issue.title },
+ providerOverride: body.providerOverride,
+ tag: `pipeline-storyboards-extract-${sourceKind}`,
+ });
+
+ // Adapt canonical scene shape to the pipeline storyboards UI shape: alias
+ // `visualPrompt → description` (the textarea binding) and reset the per-scene
+ // image-gen job fields. Rich fields (heading/summary/dialogue/...) ride along.
+ const storyboardScenes = result.extracted.scenes.map((s) => ({
+ ...s,
+ description: s.visualPrompt || '',
+ imageJobId: null,
+ prompt: null,
+ }));
+ const { issue: updatedIssue, stage } = await issuesSvc.updateStage(issue.id, 'storyboards', {
+ status: storyboardScenes.length ? 'ready' : 'empty',
+ scenes: storyboardScenes,
+ lastRunId: result.runId,
+ errorMessage: '',
+ });
+
+ res.json({
+ issue: updatedIssue,
+ stage,
+ runId: result.runId,
+ providerId: result.providerId,
+ model: result.model,
+ sceneCount: storyboardScenes.length,
+ sourceKind,
+ });
+}));
+
router.post('/issues/:id/stages/:stageId/visual', asyncHandler(async (req, res) => {
const { id, stageId } = req.params;
if (!issuesSvc.VISUAL_STAGE_IDS.includes(stageId)) {
@@ -225,10 +396,10 @@ router.post('/issues/:id/stages/:stageId/visual', asyncHandler(async (req, res)
);
}
if (stageId === 'episodeVideo') {
- throw new ServerError(
- 'Episode-video stitching via Pipeline is not yet implemented — manually trigger from Creative Director for now.',
- { status: 501, code: 'PIPELINE_NOT_IMPLEMENTED' },
- );
+ const body = validateRequest(episodeVideoSchema, req.body ?? {});
+ const result = await startEpisodeVideoForIssue(id, body).catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+ return;
}
const body = validateRequest(visualGenerateSchema, req.body ?? {});
const result = await enqueueVisualImage(id, stageId, body).catch((err) => { throw mapServiceError(err); });
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index 93011e7123..50feeb4875 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -50,6 +50,17 @@ vi.mock('../services/pipeline/visualStages.js', () => ({
})),
}));
+// The episode-video handoff creates a CD project; stub it so the route test
+// doesn't have to spin up the whole CD machinery.
+vi.mock('../services/pipeline/episodeVideo.js', () => ({
+ ERR_NO_STORYBOARDS: 'PIPELINE_EPISODE_NO_STORYBOARDS',
+ startEpisodeVideoForIssue: vi.fn(async (issueId, opts) => ({
+ cdProjectId: `cd-mock-${issueId.slice(0, 6)}`,
+ scenes: 2,
+ reused: opts?.force ? false : false,
+ })),
+}));
+
const pipelineRouter = (await import('./pipeline.js')).default;
function makeApp() {
@@ -140,14 +151,30 @@ describe('pipeline routes', () => {
expect(r.body.mode).toBe('local');
});
- it('POST /issues/:id/stages/episodeVideo/visual returns 501 (deferred)', async () => {
+ it('POST /issues/:id/stages/episodeVideo/visual hands off to Creative Director', async () => {
const app = makeApp();
const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
const r = await request(app)
.post(`/api/pipeline/issues/${iss.body.id}/stages/episodeVideo/visual`)
- .send({ description: 'final stitch' });
- expect(r.status).toBe(501);
+ .send({});
+ expect(r.status).toBe(200);
+ expect(r.body.cdProjectId).toMatch(/^cd-mock-/);
+ expect(r.body.scenes).toBe(2);
+ });
+
+ it('POST /issues/:id/stages/episodeVideo/visual surfaces missing-storyboards as 400', async () => {
+ const ev = await import('../services/pipeline/episodeVideo.js');
+ ev.startEpisodeVideoForIssue.mockImplementationOnce(async () => {
+ throw Object.assign(new Error('Storyboards stage has no scenes with descriptions.'), { code: 'PIPELINE_EPISODE_NO_STORYBOARDS' });
+ });
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/episodeVideo/visual`)
+ .send({});
+ expect(r.status).toBe(400);
});
it('POST /issues/:id/auto-run-text returns runId + sseUrl', async () => {
@@ -165,4 +192,272 @@ describe('pipeline routes', () => {
const r = await request(app).post('/api/pipeline/issues/iss-nope/auto-run-text').send({});
expect(r.status).toBe(404);
});
+
+ it('POST /series/:id/extract-bible 400s when no issueId and no corpus is supplied', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const r = await request(app).post(`/api/pipeline/series/${ser.body.id}/extract-bible`).send({});
+ expect(r.status).toBe(400);
+ });
+
+ it('POST /series/:id/extract-bible 400s when the issue has no prose stage output', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ const r = await request(app)
+ .post(`/api/pipeline/series/${ser.body.id}/extract-bible`)
+ .send({ issueId: iss.body.id });
+ expect(r.status).toBe(400);
+ expect(r.body.error || r.body.message).toMatch(/no prose/i);
+ });
+
+ it('POST /series/:id/extract-bible 400s when the issue belongs to a different series', async () => {
+ const app = makeApp();
+ const ser1 = await request(app).post('/api/pipeline/series').send({ name: 'S1' });
+ const ser2 = await request(app).post('/api/pipeline/series').send({ name: 'S2' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser1.body.id}/issues`).send({ title: 'I' });
+ const r = await request(app)
+ .post(`/api/pipeline/series/${ser2.body.id}/extract-bible`)
+ .send({ issueId: iss.body.id });
+ expect(r.status).toBe(400);
+ });
+
+ it('POST /series/:id/extract-bible runs the requested kinds and merges into the series', async () => {
+ // Stub the bible extractor to skip the LLM call entirely.
+ const extractor = await import('../lib/bibleExtractor.js');
+ const spy = vi.spyOn(extractor, 'extractBible').mockImplementation(async ({ kind }) => ({
+ extracted: kind === 'character'
+ ? [{ name: 'Aria', physicalDescription: 'tall' }]
+ : kind === 'setting'
+ ? [{ slugline: 'INT. FOUNDRY — NIGHT', description: 'molten light' }]
+ : [{ name: 'The Locket', significance: "mother's" }],
+ runId: `run-${kind}`, providerId: 'mock', model: 'mock-model',
+ }));
+
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ // Seed prose
+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
+ stages: { prose: { status: 'ready', output: 'Once upon a time...' } },
+ });
+
+ const r = await request(app)
+ .post(`/api/pipeline/series/${ser.body.id}/extract-bible`)
+ .send({ issueId: iss.body.id, kinds: ['character', 'setting'] });
+
+ expect(r.status).toBe(200);
+ expect(r.body.series.characters[0].name).toBe('Aria');
+ expect(r.body.series.settings[0].slugline).toBe('INT. FOUNDRY — NIGHT');
+ // Objects bible was not requested → still empty
+ expect(r.body.series.objects).toEqual([]);
+ expect(r.body.results.characters.runId).toBe('run-character');
+ expect(spy).toHaveBeenCalledTimes(2);
+ spy.mockRestore();
+ });
+
+ it('POST /series/:id/extract-bible with parallel:true fans all kinds out concurrently', async () => {
+ // Track interleaving by recording per-call start + finish times. In
+ // parallel mode all starts come before any finish; sequential mode has
+ // finish[N] before start[N+1].
+ const extractor = await import('../lib/bibleExtractor.js');
+ const events = [];
+ const spy = vi.spyOn(extractor, 'extractBible').mockImplementation(async ({ kind }) => {
+ events.push({ kind, event: 'start' });
+ await new Promise((r) => setTimeout(r, 30));
+ events.push({ kind, event: 'finish' });
+ return { extracted: [], runId: `run-${kind}`, providerId: 'mock', model: 'mock-model' };
+ });
+
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const r = await request(app)
+ .post(`/api/pipeline/series/${ser.body.id}/extract-bible`)
+ .send({ corpus: 'x', parallel: true });
+
+ expect(r.status).toBe(200);
+ expect(spy).toHaveBeenCalledTimes(3);
+ // Parallel guarantee: every start fired before the first finish.
+ const firstFinishIdx = events.findIndex((e) => e.event === 'finish');
+ const startsBeforeFirstFinish = events.slice(0, firstFinishIdx).filter((e) => e.event === 'start').length;
+ expect(startsBeforeFirstFinish).toBe(3);
+ spy.mockRestore();
+ });
+
+ it('POST /series/:id/extract-bible defaults to sequential (CLI-provider safe)', async () => {
+ const extractor = await import('../lib/bibleExtractor.js');
+ const events = [];
+ const spy = vi.spyOn(extractor, 'extractBible').mockImplementation(async ({ kind }) => {
+ events.push({ kind, event: 'start' });
+ await new Promise((r) => setTimeout(r, 10));
+ events.push({ kind, event: 'finish' });
+ return { extracted: [], runId: `run-${kind}`, providerId: 'mock', model: 'mock-model' };
+ });
+
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const r = await request(app)
+ .post(`/api/pipeline/series/${ser.body.id}/extract-bible`)
+ .send({ corpus: 'x' });
+
+ expect(r.status).toBe(200);
+ expect(spy).toHaveBeenCalledTimes(3);
+ // Sequential: each kind finishes before the next one starts. The events
+ // array must alternate start, finish, start, finish, start, finish.
+ const eventTypes = events.map((e) => e.event);
+ expect(eventTypes).toEqual(['start', 'finish', 'start', 'finish', 'start', 'finish']);
+ spy.mockRestore();
+ });
+
+ it('POST /series/:id/extract-bible dedups duplicate kinds (no extra LLM calls)', async () => {
+ const extractor = await import('../lib/bibleExtractor.js');
+ const calls = [];
+ const spy = vi.spyOn(extractor, 'extractBible').mockImplementation(async ({ kind }) => {
+ calls.push(kind);
+ return { extracted: [], runId: `run-${kind}`, providerId: 'mock', model: 'mock-model' };
+ });
+
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const r = await request(app)
+ .post(`/api/pipeline/series/${ser.body.id}/extract-bible`)
+ .send({ corpus: 'x', kinds: ['character', 'character', 'setting'] });
+
+ expect(r.status).toBe(200);
+ // Duplicates collapsed before the LLM dispatch — 2 calls for 2 unique kinds.
+ expect(spy).toHaveBeenCalledTimes(2);
+ expect(calls.sort()).toEqual(['character', 'setting']);
+ spy.mockRestore();
+ });
+
+ // ---- storyboards/extract-scenes ----
+
+ it('POST /issues/:id/stages/storyboards/extract-scenes 400s when the source stage is empty', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/storyboards/extract-scenes`)
+ .send({ from: 'tvScript' });
+ expect(r.status).toBe(400);
+ expect(r.body.error || r.body.message).toMatch(/empty/i);
+ });
+
+ it('POST /issues/:id/stages/storyboards/extract-scenes 409s when scenes already exist (no force)', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
+ stages: {
+ tvScript: { status: 'ready', output: '## TEASER\n\n**INT. ROOM — NIGHT**\n\nAction.' },
+ storyboards: { scenes: [{ slugline: 'EXT. CITY', description: 'pre-existing' }] },
+ },
+ });
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/storyboards/extract-scenes`)
+ .send({ from: 'tvScript' });
+ expect(r.status).toBe(409);
+ expect(r.body.error || r.body.message).toMatch(/force/i);
+ });
+
+ it('POST /issues/:id/stages/storyboards/extract-scenes runs the extractor and persists scenes (visualPrompt → description)', async () => {
+ const extractor = await import('../lib/sceneExtractor.js');
+ const spy = vi.spyOn(extractor, 'extractScenes').mockResolvedValue({
+ extracted: {
+ title: 'The Pilot', logline: 'A heist gone wrong.',
+ scenes: [
+ { id: 'scene-01', heading: 'Scene 1 — Vault', slugline: 'INT. VAULT — NIGHT', summary: 'They break in.', characters: ['ALICE'], action: 'A drill bites.', dialogue: [{ character: 'ALICE', line: 'Quiet.' }], visualPrompt: 'a high-tech vault, two figures in tactical gear, dim red emergency light', sourceSegmentIds: [] },
+ { id: 'scene-02', heading: 'Scene 2 — Escape', slugline: 'EXT. ROOFTOP — DAWN', summary: '...', characters: [], action: '', dialogue: [], visualPrompt: 'a rooftop at first light, helicopter approaching', sourceSegmentIds: [] },
+ ],
+ },
+ runId: 'run-scenes-1', providerId: 'mock', model: 'mock-model',
+ });
+
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({
+ name: 'S', characters: [{ name: 'Alice', physicalDescription: 'tall, freckles' }],
+ });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
+ stages: { tvScript: { status: 'ready', output: '## TEASER\n\n**INT. VAULT — NIGHT**\n\nThey break in.' } },
+ });
+
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/storyboards/extract-scenes`)
+ .send({ from: 'tvScript' });
+
+ expect(r.status).toBe(200);
+ expect(r.body.sceneCount).toBe(2);
+ expect(r.body.runId).toBe('run-scenes-1');
+ expect(r.body.sourceKind).toBe('tvScript');
+ // visualPrompt → description aliasing for UI compat
+ expect(r.body.stage.scenes[0].description).toBe('a high-tech vault, two figures in tactical gear, dim red emergency light');
+ expect(r.body.stage.scenes[0].slugline).toBe('INT. VAULT — NIGHT');
+ expect(r.body.stage.scenes[0].imageJobId).toBeNull();
+ // Rich fields ride along
+ expect(r.body.stage.scenes[0].heading).toBe('Scene 1 — Vault');
+ expect(r.body.stage.scenes[0].dialogue[0]).toEqual({ character: 'ALICE', line: 'Quiet.' });
+ expect(r.body.stage.lastRunId).toBe('run-scenes-1');
+ expect(r.body.stage.status).toBe('ready');
+
+ // Series characters were forwarded to the extractor for bible deference
+ const firstCall = spy.mock.calls[0][0];
+ expect(firstCall.characters[0].name).toBe('Alice');
+ expect(firstCall.sourceKind).toBe('tvScript');
+ expect(firstCall.series).toEqual({ name: 'S', styleNotes: '' });
+ spy.mockRestore();
+ });
+
+ it('POST /issues/:id/stages/storyboards/extract-scenes with from=prose routes to the prose stage output', async () => {
+ const extractor = await import('../lib/sceneExtractor.js');
+ const spy = vi.spyOn(extractor, 'extractScenes').mockResolvedValue({
+ extracted: { title: null, logline: null, scenes: [{ visualPrompt: 'a paragraph beat' }] },
+ runId: 'run-scenes-2', providerId: 'mock', model: 'mock-model',
+ });
+
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
+ stages: { prose: { status: 'ready', output: 'Once upon a time, a paragraph happened.' } },
+ });
+
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/storyboards/extract-scenes`)
+ .send({ from: 'prose' });
+
+ expect(r.status).toBe(200);
+ expect(r.body.sourceKind).toBe('prose');
+ expect(r.body.sceneCount).toBe(1);
+ const callArgs = spy.mock.calls[0][0];
+ expect(callArgs.source).toBe('Once upon a time, a paragraph happened.');
+ expect(callArgs.sourceKind).toBe('prose');
+ spy.mockRestore();
+ });
+
+ it('POST /issues/:id/stages/storyboards/extract-scenes with force=true overwrites existing scenes', async () => {
+ const extractor = await import('../lib/sceneExtractor.js');
+ const spy = vi.spyOn(extractor, 'extractScenes').mockResolvedValue({
+ extracted: { title: null, logline: null, scenes: [{ visualPrompt: 'fresh scene' }] },
+ runId: 'run-scenes-3', providerId: 'mock', model: 'mock-model',
+ });
+
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
+ stages: {
+ tvScript: { status: 'ready', output: '## TEASER\n\n**INT. ROOM — NIGHT**' },
+ storyboards: { scenes: [{ slugline: 'OLD', description: 'will be replaced' }] },
+ },
+ });
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/storyboards/extract-scenes`)
+ .send({ from: 'tvScript', force: true });
+
+ expect(r.status).toBe(200);
+ expect(r.body.sceneCount).toBe(1);
+ expect(r.body.stage.scenes[0].description).toBe('fresh scene');
+ spy.mockRestore();
+ });
});
diff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.js
index a4454871da..f09d4dec63 100644
--- a/server/routes/writersRoom.js
+++ b/server/routes/writersRoom.js
@@ -4,7 +4,8 @@
*/
import { Router } from 'express';
-import { asyncHandler } from '../lib/errorHandler.js';
+import { z } from 'zod';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import {
validateRequest,
writersRoomFolderCreateSchema,
@@ -41,6 +42,7 @@ import {
import {
listObjects, createObject, updateObject, deleteObject,
} from '../services/writersRoom/objects.js';
+import { promoteWorkToPipeline, ERR_NO_DRAFT_BODY } from '../services/writersRoom/promoteToPipeline.js';
import { addItem as addCollectionItem, ERR_DUPLICATE } from '../services/mediaCollections.js';
const router = Router();
@@ -85,6 +87,21 @@ router.delete('/works/:id', asyncHandler(async (req, res) => {
res.json(await deleteWork(req.params.id));
}));
+// ---------- pipeline bridge (item 6 of the WR↔Pipeline DRY unification) ----------
+
+const promoteSchema = z.object({ force: z.boolean().optional() });
+
+router.post('/works/:id/promote-to-pipeline', asyncHandler(async (req, res) => {
+ const body = validateRequest(promoteSchema, req.body ?? {});
+ const result = await promoteWorkToPipeline(req.params.id, body).catch((err) => {
+ if (err?.code === ERR_NO_DRAFT_BODY) {
+ throw new ServerError(err.message, { status: 400, code: ERR_NO_DRAFT_BODY });
+ }
+ throw err;
+ });
+ res.status(result.reused ? 200 : 201).json(result);
+}));
+
// ---------- draft body / versions ----------
router.put('/works/:id/draft', asyncHandler(async (req, res) => {
diff --git a/server/routes/writersRoom.test.js b/server/routes/writersRoom.test.js
index 2e774b426d..ff794a39a2 100644
--- a/server/routes/writersRoom.test.js
+++ b/server/routes/writersRoom.test.js
@@ -49,6 +49,11 @@ vi.mock('../services/mediaCollections.js', () => ({
ERR_DUPLICATE: 'ERR_DUPLICATE',
}));
+vi.mock('../services/writersRoom/promoteToPipeline.js', () => ({
+ ERR_NO_DRAFT_BODY: 'WR_PROMOTE_NO_DRAFT_BODY',
+ promoteWorkToPipeline: vi.fn(),
+}));
+
import * as svc from '../services/writersRoom/local.js';
import * as charSvc from '../services/writersRoom/characters.js';
import * as settingsSvc from '../services/writersRoom/settings.js';
@@ -278,4 +283,64 @@ describe('writersRoom routes', () => {
expect(settingsSvc.deleteSetting).toHaveBeenCalledWith('wr-work-1', 'wr-setting-1');
});
});
+
+ describe('promote-to-pipeline', () => {
+ it('POST /works/:id/promote-to-pipeline returns 201 with series + issue on fresh promote', async () => {
+ const promoter = await import('../services/writersRoom/promoteToPipeline.js');
+ promoter.promoteWorkToPipeline.mockResolvedValue({
+ series: { id: 'ser-1', name: 'A', writersRoomWorkId: 'wr-work-1' },
+ issue: { id: 'iss-1', seriesId: 'ser-1', title: 'A' },
+ reused: false,
+ });
+
+ const r = await request(app)
+ .post('/api/writers-room/works/wr-work-1/promote-to-pipeline')
+ .send({});
+ expect(r.status).toBe(201);
+ expect(r.body.series.id).toBe('ser-1');
+ expect(r.body.issue.id).toBe('iss-1');
+ expect(r.body.reused).toBe(false);
+ expect(promoter.promoteWorkToPipeline).toHaveBeenCalledWith('wr-work-1', {});
+ });
+
+ it('POST /works/:id/promote-to-pipeline returns 200 + reused=true when the link already exists', async () => {
+ const promoter = await import('../services/writersRoom/promoteToPipeline.js');
+ promoter.promoteWorkToPipeline.mockResolvedValue({
+ series: { id: 'ser-1' }, issue: { id: 'iss-1' }, reused: true,
+ });
+
+ const r = await request(app)
+ .post('/api/writers-room/works/wr-work-1/promote-to-pipeline')
+ .send({});
+ expect(r.status).toBe(200);
+ expect(r.body.reused).toBe(true);
+ });
+
+ it('POST /works/:id/promote-to-pipeline forwards force flag through', async () => {
+ const promoter = await import('../services/writersRoom/promoteToPipeline.js');
+ promoter.promoteWorkToPipeline.mockResolvedValue({
+ series: { id: 'ser-2' }, issue: { id: 'iss-2' }, reused: false,
+ });
+
+ await request(app)
+ .post('/api/writers-room/works/wr-work-1/promote-to-pipeline')
+ .send({ force: true });
+ expect(promoter.promoteWorkToPipeline).toHaveBeenCalledWith('wr-work-1', { force: true });
+ });
+
+ it('POST /works/:id/promote-to-pipeline surfaces empty-draft as 400', async () => {
+ const promoter = await import('../services/writersRoom/promoteToPipeline.js');
+ promoter.promoteWorkToPipeline.mockRejectedValue(
+ Object.assign(new Error('Cannot promote — the active draft has no prose. Write some text first.'), {
+ code: 'WR_PROMOTE_NO_DRAFT_BODY',
+ }),
+ );
+
+ const r = await request(app)
+ .post('/api/writers-room/works/wr-work-1/promote-to-pipeline')
+ .send({});
+ expect(r.status).toBe(400);
+ expect(r.body.error || r.body.message).toMatch(/no prose/i);
+ });
+ });
});
diff --git a/server/services/pipeline/autoRunner.js b/server/services/pipeline/autoRunner.js
index 9dc3b56ec9..573ba501ac 100644
--- a/server/services/pipeline/autoRunner.js
+++ b/server/services/pipeline/autoRunner.js
@@ -19,6 +19,7 @@ import { randomUUID } from 'crypto';
import { broadcastSse, attachSseClient, closeJobAfterDelay } from '../../lib/sseUtils.js';
import { generateStage } from './textStages.js';
import { getIssue, updateIssue } from './issues.js';
+import { startEpisodeVideoForIssue, ERR_NO_STORYBOARDS } from './episodeVideo.js';
// runs: Map<issueId, { runId, clients[], lastPayload, cancelRequested, startedAt }>
const runs = new Map();
@@ -86,8 +87,37 @@ export async function startAutoRunTextStages(issueId, options = {}) {
]);
}
- const status = record.cancelRequested ? 'needs-review' : 'needs-review';
- await updateIssue(issueId, { status }).catch(() => null);
+ // Optional Stage 4: episode video. Gated behind `includeVideo: true` so
+ // the default auto-run still stops before burning GPU minutes. The CD
+ // pipeline runs entirely server-side and takes minutes per scene — we
+ // fire-and-forget the kickoff and surface the cdProjectId via SSE so
+ // the UI can switch to polling the CD project for progress.
+ if (options.includeVideo && !record.cancelRequested) {
+ broadcast(issueId, { type: 'stage:start', stage: 'episodeVideo' });
+ const kickoff = await startEpisodeVideoForIssue(issueId, {
+ aspectRatio: options.aspectRatio,
+ quality: options.quality,
+ modelId: options.modelId,
+ }).catch((err) => {
+ if (err?.code === ERR_NO_STORYBOARDS) {
+ broadcast(issueId, { type: 'skip', stage: 'episodeVideo', reason: 'storyboards stage has no scenes — fill it in first' });
+ return null;
+ }
+ broadcast(issueId, { type: 'stage:error', stage: 'episodeVideo', error: (err?.message || String(err)).slice(0, 500) });
+ return null;
+ });
+ if (kickoff) {
+ broadcast(issueId, {
+ type: 'stage:complete',
+ stage: 'episodeVideo',
+ cdProjectId: kickoff.cdProjectId,
+ scenes: kickoff.scenes,
+ reused: kickoff.reused,
+ });
+ }
+ }
+
+ await updateIssue(issueId, { status: 'needs-review' }).catch(() => null);
broadcast(issueId, {
type: record.cancelRequested ? 'canceled' : 'complete',
runId,
@@ -129,5 +159,32 @@ async function runStageIfNeeded(issueId, stageId, options) {
});
}
+/**
+ * Boot-time recovery for issues stuck in `status: 'running'`.
+ *
+ * The in-memory `runs` map is lost on server restart — there's no way to
+ * reattach SSE to the dead run, and the issue would remain stuck in
+ * `running` forever (the UI shows a spinner that never resolves).
+ *
+ * On boot, walk every issue and demote any `running` to `needs-review` (the
+ * same terminal state a normal-completion path lands on). Idempotent. Fires
+ * as a fire-and-forget side effect; failures are logged but never escalated
+ * — the listIssues call has its own error handling and an exception here
+ * shouldn't block server startup.
+ *
+ * Mirrors writers-room/evaluator.js#recoverStuckAnalyses.
+ */
+export async function recoverStuckAutoRuns() {
+ const { listIssues } = await import('./issues.js');
+ const all = await listIssues().catch(() => []);
+ const stuck = all.filter((i) => i.status === 'running');
+ if (stuck.length === 0) return 0;
+ for (const issue of stuck) {
+ await updateIssue(issue.id, { status: 'needs-review' }).catch(() => null);
+ }
+ console.log(`📝 pipeline: recovered ${stuck.length} stuck auto-run${stuck.length === 1 ? '' : 's'} on boot`);
+ return stuck.length;
+}
+
// Export internals for tests.
export const __testing = { runs };
diff --git a/server/services/pipeline/autoRunner.test.js b/server/services/pipeline/autoRunner.test.js
index b0f0c0e38d..80b5129bbd 100644
--- a/server/services/pipeline/autoRunner.test.js
+++ b/server/services/pipeline/autoRunner.test.js
@@ -33,6 +33,18 @@ vi.mock('./textStages.js', async () => {
};
});
+// Mock the episode-video handoff so the coordinator test stays focused on
+// the text-stage chain and doesn't transitively load the CD module graph
+// (which hits services/appActivity.js at import time and needs PATHS.cos).
+const videoKickoffs = [];
+vi.mock('./episodeVideo.js', () => ({
+ ERR_NO_STORYBOARDS: 'PIPELINE_EPISODE_NO_STORYBOARDS',
+ startEpisodeVideoForIssue: vi.fn(async (issueId, opts) => {
+ videoKickoffs.push({ issueId, opts });
+ return { cdProjectId: `cd-mock-${issueId.slice(0, 6)}`, scenes: 2, reused: false };
+ }),
+}));
+
const seriesSvc = await import('./series.js');
const issuesSvc = await import('./issues.js');
const autoRunner = await import('./autoRunner.js');
@@ -112,6 +124,29 @@ describe('pipeline auto-runner', () => {
await waitFor(() => generated.length === 4);
});
+ it('does NOT kick off episodeVideo by default', async () => {
+ const { issue } = await seed();
+ await autoRunner.startAutoRunTextStages(issue.id);
+ await waitFor(() => generated.length === 4);
+ // Give the coordinator's terminal broadcast a chance to land.
+ await waitFor(() => {
+ const run = autoRunner.__testing.runs.get(issue.id);
+ return run?.lastPayload?.type === 'complete';
+ });
+ expect(videoKickoffs).toHaveLength(0);
+ });
+
+ it('kicks off episodeVideo when includeVideo:true', async () => {
+ const { issue } = await seed();
+ await issuesSvc.updateStage(issue.id, 'storyboards', {
+ status: 'edited',
+ scenes: [{ description: 'a scene' }, { description: 'another' }],
+ });
+ await autoRunner.startAutoRunTextStages(issue.id, { includeVideo: true });
+ await waitFor(() => videoKickoffs.length === 1, { timeoutMs: 2000 });
+ expect(videoKickoffs[0].issueId).toBe(issue.id);
+ });
+
it('cancelAutoRun stops the chain between stages', async () => {
const { issue } = await seed();
// Generator needs a real timer delay so the test can poll generated,
@@ -145,4 +180,29 @@ describe('pipeline auto-runner', () => {
const finalRun = autoRunner.__testing.runs.get(issue.id);
expect(finalRun?.lastPayload?.type).toBe('canceled');
});
+
+ describe('recoverStuckAutoRuns', () => {
+ it('demotes any issue in status: running to needs-review on boot', async () => {
+ const series = await seriesSvc.createSeries({ name: 'S' });
+ const a = await issuesSvc.createIssue({ seriesId: series.id, title: 'Stuck A' });
+ const b = await issuesSvc.createIssue({ seriesId: series.id, title: 'Stuck B' });
+ const c = await issuesSvc.createIssue({ seriesId: series.id, title: 'Not stuck' });
+ await issuesSvc.updateIssue(a.id, { status: 'running' });
+ await issuesSvc.updateIssue(b.id, { status: 'running' });
+ await issuesSvc.updateIssue(c.id, { status: 'needs-review' });
+
+ const count = await autoRunner.recoverStuckAutoRuns();
+ expect(count).toBe(2);
+
+ expect((await issuesSvc.getIssue(a.id)).status).toBe('needs-review');
+ expect((await issuesSvc.getIssue(b.id)).status).toBe('needs-review');
+ // Already-terminal issue is left untouched
+ expect((await issuesSvc.getIssue(c.id)).status).toBe('needs-review');
+ });
+
+ it('returns 0 when no issues are stuck (idempotent — safe to call on every boot)', async () => {
+ const count = await autoRunner.recoverStuckAutoRuns();
+ expect(count).toBe(0);
+ });
+ });
});
diff --git a/server/services/pipeline/episodeVideo.js b/server/services/pipeline/episodeVideo.js
new file mode 100644
index 0000000000..59d86687f1
--- /dev/null
+++ b/server/services/pipeline/episodeVideo.js
@@ -0,0 +1,137 @@
+/**
+ * Pipeline — Episode Video stage handoff.
+ *
+ * The Pipeline's `episodeVideo` stage drives the full per-scene render +
+ * stitch loop, but reuses the Creative Director machinery instead of
+ * duplicating it. We create a CD project with `autoAcceptScenes: true` so
+ * no LLM evaluator round-trip runs (the Pipeline already had the human
+ * vetting the storyboard scenes), then call into CD's existing
+ * `advanceAfterSceneSettled` to kick off the first render. CD's own
+ * sceneRunner / completionHook / stitchRunner take it from there.
+ *
+ * The CD project id is persisted on the issue's `stages.episodeVideo` so
+ * the UI can poll `/api/creative-director/:id` to render progress and
+ * surface the final stitched video when complete.
+ */
+import { composeVisualPrompt } from './visualStages.js';
+import { getIssue, updateStage } from './issues.js';
+import { getSeries } from './series.js';
+import { createProject as createCDProject, setTreatment as setCDTreatment } from '../creativeDirector/local.js';
+import { startCreativeDirectorProject } from '../creativeDirector/completionHook.js';
+import { getDefaultVideoModelId } from '../../lib/mediaModels.js';
+import { buildSettingByKey } from '../../lib/scenePrompt.js';
+import { getSettings } from '../settings.js';
+
+export const ERR_NO_STORYBOARDS = 'PIPELINE_EPISODE_NO_STORYBOARDS';
+const makeErr = (message, code) => Object.assign(new Error(message), { code });
+
+const DEFAULT_SCENE_DURATION = 3;
+const MAX_SCENES = 30;
+
+/**
+ * Build the CD treatment from a pipeline issue's storyboards stage. Each
+ * storyboard scene becomes one CD scene; the series styleNotes are
+ * prepended into each prompt so the renders share visual identity. After
+ * the first scene we set `useContinuationFromPrior: true` so i2v chaining
+ * carries the seed forward — same trick as the smoke fixture, applied to
+ * narrative content.
+ */
+export function buildTreatmentFromStoryboards({ issue, series }) {
+ const storyboards = issue.stages?.storyboards;
+ const rawScenes = Array.isArray(storyboards?.scenes) ? storyboards.scenes : [];
+ const usable = rawScenes
+ .filter((s) => (s?.description || '').trim().length > 0)
+ .slice(0, MAX_SCENES);
+ if (!usable.length) {
+ throw makeErr(
+ 'Storyboards stage has no scenes with descriptions. Add scenes on the Storyboards stage first.',
+ ERR_NO_STORYBOARDS,
+ );
+ }
+ const settingByKey = buildSettingByKey(series?.settings);
+ const scenes = usable.map((s, idx) => ({
+ sceneId: `iss-${issue.id.slice(-8)}-s${idx + 1}`,
+ order: idx,
+ intent: (s.slugline || `Scene ${idx + 1}`).slice(0, 1000),
+ prompt: composeVisualPrompt({ series, description: s.description, slugline: s.slugline || '', settingByKey }).slice(0, 8000),
+ negativePrompt: 'text, watermark, blur, motion blur, low quality',
+ durationSeconds: Number.isFinite(s.durationSeconds) ? Math.min(10, Math.max(1, s.durationSeconds)) : DEFAULT_SCENE_DURATION,
+ useContinuationFromPrior: idx > 0,
+ sourceImageFile: null,
+ }));
+ const logline = (series?.logline || issue.title || 'Episode video').slice(0, 500);
+ const synopsis = ((issue.stages?.idea?.output || issue.title || 'Pipeline episode') + '').slice(0, 5000);
+ return {
+ logline,
+ synopsis,
+ scenes,
+ };
+}
+
+/**
+ * Create a CD project from a pipeline issue's storyboards stage and kick
+ * off the render → stitch loop. Persists `cdProjectId` on the issue's
+ * `stages.episodeVideo` so subsequent polls find the running CD project.
+ *
+ * Idempotent in spirit: if the stage already has a `cdProjectId` and
+ * `options.force` is not set, returns the existing id instead of creating
+ * a duplicate. The route layer can call this again to reuse an in-flight
+ * run safely.
+ */
+export async function startEpisodeVideoForIssue(issueId, options = {}) {
+ const [issue, settings] = await Promise.all([getIssue(issueId), getSettings()]);
+
+ const existing = issue.stages?.episodeVideo?.cdProjectId;
+ if (existing && !options.force) {
+ // Mirror buildTreatmentFromStoryboards exactly so the reuse-path scenes
+ // count matches what the existing CD treatment actually holds: filter
+ // empty descriptions AND cap at MAX_SCENES. SSE / UI status messaging
+ // stays consistent between fresh-start and reuse paths.
+ const scenes = (issue.stages?.storyboards?.scenes || [])
+ .filter((s) => (s?.description || '').trim().length > 0)
+ .slice(0, MAX_SCENES).length;
+ return { cdProjectId: existing, reused: true, scenes };
+ }
+
+ const series = await getSeries(issue.seriesId);
+ const treatment = buildTreatmentFromStoryboards({ issue, series });
+ const aspectRatio = options.aspectRatio || '16:9';
+ const quality = options.quality || 'standard';
+ const modelId = options.modelId || settings?.videoGen?.defaultModelId || getDefaultVideoModelId();
+
+ const project = await createCDProject({
+ name: `Pipeline: ${(series?.name || 'Series').slice(0, 60)} — ${(issue.title || issueId).slice(0, 60)}`,
+ aspectRatio,
+ quality,
+ modelId,
+ targetDurationSeconds: Math.min(600, treatment.scenes.reduce((sum, s) => sum + s.durationSeconds, 0)),
+ styleSpec: series?.styleNotes || '',
+ startingImageFile: null,
+ userStory: issue.stages?.prose?.output || null,
+ disableAudio: true,
+ autoAcceptScenes: true,
+ });
+ await setCDTreatment(project.id, treatment);
+
+ await updateStage(issueId, 'episodeVideo', {
+ status: 'generating',
+ cdProjectId: project.id,
+ // Persist the chosen render settings so a page reload restores the
+ // pickers — otherwise restart from a fresh tab would silently fall back
+ // to defaults that the user can't see or adjust.
+ aspectRatio,
+ quality,
+ output: '',
+ errorMessage: '',
+ });
+
+ // Kick off the orchestrator — fire-and-forget so the route can return
+ // immediately. Failures land on the CD project's `failureReason` field
+ // and surface via the UI's CD project poll, not via this Promise.
+ startCreativeDirectorProject(project.id).catch((err) =>
+ console.log(`⚠️ Pipeline episode CD start failed for ${project.id}: ${err.message}`),
+ );
+
+ console.log(`🎬 Pipeline episode video — issue=${issueId.slice(0, 8)} cdProject=${project.id.slice(0, 8)} scenes=${treatment.scenes.length}`);
+ return { cdProjectId: project.id, scenes: treatment.scenes.length, reused: false };
+}
diff --git a/server/services/pipeline/episodeVideo.test.js b/server/services/pipeline/episodeVideo.test.js
new file mode 100644
index 0000000000..68ce72c4b7
--- /dev/null
+++ b/server/services/pipeline/episodeVideo.test.js
@@ -0,0 +1,197 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const fileStore = new Map();
+
+vi.mock('../../lib/fileUtils.js', () => ({
+ PATHS: { data: '/mock/data' },
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
+ readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),
+}));
+
+let uuidCounter = 0;
+vi.mock('crypto', async () => {
+ const actual = await vi.importActual('crypto');
+ return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
+});
+
+const cdCreated = [];
+const cdTreatments = [];
+vi.mock('../creativeDirector/local.js', () => ({
+ createProject: vi.fn(async (input) => {
+ const project = { id: `cd-uuid-${++uuidCounter}`, ...input, treatment: null };
+ cdCreated.push(project);
+ return project;
+ }),
+ setTreatment: vi.fn(async (id, treatment) => {
+ cdTreatments.push({ id, treatment });
+ return { id, treatment };
+ }),
+}));
+
+vi.mock('../creativeDirector/completionHook.js', () => ({
+ startCreativeDirectorProject: vi.fn(async () => undefined),
+}));
+
+vi.mock('../../lib/mediaModels.js', () => ({
+ getDefaultVideoModelId: () => 'ltx23_distilled_q4',
+}));
+
+vi.mock('../settings.js', () => ({
+ getSettings: vi.fn(async () => ({})),
+}));
+
+const svc = await import('./episodeVideo.js');
+const issuesSvc = await import('./issues.js');
+const seriesSvc = await import('./series.js');
+
+async function seedSeriesAndIssue({ scenes = [] } = {}) {
+ const series = await seriesSvc.createSeries({
+ name: 'TestSeries',
+ logline: 'A test logline.',
+ premise: 'Premise.',
+ styleNotes: 'moebius linework, cinematic',
+ });
+ const issue = await issuesSvc.createIssue({
+ seriesId: series.id,
+ title: 'Pilot',
+ });
+ if (scenes.length) {
+ await issuesSvc.updateStage(issue.id, 'storyboards', {
+ status: 'edited',
+ scenes,
+ });
+ }
+ return { series, issue };
+}
+
+describe('pipeline episodeVideo helper', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ cdCreated.length = 0;
+ cdTreatments.length = 0;
+ uuidCounter = 0;
+ vi.clearAllMocks();
+ });
+
+ it('buildTreatmentFromStoryboards composes prompts with series style notes', () => {
+ const treatment = svc.buildTreatmentFromStoryboards({
+ series: { logline: 'A logline.', styleNotes: 'moebius linework' },
+ issue: {
+ id: 'iss-12345678',
+ title: 'Pilot',
+ stages: {
+ idea: { output: 'beat sheet' },
+ storyboards: {
+ scenes: [
+ { slugline: 'INT. FOUNDRY', description: 'Lina enters' },
+ { slugline: 'EXT. STREET', description: 'A chase begins' },
+ ],
+ },
+ },
+ },
+ });
+ expect(treatment.scenes).toHaveLength(2);
+ expect(treatment.scenes[0].prompt).toContain('moebius linework');
+ expect(treatment.scenes[0].prompt).toContain('Lina enters');
+ expect(treatment.scenes[0].useContinuationFromPrior).toBe(false);
+ expect(treatment.scenes[1].useContinuationFromPrior).toBe(true);
+ expect(treatment.logline).toBe('A logline.');
+ });
+
+ it('buildTreatmentFromStoryboards rejects empty storyboards', () => {
+ expect(() => svc.buildTreatmentFromStoryboards({
+ series: { styleNotes: 's' },
+ issue: { id: 'iss-1', title: 't', stages: { storyboards: { scenes: [] } } },
+ })).toThrow(/no scenes/i);
+ });
+
+ it('buildTreatmentFromStoryboards drops scenes without description', () => {
+ const treatment = svc.buildTreatmentFromStoryboards({
+ series: { styleNotes: 's' },
+ issue: {
+ id: 'iss-12345678',
+ title: 't',
+ stages: {
+ storyboards: {
+ scenes: [
+ { description: 'first' },
+ { description: ' ' },
+ { description: 'third' },
+ ],
+ },
+ },
+ },
+ });
+ expect(treatment.scenes).toHaveLength(2);
+ });
+
+ it('startEpisodeVideoForIssue creates a CD project + persists cdProjectId on the stage', async () => {
+ const { issue } = await seedSeriesAndIssue({
+ scenes: [
+ { slugline: 'INT.', description: 'opens on a foundry' },
+ { slugline: 'EXT.', description: 'streets at dusk' },
+ ],
+ });
+ const result = await svc.startEpisodeVideoForIssue(issue.id);
+ expect(result.cdProjectId).toMatch(/^cd-/);
+ expect(result.scenes).toBe(2);
+ expect(result.reused).toBe(false);
+ expect(cdCreated).toHaveLength(1);
+ expect(cdCreated[0].autoAcceptScenes).toBe(true);
+ expect(cdCreated[0].disableAudio).toBe(true);
+ expect(cdTreatments).toHaveLength(1);
+ expect(cdTreatments[0].treatment.scenes).toHaveLength(2);
+ const refreshed = await issuesSvc.getIssue(issue.id);
+ expect(refreshed.stages.episodeVideo.cdProjectId).toBe(result.cdProjectId);
+ expect(refreshed.stages.episodeVideo.status).toBe('generating');
+ // Persisted render settings so a page reload (or a fresh tab) can
+ // restore the picker state — defaults applied since no overrides given.
+ expect(refreshed.stages.episodeVideo.aspectRatio).toBe('16:9');
+ expect(refreshed.stages.episodeVideo.quality).toBe('standard');
+ });
+
+ it('startEpisodeVideoForIssue persists user-overridden aspectRatio + quality on the stage', async () => {
+ const { issue } = await seedSeriesAndIssue({
+ scenes: [{ description: 'foo' }],
+ });
+ await svc.startEpisodeVideoForIssue(issue.id, { aspectRatio: '9:16', quality: 'high' });
+ const refreshed = await issuesSvc.getIssue(issue.id);
+ expect(refreshed.stages.episodeVideo.aspectRatio).toBe('9:16');
+ expect(refreshed.stages.episodeVideo.quality).toBe('high');
+ });
+
+ it('startEpisodeVideoForIssue reuses an existing cdProjectId by default', async () => {
+ const { issue } = await seedSeriesAndIssue({
+ scenes: [{ description: 'one' }, { description: 'two' }, { description: '' }],
+ });
+ const first = await svc.startEpisodeVideoForIssue(issue.id);
+ cdCreated.length = 0;
+ const second = await svc.startEpisodeVideoForIssue(issue.id);
+ expect(second.cdProjectId).toBe(first.cdProjectId);
+ expect(second.reused).toBe(true);
+ // Reuse path emits the same `scenes` count shape as the fresh-start path
+ // so SSE consumers (autoRunner) don't have to guard against undefined.
+ // Empty descriptions are filtered (matches buildTreatmentFromStoryboards).
+ expect(second.scenes).toBe(2);
+ expect(cdCreated).toHaveLength(0);
+ });
+
+ it('startEpisodeVideoForIssue force:true creates a new project', async () => {
+ const { issue } = await seedSeriesAndIssue({
+ scenes: [{ description: 'one' }],
+ });
+ const first = await svc.startEpisodeVideoForIssue(issue.id);
+ cdCreated.length = 0;
+ const second = await svc.startEpisodeVideoForIssue(issue.id, { force: true });
+ expect(second.cdProjectId).not.toBe(first.cdProjectId);
+ expect(second.reused).toBe(false);
+ expect(cdCreated).toHaveLength(1);
+ });
+
+ it('startEpisodeVideoForIssue rejects when storyboards is empty', async () => {
+ const { issue } = await seedSeriesAndIssue({ scenes: [] });
+ await expect(svc.startEpisodeVideoForIssue(issue.id))
+ .rejects.toMatchObject({ code: svc.ERR_NO_STORYBOARDS });
+ });
+});
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index f1d12a1c88..1da9f276b3 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -22,7 +22,8 @@ import { join } from 'path';
import { randomUUID } from 'crypto';
import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';
-const STATE_PATH = join(PATHS.data, 'pipeline-issues.json');
+// Lazy resolution — see series.js for context.
+const statePath = () => join(PATHS.data, 'pipeline-issues.json');
export const ERR_NOT_FOUND = 'PIPELINE_ISSUE_NOT_FOUND';
export const ERR_VALIDATION = 'PIPELINE_ISSUE_VALIDATION';
@@ -70,6 +71,14 @@ const sanitizeStage = (raw) => {
};
};
+// Episode-video render settings the user chose at kickoff time. Persisted
+// on the stage so a page reload doesn't reset them to the defaults — the
+// restart flow can render the same pickers populated with the user's
+// previous choice. The CD project itself owns the authoritative values once
+// rendering starts; these are the *requested* settings for the next start.
+const ASPECT_RATIO_VALUES = new Set(['16:9', '9:16', '1:1']);
+const QUALITY_VALUES = new Set(['draft', 'standard', 'high']);
+
const sanitizeVisualStage = (raw) => {
// Visual stages keep arbitrary structured artifact lists. Sanitize the
// wrapper but pass through known shapes.
@@ -80,6 +89,8 @@ const sanitizeVisualStage = (raw) => {
scenes: Array.isArray(raw?.scenes) ? raw.scenes.slice(0, 200) : [],
cdProjectId: isStr(raw?.cdProjectId) && raw.cdProjectId ? raw.cdProjectId : null,
videoPath: isStr(raw?.videoPath) && raw.videoPath ? raw.videoPath : null,
+ aspectRatio: ASPECT_RATIO_VALUES.has(raw?.aspectRatio) ? raw.aspectRatio : null,
+ quality: QUALITY_VALUES.has(raw?.quality) ? raw.quality : null,
};
};
@@ -114,13 +125,13 @@ const sanitizeIssue = (raw) => {
async function readState() {
await ensureDir(PATHS.data);
- const raw = await readJSONFile(STATE_PATH, { issues: [] }, { logError: false });
+ const raw = await readJSONFile(statePath(), { issues: [] }, { logError: false });
const issues = Array.isArray(raw.issues) ? raw.issues.map(sanitizeIssue).filter(Boolean) : [];
return { issues };
}
async function writeState(state) {
- await atomicWrite(STATE_PATH, state);
+ await atomicWrite(statePath(), state);
}
export async function listIssues({ seriesId = null } = {}) {
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index 8acc85cc94..a9a8d451a6 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -13,8 +13,16 @@
import { join } from 'path';
import { randomUUID } from 'crypto';
import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';
+import {
+ sanitizeBibleList, mergeExtractedBible,
+ BIBLE_LIMITS, BIBLE_KIND, BIBLE_FIELD,
+ isStr, trimTo,
+} from '../../lib/storyBible.js';
+import { extractBible } from '../../lib/bibleExtractor.js';
-const STATE_PATH = join(PATHS.data, 'pipeline-series.json');
+// Lazy resolution — PATHS.data may not be available at module-load time
+// (e.g. tests that swap it through a Proxy mock).
+const statePath = () => join(PATHS.data, 'pipeline-series.json');
export const ERR_NOT_FOUND = 'PIPELINE_SERIES_NOT_FOUND';
export const ERR_VALIDATION = 'PIPELINE_SERIES_VALIDATION';
@@ -24,51 +32,19 @@ export const NAME_MAX = 200;
export const LOGLINE_MAX = 500;
export const PREMISE_MAX = 8000;
export const STYLE_NOTES_MAX = 4000;
-export const CHARACTER_NAME_MAX = 200;
-export const CHARACTER_DESCRIPTION_MAX = 2000;
-export const CHARACTERS_PER_SERIES_MAX = 50;
-export const IMAGE_REFS_PER_CHARACTER_MAX = 12;
-export const IMAGE_REF_MAX = 500;
+export const CHARACTER_NAME_MAX = BIBLE_LIMITS.NAME_MAX;
+export const CHARACTER_DESCRIPTION_MAX = BIBLE_LIMITS.PHYSICAL_DESCRIPTION_MAX;
+export const CHARACTERS_PER_SERIES_MAX = BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX;
+export const BIBLE_ENTRIES_PER_SERIES_MAX = BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX;
+export const IMAGE_REFS_PER_CHARACTER_MAX = BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX;
+export const IMAGE_REF_MAX = BIBLE_LIMITS.IMAGE_REF_MAX;
export const WORLD_ID_MAX = 64;
+export const WRITERS_ROOM_WORK_ID_MAX = 64;
export const TARGET_FORMATS = Object.freeze(['comic', 'tv', 'comic+tv']);
export const ISSUE_COUNT_TARGET_MAX = 999;
const DEFAULT_STATE = { series: [] };
-const isStr = (v) => typeof v === 'string';
-const trimTo = (v, max) => (isStr(v) ? v.trim().slice(0, max) : '');
-
-const sanitizeCharacter = (raw) => {
- if (!raw || typeof raw !== 'object') return null;
- const name = trimTo(raw.name, CHARACTER_NAME_MAX);
- if (!name) return null;
- const description = trimTo(raw.description, CHARACTER_DESCRIPTION_MAX);
- const imageRefs = Array.isArray(raw.imageRefs)
- ? raw.imageRefs
- .map((r) => trimTo(r, IMAGE_REF_MAX))
- .filter(Boolean)
- .slice(0, IMAGE_REFS_PER_CHARACTER_MAX)
- : [];
- return {
- id: isStr(raw.id) && raw.id ? raw.id : `chr-${randomUUID()}`,
- name,
- description,
- imageRefs,
- };
-};
-
-const sanitizeCharacters = (raw = []) => {
- if (!Array.isArray(raw)) return [];
- const out = [];
- for (const c of raw) {
- const sanitized = sanitizeCharacter(c);
- if (!sanitized) continue;
- out.push(sanitized);
- if (out.length >= CHARACTERS_PER_SERIES_MAX) break;
- }
- return out;
-};
-
const sanitizeSeries = (raw) => {
if (!raw || typeof raw !== 'object') return null;
if (!isStr(raw.id) || !raw.id) return null;
@@ -86,7 +62,12 @@ const sanitizeSeries = (raw) => {
logline: trimTo(raw.logline, LOGLINE_MAX),
premise: trimTo(raw.premise, PREMISE_MAX),
worldId: trimTo(raw.worldId, WORLD_ID_MAX) || null,
- characters: sanitizeCharacters(raw.characters || []),
+ // Bidirectional link to a Writers Room work (item 6 of the DRY
+ // unification). Set by the "Promote to pipeline" flow; never auto-cleared.
+ writersRoomWorkId: trimTo(raw.writersRoomWorkId, WRITERS_ROOM_WORK_ID_MAX) || null,
+ characters: sanitizeBibleList(raw.characters, BIBLE_KIND.CHARACTER),
+ settings: sanitizeBibleList(raw.settings, BIBLE_KIND.SETTING),
+ objects: sanitizeBibleList(raw.objects, BIBLE_KIND.OBJECT),
styleNotes: trimTo(raw.styleNotes, STYLE_NOTES_MAX),
targetFormat,
issueCountTarget,
@@ -97,13 +78,13 @@ const sanitizeSeries = (raw) => {
async function readState() {
await ensureDir(PATHS.data);
- const raw = await readJSONFile(STATE_PATH, DEFAULT_STATE, { logError: false });
+ const raw = await readJSONFile(statePath(), DEFAULT_STATE, { logError: false });
const series = Array.isArray(raw.series) ? raw.series.map(sanitizeSeries).filter(Boolean) : [];
return { series };
}
async function writeState(state) {
- await atomicWrite(STATE_PATH, state);
+ await atomicWrite(statePath(), state);
}
export async function listSeries() {
@@ -129,7 +110,10 @@ export async function createSeries(input = {}) {
logline: input.logline || '',
premise: input.premise || '',
worldId: input.worldId || null,
+ writersRoomWorkId: input.writersRoomWorkId || null,
characters: input.characters || [],
+ settings: input.settings || [],
+ objects: input.objects || [],
styleNotes: input.styleNotes || '',
targetFormat: input.targetFormat || 'comic+tv',
issueCountTarget: input.issueCountTarget || 0,
@@ -152,7 +136,10 @@ export async function updateSeries(id, patch = {}) {
...('logline' in patch ? { logline: patch.logline } : {}),
...('premise' in patch ? { premise: patch.premise } : {}),
...('worldId' in patch ? { worldId: patch.worldId } : {}),
+ ...('writersRoomWorkId' in patch ? { writersRoomWorkId: patch.writersRoomWorkId } : {}),
...('characters' in patch ? { characters: patch.characters } : {}),
+ ...('settings' in patch ? { settings: patch.settings } : {}),
+ ...('objects' in patch ? { objects: patch.objects } : {}),
...('styleNotes' in patch ? { styleNotes: patch.styleNotes } : {}),
...('targetFormat' in patch ? { targetFormat: patch.targetFormat } : {}),
...('issueCountTarget' in patch ? { issueCountTarget: patch.issueCountTarget } : {}),
@@ -164,6 +151,63 @@ export async function updateSeries(id, patch = {}) {
return merged;
}
+/**
+ * Run bible extraction across the requested kinds and merge results into a
+ * series. The route layer used to thread extract → merge → patch itself,
+ * which made `mergeExtractedBible` a route-layer concern. Lifting it here
+ * gives the route a 3-line call and lets future consumers (re-sync from
+ * Writers Room, batch bible refresh, etc) reuse the same orchestration.
+ *
+ * @param {string} seriesId
+ * @param {object} opts
+ * @param {string[]} opts.kinds BIBLE_KIND values to run (defaults to all three)
+ * @param {string} opts.corpus prose body to extract from
+ * @param {boolean} [opts.parallel] fan out the kinds concurrently (HTTP-API providers only)
+ * @param {string} [opts.providerOverride]
+ * @returns {Promise<{ series, results }>} results is keyed by BIBLE_FIELD (e.g. `characters`)
+ */
+export async function extractAndMergeIntoSeries(seriesId, opts = {}) {
+ const series = await getSeries(seriesId);
+ // Dedup `kinds` — duplicates would run extra LLM calls AND last-write-wins
+ // the merge for the same field, so the only observable effect of a repeat
+ // is a wasted provider round-trip. Preserve first-seen order so callers
+ // can rely on response key order in `results`.
+ const rawKinds = (opts.kinds && opts.kinds.length)
+ ? opts.kinds
+ : [BIBLE_KIND.CHARACTER, BIBLE_KIND.SETTING, BIBLE_KIND.OBJECT];
+ const kinds = [...new Set(rawKinds)];
+ if (!isStr(opts.corpus) || !opts.corpus.trim()) {
+ throw makeErr('extractAndMergeIntoSeries: corpus is required', ERR_VALIDATION);
+ }
+
+ const runOne = (kind) => extractBible({
+ kind,
+ corpus: opts.corpus,
+ existing: series[BIBLE_FIELD[kind]] || [],
+ context: { series: { id: series.id, name: series.name } },
+ providerOverride: opts.providerOverride,
+ source: `pipeline-bible-${kind}`,
+ }).then((result) => ({ kind, result }));
+
+ const completed = opts.parallel
+ ? await Promise.all(kinds.map(runOne))
+ : await kinds.reduce(async (acc, kind) => [...(await acc), await runOne(kind)], Promise.resolve([]));
+
+ const results = {};
+ const patch = {};
+ for (const { kind, result } of completed) {
+ const field = BIBLE_FIELD[kind];
+ patch[field] = mergeExtractedBible(series[field] || [], result.extracted, kind);
+ results[field] = {
+ extracted: result.extracted, runId: result.runId,
+ providerId: result.providerId, model: result.model,
+ };
+ }
+
+ const updated = await updateSeries(series.id, patch);
+ return { series: updated, results };
+}
+
export async function deleteSeries(id) {
const state = await readState();
const before = state.series.length;
diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.js
index aea48bbf46..dc4c48b5ae 100644
--- a/server/services/pipeline/textStages.js
+++ b/server/services/pipeline/textStages.js
@@ -14,9 +14,7 @@
* boundary in autoRunner.js, which routes failures through a finalizer.
*/
-import { buildPrompt } from '../promptService.js';
-import { getActiveProvider, getProviderById } from '../providers.js';
-import { executeApiRun, executeCliRun, createRun } from '../runner.js';
+import { runStagedLLM } from '../../lib/stageRunner.js';
import { getSeries } from './series.js';
import { getIssue, updateStage, TEXT_STAGE_IDS } from './issues.js';
@@ -27,55 +25,6 @@ const STAGE_TO_TEMPLATE = Object.freeze({
tvScript: 'pipeline-tv-script',
});
-const isCliProvider = (provider) => provider?.type === 'cli';
-
-// Wraps executeCliRun / executeApiRun as a Promise. Mirrors the pattern in
-// worldBuilderExpand.js#callLLM — both runner entry points are async and can
-// reject before onComplete fires, so we forward those rejections through the
-// outer Promise instead of letting them surface as unhandledRejection.
-async function callLLM(provider, model, prompt) {
- const { runId } = await createRun({
- providerId: provider.id,
- model,
- prompt,
- source: 'pipeline-text-stage',
- });
- return new Promise((resolve, reject) => {
- let text = '';
- if (isCliProvider(provider)) {
- executeCliRun(
- runId,
- provider,
- prompt,
- process.cwd(),
- (chunk) => { text += chunk; },
- (result) => {
- if (result?.error || result?.success === false) {
- reject(new Error(result?.error || 'CLI execution failed'));
- } else {
- resolve({ text, runId });
- }
- },
- provider.timeout ?? 300000,
- ).catch(reject);
- } else {
- executeApiRun(
- runId,
- provider,
- model,
- prompt,
- process.cwd(),
- [],
- (data) => { text += typeof data === 'string' ? data : (data?.text || ''); },
- (result) => {
- if (result?.error) reject(new Error(result.error));
- else resolve({ text, runId });
- },
- ).catch(reject);
- }
- });
-}
-
/**
* Build the variable bag fed into the stage template. Includes the series
* bible (`series.*`) and every *prior* text stage's content (`stages.*`).
@@ -134,28 +83,17 @@ export async function generateStage(issueId, stageId, options = {}) {
await updateStage(issueId, stageId, { status: 'generating', errorMessage: '' });
const ctx = buildStageContext({ series, issue, stageId, seedInput: options.seedInput });
- const prompt = await buildPrompt(template, ctx);
-
- let provider = options.providerId ? await getProviderById(options.providerId).catch(() => null) : null;
- if (!provider) provider = await getActiveProvider();
- if (!provider) {
- await updateStage(issueId, stageId, {
- status: 'error',
- errorMessage: 'No AI provider available',
- });
- throw new Error('No AI provider available for pipeline text stage');
- }
- const model = options.model || provider.defaultModel || provider.models?.[0] || null;
-
- console.log(`📝 Pipeline stage — issue=${issueId.slice(0, 8)} stage=${stageId} provider=${provider.name}/${model || 'default'}`);
// Catch only at this boundary so the stage record persists the failure
// before the error bubbles to the caller — without this, an LLM throw
// would leave the stage stuck in `generating` forever.
- let text;
- let runId;
+ let result;
try {
- ({ text, runId } = await callLLM(provider, model, prompt));
+ result = await runStagedLLM(template, ctx, {
+ providerOverride: options.providerId,
+ modelOverride: options.model,
+ source: 'pipeline-text-stage',
+ });
} catch (err) {
await updateStage(issueId, stageId, {
status: 'error',
@@ -164,16 +102,16 @@ export async function generateStage(issueId, stageId, options = {}) {
throw err;
}
- const output = (text || '').trim();
+ const output = (result.content || '').trim();
const { issue: updatedIssue, stage } = await updateStage(issueId, stageId, {
status: output ? 'ready' : 'error',
output,
- lastRunId: runId,
+ lastRunId: result.runId,
errorMessage: output ? '' : 'LLM returned empty response',
});
- console.log(`✅ Pipeline stage — issue=${issueId.slice(0, 8)} stage=${stageId} runId=${runId} length=${output.length}`);
- return { issue: updatedIssue, stage, runId };
+ console.log(`✅ Pipeline stage — issue=${issueId.slice(0, 8)} stage=${stageId} runId=${result.runId} length=${output.length}`);
+ return { issue: updatedIssue, stage, runId: result.runId };
}
// Export internals for tests.
diff --git a/server/services/pipeline/textStages.test.js b/server/services/pipeline/textStages.test.js
index ec68aba3a8..bd20f7eef5 100644
--- a/server/services/pipeline/textStages.test.js
+++ b/server/services/pipeline/textStages.test.js
@@ -22,10 +22,11 @@ vi.mock('../providers.js', () => ({
id: 'mock-provider',
name: 'Mock',
type: 'api',
+ enabled: true,
defaultModel: 'mock-model',
})),
getProviderById: vi.fn(async (id) => (id === 'mock-provider' ? {
- id, name: 'Mock', type: 'api', defaultModel: 'mock-model',
+ id, name: 'Mock', type: 'api', enabled: true, defaultModel: 'mock-model',
} : null)),
}));
@@ -46,6 +47,9 @@ vi.mock('../runner.js', () => ({
vi.mock('../promptService.js', () => ({
// Don't truncate — the prior-stages assertion looks at the rendered ctx.
buildPrompt: vi.fn(async (stageName, ctx) => `RENDERED:${stageName}:${JSON.stringify(ctx)}`),
+ // stageRunner now reads stage.provider/stage.model — return null so it
+ // falls through to the active provider in the mocked providers module.
+ getStage: vi.fn(() => null),
}));
const issuesSvc = await import('./issues.js');
diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.js
index 691d09d072..58e9321046 100644
--- a/server/services/pipeline/visualStages.js
+++ b/server/services/pipeline/visualStages.js
@@ -17,18 +17,28 @@ import { enqueueJob } from '../mediaJobQueue/index.js';
import { getSettings } from '../settings.js';
import { getSeries } from './series.js';
import { getIssue, VISUAL_STAGE_IDS } from './issues.js';
+import { buildScenePrompt, buildSettingByKey, matchSceneSetting } from '../../lib/scenePrompt.js';
const SUPPORTED_MODES = new Set(['local', 'codex']);
-/**
- * Build an image-gen prompt for a pipeline visual element by combining a
- * caller-supplied scene/panel description with the series' style notes.
- * Keeps the style fragment short — the description provides the subject.
- */
-export function composeVisualPrompt({ series, description, extraStyle = '' }) {
- const style = [series?.styleNotes, extraStyle].map((s) => (s || '').trim()).filter(Boolean).join(', ');
- const subject = (description || '').trim();
- return [style, subject].filter(Boolean).join(', ');
+// Build a pipeline image-gen prompt; delegates to the shared `buildScenePrompt`
+// so Pipeline + Writers Room renders agree byte-for-byte.
+//
+// Pipeline storyboard scenes don't yet carry a per-scene `characters[]`
+// list — once the scene extractor (PLAN item 5) populates it, callers will
+// pass `matchedCharacters` to selectively inject the cast. Until then we
+// inject none, so a 30-character series doesn't pollute every render with
+// the entire bible.
+export function composeVisualPrompt({ series, description, slugline = '', extraStyle = '', settingByKey = null, matchedCharacters = [] }) {
+ const worldStyle = [series?.styleNotes, extraStyle].map((s) => (s || '').trim()).filter(Boolean).join(', ');
+ const map = settingByKey || buildSettingByKey(series?.settings);
+ return buildScenePrompt(
+ series?.name || '',
+ { visualPrompt: description || '', slugline },
+ matchedCharacters,
+ worldStyle,
+ matchSceneSetting(slugline, map),
+ );
}
/**
@@ -46,9 +56,8 @@ export async function enqueueVisualImage(issueId, stageId, options = {}) {
if (!VISUAL_STAGE_IDS.includes(stageId)) {
throw new Error(`enqueueVisualImage: not a visual stage: ${stageId}`);
}
- const issue = await getIssue(issueId);
+ const [issue, settings] = await Promise.all([getIssue(issueId), getSettings()]);
const series = await getSeries(issue.seriesId);
- const settings = await getSettings();
const mode = SUPPORTED_MODES.has(options.mode) ? options.mode
: (SUPPORTED_MODES.has(settings.imageGen?.mode) ? settings.imageGen.mode : 'local');
@@ -56,7 +65,8 @@ export async function enqueueVisualImage(issueId, stageId, options = {}) {
const prompt = composeVisualPrompt({
series,
description: options.description,
- extraStyle: options.extraStyle || '',
+ slugline: options.slugline,
+ extraStyle: options.extraStyle,
});
if (!prompt) throw new Error('enqueueVisualImage: prompt is empty (no description, no style)');
diff --git a/server/services/promptService.js b/server/services/promptService.js
index 4ca3d7177b..0e81744833 100644
--- a/server/services/promptService.js
+++ b/server/services/promptService.js
@@ -10,7 +10,10 @@
* `templateEngine === 'mustache'` semantics still hold; we extend them.
*/
+import { join } from 'path';
import { applyTemplate } from '../lib/promptTemplate.js';
+import { expandPartials } from '../lib/promptPartials.js';
+import { PATHS } from '../lib/fileUtils.js';
// This will be initialized by server/index.js and set via setAIToolkit()
let aiToolkitInstance = null;
@@ -79,8 +82,16 @@ export async function buildPrompt(stageName, data = {}) {
const prompts = aiToolkitInstance.services.prompts;
const stage = prompts.getStage(stageName);
if (!stage) throw new Error(`Stage ${stageName} not found`);
- const template = await prompts.getStageTemplate(stageName);
- if (!template) throw new Error(`Template for ${stageName} not found`);
+ const rawTemplate = await prompts.getStageTemplate(stageName);
+ if (!rawTemplate) throw new Error(`Template for ${stageName} not found`);
+ // Expand `{{> partial-name }}` references against data/prompts/_partials/
+ // BEFORE the variable+section pass so a partial can carry its own
+ // {{variables}} that resolve against the same render context as the
+ // including template. Cheap when no partials are referenced — the expander
+ // short-circuits on a missing `{{>` sentinel.
+ const template = await expandPartials(rawTemplate, {
+ partialsDir: join(PATHS.data, 'prompts', '_partials'),
+ });
// Auto-merge stage-declared shared variables (variables.json) into the
// render context so templates can reference `{{schemaSnippet}}` etc.
// without callers having to know which named variables their stage uses.
diff --git a/server/services/worldBuilder.js b/server/services/worldBuilder.js
index 3aca2a998c..ee627c2ad7 100644
--- a/server/services/worldBuilder.js
+++ b/server/services/worldBuilder.js
@@ -25,6 +25,7 @@
import { join } from 'path';
import { randomUUID } from 'crypto';
import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';
+import { composeStyledPrompt } from '../lib/composeStyledPrompt.js';
const STATE_PATH = join(PATHS.data, 'world-builder.json');
@@ -343,8 +344,10 @@ export function compilePrompts(world, options = {}) {
}
const batchPerVariation = Math.max(1, Math.min(20, Number(options.batchPerVariation) || 1));
- const stylePart = world.stylePrompt?.trim();
- const negativePrompt = world.negativePrompt?.trim() || '';
+ const stylePreset = {
+ prompt: world.stylePrompt?.trim() || '',
+ negativePrompt: world.negativePrompt?.trim() || '',
+ };
const compiled = [];
if (promptMode === 'variations' || promptMode === 'all') {
@@ -356,7 +359,7 @@ export function compilePrompts(world, options = {}) {
? variations
: variations.filter((v) => Array.isArray(sel) && sel.some((s) => s.toLowerCase() === v.label.toLowerCase()));
for (const variation of filtered) {
- const prompt = [stylePart, variation.prompt].filter(Boolean).join(', ');
+ const { prompt, negativePrompt } = composeStyledPrompt(variation.prompt, '', stylePreset);
for (let i = 0; i < batchPerVariation; i += 1) {
compiled.push({
category,
@@ -377,7 +380,7 @@ export function compilePrompts(world, options = {}) {
? sheets
: sheets.filter((s) => Array.isArray(sheetSelection) && sheetSelection.some((label) => label.toLowerCase() === s.label.toLowerCase()));
for (const sheet of filteredSheets) {
- const prompt = [stylePart, sheet.prompt].filter(Boolean).join(', ');
+ const { prompt, negativePrompt } = composeStyledPrompt(sheet.prompt, '', stylePreset);
const category = sheet.kind === 'world_pitch_poster'
? 'world_pitch_posters'
: 'composite_sheets';
diff --git a/server/services/worldBuilder.test.js b/server/services/worldBuilder.test.js
index ace2e4cebe..12cc13cee5 100644
--- a/server/services/worldBuilder.test.js
+++ b/server/services/worldBuilder.test.js
@@ -129,7 +129,9 @@ describe('worldBuilder service', () => {
const compiled = svc.compilePrompts(w);
// 2 landscapes + 1 character = 3 (other categories empty)
expect(compiled).toHaveLength(3);
- expect(compiled[0].prompt).toBe('moebius linework, scavengers reign palette, crystalline canyon, alien sun');
+ // Style prefix uses `. ` separator (composeStyledPrompt convention,
+ // shared with the scenePrompt composer in the client).
+ expect(compiled[0].prompt).toBe('moebius linework, scavengers reign palette. crystalline canyon, alien sun');
expect(compiled[0].category).toBe('landscapes');
expect(compiled[0].label).toBe('Crystal Canyon');
expect(compiled[0].negativePrompt).toBe('blurry, lowres');
@@ -209,7 +211,7 @@ describe('worldBuilder service', () => {
expect(compiled[0]).toMatchObject({
category: 'composite_sheets',
label: 'Canopy Symbiotes sheet',
- prompt: 'moebius linework, scavengers reign palette, clean costume reference sheet, lineup, materials, fasteners, palette',
+ prompt: 'moebius linework, scavengers reign palette. clean costume reference sheet, lineup, materials, fasteners, palette',
});
});
diff --git a/server/services/writersRoom/characters.js b/server/services/writersRoom/characters.js
index 652a0fd62a..5a120dd105 100644
--- a/server/services/writersRoom/characters.js
+++ b/server/services/writersRoom/characters.js
@@ -1,70 +1,46 @@
/**
* Writers Room — editable character profile bible.
*
- * Canonical, user-editable character roster per work, stored at
- * data/writers-room/works/<workId>/characters.json. Distinct from analysis
- * snapshots: the snapshot in data/.../analysis/ is immutable history; this
- * file is the working bible that survives across analysis runs and can be
- * hand-edited by the writer.
+ * Per-work canonical roster stored at data/writers-room/works/<workId>/
+ * characters.json. Distinct from the immutable analysis snapshots — the
+ * snapshot is history; this file is the working bible that survives across
+ * runs and accepts hand-edits.
*
- * Merge rule: a re-run of `characters` analysis fills empty fields and adds
- * new characters, but never overwrites a non-empty field on an existing
- * profile. The writer's edits are authoritative.
+ * Shape + extraction-merge live in `server/lib/storyBible.js`; this module
+ * owns CRUD, file I/O, and the writers-room id prefix (`wr-char-`).
*/
import { join } from 'path';
import { randomUUID } from 'crypto';
import { PATHS, atomicWrite, ensureDir, readJSONFile } from '../../lib/fileUtils.js';
+import {
+ sanitizeCharacter,
+ sanitizeBibleList,
+ mergeExtractedBible,
+ normalizeBibleName,
+} from '../../lib/storyBible.js';
import { nowIso, badRequest, notFound, assertValidWorkId } from './_shared.js';
const CHAR_ID_RE = /^wr-char-[0-9a-f-]+$/i;
+const ID_PREFIX = 'wr-char-';
const root = () => join(PATHS.data, 'writers-room');
const charsFile = (workId) => {
- // Defense-in-depth: the route layer validates the URL parameter, but this
- // module is also imported directly (e.g. by mergeExtractedCharacters from
- // the analysis pipeline). Refusing path-traversal-shaped ids here makes
- // workId-as-filesystem-path safe regardless of caller.
+ // Defense-in-depth: routes validate the URL parameter, but this module is
+ // also imported directly (mergeExtractedCharacters from the analysis
+ // pipeline). Refusing path-traversal-shaped ids here makes workId-as-fs-
+ // path safe regardless of caller.
assertValidWorkId(workId);
return join(root(), 'works', workId, 'characters.json');
};
const EDITABLE_FIELDS = ['name', 'aliases', 'role', 'physicalDescription', 'personality', 'background', 'notes'];
-function emptyProfile() {
- return {
- id: '',
- name: '',
- aliases: [],
- role: '',
- physicalDescription: '',
- personality: '',
- background: '',
- notes: '',
- firstAppearance: null,
- evidence: [],
- missingFromProse: [],
- source: 'user',
- createdAt: nowIso(),
- updatedAt: nowIso(),
- };
-}
-
-function normalizeName(name) {
- return String(name || '').trim().toLowerCase();
-}
-
-function isBlank(v) {
- if (v == null) return true;
- if (Array.isArray(v)) return v.length === 0;
- if (typeof v === 'string') return v.trim() === '';
- return false;
-}
-
async function loadFile(workId) {
const fallback = { characters: [], updatedAt: null };
const parsed = await readJSONFile(charsFile(workId), fallback);
- return parsed && Array.isArray(parsed.characters) ? parsed : fallback;
+ if (!parsed || !Array.isArray(parsed.characters)) return fallback;
+ return { ...parsed, characters: sanitizeBibleList(parsed.characters, 'character', { idPrefix: ID_PREFIX }) };
}
async function saveFile(workId, state) {
@@ -90,19 +66,17 @@ export async function createCharacter(workId, patch = {}) {
const name = String(patch.name || '').trim();
if (!name) throw badRequest('Character name required');
const state = await loadFile(workId);
- if (state.characters.some((c) => normalizeName(c.name) === normalizeName(name))) {
+ if (state.characters.some((c) => normalizeBibleName(c.name) === normalizeBibleName(name))) {
throw badRequest(`A character named "${name}" already exists`);
}
- const profile = {
- ...emptyProfile(),
- id: `wr-char-${randomUUID()}`,
- name,
- source: 'user',
- };
+ // Merge user-supplied editable fields into the canonical empty profile,
+ // then route through the shared sanitizer so caps/array-cleanup apply.
+ const draft = { id: `${ID_PREFIX}${randomUUID()}`, name, source: 'user' };
for (const field of EDITABLE_FIELDS) {
if (field === 'name') continue;
- if (patch[field] !== undefined) profile[field] = patch[field];
+ if (patch[field] !== undefined) draft[field] = patch[field];
}
+ const profile = sanitizeCharacter(draft, { idPrefix: ID_PREFIX, preserveTimestamps: false });
state.characters.push(profile);
await saveFile(workId, state);
return profile;
@@ -119,22 +93,21 @@ export async function updateCharacter(workId, characterId, patch = {}) {
if (field === 'name') {
const newName = String(patch.name || '').trim();
if (!newName) throw badRequest('Character name cannot be blank');
- const conflict = state.characters.some((c) => c.id !== characterId && normalizeName(c.name) === normalizeName(newName));
+ const conflict = state.characters.some((c) => c.id !== characterId && normalizeBibleName(c.name) === normalizeBibleName(newName));
if (conflict) throw badRequest(`A character named "${newName}" already exists`);
next.name = newName;
- } else if (field === 'aliases') {
- next.aliases = Array.isArray(patch.aliases)
- ? patch.aliases.map((a) => String(a).trim()).filter(Boolean)
- : [];
} else {
next[field] = patch[field];
}
}
next.source = 'user';
- next.updatedAt = nowIso();
- state.characters[idx] = next;
+ // Re-sanitize so freshly-supplied fields get capped/cleaned consistently.
+ state.characters[idx] = sanitizeCharacter(
+ { ...next, updatedAt: nowIso() },
+ { idPrefix: ID_PREFIX, preserveTimestamps: true },
+ );
await saveFile(workId, state);
- return next;
+ return state.characters[idx];
}
export async function deleteCharacter(workId, characterId) {
@@ -148,77 +121,14 @@ export async function deleteCharacter(workId, characterId) {
}
/**
- * Merge an AI-extracted character set into the editable bible.
- * - Existing characters (matched by case-insensitive name OR by an alias)
- * keep every non-blank field. Only blank fields get filled from `extracted`.
- * - New characters are inserted with `source: 'ai'`.
- * - `firstAppearance`, `evidence`, and `missingFromProse` always reflect the
- * latest analysis (they're prose-derived, not user-curated).
- *
- * Returns the merged character list.
+ * Merge an AI-extracted character set into the editable bible. Delegates
+ * to `mergeExtractedBible` so the writers-room and pipeline-side merges
+ * follow byte-identical rules.
*/
export async function mergeExtractedCharacters(workId, extracted) {
if (!Array.isArray(extracted)) return listCharacters(workId);
const state = await loadFile(workId);
- const byKey = new Map();
- // Index every character by its name AND every alias so a later batch entry
- // referencing the same person via any of those tokens resolves to one
- // canonical profile (no duplicates).
- const indexCharacter = (c) => {
- const nameKey = normalizeName(c.name);
- if (nameKey) byKey.set(nameKey, c);
- for (const alias of c.aliases || []) {
- const aliasKey = normalizeName(alias);
- if (aliasKey) byKey.set(aliasKey, c);
- }
- };
- for (const c of state.characters) indexCharacter(c);
- for (const incoming of extracted) {
- if (!incoming || !incoming.name) continue;
- const key = normalizeName(incoming.name);
- const existing = byKey.get(key);
- if (existing) {
- // Fill in only blank user-editable fields. Prose-derived metadata
- // (firstAppearance / evidence / missingFromProse) always refreshes.
- for (const field of ['role', 'physicalDescription', 'personality', 'background']) {
- if (isBlank(existing[field]) && !isBlank(incoming[field])) {
- existing[field] = incoming[field];
- }
- }
- if (isBlank(existing.aliases) && Array.isArray(incoming.aliases)) {
- existing.aliases = incoming.aliases.map((a) => String(a).trim()).filter(Boolean);
- // Re-index this character under its newly-filled aliases so later
- // entries in the same batch that reference the character via one of
- // those aliases resolve to this profile instead of being inserted
- // as a duplicate.
- indexCharacter(existing);
- }
- existing.firstAppearance = incoming.firstAppearance ?? existing.firstAppearance ?? null;
- existing.evidence = Array.isArray(incoming.evidence) ? incoming.evidence : (existing.evidence || []);
- existing.missingFromProse = Array.isArray(incoming.missingFromProse) ? incoming.missingFromProse : [];
- existing.updatedAt = nowIso();
- } else {
- const profile = {
- ...emptyProfile(),
- id: `wr-char-${randomUUID()}`,
- name: String(incoming.name).trim(),
- aliases: Array.isArray(incoming.aliases) ? incoming.aliases.map((a) => String(a).trim()).filter(Boolean) : [],
- role: String(incoming.role || '').trim(),
- physicalDescription: String(incoming.physicalDescription || '').trim(),
- personality: String(incoming.personality || '').trim(),
- background: String(incoming.background || '').trim(),
- firstAppearance: incoming.firstAppearance ?? null,
- evidence: Array.isArray(incoming.evidence) ? incoming.evidence : [],
- missingFromProse: Array.isArray(incoming.missingFromProse) ? incoming.missingFromProse : [],
- source: 'ai',
- };
- state.characters.push(profile);
- // Index the new profile under both its name and any aliases so a
- // later entry in this batch that uses one of those aliases as its
- // `name` matches this character instead of creating a second one.
- indexCharacter(profile);
- }
- }
+ state.characters = mergeExtractedBible(state.characters, extracted, 'character', { idPrefix: ID_PREFIX });
await saveFile(workId, state);
- return state.characters.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
+ return state.characters;
}
diff --git a/server/services/writersRoom/evaluator.js b/server/services/writersRoom/evaluator.js
index f5f701f76d..c750a448f3 100644
--- a/server/services/writersRoom/evaluator.js
+++ b/server/services/writersRoom/evaluator.js
@@ -5,13 +5,14 @@
*/
import { join } from 'path';
-import { spawn } from 'child_process';
import { readFile, readdir, rm } from 'fs/promises';
import { PATHS, atomicWrite, ensureDir, safeJSONParse } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { stripCodeFences } from '../../lib/aiProvider.js';
-import { getActiveProvider, getProviderById } from '../providers.js';
-import { buildPrompt, getStage } from '../promptService.js';
+import { runStagedLLM } from '../../lib/stageRunner.js';
+import { extractBible } from '../../lib/bibleExtractor.js';
+import { extractScenes, SOURCE_KIND } from '../../lib/sceneExtractor.js';
+import { BIBLE_KIND } from '../../lib/storyBible.js';
import { ANALYSIS_KINDS } from '../../lib/writersRoomPresets.js';
import { getWorkWithBody } from './local.js';
import { listCharacters, mergeExtractedCharacters } from './characters.js';
@@ -45,171 +46,13 @@ const analysisDir = (workId) => {
};
const analysisPath = (workId, id) => join(analysisDir(workId), `${id}.json`);
-// ---------- LLM invocation ----------
-
-// Tier names used in stage configs (PromptManager UI). Map to the provider's
-// configured per-tier model id; an unset tier falls back to defaultModel so
-// stages with `model: 'heavy'` still run on providers that don't break out tiers.
-const TIER_TO_MODEL_KEY = {
- default: 'defaultModel',
- quick: 'lightModel',
- coding: 'mediumModel',
- heavy: 'heavyModel',
-};
-
-function isTierName(model) {
- return typeof model === 'string' && model in TIER_TO_MODEL_KEY;
-}
-
-function resolveModel(provider, stageModel) {
- if (!stageModel) return provider.defaultModel || null;
- if (isTierName(stageModel)) {
- return provider[TIER_TO_MODEL_KEY[stageModel]] || provider.defaultModel || null;
- }
- return stageModel;
-}
-
-// Stage config can pin a specific provider via `stage.provider`. When set we
-// must use that provider (or fail) — falling back to the active provider would
-// silently route the call through whatever's currently selected, defeating the
-// whole point of the per-stage override.
-async function resolveProviderForStage(stage) {
- if (stage?.provider) {
- const pinned = await getProviderById(stage.provider).catch(() => null);
- if (pinned?.enabled) return pinned;
- throw new ServerError(
- `Stage provider "${stage.provider}" is not available — re-pick a provider in Prompts or the Storyboard settings`,
- { status: 503, code: 'STAGE_PROVIDER_UNAVAILABLE' }
- );
- }
- const active = await getActiveProvider().catch(() => null);
- if (active?.enabled) return active;
- throw new ServerError('No AI provider available', { status: 503, code: 'NO_PROVIDER' });
-}
-
-async function callApiProvider(provider, model, prompt, temperature) {
- const headers = { 'Content-Type': 'application/json' };
- if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;
- const response = await fetch(`${provider.endpoint}/chat/completions`, {
- method: 'POST',
- headers,
- body: JSON.stringify({
- model,
- messages: [{ role: 'user', content: prompt }],
- temperature,
- }),
- signal: AbortSignal.timeout(provider.timeout || 300000),
- });
- if (!response.ok) {
- const text = await response.text().catch(() => '');
- throw new Error(`AI API error: ${response.status} - ${text.slice(0, 500)}`);
- }
- const data = await response.json();
- return data.choices?.[0]?.message?.content || '';
-}
-
-// Each CLI needs a different incantation to run non-interactively from a
-// server process. Get it wrong and the CLI either hangs waiting for a TTY or
-// exits with "Error: stdin is not a terminal". Mirrors `runner.js` /
-// `agentCliSpawning.js` so the writers-room path agrees with how PortOS
-// already spawns these CLIs everywhere else.
-function buildCliInvocation(provider, model) {
- const baseArgs = [...(provider.args || [])];
- if (provider.headlessArgs?.length) baseArgs.push(...provider.headlessArgs);
- const effectiveModel = provider.id === 'codex' && model === 'codex-configured-default' ? null : model;
-
- switch (provider.id) {
- case 'gemini-cli': {
- const args = [...baseArgs];
- if (!args.includes('--output-format') && !args.includes('-o')) {
- args.push('--output-format', 'text');
- }
- if (effectiveModel) args.push('--model', effectiveModel);
- return { args, promptViaStdin: false };
- }
- case 'codex': {
- // `codex exec -` reads the prompt from stdin. Without `exec` codex
- // launches its REPL and bails with "Error: stdin is not a terminal".
- const args = [...baseArgs, 'exec'];
- if (effectiveModel) args.push('--model', effectiveModel);
- args.push('-');
- return { args, promptViaStdin: true };
- }
- case 'claude-code':
- case 'claude-code-bedrock': {
- const args = [...baseArgs, '-p', '-'];
- if (effectiveModel) args.push('--model', effectiveModel);
- return { args, promptViaStdin: true };
- }
- default: {
- const args = [...baseArgs];
- if (effectiveModel) args.push('--model', effectiveModel);
- return { args, promptViaStdin: true };
- }
- }
-}
-
-function callCliProvider(provider, model, prompt) {
- return new Promise((resolve, reject) => {
- const { args, promptViaStdin } = buildCliInvocation(provider, model);
- // gemini-cli takes the prompt as a flag because its non-interactive mode
- // requires `--prompt` plus stdio: ['ignore', ...]. Every other CLI accepts
- // the prompt on stdin, which dodges argv ceilings on long drafts.
- if (!promptViaStdin) args.push('--prompt', prompt);
- const child = spawn(provider.command, args, {
- env: (() => { const e = { ...process.env, ...provider.envVars }; delete e.CLAUDECODE; return e; })(),
- stdio: [promptViaStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'],
- shell: false,
- windowsHide: true,
- });
- let output = '';
- child.stdout.on('data', (d) => { output += d.toString(); });
- child.stderr.on('data', (d) => { output += d.toString(); });
- const timeoutMs = provider.timeout || 300000;
- const killer = setTimeout(() => {
- child.kill('SIGKILL');
- reject(new Error(`CLI AI call timed out after ${timeoutMs}ms`));
- }, timeoutMs);
- child.on('close', (code) => {
- clearTimeout(killer);
- if (code === 0) resolve(output);
- // Tail the output rather than head — CLI banners/transcripts come first
- // and the actual error/stack lives at the end. 500 chars of header was
- // hiding real failures (e.g. provider auth errors) under a Codex banner.
- else reject(new Error(`CLI exited with code ${code}${output ? ': ' + output.slice(-2000) : ''}`));
- });
- child.on('error', (err) => { clearTimeout(killer); reject(err); });
- if (promptViaStdin) child.stdin.end(prompt);
- });
-}
-
-async function callAI(stageName, variables, temperature) {
- const stage = getStage(stageName);
- const provider = await resolveProviderForStage(stage);
- const prompt = await buildPrompt(stageName, variables);
- let model = resolveModel(provider, stage?.model);
- if (provider.id === 'gemini-cli' && !model) {
- model = provider.lightModel || 'gemini-2.5-flash';
- }
- console.log(`📝 wr eval: ${provider.id} / ${model || '(default)'} / ${stageName}`);
- if (provider.type === 'api') {
- const content = await callApiProvider(provider, model, prompt, temperature);
- return { content, model: model || null, providerId: provider.id };
- }
- if (provider.type === 'cli') {
- const content = await callCliProvider(provider, model, prompt);
- return { content, model: model || null, providerId: provider.id };
- }
- throw new Error(`Unsupported provider type: ${provider.type}`);
-}
-
// ---------- response parsing ----------
function extractJson(text) {
if (!text || typeof text !== 'string') throw new Error('Empty AI response');
let str = stripCodeFences(text);
// Some providers prepend explanation text; pull the first balanced object/array.
- const objMatch = str.match(/[\{\[][\s\S]*[\}\]]/);
+ const objMatch = str.match(/[{[][\s\S]*[\]}]/);
if (objMatch) str = objMatch[0];
return JSON.parse(str);
}
@@ -232,83 +75,18 @@ const SHAPERS = {
suggestions: Array.isArray(parsed.suggestions) ? parsed.suggestions.filter((s) => s && typeof s === 'object') : [],
};
},
- characters: (raw) => {
- const parsed = extractJson(raw);
- const list = Array.isArray(parsed.characters) ? parsed.characters : [];
- return {
- characters: list
- .filter((c) => c && typeof c === 'object' && typeof c.name === 'string' && c.name.trim())
- .map((c) => ({
- name: c.name.trim(),
- aliases: Array.isArray(c.aliases) ? c.aliases.filter((a) => typeof a === 'string') : [],
- role: typeof c.role === 'string' ? c.role : '',
- physicalDescription: typeof c.physicalDescription === 'string' ? c.physicalDescription : '',
- personality: typeof c.personality === 'string' ? c.personality : '',
- background: typeof c.background === 'string' ? c.background : '',
- firstAppearance: typeof c.firstAppearance === 'string' ? c.firstAppearance : null,
- evidence: Array.isArray(c.evidence) ? c.evidence.filter((e) => typeof e === 'string') : [],
- missingFromProse: Array.isArray(c.missingFromProse) ? c.missingFromProse.filter((m) => typeof m === 'string') : [],
- })),
- };
- },
- script: (raw) => {
- const parsed = extractJson(raw);
- const scenes = Array.isArray(parsed.scenes) ? parsed.scenes : [];
- return {
- title: typeof parsed.title === 'string' ? parsed.title : null,
- logline: typeof parsed.logline === 'string' ? parsed.logline : null,
- scenes: scenes.map((s, i) => ({
- id: typeof s.id === 'string' ? s.id : `scene-${String(i + 1).padStart(2, '0')}`,
- heading: typeof s.heading === 'string' ? s.heading : `Scene ${i + 1}`,
- slugline: typeof s.slugline === 'string' ? s.slugline : null,
- summary: typeof s.summary === 'string' ? s.summary : '',
- characters: Array.isArray(s.characters) ? s.characters.filter((c) => typeof c === 'string') : [],
- action: typeof s.action === 'string' ? s.action : '',
- dialogue: Array.isArray(s.dialogue) ? s.dialogue.filter((d) => d && typeof d === 'object') : [],
- visualPrompt: typeof s.visualPrompt === 'string' ? s.visualPrompt : '',
- sourceSegmentIds: Array.isArray(s.sourceSegmentIds) ? s.sourceSegmentIds.filter((id) => typeof id === 'string') : [],
- })),
- };
- },
- settings: (raw) => {
- const parsed = extractJson(raw);
- const list = Array.isArray(parsed.settings) ? parsed.settings : [];
- return {
- settings: list
- .filter((s) => s && typeof s === 'object' && (typeof s.slugline === 'string' || typeof s.name === 'string'))
- .map((s) => ({
- slugline: typeof s.slugline === 'string' ? s.slugline.trim() : '',
- name: typeof s.name === 'string' ? s.name.trim() : '',
- description: typeof s.description === 'string' ? s.description : '',
- palette: typeof s.palette === 'string' ? s.palette : '',
- era: typeof s.era === 'string' ? s.era : '',
- weather: typeof s.weather === 'string' ? s.weather : '',
- recurringDetails: typeof s.recurringDetails === 'string' ? s.recurringDetails : '',
- firstAppearance: typeof s.firstAppearance === 'string' ? s.firstAppearance : null,
- evidence: Array.isArray(s.evidence) ? s.evidence.filter((e) => typeof e === 'string') : [],
- missingFromProse: Array.isArray(s.missingFromProse) ? s.missingFromProse.filter((m) => typeof m === 'string') : [],
- })),
- };
- },
- objects: (raw) => {
- const parsed = extractJson(raw);
- const list = Array.isArray(parsed.objects) ? parsed.objects : [];
- return {
- objects: list
- .filter((o) => o && typeof o === 'object' && typeof o.name === 'string' && o.name.trim())
- .map((o) => ({
- name: o.name.trim(),
- aliases: Array.isArray(o.aliases) ? o.aliases.filter((a) => typeof a === 'string') : [],
- description: typeof o.description === 'string' ? o.description : '',
- significance: typeof o.significance === 'string' ? o.significance : '',
- firstAppearance: typeof o.firstAppearance === 'string' ? o.firstAppearance : null,
- evidence: Array.isArray(o.evidence) ? o.evidence.filter((e) => typeof e === 'string') : [],
- missingFromProse: Array.isArray(o.missingFromProse) ? o.missingFromProse.filter((m) => typeof m === 'string') : [],
- })),
- };
- },
+ // characters / settings / objects route through `extractBible`,
+ // and `script` routes through `extractScenes` — no per-kind shaper here.
};
+const BIBLE_ANALYSIS = Object.freeze({
+ characters: { kind: BIBLE_KIND.CHARACTER, list: listCharacters, merge: mergeExtractedCharacters },
+ settings: { kind: BIBLE_KIND.SETTING, list: listSettings, merge: mergeExtractedSettings },
+ objects: { kind: BIBLE_KIND.OBJECT, list: listObjects, merge: mergeExtractedObjects },
+});
+
+const isBibleKind = (k) => k in BIBLE_ANALYSIS;
+
// ---------- storage ----------
async function listAnalysisIds(workId) {
@@ -501,76 +279,73 @@ export async function runAnalysis(workId, { kind } = {}) {
// back in one round-trip. A failure mid-call is persisted as a `failed`
// snapshot so partial work never silently disappears.
try {
- const variables = {
- work: {
- id: manifest.id,
- title: manifest.title,
- kind: manifest.kind,
- status: manifest.status,
- wordCount: draft?.wordCount || 0,
- },
- draftBody: body,
- returnsJson,
+ const workCtx = {
+ id: manifest.id,
+ title: manifest.title,
+ kind: manifest.kind,
+ status: manifest.status,
+ wordCount: draft?.wordCount || 0,
};
- // Strip down each bible to the fields the prompts care about — no ids,
- // timestamps, or source markers. Same shape goes to both the bible's own
- // re-extraction (preserve-user-edits) AND to script (Adapt) so it can
- // cite canonical names + descriptions in visualPrompt fields.
- const trimCharacter = (c) => ({
- name: c.name,
- aliases: c.aliases,
- role: c.role,
- physicalDescription: c.physicalDescription,
- personality: c.personality,
- background: c.background,
- });
- const trimSetting = (s) => ({
- name: s.name,
- slugline: s.slugline,
- description: s.description,
- palette: s.palette,
- era: s.era,
- weather: s.weather,
- recurringDetails: s.recurringDetails,
- });
- // For 'script' both bibles load — fire them in parallel so the script
- // pipeline doesn't pay two sequential disk reads. For 'characters' or
- // 'settings' alone Promise.all is degenerate (one element) but the shape
- // keeps the call site uniform.
- const trimObject = (o) => ({
- name: o.name,
- aliases: o.aliases,
- description: o.description,
- significance: o.significance,
- });
- const [existingChars, existingSets, existingObjs] = await Promise.all([
- (kind === 'characters' || kind === 'script') ? listCharacters(workId) : null,
- (kind === 'settings' || kind === 'script') ? listSettings(workId) : null,
- (kind === 'objects' || kind === 'script') ? listObjects(workId) : null,
- ]);
- if (existingChars) variables.existingCharactersJson = JSON.stringify(existingChars.map(trimCharacter));
- if (existingSets) variables.existingSettingsJson = JSON.stringify(existingSets.map(trimSetting));
- if (existingObjs) variables.existingObjectsJson = JSON.stringify(existingObjs.map(trimObject));
- const temperature = kind === 'format' ? 0.2 : 0.4;
- const { content, model: usedModel, providerId: usedProvider } = await callAI(stage, variables, temperature);
- const result = SHAPERS[kind](content);
- let mergedProfiles = null;
- if (kind === 'characters') {
- mergedProfiles = await mergeExtractedCharacters(workId, result.characters || []);
- } else if (kind === 'settings') {
- mergedProfiles = await mergeExtractedSettings(workId, result.settings || []);
- } else if (kind === 'objects') {
- mergedProfiles = await mergeExtractedObjects(workId, result.objects || []);
+ if (isBibleKind(kind)) {
+ const { kind: bibleKind, list, merge } = BIBLE_ANALYSIS[kind];
+ const existing = await list(workId);
+ const { extracted, runId, providerId, model } = await extractBible({
+ kind: bibleKind,
+ corpus: body,
+ existing,
+ context: { work: workCtx, returnsJson },
+ source: `writers-room-${kind}`,
+ });
+ const mergedProfiles = await merge(workId, extracted);
+ const finished = {
+ ...baseSnapshot,
+ status: 'succeeded',
+ providerId, model,
+ result: { [kind]: extracted, mergedProfiles },
+ rawResponse: JSON.stringify({ [kind]: extracted }),
+ runId,
+ completedAt: nowIso(),
+ };
+ await saveAnalysis(workId, finished);
+ return finished;
+ }
+
+ if (kind === 'script') {
+ const [characters, settings, objects] = await Promise.all([
+ listCharacters(workId), listSettings(workId), listObjects(workId),
+ ]);
+ const { extracted, runId, providerId, model } = await extractScenes({
+ source: body,
+ sourceKind: SOURCE_KIND.PROSE,
+ characters, settings, objects,
+ work: workCtx,
+ tag: 'writers-room-script',
+ });
+ const finished = {
+ ...baseSnapshot,
+ status: 'succeeded',
+ providerId, model,
+ result: extracted,
+ rawResponse: JSON.stringify(extracted),
+ runId,
+ completedAt: nowIso(),
+ };
+ await saveAnalysis(workId, finished);
+ return finished;
}
+
+ const variables = { work: workCtx, draftBody: body, returnsJson };
+ const { content, model: usedModel, providerId: usedProvider } = await runStagedLLM(stage, variables, {
+ source: `writers-room-${kind}`,
+ });
+ const result = SHAPERS[kind](content);
const finished = {
...baseSnapshot,
status: 'succeeded',
providerId: usedProvider,
model: usedModel,
- result: mergedProfiles
- ? { ...result, mergedProfiles }
- : result,
+ result,
rawResponse: content,
completedAt: nowIso(),
};
diff --git a/server/services/writersRoom/evaluator.test.js b/server/services/writersRoom/evaluator.test.js
deleted file mode 100644
index a560125e7f..0000000000
--- a/server/services/writersRoom/evaluator.test.js
+++ /dev/null
@@ -1,132 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-import EventEmitter from 'events';
-
-vi.mock('child_process', async (importOriginal) => {
- const actual = await importOriginal();
- return { ...actual, spawn: vi.fn() };
-});
-
-vi.mock('../../lib/fileUtils.js', () => ({
- PATHS: { data: '/tmp/wr-eval-test' },
- atomicWrite: vi.fn().mockResolvedValue(undefined),
- ensureDir: vi.fn().mockResolvedValue(undefined),
- safeJSONParse: vi.fn((v) => (typeof v === 'string' ? JSON.parse(v) : v)),
-}));
-
-vi.mock('../providers.js', () => ({
- getActiveProvider: vi.fn(),
- getProviderById: vi.fn(),
-}));
-
-vi.mock('../promptService.js', () => ({
- buildPrompt: vi.fn().mockResolvedValue('test prompt'),
- getStage: vi.fn().mockReturnValue({ stage: 'writers-room-evaluate', model: null }),
-}));
-
-vi.mock('./local.js', () => ({
- getWorkWithBody: vi.fn(),
-}));
-
-vi.mock('./characters.js', () => ({
- listCharacters: vi.fn().mockResolvedValue([]),
- mergeExtractedCharacters: vi.fn().mockResolvedValue([]),
-}));
-
-vi.mock('./settings.js', () => ({
- listSettings: vi.fn().mockResolvedValue([]),
- mergeExtractedSettings: vi.fn().mockResolvedValue([]),
-}));
-
-const { spawn } = await import('child_process');
-const providers = await import('../providers.js');
-const local = await import('./local.js');
-const evaluator = await import('./evaluator.js');
-const { runAnalysis } = evaluator;
-
-// A minimal work manifest + body that satisfies runAnalysis's guard checks
-// (WORK_ID_RE requires wr-work- followed by only hex digits and dashes)
-const FAKE_WORK_ID = 'wr-work-aabbccdd-eeff-1122-3344-556677889900';
-const fakeWorkManifest = {
- id: FAKE_WORK_ID,
- title: 'Test Work',
- kind: 'novel',
- status: 'drafting',
- activeDraftVersionId: 'wr-draft-v1',
- drafts: [{ id: 'wr-draft-v1', wordCount: 10, contentHash: 'abc123' }],
-};
-
-function makeChild(exitCode = 0) {
- const child = new EventEmitter();
- child.stdout = new EventEmitter();
- child.stderr = new EventEmitter();
- child.stdin = { on: vi.fn(), end: vi.fn() };
- child.kill = vi.fn();
- child.killed = false;
- return child;
-}
-
-beforeEach(() => {
- vi.clearAllMocks();
- local.getWorkWithBody.mockResolvedValue({
- manifest: fakeWorkManifest,
- body: 'Once upon a time there was a test.',
- });
-});
-
-describe('evaluator buildCliInvocation — Codex sentinel suppression', () => {
- it('omits --model when the model is codex-configured-default', async () => {
- providers.getActiveProvider.mockResolvedValue({
- id: 'codex',
- type: 'cli',
- enabled: true,
- command: 'codex',
- args: [],
- defaultModel: 'codex-configured-default',
- timeout: 5000,
- });
-
- const child = makeChild();
- spawn.mockReturnValue(child);
-
- setImmediate(() => {
- child.stdout.emit('data', Buffer.from(JSON.stringify({ logline: 'a', summary: 'b', themes: [], strengths: [], issues: [], suggestions: [] })));
- child.emit('close', 0);
- });
-
- await runAnalysis(FAKE_WORK_ID, { kind: 'evaluate' });
-
- const [, capturedArgs] = spawn.mock.calls.at(-1);
- expect(capturedArgs).not.toContain('--model');
- expect(capturedArgs).not.toContain('codex-configured-default');
- // Codex exec + stdin marker must still be present
- expect(capturedArgs).toContain('exec');
- expect(capturedArgs).toContain('-');
- });
-
- it('passes --model when a real model name is provided', async () => {
- providers.getActiveProvider.mockResolvedValue({
- id: 'codex',
- type: 'cli',
- enabled: true,
- command: 'codex',
- args: [],
- defaultModel: 'o4-mini',
- timeout: 5000,
- });
-
- const child = makeChild();
- spawn.mockReturnValue(child);
-
- setImmediate(() => {
- child.stdout.emit('data', Buffer.from(JSON.stringify({ logline: 'a', summary: 'b', themes: [], strengths: [], issues: [], suggestions: [] })));
- child.emit('close', 0);
- });
-
- await runAnalysis(FAKE_WORK_ID, { kind: 'evaluate' });
-
- const [, capturedArgs] = spawn.mock.calls.at(-1);
- const modelIdx = capturedArgs.indexOf('--model');
- expect(modelIdx).toBeGreaterThanOrEqual(0);
- expect(capturedArgs[modelIdx + 1]).toBe('o4-mini');
- });
-});
diff --git a/server/services/writersRoom/local.js b/server/services/writersRoom/local.js
index 2c0e64e2c4..6a87ed2638 100644
--- a/server/services/writersRoom/local.js
+++ b/server/services/writersRoom/local.js
@@ -245,6 +245,8 @@ export async function listWorks() {
activeDraftVersionId: manifest.activeDraftVersionId,
wordCount: activeDraft?.wordCount ?? 0,
draftCount: (manifest.drafts || []).length,
+ pipelineSeriesId: manifest.pipelineSeriesId || null,
+ pipelineIssueId: manifest.pipelineIssueId || null,
createdAt: manifest.createdAt,
updatedAt: manifest.updatedAt,
};
@@ -337,6 +339,24 @@ export async function updateWork(id, patch) {
return next;
}
+/**
+ * Bidirectional bridge link: record that this work was promoted to a pipeline
+ * series + first issue. Set once by `promoteToPipeline`; the WR side reads it
+ * to render the "Open in pipeline" CTA on the work detail page. Distinct from
+ * `updateWork` because the link isn't user-editable. Pass `null` to unlink.
+ */
+export async function linkToPipeline(id, { seriesId = null, issueId = null } = {}) {
+ const manifest = await getWork(id);
+ const next = {
+ ...manifest,
+ pipelineSeriesId: seriesId ? String(seriesId).slice(0, 64) : null,
+ pipelineIssueId: issueId ? String(issueId).slice(0, 64) : null,
+ updatedAt: nowIso(),
+ };
+ await saveManifest(id, next);
+ return next;
+}
+
export async function deleteWork(id) {
// 404 the caller if the manifest is missing; rm() with force:true would
// silently succeed on a non-existent dir and the user gets no signal.
diff --git a/server/services/writersRoom/objects.js b/server/services/writersRoom/objects.js
index 0f956d7190..a33b59cd99 100644
--- a/server/services/writersRoom/objects.js
+++ b/server/services/writersRoom/objects.js
@@ -1,22 +1,25 @@
/**
* Writers Room — editable recurring-objects bible.
*
- * Mirrors the characters/settings bible pattern (per-work canonical roster
- * stored at data/writers-room/works/<workId>/objects.json). Distinct from the
- * immutable analysis snapshot — the snapshot is history; this is the working
- * bible that survives across runs and accepts hand-edits.
- *
- * Merge rule: a re-run of `objects` analysis fills empty fields and adds new
- * objects, but never overwrites a non-empty field on an existing profile. The
- * writer's edits are authoritative.
+ * Per-work canonical roster stored at data/writers-room/works/<workId>/
+ * objects.json. Shape + extraction-merge live in `server/lib/storyBible.js`;
+ * this module owns CRUD, file I/O, and the writers-room id prefix
+ * (`wr-object-`).
*/
import { join } from 'path';
import { randomUUID } from 'crypto';
import { PATHS, atomicWrite, ensureDir, readJSONFile } from '../../lib/fileUtils.js';
+import {
+ sanitizeObject,
+ sanitizeBibleList,
+ mergeExtractedBible,
+ normalizeBibleName,
+} from '../../lib/storyBible.js';
import { nowIso, badRequest, notFound, assertValidWorkId } from './_shared.js';
const OBJECT_ID_RE = /^wr-object-[0-9a-f-]+$/i;
+const ID_PREFIX = 'wr-object-';
const root = () => join(PATHS.data, 'writers-room');
const objectsFile = (workId) => {
@@ -26,38 +29,11 @@ const objectsFile = (workId) => {
const EDITABLE_FIELDS = ['name', 'aliases', 'description', 'significance', 'notes'];
-function emptyProfile() {
- return {
- id: '',
- name: '',
- aliases: [],
- description: '',
- significance: '',
- notes: '',
- firstAppearance: null,
- evidence: [],
- missingFromProse: [],
- source: 'user',
- createdAt: nowIso(),
- updatedAt: nowIso(),
- };
-}
-
-function normalizeName(name) {
- return String(name || '').trim().toLowerCase();
-}
-
-function isBlank(v) {
- if (v == null) return true;
- if (Array.isArray(v)) return v.length === 0;
- if (typeof v === 'string') return v.trim() === '';
- return false;
-}
-
async function loadFile(workId) {
const fallback = { objects: [], updatedAt: null };
const parsed = await readJSONFile(objectsFile(workId), fallback);
- return parsed && Array.isArray(parsed.objects) ? parsed : fallback;
+ if (!parsed || !Array.isArray(parsed.objects)) return fallback;
+ return { ...parsed, objects: sanitizeBibleList(parsed.objects, 'object', { idPrefix: ID_PREFIX }) };
}
async function saveFile(workId, state) {
@@ -83,19 +59,15 @@ export async function createObject(workId, patch = {}) {
const name = String(patch.name || '').trim();
if (!name) throw badRequest('Object name required');
const state = await loadFile(workId);
- if (state.objects.some((o) => normalizeName(o.name) === normalizeName(name))) {
+ if (state.objects.some((o) => normalizeBibleName(o.name) === normalizeBibleName(name))) {
throw badRequest(`An object named "${name}" already exists`);
}
- const profile = {
- ...emptyProfile(),
- id: `wr-object-${randomUUID()}`,
- name,
- source: 'user',
- };
+ const draft = { id: `${ID_PREFIX}${randomUUID()}`, name, source: 'user' };
for (const field of EDITABLE_FIELDS) {
if (field === 'name') continue;
- if (patch[field] !== undefined) profile[field] = patch[field];
+ if (patch[field] !== undefined) draft[field] = patch[field];
}
+ const profile = sanitizeObject(draft, { idPrefix: ID_PREFIX, preserveTimestamps: false });
state.objects.push(profile);
await saveFile(workId, state);
return profile;
@@ -112,22 +84,20 @@ export async function updateObject(workId, objectId, patch = {}) {
if (field === 'name') {
const newName = String(patch.name || '').trim();
if (!newName) throw badRequest('Object name cannot be blank');
- const conflict = state.objects.some((o) => o.id !== objectId && normalizeName(o.name) === normalizeName(newName));
+ const conflict = state.objects.some((o) => o.id !== objectId && normalizeBibleName(o.name) === normalizeBibleName(newName));
if (conflict) throw badRequest(`An object named "${newName}" already exists`);
next.name = newName;
- } else if (field === 'aliases') {
- next.aliases = Array.isArray(patch.aliases)
- ? patch.aliases.map((a) => String(a).trim()).filter(Boolean)
- : [];
} else {
next[field] = patch[field];
}
}
next.source = 'user';
- next.updatedAt = nowIso();
- state.objects[idx] = next;
+ state.objects[idx] = sanitizeObject(
+ { ...next, updatedAt: nowIso() },
+ { idPrefix: ID_PREFIX, preserveTimestamps: true },
+ );
await saveFile(workId, state);
- return next;
+ return state.objects[idx];
}
export async function deleteObject(workId, objectId) {
@@ -140,65 +110,10 @@ export async function deleteObject(workId, objectId) {
return { ok: true };
}
-/**
- * Merge an AI-extracted object set into the editable bible.
- * Mirrors the characters merge: existing entries (by case-insensitive name OR
- * alias) keep every non-blank field, only blanks fill from incoming. New
- * objects are inserted with source: 'ai'. firstAppearance/evidence/
- * missingFromProse always refresh from the latest analysis.
- */
export async function mergeExtractedObjects(workId, extracted) {
if (!Array.isArray(extracted)) return listObjects(workId);
const state = await loadFile(workId);
- const byKey = new Map();
- const indexObject = (o) => {
- const nameKey = normalizeName(o.name);
- if (nameKey) byKey.set(nameKey, o);
- for (const alias of o.aliases || []) {
- const aliasKey = normalizeName(alias);
- if (aliasKey) byKey.set(aliasKey, o);
- }
- };
- for (const o of state.objects) indexObject(o);
- for (const incoming of extracted) {
- if (!incoming || !incoming.name) continue;
- const key = normalizeName(incoming.name);
- const existing = byKey.get(key);
- if (existing) {
- for (const field of ['description', 'significance']) {
- if (isBlank(existing[field]) && !isBlank(incoming[field])) {
- existing[field] = incoming[field];
- }
- }
- if (isBlank(existing.aliases) && Array.isArray(incoming.aliases)) {
- existing.aliases = incoming.aliases.map((a) => String(a).trim()).filter(Boolean);
- indexObject(existing);
- }
- // firstAppearance is prose-derived metadata that the latest analysis
- // run is authoritative for: replace verbatim, including explicit null
- // (the object may no longer have a clear first scene after edits, and
- // pinning the stale value would mislead the bible).
- existing.firstAppearance = incoming.firstAppearance ?? null;
- existing.evidence = Array.isArray(incoming.evidence) ? incoming.evidence : (existing.evidence || []);
- existing.missingFromProse = Array.isArray(incoming.missingFromProse) ? incoming.missingFromProse : [];
- existing.updatedAt = nowIso();
- } else {
- const profile = {
- ...emptyProfile(),
- id: `wr-object-${randomUUID()}`,
- name: String(incoming.name).trim(),
- aliases: Array.isArray(incoming.aliases) ? incoming.aliases.map((a) => String(a).trim()).filter(Boolean) : [],
- description: String(incoming.description || '').trim(),
- significance: String(incoming.significance || '').trim(),
- firstAppearance: incoming.firstAppearance ?? null,
- evidence: Array.isArray(incoming.evidence) ? incoming.evidence : [],
- missingFromProse: Array.isArray(incoming.missingFromProse) ? incoming.missingFromProse : [],
- source: 'ai',
- };
- state.objects.push(profile);
- indexObject(profile);
- }
- }
+ state.objects = mergeExtractedBible(state.objects, extracted, 'object', { idPrefix: ID_PREFIX });
await saveFile(workId, state);
- return state.objects.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
+ return state.objects;
}
diff --git a/server/services/writersRoom/promoteToPipeline.js b/server/services/writersRoom/promoteToPipeline.js
new file mode 100644
index 0000000000..5df54712de
--- /dev/null
+++ b/server/services/writersRoom/promoteToPipeline.js
@@ -0,0 +1,122 @@
+/**
+ * Writers Room ↔ Pipeline bridge (item 6 of the DRY unification).
+ *
+ * `promoteWorkToPipeline(workId)` creates a Pipeline Series + first Issue from
+ * a Writers Room work — carrying over bibles (characters / settings / objects),
+ * the active draft body, and the latest script-analysis scenes — then records
+ * the bidirectional id link on both sides.
+ *
+ * Idempotent by default: if a work already records a pipelineSeriesId AND
+ * the linked series still exists, return that series + issue instead of
+ * creating duplicates. Pass `force: true` to make a fresh series anyway
+ * (useful for re-syncing after a destructive pipeline-side edit).
+ *
+ * One-way: this is only the WR → Pipeline transfer. The link is stable
+ * forever, but content does NOT auto-sync — calling this again on a linked
+ * work returns the existing pair without re-copying. A future "re-sync"
+ * action will be a separate explicit endpoint.
+ */
+
+import * as wrLocal from './local.js';
+import { listCharacters } from './characters.js';
+import { listSettings } from './settings.js';
+import { listObjects } from './objects.js';
+import { getAnalysis } from './evaluator.js';
+import * as seriesSvc from '../pipeline/series.js';
+import * as issuesSvc from '../pipeline/issues.js';
+
+export const ERR_NO_DRAFT_BODY = 'WR_PROMOTE_NO_DRAFT_BODY';
+
+/**
+ * Pull the latest script-analysis scenes for the work, if any.
+ * Returns the canonical scene shape (visualPrompt + the rich fields) — we
+ * apply the `visualPrompt → description` UI-shape alias at the issue-write
+ * step below, matching the pipeline storyboards extractor route.
+ */
+async function loadScriptScenes(workId) {
+ const analysis = await getAnalysis(workId, 'script').catch((err) => {
+ // No analysis yet → treat as "no scenes to transfer," not an error.
+ if (err?.status === 404 || err?.code === 'NOT_FOUND') return null;
+ throw err;
+ });
+ if (!analysis || analysis.status !== 'succeeded') return [];
+ const scenes = analysis?.result?.scenes;
+ return Array.isArray(scenes) ? scenes : [];
+}
+
+function buildStoryboardScenes(canonicalScenes) {
+ // Mirror the adapter in routes/pipeline.js's /extract-scenes handler so the
+ // promoted issue's storyboards stage shape is byte-for-byte identical to
+ // what the in-pipeline "Generate scenes from {prose|tv-script}" button
+ // would produce. Rich fields (heading/summary/dialogue/...) ride along.
+ return canonicalScenes.map((s) => ({
+ ...s,
+ description: s.visualPrompt || '',
+ imageJobId: null,
+ prompt: null,
+ }));
+}
+
+export async function promoteWorkToPipeline(workId, { force = false } = {}) {
+ const { manifest, body } = await wrLocal.getWorkWithBody(workId);
+ const proseBody = (body || '').trim();
+ if (!proseBody) {
+ const err = new Error('Cannot promote — the active draft has no prose. Write some text first.');
+ err.code = ERR_NO_DRAFT_BODY;
+ throw err;
+ }
+
+ // Idempotent fast-path. Re-validate that the linked series + issue still
+ // exist (a user can delete them out-of-band); if either is missing we drop
+ // the stale link and fall through to a fresh create.
+ if (!force && manifest.pipelineSeriesId && manifest.pipelineIssueId) {
+ const existingSeries = await seriesSvc.getSeries(manifest.pipelineSeriesId).catch(() => null);
+ const existingIssue = await issuesSvc.getIssue(manifest.pipelineIssueId).catch(() => null);
+ // Verify the issue actually belongs to the linked series — otherwise a
+ // manual edit / partial delete / future migration could leave the work
+ // pointing at a mismatched pair, and we'd return an unrelated issue.
+ // A mismatch is treated like a missing record: drop the stale link and
+ // fall through to a fresh create.
+ if (existingSeries && existingIssue && existingIssue.seriesId === existingSeries.id) {
+ return { series: existingSeries, issue: existingIssue, reused: true };
+ }
+ await wrLocal.linkToPipeline(workId, { seriesId: null, issueId: null });
+ }
+
+ const [characters, settings, objects, scriptScenes] = await Promise.all([
+ listCharacters(workId),
+ listSettings(workId),
+ listObjects(workId),
+ loadScriptScenes(workId),
+ ]);
+
+ const series = await seriesSvc.createSeries({
+ name: manifest.title,
+ logline: '',
+ premise: '',
+ characters,
+ settings,
+ objects,
+ styleNotes: '',
+ targetFormat: 'comic+tv',
+ issueCountTarget: 1,
+ writersRoomWorkId: workId,
+ });
+
+ const storyboards = buildStoryboardScenes(scriptScenes);
+ const issue = await issuesSvc.createIssue({
+ seriesId: series.id,
+ title: manifest.title,
+ number: 1,
+ stages: {
+ prose: { status: 'edited', output: proseBody, input: '' },
+ storyboards: storyboards.length
+ ? { status: 'ready', scenes: storyboards }
+ : { status: 'empty' },
+ },
+ });
+
+ await wrLocal.linkToPipeline(workId, { seriesId: series.id, issueId: issue.id });
+
+ return { series, issue, reused: false };
+}
diff --git a/server/services/writersRoom/promoteToPipeline.test.js b/server/services/writersRoom/promoteToPipeline.test.js
new file mode 100644
index 0000000000..c099b960d0
--- /dev/null
+++ b/server/services/writersRoom/promoteToPipeline.test.js
@@ -0,0 +1,189 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtempSync, rmSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+let tempRoot;
+
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ return new Proxy(actual, {
+ get(target, prop) {
+ if (prop === 'PATHS') return { ...actual.PATHS, data: tempRoot };
+ return target[prop];
+ },
+ });
+});
+
+const wrLocal = await import('./local.js');
+const { promoteWorkToPipeline, ERR_NO_DRAFT_BODY } = await import('./promoteToPipeline.js');
+const { createCharacter } = await import('./characters.js');
+const { createSetting } = await import('./settings.js');
+const { createObject } = await import('./objects.js');
+const seriesSvc = await import('../pipeline/series.js');
+const issuesSvc = await import('../pipeline/issues.js');
+
+beforeEach(() => {
+ tempRoot = mkdtempSync(join(tmpdir(), 'wr-promote-test-'));
+});
+
+afterEach(() => {
+ if (tempRoot && existsSync(tempRoot)) rmSync(tempRoot, { recursive: true, force: true });
+});
+
+async function seedWorkWithProse(prose = 'Once upon a time there was a paragraph.') {
+ const work = await wrLocal.createWork({ title: 'Test Work', kind: 'short-story' });
+ await wrLocal.saveDraftBody(work.id, prose);
+ return work;
+}
+
+describe('promoteWorkToPipeline', () => {
+ it('rejects a work whose active draft is empty', async () => {
+ const work = await wrLocal.createWork({ title: 'Blank', kind: 'short-story' });
+ let caught;
+ try {
+ await promoteWorkToPipeline(work.id);
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeDefined();
+ expect(caught.code).toBe(ERR_NO_DRAFT_BODY);
+ });
+
+ it('creates a series + first issue and copies prose into stages.prose.output', async () => {
+ const work = await seedWorkWithProse('The vault loomed in the dark.');
+
+ const result = await promoteWorkToPipeline(work.id);
+
+ expect(result.reused).toBe(false);
+ expect(result.series.id).toMatch(/^ser-/);
+ expect(result.series.name).toBe('Test Work');
+ expect(result.series.writersRoomWorkId).toBe(work.id);
+ expect(result.issue.seriesId).toBe(result.series.id);
+ expect(result.issue.title).toBe('Test Work');
+ expect(result.issue.stages.prose.output).toBe('The vault loomed in the dark.');
+ expect(result.issue.stages.prose.status).toBe('edited');
+ // No script analysis yet → storyboards empty
+ expect(result.issue.stages.storyboards.scenes).toEqual([]);
+ expect(result.issue.stages.storyboards.status).toBe('empty');
+ });
+
+ it('records the bidirectional link on both sides', async () => {
+ const work = await seedWorkWithProse();
+ const { series, issue } = await promoteWorkToPipeline(work.id);
+
+ const reloadedWork = await wrLocal.getWork(work.id);
+ expect(reloadedWork.pipelineSeriesId).toBe(series.id);
+ expect(reloadedWork.pipelineIssueId).toBe(issue.id);
+
+ const reloadedSeries = await seriesSvc.getSeries(series.id);
+ expect(reloadedSeries.writersRoomWorkId).toBe(work.id);
+ });
+
+ it('carries over characters / settings / objects bibles into the series', async () => {
+ const work = await seedWorkWithProse();
+ await createCharacter(work.id, { name: 'Aria', physicalDescription: 'tall, freckles' });
+ await createSetting(work.id, { name: 'The Foundry', slugline: 'INT. FOUNDRY — NIGHT', description: 'molten light' });
+ await createObject(work.id, { name: 'The Locket', significance: "mother's keepsake" });
+
+ const { series } = await promoteWorkToPipeline(work.id);
+
+ expect(series.characters).toHaveLength(1);
+ expect(series.characters[0].name).toBe('Aria');
+ expect(series.characters[0].physicalDescription).toBe('tall, freckles');
+ expect(series.settings).toHaveLength(1);
+ expect(series.settings[0].slugline).toBe('INT. FOUNDRY — NIGHT');
+ expect(series.objects).toHaveLength(1);
+ expect(series.objects[0].name).toBe('The Locket');
+ });
+
+ it('is idempotent: a second promote returns the same series/issue with reused=true', async () => {
+ const work = await seedWorkWithProse();
+ const first = await promoteWorkToPipeline(work.id);
+ const second = await promoteWorkToPipeline(work.id);
+
+ expect(second.reused).toBe(true);
+ expect(second.series.id).toBe(first.series.id);
+ expect(second.issue.id).toBe(first.issue.id);
+
+ // Side-effect check: no duplicate series in storage
+ const all = await seriesSvc.listSeries();
+ expect(all.filter((s) => s.writersRoomWorkId === work.id)).toHaveLength(1);
+ });
+
+ it('with force:true creates a fresh series even when the work is already linked', async () => {
+ const work = await seedWorkWithProse();
+ const first = await promoteWorkToPipeline(work.id);
+ const second = await promoteWorkToPipeline(work.id, { force: true });
+
+ expect(second.reused).toBe(false);
+ expect(second.series.id).not.toBe(first.series.id);
+ // Work's link points at the new series
+ const reloaded = await wrLocal.getWork(work.id);
+ expect(reloaded.pipelineSeriesId).toBe(second.series.id);
+ });
+
+ it('falls through to a fresh create if the work links to a deleted series', async () => {
+ const work = await seedWorkWithProse();
+ const first = await promoteWorkToPipeline(work.id);
+ await seriesSvc.deleteSeries(first.series.id);
+
+ const second = await promoteWorkToPipeline(work.id);
+ expect(second.reused).toBe(false);
+ expect(second.series.id).not.toBe(first.series.id);
+ });
+
+ it('falls through to a fresh create when the linked issue belongs to a different series (mismatched link)', async () => {
+ const work = await seedWorkWithProse();
+ const first = await promoteWorkToPipeline(work.id);
+ // Simulate a corrupted link: rewrite the work manifest to point at the
+ // first series but a DIFFERENT (unrelated) series' issue. Mirrors a
+ // manual edit, partial delete, or migration bug.
+ const strayerSeries = await seriesSvc.createSeries({ name: 'Strayer' });
+ const strayerIssue = await issuesSvc.createIssue({ seriesId: strayerSeries.id, title: 'Stray' });
+ await wrLocal.linkToPipeline(work.id, { seriesId: first.series.id, issueId: strayerIssue.id });
+
+ const second = await promoteWorkToPipeline(work.id);
+ expect(second.reused).toBe(false);
+ // The new pair must be self-consistent (issue belongs to the new series).
+ expect(second.issue.seriesId).toBe(second.series.id);
+ });
+
+ it('populates storyboards scenes from a succeeded script analysis (visualPrompt → description)', async () => {
+ const work = await seedWorkWithProse();
+
+ // Hand-write a `script` analysis snapshot on disk to mimic a completed run
+ // — running the real LLM-driven evaluator would require provider stubs.
+ const fs = await import('fs/promises');
+ const analysisDir = join(tempRoot, 'writers-room', 'works', work.id, 'analysis');
+ await fs.mkdir(analysisDir, { recursive: true });
+ await fs.writeFile(join(analysisDir, 'script.json'), JSON.stringify({
+ id: 'script', workId: work.id, kind: 'script', status: 'succeeded',
+ result: {
+ title: 'The Pilot', logline: 'A heist gone wrong.',
+ scenes: [
+ { id: 'scene-01', heading: 'Scene 1 — Vault', slugline: 'INT. VAULT — NIGHT',
+ summary: 'They break in.', characters: ['ALICE'],
+ action: 'A drill bites.', dialogue: [{ character: 'ALICE', line: 'Quiet.' }],
+ visualPrompt: 'a high-tech vault, two figures in tactical gear',
+ sourceSegmentIds: [] },
+ { id: 'scene-02', heading: 'Scene 2 — Escape', slugline: 'EXT. ROOFTOP — DAWN',
+ summary: '...', characters: [], action: '', dialogue: [],
+ visualPrompt: 'a rooftop at first light', sourceSegmentIds: [] },
+ ],
+ },
+ createdAt: new Date().toISOString(), completedAt: new Date().toISOString(),
+ }));
+
+ const { issue } = await promoteWorkToPipeline(work.id);
+
+ expect(issue.stages.storyboards.scenes).toHaveLength(2);
+ expect(issue.stages.storyboards.status).toBe('ready');
+ expect(issue.stages.storyboards.scenes[0].description).toBe('a high-tech vault, two figures in tactical gear');
+ expect(issue.stages.storyboards.scenes[0].slugline).toBe('INT. VAULT — NIGHT');
+ expect(issue.stages.storyboards.scenes[0].imageJobId).toBeNull();
+ // Rich fields ride along
+ expect(issue.stages.storyboards.scenes[0].heading).toBe('Scene 1 — Vault');
+ expect(issue.stages.storyboards.scenes[0].dialogue[0]).toEqual({ character: 'ALICE', line: 'Quiet.' });
+ });
+});
diff --git a/server/services/writersRoom/settings.js b/server/services/writersRoom/settings.js
index 05f471322a..51602399ad 100644
--- a/server/services/writersRoom/settings.js
+++ b/server/services/writersRoom/settings.js
@@ -1,77 +1,49 @@
/**
* Writers Room — editable setting/world bible.
*
- * Per-location bible keyed by screenplay slugline (e.g. `INT. KITCHEN — NIGHT`)
- * so SceneCard can match a scene's slugline to its canonical setting and
- * inject the description into the image prompt.
+ * Per-location bible keyed by screenplay slugline so SceneCard can match a
+ * scene's slugline to its canonical setting and inject the description into
+ * the image prompt.
*
- * Stored at data/writers-room/works/<workId>/settings.json. Same merge rule
- * as characters: a re-run of `settings` analysis fills empty fields and adds
- * new locations, but never overwrites a non-empty field on an existing entry.
+ * Per-work file at data/writers-room/works/<workId>/settings.json. Shape +
+ * extraction-merge live in `server/lib/storyBible.js`; this module owns
+ * CRUD, file I/O, and the writers-room id prefix (`wr-setting-`).
*/
import { join } from 'path';
import { randomUUID } from 'crypto';
import { PATHS, atomicWrite, ensureDir, readJSONFile } from '../../lib/fileUtils.js';
+import { normalizeSlugline as canonicalNormalizeSlugline } from '../../lib/scenePrompt.js';
+import {
+ sanitizeSetting,
+ sanitizeBibleList,
+ mergeExtractedBible,
+} from '../../lib/storyBible.js';
import { nowIso, badRequest, notFound, assertValidWorkId } from './_shared.js';
const SETTING_ID_RE = /^wr-setting-[0-9a-f-]+$/i;
+const ID_PREFIX = 'wr-setting-';
const root = () => join(PATHS.data, 'writers-room');
const settingsFile = (workId) => {
// Defense-in-depth: refuse path-traversal-shaped workIds before
- // interpolating them into the on-disk path. Routes already validate, but
- // this module is also called directly from analysis-merge code paths.
+ // interpolating them into the on-disk path.
assertValidWorkId(workId);
return join(root(), 'works', workId, 'settings.json');
};
-const EDITABLE_FIELDS = ['name', 'slugline', 'description', 'palette', 'era', 'weather', 'recurringDetails', 'notes'];
+// `name` + `slugline` handled separately (identifier rule + conflict check).
+const EDITABLE_FIELDS = ['description', 'palette', 'era', 'weather', 'recurringDetails', 'notes'];
-function emptySetting() {
- return {
- id: '',
- name: '',
- slugline: '',
- description: '',
- palette: '',
- era: '',
- weather: '',
- recurringDetails: '',
- notes: '',
- firstAppearance: null,
- evidence: [],
- missingFromProse: [],
- source: 'user',
- createdAt: nowIso(),
- updatedAt: nowIso(),
- };
-}
-
-// Sluglines are matched case-insensitively with whitespace+punctuation
-// collapsed so `INT. KITCHEN — NIGHT` and `INT KITCHEN - NIGHT` resolve to
-// the same bible entry. Em-dashes vs hyphens vs spaces in user-edited prose
-// would otherwise fragment a single location across multiple records.
-export function normalizeSlugline(s) {
- return String(s || '')
- .toUpperCase()
- .replace(/[—–-]/g, ' ')
- .replace(/[.,:;]/g, '')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function isBlank(v) {
- if (v == null) return true;
- if (Array.isArray(v)) return v.length === 0;
- if (typeof v === 'string') return v.trim() === '';
- return false;
-}
+// Re-export under the historical name for the existing test + import surface.
+// Canonical implementation in server/lib/scenePrompt.js.
+export const normalizeSlugline = canonicalNormalizeSlugline;
async function loadFile(workId) {
const fallback = { settings: [], updatedAt: null };
const parsed = await readJSONFile(settingsFile(workId), fallback);
- return parsed && Array.isArray(parsed.settings) ? parsed : fallback;
+ if (!parsed || !Array.isArray(parsed.settings)) return fallback;
+ return { ...parsed, settings: sanitizeBibleList(parsed.settings, 'setting', { idPrefix: ID_PREFIX }) };
}
async function saveFile(workId, state) {
@@ -98,21 +70,20 @@ export async function createSetting(workId, patch = {}) {
const name = String(patch.name || '').trim();
if (!slugline && !name) throw badRequest('Setting requires either a slugline or a name');
const state = await loadFile(workId);
- const key = normalizeSlugline(slugline || name);
- if (state.settings.some((s) => normalizeSlugline(s.slugline || s.name) === key)) {
+ const key = canonicalNormalizeSlugline(slugline || name);
+ if (state.settings.some((s) => canonicalNormalizeSlugline(s.slugline || s.name) === key)) {
throw badRequest(`A setting matching "${slugline || name}" already exists`);
}
- const profile = {
- ...emptySetting(),
- id: `wr-setting-${randomUUID()}`,
+ const draft = {
+ id: `${ID_PREFIX}${randomUUID()}`,
slugline,
name: name || slugline,
source: 'user',
};
for (const field of EDITABLE_FIELDS) {
- if (field === 'slugline' || field === 'name') continue;
- if (patch[field] !== undefined) profile[field] = patch[field];
+ if (patch[field] !== undefined) draft[field] = patch[field];
}
+ const profile = sanitizeSetting(draft, { idPrefix: ID_PREFIX, preserveTimestamps: false });
state.settings.push(profile);
await saveFile(workId, state);
return profile;
@@ -124,33 +95,31 @@ export async function updateSetting(workId, settingId, patch = {}) {
const idx = state.settings.findIndex((s) => s.id === settingId);
if (idx < 0) throw notFound('Setting');
const next = { ...state.settings[idx] };
- for (const field of EDITABLE_FIELDS) {
+ for (const field of ['slugline', 'name']) {
if (patch[field] === undefined) continue;
- if (field === 'slugline' || field === 'name') {
- const newVal = String(patch[field] || '').trim();
- const key = normalizeSlugline(newVal);
- if (key) {
- const conflict = state.settings.some((s) => s.id !== settingId && normalizeSlugline(s.slugline || s.name) === key);
- if (conflict) throw badRequest(`A setting matching "${newVal}" already exists`);
- }
- next[field] = newVal;
- } else {
- next[field] = patch[field];
+ const newVal = String(patch[field] || '').trim();
+ const key = canonicalNormalizeSlugline(newVal);
+ if (key) {
+ const conflict = state.settings.some((s) => s.id !== settingId && canonicalNormalizeSlugline(s.slugline || s.name) === key);
+ if (conflict) throw badRequest(`A setting matching "${newVal}" already exists`);
}
+ next[field] = newVal;
}
- // Enforce the same invariant as `createSetting`: at least one of
- // `slugline` / `name` must be non-empty. Without this final check, a
- // PATCH that blanks the only non-empty identifier (e.g. a name-only
- // setting receiving `{ name: '' }`, or a slugline-only setting being
- // sent `{ slugline: '' }`) would silently leave the setting unaddressable.
+ for (const field of EDITABLE_FIELDS) {
+ if (patch[field] !== undefined) next[field] = patch[field];
+ }
+ // A PATCH that blanks the only non-empty identifier (e.g. name-only
+ // setting receiving `{ name: '' }`) would leave the setting unaddressable.
if (!next.slugline && !next.name) {
throw badRequest('Setting needs slugline or name');
}
next.source = 'user';
- next.updatedAt = nowIso();
- state.settings[idx] = next;
+ state.settings[idx] = sanitizeSetting(
+ { ...next, updatedAt: nowIso() },
+ { idPrefix: ID_PREFIX, preserveTimestamps: true },
+ );
await saveFile(workId, state);
- return next;
+ return state.settings[idx];
}
export async function deleteSetting(workId, settingId) {
@@ -163,80 +132,10 @@ export async function deleteSetting(workId, settingId) {
return { ok: true };
}
-/**
- * Merge an AI-extracted setting set into the editable bible.
- * - Existing settings (matched by normalized slugline OR name) keep every
- * non-blank field. Only blank fields get filled from `extracted`.
- * - New settings are inserted with `source: 'ai'`.
- * - `firstAppearance`, `evidence`, `missingFromProse` always reflect the
- * latest analysis.
- */
export async function mergeExtractedSettings(workId, extracted) {
if (!Array.isArray(extracted)) return listSettings(workId);
const state = await loadFile(workId);
- const byKey = new Map();
- // Index a setting under BOTH its normalized slugline and its normalized
- // name so an extracted entry that references the location via either
- // identifier resolves to one canonical record. Indexing by only one of
- // those keys lets a slugline-only incoming entry collide with a name-only
- // existing entry (or vice versa) and create a duplicate setting.
- const indexSetting = (s) => {
- const slugKey = normalizeSlugline(s.slugline);
- const nameKey = normalizeSlugline(s.name);
- if (slugKey) byKey.set(slugKey, s);
- if (nameKey) byKey.set(nameKey, s);
- };
- for (const s of state.settings) indexSetting(s);
- for (const incoming of extracted) {
- if (!incoming || (!incoming.slugline && !incoming.name)) continue;
- const slugKey = normalizeSlugline(incoming.slugline);
- const nameKey = normalizeSlugline(incoming.name);
- const existing = (slugKey && byKey.get(slugKey)) || (nameKey && byKey.get(nameKey)) || null;
- if (existing) {
- for (const field of ['description', 'palette', 'era', 'weather', 'recurringDetails']) {
- if (isBlank(existing[field]) && !isBlank(incoming[field])) {
- existing[field] = incoming[field];
- }
- }
- if (isBlank(existing.name) && !isBlank(incoming.name)) {
- existing.name = String(incoming.name).trim();
- // Re-index now that name is populated so a subsequent entry in the
- // same batch keyed by that name resolves to this record.
- indexSetting(existing);
- }
- // Back-fill slugline when the existing record was created name-only
- // (typical for hand-edited entries). Without this, a storyboard scene's
- // slugline can never match this setting record so setting injection
- // silently no-ops even though the merge correctly de-duped. Re-index
- // afterward so later batch entries keyed by the new slugline resolve.
- if (isBlank(existing.slugline) && !isBlank(incoming.slugline)) {
- existing.slugline = String(incoming.slugline).trim();
- indexSetting(existing);
- }
- existing.firstAppearance = incoming.firstAppearance ?? existing.firstAppearance ?? null;
- existing.evidence = Array.isArray(incoming.evidence) ? incoming.evidence : (existing.evidence || []);
- existing.missingFromProse = Array.isArray(incoming.missingFromProse) ? incoming.missingFromProse : [];
- existing.updatedAt = nowIso();
- } else {
- const profile = {
- ...emptySetting(),
- id: `wr-setting-${randomUUID()}`,
- slugline: String(incoming.slugline || '').trim(),
- name: String(incoming.name || incoming.slugline || '').trim(),
- description: String(incoming.description || '').trim(),
- palette: String(incoming.palette || '').trim(),
- era: String(incoming.era || '').trim(),
- weather: String(incoming.weather || '').trim(),
- recurringDetails: String(incoming.recurringDetails || '').trim(),
- firstAppearance: incoming.firstAppearance ?? null,
- evidence: Array.isArray(incoming.evidence) ? incoming.evidence : [],
- missingFromProse: Array.isArray(incoming.missingFromProse) ? incoming.missingFromProse : [],
- source: 'ai',
- };
- state.settings.push(profile);
- indexSetting(profile);
- }
- }
+ state.settings = mergeExtractedBible(state.settings, extracted, 'setting', { idPrefix: ID_PREFIX });
await saveFile(workId, state);
- return state.settings.sort((a, b) => (a.slugline || a.name || '').localeCompare(b.slugline || b.name || ''));
+ return state.settings;
}