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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(pipeline): rename tvScript→teleplay end-to-end, persist comic-page filenames past 24h archive TTL
[._.]/ Adam Eivy96bc7f17749a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 4e526c029d..1b6082f0d6 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,7 +2,28 @@## Added-- **Sharing v1.4 — universe shares include the collection + new peer images flow in.**+- **Comic Pages — rendered filename persisted on the record (survives queue TTL).**+ Comic-page records previously stored only `imageJobId`. After the+ mediaJobQueue's 24-hour archive TTL, the UI could no longer resolve+ a filename to render — even though the PNG was still on disk — and+ `MediaJobThumb` showed a spinner forever. New+ `server/services/pipeline/comicPagesFilenameHook.js` subscribes to+ `mediaJobEvents('completed')` and stamps `filename` onto+ `stages.comicPages.cover` / `.pages[i]` at completion time+ (gated on a still-matching `imageJobId` so a re-render between+ enqueue and completion doesn't overwrite the newer filename with the+ older one). New shared owner builder/parser+ (`server/services/pipeline/owners.js`) replaces inline owner-string+ templates in `visualStages.js` and the hook's regex so producers+ and consumers can't drift. `MediaJobThumb` short-circuits on+ `fallbackFilename`: when the parent has the saved filename, the+ component skips the live `getMediaJob` fetch and socket subscription+ entirely (no more 404s on completed-and-pruned jobs). Re-render+ routes (`comicPages/cover/render`, `comicPages/pages/:i/render`)+ clear `filename: null` alongside setting the new `imageJobId` so+ the stale image doesn't flash while a fresh render is in flight.++Sharing a universe now bundles the linked media collection ("Universe:<name>" — the bucket of images the user generated via Universe Builder),so recipients see those images alongside the universe instead of an@@ -636,7 +657,33 @@## Changed-- **Data migration scripts for bringing old machines forward.** Two new+- **Pipeline stage `tvScript` renamed to `teleplay` end-to-end.** Full+ rename of the internal stage id, not just the visible label. Touches+ server schemas (`TEXT_STAGE_IDS`, `STAGE_IDS`), routes+ (`stages/teleplay/generate`, `SOURCE_KIND.TELEPLAY`), the auto-runner+ fan-out, scene extractor source kinds, client services+ (`PIPELINE_TEXT_STAGES`, stage labels, page imports), the+ `TeleplayStage.jsx` component (renamed from `TVScriptStage.jsx`), and+ the prompt file+ (`data.sample/prompts/stages/pipeline-teleplay.md`,+ installed copy renamed too; hash table keys in `setup-data.js`+ updated; `stage-config.json` key renamed). All 32 existing pipeline+ issues had their `stages.tvScript` records renamed to+ `stages.teleplay` in `data/pipeline-issues.json` — single-instance+ app, no migration path needed. Voice agent keeps both spoken aliases+ (`tv script`, `teleplay`) but both now resolve to the `teleplay`+ stage id. Historical references in `DONE.md`, prior changelog+ versions, `data/migrations/003-*.js`, and `data/runs/*/metadata.json`+ left as-is (record of past work, not current state).++- **Sidebar nav: "Pipeline" → "Series".** Label change only — URLs,+ files, server routes, and API endpoints all retain the `pipeline`+ namespace because the inner Series record already owns the word+ "Series" and `/series/series/:id` would be ugly. Updates the visible+ sidebar entry (`Layout.jsx`), nav-manifest label (also adds `series`+ as an alias for ⌘K + voice), and the Series-index page H1.++scripts under `server/scripts/`:- `migrateWorldToUniverse.js` — renames `data/world-builder.json` →`data/universe-builder.json`, the top-level `worlds[]` → `universes[]`@@ -822,7 +869,27 @@## Fixed-- **Pipeline stage prompts — length profile variables reach existing installs.**+- **`updateStageWithLatest` short-circuits on empty-patch returns.** A+ computeFn returning `{}` (the "I decided not to write" signal — e.g.+ a stale media-job completion landing against a re-rendered page) no+ longer writes the issue file or fires `emitRecordUpdated('series',+ ...)`. Previously every such no-op merged `updatedAt` and triggered+ the share-bucket subscription's debounced re-export of the entire+ series — multiplied by every duplicate image-gen `completed` event+ that arrived for an old jobId after the user re-ran a render. Fix+ benefits every other caller that adopts the empty-patch convention.++- **`severity: 'warning'` server errors stop surfacing as console errors.**+ Routes can flag expected high-volume 404s (e.g. speculative+ `GET /api/media-jobs/:id` lookups for jobs past the queue's 24h+ archive TTL) with `severity: 'warning'` — the original intent per+ `mediaJobs.js`'s comment. Now honored on both ends: client+ `useErrorNotifications.handleError` returns early for warnings+ (no toast, no `console.error`), and the server `asyncHandler`'s+ log branch suppresses the `❌ Route error: ...` line for the same.+ The network-tab 404 is the only remaining signal.++Running `npm run migrations` now auto-updates the five pipeline stage prompttemplates (`pipeline-idea-expansion.md`, `pipeline-prose.md`,`pipeline-comic-script.md`, `pipeline-tv-script.md`,diff --git a/PLAN.md b/PLAN.mdindex ee66718668..b507c7dad0 100644--- a/PLAN.md+++ b/PLAN.md@@ -65,7 +65,7 @@ Captured 2026-05-13 while landing layer-1 (prior episodes in season prompt), lay- [ ] **Setting palette/era/weather plumbed to visual stages.** `storyBible.js` setting shape carries `palette`, `era`, `weather`, `recurringDetails`, but `composeVisualPrompt` / `composeComicPagePrompt` only consult `description`. The fields exist for image renderers — wire `matchSceneSetting`'s match through into a "Setting: <era> <palette> <recurring>" prefix on the rendered prompt.- [ ] **World-entity name validation in text stages.** Arc-verify checks world drift (factions/characters/locations the arc names that don't exist in the World Builder world), but per-issue text stages (idea → prose → script) don't reference world entities at all. New world entities introduced in volumes 2/3 of a series aren't surfaced to the prose LLM. Add a `worldEntitiesSummary` prompt var to the prose stage, similar to how arc-overview gets `worldCategoriesText`.- [ ] **Character voice / speech-pattern field.** Current character shape has `personality` + `background` but no dedicated `voice` / `speech patterns` field. Prose and script generation can't carry voice consistency across issues without an authored anchor. Either add a `voice` field to the bible schema (and bibleExtractor stage prompt) or document that voice should land in `personality`.-- [ ] **Extraction after comicScript / tvScript stages.** Layer-2 extraction now runs after prose. Scripts derive FROM prose so most new characters should already be in the bible, but minor characters introduced only at script time (named extras, throwaway villains) still slip through. Decide whether to also run extraction post-script or accept the gap.+- [ ] **Extraction after comicScript / teleplay stages.** Layer-2 extraction now runs after prose. Scripts derive FROM prose so most new characters should already be in the bible, but minor characters introduced only at script time (named extras, throwaway villains) still slip through. Decide whether to also run extraction post-script or accept the gap.- [ ] **Solidify character descriptions before visual render.** User asked: as the series progresses, characters accumulate descriptions across multiple extractions but may still have gaps. Add a "Solidify characters" action in the bible sidebar that runs an LLM pass synthesizing one canonical `physicalDescription` per character from all accumulated `firstAppearance` + `evidence` + existing text. Useful before kicking off the visual render passes for an issue.- [ ] **Resolve-issues inherits verify gaps.** Verify and resolve share `buildVerifyContext` so the new episode-synopsis context is already wired into both. But double-check the resolve LLM prompt instructs it to USE episode synopses when patching the arc — otherwise it'll just rewrite season-level synopses and leave per-episode contradictions intact.diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex da3191de2f..7ac7ee1024 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -195,7 +195,7 @@ const navItems = [defaultTo: '/media',children: [{ to: '/media', label: 'Media Gen', icon: Layers },- { to: '/pipeline', label: 'Pipeline', icon: WorkflowIcon, dynamic: 'pipelineSeries' },+ { to: '/pipeline', label: 'Series', icon: WorkflowIcon, dynamic: 'pipelineSeries' },{ to: '/sharing', label: 'Sharing', icon: Share2 },{ to: '/universe-builder', label: 'Universe Builder', icon: Globe },{ to: '/writers-room', label: 'Writers Room', icon: NotebookPen }diff --git a/client/src/components/pipeline/MediaJobThumb.jsx b/client/src/components/pipeline/MediaJobThumb.jsxindex e968c4176c..f1e6ed8670 100644--- a/client/src/components/pipeline/MediaJobThumb.jsx+++ b/client/src/components/pipeline/MediaJobThumb.jsx@@ -19,20 +19,34 @@ import useMediaJobProgress from '../../hooks/useMediaJobProgress';export default function MediaJobThumb({jobId, label = 'Render', size = 'sm', kind = 'image',onPreview = null, onStatus = null, onFilename = null,+ // Saved filename on the parent record (e.g. comicPages page.filename).+ // When the parent already has the rendered filename, the job is done+ // by definition (the comic-pages filename hook only stamps on completion)+ // — skip the live media-job lookup and subscription entirely.+ fallbackFilename = null,}) {+ // Short-circuit live progress when the parent has the final filename.+ // Re-renders clear `filename` server-side, so a truthy fallbackFilename+ // is an authoritative "this render is complete" signal. Pass null jobId+ // to the hook so it skips the fetch + socket subscriptions; the hook+ // tolerates null cleanly. Image-only — video fallback would also need+ // a poster, so keep the live subscription path for video.+ const hasStaticFallback = !!fallbackFilename && kind === 'image';+ const liveJobId = hasStaticFallback ? null : jobId;const { status, progress, step, totalSteps, currentImage, filename, error } =- useMediaJobProgress(jobId, { kind });- // Local missing-media state. Reset when jobId changes so a fresh render- // doesn't inherit the prior render's failure flag.+ useMediaJobProgress(liveJobId, { kind });const [missing, setMissing] = useState(false);const [attempt, setAttempt] = useState(0);useEffect(() => { setMissing(false); setAttempt(0); }, [jobId]);+ const effectiveStatus = hasStaticFallback ? 'completed' : status;+ const effectiveFilename = hasStaticFallback ? fallbackFilename : filename;+// Forward subscription state to the parent so callers (e.g. PageRow's// disable-while-rendering logic, lightbox nav builders) don't need a// duplicate useMediaJobProgress subscription on the same jobId.- useEffect(() => { if (onStatus) onStatus(status); }, [status, onStatus]);- useEffect(() => { if (onFilename && filename) onFilename(filename); }, [filename, onFilename]);+ useEffect(() => { if (onStatus) onStatus(effectiveStatus); }, [effectiveStatus, onStatus]);+ useEffect(() => { if (onFilename && effectiveFilename) onFilename(effectiveFilename); }, [effectiveFilename, onFilename]);if (!jobId) return null;@@ -67,7 +81,7 @@ export default function MediaJobThumb({const cacheBust = attempt > 0 ? `?retry=${attempt}` : '';- if (status === 'completed' && kind === 'video') {+ if (effectiveStatus === 'completed' && kind === 'video') {return (<videokey={attempt}@@ -84,11 +98,11 @@ export default function MediaJobThumb({/>);}- if (status === 'completed' && filename) {+ if (effectiveStatus === 'completed' && effectiveFilename) {const imgEl = (<imgkey={attempt}- src={`/data/images/${filename}${cacheBust}`}+ src={`/data/images/${effectiveFilename}${cacheBust}`}alt={label}onError={() => setMissing(true)}className={imgFit}@@ -100,7 +114,7 @@ export default function MediaJobThumb({return (<buttontype="button"- onClick={() => onPreview(filename)}+ onClick={() => onPreview(effectiveFilename)}title="Open preview"className={`${wrapperClass} cursor-zoom-in p-0`}>@@ -110,7 +124,7 @@ export default function MediaJobThumb({}return (<a- href={`/data/images/${filename}${cacheBust}`}+ href={`/data/images/${effectiveFilename}${cacheBust}`}target="_blank"rel="noopener noreferrer"title="Open full image in a new tab"diff --git a/client/src/components/pipeline/stages/ComicPagesStage.jsx b/client/src/components/pipeline/stages/ComicPagesStage.jsxindex bcb150268b..39be0c07b0 100644--- a/client/src/components/pipeline/stages/ComicPagesStage.jsx+++ b/client/src/components/pipeline/stages/ComicPagesStage.jsx@@ -229,7 +229,7 @@ export default function ComicPagesStage({ issue, onStageUpdate, actionsGated = f</button>{page.imageJobId ? (<div className="flex items-center gap-2">- <MediaJobThumb jobId={page.imageJobId} label={`Page ${pi + 1}`} size="md" />+ <MediaJobThumb jobId={page.imageJobId} label={`Page ${pi + 1}`} size="md" fallbackFilename={page.filename || null} /><span className="text-[10px] text-gray-500 font-mono break-all" title="Last page render job">{page.imageJobId.slice(0, 8)}</span>diff --git a/client/src/components/pipeline/stages/ComicScriptStage.jsx b/client/src/components/pipeline/stages/ComicScriptStage.jsxindex 02feba1ad9..840178cfb6 100644--- a/client/src/components/pipeline/stages/ComicScriptStage.jsx+++ b/client/src/components/pipeline/stages/ComicScriptStage.jsx@@ -335,7 +335,7 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions</button>{cover.imageJobId ? (<div className="flex items-center gap-2">- <MediaJobThumb jobId={cover.imageJobId} label="Cover" size="md" onStatus={setCoverJobStatus} />+ <MediaJobThumb jobId={cover.imageJobId} label="Cover" size="md" onStatus={setCoverJobStatus} fallbackFilename={cover.filename || null} /><span className="text-[10px] text-gray-500 font-mono break-all" title="Last cover render job">{cover.imageJobId.slice(0, 8)}</span>@@ -520,6 +520,7 @@ function PageRow({ issue, pageIndex, page, renderOpts = {}, onStageUpdate, onPreonPreview={(filename) => onPreview?.(pageIndex, filename, page)}onStatus={setJobStatus}onFilename={onJobFilename}+ fallbackFilename={page.filename || null}/>) : (<span className="text-xs text-gray-500 italic">No render yet — click <em>Render</em>.</span>diff --git a/client/src/components/pipeline/stages/ProseStage.jsx b/client/src/components/pipeline/stages/ProseStage.jsxindex a4cd551820..c97fd431cd 100644--- a/client/src/components/pipeline/stages/ProseStage.jsx+++ b/client/src/components/pipeline/stages/ProseStage.jsx@@ -9,7 +9,7 @@ export default function ProseStage({ issue, onStageUpdate }) {stageId="prose"onStageUpdate={onStageUpdate}generateLabel="Draft prose"- outputPlaceholder="An 800–1500 word short-story draft for this issue. Will be lightly structured with `## Scene N — Slugline` H2 markers so the comic and TV script stages have stable anchors."+ 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 teleplay stages have stable anchors."/>);}diff --git a/client/src/components/pipeline/stages/StoryboardsStage.jsx b/client/src/components/pipeline/stages/StoryboardsStage.jsxindex 1b7eccffe0..440d52235d 100644--- a/client/src/components/pipeline/stages/StoryboardsStage.jsx+++ b/client/src/components/pipeline/stages/StoryboardsStage.jsx@@ -1,5 +1,5 @@/**- * Storyboards stage — one storyboard image per TV-script scene, plus+ * Storyboards stage — one storyboard image per teleplay scene, plus* single-scene video preview and AI-driven prompt refinement.** Each scene row exposes four actions:@@ -12,7 +12,7 @@* stitch in `episodeVideo.js`.* - **Trash** — removes the scene from the list.*- * Auto-fill: "From TV script" / "From prose" buttons run the scene+ * Auto-fill: "From teleplay" / "From prose" buttons run the scene* extractor against the corresponding text stage and replace the list.*/@@ -46,7 +46,7 @@ export default function StoryboardsStage({ issue, onStageUpdate, actionsGated =if (armTimerRef.current) clearTimeout(armTimerRef.current);}, []);- const tvScriptReady = !!(issue.stages?.tvScript?.output || '').trim();+ const teleplayReady = !!(issue.stages?.teleplay?.output || '').trim();const proseReady = !!(issue.stages?.prose?.output || '').trim();// Any non-null, non-arm value means an extract POST is in flight — both// buttons must lock out concurrent submits so racing requests can't@@ -190,21 +190,21 @@ export default function StoryboardsStage({ issue, onStageUpdate, actionsGated =<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. Stitch the final episode in the Episode Video stage once the storyboards are ready.+ One image per scene, fed by the Teleplay. Use sluglines to keep parity with the Teleplay. Stitch the final episode in the Episode Video stage once the storyboards are ready.</p></div><div className="flex items-center gap-2 flex-wrap"><buttontype="button"- onClick={() => onExtractClick('tvScript')}- disabled={!tvScriptReady || extractInFlight}- title={tvScriptReady ? 'Parse the teleplay sluglines into structured scenes' : 'Generate the TV script first'}+ onClick={() => onExtractClick('teleplay')}+ disabled={!teleplayReady || extractInFlight}+ title={teleplayReady ? 'Parse the Teleplay sluglines into structured scenes' : 'Generate the Teleplay first'}className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-card border border-port-border text-white text-sm hover:border-port-accent/50 disabled:opacity-40 disabled:cursor-not-allowed">- {extractingFrom === 'tvScript'+ {extractingFrom === 'teleplay'? <Loader2 size={14} className="animate-spin" />: <Wand2 size={14} />}- {extractingFrom === 'arm:tvScript' ? 'Click again to replace' : 'From TV script'}+ {extractingFrom === 'arm:teleplay' ? 'Click again to replace' : 'From Teleplay'}</button><buttontype="button"diff --git a/client/src/components/pipeline/stages/TVScriptStage.jsx b/client/src/components/pipeline/stages/TeleplayStage.jsxsimilarity index 81%rename from client/src/components/pipeline/stages/TVScriptStage.jsxrename to client/src/components/pipeline/stages/TeleplayStage.jsxindex 2d7420bc6a..942912bd40 100644--- a/client/src/components/pipeline/stages/TVScriptStage.jsx+++ b/client/src/components/pipeline/stages/TeleplayStage.jsx@@ -1,10 +1,10 @@import TextStagePanel from './TextStagePanel';-export default function TVScriptStage(props) {+export default function TeleplayStage(props) {return (<TextStagePanel{...props}- stageId="tvScript"+ stageId="teleplay"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.jsxindex 53014ee1a4..e8621b7e18 100644--- a/client/src/components/pipeline/stages/TextStagePanel.jsx+++ b/client/src/components/pipeline/stages/TextStagePanel.jsx@@ -1,5 +1,5 @@/**- * Shared editor for the four text stages (idea, prose, comicScript, tvScript).+ * Shared editor for the four text stages (idea, prose, comicScript, teleplay).* 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.diff --git a/client/src/hooks/useErrorNotifications.js b/client/src/hooks/useErrorNotifications.jsindex d673dfc287..a65451a0d8 100644--- a/client/src/hooks/useErrorNotifications.js+++ b/client/src/hooks/useErrorNotifications.js@@ -20,6 +20,11 @@ export function useErrorNotifications() {socket.emit('errors:subscribe');const handleError = (error) => {+ // `severity: 'warning'` routes (e.g. speculative GET /api/media-jobs/:id+ // 404s for jobs past the 24h archive TTL) opt out of toast + console+ // surfacing entirely — the network-tab 404 is sufficient signal.+ if (error.severity === 'warning') return;+if (error.code === 'PLATFORM_UNAVAILABLE') {toast(error.message, { duration: 5000, icon: '⚠️' });console.warn(`[${error.code}] ${error.message}`, error.context);diff --git a/client/src/hooks/useMediaJobProgress.js b/client/src/hooks/useMediaJobProgress.jsindex cdfa2ce83b..ee48a5102b 100644--- a/client/src/hooks/useMediaJobProgress.js+++ b/client/src/hooks/useMediaJobProgress.js@@ -19,17 +19,19 @@ import { getMediaJob } from '../services/apiMediaJobs';* back to a page mid-render picks up the in-flight job's snapshot* instead of showing an empty preview until the next event lands.*/+const INITIAL_STATE = Object.freeze({+ status: 'unknown',+ progress: 0,+ step: 0,+ totalSteps: null,+ currentImage: null,+ filename: null,+ path: null,+ error: null,+});+export default function useMediaJobProgress(jobId, { kind = 'image' } = {}) {- const [state, setState] = useState(() => ({- status: 'unknown',- progress: 0,- step: 0,- totalSteps: null,- currentImage: null,- filename: null,- path: null,- error: null,- }));+ const [state, setState] = useState(INITIAL_STATE);// Track mount so the initial fetch's setState doesn't fire after unmount// (the panel could be removed while the GET is in flight).//@@ -49,10 +51,7 @@ export default function useMediaJobProgress(jobId, { kind = 'image' } = {}) {// Reset state on every jobId change so the previous job's filename /// currentImage doesn't briefly leak into the new job's render window// (between the listener attach and the new fetch resolving).- setState({- status: 'unknown', progress: 0, step: 0, totalSteps: null,- currentImage: null, filename: null, path: null, error: null,- });+ setState(INITIAL_STATE);if (!jobId) return undefined;// Hydrate from the server. The job may already be completed (the user@@ -69,7 +68,9 @@ export default function useMediaJobProgress(jobId, { kind = 'image' } = {}) {error: job.error || prev.error,}));}).catch(() => {- // 404 just means the job archive expired — keep `status: unknown`.+ // 404 (job past 24h archive TTL) and any other failure stay silent;+ // MediaJobThumb's `fallbackFilename` path bypasses this fetch entirely+ // when the parent already has the completed render's filename.});const evtPrefix = kind === 'video' ? 'video-gen' : 'image-gen';diff --git a/client/src/pages/Pipeline.jsx b/client/src/pages/Pipeline.jsxindex 599155c13f..09ea31aff2 100644--- a/client/src/pages/Pipeline.jsx+++ b/client/src/pages/Pipeline.jsx@@ -128,7 +128,7 @@ export default function Pipeline() {<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>+ <h1 className="text-2xl font-bold text-white">Series</h1></div><buttontype="button"@@ -143,7 +143,7 @@ export default function Pipeline() {<p className="text-sm text-gray-400 mb-6">Each series carries a shared bible — logline, premise, characters, style, optional World — thatevery 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.+ comic script + teleplay (text), and hands off to image gen / Creative Director for the visual stages.</p>{showForm && (diff --git a/client/src/pages/PipelineIssue.jsx b/client/src/pages/PipelineIssue.jsxindex cd48ed2abc..fa4fc4045d 100644--- a/client/src/pages/PipelineIssue.jsx+++ b/client/src/pages/PipelineIssue.jsx@@ -3,7 +3,7 @@** 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.+ * + teleplay) and streams progress via SSE.*/import { useEffect, useState, useMemo } from 'react';@@ -24,7 +24,7 @@ import IdeaStage from '../components/pipeline/stages/IdeaStage';import ProseStage from '../components/pipeline/stages/ProseStage';import NounsStage from '../components/pipeline/stages/NounsStage';import ComicScriptStage from '../components/pipeline/stages/ComicScriptStage';-import TVScriptStage from '../components/pipeline/stages/TVScriptStage';+import TeleplayStage from '../components/pipeline/stages/TeleplayStage';import ComicPagesStage from '../components/pipeline/stages/ComicPagesStage';import StoryboardsStage from '../components/pipeline/stages/StoryboardsStage';import EpisodeVideoStage from '../components/pipeline/stages/EpisodeVideoStage';@@ -44,7 +44,7 @@ const STAGE_ICONS = {prose: BookOpen,nouns: Users,comicScript: FileText,- tvScript: FilmIcon,+ teleplay: FilmIcon,comicPages: LayoutGrid,storyboards: ImageIcon,episodeVideo: Clapperboard,@@ -55,7 +55,7 @@ const STAGE_COMPONENTS = {prose: ProseStage,nouns: NounsStage,comicScript: ComicScriptStage,- tvScript: TVScriptStage,+ teleplay: TeleplayStage,comicPages: ComicPagesStage,storyboards: StoryboardsStage,episodeVideo: EpisodeVideoStage,@@ -244,7 +244,7 @@ export default function PipelineIssue() {onClick={() => handleAutoRun({})}disabled={autoRunStarting || autoRunActive || lengthProfileSaving || genConfigSaving}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={lengthProfileSaving ? 'Saving length profile…' : genConfigSaving ? 'Saving visual settings…' : 'Run idea → prose → (comic script + TV script) end to end'}+ title={lengthProfileSaving ? 'Saving length profile…' : genConfigSaving ? 'Saving visual settings…' : 'Run idea → prose → (comic script + teleplay) end to end'}>{autoRunStarting || autoRunActive ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}Auto-run textdiff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex a9125bffdf..9506988458 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -6,7 +6,7 @@ import { request } from './apiCore.js';// generic image gen API). It appears in PIPELINE_TAB_STAGES so it gets a tab// between Prose and Comic Pages, but it's NOT in server TEXT_STAGE_IDS — so// auto-run text chain skips it and POST /stages/nouns/generate would 400.-export const PIPELINE_TEXT_STAGES = Object.freeze(['idea', 'prose', 'comicScript', 'tvScript']);+export const PIPELINE_TEXT_STAGES = Object.freeze(['idea', 'prose', 'comicScript', 'teleplay']);export const PIPELINE_VISUAL_STAGES = Object.freeze(['comicPages', 'storyboards', 'episodeVideo']);export const PIPELINE_UI_STAGES = Object.freeze(['nouns']);export const PIPELINE_STAGES = Object.freeze([...PIPELINE_TEXT_STAGES, ...PIPELINE_VISUAL_STAGES, ...PIPELINE_UI_STAGES]);@@ -15,9 +15,9 @@ export const PIPELINE_STAGES = Object.freeze([...PIPELINE_TEXT_STAGES, ...PIPELI// folded into the Comic Script tab (one merged page-by-page editor) — the// data still flows through the comicPages routes, the tab is just hidden.// `nouns` is inserted between Prose and Comic Pages so the workflow reads-// Idea → Prose → Nouns → Comic → TV Script → Storyboards → Episode Video.+// Idea → Prose → Nouns → Comic → Teleplay → Storyboards → Episode Video.export const PIPELINE_TAB_STAGES = Object.freeze([- 'idea', 'prose', 'nouns', 'comicScript', 'tvScript', 'storyboards', 'episodeVideo',+ 'idea', 'prose', 'nouns', 'comicScript', 'teleplay', 'storyboards', 'episodeVideo',]);export const PIPELINE_STAGE_LABELS = Object.freeze({@@ -27,7 +27,7 @@ export const PIPELINE_STAGE_LABELS = Object.freeze({// `comicScript` stage now owns the merged Comic Pages editor — the// standalone Comic Pages tab is hidden via PIPELINE_TAB_STAGES below.comicScript: 'Comic',- tvScript: 'TV Script',+ teleplay: 'Teleplay',comicPages: 'Comic',storyboards: 'Storyboards',episodeVideo: 'Video',@@ -124,7 +124,7 @@ export const generatePipelineVisualImage = (issueId, stageId, opts) =>});// Auto-fill the storyboards stage's scenes[] from the issue's prose or-// tvScript text stage. `from` defaults server-side to 'tvScript'. Pass+// teleplay text stage. `from` defaults server-side to 'teleplay'. Pass// `force: true` to replace existing hand-curated scenes.export const extractPipelineStoryboardScenes = (issueId, { from, providerOverride, force } = {}) =>request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/storyboards/extract-scenes`, {diff --git a/data.sample/prompts/stage-config.json b/data.sample/prompts/stage-config.jsonindex 0e95c7dd31..21c26a976b 100644--- a/data.sample/prompts/stage-config.json+++ b/data.sample/prompts/stage-config.json@@ -207,7 +207,7 @@"returnsJson": false,"variables": []},- "pipeline-tv-script": {+ "pipeline-teleplay": {"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",diff --git a/data.sample/prompts/stages/pipeline-tv-script.md b/data.sample/prompts/stages/pipeline-teleplay.mdsimilarity index 100%rename from data.sample/prompts/stages/pipeline-tv-script.mdrename to data.sample/prompts/stages/pipeline-teleplay.mddiff --git a/scripts/setup-data.js b/scripts/setup-data.jsindex 7021ecee1a..819ab6598e 100644--- a/scripts/setup-data.js+++ b/scripts/setup-data.js@@ -132,14 +132,14 @@ const PIPELINE_LENGTH_OLD_MD5 = {'pipeline-idea-expansion.md': 'aee25112b2c596f643b17c559b772c22','pipeline-prose.md': 'bfea5aeeb471aae9749baee765b473a7','pipeline-comic-script.md': '40e5fdc1a1e68a7419b7dad936366c1a',- 'pipeline-tv-script.md': '3f6fecc25573ed054b47db392250034a',+ 'pipeline-teleplay.md': '3f6fecc25573ed054b47db392250034a','pipeline-season-episodes.md':'6e349ad26bed8a0ccb042571f03f03eb',};const PIPELINE_LENGTH_NEW_MD5 = {'pipeline-idea-expansion.md': '41facefbc0c0549d456bef9111f95ab9','pipeline-prose.md': '30ac30ec2b9d3e2a9eb869c181732cc6','pipeline-comic-script.md': 'beab031951859ca13579cdb9c4dbe769',- 'pipeline-tv-script.md': '376f779f4687b598f1c92ca4e770fd5a',+ 'pipeline-teleplay.md': '376f779f4687b598f1c92ca4e770fd5a','pipeline-season-episodes.md':'c4928e2a5f833358116b29d2d669888d',};const PIPELINE_LENGTH_PROMPTS = Object.keys(PIPELINE_LENGTH_OLD_MD5);diff --git a/server/index.js b/server/index.jsindex 63bc47f724..08bc146ea9 100644--- a/server/index.js+++ b/server/index.js@@ -89,6 +89,7 @@ import creativeDirectorRoutes from './routes/creativeDirector.js';import writersRoomRoutes from './routes/writersRoom.js';import universeBuilderRoutes from './routes/universeBuilder.js';import { initUniverseBuilderCollectionHook } from './services/universeBuilderCollectionHook.js';+import { initComicPagesFilenameHook } from './services/pipeline/comicPagesFilenameHook.js';import pipelineRoutes from './routes/pipeline.js';import { initMediaJobQueue } from './services/mediaJobQueue/index.js';import { recoverInFlightProjects } from './services/creativeDirector/recovery.js';@@ -508,6 +509,10 @@ ensureSelf()// Universe Builder needs the media job queue running before it can listen// for `completed` events — so initialize the hook here.initUniverseBuilderCollectionHook();+ // Pipeline comic-pages filename hook also subscribes to media-job+ // completion — stamps `filename` onto cover/page records so the UI can+ // still render them after the 24h media-job archive TTL elapses.+ initComicPagesFilenameHook();}).then(() => {// Sharing: attach chokidar watchers to every registered share bucket sodiff --git a/server/lib/errorHandler.js b/server/lib/errorHandler.jsindex 5c749297ab..0ed688defe 100644--- a/server/lib/errorHandler.js+++ b/server/lib/errorHandler.js@@ -50,6 +50,9 @@ export function asyncHandler(fn) {const logMsg = `❌ Route error: ${error.message}`;if (error.code === 'PLATFORM_UNAVAILABLE') {console.warn(`⚠️ Platform unavailable: ${error.message}`);+ } else if (error.severity === 'warning') {+ // Expected high-volume 404s (e.g. speculative media-job archive+ // lookups) — already classified as benign; don't pollute server logs.} else if (error.status >= 500) {console.error(logMsg, error.stack ? error.stack : '');} else {diff --git a/server/lib/issueLength.js b/server/lib/issueLength.jsindex eec5117ca5..5fd1172e11 100644--- a/server/lib/issueLength.js+++ b/server/lib/issueLength.js@@ -1,6 +1,6 @@/*** Issue length profiles — per-issue size targets fed into every text stage- * prompt (idea / prose / comicScript / tvScript) so the LLM scales the beat+ * prompt (idea / prose / comicScript / teleplay) so the LLM scales the beat* sheet, prose word count, comic page count, and TV runtime to match.** Each issue stores a profile name; the lookup here materializes that intodiff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 22598a9da0..2490d5a7b8 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -19,7 +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.universe-builder', path: '/universe-builder', label: 'Universe Builder', section: 'Create', aliases: ['universe-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.create.pipeline', path: '/pipeline', label: 'Series', section: 'Create', aliases: ['series', 'pipeline', 'production', 'series-pipeline', 'production-pipeline'], keywords: ['series', 'issue', 'episode', 'comic', 'script', 'prose', 'storyboard', 'narrative', 'workflow'] },{ id: 'nav.create.sharing', path: '/sharing', label: 'Sharing', section: 'Create', aliases: ['sharing', 'share', 'buckets', 'share-buckets'], keywords: ['google drive', 'dropbox', 'icloud', 'syncthing', 'export', 'import', 'collaborate', 'federation', 'peer', 'cross-network'] },{ 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'] },diff --git a/server/lib/sceneExtractor.js b/server/lib/sceneExtractor.jsindex 96bdfec5e2..aa4595ef9e 100644--- a/server/lib/sceneExtractor.js+++ b/server/lib/sceneExtractor.js@@ -13,7 +13,7 @@** - `prose` → uses the existing `writers-room-script` stage prompt* (prose-paragraph granularity, sluglines invented).- * - `tvScript`→ uses the new `pipeline-extract-scenes` stage prompt+ * - `teleplay`→ uses the new `pipeline-extract-scenes` stage prompt* (sluglines already present in the teleplay markdown,* parse them rather than invent).*/@@ -21,11 +21,11 @@import { runStagedLLM } from './stageRunner.js';import { BIBLE_KIND, pickPromptFields, isStr, trimTo } from './storyBible.js';-export const SOURCE_KIND = Object.freeze({ PROSE: 'prose', TV_SCRIPT: 'tvScript' });+export const SOURCE_KIND = Object.freeze({ PROSE: 'prose', TELEPLAY: 'teleplay' });const STAGE_FOR_SOURCE = Object.freeze({[SOURCE_KIND.PROSE]: 'writers-room-script',- [SOURCE_KIND.TV_SCRIPT]: 'pipeline-extract-scenes',+ [SOURCE_KIND.TELEPLAY]: 'pipeline-extract-scenes',});// Per-field caps. Match the BIBLE_LIMITS pattern: bound every LLM-sourced@@ -99,7 +99,7 @@ export function sanitizeSceneList(raw, { maxScenes = 200 } = {}) {/*** @param {object} args* @param {string} args.source prose body OR teleplay markdown- * @param {string} args.sourceKind 'prose' | 'tvScript'+ * @param {string} args.sourceKind 'prose' | 'teleplay'* @param {Array} [args.characters] bible entries (for deference)* @param {Array} [args.settings] bible entries (for deference)* @param {Array} [args.objects] bible entries (for deference)diff --git a/server/lib/sceneExtractor.test.js b/server/lib/sceneExtractor.test.jsindex 847f9634fc..ae55f9a043 100644--- a/server/lib/sceneExtractor.test.js+++ b/server/lib/sceneExtractor.test.js@@ -159,7 +159,7 @@ describe('extractScenes', () => {expect(result.model).toBe('gpt-oss-120b');});- it('routes tvScript source through the pipeline-extract-scenes stage with series + issue context', async () => {+ it('routes teleplay source through the pipeline-extract-scenes stage with series + issue context', async () => {runStagedLLM.mockResolvedValue({content: { title: 'X', logline: 'L', scenes: [{ slugline: 'INT. ROOM' }] },runId: 'run-2', providerId: 'lmstudio', model: 'gpt-oss-120b',@@ -167,7 +167,7 @@ describe('extractScenes', () => {await extractScenes({source: '## TEASER\n\n### Scene 1\n\n**INT. ROOM — NIGHT**\n\nAction.',- sourceKind: SOURCE_KIND.TV_SCRIPT,+ sourceKind: SOURCE_KIND.TELEPLAY,series: { name: 'Show', styleNotes: 'noir' },issue: { number: 3, title: 'The Pilot' },});@@ -176,7 +176,7 @@ describe('extractScenes', () => {expect(stage).toBe('pipeline-extract-scenes');expect(vars.series).toEqual({ name: 'Show', styleNotes: 'noir' });expect(vars.issue).toEqual({ number: 3, title: 'The Pilot' });- expect(opts.source).toBe('scene-extract-tvScript');+ expect(opts.source).toBe('scene-extract-teleplay');});it('forwards providerOverride + custom run-tracking tag', async () => {diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex 2a107b9c50..35aec964fb 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -335,13 +335,13 @@ const promptRefineSchema = z.object({});// Source for scene extraction: which text stage to read from (`prose` →-// granular paragraph-grain breakdown via `writers-room-script`; `tvScript`+// granular paragraph-grain breakdown via `writers-room-script`; `teleplay`// → slugline-grain parse via `pipeline-extract-scenes`). `force` overrides// the "you have N hand-curated scenes already" guard.// Enum values match `SOURCE_KIND` verbatim so the route forwards `body.from`// straight through — same string also names the issue's text stage.const extractScenesSchema = z.object({- from: z.enum([SOURCE_KIND.PROSE, SOURCE_KIND.TV_SCRIPT]).optional().default(SOURCE_KIND.TV_SCRIPT),+ from: z.enum([SOURCE_KIND.PROSE, SOURCE_KIND.TELEPLAY]).optional().default(SOURCE_KIND.TELEPLAY),providerOverride: z.string().trim().max(80).optional(),force: z.boolean().optional(),});@@ -730,7 +730,7 @@ router.post('/issues/:id/stages/:stageId/generate', asyncHandler(async (req, res}));// Auto-fill stages.storyboards.scenes[] from a text stage. Reads the issue's-// prose (paragraph-grain) or tvScript (slugline-grain) output, runs the+// prose (paragraph-grain) or teleplay (slugline-grain) output, runs the// shared scene extractor, and replaces stages.storyboards.scenes with the// result mapped to the storyboards UI shape (visualPrompt → description).router.post('/issues/:id/stages/storyboards/extract-scenes', asyncHandler(async (req, res) => {@@ -921,6 +921,10 @@ router.post('/issues/:id/stages/comicPages/cover/render', asyncHandler(async (rescript: result.coverScript || '',imageJobId: result.jobId,prompt: result.prompt,+ // Clear the prior render's filename so the UI doesn't show the stale+ // image while the new job is in flight. The comic-pages filename hook+ // re-stamps it on completion.+ filename: null,};const { issue: updatedIssue, stage } = await issuesSvc.updateStage(req.params.id, 'comicPages', {cover: nextCover,@@ -984,6 +988,9 @@ router.post('/issues/:id/stages/comicPages/pages/:pageIndex/render', asyncHandle...currentPages[pageIndex],imageJobId: result.jobId,prompt: result.prompt,+ // Clear the prior render's filename so the UI doesn't show the stale+ // image while the new job is in flight. The hook re-stamps on completion.+ filename: null,};return { status: 'edited', pages: nextPages };},diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.jsindex 75b64b8308..da226b86d3 100644--- a/server/routes/pipeline.test.js+++ b/server/routes/pipeline.test.js@@ -468,7 +468,7 @@ describe('pipeline routes', () => {const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });const r = await request(app).post(`/api/pipeline/issues/${iss.body.id}/stages/storyboards/extract-scenes`)- .send({ from: 'tvScript' });+ .send({ from: 'teleplay' });expect(r.status).toBe(400);expect(r.body.error || r.body.message).toMatch(/empty/i);});@@ -479,13 +479,13 @@ describe('pipeline routes', () => {const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({stages: {- tvScript: { status: 'ready', output: '## TEASER\n\n**INT. ROOM — NIGHT**\n\nAction.' },+ teleplay: { status: 'ready', output: '## TEASER\n\n**INT. ROOM — NIGHT**\n\nAction.' },storyboards: { scenes: [{ slugline: 'EXT. CITY', description: 'pre-existing' }] },},});const r = await request(app).post(`/api/pipeline/issues/${iss.body.id}/stages/storyboards/extract-scenes`)- .send({ from: 'tvScript' });+ .send({ from: 'teleplay' });expect(r.status).toBe(409);expect(r.body.error || r.body.message).toMatch(/force/i);});@@ -509,17 +509,17 @@ describe('pipeline routes', () => {});const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({- stages: { tvScript: { status: 'ready', output: '## TEASER\n\n**INT. VAULT — NIGHT**\n\nThey break in.' } },+ stages: { teleplay: { status: 'ready', output: '## TEASER\n\n**INT. VAULT — NIGHT**\n\nThey break in.' } },});const r = await request(app).post(`/api/pipeline/issues/${iss.body.id}/stages/storyboards/extract-scenes`)- .send({ from: 'tvScript' });+ .send({ from: 'teleplay' });expect(r.status).toBe(200);expect(r.body.sceneCount).toBe(2);expect(r.body.runId).toBe('run-scenes-1');- expect(r.body.sourceKind).toBe('tvScript');+ expect(r.body.sourceKind).toBe('teleplay');// visualPrompt → description aliasing for UI compatexpect(r.body.stage.scenes[0].description).toBe('a high-tech vault, two figures in tactical gear, dim red emergency light');expect(r.body.stage.scenes[0].slugline).toBe('INT. VAULT — NIGHT');@@ -533,7 +533,7 @@ describe('pipeline routes', () => {// Series characters were forwarded to the extractor for bible deferenceconst firstCall = spy.mock.calls[0][0];expect(firstCall.characters[0].name).toBe('Alice');- expect(firstCall.sourceKind).toBe('tvScript');+ expect(firstCall.sourceKind).toBe('teleplay');expect(firstCall.series).toEqual({ name: 'S', styleNotes: '' });spy.mockRestore();});@@ -577,13 +577,13 @@ describe('pipeline routes', () => {const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({stages: {- tvScript: { status: 'ready', output: '## TEASER\n\n**INT. ROOM — NIGHT**' },+ teleplay: { status: 'ready', output: '## TEASER\n\n**INT. ROOM — NIGHT**' },storyboards: { scenes: [{ slugline: 'OLD', description: 'will be replaced' }] },},});const r = await request(app).post(`/api/pipeline/issues/${iss.body.id}/stages/storyboards/extract-scenes`)- .send({ from: 'tvScript', force: true });+ .send({ from: 'teleplay', force: true });expect(r.status).toBe(200);expect(r.body.sceneCount).toBe(1);diff --git a/server/services/canonUsage.js b/server/services/canonUsage.jsindex fd6dd2774d..cca7569a57 100644--- a/server/services/canonUsage.js+++ b/server/services/canonUsage.js@@ -30,7 +30,7 @@ function corpusForIssue(issue) {stages.idea?.output,stages.idea?.input,stages.comicScript?.output,- stages.tvScript?.output,+ stages.teleplay?.output,];return parts.filter(Boolean).join('\n\n');}diff --git a/server/services/pipeline/autoRunner.js b/server/services/pipeline/autoRunner.jsindex 573ba501ac..3194131999 100644--- a/server/services/pipeline/autoRunner.js+++ b/server/services/pipeline/autoRunner.js@@ -1,7 +1,7 @@/*** Pipeline — Auto-runner for the text-stage chain*- * Runs idea → prose → (comicScript + tvScript in parallel) for one issue and+ * Runs idea → prose → (comicScript + teleplay 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.@@ -68,7 +68,7 @@ export async function startAutoRunTextStages(issueId, options = {}) {// 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'] });+ broadcast(issueId, { type: 'start', runId, stages: ['idea', 'prose', 'comicScript', 'teleplay'] });try {// Stage 1: idea — skip if already ready/edited and not force-rerun@@ -79,11 +79,11 @@ export async function startAutoRunTextStages(issueId, options = {}) {if (!record.cancelRequested) {await runStageIfNeeded(issueId, 'prose', options);}- // Stage 3: comicScript + tvScript in parallel — both depend only on prose+ // Stage 3: comicScript + teleplay in parallel — both depend only on proseif (!record.cancelRequested) {await Promise.all([runStageIfNeeded(issueId, 'comicScript', options),- runStageIfNeeded(issueId, 'tvScript', options),+ runStageIfNeeded(issueId, 'teleplay', options),]);}diff --git a/server/services/pipeline/autoRunner.test.js b/server/services/pipeline/autoRunner.test.jsindex 80b5129bbd..5e3acd3369 100644--- a/server/services/pipeline/autoRunner.test.js+++ b/server/services/pipeline/autoRunner.test.js@@ -77,7 +77,7 @@ describe('pipeline auto-runner', () => {return { series, issue };}- it('runs idea → prose → (comicScript + tvScript in parallel) end to end', async () => {+ it('runs idea → prose → (comicScript + teleplay in parallel) end to end', async () => {const { issue } = await seed();const { runId, alreadyRunning } = await autoRunner.startAutoRunTextStages(issue.id);expect(runId).toBeTruthy();@@ -88,7 +88,7 @@ describe('pipeline auto-runner', () => {// 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']));+ expect(new Set(generated.slice(2))).toEqual(new Set(['comicScript', 'teleplay']));// Issue status flips to needs-review when all stages complete (user must// review before marking shipped).@@ -104,7 +104,7 @@ describe('pipeline auto-runner', () => {expect(generated).not.toContain('idea');expect(generated).toContain('prose');expect(generated).toContain('comicScript');- expect(generated).toContain('tvScript');+ expect(generated).toContain('teleplay');});it('reruns a ready stage when force=true', async () => {diff --git a/server/services/pipeline/comicPagesFilenameHook.js b/server/services/pipeline/comicPagesFilenameHook.jsnew file mode 100644index 0000000000..5389693260--- /dev/null+++ b/server/services/pipeline/comicPagesFilenameHook.js@@ -0,0 +1,83 @@+/**+ * Pipeline comic-pages — filename hook.+ *+ * The pipeline previously stored only `imageJobId` on each cover/page.+ * `mediaJobQueue` prunes completed jobs after 24h, so the UI can no longer+ * resolve a filename to render even though the PNG is still on disk.+ * This listener stamps `filename` onto the record at completion time so+ * the client has a fallback that survives the queue's TTL.+ *+ * Panel renders are intentionally NOT handled here — `enqueueVisualImage`'s+ * owner string doesn't encode page/panel position, so we can't locate the+ * target record from the event alone. Encode position into that owner+ * before extending this hook to panels.+ *+ * Failures are logged but never thrown — a bookkeeping miss must not+ * crash the server or fail the user's render.+ */++import { mediaJobEvents } from '../mediaJobQueue/index.js';+import { updateStageWithLatest } from './issues.js';+import { parseComicPagesOwner } from './owners.js';++let registeredHandler = null;++export function initComicPagesFilenameHook() {+ if (registeredHandler) return;++ registeredHandler = (job) => {+ void (async () => {+ if (!job || job.kind !== 'image') return;+ const filename = job.result?.filename;+ if (typeof filename !== 'string' || !filename) return;+ const parsed = parseComicPagesOwner(job.owner);+ if (!parsed) return;++ const shortId = String(job.id || '').slice(0, 8);+ let stamped = false;+ await updateStageWithLatest(+ parsed.issueId,+ 'comicPages',+ (currentStage) => {+ if (parsed.target === 'cover') {+ const cover = currentStage?.cover;+ // Only stamp if THIS job is still the cover's active render —+ // a re-render that landed between enqueue and this event would+ // otherwise be overwritten with the older filename. Empty patch+ // is a no-op (updateStageWithLatest short-circuits on `{}`).+ if (!cover || cover.imageJobId !== job.id) return {};+ stamped = true;+ return { cover: { ...cover, filename } };+ }+ const pages = Array.isArray(currentStage?.pages) ? currentStage.pages : [];+ const page = pages[parsed.pageIndex];+ if (!page || page.imageJobId !== job.id) return {};+ const nextPages = [...pages];+ nextPages[parsed.pageIndex] = { ...page, filename };+ stamped = true;+ return { pages: nextPages };+ },+ ).catch((err) => {+ console.error(`❌ comicPages filename hook failed for job ${shortId}: ${err?.message || err}`);+ });++ if (stamped) {+ const where = parsed.target === 'cover' ? 'cover' : `page${parsed.pageIndex}`;+ console.log(`📎 comicPages filename stamped — issue=${parsed.issueId.slice(0, 8)} ${where} ← ${filename}`);+ }+ })().catch((err) => {+ console.error(`❌ comicPages filename hook crashed: ${err?.message || err}`);+ });+ };+ mediaJobEvents.on('completed', registeredHandler);+ console.log('📎 comicPages filename hook initialized');+}++export const __testing = {+ reset: () => {+ if (registeredHandler) {+ mediaJobEvents.off('completed', registeredHandler);+ registeredHandler = null;+ }+ },+};diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex 54df65991b..b5ef0f8035 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -7,7 +7,7 @@* 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.teleplay — 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@@ -77,7 +77,7 @@ export const ISSUES_PER_RESPONSE_MAX = 1000;// 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 TEXT_STAGE_IDS = Object.freeze(['idea', 'prose', 'comicScript', 'teleplay']);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']);@@ -145,8 +145,12 @@ const sanitizeCover = (raw) => {const script = trimTo(raw.script, COVER_SCRIPT_MAX);const imageJobId = isStr(raw.imageJobId) && raw.imageJobId ? raw.imageJobId : null;const prompt = trimTo(raw.prompt, COVER_PROMPT_MAX);- if (!script && !imageJobId && !prompt) return null;- return { script, imageJobId, prompt: prompt || null };+ // `filename` is stamped by the comic-pages filename hook on image-gen+ // completion. It survives the 24h media-job archive TTL so the UI can+ // still render the cover after the job record expires.+ const filename = isStr(raw.filename) && raw.filename ? raw.filename : null;+ if (!script && !imageJobId && !prompt && !filename) return null;+ return { script, imageJobId, prompt: prompt || null, filename };};const sanitizeVisualStage = (raw, stageId = null) => {@@ -481,6 +485,13 @@ export function updateStageWithLatest(issueId, stageId, computeFn) {const isVisual = VISUAL_STAGE_IDS.includes(stageId);const currentStage = cur.stages[stageId];const patch = computeFn(currentStage);+ // Empty-patch fast path: a computeFn that returns `{}` is a "decided not+ // to write" signal (e.g. stale media-job completion against a re-rendered+ // page). Skip the disk write + emitRecordUpdated so it doesn't trigger+ // a re-export storm in share subscriptions for late no-op events.+ if (patch && typeof patch === 'object' && !Array.isArray(patch) && Object.keys(patch).length === 0) {+ return { issue: cur, stage: currentStage };+ }const merged = {...currentStage,...patch,diff --git a/server/services/pipeline/owners.js b/server/services/pipeline/owners.jsnew file mode 100644index 0000000000..593062ba4d--- /dev/null+++ b/server/services/pipeline/owners.js@@ -0,0 +1,30 @@+/**+ * Pipeline media-job owner strings.+ *+ * Single source of truth for the `pipeline:<issueId>:<stage>:<target>`+ * shape that's stamped onto every mediaJobQueue job enqueued from a+ * pipeline stage. Producers (visualStages.js) and consumers+ * (comicPagesFilenameHook.js) share these helpers so a typo on either+ * end is a compile/lint failure instead of a silently-unmatched event.+ */++const PREFIX = 'pipeline';++export function buildComicPagesOwner({ issueId, target, pageIndex }) {+ if (target === 'cover') return `${PREFIX}:${issueId}:comicPages:cover`;+ if (target === 'page') return `${PREFIX}:${issueId}:comicPages:page${pageIndex}`;+ throw new Error(`buildComicPagesOwner: unknown target "${target}"`);+}++const COMIC_PAGES_RE = /^pipeline:([^:]+):comicPages:(cover|page(\d+))$/;++export function parseComicPagesOwner(owner) {+ if (typeof owner !== 'string') return null;+ const m = owner.match(COMIC_PAGES_RE);+ if (!m) return null;+ const [, issueId, kind, pageIdxStr] = m;+ if (kind === 'cover') return { issueId, target: 'cover' };+ const pageIndex = Number(pageIdxStr);+ if (!Number.isInteger(pageIndex) || pageIndex < 0) return null;+ return { issueId, target: 'page', pageIndex };+}diff --git a/server/services/pipeline/owners.test.js b/server/services/pipeline/owners.test.jsnew file mode 100644index 0000000000..44a6227973--- /dev/null+++ b/server/services/pipeline/owners.test.js@@ -0,0 +1,28 @@+import { describe, it, expect } from 'vitest';+import { buildComicPagesOwner, parseComicPagesOwner } from './owners.js';++describe('pipeline owner strings', () => {+ it('round-trips a cover owner', () => {+ const owner = buildComicPagesOwner({ issueId: 'iss-abc', target: 'cover' });+ expect(owner).toBe('pipeline:iss-abc:comicPages:cover');+ expect(parseComicPagesOwner(owner)).toEqual({ issueId: 'iss-abc', target: 'cover' });+ });++ it('round-trips a page owner', () => {+ const owner = buildComicPagesOwner({ issueId: 'iss-xyz', target: 'page', pageIndex: 7 });+ expect(owner).toBe('pipeline:iss-xyz:comicPages:page7');+ expect(parseComicPagesOwner(owner)).toEqual({ issueId: 'iss-xyz', target: 'page', pageIndex: 7 });+ });++ it('builder throws on unknown target', () => {+ expect(() => buildComicPagesOwner({ issueId: 'iss-1', target: 'panel' })).toThrow();+ });++ it('parser returns null for unmatched strings', () => {+ expect(parseComicPagesOwner(null)).toBeNull();+ expect(parseComicPagesOwner('')).toBeNull();+ expect(parseComicPagesOwner('not-a-pipeline-owner')).toBeNull();+ expect(parseComicPagesOwner('pipeline:iss:storyboards:scene0')).toBeNull();+ expect(parseComicPagesOwner('pipeline:iss:comicPages:pageNaN')).toBeNull();+ });+});diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.jsindex a07054ff8c..5449754124 100644--- a/server/services/pipeline/textStages.js+++ b/server/services/pipeline/textStages.js@@ -1,7 +1,7 @@/*** Pipeline — Text Stage Execution*- * Runs a single text stage (idea / prose / comicScript / tvScript) against the+ * Runs a single text stage (idea / prose / comicScript / teleplay) 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.@@ -24,7 +24,7 @@ const STAGE_TO_TEMPLATE = Object.freeze({idea: 'pipeline-idea-expansion',prose: 'pipeline-prose',comicScript: 'pipeline-comic-script',- tvScript: 'pipeline-tv-script',+ teleplay: 'pipeline-teleplay',});/**diff --git a/server/services/pipeline/textStages.test.js b/server/services/pipeline/textStages.test.jsindex c5a486e56b..06fa6d2ddc 100644--- a/server/services/pipeline/textStages.test.js+++ b/server/services/pipeline/textStages.test.js@@ -89,16 +89,16 @@ describe('pipeline text stage generator', () => {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.+ // earlier stages but NOT teleplay (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 issuesSvc.updateStage(issue.id, 'teleplay', { 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.+ // teleplay comes AFTER comicScript and must not appear.expect(promptArg).not.toContain('TVS');});diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.jsindex fb64a04a63..719cd579b3 100644--- a/server/services/pipeline/visualStages.js+++ b/server/services/pipeline/visualStages.js@@ -27,6 +27,7 @@ import { enqueueJob } from '../mediaJobQueue/index.js';import { getSettings } from '../settings.js';import { getSeries } from './series.js';import { getIssue, updateStage, VISUAL_STAGE_IDS } from './issues.js';+import { buildComicPagesOwner } from './owners.js';import { getUniverse } from '../universeBuilder.js';import { ServerError } from '../../lib/errorHandler.js';import {@@ -235,7 +236,7 @@ export async function enqueueComicCover(issueId, options = {}) {});const jobId = enqueueImageJob({prompt, world, settings, options, mode,- owner: `pipeline:${issueId}:comicPages:cover`,+ owner: buildComicPagesOwner({ issueId, target: 'cover' }),logLine: `🎨 Pipeline comic cover — issue=${issueId.slice(0, 8)} number=${issue.number || 1}`,});return { jobId, mode, prompt, coverScript };@@ -399,7 +400,7 @@ export async function enqueueVisualComicPage(issueId, options = {}) {const jobId = enqueueImageJob({prompt, world, settings, options, mode,- owner: `pipeline:${issueId}:comicPages:page${pageIndex}`,+ owner: buildComicPagesOwner({ issueId, target: 'page', pageIndex }),logLine: `📄 Pipeline comic page — issue=${issueId.slice(0, 8)} page=${pageIndex + 1} panels=${page.panels.length}`,});return { jobId, mode, prompt, pageIndex };diff --git a/server/services/pipeline/visualStages.test.js b/server/services/pipeline/visualStages.test.jsindex f714946032..5853047220 100644--- a/server/services/pipeline/visualStages.test.js+++ b/server/services/pipeline/visualStages.test.js@@ -35,7 +35,7 @@ vi.mock('./issues.js', () => ({getIssue: (...a) => getIssueMock(...a),updateStage: (...a) => updateStageMock(...a),VISUAL_STAGE_IDS: ['comicPages', 'storyboards', 'episodeVideo'],- STAGE_IDS: ['idea', 'prose', 'comicScript', 'tvScript', 'comicPages', 'storyboards', 'episodeVideo'],+ STAGE_IDS: ['idea', 'prose', 'comicScript', 'teleplay', 'comicPages', 'storyboards', 'episodeVideo'],}));vi.mock('./series.js', () => ({diff --git a/server/services/voice/tools.js b/server/services/voice/tools.jsindex 167c413312..d491a7d53f 100644--- a/server/services/voice/tools.js+++ b/server/services/voice/tools.js@@ -26,7 +26,7 @@ const PIPELINE_STAGE_LABELS = {idea: 'Idea',prose: 'Prose',comicScript: 'Comic Script',- tvScript: 'TV Script',+ teleplay: 'Teleplay',comicPages: 'Comic Pages',storyboards: 'Storyboards',episodeVideo: 'Episode Video',@@ -37,7 +37,7 @@ const PIPELINE_STAGE_ALIASES = {idea: 'idea',prose: 'prose', story: 'prose','comic script': 'comicScript', comicscript: 'comicScript', comics: 'comicScript',- 'tv script': 'tvScript', tvscript: 'tvScript', teleplay: 'tvScript',+ 'tv script': 'teleplay', tvscript: 'teleplay', teleplay: 'teleplay','comic pages': 'comicPages', 'comic page': 'comicPages', comicpages: 'comicPages', pages: 'comicPages', page: 'comicPages',storyboards: 'storyboards', storyboard: 'storyboards', scenes: 'storyboards','episode video': 'episodeVideo', episodevideo: 'episodeVideo', episode: 'episodeVideo', video: 'episodeVideo',@@ -66,7 +66,7 @@ const navigateToPipelineStage = (issueId, stage, ctx) => {const PIPELINE_STAGE_TOOLS = [{name: 'pipeline_next_stage',- description: 'Advance to the next stage of the current pipeline issue (Idea → Prose → Comic Script → TV Script → Comic Pages → Storyboards → Episode Video). Only works on a /pipeline/issues/... page.',+ description: 'Advance to the next stage of the current pipeline issue (Idea → Prose → Comic Script → Teleplay → Comic Pages → Storyboards → Episode Video). Only works on a /pipeline/issues/... page.',parameters: { type: 'object', properties: {} },execute: async (_args, ctx = {}) => {const cur = parsePipelineIssuePath(ctx.state?.ui?.path);diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.jsindex dac189956f..5c4d4fe14a 100644--- a/server/services/voice/tools.test.js+++ b/server/services/voice/tools.test.js@@ -744,10 +744,10 @@ describe('pipeline stage navigation tools', () => {expect(ctx.sideEffects).toEqual([{ type: 'navigate', path: '/pipeline/issues/iss-x/storyboards' }]);});- it('resolves spoken aliases (teleplay → tvScript, pages → comicPages, video → episodeVideo)', async () => {+ it('resolves spoken aliases (teleplay → teleplay, pages → comicPages, video → episodeVideo)', async () => {const ctx = makeCtx('/pipeline/issues/iss-x/idea');const r1 = await dispatchTool('pipeline_open_stage', { stage: 'teleplay' }, ctx);- expect(r1.stage).toBe('tvScript');+ expect(r1.stage).toBe('teleplay');const r2 = await dispatchTool('pipeline_open_stage', { stage: 'pages' }, ctx);expect(r2.stage).toBe('comicPages');const r3 = await dispatchTool('pipeline_open_stage', { stage: 'video' }, ctx);diff --git a/server/services/writersRoom/promoteToPipeline.js b/server/services/writersRoom/promoteToPipeline.jsindex 5df54712de..57c7728f55 100644--- a/server/services/writersRoom/promoteToPipeline.js+++ b/server/services/writersRoom/promoteToPipeline.js@@ -47,7 +47,7 @@ async function loadScriptScenes(workId) {function buildStoryboardScenes(canonicalScenes) {// Mirror the adapter in routes/pipeline.js's /extract-scenes handler so the// promoted issue's storyboards stage shape is byte-for-byte identical to- // what the in-pipeline "Generate scenes from {prose|tv-script}" button+ // what the in-pipeline "Generate scenes from {prose|teleplay}" button// would produce. Rich fields (heading/summary/dialogue/...) ride along.return canonicalScenes.map((s) => ({...s,