Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-1552]): align teleplay + storyboard scene extraction with the beat-sheet canonical scene list
[._.]/ Adam Eivy95396f81fdeb
diff --git a/data.reference/prompts/stages/pipeline-teleplay.md b/data.reference/prompts/stages/pipeline-teleplay.mdindex fffef99eb0..e58969b6ba 100644--- a/data.reference/prompts/stages/pipeline-teleplay.md+++ b/data.reference/prompts/stages/pipeline-teleplay.md@@ -86,6 +86,7 @@ CUT TO:- **Strong opening (Saga-style cold open):** the TEASER lands the viewer inside a specific sensory moment in the first 30–60 seconds — a striking image, an arresting line, an unanswered question. No exposition voice-over walls, no "previously on" recaps. The opening beat is the hook that earns the rest of the episode.- **Cliffhanger / lead-in ending:** the TAG (or final scene if no TAG) must do one of: (a) reveal something that recontextualizes the episode, (b) deliver a cliffhanger — a character in peril, a decision unmade, an antagonist arriving — or (c) plant the seed for the next episode with a clear next-episode pull. Never close on tidy resolution alone — serialized TV needs forward propulsion.- Use **sluglines in bold** for every scene: `**INT. KITCHEN — NIGHT**`.+- **Honor the canonical scene list.** If the source material includes a `## Scenes` list (the beat sheet's canonical numbered scene list), reuse those scene numbers and sluglines **verbatim** — number your `### Scene N` headers to match and copy each `INT./EXT. LOCATION — TIME` slugline exactly. That list is the single source of truth for scene boundaries across every adaptation (prose, comic script, storyboards), so don't renumber, merge, split, or re-slug its scenes. Only derive scene boundaries yourself when no `## Scenes` list is provided.- Action paragraphs stay **short** (1–4 lines) and in **present tense**.- CAPS character names above their dialogue lines.- Parentheticals only when the line reading would otherwise be ambiguous.diff --git a/scripts/migrations/027-text-stage-prompts-entities-summary.js b/scripts/migrations/027-text-stage-prompts-entities-summary.jsindex 316eadbfcd..09f6d6bbbd 100644--- a/scripts/migrations/027-text-stage-prompts-entities-summary.js+++ b/scripts/migrations/027-text-stage-prompts-entities-summary.js@@ -48,6 +48,7 @@ export const ACCEPTED_OLD_MD5 = {'3f6fecc25573ed054b47db392250034a', // pre-shape (in setup-data OLD list)'1280ef6b1ad68fa44070ca7478ec2a5f', // post-027 / pre-054'2568e14beaa574d43f8018a5def51d04', // post-054 / pre-054-fence+ 'afa4215330bf856429d70d7e2f856605', // post-054-fence / pre-128 (canonical scene list)],'pipeline-comic-script.md': [ 'a4303016c34b65e4b0e641fe71252de3','1e0af305c27d0c80c4b482d2ebcb4a0d', // post-011 / pre-027 shipped@@ -66,7 +67,7 @@ export const ACCEPTED_OLD_MD5 = {export const NEW_SHIPPED_MD5 = {'pipeline-prose.md': '25e3d58c2741bd98acd5d08ba70d8a5e', // post-127 (scene markers)- 'pipeline-teleplay.md': 'afa4215330bf856429d70d7e2f856605', // post-054-fence+ 'pipeline-teleplay.md': '2ea9974ac3803658b2314db1f5818b77', // post-128 (canonical scene list)'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 67a998d4d3..835011868a 100644--- a/scripts/migrations/054-source-agnostic-stage-prompts.js+++ b/scripts/migrations/054-source-agnostic-stage-prompts.js@@ -27,7 +27,7 @@ export const ACCEPTED_OLD_MD5 = {'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'],+ 'pipeline-teleplay.md': ['1280ef6b1ad68fa44070ca7478ec2a5f', '2568e14beaa574d43f8018a5def51d04', 'afa4215330bf856429d70d7e2f856605'],};// Post-change shipped hashes (the source-agnostic + tilde-fence templates this@@ -36,7 +36,7 @@ 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)- 'pipeline-teleplay.md': 'afa4215330bf856429d70d7e2f856605',+ 'pipeline-teleplay.md': '2ea9974ac3803658b2314db1f5818b77', // post-128 (canonical scene list)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/128-teleplay-canonical-scene-list-prompt.js b/scripts/migrations/128-teleplay-canonical-scene-list-prompt.jsnew file mode 100644index 0000000000..0405483756--- /dev/null+++ b/scripts/migrations/128-teleplay-canonical-scene-list-prompt.js@@ -0,0 +1,55 @@+/**+ * Carry the canonical-scene-list instruction into the TV teleplay stage prompt+ * so the teleplay inherits the beat sheet's `## Scenes` numbers + sluglines+ * verbatim — the same instruction `pipeline-prose.md` already carries (added in+ * migration 127). With this, "Scene 2" is the same Scene 2 across the beat+ * sheet, prose, comic script, and teleplay, so storyboards/video extracted from+ * any of them share one scene id space.+ *+ * One prompt changes:+ * - `pipeline-teleplay.md` gains a "Honor the canonical scene list" rule:+ * when the source material includes a `## Scenes` list, number the+ * `### Scene N` headers to match and copy each `INT./EXT. LOCATION — TIME`+ * slugline verbatim; only derive boundaries when no list is provided.+ *+ * Strategy: hash-driven prompt-replace via `./_lib.js`. Idempotent. Existing+ * installs that already applied the earlier teleplay prompt migrations sit on+ * the prior shipped hash below; this migration carries them forward to the+ * canonical-scene-list version. (The earlier migrations in this file's lineage —+ * 027 and 054 — were resynced to the same new hash so their drift-catch tests+ * keep passing.)+ */++import { makePromptReplaceMigration } from './_lib.js';++export const ACCEPTED_OLD_MD5 = {+ 'pipeline-teleplay.md': ['afa4215330bf856429d70d7e2f856605'], // post-054-fence+};++export const NEW_SHIPPED_MD5 = {+ 'pipeline-teleplay.md': '2ea9974ac3803658b2314db1f5818b77', // post-128 (canonical scene list)+};++const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5,+ current: NEW_SHIPPED_MD5,+ label: 'teleplay canonical scene-list prompt',+ customizedHint: (filename) =>+ ` To add the canonical scene-list instruction manually, diff:\n` ++ ` data.reference/prompts/stages/${filename}\n` ++ ` against your current:\n` ++ ` data/prompts/stages/${filename}\n` ++ ` and add the "Honor the canonical scene list" rule (reuse the beat\n` ++ ` sheet's "## Scenes" numbers + sluglines verbatim instead of\n` ++ ` inventing scene boundaries).`,+ skipFooter: (count) =>+ `⚠️ ${count} teleplay prompt(s) could not be auto-updated because they\n` ++ ` were customized. The pipeline still generates teleplays, but they may\n` ++ ` not reuse the beat sheet's canonical scene numbers/sluglines — so\n` ++ ` teleplay-extracted storyboards can drift from comic-page scene numbers\n` ++ ` until you merge the prompt change manually.\n` ++ ` See data.reference/prompts/stages/pipeline-teleplay.md.`,+});++export { applyMigration };+export default { up };diff --git a/scripts/migrations/128-teleplay-canonical-scene-list-prompt.test.js b/scripts/migrations/128-teleplay-canonical-scene-list-prompt.test.jsnew file mode 100644index 0000000000..a6bc518d3e--- /dev/null+++ b/scripts/migrations/128-teleplay-canonical-scene-list-prompt.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 './128-teleplay-canonical-scene-list-prompt.js';++describe('migration 128 - teleplay canonical scene-list prompt', () => {+ runPromptMigrationTests({+ migration,+ applyMigration,+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ prefix: 'migration-128-',+ });+});diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.jsindex f45a2435f5..65a5f079b2 100644--- a/scripts/setup-data-drift.test.js+++ b/scripts/setup-data-drift.test.js@@ -27,7 +27,7 @@ const EXPECTED_STAGE_OLD = {'pipeline-idea-expansion.md': ['1ee44cf95851ff8debf18729ebcd40b4', '1f3c5d077a5ef9a4b610335d5e3edd9c', '41facefbc0c0549d456bef9111f95ab9', '49a208628290543ba2607a5ed48fdc8c', '93e9552c6662811e597a97296f3776a4', 'aee25112b2c596f643b17c559b772c22', 'b5c47c94ffc74637983c95761ab0c66c', 'c50f016639d41cd8244f5ff13429f997'],'pipeline-prose.md': ['30ac30ec2b9d3e2a9eb869c181732cc6', '84523d531eeafa60959c65c553b2563f', 'bef1bc2767b78f585f2bd89f3d615130', 'bfea5aeeb471aae9749baee765b473a7', 'd1f8e3f1d214725b5aa67f309a81cd7d'],'pipeline-comic-script.md': ['133d200d069c2e8173b7c129eea58f53', '1e0af305c27d0c80c4b482d2ebcb4a0d', '40e5fdc1a1e68a7419b7dad936366c1a', '7c05ecde539f04c9fa91e87543057204', 'a4303016c34b65e4b0e641fe71252de3', 'beab031951859ca13579cdb9c4dbe769', 'dea7d497d1cb38e7574f236f4ff8e644', 'e530fc76b89cedaef848ad7ec99c934c', 'e9ee70bf18888492edada6633cd9928a'],- 'pipeline-teleplay.md': ['1280ef6b1ad68fa44070ca7478ec2a5f', '2568e14beaa574d43f8018a5def51d04', '376f779f4687b598f1c92ca4e770fd5a', '3f6fecc25573ed054b47db392250034a'],+ 'pipeline-teleplay.md': ['1280ef6b1ad68fa44070ca7478ec2a5f', '2568e14beaa574d43f8018a5def51d04', '376f779f4687b598f1c92ca4e770fd5a', '3f6fecc25573ed054b47db392250034a', 'afa4215330bf856429d70d7e2f856605'],'pipeline-season-episodes.md': ['6e349ad26bed8a0ccb042571f03f03eb', 'c4928e2a5f833358116b29d2d669888d'],'pipeline-arc-overview.md': ['6a3ecab43d1f46b7ef9aab6c69ea0326', 'd34d72b8e49ba303d38607845dd87f1c'],'pipeline-arc-verify.md': ['52e31abc93e3105176236fcaa5d1575a', 'ff56d8387162017e08d5d0491060ddd6'],@@ -48,7 +48,7 @@ const EXPECTED_STAGE_NEW = {'pipeline-idea-expansion.md': 'd6fa86a435f978336661dcabca67258f','pipeline-prose.md': '25e3d58c2741bd98acd5d08ba70d8a5e','pipeline-comic-script.md': '49af30c05f008b20f6998a0f113f7d87',- 'pipeline-teleplay.md': 'afa4215330bf856429d70d7e2f856605',+ 'pipeline-teleplay.md': '2ea9974ac3803658b2314db1f5818b77','pipeline-season-episodes.md': '50c68a29c3ebc275db3095d06bd87100','pipeline-arc-overview.md': '0a1f6ffa6908522e3690c5e9e53a6ee0','pipeline-arc-verify.md': '36aa70cdfc25d7549573a4d556e7702c',diff --git a/server/lib/sceneExtractor.js b/server/lib/sceneExtractor.jsindex ace2358bec..0483c8a6a7 100644--- a/server/lib/sceneExtractor.js+++ b/server/lib/sceneExtractor.js@@ -152,6 +152,86 @@ export function sanitizeSceneList(raw, { maxScenes = 200 } = {}) {};}+// ---------- canonical scene list (beat sheet, no LLM) ----------++// Match the beat sheet's `## Scenes` heading (any heading level, case-insensitive).+const SCENES_HEADING_RE = /^#{1,6}\s+Scenes\b/i;+// A heading line of any level — used to bound the `## Scenes` section.+const ANY_HEADING_RE = /^#{1,6}\s+/;+// A scene list entry must start with a markdown list marker (`-`/`*`/`+`,+// `1.`/`1)`) or an explicit `Scene N` — so an intro sentence inside the+// `## Scenes` section isn't mistaken for a scene.+const SCENE_ENTRY_RE = /^\s*(?:[-*+]\s|\d{1,3}[.)]\s|Scene\s+\d)/i;+// Strip a leading markdown list marker.+const LIST_MARKER_RE = /^\s*(?:[-*+]|\d{1,3}[.)])\s*/;+// Strip a leading `Scene N` token (with an optional —/–/:/-/. separator),+// capturing the scene number.+const SCENE_PREFIX_RE = /^Scene\s+(\d{1,3})\b\s*[—–:.\-]?\s*(.*)$/i;++/**+ * Parse the beat sheet's canonical `## Scenes` list (#1552) into a lightweight+ * `[{ number, slugline, summary }]`. The beat-sheet prompt emits a numbered+ * markdown list of `Scene N — INT./EXT. LOCATION — TIME: <beats clause>`; this+ * is the single source of truth for scene boundaries every adaptation inherits.+ *+ * Returns `[]` when there's no `## Scenes` section or it holds no parseable+ * entries — the caller falls back to the LLM slugline-parse path.+ */+export function parseBeatSheetScenes(markdown) {+ if (!isStr(markdown)) return [];+ const lines = markdown.split(/\r\n|\r|\n/);+ const start = lines.findIndex((l) => SCENES_HEADING_RE.test(l.trim()));+ if (start < 0) return [];++ const out = [];+ for (let j = start + 1; j < lines.length; j++) {+ const line = lines[j];+ if (ANY_HEADING_RE.test(line.trim())) break; // next section ends the list+ if (!SCENE_ENTRY_RE.test(line)) continue; // skip blanks / intro prose+ let entry = line.replace(LIST_MARKER_RE, '').trim();+ if (!entry) continue;+ let number = null;+ const sm = entry.match(SCENE_PREFIX_RE);+ if (sm) {+ number = Number(sm[1]);+ entry = sm[2].trim();+ }+ if (!entry) continue;+ // The first colon separates the slugline from the beats clause. Sluglines+ // (INT./EXT. LOCATION — TIME) don't normally carry a colon, so this is safe.+ let slugline = entry;+ let summary = '';+ const colon = entry.indexOf(':');+ if (colon >= 0) {+ slugline = entry.slice(0, colon).trim();+ summary = entry.slice(colon + 1).trim();+ }+ if (!slugline) continue;+ out.push({ number: Number.isFinite(number) ? number : out.length + 1, slugline, summary });+ }+ return out;+}++/**+ * Map the beat sheet's canonical `## Scenes` list directly to the sanitized+ * scene shape — no LLM call. Used to seed storyboards so `storyboards.scenes`+ * numbers/sluglines match the comic pages' (both inherit the same canonical+ * list). Returns `[]` when the beat sheet has no parseable scene list.+ */+export function scenesFromBeatSheet(markdown, { maxScenes = 200 } = {}) {+ const parsed = parseBeatSheetScenes(markdown);+ if (!parsed.length) return [];+ const raw = {+ scenes: parsed.map((p) => ({+ id: `scene-${String(p.number).padStart(2, '0')}`,+ heading: p.slugline ? `Scene ${p.number} — ${p.slugline}` : `Scene ${p.number}`,+ slugline: p.slugline,+ summary: p.summary,+ })),+ };+ return sanitizeSceneList(raw, { maxScenes }).scenes;+}+// ---------- LLM driver ----------/**diff --git a/server/lib/sceneExtractor.test.js b/server/lib/sceneExtractor.test.jsindex b473f263a9..5ebdc5e494 100644--- a/server/lib/sceneExtractor.test.js+++ b/server/lib/sceneExtractor.test.js@@ -7,6 +7,8 @@ vi.mock('./stageRunner.js', () => ({import {extractScenes,sanitizeSceneList,+ parseBeatSheetScenes,+ scenesFromBeatSheet,SOURCE_KIND,} from './sceneExtractor.js';import { runStagedLLM } from './stageRunner.js';@@ -373,3 +375,108 @@ describe('extractScenes', () => {expect(result.extracted.logline).toBeNull();});});++describe('parseBeatSheetScenes', () => {+ const beatSheet = [+ '# Beat sheet',+ '',+ '## Beats',+ '1. The hook.',+ '2. The turn.',+ '',+ '## Scenes',+ 'These are the canonical scenes for this issue:',+ '1. Scene 1 — EXT. ROOFTOP — DUSK: beats 1–2, the hook and Lina\'s discovery',+ '2. Scene 2 — INT. KITCHEN — NIGHT: beat 3, the confrontation',+ '',+ '## Setting',+ 'A rooftop and a kitchen.',+ ].join('\n');++ it('extracts numbered scenes with sluglines + beats clause from the ## Scenes section', () => {+ const scenes = parseBeatSheetScenes(beatSheet);+ expect(scenes).toEqual([+ { number: 1, slugline: 'EXT. ROOFTOP — DUSK', summary: 'beats 1–2, the hook and Lina\'s discovery' },+ { number: 2, slugline: 'INT. KITCHEN — NIGHT', summary: 'beat 3, the confrontation' },+ ]);+ });++ it('stops at the next heading and ignores an intro sentence inside the section', () => {+ const scenes = parseBeatSheetScenes(beatSheet);+ // "A rooftop and a kitchen." (under ## Setting) and the intro sentence are excluded.+ expect(scenes).toHaveLength(2);+ });++ it('returns [] when there is no ## Scenes section', () => {+ expect(parseBeatSheetScenes('# Beat sheet\n\n## Beats\n1. A beat.\n')).toEqual([]);+ });++ it('returns [] for non-string input', () => {+ expect(parseBeatSheetScenes(null)).toEqual([]);+ expect(parseBeatSheetScenes(undefined)).toEqual([]);+ expect(parseBeatSheetScenes(42)).toEqual([]);+ });++ it('handles dash-bulleted entries and a missing "Scene N" prefix (falls back to list order)', () => {+ const md = [+ '## Scenes',+ '- EXT. BEACH — DAWN: opening',+ '- INT. CABIN — DAY: midpoint',+ ].join('\n');+ expect(parseBeatSheetScenes(md)).toEqual([+ { number: 1, slugline: 'EXT. BEACH — DAWN', summary: 'opening' },+ { number: 2, slugline: 'INT. CABIN — DAY', summary: 'midpoint' },+ ]);+ });++ it('parses a scene with no beats clause (slugline only)', () => {+ const md = '## Scenes\n1. Scene 1 — INT. VAULT — NIGHT';+ expect(parseBeatSheetScenes(md)).toEqual([+ { number: 1, slugline: 'INT. VAULT — NIGHT', summary: '' },+ ]);+ });++ it('honors the explicit Scene number over list order', () => {+ const md = '## Scenes\n1. Scene 3 — INT. LAB — NIGHT: the experiment';+ expect(parseBeatSheetScenes(md)).toEqual([+ { number: 3, slugline: 'INT. LAB — NIGHT', summary: 'the experiment' },+ ]);+ });+});++describe('scenesFromBeatSheet', () => {+ it('maps the canonical ## Scenes list 1:1 to sanitized scenes (numbers/sluglines preserved, no LLM)', () => {+ const md = [+ '## Scenes',+ '1. Scene 1 — EXT. ROOFTOP — DUSK: the hook',+ '2. Scene 2 — INT. KITCHEN — NIGHT: the confrontation',+ ].join('\n');+ const scenes = scenesFromBeatSheet(md);+ expect(scenes).toHaveLength(2);+ expect(scenes[0]).toMatchObject({+ id: 'scene-01',+ heading: 'Scene 1 — EXT. ROOFTOP — DUSK',+ slugline: 'EXT. ROOFTOP — DUSK',+ summary: 'the hook',+ });+ expect(scenes[1]).toMatchObject({+ id: 'scene-02',+ heading: 'Scene 2 — INT. KITCHEN — NIGHT',+ slugline: 'INT. KITCHEN — NIGHT',+ });+ // Scene-extractor never calls the LLM on this path.+ expect(runStagedLLM).not.toHaveBeenCalled();+ });++ it('pads ids from the explicit Scene number, not list position', () => {+ const md = '## Scenes\n1. Scene 7 — INT. LAB — NIGHT: the experiment';+ const [scene] = scenesFromBeatSheet(md);+ expect(scene.id).toBe('scene-07');+ expect(scene.heading).toBe('Scene 7 — INT. LAB — NIGHT');+ });++ it('returns [] when the beat sheet has no ## Scenes list (caller falls back to the LLM path)', () => {+ expect(scenesFromBeatSheet('# Beat sheet\n\n## Beats\n1. A beat.')).toEqual([]);+ expect(scenesFromBeatSheet('')).toEqual([]);+ });+});diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.jsindex aee0f5aca6..6aa14f2ee4 100644--- a/server/routes/pipeline.test.js+++ b/server/routes/pipeline.test.js@@ -1072,6 +1072,79 @@ describe('pipeline routes', () => {spy.mockRestore();});+ it('POST /issues/:id/stages/storyboards/extract-scenes prefers the beat sheet ## Scenes list (no LLM call)', async () => {+ const extractor = await import('../lib/sceneExtractor.js');+ const spy = vi.spyOn(extractor, 'extractScenes');++ const app = makeApp();+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({+ stages: {+ idea: {+ status: 'ready',+ output: [+ '# Beat sheet',+ '',+ '## Scenes',+ '1. Scene 1 — EXT. ROOFTOP — DUSK: the hook',+ '2. Scene 2 — INT. KITCHEN — NIGHT: the confrontation',+ ].join('\n'),+ },+ // teleplay present too — the beat sheet still wins.+ teleplay: { status: 'ready', output: '## TEASER\n\n**INT. ELSEWHERE — DAY**\n\nIgnored.' },+ },+ });++ const r = await request(app)+ .post(`/api/pipeline/issues/${iss.body.id}/stages/storyboards/extract-scenes`)+ .send({ from: 'teleplay' });++ expect(r.status).toBe(200);+ expect(r.body.usedCanonicalList).toBe(true);+ expect(r.body.sourceKind).toBe('beat-sheet');+ expect(r.body.runId).toBeNull();+ expect(r.body.sceneCount).toBe(2);+ // Numbers/sluglines map 1:1 from the canonical list.+ expect(r.body.stage.scenes[0].heading).toBe('Scene 1 — EXT. ROOFTOP — DUSK');+ expect(r.body.stage.scenes[0].slugline).toBe('EXT. ROOFTOP — DUSK');+ expect(r.body.stage.scenes[1].slugline).toBe('INT. KITCHEN — NIGHT');+ expect(r.body.stage.scenes[0].imageJobId).toBeNull();+ expect(r.body.stage.status).toBe('ready');+ // The deterministic path never reaches the LLM extractor.+ expect(spy).not.toHaveBeenCalled();+ spy.mockRestore();+ });++ it('POST /issues/:id/stages/storyboards/extract-scenes falls back to the LLM when the beat sheet has no scene list', async () => {+ const extractor = await import('../lib/sceneExtractor.js');+ const spy = vi.spyOn(extractor, 'extractScenes').mockResolvedValue({+ extracted: { title: null, logline: null, scenes: [{ visualPrompt: 'llm scene' }] },+ runId: 'run-fallback', providerId: 'mock', model: 'mock-model',+ });++ const app = makeApp();+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({+ stages: {+ idea: { status: 'ready', output: '# Beat sheet\n\n## Beats\n1. A beat with no ## Scenes section.' },+ teleplay: { status: 'ready', output: '## TEASER\n\n**INT. VAULT — NIGHT**\n\nThey break in.' },+ },+ });++ const r = await request(app)+ .post(`/api/pipeline/issues/${iss.body.id}/stages/storyboards/extract-scenes`)+ .send({ from: 'teleplay' });++ expect(r.status).toBe(200);+ expect(r.body.usedCanonicalList).toBe(false);+ expect(r.body.sourceKind).toBe('teleplay');+ expect(r.body.runId).toBe('run-fallback');+ expect(spy).toHaveBeenCalledTimes(1);+ spy.mockRestore();+ });+// ---- comicPages/extract-pages ----it('POST /issues/:id/stages/comicPages/extract-pages 400s when comicScript is empty', async () => {diff --git a/server/routes/pipeline/issues.js b/server/routes/pipeline/issues.jsindex 5371e0a2f7..1803281b36 100644--- a/server/routes/pipeline/issues.js+++ b/server/routes/pipeline/issues.js@@ -41,7 +41,7 @@ import { startEpisodeVideoForIssue } from '../../services/pipeline/episodeVideo.import { COMIC_PAGE_VARIANTS, slotKeyForVariant } from '../../services/pipeline/owners.js';import { ASPECT_RATIOS, QUALITIES } from '../../lib/creativeDirectorPresets.js';import { IMAGE_GEN_MODE } from '../../services/imageGen/modes.js';-import { extractScenes, SOURCE_KIND } from '../../lib/sceneExtractor.js';+import { extractScenes, scenesFromBeatSheet, SOURCE_KIND } from '../../lib/sceneExtractor.js';import { resolveSeriesLlmOverride } from '../../lib/seriesLlmOverride.js';import { parseComicScript } from '../../lib/comicScriptParser.js';import {@@ -463,6 +463,45 @@ router.post('/issues/:id/stages/storyboards/extract-scenes', asyncHandler(asyncconst body = validateRequest(extractScenesSchema, req.body ?? {});const issue = await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });issuesSvc.assertStageUnlocked(issue, 'storyboards');++ const existing = Array.isArray(issue.stages?.storyboards?.scenes) ? issue.stages.storyboards.scenes : [];+ if (existing.length > 0 && !body.force) {+ throw new ServerError(+ `Storyboards already has ${existing.length} scene${existing.length === 1 ? '' : 's'} — pass { force: true } to replace`,+ { status: 409, code: 'PIPELINE_STORYBOARDS_NOT_EMPTY' },+ );+ }++ // Adapt a canonical scene to the pipeline storyboards UI shape: alias+ // `visualPrompt → description` (the textarea binding) and reset the per-scene+ // image-gen job fields. Rich fields (heading/summary/dialogue/...) ride along.+ const toStoryboardScene = (s) => ({ ...s, description: s.visualPrompt || '', imageJobId: null, prompt: null });++ // Prefer the beat sheet's canonical `## Scenes` list when present (#1552):+ // it's deterministic, free (no LLM), and guarantees `storyboards.scenes`+ // numbers/sluglines match the comic pages' (both inherit the same canonical+ // list). Fall back to the LLM slugline-parse path only when no list exists.+ const canonicalScenes = scenesFromBeatSheet(issue.stages?.idea?.output || '');+ if (canonicalScenes.length > 0) {+ const storyboardScenes = canonicalScenes.map(toStoryboardScene);+ const { issue: updatedIssue, stage } = await issuesSvc.updateStage(issue.id, 'storyboards', {+ status: 'ready',+ scenes: storyboardScenes,+ lastRunId: null,+ errorMessage: '',+ });+ return res.json({+ issue: updatedIssue,+ stage,+ runId: null,+ providerId: null,+ model: null,+ sceneCount: storyboardScenes.length,+ sourceKind: 'beat-sheet',+ usedCanonicalList: true,+ });+ }+const series = await seriesSvc.getSeries(issue.seriesId).catch((err) => { throw mapServiceError(err); });const sourceKind = body.from;@@ -474,14 +513,6 @@ router.post('/issues/:id/stages/storyboards/extract-scenes', asyncHandler(async);}- const existing = Array.isArray(issue.stages?.storyboards?.scenes) ? issue.stages.storyboards.scenes : [];- if (existing.length > 0 && !body.force) {- throw new ServerError(- `Storyboards already has ${existing.length} scene${existing.length === 1 ? '' : 's'} — pass { force: true } to replace`,- { status: 409, code: 'PIPELINE_STORYBOARDS_NOT_EMPTY' },- );- }-// Fall back to the series' configured LLM when the client doesn't pass an// explicit override — every Pipeline LLM action should honor the// provider/model picked in the issue header (which mirrors series.llm).@@ -512,15 +543,7 @@ router.post('/issues/:id/stages/storyboards/extract-scenes', asyncHandler(asynctag: `pipeline-storyboards-extract-${sourceKind}`,});- // Adapt canonical scene shape to the pipeline storyboards UI shape: alias- // `visualPrompt → description` (the textarea binding) and reset the per-scene- // image-gen job fields. Rich fields (heading/summary/dialogue/...) ride along.- const storyboardScenes = result.extracted.scenes.map((s) => ({- ...s,- description: s.visualPrompt || '',- imageJobId: null,- prompt: null,- }));+ const storyboardScenes = result.extracted.scenes.map(toStoryboardScene);const { issue: updatedIssue, stage } = await issuesSvc.updateStage(issue.id, 'storyboards', {status: storyboardScenes.length ? 'ready' : 'empty',scenes: storyboardScenes,@@ -536,6 +559,7 @@ router.post('/issues/:id/stages/storyboards/extract-scenes', asyncHandler(asyncmodel: result.model,sceneCount: storyboardScenes.length,sourceKind,+ usedCanonicalList: false,});}));