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): issue back covers + volume covers + trade-paperback PDF
[._.]/ Adam Eivyd802eb1823d9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex a83f317504..ba3a152053 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## Added+- **Pipeline — issue back covers + volume (trade-paperback) covers + volume PDF.** Every comic issue now generates both a front and a back cover concept as part of the LLM comic-script pass (new `## Back cover concept` section, parsed alongside the existing `## Cover concept`). Both renders use the proof/final workflow and ship in the issue PDF as `cover → pages → back → colophon`. Each volume (season) gets its own front + back cover concepts via a new per-season LLM step (`POST /series/:id/seasons/:seasonId/cover-concepts/generate`) that seeds `season.cover.script` / `season.backCover.script` when blank (never clobbers user edits). The new `GET /series/:id/seasons/:seasonId/volume.pdf` compiles a full trade paperback: `[vol front] → [issue1 front → issue1 pages → issue1 back] → [issue2 …] → [vol back] → colophon`, sorted by `arcPosition ?? number`. Existing seasons get a "Generate cover concepts (LLM)" + "Compile volume PDF" button on each Arc canvas row to backfill. Migration `011-comic-script-back-cover.js` adds the back-cover section to the installed comic-script prompt for unmodified installs.- **Universe Builder — per-category "Generate N more" variations.** Each category card now has a Generate dropdown (3 / 5 / 10 / custom up to 50) next to the existing Render / + Add buttons. The LLM is given the universe's bible context (logline, premise, style notes, influences) plus the list of existing labels to skip, and returns N additional variations that get appended to the category. Locked items are unaffected — Generate is purely additive. Auto-saves when the universe is already persisted; otherwise hands you a "review then Save" toast. New endpoint: `POST /api/universe-builder/generate-variations`.## Changeddiff --git a/client/src/components/pipeline/ArcCanvas.jsx b/client/src/components/pipeline/ArcCanvas.jsxindex b6f008670f..1034cd5483 100644--- a/client/src/components/pipeline/ArcCanvas.jsx+++ b/client/src/components/pipeline/ArcCanvas.jsx@@ -28,6 +28,7 @@ import { Link } from 'react-router-dom';import {Plus, Trash2, Loader2, Sparkles, ShieldCheck, ChevronRight, ChevronDown,ChevronsUpDown, AlertCircle, Wand2, Info, ListChecks, X, Lock, Unlock,+ ImageIcon, Layers, FileDown,} from 'lucide-react';import toast from '../ui/Toast';import { timeAgo } from '../../utils/formatters';@@ -40,6 +41,9 @@ import {resolvePipelineArcIssues,listPipelineIssues, updatePipelineSeries,startPipelineVolumeBeats, cancelPipelineVolumeBeats,+ generatePipelineVolumeCover, generatePipelineVolumeBackCover,+ generatePipelineVolumeCoverConcepts,+ pipelineVolumePdfUrl,} from '../../services/api';import { usePipelineVolumeBeatsProgress } from '../../hooks/usePipelineVolumeBeatsProgress';import SeriesLlmPicker from './SeriesLlmPicker';@@ -989,6 +993,12 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUp/></div>) : null}+ <VolumeCoversPanel+ series={series}+ season={season}+ seasons={seasons}+ onSeriesUpdate={onSeriesUpdate}+ /><SeasonActionsseries={series}season={season}@@ -1011,6 +1021,258 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUp);}+// Tiny thumb cell — shows the rendered image when present, an empty-state+// dashed box otherwise. Smaller and dependency-free vs ComicScriptStage's+// MediaJobThumb (which tracks live job status); for the Arc canvas's at-a-+// glance row we only need the persisted-filename render.+function VolumeCoverThumb({ slot, label, emptyHint }) {+ const filename = slot?.filename || null;+ return (+ <div className="space-y-1">+ <div className="text-[10px] uppercase tracking-wider text-gray-500">{label}</div>+ {filename ? (+ <a+ href={`/data/images/${filename}`}+ target="_blank"+ rel="noreferrer"+ className="block aspect-[3/4] bg-port-bg border border-port-border rounded overflow-hidden hover:border-port-accent/40"+ >+ <img src={`/data/images/${filename}`} alt={label} className="w-full h-full object-cover" />+ </a>+ ) : (+ <div className="aspect-[3/4] bg-port-bg border border-dashed border-port-border rounded flex items-center justify-center text-[10px] text-gray-500 text-center p-2">+ {emptyHint}+ </div>+ )}+ </div>+ );+}++function VolumeCoversPanel({ series, season, seasons, onSeriesUpdate }) {+ const [expanded, setExpanded] = useState(false);+ const cover = season.cover || { script: '', proofImage: null, finalImage: null };+ const backCover = season.backCover || { script: '', proofImage: null, finalImage: null };++ // Local draft text so keystrokes don't round-trip until blur.+ const [draftCover, setDraftCover] = useState(cover.script || '');+ const [draftBack, setDraftBack] = useState(backCover.script || '');+ useEffect(() => { setDraftCover(cover.script || ''); }, [cover.script]);+ useEffect(() => { setDraftBack(backCover.script || ''); }, [backCover.script]);++ const [generatingConcepts, setGeneratingConcepts] = useState(false);+ // One in-flight flag per target × variant. Indexed object so the four+ // render buttons share an enable/disable shape without a 4-bool sprawl.+ const [busy, setBusy] = useState({ coverProof: false, coverFinal: false, backProof: false, backFinal: false });++ // Splice the updated season back into series.seasons[] in place — never+ // refetch the series list when a partial update will do.+ const replaceSeasonInSeries = (updatedSeason) => {+ if (!updatedSeason) return;+ onSeriesUpdate({+ ...series,+ seasons: (seasons || []).map((s) => (s.id === updatedSeason.id ? updatedSeason : s)),+ });+ };++ const persistScript = async (target, nextScript) => {+ const updatedSeason = await updatePipelineSeason(series.id, season.id, {+ [target]: { script: nextScript },+ }).catch((err) => {+ toast.error(err.message || 'Save failed');+ return null;+ });+ if (updatedSeason) replaceSeasonInSeries(updatedSeason);+ };++ const handleGenerateConcepts = async () => {+ setGeneratingConcepts(true);+ const result = await generatePipelineVolumeCoverConcepts(series.id, season.id, {+ commit: true,+ providerOverride: series.llm?.provider || undefined,+ modelOverride: series.llm?.model || undefined,+ }).catch((err) => {+ toast.error(err.message || 'Failed to generate cover concepts');+ return null;+ });+ setGeneratingConcepts(false);+ if (!result) return;+ if (result.series) {+ // Server returned the full updated series — use it for the in-place splice.+ onSeriesUpdate(result.series);+ } else if (result.season) {+ replaceSeasonInSeries(result.season);+ }+ const parts = [];+ if (result.seeded?.cover) parts.push('front');+ if (result.seeded?.backCover) parts.push('back');+ if (parts.length === 0) {+ toast.success('Cover concepts generated (existing edits preserved)');+ } else {+ toast.success(`Volume ${season.number} ${parts.join(' + ')} cover concept${parts.length > 1 ? 's' : ''} seeded`);+ }+ };++ const handleRender = async (target, variant) => {+ const busyKey = `${target === 'cover' ? 'cover' : 'back'}${variant === 'final' ? 'Final' : 'Proof'}`;+ setBusy((b) => ({ ...b, [busyKey]: true }));+ const apiCall = target === 'cover' ? generatePipelineVolumeCover : generatePipelineVolumeBackCover;+ const scriptKey = target === 'cover' ? 'coverScript' : 'backCoverScript';+ const draftText = target === 'cover' ? draftCover : draftBack;+ const label = target === 'cover' ? 'cover' : 'back cover';+ const result = await apiCall(series.id, season.id, {+ [scriptKey]: draftText || '',+ target: variant,+ }, { silent: true }).catch((err) => {+ toast.error(err.message || `Failed to render ${variant} ${label}`);+ return null;+ });+ setBusy((b) => ({ ...b, [busyKey]: false }));+ if (!result) return;+ if (result.series) onSeriesUpdate(result.series);+ else if (result.season) replaceSeasonInSeries(result.season);+ toast.success(`Queued ${result.mode} volume ${variant} ${label} render (${result.jobId.slice(0, 8)})`);+ };++ // PDF readiness mirrors the server's pickRenderedFilename fallback chain+ // (finalImage → proofImage → legacy filename) — see lib/renderSlot.js.+ const volCoverRendered = !!(cover.finalImage?.filename || cover.proofImage?.filename || cover.filename);+ const volPdfReady = volCoverRendered;+ const volPdfHref = volPdfReady ? pipelineVolumePdfUrl(series.id, season.id) : undefined;+ const volPdfTitle = volPdfReady+ ? 'Compile a trade-paperback PDF — volume front + every issue (cover, pages, back) + volume back.'+ : 'Render the volume front cover first.';++ return (+ <div className="px-3 pb-3 border-t border-port-border/50 pt-2 space-y-2">+ <div className="flex items-center gap-2 flex-wrap">+ <button+ type="button"+ onClick={() => setExpanded(!expanded)}+ className="inline-flex items-center gap-1 text-xs text-gray-300 hover:text-white"+ aria-expanded={expanded}+ >+ {expanded ? <ChevronDown size={12} /> : <ChevronRight size={12} />}+ Volume covers+ <span className="text-[10px] text-gray-500">+ {volCoverRendered ? '(front rendered)' : '(none yet)'}+ </span>+ </button>+ <button+ type="button"+ onClick={handleGenerateConcepts}+ disabled={generatingConcepts}+ title="Have the LLM propose front + back cover concepts for the volume"+ className="ml-auto inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-port-accent hover:text-white border border-port-border bg-port-bg hover:border-port-accent/40 disabled:opacity-40"+ >+ {generatingConcepts ? <Loader2 size={12} className="animate-spin" /> : <Wand2 size={12} />}+ Generate cover concepts (LLM)+ </button>+ <a+ href={volPdfHref}+ aria-disabled={!volPdfReady}+ onClick={(e) => { if (!volPdfReady) e.preventDefault(); }}+ title={volPdfTitle}+ className={`inline-flex items-center gap-1 px-2 py-1 rounded text-xs border ${+ volPdfReady+ ? 'text-white bg-port-card border-port-border hover:border-port-accent/50'+ : 'text-gray-500 bg-port-card border-port-border cursor-not-allowed'+ }`}+ >+ <FileDown size={12} /> Compile volume PDF+ </a>+ </div>++ {expanded ? (+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3">+ <VolumeCoverEditorBox+ label="Front cover"+ record={cover}+ draft={draftCover}+ setDraft={setDraftCover}+ onPersist={(next) => persistScript('cover', next)}+ onRenderProof={() => handleRender('cover', 'proof')}+ onRenderFinal={() => handleRender('cover', 'final')}+ renderingProof={busy.coverProof}+ renderingFinal={busy.coverFinal}+ placeholder="Volume front cover concept — iconic image for the whole volume. Series masthead + 'Vol. N' tag added by the renderer."+ proofTitle="Render a fast proof of the volume front cover"+ finalTitle="Render the hi-res final volume front cover"+ />+ <VolumeCoverEditorBox+ label="Back cover"+ record={backCover}+ draft={draftBack}+ setDraft={setDraftBack}+ onPersist={(next) => persistScript('backCover', next)}+ onRenderProof={() => handleRender('backCover', 'proof')}+ onRenderFinal={() => handleRender('backCover', 'final')}+ renderingProof={busy.backProof}+ renderingFinal={busy.backFinal}+ placeholder="Volume back cover concept — illustration only. No text, no masthead. Quiet companion image."+ proofTitle="Render a fast proof of the volume back cover"+ finalTitle="Render the hi-res final volume back cover"+ />+ </div>+ ) : null}+ </div>+ );+}++// One panel inside VolumeCoversPanel — header (label + 2 render buttons),+// editable script textarea, and the 2-thumb proof/final row. The front-+// and back-cover panels are structurally identical; props carry only what+// actually differs (label, persisted record, render handlers, placeholder).+function VolumeCoverEditorBox({+ label, record, draft, setDraft, onPersist,+ onRenderProof, onRenderFinal, renderingProof, renderingFinal,+ placeholder, proofTitle, finalTitle,+}) {+ return (+ <div className="space-y-2 p-2 bg-port-bg border border-port-border rounded">+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <span className="text-xs uppercase tracking-wider text-gray-500">{label}</span>+ <div className="flex items-center gap-1">+ <button+ type="button"+ onClick={onRenderProof}+ disabled={renderingProof}+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs bg-port-accent text-white hover:bg-port-accent/90 disabled:opacity-40"+ title={proofTitle}+ >+ {renderingProof ? <Loader2 size={10} className="animate-spin" /> : <ImageIcon size={10} />}+ Proof+ </button>+ <button+ type="button"+ onClick={onRenderFinal}+ disabled={renderingFinal}+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs bg-port-accent text-white hover:bg-port-accent/90 disabled:opacity-40"+ title={finalTitle}+ >+ {renderingFinal ? <Loader2 size={10} className="animate-spin" /> : <Layers size={10} />}+ Final+ </button>+ </div>+ </div>+ <textarea+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onBlur={() => {+ if ((record.script || '') !== draft) onPersist(draft);+ }}+ placeholder={placeholder}+ rows={3}+ className="w-full px-2 py-1 bg-port-card border border-port-border rounded text-white text-xs"+ maxLength={8000}+ />+ <div className="grid grid-cols-2 gap-2">+ <VolumeCoverThumb slot={record.proofImage} label="Proof" emptyHint="No proof yet." />+ <VolumeCoverThumb slot={record.finalImage} label="Final" emptyHint="No final yet." />+ </div>+ </div>+ );+}+function SeasonEditor({ series, season, seasons, onSeriesUpdate }) {const [draft, setDraft] = useState(season);const [saving, setSaving] = useState(false);diff --git a/client/src/components/pipeline/stages/ComicScriptStage.jsx b/client/src/components/pipeline/stages/ComicScriptStage.jsxindex b688b85797..4329fb7c3a 100644--- a/client/src/components/pipeline/stages/ComicScriptStage.jsx+++ b/client/src/components/pipeline/stages/ComicScriptStage.jsx@@ -16,6 +16,7 @@ import {extractPipelineComicPages,generatePipelineComicPage,generatePipelineComicCover,+ generatePipelineComicBackCover,updatePipelineComicPage,updatePipelineIssue,updateIssueStageVisualStyle,@@ -251,36 +252,52 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actionsconst 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.+ // Front + back cover live on stages.comicPages.cover / .backCover; both+ // persist alongside the page renders. Each owns a draft string separate+ // from the persisted value so keystrokes don't round-trip until blur.const cover = comicPages.cover || { script: '', proofImage: null, finalImage: null };const coverProof = getProofSlot(cover);const coverFinal = getFinalSlot(cover);const [draftCoverScript, setDraftCoverScript] = useState(cover.script || '');useEffect(() => { setDraftCoverScript(cover.script || ''); }, [cover.script]);- const [renderingCoverProof, setRenderingCoverProof] = useState(false);- const [renderingCoverFinal, setRenderingCoverFinal] = useState(false);- const [useProofForCoverFinal, setUseProofForCoverFinal] = useState(true);const { inFlight: coverProofInFlight, setStatus: setCoverProofStatus } = useSlotInFlight(coverProof);const { inFlight: coverFinalInFlight, setStatus: setCoverFinalStatus } = useSlotInFlight(coverFinal);- // Codex CLI's `$imagegen` has no init-image input, so the "use proof as- // base" upscale path can't preserve composition there. Disable the- // checkbox + show a tooltip when codex is the active backend.+ const backCover = comicPages.backCover || { script: '', proofImage: null, finalImage: null };+ const backProof = getProofSlot(backCover);+ const backFinal = getFinalSlot(backCover);+ const [draftBackCoverScript, setDraftBackCoverScript] = useState(backCover.script || '');+ useEffect(() => { setDraftBackCoverScript(backCover.script || ''); }, [backCover.script]);+ const { inFlight: backProofInFlight, setStatus: setBackProofStatus } = useSlotInFlight(backProof);+ const { inFlight: backFinalInFlight, setStatus: setBackFinalStatus } = useSlotInFlight(backFinal);++ // One indexed busy map for all four cover×variant render buttons —+ // collapses what would otherwise be four useState booleans and the+ // nested ternaries needed to pick the right setter inside the shared+ // render handler.+ const [busy, setBusy] = useState({ coverProof: false, coverFinal: false, backProof: false, backFinal: false });+ const setBusyFor = (target, variant, value) => {+ const key = `${target === 'backCover' ? 'back' : 'cover'}${variant === 'final' ? 'Final' : 'Proof'}`;+ setBusy((b) => ({ ...b, [key]: value }));+ };++ // i2i "from proof" toggles are independent per cover field — Codex+ // backend can't honor i2i regardless, so the toggle is disabled there.+ const [useProofForCoverFinal, setUseProofForCoverFinal] = useState(true);+ const [useProofForBackFinal, setUseProofForBackFinal] = useState(true);+const i2iSupported = imageCfg.mode !== 'codex';const i2iDisabledReason = i2iSupported? null: 'Codex (gpt-image-2) does not support image-to-image. Switch backend in the image-gen settings to use the proof as a base.';- 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.+ // Shared script-persist (cover / backCover) — server-side updatePipelineIssue+ // does a deep merge under stages.comicPages.<field>. Only the script text+ // is sent; render slots are written exclusively by the render route to+ // avoid blur-vs-render race conditions.+ const persistCoverFieldScript = async (field, nextScript) => {const updated = await updatePipelineIssue(issue.id, {- stages: { comicPages: { cover: { script: nextScript } } },+ stages: { comicPages: { [field]: { script: nextScript } } },}).catch((err) => {toast.error(err.message || 'Save failed');return null;@@ -288,26 +305,31 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actionsif (updated) onStageUpdate?.('comicPages', updated.stages.comicPages, updated);};- const handleRenderCover = async (target) => {- const setFlight = target === 'final' ? setRenderingCoverFinal : setRenderingCoverProof;- setFlight(true);- const useProofAsBase = target === 'final' && useProofForCoverFinal && i2iSupported;- const result = await generatePipelineComicCover(issue.id, {- coverScript: draftCoverScript || '',+ const handleRenderCoverField = async (field, variant) => {+ const isBack = field === 'backCover';+ const useProofToggle = isBack ? useProofForBackFinal : useProofForCoverFinal;+ setBusyFor(field, variant, true);+ const useProofAsBase = variant === 'final' && useProofToggle && i2iSupported;+ const draftText = isBack ? draftBackCoverScript : draftCoverScript;+ const apiCall = isBack ? generatePipelineComicBackCover : generatePipelineComicCover;+ const bodyScriptKey = isBack ? 'backCoverScript' : 'coverScript';+ const label = isBack ? 'back cover' : 'cover';+ const result = await apiCall(issue.id, {+ [bodyScriptKey]: draftText || '',...renderOpts,- target,+ target: variant,useProofAsBase,}, { silent: true }).catch((err) => {- toast.error(err.message || `Failed to render ${target} cover`);+ toast.error(err.message || `Failed to render ${variant} ${label}`);return null;});- setFlight(false);+ setBusyFor(field, variant, false);if (!result) return;if (result.issue) {onStageUpdate?.('comicPages', result.issue.stages.comicPages, result.issue);}const suffix = useProofAsBase ? ' (from proof)' : '';- toast.success(`Queued ${result.mode} ${target} cover render${suffix} (${result.jobId.slice(0, 8)})`);+ toast.success(`Queued ${result.mode} ${variant} ${label} render${suffix} (${result.jobId.slice(0, 8)})`);};const overrides = {@@ -348,8 +370,11 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions// PDF assembly's fallback chain prefers final, then proof, then legacy.const isRendered = (rec) => !!getPreferredSlot(rec)?.filename;const pdfRenderedCount = pages.filter(isRendered).length- + (isRendered(comicPages.cover) ? 1 : 0);- const pdfTotal = pages.length + (comicPages.cover ? 1 : 0);+ + (isRendered(comicPages.cover) ? 1 : 0)+ + (isRendered(comicPages.backCover) ? 1 : 0);+ const pdfTotal = pages.length+ + (comicPages.cover ? 1 : 0)+ + (comicPages.backCover ? 1 : 0);const pdfReady = pdfRenderedCount > 0;return (@@ -441,8 +466,8 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions<div className="flex items-center gap-2 flex-wrap"><buttontype="button"- onClick={() => handleRenderCover('proof')}- disabled={renderingCoverProof || coverProofInFlight || actionsGated}+ onClick={() => handleRenderCoverField('cover', 'proof')}+ disabled={busy.coverProof || coverProofInFlight || actionsGated}title={actionsGated? 'Saving settings…': coverProofInFlight@@ -450,7 +475,7 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions: 'Render a fast proof cover at the configured size — 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">- {(renderingCoverProof || coverProofInFlight) ? <Loader2 size={12} className="animate-spin" /> : <ImageIcon size={12} />}+ {(busy.coverProof || coverProofInFlight) ? <Loader2 size={12} className="animate-spin" /> : <ImageIcon size={12} />}Render proof</button><label@@ -468,9 +493,9 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions</label><buttontype="button"- onClick={() => handleRenderCover('final')}+ onClick={() => handleRenderCoverField('cover', 'final')}disabled={- renderingCoverFinal || coverFinalInFlight || actionsGated+ busy.coverFinal || coverFinalInFlight || actionsGated|| (i2iSupported && useProofForCoverFinal && !coverProof?.filename)}title={finalButtonTooltip({@@ -481,7 +506,7 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions})}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">- {(renderingCoverFinal || coverFinalInFlight) ? <Loader2 size={12} className="animate-spin" /> : <Layers size={12} />}+ {(busy.coverFinal || coverFinalInFlight) ? <Loader2 size={12} className="animate-spin" /> : <Layers size={12} />}Render final</button></div>@@ -490,7 +515,7 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actionsvalue={draftCoverScript}onChange={(e) => setDraftCoverScript(e.target.value)}onBlur={() => {- if ((cover.script || '') !== draftCoverScript) persistCoverScript(draftCoverScript);+ if ((cover.script || '') !== draftCoverScript) persistCoverFieldScript('cover', draftCoverScript);}}placeholder="Cover concept — describe the hero image, mood, lighting, framing. Series masthead and issue-number tag included in the prompt automatically."rows={3}@@ -518,6 +543,89 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions) : null}</div>+ <div className="p-3 bg-port-card border border-port-border rounded-lg space-y-2">+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <span className="text-xs uppercase tracking-wider text-gray-500">Back cover</span>+ <div className="flex items-center gap-2 flex-wrap">+ <button+ type="button"+ onClick={() => handleRenderCoverField('backCover', 'proof')}+ disabled={busy.backProof || backProofInFlight || actionsGated}+ title={actionsGated+ ? 'Saving settings…'+ : backProofInFlight+ ? 'Proof render in progress…'+ : 'Render a fast proof back-cover at the configured size — illustration only, no text, no masthead.'}+ 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"+ >+ {(busy.backProof || backProofInFlight) ? <Loader2 size={12} className="animate-spin" /> : <ImageIcon size={12} />}+ Render proof+ </button>+ <label+ className={`flex items-center gap-1 text-[11px] text-gray-400 ${i2iSupported ? 'cursor-pointer' : 'cursor-not-allowed opacity-60'}`}+ title={i2iDisabledReason || 'Use the proof image as the base for the final render — preserves composition.'}+ >+ <input+ type="checkbox"+ checked={i2iSupported && useProofForBackFinal}+ onChange={(e) => setUseProofForBackFinal(e.target.checked)}+ disabled={!i2iSupported}+ className="rounded"+ />+ from proof+ </label>+ <button+ type="button"+ onClick={() => handleRenderCoverField('backCover', 'final')}+ disabled={+ busy.backFinal || backFinalInFlight || actionsGated+ || (i2iSupported && useProofForBackFinal && !backProof?.filename)+ }+ title={finalButtonTooltip({+ gated: actionsGated,+ inFlight: backFinalInFlight,+ needsProof: i2iSupported && useProofForBackFinal && !backProof?.filename,+ defaultMsg: 'Render the hi-res final back-cover at the configured size. Tick "from proof" to upscale the proof rather than redraw it.',+ })}+ 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"+ >+ {(busy.backFinal || backFinalInFlight) ? <Loader2 size={12} className="animate-spin" /> : <Layers size={12} />}+ Render final+ </button>+ </div>+ </div>+ <textarea+ value={draftBackCoverScript}+ onChange={(e) => setDraftBackCoverScript(e.target.value)}+ onBlur={() => {+ if ((backCover.script || '') !== draftBackCoverScript) persistCoverFieldScript('backCover', draftBackCoverScript);+ }}+ placeholder="Back cover concept — illustration only. No text, no masthead. A quiet companion image: a single object, an aftermath beat, a distant silhouette."+ rows={3}+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"+ maxLength={8000}+ />+ {(backProof || backFinal) ? (+ <div className="grid grid-cols-2 gap-2">+ <RenderSlotThumb+ slot={backProof}+ label="Proof"+ thumbLabel="Proof"+ emptyHint="No proof yet."+ onStatus={setBackProofStatus}+ />+ <RenderSlotThumb+ slot={backFinal}+ label="Final"+ thumbLabel="Final"+ emptyHint="No final yet."+ onStatus={setBackFinalStatus}+ fillFromProofLabel+ />+ </div>+ ) : null}+ </div>+<ul className="space-y-4">{pages.map((page, pi) => (<PageRowdiff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex 46d32129eb..9eeee10271 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -187,6 +187,53 @@ export const generatePipelineComicCover = (issueId, opts = {}, options = {}) =>...options,});+// Render the issue's back cover. Same flow as the front cover wrapper above+// but body field is `backCoverScript` and the persisted slot is+// stages.comicPages.backCover. Server enforces an illustration-only prompt+// (no masthead, no text). Returns { jobId, mode, prompt, backCover, issue, stage }.+export const generatePipelineComicBackCover = (issueId, opts = {}, options = {}) =>+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/comicPages/back-cover/render`, {+ method: 'POST',+ body: JSON.stringify(opts),+ ...options,+ });++// Volume (season) cover render. Persists in-flight slot on+// series.seasons[].cover via the season write tail.+// Returns { jobId, mode, prompt, coverScript, season, series, variant, fromProof }.+export const generatePipelineVolumeCover = (seriesId, seasonId, opts = {}, options = {}) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/seasons/${encodeURIComponent(seasonId)}/cover/render`, {+ method: 'POST',+ body: JSON.stringify(opts),+ ...options,+ });++// Volume back-cover render — same shape, lands on season.backCover.+export const generatePipelineVolumeBackCover = (seriesId, seasonId, opts = {}, options = {}) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/seasons/${encodeURIComponent(seasonId)}/back-cover/render`, {+ method: 'POST',+ body: JSON.stringify(opts),+ ...options,+ });++// Ask the LLM to propose front + back cover concepts for the volume.+// Pass { commit: true } to also seed `season.cover.script` /+// `season.backCover.script` when those slots are currently blank (the+// server never clobbers a user edit). Returns the proposed text plus the+// updated season + series records.+export const generatePipelineVolumeCoverConcepts = (seriesId, seasonId, opts = {}) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/seasons/${encodeURIComponent(seasonId)}/cover-concepts/generate`, {+ method: 'POST',+ body: JSON.stringify(opts),+ });++// Build the trade-paperback PDF download URL for one volume. Used as an+// <a href> so the browser streams the response straight to disk.+export const pipelineVolumePdfUrl = (seriesId, seasonId, { size } = {}) => {+ const qs = size ? `?size=${encodeURIComponent(size)}` : '';+ return `/api/pipeline/series/${encodeURIComponent(seriesId)}/seasons/${encodeURIComponent(seasonId)}/volume.pdf${qs}`;+};+// 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 0835185b0d..4ee97b4f89 100644--- a/data.sample/prompts/stages/pipeline-comic-script.md+++ b/data.sample/prompts/stages/pipeline-comic-script.md@@ -39,6 +39,15 @@ the front cover. Focus on subject, framing, mood, and a striking visualdetail. The cover renderer composes the masthead + issue-number tagitself, so do NOT describe text or typography here — just the scene.>+## Back cover concept++<2–4 sentence back-cover concept: a SINGLE atmospheric illustration that+complements (not duplicates) the front cover. Quieter, often a counterpoint+— a single object, a silhouette at distance, an environmental detail, an+aftermath beat. NO text, NO masthead, NO logos, NO panel borders — the+renderer will explicitly forbid typography. Focus on subject, framing,+mood, and a striking visual detail.>+## Page 1Panel 1@@ -68,4 +77,4 @@ Panel 2- Never re-describe a character's permanent appearance once introduced; just name them.- 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. 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}}.+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 the `## Back 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-volume-cover-concepts.md b/data.sample/prompts/stages/pipeline-volume-cover-concepts.mdnew file mode 100644index 0000000000..4a8cc03867--- /dev/null+++ b/data.sample/prompts/stages/pipeline-volume-cover-concepts.md@@ -0,0 +1,38 @@+# Pipeline — Volume cover concepts++You are an art director for a collected-edition (trade paperback) comic-book volume. Produce a FRONT cover concept and a BACK cover concept for the volume below. Both are pure scene descriptions for an image-gen model — the comic's masthead, volume number, and any title typography are added by the renderer, so do NOT describe text, logos, or typography in either concept.++## Series++- **Title:** {{series.name}}+- **Logline:** {{series.logline}}+- **Style / tonal notes:** {{series.styleNotes}}++## This volume++- **Number:** {{season.number}}+- **Title:** {{season.title}}+- **Logline:** {{season.logline}}+- **Synopsis:** {{season.synopsis}}+- **Ending hook:** {{season.endingHook}}+- **Themes:** {{season.themesCsv}}+- **Issues / episodes in the volume:** {{season.episodeCountTarget}}++## Output format++Return ONLY a JSON object with this exact shape — no preamble, no commentary, no code fences:++```+{+ "coverConcept": "2-4 sentence FRONT cover concept",+ "backCoverConcept": "2-4 sentence BACK cover concept"+}+```++## Rules++- **Front cover** = the iconic image for the whole volume. Bigger and more emblematic than a single issue cover. Focus on the protagonist or the volume's central image; an antagonist or location can anchor it if the arc demands it. Specify subject, framing (wide / medium / close), lighting, mood, and one striking visual detail.+- **Back cover** = a quiet companion image that COMPLEMENTS (not duplicates) the front. Often a counterpoint: a single object, a silhouette at distance, an environmental detail, an aftermath beat. NO text, NO masthead, NO logo, NO panel borders — the renderer's prompt will forbid typography. Focus on subject, framing, mood, and one striking visual detail.+- **Don't repeat the front cover on the back.** The two are read as a pair; a back cover that mirrors the front wastes the second page.+- Stay visually concrete. Describe what the camera sees, not how characters feel.+- 2-4 sentences each. Don't pad. Don't add scene-level direction beyond what a single image needs.diff --git a/scripts/migrations/011-comic-script-back-cover.js b/scripts/migrations/011-comic-script-back-cover.jsnew file mode 100644index 0000000000..fa4ee4d506--- /dev/null+++ b/scripts/migrations/011-comic-script-back-cover.js@@ -0,0 +1,76 @@+/**+ * Add `## Back cover concept` section to the comic-script stage prompt.+ *+ * Before this migration, the comic-script template emitted only a+ * `## Cover concept` section. After: the template also asks the LLM for a+ * `## Back cover concept` (one paragraph, illustration-only, no text), which+ * the parser captures into `backCoverConcept` and the issue's+ * `stages.comicPages.backCover.script` slot reads via the extract-pages+ * route.+ *+ * Strategy: same "unmodified-only" auto-update pattern as migration 003.+ * If the live file's MD5 matches any of the historical shipped hashes+ * (pre-003 or post-003), we replace it with the current data.sample/.+ * Diverged (user-customized) files are skipped with a merge hint.+ */++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');+};++// Every historical shipped MD5 of pipeline-comic-script.md. A user at any+// of these is unmodified and can be auto-bumped to the new template.+const HISTORICAL_SHIPPED_MD5 = [+ '40e5fdc1a1e68a7419b7dad936366c1a', // pre-003 (original)+ 'beab031951859ca13579cdb9c4dbe769', // post-003 (length-profile feature)+];++// MD5 of the new data.sample/pipeline-comic-script.md (with Back cover section).+const NEW_SHIPPED_MD5 = '1e0af305c27d0c80c4b482d2ebcb4a0d';++const FILENAME = 'pipeline-comic-script.md';++export default {+ async up({ rootDir }) {+ const dataPath = join(rootDir, 'data', 'prompts', 'stages', FILENAME);+ const samplePath = join(rootDir, 'data.sample', 'prompts', 'stages', FILENAME);++ const existing = await readFile(dataPath, 'utf-8').catch((err) => {+ if (err.code !== 'ENOENT') throw err;+ return null;+ });++ if (existing === null) {+ console.log(`📄 ${FILENAME}: not present in data/, will be created by setup-data.js`);+ return;+ }++ const existingMd5 = md5(existing);++ if (existingMd5 === NEW_SHIPPED_MD5) {+ console.log(`📝 ${FILENAME}: already at new version (Back cover section present)`);+ return;+ }++ if (!HISTORICAL_SHIPPED_MD5.includes(existingMd5)) {+ console.warn(+ `⚠️ ${FILENAME} has been customized — skipping auto-update.\n` ++ ` To add the Back cover concept section manually, diff:\n` ++ ` data.sample/prompts/stages/${FILENAME}\n` ++ ` against your current:\n` ++ ` data/prompts/stages/${FILENAME}\n` ++ ` and merge the new \`## Back cover concept\` block.`,+ );+ return;+ }++ const sampleContent = await readFile(samplePath, 'utf-8');+ await writeFile(dataPath, sampleContent);+ console.log(`✅ updated ${FILENAME} — added Back cover concept section`);+ },+};diff --git a/scripts/setup-data.js b/scripts/setup-data.jsindex e14a6c453b..cc7ae81d36 100644--- a/scripts/setup-data.js+++ b/scripts/setup-data.js@@ -141,7 +141,9 @@ const SHIPPED_PROMPT_OLD_MD5 = {// auto-updatable to the post-004 hash.'pipeline-idea-expansion.md': ['aee25112b2c596f643b17c559b772c22', '41facefbc0c0549d456bef9111f95ab9'],'pipeline-prose.md': 'bfea5aeeb471aae9749baee765b473a7',- 'pipeline-comic-script.md': '40e5fdc1a1e68a7419b7dad936366c1a',+ // comic-script: 40e5fd… (pre-003) and beab03… (post-003, pre-011) both+ // auto-updatable to the post-011 (back-cover) hash.+ 'pipeline-comic-script.md': ['40e5fdc1a1e68a7419b7dad936366c1a', 'beab031951859ca13579cdb9c4dbe769'],'pipeline-teleplay.md': '3f6fecc25573ed054b47db392250034a',// season-episodes: 6e349a… (pre-003) and c4928e… (post-003, pre-005) both// auto-updatable to the post-005 (shape-aware) hash.@@ -170,7 +172,7 @@ const SHIPPED_PROMPT_OLD_MD5 = {const SHIPPED_PROMPT_NEW_MD5 = {'pipeline-idea-expansion.md': '1ee44cf95851ff8debf18729ebcd40b4','pipeline-prose.md': '30ac30ec2b9d3e2a9eb869c181732cc6',- 'pipeline-comic-script.md': 'beab031951859ca13579cdb9c4dbe769',+ 'pipeline-comic-script.md': '1e0af305c27d0c80c4b482d2ebcb4a0d','pipeline-teleplay.md': '376f779f4687b598f1c92ca4e770fd5a','pipeline-season-episodes.md':'50c68a29c3ebc275db3095d06bd87100','pipeline-arc-overview.md': 'd34d72b8e49ba303d38607845dd87f1c',diff --git a/server/index.js b/server/index.jsindex 44abc1e60c..3cc5d9e46f 100644--- a/server/index.js+++ b/server/index.js@@ -92,6 +92,7 @@ import universeBuilderRoutes from './routes/universeBuilder.js';import { initUniverseBuilderCollectionHook } from './services/universeBuilderCollectionHook.js';import { initComicPagesFilenameHook } from './services/pipeline/comicPagesFilenameHook.js';import { initStoryboardsFilenameHook } from './services/pipeline/storyboardsFilenameHook.js';+import { initSeasonCoverFilenameHook } from './services/pipeline/seasonCoverFilenameHook.js';import pipelineRoutes from './routes/pipeline.js';import { initMediaJobQueue } from './services/mediaJobQueue/index.js';import { recoverInFlightProjects } from './services/creativeDirector/recovery.js';@@ -542,6 +543,7 @@ ensureSelf()// 24h media-job archive TTL elapses.initComicPagesFilenameHook();initStoryboardsFilenameHook();+ initSeasonCoverFilenameHook();}).then(() => {// Sharing: attach chokidar watchers to every registered share bucket sodiff --git a/server/lib/comicScriptParser.js b/server/lib/comicScriptParser.jsindex 76f451eec7..353af0765c 100644--- a/server/lib/comicScriptParser.js+++ b/server/lib/comicScriptParser.js@@ -22,8 +22,13 @@ const PAGE_RE = /^##\s+Page\s+([\dIVX]+)\b/i;// 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).+// `## Back cover concept` — the optional back-cover art section the+// comic-script template emits (typically right after `## Cover concept`,+// before the first `## Page 1`). Matched BEFORE `COVER_RE` in the parse+// loop because "Back cover" would otherwise pass the loose Cover regex.+const BACK_COVER_RE = /^##\s+Back\s+cover(?:\s+concept)?\b/i;+// Any `##` heading other than Page / Cover / Back cover ends an in-progress+// cover or back-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@@ -114,11 +119,15 @@ function parsePanelBody(lines) {/*** @param {string} script markdown body from stages.comicScript.output- * @returns {{ coverConcept: string, pages: Array<{ rawText, panels: Array<{ description, caption, dialogue, sfx }> }> }}+ * @returns {{ coverConcept: string, backCoverConcept: string, pages: Array<{ rawText, panels: Array<{ description, caption, dialogue, sfx }> }> }}** - `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).+ * - `backCoverConcept`: the body of an optional `## Back cover concept`+ * section. Same shape rules as `coverConcept`. Order with respect to+ * `## Cover concept` doesn't matter — both are captured wherever they+ * appear before the first `## Page 1`.** Each page carries:* - `rawText`: the markdown slice from the page's `## Page N` header to@@ -128,7 +137,9 @@ function parsePanelBody(lines) {* - `panels`: structured panel breakdown for image-gen prompts.*/export function parseComicScript(script) {- if (typeof script !== 'string' || !script.trim()) return { coverConcept: '', pages: [] };+ if (typeof script !== 'string' || !script.trim()) {+ return { coverConcept: '', backCoverConcept: '', pages: [] };+ }const lines = script.split(/\r?\n/);const pages = [];@@ -136,10 +147,13 @@ 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).+ // Cover / back-cover concept accumulators. Each is active between its+ // own `## …` heading and the next `##` heading (Page 1, the *other*+ // cover section, or any other H2).let inCover = false;+ let inBackCover = false;const coverLines = [];+ const backCoverLines = [];const flushPanel = () => {if (!inAnyPanel || !currentPage || !currentPanelLines) return;@@ -158,12 +172,21 @@ export function parseComicScript(script) {};for (const line of lines) {+ // `BACK_COVER_RE` must run before `COVER_RE` — "## Back cover concept"+ // would otherwise match the looser `## Cover` regex first.+ if (BACK_COVER_RE.test(line)) {+ inCover = false;+ inBackCover = true;+ continue;+ }if (COVER_RE.test(line)) {inCover = true;+ inBackCover = false;continue;}if (PAGE_RE.test(line)) {inCover = false;+ inBackCover = false;flushPanel();flushPageRawText();if (pages.length >= PANEL_LIMITS.PAGES_MAX) break;@@ -172,14 +195,20 @@ export function parseComicScript(script) {pages.push(currentPage);continue;}- // Any *other* H2 also ends the cover block (e.g. a stray `## Notes`).- if (inCover && ANY_H2_RE.test(line)) {+ // Any *other* H2 also ends an in-progress cover / back-cover block+ // (e.g. a stray `## Notes`).+ if ((inCover || inBackCover) && ANY_H2_RE.test(line)) {inCover = false;+ inBackCover = false;}if (inCover) {coverLines.push(line);continue;}+ if (inBackCover) {+ backCoverLines.push(line);+ continue;+ }if (currentRawLines) currentRawLines.push(line);if (PANEL_RE.test(line)) {flushPanel();@@ -209,7 +238,11 @@ export function parseComicScript(script) {coverLines.join('\n').replace(/^\s*\n+|\n+\s*$/g, ''),PANEL_LIMITS.PAGE_SCRIPT_MAX,);- return { coverConcept, pages: filtered };+ const backCoverConcept = trimTo(+ backCoverLines.join('\n').replace(/^\s*\n+|\n+\s*$/g, ''),+ PANEL_LIMITS.PAGE_SCRIPT_MAX,+ );+ return { coverConcept, backCoverConcept, pages: filtered };}export { PANEL_LIMITS };diff --git a/server/lib/comicScriptParser.test.js b/server/lib/comicScriptParser.test.jsindex ca03952012..38ed328fe9 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({ coverConcept: '', pages: [] });- expect(parseComicScript(null)).toEqual({ coverConcept: '', pages: [] });- expect(parseComicScript('# Just a title')).toEqual({ coverConcept: '', pages: [] });+ expect(parseComicScript('')).toEqual({ coverConcept: '', backCoverConcept: '', pages: [] });+ expect(parseComicScript(null)).toEqual({ coverConcept: '', backCoverConcept: '', pages: [] });+ expect(parseComicScript('# Just a title')).toEqual({ coverConcept: '', backCoverConcept: '', pages: [] });});it('drops panels with no description and pages with no panels', () => {@@ -141,6 +141,107 @@ Description: A frame.expect(parseComicScript(script).coverConcept).toBe('');});+ it('extracts the `## Back cover concept` section into backCoverConcept', () => {+ const script = `# Issue 1 — Bone Walker++## Cover concept++KESSA on the rib spine.++## Back cover concept++The beetle alone on a moonlit dune, single point-of-interest silhouette, no text, no logos.++## Page 1++Panel 1+Description: A frame.+`;+ const { coverConcept, backCoverConcept } = parseComicScript(script);+ expect(coverConcept).toMatch(/KESSA on the rib spine/);+ expect(backCoverConcept).toMatch(/beetle alone on a moonlit dune/);+ expect(backCoverConcept).not.toMatch(/KESSA/);+ });++ it('captures back-cover when only the back-cover section is present', () => {+ const script = `## Back cover concept++Just the back.++## Page 1++Panel 1+Description: A frame.+`;+ const { coverConcept, backCoverConcept } = parseComicScript(script);+ expect(coverConcept).toBe('');+ expect(backCoverConcept).toMatch(/Just the back/);+ });++ it('accepts the short `## Back cover` heading', () => {+ const script = `## Back cover++Short form.++## Page 1++Panel 1+Description: A frame.+`;+ expect(parseComicScript(script).backCoverConcept).toMatch(/Short form/);+ });++ it('handles back-cover before cover (any order)', () => {+ const script = `## Back cover concept++Back text.++## Cover concept++Front text.++## Page 1++Panel 1+Description: A frame.+`;+ const { coverConcept, backCoverConcept } = parseComicScript(script);+ expect(coverConcept).toMatch(/Front text/);+ expect(backCoverConcept).toMatch(/Back text/);+ });++ it('terminates an in-progress back-cover block at any other H2', () => {+ const script = `## Back cover concept++Real back-cover content.++## Notes++Editorial scratchpad — should not appear in backCoverConcept.++## Page 1++Panel 1+Description: A frame.+`;+ const { backCoverConcept } = parseComicScript(script);+ expect(backCoverConcept).toMatch(/Real back-cover content/);+ expect(backCoverConcept).not.toMatch(/Editorial scratchpad/);+ });++ it('returns empty backCoverConcept when the script has no Back cover section', () => {+ const script = `## Cover concept++Only a front.++## Page 1++Panel 1+Description: A frame.+`;+ expect(parseComicScript(script).backCoverConcept).toBe('');+ });+it('captures the raw page body for each page', () => {const { pages } = parseComicScript(SAMPLE);expect(pages[0].rawText).toMatch(/### Panel 1/);diff --git a/server/lib/pdfImageEmbed.js b/server/lib/pdfImageEmbed.jsnew file mode 100644index 0000000000..1f359b5caa--- /dev/null+++ b/server/lib/pdfImageEmbed.js@@ -0,0 +1,60 @@+/**+ * PDF image-embed helpers shared between the issue-level comic PDF and the+ * volume-level trade-paperback PDF. Both assemblies read PNG/JPEG files+ * from PATHS.images, embed them into a pdf-lib document, and fit each+ * image to a printable page with a small white margin.+ *+ * Caller passes its own error codes / subject strings so a failure inside+ * one assembly surfaces a distinguishable code (e.g. `_COMIC_PDF_` vs+ * `_VOLUME_PDF_`) without forcing this module to know which path called it.+ */++import { join } from 'path';+import { readFile } from 'fs/promises';+import { PATHS, assertSafeFilename } from './fileUtils.js';+import { ServerError } from './errorHandler.js';++const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47]);+const JPEG_MAGIC = Buffer.from([0xff, 0xd8, 0xff]);+export const IMAGE_EXTS = Object.freeze(['.png', '.jpg', '.jpeg']);++// Magic-byte sniff so a .png-named file that's actually JPEG (or vice versa)+// still embeds correctly. Falls back to extension only when sniff is inconclusive.+export function detectImageKind(bytes, filename) {+ if (bytes.length >= 4 && bytes.subarray(0, 4).equals(PNG_MAGIC)) return 'png';+ if (bytes.length >= 3 && bytes.subarray(0, 3).equals(JPEG_MAGIC)) return 'jpg';+ const ext = (filename || '').toLowerCase();+ if (ext.endsWith('.png')) return 'png';+ if (ext.endsWith('.jpg') || ext.endsWith('.jpeg')) return 'jpg';+ return null;+}++export async function readImageFromMedia(filename, { subject }) {+ assertSafeFilename(filename, { extensions: IMAGE_EXTS, subject });+ return readFile(join(PATHS.images, filename));+}++export async function embedImageBytes(pdf, bytes, filename, { unsupportedCode }) {+ const kind = detectImageKind(bytes, filename);+ if (kind === 'png') return pdf.embedPng(bytes);+ if (kind === 'jpg') return pdf.embedJpg(bytes);+ throw new ServerError(`Unsupported image format for "${filename}" — expected PNG or JPEG`, {+ status: 415, code: unsupportedCode,+ });+}++// White margin reads as "edition" rather than "raw print plate" and avoids+// cropping signed art on the page edges.+export function fitImage(imgW, imgH, pageW, pageH, marginPt = 18) {+ const availW = pageW - marginPt * 2;+ const availH = pageH - marginPt * 2;+ const scale = Math.min(availW / imgW, availH / imgH);+ const drawW = imgW * scale;+ const drawH = imgH * scale;+ return {+ x: (pageW - drawW) / 2,+ y: (pageH - drawH) / 2,+ width: drawW,+ height: drawH,+ };+}diff --git a/server/lib/renderSlot.js b/server/lib/renderSlot.jsnew file mode 100644index 0000000000..2912ec60d0--- /dev/null+++ b/server/lib/renderSlot.js@@ -0,0 +1,96 @@+/**+ * Shared render-slot helpers — used by anything that owns a (proof|final)+ * image render: comic issue covers / back covers, comic page renders, and+ * volume (season) covers / back covers.+ *+ * The slot record is the in-flight + completed-render state for one image:+ *+ * { jobId, filename, prompt, width, height, createdAt, fromProof? }+ *+ * `filename` is null while in-flight; the filename hook stamps it at job+ * completion. `fromProof` is omitted for the proof slot, required for the+ * final slot (so the UI can render "(upscaled from proof)" provenance).+ *+ * This module is a leaf — no imports from other PortOS modules. That keeps+ * it usable from both issues.js (cover, backCover, page-render slots) and+ * storyArc.js (season cover, backCover slots) without circular imports.+ */++import { isStr, trimTo } from './storyBible.js';++export const COVER_SCRIPT_MAX = 8000;+export const COVER_PROMPT_MAX = 16_000;+export const RENDER_FILENAME_MAX = 500;++/**+ * Sanitize a persisted slot record (cover.proofImage, season.backCover.finalImage,+ * etc). Returns null for an empty record so the persisted JSON stays clean.+ */+export const sanitizeRenderSlot = (raw, { isFinal = false } = {}) => {+ if (!raw || typeof raw !== 'object') return null;+ const jobId = isStr(raw.jobId) && raw.jobId ? raw.jobId : null;+ const filename = isStr(raw.filename) && raw.filename+ ? raw.filename.slice(0, RENDER_FILENAME_MAX)+ : null;+ const prompt = trimTo(raw.prompt, COVER_PROMPT_MAX) || null;+ const width = Number.isFinite(raw.width) ? Math.max(0, Math.floor(raw.width)) : null;+ const height = Number.isFinite(raw.height) ? Math.max(0, Math.floor(raw.height)) : null;+ const createdAt = isStr(raw.createdAt) ? raw.createdAt : null;+ if (!jobId && !filename) return null;+ const out = { jobId, filename, prompt, width, height, createdAt };+ if (isFinal) out.fromProof = raw.fromProof === true;+ return out;+};++/**+ * Sanitize a cover-like record (one script + proof slot + final slot, plus+ * legacy pre-split fields). Used for issue.cover, issue.backCover,+ * season.cover, season.backCover.+ */+export const sanitizeCoverLike = (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);+ const filename = isStr(raw.filename) && raw.filename ? raw.filename : null;+ const proofImage = sanitizeRenderSlot(raw.proofImage);+ const finalImage = sanitizeRenderSlot(raw.finalImage, { isFinal: true });+ if (!script && !imageJobId && !prompt && !filename && !proofImage && !finalImage) return null;+ return {+ script,+ imageJobId,+ prompt: prompt || null,+ filename,+ proofImage,+ finalImage,+ };+};++/**+ * Build a fresh in-flight render slot — used by route handlers when enqueueing+ * a new render and by filename hooks when migrating a legacy in-flight job.+ * `filename` starts null; the filename hook stamps it on job completion.+ */+export const buildRenderSlot = ({ slotKey, jobId, prompt, width, height, fromProof = false, filename = null }) => ({+ jobId,+ filename,+ prompt: prompt || null,+ width: width ?? null,+ height: height ?? null,+ createdAt: new Date().toISOString(),+ ...(slotKey === 'finalImage' ? { fromProof } : {}),+});++/**+ * Read-fallback chain for "which image filename should I display / embed":+ * 1. finalImage.filename — the hi-res print-ready render (preferred)+ * 2. proofImage.filename — the fast layout render+ * 3. legacy `filename` — pre-proof/final split records+ * Returns null when nothing is available yet.+ */+export const pickRenderedFilename = (record) => {+ if (!record) return null;+ return record.finalImage?.filename+ || record.proofImage?.filename+ || (typeof record.filename === 'string' && record.filename ? record.filename : null);+};diff --git a/server/lib/storyArc.js b/server/lib/storyArc.jsindex ad47a97326..02291164b2 100644--- a/server/lib/storyArc.js+++ b/server/lib/storyArc.js@@ -18,6 +18,7 @@import { randomUUID } from 'crypto';import { isStr, trimTo } from './storyBible.js';+import { sanitizeCoverLike } from './renderSlot.js';export const ARC_LIMITS = Object.freeze({LOGLINE_MAX: 500,@@ -282,6 +283,12 @@ export function sanitizeSeason(raw, { preserveTimestamps = true } = {}) {episodeCountTarget,themes: cleanThemes(raw.themes),endingHook: trimTo(raw.endingHook, ARC_LIMITS.SEASON_ENDING_HOOK_MAX),+ // Volume (season) cover + back cover. Same script + proof + final+ // slot shape as an issue cover; rendered by enqueueVolumeCover and+ // assembled into the volume PDF as the trade-paperback bookends.+ // Both default to null; the season-cover render route writes them.+ cover: sanitizeCoverLike(raw.cover),+ backCover: sanitizeCoverLike(raw.backCover),status,createdAt: created,updatedAt: updated,diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex 1a23281aa4..9459d080d0 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -45,6 +45,9 @@ import {enqueueVisualImage,enqueueVisualComicPage,enqueueComicCover,+ enqueueComicBackCover,+ enqueueVolumeCover,+ enqueueVolumeBackCover,enqueueStoryboardSceneVideo,enqueueStoryboardShotStartFrame,refineComicPanelPrompt,@@ -58,6 +61,10 @@ import { ASPECT_RATIOS, QUALITIES } from '../lib/creativeDirectorPresets.js';import { extractScenes, SOURCE_KIND } from '../lib/sceneExtractor.js';import { listVisualStyles } from '../lib/visualStyles.js';import { buildComicPdf, PAGE_SIZES, DEFAULT_PAGE_SIZE, ERR_NO_RENDERED_PAGES } from '../services/pipeline/comicPdf.js';+import {+ buildVolumePdf,+ ERR_NO_VOLUME_COVER, ERR_NO_RENDERED_ISSUES,+} from '../services/pipeline/volumePdf.js';import { listAllVoices, synthesizeToFile, parseVoiceId, extractDialogueLines, resolveVoiceForLine } from '../services/pipeline/audio.js';import { synthesize as synthesizeVoice } from '../services/voice/tts.js';import {@@ -92,6 +99,8 @@ const SERVICE_ERROR_STATUS = {[arcPlanner.ERR_VALIDATION]: 400,[ERR_NO_STORYBOARDS]: 400,[ERR_NO_RENDERED_PAGES]: 409,+ [ERR_NO_VOLUME_COVER]: 409,+ [ERR_NO_RENDERED_ISSUES]: 409,};const mapServiceError = (err) => {@@ -153,6 +162,18 @@ const arcSchema = z.object({status: z.enum(ARC_STATUSES).optional(),});+// Volume-cover / back-cover sub-schema — accepts the script text plus the+// pre-split legacy fields. Render-slot details (`proofImage`, `finalImage`)+// arrive only from the render route's PATCH path, which builds them+// server-side; PATCHes of the season metadata only carry the user-editable+// `script`. Explicit shape (not `.passthrough()`) so the "all inputs+// validated" CLAUDE.md convention holds for new fields.+const seasonCoverSchema = z.object({+ script: z.string().max(8000).optional(),+ imageJobId: z.string().trim().max(200).nullable().optional(),+ prompt: z.string().max(16_000).nullable().optional(),+});+const seasonSchema = z.object({id: z.string().trim().min(1).max(64).optional(),number: z.number().int().min(0).max(ARC_LIMITS.SEASON_NUMBER_MAX).optional(),@@ -163,6 +184,8 @@ const seasonSchema = z.object({themes: z.array(z.string().trim().min(1).max(ARC_LIMITS.THEME_MAX)).max(ARC_LIMITS.THEMES_PER_ARC_MAX).optional(),endingHook: z.string().trim().max(ARC_LIMITS.SEASON_ENDING_HOOK_MAX).optional(),+ cover: seasonCoverSchema.nullable().optional(),+ backCover: seasonCoverSchema.nullable().optional(),status: z.enum(SEASON_STATUSES).optional(),}).passthrough();@@ -271,6 +294,16 @@ const visualStageInputSchema = stageInputSchema.extend({imageJobId: z.string().trim().max(200).nullable().optional(),prompt: z.string().max(16_000).nullable().optional(),}).nullable().optional(),+ // Comic-issue back cover — identical shape to `cover`. Only meaningful+ // on the comicPages stage. The render route + filename hook treat the+ // two slots symmetrically; only the rendered prompt differs (no+ // masthead, explicit no-text negative — back covers are illustration-+ // only).+ backCover: 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(),// Per-stage visual style override. Validated lazily by the sanitizer// (unknown catalog ids are dropped) so adding a new style doesn't force// a schema bump on every client.@@ -334,14 +367,20 @@ const visualGenerateSchema = z.object({seed: z.number().int().min(0).optional(),}).refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });-// 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(),+// Render-schema factory — every cover/back-cover render route shares the+// same shape (image-gen knobs + proof/final variant + useProofAsBase i2i),+// differing only in the script-field name. Four routes × ~16 fields each+// were a 60-line mirror before this factory; new fields now apply to all+// four call sites at once. `target` is the proof/final variant; the route+// param resolves the cover-vs-backCover slot.+//+// `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. `useProofAsBase` is silently+// ignored by Codex (gpt-image-2's $imagegen has no init-image input);+// local + external honor it.+const makeCoverRenderSchema = (scriptField) => z.object({+ [scriptField]: 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(),@@ -352,18 +391,21 @@ const comicCoverRenderSchema = z.object({cfgScale: z.number().min(0).max(30).optional(),guidance: z.number().min(0).max(30).optional(),seed: z.number().int().min(0).optional(),- // Proof vs Final render variant. Each variant lands in its own slot- // (cover.proofImage / cover.finalImage) so the user can keep a fast- // proof for layout decisions and a hi-res final for the PDF.target: z.enum(COMIC_PAGE_VARIANTS).optional().default('proof'),- // When the user likes the proof and wants the final to preserve its- // composition, set this to true — the server will pass the proof image- // as the init image for the final render at low denoise strength.- // Codex backend silently ignores it (gpt-image-2's $imagegen tool has- // no init-image input); local + external honor it.useProofAsBase: z.boolean().optional().default(false),}).refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });+const comicCoverRenderSchema = makeCoverRenderSchema('coverScript');+const comicBackCoverRenderSchema = makeCoverRenderSchema('backCoverScript');+const volumeCoverRenderSchema = makeCoverRenderSchema('coverScript');+const volumeBackCoverRenderSchema = makeCoverRenderSchema('backCoverScript');++const volumeCoverConceptsSchema = z.object({+ commit: z.boolean().optional().default(false),+ providerOverride: z.string().trim().max(80).optional(),+ modelOverride: z.string().trim().max(200).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).@@ -1070,6 +1112,99 @@ router.post('/series/:id/arc/resolve-issues', asyncHandler(async (req, res) => {res.json(result);}));+// =====================+// Volume (season) covers — front + back illustration on the season record.+// Stored on series.seasons[].cover / .backCover, sanitized by sanitizeSeason,+// rendered by enqueueVolumeCover{,BackCover}, stamped on completion by+// seasonCoverFilenameHook. Compiled with all child issues into a trade-+// paperback PDF by the volume.pdf route below.+// =====================++router.post('/series/:id/seasons/:seasonId/cover-concepts/generate', asyncHandler(async (req, res) => {+ const body = validateRequest(volumeCoverConceptsSchema, req.body ?? {});+ const result = await arcPlanner.generateVolumeCoverConcepts(req.params.id, req.params.seasonId, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++// Render the volume front cover. Persists the in-flight render slot onto+// season.cover via seriesSvc.updateSeasonOnSeries (queue-serialized) — the+// season-cover filename hook stamps the completed filename later.+// (Missing series / season surface as PIPELINE_SEASON_NOT_FOUND from+// enqueueVolumeCover's loadSeasonContext, mapped to 404 by mapServiceError.)+router.post('/series/:id/seasons/:seasonId/cover/render', asyncHandler(async (req, res) => {+ const body = validateRequest(volumeCoverRenderSchema, req.body ?? {});+ const result = await enqueueVolumeCover(req.params.id, req.params.seasonId, body)+ .catch((err) => { throw mapServiceError(err); });++ const slotKey = slotKeyForVariant(result.variant);+ const slotRecord = buildRenderSlot({+ slotKey, jobId: result.jobId, prompt: result.prompt,+ width: body.width, height: body.height, fromProof: result.fromProof,+ });+ const series = await seriesSvc.updateSeasonOnSeries(+ req.params.id,+ req.params.seasonId,+ (cur) => {+ const currentCover = cur?.cover || {};+ return {+ cover: {+ ...currentCover,+ script: result.coverScript || '',+ [slotKey]: slotRecord,+ },+ };+ },+ ).catch((err) => { throw mapServiceError(err); });+ const season = (series.seasons || []).find((s) => s.id === req.params.seasonId);+ res.json({ ...result, season, series });+}));++router.post('/series/:id/seasons/:seasonId/back-cover/render', asyncHandler(async (req, res) => {+ const body = validateRequest(volumeBackCoverRenderSchema, req.body ?? {});+ const result = await enqueueVolumeBackCover(req.params.id, req.params.seasonId, body)+ .catch((err) => { throw mapServiceError(err); });++ const slotKey = slotKeyForVariant(result.variant);+ const slotRecord = buildRenderSlot({+ slotKey, jobId: result.jobId, prompt: result.prompt,+ width: body.width, height: body.height, fromProof: result.fromProof,+ });+ const series = await seriesSvc.updateSeasonOnSeries(+ req.params.id,+ req.params.seasonId,+ (cur) => {+ const currentBack = cur?.backCover || {};+ return {+ backCover: {+ ...currentBack,+ script: result.backCoverScript || '',+ [slotKey]: slotRecord,+ },+ };+ },+ ).catch((err) => { throw mapServiceError(err); });+ const season = (series.seasons || []).find((s) => s.id === req.params.seasonId);+ res.json({ ...result, season, series });+}));++// Compile a trade-paperback PDF: volume front → for each issue+// [issue front → issue pages → issue back] → volume back → optional colophon.+// 409 with ERR_NO_VOLUME_COVER when the season has no rendered front cover;+// 409 with ERR_NO_RENDERED_ISSUES when no issue has any rendered page yet.+router.get('/series/:id/seasons/:seasonId/volume.pdf', asyncHandler(async (req, res) => {+ const sizeRaw = typeof req.query.size === 'string' ? req.query.size : '';+ const size = PAGE_SIZES[sizeRaw] ? sizeRaw : DEFAULT_PAGE_SIZE;+ const includeColophon = req.query.colophon !== 'skip';+ const { bytes, filename } = await buildVolumePdf(req.params.id, req.params.seasonId, {+ size, includeColophon,+ }).catch((err) => { throw mapServiceError(err); });+ res.setHeader('Content-Type', 'application/pdf');+ res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);+ res.setHeader('Content-Length', String(bytes.length));+ res.end(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength));+}));+// =====================// Issue routes// =====================@@ -1223,19 +1358,21 @@ router.post('/issues/:id/stages/comicPages/extract-pages', asyncHandler(async (r);}- const { pages, coverConcept } = parseComicScript(source);+ const { pages, coverConcept, backCoverConcept } = 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.+ // Preserve a user-edited cover / back-cover script if one is already set —+ // only seed from the parsed concept when the slot is currently blank.+ // Otherwise an extract re-run would clobber a hand-curated cover/back. 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 image that doesn't match the new+ // concept text.//- // The decision is made inside updateStageWithLatest so it reads the freshest- // persisted cover, not the stale snapshot from the getIssue read above. A- // concurrent cover/render call that writes imageJobId between the two awaits- // would otherwise be silently overwritten.+ // The decision is made inside updateStageWithLatest so it reads the+ // freshest persisted cover/back, not the stale snapshot from the+ // getIssue read above. A concurrent cover/render call that writes+ // imageJobId between the two awaits would otherwise be silently+ // overwritten.const { issue: updatedIssue, stage } = await issuesSvc.updateStageWithLatest(issue.id,'comicPages',@@ -1244,10 +1381,15 @@ router.post('/issues/:id/stages/comicPages/extract-pages', asyncHandler(async (rconst nextCover = coverConcept && !currentCoverScript? { script: coverConcept, imageJobId: null, prompt: null }: currentStage?.cover ?? null;+ const currentBackScript = currentStage?.backCover?.script || '';+ const nextBackCover = backCoverConcept && !currentBackScript+ ? { script: backCoverConcept, imageJobId: null, prompt: null }+ : currentStage?.backCover ?? null;return {status: pages.length ? 'ready' : 'empty',pages,cover: nextCover,+ backCover: nextBackCover,errorMessage: '',};},@@ -1349,6 +1491,38 @@ router.post('/issues/:id/stages/comicPages/cover/render', asyncHandler(async (reres.json({ ...result, cover: stage.cover, issue: updatedIssue, stage });}));+// Render the comic-issue BACK cover. Same flow as the front-cover route;+// differs in the prompt (no masthead, explicit no-text negative) and the+// persisted slot (`stages.comicPages.backCover.{proofImage|finalImage}`).+router.post('/issues/:id/stages/comicPages/back-cover/render', asyncHandler(async (req, res) => {+ const body = validateRequest(comicBackCoverRenderSchema, req.body ?? {});+ await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });++ const result = await enqueueComicBackCover(req.params.id, body)+ .catch((err) => { throw mapServiceError(err); });++ const slotKey = slotKeyForVariant(result.variant);+ const slotRecord = buildRenderSlot({+ slotKey, jobId: result.jobId, prompt: result.prompt,+ width: body.width, height: body.height, fromProof: result.fromProof,+ });+ const { issue: updatedIssue, stage } = await issuesSvc.updateStageWithLatest(+ req.params.id,+ 'comicPages',+ (currentStage) => {+ const currentBack = currentStage?.backCover || {};+ return {+ backCover: {+ ...currentBack,+ script: result.backCoverScript || '',+ [slotKey]: slotRecord,+ },+ };+ },+ ).catch((err) => { throw mapServiceError(err); });+ res.json({ ...result, backCover: stage.backCover, 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-quality@@ -1420,9 +1594,10 @@ router.get('/issues/:id/comic.pdf', asyncHandler(async (req, res) => {const sizeRaw = typeof req.query.size === 'string' ? req.query.size : '';const size = PAGE_SIZES[sizeRaw] ? sizeRaw : DEFAULT_PAGE_SIZE;const includeCover = req.query.cover !== 'skip';+ const includeBackCover = req.query.backCover !== 'skip';const includeColophon = req.query.colophon !== 'skip';const { bytes, filename } = await buildComicPdf(req.params.id, {- size, includeCover, includeColophon,+ size, includeCover, includeBackCover, includeColophon,}).catch((err) => { throw mapServiceError(err); });res.setHeader('Content-Type', 'application/pdf');res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.jsindex 2fc0c568c1..aca7f6ea2d 100644--- a/server/services/pipeline/arcPlanner.js+++ b/server/services/pipeline/arcPlanner.js@@ -21,7 +21,7 @@import { runStagedLLM } from '../../lib/stageRunner.js';import { ServerError } from '../../lib/errorHandler.js';-import { getSeries, updateSeries } from './series.js';+import { getSeries, updateSeries, updateSeasonOnSeries } from './series.js';import { listIssues } from './issues.js';import { getSeason } from './seasons.js';import {@@ -404,6 +404,87 @@ export async function generateSeasonEpisodes(seriesId, seasonId, options = {}) {};}+/**+ * Generate FRONT + BACK cover-art concepts for one volume (season). Returns+ * the proposed text without persisting; pass `commit: true` to write the+ * scripts to `season.cover.script` / `season.backCover.script` — only when+ * those slots are currently blank, never clobbering a user edit.+ *+ * Sized as a lightweight per-season LLM call rather than bolted onto the+ * arc-overview pass so (a) cover concepts can be regenerated independently+ * of the arc structure, and (b) the heavier arc-overview prompt's output+ * tokens stay focused on structural beats.+ */+export async function generateVolumeCoverConcepts(seriesId, seasonId, options = {}) {+ const series = await getSeries(seriesId);+ const seasons = series.seasons || [];+ const season = seasons.find((s) => s.id === seasonId);+ if (!season) {+ throw makeErr(`Season not found on series: ${seasonId}`, ERR_VALIDATION);+ }+ const themesCsv = Array.isArray(season.themes) ? season.themes.join(', ') : '';+ const ctx = {+ series: {+ name: series.name,+ logline: series.logline,+ styleNotes: series.styleNotes,+ },+ season: {+ number: season.number,+ title: season.title,+ logline: season.logline,+ synopsis: season.synopsis,+ endingHook: season.endingHook,+ episodeCountTarget: season.episodeCountTarget,+ themesCsv,+ },+ };+ const { content, runId, providerId, model } = await runStagedLLM(+ 'pipeline-volume-cover-concepts',+ ctx,+ {+ providerOverride: options.providerOverride,+ modelOverride: options.modelOverride,+ returnsJson: true,+ source: 'pipeline-volume-cover-concepts',+ },+ );+ const coverConcept = (typeof content?.coverConcept === 'string' ? content.coverConcept : '').trim();+ const backCoverConcept = (typeof content?.backCoverConcept === 'string' ? content.backCoverConcept : '').trim();+ let updatedSeries = null;+ const seeded = { cover: false, backCover: false };+ if (options.commit) {+ // Scoped per-season patch via updateSeasonOnSeries — runs inside the+ // series write tail, skips the full sanitizeSeries pass over every+ // bible list. The "only seed when blank" check happens INSIDE the+ // callback so it reads the freshest persisted scripts (avoiding a+ // race against a concurrent user blur-save).+ updatedSeries = await updateSeasonOnSeries(seriesId, seasonId, (cur) => {+ const patch = {};+ if (coverConcept && !(cur.cover?.script || '')) {+ patch.cover = { ...(cur.cover || {}), script: coverConcept };+ seeded.cover = true;+ }+ if (backCoverConcept && !(cur.backCover?.script || '')) {+ patch.backCover = { ...(cur.backCover || {}), script: backCoverConcept };+ seeded.backCover = true;+ }+ return patch;+ });+ }+ return {+ season: updatedSeries ? (updatedSeries.seasons || []).find((s) => s.id === seasonId) : season,+ series: updatedSeries,+ coverConcept,+ backCoverConcept,+ seeded,+ raw: content,+ runId,+ providerId,+ model,+ };+}+/*** Build the verify-pass context — a JSON-encoded tree of seasons + their* child issues so the LLM has a single structural blob to scan. Issues arediff --git a/server/services/pipeline/comicPagesFilenameHook.js b/server/services/pipeline/comicPagesFilenameHook.jsindex 3645a5da1f..609743c894 100644--- a/server/services/pipeline/comicPagesFilenameHook.js+++ b/server/services/pipeline/comicPagesFilenameHook.js@@ -37,34 +37,40 @@ const hook = createFilenameHook({parseOwner: parseComicPagesOwner,applyFilename: (currentStage, parsed, job, filename) => {const slotKey = slotKeyForVariant(parsed.variant);- if (parsed.target === 'cover') {- const cover = currentStage?.cover;- if (!cover) return null;+ // Cover and backCover share the exact same slot shape, so the+ // stamp/migrate logic is identical — only the field name on+ // `currentStage` differs. Branch on `parsed.target` instead of+ // duplicating two near-identical blocks.+ if (parsed.target === 'cover' || parsed.target === 'backCover') {+ const field = parsed.target; // 'cover' | 'backCover'+ const record = currentStage?.[field];+ if (!record) return null;// New shape: the route stamped { jobId, …, filename: null } into- // cover[slotKey] at enqueue. Only stamp the filename if THIS job is- // still the slot's active render — a re-render that landed between- // enqueue and this event would otherwise be overwritten with the- // older filename.- if (cover[slotKey]?.jobId === job.id) {+ // record[slotKey] at enqueue. Only stamp the filename if THIS job+ // is still the slot's active render — a re-render that landed+ // between enqueue and this event would otherwise be overwritten+ // with the older filename.+ if (record[slotKey]?.jobId === job.id) {return {- patch: { cover: { ...cover, [slotKey]: { ...cover[slotKey], filename } } },- label: `cover.${slotKey}`,+ patch: { [field]: { ...record, [slotKey]: { ...record[slotKey], filename } } },+ label: `${field}.${slotKey}`,};}- // Legacy shape — pre-split job that wrote cover.imageJobId. Stamp- // the result into the matching new slot AND clear the legacy- // imageJobId/filename so the UI reads exclusively from the slot.- if (cover.imageJobId === job.id) {+ // Legacy shape — pre-split job that wrote record.imageJobId.+ // Stamp the result into the matching new slot AND clear the+ // legacy imageJobId/filename so the UI reads exclusively from+ // the slot.+ if (record.imageJobId === job.id) {return {patch: {- cover: {- ...cover,- [slotKey]: legacySlotRecord(slotKey, job, filename, cover.prompt),+ [field]: {+ ...record,+ [slotKey]: legacySlotRecord(slotKey, job, filename, record.prompt),imageJobId: null,filename: null,},},- label: `cover.${slotKey} (migrated)`,+ label: `${field}.${slotKey} (migrated)`,};}return null;diff --git a/server/services/pipeline/comicPdf.js b/server/services/pipeline/comicPdf.jsindex bade369bf1..738c7ab264 100644--- a/server/services/pipeline/comicPdf.js+++ b/server/services/pipeline/comicPdf.js@@ -7,15 +7,13 @@* route surfaces "X of Y rendered" to the user before download.*/-import { join } from 'path';-import { readFile } from 'fs/promises';import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';-import { PATHS, assertSafeFilename } from '../../lib/fileUtils.js';-import { ServerError } from '../../lib/errorHandler.js';import { slugifyForFilename } from '../../lib/civitai.js';import { getIssue } from './issues.js';import { getSeries } from './series.js';import { resolveVisualStyle } from '../../lib/visualStyles.js';+import { pickRenderedFilename } from '../../lib/renderSlot.js';+import { readImageFromMedia, embedImageBytes, fitImage } from '../../lib/pdfImageEmbed.js';export const PAGE_SIZES = Object.freeze({'us-letter': { width: 612, height: 792 },@@ -27,50 +25,8 @@ export const DEFAULT_PAGE_SIZE = 'us-letter';export const ERR_NO_RENDERED_PAGES = 'PIPELINE_COMIC_PDF_NO_PAGES';const makeErr = (message, code) => Object.assign(new Error(message), { code });-const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47]);-const JPEG_MAGIC = Buffer.from([0xff, 0xd8, 0xff]);-const IMAGE_EXTS = Object.freeze(['.png', '.jpg', '.jpeg']);--// Magic-byte sniff so a .png-named file that's actually JPEG (or vice versa)-// still embeds correctly. Falls back to extension only when sniff is inconclusive.-function detectImageKind(bytes, filename) {- if (bytes.length >= 4 && bytes.subarray(0, 4).equals(PNG_MAGIC)) return 'png';- if (bytes.length >= 3 && bytes.subarray(0, 3).equals(JPEG_MAGIC)) return 'jpg';- const ext = (filename || '').toLowerCase();- if (ext.endsWith('.png')) return 'png';- if (ext.endsWith('.jpg') || ext.endsWith('.jpeg')) return 'jpg';- return null;-}--async function readImageFromMedia(filename) {- assertSafeFilename(filename, { extensions: IMAGE_EXTS, subject: 'comic page image' });- return readFile(join(PATHS.images, filename));-}--async function embedImageBytes(pdf, bytes, filename) {- const kind = detectImageKind(bytes, filename);- if (kind === 'png') return pdf.embedPng(bytes);- if (kind === 'jpg') return pdf.embedJpg(bytes);- throw new ServerError(`Unsupported image format for "${filename}" — expected PNG or JPEG`, {- status: 415, code: 'PIPELINE_COMIC_PDF_UNSUPPORTED_IMAGE',- });-}--// White margin reads as "edition" rather than "raw print plate" and avoids-// cropping signed art on the page edges.-function fitImage(imgW, imgH, pageW, pageH, marginPt = 18) {- const availW = pageW - marginPt * 2;- const availH = pageH - marginPt * 2;- const scale = Math.min(availW / imgW, availH / imgH);- const drawW = imgW * scale;- const drawH = imgH * scale;- return {- x: (pageW - drawW) / 2,- y: (pageH - drawH) / 2,- width: drawW,- height: drawH,- };-}+const READ_OPTS = { subject: 'comic page image' };+const EMBED_OPTS = { unsupportedCode: 'PIPELINE_COMIC_PDF_UNSUPPORTED_IMAGE' };/*** @returns {{ bytes: Uint8Array, pageCount: number, filename: string }}@@ -82,24 +38,16 @@ export async function buildComicPdf(issueId, opts = {}) {const sizeKey = PAGE_SIZES[opts.size] ? opts.size : DEFAULT_PAGE_SIZE;const { width: pageW, height: pageH } = PAGE_SIZES[sizeKey];const includeCover = opts.includeCover !== false;+ const includeBackCover = opts.includeBackCover !== false;const includeColophon = opts.includeColophon !== false;- // Read-fallback chain for each cover/page filename:- // 1. finalImage.filename — the hi-res print-ready render (preferred)- // 2. proofImage.filename — the fast layout render- // 3. legacy `filename` — pre-proof/final split records- // The user can keep iterating on the proof while the final is in flight,- // and the PDF will still assemble — just at whichever resolution is- // currently available.- const pickRenderedFilename = (record) => {- if (!record) return null;- return record.finalImage?.filename- || record.proofImage?.filename- || (typeof record.filename === 'string' && record.filename ? record.filename : null);- };+ // Read-fallback chain (finalImage → proofImage → legacy filename) lives+ // in server/lib/renderSlot.js so volume PDFs share it. See pickRenderedFilename+ // import + re-export at the top of this file.const comicPages = issue.stages?.comicPages || {};const cover = includeCover ? comicPages.cover : null;+ const backCover = includeBackCover ? comicPages.backCover : null;const pages = Array.isArray(comicPages.pages) ? comicPages.pages : [];const targets = [];@@ -109,6 +57,8 @@ export async function buildComicPdf(issueId, opts = {}) {const name = pickRenderedFilename(p);if (name) targets.push(name);}+ const backCoverFilename = pickRenderedFilename(backCover);+ if (backCoverFilename) targets.push(backCoverFilename);if (targets.length === 0) {throw makeErr('Issue has no rendered pages or cover yet', ERR_NO_RENDERED_PAGES);}@@ -118,7 +68,7 @@ export async function buildComicPdf(issueId, opts = {}) {// One bad page must not fail the whole download, so errors are captured// alongside the bytes and logged when the loop reaches them.const loaded = await Promise.all(targets.map((filename) =>- readImageFromMedia(filename)+ readImageFromMedia(filename, READ_OPTS).then((bytes) => ({ filename, bytes })).catch((err) => ({ filename, err })),));@@ -137,7 +87,7 @@ export async function buildComicPdf(issueId, opts = {}) {console.error(`❌ comicPdf — skipped "${entry.filename}": ${entry.err.message || entry.err}`);continue;}- const img = await embedImageBytes(pdf, entry.bytes, entry.filename).catch((err) => {+ const img = await embedImageBytes(pdf, entry.bytes, entry.filename, EMBED_OPTS).catch((err) => {console.error(`❌ comicPdf — embed failed "${entry.filename}": ${err.message || err}`);return null;});diff --git a/server/services/pipeline/comicPdf.test.js b/server/services/pipeline/comicPdf.test.jsindex b0b9517ae1..cd80fadd6b 100644--- a/server/services/pipeline/comicPdf.test.js+++ b/server/services/pipeline/comicPdf.test.js@@ -140,6 +140,38 @@ describe('buildComicPdf — happy path', () => {const { filename } = await buildComicPdf('iss-test');expect(filename).toBe('bone-walker-03.pdf');});++ it('appends backCover after pages (cover → pages → back → colophon)', async () => {+ await writeFile(join(FAKE_IMAGES_DIR, 'back.png'), TINY_PNG);+ getIssueMock.mockResolvedValueOnce({+ ...structuredClone(mockIssue),+ stages: {+ comicPages: {+ cover: { filename: 'cover.png' },+ pages: [{ filename: 'page1.png' }, { filename: 'page2.png' }],+ backCover: { filename: 'back.png' },+ },+ },+ });+ const { pageCount } = await buildComicPdf('iss-test');+ expect(pageCount).toBe(5); // cover + 2 pages + back + colophon+ });++ it('omits the back cover when includeBackCover=false', async () => {+ await writeFile(join(FAKE_IMAGES_DIR, 'back.png'), TINY_PNG);+ getIssueMock.mockResolvedValueOnce({+ ...structuredClone(mockIssue),+ stages: {+ comicPages: {+ cover: { filename: 'cover.png' },+ pages: [{ filename: 'page1.png' }],+ backCover: { filename: 'back.png' },+ },+ },+ });+ const { pageCount } = await buildComicPdf('iss-test', { includeBackCover: false });+ expect(pageCount).toBe(3); // cover + page1 + colophon — back skipped+ });});describe('buildComicPdf — rejection paths', () => {diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex 954d8ffa6f..563fc92b35 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -29,6 +29,7 @@ import { sanitizeOrigin } from '../../lib/sharingOrigin.js';import { sanitizeVisualStyleRef } from '../../lib/visualStyles.js';import { ARC_ROLES } from '../../lib/storyArc.js';import { isStr, trimTo } from '../../lib/storyBible.js';+import { sanitizeCoverLike } from '../../lib/renderSlot.js';import { emitRecordUpdated } from '../sharing/recordEvents.js';import { applyVolumeOrderedNumbers, UNSCOPED_ANCHOR } from '../../lib/pipelineIssueOrder.js';import * as seriesSvc from './series.js';@@ -158,61 +159,11 @@ const sanitizeGenConfig = (raw) => {return { imageMode, imageModelId, refineProvider, refineModel };};-const COVER_SCRIPT_MAX = 8000;-const COVER_PROMPT_MAX = 16_000;-const RENDER_FILENAME_MAX = 500;--// Proof vs final render slot — each cover/page can have one of each. Stored-// as a structured record so the UI/PDF can pick the right resolution without-// re-rendering, and so the i2i "use proof as base" path has a stable-// filename to read for the final render's init image.-//-// `final` slots additionally carry `fromProof: boolean` so the UI can show-// "(upscaled from proof)" provenance.-const sanitizeRenderSlot = (raw, { isFinal = false } = {}) => {- if (!raw || typeof raw !== 'object') return null;- const jobId = isStr(raw.jobId) && raw.jobId ? raw.jobId : null;- const filename = isStr(raw.filename) && raw.filename- ? raw.filename.slice(0, RENDER_FILENAME_MAX)- : null;- const prompt = trimTo(raw.prompt, COVER_PROMPT_MAX) || null;- const width = Number.isFinite(raw.width) ? Math.max(0, Math.floor(raw.width)) : null;- const height = Number.isFinite(raw.height) ? Math.max(0, Math.floor(raw.height)) : null;- const createdAt = isStr(raw.createdAt) ? raw.createdAt : null;- // Empty slot — drop it so the persisted JSON stays clean.- if (!jobId && !filename) return null;- const out = { jobId, filename, prompt, width, height, createdAt };- if (isFinal) out.fromProof = raw.fromProof === true;- return out;-};--const sanitizeCover = (raw) => {- if (!raw || typeof raw !== 'object') return null;- const script = trimTo(raw.script, COVER_SCRIPT_MAX);- // Legacy fields — pre-proof/final split. Preserved so existing data still- // displays via the UI/PDF read-fallback chain (final → proof → legacy).- // New renders write to proofImage/finalImage; the filename hook migrates- // any in-flight legacy job's completion into the new slots on landing.- const imageJobId = isStr(raw.imageJobId) && raw.imageJobId ? raw.imageJobId : null;- const prompt = trimTo(raw.prompt, COVER_PROMPT_MAX);- const filename = isStr(raw.filename) && raw.filename ? raw.filename : null;- const proofImage = sanitizeRenderSlot(raw.proofImage);- const finalImage = sanitizeRenderSlot(raw.finalImage, { isFinal: true });- if (!script && !imageJobId && !prompt && !filename && !proofImage && !finalImage) return null;- return {- script,- imageJobId,- prompt: prompt || null,- filename,- proofImage,- finalImage,- };-};-// Page records (pages[]) are pass-through in sanitizeVisualStage's array// slice, so the new proofImage/finalImage fields survive there without an// explicit sanitizer. If pages ever gets a deep sanitizer, route slot-// records through sanitizeRenderSlot the same way the cover does.+// records through sanitizeRenderSlot (lib/renderSlot.js) the same way+// the cover does.const sanitizeVisualStage = (raw, stageId = null) => {// Visual stages keep arbitrary structured artifact lists. Sanitize the@@ -229,14 +180,16 @@ const sanitizeVisualStage = (raw, stageId = 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,+ // `cover` and `backCover` are meaningful only on comicPages — they carry+ // the front/back-cover concept + render jobs. Dropping them 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' ? sanitizeCoverLike(raw?.cover) : null,+ backCover: stageId === null || stageId === 'comicPages' ? sanitizeCoverLike(raw?.backCover) : null,// Per-stage override so a series can mix aesthetics// (e.g. graphic-novel panels + cinematic storyboards).visualStyleOverride: sanitizeVisualStyleRef(raw?.visualStyleOverride),diff --git a/server/services/pipeline/owners.js b/server/services/pipeline/owners.jsindex bb8fd3b1c7..0ac334d37d 100644--- a/server/services/pipeline/owners.js+++ b/server/services/pipeline/owners.js@@ -26,13 +26,14 @@ export function buildComicPagesOwner({ issueId, target, pageIndex, variant = 'prthrow new Error(`buildComicPagesOwner: unknown variant "${variant}"`);}if (target === 'cover') return `${PREFIX}:${issueId}:comicPages:cover:${variant}`;+ if (target === 'backCover') return `${PREFIX}:${issueId}:comicPages:backCover:${variant}`;if (target === 'page') return `${PREFIX}:${issueId}:comicPages:page${pageIndex}:${variant}`;throw new Error(`buildComicPagesOwner: unknown target "${target}"`);}// Suffix `(:proof|:final)?` is optional so legacy owners still parse. New// jobs always include the variant; old jobs default to 'proof' below.-const COMIC_PAGES_RE = /^pipeline:([^:]+):comicPages:(cover|page(\d+))(?::(proof|final))?$/;+const COMIC_PAGES_RE = /^pipeline:([^:]+):comicPages:(cover|backCover|page(\d+))(?::(proof|final))?$/;export function parseComicPagesOwner(owner) {if (typeof owner !== 'string') return null;@@ -41,11 +42,37 @@ export function parseComicPagesOwner(owner) {const [, issueId, kind, pageIdxStr, variantMatch] = m;const variant = variantMatch || 'proof';if (kind === 'cover') return { issueId, target: 'cover', variant };+ if (kind === 'backCover') return { issueId, target: 'backCover', variant };const pageIndex = Number(pageIdxStr);if (!Number.isInteger(pageIndex) || pageIndex < 0) return null;return { issueId, target: 'page', pageIndex, variant };}+// Season-cover owners — `pipeline:season:<seriesId>:<seasonId>:<target>:<variant>`+// where target ∈ {cover, backCover}. Distinct namespace from issue owners so+// the comic-pages filename hook never accidentally matches a season-cover+// completion event (the issue regex is anchored on `comicPages:` after the+// issue id; season owners use `season:` after the prefix instead).+export function buildSeasonCoverOwner({ seriesId, seasonId, target, variant = 'proof' }) {+ if (!COMIC_PAGE_VARIANTS.includes(variant)) {+ throw new Error(`buildSeasonCoverOwner: unknown variant "${variant}"`);+ }+ if (target !== 'cover' && target !== 'backCover') {+ throw new Error(`buildSeasonCoverOwner: unknown target "${target}"`);+ }+ return `${PREFIX}:season:${seriesId}:${seasonId}:${target}:${variant}`;+}++const SEASON_COVER_RE = /^pipeline:season:([^:]+):([^:]+):(cover|backCover):(proof|final)$/;++export function parseSeasonCoverOwner(owner) {+ if (typeof owner !== 'string') return null;+ const m = owner.match(SEASON_COVER_RE);+ if (!m) return null;+ const [, seriesId, seasonId, target, variant] = m;+ return { seriesId, seasonId, target, variant };+}+// Per-shot start-frame renders inside the storyboards stage. Scene-level// owners (`pipeline:<id>:storyboards:scene<N>`) still exist for legacy// scene-image renders that don't decompose into shots — that string isdiff --git a/server/services/pipeline/owners.test.js b/server/services/pipeline/owners.test.jsindex b974197c0f..ff8fb79097 100644--- a/server/services/pipeline/owners.test.js+++ b/server/services/pipeline/owners.test.js@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest';import {buildComicPagesOwner, parseComicPagesOwner,buildStoryboardsShotOwner, parseStoryboardsShotOwner,+ buildSeasonCoverOwner, parseSeasonCoverOwner,} from './owners.js';describe('pipeline owner strings', () => {@@ -17,6 +18,16 @@ describe('pipeline owner strings', () => {expect(parseComicPagesOwner(owner)).toEqual({ issueId: 'iss-abc', target: 'cover', variant: 'final' });});+ it('round-trips backCover owners (proof + final)', () => {+ const proof = buildComicPagesOwner({ issueId: 'iss-abc', target: 'backCover', variant: 'proof' });+ expect(proof).toBe('pipeline:iss-abc:comicPages:backCover:proof');+ expect(parseComicPagesOwner(proof)).toEqual({ issueId: 'iss-abc', target: 'backCover', variant: 'proof' });++ const final = buildComicPagesOwner({ issueId: 'iss-abc', target: 'backCover', variant: 'final' });+ expect(final).toBe('pipeline:iss-abc:comicPages:backCover:final');+ expect(parseComicPagesOwner(final)).toEqual({ issueId: 'iss-abc', target: 'backCover', variant: 'final' });+ });+it('round-trips a page owner — default variant is proof', () => {const owner = buildComicPagesOwner({ issueId: 'iss-xyz', target: 'page', pageIndex: 7 });expect(owner).toBe('pipeline:iss-xyz:comicPages:page7:proof');@@ -67,4 +78,42 @@ describe('pipeline owner strings', () => {expect(parseComicPagesOwner('pipeline:iss:storyboards:scene1:shot2')).toBeNull();expect(parseStoryboardsShotOwner('pipeline:iss:comicPages:page3')).toBeNull();});++ it('round-trips season-cover owners across both variants and both targets', () => {+ for (const target of ['cover', 'backCover']) {+ for (const variant of ['proof', 'final']) {+ const owner = buildSeasonCoverOwner({+ seriesId: 'ser-foo', seasonId: 'sea-bar', target, variant,+ });+ expect(owner).toBe(`pipeline:season:ser-foo:sea-bar:${target}:${variant}`);+ expect(parseSeasonCoverOwner(owner)).toEqual({+ seriesId: 'ser-foo', seasonId: 'sea-bar', target, variant,+ });+ }+ }+ });++ it('season-cover builder rejects unknown target / variant', () => {+ expect(() => buildSeasonCoverOwner({+ seriesId: 's', seasonId: 'sea', target: 'panel', variant: 'proof',+ })).toThrow();+ expect(() => buildSeasonCoverOwner({+ seriesId: 's', seasonId: 'sea', target: 'cover', variant: 'sketch',+ })).toThrow();+ });++ it('season-cover and issue-cover owners do not match each other', () => {+ const issueCover = 'pipeline:iss-abc:comicPages:cover:proof';+ const seasonCover = 'pipeline:season:ser-foo:sea-bar:cover:proof';+ expect(parseSeasonCoverOwner(issueCover)).toBeNull();+ expect(parseComicPagesOwner(seasonCover)).toBeNull();+ });++ it('season-cover parser rejects malformed strings', () => {+ expect(parseSeasonCoverOwner(null)).toBeNull();+ expect(parseSeasonCoverOwner('')).toBeNull();+ expect(parseSeasonCoverOwner('pipeline:season:s:sea:cover')).toBeNull(); // missing variant+ expect(parseSeasonCoverOwner('pipeline:season:s:sea:panel:proof')).toBeNull(); // bad target+ expect(parseSeasonCoverOwner('pipeline:s:sea:cover:proof')).toBeNull(); // missing 'season:'+ });});diff --git a/server/services/pipeline/seasonCoverFilenameHook.js b/server/services/pipeline/seasonCoverFilenameHook.jsnew file mode 100644index 0000000000..3a2c0de482--- /dev/null+++ b/server/services/pipeline/seasonCoverFilenameHook.js@@ -0,0 +1,81 @@+/**+ * Pipeline season (volume) cover — filename hook.+ *+ * Listens for mediaJobQueue 'completed' events and stamps `filename` onto+ * `series.seasons[].cover[slotKey]` (or `…[].backCover[slotKey]`) when the+ * job's owner string is a season-cover owner.+ *+ * Cannot use `createFilenameHook` from filenameHookFactory.js: the factory+ * is hard-coded to issue-scope (`updateStageWithLatest(parsed.issueId, …)`).+ * Season covers live on the series record, not on an issue stage — so we+ * write a small bespoke handler that routes through+ * `seriesSvc.updateSeasonOnSeries`, which serializes against the shared+ * `pipeline-series.json` via `seriesWriteTail`.+ *+ * Idempotency: skips when the slot's recorded `jobId` no longer matches+ * (a re-render landed between enqueue and this completion event). The+ * route stamps `{ jobId, filename: null }` at enqueue; this hook+ * stamps `filename` only when the jobId is still ours.+ */++import { mediaJobEvents } from '../mediaJobQueue/index.js';+import { parseSeasonCoverOwner, slotKeyForVariant } from './owners.js';+import * as seriesSvc from './series.js';++let registeredHandler = null;++const handler = (job) => {+ void (async () => {+ if (!job || job.kind !== 'image') return;+ const filename = job.result?.filename;+ if (typeof filename !== 'string' || !filename) return;+ const parsed = parseSeasonCoverOwner(job.owner);+ if (!parsed) return;++ const shortId = String(job.id || '').slice(0, 8);+ const slotKey = slotKeyForVariant(parsed.variant);+ const { seriesId, seasonId, target } = parsed;+ let stamped = false;++ await seriesSvc.updateSeasonOnSeries(seriesId, seasonId, (cur) => {+ const record = cur?.[target];+ if (!record) return {}; // season cleared the cover record between enqueue + landing+ // Only stamp when THIS job is still the slot's active render. A+ // re-render queued after us would have replaced `[slotKey].jobId`+ // already — in that case dropping our completion is the correct+ // behavior (the newer job's filename will overwrite ours anyway).+ if (record[slotKey]?.jobId !== job.id) return {};+ stamped = true;+ return {+ [target]: {+ ...record,+ [slotKey]: { ...record[slotKey], filename },+ },+ };+ }).catch((err) => {+ console.error(`❌ seasonCover filename hook failed for job ${shortId}: ${err?.message || err}`);+ });++ if (stamped) {+ console.log(`📎 seasonCover filename stamped — series=${seriesId.slice(0, 8)} season=${seasonId.slice(0, 8)} ${target}.${slotKey} ← ${filename}`);+ }+ })().catch((err) => {+ console.error(`❌ seasonCover filename hook crashed: ${err?.message || err}`);+ });+};++export function initSeasonCoverFilenameHook() {+ if (registeredHandler) return;+ registeredHandler = handler;+ mediaJobEvents.on('completed', registeredHandler);+ console.log('📎 seasonCover filename hook initialized');+}++export const __testing = {+ reset() {+ if (registeredHandler) {+ mediaJobEvents.off('completed', registeredHandler);+ registeredHandler = null;+ }+ },+};diff --git a/server/services/pipeline/seasons.js b/server/services/pipeline/seasons.jsindex 984bc9e5a1..2966cf0abc 100644--- a/server/services/pipeline/seasons.js+++ b/server/services/pipeline/seasons.js@@ -59,28 +59,28 @@ export async function createSeason(seriesId, input = {}) {}export async function updateSeason(seriesId, seasonId, patch = {}) {- const series = await seriesSvc.getSeries(seriesId);- const seasons = series.seasons || [];- const cur = seasons.find((s) => s.id === seasonId);- if (!cur) throw makeErr(`Season not found: ${seasonId}`, ERR_NOT_FOUND);- // Preserve `createdAt` and force a fresh `updatedAt` by overwriting them- // directly in the sanitizer input — the default `preserveTimestamps: true`- // path then just reads them through cleanly.- const next = sanitizeSeason({- ...cur,- ...patch,- id: cur.id,- createdAt: cur.createdAt,- updatedAt: new Date().toISOString(),+ // Routed through the series write queue so the read-modify-write of one+ // season can't be raced by a concurrent series PATCH or a cover-render+ // landing. Caller still receives the final season as before.+ let priorNumber = null;+ let nextNumber = null;+ const updated = await seriesSvc.updateSeasonOnSeries(seriesId, seasonId, (cur) => {+ priorNumber = cur.number;+ const next = sanitizeSeason({+ ...cur,+ ...patch,+ id: cur.id,+ createdAt: cur.createdAt,+ updatedAt: new Date().toISOString(),+ });+ if (!next) throw makeErr('Season requires a title or a number > 0', ERR_VALIDATION);+ nextNumber = next.number;+ return next;});- if (!next) throw makeErr('Season requires a title or a number > 0', ERR_VALIDATION);- // Re-write the whole seasons array — the series sanitizer re-sorts by- // `number` ascending so a number change moves the season automatically.- const merged = seasons.map((s) => (s.id === seasonId ? next : s));- const updated = await seriesSvc.updateSeries(seriesId, { seasons: merged });// Issue numbers derive from volume order — a volume `number` swap- // reshuffles every issue's slot in the series.- if (cur.number !== next.number) {+ // reshuffles every issue's slot in the series. Runs OUTSIDE the queue+ // because it mutates issues.json, not series.json.+ if (priorNumber !== nextNumber) {await issuesSvc.recomputeIssueNumbersForSeries(seriesId);}return updated.seasons.find((s) => s.id === seasonId);diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex e9697e2f68..ac972e5412 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -28,6 +28,26 @@ import { emitRecordUpdated, emitRecordDeleted } from '../sharing/recordEvents.js// (e.g. tests that swap it through a Proxy mock).const statePath = () => join(PATHS.data, 'pipeline-series.json');+// File-level write lock — same pattern as issueWriteTail in issues.js.+// Required because multiple write paths can race on the single shared+// pipeline-series.json file: PATCH /series/:id (bible edits), PATCH+// /seasons/:seasonId (season metadata), the new volume cover-render route,+// the season-cover filename hook landing, and the bible-extract merge.+// All of those read-then-write the same JSON; without serialization a+// later writer's `readState` can land on a pre-image snapshot and clobber+// the earlier write. CLAUDE.md: "single tail per shared file."+let seriesWriteTail = Promise.resolve();++function queueSeriesWrite(fn) {+ const next = seriesWriteTail.then(fn, fn); // run fn even when prev rejects+ const silenced = next.catch(() => {});+ seriesWriteTail = silenced;+ silenced.finally(() => {+ if (seriesWriteTail === silenced) seriesWriteTail = Promise.resolve();+ });+ return next;+}+export const ERR_NOT_FOUND = 'PIPELINE_SERIES_NOT_FOUND';export const ERR_VALIDATION = 'PIPELINE_SERIES_VALIDATION';export const ERR_DUPLICATE = 'PIPELINE_SERIES_DUPLICATE';@@ -140,31 +160,33 @@ export async function getSeries(id) {export async function createSeries(input = {}) {const name = trimTo(input.name, NAME_MAX);if (!name) throw makeErr(`Series name is required (1..${NAME_MAX} chars)`, ERR_VALIDATION);- const state = await readState();- const now = new Date().toISOString();- const next = sanitizeSeries({- id: `ser-${randomUUID()}`,- name,- logline: input.logline || '',- premise: input.premise || '',- universeId: input.universeId || null,- writersRoomWorkId: input.writersRoomWorkId || null,- characters: input.characters || [],- settings: input.settings || [],- objects: input.objects || [],- arc: input.arc || null,- seasons: input.seasons || [],- locked: input.locked || {},- styleNotes: input.styleNotes || '',- targetFormat: input.targetFormat || 'comic+tv',- issueCountTarget: input.issueCountTarget || 0,- llm: input.llm || null,- createdAt: now,- updatedAt: now,+ return queueSeriesWrite(async () => {+ const state = await readState();+ const now = new Date().toISOString();+ const next = sanitizeSeries({+ id: `ser-${randomUUID()}`,+ name,+ logline: input.logline || '',+ premise: input.premise || '',+ universeId: input.universeId || null,+ writersRoomWorkId: input.writersRoomWorkId || null,+ characters: input.characters || [],+ settings: input.settings || [],+ objects: input.objects || [],+ arc: input.arc || null,+ seasons: input.seasons || [],+ locked: input.locked || {},+ styleNotes: input.styleNotes || '',+ targetFormat: input.targetFormat || 'comic+tv',+ issueCountTarget: input.issueCountTarget || 0,+ llm: input.llm || null,+ createdAt: now,+ updatedAt: now,+ });+ state.series.push(next);+ await writeState(state);+ return next;});- state.series.push(next);- await writeState(state);- return next;}/**@@ -180,53 +202,97 @@ export async function insertSeriesWithId(input = {}) {}const name = trimTo(input.name, NAME_MAX);if (!name) throw makeErr(`Series name is required (1..${NAME_MAX} chars)`, ERR_VALIDATION);- const state = await readState();- if (state.series.some((s) => s.id === input.id)) {- throw makeErr(`Series id already exists: ${input.id}`, ERR_DUPLICATE);- }- const next = sanitizeSeries({ ...input, name });- if (!next) throw makeErr('Invalid series payload', ERR_VALIDATION);- state.series.push(next);- await writeState(state);- return next;+ return queueSeriesWrite(async () => {+ const state = await readState();+ if (state.series.some((s) => s.id === input.id)) {+ throw makeErr(`Series id already exists: ${input.id}`, ERR_DUPLICATE);+ }+ const next = sanitizeSeries({ ...input, name });+ if (!next) throw makeErr('Invalid series payload', ERR_VALIDATION);+ state.series.push(next);+ await writeState(state);+ return next;+ });}export async function updateSeries(id, patch = {}) {- const state = await readState();- const idx = state.series.findIndex((s) => s.id === id);- if (idx < 0) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);- const cur = state.series[idx];- // Per-field merge so `{ provider: 'codex' }` doesn't clobber an existing `model`.- const mergedLlm = 'llm' in patch- ? { ...(cur.llm || {}), ...(patch.llm || {}) }- : cur.llm;- const merged = sanitizeSeries({- ...cur,- ...('name' in patch ? { name: patch.name } : {}),- ...('logline' in patch ? { logline: patch.logline } : {}),- ...('premise' in patch ? { premise: patch.premise } : {}),- ...('universeId' in patch ? { universeId: patch.universeId } : {}),- ...('writersRoomWorkId' in patch ? { writersRoomWorkId: patch.writersRoomWorkId } : {}),- ...('characters' in patch ? { characters: patch.characters } : {}),- ...('settings' in patch ? { settings: patch.settings } : {}),- ...('objects' in patch ? { objects: patch.objects } : {}),- ...('arc' in patch ? { arc: patch.arc } : {}),- ...('seasons' in patch ? { seasons: patch.seasons } : {}),- // Wholesale replace — `locked: {}` clears every lock; omission preserves.- ...('locked' in patch ? { locked: patch.locked } : {}),- ...('styleNotes' in patch ? { styleNotes: patch.styleNotes } : {}),- ...('visualStyleDefault' in patch ? { visualStyleDefault: patch.visualStyleDefault } : {}),- ...('targetFormat' in patch ? { targetFormat: patch.targetFormat } : {}),- ...('issueCountTarget' in patch ? { issueCountTarget: patch.issueCountTarget } : {}),- ...('origin' in patch ? { origin: patch.origin } : {}),- llm: mergedLlm,- updatedAt: new Date().toISOString(),+ return queueSeriesWrite(async () => {+ const state = await readState();+ const idx = state.series.findIndex((s) => s.id === id);+ if (idx < 0) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);+ const cur = state.series[idx];+ // Per-field merge so `{ provider: 'codex' }` doesn't clobber an existing `model`.+ const mergedLlm = 'llm' in patch+ ? { ...(cur.llm || {}), ...(patch.llm || {}) }+ : cur.llm;+ const merged = sanitizeSeries({+ ...cur,+ ...('name' in patch ? { name: patch.name } : {}),+ ...('logline' in patch ? { logline: patch.logline } : {}),+ ...('premise' in patch ? { premise: patch.premise } : {}),+ ...('universeId' in patch ? { universeId: patch.universeId } : {}),+ ...('writersRoomWorkId' in patch ? { writersRoomWorkId: patch.writersRoomWorkId } : {}),+ ...('characters' in patch ? { characters: patch.characters } : {}),+ ...('settings' in patch ? { settings: patch.settings } : {}),+ ...('objects' in patch ? { objects: patch.objects } : {}),+ ...('arc' in patch ? { arc: patch.arc } : {}),+ ...('seasons' in patch ? { seasons: patch.seasons } : {}),+ // Wholesale replace — `locked: {}` clears every lock; omission preserves.+ ...('locked' in patch ? { locked: patch.locked } : {}),+ ...('styleNotes' in patch ? { styleNotes: patch.styleNotes } : {}),+ ...('visualStyleDefault' in patch ? { visualStyleDefault: patch.visualStyleDefault } : {}),+ ...('targetFormat' in patch ? { targetFormat: patch.targetFormat } : {}),+ ...('issueCountTarget' in patch ? { issueCountTarget: patch.issueCountTarget } : {}),+ ...('origin' in patch ? { origin: patch.origin } : {}),+ llm: mergedLlm,+ updatedAt: new Date().toISOString(),+ });+ if (!merged) throw makeErr('Invalid series payload', ERR_VALIDATION);+ state.series[idx] = merged;+ await writeState(state);+ emitRecordUpdated('series', merged.id);+ return merged;+ });+}++/**+ * Apply a structured patch to one season inside a series. Routes through the+ * shared series write tail so a season-cover render PATCH, the season-cover+ * filename hook landing, and a user-driven season metadata edit all serialize+ * against the single pipeline-series.json file. Returns the updated series.+ *+ * Throws `PIPELINE_SEASON_NOT_FOUND` (the seasons-service ERR_NOT_FOUND+ * value, inlined here to avoid a circular import seasons → series → seasons)+ * when the season is missing so the season-resource routes surface a 404+ * with "Season not found" rather than "Series not found".+ */+export async function updateSeasonOnSeries(seriesId, seasonId, patchFn) {+ return queueSeriesWrite(async () => {+ const state = await readState();+ const idx = state.series.findIndex((s) => s.id === seriesId);+ if (idx < 0) throw makeErr(`Series not found: ${seriesId}`, ERR_NOT_FOUND);+ const cur = state.series[idx];+ const seasons = Array.isArray(cur.seasons) ? cur.seasons : [];+ const seasonIdx = seasons.findIndex((s) => s.id === seasonId);+ if (seasonIdx < 0) {+ throw makeErr(`Season not found: ${seasonId}`, 'PIPELINE_SEASON_NOT_FOUND');+ }+ const existing = seasons[seasonIdx];+ const patched = patchFn(existing);+ const nextSeasons = [...seasons];+ // Force a fresh updatedAt on the touched season so LWW comparisons fire.+ nextSeasons[seasonIdx] = { ...existing, ...patched, updatedAt: new Date().toISOString() };+ const merged = sanitizeSeries({+ ...cur,+ seasons: nextSeasons,+ updatedAt: new Date().toISOString(),+ });+ if (!merged) throw makeErr('Invalid series payload after season patch', ERR_VALIDATION);+ state.series[idx] = merged;+ await writeState(state);+ emitRecordUpdated('series', merged.id);+ return merged;});- if (!merged) throw makeErr('Invalid series payload', ERR_VALIDATION);- state.series[idx] = merged;- await writeState(state);- emitRecordUpdated('series', merged.id);- return merged;}/**@@ -240,35 +306,37 @@ export async function updateSeries(id, patch = {}) {*/export async function purgeImageRefFromAllSeries(filename) {if (!filename || typeof filename !== 'string') return { removed: 0 };- const state = await readState();- let removed = 0;- const touchedIds = [];- const nextSeries = state.series.map((s) => {- let touched = false;- const patched = { ...s };- for (const key of BIBLE_KEYS) {- const list = Array.isArray(s[key]) ? s[key] : null;- if (!list) continue;- const nextList = list.map((entry) => {- const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : null;- if (!refs || !refs.includes(filename)) return entry;- const trimmed = refs.filter((f) => f !== filename);- removed += refs.length - trimmed.length;- touched = true;- return { ...entry, imageRefs: trimmed };- });- if (touched) patched[key] = nextList;+ return queueSeriesWrite(async () => {+ const state = await readState();+ let removed = 0;+ const touchedIds = [];+ const nextSeries = state.series.map((s) => {+ let touched = false;+ const patched = { ...s };+ for (const key of BIBLE_KEYS) {+ const list = Array.isArray(s[key]) ? s[key] : null;+ if (!list) continue;+ const nextList = list.map((entry) => {+ const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : null;+ if (!refs || !refs.includes(filename)) return entry;+ const trimmed = refs.filter((f) => f !== filename);+ removed += refs.length - trimmed.length;+ touched = true;+ return { ...entry, imageRefs: trimmed };+ });+ if (touched) patched[key] = nextList;+ }+ if (touched) touchedIds.push(s.id);+ return touched ? { ...patched, updatedAt: new Date().toISOString() } : s;+ });+ if (removed > 0) {+ await writeState({ series: nextSeries });+ // Each touched series is a mutation any active subscription should+ // propagate to its bucket; otherwise recipients keep stale imageRefs.+ for (const id of touchedIds) emitRecordUpdated('series', id);}- if (touched) touchedIds.push(s.id);- return touched ? { ...patched, updatedAt: new Date().toISOString() } : s;+ return { removed };});- if (removed > 0) {- await writeState({ series: nextSeries });- // Each touched series is a mutation any active subscription should- // propagate to its bucket; otherwise recipients keep stale imageRefs.- for (const id of touchedIds) emitRecordUpdated('series', id);- }- return { removed };}/**@@ -346,13 +414,15 @@ export async function extractAndMergeIntoSeries(seriesId, opts = {}) {}export async function deleteSeries(id) {- const state = await readState();- const before = state.series.length;- state.series = state.series.filter((s) => s.id !== id);- if (state.series.length === before) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);- await writeState(state);- // Any live share-bucket subscription for this series tears itself down via- // the recordEvents listener instead of orphaning.- emitRecordDeleted('series', id);- return { id };+ return queueSeriesWrite(async () => {+ const state = await readState();+ const before = state.series.length;+ state.series = state.series.filter((s) => s.id !== id);+ if (state.series.length === before) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);+ await writeState(state);+ // Any live share-bucket subscription for this series tears itself down via+ // the recordEvents listener instead of orphaning.+ emitRecordDeleted('series', id);+ return { id };+ });}diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.jsindex dc3c7be0eb..2b9812d45e 100644--- a/server/services/pipeline/visualStages.js+++ b/server/services/pipeline/visualStages.js@@ -29,7 +29,7 @@ import { getSettings } from '../settings.js';import { getSeries } from './series.js';import { getIssue, updateStage, VISUAL_STAGE_IDS } from './issues.js';import { PATHS } from '../../lib/fileUtils.js';-import { buildComicPagesOwner, buildStoryboardsShotOwner } from './owners.js';+import { buildComicPagesOwner, buildSeasonCoverOwner, buildStoryboardsShotOwner } from './owners.js';import { getUniverse, joinInfluenceList } from '../universeBuilder.js';import { ServerError } from '../../lib/errorHandler.js';import {@@ -89,19 +89,11 @@ const resolveMode = (options, settings) => {// slot, even if a future client bypasses the route schema.const resolveVariant = (target) => (target === 'final' ? 'final' : 'proof');-// Shape for a fresh in-flight render slot — used by both route handlers-// (cover + page) and the filename hook's legacy-migration path. `filename`-// starts null; the comic-pages filename hook stamps it on job completion.-// `fromProof` is omitted for the proof slot and required for the final slot.-export const buildRenderSlot = ({ slotKey, jobId, prompt, width, height, fromProof = false, filename = null }) => ({- jobId,- filename,- prompt: prompt || null,- width: width ?? null,- height: height ?? null,- createdAt: new Date().toISOString(),- ...(slotKey === 'finalImage' ? { fromProof } : {}),-});+// `buildRenderSlot` moved to server/lib/renderSlot.js so season-cover+// render paths (which don't import from visualStages.js) can share the+// shape. Re-exported here for back-compat with route-level callers that+// still import it from this module.+export { buildRenderSlot } from '../../lib/renderSlot.js';// Default denoise strength for the "use proof as base" upscale path. Low// enough to preserve composition (panel layout, character placement),@@ -283,6 +275,80 @@ export function composeComicCoverPrompt({return applyWorldStyle(`${layout}\n\n${body}`, world);}+/**+ * Compose a comic-book BACK-cover prompt. Distinguishing constraints vs.+ * front cover: no masthead, no issue-number tag, no title banner — back+ * covers are pure illustration in this app. The negative clause forbids+ * typography explicitly because diffusion models default to "helpfully"+ * re-adding logos/UPC blocks/credits typography when the canvas reads as+ * a comic back cover.+ *+ * Returns the full prompt string (with world style baked in when present).+ */+export function composeComicBackCoverPrompt({+ series, world, issue, backCoverScript = '', extraStyle = '',+}) {+ const issueTitle = (issue?.title || '').trim();+ const concept = (backCoverScript || '').trim();++ const styleStack = stackStyle(series, extraStyle);+ const styleClause = styleStack ? ` Art style: ${styleStack}.` : '';++ // Fallback when the user hasn't written a back-cover script yet — keep+ // it thematically on-target so a one-click render still produces+ // something meaningful instead of a blank canvas.+ const sceneDescription = concept+ || (issueTitle ? `A quiet companion image evoking "${issueTitle}" — atmospheric, single subject.` : 'A quiet companion image — atmospheric, single subject.');++ const layout = `A single full printable comic-book BACK cover for a serialized issue. NO text of any kind — no masthead, no logo, no title, no issue-number tag, no UPC, no credits, no typography, no captions, no panel borders, no multi-panel layout. The entire cover is one bold illustrated hero image, edge-to-edge.${styleClause}`;+ const body = `Back-cover concept: ${sceneDescription}`;+ return applyWorldStyle(`${layout}\n\n${body}`, world);+}++/**+ * Shared enqueue path for issue covers and back covers — front/back share+ * 95% of the plumbing (variant resolution, proof-as-base init image,+ * owner + job + log). Only the script-field name, slot location on the+ * stage, and prompt composer differ; those are passed in by the caller.+ *+ * Returns { jobId, mode, prompt, script, variant, fromProof } — the+ * `script` field is the resolved text (option override or persisted),+ * named neutrally because the caller knows whether it's a coverScript or+ * a backCoverScript.+ */+async function enqueueComicCoverLike(issueId, target, options = {}) {+ if (target !== 'cover' && target !== 'backCover') {+ throw new Error(`enqueueComicCoverLike: unknown target "${target}"`);+ }+ const { issue, settings, series, world } = await loadBibleContext(issueId);+ const record = issue.stages?.comicPages?.[target] || null;+ const scriptOptionKey = target === 'cover' ? 'coverScript' : 'backCoverScript';+ const script = typeof options[scriptOptionKey] === 'string'+ ? options[scriptOptionKey]+ : (record?.script || '');+ const mode = resolveMode(options, settings);+ const variant = resolveVariant(options.target);+ const fromProof = variant === 'final' && options.useProofAsBase === true;+ const initImagePath = fromProof+ ? resolveProofInitImage(record?.proofImage, target)+ : null;+ const initImageStrength = fromProof+ ? (Number.isFinite(options.initImageStrength) ? options.initImageStrength : PROOF_AS_BASE_DEFAULT_STRENGTH)+ : undefined;+ const extraStyle = composeExtraStyle(series, issue, 'comicPages', options.extraStyle);+ const prompt = target === 'cover'+ ? composeComicCoverPrompt({ series, world, issue, coverScript: script, extraStyle })+ : composeComicBackCoverPrompt({ series, world, issue, backCoverScript: script, extraStyle });+ const logTarget = target === 'cover' ? 'cover' : 'back cover';+ const jobId = enqueueImageJob({+ prompt, world, settings, mode,+ options: { ...options, initImagePath, initImageStrength },+ owner: buildComicPagesOwner({ issueId, target, variant }),+ logLine: `🎨 Pipeline comic ${logTarget} — issue=${issueId.slice(0, 8)} number=${issue.number || 1} variant=${variant}${fromProof ? ' (from proof)' : ''}`,+ });+ return { jobId, mode, prompt, script, variant, fromProof };+}+/*** Enqueue a comic-issue front-cover image render. Builds a cover-art* prompt (series masthead + issue-number tag + user's cover concept) and@@ -299,31 +365,150 @@ export function composeComicCoverPrompt({* route can construct the slot record without re-reading 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 { script, ...rest } = await enqueueComicCoverLike(issueId, 'cover', options);+ return { ...rest, coverScript: script };+}++/**+ * Enqueue a comic-issue back-cover image render. Same flow as+ * `enqueueComicCover` but with a back-cover-specific prompt (no+ * masthead / issue-number / title; explicit no-text negative) and the+ * job lands on `stages.comicPages.backCover.{proofImage|finalImage}`.+ *+ * Returns { jobId, mode, prompt, backCoverScript, variant, fromProof }.+ */+export async function enqueueComicBackCover(issueId, options = {}) {+ const { script, ...rest } = await enqueueComicCoverLike(issueId, 'backCover', options);+ return { ...rest, backCoverScript: script };+}++// ---- Volume (season) covers ---------------------------------------------++const loadSeasonContext = async (seriesId, seasonId) => {+ const seriesChain = (async () => {+ const series = await getSeries(seriesId);+ const world = series.universeId ? await getUniverse(series.universeId).catch(() => null) : null;+ return { series, world };+ })();+ const [chain, settings] = await Promise.all([seriesChain, getSettings()]);+ const season = (chain.series.seasons || []).find((s) => s.id === seasonId);+ if (!season) {+ throw new ServerError(`Season not found: ${seasonId}`, {+ status: 404, code: 'PIPELINE_SEASON_NOT_FOUND',+ });+ }+ return { ...chain, season, settings };+};++export function composeVolumeCoverPrompt({+ series, world, season, coverScript = '', extraStyle = '',+}) {+ const seriesName = (series?.name || '').trim();+ const volumeNumber = Number.isFinite(season?.number) ? Math.max(1, Math.floor(season.number)) : 1;+ const volumeTitle = (season?.title || '').trim();+ const concept = (coverScript || '').trim();++ const styleStack = stackStyle(series, extraStyle);+ const styleClause = styleStack ? ` Art style: ${styleStack}.` : '';++ 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 volume tag reading "VOL. ${volumeNumber}" in the top-left corner — small but readable.`;+ const titleLine = volumeTitle+ ? ` Include the volume title "${volumeTitle}" as a secondary banner below the masthead.`+ : '';++ const sceneDescription = concept+ || (volumeTitle+ ? `A single dramatic hero image evoking the volume "${volumeTitle}" — the collected arc, not any single issue.`+ : 'A single dramatic hero image of the protagonist that embodies the collected arc.');++ const layout = `A single full printable comic-book trade-paperback FRONT cover collecting an entire volume of issues. ${titleBlock} ${numberBlock}${titleLine} The rest of the cover is one bold hero image — bigger and more iconic than any single-issue cover (no panel borders, no multi-panel layout — this is a collected-edition cover).${styleClause}`;+ const body = `Volume cover concept: ${sceneDescription}`;+ return applyWorldStyle(`${layout}\n\n${body}`, world);+}++export function composeVolumeBackCoverPrompt({+ series, world, season, backCoverScript = '', extraStyle = '',+}) {+ const volumeTitle = (season?.title || '').trim();+ const concept = (backCoverScript || '').trim();++ const styleStack = stackStyle(series, extraStyle);+ const styleClause = styleStack ? ` Art style: ${styleStack}.` : '';++ const sceneDescription = concept+ || (volumeTitle+ ? `A quiet companion image evoking the volume "${volumeTitle}" — atmospheric, single subject.`+ : 'A quiet companion image — atmospheric, single subject.');++ const layout = `A single full printable comic-book trade-paperback BACK cover. NO text of any kind — no masthead, no logo, no title, no volume tag, no UPC, no credits, no typography, no captions, no panel borders, no multi-panel layout. The entire cover is one bold illustrated hero image, edge-to-edge.${styleClause}`;+ const body = `Volume back-cover concept: ${sceneDescription}`;+ return applyWorldStyle(`${layout}\n\n${body}`, world);+}++/**+ * Shared volume-cover enqueue helper — front + back covers share variant+ * resolution, proof-as-base i2i path, owner build, and job enqueue. Only the+ * prompt composer + script field name differ.+ *+ * Returns { jobId, mode, prompt, script, variant, fromProof } — `script`+ * is the resolved text (option override or persisted); caller renames to+ * `coverScript` / `backCoverScript` for its public API symmetry.+ */+async function enqueueVolumeCoverLike(seriesId, seasonId, target, options = {}) {+ if (target !== 'cover' && target !== 'backCover') {+ throw new Error(`enqueueVolumeCoverLike: unknown target "${target}"`);+ }+ const { series, world, season, settings } = await loadSeasonContext(seriesId, seasonId);+ const record = season[target] || null;+ const scriptOptionKey = target === 'cover' ? 'coverScript' : 'backCoverScript';+ const script = typeof options[scriptOptionKey] === 'string'+ ? options[scriptOptionKey]+ : (record?.script || '');const mode = resolveMode(options, settings);const variant = resolveVariant(options.target);const fromProof = variant === 'final' && options.useProofAsBase === true;const initImagePath = fromProof- ? resolveProofInitImage(cover?.proofImage, 'cover')+ ? resolveProofInitImage(record?.proofImage, `volume ${target}`): null;const initImageStrength = fromProof? (Number.isFinite(options.initImageStrength) ? options.initImageStrength : PROOF_AS_BASE_DEFAULT_STRENGTH): undefined;- const prompt = composeComicCoverPrompt({- series, world, issue, coverScript,- extraStyle: composeExtraStyle(series, issue, 'comicPages', options.extraStyle),- });+ // Volume covers use the series-level visual style (no per-issue override,+ // since a volume spans many issues that may have different overrides).+ const styleFragment = resolveVisualStyle(series, null, 'comicPages')?.promptFragment || '';+ const extraStyle = joinStyleParts(styleFragment, options.extraStyle);+ const prompt = target === 'cover'+ ? composeVolumeCoverPrompt({ series, world, season, coverScript: script, extraStyle })+ : composeVolumeBackCoverPrompt({ series, world, season, backCoverScript: script, extraStyle });+ const logTarget = target === 'cover' ? 'cover' : 'back cover';const jobId = enqueueImageJob({prompt, world, settings, mode,options: { ...options, initImagePath, initImageStrength },- owner: buildComicPagesOwner({ issueId, target: 'cover', variant }),- logLine: `🎨 Pipeline comic cover — issue=${issueId.slice(0, 8)} number=${issue.number || 1} variant=${variant}${fromProof ? ' (from proof)' : ''}`,+ owner: buildSeasonCoverOwner({ seriesId, seasonId, target, variant }),+ logLine: `🎨 Pipeline volume ${logTarget} — series=${seriesId.slice(0, 8)} season=${seasonId.slice(0, 8)} vol=${season.number || 1} variant=${variant}${fromProof ? ' (from proof)' : ''}`,});- return { jobId, mode, prompt, coverScript, variant, fromProof };+ return { jobId, mode, prompt, script, variant, fromProof };+}++/**+ * Enqueue a volume (season) FRONT cover render. Returns+ * { jobId, mode, prompt, coverScript, variant, fromProof }.+ */+export async function enqueueVolumeCover(seriesId, seasonId, options = {}) {+ const { script, ...rest } = await enqueueVolumeCoverLike(seriesId, seasonId, 'cover', options);+ return { ...rest, coverScript: script };+}++/**+ * Enqueue a volume (season) BACK cover render. Returns+ * { jobId, mode, prompt, backCoverScript, variant, fromProof }.+ */+export async function enqueueVolumeBackCover(seriesId, seasonId, options = {}) {+ const { script, ...rest } = await enqueueVolumeCoverLike(seriesId, seasonId, 'backCover', options);+ return { ...rest, backCoverScript: script };}export function composeComicPagePrompt({diff --git a/server/services/pipeline/volumePdf.js b/server/services/pipeline/volumePdf.jsnew file mode 100644index 0000000000..969c1cf49c--- /dev/null+++ b/server/services/pipeline/volumePdf.js@@ -0,0 +1,184 @@+/**+ * Assemble a print-ready trade-paperback PDF for one volume (season).+ *+ * Order: [vol front] → for each issue in arcPosition order:+ * [issue front] → [issue pages…] → [issue back]+ * → [vol back] → optional colophon.+ *+ * Issues with `seasonId === null` are ignored (they're not in this volume).+ * Issues in the volume that lack a rendered slot for a given page/cover are+ * silently skipped — the colophon surfaces "M of N issues, P of Q pages+ * rendered" so the user can see what's still pending.+ *+ * Volume cover existence is required: a coverless volume PDF would assemble+ * silently and look like a "publisher proof" instead of a trade paperback,+ * so the route surfaces a 409 with ERR_NO_VOLUME_COVER instead.+ */++import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';+import { slugifyForFilename } from '../../lib/civitai.js';+import { pickRenderedFilename } from '../../lib/renderSlot.js';+import { readImageFromMedia, embedImageBytes, fitImage } from '../../lib/pdfImageEmbed.js';+import { getSeries } from './series.js';+import { getSeason } from './seasons.js';+import { listIssues } from './issues.js';+import { PAGE_SIZES, DEFAULT_PAGE_SIZE } from './comicPdf.js';++export const ERR_NO_VOLUME_COVER = 'PIPELINE_VOLUME_PDF_NO_COVER';+export const ERR_NO_RENDERED_ISSUES = 'PIPELINE_VOLUME_PDF_NO_RENDERED_ISSUES';+const makeErr = (message, code) => Object.assign(new Error(message), { code });++const READ_OPTS = { subject: 'volume page image' };+const EMBED_OPTS = { unsupportedCode: 'PIPELINE_VOLUME_PDF_UNSUPPORTED_IMAGE' };++/**+ * @returns {{ bytes: Uint8Array, pageCount: number, filename: string, issueManifest: Array }}+ */+export async function buildVolumePdf(seriesId, seasonId, opts = {}) {+ const season = await getSeason(seriesId, seasonId);+ const series = await getSeries(seriesId);++ const sizeKey = PAGE_SIZES[opts.size] ? opts.size : DEFAULT_PAGE_SIZE;+ const { width: pageW, height: pageH } = PAGE_SIZES[sizeKey];+ const includeColophon = opts.includeColophon !== false;++ const volCoverFilename = pickRenderedFilename(season.cover);+ if (!volCoverFilename) {+ throw makeErr(+ `Volume ${season.number || 1} has no rendered front cover yet — render it before compiling the volume PDF.`,+ ERR_NO_VOLUME_COVER,+ );+ }+ const volBackFilename = pickRenderedFilename(season.backCover);++ // All issues in this volume, sorted by arcPosition (with `??` fallback to+ // `number`). `||` would silently demote `arcPosition === 0` — a legitimate+ // first-position value — so use nullish coalescing.+ const all = await listIssues({ seriesId });+ const issuesInVolume = all+ .filter((iss) => iss.seasonId === seasonId)+ .sort((a, b) => (a.arcPosition ?? a.number ?? 0) - (b.arcPosition ?? b.number ?? 0));++ // Build the ordered filename list + a parallel manifest for the colophon.+ // The manifest tracks how many pages each issue contributed so the+ // colophon can surface "Issue #3 — 14 of 22 pages rendered" honestly.+ const targets = [{ filename: volCoverFilename, kind: 'vol-cover' }];+ const issueManifest = [];+ for (const iss of issuesInVolume) {+ const cp = iss.stages?.comicPages || {};+ const issueCoverFn = pickRenderedFilename(cp.cover);+ const issueBackFn = pickRenderedFilename(cp.backCover);+ const pages = Array.isArray(cp.pages) ? cp.pages : [];+ const pageFilenames = pages.map(pickRenderedFilename).filter(Boolean);++ const totalSlots = (cp.cover ? 1 : 0) + pages.length + (cp.backCover ? 1 : 0);+ const renderedSlots = (issueCoverFn ? 1 : 0) + pageFilenames.length + (issueBackFn ? 1 : 0);++ issueManifest.push({+ number: iss.number,+ title: iss.title,+ pagesRendered: pageFilenames.length,+ pagesTotal: pages.length,+ coverRendered: !!issueCoverFn,+ backCoverRendered: !!issueBackFn,+ totalSlots,+ renderedSlots,+ });++ if (issueCoverFn) targets.push({ filename: issueCoverFn, kind: 'issue-cover' });+ for (const fn of pageFilenames) targets.push({ filename: fn, kind: 'page' });+ if (issueBackFn) targets.push({ filename: issueBackFn, kind: 'issue-back' });+ }+ if (volBackFilename) targets.push({ filename: volBackFilename, kind: 'vol-back' });++ if (targets.length === 1) {+ // Only the volume front cover and nothing else — not really a volume.+ throw makeErr(+ `Volume ${season.number || 1} has no rendered issue pages yet — render at least one issue's pages first.`,+ ERR_NO_RENDERED_ISSUES,+ );+ }++ // Parallel disk reads; embed sequentially because pdf-lib is single-threaded.+ // A failed read for one image must not fail the whole download.+ const loaded = await Promise.all(targets.map(({ filename, kind }) =>+ readImageFromMedia(filename, READ_OPTS)+ .then((bytes) => ({ filename, kind, bytes }))+ .catch((err) => ({ filename, kind, err })),+ ));++ const pdf = await PDFDocument.create();+ const volTitle = season.title || `Volume ${season.number || 1}`;+ pdf.setTitle(`${series.name || 'Untitled'} — ${volTitle}`.trim());+ if (series.logline) pdf.setSubject(series.logline);+ pdf.setProducer('PortOS');+ pdf.setCreator('PortOS pipeline');++ let pageCount = 0;+ for (const entry of loaded) {+ if (entry.err) {+ console.error(`❌ volumePdf — skipped "${entry.filename}": ${entry.err.message || entry.err}`);+ continue;+ }+ const img = await embedImageBytes(pdf, entry.bytes, entry.filename, EMBED_OPTS).catch((err) => {+ console.error(`❌ volumePdf — embed failed "${entry.filename}": ${err.message || err}`);+ return null;+ });+ if (!img) continue;+ const page = pdf.addPage([pageW, pageH]);+ page.drawImage(img, fitImage(img.width, img.height, pageW, pageH));+ pageCount += 1;+ }++ if (pageCount === 0) {+ throw makeErr('No usable pages — all embeds failed', ERR_NO_RENDERED_ISSUES);+ }++ if (includeColophon) {+ const colophon = pdf.addPage([pageW, pageH]);+ const font = await pdf.embedFont(StandardFonts.Helvetica);+ const fontBold = await pdf.embedFont(StandardFonts.HelveticaBold);+ const left = 72;+ let cursor = pageH - 96;+ const drawLine = (text, { size = 11, bold = false, color = rgb(0.2, 0.2, 0.2) } = {}) => {+ colophon.drawText(text, { x: left, y: cursor, size, font: bold ? fontBold : font, color });+ cursor -= size + 8;+ };+ drawLine(series.name || 'Untitled Series', { size: 22, bold: true, color: rgb(0, 0, 0) });+ drawLine(`Volume ${season.number || 1} — ${season.title || ''}`.trim(), { size: 14, bold: true });+ cursor -= 12;+ if (season.logline) drawLine(`Logline: ${season.logline}`, { size: 10 });+ drawLine(`Issues: ${issuesInVolume.length} Pages: ${pageCount} Generated: ${new Date().toISOString().slice(0, 19).replace('T', ' ')} UTC`, { size: 10 });+ cursor -= 8;+ drawLine('Contents:', { size: 11, bold: true });+ for (const m of issueManifest) {+ // `totalSlots === 0` happens when the issue has no cover, no pages,+ // and no back cover — labeling that "complete" would imply the issue+ // is shipped when in fact there's nothing in it.+ const renderStatus = m.totalSlots === 0+ ? 'empty'+ : m.renderedSlots === m.totalSlots+ ? 'complete'+ : `${m.renderedSlots}/${m.totalSlots} rendered`;+ drawLine(` #${m.number || '?'} — ${m.title || '(untitled)'} (${renderStatus})`, { size: 10 });+ }+ cursor -= 16;+ drawLine('Generated by PortOS pipeline.', { size: 9, color: rgb(0.45, 0.45, 0.45) });+ pageCount += 1;+ }++ const bytes = await pdf.save();+ return {+ bytes,+ pageCount,+ filename: buildVolumePdfFilename(series, season),+ issueManifest,+ };+}++function buildVolumePdfFilename(series, season) {+ const seriesSlug = slugifyForFilename(series.name || 'series');+ const num = String(season.number || 1).padStart(2, '0');+ const titleSlug = season.title ? slugifyForFilename(season.title) : '';+ return titleSlug ? `${seriesSlug}-vol-${num}-${titleSlug}.pdf` : `${seriesSlug}-vol-${num}.pdf`;+}