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): length profile, per-stage gen config, comic front cover (#233)
[._.]/ Adam Eivyab0adfbfefe9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 5078ea0d30..289590f7be 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,44 @@## Added+- **Pipeline — per-issue length profile, per-stage gen config, comic front cover.**+ Three additive pipeline-UX features rescued from a pre-crash recovery branch+ and cherry-picked into main:+ - **Length profile picker** in the pipeline issue header. Sets+ `issue.lengthProfile` (`teaser` / `standard` / `extended` / `finale` /+ `custom`) plus optional `pageTarget` + `minutesTarget`. New+ `server/lib/issueLength.js` materializes the profile into prompt-template+ variables (`{{lengthTargets.profile}}`, `pageTarget`, `minutesTarget`,+ `proseWordsMin/Max`, `beatsMin/Max`) that the idea, prose, comic-script,+ TV-script prompts now consume — beat counts, prose word ranges, and page+ counts scale with the picked profile instead of being hardcoded to 22+ pages / 24 minutes. The season-episodes generator emits a `lengthProfile`+ per episode so a finale auto-scales without manual tweaking.+ - **Per-stage generation settings.** New gear-icon modal in the issue+ header on the **Storyboards** tab exposes `imageMode` (`auto` / `local` /+ `codex`), pinned local image model, and a refine-LLM override. Persisted+ on `stages.<stageId>.genConfig` so reloads keep the user's choice; the+ Comic editor (`comicScript` tab) keeps its existing image-gen drawer so+ the gear stays off that tab to avoid duplicate controls. The same+ `genConfig` shape persists on `stages.comicPages.genConfig` as well —+ threaded through `generatePipelineComicPage`,+ `generatePipelineVisualImage`, and the two refine-prompt endpoints —+ so a future header-gear extension to the Comic tab can opt in without+ a schema change. Visual stages' server resolver now defaults to codex+ when `imageGen.codex.enabled` (still falls back to local diffusion+ otherwise).+ - **Comic-issue front cover.** Optional cover concept per issue persisted+ on `stages.comicPages.cover` (`script` + `imageJobId` + `prompt`). New+ `POST /pipeline/issues/:id/stages/comicPages/cover/render` route builds+ the cover prompt server-side (series masthead + issue-number tag + the+ user's concept) and enqueues an image-gen job; the cover card sits+ above the page list in the Comic tab (the merged Comic editor).+ - **Comic-script parser** now recognizes an optional `## Cover concept`+ section and the simpler `Panel N` / `Field:` plain-line format the+ updated prompts emit, alongside the legacy `### Panel N` /+ `**Field:**` form. `parseComicScript` returns+ `{ coverConcept, pages: [{ rawText, panels }] }`.+- **Shell — UUID-based URLs for each sub-shell session.** The shell page nowmounts at `/shell/:sessionId` in addition to `/shell`, and mirrors the activesession id into the URL whenever a session is started, attached, or switched.@@ -545,6 +583,17 @@## Fixed+- **Pipeline stage prompts — length profile variables reach existing installs.**+ Running `npm run migrations` now auto-updates the five pipeline stage prompt+ templates (`pipeline-idea-expansion.md`, `pipeline-prose.md`,+ `pipeline-comic-script.md`, `pipeline-tv-script.md`,+ `pipeline-season-episodes.md`) on machines that were set up before the+ length-profile feature landed. Migration `003` compares each file's MD5 to+ the pre-feature shipped hash: unmodified files are overwritten with the new+ template; customized files are skipped with a diff hint. `setup-data.js` also+ emits a one-line warning at install time when any stage prompt has drifted,+ pointing at the migration command.+- **CoS-spawned PRs — concise title + no double "Summary" heading.** Tworelated bugs in the PR-creation path:- The PR title was the raw user task description (e.g. "on thediff --git a/CLAUDE.md b/CLAUDE.mdindex a365e501f8..30675c5318 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -159,6 +159,9 @@ When working **directly in the Claude Code TUI** with the user driving, edit the- **Schema parity when adding fields.** When you add a field to a sanitizer, `createXxx`, or a payload shape, update the corresponding Zod schema (`server/lib/aiToolkit/validation.js` for toolkit shapes, `server/lib/validation.js` for PortOS routes) in the same change. Wire validation into POST and PUT (PUT can use `schema.partial()`); the PortOS convention is *all* inputs validated. Tolerate UI sentinels (`endpoint: ''` for CLI providers) with `z.preprocess(v => v === '' ? undefined : v, …)`. When a service migrates legacy keys on read, the schema must still accept the legacy shape so older clients don't 400 before the migration runs.- **Silent vs. toasting API requests.** The `request()` helper in `client/src/services/apiCore.js` toasts errors by default. When a caller already owns its own error UI — either via `useAsyncAction` (which toasts on throw) or a `.catch(() => fallback)` that intentionally swallows the failure — pass `{ silent: true }` to the API helper so the toast only fires from one layer. Add an `options` parameter to new API wrappers so callers can opt into silent mode.- **"Run Now" actions must gate on saved state, not the form input.** When a settings page has a companion "Run this now" button that triggers a server action reading server-side settings (not the local form values), the button must be gated on the *saved* value, not the in-memory input. Track a parallel `saved*` state for each setting the action depends on, update it on successful save, and use it for the action's enabled gate. Disable the action while the form is dirty *or* a save is in flight — a tooltip-only warning is missed on touch and produces surprising "I edited X and ran, but X didn't apply" bugs.+- **In-flight saves must gate dependent actions, not just the form.** When a field's PATCH is async and a button triggers server-side work that reads that field (auto-run, regenerate, etc.), the button must disable while the PATCH is in flight — not just while the input is "dirty." Otherwise the user picks a new value, the input clears, and they click the action before the server has the new value persisted. Track a `<field>Saving` boolean alongside the action's other disable predicates, set it before the PATCH and clear it in `.finally()`. See `PipelineIssue.jsx` `lengthProfileSaving` for the canonical example.+- **Async PATCH races on shared records — serialize writes server-side.** When two write paths can mutate the same record concurrently (e.g. a blur-save plus an explicit "Render" button against `stages.comicPages.cover`), client-side guards (refs, `onMouseDown`, status checks) are unreliable — keyboard activation, status==='unknown' stalls, and `loadState → modify → saveState` interleaving all defeat them. The correct fix is to serialize writes at the *file* level on the server (every PATCH awaits the previous one to settle before reading state, so it merges against the freshest persisted record). See `issueWriteTail` in `server/services/pipeline/issues.js`. A `Map<recordId, Promise>` is *not* enough — two writes to different record ids share the same JSON state file and can still clobber each other; collapse the queue to a single tail per shared file.+- **Stage-prompt template changes need a migration.** `scripts/setup-data.js` only copies *missing* prompt files to `data/prompts/stages/` — existing installs keep their old templates. When you add a `{{template.variable}}` reference to a `data.sample/prompts/stages/*.md` file, also add an entry to `data/migrations/NNN-…js` that updates the corresponding installed prompt when its hash still matches the pre-change shipped version. Normalize line endings (`\r\n` → `\n`, bare `\r` → `\n`) before hashing so the comparison is correct on Windows checkouts. The drift warning in `scripts/setup-data.js` distinguishes auto-updatable (matches old shipped hash) from customized (matches neither) — when adding to the migrated list, mirror both `OLD_SHIPPED_MD5` and `NEW_SHIPPED_MD5` there too so the warning stays actionable. See `data/migrations/003-update-pipeline-stage-prompts.js`.- **High-frequency state writes must batch.** Per-line state mutations that round-trip through `withStateLock → loadState → saveState` (e.g. `appendAgentOutput` in `cosAgents.js`) are fine for human-pace events but catastrophic when called from a hot loop — PTY output streams, AI tool-call streams, or any producer that can emit dozens of events per second. When wiring a new streaming producer, add a batched variant that takes an array (see `appendAgentOutputLines` for the pattern) and flush from the caller on a ~250ms debounce. Always drain the pending buffer in the producer's `finish`/`cleanup` path before the final state write so completion events don't beat the last output batch to disk.- **Socket event-driven state — don't pre-clear before the server confirms.** When swapping which entity a socket-driven UI is showing (shell session, agent run, etc.), wait for the server's success event to drive the swap atomically; the error event is the recovery point. Pre-clearing the local `*Ref` / visible state up front leaves the UI stranded on a dead URL when the success event never arrives (target died mid-request, server rejected the switch). Pair every `socket.on('X:error')` that follows a stateful request with a recovery branch that restores the previously-displayed state or falls back to a live alternative.- **Single-subscriber socket resources need notify + recipient-relative advertise + filter + claim.** Some server-side resources (PTY shell sessions, etc.) intentionally store one attached socket and fan output to it. The contract: (1) emit `<resource>:detached` on the previous socket when a new socket takes over so the displaced client can drop its local view; (2) include an `attached: boolean` field on each list-entry payload, computed *relative to the recipient socket* (true only when bound to a different socket) — a globally-truthy `attached` makes a client's own sessions look unavailable to itself; (3) broadcast list updates from both attach AND detach paths; (4) auto-pick paths send `claim: true` and the server refuses to displace a different socket. Manual paths (tab click, deep-link URL) default to `claim: false` so explicit intent still wins. See `server/services/shell.js` for the canonical implementation.diff --git a/client/src/components/pipeline/LengthProfilePicker.jsx b/client/src/components/pipeline/LengthProfilePicker.jsxnew file mode 100644index 0000000000..e34d96b562--- /dev/null+++ b/client/src/components/pipeline/LengthProfilePicker.jsx@@ -0,0 +1,169 @@+/**+ * Inline length-profile picker for the issue page header. Shows a compact+ * chip with the current preset + page/minute summary. Clicking opens a+ * dropdown with the four presets and a Custom option. Selecting Custom+ * expands two number inputs (pages, minutes) inline in the dropdown.+ *+ * The schema (`issue.lengthProfile`, `issue.pageTarget`, `issue.minutesTarget`)+ * is persisted by the server's issue sanitizer; this component just emits the+ * patch shape via `onChange`.+ */++import { useEffect, useRef, useState } from 'react';+import { ChevronDown, Gauge } from 'lucide-react';+import { LENGTH_PROFILES, summarizeLengthProfile, clampInt, CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX } from '../../lib/issueLength';++const PRESET_ORDER = ['teaser', 'standard', 'extended', 'finale'];++export default function LengthProfilePicker({ issue, onChange, disabled = false }) {+ const [open, setOpen] = useState(false);+ const wrapRef = useRef(null);+ const profile = issue?.lengthProfile || 'standard';+ const summary = summarizeLengthProfile(issue);++ // Auto-close the menu if the parent disables us mid-interaction. Prevents+ // a stranded open menu over a disabled trigger during auto-run kickoff.+ useEffect(() => {+ if (disabled && open) setOpen(false);+ }, [disabled, open]);++ // Close on outside click or Escape.+ useEffect(() => {+ if (!open) return undefined;+ const onDoc = (e) => {+ if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);+ };+ const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };+ document.addEventListener('mousedown', onDoc);+ document.addEventListener('keydown', onKey);+ return () => {+ document.removeEventListener('mousedown', onDoc);+ document.removeEventListener('keydown', onKey);+ };+ }, [open]);++ const choose = (next) => {+ // For presets we send just `lengthProfile`; pageTarget / minutesTarget+ // stay at whatever the issue had (or null) so toggling back to Custom+ // remembers the user's last manual values.+ onChange?.({ lengthProfile: next });+ setOpen(false);+ };++ // Custom mode: edit pages + minutes inline. Defaults reflect the saved+ // values, falling back to the standard preset so the inputs aren't blank+ // the first time the user clicks Custom.+ const std = LENGTH_PROFILES.standard;+ const [customPages, setCustomPages] = useState(+ issue?.pageTarget ?? std.pageTarget,+ );+ const [customMinutes, setCustomMinutes] = useState(+ issue?.minutesTarget ?? std.minutesTarget,+ );+ useEffect(() => {+ setCustomPages(issue?.pageTarget ?? std.pageTarget);+ setCustomMinutes(issue?.minutesTarget ?? std.minutesTarget);+ }, [issue?.pageTarget, issue?.minutesTarget, std.pageTarget, std.minutesTarget]);++ const clampedPages = clampInt(customPages, CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX);+ const clampedMinutes = clampInt(customMinutes, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX);+ const applyDisabled = clampedPages === null || clampedMinutes === null;++ const saveCustom = () => {+ onChange?.({+ lengthProfile: 'custom',+ pageTarget: clampedPages,+ minutesTarget: clampedMinutes,+ });+ setOpen(false);+ };++ return (+ <div ref={wrapRef} className="relative">+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ disabled={disabled}+ className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md bg-port-card border border-port-border text-xs text-gray-300 hover:text-white hover:border-port-accent/50 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:text-gray-300 disabled:hover:border-port-border"+ title={disabled+ ? 'Length profile is locked while auto-run is active'+ : 'Episode length profile — drives beat / prose / script size targets'}+ aria-expanded={open}+ aria-disabled={disabled}+ aria-label={`Length profile: ${summary.label} (${summary.detail})`}+ >+ <Gauge size={12} className="text-gray-500" />+ <span className="font-medium text-white">{summary.label}</span>+ <span className="text-gray-500">· {summary.detail}</span>+ <ChevronDown size={12} className="text-gray-500" />+ </button>++ {open && (+ <div className="absolute right-0 mt-1 w-72 bg-port-card border border-port-border rounded-lg shadow-lg z-30 p-1">+ {PRESET_ORDER.map((id) => {+ const preset = LENGTH_PROFILES[id];+ const active = profile === id;+ return (+ <button+ key={id}+ type="button"+ onClick={() => choose(id)}+ className={`w-full text-left px-2 py-1.5 rounded text-xs ${+ active ? 'bg-port-accent/15 text-white' : 'text-gray-300 hover:bg-port-bg hover:text-white'+ }`}+ >+ <div className="flex items-center justify-between gap-2">+ <span className="font-medium">{preset.label}</span>+ <span className="text-[10px] text-gray-500">{preset.pageTarget}pg / {preset.minutesTarget}min</span>+ </div>+ <div className="text-[10px] text-gray-500 mt-0.5">{preset.description}</div>+ </button>+ );+ })}++ <div className={`mt-1 pt-1 border-t border-port-border ${profile === 'custom' ? 'bg-port-accent/5 rounded' : ''}`}>+ <div className="px-2 py-1.5">+ <div className="flex items-center justify-between gap-2 mb-1">+ <span className="text-xs font-medium text-white">Custom</span>+ <span className="text-[10px] text-gray-500">free-form pages + minutes</span>+ </div>+ <div className="flex items-center gap-2">+ <label className="flex-1 text-[10px] text-gray-500">+ Pages+ <input+ type="number"+ min={CUSTOM_PAGE_MIN}+ max={CUSTOM_PAGE_MAX}+ value={customPages}+ onChange={(e) => setCustomPages(e.target.value)}+ className="block w-full mt-0.5 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-xs"+ />+ </label>+ <label className="flex-1 text-[10px] text-gray-500">+ Minutes+ <input+ type="number"+ min={CUSTOM_MINUTE_MIN}+ max={CUSTOM_MINUTE_MAX}+ value={customMinutes}+ onChange={(e) => setCustomMinutes(e.target.value)}+ className="block w-full mt-0.5 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-xs"+ />+ </label>+ </div>+ <button+ type="button"+ onClick={saveCustom}+ disabled={applyDisabled}+ title={applyDisabled ? 'Enter a page count and minute count to apply' : 'Save custom length profile'}+ className="mt-2 w-full px-2 py-1 rounded bg-port-accent text-white text-xs font-medium hover:bg-port-accent/90 disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-port-accent"+ >+ Apply custom length+ </button>+ </div>+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/pipeline/stages/ComicPagesStage.jsx b/client/src/components/pipeline/stages/ComicPagesStage.jsxindex 3e7a933384..8715a2372c 100644--- a/client/src/components/pipeline/stages/ComicPagesStage.jsx+++ b/client/src/components/pipeline/stages/ComicPagesStage.jsx@@ -10,10 +10,19 @@ import {extractPipelineComicPages,} from '../../../services/api';import MediaJobThumb from '../MediaJobThumb';+import { genConfigToImageOptions, genConfigToRefineOptions } from './VisualGenSettings';++// NOTE: `ComicPagesStage` is currently unreachable in the running app —+// `PipelineIssue.jsx` redirects /comicPages URLs to /comicScript, where+// `ComicScriptStage` owns the merged page editor. The cover UI for this+// stage lives in ComicScriptStage. This component stays in the tree as a+// pure per-panel editor so a future view that lands directly here still+// works.export default function ComicPagesStage({ issue, onStageUpdate }) {const stage = issue.stages?.comicPages || { status: 'empty', pages: [] };const [pages, setPages] = useState(stage.pages || []);+ const genConfig = stage.genConfig || null;const [savingIdx, setSavingIdx] = useState(null);const [refiningKey, setRefiningKey] = useState(null);// Per-page in-flight state. Codex can render multiple pages in parallel, so@@ -100,7 +109,7 @@ export default function ComicPagesStage({ issue, onStageUpdate }) {return;}markRendering(pi, true);- const result = await generatePipelineComicPage(issue.id, pi).catch((err) => {+ const result = await generatePipelineComicPage(issue.id, pi, genConfigToImageOptions(genConfig)).catch((err) => {toast.error(err.message || 'Failed to enqueue page render');return null;});@@ -128,7 +137,7 @@ export default function ComicPagesStage({ issue, onStageUpdate }) {}const key = `${pi}:${ni}`;setRefiningKey(key);- const result = await refinePipelineComicPanelPrompt(issue.id, pi, ni, {})+ const result = await refinePipelineComicPanelPrompt(issue.id, pi, ni, genConfigToRefineOptions(genConfig)).catch((err) => {toast.error(err.message || 'Refine failed');return null;@@ -152,6 +161,7 @@ export default function ComicPagesStage({ issue, onStageUpdate }) {setSavingIdx(`${pi}:${ni}`);const result = await generatePipelineVisualImage(issue.id, 'comicPages', {description: panel.description,+ ...genConfigToImageOptions(genConfig),}).catch((err) => {toast.error(err.message || 'Failed to enqueue image');return null;diff --git a/client/src/components/pipeline/stages/ComicScriptStage.jsx b/client/src/components/pipeline/stages/ComicScriptStage.jsxindex 113cd0cc40..0608d853a4 100644--- a/client/src/components/pipeline/stages/ComicScriptStage.jsx+++ b/client/src/components/pipeline/stages/ComicScriptStage.jsx@@ -15,6 +15,7 @@ import {generatePipelineStage,extractPipelineComicPages,generatePipelineComicPage,+ generatePipelineComicCover,updatePipelineComicPage,updatePipelineIssue,PIPELINE_STAGE_LABELS,@@ -159,6 +160,70 @@ export default function ComicScriptStage({ issue, series, onStageUpdate }) {const renderOpts = useMemo(() => pipelineImageCfgToRenderOpts(imageCfg), [imageCfg]);+ // Front cover lives on stages.comicPages.cover so it persists alongside the+ // page renders. The textarea owns a draft string separate from the persisted+ // value so keystrokes don't round-trip until blur.+ const cover = comicPages.cover || { script: '', imageJobId: null, prompt: null };+ const [draftCoverScript, setDraftCoverScript] = useState(cover.script || '');+ useEffect(() => { setDraftCoverScript(cover.script || ''); }, [cover.script]);+ const [renderingCover, setRenderingCover] = useState(false);+ // Mirror PageRow's job-status pattern: start 'unknown' so we treat any+ // existing jobId as in-flight until MediaJobThumb reports back.+ const [coverJobStatus, setCoverJobStatus] = useState('unknown');+ // `unknown` means the GET /media-jobs/:id is still in-flight OR the job+ // archive has expired (404). After a short grace period, stop treating an+ // unresolved `unknown` as in-flight so a stale imageJobId (job archived,+ // page reloaded) doesn't permanently disable "Render cover". The 5-second+ // window comfortably outlasts any LAN round-trip while being short enough+ // that an actual expired-archive case doesn't frustrate the user.+ const [coverUnknownExpired, setCoverUnknownExpired] = useState(false);+ // Reset both whenever the jobId changes so a freshly-queued job gets a+ // clean slate and is immediately treated as in-flight.+ useEffect(() => {+ setCoverJobStatus('unknown');+ setCoverUnknownExpired(false);+ if (!cover.imageJobId) return undefined;+ const t = setTimeout(() => setCoverUnknownExpired(true), 5000);+ return () => clearTimeout(t);+ }, [cover.imageJobId]);+ const coverJobInFlight = !!cover.imageJobId+ && coverJobStatus !== 'completed'+ && coverJobStatus !== 'failed'+ && coverJobStatus !== 'canceled'+ && !(coverJobStatus === 'unknown' && coverUnknownExpired);++ const persistCoverScript = async (nextScript) => {+ // Only send the script text. Never clear imageJobId/prompt from the blur+ // handler — doing so races with the render route's PATCH (which persists the+ // new jobId) and whoever lands last wins. The render button is already+ // disabled while a job is in-flight, so stale renders can only linger after+ // a completed/failed job; the user re-renders explicitly to replace them.+ const updated = await updatePipelineIssue(issue.id, {+ stages: { comicPages: { cover: { script: nextScript } } },+ }).catch((err) => {+ toast.error(err.message || 'Save failed');+ return null;+ });+ if (updated) onStageUpdate?.('comicPages', updated.stages.comicPages, updated);+ };++ const handleRenderCover = async () => {+ setRenderingCover(true);+ const result = await generatePipelineComicCover(issue.id, {+ coverScript: draftCoverScript || '',+ ...renderOpts,+ }).catch((err) => {+ toast.error(err.message || 'Failed to render cover');+ return null;+ });+ setRenderingCover(false);+ if (!result) return;+ if (result.issue) {+ onStageUpdate?.('comicPages', result.issue.stages.comicPages, result.issue);+ }+ toast.success(`Queued ${result.mode} cover render (${result.jobId.slice(0, 8)})`);+ };+const overrides = {providerId: series?.llm?.provider || undefined,model: series?.llm?.model || undefined,@@ -250,6 +315,45 @@ export default function ComicScriptStage({ issue, series, onStageUpdate }) {</p>) : null}+ <div className="p-3 bg-port-card border border-port-border rounded-lg">+ <div className="flex items-center justify-between mb-2 gap-2 flex-wrap">+ <span className="text-xs uppercase tracking-wider text-gray-500">Cover</span>+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={handleRenderCover}+ disabled={renderingCover || coverJobInFlight}+ title={coverJobInFlight+ ? 'Cover render in progress…'+ : 'Render the issue\'s front cover — series masthead + issue number tag + your cover concept.'}+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-accent text-white text-xs font-medium hover:bg-port-accent/90 disabled:opacity-40 disabled:cursor-not-allowed"+ >+ {(renderingCover || coverJobInFlight) ? <Loader2 size={12} className="animate-spin" /> : <ImageIcon size={12} />}+ Render cover+ </button>+ {cover.imageJobId ? (+ <div className="flex items-center gap-2">+ <MediaJobThumb jobId={cover.imageJobId} label="Cover" size="md" onStatus={setCoverJobStatus} />+ <span className="text-[10px] text-gray-500 font-mono break-all" title="Last cover render job">+ {cover.imageJobId.slice(0, 8)}+ </span>+ </div>+ ) : null}+ </div>+ </div>+ <textarea+ value={draftCoverScript}+ onChange={(e) => setDraftCoverScript(e.target.value)}+ onBlur={() => {+ if ((cover.script || '') !== draftCoverScript) persistCoverScript(draftCoverScript);+ }}+ placeholder="Cover concept — describe the hero image, mood, lighting, framing. Series masthead and issue-number tag included in the prompt automatically."+ rows={3}+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"+ maxLength={8000}+ />+ </div>+<ul className="space-y-4">{pages.map((page, pi) => (<PageRowdiff --git a/client/src/components/pipeline/stages/StoryboardsStage.jsx b/client/src/components/pipeline/stages/StoryboardsStage.jsxindex ea7ab80d16..c1336be420 100644--- a/client/src/components/pipeline/stages/StoryboardsStage.jsx+++ b/client/src/components/pipeline/stages/StoryboardsStage.jsx@@ -27,10 +27,13 @@ import {extractPipelineStoryboardScenes,} from '../../../services/api';import MediaJobThumb from '../MediaJobThumb';+import { genConfigToImageOptions, genConfigToRefineOptions } from './VisualGenSettings';export default function StoryboardsStage({ issue, onStageUpdate }) {const stage = issue.stages?.storyboards || { status: 'empty', scenes: [] };const [scenes, setScenes] = useState(stage.scenes || []);+ // Per-stage gen config — edited from the page-level settings modal.+ const genConfig = stage.genConfig || null;const [savingIdx, setSavingIdx] = useState(null);const [renderingVideoIdx, setRenderingVideoIdx] = useState(null);const [refiningIdx, setRefiningIdx] = useState(null);@@ -116,6 +119,7 @@ export default function StoryboardsStage({ issue, onStageUpdate }) {const result = await generatePipelineVisualImage(issue.id, 'storyboards', {description: scene.description,slugline: scene.slugline || '',+ ...genConfigToImageOptions(genConfig),}).catch((err) => {toast.error(err.message || 'Failed to enqueue image');return null;@@ -137,7 +141,7 @@ export default function StoryboardsStage({ issue, onStageUpdate }) {return;}setRefiningIdx(i);- const result = await refinePipelineSceneImagePrompt(issue.id, i, {})+ const result = await refinePipelineSceneImagePrompt(issue.id, i, genConfigToRefineOptions(genConfig)).catch((err) => {toast.error(err.message || 'Refine failed');return null;diff --git a/client/src/components/pipeline/stages/VisualGenSettings.jsx b/client/src/components/pipeline/stages/VisualGenSettings.jsxnew file mode 100644index 0000000000..baa04a4f37--- /dev/null+++ b/client/src/components/pipeline/stages/VisualGenSettings.jsx@@ -0,0 +1,322 @@+/**+ * Per-stage generation settings panel for visual pipeline stages+ * (comicPages, storyboards). Lets the user pick:+ *+ * - Image backend: 'auto' | 'local' | 'codex'+ * ('auto' defers to the server resolver — prefers codex when enabled,+ * else falls back to local diffusion.)+ * - Local image model (only shown when backend is local).+ * - LLM provider + model for the "AI: refine" prompt button.+ *+ * Settings persist on `stages.<stageId>.genConfig` so reloads keep the+ * user's choice. Callers pass the current genConfig + an onChange handler+ * that writes the new value via updatePipelineIssue.+ */++import { useEffect, useMemo, useState } from 'react';+import { ChevronDown, ChevronRight, SlidersHorizontal, Sparkles } from 'lucide-react';+import {+ getSettings, listImageModels, getProviders,+} from '../../../services/api';+import { filterSelectableModels } from '../../../utils/providers';+import { deriveAvailableBackends } from '../../../lib/imageGenBackends';+import BackendChipStrip from '../../media/BackendChipStrip';+import ProviderModelSelector from '../../ProviderModelSelector';++const DEFAULT_CONFIG = Object.freeze({+ imageMode: 'auto',+ imageModelId: null,+ refineProvider: null,+ refineModel: null,+});++// "auto" is the default sentinel — the backend strip displays it as a+// dedicated chip that means "follow the server's resolver". The actual+// dispatch happens server-side in visualStages.js#resolveMode.+const AUTO_BACKEND = Object.freeze({ id: 'auto', label: 'Auto', icon: Sparkles });++const MODE_BLURB = {+ auto: 'Auto follows the server default.',+ codex: 'Renders via your logged-in Codex session. Model/steps/seed are picked by Codex.',+ local: 'Renders locally via mflux/diffusers. Pick the model below.',+};++// Cache the three session-stable lookups (settings, image models, providers)+// at module scope so every Comic/Storyboard stage mount on the same Pipeline+// page (or after a remount) reuses the result instead of re-fetching. Stored+// as the in-flight Promise so concurrent mounts don't race. The cache is+// cleared when ANY underlying request failed so a transient error during+// settings/provider startup doesn't lock the panel into stale fallbacks for+// the rest of the SPA session — the next mount retries.+let lookupCache = null;+const loadLookups = () => {+ if (lookupCache) return lookupCache;+ let anyFailed = false;+ const promise = Promise.all([+ getSettings().catch(() => { anyFailed = true; return null; }),+ listImageModels().catch(() => { anyFailed = true; return []; }),+ getProviders().catch(() => { anyFailed = true; return { providers: [] }; }),+ ]).then((vals) => {+ if (anyFailed) lookupCache = null;+ return vals;+ });+ lookupCache = promise;+ return promise;+};++// Mirror of server-side `visualStages.js#resolveMode`. The "Auto →" label in+// this panel must match what the server will actually dispatch — otherwise+// the modal tells the user "Auto is currently Codex" while the render flows+// to local diffusion (or vice versa). Priority:+// 1. settings.imageGen.mode pinned to 'codex' AND codex.enabled → 'codex'+// 2. settings.imageGen.mode pinned to 'local' → 'local'+// 3. settings.imageGen.codex.enabled (auto-default) → 'codex'+// 4. local pythonPath configured → 'local'+// 5. otherwise → not configured+// Codex is gated on the enabled flag at every step — a stale 'codex' pin+// from before the toggle was turned off must resolve as local, not Codex.+const resolveAutoLabel = (s) => {+ const codexEnabled = s?.imageGen?.codex?.enabled === true;+ const pinned = s?.imageGen?.mode;+ if (pinned === 'codex' && codexEnabled) return 'Codex';+ if (pinned === 'local') return 'Local diffusion';+ if (codexEnabled) return 'Codex';+ if (s?.imageGen?.local?.pythonPath) return 'Local diffusion';+ return 'Local diffusion (not configured)';+};++const summarizeMode = (cfg, autoResolution) => {+ if (cfg.imageMode === 'auto' && !cfg.imageModelId && !cfg.refineProvider) {+ return `Auto → ${autoResolution.toLowerCase()}`;+ }+ const head = cfg.imageMode === 'auto'+ ? `auto → ${autoResolution.toLowerCase()}`+ : cfg.imageMode;+ const tail = cfg.imageMode === 'local' && cfg.imageModelId ? ` / ${cfg.imageModelId}` : '';+ return `Pinned: ${head}${tail}`;+};++// The actual settings panel body. Extracted so the same controls can live+// either inside a self-contained accordion (legacy inline placement) or+// chromelessly inside a parent-owned container like a settings modal.+function VisualGenSettingsBody({ cfg, update, stageLabel, systemSettings, imageModels, providers, providersLoaded, refineModels, availableBackends, blurb }) {+ return (+ <div className="space-y-3">+ <div>+ <div className="text-[10px] uppercase tracking-wider text-gray-500 mb-1">+ Image backend+ </div>+ <BackendChipStrip+ availableBackends={availableBackends}+ value={cfg.imageMode}+ onChange={(id) => update({ imageMode: id, ...(id !== 'local' ? { imageModelId: null } : {}) })}+ size="sm"+ ariaLabel={`${stageLabel} image backend`}+ titlePrefix="Render images via"+ />+ <p className="text-[10px] text-gray-500 mt-1">{blurb}</p>+ {cfg.imageMode === 'codex' && !systemSettings?.imageGen?.codex?.enabled && (+ <p className="text-[10px] text-port-warning mt-1">+ Codex Imagegen is disabled in Settings — renders will fall back to local diffusion.+ </p>+ )}+ </div>++ {cfg.imageMode === 'local' && (+ <div>+ <div className="text-[10px] uppercase tracking-wider text-gray-500 mb-1">+ Local image model+ </div>+ <select+ value={cfg.imageModelId || ''}+ onChange={(e) => update({ imageModelId: e.target.value || null })}+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-xs"+ >+ <option value="">Default ({imageModels.find((m) => m.default)?.name || imageModels[0]?.name || 'flux-1'})</option>+ {imageModels.map((m) => (+ <option key={m.id} value={m.id}>{m.name || m.id}</option>+ ))}+ </select>+ </div>+ )}++ <div>+ <div className="text-[10px] uppercase tracking-wider text-gray-500 mb-1">+ AI refine LLM+ </div>+ {providersLoaded && providers.length === 0 ? (+ <p className="text-[10px] text-gray-600 italic">+ No enabled providers — add one in Settings → AI Providers.+ </p>+ ) : (+ <>+ <div className="flex items-center gap-2 mb-1">+ <label className="text-[10px] text-gray-500 inline-flex items-center gap-1">+ <input+ type="checkbox"+ checked={!!cfg.refineProvider}+ disabled={!providersLoaded || providers.length === 0}+ title={!providersLoaded ? 'Loading providers…' : undefined}+ onChange={(e) => {+ if (e.target.checked) {+ const first = providers[0];+ update({+ refineProvider: first.id,+ refineModel: first.defaultModel || filterSelectableModels(first.models)[0] || '',+ });+ } else {+ update({ refineProvider: null, refineModel: null });+ }+ }}+ />+ Override default+ </label>+ </div>+ {cfg.refineProvider && (+ <ProviderModelSelector+ providers={providers}+ selectedProviderId={cfg.refineProvider}+ selectedModel={cfg.refineModel || ''}+ availableModels={refineModels}+ onProviderChange={(id) => {+ const p = providers.find((pr) => pr.id === id);+ update({+ refineProvider: id,+ refineModel: p?.defaultModel || filterSelectableModels(p?.models)[0] || '',+ });+ }}+ onModelChange={(model) => update({ refineModel: model })}+ compact+ />+ )}+ <p className="text-[10px] text-gray-500 mt-1">+ Used by the <strong className="text-gray-400">AI: refine</strong> button to rewrite panel/scene descriptions into richer image-gen prompts.+ </p>+ </>+ )}+ </div>+ </div>+ );+}++// Internal hook: all the shared loads (settings / image models / providers)+// plus the derived state every flavor of the panel needs. Returns the+// "props bundle" callers feed straight into <VisualGenSettingsBody>.+// `refreshOnMount` — when true, busts the module-level cache on each mount so+// the panel always fetches fresh settings/providers. Used by VisualGenSettingsPanel+// (mounted inside a Modal that is freshly constructed each open) so users who+// enable Codex or swap providers in Settings see the change immediately on the+// next modal open without reloading the SPA.+function useVisualGenSettings(value, stageLabel, refreshOnMount = false) {+ const cfg = { ...DEFAULT_CONFIG, ...(value || {}) };+ const [systemSettings, setSystemSettings] = useState(null);+ const [imageModels, setImageModels] = useState([]);+ const [providers, setProviders] = useState([]);+ const [providersLoaded, setProvidersLoaded] = useState(false);++ useEffect(() => {+ let cancelled = false;+ if (refreshOnMount) lookupCache = null;+ loadLookups().then(([s, modelList, providerResp]) => {+ if (cancelled) return;+ setSystemSettings(s);+ setImageModels(Array.isArray(modelList) ? modelList : []);+ setProviders((providerResp?.providers || []).filter((p) => p.enabled));+ setProvidersLoaded(true);+ });+ return () => { cancelled = true; };+ }, []);++ const baseBackends = useMemo(+ () => deriveAvailableBackends(systemSettings, { excludeExternal: true }),+ [systemSettings],+ );+ const availableBackends = useMemo(() => [AUTO_BACKEND, ...baseBackends], [baseBackends]);++ const refineModels = useMemo(() => {+ const p = providers.find((pr) => pr.id === cfg.refineProvider);+ return p ? filterSelectableModels(p.models || [p.defaultModel]) : [];+ }, [providers, cfg.refineProvider]);++ const autoResolution = resolveAutoLabel(systemSettings);+ const summary = summarizeMode(cfg, autoResolution);+ const blurb = cfg.imageMode === 'auto'+ ? `Auto follows the server default — currently ${autoResolution}.`+ : MODE_BLURB[cfg.imageMode];++ return {+ cfg, stageLabel, systemSettings, imageModels, providers, providersLoaded,+ availableBackends, refineModels, summary, blurb,+ };+}++/**+ * Chromeless settings panel — just the controls, no accordion wrapper.+ * Use when embedding inside a Modal or other parent-owned container.+ */+export function VisualGenSettingsPanel({ value, onChange, stageLabel = 'Visual stage' }) {+ const bag = useVisualGenSettings(value, stageLabel, true);+ const update = (patch) => onChange?.({ ...bag.cfg, ...patch });+ return <VisualGenSettingsBody {...bag} update={update} />;+}++/**+ * Summarize the current genConfig in a short line ("Auto → codex",+ * "Pinned: local / flux-1", etc). Exported so a settings trigger button+ * elsewhere can show the same one-liner as the legacy accordion header.+ */+export function summarizeGenConfig(cfg) {+ const merged = { ...DEFAULT_CONFIG, ...(cfg || {}) };+ // We don't have systemSettings on the synchronous call path — the+ // accordion shows "Auto → codex/local"; without the lookups we surface a+ // generic "Auto" instead and let the modal body fill in detail.+ return summarizeMode(merged, 'server default');+}++export default function VisualGenSettings({ value, onChange, stageLabel = 'Visual stage' }) {+ const bag = useVisualGenSettings(value, stageLabel);+ const update = (patch) => onChange?.({ ...bag.cfg, ...patch });+ const [open, setOpen] = useState(false);++ return (+ <div className="rounded-lg border border-port-border bg-port-card">+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ className="w-full flex items-center gap-2 px-3 py-2 text-left text-xs text-gray-300 hover:text-white"+ >+ {open ? <ChevronDown size={14} /> : <ChevronRight size={14} />}+ <SlidersHorizontal size={14} className="text-gray-500" />+ <span className="font-medium">Generation settings</span>+ <span className="ml-2 text-[10px] text-gray-500">{bag.summary}</span>+ </button>++ {open && (+ <div className="px-3 pb-3 pt-1 border-t border-port-border">+ <VisualGenSettingsBody {...bag} update={update} />+ </div>+ )}+ </div>+ );+}++/**+ * Helper: turn a stage's persisted genConfig into the option overrides+ * that the visual-stage generate APIs expect. Skips fields when the+ * config is set to "auto"/null so the server falls back to its resolver.+ */+export function genConfigToImageOptions(cfg) {+ if (!cfg) return {};+ const out = {};+ if (cfg.imageMode && cfg.imageMode !== 'auto') out.mode = cfg.imageMode;+ if (cfg.imageMode === 'local' && cfg.imageModelId) out.modelId = cfg.imageModelId;+ return out;+}++export function genConfigToRefineOptions(cfg) {+ if (!cfg) return {};+ const out = {};+ if (cfg.refineProvider) out.providerId = cfg.refineProvider;+ if (cfg.refineModel) out.model = cfg.refineModel;+ return out;+}diff --git a/client/src/lib/issueLength.js b/client/src/lib/issueLength.jsnew file mode 100644index 0000000000..672858d765--- /dev/null+++ b/client/src/lib/issueLength.js@@ -0,0 +1,68 @@+/**+ * Client-side mirror of `server/lib/issueLength.js` — kept in lock-step+ * with the server table. The client only needs the labels + headline+ * numbers (pages / minutes) for the header dropdown; the full prose-word+ * / beat-count derivation lives server-side where the prompts render.+ */++export const LENGTH_PROFILES = Object.freeze({+ teaser: Object.freeze({+ label: 'Teaser',+ description: 'Short promo issue / web teaser.',+ pageTarget: 8,+ minutesTarget: 10,+ }),+ standard: Object.freeze({+ label: 'Standard',+ description: 'Standard floppy / half-hour episode (default).',+ pageTarget: 22,+ minutesTarget: 24,+ }),+ extended: Object.freeze({+ label: 'Extended',+ description: 'Premiere / longer special.',+ pageTarget: 32,+ minutesTarget: 36,+ }),+ finale: Object.freeze({+ label: 'Finale',+ description: 'Season / series finale or annual.',+ pageTarget: 44,+ minutesTarget: 48,+ }),+});++export const DEFAULT_LENGTH_PROFILE = 'standard';++// Working bounds for custom overrides — mirrored from `server/lib/issueLength.js`+// (CUSTOM_PAGE_MIN / CUSTOM_PAGE_MAX / CUSTOM_MINUTE_MIN / CUSTOM_MINUTE_MAX).+// The client cannot import from the server, so these values are duplicated here+// manually. If you change the range on the server side, update this file too.+export const CUSTOM_PAGE_MIN = 4;+export const CUSTOM_PAGE_MAX = 120;+export const CUSTOM_MINUTE_MIN = 4;+export const CUSTOM_MINUTE_MAX = 240;++// Clamp + round + fallback. Returns `null` for non-finite input so callers+// can distinguish "user cleared the field" from "user typed nonsense".+// Empty string is treated as absent (not coerced to 0) so clearing a Custom+// number input returns null rather than being clamped up to the minimum.+export function clampInt(raw, min, max) {+ if (raw === '' || raw === null || raw === undefined) return null;+ const n = Number(raw);+ if (!Number.isFinite(n)) return null;+ return Math.max(min, Math.min(max, Math.round(n)));+}++// Render a one-line summary for the header chip, e.g.+// "Standard · 22pg / 24min" or "Custom · 18pg / 20min".+export function summarizeLengthProfile(issue) {+ const profile = issue?.lengthProfile || DEFAULT_LENGTH_PROFILE;+ if (profile === 'custom') {+ const pages = Number.isFinite(issue?.pageTarget) ? issue.pageTarget : LENGTH_PROFILES.standard.pageTarget;+ const minutes = Number.isFinite(issue?.minutesTarget) ? issue.minutesTarget : LENGTH_PROFILES.standard.minutesTarget;+ return { label: 'Custom', detail: `${pages}pg / ${minutes}min` };+ }+ const preset = LENGTH_PROFILES[profile] || LENGTH_PROFILES.standard;+ return { label: preset.label, detail: `${preset.pageTarget}pg / ${preset.minutesTarget}min` };+}diff --git a/client/src/pages/PipelineIssue.jsx b/client/src/pages/PipelineIssue.jsxindex 98d2c3dc89..51ad455d49 100644--- a/client/src/pages/PipelineIssue.jsx+++ b/client/src/pages/PipelineIssue.jsx@@ -10,11 +10,12 @@ 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, Users,+ LayoutGrid, Image as ImageIcon, Clapperboard, Users, Settings,} from 'lucide-react';import toast from '../components/ui/Toast';+import Modal from '../components/ui/Modal';import {- getPipelineIssue, getPipelineSeries,+ getPipelineIssue, getPipelineSeries, updatePipelineIssue,startPipelineAutoRunText, cancelPipelineAutoRunText,PIPELINE_STAGES, PIPELINE_TAB_STAGES, PIPELINE_STAGE_LABELS,} from '../services/api';@@ -28,6 +29,15 @@ import ComicPagesStage from '../components/pipeline/stages/ComicPagesStage';import StoryboardsStage from '../components/pipeline/stages/StoryboardsStage';import EpisodeVideoStage from '../components/pipeline/stages/EpisodeVideoStage';import SeriesLlmPicker from '../components/pipeline/SeriesLlmPicker';+import LengthProfilePicker from '../components/pipeline/LengthProfilePicker';+import { VisualGenSettingsPanel } from '../components/pipeline/stages/VisualGenSettings';++// Stages that surface a header-level settings gear. The Comic editor+// (`comicScript`) owns its own image-gen drawer inside ComicScriptStage,+// so it stays off this list — only Storyboards needs the shared modal.+const VISUAL_STAGE_LABELS = {+ storyboards: 'Storyboards',+};const STAGE_ICONS = {idea: Lightbulb,@@ -73,6 +83,11 @@ export default function PipelineIssue() {const [loading, setLoading] = useState(true);const [autoRunStarting, setAutoRunStarting] = useState(false);const [autoRunActive, setAutoRunActive] = useState(false);+ const [settingsOpen, setSettingsOpen] = useState(false);+ const [lengthProfileSaving, setLengthProfileSaving] = useState(false);+ // Close the settings modal whenever the active stage changes so it doesn't+ // reopen unexpectedly when the user returns to a previously-visited stage.+ useEffect(() => { setSettingsOpen(false); }, [stageId]);const { latest, frames } = usePipelineAutoRunProgress(issueId, { enabled: autoRunActive });useEffect(() => {@@ -130,6 +145,30 @@ export default function PipelineIssue() {});};+ // Persist length-profile changes from the header picker. The patch is a+ // flat issue-level patch (no `stages.*` envelope) so the issue sanitizer+ // routes lengthProfile / pageTarget / minutesTarget straight onto the record.+ const handleLengthChange = async (patch) => {+ setLengthProfileSaving(true);+ updatePipelineIssue(issueId, patch)+ .then((updated) => { if (updated) setIssue(updated); })+ .catch((err) => { toast.error(err.message || 'Save failed'); })+ .finally(() => setLengthProfileSaving(false));+ };++ // Persist genConfig changes from the header settings modal. The active+ // visual stage owns the config record (we keep per-stage genConfig so a+ // user can pin "codex" for comicPages but "local" for storyboards).+ const handleGenConfigChange = async (next) => {+ const updated = await updatePipelineIssue(issueId, {+ stages: { [stageId]: { genConfig: next } },+ }).catch((err) => {+ toast.error(err.message || 'Save failed');+ return null;+ });+ if (updated) setIssue(updated);+ };+const handleStageUpdate = (id, updatedStage, updatedIssue) => {if (updatedIssue) {setIssue(updatedIssue);@@ -152,6 +191,7 @@ export default function PipelineIssue() {if (!issue) return null;const StageComponent = STAGE_COMPONENTS[stageId];+ const isVisualStage = stageId in VISUAL_STAGE_LABELS;return (<div className="flex flex-col h-full">@@ -176,6 +216,11 @@ export default function PipelineIssue() {<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 flex-wrap">+ <LengthProfilePicker+ issue={issue}+ onChange={handleLengthChange}+ disabled={autoRunStarting || autoRunActive || lengthProfileSaving}+ />{series ? (<SeriesLlmPickerseries={series}@@ -195,9 +240,9 @@ export default function PipelineIssue() {<buttontype="button"onClick={() => handleAutoRun({})}- disabled={autoRunStarting || autoRunActive}+ disabled={autoRunStarting || autoRunActive || lengthProfileSaving}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"+ title={lengthProfileSaving ? 'Saving length profile…' : 'Run idea → prose → (comic script + TV script) end to end'}>{autoRunStarting || autoRunActive ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}Auto-run text@@ -205,13 +250,24 @@ export default function PipelineIssue() {<buttontype="button"onClick={() => handleAutoRun({ includeVideo: true })}- disabled={autoRunStarting || autoRunActive}+ disabled={autoRunStarting || autoRunActive || lengthProfileSaving}className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-card border border-port-accent/40 text-white text-sm font-medium disabled:opacity-50 hover:bg-port-accent/10"- title="Run text stages and then kick off episode video via Creative Director (burns GPU)"+ title={lengthProfileSaving ? 'Saving length profile…' : 'Run text stages and then kick off episode video via Creative Director (burns GPU)'}>{autoRunStarting || autoRunActive ? <Loader2 size={14} className="animate-spin" /> : <Clapperboard size={14} />}Run everything (incl. video)</button>+ {isVisualStage && (+ <button+ type="button"+ onClick={() => setSettingsOpen(true)}+ className="inline-flex items-center justify-center p-2 rounded-lg bg-port-card border border-port-border text-gray-300 hover:text-white hover:border-port-accent/50"+ title={`${VISUAL_STAGE_LABELS[stageId]} generation settings`}+ aria-label={`${VISUAL_STAGE_LABELS[stageId]} generation settings`}+ >+ <Settings size={16} />+ </button>+ )}</div></div>@@ -266,6 +322,32 @@ export default function PipelineIssue() {</details>) : null}</div>++ {/* Per-stage generation settings — only available on visual stages. */}+ {isVisualStage && (+ <Modal open={settingsOpen} onClose={() => setSettingsOpen(false)} size="lg" ariaLabel="Generation settings">+ <div className="bg-port-card border border-port-border rounded-lg p-5 space-y-4">+ <div className="flex items-center justify-between">+ <h2 className="text-base font-semibold text-white">+ {VISUAL_STAGE_LABELS[stageId]} — Generation settings+ </h2>+ <button+ type="button"+ onClick={() => setSettingsOpen(false)}+ className="p-1 text-gray-400 hover:text-white"+ aria-label="Close"+ >+ <X size={16} />+ </button>+ </div>+ <VisualGenSettingsPanel+ value={issue.stages?.[stageId]?.genConfig || null}+ onChange={handleGenConfigChange}+ stageLabel={VISUAL_STAGE_LABELS[stageId]}+ />+ </div>+ </Modal>+ )}</div>);}diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex 2c1ba5a73b..f51a45e984 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -151,6 +151,17 @@ export const generatePipelineComicPage = (issueId, pageIndex, opts = {}) =>body: JSON.stringify(opts),});+// Render the issue's front cover. Pass `coverScript` to render a not-yet-+// saved concept (the route persists it back to stages.comicPages.cover so+// the next reload reflects what was rendered). Server folds in series+// name, issue number, issue title, and style notes — caller only owns the+// cover-concept text. Returns { jobId, mode, prompt, cover, issue, stage }.+export const generatePipelineComicCover = (issueId, opts = {}) =>+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/comicPages/cover/render`, {+ method: 'POST',+ body: JSON.stringify(opts),+ });+// Patch one comic page's raw markdown — the server re-parses panels from the// edited rawText so subsequent renders still get a structured prompt.// Returns { issue, stage, page }.diff --git a/data.sample/prompts/stages/pipeline-comic-script.md b/data.sample/prompts/stages/pipeline-comic-script.mdindex a077679422..0835185b0d 100644--- a/data.sample/prompts/stages/pipeline-comic-script.md+++ b/data.sample/prompts/stages/pipeline-comic-script.md@@ -17,6 +17,7 @@ You are a comics writer turning a prose draft into a publishable comic-book issu- **Number:** {{issue.number}}- **Title:** {{issue.title}}+- **Length profile:** {{lengthTargets.profile}} — target {{lengthTargets.pageTarget}}-page issue## Prose source@@ -26,28 +27,38 @@ You are a comics writer turning a prose draft into a publishable comic-book issu## Output format-Return a markdown document with this exact structure:+Return a markdown document with this exact structure. **Do not bold the field labels and do not put `###` in front of `Panel N`** — keep the formatting minimal so the image generator can read the panel content cleanly.```# Issue {{issue.number}} — <Title>+## Cover concept++<2–4 sentence cover-art concept: the single hero image that should land on+the front cover. Focus on subject, framing, mood, and a striking visual+detail. The cover renderer composes the masthead + issue-number tag+itself, so do NOT describe text or typography here — just the scene.>+## 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:**+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)">+SFX: <sound effect words, or "(none)">-### Panel 2+Panel 2...```## Rules-- Target a standard **22-page** comic issue (100–140 panels total). Plan **5–7 panels per page**, with rare 1-panel splash pages for big reveals. If the prose draft is short, expand the action — pace beats across more panels, add reaction shots, environmental establishing panels, and visual transitions — rather than cutting page count. Only deviate from 22 pages if the issue genuinely demands it (e.g. a designated double-sized special).+- **Target a {{lengthTargets.pageTarget}}-page single issue.** Pace the prose source across exactly {{lengthTargets.pageTarget}} pages — inflate quiet beats with reaction shots, environmental panels, and silent panels if the prose is thin; compress dense action across multiple pages with panel-to-panel motion if it is rich. Do not pad for padding's sake, but do not skip pages either.+- Plan **4–6 panels per page on average**, with occasional 1-panel splashes for big reveals, double-page spreads (`Panel 1 (DPS)`) for major action, and the rare 7–8 panel grid for fast cuts.+- **Strong opening (Saga-style):** page 1 lands the reader inside a specific, sensory moment — a striking image plus one line of voice-over or arresting dialogue. No expository "previously on" walls. The first panel should be a hook the reader cannot put down. Page 1 is often a splash or near-splash.+- **Cliffhanger / lead-in ending:** the final page (and ideally the final panel) must do one of: (a) reveal something that flips what we thought we knew, (b) deliver a cliffhanger — character in peril, decision unmade, antagonist arriving — or (c) plant the seed for the next issue with a clear "to be continued" pull. Never end on resolution alone.- 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.@@ -55,6 +66,6 @@ Return a markdown document with this exact structure:- 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.+- Vary page rhythm: don't let every page be the same panel count. Use page turns deliberately — what the reader sees when they turn from an odd page to the next even page is one of the strongest tools you have. Land big reveals on page-turn moments.-Return ONLY the script. No preamble, no commentary.+Return ONLY the script. No preamble, no commentary. The output MUST start with the `# Issue {{issue.number}} — <Title>` heading, followed immediately by the `## Cover concept` section, then exactly {{lengthTargets.pageTarget}} `## Page N` headers numbered Page 1 through Page {{lengthTargets.pageTarget}}.diff --git a/data.sample/prompts/stages/pipeline-idea-expansion.md b/data.sample/prompts/stages/pipeline-idea-expansion.mdindex 485b750197..8f91e9929b 100644--- a/data.sample/prompts/stages/pipeline-idea-expansion.md+++ b/data.sample/prompts/stages/pipeline-idea-expansion.md@@ -24,6 +24,7 @@ You are a story consultant who turns a rough seed idea into a tight beat sheet f- **Number:** {{issue.number}}- **Working title:** {{issue.title}}+- **Length profile:** {{lengthTargets.profile}} — target {{lengthTargets.pageTarget}}-page comic / {{lengthTargets.minutesTarget}}-minute episode## Rough seed from the user@@ -38,7 +39,7 @@ 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.+4. **`## Beat sheet`** — **{{lengthTargets.beatsMin}}–{{lengthTargets.beatsMax}} beats** numbered as a markdown list. Each beat is one sentence describing a concrete dramatic event. Cover **hook (Saga-style opening — a single arresting image or moment, not exposition) → setup → rising action → midpoint reversal → second-half escalation → climax → cliffhanger / lead-in to the next issue.** This beat sheet feeds a {{lengthTargets.proseWordsMin}}–{{lengthTargets.proseWordsMax}} word prose draft, which feeds a {{lengthTargets.pageTarget}}-page comic script — too few beats and the downstream stages have nothing to pace against. The final beat MUST be a cliffhanger, reveal, or strong lead-in to the next issue, not a tidy resolution.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` (OPTIONAL — usually omit)** — ONLY include this section when something fundamentally cannot be decided without user input (e.g. the seed asks the writer to choose between two specific named entities, or references off-canvas information only the user knows). Do NOT use this section for choices you could make yourself by leaning on the series bible. If every beat is committed, omit the section entirely.diff --git a/data.sample/prompts/stages/pipeline-prose.md b/data.sample/prompts/stages/pipeline-prose.mdindex ca78a6c44e..b6687f79c2 100644--- a/data.sample/prompts/stages/pipeline-prose.md+++ b/data.sample/prompts/stages/pipeline-prose.md@@ -19,6 +19,7 @@ You are a short-fiction author drafting one issue / episode of an ongoing series- **Number:** {{issue.number}}- **Title:** {{issue.title}}+- **Length profile:** {{lengthTargets.profile}} — target {{lengthTargets.pageTarget}} comic pages / {{lengthTargets.minutesTarget}}-minute episode## Beat sheet (from the idea stage)@@ -28,13 +29,13 @@ You are a short-fiction author drafting one issue / episode of an ongoing series## 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.+A self-contained short-story draft for this issue, **{{lengthTargets.proseWordsMin}}–{{lengthTargets.proseWordsMax}} words** (sized to feed a {{lengthTargets.pageTarget}}-page comic adaptation downstream — too thin and the script writer has to invent filler beats). 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. Plan for natural page-turn beats — this issue should have **{{lengthTargets.beatsMin}}–{{lengthTargets.beatsMax}} scenes**.- Write in **present tense** throughout — every action, every beat. Present tense reads "she opens the door," not "she opened the door." This is non-negotiable: the downstream comic and TV adaptations both work in present tense, and matching tense upstream keeps the visual beats translatable. Use third-person POV unless the series notes specify otherwise.-- Open *in scene*, not on exposition.+- **Open in a hook (Saga-style):** start in a specific sensory moment — a striking image, an arresting action, or a single line of voice-over that lands the reader inside the story. No "previously on" exposition. The opening paragraph is the first thing the comic page-1 splash will render, so make it visually loaded.- 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.+- Hit every beat from the beat sheet, but feel free to inflate one beat into multiple scenes if it has more weight. With {{lengthTargets.pageTarget}} pages downstream, lean toward *more* dramatized texture per beat rather than racing to the climax.+- **Land the ending on a cliffhanger or strong lead-in to the next issue** — a reveal that flips what the reader thought, a character in unresolved peril, or an antagonist's arrival. The last paragraph is what the comic's final-page panel will render, so make it visually decisive. Resolution-only endings are not acceptable; serialized comics need pull.- 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-season-episodes.md b/data.sample/prompts/stages/pipeline-season-episodes.mdindex b450256f85..fb48729260 100644--- a/data.sample/prompts/stages/pipeline-season-episodes.md+++ b/data.sample/prompts/stages/pipeline-season-episodes.md@@ -63,6 +63,13 @@ For each episode write:- **`synopsis`** — 2–3 sentences. What *happens* in this episode at the arc level. Don't write scene blocking — keep it at the level a season planner needs.- **`primaryCharacters`** — array of CAPS character names from the bible who carry the episode. Usually 1–3; never empty for a main character series.- **`arcRole`** — single token describing the episode's structural job in this season. Pick one of: `pilot` / `complication` / `midpoint` / `b-plot` / `all-is-lost` / `finale`. Used downstream to verify the season has balanced shape.+- **`lengthProfile`** — single token sizing this episode for downstream prose / script / video generation. Pick one of:+ - `teaser` — promo / cold-open / mini-issue (~8 pages comic / ~10 min episode). Use sparingly, mostly for B-plot or anthology beats.+ - `standard` — the working default (~22 pages / ~24 min). Use for most episodes.+ - `extended` — premiere / set-piece episodes (~32 pages / ~36 min). Use for pilots that have to establish a lot of world, or mid-season turning points that earn extra runtime.+ - `finale` — season climax (~44 pages / ~48 min). Reserve for the actual `arcRole: 'finale'` episode (and occasionally `all-is-lost` if the budget allows). Don't apply to every episode — finale-length used everywhere becomes meaningless.++ Default to `standard` when nothing argues for a different size.## Output contract@@ -77,7 +84,8 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c"logline": "string","synopsis": "string","primaryCharacters": ["NAME", "..."],- "arcRole": "pilot"+ "arcRole": "pilot",+ "lengthProfile": "standard"}]}diff --git a/data.sample/prompts/stages/pipeline-tv-script.md b/data.sample/prompts/stages/pipeline-tv-script.mdindex 233feb9b13..df1bd368ed 100644--- a/data.sample/prompts/stages/pipeline-tv-script.md+++ b/data.sample/prompts/stages/pipeline-tv-script.md@@ -17,6 +17,7 @@ You are a TV writer adapting a prose draft into a single-episode teleplay in sta- **Number:** {{issue.number}}- **Title:** {{issue.title}}+- **Length profile:** {{lengthTargets.profile}} — target {{lengthTargets.minutesTarget}}-minute episode## Prose source@@ -59,14 +60,16 @@ CUT TO:## 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.)+- **Target a {{lengthTargets.minutesTarget}}-minute episode.** Use the **TEASER → ACT ONE → ACT TWO → ACT THREE → TAG** structure (collapse to TEASER → ONE ACT for very short episodes, or expand to TEASER → ACT ONE → ACT TWO → ACT THREE → ACT FOUR → TAG for long specials). One script page ≈ one minute of screen time, so aim for **~{{lengthTargets.minutesTarget}} pages of formatted teleplay**.+- **Strong opening (Saga-style cold open):** the TEASER lands the viewer inside a specific sensory moment in the first 30–60 seconds — a striking image, an arresting line, an unanswered question. No exposition voice-over walls, no "previously on" recaps. The opening beat is the hook that earns the rest of the episode.+- **Cliffhanger / lead-in ending:** the TAG (or final scene if no TAG) must do one of: (a) reveal something that recontextualizes the episode, (b) deliver a cliffhanger — a character in peril, a decision unmade, an antagonist arriving — or (c) plant the seed for the next episode with a clear next-episode pull. Never close on tidy resolution alone — serialized TV needs forward propulsion.- 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.+- Cover the same story beats as the prose, but free to add visual texture (establishing shots, silent reaction beats, B-story interludes) the prose only implied — you have {{lengthTargets.minutesTarget}} minutes of screen time, not {{lengthTargets.proseWordsMin}}–{{lengthTargets.proseWordsMax}} words of compressed text.+- **End every act with a button** — an image, a line, or a reveal that pulls the viewer past the act break. Act-outs are non-negotiable; they're where the audience decides whether to stick around.+- Vary scene length: rapid-fire montage sequences should sit next to one-location dialogue scenes that breathe. Don't let every scene be the same energy.Return ONLY the teleplay. No preamble, no commentary, no "FADE IN:" header unless the script genuinely opens cold.diff --git a/data/migrations/003-update-pipeline-stage-prompts.js b/data/migrations/003-update-pipeline-stage-prompts.jsnew file mode 100644index 0000000000..bcbd7107d8--- /dev/null+++ b/data/migrations/003-update-pipeline-stage-prompts.js@@ -0,0 +1,123 @@+/**+ * Update five pipeline stage prompt templates that were updated in the+ * "length profile" feature (feat/pipeline-genconfig-length-cover).+ *+ * The prompts now carry `{{lengthTargets.*}}` variables so the idea, prose,+ * comic-script, and TV-script stages scale their beat counts, word targets,+ * and page/minute targets with the per-issue length profile picker instead of+ * using the old hardcoded numbers.+ *+ * Strategy — "unmodified-only" update:+ * Each file is compared against the MD5 of the version that shipped before+ * this feature landed (the "old shipped" hash). If the file on disk still+ * matches that hash, the user hasn't customized it and we replace it with+ * the current data.sample version. If the hash diverges (customized), we+ * skip and warn so the user can merge manually.+ *+ * Idempotent — a re-run that finds the current data.sample hash on disk+ * is a no-op.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';+import { createHash } from 'crypto';++const md5 = (str) => {+ const normalized = str.replace(/\r\n/g, '\n').replace(/\r/g, '\n');+ return createHash('md5').update(normalized).digest('hex');+};++// MD5 hashes of the version shipped BEFORE the length-profile feature.+// Computed from git show <merge-base>:data.sample/prompts/stages/<file>.+// If the live file matches one of these, the user hasn't customized it.+const OLD_SHIPPED_MD5 = {+ 'pipeline-idea-expansion.md': 'aee25112b2c596f643b17c559b772c22',+ 'pipeline-prose.md': 'bfea5aeeb471aae9749baee765b473a7',+ 'pipeline-comic-script.md': '40e5fdc1a1e68a7419b7dad936366c1a',+ 'pipeline-tv-script.md': '3f6fecc25573ed054b47db392250034a',+ 'pipeline-season-episodes.md':'6e349ad26bed8a0ccb042571f03f03eb',+};++// MD5 hashes of the updated versions in data.sample (what this migration+// copies in). Used to detect "already up to date" on re-runs.+const NEW_SHIPPED_MD5 = {+ 'pipeline-idea-expansion.md': '41facefbc0c0549d456bef9111f95ab9',+ 'pipeline-prose.md': '30ac30ec2b9d3e2a9eb869c181732cc6',+ 'pipeline-comic-script.md': 'beab031951859ca13579cdb9c4dbe769',+ 'pipeline-tv-script.md': '376f779f4687b598f1c92ca4e770fd5a',+ 'pipeline-season-episodes.md':'c4928e2a5f833358116b29d2d669888d',+};++export default {+ async up({ rootDir }) {+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');+ const sampleDir = join(rootDir, 'data.sample', 'prompts', 'stages');++ let updated = 0;+ let alreadyCurrent = 0;+ let skipped = 0;++ for (const filename of Object.keys(OLD_SHIPPED_MD5)) {+ const dataPath = join(stagesDir, filename);+ const samplePath = join(sampleDir, filename);++ const existing = await readFile(dataPath, 'utf-8').catch((err) => {+ if (err.code !== 'ENOENT') throw err;+ return null;+ });++ if (existing === null) {+ // File missing from data/ — setup-data.js will copy it on next run;+ // nothing for this migration to do.+ console.log(`📄 pipeline stage prompt ${filename}: not present in data/, will be created by setup-data.js`);+ continue;+ }++ const existingMd5 = md5(existing);++ if (existingMd5 === NEW_SHIPPED_MD5[filename]) {+ // Already at the new version — idempotent no-op.+ alreadyCurrent++;+ continue;+ }++ if (existingMd5 !== OLD_SHIPPED_MD5[filename]) {+ // Diverged from the old shipped version — user has customized this file.+ // Warn and skip to avoid clobbering their edits.+ console.warn(+ `⚠️ pipeline stage prompt ${filename} has been customized — skipping auto-update.\n` ++ ` To apply the length-profile variables manually, diff:\n` ++ ` data.sample/prompts/stages/${filename}\n` ++ ` against your current:\n` ++ ` data/prompts/stages/${filename}\n` ++ ` and merge the {{lengthTargets.*}} template variables.`,+ );+ skipped++;+ continue;+ }++ // File matches the old shipped version — safe to replace.+ const sampleContent = await readFile(samplePath, 'utf-8');+ await writeFile(dataPath, sampleContent);+ console.log(`✅ updated pipeline stage prompt: ${filename}`);+ updated++;+ }++ if (updated > 0) {+ console.log(`📝 pipeline stage prompt migration: ${updated} updated, ${alreadyCurrent} already current, ${skipped} skipped (customized)`);+ } else if (skipped > 0) {+ console.log(`📝 pipeline stage prompt migration: all files either current or customized (${skipped} skipped)`);+ } else {+ console.log(`📝 pipeline stage prompt migration: all files already up to date`);+ }++ if (skipped > 0) {+ console.warn(+ `\n⚠️ ${skipped} prompt(s) could not be auto-updated because they were customized.\n` ++ ` The length profile picker UI will work, but those prompts won't use\n` ++ ` {{lengthTargets.*}} variables until you merge them manually.\n` ++ ` See data.sample/prompts/stages/ for the updated templates.`,+ );+ }+ },+};diff --git a/scripts/setup-data.js b/scripts/setup-data.jsindex 9e233859fc..7021ecee1a 100644--- a/scripts/setup-data.js+++ b/scripts/setup-data.js@@ -1,5 +1,6 @@#!/usr/bin/env nodeimport { existsSync, mkdirSync, cpSync, readdirSync, statSync, readFileSync, writeFileSync } from 'fs';+import { createHash } from 'crypto';import { dirname, join } from 'path';import { fileURLToPath } from 'url';@@ -109,3 +110,78 @@ if (!existsSync(migrationsDir)) {console.log('📁 Creating missing directory: migrations');mkdirSync(migrationsDir, { recursive: true });}++// Drift detection — warn when a data.sample/prompts/stages/*.md differs from+// the installed data/prompts/stages/*.md copy. Only fires on existing installs+// (fresh installs already got a full copy above). Prompt templates drift when+// a PortOS update adds new template variables (e.g. {{lengthTargets.*}}) that+// existing installs won't pick up because setup-data.js only copies *missing*+// files.+//+// NOTE: only the five files managed by data/migrations/003-update-pipeline-stage-prompts.js+// are checked here — scanning all stage prompts would produce misleading warnings for+// prompts that have no migration counterpart (e.g. cd-evaluate.md, writers-room prompts).+//+// Hash constants mirror data/migrations/003-update-pipeline-stage-prompts.js so we+// can distinguish three cases without importing that module:+// • hash === OLD_SHIPPED_MD5 → auto-updatable, migration not yet applied+// • hash === NEW_SHIPPED_MD5 → already up to date (migration applied or manual merge done)+// • neither → customized, needs manual merge+// Update these whenever 003 (or a successor migration) changes the hashes.+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-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-season-episodes.md':'c4928e2a5f833358116b29d2d669888d',+};+const PIPELINE_LENGTH_PROMPTS = Object.keys(PIPELINE_LENGTH_OLD_MD5);++const sampleStagesDir = join(sampleDir, 'prompts', 'stages');+const dataStagesDir = join(dataDir, 'prompts', 'stages');+if (existsSync(sampleStagesDir) && existsSync(dataStagesDir)) {+ const md5 = (s) => {+ const normalized = s.replace(/\r\n/g, '\n').replace(/\r/g, '\n');+ return createHash('md5').update(normalized).digest('hex');+ };++ const autoUpdatable = [];+ const customized = [];++ for (const f of PIPELINE_LENGTH_PROMPTS) {+ const dataPath = join(dataStagesDir, f);+ if (!existsSync(dataPath)) continue; // missing files handled above+ const dataMd5 = md5(readFileSync(dataPath, 'utf8'));+ if (dataMd5 === PIPELINE_LENGTH_NEW_MD5[f]) continue; // already up to date+ if (dataMd5 === PIPELINE_LENGTH_OLD_MD5[f]) {+ autoUpdatable.push(f);+ } else {+ customized.push(f);+ }+ }++ if (autoUpdatable.length > 0) {+ console.warn(+ `\n⚠️ ${autoUpdatable.length} pipeline stage prompt(s) have a pending migration — run \`npm run migrations\` to auto-update:\n` ++ autoUpdatable.map(f => ` • ${f}`).join('\n') + '\n',+ );+ }++ if (customized.length > 0) {+ console.warn(+ `\n⚠️ ${customized.length} pipeline stage prompt(s) are customized and cannot be auto-updated.\n` ++ ` Manually merge the new template variables into each file:\n` ++ customized.map(f =>+ ` • data/prompts/stages/${f}\n` ++ ` Compare with: data.sample/prompts/stages/${f}`,+ ).join('\n') + '\n',+ );+ }+}diff --git a/server/lib/comicScriptParser.js b/server/lib/comicScriptParser.jsindex b30969406e..b035be4f57 100644--- a/server/lib/comicScriptParser.js+++ b/server/lib/comicScriptParser.js@@ -2,21 +2,40 @@* Pure parser for the Marvel/DC-format comic script the pipeline-comic-script* stage produces (see data.sample/prompts/stages/pipeline-comic-script.md —* data/ is gitignored; data.sample/ is the authoritative template, copied- * into data/ at setup time). Splits- * the markdown into a structured `{ pages: [{ panels: [...] }] }` shape so- * the comicPages stage UI can drop the LLM-authored panel descriptions+ * into data/ at setup time). Splits the markdown into a structured+ * `{ coverConcept, pages: [{ rawText, panels: [...] }] }` shape so the+ * comicPages stage UI can drop the LLM-authored panel descriptions* directly into image-gen prompts without a second round-trip.*- * Strict-but-tolerant: requires `## Page N` / `### Panel N` headers, then- * each panel's `**Description:** ...`, `**Caption:** ...`, `**Dialogue:** ...`,- * `**SFX:** ...` blocks per the template. "(none)" / empty values normalize- * to `''` for caption/sfx and `[]` for dialogue (never null) so downstream- * template renderers don't need null-guards. Unexpected text between panels- * is ignored.+ * Strict-but-tolerant. Page headers are always `## Page N`. Panel headers+ * accept both the legacy `### Panel N` and the simpler plain `Panel N`+ * form. Field labels accept both `**Description:** ...` and the plain+ * `Description: ...` form for an allowlist of fields. "(none)" / empty+ * values normalize to `''` for caption/sfx and `[]` for dialogue (never+ * null) so downstream template renderers don't need null-guards.+ * Unexpected text between panels is ignored.*/const PAGE_RE = /^##\s+Page\s+([\dIVX]+)\b/i;-const PANEL_RE = /^###\s+Panel\s+([\dIVX]+)\b/i;-const FIELD_RE = /^\*\*([A-Za-z][\w ]*?)\s*:\*\*\s*(.*)$/;+// `## Cover concept` — the optional cover-art section the comic-script+// template emits before the first `## Page 1` header. Also accepts the+// short `## Cover` form so a hand-edited script doesn't have to be exact.+const COVER_RE = /^##\s+Cover(?:\s+concept)?\b/i;+// Any `##` heading other than Page / Cover ends an in-progress cover block+// (e.g. a stray `## Notes` section).+const ANY_H2_RE = /^##\s+/;+// Plain `Panel N` is preferred by the current prompt template — `## Page N`+// is the deepest header level we use, so panels live below it without their+// own heading. Legacy `### Panel N` still accepted for back-compat.+//+// The line must be a standalone header — `Panel N` followed by nothing,+// an optional parenthetical (e.g. `Panel 1 (DPS)` for a double-page spread),+// or an optional trailing colon. Without the end-anchor a description line+// like "Panel 2 is offline on the monitor." starts a new panel and silently+// drops the rest of the prior panel's body.+const PANEL_RE = /^(?:###\s+)?Panel\s+([\dIVX]+)\s*(?:\([^)]+\))?\s*:?\s*$/i;+// Caption may repeat with a trailing index (`Caption 2:`); parsePanelBody+// folds those into one caption block.+const FIELD_RE = /^(?:\*\*)?(Description|Caption(?:\s+\d+)?|Dialogue|SFX)\s*:(?:\*\*)?\s*(.*)$/i;const NONE_RE = /^\(\s*none\s*\)$/i;const isNoneValue = (s) => !s || NONE_RE.test(s.trim());@@ -29,6 +48,10 @@ const PANEL_LIMITS = Object.freeze({DIALOGUE_LINE_MAX: 1000,DIALOGUE_ENTRIES_MAX: 24,SFX_MAX: 200,+ // Cap on the full per-page rawText the UI shows as a single editable+ // textarea. Wide enough for a maxed-out page (24 panels × ~1.5KB each)+ // with comfortable headroom.+ PAGE_SCRIPT_MAX: 40_000,});const trimTo = (s, max) => (typeof s === 'string' ? s.trim().slice(0, max) : '');@@ -41,8 +64,8 @@ const trimTo = (s, max) => (typeof s === 'string' ? s.trim().slice(0, max) : '')*/function parsePanelBody(lines) {// Field collector: accumulate consecutive non-header lines under whichever- // **Field:** label was most recently opened. Captions can repeat- // (`**Caption:**` then `**Caption 2:**`), so concat them with newlines.+ // field label was most recently opened. Captions can repeat+ // (`Caption:` then `Caption 2:`), so concat them with newlines.let activeField = null;const fields = {}; // canonical key → joined stringfor (const raw of lines) {@@ -91,14 +114,21 @@ function parsePanelBody(lines) {/*** @param {string} script markdown body from stages.comicScript.output- * @returns {{ pages: Array<{ rawText, panels: Array<{ description, caption, dialogue, sfx }> }> }}+ * @returns {{ coverConcept: string, pages: Array<{ rawText, panels: Array<{ description, caption, dialogue, sfx }> }> }}*- * `rawText` carries the markdown slice from the page's `## Page N` header to- * (not including) the next page header. The merged Comic tab uses this for- * per-page editing while panels remain the source for the image prompt.+ * - `coverConcept`: the body of an optional `## Cover concept` section that+ * appears before the first `## Page 1` header. Empty string when the+ * script doesn't include one (legacy scripts, hand-curated content).+ *+ * Each page carries:+ * - `rawText`: the markdown slice from the page's `## Page N` header to+ * (not including) the next page header. The merged Comic tab uses this+ * for per-page editing while panels remain the source for the image+ * prompt.+ * - `panels`: structured panel breakdown for image-gen prompts.*/export function parseComicScript(script) {- if (typeof script !== 'string' || !script.trim()) return { pages: [] };+ if (typeof script !== 'string' || !script.trim()) return { coverConcept: '', pages: [] };const lines = script.split(/\r?\n/);const pages = [];@@ -106,6 +136,10 @@ export function parseComicScript(script) {let currentRawLines = null;let currentPanelLines = null;let inAnyPanel = false;+ // Cover-concept accumulator. Active between a `## Cover concept` heading+ // and the next `##` heading (Page 1 or any other H2).+ let inCover = false;+ const coverLines = [];const flushPanel = () => {if (!inAnyPanel || !currentPage || !currentPanelLines) return;@@ -117,16 +151,35 @@ export function parseComicScript(script) {inAnyPanel = false;};+ const flushPageRawText = () => {+ if (!currentPage || !currentRawLines) return;+ const joined = currentRawLines.join('\n').replace(/^\s*\n+|\n+\s*$/g, '');+ currentPage.rawText = trimTo(joined, PANEL_LIMITS.PAGE_SCRIPT_MAX);+ };+for (const line of lines) {+ if (COVER_RE.test(line)) {+ inCover = true;+ continue;+ }if (PAGE_RE.test(line)) {+ inCover = false;flushPanel();- if (currentPage && currentRawLines) currentPage.rawText = currentRawLines.join('\n').trim();+ flushPageRawText();if (pages.length >= PANEL_LIMITS.PAGES_MAX) break;currentPage = { panels: [], rawText: '' };currentRawLines = [line];pages.push(currentPage);continue;}+ // Any *other* H2 also ends the cover block (e.g. a stray `## Notes`).+ if (inCover && ANY_H2_RE.test(line)) {+ inCover = false;+ }+ if (inCover) {+ coverLines.push(line);+ continue;+ }if (currentRawLines) currentRawLines.push(line);if (PANEL_RE.test(line)) {flushPanel();@@ -149,10 +202,14 @@ export function parseComicScript(script) {}}flushPanel();- if (currentPage && currentRawLines) currentPage.rawText = currentRawLines.join('\n').trim();+ flushPageRawText();const filtered = pages.filter((p) => p.panels.length > 0);- return { pages: filtered };+ const coverConcept = trimTo(+ coverLines.join('\n').replace(/^\s*\n+|\n+\s*$/g, ''),+ PANEL_LIMITS.PAGE_SCRIPT_MAX,+ );+ return { coverConcept, pages: filtered };}export { PANEL_LIMITS };diff --git a/server/lib/comicScriptParser.test.js b/server/lib/comicScriptParser.test.jsindex 443957b7e7..ca03952012 100644--- a/server/lib/comicScriptParser.test.js+++ b/server/lib/comicScriptParser.test.js@@ -59,9 +59,9 @@ describe('parseComicScript', () => {});it('handles empty / non-string input', () => {- expect(parseComicScript('')).toEqual({ pages: [] });- expect(parseComicScript(null)).toEqual({ pages: [] });- expect(parseComicScript('# Just a title')).toEqual({ pages: [] });+ expect(parseComicScript('')).toEqual({ coverConcept: '', pages: [] });+ expect(parseComicScript(null)).toEqual({ coverConcept: '', pages: [] });+ expect(parseComicScript('# Just a title')).toEqual({ coverConcept: '', pages: [] });});it('drops panels with no description and pages with no panels', () => {@@ -80,4 +80,147 @@ describe('parseComicScript', () => {expect(pages[0].panels).toHaveLength(1);expect(pages[0].panels[0].description).toMatch(/Real panel/);});++ it('extracts the `## Cover concept` section into coverConcept and keeps it out of page 1\'s rawText', () => {+ const script = `# Issue 1 — Bone Walker++## Cover concept++KESSA crouched on the rib spine at dawn, beetle in her cupped hand, the sky behind her bruised purple.++## Page 1++Panel 1+Description: Wide establishing shot inside the rib.+`;+ const { coverConcept, pages } = parseComicScript(script);+ expect(coverConcept).toMatch(/KESSA crouched on the rib spine/);+ expect(pages).toHaveLength(1);+ expect(pages[0].rawText).toMatch(/Wide establishing shot/);+ expect(pages[0].rawText).not.toMatch(/rib spine at dawn/);+ });++ it('also accepts the short `## Cover` heading', () => {+ const script = `## Cover++Brief cover sketch.++## Page 1++Panel 1+Description: A frame.+`;+ expect(parseComicScript(script).coverConcept).toMatch(/Brief cover sketch/);+ });++ it('terminates an in-progress cover block at any other H2 (e.g. `## Notes`)', () => {+ const script = `## Cover concept++The cover.++## Notes++Editorial scratchpad — should not appear in coverConcept.++## Page 1++Panel 1+Description: A frame.+`;+ const { coverConcept } = parseComicScript(script);+ expect(coverConcept).toMatch(/The cover\./);+ expect(coverConcept).not.toMatch(/Editorial scratchpad/);+ });++ it('returns empty coverConcept when the script has no Cover section', () => {+ const script = `## Page 1++Panel 1+Description: A frame.+`;+ expect(parseComicScript(script).coverConcept).toBe('');+ });++ it('captures the raw page body for each page', () => {+ const { pages } = parseComicScript(SAMPLE);+ expect(pages[0].rawText).toMatch(/### Panel 1/);+ expect(pages[0].rawText).toMatch(/Wide establishing shot/);+ expect(pages[0].rawText).toMatch(/### Panel 2/);+ expect(pages[0].rawText).toMatch(/KESSA:/);+ // The page-2 boundary should not leak into page-1's rawText.+ expect(pages[0].rawText).not.toMatch(/dead god/);+ });++ it('parses the new plain format (no markdown-bold field labels, no `###` panel headers)', () => {+ const script = `# Issue 1 — Bone Walker++## Page 1++Panel 1+Description: Wide establishing shot inside a fossilized rib, sun streaming in.+Caption: The titan died nine thousand years ago.+Dialogue: (none)+SFX: (none)++Panel 2+Description: Tight close-up — a beetle picks its way along polished bone.+Caption: No one has told the rib.+Dialogue:+- KESSA: "Beetle. If you had any sense, you'd stow away."+SFX: "fmp"+`;+ const { pages } = parseComicScript(script);+ expect(pages).toHaveLength(1);+ expect(pages[0].panels).toHaveLength(2);+ expect(pages[0].panels[0].description).toMatch(/establishing shot/);+ expect(pages[0].panels[0].caption).toMatch(/titan died/);+ expect(pages[0].panels[1].dialogue).toEqual([+ { character: 'KESSA', line: "Beetle. If you had any sense, you'd stow away." },+ ]);+ expect(pages[0].panels[1].sfx).toMatch(/fmp/);+ });++ it('does not start a new panel when "Panel N" appears mid-description', () => {+ // Regression: the relaxed plain-panel regex must require the panel header+ // to be a standalone line. Without the end-anchor, a description line+ // like "Panel 2 is offline on the monitor." used to split the panel.+ const script = `## Page 1++Panel 1+Description: A wide shot of the security room. Panel 2 is offline on the monitor in the corner. Etta studies the dead feed.+Caption: A quiet sweep before the storm.+`;+ const { pages } = parseComicScript(script);+ expect(pages).toHaveLength(1);+ expect(pages[0].panels).toHaveLength(1);+ expect(pages[0].panels[0].description).toMatch(/Panel 2 is offline on the monitor/);+ });++ it('accepts the `Panel N (DPS)` double-page-spread header form', () => {+ const script = `## Page 1++Panel 1 (DPS)+Description: A bold double-page spread of the city skyline at dawn.++Panel 2+Description: Tight on Kessa's hands clutching the railing.+`;+ const { pages } = parseComicScript(script);+ expect(pages).toHaveLength(1);+ expect(pages[0].panels).toHaveLength(2);+ expect(pages[0].panels[0].description).toMatch(/double-page spread/);+ expect(pages[0].panels[1].description).toMatch(/clutching the railing/);+ });++ it('caps rawText at PAGE_SCRIPT_MAX', () => {+ // Build a page with a single panel whose description is enormous, then+ // assert the page's rawText is bounded. We can't import PANEL_LIMITS+ // here without a circular-style import in the test — the assertion just+ // proves a hard cap exists.+ const fat = 'lorem ipsum dolor sit amet '.repeat(5000); // ~135 KB+ const script = `## Page 1\n\nPanel 1\nDescription: ${fat}\n`;+ const { pages } = parseComicScript(script);+ expect(pages).toHaveLength(1);+ expect(pages[0].rawText.length).toBeLessThanOrEqual(40_000);+ });});diff --git a/server/lib/issueLength.js b/server/lib/issueLength.jsnew file mode 100644index 0000000000..eec5117ca5--- /dev/null+++ b/server/lib/issueLength.js@@ -0,0 +1,140 @@+/**+ * Issue length profiles — per-issue size targets fed into every text stage+ * prompt (idea / prose / comicScript / tvScript) 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 into+ * the concrete numbers downstream templates need:+ *+ * pageTarget comic pages+ * minutesTarget TV episode runtime in minutes+ * proseWordsMin prose draft floor+ * proseWordsMax prose draft ceiling+ * beatsMin beat-sheet floor+ * beatsMax beat-sheet ceiling+ *+ * Presets are calibrated so prose words ≈ pages × 125 (the working ratio+ * for a comic adaptation where each page reads ~30 words of dialogue plus+ * ~80 words of described action). Beat count scales with prose volume.+ *+ * The 'custom' sentinel lets the user pin a page count and minute count+ * directly; the other targets are derived proportionally off the 'standard'+ * baseline so the upstream stages still have something concrete.+ */++export const LENGTH_PROFILES = Object.freeze({+ teaser: Object.freeze({+ label: 'Teaser',+ description: 'Short promo issue / web teaser — a single big beat, cliffhanger ending.',+ pageTarget: 8,+ minutesTarget: 10,+ proseWordsMin: 1100,+ proseWordsMax: 1600,+ beatsMin: 4,+ beatsMax: 6,+ }),+ standard: Object.freeze({+ label: 'Standard',+ description: 'Standard floppy comic / half-hour episode — the working default.',+ pageTarget: 22,+ minutesTarget: 24,+ proseWordsMin: 2500,+ proseWordsMax: 4000,+ beatsMin: 8,+ beatsMax: 12,+ }),+ extended: Object.freeze({+ label: 'Extended',+ description: 'Premiere or special-length issue — extra room for setup or set-piece beats.',+ pageTarget: 32,+ minutesTarget: 36,+ proseWordsMin: 4500,+ proseWordsMax: 6500,+ beatsMin: 12,+ beatsMax: 16,+ }),+ finale: Object.freeze({+ label: 'Finale',+ description: 'Season/series finale or annual — full-runtime climax with reveals and act-outs.',+ pageTarget: 44,+ minutesTarget: 48,+ proseWordsMin: 6500,+ proseWordsMax: 8500,+ beatsMin: 14,+ beatsMax: 20,+ }),+});++export const DEFAULT_LENGTH_PROFILE = 'standard';+export const LENGTH_PROFILE_NAMES = Object.freeze([+ ...Object.keys(LENGTH_PROFILES),+ 'custom',+]);++// Working bounds for custom overrides. Keeps a typo from asking for a+// 5000-page comic and a 600-minute movie. Exported so the issue sanitizer,+// the Zod patch schema, and the client picker all clamp to the same range —+// otherwise the persisted value can drift past the values+// `computeIssueTargets` is willing to honor at render time.+export const CUSTOM_PAGE_MIN = 4;+export const CUSTOM_PAGE_MAX = 120;+export const CUSTOM_MINUTE_MIN = 4;+export const CUSTOM_MINUTE_MAX = 240;+const STANDARD_PAGES = LENGTH_PROFILES.standard.pageTarget;+const STANDARD_WORDS_MIN = LENGTH_PROFILES.standard.proseWordsMin;+const STANDARD_WORDS_MAX = LENGTH_PROFILES.standard.proseWordsMax;+const STANDARD_BEATS_MIN = LENGTH_PROFILES.standard.beatsMin;+const STANDARD_BEATS_MAX = LENGTH_PROFILES.standard.beatsMax;++const clampInt = (raw, min, max, fallback) => {+ const n = Number(raw);+ if (!Number.isFinite(n)) return fallback;+ return Math.max(min, Math.min(max, Math.round(n)));+};++/**+ * Return the materialized length targets for an issue. Handles:+ * - missing/invalid profile → standard+ * - one of the named presets → table lookup+ * - 'custom' → uses issue.pageTarget / issue.minutesTarget, derives prose+ * and beat ranges by scaling against the standard preset+ *+ * Always returns a fully-populated object so prompt templates can use the+ * fields unconditionally.+ */+export function computeIssueTargets(issue = {}) {+ const profile = LENGTH_PROFILE_NAMES.includes(issue.lengthProfile)+ ? issue.lengthProfile+ : DEFAULT_LENGTH_PROFILE;++ if (profile === 'custom') {+ const pages = clampInt(+ issue.pageTarget,+ CUSTOM_PAGE_MIN,+ CUSTOM_PAGE_MAX,+ LENGTH_PROFILES.standard.pageTarget,+ );+ const minutes = clampInt(+ issue.minutesTarget,+ CUSTOM_MINUTE_MIN,+ CUSTOM_MINUTE_MAX,+ LENGTH_PROFILES.standard.minutesTarget,+ );+ // Anchor prose + beat counts to the comic-page scale — that's what the+ // prose draft is sized to feed downstream.+ const scale = pages / STANDARD_PAGES;+ return {+ profile,+ label: 'Custom',+ pageTarget: pages,+ minutesTarget: minutes,+ proseWordsMin: Math.max(600, Math.round(STANDARD_WORDS_MIN * scale)),+ proseWordsMax: Math.max(1000, Math.round(STANDARD_WORDS_MAX * scale)),+ beatsMin: Math.max(3, Math.round(STANDARD_BEATS_MIN * scale)),+ beatsMax: Math.max(5, Math.round(STANDARD_BEATS_MAX * scale)),+ };+ }++ const preset = LENGTH_PROFILES[profile];+ return { profile, ...preset };+}diff --git a/server/lib/issueLength.test.js b/server/lib/issueLength.test.jsnew file mode 100644index 0000000000..577167e973--- /dev/null+++ b/server/lib/issueLength.test.js@@ -0,0 +1,120 @@+import { describe, it, expect } from 'vitest';+import {+ LENGTH_PROFILES,+ LENGTH_PROFILE_NAMES,+ DEFAULT_LENGTH_PROFILE,+ CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX,+ CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX,+ computeIssueTargets,+} from './issueLength.js';++describe('computeIssueTargets — preset profiles', () => {+ for (const id of Object.keys(LENGTH_PROFILES)) {+ it(`materializes "${id}" with the table values`, () => {+ const targets = computeIssueTargets({ lengthProfile: id });+ expect(targets.profile).toBe(id);+ expect(targets).toMatchObject(LENGTH_PROFILES[id]);+ });+ }++ it('falls back to the default profile when lengthProfile is missing', () => {+ const targets = computeIssueTargets({});+ expect(targets.profile).toBe(DEFAULT_LENGTH_PROFILE);+ expect(targets).toMatchObject(LENGTH_PROFILES[DEFAULT_LENGTH_PROFILE]);+ });++ it('falls back to the default profile when lengthProfile is unrecognized', () => {+ const targets = computeIssueTargets({ lengthProfile: 'gargantuan' });+ expect(targets.profile).toBe(DEFAULT_LENGTH_PROFILE);+ });+});++describe('computeIssueTargets — custom profile', () => {+ it('uses the supplied page/minute counts', () => {+ const targets = computeIssueTargets({+ lengthProfile: 'custom', pageTarget: 50, minutesTarget: 60,+ });+ expect(targets.profile).toBe('custom');+ expect(targets.pageTarget).toBe(50);+ expect(targets.minutesTarget).toBe(60);+ expect(targets.label).toBe('Custom');+ });++ it('clamps pageTarget below the floor up to the minimum', () => {+ const targets = computeIssueTargets({+ lengthProfile: 'custom', pageTarget: 1, minutesTarget: 30,+ });+ expect(targets.pageTarget).toBe(CUSTOM_PAGE_MIN);+ });++ it('clamps pageTarget above the ceiling down to the maximum', () => {+ const targets = computeIssueTargets({+ lengthProfile: 'custom', pageTarget: 10_000, minutesTarget: 30,+ });+ expect(targets.pageTarget).toBe(CUSTOM_PAGE_MAX);+ });++ it('clamps minutesTarget below the floor up to the minimum', () => {+ const targets = computeIssueTargets({+ lengthProfile: 'custom', pageTarget: 22, minutesTarget: 1,+ });+ expect(targets.minutesTarget).toBe(CUSTOM_MINUTE_MIN);+ });++ it('clamps minutesTarget above the ceiling down to the maximum', () => {+ const targets = computeIssueTargets({+ lengthProfile: 'custom', pageTarget: 22, minutesTarget: 9999,+ });+ expect(targets.minutesTarget).toBe(CUSTOM_MINUTE_MAX);+ });++ it('falls back custom page/minute targets to the standard preset when non-numeric', () => {+ const targets = computeIssueTargets({+ lengthProfile: 'custom', pageTarget: 'abc', minutesTarget: undefined,+ });+ expect(targets.pageTarget).toBe(LENGTH_PROFILES.standard.pageTarget);+ expect(targets.minutesTarget).toBe(LENGTH_PROFILES.standard.minutesTarget);+ });++ it('scales prose word range proportionally to page count', () => {+ // A request for twice as many pages as the standard preset should+ // proportionally scale the prose word range upward.+ const doublePages = LENGTH_PROFILES.standard.pageTarget * 2;+ const targets = computeIssueTargets({+ lengthProfile: 'custom', pageTarget: doublePages, minutesTarget: 24,+ });+ expect(targets.proseWordsMin).toBeGreaterThanOrEqual(LENGTH_PROFILES.standard.proseWordsMin * 1.8);+ expect(targets.proseWordsMax).toBeGreaterThanOrEqual(LENGTH_PROFILES.standard.proseWordsMax * 1.8);+ });++ it('floors prose word range at 600/1000 so the smallest custom still has a workable target', () => {+ const targets = computeIssueTargets({+ lengthProfile: 'custom', pageTarget: CUSTOM_PAGE_MIN, minutesTarget: 24,+ });+ expect(targets.proseWordsMin).toBeGreaterThanOrEqual(600);+ expect(targets.proseWordsMax).toBeGreaterThanOrEqual(1000);+ });++ it('floors beat range at 3/5 so the smallest custom still has a workable target', () => {+ const targets = computeIssueTargets({+ lengthProfile: 'custom', pageTarget: CUSTOM_PAGE_MIN, minutesTarget: 24,+ });+ expect(targets.beatsMin).toBeGreaterThanOrEqual(3);+ expect(targets.beatsMax).toBeGreaterThanOrEqual(5);+ });++ it('rounds non-integer pageTarget input', () => {+ const targets = computeIssueTargets({+ lengthProfile: 'custom', pageTarget: 22.7, minutesTarget: 24,+ });+ expect(Number.isInteger(targets.pageTarget)).toBe(true);+ expect(targets.pageTarget).toBe(23);+ });+});++describe('LENGTH_PROFILE_NAMES contract', () => {+ it('always includes the default profile and the custom sentinel', () => {+ expect(LENGTH_PROFILE_NAMES).toContain(DEFAULT_LENGTH_PROFILE);+ expect(LENGTH_PROFILE_NAMES).toContain('custom');+ });+});diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex 80ce5bd25b..fa05710405 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -40,6 +40,7 @@ import * as autoRunner from '../services/pipeline/autoRunner.js';import {enqueueVisualImage,enqueueVisualComicPage,+ enqueueComicCover,enqueueStoryboardSceneVideo,refineComicPanelPrompt,refineStoryboardScenePrompt,@@ -49,6 +50,10 @@ import { startEpisodeVideoForIssue, ERR_NO_STORYBOARDS } from '../services/pipelimport { ASPECT_RATIOS, QUALITIES } from '../lib/creativeDirectorPresets.js';import { extractScenes, SOURCE_KIND } from '../lib/sceneExtractor.js';import { parseComicScript } from '../lib/comicScriptParser.js';+import {+ LENGTH_PROFILE_NAMES,+ CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX,+} from '../lib/issueLength.js';import { llmSchema } from './universeBuilder.js';import { BIBLE_KIND } from '../lib/storyBible.js';import { ARC_LIMITS, ARC_STATUSES, SEASON_STATUSES } from '../lib/storyArc.js';@@ -181,6 +186,12 @@ const seasonDeleteSchema = z.object({const issueCreateSchema = z.object({title: z.string().trim().min(1).max(issuesSvc.TITLE_MAX),number: z.number().int().min(1).max(9999).optional(),+ // Per-issue length profile — can be set at create time so a user creating+ // a standalone oversized issue (e.g. an annual) doesn't have to open the+ // picker after the fact. Defaults server-side to 'standard'.+ lengthProfile: z.enum(LENGTH_PROFILE_NAMES).optional(),+ pageTarget: z.number().int().min(CUSTOM_PAGE_MIN).max(CUSTOM_PAGE_MAX).nullable().optional(),+ minutesTarget: z.number().int().min(CUSTOM_MINUTE_MIN).max(CUSTOM_MINUTE_MAX).nullable().optional(),});const stageInputSchema = z.object({@@ -201,6 +212,22 @@ const visualStageInputSchema = stageInputSchema.extend({videoPath: z.string().trim().max(1000).nullable().optional(),aspectRatio: z.enum(ASPECT_RATIOS).nullable().optional(),quality: z.enum(QUALITIES).nullable().optional(),+ // Per-stage gen config — image mode + optional pinned model + optional+ // refine-LLM override. Sanitizer drops the field entirely when nothing+ // is set, so a `null` here clears it.+ genConfig: z.object({+ imageMode: z.enum(['auto', 'local', 'codex']).optional(),+ imageModelId: z.string().trim().max(200).nullable().optional(),+ refineProvider: z.string().trim().max(200).nullable().optional(),+ refineModel: z.string().trim().max(200).nullable().optional(),+ }).nullable().optional(),+ // Comic-issue front cover. Only meaningful on the comicPages stage; the+ // service-side sanitizer drops the field on other visual stages.+ cover: z.object({+ script: z.string().max(8000).optional(),+ imageJobId: z.string().trim().max(200).nullable().optional(),+ prompt: z.string().max(16_000).nullable().optional(),+ }).nullable().optional(),});const issuePatchSchema = z.object({@@ -211,6 +238,12 @@ const issuePatchSchema = z.object({// ordinal within that season. `null` clears the assignment.seasonId: z.string().trim().min(1).max(issuesSvc.SEASON_ID_MAX).nullable().optional(),arcPosition: z.number().int().min(0).max(issuesSvc.ARC_POSITION_MAX).nullable().optional(),+ // Per-issue length profile. Drives the prompt-template size targets+ // (beats / prose words / page count / minute count). pageTarget ++ // minutesTarget are only meaningful when lengthProfile === 'custom'.+ lengthProfile: z.enum(LENGTH_PROFILE_NAMES).optional(),+ pageTarget: z.number().int().min(CUSTOM_PAGE_MIN).max(CUSTOM_PAGE_MAX).nullable().optional(),+ minutesTarget: z.number().int().min(CUSTOM_MINUTE_MIN).max(CUSTOM_MINUTE_MAX).nullable().optional(),// Use visualStageInputSchema as the union arm so visual-stage payloads keep// their `scenes` / `pages` / `cdProjectId` / `videoPath` fields. The schema// is a superset of stageInputSchema (those four are optional additions), so@@ -241,6 +274,26 @@ const visualGenerateSchema = z.object({seed: z.number().int().min(0).optional(),});+// Comic-issue front cover render. Accepts an optional `coverScript`+// override (otherwise the route reads it from stages.comicPages.cover.script);+// the rest of the prompt is built server-side from series + issue metadata.+// `seed` mirrors the page/panel render schemas so the shared image-gen drawer+// flows the same render settings into the cover — enqueueImageJob honors it+// via options.seed.+const comicCoverRenderSchema = z.object({+ coverScript: z.string().max(8000).optional(),+ 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(),+ seed: z.number().int().min(0).optional(),+});+// Full-comic-page render: same knobs as panel render minus `description` /// `slugline` (the prompt is built server-side from the page's panels[] so it// stays in sync with whatever the script-extractor produced).@@ -544,6 +597,9 @@ router.post('/series/:id/seasons/:seasonId/episodes/generate', asyncHandler(asyn// don't collide.seasonId: req.params.seasonId,arcPosition: ep.number,+ // Episode-level length sizing from the season-episodes LLM pass.+ // Defaults to 'standard' inside the issue sanitizer when missing.+ lengthProfile: ep.lengthProfile,stages: {idea: {status: ep.synopsis ? 'edited' : 'empty',@@ -759,11 +815,24 @@ router.post('/issues/:id/stages/comicPages/extract-pages', asyncHandler(async (r);}- const { pages } = parseComicScript(source);+ const { pages, coverConcept } = parseComicScript(source);++ // Preserve a user-edited cover script if one is already set — only seed+ // from the parsed concept when the cover is currently blank. Otherwise an+ // extract re-run would clobber a hand-curated cover. When we DO seed, also+ // clear any prior imageJobId / prompt — they were rendered against the old+ // (likely placeholder / fallback) script, so leaving them would show a+ // rendered cover image that doesn't match the new concept text.+ const existingCover = issue.stages?.comicPages?.cover || null;+ const existingCoverScript = existingCover?.script || '';+ const nextCover = coverConcept && !existingCoverScript+ ? { script: coverConcept, imageJobId: null, prompt: null }+ : existingCover;const { issue: updatedIssue, stage } = await issuesSvc.updateStage(issue.id, 'comicPages', {status: pages.length ? 'ready' : 'empty',pages,+ cover: nextCover,errorMessage: '',});@@ -813,6 +882,33 @@ router.patch('/issues/:id/stages/comicPages/pages/:pageIndex', asyncHandler(asynres.json({ issue: updatedIssue, stage, page: pages[pageIndex] });}));+// Render the comic-issue front cover. Builds a cover-art prompt (series+// masthead + issue-number tag + the user's cover concept) and persists the+// returned jobId on stages.comicPages.cover.imageJobId. Pass `coverScript`+// in the body to override or update the persisted cover concept in the+// same call. Returns { jobId, mode, prompt, cover, issue, stage }.+router.post('/issues/:id/stages/comicPages/cover/render', asyncHandler(async (req, res) => {+ const body = validateRequest(comicCoverRenderSchema, req.body ?? {});+ // Make sure the issue exists up front — defense in depth + clean 404+ // before we spend the bible-context load.+ await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });++ const result = await enqueueComicCover(req.params.id, body)+ .catch((err) => { throw mapServiceError(err); });++ // Persist coverScript + jobId + prompt back onto the issue so the UI+ // shows the in-flight render on reload, even if the user navigates away.+ const nextCover = {+ script: result.coverScript || '',+ imageJobId: result.jobId,+ prompt: result.prompt,+ };+ const { issue: updatedIssue, stage } = await issuesSvc.updateStage(req.params.id, 'comicPages', {+ cover: nextCover,+ });+ res.json({ ...result, cover: stage.cover, issue: updatedIssue, stage });+}));+// Render a full comic page (multi-panel layout in one image) — the// recommended default for cloud-class image models (Codex, Google Imagen);// local diffusion models can render this but tend to produce draft-qualitydiff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.jsindex aa717b3fdb..75b64b8308 100644--- a/server/routes/pipeline.test.js+++ b/server/routes/pipeline.test.js@@ -69,6 +69,14 @@ vi.mock('../services/pipeline/visualStages.js', () => ({prompt: `comic-page prompt for page ${opts.pageIndex + 1}`,pageIndex: opts.pageIndex,})),+ // Front cover render. Returns shape the route merges with the persisted cover:+ // { jobId, mode, prompt, coverScript }.+ enqueueComicCover: vi.fn(async (_issueId, body) => ({+ jobId: `cover-job-${++uuidCounter}`,+ mode: 'local',+ prompt: 'cover art prompt',+ coverScript: body?.coverScript ?? 'default cover concept',+ })),// Single-scene video render. Returns the shape the route forwards verbatim// to clients: { jobId, prompt, sceneIndex, issue, stage }.enqueueStoryboardSceneVideo: vi.fn(async (issueId, sceneIndex) => ({@@ -680,6 +688,69 @@ describe('pipeline routes', () => {expect(r.body.stage.pages[0].panels[0].description).toBe('Fresh.');});+ it('POST /issues/:id/stages/comicPages/extract-pages seeds blank cover.script from parsed coverConcept', 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 script = [+ '## Cover concept',+ 'A lone figure stands on a crumbling bridge.',+ '',+ '## Page 1',+ '',+ 'Panel 1',+ '**Description:** The bridge at dusk.',+ '**Caption:** (none)',+ '**Dialogue:** (none)',+ '**SFX:** (none)',+ ].join('\n');+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({+ stages: { comicScript: { status: 'ready', output: script } },+ });+ const r = await request(app)+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/extract-pages`)+ .send({});+ expect(r.status).toBe(200);+ // Response reflects the seeded cover+ expect(r.body.stage.cover.script).toBe('A lone figure stands on a crumbling bridge.');+ expect(r.body.stage.cover.imageJobId).toBeNull();+ expect(r.body.stage.cover.prompt).toBeNull();+ // Persisted issue also carries the seeded cover+ expect(r.body.issue.stages.comicPages.cover.script).toBe('A lone figure stands on a crumbling bridge.');+ });++ it('POST /issues/:id/stages/comicPages/extract-pages does not clobber an existing cover.script', 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 script = [+ '## Cover concept',+ 'A brand-new concept from the re-run.',+ '',+ '## Page 1',+ '',+ 'Panel 1',+ '**Description:** The bridge at dawn.',+ '**Caption:** (none)',+ '**Dialogue:** (none)',+ '**SFX:** (none)',+ ].join('\n');+ // Pre-seed the issue with an existing user-edited cover script+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({+ stages: {+ comicScript: { status: 'ready', output: script },+ comicPages: { cover: { script: 'user edit', imageJobId: 'old-job', prompt: 'old prompt' } },+ },+ });+ const r = await request(app)+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/extract-pages`)+ .send({});+ expect(r.status).toBe(200);+ // The existing cover must be preserved exactly — no clobber+ expect(r.body.stage.cover.script).toBe('user edit');+ expect(r.body.issue.stages.comicPages.cover.script).toBe('user edit');+ });+// ---- comicPages/pages/:pageIndex/render ----it('POST /issues/:id/stages/comicPages/pages/:pageIndex/render 400s for a non-integer pageIndex', async () => {@@ -741,6 +812,46 @@ describe('pipeline routes', () => {expect(visualStages.enqueueVisualComicPage).not.toHaveBeenCalled();});+ // ---- comicPages/cover/render ----++ it('POST /issues/:id/stages/comicPages/cover/render returns jobId + prompt and persists cover on the issue', 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/cover/render`)+ .send({ coverScript: 'Hero stands atop the foundry, smoke rising' });+ expect(r.status).toBe(200);+ expect(r.body.jobId).toMatch(/^cover-job-/);+ expect(r.body.prompt).toBe('cover art prompt');+ // Persistence: stages.comicPages.cover must carry script, imageJobId, prompt.+ expect(r.body.cover.script).toBe('Hero stands atop the foundry, smoke rising');+ expect(r.body.cover.imageJobId).toBe(r.body.jobId);+ expect(r.body.cover.prompt).toBe(r.body.prompt);+ // Top-level issue + stage are also returned.+ expect(r.body.issue.id).toBe(iss.body.id);+ expect(r.body.stage.cover.imageJobId).toBe(r.body.jobId);+ });++ it('POST /issues/:id/stages/comicPages/cover/render 404s for an unknown issue', async () => {+ const app = makeApp();+ const r = await request(app)+ .post('/api/pipeline/issues/iss-nope/stages/comicPages/cover/render')+ .send({});+ expect(r.status).toBe(404);+ });++ it('POST /issues/:id/stages/comicPages/cover/render 400s when the body fails schema validation', 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' });+ // `width` must be an integer; sending a string triggers Zod validation failure.+ const r = await request(app)+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicPages/cover/render`)+ .send({ width: 'not-a-number' });+ expect(r.status).toBe(400);+ });+// -----------------------// Season routes (Phase 2 of Story Arc Planning)// -----------------------@@ -951,7 +1062,7 @@ describe('pipeline routes', () => {seasonEpisodesSpy = vi.fn(async () => ({season: sea.body,episodes: [- { number: 1, title: 'Ep 1', logline: 'L1', synopsis: 'Pilot synopsis', primaryCharacters: ['LINA'], arcRole: 'pilot' },+ { number: 1, title: 'Ep 1', logline: 'L1', synopsis: 'Pilot synopsis', primaryCharacters: ['LINA'], arcRole: 'pilot', lengthProfile: 'extended' },{ number: 2, title: 'Ep 2', logline: 'L2', synopsis: 'Comp synopsis', primaryCharacters: ['LINA'], arcRole: 'complication' },],runId: 'run-2', providerId: 'p', model: 'm',@@ -967,6 +1078,8 @@ describe('pipeline routes', () => {expect(r.body.createdIssues[0].title).toBe('Ep 1');// Synopsis lands in stages.idea.input so auto-run-text has a seed.expect(r.body.createdIssues[0].stages.idea.input).toContain('Pilot synopsis');+ // Non-default lengthProfile must be forwarded from the episode into the created issue.+ expect(r.body.createdIssues[0].lengthProfile).toBe('extended');expect(r.body.createdIssues[1].arcPosition).toBe(2);const issues = await request(app).get(`/api/pipeline/series/${ser.body.id}/issues`);diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.jsindex 4b0073108b..0a78954e6a 100644--- a/server/services/pipeline/arcPlanner.js+++ b/server/services/pipeline/arcPlanner.js@@ -25,6 +25,7 @@ import { getSeries, updateSeries } from './series.js';import { listIssues } from './issues.js';import { sanitizeArc, sanitizeSeasonList, sanitizeSeason, buildSeason } from '../../lib/storyArc.js';import { recommendStructure, describeStructure } from '../../lib/seasonStructure.js';+import { LENGTH_PROFILE_NAMES, DEFAULT_LENGTH_PROFILE } from '../../lib/issueLength.js';import { getUniverse } from '../universeBuilder.js';import { getSeriesCanon } from './seriesCanon.js';import { renderCategoriesForPrompt, renderCompositesForPrompt } from '../../lib/universePromptRenderers.js';@@ -34,6 +35,16 @@ const makeErr = (message, code) => Object.assign(new Error(message), { code });const VERIFY_SEVERITIES = new Set(['high', 'medium', 'low']);const ARC_ROLES = new Set(['pilot', 'complication', 'midpoint', 'b-plot', 'all-is-lost', 'finale']);+// Season-episode generation must produce concrete preset profiles only — the+// 'custom' sentinel needs companion pageTarget/minutesTarget values the LLM is+// not asked to invent, so a 'custom' here would silently render as 'standard'+// at prompt time. Limit to the canonical preset names.+const SEASON_LENGTH_PRESETS = new Set(LENGTH_PROFILE_NAMES.filter((n) => n !== 'custom'));+// Finale-role episodes should size like a finale even when the LLM omits+// (or misspells) lengthProfile. Other arcRoles fall back to the default+// profile so a missing/misspelled length doesn't cascade into the wrong+// size for the whole arc.+const lengthProfileForArcRole = (arcRole) => (arcRole === 'finale' ? 'finale' : DEFAULT_LENGTH_PROFILE);// Each prior season renders as its header (logline + synopsis) plus the// committed per-episode beats from `stages.idea.input` — that field was@@ -243,6 +254,16 @@ function shapeEpisodes(rawEpisodes) {: nextNumber;nextNumber = number + 1;const arcRole = ARC_ROLES.has(raw?.arcRole) ? raw.arcRole : null;+ // Episode-level length sizing — fed straight into the issue's+ // lengthProfile when the route creates issues from this preview. Only the+ // concrete presets are accepted here (no 'custom' sentinel — the LLM is+ // never asked to invent custom page/minute targets, and a 'custom' value+ // without companion numbers silently degrades to 'standard' downstream).+ // The fallback is derived from arcRole so a finale episode still sizes+ // like a finale when the LLM omits the field.+ const lengthProfile = SEASON_LENGTH_PRESETS.has(raw?.lengthProfile)+ ? raw.lengthProfile+ : lengthProfileForArcRole(arcRole);const primaryCharacters = Array.isArray(raw?.primaryCharacters)? raw.primaryCharacters.filter((c) => typeof c === 'string' && c.trim()).map((c) => c.trim().slice(0, 200)).slice(0, 12): [];@@ -253,6 +274,7 @@ function shapeEpisodes(rawEpisodes) {synopsis: typeof raw?.synopsis === 'string' ? raw.synopsis.trim().slice(0, 4000) : '',primaryCharacters,arcRole,+ lengthProfile,});}return out;diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.jsindex 348b4daa8f..f6436ce0f5 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -250,6 +250,29 @@ describe('arcPlanner — generateSeasonEpisodes', () => {expect(out.episodes[1].arcRole).toBe(null); // invalid role drops to nullexpect(out.episodes[1].primaryCharacters).toEqual(['LINA']); // non-string + blank entries filtered});++ it('rejects the `custom` length sentinel and derives a finale-role fallback to `finale`', async () => {+ const { series, seasons } = await setupSeriesWithSeasons();+ stageRunnerSpy = vi.fn(async () => ({+ content: {+ episodes: [+ // LLM emitted `custom` without page/minute companions → reject sentinel,+ // fall back via arcRole. arcRole=finale → finale preset.+ { number: 1, title: 'Finale', arcRole: 'finale', lengthProfile: 'custom' },+ // arcRole=midpoint and missing lengthProfile → default profile (standard).+ { number: 2, title: 'Midpoint', arcRole: 'midpoint' },+ // Valid preset is kept as-is.+ { number: 3, title: 'Extra', lengthProfile: 'extended' },+ ],+ },+ runId: 'r1', providerId: 'p', model: 'm',+ }));+ const out = await planner.generateSeasonEpisodes(series.id, seasons[0].id);+ const byTitle = Object.fromEntries(out.episodes.map((e) => [e.title, e]));+ expect(byTitle.Finale.lengthProfile).toBe('finale');+ expect(byTitle.Midpoint.lengthProfile).toBe('standard');+ expect(byTitle.Extra.lengthProfile).toBe('extended');+ });});describe('arcPlanner — verifyArc', () => {diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex c6dd8d4137..c6761cc434 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -21,10 +21,38 @@import { join } from 'path';import { randomUUID } from 'crypto';import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';+import {+ LENGTH_PROFILE_NAMES, DEFAULT_LENGTH_PROFILE,+ CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX,+} from '../../lib/issueLength.js';// Lazy resolution — see series.js for context.const statePath = () => join(PATHS.data, 'pipeline-issues.json');+// File-level write lock: serializes concurrent updateIssue / updateStage calls+// against the shared pipeline-issues.json state file so a blur-save PATCH can+// never clobber an in-flight cover-render PATCH (and vice-versa, across any+// pair of issues — not just two writes to the same issue id). Each enqueue+// awaits the previous write to settle before reading state, so it always+// merges against the freshest persisted record. CLAUDE.md: "simple+// re-entrancy guards… are fine and expected."+let issueWriteTail = Promise.resolve();++function queueIssueWrite(_issueId, fn) {+ const next = issueWriteTail.then(fn, fn); // run fn even when prev rejects+ // Track the silenced tail so a rejection doesn't poison subsequent waiters,+ // but only as long as this write is the tail — if another write enqueues+ // after us, it becomes the tail and we drop our reference so the chain+ // doesn't retain settled promises (and their resolved payloads) for the+ // life of the process.+ const silenced = next.catch(() => {});+ issueWriteTail = silenced;+ silenced.finally(() => {+ if (issueWriteTail === silenced) issueWriteTail = Promise.resolve();+ });+ return next; // callers still see the real resolve/reject+}+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 });@@ -83,7 +111,40 @@ const sanitizeStage = (raw) => {const ASPECT_RATIO_VALUES = new Set(['16:9', '9:16', '1:1']);const QUALITY_VALUES = new Set(['draft', 'standard', 'high']);-const sanitizeVisualStage = (raw) => {+// `imageMode: 'auto'` defers to the server resolver (codex when enabled,+// local otherwise). Returns null when nothing was set so the persisted+// JSON stays clean for issues that never opened the panel.+const IMAGE_MODE_VALUES = new Set(['auto', 'local', 'codex']);+const GEN_CONFIG_STR_MAX = 200;+const sanitizeGenConfig = (raw) => {+ if (!raw || typeof raw !== 'object') return null;+ const imageMode = IMAGE_MODE_VALUES.has(raw.imageMode) ? raw.imageMode : 'auto';+ // imageModelId is only meaningful for local diffusion — clear it for other+ // modes so a previously-pinned model doesn't silently persist in the config+ // and mislead the UI or any future reader that doesn't filter by mode.+ const imageModelId = imageMode === 'local'+ ? (trimTo(raw.imageModelId, GEN_CONFIG_STR_MAX) || null)+ : null;+ const refineProvider = trimTo(raw.refineProvider, GEN_CONFIG_STR_MAX) || null;+ const refineModel = trimTo(raw.refineModel, GEN_CONFIG_STR_MAX) || null;+ if (imageMode === 'auto' && !imageModelId && !refineProvider && !refineModel) {+ return null;+ }+ return { imageMode, imageModelId, refineProvider, refineModel };+};++const COVER_SCRIPT_MAX = 8000;+const COVER_PROMPT_MAX = 16_000;+const sanitizeCover = (raw) => {+ if (!raw || typeof raw !== 'object') return null;+ 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 };+};++const sanitizeVisualStage = (raw, stageId = null) => {// Visual stages keep arbitrary structured artifact lists. Sanitize the// wrapper but pass through known shapes.const base = sanitizeStage(raw);@@ -95,13 +156,24 @@ const sanitizeVisualStage = (raw) => {videoPath: isStr(raw?.videoPath) && raw.videoPath ? raw.videoPath : null,aspectRatio: ASPECT_RATIO_VALUES.has(raw?.aspectRatio) ? raw.aspectRatio : null,quality: QUALITY_VALUES.has(raw?.quality) ? raw.quality : null,+ // genConfig is read by comicPages/storyboards; pass-through is a no-op on+ // episodeVideo, which never looks at it.+ genConfig: sanitizeGenConfig(raw?.genConfig),+ // `cover` is meaningful only on comicPages — it carries the front-cover+ // concept + render job. Dropping it on storyboards / episodeVideo makes+ // the contract explicit (matches the comment in pipeline.js's visual+ // stage schema). When stageId is omitted (legacy callers / stage-shape+ // sanitize at issue load time without per-stage context), keep the+ // field — `sanitizeStages` below threads the stageId through so the+ // canonical persistence path enforces the rule.+ cover: stageId === null || stageId === 'comicPages' ? sanitizeCover(raw?.cover) : 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]);+ for (const id of VISUAL_STAGE_IDS) out[id] = sanitizeVisualStage(raw[id], id);return out;};@@ -124,6 +196,21 @@ const sanitizeIssue = (raw) => {const arcPosition = Number.isFinite(raw.arcPosition)? Math.max(0, Math.min(ARC_POSITION_MAX, Math.floor(raw.arcPosition))): null;+ // Defaults to 'standard' so pre-field issues keep the prior 22pg/24min sizing.+ // pageTarget/minutesTarget are only consumed when lengthProfile==='custom',+ // but we persist them on every profile so the picker can remember a previous+ // custom value if the user toggles back. Bounds mirror the values+ // `computeIssueTargets` clamps to at render time — otherwise the persisted+ // record could disagree with the prompt-rendered length.+ const lengthProfile = LENGTH_PROFILE_NAMES.includes(raw.lengthProfile)+ ? raw.lengthProfile+ : DEFAULT_LENGTH_PROFILE;+ const pageTarget = Number.isFinite(raw.pageTarget)+ ? Math.max(CUSTOM_PAGE_MIN, Math.min(CUSTOM_PAGE_MAX, Math.round(raw.pageTarget)))+ : null;+ const minutesTarget = Number.isFinite(raw.minutesTarget)+ ? Math.max(CUSTOM_MINUTE_MIN, Math.min(CUSTOM_MINUTE_MAX, Math.round(raw.minutesTarget)))+ : null;return {id: raw.id,seriesId: trimTo(raw.seriesId, SERIES_ID_MAX),@@ -132,6 +219,9 @@ const sanitizeIssue = (raw) => {status,seasonId,arcPosition,+ lengthProfile,+ pageTarget,+ minutesTarget,stages: sanitizeStages(raw.stages || {}),createdAt,updatedAt,@@ -204,6 +294,9 @@ export async function createIssue(input = {}) {// (and any future caller wiring an issue to a season at create time).seasonId: 'seasonId' in input ? input.seasonId : null,arcPosition: 'arcPosition' in input ? input.arcPosition : null,+ lengthProfile: 'lengthProfile' in input ? input.lengthProfile : undefined,+ pageTarget: 'pageTarget' in input ? input.pageTarget : null,+ minutesTarget: 'minutesTarget' in input ? input.minutesTarget : null,stages: input.stages || {},createdAt: new Date().toISOString(),updatedAt: new Date().toISOString(),@@ -220,15 +313,60 @@ function nextIssueNumber(issues, seriesId) {return Math.max(...peers.map((i) => i.number || 0)) + 1;}-export async function updateIssue(id, patch = {}) {+export function updateIssue(id, patch = {}) {+ return queueIssueWrite(id, async () => {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;+ // Per-stage merge: a stage patch carries only the fields the caller is+ // changing (e.g. `{ genConfig }` or `{ cover }`). Without this, the top-level+ // spread would replace the entire stage object and silently drop sibling+ // fields like `scenes` / `pages` / `genConfig`. Sanitization then defaults+ // those back to empty arrays/null, erasing work the user (or LLM) just did.+ // Callers that need stage-level changes without touching issue-level fields+ // should use `updateStage`, which does a shallow merge of the patch over the+ // existing stage (`{ ...cur.stages[stageId], ...patch }`) before sanitizing.+ // Note: `updateStage` still merges — omitted sibling stage fields are+ // preserved. To clear a field explicitly, pass it as `null` or `""` in the+ // patch.+ //+ // `cover` and `genConfig` are treated as deep-merge sub-objects: a partial+ // `{ cover: { script } }` patch from a textarea-blur save must not wipe the+ // sibling `imageJobId` / `prompt` that a parallel "Render cover" mutation+ // just persisted. Passing `null` explicitly still clears the sub-object+ // (intentional-clear semantics).+ const NESTED_DEEP_MERGE_KEYS = ['cover', 'genConfig'];+ let mergedStages = cur.stages;+ if ('stages' in patch && patch.stages && typeof patch.stages === 'object') {+ mergedStages = { ...cur.stages };+ for (const [stageId, stagePatch] of Object.entries(patch.stages)) {+ const prev = cur.stages?.[stageId];+ if (prev && stagePatch && typeof prev === 'object' && typeof stagePatch === 'object') {+ const merged = { ...prev, ...stagePatch };+ for (const key of NESTED_DEEP_MERGE_KEYS) {+ if (key in stagePatch+ && stagePatch[key] && typeof stagePatch[key] === 'object'+ && prev[key] && typeof prev[key] === 'object') {+ merged[key] = { ...prev[key], ...stagePatch[key] };+ }+ }+ // Clear transient error fields when a content/status change implies+ // the previous failure is no longer the active state. Mirrors the+ // pre-per-stage-merge behavior, where a `{ status, input, output }`+ // patch replaced the whole stage and implicitly wiped errorMessage.+ if ('status' in stagePatch && stagePatch.status !== 'error'+ && stagePatch.status !== 'generating'+ && !('errorMessage' in stagePatch)) {+ merged.errorMessage = '';+ }+ mergedStages[stageId] = merged;+ } else {+ mergedStages[stageId] = stagePatch;+ }+ }+ }const merged = sanitizeIssue({...cur,@@ -237,6 +375,9 @@ export async function updateIssue(id, patch = {}) {...('status' in patch ? { status: patch.status } : {}),...('seasonId' in patch ? { seasonId: patch.seasonId } : {}),...('arcPosition' in patch ? { arcPosition: patch.arcPosition } : {}),+ ...('lengthProfile' in patch ? { lengthProfile: patch.lengthProfile } : {}),+ ...('pageTarget' in patch ? { pageTarget: patch.pageTarget } : {}),+ ...('minutesTarget' in patch ? { minutesTarget: patch.minutesTarget } : {}),stages: mergedStages,updatedAt: new Date().toISOString(),});@@ -244,6 +385,7 @@ export async function updateIssue(id, patch = {}) {state.issues[idx] = merged;await writeState(state);return merged;+ }); // end queueIssueWrite}/**@@ -252,21 +394,24 @@ export async function updateIssue(id, patch = {}) {* Patch keys: status, input, output, lastRunId, errorMessage, and (for* visual stages) pages/scenes/cdProjectId/videoPath.*/-export async function updateStage(issueId, stageId, patch = {}) {+export function updateStage(issueId, stageId, patch = {}) {if (!STAGE_IDS.includes(stageId)) {- throw makeErr(`Unknown stage: ${stageId}`, ERR_VALIDATION);+ // Validate before queueing so the caller gets an immediate rejection+ // rather than waiting in line for an error it already knows about.+ return Promise.reject(makeErr(`Unknown stage: ${stageId}`, ERR_VALIDATION));}+ return queueIssueWrite(issueId, async () => {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({+ const merged = {...cur.stages[stageId],...patch,updatedAt: new Date().toISOString(),- });+ };+ const next = isVisual ? sanitizeVisualStage(merged, stageId) : sanitizeStage(merged);const mergedIssue = sanitizeIssue({...cur,stages: { ...cur.stages, [stageId]: next },@@ -275,6 +420,7 @@ export async function updateStage(issueId, stageId, patch = {}) {state.issues[idx] = mergedIssue;await writeState(state);return { issue: mergedIssue, stage: mergedIssue.stages[stageId] };+ }); // end queueIssueWrite}export async function deleteIssue(id) {diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.jsindex fa727dc445..f61ef37320 100644--- a/server/services/pipeline/issues.test.js+++ b/server/services/pipeline/issues.test.js@@ -138,6 +138,168 @@ describe('pipeline issues service', () => {expect(updated.stages.idea.output).toBe('Beats here');});+ it('updateIssue stage patch merges per-stage fields instead of replacing', async () => {+ // A partial stage patch from the client (e.g. saving genConfig from a+ // settings drawer) must not erase the rest of that stage. The header+ // gen-config save in particular was deleting `scenes` and `cover` until+ // updateIssue was taught to per-stage-merge.+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'Merge me' });+ await svc.updateStage(i.id, 'storyboards', {+ status: 'edited',+ scenes: [{ slugline: 'INT. LAB', description: 'a scene' }],+ });+ await svc.updateStage(i.id, 'comicPages', {+ status: 'edited',+ pages: [{ panels: [{ description: 'panel one' }] }],+ cover: { script: 'cover concept', imageJobId: null, prompt: null },+ });++ // Patch only genConfig on storyboards — scenes must survive.+ const afterStoryboards = await svc.updateIssue(i.id, {+ stages: { storyboards: { genConfig: { imageMode: 'codex' } } },+ });+ expect(afterStoryboards.stages.storyboards.scenes).toHaveLength(1);+ expect(afterStoryboards.stages.storyboards.scenes[0].slugline).toBe('INT. LAB');+ expect(afterStoryboards.stages.storyboards.genConfig).toEqual({+ imageMode: 'codex', imageModelId: null, refineProvider: null, refineModel: null,+ });++ // Patch only cover on comicPages — pages must survive.+ const afterCover = await svc.updateIssue(i.id, {+ stages: { comicPages: { cover: { script: 'new concept' } } },+ });+ expect(afterCover.stages.comicPages.pages).toHaveLength(1);+ expect(afterCover.stages.comicPages.cover.script).toBe('new concept');+ });++ it('deep-merges cover sub-fields so a partial `{ cover: { script } }` patch preserves imageJobId/prompt', async () => {+ // Race regression: ComicScriptStage's textarea blur fires after a+ // "Render cover" mutation has persisted imageJobId. A naive shallow merge+ // would overwrite the imageJobId back to null. The deep-merge of `cover`+ // sub-fields keeps the freshly-queued render visible.+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'Deep merge' });+ await svc.updateStage(i.id, 'comicPages', {+ status: 'edited',+ cover: { script: 'old', imageJobId: 'job-abc12345', prompt: 'p1' },+ });+ const updated = await svc.updateIssue(i.id, {+ stages: { comicPages: { cover: { script: 'new' } } },+ });+ expect(updated.stages.comicPages.cover).toMatchObject({+ script: 'new',+ imageJobId: 'job-abc12345',+ prompt: 'p1',+ });+ });++ it('deep-merges genConfig sub-fields so a partial `{ genConfig: { imageMode } }` patch preserves the rest', async () => {+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'Gen merge' });+ // Start with local mode + a pinned model — imageModelId is valid for local mode.+ await svc.updateStage(i.id, 'storyboards', {+ status: 'edited',+ genConfig: { imageMode: 'local', imageModelId: 'flux-1', refineProvider: null, refineModel: null },+ });+ // Partial patch only changes imageMode — imageModelId should survive the deep merge.+ const updated = await svc.updateIssue(i.id, {+ stages: { storyboards: { genConfig: { imageMode: 'local' } } },+ });+ expect(updated.stages.storyboards.genConfig).toMatchObject({+ imageMode: 'local',+ imageModelId: 'flux-1',+ });+ });++ it('sanitizeGenConfig clears imageModelId when imageMode is not local', async () => {+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'Gen mode clear' });+ // A codex-mode config with an imageModelId (stale client state) must not+ // persist the model id — it is meaningless for codex/auto and would mislead+ // the UI into showing a "pinned" model that generation ignores.+ await svc.updateStage(i.id, 'storyboards', {+ status: 'edited',+ genConfig: { imageMode: 'codex', imageModelId: 'flux-1', refineProvider: null, refineModel: null },+ });+ const issue = await svc.getIssue(i.id);+ expect(issue.stages.storyboards.genConfig.imageModelId).toBeNull();+ });++ it('treats `cover: null` as an explicit clear, not a deep merge', async () => {+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'Clear cover' });+ await svc.updateStage(i.id, 'comicPages', {+ status: 'edited',+ cover: { script: 'concept', imageJobId: null, prompt: null },+ });+ const updated = await svc.updateIssue(i.id, {+ stages: { comicPages: { cover: null } },+ });+ expect(updated.stages.comicPages.cover).toBeNull();+ });++ it('clears errorMessage when a stage patch transitions out of error state', async () => {+ // Regression: per-stage merge previously preserved `errorMessage` across+ // a `{ status: 'edited', input, output }` save. The pre-merge replace-+ // behavior implicitly wiped error state, and users expect that. Patches+ // that target `error`/`generating` keep the message (still active).+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'Error clear' });+ await svc.updateStage(i.id, 'idea', {+ status: 'error',+ errorMessage: 'previous run failed',+ });+ expect((await svc.getIssue(i.id)).stages.idea.errorMessage).toBe('previous run failed');+ // Manual edit that flips status away from `error` — error message must clear.+ const edited = await svc.updateIssue(i.id, {+ stages: { idea: { status: 'edited', input: 'manual seed' } },+ });+ expect(edited.stages.idea.errorMessage).toBe('');+ expect(edited.stages.idea.input).toBe('manual seed');+ });++ it('preserves errorMessage when a patch leaves stage in error/generating state', async () => {+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'Error keep' });+ await svc.updateStage(i.id, 'idea', {+ status: 'error',+ errorMessage: 'still failing',+ });+ // Subsequent retry sets status back to generating — error should remain+ // visible until the retry transitions to ready or edited.+ const retry = await svc.updateIssue(i.id, {+ stages: { idea: { status: 'generating' } },+ });+ expect(retry.stages.idea.errorMessage).toBe('still failing');+ });++ it('drops cover field from non-comicPages visual stages on persist', async () => {+ // Contract: `cover` is only meaningful on comicPages — the route schema+ // documents this and the sanitizer enforces it. A misrouted patch should+ // not silently leave a phantom cover on storyboards / episodeVideo.+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'Cover gate' });+ const patched = await svc.updateIssue(i.id, {+ stages: {+ comicPages: { cover: { script: 'should stay', imageJobId: null, prompt: null } },+ storyboards: { cover: { script: 'should be dropped', imageJobId: null, prompt: null } },+ episodeVideo: { cover: { script: 'should be dropped too', imageJobId: null, prompt: null } },+ },+ });+ expect(patched.stages.comicPages.cover).toMatchObject({ script: 'should stay' });+ expect(patched.stages.storyboards.cover).toBeNull();+ expect(patched.stages.episodeVideo.cover).toBeNull();+ });++ it('sanitizer rounds fractional pageTarget/minutesTarget to match computeIssueTargets', async () => {+ // Regression: sanitizer was using Math.floor while computeIssueTargets uses+ // Math.round (via clampInt), so persisted values could disagree with the+ // prompt-rendered targets. e.g. pageTarget: 22.7 → stored as 22 but+ // rendered as 23. Both must agree on 23.+ const i = await svc.createIssue({+ seriesId: 'ser-1',+ title: 'Rounding regression',+ lengthProfile: 'custom',+ pageTarget: 22.7,+ minutesTarget: 23.5,+ });+ expect(i.pageTarget).toBe(23);+ expect(i.minutesTarget).toBe(24);+ });+it('deleteIssue 404s on second call', async () => {const i = await svc.createIssue({ seriesId: 'ser-1', title: 'First' });await svc.deleteIssue(i.id);diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.jsindex ea53063ae4..a07054ff8c 100644--- a/server/services/pipeline/textStages.js+++ b/server/services/pipeline/textStages.js@@ -18,6 +18,7 @@ import { runStagedLLM } from '../../lib/stageRunner.js';import { getSeries, extractAndMergeIntoSeries } from './series.js';import { getIssue, updateStage, TEXT_STAGE_IDS } from './issues.js';import { getSeriesCanon } from './seriesCanon.js';+import { computeIssueTargets } from '../../lib/issueLength.js';const STAGE_TO_TEMPLATE = Object.freeze({idea: 'pipeline-idea-expansion',@@ -56,6 +57,9 @@ function buildStageContext({ series, canon, issue, stageId, seedInput }) {number: issue.number,title: issue.title,},+ // Fed into every text template via {{lengthTargets.*}}. Always populated+ // (defaults to 'standard') so templates can use the fields unconditionally.+ lengthTargets: computeIssueTargets(issue),stages,seed: (seedInput || issue.stages?.[stageId]?.input || '').trim(),};diff --git a/server/services/pipeline/textStages.test.js b/server/services/pipeline/textStages.test.jsindex 404232ab75..c5a486e56b 100644--- a/server/services/pipeline/textStages.test.js+++ b/server/services/pipeline/textStages.test.js@@ -118,4 +118,49 @@ describe('pipeline text stage generator', () => {const { issue } = await seed();await expect(textStages.generateStage(issue.id, 'comicPages')).rejects.toThrow(/unsupported stageId/);});++ it('prompt context carries lengthTargets from a named non-default profile (extended)', async () => {+ const { series } = await seed();+ // Create an issue with the 'extended' profile — distinct from 'standard' so+ // any accidental fallback to standard is detectable via pageTarget (32 vs 22).+ const issue = await issuesSvc.createIssue({+ seriesId: series.id,+ title: 'The Surge',+ lengthProfile: 'extended',+ });+ await textStages.generateStage(issue.id, 'idea');+ const ctx = JSON.parse(llmCalls[0].prompt.replace(/^RENDERED:[^:]+:/, ''));+ const lt = ctx.lengthTargets;+ expect(lt.profile).toBe('extended');+ expect(lt.pageTarget).toBe(32);+ expect(lt.minutesTarget).toBe(36);+ expect(lt.proseWordsMin).toBe(4500);+ expect(lt.proseWordsMax).toBe(6500);+ expect(lt.beatsMin).toBe(12);+ expect(lt.beatsMax).toBe(16);+ });++ it('prompt context carries derived lengthTargets for the custom profile', async () => {+ const { series } = await seed();+ // 44 pages is 2× the standard 22-page baseline, so all derived ranges+ // should also double. minutesTarget is stored as-is (not derived).+ const issue = await issuesSvc.createIssue({+ seriesId: series.id,+ title: 'The Override',+ lengthProfile: 'custom',+ pageTarget: 44,+ minutesTarget: 50,+ });+ await textStages.generateStage(issue.id, 'idea');+ const ctx = JSON.parse(llmCalls[0].prompt.replace(/^RENDERED:[^:]+:/, ''));+ const lt = ctx.lengthTargets;+ expect(lt.profile).toBe('custom');+ expect(lt.pageTarget).toBe(44);+ expect(lt.minutesTarget).toBe(50);+ // scale = 44/22 = 2 → proseWords: 2500×2=5000, 4000×2=8000; beats: 8×2=16, 12×2=24+ expect(lt.proseWordsMin).toBe(5000);+ expect(lt.proseWordsMax).toBe(8000);+ expect(lt.beatsMin).toBe(16);+ expect(lt.beatsMax).toBe(24);+ });});diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.jsindex ef961c928c..fb64a04a63 100644--- a/server/services/pipeline/visualStages.js+++ b/server/services/pipeline/visualStages.js@@ -41,8 +41,6 @@ import { runPromptRefine } from './refineHelpers.js';import { resolveSeriesCanonSync } from './seriesCanon.js';import { ASPECT_PRESETS } from '../../lib/creativeDirectorPresets.js';-const SUPPORTED_MODES = new Set(['local', 'codex']);-const stackStyle = (series, extraStyle) =>[series?.styleNotes, extraStyle].map((s) => (s || '').trim()).filter(Boolean).join(', ');@@ -51,10 +49,27 @@ const applyWorldStyle = (prompt, world) => {return composeStyledPrompt(prompt, '', { prompt: world.stylePrompt, negativePrompt: '' }).prompt;};+// Resolution order for the image-gen mode on a pipeline visual stage:+// 1. Per-request override (`options.mode`) — set by the stage's persisted+// `genConfig` or an explicit UI selection. Codex is only honored when+// `imageGen.codex.enabled` is true; a stale 'codex' override from+// before the toggle was turned off falls through to the next step.+// 2. Saved dispatcher default (`settings.imageGen.mode`) — but only when+// it names a mode this surface supports (visual pipeline doesn't+// proxy the external SD-API path) AND, for 'codex', Codex is enabled.+// 3. Auto-default — prefer Codex when the user has enabled it+// (`imageGen.codex.enabled`), since cloud image gen produces+// print-quality comic pages out of the box. Otherwise fall back to+// local diffusion (flux-1) the way the original default behaved.const resolveMode = (options, settings) => {- if (SUPPORTED_MODES.has(options.mode)) return options.mode;+ const codexEnabled = settings?.imageGen?.codex?.enabled === true;+ if (options.mode === 'codex' && codexEnabled) return 'codex';+ if (options.mode === 'local') return 'local';const settingsMode = settings?.imageGen?.mode;- return SUPPORTED_MODES.has(settingsMode) ? settingsMode : 'local';+ if (settingsMode === 'codex' && codexEnabled) return 'codex';+ if (settingsMode === 'local') return 'local';+ if (codexEnabled) return 'codex';+ return 'local';};const loadBibleContext = async (issueId) => {@@ -157,6 +172,75 @@ function formatBalloon(character, line) {return `Speech balloon reads: "${cleanText}" ${attribution}.`;}+/**+ * Compose a comic-book front-cover prompt. The cover always renders the+ * series masthead (logo-style title) and the issue number tag in the+ * canonical top-of-cover position, plus the user's cover concept as the+ * scene content. Falls back to the issue title when the user has not+ * written a cover concept yet.+ *+ * Returns the full prompt string (with world style baked in when present).+ */+export function composeComicCoverPrompt({+ series, world, issue, coverScript = '', extraStyle = '',+}) {+ const seriesName = (series?.name || '').trim();+ const issueNumber = Number.isFinite(issue?.number) ? Math.max(1, Math.floor(issue.number)) : 1;+ const issueTitle = (issue?.title || '').trim();+ const concept = (coverScript || '').trim();++ const styleStack = stackStyle(series, extraStyle);+ const styleClause = styleStack ? ` Art style: ${styleStack}.` : '';++ // Title-block requirements get spelled out explicitly because cover-art+ // typography is the part image-gen models get most wrong on the first+ // pass — without a hard cue the model often emits panels instead of+ // a cover, or skips the issue-number tag.+ const titleBlock = seriesName+ ? `Render the series masthead "${seriesName}" as bold, large comic-book logo typography near the top of the cover.`+ : 'Render a bold comic-book series masthead as large logo typography near the top of the cover.';+ const numberBlock = `Include a clearly legible issue-number tag reading "#${issueNumber}" in the top-left corner — small but readable.`;+ const titleLine = issueTitle+ ? ` Include the issue title "${issueTitle}" as a secondary banner below the masthead.`+ : '';++ // Fall back to the issue title so a one-click render against a fresh cover+ // still produces something thematically on-target instead of a blank canvas.+ const sceneDescription = concept+ || (issueTitle ? `A single dramatic hero image evoking "${issueTitle}".` : 'A single dramatic hero image of the protagonist mid-action.');++ const layout = `A single full printable comic-book front cover for a serialized issue. ${titleBlock} ${numberBlock}${titleLine} The rest of the cover is one bold hero image (no panel borders, no multi-panel layout — this is the cover, not an interior page).${styleClause}`;+ const body = `Cover concept: ${sceneDescription}`;+ return applyWorldStyle(`${layout}\n\n${body}`, world);+}++/**+ * Enqueue a comic-issue front-cover image render. Builds a cover-art+ * prompt (series masthead + issue-number tag + user's cover concept) and+ * hands it to the image-gen queue. Caller records the returned jobId on+ * `stages.comicPages.cover.imageJobId`.+ *+ * Returns the resolved coverScript alongside { jobId, mode, prompt } so+ * the route can persist it without a second read of the issue file.+ */+export async function enqueueComicCover(issueId, options = {}) {+ const { issue, settings, series, world } = await loadBibleContext(issueId);+ const cover = issue.stages?.comicPages?.cover || null;+ const coverScript = typeof options.coverScript === 'string'+ ? options.coverScript+ : (cover?.script || '');+ const mode = resolveMode(options, settings);+ const prompt = composeComicCoverPrompt({+ series, world, issue, coverScript, extraStyle: options.extraStyle,+ });+ const jobId = enqueueImageJob({+ prompt, world, settings, options, mode,+ owner: `pipeline:${issueId}:comicPages:cover`,+ logLine: `🎨 Pipeline comic cover — issue=${issueId.slice(0, 8)} number=${issue.number || 1}`,+ });+ return { jobId, mode, prompt, coverScript };+}+export function composeComicPagePrompt({series, world, page, pageNumber, extraStyle = '',matchedCharacters = [], matchedSettings = [], matchedObjects = [],diff --git a/server/services/pipeline/visualStages.test.js b/server/services/pipeline/visualStages.test.jsindex 9a553e0af5..f714946032 100644--- a/server/services/pipeline/visualStages.test.js+++ b/server/services/pipeline/visualStages.test.js@@ -66,6 +66,8 @@ vi.mock('../../lib/mediaModels.js', () => ({const {composeComicPagePrompt,+ composeComicCoverPrompt,+ enqueueComicCover,enqueueStoryboardSceneVideo,refineComicPanelPrompt,refineStoryboardScenePrompt,@@ -319,6 +321,197 @@ describe('refineComicPanelPrompt', () => {});});+describe('composeComicCoverPrompt', () => {+ const SERIES_NAMED = { name: 'Bone Walker', styleNotes: 'gritty ink-wash' };++ it('includes the masthead text, the issue-number tag, and the cover concept body', () => {+ const prompt = composeComicCoverPrompt({+ series: SERIES_NAMED,+ issue: { number: 7, title: 'The Long Sweep' },+ coverScript: 'Kessa crouches on the rib spine at dawn.',+ });+ expect(prompt).toMatch(/series masthead "Bone Walker"/);+ expect(prompt).toMatch(/issue-number tag reading "#7"/);+ expect(prompt).toMatch(/Cover concept: Kessa crouches on the rib spine at dawn\./);+ expect(prompt).toMatch(/issue title "The Long Sweep"/);+ expect(prompt).toMatch(/Art style: gritty ink-wash/);+ });++ it('falls back to the issue title when no cover concept is supplied', () => {+ const prompt = composeComicCoverPrompt({+ series: SERIES_NAMED,+ issue: { number: 1, title: 'Sunrise' },+ coverScript: '',+ });+ expect(prompt).toMatch(/Cover concept: A single dramatic hero image evoking "Sunrise"\./);+ });++ it('falls back to a generic hero image when neither cover concept nor issue title is set', () => {+ const prompt = composeComicCoverPrompt({+ series: SERIES_NAMED,+ issue: { number: 1, title: '' },+ coverScript: '',+ });+ expect(prompt).toMatch(/A single dramatic hero image of the protagonist mid-action\./);+ });++ it('emits a generic masthead instruction when the series has no name', () => {+ const prompt = composeComicCoverPrompt({+ series: { name: '', styleNotes: '' },+ issue: { number: 3, title: 'X' },+ coverScript: 'something',+ });+ expect(prompt).toMatch(/Render a bold comic-book series masthead/);+ // No empty quoted masthead string leaks through.+ expect(prompt).not.toMatch(/masthead ""/);+ });++ it('clamps a non-positive issue number to 1 for the visible tag', () => {+ const prompt = composeComicCoverPrompt({+ series: SERIES_NAMED,+ issue: { number: 0, title: '' },+ coverScript: '',+ });+ expect(prompt).toMatch(/issue-number tag reading "#1"/);+ });++ it('prepends world.stylePrompt when a world is provided', () => {+ const world = { stylePrompt: 'cinematic ink illustration, dramatic lighting', negativePrompt: '' };+ const prompt = composeComicCoverPrompt({+ series: SERIES_NAMED,+ world,+ issue: { number: 1, title: 'X' },+ coverScript: 'something',+ });+ expect(prompt).toMatch(/cinematic ink illustration/);+ });+});++describe('enqueueComicCover', () => {+ beforeEach(() => {+ // Default mock chain: getIssue returns mockIssue with no cover, settings+ // returns local mode. Each test can override `getIssueMock` for special cases.+ getIssueMock.mockImplementation(async () => ({+ ...structuredClone(mockIssue),+ number: 5,+ title: 'Hero Issue',+ }));+ });++ it('builds the cover prompt and enqueues a local image job by default', async () => {+ const result = await enqueueComicCover('iss-test', {});+ expect(result.jobId).toBe('job-fake-1234');+ expect(result.mode).toBe('local');+ expect(result.prompt).toMatch(/issue-number tag reading "#5"/);+ expect(enqueueJobMock).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'image',+ owner: 'pipeline:iss-test:comicPages:cover',+ params: expect.objectContaining({+ pythonPath: '/usr/bin/python3',+ prompt: expect.stringContaining('Cover concept:'),+ }),+ }));+ });++ it('uses the option-supplied coverScript over the persisted stages.comicPages.cover.script', async () => {+ getIssueMock.mockResolvedValueOnce({+ ...structuredClone(mockIssue),+ number: 2,+ title: 'X',+ stages: {+ ...mockIssue.stages,+ comicPages: {+ ...mockIssue.stages.comicPages,+ cover: { script: 'persisted concept' },+ },+ },+ });+ const result = await enqueueComicCover('iss-test', { coverScript: 'fresh override concept' });+ expect(result.coverScript).toBe('fresh override concept');+ expect(result.prompt).toMatch(/Cover concept: fresh override concept/);+ expect(result.prompt).not.toMatch(/persisted concept/);+ });++ it('falls back to the persisted cover.script when no coverScript option is supplied', async () => {+ getIssueMock.mockResolvedValueOnce({+ ...structuredClone(mockIssue),+ number: 2,+ title: 'X',+ stages: {+ ...mockIssue.stages,+ comicPages: {+ ...mockIssue.stages.comicPages,+ cover: { script: 'persisted concept' },+ },+ },+ });+ const result = await enqueueComicCover('iss-test', {});+ expect(result.coverScript).toBe('persisted concept');+ expect(result.prompt).toMatch(/Cover concept: persisted concept/);+ });++ it('honors options.mode = "codex" when codex is enabled', async () => {+ const settingsMod = await import('../settings.js');+ settingsMod.getSettings.mockResolvedValueOnce({+ imageGen: {+ local: { pythonPath: '/usr/bin/python3' },+ mode: 'local',+ codex: { enabled: true, codexPath: '/usr/local/bin/codex', model: 'dall-e-3' },+ },+ videoGen: {},+ });+ const result = await enqueueComicCover('iss-test', { mode: 'codex' });+ expect(result.mode).toBe('codex');+ expect(enqueueJobMock).toHaveBeenCalledWith(expect.objectContaining({+ params: expect.objectContaining({ mode: 'codex' }),+ }));+ });++ it('falls back to local when options.mode = "codex" but codex toggle is off', async () => {+ const settingsMod = await import('../settings.js');+ settingsMod.getSettings.mockResolvedValueOnce({+ imageGen: {+ local: { pythonPath: '/usr/bin/python3' },+ mode: 'local',+ codex: { enabled: false },+ },+ videoGen: {},+ });+ const result = await enqueueComicCover('iss-test', { mode: 'codex' });+ expect(result.mode).toBe('local');+ expect(enqueueJobMock).toHaveBeenCalledWith(expect.objectContaining({+ params: expect.objectContaining({ pythonPath: '/usr/bin/python3' }),+ }));+ });++ it('falls back to local when settings.imageGen.mode = "codex" but codex toggle is off', async () => {+ const settingsMod = await import('../settings.js');+ settingsMod.getSettings.mockResolvedValueOnce({+ imageGen: {+ local: { pythonPath: '/usr/bin/python3' },+ mode: 'codex',+ codex: { enabled: false },+ },+ videoGen: {},+ });+ const result = await enqueueComicCover('iss-test', {});+ expect(result.mode).toBe('local');+ });++ it('auto-selects codex when codex is enabled and no mode is pinned', async () => {+ const settingsMod = await import('../settings.js');+ settingsMod.getSettings.mockResolvedValueOnce({+ imageGen: {+ local: { pythonPath: '/usr/bin/python3' },+ codex: { enabled: true, codexPath: '/usr/local/bin/codex', model: 'dall-e-3' },+ },+ videoGen: {},+ });+ const result = await enqueueComicCover('iss-test', {});+ expect(result.mode).toBe('codex');+ });+});+describe('refineStoryboardScenePrompt', () => {it('rejects a non-integer sceneIndex', async () => {await expect(refineStoryboardScenePrompt('iss-test', 'nope')).rejects.toThrow(/non-negative integer/);