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
refactor: split pipeline issues.js and visualStages.js along CRUD/stage/sync seams (#2531)
Adam Eivy4acec7253616
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 9d6e1abbb5..fd27d8134c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -5,6 +5,10 @@- **First-run tutorial for POST cognitive drills.** The timed, stimulus-driven cognitive drills (n-back, digit-span, stroop, schulte-table, mental-rotation, reaction-time) start flashing a stimulus the instant they mount, which is disorienting the first time you meet one. Each drill type now shows a one-time how-to card — a plain-language goal, numbered steps, and the controls — the first time it's encountered, and holds the drill (and its timers) until you tap **Start drill**. The card is config-aware (it names the n-back lag, the digit-span direction, and the reaction-time mode), then never shows again for that type (tracked per type in `localStorage`). Non-timed drills (math/memory, LLM/verbal) are self-explanatory and are not gated.- **Voice fast-resolution cascade (lower CoS latency, opt-in).** The voice Chief of Staff can now triage each spoken/typed turn through fast client-side tiers before the (slow) server LLM: **tier 1 triggers** resolve navigation commands ("go to tasks", "open the daily log") instantly in the browser with no LLM; **tier 2** runs Chrome's on-device **Gemini Nano** (Prompt API — `window.LanguageModel` / legacy `self.ai.languageModel`) for simple/conversational turns, entirely local and private; **tier 3** is the existing server pipeline (recommend Ollama), which still handles every tool/action turn, personal-data retrieval, dictation, and confirmations. Off by default (existing installs keep all-server behavior); enable under **Settings → Voice → Fast resolution**, which also shows a live on-device-model availability pill with the `chrome://flags` hint. Applies to Web-Speech STT and typed input (whisper/hands-free audio turns stay server-driven); trigger/Nano replies are spoken through the configured TTS and keep barge-in + echo-suppression working. New `llm.fastPath` config (`enabled`/`triggers`/`browserLlm`/`browser.{temperature,topK}`); new client modules `browserLlm.js` (Nano client) and `voiceFastPath.js` (routing decision). Nothing runs a model the user hasn't triggered (no cold-bootstrap).+## Changed++- **[issue-2531] Split the pipeline `issues.js` and `visualStages.js` monoliths along CRUD/stage/sync seams.** The ~1470-line `server/services/pipeline/issues.js` is now a thin barrel over `issuesShared.js` (store facade + per-series write queue + record sanitizers + `renumberInline`), `issueCrud.js` (create/read/list/update/delete + numbering/reassign), `issueStages.js` (per-stage merge/history/restore), and `issueSync.js` (peer-sync LWW merge + tombstone GC). The ~1760-line `visualStages.js` is now a thin barrel over `visualStageHelpers.js` (shared style/prompt composers + image-gen enqueue plumbing), `covers.js` (comic + volume front/back covers), `comicPages.js` (comic page renders + panel prompt refine), and `storyboards.js` (scene/shot renders + scene refine). Pure mechanical refactor — no behavior change; the single-tail-per-series write serialization (`queueSeriesIssuesWrite`) and the store's `queueTypeIndexWrite` merge snapshot are preserved, and every existing `from './issues.js'` / `from './visualStages.js'` import path still resolves through the barrels.+## Documentation- **[issue-2546] Document missing `.env` vars and the boot `CREATE INDEX` lock window.** `.env.example` now carries commented entries with purpose notes for four vars the server actually reads but never documented: `PUBLIC_HOST` (public hostname baked into Google/Spotify OAuth redirect URIs), `SPOTIFY_REDIRECT_URI` (verbatim Spotify redirect override), `CODEX_HOME` (Codex CLI home scanned for provider-usage stats), and `HUGGINGFACE_TOKEN` (the fourth HF-token alias read by the Hugging Face catalog client). Separately, `ensureSchema()` in `server/lib/db.js` creates every index (incl. the HNSW vector index) non-`CONCURRENTLY`, so the first apply on a large pre-existing table takes a write-blocking lock at boot; a comment there and a new **Boot schema upgrades & the CREATE INDEX lock window** section in `docs/STORAGE.md` explain when this bites (existing-install upgrades, not fresh installs) and why the fix for a future large-table index is a `CONCURRENTLY` db-migration rather than changing `ensureSchema()`. Docs-only — no runtime behavior change.diff --git a/server/services/pipeline/comicPages.js b/server/services/pipeline/comicPages.jsnew file mode 100644index 0000000000..9953a90fe6--- /dev/null+++ b/server/services/pipeline/comicPages.js@@ -0,0 +1,668 @@+/**+ * Pipeline — Comic page renders + panel prompt refine (#2531)+ *+ * Comic-page prompt composition, page/panel image enqueue + persist, the+ * per-page image-to-image refine, the generic visual-image enqueue, and the+ * consistency-reference resolvers. Extracted from the former monolithic+ * `visualStages.js`; shares plumbing via `./visualStageHelpers.js`.+ */++import { updateStage, updateStageWithLatest, assertStageUnlocked, VISUAL_STAGE_IDS } from './issues.js';+import { resolveGalleryImage } from '../../lib/fileUtils.js';+import { buildComicPagesOwner, slotKeyForVariant } from './owners.js';+import { ServerError } from '../../lib/errorHandler.js';+import {+ buildCharByKey, matchSceneCharacters, matchCharactersInText,+ matchPlacesInText, matchObjectsInText,+} from '../../lib/scenePrompt.js';+import { flattenCanonDescriptorFragments, richCanonDescriptorFragments } from '../../lib/canonPrompt.js';+import { sameComicScene } from '../../lib/comicScriptParser.js';+import { runPromptRefine, runImagePromptCandidates } from './refineHelpers.js';+import {+ applyWorldStyle, stackStyle, formatBalloon, loadBibleContext, resolveMode,+ resolveVariant, resolveProofInitImage, resolvePageReferenceImage,+ REFERENCE_PAGE_DEFAULT_STRENGTH, PROOF_AS_BASE_DEFAULT_STRENGTH,+ REFINE_RENDER_DEFAULT_STRENGTH, applyCharacterLorasToRender, loraRenderOptions,+ enqueueImageJob, buildRenderSlot, composeVisualPrompt, seriesBibleCtx,+ issueCtx, neighborText, loadRefineContext, assertCharacterAppearancesResolve,+} from './visualStageHelpers.js';++// Resolve the `referencePage` option ('prior' | 'next' | <0-based index>) to a+// concrete page index, or null when unset. Pure + bounds-checked against the+// page count; throws a clear 400 for an out-of-range request (prior on page 1,+// next on the last page, or an explicit index that doesn't exist).+export function resolveReferencePageIndex(referencePage, pageIndex, pageCount) {+ if (referencePage == null) return null;+ let target;+ if (referencePage === 'prior') target = pageIndex - 1;+ else if (referencePage === 'next') target = pageIndex + 1;+ else if (Number.isInteger(referencePage)) target = referencePage;+ else throw new ServerError(`Invalid referencePage: ${referencePage}`, { status: 400, code: 'PIPELINE_COMIC_REFERENCE_BAD' });+ if (target === pageIndex) {+ throw new ServerError('A page cannot be its own consistency reference', { status: 400, code: 'PIPELINE_COMIC_REFERENCE_SELF' });+ }+ if (target < 0 || target >= pageCount) {+ throw new ServerError(+ `Consistency reference page ${target + 1} is out of range (have ${pageCount} page${pageCount === 1 ? '' : 's'})`,+ { status: 400, code: 'PIPELINE_COMIC_REFERENCE_RANGE' },+ );+ }+ return target;+}++// Auto-pick a consistency reference for a fresh page render: the immediately+// prior page, but ONLY when it shares this page's scene AND has already been+// rendered. This is the default when the caller doesn't name an explicit+// `referencePage` — so a continuing scene keeps its incidental characters and+// environment consistent page-to-page, while a scene boundary renders fresh+// (the "don't reference the prior page across a scene cut" rule). Pure ++// soft: returns null (rather than throwing) when there's no prior page, the+// scenes differ, scene markers are absent (legacy scripts → no auto-chain), or+// the prior page has no image yet — auto-chaining is a best-effort nicety, not+// a hard requirement like an explicitly requested reference.+export function resolveAutoReferenceIndex(pages, pageIndex) {+ const cur = pages?.[pageIndex];+ const prior = pages?.[pageIndex - 1];+ if (!cur || !prior) return null;+ if (!sameComicScene(prior, cur)) return null;+ const hasImage = !!(prior.finalImage?.filename || prior.proofImage?.filename);+ return hasImage ? pageIndex - 1 : null;+}++// Resolve which init image (if any) a comic-page render should use, applying+// the three precedence tiers in order:+// 1. EXPLICIT `referencePage` ('prior' | 'next' | <index>) — strongest+// intent; bounds-checked (throws on an out-of-range request). `'none'`+// opts out of the AUTO tier (no cross-page reference, even mid-scene).+// 2. PROOF-AS-BASE — a final-variant upscale off this page's own proof. Beats+// auto so "Final from proof" still preserves panel layout. Orthogonal to+// `'none'` (it's a self-upscale, not a sibling reference), so it still+// applies when the user picked 'none' but left the proof-as-base box on.+// 3. AUTO — chain off the prior page when it shares this page's scene and is+// already rendered; a scene boundary (or absent scene markers) skips it.+// Pure; returns the chosen tier so the caller picks the init image + strength+// and logs it. `autoReference` is true only when the AUTO tier supplied the+// page (so callers can distinguish it from an explicit reference).+export function resolveComicPageReference({ referencePage, useProofAsBase, variant, pages, pageIndex }) {+ const explicitOff = referencePage === 'none';+ const wantsExplicit = !explicitOff && referencePage != null && referencePage !== 'auto';+ const explicitIndex = wantsExplicit+ ? resolveReferencePageIndex(referencePage, pageIndex, pages.length)+ : null;+ const fromProof = explicitIndex == null && variant === 'final' && useProofAsBase === true;+ const autoIndex = (explicitIndex == null && !fromProof && !explicitOff)+ ? resolveAutoReferenceIndex(pages, pageIndex)+ : null;+ const referencePageIndex = explicitIndex != null ? explicitIndex : autoIndex;+ return {+ referencePageIndex,+ fromReference: referencePageIndex != null,+ autoReference: referencePageIndex != null && explicitIndex == null,+ fromProof,+ };+}++export function composeComicPagePrompt({+ series, world, page, pageNumber, extraStyle = '',+ matchedCharacters = [], matchedPlaces = [], matchedObjects = [],+ // entryId/ingredientId → trained-LoRA trigger word (see+ // applyCharacterLorasToRender). Passed as a map so this compose stays pure.+ loraTriggerByKey = null,+}) {+ const panels = Array.isArray(page?.panels) ? page.panels : [];+ if (panels.length === 0) return '';++ // Placed AFTER the layout clause: diffusion models weight earlier tokens+ // more heavily, and the page-shape instruction has to claim that position.+ // A character with a trained LoRA gets its trigger word parenthesized+ // after the name — the token the adapter binds the identity to.+ const featuring = (matchedCharacters || [])+ .map((c) => ({+ name: c.name,+ trigger: loraTriggerByKey?.get(c.id) || loraTriggerByKey?.get(c.ingredientId) || null,+ desc: (c.physicalDescription || c.description || '').trim(),+ }))+ .filter((c) => c.name && c.desc)+ .map((c) => `${c.name}${c.trigger ? ` (${c.trigger})` : ''}: ${c.desc}`)+ .join('; ');++ // Place baseline: pull the full RICH descriptor set per matched place+ // (description / Palette / Era / Weather / recurringDetails). Same shared+ // helper that drives buildScenePrompt's placeFrags + synthesizeCanonPrompt's+ // body, so comic-page renders pick up the same era/weather/atmosphere cues+ // diffusion models weight for lighting + period dress. Multi-place per page+ // is supported (a single page can span more than one location).+ const placesClause = (matchedPlaces || [])+ .map((p) => {+ const body = flattenCanonDescriptorFragments(richCanonDescriptorFragments('place', p));+ const head = p.name ? `${p.name}:` : '';+ return [head, body].filter(Boolean).join(' ');+ })+ .filter(Boolean)+ .join(' | ');++ // Notable objects/props/vehicles cited in the prose. Keeps signature props+ // (e.g. "the brass key", "Wren's sloop") visually canonical across pages.+ const notable = (matchedObjects || [])+ .map((o) => ({ name: o.name, desc: (o.description || '').trim() }))+ .filter((o) => o.name && o.desc)+ .map((o) => `${o.name}: ${o.desc}`)+ .join('; ');++ // Append a sentence-terminator unless the source text already ends in one —+ // prose extracted from a script often carries its own `.`, `!`, or `?`, and+ // double-punctuating like "...sunstreaming in.." is noisy in prompts. The+ // optional trailing `"` covers the dialogue/caption case where we wrap the+ // text in quotes — `KESSA: "...away."` should NOT become `KESSA: "...away.".`.+ const endPunct = (s) => /[.!?]"?$/.test(s) ? s : `${s}.`;++ const panelLines = panels.map((p, i) => {+ const idx = i + 1;+ const desc = (p.description || '').trim() || 'continuation of previous beat';+ const parts = [`Panel ${idx}: ${endPunct(desc)}`];+ if (p.caption && p.caption.trim()) parts.push(`Narration caption box reads: "${endPunct(p.caption.trim())}"`);+ if (Array.isArray(p.dialogue) && p.dialogue.length > 0) {+ // Format each dialogue line as `Speech balloon reads: "<text>" (spoken+ // by NAME[, balloon style: <hint>])`. Lettered content (the quoted+ // text) leads so the diffusion model anchors on it; speaker + style+ // hints trail as attribution. The previous `NAME (MODIFIER): "text"`+ // shape (Marvel/DC script convention) was being lettered verbatim+ // INTO balloons by the image model — including the speaker name and+ // parentheticals like "(EARPIECE)". Dropping speaker into the+ // attribution slot and translating common parentheticals to balloon+ // styling hints (jagged for radio/earpiece, dashed for whisper, cloud+ // for thought) preserves the artistic intent without leaking labels+ // into the lettered text.+ const dlg = p.dialogue+ .map((d) => formatBalloon(d.character, d.line))+ .filter(Boolean)+ .join(' ');+ if (dlg) parts.push(dlg);+ }+ if (p.sfx && p.sfx.trim()) parts.push(`SFX lettering: ${endPunct(p.sfx.trim())}`);+ return parts.join(' ');+ });++ const styleStack = stackStyle(series, extraStyle);+ const styleClause = styleStack ? ` Art style: ${styleStack}.` : '';+ const seriesClause = series?.name ? ` from the series "${series.name}"` : '';++ const layout = `A single full printable comic book page${seriesClause}, page ${pageNumber}. Render a balanced multi-panel comic page layout with ${panels.length} clearly bordered panel${panels.length === 1 ? '' : 's'} arranged for left-to-right, top-to-bottom reading. Include lettered speech balloons for dialogue, rectangular narration boxes for captions, and stylized SFX where indicated. **Balloon lettering rule: each speech balloon contains ONLY the quoted text shown after "Speech balloon reads:". NEVER letter the speaker's name, role, or any parenthetical attribution (e.g. "(EARPIECE)", "(WHISPERED)", "(OFF-PANEL)") inside the balloon — those are tail-direction and balloon-styling cues for the artist, not lettered content.** Each panel must be visually distinct, with consistent character designs across panels.${styleClause}`;+ const featuringClause = featuring ? `\n\nFeaturing — ${featuring}` : '';+ const placeClause = placesClause ? `\n\nSetting — ${placesClause}` : '';+ const notableClause = notable ? `\n\nNotable — ${notable}` : '';++ return applyWorldStyle(`${layout}${featuringClause}${placeClause}${notableClause}\n\n${panelLines.join('\n\n')}`, world, series);+}++/**+ * Enqueue a full-comic-page image render. Builds a structured page-level+ * prompt from `issue.stages.comicPages.pages[pageIndex].panels[]` and hands+ * it to the image-gen queue. Caller records the returned jobId on the+ * appropriate variant slot (`pages[pageIndex].proofImage` /+ * `pages[pageIndex].finalImage`) based on `options.target`.+ *+ * When `options.useProofAsBase` is set and target='final', resolves the+ * page's existing proof image and passes it as initImagePath so the local+ * i2i runner can preserve panel layout while upscaling.+ *+ * Returns { jobId, mode, prompt, pageIndex, variant, fromProof }.+ */+export async function enqueueVisualComicPage(issueId, options = {}) {+ const pageIndex = Number(options.pageIndex);+ if (!Number.isInteger(pageIndex) || pageIndex < 0) {+ throw new ServerError('pageIndex must be a non-negative integer', {+ status: 400, code: 'PIPELINE_COMIC_PAGE_BAD_INDEX',+ });+ }+ const { issue, settings, series, world, canon } = await loadBibleContext(issueId);+ assertStageUnlocked(issue, 'comicPages');+ const pages = Array.isArray(issue.stages?.comicPages?.pages) ? issue.stages.comicPages.pages : [];+ const page = pages[pageIndex];+ if (!page) {+ throw new ServerError(`page index ${pageIndex} out of range (have ${pages.length})`, {+ status: 404, code: 'PIPELINE_COMIC_PAGE_NOT_FOUND',+ });+ }+ if (!Array.isArray(page.panels) || page.panels.length === 0) {+ throw new ServerError('page has no panels — add at least one panel description before rendering', {+ status: 400, code: 'PIPELINE_COMIC_PAGE_NO_PANELS',+ });+ }++ const mode = resolveMode(options, settings);+ const variant = resolveVariant(options.target);++ // Consistency reference: pass an already-rendered page as the init image so a+ // continuing scene keeps its incidental, un-described characters and+ // environment consistent (the "two newlyweds drift between pages" problem).+ // The three-tier precedence (explicit > proof-as-base > auto-within-scene)+ // lives in resolveComicPageReference.+ const { referencePageIndex, fromReference, autoReference, fromProof } = resolveComicPageReference({+ referencePage: options.referencePage,+ useProofAsBase: options.useProofAsBase,+ variant, pages, pageIndex,+ });+ const initImagePath = fromReference+ ? resolvePageReferenceImage(pages[referencePageIndex], `page ${referencePageIndex + 1}`)+ : fromProof+ ? resolveProofInitImage(page.proofImage, `page ${pageIndex + 1}`)+ : null;+ const initImageStrength = fromReference+ ? (Number.isFinite(options.initImageStrength) ? options.initImageStrength : REFERENCE_PAGE_DEFAULT_STRENGTH)+ : fromProof+ ? (Number.isFinite(options.initImageStrength) ? options.initImageStrength : PROOF_AS_BASE_DEFAULT_STRENGTH)+ : undefined;++ // Build a free-text haystack from every panel's prose (description ++ // caption + sfx). Dialogue lines feed character matching via CAPS names+ // separately because the parser already structures them.+ const proseHaystack = page.panels+ .flatMap((p) => [p.description, p.caption, p.sfx])+ .filter(Boolean)+ .join('\n');+ const dialogueNames = page.panels.flatMap((p) =>+ (p.dialogue || []).map((d) => d.character).filter(Boolean),+ );++ // Characters: union of (a) dialogue CAPS speakers and (b) anyone named in+ // panel prose. Deduplicates on id/name inside the matchers. Canon is read+ // from `canon` (Phase B helper) which prefers the linked universe and+ // falls back to series arrays for pre-migration data.+ const charByKey = buildCharByKey(canon.characters);+ const fromDialogue = matchSceneCharacters(dialogueNames, charByKey);+ const fromProse = matchCharactersInText(proseHaystack, canon.characters);+ const seenCharKeys = new Set();+ const matchedCharacters = [...fromDialogue, ...fromProse].filter((c) => {+ const k = c.id || c.name;+ if (seenCharKeys.has(k)) return false;+ seenCharKeys.add(k);+ return true;+ });++ // Places + objects: text-match against the panel prose. Codex can't take+ // reference images, so rich text descriptions in the prompt are how we+ // keep environments and signature props visually consistent page-to-page.+ const matchedPlaces = matchPlacesInText(proseHaystack, canon.places);+ const matchedObjects = matchObjectsInText(proseHaystack, canon.objects);++ // composeComicPagePrompt only returns '' when panels.length === 0, which is+ // already rejected above. The "(continuation of previous beat)" placeholder+ // covers panels with no description, so the prompt is non-empty by here.+ const { loras: characterLoras, triggerByKey } = await applyCharacterLorasToRender({+ matchedCharacters, mode, options, settings,+ });++ const prompt = composeComicPagePrompt({+ series, world, page, pageNumber: pageIndex + 1,+ extraStyle: options.extraStyle || '',+ matchedCharacters, matchedPlaces, matchedObjects,+ loraTriggerByKey: triggerByKey,+ });++ const jobId = enqueueImageJob({+ prompt, world, settings, mode,+ options: { ...options, initImagePath, initImageStrength, ...loraRenderOptions(characterLoras) },+ owner: buildComicPagesOwner({ issueId, target: 'page', pageIndex, variant }),+ logLine: `📄 Pipeline comic page — issue=${issueId.slice(0, 8)} page=${pageIndex + 1} panels=${page.panels.length} variant=${variant}${fromProof ? ' (from proof)' : ''}${fromReference ? ` (${autoReference ? 'auto-ref' : 'ref'} page ${referencePageIndex + 1})` : ''}`,+ });+ return { jobId, mode, prompt, pageIndex, variant, fromProof, fromReference, autoReference, referencePageIndex };+}++/**+ * Splice an in-flight render slot onto+ * `stages.comicPages.pages[pageIndex].{proofImage|finalImage}` through+ * `updateStageWithLatest` (the serialized issue write tail) so a concurrent+ * page edit or sibling render that wrote between the enqueue and this persist+ * can't be reverted by a stale snapshot. Shared by `renderComicPage` and+ * `refineComicPageRender` — the filename hook only attaches the completed+ * image when the target slot already carries the returned jobId (the reason+ * this write must live behind the shared entry points, not only in the route).+ *+ * Returns { issue, stage } from the write tail.+ */+async function persistComicPageSlot(issueId, pageIndex, { variant, jobId, prompt, width, height, fromProof }) {+ const slotKey = slotKeyForVariant(variant);+ const slotRecord = buildRenderSlot({ slotKey, jobId, prompt, width, height, fromProof });+ return updateStageWithLatest(issueId, 'comicPages', (currentStage) => {+ const currentPages = Array.isArray(currentStage?.pages) ? currentStage.pages : [];+ if (!currentPages[pageIndex]) {+ throw new ServerError(+ `pageIndex ${pageIndex} out of range — comicPages has ${currentPages.length} page${currentPages.length === 1 ? '' : 's'}`,+ { status: 404, code: 'PIPELINE_COMIC_PAGE_NOT_FOUND' },+ );+ }+ const nextPages = [...currentPages];+ nextPages[pageIndex] = { ...currentPages[pageIndex], [slotKey]: slotRecord };+ return { status: 'edited', pages: nextPages };+ });+}++/**+ * Enqueue + persist a full comic-page render in ONE service call — the shared+ * entry point behind both the route handler and the CDO orchestrator tool+ * (#2241, mirroring the #2234 cover treatment). The bare `enqueueVisualComicPage`+ * only queues the job; the filename hook attaches the completed render ONLY if+ * `pages[pageIndex]`'s active variant slot already carries the returned jobId,+ * and that slot write used to live in the route handler. Extracting it here+ * means the orchestrator gets orchestrated pages instead of silently dropping+ * them. `options` mirrors the route body (target/useProofAsBase/referencePage,+ * width/height, mode, …).+ *+ * Returns the enqueue result plus the persisted { issue, stage }.+ */+export async function renderComicPage(issueId, options = {}) {+ const result = await enqueueVisualComicPage(issueId, options);+ const { issue, stage } = await persistComicPageSlot(issueId, result.pageIndex, {+ variant: result.variant, jobId: result.jobId, prompt: result.prompt,+ width: options.width, height: options.height, fromProof: result.fromProof,+ });+ return { ...result, issue, stage };+}++/**+ * AI prompt-refine + image-to-image re-render for a SMALL correction to an+ * already-rendered comic page (issue #1534). Unlike `enqueueVisualComicPage`+ * (which composes a fresh prompt from the page's panels and re-renders from+ * source), this:+ *+ * 1. Takes the page's CURRENT render prompt (stored on the proof/final slot)+ * plus the user's free-text instruction, and asks the LLM to ADJUST that+ * prompt to reflect the instruction — never regenerating from the comic+ * script. Everything not called out by the instruction is preserved.+ * 2. Re-renders image-to-image using the page's EXISTING output image as the+ * init base at a low denoise, so the panel layout / composition / lettering+ * survive and only the requested change moves.+ *+ * The base image (and the slot the refined render lands back on) is the page's+ * final render when present, else its proof; `options.target` forces a variant.+ * This is the common "page is mostly right, needs a tweak" case where a full+ * re-render from the script would throw away everything good about the current+ * output.+ *+ * Returns { jobId, mode, prompt, pageIndex, variant, changes, runId, providerId }.+ */+export async function refineComicPageRender(issueId, options = {}) {+ const pageIndex = Number(options.pageIndex);+ if (!Number.isInteger(pageIndex) || pageIndex < 0) {+ throw new ServerError('pageIndex must be a non-negative integer', {+ status: 400, code: 'PIPELINE_COMIC_PAGE_BAD_INDEX',+ });+ }+ const instruction = (options.instruction || '').trim();+ if (!instruction) {+ throw new ServerError('instruction is required — describe the small change to apply', {+ status: 400, code: 'PIPELINE_COMIC_REFINE_NO_INSTRUCTION',+ });+ }++ const { issue, settings, series, world } = await loadBibleContext(issueId);+ assertStageUnlocked(issue, 'comicPages');+ const pages = Array.isArray(issue.stages?.comicPages?.pages) ? issue.stages.comicPages.pages : [];+ const page = pages[pageIndex];+ if (!page) {+ throw new ServerError(`page index ${pageIndex} out of range (have ${pages.length})`, {+ status: 404, code: 'PIPELINE_COMIC_PAGE_NOT_FOUND',+ });+ }++ // Mirror the client's getProofSlot: a legacy page (pre proof/final split)+ // stores its render at the record root (imageJobId/filename/prompt), and the+ // UI surfaces that as the proof slot — so it shows the Refine control. Resolve+ // the same legacy shape here, otherwise refining a page whose only render is+ // legacy would 400 with NO_RENDER even though the UI shows it as rendered. The+ // refined render lands on the proofImage slot, upgrading the record into the+ // new shape (same as a /render of a legacy page).+ const legacyProofSlot = (!page.proofImage?.filename && (page.imageJobId || page.filename))+ ? { filename: page.filename || null, prompt: page.prompt || null }+ : null;++ // Resolve which rendered variant to refine: an explicit target wins; else+ // prefer the final render, falling back to the proof. The refined render+ // lands back on that SAME slot (the user is correcting that image).+ const variant = options.target+ ? resolveVariant(options.target)+ : (page.finalImage?.filename ? 'final' : 'proof');+ const baseSlot = variant === 'final'+ ? page.finalImage+ : (page.proofImage?.filename ? page.proofImage : legacyProofSlot);+ const baseFilename = baseSlot?.filename;+ if (!baseFilename) {+ throw new ServerError(+ `Cannot refine page ${pageIndex + 1}'s ${variant} render: it has no rendered image yet — render the page first.`,+ { status: 400, code: 'PIPELINE_COMIC_REFINE_NO_RENDER' },+ );+ }+ // The stored slot prompt is what we adjust — refusing to fall back to a+ // recomposed-from-script prompt is the whole point (a surgical edit, not a+ // redraw). A legacy slot without a persisted prompt must be re-rendered once+ // through `/render` (which stamps the prompt) before it can be refined.+ const currentPrompt = (baseSlot.prompt || '').trim();+ if (!currentPrompt) {+ throw new ServerError(+ `Cannot refine page ${pageIndex + 1}'s ${variant} render: its stored render prompt is missing — re-render the page first.`,+ { status: 400, code: 'PIPELINE_COMIC_REFINE_NO_PROMPT' },+ );+ }+ const initImagePath = resolveGalleryImage(baseFilename, { mustExist: false });+ if (!initImagePath) {+ throw new ServerError(+ `Existing page image path escaped the gallery for page ${pageIndex + 1}: ${baseFilename}`,+ { status: 400, code: 'PIPELINE_COMIC_REFINE_NOT_FOUND' },+ );+ }++ // Ask the LLM to apply the instruction to the existing prompt. resultField+ // 'prompt' + runPromptRefine's validation guarantees a non-empty string back;+ // `changes` is the short "what I changed" bullet list the UI surfaces.+ const { refined, changes, runId, providerId } = await runPromptRefine({+ templateName: 'pipeline-comic-page-refine-render',+ variables: {+ series: seriesBibleCtx(series),+ issue: issueCtx(issue),+ pageNumber: pageIndex + 1,+ currentPrompt: currentPrompt.slice(0, 16_000),+ instruction: instruction.slice(0, 2000),+ },+ options,+ source: 'pipeline-comic-page-refine-render',+ logTag: `Pipeline comic page refine — issue=${issueId.slice(0, 8)} page=${pageIndex + 1} variant=${variant}`,+ });++ const mode = resolveMode(options, settings);+ const initImageStrength = Number.isFinite(options.initImageStrength)+ ? Math.min(Math.max(options.initImageStrength, 0), 1)+ : REFINE_RENDER_DEFAULT_STRENGTH;++ const jobId = enqueueImageJob({+ prompt: refined, world, settings, mode,+ options: { ...options, initImagePath, initImageStrength },+ owner: buildComicPagesOwner({ issueId, target: 'page', pageIndex, variant }),+ logLine: `🪄 Pipeline comic page refine — issue=${issueId.slice(0, 8)} page=${pageIndex + 1} variant=${variant} strength=${initImageStrength}`,+ });+ const { issue: persistedIssue, stage } = await persistComicPageSlot(issueId, pageIndex, {+ variant, jobId, prompt: refined, width: options.width, height: options.height,+ });+ return { jobId, mode, prompt: refined, pageIndex, variant, changes, runId, providerId, issue: persistedIssue, stage };+}++/**+ * Enqueue one image render for a pipeline issue's visual stage. The caller+ * records the returned jobId on the issue's stage artifact list+ * (e.g. stages.comicPages.pages[i].panels[j].imageJobId).+ *+ * Returns { jobId, mode, prompt }.+ */+export async function enqueueVisualImage(issueId, stageId, options = {}) {+ if (!VISUAL_STAGE_IDS.includes(stageId)) {+ throw new ServerError(`not a visual stage: ${stageId}`, {+ status: 400, code: 'PIPELINE_VISUAL_BAD_STAGE',+ });+ }+ const { issue, settings, series, world, canon } = await loadBibleContext(issueId);+ assertStageUnlocked(issue, stageId);+ // Resolve wardrobe picks against canon at the request boundary — a dangling+ // characterId/wardrobeId is a client/state bug worth a 400, not the silent+ // drop buildScenePrompt would otherwise apply.+ assertCharacterAppearancesResolve(options.characterAppearances, canon.characters);+ const mode = resolveMode(options, settings);+ // Match on description + slugline so the featured-character set (and thus+ // which wardrobe picks apply) stays consistent with the scene-video / shot+ // paths and the storyboards picker UI — all of which match both fields.+ const matchedCharacters = matchCharactersInText(+ `${options.description || ''} ${options.slugline || ''}`,+ canon.characters,+ );+ const composedPrompt = composeVisualPrompt({+ series,+ description: options.description,+ slugline: options.slugline,+ extraStyle: options.extraStyle || '',+ matchedCharacters,+ world,+ canon,+ // Storyboard scene renders thread the scene's wardrobe picks through the+ // generic visual-image route, which has no scene index to look them up.+ characterAppearances: options.characterAppearances,+ });+ if (!composedPrompt) {+ throw new ServerError('visual prompt is empty (no description, no style)', {+ status: 400, code: 'PIPELINE_VISUAL_EMPTY_PROMPT',+ });+ }++ const { loras: characterLoras } = await applyCharacterLorasToRender({+ matchedCharacters, mode, options, settings,+ });+ // composeVisualPrompt is shared with the episode-video batch path, so the+ // trigger words append here rather than threading a new param through it.+ const triggerClause = characterLoras+ .filter((l) => l.triggerWord)+ .map((l) => `${l.character?.name || 'character'} (${l.triggerWord})`)+ .join(', ');+ const prompt = triggerClause ? `${composedPrompt}\n\nFeaturing ${triggerClause}.` : composedPrompt;++ const jobId = enqueueImageJob({+ prompt, world, settings, mode,+ options: { ...options, ...loraRenderOptions(characterLoras) },+ owner: `pipeline:${issueId}:${stageId}`,+ logLine: `🎬 Pipeline visual — issue=${issueId.slice(0, 8)} stage=${stageId}`,+ });+ return { jobId, mode, prompt };+}++// Validate the page/panel indices, lock, and non-empty description, then+// build the `pipeline-comic-panel-image-prompt` template variables. Shared by+// the 1:1 refine (replaces the description) and the N-candidate fan-out+// (non-destructive) so both feed the LLM identical context.+async function loadComicPanelPromptContext(issueId, pageIndex, panelIndex) {+ const pi = Number(pageIndex);+ const ni = Number(panelIndex);+ if (!Number.isInteger(pi) || pi < 0 || !Number.isInteger(ni) || ni < 0) {+ throw new ServerError('pageIndex and panelIndex must be non-negative integers', {+ status: 400, code: 'PIPELINE_PANEL_BAD_INDEX',+ });+ }+ const { issue, series } = await loadRefineContext(issueId);+ assertStageUnlocked(issue, 'comicPages');+ const pages = Array.isArray(issue.stages?.comicPages?.pages) ? [...issue.stages.comicPages.pages] : [];+ const page = pages[pi];+ if (!page) {+ throw new ServerError(`pageIndex ${pi} out of range (have ${pages.length})`, {+ status: 404, code: 'PIPELINE_COMIC_PAGE_NOT_FOUND',+ });+ }+ const panels = Array.isArray(page.panels) ? [...page.panels] : [];+ const panel = panels[ni];+ if (!panel) {+ throw new ServerError(`panelIndex ${ni} out of range (have ${panels.length})`, {+ status: 404, code: 'PIPELINE_COMIC_PANEL_NOT_FOUND',+ });+ }+ if (!(panel.description || '').trim()) {+ throw new ServerError('panel has no description to refine', {+ status: 400, code: 'PIPELINE_PANEL_EMPTY_DESCRIPTION',+ });+ }++ const prev = panels[ni - 1];+ const next = panels[ni + 1];+ // Drop dialogue rows whose line is empty/whitespace — matches the same+ // filter `composeComicPagePrompt` applies, so the refine template doesn't+ // get fed noisy `CHAR: ""` fragments that would confuse the LLM.+ const dialogue = Array.isArray(panel.dialogue) && panel.dialogue.length+ ? panel.dialogue+ .map((d) => {+ const character = (d.character || 'CHAR').trim() || 'CHAR';+ const line = (d.line || '').trim();+ return line ? `${character}: "${line}"` : null;+ })+ .filter(Boolean)+ .join(' / ')+ : '';++ const variables = {+ series: seriesBibleCtx(series),+ issue: issueCtx(issue),+ pageNumber: pi + 1,+ panelNumber: ni + 1,+ panelCount: panels.length,+ description: (panel.description || '').slice(0, 4000),+ caption: (panel.caption || '').slice(0, 1000),+ hasCaption: !!(panel.caption || '').trim(),+ dialogue,+ hasDialogue: !!dialogue,+ sfx: (panel.sfx || '').slice(0, 500),+ hasSfx: !!(panel.sfx || '').trim(),+ hasNeighbors: !!(prev || next),+ previousPanel: neighborText(prev),+ nextPanel: neighborText(next),+ };+ return { issue, pi, ni, pages, page, panels, panel, variables };+}++/**+ * Run the `pipeline-comic-panel-image-prompt` template against the current+ * panel + surrounding context, then persist the refined description on the+ * panel. Returns { panel, page, issue, stage, runId, changes, providerId }.+ */+export async function refineComicPanelPrompt(issueId, pageIndex, panelIndex, options = {}) {+ const { pi, ni, pages, page, panels, panel, variables } =+ await loadComicPanelPromptContext(issueId, pageIndex, panelIndex);++ const { refined, changes, runId, providerId } = await runPromptRefine({+ templateName: 'pipeline-comic-panel-image-prompt',+ variables,+ options,+ source: 'pipeline-comic-panel-prompt-refine',+ logTag: `Pipeline comic panel refine — issue=${issueId.slice(0, 8)} p=${pi + 1} panel=${ni + 1}`,+ });++ panels[ni] = { ...panel, description: refined };+ pages[pi] = { ...page, panels };+ const { issue: updatedIssue, stage } = await updateStage(issueId, 'comicPages', {+ status: 'edited',+ pages,+ });+ return { panel: panels[ni], page: pages[pi], issue: updatedIssue, stage, runId, changes, providerId };+}++/**+ * Generate N candidate image-gen prompts for a single comic panel WITHOUT+ * mutating the panel (issue #904). The user copies one or applies it to the+ * description via the existing refine/edit paths. Returns+ * { candidates, requested, pageIndex, panelIndex }.+ */+export async function generateComicPanelImagePrompts(issueId, pageIndex, panelIndex, { count, ...options } = {}) {+ const { pi, ni, variables } = await loadComicPanelPromptContext(issueId, pageIndex, panelIndex);+ const { candidates, requested } = await runImagePromptCandidates({+ count,+ templateName: 'pipeline-comic-panel-image-prompt',+ variables,+ options,+ source: 'pipeline-comic-panel-image-prompts',+ logTag: `Pipeline comic panel image-prompts — issue=${issueId.slice(0, 8)} p=${pi + 1} panel=${ni + 1}`,+ });+ return { candidates, requested, pageIndex: pi, panelIndex: ni };+}+diff --git a/server/services/pipeline/covers.js b/server/services/pipeline/covers.jsnew file mode 100644index 0000000000..32885ac588--- /dev/null+++ b/server/services/pipeline/covers.js@@ -0,0 +1,423 @@+/**+ * Pipeline — Comic + volume cover renders (#2531)+ *+ * Front/back covers for issues and volumes (seasons): prompt composers,+ * enqueue helpers, and the enqueue+persist entry points behind the route and+ * the CDO orchestrator. Extracted from the former monolithic `visualStages.js`;+ * shares style/prompt/enqueue plumbing via `./visualStageHelpers.js`.+ */++import { getSettings } from '../settings.js';+import { getSeries, updateSeasonOnSeries } from './series.js';+import { getUniverse } from '../universeBuilder.js';+import { ServerError } from '../../lib/errorHandler.js';+import { assertStageUnlocked, updateStageWithLatest } from './issues.js';+import { buildComicPagesOwner, buildSeasonCoverOwner, slotKeyForVariant } from './owners.js';+import {+ stackStyle, buildMastheadClause, buildAuthorClause, applyWorldStyle,+ loadBibleContext, resolveMode, resolveVariant, resolveProofInitImage,+ PROOF_AS_BASE_DEFAULT_STRENGTH, enqueueImageJob, buildRenderSlot,+} from './visualStageHelpers.js';++/**+ * Compose a comic-book front-cover prompt. The cover always renders the+ * series masthead (logo-style title) and the issue number tag in the+ * canonical top-of-cover position, plus the user's cover concept as the+ * scene content. Falls back to the issue title when the user has not+ * written a cover concept yet.+ *+ * Returns the full prompt string (with world style baked in when present).+ */+export function composeComicCoverPrompt({+ series, world, issue, coverScript = '', extraStyle = '',+}) {+ const issueNumber = Number.isFinite(issue?.number) ? Math.max(1, Math.floor(issue.number)) : 1;+ const issueTitle = (issue?.title || '').trim();+ const concept = (coverScript || '').trim();++ const styleStack = stackStyle(series, extraStyle);+ const styleClause = styleStack ? ` Art style: ${styleStack}.` : '';++ // Title-block requirements get spelled out explicitly because cover-art+ // typography is the part image-gen models get most wrong on the first+ // pass — without a hard cue the model often emits panels instead of+ // a cover, or skips the issue-number tag.+ const titleBlock = buildMastheadClause(series);+ const numberBlock = `Include a clearly legible issue-number tag reading "#${issueNumber}" in the top-left corner — small but readable.`;+ const titleLine = issueTitle+ ? ` Include the issue title "${issueTitle}" as a secondary banner below the masthead.`+ : '';+ const authorLine = buildAuthorClause(series);++ // Fall back to the issue title so a one-click render against a fresh cover+ // still produces something thematically on-target instead of a blank canvas.+ const sceneDescription = concept+ || (issueTitle ? `A single dramatic hero image evoking "${issueTitle}".` : 'A single dramatic hero image of the protagonist mid-action.');++ const layout = `A single full printable comic-book front cover for a serialized issue. ${titleBlock} ${numberBlock}${titleLine}${authorLine} The rest of the cover is one bold hero image (no panel borders, no multi-panel layout — this is the cover, not an interior page).${styleClause}`;+ const body = `Cover concept: ${sceneDescription}`;+ return applyWorldStyle(`${layout}\n\n${body}`, world, series);+}++/**+ * Compose a TV episode title-screen prompt. Reuses the same masthead/logo+ * cue the comic covers do — `series.titleLogo` describes the letterform ++ * finish, the series name is lettered verbatim, and `series.author` lands as+ * a small byline. The episode's number + title appear as secondary+ * typography so the screen identifies the specific episode, not just the+ * series. Returns the full prompt with world style baked in when present.+ *+ * Caller decides where to render the result — there is no auto-prepend into+ * the episode video pipeline today. Future title-card stages can call this+ * directly; for now it is the single source of truth for "what should the TV+ * title card for this episode look like."+ */+export function composeTitleScreenPrompt({+ series, world, issue, extraStyle = '',+}) {+ const seriesName = (series?.name || '').trim();+ const issueNumber = Number.isFinite(issue?.number) ? Math.max(1, Math.floor(issue.number)) : null;+ const issueTitle = (issue?.title || '').trim();++ const styleStack = stackStyle(series, extraStyle);+ const styleClause = styleStack ? ` Art style: ${styleStack}.` : '';++ const titleBlock = buildMastheadClause(series);+ const numberLine = issueNumber+ ? ` Render an "EPISODE ${issueNumber}" tag in restrained smaller typography, positioned above the masthead.`+ : '';+ const titleLine = issueTitle+ ? ` Render the episode title "${issueTitle}" as a secondary banner below the masthead in a complementary but lighter weight.`+ : '';+ const authorLine = buildAuthorClause(series);++ const layout = `A single TV episode title screen — a static title card meant to hold on-screen for a few seconds, NOT a story panel. Centered hero typography, generous negative space, cinematic 16:9 framing. ${titleBlock}${numberLine}${titleLine}${authorLine} Subtle background imagery only — atmospheric texture, signature color of the universe, no characters, no narrative scene.${styleClause}`;+ return applyWorldStyle(layout, world, series);+}++/**+ * 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, series);+}++/**+ * 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);+ assertStageUnlocked(issue, 'comicPages');+ 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 = 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+ * hands it to the image-gen queue. Caller records the returned jobId on+ * the appropriate variant slot (cover.proofImage / cover.finalImage)+ * based on `options.target` ('proof' | 'final', default 'proof').+ *+ * When `options.useProofAsBase` is set and target='final', resolves the+ * existing proof image to an absolute path under PATHS.images and passes+ * it through as `initImagePath` so the local i2i runner can preserve+ * the proof's composition while rendering at the larger size.+ *+ * Returns { jobId, mode, prompt, coverScript, variant, fromProof } so the+ * route can construct the slot record without re-reading the issue file.+ */+export async function enqueueComicCover(issueId, options = {}) {+ 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 };+}++/**+ * Enqueue + persist a comic-issue cover render (front or back) in ONE service+ * call — the shared entry point behind both the route handler and the CDO+ * orchestrator tool (#2220). The bare `enqueueComicCover*` only queues the job;+ * the filename hook attaches the completed render ONLY if the active cover slot+ * already carries the returned jobId, and that slot write used to live in the+ * route factory. Extracting it here means the orchestrator gets orchestrated+ * covers instead of silently dropping them.+ *+ * Persists the in-flight render slot onto+ * `stages.comicPages.{cover|backCover}.{proofImage|finalImage}` through+ * `updateStageWithLatest` (the series write tail) so it serializes against a+ * concurrent blur-save of the script field — the script-gate mirrors the route:+ * only overwrite `script` when the option is a string (absent preserves, empty+ * clears). `options` mirrors the route body (coverScript/backCoverScript,+ * width/height, target, useProofAsBase, mode, …).+ *+ * Returns { jobId, mode, prompt, variant, fromProof, coverScript|backCoverScript,+ * issue, stage } — the enqueue result plus the persisted issue + comicPages stage.+ */+async function renderComicCoverLike(issueId, target, options = {}) {+ const scriptField = target === 'cover' ? 'coverScript' : 'backCoverScript';+ const { script, ...rest } = await enqueueComicCoverLike(issueId, target, options);+ const slotKey = slotKeyForVariant(rest.variant);+ const slotRecord = buildRenderSlot({+ slotKey, jobId: rest.jobId, prompt: rest.prompt,+ width: options.width, height: options.height, fromProof: rest.fromProof,+ });+ const { issue, stage } = await updateStageWithLatest(issueId, 'comicPages', (current) => {+ const currentSlot = current?.[target] || {};+ const nextSlot = { ...currentSlot, [slotKey]: slotRecord };+ if (typeof options[scriptField] === 'string') nextSlot.script = options[scriptField];+ return { [target]: nextSlot };+ });+ return { ...rest, [scriptField]: script, issue, stage };+}++/**+ * Enqueue + persist a comic-issue FRONT cover render. Wraps `enqueueComicCover`+ * plus the slot persist the filename hook depends on. See `renderComicCoverLike`.+ */+export const renderComicCover = (issueId, options = {}) =>+ renderComicCoverLike(issueId, 'cover', options);++/**+ * Enqueue + persist a comic-issue BACK cover render. Lands on+ * `stages.comicPages.backCover`. See `renderComicCoverLike`.+ */+export const renderComicBackCover = (issueId, options = {}) =>+ renderComicCoverLike(issueId, 'backCover', options);++// ---- Volume (season) covers ---------------------------------------------++const loadSeasonContext = async (seriesId, seasonId) => {+ const seriesChain = (async () => {+ const series = await getSeries(seriesId);+ const world = await getUniverse(series.universeId).catch(() => 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 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 = buildMastheadClause(series);+ 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 authorLine = buildAuthorClause(series);++ 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}${authorLine} 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, series);+}++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, series);+}++/**+ * 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(record?.proofImage, `volume ${target}`)+ : null;+ const initImageStrength = fromProof+ ? (Number.isFinite(options.initImageStrength) ? options.initImageStrength : PROOF_AS_BASE_DEFAULT_STRENGTH)+ : undefined;+ const extraStyle = 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: 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, 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 };+}++/**+ * Enqueue + persist a volume (season) cover render (front or back) in ONE+ * service call — the shared entry point behind both the route handler and the+ * CDO orchestrator (#2220). Mirrors `renderComicCoverLike` but persists the+ * in-flight slot onto `series.seasons[].{cover|backCover}` through+ * `updateSeasonOnSeries` (the per-series write tail) so the season-cover+ * filename hook can attach the completed render.+ *+ * Returns { jobId, mode, prompt, variant, fromProof, coverScript|backCoverScript,+ * season, series } — the enqueue result plus the updated season + series.+ */+async function renderVolumeCoverLike(seriesId, seasonId, target, options = {}) {+ const scriptField = target === 'cover' ? 'coverScript' : 'backCoverScript';+ const { script, ...rest } = await enqueueVolumeCoverLike(seriesId, seasonId, target, options);+ const slotKey = slotKeyForVariant(rest.variant);+ const slotRecord = buildRenderSlot({+ slotKey, jobId: rest.jobId, prompt: rest.prompt,+ width: options.width, height: options.height, fromProof: rest.fromProof,+ });+ const series = await updateSeasonOnSeries(seriesId, seasonId, (current) => {+ const currentSlot = current?.[target] || {};+ const nextSlot = { ...currentSlot, [slotKey]: slotRecord };+ if (typeof options[scriptField] === 'string') nextSlot.script = options[scriptField];+ return { [target]: nextSlot };+ });+ const season = (series.seasons || []).find((s) => s.id === seasonId);+ return { ...rest, [scriptField]: script, season, series };+}++/**+ * Enqueue + persist a volume (season) FRONT cover render. See+ * `renderVolumeCoverLike`.+ */+export const renderVolumeCover = (seriesId, seasonId, options = {}) =>+ renderVolumeCoverLike(seriesId, seasonId, 'cover', options);++/**+ * Enqueue + persist a volume (season) BACK cover render. See+ * `renderVolumeCoverLike`.+ */+export const renderVolumeBackCover = (seriesId, seasonId, options = {}) =>+ renderVolumeCoverLike(seriesId, seasonId, 'backCover', options);+diff --git a/server/services/pipeline/issueCrud.js b/server/services/pipeline/issueCrud.jsnew file mode 100644index 0000000000..6a72eb87ef--- /dev/null+++ b/server/services/pipeline/issueCrud.js@@ -0,0 +1,501 @@+/**+ * Pipeline — Issues CRUD (#2531)+ *+ * Create / read / list / update / delete of Issue records, plus the+ * numbering + season-reassignment passes. Split out of the former monolithic+ * `issues.js`; shares the store facade, per-series write queue, sanitizers, and+ * renumberInline via `./issuesShared.js`. All mutations route through the+ * per-series write tail so concurrent writes to different issues in the same+ * series serialize against the shared series index.+ */++import { randomUUID } from 'crypto';+import { isStr, trimTo } from '../../lib/storyBible.js';+import { UNSCOPED_ANCHOR } from '../../lib/pipelineIssueOrder.js';+import { emitRecordUpdated } from '../sharing/recordEvents.js';+import * as seriesSvc from './series.js';+import {+ store, queueSeriesIssuesWrite, readState, readStateForSeries,+ saveIssueNow, saveIssuesNow, renumberInline, sanitizeIssue,+ snapshotRunHistory, stripRunHistoryFromIssue, makeErr, ISSUE_ID_RE,+ ERR_NOT_FOUND, ERR_VALIDATION, ERR_DUPLICATE, ERR_SEASON_LOCKED,+ TITLE_MAX, SERIES_ID_MAX, ISSUES_PER_RESPONSE_MAX,+} from './issuesShared.js';++export async function listIssues({+ seriesId = null,+ offset = 0,+ limit = ISSUES_PER_RESPONSE_MAX,+ paginated = false,+ withHistory = true,+ includeDeleted = false,+} = {}) {+ // Scope the read to one series when filtering by it — avoids loading every+ // issue in the install just to discard the rest (the `seriesId.localeCompare`+ // tiebreak below is a no-op within a single series).+ const { issues } = seriesId ? await readStateForSeries(seriesId) : await readState();+ const live = includeDeleted ? issues : issues.filter((i) => !i.deleted);+ const filtered = seriesId ? live.filter((i) => i.seriesId === seriesId) : live;+ const sorted = [...filtered].sort((a, b) => {+ if (a.seriesId !== b.seriesId) return a.seriesId.localeCompare(b.seriesId);+ return (a.number || 0) - (b.number || 0);+ });+ const project = withHistory ? (i) => i : stripRunHistoryFromIssue;+ const safeLimit = Math.min(Math.max(1, limit), ISSUES_PER_RESPONSE_MAX);+ const safeOffset = Math.max(0, offset);+ if (paginated) {+ return {+ items: sorted.slice(safeOffset, safeOffset + safeLimit).map(project),+ total: sorted.length,+ offset: safeOffset,+ limit: safeLimit,+ };+ }+ return sorted.slice(0, ISSUES_PER_RESPONSE_MAX).map(project);+}++/**+ * Every live (or, with `includeDeleted`, every) issue id — UNCAPPED.+ *+ * `listIssues` slices at `ISSUES_PER_RESPONSE_MAX` (1000) even unpaginated, so+ * it can't back a "does this id still exist?" membership check: an install with+ * >1000 issues would report ids beyond the cap as missing. Callers that need+ * the complete id set (e.g. the conflict-journal orphan-base-hash sweep, which+ * would otherwise prune a live issue's base hash and silently disable conflict+ * detection for it) use this. Returns ids only — no projection, no history.+ */+export async function listIssueIds({ includeDeleted = false } = {}) {+ const { issues } = await readState();+ const live = includeDeleted ? issues : issues.filter((i) => !i.deleted);+ return live.map((i) => i.id);+}++/**+ * Every live issue record — UNCAPPED, unsorted, unpaginated.+ *+ * Same rationale as `listIssueIds`: `listIssues` slices at+ * `ISSUES_PER_RESPONSE_MAX` (1000) even unpaginated, so it cannot back+ * whole-library scans. Callers that group/count issues across ALL series+ * (canon-usage tallies, the orphan-shell sweep's "does this series still have+ * issues?" gate) must use this — with `listIssues({})` an install holding+ * >1000 issues would silently miss the tail, and the orphan sweep could+ * delete a series that still has issues past the cap.+ *+ * @param {object} [options]+ * @param {boolean} [options.includeDeleted=false]+ * @param {boolean} [options.withHistory=true] - false strips per-stage run history+ */+export async function listAllIssues({ includeDeleted = false, withHistory = true } = {}) {+ const { issues } = await readState();+ const live = includeDeleted ? issues : issues.filter((i) => !i.deleted);+ return withHistory ? live : live.map(stripRunHistoryFromIssue);+}++/**+ * Every live issue record for one series — UNCAPPED, sorted by issue number.+ *+ * Same cap rationale as `listAllIssues`/`listIssueIds`: `listIssues({ seriesId })`+ * slices at `ISSUES_PER_RESPONSE_MAX` (1000), so a series holding >1000 issues+ * loses its tail. Per-series scans that MUST see every issue (the editorial+ * runner's storyboard-continuity and comic-lettering projections, #1469) use+ * this — with `listIssues` those checks would silently skip every storyboard+ * scene / comic page past the 1000th issue. Sorted by `number` to match the+ * ordering `listIssues` produces within a single series.+ *+ * @param {string} seriesId+ * @param {object} [options]+ * @param {boolean} [options.includeDeleted=false]+ * @param {boolean} [options.withHistory=true] - false strips per-stage run history+ */+export async function listIssuesForSeries(seriesId, { includeDeleted = false, withHistory = true } = {}) {+ const { issues } = await readStateForSeries(seriesId);+ const live = includeDeleted ? issues : issues.filter((i) => !i.deleted);+ const sorted = [...live].sort((a, b) => (a.number || 0) - (b.number || 0));+ return withHistory ? sorted : sorted.map(stripRunHistoryFromIssue);+}++/**+ * Recently-updated issues across all series. Sorts the FULL issue set by+ * `updatedAt` desc before applying `limit` — unlike `listIssues`, which+ * sorts by `seriesId/number` then caps at `ISSUES_PER_RESPONSE_MAX`. That+ * cap would silently miss the most-recent issues once the dataset grows+ * beyond 1000, so the sidebar's recent-issues view needs this dedicated+ * helper.+ */+export async function listRecentIssues({ limit = 10, withHistory = true, includeDeleted = false } = {}) {+ const { issues } = await readState();+ const live = includeDeleted ? issues : issues.filter((i) => !i.deleted);+ // Coerce in two passes so non-finite inputs ('abc', undefined) fall to+ // the default rather than letting JS's `0 || 10` short-circuit return+ // 10 for an explicit limit=0.+ const raw = Number(limit);+ const fallback = Number.isFinite(raw) ? Math.floor(raw) : 10;+ const clamped = Math.max(1, Math.min(50, fallback));+ const project = withHistory ? (i) => i : stripRunHistoryFromIssue;+ return [...live]+ .sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''))+ .slice(0, clamped)+ .map(project);+}++export async function getIssue(id, { includeDeleted = false } = {}) {+ const found = await store().loadOne(id);+ if (!found) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);+ if (found.deleted && !includeDeleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);+ return found;+}++export function createIssue(input = {}, { preloadedSeries = null } = {}) {+ const seriesId = trimTo(input.seriesId, SERIES_ID_MAX);+ if (!seriesId) return Promise.reject(makeErr('seriesId is required', ERR_VALIDATION));+ const title = trimTo(input.title, TITLE_MAX);+ if (!title) return Promise.reject(makeErr(`title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION));+ return queueSeriesIssuesWrite(seriesId, async () => {+ const state = await readState();+ const next = sanitizeIssue({+ id: `iss-${randomUUID()}`,+ seriesId,+ // Placeholder — `renumberInline` below derives the canonical number.+ number: 0,+ title,+ status: 'draft',+ // Phase 2: optional arc pointers passed by the season-episodes generator+ // (and any future caller wiring an issue to a season at create time).+ seasonId: 'seasonId' in input ? input.seasonId : null,+ arcPosition: 'arcPosition' in input ? input.arcPosition : null,+ arcRole: 'arcRole' in input ? input.arcRole : null,+ lengthProfile: 'lengthProfile' in input ? input.lengthProfile : undefined,+ pageTarget: 'pageTarget' in input ? input.pageTarget : null,+ minutesTarget: 'minutesTarget' in input ? input.minutesTarget : null,+ stages: input.stages || {},+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ ephemeral: input.ephemeral === true,+ });+ if (!next) throw makeErr('Invalid issue payload', ERR_VALIDATION);+ state.issues.push(next);+ await renumberInline(state, seriesId, next.seasonId || UNSCOPED_ANCHOR, preloadedSeries);+ await saveIssuesNow(state.issues.filter((i) => i.seriesId === seriesId));+ // New issue = series-level change for any active share subscription.+ emitRecordUpdated('series', next.seriesId);+ return next;+ });+}++export function recomputeIssueNumbersForSeries(seriesId, fromSeasonId = null) {+ return queueSeriesIssuesWrite(seriesId, async () => {+ const state = await readState();+ const changed = await renumberInline(state, seriesId, fromSeasonId);+ if (!changed) return { changed: false };+ await saveIssuesNow(state.issues.filter((i) => i.seriesId === seriesId));+ emitRecordUpdated('series', seriesId);+ return { changed: true };+ });+}++/**+ * Reassign every issue under `(seriesId, fromSeasonId)` to `toSeasonId` in a+ * single collection load → in-memory mutate → per-record save pass.+ * Used by `deleteSeason` (and any future bulk season-move flow) to collapse+ * N per-issue write cycles into one — the legacy N+1 pattern was+ * `for (iss of children) await updateIssue(iss.id, { seasonId: toSeasonId }, { skipRenumber: true })`+ * which paid N read/write round-trips and N debounced re-exports even with+ * `withReexportSuppressed`.+ *+ * Returns `{ reassigned, fromSeasonId, toSeasonId }`. `toSeasonId` may be+ * `null` (un-grouped). A re-export of the parent series is emitted once, after+ * the renumber pass — callers under `withReexportSuppressed` get exactly one+ * `series:updated` event regardless of the issue count.+ */+export function bulkReassignSeason(seriesId, fromSeasonId, toSeasonId = null, { _preloadedSeries = null } = {}) {+ return queueSeriesIssuesWrite(seriesId, async () => {+ // Honor per-season locks — refuse to move issues OUT of or INTO a locked+ // volume. Series lives in a different write queue, so this is best-effort+ // single-user gating, not strict serialization (fine per CLAUDE.md).+ // Callers that already hold a fresh series (e.g. `deleteSeason` reads it+ // for the reassign-target validation) can pass `_preloadedSeries` to skip+ // the duplicate read.+ if (fromSeasonId || toSeasonId) {+ const series = _preloadedSeries || await seriesSvc.getSeries(seriesId);+ const seasons = Array.isArray(series.seasons) ? series.seasons : [];+ const findLocked = (id) => (id ? seasons.find((s) => s.id === id && s.locked === true) : null);+ const blocker = findLocked(fromSeasonId) || findLocked(toSeasonId);+ if (blocker) {+ throw makeErr(+ `Season "${blocker.title || blocker.number}" is locked — unlock it before reassigning issues`,+ ERR_SEASON_LOCKED,+ );+ }+ }+ const state = await readState();+ let reassigned = 0;+ const now = new Date().toISOString();+ for (let i = 0; i < state.issues.length; i += 1) {+ const iss = state.issues[i];+ if (iss.seriesId !== seriesId) continue;+ // Skip tombstones — moving a soft-deleted issue would bump its+ // `updatedAt`, which then loses LWW races with the originator's+ // tombstone and can resurrect the record on every peer.+ if (iss.deleted) continue;+ if ((iss.seasonId || null) !== (fromSeasonId || null)) continue;+ // Re-sanitize through the same pipeline updateIssue uses so the+ // in-memory rewrite gets the same shape guarantees as a route PATCH.+ const merged = sanitizeIssue({+ ...iss,+ seasonId: toSeasonId,+ updatedAt: now,+ });+ if (!merged) continue;+ state.issues[i] = merged;+ reassigned += 1;+ }+ if (reassigned === 0) return { reassigned: 0, fromSeasonId, toSeasonId };+ // One renumber pass after the bulk move — the source AND destination+ // volume both reshuffled, so use the series-wide form (fromSeasonId=null).+ await renumberInline(state, seriesId, null);+ await saveIssuesNow(state.issues.filter((i) => i.seriesId === seriesId));+ emitRecordUpdated('series', seriesId);+ return { reassigned, fromSeasonId, toSeasonId };+ });+}++/**+ * Reassign every live issue from `fromSeriesId` to `toSeriesId` — used by the+ * series-merge engine (recordMerge.js) so a duplicate series' issues survive+ * the merge instead of being orphaned under the tombstoned loser.+ *+ * Issue→season grouping is preserved across the move via `seasonIdMap` — a+ * `{ loserSeasonId: survivorSeasonId }` map the caller (`mergeSeries`) builds by+ * pairing the loser's seasons to the survivor's by `number`. An issue whose+ * `seasonId` resolves through the map lands in the matching survivor season; one+ * with no `seasonId`, or a `seasonId` the map doesn't cover (a stale ref, or a+ * loser season that didn't survive the union), lands UN-GROUPED (`seasonId:+ * null`). A single renumber pass on the survivor sequences the combined set.+ * Returns `{ reassigned }`.+ *+ * Serialized on the SURVIVOR's issues queue so the renumber can't race a+ * concurrent survivor edit. Tombstoned issues are skipped (moving them would+ * bump updatedAt and lose the originator's delete LWW race).+ */+export function reassignIssuesToSeries(fromSeriesId, toSeriesId, { seasonIdMap = {} } = {}) {+ if (!isStr(fromSeriesId) || !isStr(toSeriesId) || fromSeriesId === toSeriesId) {+ return Promise.reject(makeErr('reassignIssuesToSeries: fromSeriesId and toSeriesId must differ', ERR_VALIDATION));+ }+ // This reads/mutates issues belonging to BOTH series (it moves source issues+ // and renumbers the destination), so serialize on both per-series queues, not+ // just the destination — otherwise a concurrent edit/renumber on the source+ // (e.g. a peer-sync merge landing on the loser mid-merge) could interleave and+ // be lost. Acquire in sorted order so a future two-series caller can't deadlock.+ const [first, second] = [fromSeriesId, toSeriesId].sort();+ const body = async () => {+ const state = await readState();+ const now = new Date().toISOString();+ const moved = [];+ for (let i = 0; i < state.issues.length; i += 1) {+ const iss = state.issues[i];+ if (iss.seriesId !== fromSeriesId || iss.deleted) continue;+ // Map the issue's loser season to the survivor's same-number season so the+ // grouping survives; fall back to un-grouped when there's no mapping.+ const seasonId = (iss.seasonId && seasonIdMap[iss.seasonId]) || null;+ const merged = sanitizeIssue({ ...iss, seriesId: toSeriesId, seasonId, updatedAt: now });+ if (!merged) continue;+ state.issues[i] = merged;+ moved.push(merged);+ }+ if (moved.length === 0) return { reassigned: 0 };+ await renumberInline(state, toSeriesId, null);+ // Persist every issue now tagged to the survivor (the moved ones + any the+ // survivor already had, whose numbers may have shifted in the renumber).+ await saveIssuesNow(state.issues.filter((i) => i.seriesId === toSeriesId));+ emitRecordUpdated('series', toSeriesId);+ emitRecordUpdated('series', fromSeriesId);+ return { reassigned: moved.length };+ };+ return queueSeriesIssuesWrite(first, () => queueSeriesIssuesWrite(second, body));+}++/**+ * Insert an issue with a caller-supplied id (used by the share-bucket importer+ * so re-imports of the same issue LWW-merge onto the same local row).+ * Throws ERR_DUPLICATE / ERR_VALIDATION on contract violations.+ */+export function insertIssueWithId(input = {}) {+ if (!isStr(input.id) || !ISSUE_ID_RE.test(input.id)) {+ return Promise.reject(makeErr(`insertIssueWithId: invalid id "${input.id}" (expected iss-<uuid>)`, ERR_VALIDATION));+ }+ const seriesId = trimTo(input.seriesId, SERIES_ID_MAX);+ if (!seriesId) return Promise.reject(makeErr('seriesId is required', ERR_VALIDATION));+ const title = trimTo(input.title, TITLE_MAX);+ if (!title) return Promise.reject(makeErr(`title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION));+ return queueSeriesIssuesWrite(seriesId, async () => {+ const state = await readState();+ // Tombstone-overwrite: same contract as universeBuilder.insertUniverseWithId.+ const existingIdx = state.issues.findIndex((i) => i.id === input.id);+ if (existingIdx >= 0 && !state.issues[existingIdx].deleted) {+ throw makeErr(`Issue id already exists: ${input.id}`, ERR_DUPLICATE);+ }+ const wasResurrection = existingIdx >= 0;+ const next = sanitizeIssue({ ...input, seriesId, title });+ if (!next) throw makeErr('Invalid issue payload', ERR_VALIDATION);+ if (wasResurrection) {+ console.warn(`♻️ insertIssueWithId: overwriting tombstone for ${input.id}`);+ state.issues[existingIdx] = next;+ } else {+ state.issues.push(next);+ }+ // Imported `number` is a starting hint — local canonical numbering still+ // comes from (volume order, arcPosition) of the local state.+ await renumberInline(state, seriesId, next.seasonId || UNSCOPED_ANCHOR);+ await saveIssuesNow(state.issues.filter((i) => i.seriesId === seriesId));+ // Mirror createIssue's federation side-effect on tombstone-overwrite:+ // issues ride series-level events, so notify peers via the parent series.+ if (wasResurrection) emitRecordUpdated('series', next.seriesId);+ return next;+ });+}++function mergeIssuePatch(cur, patch = {}) {+ // Per-stage merge: a stage patch carries only the fields the caller is+ // changing (e.g. `{ genConfig }` or `{ cover }`). Without this, the top-level+ // spread would replace the entire stage object and silently drop sibling+ // fields like `scenes` / `pages` / `genConfig`. Sanitization then defaults+ // those back to empty arrays/null, erasing work the user (or LLM) just did.+ // Callers that need stage-level changes without touching issue-level fields+ // should use `updateStage`, which does a shallow merge of the patch over the+ // existing stage (`{ ...cur.stages[stageId], ...patch }`) before sanitizing.+ //+ // `cover` and `genConfig` are treated as deep-merge sub-objects: a partial+ // `{ cover: { script } }` patch from a textarea-blur save must not wipe the+ // sibling `imageJobId` / `prompt` that a parallel "Render cover" mutation+ // just persisted. Passing `null` explicitly still clears the sub-object.+ const NESTED_DEEP_MERGE_KEYS = ['cover', 'genConfig'];+ let mergedStages = cur.stages;+ if ('stages' in patch && patch.stages && typeof patch.stages === 'object') {+ mergedStages = { ...cur.stages };+ for (const [stageId, stagePatch] of Object.entries(patch.stages)) {+ const prev = cur.stages?.[stageId];+ if (prev && stagePatch && typeof prev === 'object' && typeof stagePatch === 'object') {+ const merged = { ...prev, ...stagePatch };+ merged.runHistory = snapshotRunHistory(prev, stagePatch, stageId);+ for (const key of NESTED_DEEP_MERGE_KEYS) {+ if (key in stagePatch+ && stagePatch[key] && typeof stagePatch[key] === 'object'+ && prev[key] && typeof prev[key] === 'object') {+ merged[key] = { ...prev[key], ...stagePatch[key] };+ }+ }+ if ('status' in stagePatch && stagePatch.status !== 'error'+ && stagePatch.status !== 'generating'+ && !('errorMessage' in stagePatch)) {+ merged.errorMessage = '';+ }+ mergedStages[stageId] = merged;+ } else {+ mergedStages[stageId] = stagePatch;+ }+ }+ }++ const merged = sanitizeIssue({+ ...cur,+ ...('title' in patch ? { title: patch.title } : {}),+ ...('number' in patch ? { number: patch.number } : {}),+ ...('status' in patch ? { status: patch.status } : {}),+ ...('seasonId' in patch ? { seasonId: patch.seasonId } : {}),+ ...('arcPosition' in patch ? { arcPosition: patch.arcPosition } : {}),+ ...('arcRole' in patch ? { arcRole: patch.arcRole } : {}),+ ...('lengthProfile' in patch ? { lengthProfile: patch.lengthProfile } : {}),+ ...('pageTarget' in patch ? { pageTarget: patch.pageTarget } : {}),+ ...('minutesTarget' in patch ? { minutesTarget: patch.minutesTarget } : {}),+ ...('origin' in patch ? { origin: patch.origin } : {}),+ // Local-only "don't sync" marker. Issues piggyback on their parent+ // series' subscription, so an ephemeral issue is dropped from the+ // series push payload via sanitizeRecordForWire returning null.+ ...('ephemeral' in patch ? { ephemeral: patch.ephemeral } : {}),+ stages: mergedStages,+ updatedAt: new Date().toISOString(),+ });+ if (!merged) throw makeErr('Invalid issue payload', ERR_VALIDATION);+ return merged;+}++export function updateIssue(id, patch = {}, { skipRenumber = false } = {}) {+ const needsRenumber = !skipRenumber && ('seasonId' in patch || 'arcPosition' in patch);+ if (!needsRenumber) {+ // Route through the SERIES tail (see updateStageWithLatest) so a plain+ // field update can't race a concurrent series-wide renumber rewriting this+ // issue. seriesId is immutable, so read it outside the lock to pick the+ // queue, then re-read the issue inside.+ return getIssue(id, { includeDeleted: true }).then((existing) =>+ queueSeriesIssuesWrite(existing.seriesId, async () => {+ const cur = await store().loadOne(id);+ if (!cur) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);+ if (cur.deleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);+ const merged = mergeIssuePatch(cur, patch);+ await saveIssueNow(merged);+ emitRecordUpdated('series', merged.seriesId);+ return merged;+ }),+ );+ }++ return getIssue(id, { includeDeleted: true }).then((existing) =>+ queueSeriesIssuesWrite(existing.seriesId, async () => {+ const state = await readState();+ const idx = state.issues.findIndex((i) => i.id === id);+ if (idx < 0) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);+ const cur = state.issues[idx];+ if (cur.deleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);+ const merged = mergeIssuePatch(cur, patch);+ state.issues[idx] = merged;+ // A seasonId move affects both source and destination volumes, so full+ // renumber. An arcPosition change only reorders within the current volume.+ if ('seasonId' in patch && cur.seasonId !== merged.seasonId) {+ await renumberInline(state, merged.seriesId, null);+ } else if ('arcPosition' in patch && cur.arcPosition !== merged.arcPosition) {+ await renumberInline(state, merged.seriesId, merged.seasonId || UNSCOPED_ANCHOR);+ }+ await saveIssuesNow(state.issues.filter((i) => i.seriesId === merged.seriesId));+ // Issues are exported as part of their parent series — re-export the+ // series so any active subscription picks up the issue change.+ emitRecordUpdated('series', merged.seriesId);+ return merged;+ })+ );+}++export function deleteIssue(id) {+ // Soft-delete — same tombstone-in-record pattern as universes/series. The+ // record stays on disk with `deleted: true` so the next sync propagates the+ // delete to peers; the orchestrator's GC sweep prunes it once all peers ack.+ // `renumberInline` filters tombstones, so surviving issues stay contiguous.+ return getIssue(id, { includeDeleted: true }).then((existing) =>+ queueSeriesIssuesWrite(existing.seriesId, async () => {+ const state = await readState();+ const idx = state.issues.findIndex((i) => i.id === id);+ if (idx < 0) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);+ const cur = state.issues[idx];+ if (cur.deleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);+ const seriesId = cur.seriesId;+ const now = new Date().toISOString();+ state.issues[idx] = { ...cur, deleted: true, deletedAt: now, updatedAt: now };+ await renumberInline(state, seriesId, cur.seasonId || UNSCOPED_ANCHOR);+ await saveIssuesNow(state.issues.filter((i) => i.seriesId === seriesId));+ // Series export bundles every issue, so a deletion is an update on the+ // parent series for any active share-bucket subscription.+ emitRecordUpdated('series', seriesId);+ return { id, seriesId };+ }).then(async (result) => {+ // The deleted issue may have owned the series' list thumbnail+ // (`series.coverImage`). Recompute outside the queue (it reads fresh+ // post-delete state) so the Pipeline list falls back to the next eligible+ // cover instead of pointing at a tombstone. Dynamic import dodges the+ // static cycle (seriesCoverImage → issues). Best-effort — a cosmetic+ // thumbnail must never fail the delete.+ const { refreshSeriesCoverImage } = await import('./seriesCoverImage.js');+ await refreshSeriesCoverImage(result.seriesId).catch(() => {});+ return { id: result.id };+ })+ );+}+diff --git a/server/services/pipeline/issueStages.js b/server/services/pipeline/issueStages.jsnew file mode 100644index 0000000000..9bd26edaf4--- /dev/null+++ b/server/services/pipeline/issueStages.js@@ -0,0 +1,185 @@+/**+ * Pipeline — Issue stage merge / history / restore (#2531)+ *+ * Per-stage writes (updateStage / updateStageWithLatest / updateStagesWithLatest)+ * plus run-history restore. Split out of the former monolithic `issues.js`.+ * Stage writes route through the SAME per-series write tail as CRUD (see+ * `./issuesShared.js`) so a stage save can't interleave with a series-wide+ * renumber/bulk write that rewrites the same issue — one mutex per series.+ */++import { isPlainObject } from '../../lib/objects.js';+import { isStr } from '../../lib/storyBible.js';+import { emitRecordUpdated } from '../sharing/recordEvents.js';+import { getIssue } from './issueCrud.js';+import {+ store, queueSeriesIssuesWrite, readState, saveIssueNow, saveIssuesNow,+ sanitizeIssue, sanitizeTextStage, sanitizeVisualStage, sanitizeAudioStage,+ snapshotRunHistory, makeErr,+ ERR_NOT_FOUND, ERR_VALIDATION,+ STAGE_IDS, TEXT_STAGE_IDS, VISUAL_STAGE_IDS, AUDIO_STAGE_IDS,+} from './issuesShared.js';++/**+ * Partial update to a single stage on an issue. Use this from generators so+ * a stage write doesn't have to load the full issue, mutate, and re-validate.+ * Patch keys: status, input, output, lastRunId, errorMessage, and (for+ * visual stages) pages/scenes/cdProjectId/videoPath.+ *+ * When the patch depends on the current stage value (e.g. cover preservation),+ * use `updateStageWithLatest` instead so the decision is made against the+ * freshest persisted record inside the serialized write region.+ */+export function updateStage(issueId, stageId, patch = {}) {+ return updateStageWithLatest(issueId, stageId, () => patch);+}++function mergeStagePatch(currentStage, stageId, patch, { snapshotPrior = false } = {}) {+ const isVisual = VISUAL_STAGE_IDS.includes(stageId);+ const isAudio = AUDIO_STAGE_IDS.includes(stageId);+ const nextRunHistory = snapshotRunHistory(currentStage, patch, stageId, { force: snapshotPrior });+ const merged = {+ ...currentStage,+ ...patch,+ runHistory: nextRunHistory,+ updatedAt: new Date().toISOString(),+ };+ if (isVisual) return sanitizeVisualStage(merged, stageId);+ if (isAudio) return sanitizeAudioStage(merged);+ return sanitizeTextStage(merged);+}++export function updateStagesWithLatest(seriesId, updates = [], { snapshotPrior = false } = {}) {+ if (!isStr(seriesId) || !seriesId) {+ return Promise.reject(makeErr('seriesId is required', ERR_VALIDATION));+ }+ if (!Array.isArray(updates) || updates.length === 0) {+ return Promise.resolve([]);+ }+ for (const { stageId } of updates) {+ if (!STAGE_IDS.includes(stageId)) {+ return Promise.reject(makeErr(`Unknown stage: ${stageId}`, ERR_VALIDATION));+ }+ }++ return queueSeriesIssuesWrite(seriesId, async () => {+ const state = await readState();+ const results = [];+ let changed = false;+ for (const update of updates) {+ const idx = state.issues.findIndex((i) => i.id === update.issueId);+ if (idx < 0) throw makeErr(`Issue not found: ${update.issueId}`, ERR_NOT_FOUND);+ const cur = state.issues[idx];+ if (cur.deleted || cur.seriesId !== seriesId) throw makeErr(`Issue not found: ${update.issueId}`, ERR_NOT_FOUND);+ const currentStage = cur.stages[update.stageId];+ const patch = update.computeFn(currentStage);+ if (isPlainObject(patch) && Object.keys(patch).length === 0) {+ results.push({ issue: cur, stage: currentStage });+ continue;+ }+ const nextStage = mergeStagePatch(currentStage, update.stageId, patch, { snapshotPrior });+ const mergedIssue = sanitizeIssue({+ ...cur,+ stages: { ...cur.stages, [update.stageId]: nextStage },+ updatedAt: new Date().toISOString(),+ });+ if (!mergedIssue) throw makeErr('Invalid issue payload', ERR_VALIDATION);+ state.issues[idx] = mergedIssue;+ results.push({ issue: mergedIssue, stage: mergedIssue.stages[update.stageId] });+ changed = true;+ }+ if (changed) {+ await saveIssuesNow(state.issues.filter((i) => i.seriesId === seriesId));+ emitRecordUpdated('series', seriesId);+ }+ return results;+ });+}++/**+ * Restore a prior `runHistory` snapshot as the active stage state. Looks up the+ * snapshot by `runId` against the freshest persisted record (so a concurrent+ * generate can't make the chosen snapshot disappear out from under the call).+ * The previous active state is itself snapshotted into runHistory by the normal+ * lastRunId-changed trigger in `updateStageWithLatest`, so restore is just+ * another version event — there's no special "rollback" semantics.+ *+ * Resolves with `{ issue, stage }`. Rejects with ERR_VALIDATION when the runId+ * isn't present in the current runHistory.+ */+export function restoreStageFromHistory(issueId, stageId, runId) {+ if (!TEXT_STAGE_IDS.includes(stageId)) {+ return Promise.reject(makeErr(`Stage "${stageId}" does not support history restore`, ERR_VALIDATION));+ }+ if (!isStr(runId) || !runId) {+ return Promise.reject(makeErr('runId is required', ERR_VALIDATION));+ }+ return updateStageWithLatest(issueId, stageId, (cur) => {+ const snapshot = (cur?.runHistory || []).find((entry) => entry.runId === runId);+ if (!snapshot) throw makeErr(`Snapshot not found in stage history: ${runId}`, ERR_VALIDATION);+ return {+ status: 'edited',+ input: snapshot.input || '',+ output: snapshot.output || '',+ lastRunId: snapshot.runId,+ errorMessage: '',+ };+ });+}++/**+ * Like `updateStage`, but the patch is computed from the *latest* persisted+ * stage inside the serialized write region. Use this when the patch value+ * depends on the current stage state (e.g. cover preservation) so a concurrent+ * write that lands between the outer `getIssue` read and this call is not+ * silently overwritten.+ *+ * `computeFn(currentStage) → patch` — called with the freshest stage record+ * inside the queue; its return value is shallow-merged over the stage exactly+ * as `updateStage` merges a static patch.+ */+export function updateStageWithLatest(issueId, stageId, computeFn, { snapshotPrior = false } = {}) {+ if (!STAGE_IDS.includes(stageId)) {+ // Validate before queueing so the caller gets an immediate rejection+ // rather than waiting in line for an error it already knows about.+ return Promise.reject(makeErr(`Unknown stage: ${stageId}`, ERR_VALIDATION));+ }+ // Serialize on the SERIES tail (not the per-id queue) so a stage save can't+ // interleave with a series-wide renumber/bulk write that rewrites this same+ // issue — both share one mutex per series. The per-record split (migrations+ // 035/036) otherwise left renumbers on the series queue and stage saves on+ // the per-id queue (two independent mutexes over the same shared resource);+ // see CLAUDE.md "single tail per shared file". seriesId is immutable, so read+ // it outside the lock to pick the queue, then re-read the issue INSIDE the+ // lock for the freshest stage.+ const work = async () => {+ const cur = await store().loadOne(issueId);+ if (!cur) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);+ if (cur.deleted) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);+ const currentStage = cur.stages[stageId];+ const patch = computeFn(currentStage);+ // Empty-patch fast path: a computeFn that returns `{}` is a "decided not+ // to write" signal (e.g. stale media-job completion against a re-rendered+ // page). Skip the disk write + emitRecordUpdated so it doesn't trigger+ // a re-export storm in share subscriptions for late no-op events.+ if (isPlainObject(patch) && Object.keys(patch).length === 0) {+ return { issue: cur, stage: currentStage };+ }+ // Snapshot the prior `{ runId, input, output }` into runHistory when this+ // patch carries a fresh lastRunId (i.e. a generate just replaced prior+ // content). Computed BEFORE the spread so it reads pre-merge state.+ const next = mergeStagePatch(currentStage, stageId, patch, { snapshotPrior });+ const mergedIssue = sanitizeIssue({+ ...cur,+ stages: { ...cur.stages, [stageId]: next },+ updatedAt: new Date().toISOString(),+ });+ await saveIssueNow(mergedIssue);+ emitRecordUpdated('series', mergedIssue.seriesId);+ return { issue: mergedIssue, stage: mergedIssue.stages[stageId] };+ };+ return getIssue(issueId, { includeDeleted: true }).then((existing) =>+ queueSeriesIssuesWrite(existing.seriesId, work),+ );+}+diff --git a/server/services/pipeline/issueSync.js b/server/services/pipeline/issueSync.jsnew file mode 100644index 0000000000..64bf98c208--- /dev/null+++ b/server/services/pipeline/issueSync.js@@ -0,0 +1,180 @@+/**+ * Pipeline — Issue peer-sync merge + tombstone GC (#2531)+ *+ * mergeIssuesFromSync (LWW merge of a remote peer's issues) and+ * pruneTombstonedIssues (tombstone GC). Split out of the former monolithic+ * `issues.js`. Both serialize on the store's single type-index write tail+ * (`store().queueTypeIndexWrite`) for one consistent merge/prune snapshot.+ */++import { isStr } from '../../lib/storyBible.js';+import { emitRecordUpdated } from '../sharing/recordEvents.js';+import * as seriesSvc from './series.js';+import {+ maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord,+ flushBaseHashes, deleteSyncBaseHash,+} from '../../lib/conflictJournal.js';+import { store, readState, saveIssuesNow, renumberInline, sanitizeIssue } from './issuesShared.js';++/**+ * Sync-orchestrator entry point. Merges a remote peer's issues array into+ * local state through the collection store's type-index queue for one+ * consistent merge snapshot. Each incoming record passes through+ * `sanitizeIssue` for shape enforcement (stage statuses, trimmed fields,+ * valid id format). LWW by `updatedAt`; returns `{ applied, count }` where+ * `count` is the number of issues actually changed/added.+ */+export async function mergeIssuesFromSync(remoteIssues, { source = { via: 'sync', peerId: null } } = {}) {+ if (!Array.isArray(remoteIssues)) return { applied: false, count: 0 };+ // Series IDs whose issue set saw at least one delete-transition — drives a+ // post-write renumber so the receiver's issue numbering catches up with the+ // sender's (otherwise a synced tombstone would leave a gap).+ //+ // Edit-only merges (no delete-transitions) do NOT emit `recordUpdated` for+ // the parent series — see `mergeUniversesFromSync` for the rationale (the+ // Stage 2 per-record peer-sync push owns sync-time edit emits). Delete-+ // transitions DO emit per series so subscribers know to drop the issue.+ const seriesNeedingRenumber = new Set();+ // Build the set of locally-ephemeral series ids BEFORE the queue. The+ // per-record push pipeline (applyIncomingPush) already gates the bundled+ // issues batch by parent-ephemeral, but the snapshot pipeline path+ // (applyPipelineRemote → mergeIssuesFromSync) bypasses that check. Without+ // this filter, a peer with `pipeline` sync enabled can create/update/+ // tombstone issues under a locally-private series and overwrite the+ // user's private fork.+ const ephemeralSeriesIds = new Set(+ (await seriesSvc.listSeries({ includeDeleted: true }).catch(() => []))+ .filter((s) => s?.ephemeral === true)+ .map((s) => s.id),+ );+ return store().queueTypeIndexWrite(async () => {+ const state = await readState();+ const localById = new Map(state.issues.map((i) => [i.id, i]));+ let changed = 0;+ // Track only the issue IDs that were inserted or overwritten so we persist+ // the changed subset rather than every issue in the store (avoids unbounded+ // Promise.all / EMFILE on large catalogs).+ const changedIds = new Set();+ for (const remote of remoteIssues) {+ if (!remote || typeof remote !== 'object' || !isStr(remote.id)) continue;+ // Drop issues whose parent series is locally ephemeral, BEFORE any+ // mutation. This covers create/update/tombstone uniformly — the+ // sanitized.seriesId may be either the existing local series or a+ // remote-only target; reject either way.+ if (ephemeralSeriesIds.has(remote.seriesId)) continue;+ const sanitized = sanitizeIssue(remote);+ if (!sanitized) continue;+ // Strip inbound `ephemeral` — see mergeUniversesFromSync.+ if ('ephemeral' in sanitized) delete sanitized.ephemeral;+ const local = localById.get(sanitized.id);+ // Belt-and-suspenders: if the existing local issue belongs to an+ // ephemeral series, refuse the merge even though the inbound+ // sanitized.seriesId might point elsewhere (a peer could ship an+ // issue id whose local copy is under a private series and try to+ // move it).+ if (local && ephemeralSeriesIds.has(local.seriesId)) continue;+ if (!local) {+ // No local counterpart — accept the record but don't trigger a+ // renumber pass. A tombstone for an issue we never had has nothing+ // to compact; firing `emitRecordUpdated('series', …)` for a series+ // we may not even own would spuriously re-export.+ localById.set(sanitized.id, sanitized);+ // Seed the conflict-journal base hash so a FUTURE divergence on this+ // issue is detected. Issues are pushed under their parent series'+ // subscription, so peerSync never seeds an `issue`-keyed base hash —+ // this merge path (and the importer) own it.+ await setSyncBaseHash('issue', sanitized.id, contentHashForRecord('issue', sanitized));+ changedIds.add(sanitized.id);+ changed++;+ } else if (local.ephemeral === true) {+ // Local-ephemeral issues are immune to inbound merges. See+ // mergeUniversesFromSync for the contract.+ continue;+ } else {+ const localTs = local.updatedAt || '';+ const remoteTs = sanitized.updatedAt || '';+ if (remoteTs > localTs) {+ // Non-blocking conflict journal — archive the losing local issue on+ // a true 3-way divergence; always advances the base hash. Never+ // throws into the merge (convergence wins).+ await maybeJournalBeforeOverwrite({ kind: 'issue', id: sanitized.id, local, remote: sanitized, source });+ localById.set(sanitized.id, sanitized);+ changedIds.add(sanitized.id);+ // Renumber on EITHER direction of the transition: a delete leaves+ // a gap, a resurrection (deleted→live) reintroduces a previously-+ // compacted number and can collide with live siblings until some+ // unrelated edit triggers a renumber. Cover both here.+ if (sanitized.deleted !== local.deleted) {+ seriesNeedingRenumber.add(sanitized.seriesId);+ // A resurrection may move from the OLD seriesId to a different+ // one in the inbound record (rare, but possible) — renumber both.+ if (local.seriesId && local.seriesId !== sanitized.seriesId) {+ seriesNeedingRenumber.add(local.seriesId);+ }+ }+ changed++;+ }+ }+ }+ if (changed === 0) return { applied: false, count: 0 };+ state.issues = Array.from(localById.values());+ // Compact issue numbers for each affected series — the merge may have+ // tombstoned (gap) or resurrected (collision) an issue. renumberInline+ // skips tombstones, so the resulting numbering is always contiguous+ // across live issues. Single renumber per series, all inside the queue.+ // renumberInline updates state.issues in-place; collect the renumbered+ // issue ids so they are also persisted.+ for (const seriesId of seriesNeedingRenumber) {+ const before = new Map(state.issues.map((i) => [i.id, i.number]));+ await renumberInline(state, seriesId, null);+ for (const i of state.issues) {+ if (i.seriesId === seriesId && i.number !== before.get(i.id)) {+ changedIds.add(i.id);+ }+ }+ }+ // Persist only the issues that were actually changed/renumbered, not the+ // entire catalog — avoids EMFILE + write-amplification on large stores.+ const changedIssues = state.issues.filter((i) => changedIds.has(i.id));+ await saveIssuesNow(changedIssues);+ // Re-emit a series-updated for each touched series so any active share+ // subscription re-exports the post-merge issue set.+ for (const seriesId of seriesNeedingRenumber) {+ emitRecordUpdated('series', seriesId);+ }+ // Persist the batched conflict-journal base-hash updates (seeds on insert,+ // advances on overwrite) accumulated in the loop above.+ await flushBaseHashes();+ return { applied: true, count: changed };+ });+}++/**+ * Garbage-collect issue tombstones older than `beforeMs`. See+ * `pruneTombstonedUniverses` for the contract — pure mechanical prune; the+ * caller owns the policy. Tombstones with unparseable `deletedAt` are kept.+ *+ * Issue tombstones ride series pushes (the receiver bundles child issues+ * with each series push) so the relevant ack horizon is "peers subscribed+ * to the parent series." The caller resolves that.+ */+export async function pruneTombstonedIssues(beforeMs) {+ if (!Number.isFinite(beforeMs)) return { pruned: 0 };+ return store().queueTypeIndexWrite(async () => {+ const { issues } = await readState();+ const prunable = issues.filter((i) => {+ if (!i?.deleted) return false;+ const t = Date.parse(i.deletedAt || '');+ if (!Number.isFinite(t)) return false;+ return t < beforeMs;+ });+ await Promise.all(prunable.map((i) => store().deleteOne(i.id)));+ // Evict each pruned issue's conflict-journal base hash. Issues seed an+ // `issue:<id>` base hash when their parent series is pushed (peerSync's+ // pushRecordToPeer), but no eviction existed — so a pruned issue's key+ // would linger in sync_base_hashes.json forever. Mirrors the universe /+ // series / collection prune paths.+ await Promise.all(prunable.map((i) => deleteSyncBaseHash('issue', i.id)));+ return { pruned: prunable.length };+ });+}diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex 2f1a96b7e3..7b5392ffcc 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -1,1469 +1,19 @@/**- * Pipeline — Issues Service+ * Pipeline — Issues Service (barrel, #2531)*- * An Issue (or Episode — same record, two formats) is a child of a Series and- * carries the full per-stage state of one production pipeline run:+ * The former ~1470-line monolith was split along CRUD / stage / sync seams:*- * stages.idea — beat sheet from the rough human seed- * stages.prose — short-story draft- * stages.comicScript — page/panel script (one of two parallel script stages)- * stages.teleplay — scene-by-scene teleplay (the other parallel script stage)- * stages.comicPages — image-gen output for each comic page's panels- * stages.storyboards — image-gen + per-scene video output via CD scene runner- * stages.episodeVideo — final stitched episode video via CD+ * - ./issuesShared.js — store facade, per-series write queue, sanitizers,+ * read/save helpers, renumberInline (the shared store/queue).+ * - ./issueCrud.js — create/read/list/update/delete + numbering/reassign.+ * - ./issueStages.js — per-stage merge / history / restore.+ * - ./issueSync.js — peer-sync LWW merge + tombstone GC.*- * Each stage record carries a status, the user-editable input, the AI output,- * and a `lastRunId` pointer into data/runs/<runId>/ for the LLM transcript.- *- * Persisted to data/pipeline-issues/{id}/index.json.- */--import { randomUUID } from 'crypto';-import { getIssuesStore } from './issuesStore/store.js';-import { isPlainObject } from '../../lib/objects.js';-import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';-import { IMAGE_GEN_MODE } from '../imageGen/modes.js';-import {- LENGTH_PROFILE_NAMES, DEFAULT_LENGTH_PROFILE,- CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX,-} from '../../lib/issueLength.js';-import { sanitizeOrigin } from '../../lib/sharingOrigin.js';-import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';-import { ServerError } from '../../lib/errorHandler.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 { maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash } from '../../lib/conflictJournal.js';-import * as seriesSvc from './series.js';--// Storage backend dispatcher (#1015). Issue records moved from per-record-// `data/pipeline-issues/{id}/index.json` (collectionStore) to one-row-per-issue-// in PostgreSQL (`pipeline_issues`); the facade is a drop-in for the-// collectionStore surface this service calls (loadAll/loadOne/saveOneNow/-// deleteOne/queueTypeIndexWrite), so only this factory changed.-const store = () => getIssuesStore(sanitizeIssue);--export const issueStore = () => store();--// Series-scoped write queue. ALL issue mutations — create, per-issue PATCH,-// stage writes, deletes, and sibling-renumbering ops — route through this so-// they serialize per series. Even though collectionStore keeps a per-id queue,-// per-issue edits still share the series-level `index.json` (numbering, ordering),-// so two concurrent writes to *different* issues in the same series could read a-// stale index and clobber each other. A single tail per seriesId collapses that-// race: each write awaits the previous one and merges against the freshest state.-const seriesIssueQueue = createKeyCachedQueue();-function queueSeriesIssuesWrite(seriesId, fn) {- const key = typeof seriesId === 'string' && seriesId ? seriesId : '__unknown__';- return seriesIssueQueue(key, fn);-}--export const ERR_NOT_FOUND = 'PIPELINE_ISSUE_NOT_FOUND';-export const ERR_VALIDATION = 'PIPELINE_ISSUE_VALIDATION';-export const ERR_DUPLICATE = 'PIPELINE_ISSUE_DUPLICATE';-export const ERR_SEASON_LOCKED = 'PIPELINE_ISSUE_SEASON_LOCKED';-export const ERR_STAGE_LOCKED = 'PIPELINE_STAGE_LOCKED';-const makeErr = (message, code) => Object.assign(new Error(message), { code });--const ISSUE_ID_RE = /^iss-[A-Za-z0-9-]+$/;--export const TITLE_MAX = 300;-export const SERIES_ID_MAX = 64;-export const SEASON_ID_MAX = 64;-// Issues fall back to position 0 when un-numbered; the cap keeps a runaway-// LLM payload from inflating the field unbounded.-export const ARC_POSITION_MAX = 9999;-export const STAGE_INPUT_MAX = 200_000; // ~200kB — fits a long prose draft-export const STAGE_OUTPUT_MAX = 400_000; // ~400kB — fits a long comic script-export const STAGE_NOTES_MAX = 4000;-export const ISSUES_PER_RESPONSE_MAX = 1000;-// How many prior versions of a text stage to retain for the diff modal.-// Each entry holds the full prior input+output, so the upper bound is-// N × (STAGE_INPUT_MAX + STAGE_OUTPUT_MAX) per stage. Five keeps a useful-// undo trail without ballooning pipeline-issues.json. Only text stages-// snapshot — visual/audio artifact shapes (pages[]/scenes[]/lines[]) aren't-// meaningfully diffable as plain text; see snapshot gating in-// updateStageWithLatest + updateIssue.-export const STAGE_RUN_HISTORY_MAX = 5;--// Stage IDs are ordered for UI display; the canonical order is also the-// auto-run text-chain order (idea → prose → scripts in parallel). Comic-// pages / storyboards / episode video stages are visual and stay manual-// in MVP.-export const TEXT_STAGE_IDS = Object.freeze(['idea', 'prose', 'comicScript', 'teleplay']);-export const VISUAL_STAGE_IDS = Object.freeze(['comicPages', 'storyboards', 'episodeVideo']);-// Audio is its own category — voice-over lines + music. Feature-gated on-// series.targetFormat (only meaningful when the series ships video, not-// comic-only). Kept separate from VISUAL_STAGE_IDS so the artifact shape-// (`lines[]`, `music`) stays distinct from visual stages.-export const AUDIO_STAGE_IDS = Object.freeze(['audio']);-export const STAGE_IDS = Object.freeze([...TEXT_STAGE_IDS, ...VISUAL_STAGE_IDS, ...AUDIO_STAGE_IDS]);-// Stages exposed to voice navigation ("next stage" / "previous stage" tools)-// and the tab strip. Includes audio now that the AudioStage UI is wired.-export const NAVIGABLE_STAGE_IDS = Object.freeze([...TEXT_STAGE_IDS, ...VISUAL_STAGE_IDS, ...AUDIO_STAGE_IDS]);--// "This stage has usable content and shouldn't be regenerated by default."-// `edited` = user typed into the editor; `ready` = LLM filled and the user-// hasn't asked to rerun. Both are good — auto-runners skip past them unless-// `force` is set. Defined here so every coordinator agrees on the predicate.-export function isStageReady(stage) {- if (!stage) return false;- if (stage.status !== 'ready' && stage.status !== 'edited') return false;- return !!(stage.output && stage.output.trim());-}-export const STAGE_STATUSES = Object.freeze(['empty', 'generating', 'ready', 'edited', 'needs-review', 'error']);-export const ISSUE_STATUSES = Object.freeze(['draft', 'running', 'needs-review', 'shipped']);--const emptyStage = () => ({- status: 'empty',- input: '',- output: '',- lastRunId: null,- errorMessage: '',- updatedAt: null,- locked: false,- // Most-recent-first list of prior `{ runId, createdAt, input, output }`- // snapshots, capped at STAGE_RUN_HISTORY_MAX. Populated only for text- // stages — visual/audio stages keep the field as [] for shape parity.- runHistory: [],-});--/**- * Throw a 400 ServerError when `issue.stages[stageId].locked === true`.- * Every code path that regenerates a stage's primary artifact (LLM text run,- * image render, video render, audio synth, refine-prompt, extract-scenes /- * extract-pages) must call this so the lock contract is uniform. Sibling to- * the series-level (`series.locked.arc`) and season-level (`season.locked`)- * checks elsewhere — any of the three rejects.- */-export function assertStageUnlocked(issue, stageId) {- if (issue?.stages?.[stageId]?.locked === true) {- throw new ServerError(- `Stage "${stageId}" is locked — unlock it before regenerating`,- { status: 400, code: ERR_STAGE_LOCKED },- );- }-}--const sanitizeRunHistoryEntry = (raw) => {- if (!raw || typeof raw !== 'object') return null;- const runId = isStr(raw.runId) && raw.runId ? raw.runId : null;- if (!runId) return null;- return {- runId,- createdAt: isStr(raw.createdAt) && raw.createdAt ? raw.createdAt : null,- input: trimTo(raw.input, STAGE_INPUT_MAX),- output: trimTo(raw.output, STAGE_OUTPUT_MAX),- };-};--const sanitizeRunHistory = (raw) => {- if (!Array.isArray(raw)) return [];- return raw- .map(sanitizeRunHistoryEntry)- .filter(Boolean)- .slice(0, STAGE_RUN_HISTORY_MAX);-};--export const CANON_EXTRACTION_STATUSES = Object.freeze(['ok', 'partial', 'failed']);-const CANON_KINDS = Object.freeze(['character', 'place', 'object']);--// Normalize a canon-extraction outcome marker. Returns `null` for absent /-// malformed input (the "never attempted" state) so the field stays falsy in-// the UI until a real extraction runs. `extracted` counts are coerced to-// non-negative integers; `failedKinds` is filtered to the known kinds.-const sanitizeCanonExtraction = (raw) => {- if (!raw || typeof raw !== 'object') return null;- if (!CANON_EXTRACTION_STATUSES.includes(raw.status)) return null;- const count = (v) => (Number.isFinite(v) && v > 0 ? Math.floor(v) : 0);- const ex = raw.extracted && typeof raw.extracted === 'object' ? raw.extracted : {};- return {- status: raw.status,- error: trimTo(raw.error, STAGE_NOTES_MAX),- failedKinds: Array.isArray(raw.failedKinds)- ? [...new Set(raw.failedKinds.filter((k) => CANON_KINDS.includes(k)))]- : [],- extracted: {- characters: count(ex.characters),- places: count(ex.places),- objects: count(ex.objects),- },- provider: trimTo(raw.provider, 80),- model: trimTo(raw.model, 128),- at: isStr(raw.at) ? raw.at : null,- };-};--// Persisted outcome of the last strictly-prose-grounded "describe nouns from-// prose" run (see universeCanon.describeCanonFromProse). `null` = never run.-// `none`/`thin` carry the nouns the manuscript couldn't (or only thinly)-// describe so the Nouns UI can render a persistent manuscript-quality banner.-const sanitizeDescGapList = (arr) => (Array.isArray(arr) ? arr : [])- .filter((g) => g && typeof g === 'object' && CANON_KINDS.includes(g.kind))- .slice(0, 200)- .map((g) => ({- id: trimTo(g.id, 80),- name: trimTo(g.name, 200),- kind: g.kind,- note: trimTo(g.note, 600),- }));--const sanitizeDescGaps = (raw) => {- if (!raw || typeof raw !== 'object') return null;- return {- at: isStr(raw.at) ? raw.at : null,- provider: trimTo(raw.provider, 80),- model: trimTo(raw.model, 128),- filled: Number.isFinite(raw.filled) && raw.filled > 0 ? Math.floor(raw.filled) : 0,- none: sanitizeDescGapList(raw.none),- thin: sanitizeDescGapList(raw.thin),- skippedLocked: sanitizeDescGapList(raw.skippedLocked),- };-};--const sanitizeStage = (raw) => {- if (!raw || typeof raw !== 'object') return emptyStage();- const status = STAGE_STATUSES.includes(raw.status) ? raw.status : 'empty';- return {- status,- input: trimTo(raw.input, STAGE_INPUT_MAX),- output: trimTo(raw.output, STAGE_OUTPUT_MAX),- lastRunId: isStr(raw.lastRunId) && raw.lastRunId ? raw.lastRunId : null,- errorMessage: trimTo(raw.errorMessage, STAGE_NOTES_MAX),- updatedAt: isStr(raw.updatedAt) ? raw.updatedAt : null,- // Per-stage editorial lock. When true, `generateStage` (text) and the- // visual stage `enqueueXxx` entry points refuse — lets the user freeze a- // finalized comic script while still iterating storyboards. Independent- // of `series.locked.arc` and `season.locked`; any of the three rejects.- locked: raw.locked === true,- runHistory: sanitizeRunHistory(raw.runHistory),- };-};--// Text stages (idea/prose/comicScript/teleplay) carry one extra field beyond-// the shared stage shape: `canonExtraction`, the persisted outcome of the last-// characters/places/objects extraction run against the stage output (used on-// `prose`). Layered here rather than in `sanitizeStage` so visual/audio shapes-// never inherit a concern that doesn't apply to them. `null` = never attempted.-// Per-attempt record of the last multi-candidate draft-gate run (#2169, CWQE-// Phase 5). `null` = the gate never ran (single-shot generation, the default).-// Each attempt carries its runId (so its full text is recoverable from-// runHistory) + the composite qualityScore it was judged at, and `winner` names-// the kept attempt's runId — so the UI can show "kept 8.1, rejected 6.4 / 5.9".-const sanitizeDraftGate = (raw) => {- if (!raw || typeof raw !== 'object' || !Array.isArray(raw.attempts)) return null;- const num = (v) => (Number.isFinite(v) ? Math.round(v * 100) / 100 : null);- const attempts = raw.attempts- .filter((a) => a && typeof a === 'object' && isStr(a.runId) && a.runId)- .slice(0, STAGE_RUN_HISTORY_MAX)- .map((a) => ({- runId: a.runId,- qualityScore: num(a.qualityScore),- overall: num(a.overall),- slopPenalty: num(a.slopPenalty),- rejected: a.rejected === true,- }));- if (!attempts.length) return null;- return {- winner: isStr(raw.winner) && raw.winner ? raw.winner : null,- threshold: num(raw.threshold),- attempts,- stoppedEarly: raw.stoppedEarly === true,- at: isStr(raw.at) ? raw.at : null,- };-};--const sanitizeTextStage = (raw) => ({- ...sanitizeStage(raw),- canonExtraction: sanitizeCanonExtraction(raw?.canonExtraction),- descGaps: sanitizeDescGaps(raw?.descGaps),- draftGate: sanitizeDraftGate(raw?.draftGate),-});--/**- * Decide whether `patch` represents a generate-replacement on `prevStage` and,- * if so, prepend a snapshot of the prior state to `prevStage.runHistory`.- * Returns the new runHistory array (capped at STAGE_RUN_HISTORY_MAX).- *- * Trigger conditions (ALL must hold):- * - `stageId` is in TEXT_STAGE_IDS — visual + audio shapes don't snapshot.- * - patch.lastRunId is a non-empty string that differs from prevStage.lastRunId.- * - prevStage.lastRunId is set AND prevStage.output is non-empty — there's- * prior content worth preserving for diff/restore.- *- * Skipped triggers (and why):- * - First-time generate (prev.lastRunId === null) — nothing to snapshot.- * - status: 'generating' transition — patch carries no new lastRunId yet.- * - status: 'error' from a failed LLM throw — patch carries no new lastRunId.- * - Save-edit (PATCH with input/output but no lastRunId) — caller explicitly- * editing the existing version, not replacing it. The previous run remains- * the active version; the next generate will snapshot it.- */-export function snapshotRunHistory(prevStage, patch, stageId, { force = false } = {}) {- const prevHistory = Array.isArray(prevStage?.runHistory) ? prevStage.runHistory : [];- if (!patch || typeof patch !== 'object') return prevHistory;- if (!TEXT_STAGE_IDS.includes(stageId)) return prevHistory;- const nextRunId = isStr(patch.lastRunId) ? patch.lastRunId : '';- if (!nextRunId) return prevHistory;- if (nextRunId === prevStage?.lastRunId) return prevHistory;- // Default: only snapshot a prior that was itself a recorded run (keeps the- // first generate from snapshotting an empty/seed-only stage). With `force`- // (manuscript-editor edits), snapshot ANY non-empty prior, synthesizing an id- // when the prior was never a run — so imported/hand-typed text stays- // revertible from its very first edit.- if (!prevStage?.lastRunId && !force) return prevHistory;- const prevOutput = prevStage?.output || '';- if (!prevOutput.trim()) return prevHistory;- const snapshot = {- runId: prevStage.lastRunId || `pre-${nextRunId}`,- createdAt: prevStage.updatedAt || new Date().toISOString(),- input: prevStage.input || '',- output: prevOutput,- };- // Drop any prior entry whose runId matches the now-active runId. This is- // the restore case: snapshot r1 → user restores r1 → r1 becomes the active- // runId AND is still sitting in prevHistory. Without the filter the next- // regenerate would push the just-displaced state and leave a duplicate- // r1 in the list, breaking React keys and making restore-by-runId- // ambiguous (which r1 to apply?).- const dedupedPrior = prevHistory.filter((entry) => entry.runId !== nextRunId);- return [snapshot, ...dedupedPrior].slice(0, STAGE_RUN_HISTORY_MAX);-}--// Strip per-stage `runHistory` from a sanitized issue so list-shaped-// endpoints can opt out of shipping each stage's full version history. Text-// stages can hold up to STAGE_RUN_HISTORY_MAX (5) entries × ~600KB each, so-// a maxed-out issue is ~12MB of payload that the sidebar + per-series list-// never render. Opt-in via `withHistory: false` on `listIssues` /-// `listRecentIssues` — the default is full-shape because internal callers-// (notably `exportSeries`) round-trip every stored field through the bucket-// export, and dropping history there would lose it on the receiving peer.-const stripRunHistoryFromIssue = (issue) => {- if (!issue || typeof issue !== 'object' || !issue.stages) return issue;- const strippedStages = {};- for (const [stageId, stage] of Object.entries(issue.stages)) {- strippedStages[stageId] = stage?.runHistory?.length ? { ...stage, runHistory: [] } : stage;- }- return { ...issue, stages: strippedStages };-};--// Episode-video render settings the user chose at kickoff time. Persisted-// on the stage so a page reload doesn't reset them to the defaults — the-// restart flow can render the same pickers populated with the user's-// previous choice. The CD project itself owns the authoritative values once-// rendering starts; these are the *requested* settings for the next start.-const ASPECT_RATIO_VALUES = new Set(['16:9', '9:16', '1:1']);-const QUALITY_VALUES = new Set(['draft', 'standard', 'high']);--// `imageMode: 'auto'` defers to the server resolver (codex when enabled,-// local otherwise). Returns null when nothing was set so the persisted-// JSON stays clean for issues that never opened the panel.-const IMAGE_MODE_VALUES = new Set(['auto', IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX]);-const GEN_CONFIG_STR_MAX = 200;-const sanitizeGenConfig = (raw) => {- if (!raw || typeof raw !== 'object') return null;- const imageMode = IMAGE_MODE_VALUES.has(raw.imageMode) ? raw.imageMode : 'auto';- // imageModelId is only meaningful for local diffusion — clear it for other- // modes so a previously-pinned model doesn't silently persist in the config- // and mislead the UI or any future reader that doesn't filter by mode.- const imageModelId = imageMode === IMAGE_GEN_MODE.LOCAL- ? (trimTo(raw.imageModelId, GEN_CONFIG_STR_MAX) || null)- : null;- const refineProvider = trimTo(raw.refineProvider, GEN_CONFIG_STR_MAX) || null;- const refineModel = trimTo(raw.refineModel, GEN_CONFIG_STR_MAX) || null;- // Trained character-LoRA auto-apply opt-out. Default ON — only an explicit- // false persists, so issues that never touched the toggle stay clean.- const applyCharacterLoras = raw.applyCharacterLoras !== false;- if (imageMode === 'auto' && !imageModelId && !refineProvider && !refineModel && applyCharacterLoras) {- return null;- }- return { imageMode, imageModelId, refineProvider, refineModel, applyCharacterLoras };-};--// 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 (lib/renderSlot.js) the same way-// the cover does.--const sanitizeVisualStage = (raw, stageId = null) => {- // Visual stages keep arbitrary structured artifact lists. Sanitize the- // wrapper but pass through known shapes. `canonExtraction` is text-stage-only- // (it lives on `sanitizeTextStage`), so the visual shape never carries it.- const base = sanitizeStage(raw);- return {- ...base,- pages: Array.isArray(raw?.pages) ? raw.pages.slice(0, 200) : [],- scenes: Array.isArray(raw?.scenes) ? raw.scenes.slice(0, 200) : [],- cdProjectId: isStr(raw?.cdProjectId) && raw.cdProjectId ? raw.cdProjectId : null,- videoPath: isStr(raw?.videoPath) && raw.videoPath ? raw.videoPath : null,- aspectRatio: ASPECT_RATIO_VALUES.has(raw?.aspectRatio) ? raw.aspectRatio : null,- quality: QUALITY_VALUES.has(raw?.quality) ? raw.quality : null,- // Video model id — only meaningful on episodeVideo (it picks the per-scene- // render engine). Dropped on comicPages/storyboards so the contract is- // explicit, but kept when stageId is omitted (legacy load-time sanitize- // has no per-stage context). `null` = use the server/settings default.- modelId: (stageId === null || stageId === 'episodeVideo') && isStr(raw?.modelId) && raw.modelId- ? raw.modelId.slice(0, 64)- : 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` 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,- };-};--// Audio stage shape — dialogue VO lines + optional background music. Each-// line carries the source character + the actual line text + the render job-// id + a server-stamped filename (the storyboards filename hook's pattern-// will be extended to audio in a follow-up). `voiceIdOverride` lets a single-// line use a different voice than the character's default (narrator V.O.,-// flashback voice, etc.).-const AUDIO_LINE_TEXT_MAX = 4000;-const AUDIO_LINES_MAX = 1000;-export const AUDIO_FILENAME_MAX = 500;-const AUDIO_LINE_ID_MAX = 80;-// Cap a per-line VO offset at a generous episode length so a corrupted record-// can't push an `adelay` filter into absurd territory. Two hours is far beyond-// any single issue's runtime.-const AUDIO_LINE_OFFSET_MAX_SEC = 7200;-// Normalize a per-line start offset (seconds into the stitched episode where-// this VO line plays). `null` = "not placed yet" — kept distinct from `0`-// ("plays at the very start") so the muxer can skip un-placed lines instead of-// stacking them all at t=0. Negative / non-finite input collapses to null.-export const sanitizeLineOffset = (raw) => {- if (raw === null || raw === undefined) return null;- const n = Number(raw);- if (!Number.isFinite(n) || n < 0) return null;- return Math.min(n, AUDIO_LINE_OFFSET_MAX_SEC);-};-const sanitizeAudioLine = (raw, i) => {- if (!raw || typeof raw !== 'object') return null;- const text = trimTo(raw.text, AUDIO_LINE_TEXT_MAX);- if (!text) return null;- const id = trimTo(raw.id, AUDIO_LINE_ID_MAX) || `line-${String(i + 1).padStart(3, '0')}`;- return {- id,- characterId: trimTo(raw.characterId, 80) || null,- characterName: trimTo(raw.characterName, 120) || null,- text,- voiceIdOverride: trimTo(raw.voiceIdOverride, 200) || null,- audioJobId: isStr(raw.audioJobId) && raw.audioJobId ? raw.audioJobId : null,- audioFilename: isStr(raw.audioFilename) && raw.audioFilename- ? raw.audioFilename.slice(0, AUDIO_FILENAME_MAX)- : null,- // Per-line start offset for muxing VO into the stitched episode (Phase- // 4d.2). null until the user (or a future auto-spacer) places it.- offsetSec: sanitizeLineOffset(raw.offsetSec),- };-};--const MUSIC_SOURCES = new Set(['upload', 'library', 'gen']);-const sanitizeMusicTrack = (raw) => {- if (!raw || typeof raw !== 'object') return null;- const source = MUSIC_SOURCES.has(raw.source) ? raw.source : null;- const trackFilename = trimTo(raw.trackFilename, AUDIO_FILENAME_MAX) || null;- const label = trimTo(raw.label, 200) || null;- if (!source && !trackFilename && !label) return null;- return { source, trackFilename, label };-};--// Which strategy drives the episode's non-dialogue audio (whole-episode audio,-// issue #863 / design doc 2026-06-03-whole-episode-audio-strategy.md):-// per-clip — keep each stitched clip's own soundtrack (today's default)-// silent — strip any bed-// generated — assemble the arc-driven cues[] onto the timeline-// uploaded-track — loop the single `music` pointer under the whole episode-export const AUDIO_MODES = Object.freeze(['per-clip', 'silent', 'generated', 'uploaded-track']);-// Read-side default: an absent / unknown audioMode collapses to 'per-clip' —-// today's behavior — so an un-migrated record (or one synced from an older,-// audioMode-unaware peer) reads correctly before migration 067 stamps the-// explicit value. Never let "absent" become a wrong mode (CLAUDE.md sentinel-// discipline).-export const sanitizeAudioMode = (raw) => (AUDIO_MODES.includes(raw) ? raw : 'per-clip');--// Per-cue field caps. Exported so the route's light Zod arm references the-// same numbers (the sanitizer below is authoritative; the route only guards-// against payload ballooning) and can't silently drift if these change.-export const AUDIO_CUE_ID_MAX = 80;-export const AUDIO_CUE_LABEL_MAX = 200;-export const AUDIO_CUE_PROMPT_MAX = 8000;-export const AUDIO_CUE_ENGINE_MAX = 80;-export const AUDIO_CUES_MAX = 200;--// Per-cue gain override. `null` = "use the stage / global default", distinct-// from `0` ("muted"). Clamped to a sane 0..4 range so a corrupted value can't-// blow out the mix.-const sanitizeCueGain = (raw) => {- if (raw === null || raw === undefined) return null;- const n = Number(raw);- if (!Number.isFinite(n) || n < 0) return null;- return Math.min(n, 4);-};--const sanitizeAudioCue = (raw, i) => {- if (!raw || typeof raw !== 'object') return null;- const id = trimTo(raw.id, AUDIO_CUE_ID_MAX) || `cue-${String(i + 1).padStart(3, '0')}`;- return {- id,- label: trimTo(raw.label, AUDIO_CUE_LABEL_MAX) || null,- prompt: trimTo(raw.prompt, AUDIO_CUE_PROMPT_MAX) || null,- // Engine id (musicgen | audioldm2 | suno | …). Free-form trimmed string so- // a future pluggable engine works without a sanitizer change — the render- // route resolves it against the live ENGINES registry. null = "unset".- engine: trimTo(raw.engine, AUDIO_CUE_ENGINE_MAX) || null,- // Reuse sanitizeLineOffset for cue timing: identical null-vs-0 sentinel- // ("not placed yet" vs "plays at start") and 2h cap as VO line offsets.- // durationSec is "not rendered yet" (null) → actual length once rendered.- startSec: sanitizeLineOffset(raw.startSec),- endSec: sanitizeLineOffset(raw.endSec),- trackFilename: isStr(raw.trackFilename) && raw.trackFilename- ? raw.trackFilename.slice(0, AUDIO_FILENAME_MAX)- : null,- durationSec: sanitizeLineOffset(raw.durationSec),- gain: sanitizeCueGain(raw.gain),- };-};--const sanitizeAudioStage = (raw) => {- // `canonExtraction` is text-stage-only (see sanitizeTextStage) — the audio- // shape never carries it.- const base = sanitizeStage(raw);- return {- ...base,- lines: Array.isArray(raw?.lines)- ? raw.lines.slice(0, AUDIO_LINES_MAX).map(sanitizeAudioLine).filter(Boolean)- : [],- music: sanitizeMusicTrack(raw?.music),- audioMode: sanitizeAudioMode(raw?.audioMode),- cues: Array.isArray(raw?.cues)- ? raw.cues.slice(0, AUDIO_CUES_MAX).map(sanitizeAudioCue).filter(Boolean)- : [],- };-};--const sanitizeStages = (raw = {}) => {- const out = {};- for (const id of TEXT_STAGE_IDS) out[id] = sanitizeTextStage(raw[id]);- for (const id of VISUAL_STAGE_IDS) out[id] = sanitizeVisualStage(raw[id], id);- for (const id of AUDIO_STAGE_IDS) out[id] = sanitizeAudioStage(raw[id]);- return out;-};--const sanitizeIssue = (raw) => {- if (!raw || typeof raw !== 'object') return null;- if (!isStr(raw.id) || !raw.id) return null;- if (!isStr(raw.seriesId) || !raw.seriesId) return null;- const title = trimTo(raw.title, TITLE_MAX);- if (!title) return null;- const number = Number.isFinite(raw.number) ? Math.max(0, Math.floor(raw.number)) : 0;- const status = ISSUE_STATUSES.includes(raw.status) ? raw.status : 'draft';- const createdAt = isStr(raw.createdAt) ? raw.createdAt : new Date().toISOString();- const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;- // Phase 2 of Story Arc Planning: optional pointer back into the parent- // series' arc tree. `null` is the back-compat default — every pre-existing- // issue stays un-grouped until the user (or LLM-arc-generation) assigns it.- const seasonId = isStr(raw.seasonId) && raw.seasonId- ? trimTo(raw.seasonId, SEASON_ID_MAX)- : null;- const arcPosition = Number.isFinite(raw.arcPosition)- ? Math.max(0, Math.min(ARC_POSITION_MAX, Math.floor(raw.arcPosition)))- : null;- // LLM-assigned role within the volume — drives beat-sheet cadence- // (finale vs. complication need very different shapes).- const arcRole = ARC_ROLES.includes(raw.arcRole) ? raw.arcRole : null;- // Defaults to 'standard' so pre-field issues keep the prior 22pg/24min sizing.- // pageTarget/minutesTarget are only consumed when lengthProfile==='custom',- // but we persist them on every profile so the picker can remember a previous- // custom value if the user toggles back. Bounds mirror the values- // `computeIssueTargets` clamps to at render time — otherwise the persisted- // record could disagree with the prompt-rendered length.- const lengthProfile = LENGTH_PROFILE_NAMES.includes(raw.lengthProfile)- ? raw.lengthProfile- : DEFAULT_LENGTH_PROFILE;- const pageTarget = Number.isFinite(raw.pageTarget)- ? Math.max(CUSTOM_PAGE_MIN, Math.min(CUSTOM_PAGE_MAX, Math.round(raw.pageTarget)))- : null;- const minutesTarget = Number.isFinite(raw.minutesTarget)- ? Math.max(CUSTOM_MINUTE_MIN, Math.min(CUSTOM_MINUTE_MAX, Math.round(raw.minutesTarget)))- : null;- return {- id: raw.id,- seriesId: trimTo(raw.seriesId, SERIES_ID_MAX),- number,- title,- status,- seasonId,- arcPosition,- arcRole,- lengthProfile,- pageTarget,- minutesTarget,- stages: sanitizeStages(raw.stages || {}),- // Share-bucket provenance — present on imported records, absent on locally-authored ones.- origin: sanitizeOrigin(raw.origin),- createdAt,- updatedAt,- // Soft-delete fields — see universeBuilder.sanitizeTemplate.- ...sanitizeSoftDeleteFields(raw),- // Local-only "don't sync to peers" marker. Issues piggyback on their- // parent series' subscription, so marking an issue ephemeral keeps the- // series push payload from carrying it (sanitizeRecordForWire drops it- // and the series's bundled-issues filter discards the null entry).- ...(raw.ephemeral === true ? { ephemeral: true } : {}),- };-};--async function readState() {- return { issues: await store().loadAll() };-}--// Series-scoped read — uses the indexed `idx_issues_series` query (PG) so a-// per-series scan doesn't load + sanitize every issue in the install. Callers-// that already filter by seriesId in JS should source from here instead.-async function readStateForSeries(seriesId) {- return { issues: await store().loadAllForSeries(seriesId) };-}--async function saveIssueNow(issue) {- await store().saveOneNow(issue.id, issue);- return issue;-}--async function saveIssuesNow(issues) {- await Promise.all(issues.map((issue) => saveIssueNow(issue)));-}--export async function listIssues({- seriesId = null,- offset = 0,- limit = ISSUES_PER_RESPONSE_MAX,- paginated = false,- withHistory = true,- includeDeleted = false,-} = {}) {- // Scope the read to one series when filtering by it — avoids loading every- // issue in the install just to discard the rest (the `seriesId.localeCompare`- // tiebreak below is a no-op within a single series).- const { issues } = seriesId ? await readStateForSeries(seriesId) : await readState();- const live = includeDeleted ? issues : issues.filter((i) => !i.deleted);- const filtered = seriesId ? live.filter((i) => i.seriesId === seriesId) : live;- const sorted = [...filtered].sort((a, b) => {- if (a.seriesId !== b.seriesId) return a.seriesId.localeCompare(b.seriesId);- return (a.number || 0) - (b.number || 0);- });- const project = withHistory ? (i) => i : stripRunHistoryFromIssue;- const safeLimit = Math.min(Math.max(1, limit), ISSUES_PER_RESPONSE_MAX);- const safeOffset = Math.max(0, offset);- if (paginated) {- return {- items: sorted.slice(safeOffset, safeOffset + safeLimit).map(project),- total: sorted.length,- offset: safeOffset,- limit: safeLimit,- };- }- return sorted.slice(0, ISSUES_PER_RESPONSE_MAX).map(project);-}--/**- * Every live (or, with `includeDeleted`, every) issue id — UNCAPPED.- *- * `listIssues` slices at `ISSUES_PER_RESPONSE_MAX` (1000) even unpaginated, so- * it can't back a "does this id still exist?" membership check: an install with- * >1000 issues would report ids beyond the cap as missing. Callers that need- * the complete id set (e.g. the conflict-journal orphan-base-hash sweep, which- * would otherwise prune a live issue's base hash and silently disable conflict- * detection for it) use this. Returns ids only — no projection, no history.- */-export async function listIssueIds({ includeDeleted = false } = {}) {- const { issues } = await readState();- const live = includeDeleted ? issues : issues.filter((i) => !i.deleted);- return live.map((i) => i.id);-}--/**- * Every live issue record — UNCAPPED, unsorted, unpaginated.- *- * Same rationale as `listIssueIds`: `listIssues` slices at- * `ISSUES_PER_RESPONSE_MAX` (1000) even unpaginated, so it cannot back- * whole-library scans. Callers that group/count issues across ALL series- * (canon-usage tallies, the orphan-shell sweep's "does this series still have- * issues?" gate) must use this — with `listIssues({})` an install holding- * >1000 issues would silently miss the tail, and the orphan sweep could- * delete a series that still has issues past the cap.- *- * @param {object} [options]- * @param {boolean} [options.includeDeleted=false]- * @param {boolean} [options.withHistory=true] - false strips per-stage run history- */-export async function listAllIssues({ includeDeleted = false, withHistory = true } = {}) {- const { issues } = await readState();- const live = includeDeleted ? issues : issues.filter((i) => !i.deleted);- return withHistory ? live : live.map(stripRunHistoryFromIssue);-}--/**- * Every live issue record for one series — UNCAPPED, sorted by issue number.- *- * Same cap rationale as `listAllIssues`/`listIssueIds`: `listIssues({ seriesId })`- * slices at `ISSUES_PER_RESPONSE_MAX` (1000), so a series holding >1000 issues- * loses its tail. Per-series scans that MUST see every issue (the editorial- * runner's storyboard-continuity and comic-lettering projections, #1469) use- * this — with `listIssues` those checks would silently skip every storyboard- * scene / comic page past the 1000th issue. Sorted by `number` to match the- * ordering `listIssues` produces within a single series.- *- * @param {string} seriesId- * @param {object} [options]- * @param {boolean} [options.includeDeleted=false]- * @param {boolean} [options.withHistory=true] - false strips per-stage run history- */-export async function listIssuesForSeries(seriesId, { includeDeleted = false, withHistory = true } = {}) {- const { issues } = await readStateForSeries(seriesId);- const live = includeDeleted ? issues : issues.filter((i) => !i.deleted);- const sorted = [...live].sort((a, b) => (a.number || 0) - (b.number || 0));- return withHistory ? sorted : sorted.map(stripRunHistoryFromIssue);-}--/**- * Recently-updated issues across all series. Sorts the FULL issue set by- * `updatedAt` desc before applying `limit` — unlike `listIssues`, which- * sorts by `seriesId/number` then caps at `ISSUES_PER_RESPONSE_MAX`. That- * cap would silently miss the most-recent issues once the dataset grows- * beyond 1000, so the sidebar's recent-issues view needs this dedicated- * helper.- */-export async function listRecentIssues({ limit = 10, withHistory = true, includeDeleted = false } = {}) {- const { issues } = await readState();- const live = includeDeleted ? issues : issues.filter((i) => !i.deleted);- // Coerce in two passes so non-finite inputs ('abc', undefined) fall to- // the default rather than letting JS's `0 || 10` short-circuit return- // 10 for an explicit limit=0.- const raw = Number(limit);- const fallback = Number.isFinite(raw) ? Math.floor(raw) : 10;- const clamped = Math.max(1, Math.min(50, fallback));- const project = withHistory ? (i) => i : stripRunHistoryFromIssue;- return [...live]- .sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''))- .slice(0, clamped)- .map(project);-}--export async function getIssue(id, { includeDeleted = false } = {}) {- const found = await store().loadOne(id);- if (!found) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);- if (found.deleted && !includeDeleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);- return found;-}--export function createIssue(input = {}, { preloadedSeries = null } = {}) {- const seriesId = trimTo(input.seriesId, SERIES_ID_MAX);- if (!seriesId) return Promise.reject(makeErr('seriesId is required', ERR_VALIDATION));- const title = trimTo(input.title, TITLE_MAX);- if (!title) return Promise.reject(makeErr(`title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION));- return queueSeriesIssuesWrite(seriesId, async () => {- const state = await readState();- const next = sanitizeIssue({- id: `iss-${randomUUID()}`,- seriesId,- // Placeholder — `renumberInline` below derives the canonical number.- number: 0,- title,- status: 'draft',- // Phase 2: optional arc pointers passed by the season-episodes generator- // (and any future caller wiring an issue to a season at create time).- seasonId: 'seasonId' in input ? input.seasonId : null,- arcPosition: 'arcPosition' in input ? input.arcPosition : null,- arcRole: 'arcRole' in input ? input.arcRole : null,- lengthProfile: 'lengthProfile' in input ? input.lengthProfile : undefined,- pageTarget: 'pageTarget' in input ? input.pageTarget : null,- minutesTarget: 'minutesTarget' in input ? input.minutesTarget : null,- stages: input.stages || {},- createdAt: new Date().toISOString(),- updatedAt: new Date().toISOString(),- ephemeral: input.ephemeral === true,- });- if (!next) throw makeErr('Invalid issue payload', ERR_VALIDATION);- state.issues.push(next);- await renumberInline(state, seriesId, next.seasonId || UNSCOPED_ANCHOR, preloadedSeries);- await saveIssuesNow(state.issues.filter((i) => i.seriesId === seriesId));- // New issue = series-level change for any active share subscription.- emitRecordUpdated('series', next.seriesId);- return next;- });-}--async function renumberInline(state, seriesId, fromSeasonId = null, preloadedSeries = null) {- // Batch callers (e.g. commitEpisodesToIssues seeding a whole season) thread- // the already-fetched series so an N-episode loop doesn't pay N redundant- // getSeries reads of an unchanging record. Guard on id match so a mismatched- // preload can never renumber against the wrong season list.- const series = (preloadedSeries && preloadedSeries.id === seriesId)- ? preloadedSeries- : await seriesSvc.getSeries(seriesId).catch(() => null);- // Exclude tombstones from numbering — surviving issues should keep a- // contiguous sequence regardless of how many deletes happened.- // applyVolumeOrderedNumbers mutates each issue's `number` in place, so the- // filtered array still aliases the same objects in state.issues.- return applyVolumeOrderedNumbers({- issues: state.issues.filter((i) => !i.deleted),- seriesId,- seasons: series?.seasons || [],- fromSeasonId,- });-}--export function recomputeIssueNumbersForSeries(seriesId, fromSeasonId = null) {- return queueSeriesIssuesWrite(seriesId, async () => {- const state = await readState();- const changed = await renumberInline(state, seriesId, fromSeasonId);- if (!changed) return { changed: false };- await saveIssuesNow(state.issues.filter((i) => i.seriesId === seriesId));- emitRecordUpdated('series', seriesId);- return { changed: true };- });-}--/**- * Reassign every issue under `(seriesId, fromSeasonId)` to `toSeasonId` in a- * single collection load → in-memory mutate → per-record save pass.- * Used by `deleteSeason` (and any future bulk season-move flow) to collapse- * N per-issue write cycles into one — the legacy N+1 pattern was- * `for (iss of children) await updateIssue(iss.id, { seasonId: toSeasonId }, { skipRenumber: true })`- * which paid N read/write round-trips and N debounced re-exports even with- * `withReexportSuppressed`.- *- * Returns `{ reassigned, fromSeasonId, toSeasonId }`. `toSeasonId` may be- * `null` (un-grouped). A re-export of the parent series is emitted once, after- * the renumber pass — callers under `withReexportSuppressed` get exactly one- * `series:updated` event regardless of the issue count.- */-export function bulkReassignSeason(seriesId, fromSeasonId, toSeasonId = null, { _preloadedSeries = null } = {}) {- return queueSeriesIssuesWrite(seriesId, async () => {- // Honor per-season locks — refuse to move issues OUT of or INTO a locked- // volume. Series lives in a different write queue, so this is best-effort- // single-user gating, not strict serialization (fine per CLAUDE.md).- // Callers that already hold a fresh series (e.g. `deleteSeason` reads it- // for the reassign-target validation) can pass `_preloadedSeries` to skip- // the duplicate read.- if (fromSeasonId || toSeasonId) {- const series = _preloadedSeries || await seriesSvc.getSeries(seriesId);- const seasons = Array.isArray(series.seasons) ? series.seasons : [];- const findLocked = (id) => (id ? seasons.find((s) => s.id === id && s.locked === true) : null);- const blocker = findLocked(fromSeasonId) || findLocked(toSeasonId);- if (blocker) {- throw makeErr(- `Season "${blocker.title || blocker.number}" is locked — unlock it before reassigning issues`,- ERR_SEASON_LOCKED,- );- }- }- const state = await readState();- let reassigned = 0;- const now = new Date().toISOString();- for (let i = 0; i < state.issues.length; i += 1) {- const iss = state.issues[i];- if (iss.seriesId !== seriesId) continue;- // Skip tombstones — moving a soft-deleted issue would bump its- // `updatedAt`, which then loses LWW races with the originator's- // tombstone and can resurrect the record on every peer.- if (iss.deleted) continue;- if ((iss.seasonId || null) !== (fromSeasonId || null)) continue;- // Re-sanitize through the same pipeline updateIssue uses so the- // in-memory rewrite gets the same shape guarantees as a route PATCH.- const merged = sanitizeIssue({- ...iss,- seasonId: toSeasonId,- updatedAt: now,- });- if (!merged) continue;- state.issues[i] = merged;- reassigned += 1;- }- if (reassigned === 0) return { reassigned: 0, fromSeasonId, toSeasonId };- // One renumber pass after the bulk move — the source AND destination- // volume both reshuffled, so use the series-wide form (fromSeasonId=null).- await renumberInline(state, seriesId, null);- await saveIssuesNow(state.issues.filter((i) => i.seriesId === seriesId));- emitRecordUpdated('series', seriesId);- return { reassigned, fromSeasonId, toSeasonId };- });-}--/**- * Reassign every live issue from `fromSeriesId` to `toSeriesId` — used by the- * series-merge engine (recordMerge.js) so a duplicate series' issues survive- * the merge instead of being orphaned under the tombstoned loser.- *- * Issue→season grouping is preserved across the move via `seasonIdMap` — a- * `{ loserSeasonId: survivorSeasonId }` map the caller (`mergeSeries`) builds by- * pairing the loser's seasons to the survivor's by `number`. An issue whose- * `seasonId` resolves through the map lands in the matching survivor season; one- * with no `seasonId`, or a `seasonId` the map doesn't cover (a stale ref, or a- * loser season that didn't survive the union), lands UN-GROUPED (`seasonId:- * null`). A single renumber pass on the survivor sequences the combined set.- * Returns `{ reassigned }`.- *- * Serialized on the SURVIVOR's issues queue so the renumber can't race a- * concurrent survivor edit. Tombstoned issues are skipped (moving them would- * bump updatedAt and lose the originator's delete LWW race).- */-export function reassignIssuesToSeries(fromSeriesId, toSeriesId, { seasonIdMap = {} } = {}) {- if (!isStr(fromSeriesId) || !isStr(toSeriesId) || fromSeriesId === toSeriesId) {- return Promise.reject(makeErr('reassignIssuesToSeries: fromSeriesId and toSeriesId must differ', ERR_VALIDATION));- }- // This reads/mutates issues belonging to BOTH series (it moves source issues- // and renumbers the destination), so serialize on both per-series queues, not- // just the destination — otherwise a concurrent edit/renumber on the source- // (e.g. a peer-sync merge landing on the loser mid-merge) could interleave and- // be lost. Acquire in sorted order so a future two-series caller can't deadlock.- const [first, second] = [fromSeriesId, toSeriesId].sort();- const body = async () => {- const state = await readState();- const now = new Date().toISOString();- const moved = [];- for (let i = 0; i < state.issues.length; i += 1) {- const iss = state.issues[i];- if (iss.seriesId !== fromSeriesId || iss.deleted) continue;- // Map the issue's loser season to the survivor's same-number season so the- // grouping survives; fall back to un-grouped when there's no mapping.- const seasonId = (iss.seasonId && seasonIdMap[iss.seasonId]) || null;- const merged = sanitizeIssue({ ...iss, seriesId: toSeriesId, seasonId, updatedAt: now });- if (!merged) continue;- state.issues[i] = merged;- moved.push(merged);- }- if (moved.length === 0) return { reassigned: 0 };- await renumberInline(state, toSeriesId, null);- // Persist every issue now tagged to the survivor (the moved ones + any the- // survivor already had, whose numbers may have shifted in the renumber).- await saveIssuesNow(state.issues.filter((i) => i.seriesId === toSeriesId));- emitRecordUpdated('series', toSeriesId);- emitRecordUpdated('series', fromSeriesId);- return { reassigned: moved.length };- };- return queueSeriesIssuesWrite(first, () => queueSeriesIssuesWrite(second, body));-}--/**- * Insert an issue with a caller-supplied id (used by the share-bucket importer- * so re-imports of the same issue LWW-merge onto the same local row).- * Throws ERR_DUPLICATE / ERR_VALIDATION on contract violations.+ * This barrel re-exports the full public surface so every existing+ * `from './issues.js'` import path stays valid.*/-export function insertIssueWithId(input = {}) {- if (!isStr(input.id) || !ISSUE_ID_RE.test(input.id)) {- return Promise.reject(makeErr(`insertIssueWithId: invalid id "${input.id}" (expected iss-<uuid>)`, ERR_VALIDATION));- }- const seriesId = trimTo(input.seriesId, SERIES_ID_MAX);- if (!seriesId) return Promise.reject(makeErr('seriesId is required', ERR_VALIDATION));- const title = trimTo(input.title, TITLE_MAX);- if (!title) return Promise.reject(makeErr(`title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION));- return queueSeriesIssuesWrite(seriesId, async () => {- const state = await readState();- // Tombstone-overwrite: same contract as universeBuilder.insertUniverseWithId.- const existingIdx = state.issues.findIndex((i) => i.id === input.id);- if (existingIdx >= 0 && !state.issues[existingIdx].deleted) {- throw makeErr(`Issue id already exists: ${input.id}`, ERR_DUPLICATE);- }- const wasResurrection = existingIdx >= 0;- const next = sanitizeIssue({ ...input, seriesId, title });- if (!next) throw makeErr('Invalid issue payload', ERR_VALIDATION);- if (wasResurrection) {- console.warn(`♻️ insertIssueWithId: overwriting tombstone for ${input.id}`);- state.issues[existingIdx] = next;- } else {- state.issues.push(next);- }- // Imported `number` is a starting hint — local canonical numbering still- // comes from (volume order, arcPosition) of the local state.- await renumberInline(state, seriesId, next.seasonId || UNSCOPED_ANCHOR);- await saveIssuesNow(state.issues.filter((i) => i.seriesId === seriesId));- // Mirror createIssue's federation side-effect on tombstone-overwrite:- // issues ride series-level events, so notify peers via the parent series.- if (wasResurrection) emitRecordUpdated('series', next.seriesId);- return next;- });-}-function mergeIssuePatch(cur, patch = {}) {- // Per-stage merge: a stage patch carries only the fields the caller is- // changing (e.g. `{ genConfig }` or `{ cover }`). Without this, the top-level- // spread would replace the entire stage object and silently drop sibling- // fields like `scenes` / `pages` / `genConfig`. Sanitization then defaults- // those back to empty arrays/null, erasing work the user (or LLM) just did.- // Callers that need stage-level changes without touching issue-level fields- // should use `updateStage`, which does a shallow merge of the patch over the- // existing stage (`{ ...cur.stages[stageId], ...patch }`) before sanitizing.- //- // `cover` and `genConfig` are treated as deep-merge sub-objects: a partial- // `{ cover: { script } }` patch from a textarea-blur save must not wipe the- // sibling `imageJobId` / `prompt` that a parallel "Render cover" mutation- // just persisted. Passing `null` explicitly still clears the sub-object.- const NESTED_DEEP_MERGE_KEYS = ['cover', 'genConfig'];- let mergedStages = cur.stages;- if ('stages' in patch && patch.stages && typeof patch.stages === 'object') {- mergedStages = { ...cur.stages };- for (const [stageId, stagePatch] of Object.entries(patch.stages)) {- const prev = cur.stages?.[stageId];- if (prev && stagePatch && typeof prev === 'object' && typeof stagePatch === 'object') {- const merged = { ...prev, ...stagePatch };- merged.runHistory = snapshotRunHistory(prev, stagePatch, stageId);- for (const key of NESTED_DEEP_MERGE_KEYS) {- if (key in stagePatch- && stagePatch[key] && typeof stagePatch[key] === 'object'- && prev[key] && typeof prev[key] === 'object') {- merged[key] = { ...prev[key], ...stagePatch[key] };- }- }- if ('status' in stagePatch && stagePatch.status !== 'error'- && stagePatch.status !== 'generating'- && !('errorMessage' in stagePatch)) {- merged.errorMessage = '';- }- mergedStages[stageId] = merged;- } else {- mergedStages[stageId] = stagePatch;- }- }- }-- const merged = sanitizeIssue({- ...cur,- ...('title' in patch ? { title: patch.title } : {}),- ...('number' in patch ? { number: patch.number } : {}),- ...('status' in patch ? { status: patch.status } : {}),- ...('seasonId' in patch ? { seasonId: patch.seasonId } : {}),- ...('arcPosition' in patch ? { arcPosition: patch.arcPosition } : {}),- ...('arcRole' in patch ? { arcRole: patch.arcRole } : {}),- ...('lengthProfile' in patch ? { lengthProfile: patch.lengthProfile } : {}),- ...('pageTarget' in patch ? { pageTarget: patch.pageTarget } : {}),- ...('minutesTarget' in patch ? { minutesTarget: patch.minutesTarget } : {}),- ...('origin' in patch ? { origin: patch.origin } : {}),- // Local-only "don't sync" marker. Issues piggyback on their parent- // series' subscription, so an ephemeral issue is dropped from the- // series push payload via sanitizeRecordForWire returning null.- ...('ephemeral' in patch ? { ephemeral: patch.ephemeral } : {}),- stages: mergedStages,- updatedAt: new Date().toISOString(),- });- if (!merged) throw makeErr('Invalid issue payload', ERR_VALIDATION);- return merged;-}--export function updateIssue(id, patch = {}, { skipRenumber = false } = {}) {- const needsRenumber = !skipRenumber && ('seasonId' in patch || 'arcPosition' in patch);- if (!needsRenumber) {- // Route through the SERIES tail (see updateStageWithLatest) so a plain- // field update can't race a concurrent series-wide renumber rewriting this- // issue. seriesId is immutable, so read it outside the lock to pick the- // queue, then re-read the issue inside.- return getIssue(id, { includeDeleted: true }).then((existing) =>- queueSeriesIssuesWrite(existing.seriesId, async () => {- const cur = await store().loadOne(id);- if (!cur) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);- if (cur.deleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);- const merged = mergeIssuePatch(cur, patch);- await saveIssueNow(merged);- emitRecordUpdated('series', merged.seriesId);- return merged;- }),- );- }-- return getIssue(id, { includeDeleted: true }).then((existing) =>- queueSeriesIssuesWrite(existing.seriesId, async () => {- const state = await readState();- const idx = state.issues.findIndex((i) => i.id === id);- if (idx < 0) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);- const cur = state.issues[idx];- if (cur.deleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);- const merged = mergeIssuePatch(cur, patch);- state.issues[idx] = merged;- // A seasonId move affects both source and destination volumes, so full- // renumber. An arcPosition change only reorders within the current volume.- if ('seasonId' in patch && cur.seasonId !== merged.seasonId) {- await renumberInline(state, merged.seriesId, null);- } else if ('arcPosition' in patch && cur.arcPosition !== merged.arcPosition) {- await renumberInline(state, merged.seriesId, merged.seasonId || UNSCOPED_ANCHOR);- }- await saveIssuesNow(state.issues.filter((i) => i.seriesId === merged.seriesId));- // Issues are exported as part of their parent series — re-export the- // series so any active subscription picks up the issue change.- emitRecordUpdated('series', merged.seriesId);- return merged;- })- );-}--/**- * Partial update to a single stage on an issue. Use this from generators so- * a stage write doesn't have to load the full issue, mutate, and re-validate.- * Patch keys: status, input, output, lastRunId, errorMessage, and (for- * visual stages) pages/scenes/cdProjectId/videoPath.- *- * When the patch depends on the current stage value (e.g. cover preservation),- * use `updateStageWithLatest` instead so the decision is made against the- * freshest persisted record inside the serialized write region.- */-export function updateStage(issueId, stageId, patch = {}) {- return updateStageWithLatest(issueId, stageId, () => patch);-}--function mergeStagePatch(currentStage, stageId, patch, { snapshotPrior = false } = {}) {- const isVisual = VISUAL_STAGE_IDS.includes(stageId);- const isAudio = AUDIO_STAGE_IDS.includes(stageId);- const nextRunHistory = snapshotRunHistory(currentStage, patch, stageId, { force: snapshotPrior });- const merged = {- ...currentStage,- ...patch,- runHistory: nextRunHistory,- updatedAt: new Date().toISOString(),- };- if (isVisual) return sanitizeVisualStage(merged, stageId);- if (isAudio) return sanitizeAudioStage(merged);- return sanitizeTextStage(merged);-}--export function updateStagesWithLatest(seriesId, updates = [], { snapshotPrior = false } = {}) {- if (!isStr(seriesId) || !seriesId) {- return Promise.reject(makeErr('seriesId is required', ERR_VALIDATION));- }- if (!Array.isArray(updates) || updates.length === 0) {- return Promise.resolve([]);- }- for (const { stageId } of updates) {- if (!STAGE_IDS.includes(stageId)) {- return Promise.reject(makeErr(`Unknown stage: ${stageId}`, ERR_VALIDATION));- }- }-- return queueSeriesIssuesWrite(seriesId, async () => {- const state = await readState();- const results = [];- let changed = false;- for (const update of updates) {- const idx = state.issues.findIndex((i) => i.id === update.issueId);- if (idx < 0) throw makeErr(`Issue not found: ${update.issueId}`, ERR_NOT_FOUND);- const cur = state.issues[idx];- if (cur.deleted || cur.seriesId !== seriesId) throw makeErr(`Issue not found: ${update.issueId}`, ERR_NOT_FOUND);- const currentStage = cur.stages[update.stageId];- const patch = update.computeFn(currentStage);- if (isPlainObject(patch) && Object.keys(patch).length === 0) {- results.push({ issue: cur, stage: currentStage });- continue;- }- const nextStage = mergeStagePatch(currentStage, update.stageId, patch, { snapshotPrior });- const mergedIssue = sanitizeIssue({- ...cur,- stages: { ...cur.stages, [update.stageId]: nextStage },- updatedAt: new Date().toISOString(),- });- if (!mergedIssue) throw makeErr('Invalid issue payload', ERR_VALIDATION);- state.issues[idx] = mergedIssue;- results.push({ issue: mergedIssue, stage: mergedIssue.stages[update.stageId] });- changed = true;- }- if (changed) {- await saveIssuesNow(state.issues.filter((i) => i.seriesId === seriesId));- emitRecordUpdated('series', seriesId);- }- return results;- });-}--/**- * Restore a prior `runHistory` snapshot as the active stage state. Looks up the- * snapshot by `runId` against the freshest persisted record (so a concurrent- * generate can't make the chosen snapshot disappear out from under the call).- * The previous active state is itself snapshotted into runHistory by the normal- * lastRunId-changed trigger in `updateStageWithLatest`, so restore is just- * another version event — there's no special "rollback" semantics.- *- * Resolves with `{ issue, stage }`. Rejects with ERR_VALIDATION when the runId- * isn't present in the current runHistory.- */-export function restoreStageFromHistory(issueId, stageId, runId) {- if (!TEXT_STAGE_IDS.includes(stageId)) {- return Promise.reject(makeErr(`Stage "${stageId}" does not support history restore`, ERR_VALIDATION));- }- if (!isStr(runId) || !runId) {- return Promise.reject(makeErr('runId is required', ERR_VALIDATION));- }- return updateStageWithLatest(issueId, stageId, (cur) => {- const snapshot = (cur?.runHistory || []).find((entry) => entry.runId === runId);- if (!snapshot) throw makeErr(`Snapshot not found in stage history: ${runId}`, ERR_VALIDATION);- return {- status: 'edited',- input: snapshot.input || '',- output: snapshot.output || '',- lastRunId: snapshot.runId,- errorMessage: '',- };- });-}--export function deleteIssue(id) {- // Soft-delete — same tombstone-in-record pattern as universes/series. The- // record stays on disk with `deleted: true` so the next sync propagates the- // delete to peers; the orchestrator's GC sweep prunes it once all peers ack.- // `renumberInline` filters tombstones, so surviving issues stay contiguous.- return getIssue(id, { includeDeleted: true }).then((existing) =>- queueSeriesIssuesWrite(existing.seriesId, async () => {- const state = await readState();- const idx = state.issues.findIndex((i) => i.id === id);- if (idx < 0) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);- const cur = state.issues[idx];- if (cur.deleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);- const seriesId = cur.seriesId;- const now = new Date().toISOString();- state.issues[idx] = { ...cur, deleted: true, deletedAt: now, updatedAt: now };- await renumberInline(state, seriesId, cur.seasonId || UNSCOPED_ANCHOR);- await saveIssuesNow(state.issues.filter((i) => i.seriesId === seriesId));- // Series export bundles every issue, so a deletion is an update on the- // parent series for any active share-bucket subscription.- emitRecordUpdated('series', seriesId);- return { id, seriesId };- }).then(async (result) => {- // The deleted issue may have owned the series' list thumbnail- // (`series.coverImage`). Recompute outside the queue (it reads fresh- // post-delete state) so the Pipeline list falls back to the next eligible- // cover instead of pointing at a tombstone. Dynamic import dodges the- // static cycle (seriesCoverImage → issues). Best-effort — a cosmetic- // thumbnail must never fail the delete.- const { refreshSeriesCoverImage } = await import('./seriesCoverImage.js');- await refreshSeriesCoverImage(result.seriesId).catch(() => {});- return { id: result.id };- })- );-}--/**- * Like `updateStage`, but the patch is computed from the *latest* persisted- * stage inside the serialized write region. Use this when the patch value- * depends on the current stage state (e.g. cover preservation) so a concurrent- * write that lands between the outer `getIssue` read and this call is not- * silently overwritten.- *- * `computeFn(currentStage) → patch` — called with the freshest stage record- * inside the queue; its return value is shallow-merged over the stage exactly- * as `updateStage` merges a static patch.- */-export function updateStageWithLatest(issueId, stageId, computeFn, { snapshotPrior = false } = {}) {- if (!STAGE_IDS.includes(stageId)) {- // Validate before queueing so the caller gets an immediate rejection- // rather than waiting in line for an error it already knows about.- return Promise.reject(makeErr(`Unknown stage: ${stageId}`, ERR_VALIDATION));- }- // Serialize on the SERIES tail (not the per-id queue) so a stage save can't- // interleave with a series-wide renumber/bulk write that rewrites this same- // issue — both share one mutex per series. The per-record split (migrations- // 035/036) otherwise left renumbers on the series queue and stage saves on- // the per-id queue (two independent mutexes over the same shared resource);- // see CLAUDE.md "single tail per shared file". seriesId is immutable, so read- // it outside the lock to pick the queue, then re-read the issue INSIDE the- // lock for the freshest stage.- const work = async () => {- const cur = await store().loadOne(issueId);- if (!cur) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);- if (cur.deleted) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);- const currentStage = cur.stages[stageId];- const patch = computeFn(currentStage);- // Empty-patch fast path: a computeFn that returns `{}` is a "decided not- // to write" signal (e.g. stale media-job completion against a re-rendered- // page). Skip the disk write + emitRecordUpdated so it doesn't trigger- // a re-export storm in share subscriptions for late no-op events.- if (isPlainObject(patch) && Object.keys(patch).length === 0) {- return { issue: cur, stage: currentStage };- }- // Snapshot the prior `{ runId, input, output }` into runHistory when this- // patch carries a fresh lastRunId (i.e. a generate just replaced prior- // content). Computed BEFORE the spread so it reads pre-merge state.- const next = mergeStagePatch(currentStage, stageId, patch, { snapshotPrior });- const mergedIssue = sanitizeIssue({- ...cur,- stages: { ...cur.stages, [stageId]: next },- updatedAt: new Date().toISOString(),- });- await saveIssueNow(mergedIssue);- emitRecordUpdated('series', mergedIssue.seriesId);- return { issue: mergedIssue, stage: mergedIssue.stages[stageId] };- };- return getIssue(issueId, { includeDeleted: true }).then((existing) =>- queueSeriesIssuesWrite(existing.seriesId, work),- );-}--/**- * Sync-orchestrator entry point. Merges a remote peer's issues array into- * local state through the collection store's type-index queue for one- * consistent merge snapshot. Each incoming record passes through- * `sanitizeIssue` for shape enforcement (stage statuses, trimmed fields,- * valid id format). LWW by `updatedAt`; returns `{ applied, count }` where- * `count` is the number of issues actually changed/added.- */-export async function mergeIssuesFromSync(remoteIssues, { source = { via: 'sync', peerId: null } } = {}) {- if (!Array.isArray(remoteIssues)) return { applied: false, count: 0 };- // Series IDs whose issue set saw at least one delete-transition — drives a- // post-write renumber so the receiver's issue numbering catches up with the- // sender's (otherwise a synced tombstone would leave a gap).- //- // Edit-only merges (no delete-transitions) do NOT emit `recordUpdated` for- // the parent series — see `mergeUniversesFromSync` for the rationale (the- // Stage 2 per-record peer-sync push owns sync-time edit emits). Delete-- // transitions DO emit per series so subscribers know to drop the issue.- const seriesNeedingRenumber = new Set();- // Build the set of locally-ephemeral series ids BEFORE the queue. The- // per-record push pipeline (applyIncomingPush) already gates the bundled- // issues batch by parent-ephemeral, but the snapshot pipeline path- // (applyPipelineRemote → mergeIssuesFromSync) bypasses that check. Without- // this filter, a peer with `pipeline` sync enabled can create/update/- // tombstone issues under a locally-private series and overwrite the- // user's private fork.- const ephemeralSeriesIds = new Set(- (await seriesSvc.listSeries({ includeDeleted: true }).catch(() => []))- .filter((s) => s?.ephemeral === true)- .map((s) => s.id),- );- return store().queueTypeIndexWrite(async () => {- const state = await readState();- const localById = new Map(state.issues.map((i) => [i.id, i]));- let changed = 0;- // Track only the issue IDs that were inserted or overwritten so we persist- // the changed subset rather than every issue in the store (avoids unbounded- // Promise.all / EMFILE on large catalogs).- const changedIds = new Set();- for (const remote of remoteIssues) {- if (!remote || typeof remote !== 'object' || !isStr(remote.id)) continue;- // Drop issues whose parent series is locally ephemeral, BEFORE any- // mutation. This covers create/update/tombstone uniformly — the- // sanitized.seriesId may be either the existing local series or a- // remote-only target; reject either way.- if (ephemeralSeriesIds.has(remote.seriesId)) continue;- const sanitized = sanitizeIssue(remote);- if (!sanitized) continue;- // Strip inbound `ephemeral` — see mergeUniversesFromSync.- if ('ephemeral' in sanitized) delete sanitized.ephemeral;- const local = localById.get(sanitized.id);- // Belt-and-suspenders: if the existing local issue belongs to an- // ephemeral series, refuse the merge even though the inbound- // sanitized.seriesId might point elsewhere (a peer could ship an- // issue id whose local copy is under a private series and try to- // move it).- if (local && ephemeralSeriesIds.has(local.seriesId)) continue;- if (!local) {- // No local counterpart — accept the record but don't trigger a- // renumber pass. A tombstone for an issue we never had has nothing- // to compact; firing `emitRecordUpdated('series', …)` for a series- // we may not even own would spuriously re-export.- localById.set(sanitized.id, sanitized);- // Seed the conflict-journal base hash so a FUTURE divergence on this- // issue is detected. Issues are pushed under their parent series'- // subscription, so peerSync never seeds an `issue`-keyed base hash —- // this merge path (and the importer) own it.- await setSyncBaseHash('issue', sanitized.id, contentHashForRecord('issue', sanitized));- changedIds.add(sanitized.id);- changed++;- } else if (local.ephemeral === true) {- // Local-ephemeral issues are immune to inbound merges. See- // mergeUniversesFromSync for the contract.- continue;- } else {- const localTs = local.updatedAt || '';- const remoteTs = sanitized.updatedAt || '';- if (remoteTs > localTs) {- // Non-blocking conflict journal — archive the losing local issue on- // a true 3-way divergence; always advances the base hash. Never- // throws into the merge (convergence wins).- await maybeJournalBeforeOverwrite({ kind: 'issue', id: sanitized.id, local, remote: sanitized, source });- localById.set(sanitized.id, sanitized);- changedIds.add(sanitized.id);- // Renumber on EITHER direction of the transition: a delete leaves- // a gap, a resurrection (deleted→live) reintroduces a previously-- // compacted number and can collide with live siblings until some- // unrelated edit triggers a renumber. Cover both here.- if (sanitized.deleted !== local.deleted) {- seriesNeedingRenumber.add(sanitized.seriesId);- // A resurrection may move from the OLD seriesId to a different- // one in the inbound record (rare, but possible) — renumber both.- if (local.seriesId && local.seriesId !== sanitized.seriesId) {- seriesNeedingRenumber.add(local.seriesId);- }- }- changed++;- }- }- }- if (changed === 0) return { applied: false, count: 0 };- state.issues = Array.from(localById.values());- // Compact issue numbers for each affected series — the merge may have- // tombstoned (gap) or resurrected (collision) an issue. renumberInline- // skips tombstones, so the resulting numbering is always contiguous- // across live issues. Single renumber per series, all inside the queue.- // renumberInline updates state.issues in-place; collect the renumbered- // issue ids so they are also persisted.- for (const seriesId of seriesNeedingRenumber) {- const before = new Map(state.issues.map((i) => [i.id, i.number]));- await renumberInline(state, seriesId, null);- for (const i of state.issues) {- if (i.seriesId === seriesId && i.number !== before.get(i.id)) {- changedIds.add(i.id);- }- }- }- // Persist only the issues that were actually changed/renumbered, not the- // entire catalog — avoids EMFILE + write-amplification on large stores.- const changedIssues = state.issues.filter((i) => changedIds.has(i.id));- await saveIssuesNow(changedIssues);- // Re-emit a series-updated for each touched series so any active share- // subscription re-exports the post-merge issue set.- for (const seriesId of seriesNeedingRenumber) {- emitRecordUpdated('series', seriesId);- }- // Persist the batched conflict-journal base-hash updates (seeds on insert,- // advances on overwrite) accumulated in the loop above.- await flushBaseHashes();- return { applied: true, count: changed };- });-}--/**- * Garbage-collect issue tombstones older than `beforeMs`. See- * `pruneTombstonedUniverses` for the contract — pure mechanical prune; the- * caller owns the policy. Tombstones with unparseable `deletedAt` are kept.- *- * Issue tombstones ride series pushes (the receiver bundles child issues- * with each series push) so the relevant ack horizon is "peers subscribed- * to the parent series." The caller resolves that.- */-export async function pruneTombstonedIssues(beforeMs) {- if (!Number.isFinite(beforeMs)) return { pruned: 0 };- return store().queueTypeIndexWrite(async () => {- const { issues } = await readState();- const prunable = issues.filter((i) => {- if (!i?.deleted) return false;- const t = Date.parse(i.deletedAt || '');- if (!Number.isFinite(t)) return false;- return t < beforeMs;- });- await Promise.all(prunable.map((i) => store().deleteOne(i.id)));- // Evict each pruned issue's conflict-journal base hash. Issues seed an- // `issue:<id>` base hash when their parent series is pushed (peerSync's- // pushRecordToPeer), but no eviction existed — so a pruned issue's key- // would linger in sync_base_hashes.json forever. Mirrors the universe /- // series / collection prune paths.- await Promise.all(prunable.map((i) => deleteSyncBaseHash('issue', i.id)));- return { pruned: prunable.length };- });-}+export * from './issuesShared.js';+export * from './issueCrud.js';+export * from './issueStages.js';+export * from './issueSync.js';diff --git a/server/services/pipeline/issuesShared.js b/server/services/pipeline/issuesShared.jsnew file mode 100644index 0000000000..9b10435296--- /dev/null+++ b/server/services/pipeline/issuesShared.js@@ -0,0 +1,683 @@+/**+ * Pipeline — Issues shared store/queue + record sanitizers (#2531)+ *+ * Split out of the former monolithic `issues.js` so `issueCrud` / `issueStages`+ * / `issueSync` can share ONE store facade, ONE per-series write queue, and ONE+ * set of record sanitizers. This module owns:+ *+ * - the storage-backend dispatcher `store()` (issuesStore/store.js facade),+ * - the per-series write tail `queueSeriesIssuesWrite` (single tail per+ * seriesId — see the note on the queue below; two writes to different+ * issues in the same series share the series-level index and MUST collapse+ * to one tail),+ * - the record + stage sanitizers (sanitizeIssue and friends),+ * - the read/save helpers (readState / saveIssueNow / …) and renumberInline.+ *+ * An Issue (or Episode — same record, two formats) is a child of a Series and+ * carries the full per-stage state of one production pipeline run. Persisted to+ * data/pipeline-issues/{id}/index.json (PG-backed via the store facade).+ */++import { getIssuesStore } from './issuesStore/store.js';+import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';+import { IMAGE_GEN_MODE } from '../imageGen/modes.js';+import {+ LENGTH_PROFILE_NAMES, DEFAULT_LENGTH_PROFILE,+ CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX,+} from '../../lib/issueLength.js';+import { sanitizeOrigin } from '../../lib/sharingOrigin.js';+import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';+import { ServerError } from '../../lib/errorHandler.js';+import { ARC_ROLES } from '../../lib/storyArc.js';+import { isStr, trimTo } from '../../lib/storyBible.js';+import { sanitizeCoverLike } from '../../lib/renderSlot.js';+import { applyVolumeOrderedNumbers } from '../../lib/pipelineIssueOrder.js';+import * as seriesSvc from './series.js';++// Storage backend dispatcher (#1015). Issue records moved from per-record+// `data/pipeline-issues/{id}/index.json` (collectionStore) to one-row-per-issue+// in PostgreSQL (`pipeline_issues`); the facade is a drop-in for the+// collectionStore surface this service calls (loadAll/loadOne/saveOneNow/+// deleteOne/queueTypeIndexWrite), so only this factory changed.+const store = () => getIssuesStore(sanitizeIssue);++export const issueStore = () => store();++// Series-scoped write queue. ALL issue mutations — create, per-issue PATCH,+// stage writes, deletes, and sibling-renumbering ops — route through this so+// they serialize per series. Even though collectionStore keeps a per-id queue,+// per-issue edits still share the series-level `index.json` (numbering, ordering),+// so two concurrent writes to *different* issues in the same series could read a+// stale index and clobber each other. A single tail per seriesId collapses that+// race: each write awaits the previous one and merges against the freshest state.+const seriesIssueQueue = createKeyCachedQueue();+function queueSeriesIssuesWrite(seriesId, fn) {+ const key = typeof seriesId === 'string' && seriesId ? seriesId : '__unknown__';+ return seriesIssueQueue(key, fn);+}++export const ERR_NOT_FOUND = 'PIPELINE_ISSUE_NOT_FOUND';+export const ERR_VALIDATION = 'PIPELINE_ISSUE_VALIDATION';+export const ERR_DUPLICATE = 'PIPELINE_ISSUE_DUPLICATE';+export const ERR_SEASON_LOCKED = 'PIPELINE_ISSUE_SEASON_LOCKED';+export const ERR_STAGE_LOCKED = 'PIPELINE_STAGE_LOCKED';+const makeErr = (message, code) => Object.assign(new Error(message), { code });++const ISSUE_ID_RE = /^iss-[A-Za-z0-9-]+$/;++export const TITLE_MAX = 300;+export const SERIES_ID_MAX = 64;+export const SEASON_ID_MAX = 64;+// Issues fall back to position 0 when un-numbered; the cap keeps a runaway+// LLM payload from inflating the field unbounded.+export const ARC_POSITION_MAX = 9999;+export const STAGE_INPUT_MAX = 200_000; // ~200kB — fits a long prose draft+export const STAGE_OUTPUT_MAX = 400_000; // ~400kB — fits a long comic script+export const STAGE_NOTES_MAX = 4000;+export const ISSUES_PER_RESPONSE_MAX = 1000;+// How many prior versions of a text stage to retain for the diff modal.+// Each entry holds the full prior input+output, so the upper bound is+// N × (STAGE_INPUT_MAX + STAGE_OUTPUT_MAX) per stage. Five keeps a useful+// undo trail without ballooning pipeline-issues.json. Only text stages+// snapshot — visual/audio artifact shapes (pages[]/scenes[]/lines[]) aren't+// meaningfully diffable as plain text; see snapshot gating in+// updateStageWithLatest + updateIssue.+export const STAGE_RUN_HISTORY_MAX = 5;++// Stage IDs are ordered for UI display; the canonical order is also the+// auto-run text-chain order (idea → prose → scripts in parallel). Comic+// pages / storyboards / episode video stages are visual and stay manual+// in MVP.+export const TEXT_STAGE_IDS = Object.freeze(['idea', 'prose', 'comicScript', 'teleplay']);+export const VISUAL_STAGE_IDS = Object.freeze(['comicPages', 'storyboards', 'episodeVideo']);+// Audio is its own category — voice-over lines + music. Feature-gated on+// series.targetFormat (only meaningful when the series ships video, not+// comic-only). Kept separate from VISUAL_STAGE_IDS so the artifact shape+// (`lines[]`, `music`) stays distinct from visual stages.+export const AUDIO_STAGE_IDS = Object.freeze(['audio']);+export const STAGE_IDS = Object.freeze([...TEXT_STAGE_IDS, ...VISUAL_STAGE_IDS, ...AUDIO_STAGE_IDS]);+// Stages exposed to voice navigation ("next stage" / "previous stage" tools)+// and the tab strip. Includes audio now that the AudioStage UI is wired.+export const NAVIGABLE_STAGE_IDS = Object.freeze([...TEXT_STAGE_IDS, ...VISUAL_STAGE_IDS, ...AUDIO_STAGE_IDS]);++// "This stage has usable content and shouldn't be regenerated by default."+// `edited` = user typed into the editor; `ready` = LLM filled and the user+// hasn't asked to rerun. Both are good — auto-runners skip past them unless+// `force` is set. Defined here so every coordinator agrees on the predicate.+export function isStageReady(stage) {+ if (!stage) return false;+ if (stage.status !== 'ready' && stage.status !== 'edited') return false;+ return !!(stage.output && stage.output.trim());+}+export const STAGE_STATUSES = Object.freeze(['empty', 'generating', 'ready', 'edited', 'needs-review', 'error']);+export const ISSUE_STATUSES = Object.freeze(['draft', 'running', 'needs-review', 'shipped']);++const emptyStage = () => ({+ status: 'empty',+ input: '',+ output: '',+ lastRunId: null,+ errorMessage: '',+ updatedAt: null,+ locked: false,+ // Most-recent-first list of prior `{ runId, createdAt, input, output }`+ // snapshots, capped at STAGE_RUN_HISTORY_MAX. Populated only for text+ // stages — visual/audio stages keep the field as [] for shape parity.+ runHistory: [],+});++/**+ * Throw a 400 ServerError when `issue.stages[stageId].locked === true`.+ * Every code path that regenerates a stage's primary artifact (LLM text run,+ * image render, video render, audio synth, refine-prompt, extract-scenes /+ * extract-pages) must call this so the lock contract is uniform. Sibling to+ * the series-level (`series.locked.arc`) and season-level (`season.locked`)+ * checks elsewhere — any of the three rejects.+ */+export function assertStageUnlocked(issue, stageId) {+ if (issue?.stages?.[stageId]?.locked === true) {+ throw new ServerError(+ `Stage "${stageId}" is locked — unlock it before regenerating`,+ { status: 400, code: ERR_STAGE_LOCKED },+ );+ }+}++const sanitizeRunHistoryEntry = (raw) => {+ if (!raw || typeof raw !== 'object') return null;+ const runId = isStr(raw.runId) && raw.runId ? raw.runId : null;+ if (!runId) return null;+ return {+ runId,+ createdAt: isStr(raw.createdAt) && raw.createdAt ? raw.createdAt : null,+ input: trimTo(raw.input, STAGE_INPUT_MAX),+ output: trimTo(raw.output, STAGE_OUTPUT_MAX),+ };+};++const sanitizeRunHistory = (raw) => {+ if (!Array.isArray(raw)) return [];+ return raw+ .map(sanitizeRunHistoryEntry)+ .filter(Boolean)+ .slice(0, STAGE_RUN_HISTORY_MAX);+};++export const CANON_EXTRACTION_STATUSES = Object.freeze(['ok', 'partial', 'failed']);+const CANON_KINDS = Object.freeze(['character', 'place', 'object']);++// Normalize a canon-extraction outcome marker. Returns `null` for absent /+// malformed input (the "never attempted" state) so the field stays falsy in+// the UI until a real extraction runs. `extracted` counts are coerced to+// non-negative integers; `failedKinds` is filtered to the known kinds.+const sanitizeCanonExtraction = (raw) => {+ if (!raw || typeof raw !== 'object') return null;+ if (!CANON_EXTRACTION_STATUSES.includes(raw.status)) return null;+ const count = (v) => (Number.isFinite(v) && v > 0 ? Math.floor(v) : 0);+ const ex = raw.extracted && typeof raw.extracted === 'object' ? raw.extracted : {};+ return {+ status: raw.status,+ error: trimTo(raw.error, STAGE_NOTES_MAX),+ failedKinds: Array.isArray(raw.failedKinds)+ ? [...new Set(raw.failedKinds.filter((k) => CANON_KINDS.includes(k)))]+ : [],+ extracted: {+ characters: count(ex.characters),+ places: count(ex.places),+ objects: count(ex.objects),+ },+ provider: trimTo(raw.provider, 80),+ model: trimTo(raw.model, 128),+ at: isStr(raw.at) ? raw.at : null,+ };+};++// Persisted outcome of the last strictly-prose-grounded "describe nouns from+// prose" run (see universeCanon.describeCanonFromProse). `null` = never run.+// `none`/`thin` carry the nouns the manuscript couldn't (or only thinly)+// describe so the Nouns UI can render a persistent manuscript-quality banner.+const sanitizeDescGapList = (arr) => (Array.isArray(arr) ? arr : [])+ .filter((g) => g && typeof g === 'object' && CANON_KINDS.includes(g.kind))+ .slice(0, 200)+ .map((g) => ({+ id: trimTo(g.id, 80),+ name: trimTo(g.name, 200),+ kind: g.kind,+ note: trimTo(g.note, 600),+ }));++const sanitizeDescGaps = (raw) => {+ if (!raw || typeof raw !== 'object') return null;+ return {+ at: isStr(raw.at) ? raw.at : null,+ provider: trimTo(raw.provider, 80),+ model: trimTo(raw.model, 128),+ filled: Number.isFinite(raw.filled) && raw.filled > 0 ? Math.floor(raw.filled) : 0,+ none: sanitizeDescGapList(raw.none),+ thin: sanitizeDescGapList(raw.thin),+ skippedLocked: sanitizeDescGapList(raw.skippedLocked),+ };+};++const sanitizeStage = (raw) => {+ if (!raw || typeof raw !== 'object') return emptyStage();+ const status = STAGE_STATUSES.includes(raw.status) ? raw.status : 'empty';+ return {+ status,+ input: trimTo(raw.input, STAGE_INPUT_MAX),+ output: trimTo(raw.output, STAGE_OUTPUT_MAX),+ lastRunId: isStr(raw.lastRunId) && raw.lastRunId ? raw.lastRunId : null,+ errorMessage: trimTo(raw.errorMessage, STAGE_NOTES_MAX),+ updatedAt: isStr(raw.updatedAt) ? raw.updatedAt : null,+ // Per-stage editorial lock. When true, `generateStage` (text) and the+ // visual stage `enqueueXxx` entry points refuse — lets the user freeze a+ // finalized comic script while still iterating storyboards. Independent+ // of `series.locked.arc` and `season.locked`; any of the three rejects.+ locked: raw.locked === true,+ runHistory: sanitizeRunHistory(raw.runHistory),+ };+};++// Text stages (idea/prose/comicScript/teleplay) carry one extra field beyond+// the shared stage shape: `canonExtraction`, the persisted outcome of the last+// characters/places/objects extraction run against the stage output (used on+// `prose`). Layered here rather than in `sanitizeStage` so visual/audio shapes+// never inherit a concern that doesn't apply to them. `null` = never attempted.+// Per-attempt record of the last multi-candidate draft-gate run (#2169, CWQE+// Phase 5). `null` = the gate never ran (single-shot generation, the default).+// Each attempt carries its runId (so its full text is recoverable from+// runHistory) + the composite qualityScore it was judged at, and `winner` names+// the kept attempt's runId — so the UI can show "kept 8.1, rejected 6.4 / 5.9".+const sanitizeDraftGate = (raw) => {+ if (!raw || typeof raw !== 'object' || !Array.isArray(raw.attempts)) return null;+ const num = (v) => (Number.isFinite(v) ? Math.round(v * 100) / 100 : null);+ const attempts = raw.attempts+ .filter((a) => a && typeof a === 'object' && isStr(a.runId) && a.runId)+ .slice(0, STAGE_RUN_HISTORY_MAX)+ .map((a) => ({+ runId: a.runId,+ qualityScore: num(a.qualityScore),+ overall: num(a.overall),+ slopPenalty: num(a.slopPenalty),+ rejected: a.rejected === true,+ }));+ if (!attempts.length) return null;+ return {+ winner: isStr(raw.winner) && raw.winner ? raw.winner : null,+ threshold: num(raw.threshold),+ attempts,+ stoppedEarly: raw.stoppedEarly === true,+ at: isStr(raw.at) ? raw.at : null,+ };+};++const sanitizeTextStage = (raw) => ({+ ...sanitizeStage(raw),+ canonExtraction: sanitizeCanonExtraction(raw?.canonExtraction),+ descGaps: sanitizeDescGaps(raw?.descGaps),+ draftGate: sanitizeDraftGate(raw?.draftGate),+});++/**+ * Decide whether `patch` represents a generate-replacement on `prevStage` and,+ * if so, prepend a snapshot of the prior state to `prevStage.runHistory`.+ * Returns the new runHistory array (capped at STAGE_RUN_HISTORY_MAX).+ *+ * Trigger conditions (ALL must hold):+ * - `stageId` is in TEXT_STAGE_IDS — visual + audio shapes don't snapshot.+ * - patch.lastRunId is a non-empty string that differs from prevStage.lastRunId.+ * - prevStage.lastRunId is set AND prevStage.output is non-empty — there's+ * prior content worth preserving for diff/restore.+ *+ * Skipped triggers (and why):+ * - First-time generate (prev.lastRunId === null) — nothing to snapshot.+ * - status: 'generating' transition — patch carries no new lastRunId yet.+ * - status: 'error' from a failed LLM throw — patch carries no new lastRunId.+ * - Save-edit (PATCH with input/output but no lastRunId) — caller explicitly+ * editing the existing version, not replacing it. The previous run remains+ * the active version; the next generate will snapshot it.+ */+export function snapshotRunHistory(prevStage, patch, stageId, { force = false } = {}) {+ const prevHistory = Array.isArray(prevStage?.runHistory) ? prevStage.runHistory : [];+ if (!patch || typeof patch !== 'object') return prevHistory;+ if (!TEXT_STAGE_IDS.includes(stageId)) return prevHistory;+ const nextRunId = isStr(patch.lastRunId) ? patch.lastRunId : '';+ if (!nextRunId) return prevHistory;+ if (nextRunId === prevStage?.lastRunId) return prevHistory;+ // Default: only snapshot a prior that was itself a recorded run (keeps the+ // first generate from snapshotting an empty/seed-only stage). With `force`+ // (manuscript-editor edits), snapshot ANY non-empty prior, synthesizing an id+ // when the prior was never a run — so imported/hand-typed text stays+ // revertible from its very first edit.+ if (!prevStage?.lastRunId && !force) return prevHistory;+ const prevOutput = prevStage?.output || '';+ if (!prevOutput.trim()) return prevHistory;+ const snapshot = {+ runId: prevStage.lastRunId || `pre-${nextRunId}`,+ createdAt: prevStage.updatedAt || new Date().toISOString(),+ input: prevStage.input || '',+ output: prevOutput,+ };+ // Drop any prior entry whose runId matches the now-active runId. This is+ // the restore case: snapshot r1 → user restores r1 → r1 becomes the active+ // runId AND is still sitting in prevHistory. Without the filter the next+ // regenerate would push the just-displaced state and leave a duplicate+ // r1 in the list, breaking React keys and making restore-by-runId+ // ambiguous (which r1 to apply?).+ const dedupedPrior = prevHistory.filter((entry) => entry.runId !== nextRunId);+ return [snapshot, ...dedupedPrior].slice(0, STAGE_RUN_HISTORY_MAX);+}++// Strip per-stage `runHistory` from a sanitized issue so list-shaped+// endpoints can opt out of shipping each stage's full version history. Text+// stages can hold up to STAGE_RUN_HISTORY_MAX (5) entries × ~600KB each, so+// a maxed-out issue is ~12MB of payload that the sidebar + per-series list+// never render. Opt-in via `withHistory: false` on `listIssues` /+// `listRecentIssues` — the default is full-shape because internal callers+// (notably `exportSeries`) round-trip every stored field through the bucket+// export, and dropping history there would lose it on the receiving peer.+const stripRunHistoryFromIssue = (issue) => {+ if (!issue || typeof issue !== 'object' || !issue.stages) return issue;+ const strippedStages = {};+ for (const [stageId, stage] of Object.entries(issue.stages)) {+ strippedStages[stageId] = stage?.runHistory?.length ? { ...stage, runHistory: [] } : stage;+ }+ return { ...issue, stages: strippedStages };+};++// Episode-video render settings the user chose at kickoff time. Persisted+// on the stage so a page reload doesn't reset them to the defaults — the+// restart flow can render the same pickers populated with the user's+// previous choice. The CD project itself owns the authoritative values once+// rendering starts; these are the *requested* settings for the next start.+const ASPECT_RATIO_VALUES = new Set(['16:9', '9:16', '1:1']);+const QUALITY_VALUES = new Set(['draft', 'standard', 'high']);++// `imageMode: 'auto'` defers to the server resolver (codex when enabled,+// local otherwise). Returns null when nothing was set so the persisted+// JSON stays clean for issues that never opened the panel.+const IMAGE_MODE_VALUES = new Set(['auto', IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX]);+const GEN_CONFIG_STR_MAX = 200;+const sanitizeGenConfig = (raw) => {+ if (!raw || typeof raw !== 'object') return null;+ const imageMode = IMAGE_MODE_VALUES.has(raw.imageMode) ? raw.imageMode : 'auto';+ // imageModelId is only meaningful for local diffusion — clear it for other+ // modes so a previously-pinned model doesn't silently persist in the config+ // and mislead the UI or any future reader that doesn't filter by mode.+ const imageModelId = imageMode === IMAGE_GEN_MODE.LOCAL+ ? (trimTo(raw.imageModelId, GEN_CONFIG_STR_MAX) || null)+ : null;+ const refineProvider = trimTo(raw.refineProvider, GEN_CONFIG_STR_MAX) || null;+ const refineModel = trimTo(raw.refineModel, GEN_CONFIG_STR_MAX) || null;+ // Trained character-LoRA auto-apply opt-out. Default ON — only an explicit+ // false persists, so issues that never touched the toggle stay clean.+ const applyCharacterLoras = raw.applyCharacterLoras !== false;+ if (imageMode === 'auto' && !imageModelId && !refineProvider && !refineModel && applyCharacterLoras) {+ return null;+ }+ return { imageMode, imageModelId, refineProvider, refineModel, applyCharacterLoras };+};++// 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 (lib/renderSlot.js) the same way+// the cover does.++const sanitizeVisualStage = (raw, stageId = null) => {+ // Visual stages keep arbitrary structured artifact lists. Sanitize the+ // wrapper but pass through known shapes. `canonExtraction` is text-stage-only+ // (it lives on `sanitizeTextStage`), so the visual shape never carries it.+ const base = sanitizeStage(raw);+ return {+ ...base,+ pages: Array.isArray(raw?.pages) ? raw.pages.slice(0, 200) : [],+ scenes: Array.isArray(raw?.scenes) ? raw.scenes.slice(0, 200) : [],+ cdProjectId: isStr(raw?.cdProjectId) && raw.cdProjectId ? raw.cdProjectId : null,+ videoPath: isStr(raw?.videoPath) && raw.videoPath ? raw.videoPath : null,+ aspectRatio: ASPECT_RATIO_VALUES.has(raw?.aspectRatio) ? raw.aspectRatio : null,+ quality: QUALITY_VALUES.has(raw?.quality) ? raw.quality : null,+ // Video model id — only meaningful on episodeVideo (it picks the per-scene+ // render engine). Dropped on comicPages/storyboards so the contract is+ // explicit, but kept when stageId is omitted (legacy load-time sanitize+ // has no per-stage context). `null` = use the server/settings default.+ modelId: (stageId === null || stageId === 'episodeVideo') && isStr(raw?.modelId) && raw.modelId+ ? raw.modelId.slice(0, 64)+ : 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` 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,+ };+};++// Audio stage shape — dialogue VO lines + optional background music. Each+// line carries the source character + the actual line text + the render job+// id + a server-stamped filename (the storyboards filename hook's pattern+// will be extended to audio in a follow-up). `voiceIdOverride` lets a single+// line use a different voice than the character's default (narrator V.O.,+// flashback voice, etc.).+const AUDIO_LINE_TEXT_MAX = 4000;+const AUDIO_LINES_MAX = 1000;+export const AUDIO_FILENAME_MAX = 500;+const AUDIO_LINE_ID_MAX = 80;+// Cap a per-line VO offset at a generous episode length so a corrupted record+// can't push an `adelay` filter into absurd territory. Two hours is far beyond+// any single issue's runtime.+const AUDIO_LINE_OFFSET_MAX_SEC = 7200;+// Normalize a per-line start offset (seconds into the stitched episode where+// this VO line plays). `null` = "not placed yet" — kept distinct from `0`+// ("plays at the very start") so the muxer can skip un-placed lines instead of+// stacking them all at t=0. Negative / non-finite input collapses to null.+export const sanitizeLineOffset = (raw) => {+ if (raw === null || raw === undefined) return null;+ const n = Number(raw);+ if (!Number.isFinite(n) || n < 0) return null;+ return Math.min(n, AUDIO_LINE_OFFSET_MAX_SEC);+};+const sanitizeAudioLine = (raw, i) => {+ if (!raw || typeof raw !== 'object') return null;+ const text = trimTo(raw.text, AUDIO_LINE_TEXT_MAX);+ if (!text) return null;+ const id = trimTo(raw.id, AUDIO_LINE_ID_MAX) || `line-${String(i + 1).padStart(3, '0')}`;+ return {+ id,+ characterId: trimTo(raw.characterId, 80) || null,+ characterName: trimTo(raw.characterName, 120) || null,+ text,+ voiceIdOverride: trimTo(raw.voiceIdOverride, 200) || null,+ audioJobId: isStr(raw.audioJobId) && raw.audioJobId ? raw.audioJobId : null,+ audioFilename: isStr(raw.audioFilename) && raw.audioFilename+ ? raw.audioFilename.slice(0, AUDIO_FILENAME_MAX)+ : null,+ // Per-line start offset for muxing VO into the stitched episode (Phase+ // 4d.2). null until the user (or a future auto-spacer) places it.+ offsetSec: sanitizeLineOffset(raw.offsetSec),+ };+};++const MUSIC_SOURCES = new Set(['upload', 'library', 'gen']);+const sanitizeMusicTrack = (raw) => {+ if (!raw || typeof raw !== 'object') return null;+ const source = MUSIC_SOURCES.has(raw.source) ? raw.source : null;+ const trackFilename = trimTo(raw.trackFilename, AUDIO_FILENAME_MAX) || null;+ const label = trimTo(raw.label, 200) || null;+ if (!source && !trackFilename && !label) return null;+ return { source, trackFilename, label };+};++// Which strategy drives the episode's non-dialogue audio (whole-episode audio,+// issue #863 / design doc 2026-06-03-whole-episode-audio-strategy.md):+// per-clip — keep each stitched clip's own soundtrack (today's default)+// silent — strip any bed+// generated — assemble the arc-driven cues[] onto the timeline+// uploaded-track — loop the single `music` pointer under the whole episode+export const AUDIO_MODES = Object.freeze(['per-clip', 'silent', 'generated', 'uploaded-track']);+// Read-side default: an absent / unknown audioMode collapses to 'per-clip' —+// today's behavior — so an un-migrated record (or one synced from an older,+// audioMode-unaware peer) reads correctly before migration 067 stamps the+// explicit value. Never let "absent" become a wrong mode (CLAUDE.md sentinel+// discipline).+export const sanitizeAudioMode = (raw) => (AUDIO_MODES.includes(raw) ? raw : 'per-clip');++// Per-cue field caps. Exported so the route's light Zod arm references the+// same numbers (the sanitizer below is authoritative; the route only guards+// against payload ballooning) and can't silently drift if these change.+export const AUDIO_CUE_ID_MAX = 80;+export const AUDIO_CUE_LABEL_MAX = 200;+export const AUDIO_CUE_PROMPT_MAX = 8000;+export const AUDIO_CUE_ENGINE_MAX = 80;+export const AUDIO_CUES_MAX = 200;++// Per-cue gain override. `null` = "use the stage / global default", distinct+// from `0` ("muted"). Clamped to a sane 0..4 range so a corrupted value can't+// blow out the mix.+const sanitizeCueGain = (raw) => {+ if (raw === null || raw === undefined) return null;+ const n = Number(raw);+ if (!Number.isFinite(n) || n < 0) return null;+ return Math.min(n, 4);+};++const sanitizeAudioCue = (raw, i) => {+ if (!raw || typeof raw !== 'object') return null;+ const id = trimTo(raw.id, AUDIO_CUE_ID_MAX) || `cue-${String(i + 1).padStart(3, '0')}`;+ return {+ id,+ label: trimTo(raw.label, AUDIO_CUE_LABEL_MAX) || null,+ prompt: trimTo(raw.prompt, AUDIO_CUE_PROMPT_MAX) || null,+ // Engine id (musicgen | audioldm2 | suno | …). Free-form trimmed string so+ // a future pluggable engine works without a sanitizer change — the render+ // route resolves it against the live ENGINES registry. null = "unset".+ engine: trimTo(raw.engine, AUDIO_CUE_ENGINE_MAX) || null,+ // Reuse sanitizeLineOffset for cue timing: identical null-vs-0 sentinel+ // ("not placed yet" vs "plays at start") and 2h cap as VO line offsets.+ // durationSec is "not rendered yet" (null) → actual length once rendered.+ startSec: sanitizeLineOffset(raw.startSec),+ endSec: sanitizeLineOffset(raw.endSec),+ trackFilename: isStr(raw.trackFilename) && raw.trackFilename+ ? raw.trackFilename.slice(0, AUDIO_FILENAME_MAX)+ : null,+ durationSec: sanitizeLineOffset(raw.durationSec),+ gain: sanitizeCueGain(raw.gain),+ };+};++const sanitizeAudioStage = (raw) => {+ // `canonExtraction` is text-stage-only (see sanitizeTextStage) — the audio+ // shape never carries it.+ const base = sanitizeStage(raw);+ return {+ ...base,+ lines: Array.isArray(raw?.lines)+ ? raw.lines.slice(0, AUDIO_LINES_MAX).map(sanitizeAudioLine).filter(Boolean)+ : [],+ music: sanitizeMusicTrack(raw?.music),+ audioMode: sanitizeAudioMode(raw?.audioMode),+ cues: Array.isArray(raw?.cues)+ ? raw.cues.slice(0, AUDIO_CUES_MAX).map(sanitizeAudioCue).filter(Boolean)+ : [],+ };+};++const sanitizeStages = (raw = {}) => {+ const out = {};+ for (const id of TEXT_STAGE_IDS) out[id] = sanitizeTextStage(raw[id]);+ for (const id of VISUAL_STAGE_IDS) out[id] = sanitizeVisualStage(raw[id], id);+ for (const id of AUDIO_STAGE_IDS) out[id] = sanitizeAudioStage(raw[id]);+ return out;+};++const sanitizeIssue = (raw) => {+ if (!raw || typeof raw !== 'object') return null;+ if (!isStr(raw.id) || !raw.id) return null;+ if (!isStr(raw.seriesId) || !raw.seriesId) return null;+ const title = trimTo(raw.title, TITLE_MAX);+ if (!title) return null;+ const number = Number.isFinite(raw.number) ? Math.max(0, Math.floor(raw.number)) : 0;+ const status = ISSUE_STATUSES.includes(raw.status) ? raw.status : 'draft';+ const createdAt = isStr(raw.createdAt) ? raw.createdAt : new Date().toISOString();+ const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;+ // Phase 2 of Story Arc Planning: optional pointer back into the parent+ // series' arc tree. `null` is the back-compat default — every pre-existing+ // issue stays un-grouped until the user (or LLM-arc-generation) assigns it.+ const seasonId = isStr(raw.seasonId) && raw.seasonId+ ? trimTo(raw.seasonId, SEASON_ID_MAX)+ : null;+ const arcPosition = Number.isFinite(raw.arcPosition)+ ? Math.max(0, Math.min(ARC_POSITION_MAX, Math.floor(raw.arcPosition)))+ : null;+ // LLM-assigned role within the volume — drives beat-sheet cadence+ // (finale vs. complication need very different shapes).+ const arcRole = ARC_ROLES.includes(raw.arcRole) ? raw.arcRole : null;+ // Defaults to 'standard' so pre-field issues keep the prior 22pg/24min sizing.+ // pageTarget/minutesTarget are only consumed when lengthProfile==='custom',+ // but we persist them on every profile so the picker can remember a previous+ // custom value if the user toggles back. Bounds mirror the values+ // `computeIssueTargets` clamps to at render time — otherwise the persisted+ // record could disagree with the prompt-rendered length.+ const lengthProfile = LENGTH_PROFILE_NAMES.includes(raw.lengthProfile)+ ? raw.lengthProfile+ : DEFAULT_LENGTH_PROFILE;+ const pageTarget = Number.isFinite(raw.pageTarget)+ ? Math.max(CUSTOM_PAGE_MIN, Math.min(CUSTOM_PAGE_MAX, Math.round(raw.pageTarget)))+ : null;+ const minutesTarget = Number.isFinite(raw.minutesTarget)+ ? Math.max(CUSTOM_MINUTE_MIN, Math.min(CUSTOM_MINUTE_MAX, Math.round(raw.minutesTarget)))+ : null;+ return {+ id: raw.id,+ seriesId: trimTo(raw.seriesId, SERIES_ID_MAX),+ number,+ title,+ status,+ seasonId,+ arcPosition,+ arcRole,+ lengthProfile,+ pageTarget,+ minutesTarget,+ stages: sanitizeStages(raw.stages || {}),+ // Share-bucket provenance — present on imported records, absent on locally-authored ones.+ origin: sanitizeOrigin(raw.origin),+ createdAt,+ updatedAt,+ // Soft-delete fields — see universeBuilder.sanitizeTemplate.+ ...sanitizeSoftDeleteFields(raw),+ // Local-only "don't sync to peers" marker. Issues piggyback on their+ // parent series' subscription, so marking an issue ephemeral keeps the+ // series push payload from carrying it (sanitizeRecordForWire drops it+ // and the series's bundled-issues filter discards the null entry).+ ...(raw.ephemeral === true ? { ephemeral: true } : {}),+ };+};++async function readState() {+ return { issues: await store().loadAll() };+}++// Series-scoped read — uses the indexed `idx_issues_series` query (PG) so a+// per-series scan doesn't load + sanitize every issue in the install. Callers+// that already filter by seriesId in JS should source from here instead.+async function readStateForSeries(seriesId) {+ return { issues: await store().loadAllForSeries(seriesId) };+}++async function saveIssueNow(issue) {+ await store().saveOneNow(issue.id, issue);+ return issue;+}++async function saveIssuesNow(issues) {+ await Promise.all(issues.map((issue) => saveIssueNow(issue)));+}++async function renumberInline(state, seriesId, fromSeasonId = null, preloadedSeries = null) {+ // Batch callers (e.g. commitEpisodesToIssues seeding a whole season) thread+ // the already-fetched series so an N-episode loop doesn't pay N redundant+ // getSeries reads of an unchanging record. Guard on id match so a mismatched+ // preload can never renumber against the wrong season list.+ const series = (preloadedSeries && preloadedSeries.id === seriesId)+ ? preloadedSeries+ : await seriesSvc.getSeries(seriesId).catch(() => null);+ // Exclude tombstones from numbering — surviving issues should keep a+ // contiguous sequence regardless of how many deletes happened.+ // applyVolumeOrderedNumbers mutates each issue's `number` in place, so the+ // filtered array still aliases the same objects in state.issues.+ return applyVolumeOrderedNumbers({+ issues: state.issues.filter((i) => !i.deleted),+ seriesId,+ seasons: series?.seasons || [],+ fromSeasonId,+ });+}+++// Internal helpers shared across issueCrud / issueStages / issueSync. Exported+// here (rather than inline) so the split modules can reach the single store+// facade, write queue, sanitizers, and renumber pass.+export {+ store,+ queueSeriesIssuesWrite,+ makeErr,+ ISSUE_ID_RE,+ readState,+ readStateForSeries,+ saveIssueNow,+ saveIssuesNow,+ renumberInline,+ sanitizeIssue,+ sanitizeTextStage,+ sanitizeVisualStage,+ sanitizeAudioStage,+ stripRunHistoryFromIssue,+};diff --git a/server/services/pipeline/storyboards.js b/server/services/pipeline/storyboards.jsnew file mode 100644index 0000000000..ba03a7b415--- /dev/null+++ b/server/services/pipeline/storyboards.js@@ -0,0 +1,277 @@+/**+ * Pipeline — Storyboard scene/shot renders + scene prompt refine (#2531)+ *+ * Single-scene video + single-shot start-frame enqueue, plus the storyboard+ * scene prompt refine / N-candidate fan-out. Extracted from the former+ * monolithic `visualStages.js`; shares plumbing via `./visualStageHelpers.js`.+ */++import { enqueueJob } from '../mediaJobQueue/index.js';+import { updateStage, assertStageUnlocked } from './issues.js';+import { buildStoryboardsShotOwner } from './owners.js';+import { ServerError } from '../../lib/errorHandler.js';+import { matchCharactersInText } from '../../lib/scenePrompt.js';+import { getDefaultVideoModelId, getVideoModels } from '../../lib/mediaModels.js';+import { ASPECT_PRESETS } from '../../lib/creativeDirectorPresets.js';+import { runPromptRefine, runImagePromptCandidates } from './refineHelpers.js';+import {+ composeVisualPrompt, resolveMode, enqueueImageJob, loadBibleContext,+ seriesBibleCtx, issueCtx, neighborText, loadRefineContext,+} from './visualStageHelpers.js';++/**+ * Enqueue a single-scene video render for a storyboard scene. Builds the+ * same prompt the episode-video CD treatment would build for this scene+ * (composeVisualPrompt with style notes + world style), then enqueues a+ * video job through the shared mediaJobQueue.+ *+ * Persists the resulting jobId on `stages.storyboards.scenes[index]+ * .sceneVideoJobId` so the UI can reflect it on reload.+ *+ * Returns { jobId, prompt, sceneIndex }.+ */+export async function enqueueStoryboardSceneVideo(issueId, sceneIndex, options = {}) {+ const idx = Number(sceneIndex);+ if (!Number.isInteger(idx) || idx < 0) {+ throw new ServerError('sceneIndex must be a non-negative integer', {+ status: 400, code: 'PIPELINE_SCENE_BAD_INDEX',+ });+ }+ const { issue, settings, series, world, canon } = await loadBibleContext(issueId);+ assertStageUnlocked(issue, 'storyboards');+ const pythonPath = settings.imageGen?.local?.pythonPath || null;+ if (!pythonPath) {+ throw new ServerError(+ 'Local video generation is not configured (settings.imageGen.local.pythonPath is missing).',+ { status: 400, code: 'VIDEO_GEN_NOT_CONFIGURED' },+ );+ }+ const scenes = Array.isArray(issue.stages?.storyboards?.scenes)+ ? [...issue.stages.storyboards.scenes]+ : [];+ const scene = scenes[idx];+ if (!scene) {+ throw new ServerError(`sceneIndex ${idx} out of range (have ${scenes.length})`, {+ status: 404, code: 'PIPELINE_SCENE_NOT_FOUND',+ });+ }+ if (!(scene.description || '').trim()) {+ throw new ServerError('scene has no description — add a description before rendering', {+ status: 400, code: 'PIPELINE_SCENE_EMPTY_DESCRIPTION',+ });+ }++ const matchedCharacters = matchCharactersInText(+ `${scene.description || ''} ${scene.slugline || ''}`,+ canon.characters,+ );+ const prompt = composeVisualPrompt({+ series,+ description: scene.description,+ slugline: scene.slugline || '',+ extraStyle: options.extraStyle || '',+ matchedCharacters,+ world,+ canon,+ characterAppearances: scene.characterAppearances,+ });++ const aspectRatio = ASPECT_PRESETS[options.aspectRatio] ? options.aspectRatio : '16:9';+ const { width, height } = ASPECT_PRESETS[aspectRatio];+ const modelId = options.modelId || settings.videoGen?.defaultModelId || getDefaultVideoModelId();+ // Validate the model exists for this platform before enqueueing — otherwise+ // the worker will fail with "Unknown video model" and leave a persisted+ // doomed entry in the queue. Mirrors the same fail-fast pattern as+ // /api/video-gen's route validation.+ if (!getVideoModels().some((m) => m.id === modelId)) {+ throw new ServerError(`Unknown video model "${modelId}"`, {+ status: 400, code: 'PIPELINE_UNKNOWN_VIDEO_MODEL',+ });+ }+ const negativePrompt = options.negativePrompt || 'text, watermark, blur, motion blur, low quality';++ const { jobId } = enqueueJob({+ kind: 'video',+ params: {+ pythonPath,+ prompt,+ negativePrompt,+ modelId,+ width,+ height,+ mode: 't2v',+ disableAudio: true,+ tiling: 'auto',+ chunks: 1,+ },+ owner: `pipeline:${issueId}:storyboards:scene${idx}`,+ });++ scenes[idx] = { ...scene, sceneVideoJobId: jobId };+ const { issue: updatedIssue, stage } = await updateStage(issueId, 'storyboards', {+ status: 'edited',+ scenes,+ });+ console.log(`🎥 Pipeline scene video — issue=${issueId.slice(0, 8)} scene=${idx + 1} jobId=${jobId.slice(0, 8)}`);+ return { jobId, prompt, sceneIndex: idx, issue: updatedIssue, stage };+}++/**+ * Enqueue an image render for a single shot inside a storyboard scene. Mirror+ * of enqueueStoryboardSceneVideo but for IMAGE (start-frame), at shot+ * granularity. Shot description is the primary anchor; falls back to the+ * parent scene's description when the shot is sparse so a fresh shot still+ * renders something coherent.+ */+export async function enqueueStoryboardShotStartFrame(issueId, sceneIndex, shotIndex, options = {}) {+ const sIdx = Number(sceneIndex);+ const tIdx = Number(shotIndex);+ if (!Number.isInteger(sIdx) || sIdx < 0 || !Number.isInteger(tIdx) || tIdx < 0) {+ throw new ServerError('sceneIndex and shotIndex must be non-negative integers', {+ status: 400, code: 'PIPELINE_SHOT_BAD_INDEX',+ });+ }+ const { issue, settings, series, world, canon } = await loadBibleContext(issueId);+ assertStageUnlocked(issue, 'storyboards');+ const scenes = Array.isArray(issue.stages?.storyboards?.scenes)+ ? [...issue.stages.storyboards.scenes]+ : [];+ const scene = scenes[sIdx];+ if (!scene) {+ throw new ServerError(`sceneIndex ${sIdx} out of range (have ${scenes.length})`, {+ status: 404, code: 'PIPELINE_SCENE_NOT_FOUND',+ });+ }+ const shots = Array.isArray(scene.shots) ? [...scene.shots] : [];+ const shot = shots[tIdx];+ if (!shot) {+ throw new ServerError(`shotIndex ${tIdx} out of range (have ${shots.length})`, {+ status: 404, code: 'PIPELINE_SHOT_NOT_FOUND',+ });+ }++ const shotDescription = (shot.description || '').trim();+ const description = shotDescription || (scene.description || '').trim();+ if (!description) {+ throw new ServerError('shot has no description (parent scene also empty) — add a description first', {+ status: 400, code: 'PIPELINE_SHOT_EMPTY_DESCRIPTION',+ });+ }++ const mode = resolveMode(options, settings);+ const matchedCharacters = matchCharactersInText(+ `${description} ${scene.slugline || ''}`,+ canon.characters,+ );+ const prompt = composeVisualPrompt({+ series,+ description,+ slugline: scene.slugline || '',+ extraStyle: options.extraStyle || '',+ matchedCharacters,+ world,+ canon,+ // A shot inherits its parent scene's wardrobe picks.+ characterAppearances: scene.characterAppearances,+ });++ const jobId = enqueueImageJob({+ prompt, world, settings, options, mode,+ owner: buildStoryboardsShotOwner({ issueId, sceneIndex: sIdx, shotIndex: tIdx }),+ logLine: `🎞️ Pipeline shot start-frame — issue=${issueId.slice(0, 8)} scene=${sIdx + 1} shot=${tIdx + 1}`,+ });++ shots[tIdx] = { ...shot, startFrameJobId: jobId };+ scenes[sIdx] = { ...scene, shots };+ const { issue: updatedIssue, stage } = await updateStage(issueId, 'storyboards', {+ status: 'edited',+ scenes,+ });+ return { jobId, mode, prompt, sceneIndex: sIdx, shotIndex: tIdx, issue: updatedIssue, stage };+}++// Validate the scene index, lock, and non-empty description, then build the+// `pipeline-storyboard-image-prompt` template variables. Shared by the 1:1+// refine and the N-candidate fan-out so both feed the LLM identical context.+async function loadStoryboardScenePromptContext(issueId, sceneIndex) {+ const idx = Number(sceneIndex);+ if (!Number.isInteger(idx) || idx < 0) {+ throw new ServerError('sceneIndex must be a non-negative integer', {+ status: 400, code: 'PIPELINE_SCENE_BAD_INDEX',+ });+ }+ const { issue, series } = await loadRefineContext(issueId);+ assertStageUnlocked(issue, 'storyboards');+ const scenes = Array.isArray(issue.stages?.storyboards?.scenes)+ ? [...issue.stages.storyboards.scenes]+ : [];+ const scene = scenes[idx];+ if (!scene) {+ throw new ServerError(`sceneIndex ${idx} out of range (have ${scenes.length})`, {+ status: 404, code: 'PIPELINE_SCENE_NOT_FOUND',+ });+ }+ if (!(scene.description || '').trim()) {+ throw new ServerError('scene has no description to refine', {+ status: 400, code: 'PIPELINE_SCENE_EMPTY_DESCRIPTION',+ });+ }++ const prev = scenes[idx - 1];+ const next = scenes[idx + 1];+ const variables = {+ series: seriesBibleCtx(series),+ issue: issueCtx(issue),+ sceneNumber: idx + 1,+ sceneCount: scenes.length,+ slugline: (scene.slugline || '').slice(0, 200),+ hasSlugline: !!(scene.slugline || '').trim(),+ description: (scene.description || '').slice(0, 4000),+ hasNeighbors: !!(prev || next),+ previousScene: neighborText(prev),+ nextScene: neighborText(next),+ };+ return { issue, idx, scenes, scene, variables };+}++/**+ * Run the `pipeline-storyboard-image-prompt` template against the current+ * storyboard scene + surrounding context, then persist the refined+ * description on the scene. Returns { scene, issue, stage, runId, changes, providerId }.+ */+export async function refineStoryboardScenePrompt(issueId, sceneIndex, options = {}) {+ const { idx, scenes, scene, variables } = await loadStoryboardScenePromptContext(issueId, sceneIndex);++ const { refined, changes, runId, providerId } = await runPromptRefine({+ templateName: 'pipeline-storyboard-image-prompt',+ variables,+ options,+ source: 'pipeline-storyboard-prompt-refine',+ logTag: `Pipeline scene refine — issue=${issueId.slice(0, 8)} scene=${idx + 1}`,+ });++ scenes[idx] = { ...scene, description: refined };+ const { issue: updatedIssue, stage } = await updateStage(issueId, 'storyboards', {+ status: 'edited',+ scenes,+ });+ return { scene: scenes[idx], issue: updatedIssue, stage, runId, changes, providerId };+}++/**+ * Generate N candidate image-gen prompts for a single storyboard scene+ * WITHOUT mutating the scene (issue #904). Returns+ * { candidates, requested, sceneIndex }.+ */+export async function generateStoryboardSceneImagePrompts(issueId, sceneIndex, { count, ...options } = {}) {+ const { idx, variables } = await loadStoryboardScenePromptContext(issueId, sceneIndex);+ const { candidates, requested } = await runImagePromptCandidates({+ count,+ templateName: 'pipeline-storyboard-image-prompt',+ variables,+ options,+ source: 'pipeline-storyboard-image-prompts',+ logTag: `Pipeline scene image-prompts — issue=${issueId.slice(0, 8)} scene=${idx + 1}`,+ });+ return { candidates, requested, sceneIndex: idx };+}diff --git a/server/services/pipeline/visualStageHelpers.js b/server/services/pipeline/visualStageHelpers.jsnew file mode 100644index 0000000000..e6c922c773--- /dev/null+++ b/server/services/pipeline/visualStageHelpers.js@@ -0,0 +1,451 @@+/**+ * Pipeline — Visual stage shared prompt + enqueue helpers (#2531)+ *+ * Extracted from the former monolithic `visualStages.js` so the covers /+ * comicPages / storyboards feature modules can share ONE set of style + prompt+ * composers, the image-gen enqueue plumbing (`enqueueImageJob`,+ * `applyCharacterLorasToRender`), the proof/reference init-image resolvers, and+ * the LLM-refine context loaders. Pure move — no behavior change.+ */++import { enqueueJob } from '../mediaJobQueue/index.js';+import { getSettings } from '../settings.js';+import { getSeries, STYLE_PROMPT_OVERRIDE_MODE_DEFAULT } from './series.js';+import { getIssue } from './issues.js';+import { resolveGalleryImage } from '../../lib/fileUtils.js';+import { getUniverse, joinInfluenceList } from '../universeBuilder.js';+import { ServerError } from '../../lib/errorHandler.js';+import { buildScenePrompt, buildPlaceByKey, matchScenePlace } from '../../lib/scenePrompt.js';+import { composeStyledPrompt } from '../../lib/composeStyledPrompt.js';+import { getImageModels } from '../../lib/mediaModels.js';+import { loraCompatKey } from '../../lib/runners.js';+import { resolveCharacterLoras } from '../characterLoraResolver.js';+import { pickCanon } from './seriesCanon.js';+import { IMAGE_GEN_MODE } from '../imageGen/modes.js';+import { resolveImageCleaners } from '../imageGen/index.js';++const joinStyleParts = (...parts) =>+ parts.map((s) => (s || '').trim()).filter(Boolean).join(', ');++const joinStyleSentences = (...parts) =>+ parts.map((s) => (s || '').trim()).filter(Boolean).join('. ');++const stackStyle = (series, extraStyle) => joinStyleParts(series?.styleNotes, extraStyle);++// Composes `series.stylePromptOverride` against the universe's embrace+// influences. The mode (prepend/append/override) is documented next to the+// `STYLE_PROMPT_OVERRIDE_MODES` constant in series.js — it's the single+// source of truth.+const buildStyleClause = (world, series) => {+ const override = (series?.stylePromptOverride || '').trim();+ const mode = series?.stylePromptOverrideMode || STYLE_PROMPT_OVERRIDE_MODE_DEFAULT;+ if (override && mode === 'override') return override;+ const universeStyle = joinInfluenceList(world?.influences?.embrace);+ return mode === 'append'+ ? joinStyleSentences(universeStyle, override)+ : joinStyleSentences(override, universeStyle);+};++const applyWorldStyle = (prompt, world, series = null) => {+ const stylePrompt = buildStyleClause(world, series);+ if (!stylePrompt) return prompt;+ return composeStyledPrompt(prompt, '', { prompt: stylePrompt, negativePrompt: '' }).prompt;+};++// Resolution order for the image-gen mode on a pipeline visual stage:+// 1. Per-request override (`options.mode`) — set by the stage's persisted+// `genConfig` or an explicit UI selection. Codex is only honored when+// `imageGen.codex.enabled` is true; a stale 'codex' override from+// before the toggle was turned off falls through to the next step.+// 2. Saved dispatcher default (`settings.imageGen.mode`) — but only when+// it names a mode this surface supports (visual pipeline doesn't+// proxy the external SD-API path) AND, for 'codex', Codex is enabled.+// 3. Auto-default — prefer Codex when the user has enabled it+// (`imageGen.codex.enabled`), since cloud image gen produces+// print-quality comic pages out of the box. Otherwise fall back to+// local diffusion (flux-1) the way the original default behaved.+const resolveMode = (options, settings) => {+ const codexEnabled = settings?.imageGen?.codex?.enabled === true;+ if (options.mode === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;+ if (options.mode === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;+ const settingsMode = settings?.imageGen?.mode;+ if (settingsMode === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;+ if (settingsMode === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;+ if (codexEnabled) return IMAGE_GEN_MODE.CODEX;+ return IMAGE_GEN_MODE.LOCAL;+};++/**+ * Resolve trained character LoRAs for a pipeline render. Local mode only —+ * codex has no LoRA support, so resolution is skipped there with one log+ * line. `options.applyCharacterLoras === false` is the per-render opt-out+ * (default on). The compat key comes from the model the local render will+ * actually use (request override → saved local model → first registered),+ * mirroring resolveSheetModelId's order; an unresolvable model just means+ * no compat filtering.+ *+ * Returns `{ loras, triggerByKey }` — `triggerByKey` maps canon+ * entryId/ingredientId → trigger word for prompt weaving.+ */+async function applyCharacterLorasToRender({ matchedCharacters, mode, options, settings }) {+ const none = { loras: [], triggerByKey: new Map() };+ if (options.applyCharacterLoras === false || !matchedCharacters?.length) return none;+ if (mode !== IMAGE_GEN_MODE.LOCAL) {+ console.log(`⚠️ character LoRA skipped — ${mode} mode has no LoRA support`);+ return none;+ }+ const allModels = getImageModels();+ const model = allModels.find((m) => m.id === options.modelId)+ || allModels.find((m) => m.id === settings?.imageGen?.local?.modelId)+ || allModels[0]+ || null;+ const compatKey = model ? loraCompatKey(model) : null;+ const loras = await resolveCharacterLoras(matchedCharacters, { compatKey }).catch((err) => {+ console.error(`❌ character LoRA resolution failed: ${err?.message}`);+ return [];+ });+ if (!loras.length) return none;+ const triggerByKey = new Map();+ for (const lora of loras) {+ if (!lora.triggerWord || !lora.character) continue;+ if (lora.character.entryId) triggerByKey.set(lora.character.entryId, lora.triggerWord);+ if (lora.character.ingredientId) triggerByKey.set(lora.character.ingredientId, lora.triggerWord);+ }+ console.log(`🧬 character LoRA auto-apply — ${loras.map((l) => `${l.character?.name || '?'}→${l.filename}`).join(', ')}`);+ return { loras, triggerByKey };+}++const loraRenderOptions = (loras) => (loras.length+ ? { loraFilenames: loras.map((l) => l.filename), loraScales: loras.map((l) => l.scale) }+ : {});++// Defensive fallback — an unrecognized value must never land in the final+// slot, even if a future client bypasses the route schema.+const resolveVariant = (target) => (target === 'final' ? 'final' : 'proof');++// `buildRenderSlot` moved to server/lib/renderSlot.js so season-cover+// render paths (which don't import from visualStages.js) can share the+// shape. Imported for the shared cover-render persist path below and+// re-exported for back-compat with route-level callers that still import it+// from this module.+import { buildRenderSlot } from '../../lib/renderSlot.js';++export { buildRenderSlot };++// Default denoise strength for the "use proof as base" upscale path. Low+// enough to preserve composition (panel layout, character placement),+// high enough to let the model add the extra detail the larger canvas+// affords. Tweakable per-call via options.initImageStrength.+const PROOF_AS_BASE_DEFAULT_STRENGTH = 0.25;++// Resolve a stored proof filename (e.g. "abc123.png") to an absolute path+// under PATHS.images, enforcing the gallery prefix. `mustExist:false` skips+// the existsSync check — the downstream image-gen runner reads the path and+// will surface a clear error if the file vanished between enqueue and exec;+// an existsSync here would add a TOCTOU race for no real benefit.+const resolveProofInitImage = (proofImage, label) => {+ const name = proofImage?.filename;+ if (typeof name !== 'string' || !name) {+ throw new ServerError(+ `Cannot use proof as base for ${label}: no proof render available yet — render the proof first.`,+ { status: 400, code: 'PIPELINE_COMIC_PROOF_MISSING' },+ );+ }+ const resolved = resolveGalleryImage(name, { mustExist: false });+ if (!resolved) {+ throw new ServerError(+ `Proof image path escaped the gallery for ${label}: ${name}`,+ { status: 400, code: 'PIPELINE_COMIC_PROOF_NOT_FOUND' },+ );+ }+ return resolved;+};++// Consistency-reference denoise: when an ADJACENT page is passed as a reference+// (continuing the same scene so incidental, un-described characters and the+// environment stay consistent), we want the NEW page's composition to come from+// its own prompt while only borrowing identity/style from the reference. So this+// is a HIGH denoise (mostly follow the prompt) — the opposite of proof-as-base's+// 0.25 (preserve layout for an upscale). Local i2i honors it; codex passes the+// reference as an `-i` attachment (reference mode), where strength is moot.+const REFERENCE_PAGE_DEFAULT_STRENGTH = 0.8;++// Default denoise for the per-page "Refine" image-to-image correction (issue+// #1534). The page is re-rendered FROM ITS OWN existing image, so this is a+// low strength: preserve the panel layout / composition / lettering and move+// only enough pixels to honor the small requested change. Higher than+// proof-as-base's 0.25 (which merely upscales) because a refine must actually+// apply an edit; far below the reference path's 0.8 (which mostly follows a+// fresh prompt). Tweakable per-call via options.initImageStrength.+const REFINE_RENDER_DEFAULT_STRENGTH = 0.35;++// Resolve an adjacent page's rendered image to a gallery path for use as a+// consistency reference. Prefers the final render, falls back to the proof.+// Throws a clear 400 when that page hasn't been rendered yet.+const resolvePageReferenceImage = (refPage, label) => {+ const name = refPage?.finalImage?.filename || refPage?.proofImage?.filename;+ if (typeof name !== 'string' || !name) {+ throw new ServerError(+ `Cannot use ${label} as a consistency reference: it has no rendered image yet — render that page first.`,+ { status: 400, code: 'PIPELINE_COMIC_REFERENCE_MISSING' },+ );+ }+ const resolved = resolveGalleryImage(name, { mustExist: false });+ if (!resolved) {+ throw new ServerError(+ `Reference image path escaped the gallery for ${label}: ${name}`,+ { status: 400, code: 'PIPELINE_COMIC_REFERENCE_NOT_FOUND' },+ );+ }+ return resolved;+};++const loadBibleContext = async (issueId) => {+ const issueChain = (async () => {+ const issue = await getIssue(issueId);+ const series = await getSeries(issue.seriesId);+ // `.catch(() => null)` covers a dangling universe reference. Empty+ // canon still lets scene description flow through; downstream stages+ // just lose character / place / object metadata.+ const world = await getUniverse(series.universeId).catch(() => null);+ return { issue, series, world, canon: pickCanon(world) };+ })();+ const [chain, settings] = await Promise.all([issueChain, getSettings()]);+ return { ...chain, settings };+};++const enqueueImageJob = ({ prompt, world, settings, options, mode, owner, logLine }) => {+ // Merge user + world negatives — mirrors composeStyledPrompt's preset+ // negative handling so the world's global negative-prompt terms stay in+ // effect even when the caller supplies their own additions. Deduplicated+ // by token so a user repeating a world negative doesn't double-weight it.+ const userNeg = (options.negativePrompt || '').trim();+ const worldNeg = joinInfluenceList(world?.influences?.avoid);+ const negativeTokens = [userNeg, worldNeg]+ .flatMap((s) => s.split(',').map((t) => t.trim()).filter(Boolean));+ const negativePrompt = [...new Set(negativeTokens)].join(', ') || undefined;+ const baseParams = {+ prompt,+ negativePrompt,+ width: options.width,+ height: options.height,+ steps: options.steps,+ guidance: options.guidance ?? options.cfgScale,+ cfgScale: options.cfgScale,+ // Honored by local mflux + diffusers runners; codex picks its own.+ ...(Number.isFinite(options.seed) ? { seed: options.seed } : {}),+ // i2i upscale path: when the caller passes an init image (e.g.+ // "use proof as base" for a final render) we forward it to the active+ // backend. Local mflux uses it as `--image-path`; codex attaches it via+ // the CLI's `-i` flag and routes it to gpt-image-2's image-edit mode.+ // The external SD-API backend has no i2i wiring and drops both fields+ // at the dispatcher.+ ...(options.initImagePath ? { initImagePath: options.initImagePath } : {}),+ ...(Number.isFinite(options.initImageStrength) ? { initImageStrength: options.initImageStrength } : {}),+ // Character LoRAs resolved by applyCharacterLorasToRender — only the+ // local runner honors these (codex has no LoRA support; the resolver is+ // skipped there so the spread stays empty).+ ...(options.loraFilenames?.length ? { loraFilenames: options.loraFilenames, loraScales: options.loraScales } : {}),+ };+ // The queue dispatches directly to imageGen/{codex,local}.generateImage,+ // bypassing imageGen/index.js's dispatcher that resolves cleaners for+ // direct callers. The /api/image-gen/generate route resolves them at the+ // route layer; pipeline renders need the same resolution here, otherwise+ // the saved settings.imageGen[mode].{cleanC2PA,denoise} would have no+ // effect on storyboard, comic-panel, or cover renders.+ const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);+ const params = mode === IMAGE_GEN_MODE.CODEX+ ? { mode: IMAGE_GEN_MODE.CODEX, codexPath: settings.imageGen?.codex?.codexPath, model: settings.imageGen?.codex?.model, cleanC2PA, denoise, ...baseParams }+ : { pythonPath: settings.imageGen?.local?.pythonPath || null, modelId: options.modelId, cleanC2PA, denoise, ...baseParams };+ const { jobId } = enqueueJob({ kind: 'image', params, owner });+ console.log(`${logLine} mode=${mode} jobId=${jobId.slice(0, 8)}`);+ return jobId;+};++// Canon places now live on the linked universe (Phase B.4). Callers can+// either pass a pre-built `placeByKey` (when they've already computed it+// for reuse across many scenes — see episodeVideo) or pass `canon` and let+// us build the map here. `series?.places` is no longer read — that field+// was retired with the series-side canon teardown.+export function composeVisualPrompt({ series, description, slugline = '', extraStyle = '', placeByKey = null, matchedCharacters = [], world = null, canon = null, characterAppearances = [] }) {+ const map = placeByKey || buildPlaceByKey(canon?.places);+ const scenePrompt = buildScenePrompt(+ series?.name || '',+ { visualPrompt: description || '', slugline, characterAppearances },+ matchedCharacters,+ stackStyle(series, extraStyle),+ matchScenePlace(slugline, map),+ );+ return applyWorldStyle(scenePrompt, world, series);+}++// Marvel/DC scripts attach parentheticals to speakers — `ETTA (EARPIECE):`,+// `KESSA (WHISPERED):`, `LINA (THOUGHT):`. These tell a human artist HOW to+// draw the balloon (jagged for transmitted voices, dashed for whispers,+// cloud-outline for thoughts), but a diffusion model treats them as more text+// to letter. Map them to visual balloon-style hints so the artist still gets+// the cue without the label leaking into the lettering.+// `disembodied: true` marks a modifier whose SPEAKER is NOT physically in the+// panel — a station PA, a radio voice, an off-panel shout. Without an explicit+// cue the image model gives the line a normal tailed balloon and points it at+// whoever IS drawn (e.g. JUNO's `(SPEAKERS)` PA line got attributed to a+// visible newlywed). formatBalloon turns the flag into a "do NOT tail to any+// visible character" instruction. Order matters — first match wins, so the+// broadcast/PA rule precedes the generic transmission rule.+const BALLOON_STYLE_HINTS = [+ { test: /\b(SPEAKERS?|P\.?A\.?|BROADCAST|ANNOUNCE(?:D|S|MENT)?|ANNOUNCER|LOUDSPEAKER|OVERHEAD|INTERCOM|TANNOY|PAGING|STATIONWIDE|SHIPWIDE)\b/, hint: 'jagged electronic broadcast/PA balloon, no tail (disembodied announcement from an overhead source)', disembodied: true },+ // Transmission devices are AMBIGUOUS — the speaker may be a visible character+ // talking into the device, or a remote voice — so this gets the electronic+ // style WITHOUT the "not in panel" claim (that's reserved for unambiguous+ // broadcast/off-panel/V.O. above).+ { test: /\b(EARPIECE|RADIO|COMMS?|TRANSMISSION|PHONE|HOLO|HOLOGRAM|TV|MONITOR|VIDEO|COMLINK|CHANNEL)\b/, hint: 'jagged electronic/transmission balloon with bolt-shaped tail' },+ { test: /\b(OFF[\- ]?PANEL|OFF[\- ]?SCREEN|O\.?S\.?|O\.?P\.?)\b/, hint: 'off-panel balloon with the tail pointing past the panel border', disembodied: true },+ { test: /\b(NARRATION|VOICE[\- ]?OVER|V\.?O\.?)\b/, hint: 'rectangular narration caption rather than a speech balloon', disembodied: true },+ { test: /\b(WHISPER(?:ED|S|ING)?|SOTTO|HUSHED|QUIET)\b/, hint: 'dashed-outline whisper balloon' },+ { test: /\b(SHOUT(?:ED|S|ING)?|YELL(?:ED|S|ING)?|SCREAM(?:ED|S|ING)?|ANGRY|BURST)\b/, hint: 'spiked/burst-shaped balloon' },+ { test: /\b(THOUGHT|THINKING|INTERNAL)\b/, hint: 'cloud-outline thought balloon with chain-of-bubbles tail' },+ { test: /\b(SING(?:S|ING)?|SONG|MUSICAL)\b/, hint: 'wavy musical balloon with musical-note flourish' },+];++/**+ * Build one balloon attribution string: `Speech balloon reads: "<text>" (spoken+ * by NAME[, <style hint>]).` Leads with the lettered text so the diffusion+ * model anchors on the balloon's contents; parses any parenthetical modifier+ * on the speaker into a visual styling hint (radio, whisper, thought, etc.).+ * Returns null if `line` is blank — the caller filters those out.+ */+function formatBalloon(character, line) {+ const text = (line || '').trim();+ if (!text) return null;+ const raw = (character || '').trim() || 'CHAR';+ // Split `NAME (MODIFIER)` → speaker base + modifier text. Tolerate stacked+ // parens (`NAME (EARPIECE, WHISPERED)`) by treating the whole inner-paren+ // blob as one modifier string for hint detection.+ const m = raw.match(/^([^(]+?)\s*\(([^)]*)\)\s*$/);+ const speaker = (m ? m[1] : raw).trim() || 'CHAR';+ const modifier = m ? m[2].trim() : '';+ const cleanText = text.replace(/^"+|"+$/g, '').trim();+ const styleEntry = modifier+ ? BALLOON_STYLE_HINTS.find((h) => h.test.test(modifier.toUpperCase())) || null+ : null;+ // A disembodied speaker (PA, radio, off-panel, V.O.) is NOT in the panel, so+ // spell that out — otherwise the model letters a normal balloon and tails it+ // to whoever IS drawn, mis-attributing the line (the JUNO `(SPEAKERS)` bug).+ const attribution = styleEntry?.disembodied+ ? `(spoken by ${speaker}, who is NOT visible in this panel — render as a ${styleEntry.hint}; do NOT attach the balloon tail to any visible character)`+ : styleEntry+ ? `(spoken by ${speaker}; ${styleEntry.hint})`+ : `(spoken by ${speaker})`;+ // Terminator handled here so endPunct() at the call site doesn't have to+ // navigate the closing paren — we always end with `).`.+ return `Speech balloon reads: "${cleanText}" ${attribution}.`;+}++// Build the masthead clause for a front cover. When `series.titleLogo` is set,+// it replaces the generic "bold comic-book logo typography" fallback with the+// LLM-designed (or user-edited) design description so every cover renders a+// consistent logo. The series name is still rendered verbatim — the titleLogo+// describes HOW it looks (letterform, finish, color), not WHAT it says.+function buildMastheadClause(series) {+ const seriesName = (series?.name || '').trim();+ const logoDesign = (series?.titleLogo || '').trim();+ if (!seriesName) {+ return logoDesign+ ? `Render a bold comic-book series masthead near the top of the cover. Logo design: ${logoDesign}`+ : 'Render a bold comic-book series masthead as large logo typography near the top of the cover.';+ }+ return logoDesign+ ? `Render the series masthead "${seriesName}" as large comic-book logo typography near the top of the cover. Logo design: ${logoDesign}`+ : `Render the series masthead "${seriesName}" as bold, large comic-book logo typography near the top of the cover.`;+}++// Optional author byline injected near the bottom of front covers + trade+// paperback fronts. Skipped when the series has no author set so older series+// still render without an empty "By —" caption.+const buildAuthorClause = (series) => {+ const author = (series?.author || '').trim();+ return author+ ? ` Include a small author byline reading "By ${author}" near the bottom of the cover — restrained, lettered in a smaller weight than the masthead.`+ : '';+};++/**+ * Validate per-scene wardrobe picks at the request boundary. The generic+ * visual-image route accepts `characterAppearances` ([{ characterId,+ * wardrobeId? }]) threaded from the storyboards picker; the Zod schema only+ * checks shape (non-empty ids), so this is the first point that can confirm+ * the ids actually resolve to a canon character + one of its wardrobes.+ *+ * Throws a 400 ServerError on a dangling characterId/wardrobeId rather than+ * leaning on `buildScenePrompt`'s defensive read, which would silently drop+ * the pick. A dangling id is a client/state bug (stale picker, deleted+ * character) worth surfacing — not a no-op. A null/absent `wardrobeId` is+ * valid (the character renders on their canonical body description); only a+ * non-empty wardrobeId is resolved against the character's wardrobes.+ *+ * Scoped to the request boundary on purpose: the persisted-scene paths+ * (`enqueueStoryboardSceneVideo`, `enqueueStoryboardShotStartFrame`) and the+ * shared `composeVisualPrompt` primitive — also used by episode-video batch+ * stitching — keep `buildScenePrompt`'s resilient silent-drop convention so a+ * single dangling pick can't abort a whole batch render.+ */+export function assertCharacterAppearancesResolve(characterAppearances, characters) {+ const picks = Array.isArray(characterAppearances) ? characterAppearances : [];+ if (!picks.length) return;+ const charById = new Map(+ (Array.isArray(characters) ? characters : [])+ .filter((c) => c && c.id)+ .map((c) => [c.id, c]),+ );+ for (const pick of picks) {+ if (!pick || !pick.characterId) continue;+ const character = charById.get(pick.characterId);+ if (!character) {+ throw new ServerError(+ `characterAppearances references unknown character id "${pick.characterId}"`,+ { status: 400, code: 'PIPELINE_VISUAL_BAD_CHARACTER' },+ );+ }+ if (pick.wardrobeId) {+ const wardrobe = (character.wardrobes || []).find((w) => w && w.id === pick.wardrobeId);+ if (!wardrobe) {+ throw new ServerError(+ `characterAppearances references unknown wardrobe id "${pick.wardrobeId}" for character "${character.name || pick.characterId}"`,+ { status: 400, code: 'PIPELINE_VISUAL_BAD_WARDROBE' },+ );+ }+ }+ }+}++const seriesBibleCtx = (series) => ({+ name: series.name || '',+ styleNotes: series.styleNotes || '',+ logline: series.logline || '',+ premise: series.premise || '',+});++const issueCtx = (issue) => ({ number: issue.number || 0, title: issue.title || '' });++const neighborText = (item) => (item?.description || '').trim().slice(0, 240) || '(empty)';++// Refine path needs issue + series only — skip the settings + world reads+// that loadBibleContext does for the image/video enqueue path.+async function loadRefineContext(issueId) {+ const issue = await getIssue(issueId);+ const series = await getSeries(issue.seriesId);+ return { issue, series };+}++++// Shared helpers consumed by covers / comicPages / storyboards. Exported here+// (rather than inline) so the split feature modules reach one implementation.+export {+ stackStyle, buildMastheadClause, buildAuthorClause, applyWorldStyle,+ loadBibleContext, resolveMode, resolveVariant, resolveProofInitImage,+ PROOF_AS_BASE_DEFAULT_STRENGTH, enqueueImageJob, formatBalloon,+ resolvePageReferenceImage, REFERENCE_PAGE_DEFAULT_STRENGTH,+ REFINE_RENDER_DEFAULT_STRENGTH, applyCharacterLorasToRender, loraRenderOptions,+ seriesBibleCtx, issueCtx, neighborText, loadRefineContext,+};diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.jsindex 2d8e37b244..6dfb386b2a 100644--- a/server/services/pipeline/visualStages.js+++ b/server/services/pipeline/visualStages.js@@ -1,1763 +1,18 @@/**- * Pipeline — Visual stage handoff helpers+ * Pipeline — Visual stage handoff helpers (barrel, #2531)*- * Responsibilities, in order of how they evolved:+ * The former ~1760-line monolith was split along feature seams:*- * 1. **Image enqueue** (`enqueueVisualImage`, `enqueueVisualComicPage`) —- * build the right diffusion params for a comicPages panel / page or a- * storyboards scene and hand off to `mediaJobQueue`. The route layer- * persists the returned jobId into the issue's stage record.+ * - ./visualStageHelpers.js — shared style/prompt composers + enqueue plumbing.+ * - ./covers.js — comic + volume front/back cover renders.+ * - ./comicPages.js — comic page renders + panel prompt refine.+ * - ./storyboards.js — storyboard scene/shot renders + scene refine.*- * 2. **Single-scene video enqueue** (`enqueueStoryboardSceneVideo`) —- * render one storyboard scene as a t2v clip without committing to the- * full episode-video stitch. Persists `sceneVideoJobId` on the scene- * so a reload still surfaces the in-flight render.- *- * 3. **LLM-driven prompt refinement** (`refineComicPanelPrompt`,- * `refineStoryboardScenePrompt`) — elaborate a panel/scene description- * into a richer image-gen prompt via `runStagedLLM`, then persist the- * refined text back on the source record. Shared `runPromptRefine`- * helper + slim `loadRefineContext` keep the two surfaces DRY.- *- * Full episode-video stitching still lives in `episodeVideo.js` — that- * path drives the Creative Director scene runner end-to-end.- */--import { enqueueJob } from '../mediaJobQueue/index.js';-import { getSettings } from '../settings.js';-import { getSeries, updateSeasonOnSeries } from './series.js';-import { getIssue, updateStage, updateStageWithLatest, assertStageUnlocked, VISUAL_STAGE_IDS } from './issues.js';-import { resolveGalleryImage } from '../../lib/fileUtils.js';-import { buildComicPagesOwner, buildSeasonCoverOwner, buildStoryboardsShotOwner, slotKeyForVariant } from './owners.js';-import { getUniverse, joinInfluenceList } from '../universeBuilder.js';-import { ServerError } from '../../lib/errorHandler.js';-import {- buildScenePrompt, buildPlaceByKey, matchScenePlace,- buildCharByKey, matchSceneCharacters, matchCharactersInText,- matchPlacesInText, matchObjectsInText,-} from '../../lib/scenePrompt.js';-import { flattenCanonDescriptorFragments, richCanonDescriptorFragments } from '../../lib/canonPrompt.js';-import { composeStyledPrompt } from '../../lib/composeStyledPrompt.js';-import { getDefaultVideoModelId, getVideoModels, getImageModels } from '../../lib/mediaModels.js';-import { loraCompatKey } from '../../lib/runners.js';-import { resolveCharacterLoras } from '../characterLoraResolver.js';-import { runStagedLLM } from '../../lib/stageRunner.js';-import { runPromptRefine, runImagePromptCandidates } from './refineHelpers.js';-import { pickCanon } from './seriesCanon.js';-import { STYLE_PROMPT_OVERRIDE_MODE_DEFAULT } from './series.js';-import { ASPECT_PRESETS } from '../../lib/creativeDirectorPresets.js';-import { sameComicScene } from '../../lib/comicScriptParser.js';-import { IMAGE_GEN_MODE } from '../imageGen/modes.js';-import { resolveImageCleaners } from '../imageGen/index.js';--const joinStyleParts = (...parts) =>- parts.map((s) => (s || '').trim()).filter(Boolean).join(', ');--const joinStyleSentences = (...parts) =>- parts.map((s) => (s || '').trim()).filter(Boolean).join('. ');--const stackStyle = (series, extraStyle) => joinStyleParts(series?.styleNotes, extraStyle);--// Composes `series.stylePromptOverride` against the universe's embrace-// influences. The mode (prepend/append/override) is documented next to the-// `STYLE_PROMPT_OVERRIDE_MODES` constant in series.js — it's the single-// source of truth.-const buildStyleClause = (world, series) => {- const override = (series?.stylePromptOverride || '').trim();- const mode = series?.stylePromptOverrideMode || STYLE_PROMPT_OVERRIDE_MODE_DEFAULT;- if (override && mode === 'override') return override;- const universeStyle = joinInfluenceList(world?.influences?.embrace);- return mode === 'append'- ? joinStyleSentences(universeStyle, override)- : joinStyleSentences(override, universeStyle);-};--const applyWorldStyle = (prompt, world, series = null) => {- const stylePrompt = buildStyleClause(world, series);- if (!stylePrompt) return prompt;- return composeStyledPrompt(prompt, '', { prompt: stylePrompt, negativePrompt: '' }).prompt;-};--// Resolution order for the image-gen mode on a pipeline visual stage:-// 1. Per-request override (`options.mode`) — set by the stage's persisted-// `genConfig` or an explicit UI selection. Codex is only honored when-// `imageGen.codex.enabled` is true; a stale 'codex' override from-// before the toggle was turned off falls through to the next step.-// 2. Saved dispatcher default (`settings.imageGen.mode`) — but only when-// it names a mode this surface supports (visual pipeline doesn't-// proxy the external SD-API path) AND, for 'codex', Codex is enabled.-// 3. Auto-default — prefer Codex when the user has enabled it-// (`imageGen.codex.enabled`), since cloud image gen produces-// print-quality comic pages out of the box. Otherwise fall back to-// local diffusion (flux-1) the way the original default behaved.-const resolveMode = (options, settings) => {- const codexEnabled = settings?.imageGen?.codex?.enabled === true;- if (options.mode === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;- if (options.mode === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;- const settingsMode = settings?.imageGen?.mode;- if (settingsMode === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;- if (settingsMode === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;- if (codexEnabled) return IMAGE_GEN_MODE.CODEX;- return IMAGE_GEN_MODE.LOCAL;-};--/**- * Resolve trained character LoRAs for a pipeline render. Local mode only —- * codex has no LoRA support, so resolution is skipped there with one log- * line. `options.applyCharacterLoras === false` is the per-render opt-out- * (default on). The compat key comes from the model the local render will- * actually use (request override → saved local model → first registered),- * mirroring resolveSheetModelId's order; an unresolvable model just means- * no compat filtering.- *- * Returns `{ loras, triggerByKey }` — `triggerByKey` maps canon- * entryId/ingredientId → trigger word for prompt weaving.- */-async function applyCharacterLorasToRender({ matchedCharacters, mode, options, settings }) {- const none = { loras: [], triggerByKey: new Map() };- if (options.applyCharacterLoras === false || !matchedCharacters?.length) return none;- if (mode !== IMAGE_GEN_MODE.LOCAL) {- console.log(`⚠️ character LoRA skipped — ${mode} mode has no LoRA support`);- return none;- }- const allModels = getImageModels();- const model = allModels.find((m) => m.id === options.modelId)- || allModels.find((m) => m.id === settings?.imageGen?.local?.modelId)- || allModels[0]- || null;- const compatKey = model ? loraCompatKey(model) : null;- const loras = await resolveCharacterLoras(matchedCharacters, { compatKey }).catch((err) => {- console.error(`❌ character LoRA resolution failed: ${err?.message}`);- return [];- });- if (!loras.length) return none;- const triggerByKey = new Map();- for (const lora of loras) {- if (!lora.triggerWord || !lora.character) continue;- if (lora.character.entryId) triggerByKey.set(lora.character.entryId, lora.triggerWord);- if (lora.character.ingredientId) triggerByKey.set(lora.character.ingredientId, lora.triggerWord);- }- console.log(`🧬 character LoRA auto-apply — ${loras.map((l) => `${l.character?.name || '?'}→${l.filename}`).join(', ')}`);- return { loras, triggerByKey };-}--const loraRenderOptions = (loras) => (loras.length- ? { loraFilenames: loras.map((l) => l.filename), loraScales: loras.map((l) => l.scale) }- : {});--// Defensive fallback — an unrecognized value must never land in the final-// slot, even if a future client bypasses the route schema.-const resolveVariant = (target) => (target === 'final' ? 'final' : 'proof');--// `buildRenderSlot` moved to server/lib/renderSlot.js so season-cover-// render paths (which don't import from visualStages.js) can share the-// shape. Imported for the shared cover-render persist path below and-// re-exported for back-compat with route-level callers that still import it-// from this module.-import { buildRenderSlot } from '../../lib/renderSlot.js';--export { buildRenderSlot };--// Default denoise strength for the "use proof as base" upscale path. Low-// enough to preserve composition (panel layout, character placement),-// high enough to let the model add the extra detail the larger canvas-// affords. Tweakable per-call via options.initImageStrength.-const PROOF_AS_BASE_DEFAULT_STRENGTH = 0.25;--// Resolve a stored proof filename (e.g. "abc123.png") to an absolute path-// under PATHS.images, enforcing the gallery prefix. `mustExist:false` skips-// the existsSync check — the downstream image-gen runner reads the path and-// will surface a clear error if the file vanished between enqueue and exec;-// an existsSync here would add a TOCTOU race for no real benefit.-const resolveProofInitImage = (proofImage, label) => {- const name = proofImage?.filename;- if (typeof name !== 'string' || !name) {- throw new ServerError(- `Cannot use proof as base for ${label}: no proof render available yet — render the proof first.`,- { status: 400, code: 'PIPELINE_COMIC_PROOF_MISSING' },- );- }- const resolved = resolveGalleryImage(name, { mustExist: false });- if (!resolved) {- throw new ServerError(- `Proof image path escaped the gallery for ${label}: ${name}`,- { status: 400, code: 'PIPELINE_COMIC_PROOF_NOT_FOUND' },- );- }- return resolved;-};--// Consistency-reference denoise: when an ADJACENT page is passed as a reference-// (continuing the same scene so incidental, un-described characters and the-// environment stay consistent), we want the NEW page's composition to come from-// its own prompt while only borrowing identity/style from the reference. So this-// is a HIGH denoise (mostly follow the prompt) — the opposite of proof-as-base's-// 0.25 (preserve layout for an upscale). Local i2i honors it; codex passes the-// reference as an `-i` attachment (reference mode), where strength is moot.-const REFERENCE_PAGE_DEFAULT_STRENGTH = 0.8;--// Default denoise for the per-page "Refine" image-to-image correction (issue-// #1534). The page is re-rendered FROM ITS OWN existing image, so this is a-// low strength: preserve the panel layout / composition / lettering and move-// only enough pixels to honor the small requested change. Higher than-// proof-as-base's 0.25 (which merely upscales) because a refine must actually-// apply an edit; far below the reference path's 0.8 (which mostly follows a-// fresh prompt). Tweakable per-call via options.initImageStrength.-const REFINE_RENDER_DEFAULT_STRENGTH = 0.35;--// Resolve an adjacent page's rendered image to a gallery path for use as a-// consistency reference. Prefers the final render, falls back to the proof.-// Throws a clear 400 when that page hasn't been rendered yet.-const resolvePageReferenceImage = (refPage, label) => {- const name = refPage?.finalImage?.filename || refPage?.proofImage?.filename;- if (typeof name !== 'string' || !name) {- throw new ServerError(- `Cannot use ${label} as a consistency reference: it has no rendered image yet — render that page first.`,- { status: 400, code: 'PIPELINE_COMIC_REFERENCE_MISSING' },- );- }- const resolved = resolveGalleryImage(name, { mustExist: false });- if (!resolved) {- throw new ServerError(- `Reference image path escaped the gallery for ${label}: ${name}`,- { status: 400, code: 'PIPELINE_COMIC_REFERENCE_NOT_FOUND' },- );- }- return resolved;-};--// Resolve the `referencePage` option ('prior' | 'next' | <0-based index>) to a-// concrete page index, or null when unset. Pure + bounds-checked against the-// page count; throws a clear 400 for an out-of-range request (prior on page 1,-// next on the last page, or an explicit index that doesn't exist).-export function resolveReferencePageIndex(referencePage, pageIndex, pageCount) {- if (referencePage == null) return null;- let target;- if (referencePage === 'prior') target = pageIndex - 1;- else if (referencePage === 'next') target = pageIndex + 1;- else if (Number.isInteger(referencePage)) target = referencePage;- else throw new ServerError(`Invalid referencePage: ${referencePage}`, { status: 400, code: 'PIPELINE_COMIC_REFERENCE_BAD' });- if (target === pageIndex) {- throw new ServerError('A page cannot be its own consistency reference', { status: 400, code: 'PIPELINE_COMIC_REFERENCE_SELF' });- }- if (target < 0 || target >= pageCount) {- throw new ServerError(- `Consistency reference page ${target + 1} is out of range (have ${pageCount} page${pageCount === 1 ? '' : 's'})`,- { status: 400, code: 'PIPELINE_COMIC_REFERENCE_RANGE' },- );- }- return target;-}--// Auto-pick a consistency reference for a fresh page render: the immediately-// prior page, but ONLY when it shares this page's scene AND has already been-// rendered. This is the default when the caller doesn't name an explicit-// `referencePage` — so a continuing scene keeps its incidental characters and-// environment consistent page-to-page, while a scene boundary renders fresh-// (the "don't reference the prior page across a scene cut" rule). Pure +-// soft: returns null (rather than throwing) when there's no prior page, the-// scenes differ, scene markers are absent (legacy scripts → no auto-chain), or-// the prior page has no image yet — auto-chaining is a best-effort nicety, not-// a hard requirement like an explicitly requested reference.-export function resolveAutoReferenceIndex(pages, pageIndex) {- const cur = pages?.[pageIndex];- const prior = pages?.[pageIndex - 1];- if (!cur || !prior) return null;- if (!sameComicScene(prior, cur)) return null;- const hasImage = !!(prior.finalImage?.filename || prior.proofImage?.filename);- return hasImage ? pageIndex - 1 : null;-}--// Resolve which init image (if any) a comic-page render should use, applying-// the three precedence tiers in order:-// 1. EXPLICIT `referencePage` ('prior' | 'next' | <index>) — strongest-// intent; bounds-checked (throws on an out-of-range request). `'none'`-// opts out of the AUTO tier (no cross-page reference, even mid-scene).-// 2. PROOF-AS-BASE — a final-variant upscale off this page's own proof. Beats-// auto so "Final from proof" still preserves panel layout. Orthogonal to-// `'none'` (it's a self-upscale, not a sibling reference), so it still-// applies when the user picked 'none' but left the proof-as-base box on.-// 3. AUTO — chain off the prior page when it shares this page's scene and is-// already rendered; a scene boundary (or absent scene markers) skips it.-// Pure; returns the chosen tier so the caller picks the init image + strength-// and logs it. `autoReference` is true only when the AUTO tier supplied the-// page (so callers can distinguish it from an explicit reference).-export function resolveComicPageReference({ referencePage, useProofAsBase, variant, pages, pageIndex }) {- const explicitOff = referencePage === 'none';- const wantsExplicit = !explicitOff && referencePage != null && referencePage !== 'auto';- const explicitIndex = wantsExplicit- ? resolveReferencePageIndex(referencePage, pageIndex, pages.length)- : null;- const fromProof = explicitIndex == null && variant === 'final' && useProofAsBase === true;- const autoIndex = (explicitIndex == null && !fromProof && !explicitOff)- ? resolveAutoReferenceIndex(pages, pageIndex)- : null;- const referencePageIndex = explicitIndex != null ? explicitIndex : autoIndex;- return {- referencePageIndex,- fromReference: referencePageIndex != null,- autoReference: referencePageIndex != null && explicitIndex == null,- fromProof,- };-}--const loadBibleContext = async (issueId) => {- const issueChain = (async () => {- const issue = await getIssue(issueId);- const series = await getSeries(issue.seriesId);- // `.catch(() => null)` covers a dangling universe reference. Empty- // canon still lets scene description flow through; downstream stages- // just lose character / place / object metadata.- const world = await getUniverse(series.universeId).catch(() => null);- return { issue, series, world, canon: pickCanon(world) };- })();- const [chain, settings] = await Promise.all([issueChain, getSettings()]);- return { ...chain, settings };-};--const enqueueImageJob = ({ prompt, world, settings, options, mode, owner, logLine }) => {- // Merge user + world negatives — mirrors composeStyledPrompt's preset- // negative handling so the world's global negative-prompt terms stay in- // effect even when the caller supplies their own additions. Deduplicated- // by token so a user repeating a world negative doesn't double-weight it.- const userNeg = (options.negativePrompt || '').trim();- const worldNeg = joinInfluenceList(world?.influences?.avoid);- const negativeTokens = [userNeg, worldNeg]- .flatMap((s) => s.split(',').map((t) => t.trim()).filter(Boolean));- const negativePrompt = [...new Set(negativeTokens)].join(', ') || undefined;- const baseParams = {- prompt,- negativePrompt,- width: options.width,- height: options.height,- steps: options.steps,- guidance: options.guidance ?? options.cfgScale,- cfgScale: options.cfgScale,- // Honored by local mflux + diffusers runners; codex picks its own.- ...(Number.isFinite(options.seed) ? { seed: options.seed } : {}),- // i2i upscale path: when the caller passes an init image (e.g.- // "use proof as base" for a final render) we forward it to the active- // backend. Local mflux uses it as `--image-path`; codex attaches it via- // the CLI's `-i` flag and routes it to gpt-image-2's image-edit mode.- // The external SD-API backend has no i2i wiring and drops both fields- // at the dispatcher.- ...(options.initImagePath ? { initImagePath: options.initImagePath } : {}),- ...(Number.isFinite(options.initImageStrength) ? { initImageStrength: options.initImageStrength } : {}),- // Character LoRAs resolved by applyCharacterLorasToRender — only the- // local runner honors these (codex has no LoRA support; the resolver is- // skipped there so the spread stays empty).- ...(options.loraFilenames?.length ? { loraFilenames: options.loraFilenames, loraScales: options.loraScales } : {}),- };- // The queue dispatches directly to imageGen/{codex,local}.generateImage,- // bypassing imageGen/index.js's dispatcher that resolves cleaners for- // direct callers. The /api/image-gen/generate route resolves them at the- // route layer; pipeline renders need the same resolution here, otherwise- // the saved settings.imageGen[mode].{cleanC2PA,denoise} would have no- // effect on storyboard, comic-panel, or cover renders.- const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);- const params = mode === IMAGE_GEN_MODE.CODEX- ? { mode: IMAGE_GEN_MODE.CODEX, codexPath: settings.imageGen?.codex?.codexPath, model: settings.imageGen?.codex?.model, cleanC2PA, denoise, ...baseParams }- : { pythonPath: settings.imageGen?.local?.pythonPath || null, modelId: options.modelId, cleanC2PA, denoise, ...baseParams };- const { jobId } = enqueueJob({ kind: 'image', params, owner });- console.log(`${logLine} mode=${mode} jobId=${jobId.slice(0, 8)}`);- return jobId;-};--// Canon places now live on the linked universe (Phase B.4). Callers can-// either pass a pre-built `placeByKey` (when they've already computed it-// for reuse across many scenes — see episodeVideo) or pass `canon` and let-// us build the map here. `series?.places` is no longer read — that field-// was retired with the series-side canon teardown.-export function composeVisualPrompt({ series, description, slugline = '', extraStyle = '', placeByKey = null, matchedCharacters = [], world = null, canon = null, characterAppearances = [] }) {- const map = placeByKey || buildPlaceByKey(canon?.places);- const scenePrompt = buildScenePrompt(- series?.name || '',- { visualPrompt: description || '', slugline, characterAppearances },- matchedCharacters,- stackStyle(series, extraStyle),- matchScenePlace(slugline, map),- );- return applyWorldStyle(scenePrompt, world, series);-}--// Marvel/DC scripts attach parentheticals to speakers — `ETTA (EARPIECE):`,-// `KESSA (WHISPERED):`, `LINA (THOUGHT):`. These tell a human artist HOW to-// draw the balloon (jagged for transmitted voices, dashed for whispers,-// cloud-outline for thoughts), but a diffusion model treats them as more text-// to letter. Map them to visual balloon-style hints so the artist still gets-// the cue without the label leaking into the lettering.-// `disembodied: true` marks a modifier whose SPEAKER is NOT physically in the-// panel — a station PA, a radio voice, an off-panel shout. Without an explicit-// cue the image model gives the line a normal tailed balloon and points it at-// whoever IS drawn (e.g. JUNO's `(SPEAKERS)` PA line got attributed to a-// visible newlywed). formatBalloon turns the flag into a "do NOT tail to any-// visible character" instruction. Order matters — first match wins, so the-// broadcast/PA rule precedes the generic transmission rule.-const BALLOON_STYLE_HINTS = [- { test: /\b(SPEAKERS?|P\.?A\.?|BROADCAST|ANNOUNCE(?:D|S|MENT)?|ANNOUNCER|LOUDSPEAKER|OVERHEAD|INTERCOM|TANNOY|PAGING|STATIONWIDE|SHIPWIDE)\b/, hint: 'jagged electronic broadcast/PA balloon, no tail (disembodied announcement from an overhead source)', disembodied: true },- // Transmission devices are AMBIGUOUS — the speaker may be a visible character- // talking into the device, or a remote voice — so this gets the electronic- // style WITHOUT the "not in panel" claim (that's reserved for unambiguous- // broadcast/off-panel/V.O. above).- { test: /\b(EARPIECE|RADIO|COMMS?|TRANSMISSION|PHONE|HOLO|HOLOGRAM|TV|MONITOR|VIDEO|COMLINK|CHANNEL)\b/, hint: 'jagged electronic/transmission balloon with bolt-shaped tail' },- { test: /\b(OFF[\- ]?PANEL|OFF[\- ]?SCREEN|O\.?S\.?|O\.?P\.?)\b/, hint: 'off-panel balloon with the tail pointing past the panel border', disembodied: true },- { test: /\b(NARRATION|VOICE[\- ]?OVER|V\.?O\.?)\b/, hint: 'rectangular narration caption rather than a speech balloon', disembodied: true },- { test: /\b(WHISPER(?:ED|S|ING)?|SOTTO|HUSHED|QUIET)\b/, hint: 'dashed-outline whisper balloon' },- { test: /\b(SHOUT(?:ED|S|ING)?|YELL(?:ED|S|ING)?|SCREAM(?:ED|S|ING)?|ANGRY|BURST)\b/, hint: 'spiked/burst-shaped balloon' },- { test: /\b(THOUGHT|THINKING|INTERNAL)\b/, hint: 'cloud-outline thought balloon with chain-of-bubbles tail' },- { test: /\b(SING(?:S|ING)?|SONG|MUSICAL)\b/, hint: 'wavy musical balloon with musical-note flourish' },-];--/**- * Build one balloon attribution string: `Speech balloon reads: "<text>" (spoken- * by NAME[, <style hint>]).` Leads with the lettered text so the diffusion- * model anchors on the balloon's contents; parses any parenthetical modifier- * on the speaker into a visual styling hint (radio, whisper, thought, etc.).- * Returns null if `line` is blank — the caller filters those out.- */-function formatBalloon(character, line) {- const text = (line || '').trim();- if (!text) return null;- const raw = (character || '').trim() || 'CHAR';- // Split `NAME (MODIFIER)` → speaker base + modifier text. Tolerate stacked- // parens (`NAME (EARPIECE, WHISPERED)`) by treating the whole inner-paren- // blob as one modifier string for hint detection.- const m = raw.match(/^([^(]+?)\s*\(([^)]*)\)\s*$/);- const speaker = (m ? m[1] : raw).trim() || 'CHAR';- const modifier = m ? m[2].trim() : '';- const cleanText = text.replace(/^"+|"+$/g, '').trim();- const styleEntry = modifier- ? BALLOON_STYLE_HINTS.find((h) => h.test.test(modifier.toUpperCase())) || null- : null;- // A disembodied speaker (PA, radio, off-panel, V.O.) is NOT in the panel, so- // spell that out — otherwise the model letters a normal balloon and tails it- // to whoever IS drawn, mis-attributing the line (the JUNO `(SPEAKERS)` bug).- const attribution = styleEntry?.disembodied- ? `(spoken by ${speaker}, who is NOT visible in this panel — render as a ${styleEntry.hint}; do NOT attach the balloon tail to any visible character)`- : styleEntry- ? `(spoken by ${speaker}; ${styleEntry.hint})`- : `(spoken by ${speaker})`;- // Terminator handled here so endPunct() at the call site doesn't have to- // navigate the closing paren — we always end with `).`.- return `Speech balloon reads: "${cleanText}" ${attribution}.`;-}--// Build the masthead clause for a front cover. When `series.titleLogo` is set,-// it replaces the generic "bold comic-book logo typography" fallback with the-// LLM-designed (or user-edited) design description so every cover renders a-// consistent logo. The series name is still rendered verbatim — the titleLogo-// describes HOW it looks (letterform, finish, color), not WHAT it says.-function buildMastheadClause(series) {- const seriesName = (series?.name || '').trim();- const logoDesign = (series?.titleLogo || '').trim();- if (!seriesName) {- return logoDesign- ? `Render a bold comic-book series masthead near the top of the cover. Logo design: ${logoDesign}`- : 'Render a bold comic-book series masthead as large logo typography near the top of the cover.';- }- return logoDesign- ? `Render the series masthead "${seriesName}" as large comic-book logo typography near the top of the cover. Logo design: ${logoDesign}`- : `Render the series masthead "${seriesName}" as bold, large comic-book logo typography near the top of the cover.`;-}--// Optional author byline injected near the bottom of front covers + trade-// paperback fronts. Skipped when the series has no author set so older series-// still render without an empty "By —" caption.-const buildAuthorClause = (series) => {- const author = (series?.author || '').trim();- return author- ? ` Include a small author byline reading "By ${author}" near the bottom of the cover — restrained, lettered in a smaller weight than the masthead.`- : '';-};--/**- * Compose a comic-book front-cover prompt. The cover always renders the- * series masthead (logo-style title) and the issue number tag in the- * canonical top-of-cover position, plus the user's cover concept as the- * scene content. Falls back to the issue title when the user has not- * written a cover concept yet.- *- * Returns the full prompt string (with world style baked in when present).- */-export function composeComicCoverPrompt({- series, world, issue, coverScript = '', extraStyle = '',-}) {- const issueNumber = Number.isFinite(issue?.number) ? Math.max(1, Math.floor(issue.number)) : 1;- const issueTitle = (issue?.title || '').trim();- const concept = (coverScript || '').trim();-- const styleStack = stackStyle(series, extraStyle);- const styleClause = styleStack ? ` Art style: ${styleStack}.` : '';-- // Title-block requirements get spelled out explicitly because cover-art- // typography is the part image-gen models get most wrong on the first- // pass — without a hard cue the model often emits panels instead of- // a cover, or skips the issue-number tag.- const titleBlock = buildMastheadClause(series);- const numberBlock = `Include a clearly legible issue-number tag reading "#${issueNumber}" in the top-left corner — small but readable.`;- const titleLine = issueTitle- ? ` Include the issue title "${issueTitle}" as a secondary banner below the masthead.`- : '';- const authorLine = buildAuthorClause(series);-- // Fall back to the issue title so a one-click render against a fresh cover- // still produces something thematically on-target instead of a blank canvas.- const sceneDescription = concept- || (issueTitle ? `A single dramatic hero image evoking "${issueTitle}".` : 'A single dramatic hero image of the protagonist mid-action.');-- const layout = `A single full printable comic-book front cover for a serialized issue. ${titleBlock} ${numberBlock}${titleLine}${authorLine} The rest of the cover is one bold hero image (no panel borders, no multi-panel layout — this is the cover, not an interior page).${styleClause}`;- const body = `Cover concept: ${sceneDescription}`;- return applyWorldStyle(`${layout}\n\n${body}`, world, series);-}--/**- * Compose a TV episode title-screen prompt. Reuses the same masthead/logo- * cue the comic covers do — `series.titleLogo` describes the letterform +- * finish, the series name is lettered verbatim, and `series.author` lands as- * a small byline. The episode's number + title appear as secondary- * typography so the screen identifies the specific episode, not just the- * series. Returns the full prompt with world style baked in when present.- *- * Caller decides where to render the result — there is no auto-prepend into- * the episode video pipeline today. Future title-card stages can call this- * directly; for now it is the single source of truth for "what should the TV- * title card for this episode look like."+ * This barrel re-exports the full public surface so every existing+ * `from './visualStages.js'` import path stays valid.*/-export function composeTitleScreenPrompt({- series, world, issue, extraStyle = '',-}) {- const seriesName = (series?.name || '').trim();- const issueNumber = Number.isFinite(issue?.number) ? Math.max(1, Math.floor(issue.number)) : null;- const issueTitle = (issue?.title || '').trim();- const styleStack = stackStyle(series, extraStyle);- const styleClause = styleStack ? ` Art style: ${styleStack}.` : '';-- const titleBlock = buildMastheadClause(series);- const numberLine = issueNumber- ? ` Render an "EPISODE ${issueNumber}" tag in restrained smaller typography, positioned above the masthead.`- : '';- const titleLine = issueTitle- ? ` Render the episode title "${issueTitle}" as a secondary banner below the masthead in a complementary but lighter weight.`- : '';- const authorLine = buildAuthorClause(series);-- const layout = `A single TV episode title screen — a static title card meant to hold on-screen for a few seconds, NOT a story panel. Centered hero typography, generous negative space, cinematic 16:9 framing. ${titleBlock}${numberLine}${titleLine}${authorLine} Subtle background imagery only — atmospheric texture, signature color of the universe, no characters, no narrative scene.${styleClause}`;- return applyWorldStyle(layout, world, series);-}--/**- * 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, series);-}--/**- * 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);- assertStageUnlocked(issue, 'comicPages');- 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 = 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- * hands it to the image-gen queue. Caller records the returned jobId on- * the appropriate variant slot (cover.proofImage / cover.finalImage)- * based on `options.target` ('proof' | 'final', default 'proof').- *- * When `options.useProofAsBase` is set and target='final', resolves the- * existing proof image to an absolute path under PATHS.images and passes- * it through as `initImagePath` so the local i2i runner can preserve- * the proof's composition while rendering at the larger size.- *- * Returns { jobId, mode, prompt, coverScript, variant, fromProof } so the- * route can construct the slot record without re-reading the issue file.- */-export async function enqueueComicCover(issueId, options = {}) {- 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 };-}--/**- * Enqueue + persist a comic-issue cover render (front or back) in ONE service- * call — the shared entry point behind both the route handler and the CDO- * orchestrator tool (#2220). The bare `enqueueComicCover*` only queues the job;- * the filename hook attaches the completed render ONLY if the active cover slot- * already carries the returned jobId, and that slot write used to live in the- * route factory. Extracting it here means the orchestrator gets orchestrated- * covers instead of silently dropping them.- *- * Persists the in-flight render slot onto- * `stages.comicPages.{cover|backCover}.{proofImage|finalImage}` through- * `updateStageWithLatest` (the series write tail) so it serializes against a- * concurrent blur-save of the script field — the script-gate mirrors the route:- * only overwrite `script` when the option is a string (absent preserves, empty- * clears). `options` mirrors the route body (coverScript/backCoverScript,- * width/height, target, useProofAsBase, mode, …).- *- * Returns { jobId, mode, prompt, variant, fromProof, coverScript|backCoverScript,- * issue, stage } — the enqueue result plus the persisted issue + comicPages stage.- */-async function renderComicCoverLike(issueId, target, options = {}) {- const scriptField = target === 'cover' ? 'coverScript' : 'backCoverScript';- const { script, ...rest } = await enqueueComicCoverLike(issueId, target, options);- const slotKey = slotKeyForVariant(rest.variant);- const slotRecord = buildRenderSlot({- slotKey, jobId: rest.jobId, prompt: rest.prompt,- width: options.width, height: options.height, fromProof: rest.fromProof,- });- const { issue, stage } = await updateStageWithLatest(issueId, 'comicPages', (current) => {- const currentSlot = current?.[target] || {};- const nextSlot = { ...currentSlot, [slotKey]: slotRecord };- if (typeof options[scriptField] === 'string') nextSlot.script = options[scriptField];- return { [target]: nextSlot };- });- return { ...rest, [scriptField]: script, issue, stage };-}--/**- * Enqueue + persist a comic-issue FRONT cover render. Wraps `enqueueComicCover`- * plus the slot persist the filename hook depends on. See `renderComicCoverLike`.- */-export const renderComicCover = (issueId, options = {}) =>- renderComicCoverLike(issueId, 'cover', options);--/**- * Enqueue + persist a comic-issue BACK cover render. Lands on- * `stages.comicPages.backCover`. See `renderComicCoverLike`.- */-export const renderComicBackCover = (issueId, options = {}) =>- renderComicCoverLike(issueId, 'backCover', options);--// ---- Volume (season) covers -----------------------------------------------const loadSeasonContext = async (seriesId, seasonId) => {- const seriesChain = (async () => {- const series = await getSeries(seriesId);- const world = await getUniverse(series.universeId).catch(() => 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 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 = buildMastheadClause(series);- 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 authorLine = buildAuthorClause(series);-- 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}${authorLine} 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, series);-}--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, series);-}--/**- * 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(record?.proofImage, `volume ${target}`)- : null;- const initImageStrength = fromProof- ? (Number.isFinite(options.initImageStrength) ? options.initImageStrength : PROOF_AS_BASE_DEFAULT_STRENGTH)- : undefined;- const extraStyle = 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: 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, 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 };-}--/**- * Enqueue + persist a volume (season) cover render (front or back) in ONE- * service call — the shared entry point behind both the route handler and the- * CDO orchestrator (#2220). Mirrors `renderComicCoverLike` but persists the- * in-flight slot onto `series.seasons[].{cover|backCover}` through- * `updateSeasonOnSeries` (the per-series write tail) so the season-cover- * filename hook can attach the completed render.- *- * Returns { jobId, mode, prompt, variant, fromProof, coverScript|backCoverScript,- * season, series } — the enqueue result plus the updated season + series.- */-async function renderVolumeCoverLike(seriesId, seasonId, target, options = {}) {- const scriptField = target === 'cover' ? 'coverScript' : 'backCoverScript';- const { script, ...rest } = await enqueueVolumeCoverLike(seriesId, seasonId, target, options);- const slotKey = slotKeyForVariant(rest.variant);- const slotRecord = buildRenderSlot({- slotKey, jobId: rest.jobId, prompt: rest.prompt,- width: options.width, height: options.height, fromProof: rest.fromProof,- });- const series = await updateSeasonOnSeries(seriesId, seasonId, (current) => {- const currentSlot = current?.[target] || {};- const nextSlot = { ...currentSlot, [slotKey]: slotRecord };- if (typeof options[scriptField] === 'string') nextSlot.script = options[scriptField];- return { [target]: nextSlot };- });- const season = (series.seasons || []).find((s) => s.id === seasonId);- return { ...rest, [scriptField]: script, season, series };-}--/**- * Enqueue + persist a volume (season) FRONT cover render. See- * `renderVolumeCoverLike`.- */-export const renderVolumeCover = (seriesId, seasonId, options = {}) =>- renderVolumeCoverLike(seriesId, seasonId, 'cover', options);--/**- * Enqueue + persist a volume (season) BACK cover render. See- * `renderVolumeCoverLike`.- */-export const renderVolumeBackCover = (seriesId, seasonId, options = {}) =>- renderVolumeCoverLike(seriesId, seasonId, 'backCover', options);--export function composeComicPagePrompt({- series, world, page, pageNumber, extraStyle = '',- matchedCharacters = [], matchedPlaces = [], matchedObjects = [],- // entryId/ingredientId → trained-LoRA trigger word (see- // applyCharacterLorasToRender). Passed as a map so this compose stays pure.- loraTriggerByKey = null,-}) {- const panels = Array.isArray(page?.panels) ? page.panels : [];- if (panels.length === 0) return '';-- // Placed AFTER the layout clause: diffusion models weight earlier tokens- // more heavily, and the page-shape instruction has to claim that position.- // A character with a trained LoRA gets its trigger word parenthesized- // after the name — the token the adapter binds the identity to.- const featuring = (matchedCharacters || [])- .map((c) => ({- name: c.name,- trigger: loraTriggerByKey?.get(c.id) || loraTriggerByKey?.get(c.ingredientId) || null,- desc: (c.physicalDescription || c.description || '').trim(),- }))- .filter((c) => c.name && c.desc)- .map((c) => `${c.name}${c.trigger ? ` (${c.trigger})` : ''}: ${c.desc}`)- .join('; ');-- // Place baseline: pull the full RICH descriptor set per matched place- // (description / Palette / Era / Weather / recurringDetails). Same shared- // helper that drives buildScenePrompt's placeFrags + synthesizeCanonPrompt's- // body, so comic-page renders pick up the same era/weather/atmosphere cues- // diffusion models weight for lighting + period dress. Multi-place per page- // is supported (a single page can span more than one location).- const placesClause = (matchedPlaces || [])- .map((p) => {- const body = flattenCanonDescriptorFragments(richCanonDescriptorFragments('place', p));- const head = p.name ? `${p.name}:` : '';- return [head, body].filter(Boolean).join(' ');- })- .filter(Boolean)- .join(' | ');-- // Notable objects/props/vehicles cited in the prose. Keeps signature props- // (e.g. "the brass key", "Wren's sloop") visually canonical across pages.- const notable = (matchedObjects || [])- .map((o) => ({ name: o.name, desc: (o.description || '').trim() }))- .filter((o) => o.name && o.desc)- .map((o) => `${o.name}: ${o.desc}`)- .join('; ');-- // Append a sentence-terminator unless the source text already ends in one —- // prose extracted from a script often carries its own `.`, `!`, or `?`, and- // double-punctuating like "...sunstreaming in.." is noisy in prompts. The- // optional trailing `"` covers the dialogue/caption case where we wrap the- // text in quotes — `KESSA: "...away."` should NOT become `KESSA: "...away.".`.- const endPunct = (s) => /[.!?]"?$/.test(s) ? s : `${s}.`;-- const panelLines = panels.map((p, i) => {- const idx = i + 1;- const desc = (p.description || '').trim() || 'continuation of previous beat';- const parts = [`Panel ${idx}: ${endPunct(desc)}`];- if (p.caption && p.caption.trim()) parts.push(`Narration caption box reads: "${endPunct(p.caption.trim())}"`);- if (Array.isArray(p.dialogue) && p.dialogue.length > 0) {- // Format each dialogue line as `Speech balloon reads: "<text>" (spoken- // by NAME[, balloon style: <hint>])`. Lettered content (the quoted- // text) leads so the diffusion model anchors on it; speaker + style- // hints trail as attribution. The previous `NAME (MODIFIER): "text"`- // shape (Marvel/DC script convention) was being lettered verbatim- // INTO balloons by the image model — including the speaker name and- // parentheticals like "(EARPIECE)". Dropping speaker into the- // attribution slot and translating common parentheticals to balloon- // styling hints (jagged for radio/earpiece, dashed for whisper, cloud- // for thought) preserves the artistic intent without leaking labels- // into the lettered text.- const dlg = p.dialogue- .map((d) => formatBalloon(d.character, d.line))- .filter(Boolean)- .join(' ');- if (dlg) parts.push(dlg);- }- if (p.sfx && p.sfx.trim()) parts.push(`SFX lettering: ${endPunct(p.sfx.trim())}`);- return parts.join(' ');- });-- const styleStack = stackStyle(series, extraStyle);- const styleClause = styleStack ? ` Art style: ${styleStack}.` : '';- const seriesClause = series?.name ? ` from the series "${series.name}"` : '';-- const layout = `A single full printable comic book page${seriesClause}, page ${pageNumber}. Render a balanced multi-panel comic page layout with ${panels.length} clearly bordered panel${panels.length === 1 ? '' : 's'} arranged for left-to-right, top-to-bottom reading. Include lettered speech balloons for dialogue, rectangular narration boxes for captions, and stylized SFX where indicated. **Balloon lettering rule: each speech balloon contains ONLY the quoted text shown after "Speech balloon reads:". NEVER letter the speaker's name, role, or any parenthetical attribution (e.g. "(EARPIECE)", "(WHISPERED)", "(OFF-PANEL)") inside the balloon — those are tail-direction and balloon-styling cues for the artist, not lettered content.** Each panel must be visually distinct, with consistent character designs across panels.${styleClause}`;- const featuringClause = featuring ? `\n\nFeaturing — ${featuring}` : '';- const placeClause = placesClause ? `\n\nSetting — ${placesClause}` : '';- const notableClause = notable ? `\n\nNotable — ${notable}` : '';-- return applyWorldStyle(`${layout}${featuringClause}${placeClause}${notableClause}\n\n${panelLines.join('\n\n')}`, world, series);-}--/**- * Enqueue a full-comic-page image render. Builds a structured page-level- * prompt from `issue.stages.comicPages.pages[pageIndex].panels[]` and hands- * it to the image-gen queue. Caller records the returned jobId on the- * appropriate variant slot (`pages[pageIndex].proofImage` /- * `pages[pageIndex].finalImage`) based on `options.target`.- *- * When `options.useProofAsBase` is set and target='final', resolves the- * page's existing proof image and passes it as initImagePath so the local- * i2i runner can preserve panel layout while upscaling.- *- * Returns { jobId, mode, prompt, pageIndex, variant, fromProof }.- */-export async function enqueueVisualComicPage(issueId, options = {}) {- const pageIndex = Number(options.pageIndex);- if (!Number.isInteger(pageIndex) || pageIndex < 0) {- throw new ServerError('pageIndex must be a non-negative integer', {- status: 400, code: 'PIPELINE_COMIC_PAGE_BAD_INDEX',- });- }- const { issue, settings, series, world, canon } = await loadBibleContext(issueId);- assertStageUnlocked(issue, 'comicPages');- const pages = Array.isArray(issue.stages?.comicPages?.pages) ? issue.stages.comicPages.pages : [];- const page = pages[pageIndex];- if (!page) {- throw new ServerError(`page index ${pageIndex} out of range (have ${pages.length})`, {- status: 404, code: 'PIPELINE_COMIC_PAGE_NOT_FOUND',- });- }- if (!Array.isArray(page.panels) || page.panels.length === 0) {- throw new ServerError('page has no panels — add at least one panel description before rendering', {- status: 400, code: 'PIPELINE_COMIC_PAGE_NO_PANELS',- });- }-- const mode = resolveMode(options, settings);- const variant = resolveVariant(options.target);-- // Consistency reference: pass an already-rendered page as the init image so a- // continuing scene keeps its incidental, un-described characters and- // environment consistent (the "two newlyweds drift between pages" problem).- // The three-tier precedence (explicit > proof-as-base > auto-within-scene)- // lives in resolveComicPageReference.- const { referencePageIndex, fromReference, autoReference, fromProof } = resolveComicPageReference({- referencePage: options.referencePage,- useProofAsBase: options.useProofAsBase,- variant, pages, pageIndex,- });- const initImagePath = fromReference- ? resolvePageReferenceImage(pages[referencePageIndex], `page ${referencePageIndex + 1}`)- : fromProof- ? resolveProofInitImage(page.proofImage, `page ${pageIndex + 1}`)- : null;- const initImageStrength = fromReference- ? (Number.isFinite(options.initImageStrength) ? options.initImageStrength : REFERENCE_PAGE_DEFAULT_STRENGTH)- : fromProof- ? (Number.isFinite(options.initImageStrength) ? options.initImageStrength : PROOF_AS_BASE_DEFAULT_STRENGTH)- : undefined;-- // Build a free-text haystack from every panel's prose (description +- // caption + sfx). Dialogue lines feed character matching via CAPS names- // separately because the parser already structures them.- const proseHaystack = page.panels- .flatMap((p) => [p.description, p.caption, p.sfx])- .filter(Boolean)- .join('\n');- const dialogueNames = page.panels.flatMap((p) =>- (p.dialogue || []).map((d) => d.character).filter(Boolean),- );-- // Characters: union of (a) dialogue CAPS speakers and (b) anyone named in- // panel prose. Deduplicates on id/name inside the matchers. Canon is read- // from `canon` (Phase B helper) which prefers the linked universe and- // falls back to series arrays for pre-migration data.- const charByKey = buildCharByKey(canon.characters);- const fromDialogue = matchSceneCharacters(dialogueNames, charByKey);- const fromProse = matchCharactersInText(proseHaystack, canon.characters);- const seenCharKeys = new Set();- const matchedCharacters = [...fromDialogue, ...fromProse].filter((c) => {- const k = c.id || c.name;- if (seenCharKeys.has(k)) return false;- seenCharKeys.add(k);- return true;- });-- // Places + objects: text-match against the panel prose. Codex can't take- // reference images, so rich text descriptions in the prompt are how we- // keep environments and signature props visually consistent page-to-page.- const matchedPlaces = matchPlacesInText(proseHaystack, canon.places);- const matchedObjects = matchObjectsInText(proseHaystack, canon.objects);-- // composeComicPagePrompt only returns '' when panels.length === 0, which is- // already rejected above. The "(continuation of previous beat)" placeholder- // covers panels with no description, so the prompt is non-empty by here.- const { loras: characterLoras, triggerByKey } = await applyCharacterLorasToRender({- matchedCharacters, mode, options, settings,- });-- const prompt = composeComicPagePrompt({- series, world, page, pageNumber: pageIndex + 1,- extraStyle: options.extraStyle || '',- matchedCharacters, matchedPlaces, matchedObjects,- loraTriggerByKey: triggerByKey,- });-- const jobId = enqueueImageJob({- prompt, world, settings, mode,- options: { ...options, initImagePath, initImageStrength, ...loraRenderOptions(characterLoras) },- owner: buildComicPagesOwner({ issueId, target: 'page', pageIndex, variant }),- logLine: `📄 Pipeline comic page — issue=${issueId.slice(0, 8)} page=${pageIndex + 1} panels=${page.panels.length} variant=${variant}${fromProof ? ' (from proof)' : ''}${fromReference ? ` (${autoReference ? 'auto-ref' : 'ref'} page ${referencePageIndex + 1})` : ''}`,- });- return { jobId, mode, prompt, pageIndex, variant, fromProof, fromReference, autoReference, referencePageIndex };-}--/**- * Splice an in-flight render slot onto- * `stages.comicPages.pages[pageIndex].{proofImage|finalImage}` through- * `updateStageWithLatest` (the serialized issue write tail) so a concurrent- * page edit or sibling render that wrote between the enqueue and this persist- * can't be reverted by a stale snapshot. Shared by `renderComicPage` and- * `refineComicPageRender` — the filename hook only attaches the completed- * image when the target slot already carries the returned jobId (the reason- * this write must live behind the shared entry points, not only in the route).- *- * Returns { issue, stage } from the write tail.- */-async function persistComicPageSlot(issueId, pageIndex, { variant, jobId, prompt, width, height, fromProof }) {- const slotKey = slotKeyForVariant(variant);- const slotRecord = buildRenderSlot({ slotKey, jobId, prompt, width, height, fromProof });- return updateStageWithLatest(issueId, 'comicPages', (currentStage) => {- const currentPages = Array.isArray(currentStage?.pages) ? currentStage.pages : [];- if (!currentPages[pageIndex]) {- throw new ServerError(- `pageIndex ${pageIndex} out of range — comicPages has ${currentPages.length} page${currentPages.length === 1 ? '' : 's'}`,- { status: 404, code: 'PIPELINE_COMIC_PAGE_NOT_FOUND' },- );- }- const nextPages = [...currentPages];- nextPages[pageIndex] = { ...currentPages[pageIndex], [slotKey]: slotRecord };- return { status: 'edited', pages: nextPages };- });-}--/**- * Enqueue + persist a full comic-page render in ONE service call — the shared- * entry point behind both the route handler and the CDO orchestrator tool- * (#2241, mirroring the #2234 cover treatment). The bare `enqueueVisualComicPage`- * only queues the job; the filename hook attaches the completed render ONLY if- * `pages[pageIndex]`'s active variant slot already carries the returned jobId,- * and that slot write used to live in the route handler. Extracting it here- * means the orchestrator gets orchestrated pages instead of silently dropping- * them. `options` mirrors the route body (target/useProofAsBase/referencePage,- * width/height, mode, …).- *- * Returns the enqueue result plus the persisted { issue, stage }.- */-export async function renderComicPage(issueId, options = {}) {- const result = await enqueueVisualComicPage(issueId, options);- const { issue, stage } = await persistComicPageSlot(issueId, result.pageIndex, {- variant: result.variant, jobId: result.jobId, prompt: result.prompt,- width: options.width, height: options.height, fromProof: result.fromProof,- });- return { ...result, issue, stage };-}--/**- * AI prompt-refine + image-to-image re-render for a SMALL correction to an- * already-rendered comic page (issue #1534). Unlike `enqueueVisualComicPage`- * (which composes a fresh prompt from the page's panels and re-renders from- * source), this:- *- * 1. Takes the page's CURRENT render prompt (stored on the proof/final slot)- * plus the user's free-text instruction, and asks the LLM to ADJUST that- * prompt to reflect the instruction — never regenerating from the comic- * script. Everything not called out by the instruction is preserved.- * 2. Re-renders image-to-image using the page's EXISTING output image as the- * init base at a low denoise, so the panel layout / composition / lettering- * survive and only the requested change moves.- *- * The base image (and the slot the refined render lands back on) is the page's- * final render when present, else its proof; `options.target` forces a variant.- * This is the common "page is mostly right, needs a tweak" case where a full- * re-render from the script would throw away everything good about the current- * output.- *- * Returns { jobId, mode, prompt, pageIndex, variant, changes, runId, providerId }.- */-export async function refineComicPageRender(issueId, options = {}) {- const pageIndex = Number(options.pageIndex);- if (!Number.isInteger(pageIndex) || pageIndex < 0) {- throw new ServerError('pageIndex must be a non-negative integer', {- status: 400, code: 'PIPELINE_COMIC_PAGE_BAD_INDEX',- });- }- const instruction = (options.instruction || '').trim();- if (!instruction) {- throw new ServerError('instruction is required — describe the small change to apply', {- status: 400, code: 'PIPELINE_COMIC_REFINE_NO_INSTRUCTION',- });- }-- const { issue, settings, series, world } = await loadBibleContext(issueId);- assertStageUnlocked(issue, 'comicPages');- const pages = Array.isArray(issue.stages?.comicPages?.pages) ? issue.stages.comicPages.pages : [];- const page = pages[pageIndex];- if (!page) {- throw new ServerError(`page index ${pageIndex} out of range (have ${pages.length})`, {- status: 404, code: 'PIPELINE_COMIC_PAGE_NOT_FOUND',- });- }-- // Mirror the client's getProofSlot: a legacy page (pre proof/final split)- // stores its render at the record root (imageJobId/filename/prompt), and the- // UI surfaces that as the proof slot — so it shows the Refine control. Resolve- // the same legacy shape here, otherwise refining a page whose only render is- // legacy would 400 with NO_RENDER even though the UI shows it as rendered. The- // refined render lands on the proofImage slot, upgrading the record into the- // new shape (same as a /render of a legacy page).- const legacyProofSlot = (!page.proofImage?.filename && (page.imageJobId || page.filename))- ? { filename: page.filename || null, prompt: page.prompt || null }- : null;-- // Resolve which rendered variant to refine: an explicit target wins; else- // prefer the final render, falling back to the proof. The refined render- // lands back on that SAME slot (the user is correcting that image).- const variant = options.target- ? resolveVariant(options.target)- : (page.finalImage?.filename ? 'final' : 'proof');- const baseSlot = variant === 'final'- ? page.finalImage- : (page.proofImage?.filename ? page.proofImage : legacyProofSlot);- const baseFilename = baseSlot?.filename;- if (!baseFilename) {- throw new ServerError(- `Cannot refine page ${pageIndex + 1}'s ${variant} render: it has no rendered image yet — render the page first.`,- { status: 400, code: 'PIPELINE_COMIC_REFINE_NO_RENDER' },- );- }- // The stored slot prompt is what we adjust — refusing to fall back to a- // recomposed-from-script prompt is the whole point (a surgical edit, not a- // redraw). A legacy slot without a persisted prompt must be re-rendered once- // through `/render` (which stamps the prompt) before it can be refined.- const currentPrompt = (baseSlot.prompt || '').trim();- if (!currentPrompt) {- throw new ServerError(- `Cannot refine page ${pageIndex + 1}'s ${variant} render: its stored render prompt is missing — re-render the page first.`,- { status: 400, code: 'PIPELINE_COMIC_REFINE_NO_PROMPT' },- );- }- const initImagePath = resolveGalleryImage(baseFilename, { mustExist: false });- if (!initImagePath) {- throw new ServerError(- `Existing page image path escaped the gallery for page ${pageIndex + 1}: ${baseFilename}`,- { status: 400, code: 'PIPELINE_COMIC_REFINE_NOT_FOUND' },- );- }-- // Ask the LLM to apply the instruction to the existing prompt. resultField- // 'prompt' + runPromptRefine's validation guarantees a non-empty string back;- // `changes` is the short "what I changed" bullet list the UI surfaces.- const { refined, changes, runId, providerId } = await runPromptRefine({- templateName: 'pipeline-comic-page-refine-render',- variables: {- series: seriesBibleCtx(series),- issue: issueCtx(issue),- pageNumber: pageIndex + 1,- currentPrompt: currentPrompt.slice(0, 16_000),- instruction: instruction.slice(0, 2000),- },- options,- source: 'pipeline-comic-page-refine-render',- logTag: `Pipeline comic page refine — issue=${issueId.slice(0, 8)} page=${pageIndex + 1} variant=${variant}`,- });-- const mode = resolveMode(options, settings);- const initImageStrength = Number.isFinite(options.initImageStrength)- ? Math.min(Math.max(options.initImageStrength, 0), 1)- : REFINE_RENDER_DEFAULT_STRENGTH;-- const jobId = enqueueImageJob({- prompt: refined, world, settings, mode,- options: { ...options, initImagePath, initImageStrength },- owner: buildComicPagesOwner({ issueId, target: 'page', pageIndex, variant }),- logLine: `🪄 Pipeline comic page refine — issue=${issueId.slice(0, 8)} page=${pageIndex + 1} variant=${variant} strength=${initImageStrength}`,- });- const { issue: persistedIssue, stage } = await persistComicPageSlot(issueId, pageIndex, {- variant, jobId, prompt: refined, width: options.width, height: options.height,- });- return { jobId, mode, prompt: refined, pageIndex, variant, changes, runId, providerId, issue: persistedIssue, stage };-}--/**- * Validate per-scene wardrobe picks at the request boundary. The generic- * visual-image route accepts `characterAppearances` ([{ characterId,- * wardrobeId? }]) threaded from the storyboards picker; the Zod schema only- * checks shape (non-empty ids), so this is the first point that can confirm- * the ids actually resolve to a canon character + one of its wardrobes.- *- * Throws a 400 ServerError on a dangling characterId/wardrobeId rather than- * leaning on `buildScenePrompt`'s defensive read, which would silently drop- * the pick. A dangling id is a client/state bug (stale picker, deleted- * character) worth surfacing — not a no-op. A null/absent `wardrobeId` is- * valid (the character renders on their canonical body description); only a- * non-empty wardrobeId is resolved against the character's wardrobes.- *- * Scoped to the request boundary on purpose: the persisted-scene paths- * (`enqueueStoryboardSceneVideo`, `enqueueStoryboardShotStartFrame`) and the- * shared `composeVisualPrompt` primitive — also used by episode-video batch- * stitching — keep `buildScenePrompt`'s resilient silent-drop convention so a- * single dangling pick can't abort a whole batch render.- */-export function assertCharacterAppearancesResolve(characterAppearances, characters) {- const picks = Array.isArray(characterAppearances) ? characterAppearances : [];- if (!picks.length) return;- const charById = new Map(- (Array.isArray(characters) ? characters : [])- .filter((c) => c && c.id)- .map((c) => [c.id, c]),- );- for (const pick of picks) {- if (!pick || !pick.characterId) continue;- const character = charById.get(pick.characterId);- if (!character) {- throw new ServerError(- `characterAppearances references unknown character id "${pick.characterId}"`,- { status: 400, code: 'PIPELINE_VISUAL_BAD_CHARACTER' },- );- }- if (pick.wardrobeId) {- const wardrobe = (character.wardrobes || []).find((w) => w && w.id === pick.wardrobeId);- if (!wardrobe) {- throw new ServerError(- `characterAppearances references unknown wardrobe id "${pick.wardrobeId}" for character "${character.name || pick.characterId}"`,- { status: 400, code: 'PIPELINE_VISUAL_BAD_WARDROBE' },- );- }- }- }-}--/**- * Enqueue one image render for a pipeline issue's visual stage. The caller- * records the returned jobId on the issue's stage artifact list- * (e.g. stages.comicPages.pages[i].panels[j].imageJobId).- *- * Returns { jobId, mode, prompt }.- */-export async function enqueueVisualImage(issueId, stageId, options = {}) {- if (!VISUAL_STAGE_IDS.includes(stageId)) {- throw new ServerError(`not a visual stage: ${stageId}`, {- status: 400, code: 'PIPELINE_VISUAL_BAD_STAGE',- });- }- const { issue, settings, series, world, canon } = await loadBibleContext(issueId);- assertStageUnlocked(issue, stageId);- // Resolve wardrobe picks against canon at the request boundary — a dangling- // characterId/wardrobeId is a client/state bug worth a 400, not the silent- // drop buildScenePrompt would otherwise apply.- assertCharacterAppearancesResolve(options.characterAppearances, canon.characters);- const mode = resolveMode(options, settings);- // Match on description + slugline so the featured-character set (and thus- // which wardrobe picks apply) stays consistent with the scene-video / shot- // paths and the storyboards picker UI — all of which match both fields.- const matchedCharacters = matchCharactersInText(- `${options.description || ''} ${options.slugline || ''}`,- canon.characters,- );- const composedPrompt = composeVisualPrompt({- series,- description: options.description,- slugline: options.slugline,- extraStyle: options.extraStyle || '',- matchedCharacters,- world,- canon,- // Storyboard scene renders thread the scene's wardrobe picks through the- // generic visual-image route, which has no scene index to look them up.- characterAppearances: options.characterAppearances,- });- if (!composedPrompt) {- throw new ServerError('visual prompt is empty (no description, no style)', {- status: 400, code: 'PIPELINE_VISUAL_EMPTY_PROMPT',- });- }-- const { loras: characterLoras } = await applyCharacterLorasToRender({- matchedCharacters, mode, options, settings,- });- // composeVisualPrompt is shared with the episode-video batch path, so the- // trigger words append here rather than threading a new param through it.- const triggerClause = characterLoras- .filter((l) => l.triggerWord)- .map((l) => `${l.character?.name || 'character'} (${l.triggerWord})`)- .join(', ');- const prompt = triggerClause ? `${composedPrompt}\n\nFeaturing ${triggerClause}.` : composedPrompt;-- const jobId = enqueueImageJob({- prompt, world, settings, mode,- options: { ...options, ...loraRenderOptions(characterLoras) },- owner: `pipeline:${issueId}:${stageId}`,- logLine: `🎬 Pipeline visual — issue=${issueId.slice(0, 8)} stage=${stageId}`,- });- return { jobId, mode, prompt };-}--/**- * Enqueue a single-scene video render for a storyboard scene. Builds the- * same prompt the episode-video CD treatment would build for this scene- * (composeVisualPrompt with style notes + world style), then enqueues a- * video job through the shared mediaJobQueue.- *- * Persists the resulting jobId on `stages.storyboards.scenes[index]- * .sceneVideoJobId` so the UI can reflect it on reload.- *- * Returns { jobId, prompt, sceneIndex }.- */-export async function enqueueStoryboardSceneVideo(issueId, sceneIndex, options = {}) {- const idx = Number(sceneIndex);- if (!Number.isInteger(idx) || idx < 0) {- throw new ServerError('sceneIndex must be a non-negative integer', {- status: 400, code: 'PIPELINE_SCENE_BAD_INDEX',- });- }- const { issue, settings, series, world, canon } = await loadBibleContext(issueId);- assertStageUnlocked(issue, 'storyboards');- const pythonPath = settings.imageGen?.local?.pythonPath || null;- if (!pythonPath) {- throw new ServerError(- 'Local video generation is not configured (settings.imageGen.local.pythonPath is missing).',- { status: 400, code: 'VIDEO_GEN_NOT_CONFIGURED' },- );- }- const scenes = Array.isArray(issue.stages?.storyboards?.scenes)- ? [...issue.stages.storyboards.scenes]- : [];- const scene = scenes[idx];- if (!scene) {- throw new ServerError(`sceneIndex ${idx} out of range (have ${scenes.length})`, {- status: 404, code: 'PIPELINE_SCENE_NOT_FOUND',- });- }- if (!(scene.description || '').trim()) {- throw new ServerError('scene has no description — add a description before rendering', {- status: 400, code: 'PIPELINE_SCENE_EMPTY_DESCRIPTION',- });- }-- const matchedCharacters = matchCharactersInText(- `${scene.description || ''} ${scene.slugline || ''}`,- canon.characters,- );- const prompt = composeVisualPrompt({- series,- description: scene.description,- slugline: scene.slugline || '',- extraStyle: options.extraStyle || '',- matchedCharacters,- world,- canon,- characterAppearances: scene.characterAppearances,- });-- const aspectRatio = ASPECT_PRESETS[options.aspectRatio] ? options.aspectRatio : '16:9';- const { width, height } = ASPECT_PRESETS[aspectRatio];- const modelId = options.modelId || settings.videoGen?.defaultModelId || getDefaultVideoModelId();- // Validate the model exists for this platform before enqueueing — otherwise- // the worker will fail with "Unknown video model" and leave a persisted- // doomed entry in the queue. Mirrors the same fail-fast pattern as- // /api/video-gen's route validation.- if (!getVideoModels().some((m) => m.id === modelId)) {- throw new ServerError(`Unknown video model "${modelId}"`, {- status: 400, code: 'PIPELINE_UNKNOWN_VIDEO_MODEL',- });- }- const negativePrompt = options.negativePrompt || 'text, watermark, blur, motion blur, low quality';-- const { jobId } = enqueueJob({- kind: 'video',- params: {- pythonPath,- prompt,- negativePrompt,- modelId,- width,- height,- mode: 't2v',- disableAudio: true,- tiling: 'auto',- chunks: 1,- },- owner: `pipeline:${issueId}:storyboards:scene${idx}`,- });-- scenes[idx] = { ...scene, sceneVideoJobId: jobId };- const { issue: updatedIssue, stage } = await updateStage(issueId, 'storyboards', {- status: 'edited',- scenes,- });- console.log(`🎥 Pipeline scene video — issue=${issueId.slice(0, 8)} scene=${idx + 1} jobId=${jobId.slice(0, 8)}`);- return { jobId, prompt, sceneIndex: idx, issue: updatedIssue, stage };-}--/**- * Enqueue an image render for a single shot inside a storyboard scene. Mirror- * of enqueueStoryboardSceneVideo but for IMAGE (start-frame), at shot- * granularity. Shot description is the primary anchor; falls back to the- * parent scene's description when the shot is sparse so a fresh shot still- * renders something coherent.- */-export async function enqueueStoryboardShotStartFrame(issueId, sceneIndex, shotIndex, options = {}) {- const sIdx = Number(sceneIndex);- const tIdx = Number(shotIndex);- if (!Number.isInteger(sIdx) || sIdx < 0 || !Number.isInteger(tIdx) || tIdx < 0) {- throw new ServerError('sceneIndex and shotIndex must be non-negative integers', {- status: 400, code: 'PIPELINE_SHOT_BAD_INDEX',- });- }- const { issue, settings, series, world, canon } = await loadBibleContext(issueId);- assertStageUnlocked(issue, 'storyboards');- const scenes = Array.isArray(issue.stages?.storyboards?.scenes)- ? [...issue.stages.storyboards.scenes]- : [];- const scene = scenes[sIdx];- if (!scene) {- throw new ServerError(`sceneIndex ${sIdx} out of range (have ${scenes.length})`, {- status: 404, code: 'PIPELINE_SCENE_NOT_FOUND',- });- }- const shots = Array.isArray(scene.shots) ? [...scene.shots] : [];- const shot = shots[tIdx];- if (!shot) {- throw new ServerError(`shotIndex ${tIdx} out of range (have ${shots.length})`, {- status: 404, code: 'PIPELINE_SHOT_NOT_FOUND',- });- }-- const shotDescription = (shot.description || '').trim();- const description = shotDescription || (scene.description || '').trim();- if (!description) {- throw new ServerError('shot has no description (parent scene also empty) — add a description first', {- status: 400, code: 'PIPELINE_SHOT_EMPTY_DESCRIPTION',- });- }-- const mode = resolveMode(options, settings);- const matchedCharacters = matchCharactersInText(- `${description} ${scene.slugline || ''}`,- canon.characters,- );- const prompt = composeVisualPrompt({- series,- description,- slugline: scene.slugline || '',- extraStyle: options.extraStyle || '',- matchedCharacters,- world,- canon,- // A shot inherits its parent scene's wardrobe picks.- characterAppearances: scene.characterAppearances,- });-- const jobId = enqueueImageJob({- prompt, world, settings, options, mode,- owner: buildStoryboardsShotOwner({ issueId, sceneIndex: sIdx, shotIndex: tIdx }),- logLine: `🎞️ Pipeline shot start-frame — issue=${issueId.slice(0, 8)} scene=${sIdx + 1} shot=${tIdx + 1}`,- });-- shots[tIdx] = { ...shot, startFrameJobId: jobId };- scenes[sIdx] = { ...scene, shots };- const { issue: updatedIssue, stage } = await updateStage(issueId, 'storyboards', {- status: 'edited',- scenes,- });- return { jobId, mode, prompt, sceneIndex: sIdx, shotIndex: tIdx, issue: updatedIssue, stage };-}--const seriesBibleCtx = (series) => ({- name: series.name || '',- styleNotes: series.styleNotes || '',- logline: series.logline || '',- premise: series.premise || '',-});--const issueCtx = (issue) => ({ number: issue.number || 0, title: issue.title || '' });--const neighborText = (item) => (item?.description || '').trim().slice(0, 240) || '(empty)';--// Refine path needs issue + series only — skip the settings + world reads-// that loadBibleContext does for the image/video enqueue path.-async function loadRefineContext(issueId) {- const issue = await getIssue(issueId);- const series = await getSeries(issue.seriesId);- return { issue, series };-}---// Validate the page/panel indices, lock, and non-empty description, then-// build the `pipeline-comic-panel-image-prompt` template variables. Shared by-// the 1:1 refine (replaces the description) and the N-candidate fan-out-// (non-destructive) so both feed the LLM identical context.-async function loadComicPanelPromptContext(issueId, pageIndex, panelIndex) {- const pi = Number(pageIndex);- const ni = Number(panelIndex);- if (!Number.isInteger(pi) || pi < 0 || !Number.isInteger(ni) || ni < 0) {- throw new ServerError('pageIndex and panelIndex must be non-negative integers', {- status: 400, code: 'PIPELINE_PANEL_BAD_INDEX',- });- }- const { issue, series } = await loadRefineContext(issueId);- assertStageUnlocked(issue, 'comicPages');- const pages = Array.isArray(issue.stages?.comicPages?.pages) ? [...issue.stages.comicPages.pages] : [];- const page = pages[pi];- if (!page) {- throw new ServerError(`pageIndex ${pi} out of range (have ${pages.length})`, {- status: 404, code: 'PIPELINE_COMIC_PAGE_NOT_FOUND',- });- }- const panels = Array.isArray(page.panels) ? [...page.panels] : [];- const panel = panels[ni];- if (!panel) {- throw new ServerError(`panelIndex ${ni} out of range (have ${panels.length})`, {- status: 404, code: 'PIPELINE_COMIC_PANEL_NOT_FOUND',- });- }- if (!(panel.description || '').trim()) {- throw new ServerError('panel has no description to refine', {- status: 400, code: 'PIPELINE_PANEL_EMPTY_DESCRIPTION',- });- }-- const prev = panels[ni - 1];- const next = panels[ni + 1];- // Drop dialogue rows whose line is empty/whitespace — matches the same- // filter `composeComicPagePrompt` applies, so the refine template doesn't- // get fed noisy `CHAR: ""` fragments that would confuse the LLM.- const dialogue = Array.isArray(panel.dialogue) && panel.dialogue.length- ? panel.dialogue- .map((d) => {- const character = (d.character || 'CHAR').trim() || 'CHAR';- const line = (d.line || '').trim();- return line ? `${character}: "${line}"` : null;- })- .filter(Boolean)- .join(' / ')- : '';-- const variables = {- series: seriesBibleCtx(series),- issue: issueCtx(issue),- pageNumber: pi + 1,- panelNumber: ni + 1,- panelCount: panels.length,- description: (panel.description || '').slice(0, 4000),- caption: (panel.caption || '').slice(0, 1000),- hasCaption: !!(panel.caption || '').trim(),- dialogue,- hasDialogue: !!dialogue,- sfx: (panel.sfx || '').slice(0, 500),- hasSfx: !!(panel.sfx || '').trim(),- hasNeighbors: !!(prev || next),- previousPanel: neighborText(prev),- nextPanel: neighborText(next),- };- return { issue, pi, ni, pages, page, panels, panel, variables };-}--/**- * Run the `pipeline-comic-panel-image-prompt` template against the current- * panel + surrounding context, then persist the refined description on the- * panel. Returns { panel, page, issue, stage, runId, changes, providerId }.- */-export async function refineComicPanelPrompt(issueId, pageIndex, panelIndex, options = {}) {- const { pi, ni, pages, page, panels, panel, variables } =- await loadComicPanelPromptContext(issueId, pageIndex, panelIndex);-- const { refined, changes, runId, providerId } = await runPromptRefine({- templateName: 'pipeline-comic-panel-image-prompt',- variables,- options,- source: 'pipeline-comic-panel-prompt-refine',- logTag: `Pipeline comic panel refine — issue=${issueId.slice(0, 8)} p=${pi + 1} panel=${ni + 1}`,- });-- panels[ni] = { ...panel, description: refined };- pages[pi] = { ...page, panels };- const { issue: updatedIssue, stage } = await updateStage(issueId, 'comicPages', {- status: 'edited',- pages,- });- return { panel: panels[ni], page: pages[pi], issue: updatedIssue, stage, runId, changes, providerId };-}--/**- * Generate N candidate image-gen prompts for a single comic panel WITHOUT- * mutating the panel (issue #904). The user copies one or applies it to the- * description via the existing refine/edit paths. Returns- * { candidates, requested, pageIndex, panelIndex }.- */-export async function generateComicPanelImagePrompts(issueId, pageIndex, panelIndex, { count, ...options } = {}) {- const { pi, ni, variables } = await loadComicPanelPromptContext(issueId, pageIndex, panelIndex);- const { candidates, requested } = await runImagePromptCandidates({- count,- templateName: 'pipeline-comic-panel-image-prompt',- variables,- options,- source: 'pipeline-comic-panel-image-prompts',- logTag: `Pipeline comic panel image-prompts — issue=${issueId.slice(0, 8)} p=${pi + 1} panel=${ni + 1}`,- });- return { candidates, requested, pageIndex: pi, panelIndex: ni };-}--// Validate the scene index, lock, and non-empty description, then build the-// `pipeline-storyboard-image-prompt` template variables. Shared by the 1:1-// refine and the N-candidate fan-out so both feed the LLM identical context.-async function loadStoryboardScenePromptContext(issueId, sceneIndex) {- const idx = Number(sceneIndex);- if (!Number.isInteger(idx) || idx < 0) {- throw new ServerError('sceneIndex must be a non-negative integer', {- status: 400, code: 'PIPELINE_SCENE_BAD_INDEX',- });- }- const { issue, series } = await loadRefineContext(issueId);- assertStageUnlocked(issue, 'storyboards');- const scenes = Array.isArray(issue.stages?.storyboards?.scenes)- ? [...issue.stages.storyboards.scenes]- : [];- const scene = scenes[idx];- if (!scene) {- throw new ServerError(`sceneIndex ${idx} out of range (have ${scenes.length})`, {- status: 404, code: 'PIPELINE_SCENE_NOT_FOUND',- });- }- if (!(scene.description || '').trim()) {- throw new ServerError('scene has no description to refine', {- status: 400, code: 'PIPELINE_SCENE_EMPTY_DESCRIPTION',- });- }-- const prev = scenes[idx - 1];- const next = scenes[idx + 1];- const variables = {- series: seriesBibleCtx(series),- issue: issueCtx(issue),- sceneNumber: idx + 1,- sceneCount: scenes.length,- slugline: (scene.slugline || '').slice(0, 200),- hasSlugline: !!(scene.slugline || '').trim(),- description: (scene.description || '').slice(0, 4000),- hasNeighbors: !!(prev || next),- previousScene: neighborText(prev),- nextScene: neighborText(next),- };- return { issue, idx, scenes, scene, variables };-}--/**- * Run the `pipeline-storyboard-image-prompt` template against the current- * storyboard scene + surrounding context, then persist the refined- * description on the scene. Returns { scene, issue, stage, runId, changes, providerId }.- */-export async function refineStoryboardScenePrompt(issueId, sceneIndex, options = {}) {- const { idx, scenes, scene, variables } = await loadStoryboardScenePromptContext(issueId, sceneIndex);-- const { refined, changes, runId, providerId } = await runPromptRefine({- templateName: 'pipeline-storyboard-image-prompt',- variables,- options,- source: 'pipeline-storyboard-prompt-refine',- logTag: `Pipeline scene refine — issue=${issueId.slice(0, 8)} scene=${idx + 1}`,- });-- scenes[idx] = { ...scene, description: refined };- const { issue: updatedIssue, stage } = await updateStage(issueId, 'storyboards', {- status: 'edited',- scenes,- });- return { scene: scenes[idx], issue: updatedIssue, stage, runId, changes, providerId };-}--/**- * Generate N candidate image-gen prompts for a single storyboard scene- * WITHOUT mutating the scene (issue #904). Returns- * { candidates, requested, sceneIndex }.- */-export async function generateStoryboardSceneImagePrompts(issueId, sceneIndex, { count, ...options } = {}) {- const { idx, variables } = await loadStoryboardScenePromptContext(issueId, sceneIndex);- const { candidates, requested } = await runImagePromptCandidates({- count,- templateName: 'pipeline-storyboard-image-prompt',- variables,- options,- source: 'pipeline-storyboard-image-prompts',- logTag: `Pipeline scene image-prompts — issue=${issueId.slice(0, 8)} scene=${idx + 1}`,- });- return { candidates, requested, sceneIndex: idx };-}+export * from './visualStageHelpers.js';+export * from './covers.js';+export * from './comicPages.js';+export * from './storyboards.js';