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
Mark comic pages by scene so renders chain within a scene and break across cuts
[._.]/ Adam Eivycb85498cdb39
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 8ea83b5332..fa88a554f8 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -14,6 +14,7 @@## Comic pages+- **Comic pages now carry scene markers, and page renders chain within a scene but start fresh across a scene cut.** Scene boundaries are established once at the beat-sheet stage as a canonical `## Scenes` list (numbered `INT./EXT. LOCATION — TIME` sluglines) and flow down through the prose draft into the comic script, which now tags each page header `## Page N — Scene M: SLUGLINE`. The Comic tab shows the scene on every page, and the parser records `sceneNumber`/`sceneHeading` per page. The payoff is in rendering: the consistency-reference picker now defaults to **auto**, which uses the *previous* page as an image reference only when that page is in the **same scene** and already rendered — so incidental, un-described characters and the environment stay consistent through a continuing scene, while the first page of a new scene renders clean instead of dragging the prior scene's look across the cut. You can still override per page: **none** forces a fresh render mid-scene, or pick **prev/next page** to force a specific reference (e.g. to fix a character-consistency drift across a scene boundary). Pages with no scene markers (legacy comics) behave exactly as before — no auto-chaining. (Series Autopilot's page renders inherit the same within-scene continuity automatically.)- **[issue-1534] Refine a rendered comic page with a small fix instead of re-rendering it from scratch.** Each rendered page now has a **Refine** box: type a free-text adjustment ("warm the lighting", "remove the extra signage text", "make the two background figures match across panels") and the page re-renders image-to-image from its *existing* image, applying only that change while preserving everything that was already right. The AI tweaks the page's current render prompt to reflect your instruction (it does not regenerate the prompt from the comic script), then runs a low-denoise re-render off the page's own image — so the panel layout, composition, and lettering survive. It refines the page's final render when one exists, otherwise its proof, and shows a short "what changed" summary after each refine. Works with both the local and Codex image backends.## ChatGPT importdiff --git a/client/src/components/pipeline/stages/ComicScriptStage.jsx b/client/src/components/pipeline/stages/ComicScriptStage.jsxindex 8838e9dfce..1b0414c0f1 100644--- a/client/src/components/pipeline/stages/ComicScriptStage.jsx+++ b/client/src/components/pipeline/stages/ComicScriptStage.jsx@@ -846,11 +846,12 @@ function PageRow({const handleRender = async (target) => {const setFlight = target === 'final' ? setRenderingFinal : setRenderingProof;setFlight(true);- // A selected consistency reference takes precedence over proof-as-base- // (the server resolves referencePage first), so don't claim/require proof- // in that case — otherwise the Final button's proof gate blocks a- // reference-only render and the toast mislabels it "(from proof)".- const useProofAsBase = target === 'final' && useProofForFinal && !refPage;+ // Only an EXPLICIT adjacent reference ('prior'/'next') takes precedence over+ // proof-as-base (the server resolves it first). 'auto' and 'none' leave+ // proof-as-base intact: 'none' just forbids an auto reference, and an auto+ // reference is itself lower precedence than proof-as-base server-side.+ const explicitRef = refPage === 'prior' || refPage === 'next';+ const useProofAsBase = target === 'final' && useProofForFinal && !explicitRef;const res = await generatePipelineComicPage(issue.id, pageIndex, {...renderOpts,target,@@ -860,8 +861,13 @@ function PageRow({setFlight(false);if (res) {onStageUpdate?.('comicPages', res.stage);- const refSuffix = refPage ? ` (ref: ${refPage} page)` : '';- const suffix = useProofAsBase ? ' (from proof)' : refSuffix;+ // Prefer the server's resolved outcome — auto may or may not have found a+ // same-scene prior page with a render, so trust res over the local intent.+ const suffix = res.fromProof+ ? ' (from proof)'+ : res.fromReference+ ? ` (${res.autoReference ? 'auto-ref' : 'ref'} page ${res.referencePageIndex + 1})`+ : '';toast.success(`Page ${pageIndex + 1} ${target}${suffix} render queued (${res.mode || renderOpts.mode || IMAGE_GEN_MODE.LOCAL})`);}};@@ -897,9 +903,10 @@ function PageRow({}};- // A selected reference render uses the adjacent page (not this page's proof)+ // An EXPLICIT adjacent reference render uses that page (not this page's proof)// as its base, so it doesn't need a proof to exist — only proof-as-base does.- const finalNeedsProof = useProofForFinal && !refPage && !proofSlot?.filename;+ // 'auto'/'none' still go through proof-as-base, so they keep the proof gate.+ const finalNeedsProof = useProofForFinal && !(refPage === 'prior' || refPage === 'next') && !proofSlot?.filename;// The Refine control only makes sense once the page has a render to correct// (final preferred, else proof). Gate on jobId OR filename — not filename// alone: refining a proof-only page replaces its slot with an in-flight@@ -912,8 +919,16 @@ function PageRow({return (<li className="rounded-lg border border-port-border bg-port-card/40"><div className="flex items-center justify-between gap-2 px-3 py-2 border-b border-port-border flex-wrap">- <div className="flex items-center gap-2">+ <div className="flex items-center gap-2 flex-wrap"><span className="text-xs uppercase tracking-wider text-gray-500">Page {pageIndex + 1}</span>+ {(Number.isInteger(page.sceneNumber) || page.sceneHeading) ? (+ <span+ className="text-[10px] text-port-accent/80 border border-port-accent/30 rounded px-1"+ title="The scene this page belongs to. Renders auto-chain off the prior page within the same scene and start fresh across a scene boundary."+ >+ {Number.isInteger(page.sceneNumber) ? `Scene ${page.sceneNumber}` : 'Scene'}{page.sceneHeading ? `: ${page.sceneHeading}` : ''}+ </span>+ ) : null}<span className="text-[10px] text-gray-600">{page.panels?.length || 0} panel{page.panels?.length === 1 ? '' : 's'}</span>{dirty ? <span className="text-[10px] text-port-warning">unsaved</span> : null}</div>@@ -927,24 +942,23 @@ function PageRow({{saving ? <Loader2 size={12} className="animate-spin" /> : <Save size={12} />}Save</button>- {(hasPrior || hasNext) ? (- <label- className="flex items-center gap-1 text-[11px] text-gray-400"- title="Render this page using an adjacent page's image as a consistency reference — keeps incidental, un-described characters and the environment consistent across a continuing scene."+ <label+ className="flex items-center gap-1 text-[11px] text-gray-400"+ title="Consistency reference for this page's render. 'auto' chains off the prior page when it's in the same scene (keeps incidental characters + environment consistent) and renders fresh across a scene boundary. 'none' forces a fresh render even mid-scene. 'prev/next page' force that specific page as the reference."+ >+ <span className="text-gray-500">ref</span>+ <select+ value={refPage}+ onChange={(e) => setRefPage(e.target.value)}+ className="bg-port-bg border border-port-border rounded text-[11px] text-white px-1 py-0.5"+ aria-label={`Consistency reference page for page ${pageIndex + 1}`}>- <span className="text-gray-500">ref</span>- <select- value={refPage}- onChange={(e) => setRefPage(e.target.value)}- className="bg-port-bg border border-port-border rounded text-[11px] text-white px-1 py-0.5"- aria-label={`Consistency reference page for page ${pageIndex + 1}`}- >- <option value="">none</option>- {hasPrior ? <option value="prior">prev page</option> : null}- {hasNext ? <option value="next">next page</option> : null}- </select>- </label>- ) : null}+ <option value="">auto (same scene)</option>+ <option value="none">none (fresh)</option>+ {hasPrior ? <option value="prior">prev page</option> : null}+ {hasNext ? <option value="next">next page</option> : null}+ </select>+ </label><buttontype="button"onClick={() => handleRender('proof')}diff --git a/data.reference/prompts/stages/pipeline-comic-script.md b/data.reference/prompts/stages/pipeline-comic-script.mdindex 2f3c6b9b11..5b7cdcc033 100644--- a/data.reference/prompts/stages/pipeline-comic-script.md+++ b/data.reference/prompts/stages/pipeline-comic-script.md@@ -70,7 +70,7 @@ aftermath beat. NO text, NO masthead, NO logos, NO panel borders — therenderer will explicitly forbid typography. Focus on subject, framing,mood, and a striking visual detail.>-## Page 1+## Page 1 — Scene 1: INT./EXT. LOCATION — TIMEPanel 1Description: <visually concrete description of the frame: subjects, action, framing (wide / medium / close), lighting, mood>@@ -84,10 +84,13 @@ Panel 2...```+The `— Scene N: SLUGLINE` suffix on each `## Page N` header is the **scene marker** (see the scene-continuity rule below). The `## Page N` part and its number are unchanged — the suffix is additive.+## Rules- **Target a {{lengthTargets.pageTarget}}-page single issue.** Pace the source material across exactly {{lengthTargets.pageTarget}} pages — inflate quiet beats with reaction shots, environmental panels, and silent panels if the source is thin; compress dense action across multiple pages with panel-to-panel motion if it is rich. Do not pad for padding's sake, but do not skip pages either.- Plan **4–6 panels per page on average**, with occasional 1-panel splashes for big reveals, double-page spreads (`Panel 1 (DPS)`) for major action, and the rare 7–8 panel grid for fast cuts.+- **Tag every page header with its scene: `## Page N — Scene M: SLUGLINE`.** The source material is divided into scenes (the prose draft marks them with `## Scene N — Slugline` headers; the beat sheet lists them). Carry that scene structure onto the pages. A scene is a continuous unit of place + time — increment the scene number (and write a new `INT./EXT. LOCATION — TIME` slugline) **only** when the location, time, or POV genuinely shifts. Consecutive pages inside one scene MUST repeat the same `Scene M: SLUGLINE` so the renderer knows they're continuous and keeps characters/environment consistent across them; the FIRST page of a new scene starts the new number, which signals the renderer to start that page fresh. If the source has no scene divisions, infer them from where place/time/POV change. Use the exact slugline form `INT.`/`EXT.` + LOCATION + `—` + TIME (e.g. `EXT. ROOFTOP — DUSK`). The suffix is the ONLY thing that may follow the page number — never put panel content there.- **NEVER put action, dialogue, or scene content in the page-level description.** Any text you place between a `## Page N` header and its first `Panel` is layout intent ONLY — **1–3 lines max** (e.g. "Six-panel grid, tight cuts" or "Full-page splash"), or omit it entirely. Every beat of action, every line of dialogue, every caption, and all scene content MUST live inside a `Panel N` block, never in the page header. A page whose content lands in the page-level description instead of panels is malformed and will not render.- **Every page MUST decompose into discrete `Panel N` blocks** (how many follows the panel-count rule above — 4–6 on average, a single `Panel 1` for a splash, the rare 7–8 grid for fast cuts), each carrying its own `Description:`, `Caption:`, `Dialogue:`, and `SFX:` fields (use `(none)` for an empty caption/SFX rather than dropping the field). A page rendered as loose prose under the header instead of numbered panel blocks is malformed and will not render — even a splash is written as `Panel 1`, never as page-level prose.- **Visible in-world text must be exact.** If a panel shows readable text inside the art — a draft line, screen, sign, note, terminal, label, projected warning, highlighted sentence, erased line, etc. — quote the exact words in `Description:`. If a later panel highlights, changes, reacts to, or removes that same text, repeat the same wording or state precisely that those quoted words are no longer visible. Never refer to an unnamed "second line," "new line," "draft text," or similar text beat without specifying what the reader sees.@@ -103,4 +106,4 @@ Panel 2- Never re-describe a character's permanent appearance once introduced; just name them.- Vary page rhythm: don't let every page be the same panel count. Use page turns deliberately — what the reader sees when they turn from an odd page to the next even page is one of the strongest tools you have. Land big reveals on page-turn moments.-Return ONLY the script. No preamble, no commentary. The output MUST start with the `# Issue {{issue.number}} — <Title>` heading, followed immediately by the `## Cover concept` section, then the `## Back cover concept` section, then exactly {{lengthTargets.pageTarget}} `## Page N` headers numbered Page 1 through Page {{lengthTargets.pageTarget}}.+Return ONLY the script. No preamble, no commentary. The output MUST start with the `# Issue {{issue.number}} — <Title>` heading, followed immediately by the `## Cover concept` section, then the `## Back cover concept` section, then exactly {{lengthTargets.pageTarget}} `## Page N — Scene M: SLUGLINE` headers numbered Page 1 through Page {{lengthTargets.pageTarget}}, each carrying its scene marker.diff --git a/data.reference/prompts/stages/pipeline-idea-expansion.md b/data.reference/prompts/stages/pipeline-idea-expansion.mdindex 87da2eb22e..a5acd9ab1e 100644--- a/data.reference/prompts/stages/pipeline-idea-expansion.md+++ b/data.reference/prompts/stages/pipeline-idea-expansion.md@@ -165,9 +165,10 @@ A markdown document with the following sections, in this exact order:2. **`## Logline`** — one sentence pitching the issue.3. **`## Theme`** — one sentence on the emotional/thematic core. What is this issue *about* underneath the plot?4. **`## Beat sheet`** — **{{lengthTargets.beatsMin}}–{{lengthTargets.beatsMax}} beats** numbered as a markdown list. Each beat is one sentence describing a concrete dramatic event. Cover **hook (Saga-style opening — a single arresting image or moment, not exposition) → setup → rising action → midpoint reversal → second-half escalation → climax → cliffhanger / lead-in to the next issue.** This beat sheet feeds a {{lengthTargets.proseWordsMin}}–{{lengthTargets.proseWordsMax}} word prose draft, which feeds a {{lengthTargets.pageTarget}}-page comic script — too few beats and the downstream stages have nothing to pace against. Every beat must stay within THIS issue's scope (the seed — or, when back-filling, the source material — above); do not dramatize events the neighboring issues own. The final beat MUST be a cliffhanger, reveal, or strong lead-in to the next issue, not a tidy resolution — and it must be THIS issue's cliffhanger, not the next issue's climax.-5. **`## Setting`** — 2–3 sentences naming the locations this issue uses and how they look. Reference the world's visual style.-6. **`## New characters (if any)`** — for any character the seed introduces that isn't in the series bible, give a one-line `**Name** — physical + role description`. Skip the section if there are none.-7. **`## Open questions` (OPTIONAL — usually omit)** — ONLY include this section when something fundamentally cannot be decided without user input (e.g. the seed asks the writer to choose between two specific named entities, or references off-canvas information only the user knows). Do NOT use this section for choices you could make yourself by leaning on the series bible. If every beat is committed, omit the section entirely.+5. **`## Scenes`** — the canonical scene list for this issue, a numbered markdown list. Each entry is `Scene N — INT./EXT. LOCATION — TIME` followed by a short clause naming which beats it covers (e.g. `Scene 1 — EXT. ROOFTOP — DUSK: beats 1–2, the hook and Lina's discovery`). A **scene** is one continuous unit of place + time — start a new scene only when the location, time, or POV shifts. These sluglines are the single source of truth for scene boundaries downstream: the prose draft, comic script, and teleplay all inherit them, so be deliberate and use the exact slugline form `INT.`/`EXT.` + LOCATION + `—` + TIME. Aim for a handful of scenes (typically fewer than the beat count — several beats often share one scene).+6. **`## Setting`** — 2–3 sentences naming the locations this issue uses and how they look. Reference the world's visual style.+7. **`## New characters (if any)`** — for any character the seed introduces that isn't in the series bible, give a one-line `**Name** — physical + role description`. Skip the section if there are none.+8. **`## Open questions` (OPTIONAL — usually omit)** — ONLY include this section when something fundamentally cannot be decided without user input (e.g. the seed asks the writer to choose between two specific named entities, or references off-canvas information only the user knows). Do NOT use this section for choices you could make yourself by leaning on the series bible. If every beat is committed, omit the section entirely.Be concrete. Beats like "the character has an internal moment" are useless; beats like "Lina finds the burnt photograph hidden under the floorboard and recognizes the figure as her uncle" are useful.diff --git a/data.reference/prompts/stages/pipeline-prose.md b/data.reference/prompts/stages/pipeline-prose.mdindex 04b14e2b08..a3c9fe8776 100644--- a/data.reference/prompts/stages/pipeline-prose.md+++ b/data.reference/prompts/stages/pipeline-prose.md@@ -51,7 +51,7 @@ User-supplied source follows. Treat everything between the `~~~~~~~~~~~~~~~~` fe## What to write-A self-contained short-story draft for this issue, **{{lengthTargets.proseWordsMin}}–{{lengthTargets.proseWordsMax}} words** (sized to feed a {{lengthTargets.pageTarget}}-page comic adaptation downstream — too thin and the script writer has to invent filler beats). Structure it with H2 markdown scene breaks (`## Scene N — Slugline`) every time the location, time, or POV shifts — these scene breaks become the anchor points for the later script adaptations, so be deliberate about them. Plan for natural page-turn beats — this issue should have **{{lengthTargets.beatsMin}}–{{lengthTargets.beatsMax}} scenes**.+A self-contained short-story draft for this issue, **{{lengthTargets.proseWordsMin}}–{{lengthTargets.proseWordsMax}} words** (sized to feed a {{lengthTargets.pageTarget}}-page comic adaptation downstream — too thin and the script writer has to invent filler beats). Structure it with H2 markdown scene breaks (`## Scene N — Slugline`) every time the location, time, or POV shifts — these scene breaks become the anchor points for the later script adaptations, so be deliberate about them. **If the source material includes a `## Scenes` list (the beat sheet's canonical scene list), reuse those scene numbers and sluglines verbatim** — that list is the single source of truth for scene boundaries across every adaptation, so don't renumber or re-slug them. When no scene list is provided, derive the boundaries yourself from where place/time/POV change. Plan for natural page-turn beats.- Write in **present tense** throughout — every action, every beat. Present tense reads "she opens the door," not "she opened the door." This is non-negotiable: the downstream comic and TV adaptations both work in present tense, and matching tense upstream keeps the visual beats translatable. Use third-person POV unless the series notes specify otherwise.- **Open in a hook (Saga-style):** start in a specific sensory moment — a striking image, an arresting action, or a single line of voice-over that lands the reader inside the story. No "previously on" exposition. The opening paragraph is the first thing the comic page-1 splash will render, so make it visually loaded.diff --git a/scripts/migrations/003-update-pipeline-stage-prompts.js b/scripts/migrations/003-update-pipeline-stage-prompts.jsindex 3cfbd796e6..70c37121aa 100644--- a/scripts/migrations/003-update-pipeline-stage-prompts.js+++ b/scripts/migrations/003-update-pipeline-stage-prompts.js@@ -19,7 +19,7 @@import { makePromptReplaceMigration } from './_lib.js';export const ACCEPTED_OLD_MD5 = {- 'pipeline-idea-expansion.md': [+ 'pipeline-idea-expansion.md': [ '93e9552c6662811e597a97296f3776a4','aee25112b2c596f643b17c559b772c22', // pre-003 (original)'41facefbc0c0549d456bef9111f95ab9', // post-003 / pre-004 — the hash this migration originally produced'1ee44cf95851ff8debf18729ebcd40b4', // post-004 / pre-025@@ -27,13 +27,13 @@ export const ACCEPTED_OLD_MD5 = {'b5c47c94ffc74637983c95761ab0c66c', // post-054 / pre-054-fence'49a208628290543ba2607a5ed48fdc8c', // post-054-fence / pre-098],- 'pipeline-prose.md': [+ 'pipeline-prose.md': [ '84523d531eeafa60959c65c553b2563f','bfea5aeeb471aae9749baee765b473a7', // pre-003 (original)'30ac30ec2b9d3e2a9eb869c181732cc6', // post-003 / pre-027 — the hash this migration originally produced'd1f8e3f1d214725b5aa67f309a81cd7d', // post-027 / pre-054'bef1bc2767b78f585f2bd89f3d615130', // post-054 / pre-054-fence],- 'pipeline-comic-script.md': [+ 'pipeline-comic-script.md': [ 'a4303016c34b65e4b0e641fe71252de3','40e5fdc1a1e68a7419b7dad936366c1a', // pre-003 (original)'beab031951859ca13579cdb9c4dbe769', // post-003 / pre-013 — the hash this migration originally produced'1e0af305c27d0c80c4b482d2ebcb4a0d', // post-013 / pre-027@@ -51,9 +51,9 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-idea-expansion.md': '93e9552c6662811e597a97296f3776a4', // post-124 (scope-discipline + {{#paddingRisk}})- 'pipeline-prose.md': '84523d531eeafa60959c65c553b2563f', // post-054-fence- 'pipeline-comic-script.md': 'a4303016c34b65e4b0e641fe71252de3', // post-121 (visible text exactness)+ 'pipeline-idea-expansion.md': 'd6fa86a435f978336661dcabca67258f', // post-127 (scene markers)+ 'pipeline-prose.md': '25e3d58c2741bd98acd5d08ba70d8a5e', // post-127 (scene markers)+ 'pipeline-comic-script.md': '49af30c05f008b20f6998a0f113f7d87', // post-127 (scene markers)'pipeline-tv-script.md': '376f779f4687b598f1c92ca4e770fd5a', // retired upstream (no data.reference)'pipeline-season-episodes.md': '50c68a29c3ebc275db3095d06bd87100', // post-005};diff --git a/scripts/migrations/004-augment-idea-expansion-context.js b/scripts/migrations/004-augment-idea-expansion-context.jsindex 94ddd1b9f3..438795c18d 100644--- a/scripts/migrations/004-augment-idea-expansion-context.js+++ b/scripts/migrations/004-augment-idea-expansion-context.js@@ -12,7 +12,7 @@import { makePromptReplaceMigration } from './_lib.js';export const ACCEPTED_OLD_MD5 = {- 'pipeline-idea-expansion.md': [+ 'pipeline-idea-expansion.md': [ '93e9552c6662811e597a97296f3776a4','1ee44cf95851ff8debf18729ebcd40b4', // post-004 / pre-025 — the hash this migration originally produced'41facefbc0c0549d456bef9111f95ab9', // post-003 / pre-004'1f3c5d077a5ef9a4b610335d5e3edd9c', // post-025 / pre-054@@ -22,7 +22,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-idea-expansion.md': '93e9552c6662811e597a97296f3776a4', // post-124 (scope-discipline + {{#paddingRisk}})+ 'pipeline-idea-expansion.md': 'd6fa86a435f978336661dcabca67258f', // post-127 (scene markers)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/013-comic-script-back-cover.js b/scripts/migrations/013-comic-script-back-cover.jsindex 2f4d4ac1f1..1831bee9f4 100644--- a/scripts/migrations/013-comic-script-back-cover.js+++ b/scripts/migrations/013-comic-script-back-cover.js@@ -14,7 +14,7 @@import { makePromptReplaceMigration } from './_lib.js';export const ACCEPTED_OLD_MD5 = {- 'pipeline-comic-script.md': [+ 'pipeline-comic-script.md': [ 'a4303016c34b65e4b0e641fe71252de3','40e5fdc1a1e68a7419b7dad936366c1a', // pre-003 (original)'beab031951859ca13579cdb9c4dbe769', // post-003 (length-profile feature)'1e0af305c27d0c80c4b482d2ebcb4a0d', // post-013 / pre-027 — the hash this migration originally produced@@ -27,7 +27,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-comic-script.md': 'a4303016c34b65e4b0e641fe71252de3', // post-121 (visible text exactness)+ 'pipeline-comic-script.md': '49af30c05f008b20f6998a0f113f7d87', // post-127 (scene markers)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/025-idea-stage-character-detail.js b/scripts/migrations/025-idea-stage-character-detail.jsindex 8fded641a9..32f0024fad 100644--- a/scripts/migrations/025-idea-stage-character-detail.js+++ b/scripts/migrations/025-idea-stage-character-detail.js@@ -25,7 +25,7 @@ import { makePromptReplaceMigration } from './_lib.js';// Exported so the test suite can import them and detect drift without// maintaining local copies.export const ACCEPTED_OLD_MD5 = {- 'pipeline-idea-expansion.md': [+ 'pipeline-idea-expansion.md': [ '93e9552c6662811e597a97296f3776a4','1ee44cf95851ff8debf18729ebcd40b4', // post-004 shipped — current pre-025'41facefbc0c0549d456bef9111f95ab9', // post-003, pre-004, still in setup-data.js OLD list'aee25112b2c596f643b17c559b772c22', // pre-003, still in setup-data.js OLD list@@ -37,7 +37,7 @@ export const ACCEPTED_OLD_MD5 = {// New shipped hash — what data.reference carries post-migration.export const NEW_SHIPPED_MD5 = {- 'pipeline-idea-expansion.md': '93e9552c6662811e597a97296f3776a4', // post-124 (scope-discipline + {{#paddingRisk}})+ 'pipeline-idea-expansion.md': 'd6fa86a435f978336661dcabca67258f', // post-127 (scene markers)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/027-text-stage-prompts-entities-summary.js b/scripts/migrations/027-text-stage-prompts-entities-summary.jsindex 390ed913d2..316eadbfcd 100644--- a/scripts/migrations/027-text-stage-prompts-entities-summary.js+++ b/scripts/migrations/027-text-stage-prompts-entities-summary.js@@ -37,7 +37,7 @@import { makePromptReplaceMigration } from './_lib.js';export const ACCEPTED_OLD_MD5 = {- 'pipeline-prose.md': [+ 'pipeline-prose.md': [ '84523d531eeafa60959c65c553b2563f','30ac30ec2b9d3e2a9eb869c181732cc6', // post-003 / pre-027 shipped'bfea5aeeb471aae9749baee765b473a7', // pre-003 (in setup-data OLD list)'d1f8e3f1d214725b5aa67f309a81cd7d', // post-027 / pre-054@@ -49,7 +49,7 @@ export const ACCEPTED_OLD_MD5 = {'1280ef6b1ad68fa44070ca7478ec2a5f', // post-027 / pre-054'2568e14beaa574d43f8018a5def51d04', // post-054 / pre-054-fence],- 'pipeline-comic-script.md': [+ 'pipeline-comic-script.md': [ 'a4303016c34b65e4b0e641fe71252de3','1e0af305c27d0c80c4b482d2ebcb4a0d', // post-011 / pre-027 shipped'beab031951859ca13579cdb9c4dbe769', // pre-011 (in setup-data OLD list)'40e5fdc1a1e68a7419b7dad936366c1a', // pre-003 (in setup-data OLD list)@@ -65,9 +65,9 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-prose.md': '84523d531eeafa60959c65c553b2563f', // post-054-fence+ 'pipeline-prose.md': '25e3d58c2741bd98acd5d08ba70d8a5e', // post-127 (scene markers)'pipeline-teleplay.md': 'afa4215330bf856429d70d7e2f856605', // post-054-fence- 'pipeline-comic-script.md': 'a4303016c34b65e4b0e641fe71252de3', // post-121 (visible text exactness)+ 'pipeline-comic-script.md': '49af30c05f008b20f6998a0f113f7d87', // post-127 (scene markers)'universe-character-expand.md': '67b6e73ed47f318451a730088b4cff14',};diff --git a/scripts/migrations/054-source-agnostic-stage-prompts.js b/scripts/migrations/054-source-agnostic-stage-prompts.jsindex 921760d595..67a998d4d3 100644--- a/scripts/migrations/054-source-agnostic-stage-prompts.js+++ b/scripts/migrations/054-source-agnostic-stage-prompts.js@@ -24,18 +24,18 @@ import { makePromptReplaceMigration } from './_lib.js';// Pre-change shipped hashes (the source-slot templates before this change).export const ACCEPTED_OLD_MD5 = {- 'pipeline-idea-expansion.md': ['1f3c5d077a5ef9a4b610335d5e3edd9c', 'b5c47c94ffc74637983c95761ab0c66c', '49a208628290543ba2607a5ed48fdc8c'],- 'pipeline-prose.md': ['d1f8e3f1d214725b5aa67f309a81cd7d', 'bef1bc2767b78f585f2bd89f3d615130'],- 'pipeline-comic-script.md': ['133d200d069c2e8173b7c129eea58f53', 'e530fc76b89cedaef848ad7ec99c934c', 'dea7d497d1cb38e7574f236f4ff8e644', 'e9ee70bf18888492edada6633cd9928a', '7c05ecde539f04c9fa91e87543057204'],+ 'pipeline-idea-expansion.md': [ '93e9552c6662811e597a97296f3776a4','1f3c5d077a5ef9a4b610335d5e3edd9c', 'b5c47c94ffc74637983c95761ab0c66c', '49a208628290543ba2607a5ed48fdc8c'],+ 'pipeline-prose.md': [ '84523d531eeafa60959c65c553b2563f','d1f8e3f1d214725b5aa67f309a81cd7d', 'bef1bc2767b78f585f2bd89f3d615130'],+ 'pipeline-comic-script.md': [ 'a4303016c34b65e4b0e641fe71252de3','133d200d069c2e8173b7c129eea58f53', 'e530fc76b89cedaef848ad7ec99c934c', 'dea7d497d1cb38e7574f236f4ff8e644', 'e9ee70bf18888492edada6633cd9928a', '7c05ecde539f04c9fa91e87543057204'],'pipeline-teleplay.md': ['1280ef6b1ad68fa44070ca7478ec2a5f', '2568e14beaa574d43f8018a5def51d04'],};// Post-change shipped hashes (the source-agnostic + tilde-fence templates this// migration installs). Mirror these into setup-data.js's drift table.export const NEW_SHIPPED_MD5 = {- 'pipeline-idea-expansion.md': '93e9552c6662811e597a97296f3776a4', // post-124 (scope-discipline + {{#paddingRisk}})- 'pipeline-prose.md': '84523d531eeafa60959c65c553b2563f',- 'pipeline-comic-script.md': 'a4303016c34b65e4b0e641fe71252de3',+ 'pipeline-idea-expansion.md': 'd6fa86a435f978336661dcabca67258f', // post-127 (scene markers)+ 'pipeline-prose.md': '25e3d58c2741bd98acd5d08ba70d8a5e', // post-127 (scene markers)+ 'pipeline-comic-script.md': '49af30c05f008b20f6998a0f113f7d87', // post-127 (scene markers)'pipeline-teleplay.md': 'afa4215330bf856429d70d7e2f856605',};diff --git a/scripts/migrations/063-comic-script-panel-decomposition-prompt.js b/scripts/migrations/063-comic-script-panel-decomposition-prompt.jsindex 06e03cce39..f1ab4c40ff 100644--- a/scripts/migrations/063-comic-script-panel-decomposition-prompt.js+++ b/scripts/migrations/063-comic-script-panel-decomposition-prompt.js@@ -19,7 +19,7 @@import { makePromptReplaceMigration } from './_lib.js';export const ACCEPTED_OLD_MD5 = {- 'pipeline-comic-script.md': [+ 'pipeline-comic-script.md': [ 'a4303016c34b65e4b0e641fe71252de3','dea7d497d1cb38e7574f236f4ff8e644','e9ee70bf18888492edada6633cd9928a', // post-063 / pre-121'7c05ecde539f04c9fa91e87543057204', // pre-121 reference body@@ -27,7 +27,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-comic-script.md': 'a4303016c34b65e4b0e641fe71252de3',+ 'pipeline-comic-script.md': '49af30c05f008b20f6998a0f113f7d87', // post-127 (scene markers)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/098-idea-stage-ticking-clock.js b/scripts/migrations/098-idea-stage-ticking-clock.jsindex 75a192d85d..d8512ff781 100644--- a/scripts/migrations/098-idea-stage-ticking-clock.js+++ b/scripts/migrations/098-idea-stage-ticking-clock.js@@ -34,14 +34,14 @@ import { makePromptReplaceMigration } from './_lib.js';// Pre-change shipped hash: the post-054 (source-agnostic) idea-expansion body.export const ACCEPTED_OLD_MD5 = {- 'pipeline-idea-expansion.md': ['49a208628290543ba2607a5ed48fdc8c'],+ 'pipeline-idea-expansion.md': [ '93e9552c6662811e597a97296f3776a4','49a208628290543ba2607a5ed48fdc8c'],};// Post-change shipped hash. Bumped to the current shipped body whenever a later// migration edits this file, so the drift-catch test (NEW == live sample) stays// green. Latest: post-124 (scope-discipline + {{#paddingRisk}}).export const NEW_SHIPPED_MD5 = {- 'pipeline-idea-expansion.md': '93e9552c6662811e597a97296f3776a4',+ 'pipeline-idea-expansion.md': 'd6fa86a435f978336661dcabca67258f', // post-127 (scene markers)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/124-idea-stage-scope-discipline.js b/scripts/migrations/124-idea-stage-scope-discipline.jsindex 98ed868df4..d0df720b00 100644--- a/scripts/migrations/124-idea-stage-scope-discipline.js+++ b/scripts/migrations/124-idea-stage-scope-discipline.js@@ -30,14 +30,14 @@ import { makePromptReplaceMigration } from './_lib.js';// Pre-change shipped hash: the post-098 (ticking-clock) idea-expansion body.export const ACCEPTED_OLD_MD5 = {- 'pipeline-idea-expansion.md': ['c50f016639d41cd8244f5ff13429f997'],+ 'pipeline-idea-expansion.md': [ '93e9552c6662811e597a97296f3776a4','c50f016639d41cd8244f5ff13429f997'],};// Post-change shipped hash (scope-boundary language + {{#paddingRisk}} section).// Mirror this into every earlier migration that tracks the same file// (003/004/025/054/098) so their drift-catch tests stay green.export const NEW_SHIPPED_MD5 = {- 'pipeline-idea-expansion.md': '93e9552c6662811e597a97296f3776a4',+ 'pipeline-idea-expansion.md': 'd6fa86a435f978336661dcabca67258f', // post-127 (scene markers)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/126-comic-script-visible-text-prompt.js b/scripts/migrations/126-comic-script-visible-text-prompt.jsindex e0a2e71e2c..558d1fe95e 100644--- a/scripts/migrations/126-comic-script-visible-text-prompt.js+++ b/scripts/migrations/126-comic-script-visible-text-prompt.js@@ -13,14 +13,14 @@import { makePromptReplaceMigration } from './_lib.js';export const ACCEPTED_OLD_MD5 = {- 'pipeline-comic-script.md': [+ 'pipeline-comic-script.md': [ 'a4303016c34b65e4b0e641fe71252de3','e9ee70bf18888492edada6633cd9928a', // post-063 (panel decomposition)'7c05ecde539f04c9fa91e87543057204', // pre-126 (current reference body)],};export const NEW_SHIPPED_MD5 = {- 'pipeline-comic-script.md': 'a4303016c34b65e4b0e641fe71252de3', // post-126 (visible text exactness)+ 'pipeline-comic-script.md': '49af30c05f008b20f6998a0f113f7d87', // post-127 (scene markers)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/127-pipeline-scene-markers-prompts.js b/scripts/migrations/127-pipeline-scene-markers-prompts.jsnew file mode 100644index 0000000000..8a6fb3e199--- /dev/null+++ b/scripts/migrations/127-pipeline-scene-markers-prompts.js@@ -0,0 +1,58 @@+/**+ * Introduce scene markers across the pipeline's text-stage prompts so a single+ * canonical scene list flows from the beat sheet down to the comic pages.+ *+ * Three prompts change:+ * - `pipeline-idea-expansion.md` (beat sheet) gains a `## Scenes` section —+ * the canonical numbered scene list (`Scene N — INT./EXT. LOCATION — TIME`)+ * that every downstream adaptation inherits.+ * - `pipeline-prose.md` is told to reuse the beat sheet's scene numbers ++ * sluglines verbatim rather than re-deriving them.+ * - `pipeline-comic-script.md` tags each page header `## Page N — Scene M:+ * SLUGLINE`, so the comic-page parser can record per-page scene info and+ * the render path can chain renders within a scene but break across one+ * (don't reference the prior page across a scene cut).+ *+ * Strategy: hash-driven prompt-replace via `./_lib.js`. Idempotent. Existing+ * installs that already applied the earlier prompt migrations sit on the prior+ * shipped hashes below; this migration carries them forward to the scene-marker+ * versions. (The earlier migrations in this file's lineage were resynced to the+ * same new hashes so their drift-catch tests keep passing.)+ */++import { makePromptReplaceMigration } from './_lib.js';++export const ACCEPTED_OLD_MD5 = {+ 'pipeline-idea-expansion.md': ['93e9552c6662811e597a97296f3776a4'], // post-124 (scope-discipline)+ 'pipeline-prose.md': ['84523d531eeafa60959c65c553b2563f'], // post-054-fence+ 'pipeline-comic-script.md': ['a4303016c34b65e4b0e641fe71252de3'], // post-126 (visible text exactness)+};++export const NEW_SHIPPED_MD5 = {+ 'pipeline-idea-expansion.md': 'd6fa86a435f978336661dcabca67258f', // post-127 (scene markers)+ 'pipeline-prose.md': '25e3d58c2741bd98acd5d08ba70d8a5e', // post-127 (scene markers)+ 'pipeline-comic-script.md': '49af30c05f008b20f6998a0f113f7d87', // post-127 (scene markers)+};++const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5,+ current: NEW_SHIPPED_MD5,+ label: 'pipeline scene-marker prompts',+ customizedHint: (filename) =>+ ` To add scene markers manually, diff:\n` ++ ` data.reference/prompts/stages/${filename}\n` ++ ` against your current:\n` ++ ` data/prompts/stages/${filename}\n` ++ ` and add the scene-list / scene-slug carrying changes (beat sheet's\n` ++ ` "## Scenes" section, prose reusing those sluglines, and the comic\n` ++ ` script's "## Page N — Scene M: SLUGLINE" page headers).`,+ skipFooter: (count) =>+ `⚠️ ${count} pipeline prompt(s) could not be auto-updated because they\n` ++ ` were customized. The pipeline still generates, but scene markers may\n` ++ ` be missing — so comic-page renders won't auto-chain within a scene\n` ++ ` or break across one until you merge the prompt changes manually.\n` ++ ` See data.reference/prompts/stages/pipeline-{idea-expansion,prose,comic-script}.md.`,+});++export { applyMigration };+export default { up };diff --git a/scripts/migrations/127-pipeline-scene-markers-prompts.test.js b/scripts/migrations/127-pipeline-scene-markers-prompts.test.jsnew file mode 100644index 0000000000..e8336c14fb--- /dev/null+++ b/scripts/migrations/127-pipeline-scene-markers-prompts.test.js@@ -0,0 +1,14 @@+import { describe } from 'vitest';++import { runPromptMigrationTests } from './_testHelpers.js';+import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './127-pipeline-scene-markers-prompts.js';++describe('migration 127 - pipeline scene-marker prompts', () => {+ runPromptMigrationTests({+ migration,+ applyMigration,+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ prefix: 'migration-127-',+ });+});diff --git a/server/lib/comicScriptParser.js b/server/lib/comicScriptParser.jsindex b3ec6a2d86..7691bacd40 100644--- a/server/lib/comicScriptParser.js+++ b/server/lib/comicScriptParser.js@@ -16,8 +16,16 @@* Unexpected text between panels is ignored.*/import { trimTo } from './storyBible.js';+import { normalizeSlugline } from './scenePrompt.js';const PAGE_RE = /^##\s+Page\s+([\dIVX]+)\b/i;+// Capture everything after the page number on a `## Page N …` header so the+// optional scene marker can be parsed off the tail (see parsePageSceneTail).+const PAGE_WITH_TAIL_RE = /^##\s+Page\s+[\dIVX]+\s*(.*)$/i;+// A slugline lead — `INT.`, `EXT.`, `EST.`, `INT./EXT.`, `I/E`. Used to decide+// whether a header tail with no explicit `Scene N` is a scene heading (accept)+// or just page-layout noise like `(splash)` / `- six-panel grid` (ignore).+const SLUGLINE_LEAD_RE = /^(?:INT|EXT|EST|INT\.\/EXT|I\/E)\b/i;// `## Cover concept` — the optional cover-art section the comic-script// template emits before the first `## Page 1` header. Also accepts the// short `## Cover` form so a hand-edited script doesn't have to be exact.@@ -47,6 +55,64 @@ const FIELD_RE = /^(?:\*\*)?(Description|Caption(?:\s+\d+)?|Dialogue|SFX)\s*:(?:const NONE_RE = /^\(\s*none\s*\)$/i;const isNoneValue = (s) => !s || NONE_RE.test(s.trim());+// --- Scene markers ---------------------------------------------------------+//+// The comic-script stage tags each page header with the scene it belongs to —+// `## Page 3 — Scene 2: INT. KITCHEN — NIGHT`. That scene structure is the+// beat sheet's canonical scene list, carried down through the prose's+// `## Scene N — Slugline` sections. Parsing it onto each page lets the render+// path tell "continuing the same scene" (chain off the prior page's image for+// character / environment continuity) from "new scene" (render fresh) — see+// resolveAutoReferenceIndex in server/services/pipeline/visualStages.js.+//+// Both the scene number and the slugline are optional and the separator is+// tolerant (em-dash, en-dash, hyphen, or colon). A header with no scene marker+// (legacy scripts, bare imports) parses to `{ sceneNumber: null, sceneHeading:+// null }`, which the render path reads as "no scene signal → don't auto-chain"+// — preserving the pre-feature behavior for those pages.+function parsePageSceneTail(tail) {+ const t = (tail || '').trim();+ if (!t) return { sceneNumber: null, sceneHeading: null };+ // The tail must open with a separator to count as a scene marker — this+ // guards page-layout parentheticals (`(DPS)`, `(splash)`) that legitimately+ // follow the page number from being misread as a scene.+ const sep = t.match(/^[—–:-]\s*(.*)$/);+ if (!sep) return { sceneNumber: null, sceneHeading: null };+ const rest = sep[1].trim();+ // Explicit `Scene N` prefix: whatever follows its separator is the heading+ // verbatim (the LLM was told to put a slugline there).+ const sm = rest.match(/^Scene\s+(\d{1,3})\b\s*[—–:-]?\s*(.*)$/i);+ if (sm) {+ const heading = sm[2].trim();+ return { sceneNumber: Number(sm[1]), sceneHeading: heading ? trimTo(heading, 200) : null };+ }+ // No explicit number — only treat a slugline-shaped tail as a heading so a+ // layout note (`- six-panel grid`) doesn't masquerade as a scene.+ if (SLUGLINE_LEAD_RE.test(rest)) {+ return { sceneNumber: null, sceneHeading: trimTo(rest, 200) };+ }+ return { sceneNumber: null, sceneHeading: null };+}++/**+ * Do two parsed comic pages belong to the SAME scene? Prefers the scene number+ * (the stable signal); falls back to comparing sluglines (canonicalized via the+ * shared `normalizeSlugline` — the same equality form used for scene/place+ * matching, so `INT. KITCHEN — NIGHT` and `int. kitchen - night.` are equal)+ * when one or both pages lack a number. Returns false when neither shares a+ * known scene signal — so pages with no scene markers never read as "same+ * scene" and the render path leaves them un-chained (pre-feature behavior).+ */+export function sameComicScene(a, b) {+ if (!a || !b) return false;+ if (Number.isInteger(a.sceneNumber) && Number.isInteger(b.sceneNumber)) {+ return a.sceneNumber === b.sceneNumber;+ }+ const ah = normalizeSlugline(a.sceneHeading);+ const bh = normalizeSlugline(b.sceneHeading);+ return ah !== '' && ah === bh;+}+// --- Bare-format normalization ---------------------------------------------//// Imported comic scripts (Create → Importer) commonly use the bare@@ -339,6 +405,10 @@ function parsePanelBody(lines) {* for per-page editing while panels remain the source for the image* prompt.* - `panels`: structured panel breakdown for image-gen prompts.+ * - `sceneNumber` / `sceneHeading`: the scene this page belongs to, parsed+ * off a `## Page N — Scene M: SLUGLINE` header (both `null` when the header+ * carries no scene marker). The render path uses them to chain renders+ * within a scene and break across one — see `sameComicScene`.*/export function parseComicScript(script) {if (typeof script !== 'string' || !script.trim()) {@@ -409,7 +479,9 @@ export function parseComicScript(script) {flushPanel();flushPageRawText();if (pages.length >= PANEL_LIMITS.PAGES_MAX) break;- currentPage = { panels: [], rawText: '' };+ const tail = line.match(PAGE_WITH_TAIL_RE);+ const { sceneNumber, sceneHeading } = parsePageSceneTail(tail ? tail[1] : '');+ currentPage = { panels: [], rawText: '', sceneNumber, sceneHeading };currentRawLines = [line];pages.push(currentPage);continue;@@ -432,7 +504,7 @@ export function parseComicScript(script) {if (PANEL_RE.test(line)) {flushPanel();if (!currentPage) {- currentPage = { panels: [], rawText: '' };+ currentPage = { panels: [], rawText: '', sceneNumber: null, sceneHeading: null };currentRawLines = [line];pages.push(currentPage);}diff --git a/server/lib/comicScriptParser.test.js b/server/lib/comicScriptParser.test.jsindex b7d24dacfc..196c8baac6 100644--- a/server/lib/comicScriptParser.test.js+++ b/server/lib/comicScriptParser.test.js@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { parseComicScript } from './comicScriptParser.js';+import { parseComicScript, sameComicScene } from './comicScriptParser.js';const SAMPLE = `# Issue 1 — Bone Walker@@ -539,3 +539,81 @@ Thud!`;});});});++describe('parseComicScript — scene markers', () => {+ const pageHeader = (h) => `${h}\nPanel 1\nDescription: A frame.\n`;++ it('parses `## Page N — Scene M: SLUGLINE` into sceneNumber + sceneHeading', () => {+ const { pages } = parseComicScript(pageHeader('## Page 1 — Scene 2: INT. KITCHEN — NIGHT'));+ expect(pages[0].sceneNumber).toBe(2);+ expect(pages[0].sceneHeading).toBe('INT. KITCHEN — NIGHT');+ });++ it('tolerates en-dash / hyphen / colon separators', () => {+ expect(parseComicScript(pageHeader('## Page 1 – Scene 3 – EXT. ROOFTOP — DUSK')).pages[0])+ .toMatchObject({ sceneNumber: 3, sceneHeading: 'EXT. ROOFTOP — DUSK' });+ expect(parseComicScript(pageHeader('## Page 1 - Scene 4: INT. VAULT')).pages[0])+ .toMatchObject({ sceneNumber: 4, sceneHeading: 'INT. VAULT' });+ });++ it('accepts a Scene number with no slugline (heading null)', () => {+ expect(parseComicScript(pageHeader('## Page 1 — Scene 5')).pages[0])+ .toMatchObject({ sceneNumber: 5, sceneHeading: null });+ });++ it('accepts a slugline-shaped tail with no Scene number', () => {+ expect(parseComicScript(pageHeader('## Page 1 — INT. KITCHEN — NIGHT')).pages[0])+ .toMatchObject({ sceneNumber: null, sceneHeading: 'INT. KITCHEN — NIGHT' });+ });++ it('ignores page-layout parentheticals and non-slugline tails (no false scene)', () => {+ expect(parseComicScript(pageHeader('## Page 1 (splash)')).pages[0])+ .toMatchObject({ sceneNumber: null, sceneHeading: null });+ expect(parseComicScript(pageHeader('## Page 1 - six-panel grid')).pages[0])+ .toMatchObject({ sceneNumber: null, sceneHeading: null });+ });++ it('leaves a plain `## Page N` header with no scene marker', () => {+ expect(parseComicScript(pageHeader('## Page 1')).pages[0])+ .toMatchObject({ sceneNumber: null, sceneHeading: null });+ });++ it('still matches the page number when a scene suffix is present', () => {+ const script = `${pageHeader('## Page 1 — Scene 1: INT. A — DAY')}${pageHeader('## Page 2 — Scene 1: INT. A — DAY')}`;+ const { pages } = parseComicScript(script);+ expect(pages).toHaveLength(2);+ expect(pages.map((p) => p.sceneNumber)).toEqual([1, 1]);+ });+});++describe('sameComicScene', () => {+ it('matches on equal scene numbers', () => {+ expect(sameComicScene({ sceneNumber: 2 }, { sceneNumber: 2 })).toBe(true);+ expect(sameComicScene({ sceneNumber: 2 }, { sceneNumber: 3 })).toBe(false);+ });++ it('falls back to normalized slugline when a number is missing', () => {+ expect(sameComicScene(+ { sceneNumber: null, sceneHeading: 'INT. KITCHEN — NIGHT' },+ { sceneNumber: null, sceneHeading: 'int. kitchen - night.' },+ )).toBe(true);+ expect(sameComicScene(+ { sceneHeading: 'INT. KITCHEN — NIGHT' },+ { sceneHeading: 'EXT. ROOFTOP — DUSK' },+ )).toBe(false);+ });++ it('returns false when neither page carries a scene signal (legacy pages)', () => {+ expect(sameComicScene({ sceneNumber: null, sceneHeading: null }, { sceneNumber: null, sceneHeading: null })).toBe(false);+ expect(sameComicScene({}, {})).toBe(false);+ expect(sameComicScene(null, { sceneNumber: 1 })).toBe(false);+ });++ it('prefers the number over the heading when both are present', () => {+ // Same number but drifting sluglines still counts as the same scene.+ expect(sameComicScene(+ { sceneNumber: 1, sceneHeading: 'INT. A — DAY' },+ { sceneNumber: 1, sceneHeading: 'INT. A — LATER' },+ )).toBe(true);+ });+});diff --git a/server/routes/pipeline/issues.js b/server/routes/pipeline/issues.jsindex ff1f98dd83..5371e0a2f7 100644--- a/server/routes/pipeline/issues.js+++ b/server/routes/pipeline/issues.js@@ -235,7 +235,11 @@ const comicPageRenderSchema = z.object({// or explicit (0-based index) already-rendered page as a reference image, so a// continuing scene keeps incidental/un-described characters + environment// consistent. Resolved + bounds-checked in enqueueVisualComicPage.- referencePage: z.union([z.enum(['prior', 'next']), z.number().int().min(0)]).optional(),+ // - omitted / 'auto' → auto-chain off the prior page within the same scene,+ // render fresh across a scene boundary (the default).+ // - 'none' → force a fresh render with no reference, even mid-scene.+ // - 'prior' / 'next' / <index> → explicit reference (errors if unrendered).+ referencePage: z.union([z.enum(['prior', 'next', 'auto', 'none']), z.number().int().min(0)]).optional(),// Per-render opt-out for trained character-LoRA auto-apply (local mode).applyCharacterLoras: z.boolean().optional().default(true),}).refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });@@ -782,6 +786,11 @@ router.patch('/issues/:id/stages/comicPages/pages/:pageIndex', asyncHandler(asynnextPages[pageIndex] = {...currentPages[pageIndex],rawText: fresh.rawText || body.rawText,+ // Re-derive the scene marker from the edited header so editing+ // `## Page N — Scene M: SLUGLINE` retags the page (and clears it when+ // the marker is removed). `?? null` normalizes the absent case.+ sceneNumber: fresh.sceneNumber ?? null,+ sceneHeading: fresh.sceneHeading ?? null,panels: fresh.panels.map((p, i) => ({...p,// Preserve in-flight per-panel jobIds against the freshest panels.diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.jsindex 3a8b671dde..cf49472952 100644--- a/server/services/pipeline/visualStages.js+++ b/server/services/pipeline/visualStages.js@@ -46,6 +46,7 @@ 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';@@ -245,6 +246,58 @@ export function resolveReferencePageIndex(referencePage, pageIndex, pageCount) {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);@@ -853,14 +906,16 @@ export async function enqueueVisualComicPage(issueId, options = {}) {const mode = resolveMode(options, settings);const variant = resolveVariant(options.target);- // Consistency reference: pass an ADJACENT (or explicit) already-rendered page- // as a reference so a continuing scene keeps its incidental, un-described- // characters and environment consistent (the "two newlyweds drift between- // pages" problem). Takes precedence over proof-as-base — both set the init- // image, and an explicit cross-page reference is the stronger intent.- const referencePageIndex = resolveReferencePageIndex(options.referencePage, pageIndex, pages.length);- const fromReference = referencePageIndex != null;- const fromProof = !fromReference && variant === 'final' && options.useProofAsBase === true;+ // 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@@ -922,9 +977,9 @@ export async function enqueueVisualComicPage(issueId, options = {}) {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 ? ` (ref page ${referencePageIndex + 1})` : ''}`,+ 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, referencePageIndex };+ return { jobId, mode, prompt, pageIndex, variant, fromProof, fromReference, autoReference, referencePageIndex };}/**diff --git a/server/services/pipeline/visualStages.test.js b/server/services/pipeline/visualStages.test.jsindex c7b1c48fc6..69d6d3f116 100644--- a/server/services/pipeline/visualStages.test.js+++ b/server/services/pipeline/visualStages.test.js@@ -98,6 +98,8 @@ const {assertCharacterAppearancesResolve,enqueueVisualImage,resolveReferencePageIndex,+ resolveAutoReferenceIndex,+ resolveComicPageReference,} = await import('./visualStages.js');// The universeBuilder mock's getUniverse is auto-captured here so individual@@ -245,6 +247,66 @@ describe('composeComicPagePrompt', () => {});});+ describe('resolveAutoReferenceIndex', () => {+ const rendered = (scene) => ({ sceneNumber: scene, finalImage: { filename: 'x.png' } });+ const unrendered = (scene) => ({ sceneNumber: scene });++ it('chains off the prior page when it shares the scene AND is rendered', () => {+ const pages = [rendered(1), unrendered(1)];+ expect(resolveAutoReferenceIndex(pages, 1)).toBe(0);+ });+ it('breaks across a scene boundary (different scene number)', () => {+ const pages = [rendered(1), unrendered(2)];+ expect(resolveAutoReferenceIndex(pages, 1)).toBeNull();+ });+ it('skips when the prior page has no render yet (soft, no throw)', () => {+ const pages = [unrendered(1), unrendered(1)];+ expect(resolveAutoReferenceIndex(pages, 1)).toBeNull();+ });+ it('skips when scene markers are absent on either page (legacy scripts)', () => {+ const pages = [{ finalImage: { filename: 'x.png' } }, {}];+ expect(resolveAutoReferenceIndex(pages, 1)).toBeNull();+ });+ it('returns null on the first page (no prior)', () => {+ expect(resolveAutoReferenceIndex([rendered(1)], 0)).toBeNull();+ });+ it('falls back to the proof image when no final render exists', () => {+ const pages = [{ sceneNumber: 1, proofImage: { filename: 'p.png' } }, unrendered(1)];+ expect(resolveAutoReferenceIndex(pages, 1)).toBe(0);+ });+ });++ describe('resolveComicPageReference (precedence tiers)', () => {+ const rendered = (scene) => ({ sceneNumber: scene, finalImage: { filename: 'x.png' } });+ const unrendered = (scene) => ({ sceneNumber: scene });+ const pages = [rendered(1), { ...unrendered(1), proofImage: { filename: 'p.png' } }];++ it('explicit reference wins over proof-as-base and auto', () => {+ const r = resolveComicPageReference({ referencePage: 'prior', useProofAsBase: true, variant: 'final', pages, pageIndex: 1 });+ expect(r).toMatchObject({ referencePageIndex: 0, fromReference: true, autoReference: false, fromProof: false });+ });+ it('proof-as-base wins over auto on a final render', () => {+ const r = resolveComicPageReference({ referencePage: undefined, useProofAsBase: true, variant: 'final', pages, pageIndex: 1 });+ expect(r).toMatchObject({ fromProof: true, fromReference: false, autoReference: false });+ });+ it('auto chains within scene when no explicit ref and not proof-as-base', () => {+ const r = resolveComicPageReference({ referencePage: undefined, useProofAsBase: false, variant: 'proof', pages, pageIndex: 1 });+ expect(r).toMatchObject({ referencePageIndex: 0, fromReference: true, autoReference: true, fromProof: false });+ });+ it("'none' opts out of auto chaining but leaves proof-as-base (orthogonal)", () => {+ const withProof = resolveComicPageReference({ referencePage: 'none', useProofAsBase: true, variant: 'final', pages, pageIndex: 1 });+ expect(withProof).toMatchObject({ referencePageIndex: null, fromReference: false, autoReference: false, fromProof: true });+ // A proof render with 'none' and no proof-as-base box → fully fresh, no reference.+ const fresh = resolveComicPageReference({ referencePage: 'none', useProofAsBase: false, variant: 'proof', pages, pageIndex: 1 });+ expect(fresh).toMatchObject({ referencePageIndex: null, fromReference: false, autoReference: false, fromProof: false });+ });+ it('across a scene boundary, auto yields nothing', () => {+ const crossScene = [rendered(1), unrendered(2)];+ const r = resolveComicPageReference({ referencePage: undefined, useProofAsBase: false, variant: 'proof', pages: crossScene, pageIndex: 1 });+ expect(r.fromReference).toBe(false);+ });+ });+it('uses singular "panel" wording for a one-panel splash page', () => {const splash = { panels: [{ description: 'Hero stands silhouetted against the sunrise.' }] };const prompt = composeComicPagePrompt({ series: SERIES, page: splash, pageNumber: 5 });