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

feat: Pipeline page — series-production workflow under Create

Adam Eivy712f0dd5274b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 58fbcede14..c95adc8341 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## 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*.
- 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.
diff --git a/PLAN.md b/PLAN.md
index fd29df4f38..261f6679a0 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -109,3 +109,23 @@ All dependencies audited and justified (2026-04-28). 0 removals. See [docs/DEPS.
- **Major Dependency Upgrades** — React 19, Zod 4, PM2 6, Vite 8.
- **Dynamic Skill Marketplace** — Self-generating skill templates from task patterns.
- **Workflow tab Phase 2** — drag-and-drop ordering of stages, custom user-defined stages, per-app workflow overrides. Builds on the new `/cos/workflow` pipeline.
+
+---
+
+## 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:
+
+- [ ] **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`.
+- [ ] **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`.
+- [ ] **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`.
+- [ ] **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.
diff --git a/client/src/App.jsx b/client/src/App.jsx
index abfce5006f..35fdb028ca 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -81,6 +81,9 @@ const CharacterSheet = lazyWithReload(() => import('./pages/CharacterSheet'));
const Wiki = lazyWithReload(() => import('./pages/Wiki'));
const RapidReaderPage = lazyWithReload(() => import('./pages/RapidReader'));
const WritersRoom = lazyWithReload(() => import('./pages/WritersRoom'));
+const Pipeline = lazyWithReload(() => import('./pages/Pipeline'));
+const PipelineSeries = lazyWithReload(() => import('./pages/PipelineSeries'));
+const PipelineIssue = lazyWithReload(() => import('./pages/PipelineIssue'));
// Loading fallback for lazy-loaded pages
const PageLoader = () => (
@@ -214,6 +217,10 @@ export default function App() {
<Route path="rapid-reader" element={<RapidReaderPage />} />
<Route path="world-builder" element={<WorldBuilder />} />
<Route path="writers-room" element={<WritersRoom />} />
+ <Route path="pipeline" element={<Pipeline />} />
+ <Route path="pipeline/series/:seriesId" element={<PipelineSeries />} />
+ <Route path="pipeline/issues/:issueId" element={<Navigate to="idea" replace />} />
+ <Route path="pipeline/issues/:issueId/:stage" element={<PipelineIssue />} />
<Route path="writers-room/works/:workId" element={<WritersRoom />} />
<Route path="agents" element={<Agents />} />
<Route path="agents/:agentId" element={<Agents />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 3a63fe3739..fb40c7a70b 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -193,6 +193,7 @@ const navItems = [
defaultTo: '/media',
children: [
{ to: '/media', label: 'Media Gen', icon: Layers },
+ { to: '/pipeline', label: 'Pipeline', icon: WorkflowIcon },
{ to: '/world-builder', label: 'World Builder', icon: Globe },
{ to: '/writers-room', label: 'Writers Room', icon: NotebookPen }
]
@@ -886,6 +887,7 @@ export default function Layout() {
location.pathname.startsWith('/meatspace') ||
location.pathname.startsWith('/media') ||
location.pathname.startsWith('/messages') ||
+ location.pathname.startsWith('/pipeline/issues/') ||
location.pathname.startsWith('/post') ||
location.pathname === '/review' ||
location.pathname.startsWith('/settings') ||
diff --git a/client/src/components/pipeline/stages/ComicPagesStage.jsx b/client/src/components/pipeline/stages/ComicPagesStage.jsx
new file mode 100644
index 0000000000..bcd7078ea8
--- /dev/null
+++ b/client/src/components/pipeline/stages/ComicPagesStage.jsx
@@ -0,0 +1,161 @@
+/**
+ * Comic Pages stage — assemble the visual side of the comic-book issue.
+ *
+ * MVP: structured list of pages, each with a list of panels. Each panel has
+ * its own prompt + an "Enqueue image" button that hands off to the existing
+ * image-gen pipeline (via /api/pipeline/issues/:id/stages/comicPages/visual).
+ * Progress for each panel's image lands via the standard media-job SSE — for
+ * the skeleton we just persist the jobId and show "queued"; deep progress
+ * integration is deferred (see PLAN.md "Pipeline — Deferred").
+ */
+
+import { useState } from 'react';
+import { Plus, Trash2, Sparkles, Loader2 } from 'lucide-react';
+import toast from '../../ui/Toast';
+import { generatePipelineVisualImage, updatePipelineIssue } from '../../../services/api';
+
+export default function ComicPagesStage({ issue, onStageUpdate }) {
+ const stage = issue.stages?.comicPages || { status: 'empty', pages: [] };
+ const [pages, setPages] = useState(stage.pages || []);
+ const [savingIdx, setSavingIdx] = useState(null);
+
+ const persist = async (nextPages) => {
+ setPages(nextPages);
+ const updated = await updatePipelineIssue(issue.id, {
+ stages: { comicPages: { status: nextPages.length ? 'edited' : 'empty', pages: nextPages } },
+ }).catch((err) => {
+ toast.error(err.message || 'Save failed');
+ return null;
+ });
+ if (updated) onStageUpdate?.('comicPages', updated.stages.comicPages, updated);
+ };
+
+ const addPage = () => persist([...pages, { panels: [{ description: '', imageJobId: null }] }]);
+ const addPanel = (pi) => {
+ const next = pages.map((p, i) => i === pi ? { ...p, panels: [...(p.panels || []), { description: '', imageJobId: null }] } : p);
+ persist(next);
+ };
+ const removePage = (pi) => persist(pages.filter((_, i) => i !== pi));
+ const removePanel = (pi, ni) => {
+ const next = pages.map((p, i) => i === pi
+ ? { ...p, panels: (p.panels || []).filter((_, j) => j !== ni) }
+ : p);
+ persist(next);
+ };
+ const updatePanel = (pi, ni, patch) => {
+ const next = pages.map((p, i) => i === pi
+ ? { ...p, panels: (p.panels || []).map((q, j) => j === ni ? { ...q, ...patch } : q) }
+ : p);
+ setPages(next); // local-first; persist on blur via a dedicated save
+ };
+
+ const handleGeneratePanel = async (pi, ni) => {
+ const panel = pages[pi].panels[ni];
+ if (!panel.description?.trim()) {
+ toast.error('Add a description first');
+ return;
+ }
+ setSavingIdx(`${pi}:${ni}`);
+ const result = await generatePipelineVisualImage(issue.id, 'comicPages', {
+ description: panel.description,
+ }).catch((err) => {
+ toast.error(err.message || 'Failed to enqueue image');
+ return null;
+ });
+ setSavingIdx(null);
+ if (!result) return;
+ const next = pages.map((p, i) => i === pi
+ ? { ...p, panels: p.panels.map((q, j) => j === ni ? { ...q, imageJobId: result.jobId, prompt: result.prompt } : q) }
+ : p);
+ persist(next);
+ toast.success(`Queued ${result.mode} image (${result.jobId.slice(0, 8)})`);
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between gap-3 flex-wrap">
+ <div>
+ <h2 className="text-lg font-semibold text-white">Comic Pages</h2>
+ <p className="text-xs text-gray-500 mt-1">
+ Define pages and panels. Each panel's description becomes an image-gen prompt prefixed by the series style.
+ Image progress lives in the existing media-job queue. Episode video / multi-panel composition stitching is deferred.
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={addPage}
+ 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 page
+ </button>
+ </div>
+
+ {pages.length === 0 ? (
+ <p className="text-xs text-gray-600 italic">No pages yet. Start with one and add panels.</p>
+ ) : (
+ <div className="space-y-4">
+ {pages.map((page, pi) => (
+ <div key={pi} className="p-3 bg-port-card border border-port-border rounded-lg">
+ <div className="flex items-center justify-between mb-2">
+ <span className="text-xs uppercase tracking-wider text-gray-500">Page {pi + 1}</span>
+ <button
+ type="button"
+ onClick={() => removePage(pi)}
+ className="text-gray-500 hover:text-port-error p-1"
+ aria-label="Remove page"
+ >
+ <Trash2 size={14} />
+ </button>
+ </div>
+ <ul className="space-y-2">
+ {(page.panels || []).map((panel, ni) => (
+ <li key={ni} className="flex items-start gap-2">
+ <span className="text-xs text-gray-600 mt-2 w-8 shrink-0">P{ni + 1}</span>
+ <textarea
+ value={panel.description || ''}
+ onChange={(e) => updatePanel(pi, ni, { description: e.target.value })}
+ onBlur={() => persist(pages)}
+ placeholder="Panel subject: wide shot, foundry crucible, dusk light, Lina silhouetted against the glow."
+ rows={2}
+ className="flex-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
+ maxLength={8000}
+ />
+ <div className="flex flex-col gap-1 items-stretch w-32">
+ <button
+ type="button"
+ onClick={() => handleGeneratePanel(pi, ni)}
+ disabled={savingIdx === `${pi}:${ni}`}
+ className="inline-flex items-center justify-center gap-1 px-2 py-1.5 rounded bg-port-accent text-white text-xs disabled:opacity-50"
+ >
+ {savingIdx === `${pi}:${ni}` ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}
+ Image
+ </button>
+ {panel.imageJobId ? (
+ <span className="text-[10px] text-gray-500 font-mono break-all">job {panel.imageJobId.slice(0, 8)}</span>
+ ) : null}
+ </div>
+ <button
+ type="button"
+ onClick={() => removePanel(pi, ni)}
+ className="text-gray-500 hover:text-port-error p-2"
+ aria-label="Remove panel"
+ >
+ <Trash2 size={14} />
+ </button>
+ </li>
+ ))}
+ </ul>
+ <button
+ type="button"
+ onClick={() => addPanel(pi)}
+ className="mt-2 inline-flex items-center gap-1 text-xs text-port-accent hover:underline"
+ >
+ <Plus size={12} /> Add panel
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/pipeline/stages/ComicScriptStage.jsx b/client/src/components/pipeline/stages/ComicScriptStage.jsx
new file mode 100644
index 0000000000..3653c19fd0
--- /dev/null
+++ b/client/src/components/pipeline/stages/ComicScriptStage.jsx
@@ -0,0 +1,12 @@
+import TextStagePanel from './TextStagePanel';
+
+export default function ComicScriptStage(props) {
+ return (
+ <TextStagePanel
+ {...props}
+ stageId="comicScript"
+ generateLabel="Adapt to comic script"
+ outputPlaceholder="Page → panel → description / caption / dialogue / SFX. Marvel/DC house format. Generated from the prose stage; iterate freely without re-running."
+ />
+ );
+}
diff --git a/client/src/components/pipeline/stages/EpisodeVideoStage.jsx b/client/src/components/pipeline/stages/EpisodeVideoStage.jsx
new file mode 100644
index 0000000000..29dab9cc79
--- /dev/null
+++ b/client/src/components/pipeline/stages/EpisodeVideoStage.jsx
@@ -0,0 +1,35 @@
+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() {
+ 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>
+ </div>
+ );
+}
diff --git a/client/src/components/pipeline/stages/IdeaStage.jsx b/client/src/components/pipeline/stages/IdeaStage.jsx
new file mode 100644
index 0000000000..db078b7237
--- /dev/null
+++ b/client/src/components/pipeline/stages/IdeaStage.jsx
@@ -0,0 +1,13 @@
+import TextStagePanel from './TextStagePanel';
+
+export default function IdeaStage(props) {
+ return (
+ <TextStagePanel
+ {...props}
+ stageId="idea"
+ generateLabel="Generate beat sheet"
+ seedPlaceholder="A rough idea for this issue — a single sentence is fine. The LLM expands it into a beat sheet."
+ outputPlaceholder="The generated beat sheet will appear here. You can edit it freely; downstream stages use this content verbatim as upstream context."
+ />
+ );
+}
diff --git a/client/src/components/pipeline/stages/ProseStage.jsx b/client/src/components/pipeline/stages/ProseStage.jsx
new file mode 100644
index 0000000000..ab4fc7ef4e
--- /dev/null
+++ b/client/src/components/pipeline/stages/ProseStage.jsx
@@ -0,0 +1,12 @@
+import TextStagePanel from './TextStagePanel';
+
+export default function ProseStage(props) {
+ return (
+ <TextStagePanel
+ {...props}
+ stageId="prose"
+ 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."
+ />
+ );
+}
diff --git a/client/src/components/pipeline/stages/StoryboardsStage.jsx b/client/src/components/pipeline/stages/StoryboardsStage.jsx
new file mode 100644
index 0000000000..4cd965ca46
--- /dev/null
+++ b/client/src/components/pipeline/stages/StoryboardsStage.jsx
@@ -0,0 +1,131 @@
+/**
+ * Storyboards stage — one storyboard image per TV-script scene.
+ *
+ * MVP: flat list of scenes. Each scene has its own description and a
+ * "Generate storyboard image" button that hands off to image-gen via the
+ * pipeline visual endpoint. Per-scene video rendering via Creative Director
+ * is deferred — see PLAN.md "Pipeline — Deferred".
+ */
+
+import { useState } from 'react';
+import { Plus, Trash2, Sparkles, Loader2 } from 'lucide-react';
+import toast from '../../ui/Toast';
+import { generatePipelineVisualImage, updatePipelineIssue } 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 persist = async (nextScenes) => {
+ setScenes(nextScenes);
+ const updated = await updatePipelineIssue(issue.id, {
+ stages: { storyboards: { status: nextScenes.length ? 'edited' : 'empty', scenes: nextScenes } },
+ }).catch((err) => {
+ toast.error(err.message || 'Save failed');
+ return null;
+ });
+ if (updated) onStageUpdate?.('storyboards', updated.stages.storyboards, updated);
+ };
+
+ const addScene = () => persist([...scenes, { slugline: '', description: '', imageJobId: null }]);
+ const removeScene = (i) => persist(scenes.filter((_, j) => j !== i));
+ const updateScene = (i, patch) => {
+ const next = scenes.map((s, j) => j === i ? { ...s, ...patch } : s);
+ setScenes(next);
+ };
+
+ const handleGenerate = async (i) => {
+ const scene = scenes[i];
+ if (!scene.description?.trim()) {
+ toast.error('Add a description first');
+ return;
+ }
+ setSavingIdx(i);
+ const result = await generatePipelineVisualImage(issue.id, 'storyboards', {
+ description: scene.description,
+ }).catch((err) => {
+ toast.error(err.message || 'Failed to enqueue image');
+ return null;
+ });
+ setSavingIdx(null);
+ if (!result) return;
+ const next = scenes.map((s, j) => j === i ? { ...s, imageJobId: result.jobId, prompt: result.prompt } : s);
+ persist(next);
+ toast.success(`Queued ${result.mode} image (${result.jobId.slice(0, 8)})`);
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between gap-3 flex-wrap">
+ <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.
+ </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>
+
+ {scenes.length === 0 ? (
+ <p className="text-xs text-gray-600 italic">No scenes yet.</p>
+ ) : (
+ <ul className="space-y-3">
+ {scenes.map((scene, i) => (
+ <li key={i} className="p-3 bg-port-card border border-port-border rounded-lg">
+ <div className="flex items-center justify-between mb-2">
+ <input
+ value={scene.slugline || ''}
+ onChange={(e) => updateScene(i, { slugline: e.target.value })}
+ onBlur={() => persist(scenes)}
+ placeholder="INT. FOUNDRY — NIGHT"
+ className="flex-1 mr-2 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-xs uppercase tracking-wider font-mono"
+ maxLength={200}
+ />
+ <button
+ type="button"
+ onClick={() => removeScene(i)}
+ className="text-gray-500 hover:text-port-error p-1"
+ aria-label="Remove scene"
+ >
+ <Trash2 size={14} />
+ </button>
+ </div>
+ <div className="flex items-start gap-2">
+ <textarea
+ value={scene.description || ''}
+ onChange={(e) => updateScene(i, { description: e.target.value })}
+ onBlur={() => persist(scenes)}
+ placeholder="Subject + framing + mood. The series style notes are prepended automatically."
+ rows={3}
+ className="flex-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
+ maxLength={8000}
+ />
+ <div className="flex flex-col gap-1 w-32">
+ <button
+ type="button"
+ onClick={() => handleGenerate(i)}
+ disabled={savingIdx === i}
+ className="inline-flex items-center justify-center gap-1 px-2 py-1.5 rounded bg-port-accent text-white text-xs disabled:opacity-50"
+ >
+ {savingIdx === i ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}
+ Storyboard
+ </button>
+ {scene.imageJobId ? (
+ <span className="text-[10px] text-gray-500 font-mono break-all">job {scene.imageJobId.slice(0, 8)}</span>
+ ) : null}
+ </div>
+ </div>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/pipeline/stages/TVScriptStage.jsx b/client/src/components/pipeline/stages/TVScriptStage.jsx
new file mode 100644
index 0000000000..2d7420bc6a
--- /dev/null
+++ b/client/src/components/pipeline/stages/TVScriptStage.jsx
@@ -0,0 +1,12 @@
+import TextStagePanel from './TextStagePanel';
+
+export default function TVScriptStage(props) {
+ return (
+ <TextStagePanel
+ {...props}
+ stageId="tvScript"
+ generateLabel="Adapt to teleplay"
+ outputPlaceholder="Slugline → action → dialogue. Standard TV format with act breaks. Generated from the prose stage; iterates independently of the comic script."
+ />
+ );
+}
diff --git a/client/src/components/pipeline/stages/TextStagePanel.jsx b/client/src/components/pipeline/stages/TextStagePanel.jsx
new file mode 100644
index 0000000000..3fec4dac33
--- /dev/null
+++ b/client/src/components/pipeline/stages/TextStagePanel.jsx
@@ -0,0 +1,151 @@
+/**
+ * Shared editor for the four text stages (idea, prose, comicScript, tvScript).
+ * Each per-stage component wraps this with stage-specific labels + placeholders
+ * — the underlying mechanic is identical: textarea for the user's edits +
+ * generate button that calls the server's text-stage runner.
+ */
+
+import { useEffect, useState } from 'react';
+import { Loader2, Sparkles, Save } from 'lucide-react';
+import toast from '../../ui/Toast';
+import { generatePipelineStage, updatePipelineIssue, PIPELINE_STAGE_LABELS } from '../../../services/api';
+
+const STATUS_LABEL = {
+ empty: 'Not started',
+ generating: 'Generating…',
+ ready: 'Ready',
+ edited: 'Edited',
+ 'needs-review': 'Needs review',
+ error: 'Error',
+};
+
+const STATUS_COLOR = {
+ empty: 'text-gray-500',
+ generating: 'text-port-accent',
+ ready: 'text-port-success',
+ edited: 'text-port-warning',
+ 'needs-review': 'text-port-warning',
+ error: 'text-port-error',
+};
+
+export default function TextStagePanel({
+ issue,
+ stageId,
+ onStageUpdate,
+ seedPlaceholder,
+ outputPlaceholder,
+ generateLabel = 'Generate',
+}) {
+ const stage = issue.stages?.[stageId] || { status: 'empty', input: '', output: '' };
+ const [draftOutput, setDraftOutput] = useState(stage.output || '');
+ const [draftInput, setDraftInput] = useState(stage.input || '');
+ const [generating, setGenerating] = useState(stage.status === 'generating');
+ const [saving, setSaving] = useState(false);
+
+ // Reset local edits when the stage record changes from the parent (e.g.
+ // auto-run pushed a new output).
+ useEffect(() => {
+ setDraftOutput(stage.output || '');
+ setDraftInput(stage.input || '');
+ setGenerating(stage.status === 'generating');
+ }, [stage.output, stage.input, stage.status, stage.lastRunId]);
+
+ const handleGenerate = async () => {
+ setGenerating(true);
+ const result = await generatePipelineStage(issue.id, stageId, { seedInput: draftInput }).catch((err) => {
+ toast.error(err.message || `Failed to generate ${stageId}`);
+ return null;
+ });
+ setGenerating(false);
+ if (!result) return;
+ onStageUpdate?.(stageId, result.stage);
+ toast.success(`${PIPELINE_STAGE_LABELS[stageId]} generated`);
+ };
+
+ const dirty = draftOutput !== (stage.output || '') || draftInput !== (stage.input || '');
+
+ const handleSave = async () => {
+ setSaving(true);
+ const patch = {
+ stages: {
+ [stageId]: {
+ status: 'edited',
+ input: draftInput,
+ output: draftOutput,
+ },
+ },
+ };
+ const updated = await updatePipelineIssue(issue.id, patch).catch((err) => {
+ toast.error(err.message || 'Save failed');
+ return null;
+ });
+ setSaving(false);
+ if (!updated) return;
+ onStageUpdate?.(stageId, updated.stages[stageId], updated);
+ toast.success(`${PIPELINE_STAGE_LABELS[stageId]} saved`);
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between gap-3 flex-wrap">
+ <div className="flex items-center gap-3">
+ <h2 className="text-lg font-semibold text-white">{PIPELINE_STAGE_LABELS[stageId]}</h2>
+ <span className={`text-[10px] uppercase tracking-wider ${STATUS_COLOR[stage.status] || 'text-gray-500'}`}>
+ {STATUS_LABEL[stage.status] || stage.status}
+ </span>
+ {stage.lastRunId ? (
+ <span className="text-[10px] text-gray-600 font-mono">run {stage.lastRunId.slice(0, 8)}</span>
+ ) : null}
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={handleSave}
+ disabled={!dirty || saving}
+ 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"
+ >
+ {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
+ Save edits
+ </button>
+ <button
+ type="button"
+ onClick={handleGenerate}
+ disabled={generating}
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"
+ >
+ {generating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
+ {generateLabel}
+ </button>
+ </div>
+ </div>
+
+ {stageId === 'idea' ? (
+ <label className="block">
+ <span className="block text-xs uppercase tracking-wider text-gray-500 mb-1">Seed idea</span>
+ <textarea
+ value={draftInput}
+ onChange={(e) => setDraftInput(e.target.value)}
+ placeholder={seedPlaceholder}
+ rows={4}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm font-mono"
+ />
+ </label>
+ ) : null}
+
+ <label className="block">
+ <span className="block text-xs uppercase tracking-wider text-gray-500 mb-1">Output</span>
+ <textarea
+ value={draftOutput}
+ onChange={(e) => setDraftOutput(e.target.value)}
+ placeholder={outputPlaceholder}
+ rows={24}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm font-mono leading-relaxed"
+ />
+ </label>
+
+ {stage.errorMessage ? (
+ <div className="text-xs text-port-error">{stage.errorMessage}</div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/client/src/hooks/usePipelineAutoRunProgress.js b/client/src/hooks/usePipelineAutoRunProgress.js
new file mode 100644
index 0000000000..d83a19a6e2
--- /dev/null
+++ b/client/src/hooks/usePipelineAutoRunProgress.js
@@ -0,0 +1,59 @@
+import { useEffect, useRef, useState } from 'react';
+import { pipelineAutoRunSseUrl } from '../services/api';
+
+/**
+ * Subscribe to the auto-run-text SSE stream for a pipeline issue. Returns the
+ * stream of progress frames as `frames` (in order) and a `latest` convenience
+ * pointer. The hook tears down the EventSource on unmount or when the issueId
+ * changes.
+ *
+ * Frame shapes (see server/services/pipeline/autoRunner.js#broadcast):
+ * { type: 'start', runId, stages }
+ * { type: 'stage:start', stage }
+ * { type: 'stage:complete', stage, status, length }
+ * { type: 'skip', stage, reason }
+ * { type: 'complete', runId, completedAt }
+ * { type: 'canceled', runId, completedAt }
+ * { type: 'error', runId, error, failedAt }
+ */
+export function usePipelineAutoRunProgress(issueId, { enabled = true } = {}) {
+ const [frames, setFrames] = useState([]);
+ const [latest, setLatest] = useState(null);
+ const [isOpen, setIsOpen] = useState(false);
+ const esRef = useRef(null);
+
+ useEffect(() => {
+ if (!issueId || !enabled) return undefined;
+ setFrames([]);
+ setLatest(null);
+ setIsOpen(false);
+
+ const url = pipelineAutoRunSseUrl(issueId);
+ const es = new EventSource(url);
+ esRef.current = es;
+
+ es.onopen = () => setIsOpen(true);
+ es.onmessage = (evt) => {
+ const data = JSON.parse(evt.data);
+ setFrames((prev) => [...prev, data]);
+ setLatest(data);
+ if (data?.type === 'complete' || data?.type === 'canceled' || data?.type === 'error') {
+ // Server closes the stream after the cleanup window. Drop the client
+ // ourselves so the browser doesn't keep retrying.
+ es.close();
+ }
+ };
+ es.onerror = () => {
+ // EventSource auto-retries on transient disconnects; only mark closed
+ // when readyState is CLOSED (terminal).
+ if (es.readyState === EventSource.CLOSED) setIsOpen(false);
+ };
+
+ return () => {
+ es.close();
+ esRef.current = null;
+ };
+ }, [issueId, enabled]);
+
+ return { frames, latest, isOpen, close: () => esRef.current?.close() };
+}
diff --git a/client/src/pages/Pipeline.jsx b/client/src/pages/Pipeline.jsx
new file mode 100644
index 0000000000..f83314c049
--- /dev/null
+++ b/client/src/pages/Pipeline.jsx
@@ -0,0 +1,201 @@
+/**
+ * Pipeline page — series index.
+ *
+ * Lists existing production series and lets the user create new ones. Each
+ * series is the long-lived parent for a set of issues/episodes that share a
+ * bible (logline, premise, characters, world ref, style). Clicking a series
+ * drills into its detail page where issues are created and managed.
+ */
+
+import { useEffect, useState } from 'react';
+import { Link } from 'react-router-dom';
+import { Plus, Workflow as WorkflowIcon, Trash2, Loader2 } from 'lucide-react';
+import toast from '../components/ui/Toast';
+import {
+ listPipelineSeries,
+ createPipelineSeries,
+ deletePipelineSeries,
+ PIPELINE_TARGET_FORMATS,
+} from '../services/api';
+
+export default function Pipeline() {
+ const [series, setSeries] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [creating, setCreating] = useState(false);
+ const [showForm, setShowForm] = useState(false);
+ const [form, setForm] = useState({ name: '', logline: '', targetFormat: 'comic+tv' });
+
+ useEffect(() => {
+ listPipelineSeries()
+ .then((items) => setSeries(Array.isArray(items) ? items : []))
+ .catch((err) => toast.error(err.message || 'Failed to load series'))
+ .finally(() => setLoading(false));
+ }, []);
+
+ const handleCreate = async (e) => {
+ e?.preventDefault();
+ const name = form.name.trim();
+ if (!name) {
+ toast.error('Series name is required');
+ return;
+ }
+ setCreating(true);
+ const created = await createPipelineSeries({
+ name,
+ logline: form.logline.trim(),
+ targetFormat: form.targetFormat,
+ }).catch((err) => {
+ toast.error(err.message || 'Failed to create series');
+ return null;
+ });
+ setCreating(false);
+ if (!created) return;
+ // Reactive insert — no full refetch (CLAUDE.md convention).
+ setSeries((prev) => [created, ...prev]);
+ setForm({ name: '', logline: '', targetFormat: 'comic+tv' });
+ setShowForm(false);
+ toast.success(`Created "${created.name}"`);
+ };
+
+ // Two-click delete: first click "arms" the row, second click fires. Avoids
+ // window.confirm (banned per CLAUDE.md) without pulling in a modal for the
+ // skeleton. armedId resets on any other click.
+ const [armedId, setArmedId] = useState(null);
+ const handleDelete = async (s) => {
+ if (armedId !== s.id) {
+ setArmedId(s.id);
+ return;
+ }
+ setArmedId(null);
+ const prior = series;
+ setSeries((prev) => prev.filter((x) => x.id !== s.id));
+ await deletePipelineSeries(s.id).catch((err) => {
+ toast.error(err.message || 'Delete failed');
+ setSeries(prior);
+ });
+ };
+
+ return (
+ <div className="p-4 md:p-6 max-w-5xl">
+ <div className="flex items-center justify-between mb-6 flex-wrap gap-3">
+ <div className="flex items-center gap-3">
+ <WorkflowIcon className="w-6 h-6 text-port-accent" />
+ <h1 className="text-2xl font-bold text-white">Pipeline</h1>
+ </div>
+ <button
+ type="button"
+ onClick={() => setShowForm((v) => !v)}
+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent hover:bg-port-accent/90 text-white text-sm font-medium"
+ >
+ <Plus size={16} aria-hidden="true" />
+ New Series
+ </button>
+ </div>
+
+ <p className="text-sm text-gray-400 mb-6">
+ Each series carries a shared bible — logline, premise, characters, style, optional World — that
+ every issue/episode below inherits into its stage prompts. Pipeline runs an idea seed through prose →
+ comic script + TV script (text), and hands off to image gen / Creative Director for the visual stages.
+ </p>
+
+ {showForm && (
+ <form onSubmit={handleCreate} className="mb-6 p-4 bg-port-card border border-port-border rounded-lg space-y-3">
+ <div>
+ <label htmlFor="series-name" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">
+ Name
+ </label>
+ <input
+ id="series-name"
+ type="text"
+ value={form.name}
+ onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
+ placeholder="Salt Run"
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ maxLength={200}
+ autoFocus
+ />
+ </div>
+ <div>
+ <label htmlFor="series-logline" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">
+ Logline
+ </label>
+ <input
+ id="series-logline"
+ type="text"
+ value={form.logline}
+ onChange={(e) => setForm((f) => ({ ...f, logline: e.target.value }))}
+ placeholder="A foundry city goes silent — and the only survivor is a child."
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ maxLength={500}
+ />
+ </div>
+ <div>
+ <label htmlFor="series-format" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">
+ Target format
+ </label>
+ <select
+ id="series-format"
+ value={form.targetFormat}
+ onChange={(e) => setForm((f) => ({ ...f, targetFormat: e.target.value }))}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ >
+ {PIPELINE_TARGET_FORMATS.map((tf) => (
+ <option key={tf} value={tf}>{tf}</option>
+ ))}
+ </select>
+ </div>
+ <div className="flex gap-2">
+ <button
+ type="submit"
+ disabled={creating}
+ 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"
+ >
+ {creating ? <Loader2 size={14} className="animate-spin" /> : null}
+ Create
+ </button>
+ <button
+ type="button"
+ onClick={() => setShowForm(false)}
+ className="px-3 py-2 rounded-lg text-gray-400 hover:text-white text-sm"
+ >
+ Cancel
+ </button>
+ </div>
+ </form>
+ )}
+
+ {loading ? (
+ <div className="text-gray-500 text-sm">Loading series…</div>
+ ) : series.length === 0 ? (
+ <div className="text-gray-500 text-sm">No series yet. Click <span className="text-port-accent">New Series</span> to start.</div>
+ ) : (
+ <ul className="space-y-2">
+ {series.map((s) => (
+ <li key={s.id} className="flex items-center justify-between gap-3 p-3 bg-port-card border border-port-border rounded-lg hover:border-port-accent/40 transition-colors">
+ <Link to={`/pipeline/series/${s.id}`} className="flex-1 min-w-0">
+ <div className="text-white font-medium truncate">{s.name}</div>
+ {s.logline ? (
+ <div className="text-xs text-gray-500 truncate">{s.logline}</div>
+ ) : (
+ <div className="text-xs text-gray-600 italic">No logline yet</div>
+ )}
+ <div className="text-xs text-gray-600 mt-1">
+ {s.targetFormat} {s.issueCountTarget ? `• target ${s.issueCountTarget} issues` : ''}
+ </div>
+ </Link>
+ <button
+ type="button"
+ onClick={() => handleDelete(s)}
+ className={`p-2 ${armedId === s.id ? 'text-port-error' : 'text-gray-500 hover:text-port-error'}`}
+ aria-label={armedId === s.id ? `Confirm delete series ${s.name}` : `Delete series ${s.name}`}
+ title={armedId === s.id ? 'Click again to confirm delete' : 'Delete series'}
+ >
+ <Trash2 size={16} />
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/PipelineIssue.jsx b/client/src/pages/PipelineIssue.jsx
new file mode 100644
index 0000000000..e40dc9429c
--- /dev/null
+++ b/client/src/pages/PipelineIssue.jsx
@@ -0,0 +1,239 @@
+/**
+ * Pipeline Issue — the actual production page.
+ *
+ * Tab-driven stage navigation per /pipeline/issues/:issueId/:stage. Top action
+ * bar exposes the auto-run-text button which kicks off idea→prose→(comicScript
+ * + tvScript) and streams progress via SSE.
+ */
+
+import { useEffect, useState, useMemo } from 'react';
+import { Link, useParams, useNavigate } from 'react-router-dom';
+import {
+ ArrowLeft, Sparkles, Loader2, X, Lightbulb, BookOpen, FileText, Film as FilmIcon,
+ LayoutGrid, Image as ImageIcon, Clapperboard,
+} from 'lucide-react';
+import toast from '../components/ui/Toast';
+import {
+ getPipelineIssue, getPipelineSeries,
+ startPipelineAutoRunText, cancelPipelineAutoRunText,
+ PIPELINE_STAGES, PIPELINE_STAGE_LABELS,
+} from '../services/api';
+import { usePipelineAutoRunProgress } from '../hooks/usePipelineAutoRunProgress';
+import IdeaStage from '../components/pipeline/stages/IdeaStage';
+import ProseStage from '../components/pipeline/stages/ProseStage';
+import ComicScriptStage from '../components/pipeline/stages/ComicScriptStage';
+import TVScriptStage from '../components/pipeline/stages/TVScriptStage';
+import ComicPagesStage from '../components/pipeline/stages/ComicPagesStage';
+import StoryboardsStage from '../components/pipeline/stages/StoryboardsStage';
+import EpisodeVideoStage from '../components/pipeline/stages/EpisodeVideoStage';
+
+const STAGE_ICONS = {
+ idea: Lightbulb,
+ prose: BookOpen,
+ comicScript: FileText,
+ tvScript: FilmIcon,
+ comicPages: LayoutGrid,
+ storyboards: ImageIcon,
+ episodeVideo: Clapperboard,
+};
+
+const STAGE_COMPONENTS = {
+ idea: IdeaStage,
+ prose: ProseStage,
+ comicScript: ComicScriptStage,
+ tvScript: TVScriptStage,
+ comicPages: ComicPagesStage,
+ storyboards: StoryboardsStage,
+ episodeVideo: EpisodeVideoStage,
+};
+
+const STATUS_DOT = {
+ empty: 'bg-gray-700',
+ generating: 'bg-port-accent animate-pulse',
+ ready: 'bg-port-success',
+ edited: 'bg-port-warning',
+ 'needs-review': 'bg-port-warning',
+ error: 'bg-port-error',
+};
+
+export default function PipelineIssue() {
+ const { issueId, stage: stageParam } = useParams();
+ const navigate = useNavigate();
+ const stageId = PIPELINE_STAGES.includes(stageParam) ? stageParam : 'idea';
+
+ const [issue, setIssue] = useState(null);
+ const [series, setSeries] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [autoRunStarting, setAutoRunStarting] = useState(false);
+ const [autoRunActive, setAutoRunActive] = useState(false);
+ const { latest, frames } = usePipelineAutoRunProgress(issueId, { enabled: autoRunActive });
+
+ useEffect(() => {
+ let canceled = false;
+ getPipelineIssue(issueId)
+ .then((iss) => {
+ if (canceled) return iss;
+ setIssue(iss);
+ return getPipelineSeries(iss.seriesId);
+ })
+ .then((s) => { if (!canceled && s) setSeries(s); })
+ .catch((err) => {
+ if (canceled) return;
+ toast.error(err.message || 'Failed to load issue');
+ navigate('/pipeline');
+ })
+ .finally(() => { if (!canceled) setLoading(false); });
+ return () => { canceled = true; };
+ }, [issueId, navigate]);
+
+ // When auto-run reports a completed stage, refresh the issue so the panels
+ // re-render with the freshly-persisted output. Cheaper than re-fetching on
+ // every frame.
+ useEffect(() => {
+ if (!latest) return;
+ if (latest.type === 'stage:complete' || latest.type === 'complete' || latest.type === 'error' || latest.type === 'canceled') {
+ getPipelineIssue(issueId).then(setIssue).catch(() => null);
+ }
+ if (latest.type === 'complete' || latest.type === 'canceled' || latest.type === 'error') {
+ setAutoRunActive(false);
+ }
+ }, [latest, issueId]);
+
+ const handleAutoRun = async () => {
+ setAutoRunStarting(true);
+ const res = await startPipelineAutoRunText(issueId, {}).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');
+ };
+
+ const handleCancelAutoRun = async () => {
+ await cancelPipelineAutoRunText(issueId).catch((err) => {
+ toast.error(err.message || 'Cancel failed');
+ });
+ };
+
+ const handleStageUpdate = (id, updatedStage, updatedIssue) => {
+ if (updatedIssue) {
+ setIssue(updatedIssue);
+ return;
+ }
+ setIssue((prev) => prev ? ({
+ ...prev,
+ stages: { ...prev.stages, [id]: updatedStage },
+ }) : prev);
+ };
+
+ const stageTabs = useMemo(() => PIPELINE_STAGES.map((id) => ({
+ id,
+ label: PIPELINE_STAGE_LABELS[id],
+ Icon: STAGE_ICONS[id],
+ status: issue?.stages?.[id]?.status || 'empty',
+ })), [issue]);
+
+ if (loading) return <div className="p-6 text-gray-500 text-sm">Loading issue…</div>;
+ if (!issue) return null;
+
+ const StageComponent = STAGE_COMPONENTS[stageId];
+
+ return (
+ <div className="flex flex-col h-full max-w-6xl">
+ {/* Header */}
+ <div className="p-4 md:p-6 border-b border-port-border space-y-3">
+ <div className="flex items-center gap-3 flex-wrap text-sm">
+ <Link to="/pipeline" className="text-gray-400 hover:text-white inline-flex items-center gap-1">
+ <ArrowLeft size={14} /> All Series
+ </Link>
+ {series ? (
+ <>
+ <span className="text-gray-600">/</span>
+ <Link to={`/pipeline/series/${series.id}`} className="text-gray-400 hover:text-white truncate max-w-[200px]">
+ {series.name}
+ </Link>
+ </>
+ ) : null}
+ <span className="text-gray-600">/</span>
+ <span className="text-white truncate">#{issue.number} {issue.title}</span>
+ </div>
+
+ <div className="flex items-center justify-between gap-3 flex-wrap">
+ <h1 className="text-xl font-bold text-white truncate">#{issue.number} — {issue.title}</h1>
+ <div className="flex items-center gap-2">
+ {autoRunActive && (
+ <button
+ type="button"
+ onClick={handleCancelAutoRun}
+ className="inline-flex items-center gap-1 px-3 py-2 rounded-lg bg-port-card border border-port-border text-port-error text-sm"
+ >
+ <X size={14} /> Cancel auto-run
+ </button>
+ )}
+ <button
+ type="button"
+ 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
+ </button>
+ </div>
+ </div>
+
+ {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 === 'skip' && <>{PIPELINE_STAGE_LABELS[latest.stage]} skipped — {latest.reason}</>}
+ {latest.type === 'start' && <>Starting auto-run…</>}
+ </div>
+ ) : null}
+ </div>
+
+ {/* Stage tabs */}
+ <div className="flex border-b border-port-border overflow-x-auto" role="tablist">
+ {stageTabs.map(({ id, label, Icon, status }) => {
+ const isActive = id === stageId;
+ return (
+ <button
+ key={id}
+ onClick={() => navigate(`/pipeline/issues/${issueId}/${id}`)}
+ role="tab"
+ aria-selected={isActive}
+ className={`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors whitespace-nowrap ${
+ isActive
+ ? 'text-port-accent border-b-2 border-port-accent bg-port-accent/5'
+ : 'text-gray-400 hover:text-white hover:bg-port-card'
+ }`}
+ >
+ <Icon size={14} aria-hidden="true" />
+ {label}
+ <span className={`w-1.5 h-1.5 rounded-full ${STATUS_DOT[status] || STATUS_DOT.empty}`} aria-hidden="true" />
+ </button>
+ );
+ })}
+ </div>
+
+ {/* Active stage panel */}
+ <div className="flex-1 overflow-auto p-4 md:p-6">
+ {StageComponent ? (
+ <StageComponent issue={issue} series={series} onStageUpdate={handleStageUpdate} />
+ ) : (
+ <div className="text-gray-500 text-sm">Unknown stage.</div>
+ )}
+ {/* Frames log for debugging during auto-run — collapsed but available. */}
+ {frames.length > 0 ? (
+ <details className="mt-6 text-xs text-gray-600">
+ <summary className="cursor-pointer text-gray-500">Auto-run frames ({frames.length})</summary>
+ <pre className="mt-2 p-3 bg-port-bg border border-port-border rounded overflow-auto max-h-64">{frames.map((f) => JSON.stringify(f)).join('\n')}</pre>
+ </details>
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsx
new file mode 100644
index 0000000000..4c3d3d6e45
--- /dev/null
+++ b/client/src/pages/PipelineSeries.jsx
@@ -0,0 +1,337 @@
+/**
+ * Pipeline — Series detail page.
+ *
+ * Edit the series bible (name, logline, premise, worldId, styleNotes,
+ * targetFormat, characters) and manage child issues/episodes.
+ */
+
+import { useEffect, useState } from 'react';
+import { Link, useParams, useNavigate } from 'react-router-dom';
+import {
+ ArrowLeft, Plus, Save, Trash2, Loader2, ChevronRight, Workflow as WorkflowIcon, Globe,
+} from 'lucide-react';
+import toast from '../components/ui/Toast';
+import {
+ getPipelineSeries, updatePipelineSeries,
+ listPipelineIssues, createPipelineIssue, deletePipelineIssue,
+ listWorlds,
+ PIPELINE_TARGET_FORMATS,
+} from '../services/api';
+
+const STATUS_COLORS = {
+ draft: 'text-gray-400 bg-gray-700/30',
+ running: 'text-port-accent bg-port-accent/10',
+ 'needs-review': 'text-port-warning bg-port-warning/10',
+ shipped: 'text-port-success bg-port-success/10',
+};
+
+export default function PipelineSeries() {
+ const { seriesId } = useParams();
+ const navigate = useNavigate();
+ const [series, setSeries] = useState(null);
+ const [issues, setIssues] = useState([]);
+ const [worlds, setWorlds] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [newIssueTitle, setNewIssueTitle] = useState('');
+ const [armedIssueId, setArmedIssueId] = useState(null);
+
+ useEffect(() => {
+ let canceled = false;
+ Promise.all([
+ getPipelineSeries(seriesId),
+ listPipelineIssues(seriesId),
+ listWorlds().catch(() => []),
+ ])
+ .then(([s, is, ws]) => {
+ if (canceled) return;
+ setSeries(s);
+ setIssues(Array.isArray(is) ? is : []);
+ setWorlds(Array.isArray(ws) ? ws : []);
+ })
+ .catch((err) => {
+ if (canceled) return;
+ toast.error(err.message || 'Failed to load series');
+ navigate('/pipeline');
+ })
+ .finally(() => { if (!canceled) setLoading(false); });
+ return () => { canceled = true; };
+ }, [seriesId, navigate]);
+
+ const patchSeries = (patch) => setSeries((prev) => ({ ...prev, ...patch }));
+
+ const handleSave = async () => {
+ if (!series) return;
+ setSaving(true);
+ const updated = await updatePipelineSeries(series.id, {
+ name: series.name,
+ logline: series.logline,
+ premise: series.premise,
+ worldId: series.worldId || null,
+ styleNotes: series.styleNotes,
+ targetFormat: series.targetFormat,
+ issueCountTarget: series.issueCountTarget,
+ characters: series.characters,
+ }).catch((err) => {
+ toast.error(err.message || 'Save failed');
+ return null;
+ });
+ setSaving(false);
+ if (updated) {
+ setSeries(updated);
+ toast.success('Series saved');
+ }
+ };
+
+ const handleAddCharacter = () => {
+ patchSeries({ characters: [...(series.characters || []), { name: '', description: '' }] });
+ };
+ const handleUpdateCharacter = (i, patch) => {
+ const next = [...series.characters];
+ next[i] = { ...next[i], ...patch };
+ patchSeries({ characters: next });
+ };
+ const handleRemoveCharacter = (i) => {
+ patchSeries({ characters: series.characters.filter((_, j) => j !== i) });
+ };
+
+ const handleCreateIssue = async (e) => {
+ e?.preventDefault();
+ const title = newIssueTitle.trim();
+ if (!title) return;
+ const created = await createPipelineIssue(seriesId, { title }).catch((err) => {
+ toast.error(err.message || 'Failed to create issue');
+ return null;
+ });
+ if (!created) return;
+ setIssues((prev) => [...prev, created]);
+ setNewIssueTitle('');
+ toast.success(`Created "${created.title}"`);
+ navigate(`/pipeline/issues/${created.id}/idea`);
+ };
+
+ const handleDeleteIssue = async (iss) => {
+ if (armedIssueId !== iss.id) {
+ setArmedIssueId(iss.id);
+ return;
+ }
+ setArmedIssueId(null);
+ const prior = issues;
+ setIssues((prev) => prev.filter((i) => i.id !== iss.id));
+ await deletePipelineIssue(iss.id).catch((err) => {
+ toast.error(err.message || 'Delete failed');
+ setIssues(prior);
+ });
+ };
+
+ if (loading) return <div className="p-6 text-gray-500 text-sm">Loading series…</div>;
+ if (!series) return null;
+
+ return (
+ <div className="p-4 md:p-6 max-w-5xl space-y-6">
+ <div className="flex items-center gap-3 flex-wrap">
+ <Link to="/pipeline" className="inline-flex items-center gap-1 text-sm text-gray-400 hover:text-white">
+ <ArrowLeft size={14} /> All Series
+ </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>
+ <button
+ type="button"
+ onClick={handleSave}
+ disabled={saving}
+ className="ml-auto inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"
+ >
+ {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
+ Save series
+ </button>
+ </div>
+
+ <section className="p-4 bg-port-card border border-port-border rounded-lg space-y-4">
+ <h2 className="text-xs uppercase tracking-wider text-gray-500">Bible</h2>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <Field label="Name">
+ <input
+ value={series.name || ''}
+ onChange={(e) => patchSeries({ name: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ maxLength={200}
+ />
+ </Field>
+ <Field label="Target format">
+ <select
+ value={series.targetFormat || 'comic+tv'}
+ onChange={(e) => patchSeries({ targetFormat: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ >
+ {PIPELINE_TARGET_FORMATS.map((tf) => <option key={tf} value={tf}>{tf}</option>)}
+ </select>
+ </Field>
+ <Field label="Logline">
+ <input
+ value={series.logline || ''}
+ onChange={(e) => patchSeries({ logline: e.target.value })}
+ placeholder="One-sentence pitch"
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ maxLength={500}
+ />
+ </Field>
+ <Field label="Target issue count">
+ <input
+ type="number"
+ min={0}
+ max={999}
+ value={series.issueCountTarget || 0}
+ onChange={(e) => patchSeries({ issueCountTarget: parseInt(e.target.value, 10) || 0 })}
+ className="w-32 px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ />
+ </Field>
+ </div>
+
+ <Field label="Premise (the bible — fed into every stage's prompt context)">
+ <textarea
+ value={series.premise || ''}
+ onChange={(e) => patchSeries({ premise: e.target.value })}
+ rows={5}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ maxLength={8000}
+ placeholder="Longer free-form premise. World, tone, central conflict, hooks. Fed verbatim into every issue's stage prompts."
+ />
+ </Field>
+
+ <Field label="Style notes (tonal / visual)">
+ <textarea
+ value={series.styleNotes || ''}
+ onChange={(e) => patchSeries({ styleNotes: e.target.value })}
+ rows={3}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ maxLength={4000}
+ placeholder="moebius linework, washed sepia, slow zooms, ambient drones. Reused as the visual prefix for every image-gen call from this series."
+ />
+ </Field>
+
+ <Field label="Linked World (from World Builder)">
+ <div className="flex items-center gap-2">
+ <select
+ value={series.worldId || ''}
+ onChange={(e) => patchSeries({ worldId: e.target.value || null })}
+ className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ >
+ <option value="">— None —</option>
+ {worlds.map((w) => <option key={w.id} value={w.id}>{w.name}</option>)}
+ </select>
+ <Link
+ to={series.worldId ? `/world-builder` : '/world-builder'}
+ className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline whitespace-nowrap"
+ >
+ <Globe size={12} />
+ {series.worldId ? 'Open World Builder' : 'Create a world'}
+ </Link>
+ </div>
+ </Field>
+
+ <div>
+ <div className="flex items-center justify-between mb-2">
+ <h3 className="text-xs uppercase tracking-wider text-gray-500">Characters</h3>
+ <button
+ type="button"
+ onClick={handleAddCharacter}
+ className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline"
+ >
+ <Plus size={12} /> Add character
+ </button>
+ </div>
+ {(series.characters || []).length === 0 ? (
+ <p className="text-xs text-gray-600 italic">No characters yet — the bible has more bite once a few are defined.</p>
+ ) : (
+ <ul className="space-y-2">
+ {series.characters.map((c, i) => (
+ <li key={i} className="flex gap-2 items-start">
+ <input
+ value={c.name}
+ onChange={(e) => handleUpdateCharacter(i, { name: e.target.value })}
+ placeholder="Name"
+ className="w-44 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
+ maxLength={200}
+ />
+ <input
+ value={c.description}
+ onChange={(e) => handleUpdateCharacter(i, { description: e.target.value })}
+ placeholder="Physical description + role (e.g. weathered foundry surveyor, 50s, slate-grey hair)"
+ className="flex-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
+ maxLength={2000}
+ />
+ <button
+ type="button"
+ onClick={() => handleRemoveCharacter(i)}
+ className="text-gray-500 hover:text-port-error p-2"
+ aria-label="Remove character"
+ >
+ <Trash2 size={14} />
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ </section>
+
+ <section>
+ <div className="flex items-center justify-between mb-3 flex-wrap gap-2">
+ <h2 className="text-sm font-semibold text-white">Issues / Episodes</h2>
+ <form onSubmit={handleCreateIssue} className="flex items-center gap-2">
+ <input
+ value={newIssueTitle}
+ onChange={(e) => setNewIssueTitle(e.target.value)}
+ placeholder="Issue title…"
+ className="w-56 px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
+ maxLength={300}
+ />
+ <button
+ type="submit"
+ disabled={!newIssueTitle.trim()}
+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-40"
+ >
+ <Plus size={14} /> New issue
+ </button>
+ </form>
+ </div>
+ {issues.length === 0 ? (
+ <p className="text-xs text-gray-600 italic">No issues yet. Create the first one to start the pipeline.</p>
+ ) : (
+ <ul className="space-y-2">
+ {issues.map((iss) => (
+ <li key={iss.id} className="flex items-center justify-between gap-3 p-3 bg-port-card border border-port-border rounded-lg hover:border-port-accent/40">
+ <Link to={`/pipeline/issues/${iss.id}/idea`} className="flex items-center gap-3 flex-1 min-w-0">
+ <span className="text-xs text-gray-500 w-10 shrink-0">#{iss.number}</span>
+ <span className="text-white truncate">{iss.title}</span>
+ <span className={`text-[10px] uppercase tracking-wider px-2 py-0.5 rounded ${STATUS_COLORS[iss.status] || STATUS_COLORS.draft}`}>
+ {iss.status}
+ </span>
+ </Link>
+ <button
+ type="button"
+ onClick={() => handleDeleteIssue(iss)}
+ className={`p-2 ${armedIssueId === iss.id ? 'text-port-error' : 'text-gray-500 hover:text-port-error'}`}
+ aria-label={armedIssueId === iss.id ? `Confirm delete issue ${iss.title}` : `Delete issue ${iss.title}`}
+ title={armedIssueId === iss.id ? 'Click again to confirm' : 'Delete issue'}
+ >
+ <Trash2 size={14} />
+ </button>
+ <ChevronRight size={14} className="text-gray-600" />
+ </li>
+ ))}
+ </ul>
+ )}
+ </section>
+ </div>
+ );
+}
+
+function Field({ label, children }) {
+ return (
+ <label className="block">
+ <span className="block text-xs uppercase tracking-wider text-gray-500 mb-1">{label}</span>
+ {children}
+ </label>
+ );
+}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 4fc8c59f2b..c4063bb732 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -40,6 +40,7 @@ export * from './apiImageVideo.js';
export * from './apiMediaJobs.js';
export * from './apiWritersRoom.js';
export * from './apiWorldBuilder.js';
+export * from './apiPipeline.js';
// Default export for simplified imports (get/post/put/delete helpers)
export { default } from './apiCore.js';
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
new file mode 100644
index 0000000000..ec8d1f8c1e
--- /dev/null
+++ b/client/src/services/apiPipeline.js
@@ -0,0 +1,82 @@
+import { request } from './apiCore.js';
+
+// Stage IDs mirror server/services/pipeline/issues.js — keep these in sync.
+export const PIPELINE_TEXT_STAGES = Object.freeze(['idea', 'prose', 'comicScript', 'tvScript']);
+export const PIPELINE_VISUAL_STAGES = Object.freeze(['comicPages', 'storyboards', 'episodeVideo']);
+export const PIPELINE_STAGES = Object.freeze([...PIPELINE_TEXT_STAGES, ...PIPELINE_VISUAL_STAGES]);
+
+export const PIPELINE_STAGE_LABELS = Object.freeze({
+ idea: 'Idea',
+ prose: 'Prose',
+ comicScript: 'Comic Script',
+ tvScript: 'TV Script',
+ comicPages: 'Comic Pages',
+ storyboards: 'Storyboards',
+ episodeVideo: 'Episode Video',
+});
+
+export const PIPELINE_TARGET_FORMATS = Object.freeze(['comic', 'tv', 'comic+tv']);
+
+// ---- Series ----
+export const listPipelineSeries = () => request('/pipeline/series');
+export const getPipelineSeries = (id) => request(`/pipeline/series/${encodeURIComponent(id)}`);
+export const createPipelineSeries = (data) => request('/pipeline/series', {
+ method: 'POST',
+ body: JSON.stringify(data),
+});
+export const updatePipelineSeries = (id, patch) => request(`/pipeline/series/${encodeURIComponent(id)}`, {
+ method: 'PATCH',
+ body: JSON.stringify(patch),
+});
+export const deletePipelineSeries = (id) => request(`/pipeline/series/${encodeURIComponent(id)}`, {
+ method: 'DELETE',
+});
+
+// ---- Issues ----
+export const listPipelineIssues = (seriesId) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/issues`);
+
+export const createPipelineIssue = (seriesId, data) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/issues`, {
+ method: 'POST',
+ body: JSON.stringify(data),
+ });
+
+export const getPipelineIssue = (id) => request(`/pipeline/issues/${encodeURIComponent(id)}`);
+
+export const updatePipelineIssue = (id, patch) =>
+ request(`/pipeline/issues/${encodeURIComponent(id)}`, {
+ method: 'PATCH',
+ body: JSON.stringify(patch),
+ });
+
+export const deletePipelineIssue = (id) =>
+ request(`/pipeline/issues/${encodeURIComponent(id)}`, { method: 'DELETE' });
+
+// ---- Stage operations ----
+export const generatePipelineStage = (issueId, stageId, opts = {}) =>
+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/${encodeURIComponent(stageId)}/generate`, {
+ method: 'POST',
+ body: JSON.stringify(opts),
+ });
+
+export const generatePipelineVisualImage = (issueId, stageId, opts) =>
+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/${encodeURIComponent(stageId)}/visual`, {
+ method: 'POST',
+ body: JSON.stringify(opts),
+ });
+
+// ---- Auto-run text chain ----
+export const startPipelineAutoRunText = (issueId, opts = {}) =>
+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/auto-run-text`, {
+ method: 'POST',
+ body: JSON.stringify(opts),
+ });
+
+export const cancelPipelineAutoRunText = (issueId) =>
+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/auto-run-text/cancel`, {
+ method: 'POST',
+ });
+
+export const pipelineAutoRunSseUrl = (issueId) =>
+ `/api/pipeline/issues/${encodeURIComponent(issueId)}/auto-run-text/progress`;
diff --git a/data.sample/prompts/stage-config.json b/data.sample/prompts/stage-config.json
index ca1cc59b80..0bbf9daee4 100644
--- a/data.sample/prompts/stage-config.json
+++ b/data.sample/prompts/stage-config.json
@@ -185,6 +185,34 @@
"model": "default",
"returnsJson": true,
"variables": []
+ },
+ "pipeline-idea-expansion": {
+ "name": "Pipeline — Idea / Beat Sheet",
+ "description": "Turn a rough seed idea for one issue or episode into a tight beat sheet with logline, theme, beats, setting, and any new characters. Spine for prose, comic script, TV script, and storyboard stages.",
+ "model": "default",
+ "returnsJson": false,
+ "variables": []
+ },
+ "pipeline-prose": {
+ "name": "Pipeline — Prose Draft",
+ "description": "Draft an 800–1500 word short-story version of one issue/episode from the beat sheet. Includes H2 scene breaks so downstream comic and TV adaptations have stable anchor points.",
+ "model": "default",
+ "returnsJson": false,
+ "variables": []
+ },
+ "pipeline-comic-script": {
+ "name": "Pipeline — Comic Book Script",
+ "description": "Adapt the prose draft into a Marvel/DC house-format comic-book issue script (page → panel → description / caption / dialogue / SFX). One of two parallel script stages, both downstream of prose.",
+ "model": "default",
+ "returnsJson": false,
+ "variables": []
+ },
+ "pipeline-tv-script": {
+ "name": "Pipeline — TV Teleplay",
+ "description": "Adapt the prose draft into a single-episode TV teleplay with sluglines, present-tense action, dialogue, and act breaks. One of two parallel script stages, both downstream of prose.",
+ "model": "default",
+ "returnsJson": false,
+ "variables": []
}
}
}
diff --git a/data.sample/prompts/stages/pipeline-comic-script.md b/data.sample/prompts/stages/pipeline-comic-script.md
new file mode 100644
index 0000000000..5196cc6a16
--- /dev/null
+++ b/data.sample/prompts/stages/pipeline-comic-script.md
@@ -0,0 +1,59 @@
+# Pipeline — Comic-Book Script
+
+You are a comics writer turning a prose draft into a publishable comic-book issue script in the Marvel/DC house format. Every panel is something an artist will draw, so every panel description must be **visually concrete** — describe what the camera sees, not how characters feel.
+
+## Series bible
+
+- **Title:** {{series.name}}
+- **Style / tonal notes:** {{series.styleNotes}}
+
+### Characters
+
+{{#series.characters}}
+- **{{name}}** — {{description}}
+{{/series.characters}}
+
+## This issue
+
+- **Number:** {{issue.number}}
+- **Title:** {{issue.title}}
+
+## Prose source
+
+```
+{{stages.prose.content}}
+```
+
+## Output format
+
+Return a markdown document with this exact structure:
+
+```
+# Issue {{issue.number}} — <Title>
+
+## Page 1
+
+### Panel 1
+**Description:** <visually concrete description of the frame: subjects, action, framing (wide / medium / close), lighting, mood>
+**Caption:** <text in narration box, or "(none)">
+**Dialogue:**
+- NAME: "line"
+- NAME: "line"
+**SFX:** <sound effect words, or "(none)">
+
+### Panel 2
+...
+```
+
+## Rules
+
+- Plan **5–7 panels per page**, with rare 1-panel splash pages for big reveals. A typical 22-page issue lands at 100–140 panels — but for a single-issue script driven by an ~800-word prose draft, target **8–12 pages** unless the prose is exceptionally action-heavy.
+- Panel descriptions stay in **present tense** and describe only what's on the page.
+- Dialogue is short — comic balloons hold about 25 words max. Break long speeches across panels.
+- Use **CAPS for character names** in dialogue attributions (`LINA:`), and call out **emphasis** with bold.
+- Captions for time/place jumps (`CAPTION: THREE HOURS LATER`) or interiority that can't be drawn.
+- SFX sparingly — only when they add to the page's energy.
+- Never re-describe a character's permanent appearance once introduced; just name them.
+- End the issue with a hook — a final-panel reveal, a question, a cliffhanger.
+
+Return ONLY the script. No preamble, no commentary.
diff --git a/data.sample/prompts/stages/pipeline-idea-expansion.md b/data.sample/prompts/stages/pipeline-idea-expansion.md
new file mode 100644
index 0000000000..315600221d
--- /dev/null
+++ b/data.sample/prompts/stages/pipeline-idea-expansion.md
@@ -0,0 +1,46 @@
+# Pipeline — Idea / Beat-Sheet Expansion
+
+You are a story consultant who turns a rough seed idea into a tight beat sheet for one issue (or episode) of an ongoing series. The beat sheet is the spine every later stage of the production pipeline will hang from — prose, comic script, TV teleplay, storyboards. Be specific. Avoid generalities.
+
+## Series bible
+
+- **Title:** {{series.name}}
+- **Logline:** {{series.logline}}
+- **Premise:** {{series.premise}}
+- **Visual / tonal style notes:** {{series.styleNotes}}
+
+### Characters in the series
+
+{{#series.characters}}
+- **{{name}}** — {{description}}
+{{/series.characters}}
+{{^series.characters}}
+*(No characters defined yet — invent placeholders only if absolutely required.)*
+{{/series.characters}}
+
+## This issue / episode
+
+- **Number:** {{issue.number}}
+- **Working title:** {{issue.title}}
+
+## Rough seed from the user
+
+```
+{{seed}}
+```
+
+## What to produce
+
+A markdown document with the following sections, in this exact order:
+
+1. **`# Issue Title`** — one line, your refined title for this issue/episode (override the working title if the seed implies a better one).
+2. **`## Logline`** — one sentence pitching the issue.
+3. **`## Theme`** — one sentence on the emotional/thematic core. What is this issue *about* underneath the plot?
+4. **`## Beat sheet`** — 5–8 beats numbered as a markdown list. Each beat is one sentence describing a concrete dramatic event. Cover setup → rising action → midpoint reversal → climax → resolution / cliffhanger.
+5. **`## Setting`** — 2–3 sentences naming the locations this issue uses and how they look. Reference the world's visual style.
+6. **`## New characters (if any)`** — for any character the seed introduces that isn't in the series bible, give a one-line `**Name** — physical + role description`. Skip the section if there are none.
+7. **`## Open questions`** — bullet list of anything you'd want the writer to confirm before drafting prose.
+
+Be concrete. Beats like "the character has an internal moment" are useless; beats like "Lina finds the burnt photograph hidden under the floorboard and recognizes the figure as her uncle" are useful.
+
+Return ONLY the markdown document. No prose before or after.
diff --git a/data.sample/prompts/stages/pipeline-prose.md b/data.sample/prompts/stages/pipeline-prose.md
new file mode 100644
index 0000000000..a426e57e66
--- /dev/null
+++ b/data.sample/prompts/stages/pipeline-prose.md
@@ -0,0 +1,40 @@
+# Pipeline — Prose Draft
+
+You are a short-fiction author drafting one issue / episode of an ongoing series as prose. The prose will later be adapted by separate passes into a comic-book script (panel-by-panel) and a TV teleplay (scene-by-scene). Write so both adaptations are downstream of strong prose — every visual beat is already on the page, and every character action is clear.
+
+## Series bible
+
+- **Title:** {{series.name}}
+- **Logline:** {{series.logline}}
+- **Premise:** {{series.premise}}
+- **Style:** {{series.styleNotes}}
+
+### Characters
+
+{{#series.characters}}
+- **{{name}}** — {{description}}
+{{/series.characters}}
+
+## This issue
+
+- **Number:** {{issue.number}}
+- **Title:** {{issue.title}}
+
+## Beat sheet (from the idea stage)
+
+```
+{{stages.idea.content}}
+```
+
+## What to write
+
+A self-contained short-story draft for this issue, **800–1500 words**. Structure it with H2 markdown scene breaks (`## Scene N — Slugline`) every time the location, time, or POV shifts — these scene breaks become the anchor points for the later script adaptations, so be deliberate about them.
+
+- Use third-person past tense unless the series notes specify otherwise.
+- Open *in scene*, not on exposition.
+- Show character through action and dialogue, not narration.
+- Hit every beat from the beat sheet, but feel free to inflate one beat into multiple scenes if it has more weight.
+- Land the ending. Cliffhangers are fine; trailing-off is not.
+- Don't invent contradictions to the character bible. Add details, but match the established ones.
+
+Return ONLY the prose. No commentary, no header summarizing the piece, no preamble. Start with the first `## Scene 1 — …` heading.
diff --git a/data.sample/prompts/stages/pipeline-tv-script.md b/data.sample/prompts/stages/pipeline-tv-script.md
new file mode 100644
index 0000000000..6e12002b32
--- /dev/null
+++ b/data.sample/prompts/stages/pipeline-tv-script.md
@@ -0,0 +1,72 @@
+# Pipeline — TV Teleplay
+
+You are a TV writer adapting a prose draft into a single-episode teleplay in standard industry format. The teleplay will later drive storyboards and a generated-video pipeline, so every scene description must be **filmable** — describe what the camera sees and hears, not what characters feel.
+
+## Series bible
+
+- **Title:** {{series.name}}
+- **Tone / style:** {{series.styleNotes}}
+
+### Characters
+
+{{#series.characters}}
+- **{{name}}** — {{description}}
+{{/series.characters}}
+
+## This episode
+
+- **Number:** {{issue.number}}
+- **Title:** {{issue.title}}
+
+## Prose source
+
+```
+{{stages.prose.content}}
+```
+
+## Output format
+
+Return a markdown document with this exact structure:
+
+```
+# Episode {{issue.number}} — <Title>
+
+## TEASER
+
+### Scene 1
+
+**INT./EXT. LOCATION — TIME OF DAY**
+
+Action paragraph in present tense, describing only what's visible / audible.
+
+CHARACTER NAME
+(parenthetical, optional)
+Dialogue line.
+
+CHARACTER NAME
+Another line of dialogue.
+
+Action continues...
+
+CUT TO:
+
+### Scene 2
+
+**EXT. NEXT LOCATION — TIME OF DAY**
+
+...
+```
+
+## Rules
+
+- Single half-hour structure: TEASER → ACT ONE → ACT TWO → ACT THREE → TAG. (For a 30-min series. Drop ACT THREE for a 22-min hard-half-hour, expand to four acts for a full hour.)
+- Use **sluglines in bold** for every scene: `**INT. KITCHEN — NIGHT**`.
+- Action paragraphs stay **short** (1–4 lines) and in **present tense**.
+- CAPS character names above their dialogue lines.
+- Parentheticals only when the line reading would otherwise be ambiguous.
+- Scene transitions in caps: `CUT TO:`, `SMASH CUT TO:`, `FADE TO:`.
+- Cover the same story beats as the prose, but free to add visual texture (establishing shots, silent reaction beats) the prose only implied.
+- Pages map to roughly one minute of screen time at 25–30 words of dialogue per page; aim for **a script that reads at the episode's target length**, not for a literal mapping.
+- End every act with a button — an image, a line, or a reveal that pulls you across the commercial break.
+
+Return ONLY the teleplay. No preamble, no commentary, no "FADE IN:" header unless the script genuinely opens cold.
diff --git a/server/index.js b/server/index.js
index bca693e3c2..670aae7d4c 100644
--- a/server/index.js
+++ b/server/index.js
@@ -88,6 +88,7 @@ import creativeDirectorRoutes from './routes/creativeDirector.js';
import writersRoomRoutes from './routes/writersRoom.js';
import worldBuilderRoutes from './routes/worldBuilder.js';
import { initWorldBuilderCollectionHook } from './services/worldBuilderCollectionHook.js';
+import pipelineRoutes from './routes/pipeline.js';
import { initMediaJobQueue } from './services/mediaJobQueue/index.js';
import { recoverInFlightProjects } from './services/creativeDirector/recovery.js';
import imageVideoModelsRoutes from './routes/imageVideoModels.js';
@@ -331,6 +332,7 @@ app.use('/api/media-jobs', mediaJobsRoutes);
app.use('/api/creative-director', creativeDirectorRoutes);
app.use('/api/writers-room', writersRoomRoutes);
app.use('/api/world-builder', worldBuilderRoutes);
+app.use('/api/pipeline', pipelineRoutes);
app.use('/api/image-video/models', imageVideoModelsRoutes);
app.use('/api/loras', lorasRoutes);
// AUTOMATIC1111-compatible surface for tailnet clients — gated by
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 471e146c63..d5c3456328 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -19,6 +19,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.media.timeline', path: '/media/timeline', label: 'Timeline', section: 'Create', aliases: ['timeline', 'video-timeline', 'editor'], keywords: ['edit', 'trim', 'composite', 'stitch', 'cut', 'compose'] },
{ id: 'nav.media.models', path: '/media/models', label: 'Media Models', section: 'Create', aliases: ['media-models', 'image-models', 'video-models', 'huggingface'], keywords: ['hf cache', 'model storage', 'disk'] },
{ id: 'nav.create.world-builder', path: '/world-builder', label: 'World Builder', section: 'Create', aliases: ['world-builder', 'worldbuilder', 'worldbuild', 'world', 'universe', 'lore'], keywords: ['style template', 'sci-fi', 'fantasy', 'concept art', 'batch render', 'variations'] },
+ { id: 'nav.create.pipeline', path: '/pipeline', label: 'Pipeline', section: 'Create', aliases: ['pipeline', 'production', 'series-pipeline', 'production-pipeline'], keywords: ['series', 'issue', 'episode', 'comic', 'script', 'prose', 'storyboard', 'narrative', 'workflow'] },
{ id: 'nav.media.loras', path: '/media/loras', label: 'LoRAs', section: 'Create', aliases: ['loras', 'lora', 'lora-manager', 'civitai'], keywords: ['lora', 'civitai', 'fine-tune', 'style adapter', 'realstagram', 'photoreal', 'flux lora'] },
{ id: 'nav.media.settings', path: '/media/image?settings=1', label: 'Media Gen Settings', section: 'Create', aliases: ['media-settings', 'image-gen-settings', 'sd-settings', 'video-gen-settings'] },
{ id: 'nav.writers-room', path: '/writers-room', label: 'Writers Room', section: 'Create', aliases: ['writers-room', 'writersroom', 'writer', 'write', 'studio', 'novel'], keywords: ['prose', 'screenplay', 'story', 'draft', 'manuscript', 'literary', 'novel', 'short story'] },
@@ -57,7 +58,10 @@ export const NAV_COMMANDS = [
{ id: 'nav.cos.learning', path: '/cos/learning', label: 'Learning', section: 'Chief of Staff', aliases: ['cos-learning'] },
{ id: 'nav.cos.memory', path: '/cos/memory', label: 'Memory', section: 'Chief of Staff', aliases: ['cos-memory'] },
{ id: 'nav.cos.schedule', path: '/cos/schedule', label: 'Schedule', section: 'Chief of Staff', aliases: ['schedule', 'cos-schedule'] },
- { id: 'nav.cos.workflow', path: '/cos/workflow', label: 'Workflow', section: 'Chief of Staff', aliases: ['workflow', 'cos-workflow', 'pipeline'], keywords: ['pipeline', 'dependencies', 'order', 'stages'] },
+ // Note: `pipeline` is intentionally NOT an alias here — that token now
+ // resolves to the dedicated /pipeline page (nav.create.pipeline). CoS still
+ // surfaces "task pipeline" via the `pipeline` keyword in the palette.
+ { id: 'nav.cos.workflow', path: '/cos/workflow', label: 'Workflow', section: 'Chief of Staff', aliases: ['workflow', 'cos-workflow'], keywords: ['pipeline', 'dependencies', 'order', 'stages', 'task pipeline'] },
{ id: 'nav.cos.productivity', path: '/cos/productivity', label: 'Streaks', section: 'Chief of Staff', aliases: ['streaks', 'cos-productivity'] },
{ id: 'nav.messages.inbox', path: '/messages/inbox', label: 'Inbox', section: 'Comms', aliases: ['messages'] },
diff --git a/server/lib/navManifest.test.js b/server/lib/navManifest.test.js
index 5ceb48e40d..2c4648787a 100644
--- a/server/lib/navManifest.test.js
+++ b/server/lib/navManifest.test.js
@@ -54,6 +54,14 @@ describe('resolveNavCommand — fuzzy matching', () => {
expect(hit?.command?.id).toBe('nav.create.world-builder');
});
+ it('resolves "pipeline" to the new Create Pipeline page (not CoS Workflow)', () => {
+ // The `pipeline` alias used to belong to /cos/workflow; the new dedicated
+ // Pipeline page owns it now. CoS Workflow keeps `pipeline` as a keyword.
+ const hit = resolveNavCommand('pipeline');
+ expect(hit?.path).toBe('/pipeline');
+ expect(hit?.command?.id).toBe('nav.create.pipeline');
+ });
+
it('resolves multi-word voice phrasings that end on a known page', () => {
// "take me to the tasks page" → normalized "take-me-to-the-tasks-page"
// → the resolver's "key contained in norm" tier picks up "tasks" via the
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
new file mode 100644
index 0000000000..cd94646861
--- /dev/null
+++ b/server/routes/pipeline.js
@@ -0,0 +1,266 @@
+/**
+ * Pipeline Routes
+ *
+ * Two resource scopes:
+ * /api/pipeline/series — Series CRUD (the long-lived narrative bible)
+ * /api/pipeline/issues — Issue/Episode CRUD + stage operations
+ *
+ * GET /series → Series[]
+ * POST /series → Series
+ * GET /series/:id → Series
+ * PATCH /series/:id → Series
+ * DELETE /series/:id → { id }
+ * GET /series/:id/issues → Issue[]
+ * POST /series/:id/issues → Issue
+ * GET /issues/:id → Issue
+ * PATCH /issues/:id → Issue
+ * DELETE /issues/:id → { id }
+ * POST /issues/:id/stages/:stageId/generate → { issue, stage, runId }
+ * POST /issues/:id/stages/:stageId/visual → { jobId, mode, prompt }
+ * POST /issues/:id/auto-run-text → { runId, alreadyRunning, sseUrl }
+ * GET /issues/:id/auto-run-text/progress → SSE (text/event-stream)
+ * POST /issues/:id/auto-run-text/cancel → { canceled }
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import * as seriesSvc from '../services/pipeline/series.js';
+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';
+
+const router = Router();
+
+const SERVICE_ERROR_STATUS = {
+ [seriesSvc.ERR_NOT_FOUND]: 404,
+ [seriesSvc.ERR_VALIDATION]: 400,
+ [issuesSvc.ERR_NOT_FOUND]: 404,
+ [issuesSvc.ERR_VALIDATION]: 400,
+};
+
+const mapServiceError = (err) => {
+ const status = SERVICE_ERROR_STATUS[err?.code];
+ if (status) return new ServerError(err.message, { status, code: err.code });
+ return err;
+};
+
+// ---- Series schemas ----
+
+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(''),
+ imageRefs: z.array(z.string().trim().min(1).max(seriesSvc.IMAGE_REF_MAX))
+ .max(seriesSvc.IMAGE_REFS_PER_CHARACTER_MAX).optional(),
+});
+
+const seriesCreateSchema = z.object({
+ name: z.string().trim().min(1).max(seriesSvc.NAME_MAX),
+ 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(),
+ 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(),
+});
+
+const seriesPatchSchema = z.object({
+ name: z.string().trim().min(1).max(seriesSvc.NAME_MAX).optional(),
+ 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(),
+ 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(),
+}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });
+
+// ---- Issue schemas ----
+
+const issueCreateSchema = z.object({
+ title: z.string().trim().min(1).max(issuesSvc.TITLE_MAX),
+ number: z.number().int().min(1).max(9999).optional(),
+});
+
+const stageInputSchema = z.object({
+ status: z.enum(issuesSvc.STAGE_STATUSES).optional(),
+ input: z.string().max(issuesSvc.STAGE_INPUT_MAX).optional(),
+ output: z.string().max(issuesSvc.STAGE_OUTPUT_MAX).optional(),
+ errorMessage: z.string().max(issuesSvc.STAGE_NOTES_MAX).optional(),
+});
+
+// Visual stage records also accept pages/scenes/cdProjectId/videoPath — those
+// are arbitrary structured artifacts written by the visual UI. Keep the
+// validation light here so the artifact shape can evolve without a schema
+// migration; the service-level sanitizer caps array length.
+const visualStageInputSchema = stageInputSchema.extend({
+ pages: z.array(z.any()).max(200).optional(),
+ scenes: z.array(z.any()).max(200).optional(),
+ cdProjectId: z.string().trim().max(64).nullable().optional(),
+ videoPath: z.string().trim().max(1000).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(),
+}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });
+
+const generateSchema = z.object({
+ seedInput: z.string().max(issuesSvc.STAGE_INPUT_MAX).optional(),
+ providerId: z.string().trim().max(80).optional(),
+ model: z.string().trim().max(200).optional(),
+});
+
+const visualGenerateSchema = z.object({
+ description: z.string().trim().min(1).max(8000),
+ negativePrompt: z.string().trim().max(2000).optional(),
+ extraStyle: z.string().trim().max(2000).optional(),
+ mode: z.enum(['local', 'codex']).optional(),
+ modelId: z.string().trim().max(64).optional(),
+ width: z.number().int().min(64).max(2048).optional(),
+ height: z.number().int().min(64).max(2048).optional(),
+ steps: z.number().int().min(1).max(150).optional(),
+ cfgScale: z.number().min(0).max(30).optional(),
+ guidance: z.number().min(0).max(30).optional(),
+});
+
+const autoRunSchema = z.object({
+ providerId: z.string().trim().max(80).optional(),
+ model: z.string().trim().max(200).optional(),
+ force: z.boolean().optional(),
+});
+
+// =====================
+// Series routes
+// =====================
+
+router.get('/series', asyncHandler(async (_req, res) => {
+ res.json(await seriesSvc.listSeries());
+}));
+
+router.post('/series', asyncHandler(async (req, res) => {
+ const body = validateRequest(seriesCreateSchema, req.body ?? {});
+ res.status(201).json(await seriesSvc.createSeries(body));
+}));
+
+router.get('/series/:id', asyncHandler(async (req, res) => {
+ const s = await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ res.json(s);
+}));
+
+router.patch('/series/:id', asyncHandler(async (req, res) => {
+ const body = validateRequest(seriesPatchSchema, req.body ?? {});
+ const s = await seriesSvc.updateSeries(req.params.id, body).catch((err) => { throw mapServiceError(err); });
+ res.json(s);
+}));
+
+router.delete('/series/:id', asyncHandler(async (req, res) => {
+ const r = await seriesSvc.deleteSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ res.json(r);
+}));
+
+router.get('/series/:id/issues', asyncHandler(async (req, res) => {
+ // Validate the series exists so a typo returns 404 instead of [] (less
+ // confusing for the UI).
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ res.json(await issuesSvc.listIssues({ seriesId: req.params.id }));
+}));
+
+router.post('/series/:id/issues', asyncHandler(async (req, res) => {
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const body = validateRequest(issueCreateSchema, req.body ?? {});
+ const created = await issuesSvc.createIssue({ ...body, seriesId: req.params.id });
+ res.status(201).json(created);
+}));
+
+// =====================
+// Issue routes
+// =====================
+
+router.get('/issues/:id', asyncHandler(async (req, res) => {
+ const issue = await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });
+ res.json(issue);
+}));
+
+router.patch('/issues/:id', asyncHandler(async (req, res) => {
+ const body = validateRequest(issuePatchSchema, req.body ?? {});
+ const issue = await issuesSvc.updateIssue(req.params.id, body).catch((err) => { throw mapServiceError(err); });
+ res.json(issue);
+}));
+
+router.delete('/issues/:id', asyncHandler(async (req, res) => {
+ const r = await issuesSvc.deleteIssue(req.params.id).catch((err) => { throw mapServiceError(err); });
+ res.json(r);
+}));
+
+// =====================
+// Stage operations
+// =====================
+
+router.post('/issues/:id/stages/:stageId/generate', asyncHandler(async (req, res) => {
+ const { id, stageId } = req.params;
+ if (!issuesSvc.TEXT_STAGE_IDS.includes(stageId)) {
+ throw new ServerError(
+ `Stage "${stageId}" is not generatable via text-LLM. Use the /visual endpoint for image stages.`,
+ { status: 400, code: 'PIPELINE_NON_TEXT_STAGE' },
+ );
+ }
+ const body = validateRequest(generateSchema, req.body ?? {});
+ const result = await generateStage(id, stageId, body).catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
+router.post('/issues/:id/stages/:stageId/visual', asyncHandler(async (req, res) => {
+ const { id, stageId } = req.params;
+ if (!issuesSvc.VISUAL_STAGE_IDS.includes(stageId)) {
+ throw new ServerError(
+ `Stage "${stageId}" is not a visual stage. Use /generate for text-LLM stages.`,
+ { status: 400, code: 'PIPELINE_NON_VISUAL_STAGE' },
+ );
+ }
+ 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(visualGenerateSchema, req.body ?? {});
+ const result = await enqueueVisualImage(id, stageId, body).catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
+// =====================
+// Auto-run text chain
+// =====================
+
+router.post('/issues/:id/auto-run-text', asyncHandler(async (req, res) => {
+ const body = validateRequest(autoRunSchema, req.body ?? {});
+ // Validate the issue exists before kicking off the runner so a bad id
+ // returns 404 instead of a half-started run.
+ await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const result = await autoRunner.startAutoRunTextStages(req.params.id, body);
+ res.json({
+ ...result,
+ sseUrl: `/api/pipeline/issues/${req.params.id}/auto-run-text/progress`,
+ });
+}));
+
+router.get('/issues/:id/auto-run-text/progress', (req, res) => {
+ const attached = autoRunner.attachClient(req.params.id, res);
+ if (!attached) {
+ res.status(404).json({ error: 'No active auto-run for this issue' });
+ }
+});
+
+router.post('/issues/:id/auto-run-text/cancel', asyncHandler(async (req, res) => {
+ const canceled = autoRunner.cancelAutoRun(req.params.id);
+ res.json({ canceled });
+}));
+
+export default router;
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
new file mode 100644
index 0000000000..93011e7123
--- /dev/null
+++ b/server/routes/pipeline.test.js
@@ -0,0 +1,168 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+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}` };
+});
+
+// Stub the actual text-stage generator: persists ready/output so the route
+// returns a realistic { issue, stage, runId }.
+vi.mock('../services/pipeline/textStages.js', async () => {
+ const issuesSvc = await import('../services/pipeline/issues.js');
+ return {
+ generateStage: vi.fn(async (issueId, stageId, opts) => {
+ const { issue, stage } = await issuesSvc.updateStage(issueId, stageId, {
+ status: 'ready',
+ output: `mock-output:${stageId}:${opts?.seedInput || ''}`,
+ lastRunId: `run-${++uuidCounter}`,
+ });
+ return { issue, stage, runId: stage.lastRunId };
+ }),
+ };
+});
+
+// Stub the auto-runner so the test doesn't have to wait for real SSE traffic.
+vi.mock('../services/pipeline/autoRunner.js', () => ({
+ startAutoRunTextStages: vi.fn(async () => ({ runId: 'auto-run-1', alreadyRunning: false })),
+ attachClient: vi.fn(() => false),
+ cancelAutoRun: vi.fn(() => true),
+ isAutoRunActive: vi.fn(() => false),
+}));
+
+vi.mock('../services/pipeline/visualStages.js', () => ({
+ enqueueVisualImage: vi.fn(async (_issueId, stageId, opts) => ({
+ jobId: `job-${++uuidCounter}`,
+ mode: 'local',
+ prompt: `style, ${opts.description}`,
+ })),
+}));
+
+const pipelineRouter = (await import('./pipeline.js')).default;
+
+function makeApp() {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/pipeline', pipelineRouter);
+ app.use(errorMiddleware);
+ return app;
+}
+
+describe('pipeline routes', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ vi.clearAllMocks();
+ });
+
+ it('POST /series → 201 with created series', async () => {
+ const app = makeApp();
+ const r = await request(app).post('/api/pipeline/series').send({
+ name: 'Salt Run',
+ logline: 'A foundry city goes silent.',
+ premise: 'Long premise...',
+ styleNotes: 'moebius linework',
+ });
+ expect(r.status).toBe(201);
+ expect(r.body.id).toMatch(/^ser-/);
+ expect(r.body.name).toBe('Salt Run');
+ });
+
+ it('POST /series rejects empty name with 400', async () => {
+ const app = makeApp();
+ const r = await request(app).post('/api/pipeline/series').send({ name: '' });
+ expect(r.status).toBe(400);
+ });
+
+ it('PATCH /series/:id 404s for unknown id', async () => {
+ const app = makeApp();
+ const r = await request(app).patch('/api/pipeline/series/ser-nope').send({ name: 'x' });
+ expect(r.status).toBe(404);
+ });
+
+ it('POST /series/:id/issues creates an issue under the series', 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}/issues`).send({ title: 'Pilot' });
+ expect(r.status).toBe(201);
+ expect(r.body.id).toMatch(/^iss-/);
+ expect(r.body.seriesId).toBe(ser.body.id);
+ expect(r.body.number).toBe(1);
+ expect(r.body.stages.idea.status).toBe('empty');
+ });
+
+ it('GET /series/:id/issues 404s for unknown series', async () => {
+ const app = makeApp();
+ const r = await request(app).get('/api/pipeline/series/ser-nope/issues');
+ expect(r.status).toBe(404);
+ });
+
+ it('POST /issues/:id/stages/:stageId/generate runs a text stage', 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/idea/generate`).send({ seedInput: 'foundry mystery' });
+ expect(r.status).toBe(200);
+ expect(r.body.stage.status).toBe('ready');
+ expect(r.body.stage.output).toContain('mock-output:idea');
+ });
+
+ it('POST /issues/:id/stages/:stageId/generate rejects visual stages', 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/comicPages/generate`).send({});
+ expect(r.status).toBe(400);
+ expect(r.body.code || r.body.error).toBeTruthy();
+ });
+
+ it('POST /issues/:id/stages/comicPages/visual enqueues an image job', 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/comicPages/visual`)
+ .send({ description: 'Lina enters the foundry, wide shot, dusk' });
+ expect(r.status).toBe(200);
+ expect(r.body.jobId).toMatch(/^job-/);
+ expect(r.body.mode).toBe('local');
+ });
+
+ it('POST /issues/:id/stages/episodeVideo/visual returns 501 (deferred)', 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);
+ });
+
+ it('POST /issues/:id/auto-run-text returns runId + sseUrl', 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}/auto-run-text`).send({});
+ expect(r.status).toBe(200);
+ expect(r.body.runId).toBe('auto-run-1');
+ expect(r.body.sseUrl).toContain('/progress');
+ });
+
+ it('POST /issues/:id/auto-run-text 404s for unknown issue', async () => {
+ const app = makeApp();
+ const r = await request(app).post('/api/pipeline/issues/iss-nope/auto-run-text').send({});
+ expect(r.status).toBe(404);
+ });
+});
diff --git a/server/services/pipeline/autoRunner.js b/server/services/pipeline/autoRunner.js
new file mode 100644
index 0000000000..9dc3b56ec9
--- /dev/null
+++ b/server/services/pipeline/autoRunner.js
@@ -0,0 +1,133 @@
+/**
+ * Pipeline — Auto-runner for the text-stage chain
+ *
+ * Runs idea → prose → (comicScript + tvScript in parallel) for one issue and
+ * streams progress to attached SSE clients. Visual stages (comicPages,
+ * storyboards, episodeVideo) stay manual — burning GPU minutes on
+ * un-reviewed content is too expensive for the MVP.
+ *
+ * Cancel: in-memory flag checked between stages. The coordinator stops
+ * before kicking off the next stage; an already-in-flight LLM call still
+ * completes (we don't kill the runner mid-stream).
+ *
+ * SSE: a single in-memory `runs` map keyed by `issueId`. Late-connecting
+ * clients receive the last broadcast frame via `attachSseClient`'s replay
+ * grace window in lib/sseUtils.js.
+ */
+
+import { randomUUID } from 'crypto';
+import { broadcastSse, attachSseClient, closeJobAfterDelay } from '../../lib/sseUtils.js';
+import { generateStage } from './textStages.js';
+import { getIssue, updateIssue } from './issues.js';
+
+// runs: Map<issueId, { runId, clients[], lastPayload, cancelRequested, startedAt }>
+const runs = new Map();
+
+export function isAutoRunActive(issueId) {
+ return runs.has(issueId);
+}
+
+export function attachClient(issueId, res) {
+ return attachSseClient(runs, issueId, res);
+}
+
+export function cancelAutoRun(issueId) {
+ const run = runs.get(issueId);
+ if (!run) return false;
+ run.cancelRequested = true;
+ return true;
+}
+
+function broadcast(issueId, payload) {
+ const run = runs.get(issueId);
+ if (!run) return;
+ broadcastSse(run, payload);
+}
+
+/**
+ * Kick off the text-stage chain for an issue. Returns the runId immediately;
+ * progress lands via SSE. Idempotent in the sense that re-calling while a
+ * run is in flight resolves to the existing runId.
+ */
+export async function startAutoRunTextStages(issueId, options = {}) {
+ if (runs.has(issueId)) return { runId: runs.get(issueId).runId, alreadyRunning: true };
+ const runId = randomUUID();
+ const record = {
+ runId,
+ clients: [],
+ lastPayload: null,
+ cancelRequested: false,
+ startedAt: new Date().toISOString(),
+ };
+ runs.set(issueId, record);
+
+ // Kick off the coordinator without awaiting. The outer try/catch is the one
+ // permitted boundary use of try/catch in this module — without it an LLM
+ // rejection would surface as an unhandledRejection on Node ≥15 and kill the
+ // process. See ~/.claude skill `nodejs-async-event-listener-unhandled-rejection`.
+ (async () => {
+ await updateIssue(issueId, { status: 'running' }).catch(() => null);
+ broadcast(issueId, { type: 'start', runId, stages: ['idea', 'prose', 'comicScript', 'tvScript'] });
+
+ try {
+ // Stage 1: idea — skip if already ready/edited and not force-rerun
+ if (!record.cancelRequested) {
+ await runStageIfNeeded(issueId, 'idea', options);
+ }
+ // Stage 2: prose — depends on idea
+ if (!record.cancelRequested) {
+ await runStageIfNeeded(issueId, 'prose', options);
+ }
+ // Stage 3: comicScript + tvScript in parallel — both depend only on prose
+ if (!record.cancelRequested) {
+ await Promise.all([
+ runStageIfNeeded(issueId, 'comicScript', options),
+ runStageIfNeeded(issueId, 'tvScript', options),
+ ]);
+ }
+
+ const status = record.cancelRequested ? 'needs-review' : 'needs-review';
+ await updateIssue(issueId, { status }).catch(() => null);
+ broadcast(issueId, {
+ type: record.cancelRequested ? 'canceled' : 'complete',
+ runId,
+ completedAt: new Date().toISOString(),
+ });
+ console.log(`✅ Pipeline auto-run ${record.cancelRequested ? 'canceled' : 'complete'} — issue=${issueId.slice(0, 8)} runId=${runId.slice(0, 8)}`);
+ } catch (err) {
+ const message = (err?.message || String(err)).slice(0, 1000);
+ console.error(`❌ Pipeline auto-run failed — issue=${issueId.slice(0, 8)} ${message}`);
+ await updateIssue(issueId, { status: 'needs-review' }).catch(() => null);
+ broadcast(issueId, { type: 'error', runId, error: message, failedAt: new Date().toISOString() });
+ } finally {
+ // Hold the SSE list open briefly so late-attaching clients still see
+ // the terminal frame via replay (matches mediaJobQueue's behavior).
+ closeJobAfterDelay(runs, issueId);
+ }
+ })();
+
+ return { runId, alreadyRunning: false };
+}
+
+async function runStageIfNeeded(issueId, stageId, options) {
+ const issue = await getIssue(issueId);
+ const cur = issue.stages?.[stageId];
+ // Skip if the user has already populated this stage and we aren't forced.
+ // 'edited' = user typed into the editor; 'ready' = LLM filled and user
+ // hasn't asked to rerun. Both are good — fall through to the next stage.
+ if (!options.force && cur && (cur.status === 'ready' || cur.status === 'edited') && cur.output) {
+ broadcast(issueId, { type: 'skip', stage: stageId, reason: 'already populated' });
+ return;
+ }
+ broadcast(issueId, { type: 'stage:start', stage: stageId });
+ const { stage } = await generateStage(issueId, stageId, options);
+ broadcast(issueId, {
+ type: 'stage:complete',
+ stage: stageId,
+ status: stage.status,
+ length: stage.output?.length || 0,
+ });
+}
+
+// Export internals for tests.
+export const __testing = { runs };
diff --git a/server/services/pipeline/autoRunner.test.js b/server/services/pipeline/autoRunner.test.js
new file mode 100644
index 0000000000..b0f0c0e38d
--- /dev/null
+++ b/server/services/pipeline/autoRunner.test.js
@@ -0,0 +1,148 @@
+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}` };
+});
+
+// Inline generator that flips the stage to ready without doing any real work.
+// We're testing the coordinator, not the LLM call site.
+const generated = [];
+vi.mock('./textStages.js', async () => {
+ const issuesSvc = await import('./issues.js');
+ return {
+ generateStage: vi.fn(async (issueId, stageId) => {
+ generated.push(stageId);
+ const { issue, stage } = await issuesSvc.updateStage(issueId, stageId, {
+ status: 'ready',
+ output: `OUTPUT-${stageId}`,
+ lastRunId: `run-${stageId}`,
+ });
+ return { issue, stage, runId: `run-${stageId}` };
+ }),
+ };
+});
+
+const seriesSvc = await import('./series.js');
+const issuesSvc = await import('./issues.js');
+const autoRunner = await import('./autoRunner.js');
+
+// Drain any in-flight microtasks/promises spawned by startAutoRunTextStages.
+const flush = () => new Promise((r) => setImmediate(r));
+
+const waitFor = async (predicate, { timeoutMs = 1000, intervalMs = 5 } = {}) => {
+ const start = Date.now();
+ while (Date.now() - start < timeoutMs) {
+ if (predicate()) return;
+ await new Promise((r) => setTimeout(r, intervalMs));
+ }
+ throw new Error('waitFor: predicate never became true');
+};
+
+describe('pipeline auto-runner', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ generated.length = 0;
+ // Clear the in-memory run map between tests.
+ autoRunner.__testing.runs.clear();
+ vi.clearAllMocks();
+ });
+
+ async function seed() {
+ const series = await seriesSvc.createSeries({ name: 'Series', logline: 'L', premise: 'P' });
+ const issue = await issuesSvc.createIssue({ seriesId: series.id, title: 'Issue' });
+ return { series, issue };
+ }
+
+ it('runs idea → prose → (comicScript + tvScript in parallel) end to end', async () => {
+ const { issue } = await seed();
+ const { runId, alreadyRunning } = await autoRunner.startAutoRunTextStages(issue.id);
+ expect(runId).toBeTruthy();
+ expect(alreadyRunning).toBe(false);
+
+ await waitFor(() => generated.length === 4);
+ // idea must come before prose (sequential); the two script stages may
+ // resolve in either order but both must follow prose.
+ expect(generated[0]).toBe('idea');
+ expect(generated[1]).toBe('prose');
+ expect(new Set(generated.slice(2))).toEqual(new Set(['comicScript', 'tvScript']));
+
+ // Issue status flips to needs-review when all stages complete (user must
+ // review before marking shipped).
+ const final = await issuesSvc.getIssue(issue.id);
+ expect(final.status).toBe('needs-review');
+ });
+
+ it('skips a stage that is already ready (no force)', async () => {
+ const { issue } = await seed();
+ await issuesSvc.updateStage(issue.id, 'idea', { status: 'ready', output: 'PREFILLED-IDEA' });
+ await autoRunner.startAutoRunTextStages(issue.id);
+ await waitFor(() => generated.length === 3);
+ expect(generated).not.toContain('idea');
+ expect(generated).toContain('prose');
+ expect(generated).toContain('comicScript');
+ expect(generated).toContain('tvScript');
+ });
+
+ it('reruns a ready stage when force=true', async () => {
+ const { issue } = await seed();
+ await issuesSvc.updateStage(issue.id, 'idea', { status: 'ready', output: 'PREFILLED-IDEA' });
+ await autoRunner.startAutoRunTextStages(issue.id, { force: true });
+ await waitFor(() => generated.length === 4);
+ expect(generated).toContain('idea');
+ });
+
+ it('returns alreadyRunning=true on concurrent start', async () => {
+ const { issue } = await seed();
+ const first = await autoRunner.startAutoRunTextStages(issue.id);
+ const second = await autoRunner.startAutoRunTextStages(issue.id);
+ expect(second.alreadyRunning).toBe(true);
+ expect(second.runId).toBe(first.runId);
+ await waitFor(() => generated.length === 4);
+ });
+
+ it('cancelAutoRun stops the chain between stages', async () => {
+ const { issue } = await seed();
+ // Generator needs a real timer delay so the test can poll generated,
+ // fire cancel, and have the coordinator's cancelRequested check land
+ // BEFORE the next stage kicks off. setImmediate microtask yielding
+ // isn't enough — vitest's setTimeout polling won't get a chance to run
+ // between micro-tasks.
+ const textStages = await import('./textStages.js');
+ textStages.generateStage.mockImplementation(async (issueId, stageId) => {
+ generated.push(stageId);
+ await new Promise((r) => setTimeout(r, 50));
+ const { issue: i, stage } = await issuesSvc.updateStage(issueId, stageId, {
+ status: 'ready', output: `O-${stageId}`, lastRunId: `r-${stageId}`,
+ });
+ return { issue: i, stage, runId: `r-${stageId}` };
+ });
+
+ autoRunner.startAutoRunTextStages(issue.id);
+ // Wait until at least the first stage starts, then cancel.
+ await waitFor(() => generated.length >= 1);
+ autoRunner.cancelAutoRun(issue.id);
+ // Coordinator must broadcast a terminal frame (canceled or complete)
+ // before we assert. `isAutoRunActive` stays true for the SSE cleanup
+ // grace window (5s), so we read the broadcast frame directly.
+ await waitFor(() => {
+ const run = autoRunner.__testing.runs.get(issue.id);
+ const t = run?.lastPayload?.type;
+ return t === 'canceled' || t === 'complete' || t === 'error';
+ });
+ expect(generated.length).toBeLessThan(4);
+ const finalRun = autoRunner.__testing.runs.get(issue.id);
+ expect(finalRun?.lastPayload?.type).toBe('canceled');
+ });
+});
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
new file mode 100644
index 0000000000..f1d12a1c88
--- /dev/null
+++ b/server/services/pipeline/issues.js
@@ -0,0 +1,234 @@
+/**
+ * Pipeline — Issues Service
+ *
+ * An Issue (or Episode — same record, two formats) is a child of a Series and
+ * carries the full per-stage state of one production pipeline run:
+ *
+ * stages.idea — beat sheet from the rough human seed
+ * stages.prose — short-story draft
+ * stages.comicScript — page/panel script (one of two parallel script stages)
+ * stages.tvScript — scene-by-scene teleplay (the other parallel script stage)
+ * stages.comicPages — image-gen output for each comic page's panels
+ * stages.storyboards — image-gen + per-scene video output via CD scene runner
+ * stages.episodeVideo — final stitched episode video via CD
+ *
+ * Each stage record carries a status, the user-editable input, the AI output,
+ * and a `lastRunId` pointer into data/runs/<runId>/ for the LLM transcript.
+ *
+ * Persisted to data/pipeline-issues.json.
+ */
+
+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');
+
+export const ERR_NOT_FOUND = 'PIPELINE_ISSUE_NOT_FOUND';
+export const ERR_VALIDATION = 'PIPELINE_ISSUE_VALIDATION';
+const makeErr = (message, code) => Object.assign(new Error(message), { code });
+
+export const TITLE_MAX = 300;
+export const SERIES_ID_MAX = 64;
+export const STAGE_INPUT_MAX = 200_000; // ~200kB — fits a long prose draft
+export const STAGE_OUTPUT_MAX = 400_000; // ~400kB — fits a long comic script
+export const STAGE_NOTES_MAX = 4000;
+export const ISSUES_PER_RESPONSE_MAX = 1000;
+
+// Stage IDs are ordered for UI display; the canonical order is also the
+// auto-run text-chain order (idea → prose → scripts in parallel). Comic
+// pages / storyboards / episode video stages are visual and stay manual
+// in MVP.
+export const TEXT_STAGE_IDS = Object.freeze(['idea', 'prose', 'comicScript', 'tvScript']);
+export const VISUAL_STAGE_IDS = Object.freeze(['comicPages', 'storyboards', 'episodeVideo']);
+export const STAGE_IDS = Object.freeze([...TEXT_STAGE_IDS, ...VISUAL_STAGE_IDS]);
+export const STAGE_STATUSES = Object.freeze(['empty', 'generating', 'ready', 'edited', 'needs-review', 'error']);
+export const ISSUE_STATUSES = Object.freeze(['draft', 'running', 'needs-review', 'shipped']);
+
+const isStr = (v) => typeof v === 'string';
+const trimTo = (v, max) => (isStr(v) ? v.trim().slice(0, max) : '');
+
+const emptyStage = () => ({
+ status: 'empty',
+ input: '',
+ output: '',
+ lastRunId: null,
+ errorMessage: '',
+ updatedAt: null,
+});
+
+const sanitizeStage = (raw) => {
+ if (!raw || typeof raw !== 'object') return emptyStage();
+ const status = STAGE_STATUSES.includes(raw.status) ? raw.status : 'empty';
+ return {
+ status,
+ input: trimTo(raw.input, STAGE_INPUT_MAX),
+ output: trimTo(raw.output, STAGE_OUTPUT_MAX),
+ lastRunId: isStr(raw.lastRunId) && raw.lastRunId ? raw.lastRunId : null,
+ errorMessage: trimTo(raw.errorMessage, STAGE_NOTES_MAX),
+ updatedAt: isStr(raw.updatedAt) ? raw.updatedAt : null,
+ };
+};
+
+const sanitizeVisualStage = (raw) => {
+ // Visual stages keep arbitrary structured artifact lists. Sanitize the
+ // wrapper but pass through known shapes.
+ const base = sanitizeStage(raw);
+ return {
+ ...base,
+ pages: Array.isArray(raw?.pages) ? raw.pages.slice(0, 200) : [],
+ 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,
+ };
+};
+
+const sanitizeStages = (raw = {}) => {
+ const out = {};
+ for (const id of TEXT_STAGE_IDS) out[id] = sanitizeStage(raw[id]);
+ for (const id of VISUAL_STAGE_IDS) out[id] = sanitizeVisualStage(raw[id]);
+ return out;
+};
+
+const sanitizeIssue = (raw) => {
+ if (!raw || typeof raw !== 'object') return null;
+ if (!isStr(raw.id) || !raw.id) return null;
+ if (!isStr(raw.seriesId) || !raw.seriesId) return null;
+ const title = trimTo(raw.title, TITLE_MAX);
+ if (!title) return null;
+ const number = Number.isFinite(raw.number) ? Math.max(0, Math.floor(raw.number)) : 0;
+ const status = ISSUE_STATUSES.includes(raw.status) ? raw.status : 'draft';
+ const createdAt = isStr(raw.createdAt) ? raw.createdAt : new Date().toISOString();
+ const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;
+ return {
+ id: raw.id,
+ seriesId: trimTo(raw.seriesId, SERIES_ID_MAX),
+ number,
+ title,
+ status,
+ stages: sanitizeStages(raw.stages || {}),
+ createdAt,
+ updatedAt,
+ };
+};
+
+async function readState() {
+ await ensureDir(PATHS.data);
+ const raw = await readJSONFile(STATE_PATH, { 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);
+}
+
+export async function listIssues({ seriesId = null } = {}) {
+ const { issues } = await readState();
+ const filtered = seriesId ? issues.filter((i) => i.seriesId === seriesId) : issues;
+ return [...filtered]
+ .sort((a, b) => {
+ if (a.seriesId !== b.seriesId) return a.seriesId.localeCompare(b.seriesId);
+ return (a.number || 0) - (b.number || 0);
+ })
+ .slice(0, ISSUES_PER_RESPONSE_MAX);
+}
+
+export async function getIssue(id) {
+ const { issues } = await readState();
+ const found = issues.find((i) => i.id === id);
+ if (!found) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);
+ return found;
+}
+
+export async function createIssue(input = {}) {
+ const seriesId = trimTo(input.seriesId, SERIES_ID_MAX);
+ if (!seriesId) throw makeErr('seriesId is required', ERR_VALIDATION);
+ const title = trimTo(input.title, TITLE_MAX);
+ if (!title) throw makeErr(`title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION);
+ const state = await readState();
+ const next = sanitizeIssue({
+ id: `iss-${randomUUID()}`,
+ seriesId,
+ number: input.number || nextIssueNumber(state.issues, seriesId),
+ title,
+ status: 'draft',
+ stages: input.stages || {},
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ });
+ if (!next) throw makeErr('Invalid issue payload', ERR_VALIDATION);
+ state.issues.push(next);
+ await writeState(state);
+ return next;
+}
+
+function nextIssueNumber(issues, seriesId) {
+ const peers = issues.filter((i) => i.seriesId === seriesId);
+ if (peers.length === 0) return 1;
+ return Math.max(...peers.map((i) => i.number || 0)) + 1;
+}
+
+export async function updateIssue(id, patch = {}) {
+ const state = await readState();
+ const idx = state.issues.findIndex((i) => i.id === id);
+ if (idx < 0) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);
+ const cur = state.issues[idx];
+
+ const mergedStages = 'stages' in patch
+ ? { ...cur.stages, ...(patch.stages || {}) }
+ : cur.stages;
+
+ const merged = sanitizeIssue({
+ ...cur,
+ ...('title' in patch ? { title: patch.title } : {}),
+ ...('number' in patch ? { number: patch.number } : {}),
+ ...('status' in patch ? { status: patch.status } : {}),
+ stages: mergedStages,
+ updatedAt: new Date().toISOString(),
+ });
+ if (!merged) throw makeErr('Invalid issue payload', ERR_VALIDATION);
+ state.issues[idx] = merged;
+ await writeState(state);
+ return merged;
+}
+
+/**
+ * Partial update to a single stage on an issue. Use this from generators so
+ * a stage write doesn't have to load the full issue, mutate, and re-validate.
+ * Patch keys: status, input, output, lastRunId, errorMessage, and (for
+ * visual stages) pages/scenes/cdProjectId/videoPath.
+ */
+export async function updateStage(issueId, stageId, patch = {}) {
+ if (!STAGE_IDS.includes(stageId)) {
+ throw makeErr(`Unknown stage: ${stageId}`, ERR_VALIDATION);
+ }
+ const state = await readState();
+ const idx = state.issues.findIndex((i) => i.id === issueId);
+ if (idx < 0) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);
+ const cur = state.issues[idx];
+ const isVisual = VISUAL_STAGE_IDS.includes(stageId);
+ const sanitize = isVisual ? sanitizeVisualStage : sanitizeStage;
+ const next = sanitize({
+ ...cur.stages[stageId],
+ ...patch,
+ updatedAt: new Date().toISOString(),
+ });
+ const mergedIssue = sanitizeIssue({
+ ...cur,
+ stages: { ...cur.stages, [stageId]: next },
+ updatedAt: new Date().toISOString(),
+ });
+ state.issues[idx] = mergedIssue;
+ await writeState(state);
+ return { issue: mergedIssue, stage: mergedIssue.stages[stageId] };
+}
+
+export async function deleteIssue(id) {
+ const state = await readState();
+ const before = state.issues.length;
+ state.issues = state.issues.filter((i) => i.id !== id);
+ if (state.issues.length === before) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);
+ await writeState(state);
+ return { id };
+}
diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.js
new file mode 100644
index 0000000000..e90315aa20
--- /dev/null
+++ b/server/services/pipeline/issues.test.js
@@ -0,0 +1,103 @@
+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 svc = await import('./issues.js');
+
+describe('pipeline issues service', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ });
+
+ it('createIssue assigns iss- id and auto-numbers within a series', async () => {
+ const a = await svc.createIssue({ seriesId: 'ser-1', title: 'First' });
+ const b = await svc.createIssue({ seriesId: 'ser-1', title: 'Second' });
+ const c = await svc.createIssue({ seriesId: 'ser-2', title: 'Other series first' });
+ expect(a.id).toMatch(/^iss-/);
+ expect(a.number).toBe(1);
+ expect(b.number).toBe(2);
+ expect(c.number).toBe(1); // independent counter per series
+ });
+
+ it('createIssue requires seriesId and title', async () => {
+ await expect(svc.createIssue({ title: 'x' })).rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ await expect(svc.createIssue({ seriesId: 'ser-1' })).rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it('every stage is initialized to "empty"', async () => {
+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'First' });
+ for (const id of svc.STAGE_IDS) {
+ expect(i.stages[id].status).toBe('empty');
+ expect(i.stages[id].output).toBe('');
+ }
+ });
+
+ it('updateStage patches only the named stage', async () => {
+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'First' });
+ const { issue, stage } = await svc.updateStage(i.id, 'idea', {
+ status: 'ready',
+ output: '# Beat sheet ...',
+ lastRunId: 'run-123',
+ });
+ expect(stage.status).toBe('ready');
+ expect(stage.output).toBe('# Beat sheet ...');
+ expect(stage.lastRunId).toBe('run-123');
+ expect(stage.updatedAt).toBeTruthy();
+ // Prose should still be empty.
+ expect(issue.stages.prose.status).toBe('empty');
+ expect(issue.stages.prose.output).toBe('');
+ });
+
+ it('updateStage rejects unknown stage ids', async () => {
+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'First' });
+ await expect(svc.updateStage(i.id, 'bogus', { status: 'ready' })).rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it('updateStage on a visual stage preserves arrays', async () => {
+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'First' });
+ const { stage } = await svc.updateStage(i.id, 'comicPages', {
+ status: 'ready',
+ pages: [{ panels: [{ imageJobId: 'j1' }] }],
+ });
+ expect(stage.pages).toHaveLength(1);
+ expect(stage.pages[0].panels[0].imageJobId).toBe('j1');
+ });
+
+ it('listIssues filters by seriesId and orders by number', async () => {
+ await svc.createIssue({ seriesId: 'ser-1', title: 'Issue 1' });
+ await svc.createIssue({ seriesId: 'ser-2', title: 'Other 1' });
+ await svc.createIssue({ seriesId: 'ser-1', title: 'Issue 2' });
+ const list1 = await svc.listIssues({ seriesId: 'ser-1' });
+ expect(list1.map((i) => i.number)).toEqual([1, 2]);
+ expect(list1.every((i) => i.seriesId === 'ser-1')).toBe(true);
+ });
+
+ it('updateIssue partial patch preserves other fields', async () => {
+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'First' });
+ await svc.updateStage(i.id, 'idea', { status: 'ready', output: 'Beats here' });
+ const updated = await svc.updateIssue(i.id, { status: 'shipped' });
+ expect(updated.status).toBe('shipped');
+ expect(updated.title).toBe('First');
+ expect(updated.stages.idea.output).toBe('Beats here');
+ });
+
+ it('deleteIssue 404s on second call', async () => {
+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'First' });
+ await svc.deleteIssue(i.id);
+ await expect(svc.deleteIssue(i.id)).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
+ });
+});
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
new file mode 100644
index 0000000000..8acc85cc94
--- /dev/null
+++ b/server/services/pipeline/series.js
@@ -0,0 +1,174 @@
+/**
+ * Pipeline — Series Service
+ *
+ * A Series is the long-lived parent record for a narrative arc (comic series,
+ * TV show, or both). It carries the shared "bible" — premise, characters,
+ * world ref, style notes — that gets injected into every Issue's stage prompts
+ * so issues stay visually and tonally consistent.
+ *
+ * Persisted to data/pipeline-series.json. Issues live in their own file
+ * (server/services/pipeline/issues.js) and reference a series by id.
+ */
+
+import { join } from 'path';
+import { randomUUID } from 'crypto';
+import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';
+
+const STATE_PATH = join(PATHS.data, 'pipeline-series.json');
+
+export const ERR_NOT_FOUND = 'PIPELINE_SERIES_NOT_FOUND';
+export const ERR_VALIDATION = 'PIPELINE_SERIES_VALIDATION';
+const makeErr = (message, code) => Object.assign(new Error(message), { code });
+
+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 WORLD_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;
+ const name = trimTo(raw.name, NAME_MAX);
+ if (!name) return null;
+ const targetFormat = TARGET_FORMATS.includes(raw.targetFormat) ? raw.targetFormat : 'comic+tv';
+ const issueCountTarget = Number.isFinite(raw.issueCountTarget)
+ ? Math.max(0, Math.min(ISSUE_COUNT_TARGET_MAX, Math.floor(raw.issueCountTarget)))
+ : 0;
+ const createdAt = isStr(raw.createdAt) ? raw.createdAt : new Date().toISOString();
+ const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;
+ return {
+ id: raw.id,
+ name,
+ logline: trimTo(raw.logline, LOGLINE_MAX),
+ premise: trimTo(raw.premise, PREMISE_MAX),
+ worldId: trimTo(raw.worldId, WORLD_ID_MAX) || null,
+ characters: sanitizeCharacters(raw.characters || []),
+ styleNotes: trimTo(raw.styleNotes, STYLE_NOTES_MAX),
+ targetFormat,
+ issueCountTarget,
+ createdAt,
+ updatedAt,
+ };
+};
+
+async function readState() {
+ await ensureDir(PATHS.data);
+ const raw = await readJSONFile(STATE_PATH, 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);
+}
+
+export async function listSeries() {
+ const { series } = await readState();
+ return [...series].sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''));
+}
+
+export async function getSeries(id) {
+ const { series } = await readState();
+ const found = series.find((s) => s.id === id);
+ if (!found) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);
+ return found;
+}
+
+export async function createSeries(input = {}) {
+ const name = trimTo(input.name, NAME_MAX);
+ if (!name) throw makeErr(`Series name is required (1..${NAME_MAX} chars)`, ERR_VALIDATION);
+ const state = await readState();
+ const now = new Date().toISOString();
+ const next = sanitizeSeries({
+ id: `ser-${randomUUID()}`,
+ name,
+ logline: input.logline || '',
+ premise: input.premise || '',
+ worldId: input.worldId || null,
+ characters: input.characters || [],
+ styleNotes: input.styleNotes || '',
+ targetFormat: input.targetFormat || 'comic+tv',
+ issueCountTarget: input.issueCountTarget || 0,
+ createdAt: now,
+ updatedAt: now,
+ });
+ state.series.push(next);
+ await writeState(state);
+ return next;
+}
+
+export async function updateSeries(id, patch = {}) {
+ const state = await readState();
+ const idx = state.series.findIndex((s) => s.id === id);
+ if (idx < 0) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);
+ const cur = state.series[idx];
+ const merged = sanitizeSeries({
+ ...cur,
+ ...('name' in patch ? { name: patch.name } : {}),
+ ...('logline' in patch ? { logline: patch.logline } : {}),
+ ...('premise' in patch ? { premise: patch.premise } : {}),
+ ...('worldId' in patch ? { worldId: patch.worldId } : {}),
+ ...('characters' in patch ? { characters: patch.characters } : {}),
+ ...('styleNotes' in patch ? { styleNotes: patch.styleNotes } : {}),
+ ...('targetFormat' in patch ? { targetFormat: patch.targetFormat } : {}),
+ ...('issueCountTarget' in patch ? { issueCountTarget: patch.issueCountTarget } : {}),
+ updatedAt: new Date().toISOString(),
+ });
+ if (!merged) throw makeErr('Invalid series payload', ERR_VALIDATION);
+ state.series[idx] = merged;
+ await writeState(state);
+ return merged;
+}
+
+export async function deleteSeries(id) {
+ const state = await readState();
+ const before = state.series.length;
+ state.series = state.series.filter((s) => s.id !== id);
+ if (state.series.length === before) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);
+ await writeState(state);
+ return { id };
+}
diff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.js
new file mode 100644
index 0000000000..66ef737c9c
--- /dev/null
+++ b/server/services/pipeline/series.test.js
@@ -0,0 +1,101 @@
+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 svc = await import('./series.js');
+
+describe('pipeline series service', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ });
+
+ it('listSeries returns [] for fresh state', async () => {
+ expect(await svc.listSeries()).toEqual([]);
+ });
+
+ it('createSeries assigns ser- prefixed id and persists the bible fields', async () => {
+ const s = await svc.createSeries({
+ name: 'Salt Run',
+ logline: 'A foundry city goes silent.',
+ premise: 'Long-form premise about a salt-mining city...',
+ worldId: 'world-123',
+ styleNotes: 'moebius linework, washed sepia',
+ targetFormat: 'comic+tv',
+ issueCountTarget: 6,
+ characters: [
+ { name: 'Lina', description: 'A young foundry surveyor.' },
+ { name: '', description: 'Skipped — no name' },
+ ],
+ });
+ expect(s.id).toMatch(/^ser-/);
+ expect(s.name).toBe('Salt Run');
+ expect(s.logline).toBe('A foundry city goes silent.');
+ expect(s.worldId).toBe('world-123');
+ expect(s.targetFormat).toBe('comic+tv');
+ expect(s.issueCountTarget).toBe(6);
+ // Empty-name character dropped; Lina gets a chr- id.
+ expect(s.characters).toHaveLength(1);
+ expect(s.characters[0].name).toBe('Lina');
+ expect(s.characters[0].id).toMatch(/^chr-/);
+ });
+
+ it('createSeries requires a non-empty name', async () => {
+ await expect(svc.createSeries({})).rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ await expect(svc.createSeries({ name: ' ' })).rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it('updateSeries merges fields without clobbering omitted ones', async () => {
+ const s = await svc.createSeries({ name: 'Salt Run', logline: 'L1', premise: 'P1', styleNotes: 'S1' });
+ const updated = await svc.updateSeries(s.id, { logline: 'L2' });
+ expect(updated.logline).toBe('L2');
+ expect(updated.premise).toBe('P1');
+ expect(updated.styleNotes).toBe('S1');
+ // ISO strings have ms precision; >= rather than > avoids flake when create
+ // and update land in the same ms tick.
+ expect(updated.updatedAt >= s.updatedAt).toBe(true);
+ });
+
+ it('updateSeries throws ERR_NOT_FOUND for unknown id', async () => {
+ await expect(svc.updateSeries('ser-nope', { name: 'x' })).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
+ });
+
+ it('deleteSeries drops the record and is idempotent only on second call', async () => {
+ const s = await svc.createSeries({ name: 'Salt Run' });
+ await svc.deleteSeries(s.id);
+ await expect(svc.deleteSeries(s.id)).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
+ expect(await svc.listSeries()).toEqual([]);
+ });
+
+ it('listSeries sorts newest updated first', async () => {
+ const a = await svc.createSeries({ name: 'A' });
+ await new Promise((r) => setTimeout(r, 5));
+ const b = await svc.createSeries({ name: 'B' });
+ const list = await svc.listSeries();
+ expect(list.map((s) => s.id)).toEqual([b.id, a.id]);
+ });
+
+ it('targetFormat falls back to comic+tv when invalid', async () => {
+ const s = await svc.createSeries({ name: 'X', targetFormat: 'nonsense' });
+ expect(s.targetFormat).toBe('comic+tv');
+ });
+
+ it('caps characters at CHARACTERS_PER_SERIES_MAX', async () => {
+ const many = Array.from({ length: svc.CHARACTERS_PER_SERIES_MAX + 10 }, (_, i) => ({ name: `c${i}` }));
+ const s = await svc.createSeries({ name: 'X', characters: many });
+ expect(s.characters).toHaveLength(svc.CHARACTERS_PER_SERIES_MAX);
+ });
+});
diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.js
new file mode 100644
index 0000000000..aea48bbf46
--- /dev/null
+++ b/server/services/pipeline/textStages.js
@@ -0,0 +1,180 @@
+/**
+ * Pipeline — Text Stage Execution
+ *
+ * Runs a single text stage (idea / prose / comicScript / tvScript) against the
+ * active LLM provider. Builds the prompt via promptService.buildPrompt — each
+ * stage has its own template in data.sample/prompts/stages/pipeline-*.md and
+ * is registered in data.sample/prompts/stage-config.json.
+ *
+ * The render context includes the series bible (logline, premise, characters,
+ * styleNotes) plus every *prior* stage's output, so downstream stages can
+ * reference upstream content with `{{stages.idea.output}}` etc.
+ *
+ * Errors bubble (per project convention — no try/catch) except at the SSE
+ * 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 { getSeries } from './series.js';
+import { getIssue, updateStage, TEXT_STAGE_IDS } from './issues.js';
+
+const STAGE_TO_TEMPLATE = Object.freeze({
+ idea: 'pipeline-idea-expansion',
+ prose: 'pipeline-prose',
+ comicScript: 'pipeline-comic-script',
+ 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.*`).
+ * Visual stages aren't included — text templates don't need rendered images.
+ */
+function buildStageContext({ series, issue, stageId, seedInput }) {
+ const stages = {};
+ for (const id of TEXT_STAGE_IDS) {
+ if (id === stageId) break; // only include stages BEFORE the current one
+ const cur = issue.stages?.[id] || {};
+ stages[id] = {
+ status: cur.status || 'empty',
+ // Prefer the user-edited input over the raw LLM output when present —
+ // matches how editors actually work the artifact.
+ content: (cur.input?.trim() || cur.output?.trim() || ''),
+ };
+ }
+ return {
+ series: {
+ name: series.name,
+ logline: series.logline,
+ premise: series.premise,
+ styleNotes: series.styleNotes,
+ worldId: series.worldId || '',
+ characters: series.characters || [],
+ },
+ issue: {
+ number: issue.number,
+ title: issue.title,
+ },
+ stages,
+ seed: (seedInput || issue.stages?.[stageId]?.input || '').trim(),
+ };
+}
+
+/**
+ * Run one text stage end-to-end:
+ * 1. Mark the stage `generating`.
+ * 2. Build the prompt via promptService.buildPrompt(<template>, ctx).
+ * 3. Call the LLM (active provider unless overridden).
+ * 4. Persist the response as `stages.<stageId>.output` with `status: ready`.
+ *
+ * Returns { issue, stage, runId }.
+ *
+ * On error, marks the stage `error` with the message and rethrows so the
+ * caller (route or autoRunner) can react.
+ */
+export async function generateStage(issueId, stageId, options = {}) {
+ if (!TEXT_STAGE_IDS.includes(stageId)) {
+ throw new Error(`generateStage: unsupported stageId "${stageId}"`);
+ }
+ const template = STAGE_TO_TEMPLATE[stageId];
+ const issue = await getIssue(issueId);
+ const series = await getSeries(issue.seriesId);
+
+ 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;
+ try {
+ ({ text, runId } = await callLLM(provider, model, prompt));
+ } catch (err) {
+ await updateStage(issueId, stageId, {
+ status: 'error',
+ errorMessage: (err?.message || String(err)).slice(0, 4000),
+ });
+ throw err;
+ }
+
+ const output = (text || '').trim();
+ const { issue: updatedIssue, stage } = await updateStage(issueId, stageId, {
+ status: output ? 'ready' : 'error',
+ output,
+ lastRunId: 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 };
+}
+
+// Export internals for tests.
+export const __testing = { buildStageContext, STAGE_TO_TEMPLATE };
diff --git a/server/services/pipeline/textStages.test.js b/server/services/pipeline/textStages.test.js
new file mode 100644
index 0000000000..ec68aba3a8
--- /dev/null
+++ b/server/services/pipeline/textStages.test.js
@@ -0,0 +1,117 @@
+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 llmCalls = [];
+
+vi.mock('../providers.js', () => ({
+ getActiveProvider: vi.fn(async () => ({
+ id: 'mock-provider',
+ name: 'Mock',
+ type: 'api',
+ defaultModel: 'mock-model',
+ })),
+ getProviderById: vi.fn(async (id) => (id === 'mock-provider' ? {
+ id, name: 'Mock', type: 'api', defaultModel: 'mock-model',
+ } : null)),
+}));
+
+vi.mock('../runner.js', () => ({
+ createRun: vi.fn(async () => ({ runId: `run-${++uuidCounter}` })),
+ // Stub executeApiRun: call onData with a canned response immediately, then
+ // onComplete with success. Mirrors what worldBuilderExpand.test.js doesn't
+ // need to do (it mocks the upstream expander), but we test the lower-level
+ // text-stage runner here.
+ executeApiRun: vi.fn(async (runId, provider, model, prompt, _cwd, _shots, onData, onComplete) => {
+ llmCalls.push({ runId, provider: provider.id, model, prompt });
+ onData('## Beat sheet\n1. Setup ...\n');
+ onComplete({ success: true });
+ }),
+ executeCliRun: vi.fn(),
+}));
+
+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)}`),
+}));
+
+const issuesSvc = await import('./issues.js');
+const seriesSvc = await import('./series.js');
+const textStages = await import('./textStages.js');
+
+describe('pipeline text stage generator', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ llmCalls.length = 0;
+ vi.clearAllMocks();
+ });
+
+ async function seed() {
+ const series = await seriesSvc.createSeries({
+ name: 'Salt Run',
+ logline: 'A foundry city goes silent.',
+ premise: 'Salt-mining city on a dying tideflat.',
+ styleNotes: 'moebius linework',
+ characters: [{ name: 'Lina', description: 'foundry surveyor' }],
+ });
+ const issue = await issuesSvc.createIssue({ seriesId: series.id, title: 'The Hush' });
+ return { series, issue };
+ }
+
+ it('generateStage moves a stage idle → ready and persists output + runId', async () => {
+ const { issue } = await seed();
+ const result = await textStages.generateStage(issue.id, 'idea', { seedInput: 'foundry mystery' });
+ expect(result.stage.status).toBe('ready');
+ expect(result.stage.output).toContain('Beat sheet');
+ expect(result.stage.lastRunId).toMatch(/^run-/);
+ expect(llmCalls).toHaveLength(1);
+ expect(llmCalls[0].prompt).toContain('RENDERED:pipeline-idea-expansion');
+ });
+
+ it('stage prompt context includes only PRIOR stages', async () => {
+ const { issue } = await seed();
+ // Fill idea + prose, then run comicScript. Context should include both
+ // earlier stages but NOT tvScript (parallel) and NOT comicScript itself.
+ await issuesSvc.updateStage(issue.id, 'idea', { status: 'ready', output: 'BEATS' });
+ await issuesSvc.updateStage(issue.id, 'prose', { status: 'ready', output: 'PROSE' });
+ await issuesSvc.updateStage(issue.id, 'tvScript', { status: 'ready', output: 'TVS' });
+ await textStages.generateStage(issue.id, 'comicScript');
+ const promptArg = llmCalls[0].prompt;
+ expect(promptArg).toContain('idea');
+ expect(promptArg).toContain('prose');
+ // Context only carries stages BEFORE comicScript in TEXT_STAGE_IDS order;
+ // tvScript comes AFTER comicScript and must not appear.
+ expect(promptArg).not.toContain('TVS');
+ });
+
+ it('marks stage as error and rethrows when LLM rejects', async () => {
+ const { issue } = await seed();
+ const runner = await import('../runner.js');
+ runner.executeApiRun.mockImplementationOnce(async (runId, _p, _m, _prompt, _cwd, _shots, _onData, onComplete) => {
+ onComplete({ error: 'simulated provider 500' });
+ });
+ await expect(textStages.generateStage(issue.id, 'idea')).rejects.toThrow(/simulated provider 500/);
+ const after = await issuesSvc.getIssue(issue.id);
+ expect(after.stages.idea.status).toBe('error');
+ expect(after.stages.idea.errorMessage).toContain('simulated provider 500');
+ });
+
+ it('rejects unsupported stage ids', async () => {
+ const { issue } = await seed();
+ await expect(textStages.generateStage(issue.id, 'comicPages')).rejects.toThrow(/unsupported stageId/);
+ });
+});
diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.js
new file mode 100644
index 0000000000..691d09d072
--- /dev/null
+++ b/server/services/pipeline/visualStages.js
@@ -0,0 +1,95 @@
+/**
+ * Pipeline — Visual stage handoff helpers
+ *
+ * Thin wrappers that enqueue image-gen jobs on behalf of the Pipeline's
+ * comicPages and storyboards stages. The route layer is responsible for
+ * persisting the returned jobIds into the issue's stage record — this module
+ * just owns the "build the right params, hand to mediaJobQueue" mechanic so
+ * the pipeline doesn't have to duplicate Image-Gen's mode-resolution code.
+ *
+ * MVP scope: image jobs only. Scene video / episode-video stitching is
+ * deferred — the storyboards and episodeVideo stages currently expose
+ * read/write of their structured fields but don't yet drive the Creative
+ * Director scene runner. See PLAN.md "Pipeline — Deferred" for the follow-up.
+ */
+
+import { enqueueJob } from '../mediaJobQueue/index.js';
+import { getSettings } from '../settings.js';
+import { getSeries } from './series.js';
+import { getIssue, VISUAL_STAGE_IDS } from './issues.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(', ');
+}
+
+/**
+ * Enqueue one image render for a pipeline issue's visual stage. The caller
+ * is responsible for recording the returned jobId on the issue's stage
+ * artifact list (e.g. stages.comicPages.pages[i].panels[j].imageJobId).
+ *
+ * `options.description` — required, the panel/scene subject text.
+ * `options.modelId`, `options.width`, `options.height`, `options.steps`,
+ * `options.guidance`, `options.negativePrompt` — optional overrides.
+ *
+ * Returns { jobId, mode, prompt }.
+ */
+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 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');
+
+ const prompt = composeVisualPrompt({
+ series,
+ description: options.description,
+ extraStyle: options.extraStyle || '',
+ });
+ if (!prompt) throw new Error('enqueueVisualImage: prompt is empty (no description, no style)');
+
+ const baseParams = {
+ prompt,
+ negativePrompt: options.negativePrompt || undefined,
+ width: options.width,
+ height: options.height,
+ steps: options.steps,
+ guidance: options.guidance ?? options.cfgScale,
+ cfgScale: options.cfgScale,
+ };
+
+ const owner = `pipeline:${issueId}:${stageId}`;
+
+ if (mode === 'codex') {
+ const c = settings.imageGen?.codex || {};
+ const { jobId } = enqueueJob({
+ kind: 'image',
+ params: { mode: 'codex', codexPath: c.codexPath, model: c.model, ...baseParams },
+ owner,
+ });
+ console.log(`🎬 Pipeline visual — issue=${issueId.slice(0, 8)} stage=${stageId} mode=codex jobId=${jobId.slice(0, 8)}`);
+ return { jobId, mode, prompt };
+ }
+
+ // mode === 'local'
+ const pythonPath = settings.imageGen?.local?.pythonPath || null;
+ const { jobId } = enqueueJob({
+ kind: 'image',
+ params: { pythonPath, modelId: options.modelId, ...baseParams },
+ owner,
+ });
+ console.log(`🎬 Pipeline visual — issue=${issueId.slice(0, 8)} stage=${stageId} mode=local jobId=${jobId.slice(0, 8)}`);
+ return { jobId, mode, prompt };
+}