Skip to content

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

pipeline: let any text stage generate from any other populated stage (backport)

[._.]/ Adam Eivy10792610f79c
diff --git a/client/src/components/pipeline/stages/TextStagePanel.jsx b/client/src/components/pipeline/stages/TextStagePanel.jsx
index d213c4c65e..04812d2497 100644
--- a/client/src/components/pipeline/stages/TextStagePanel.jsx
+++ b/client/src/components/pipeline/stages/TextStagePanel.jsx
@@ -5,18 +5,22 @@
* generate button that calls the server's text-stage runner.
*/
-import { useEffect, useState } from 'react';
+import { useEffect, useMemo, useState } from 'react';
import { Loader2, Sparkles, Save, History } from 'lucide-react';
import toast from '../../ui/Toast';
import {
generatePipelineStage, updatePipelineIssue,
PIPELINE_STAGE_LABELS,
+ PIPELINE_TEXT_STAGES,
+ PIPELINE_DEFAULT_FORWARD_SOURCE as DEFAULT_FORWARD_SOURCE,
PIPELINE_STAGE_STATUS_LABEL as STATUS_LABEL,
PIPELINE_STAGE_STATUS_COLOR as STATUS_COLOR,
} from '../../../services/api';
import { useAsyncAction } from '../../../hooks/useAsyncAction';
import StageHistoryModal from './StageHistoryModal';
+const stageHasContent = (stage) => Boolean(stage?.input?.trim() || stage?.output?.trim());
+
export default function TextStagePanel({
issue,
series,
@@ -38,6 +42,34 @@ export default function TextStagePanel({
const [historyOpen, setHistoryOpen] = useState(false);
const runHistory = stage.runHistory || [];
+ // Other text stages that currently have content — the candidate source
+ // material for this generation. Excludes the target stage itself. Lets you
+ // generate any stage FROM any other populated stage (backport), e.g. prose
+ // from a comic script. Ordered by the canonical stage order.
+ const availableSources = useMemo(
+ () => PIPELINE_TEXT_STAGES.filter(
+ (id) => id !== stageId && stageHasContent(issue.stages?.[id]),
+ ),
+ [issue.stages, stageId],
+ );
+
+ // Selected source stage ids. Defaults to the conventional forward source(s)
+ // that exist; recomputed whenever the candidate set changes (issue/stage swap).
+ // `availableKey` is a stable string proxy for the availableSources array so
+ // the effect re-runs on membership change without an array identity in deps.
+ const availableKey = availableSources.join(',');
+ const [selectedSources, setSelectedSources] = useState([]);
+ useEffect(() => {
+ const preferred = (DEFAULT_FORWARD_SOURCE[stageId] || []).filter((id) => availableSources.includes(id));
+ setSelectedSources(preferred);
+ // availableSources is captured via its `availableKey` string proxy.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [issue.id, stageId, availableKey]);
+
+ const toggleSource = (id) => setSelectedSources(
+ (prev) => (prev.includes(id) ? prev.filter((s) => s !== id) : [...prev, id]),
+ );
+
// Reset local edits when the stage record changes from the parent (e.g.
// auto-run pushed a new output).
useEffect(() => {
@@ -51,6 +83,9 @@ export default function TextStagePanel({
seedInput: draftInput,
providerId: series?.llm?.provider || undefined,
model: series?.llm?.model || undefined,
+ // Only send when there's a real choice to make — omitting it lets the
+ // server fall back to the conventional forward source (unchanged behavior).
+ ...(availableSources.length ? { sourceStageIds: selectedSources } : {}),
}),
{ errorMessage: `Failed to generate ${stageId}` },
);
@@ -131,6 +166,30 @@ export default function TextStagePanel({
</div>
</div>
+ {availableSources.length > 0 ? (
+ <div className="flex items-center gap-2 flex-wrap text-xs">
+ <span className="uppercase tracking-wider text-gray-500">Generate from:</span>
+ {availableSources.map((id) => {
+ const active = selectedSources.includes(id);
+ return (
+ <button
+ key={id}
+ type="button"
+ onClick={() => toggleSource(id)}
+ aria-pressed={active}
+ className={`px-2 py-1 rounded-full border transition-colors ${
+ active
+ ? 'bg-port-accent/20 border-port-accent text-white'
+ : 'bg-port-card border-port-border text-gray-400 hover:border-port-accent/50'
+ }`}
+ >
+ {PIPELINE_STAGE_LABELS[id]}
+ </button>
+ );
+ })}
+ </div>
+ ) : null}
+
{stageId === 'idea' ? (
<label className="block">
<span className="block text-xs uppercase tracking-wider text-gray-500 mb-1">Seed idea</span>
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index 6f74be6d4a..c2b94d2947 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -38,6 +38,16 @@ export const PIPELINE_STAGE_LABELS = Object.freeze({
audio: 'Audio',
});
+// The stage that conventionally feeds each text-stage target — mirrors the
+// server's DEFAULT_FORWARD_SOURCE (server/services/pipeline/textStages.js).
+// The text-stage source picker pre-checks these so the common forward flow
+// needs no clicks, while still letting any populated stage be a backport source.
+export const PIPELINE_DEFAULT_FORWARD_SOURCE = Object.freeze({
+ prose: ['idea'],
+ comicScript: ['prose'],
+ teleplay: ['prose'],
+});
+
export const PIPELINE_TARGET_FORMATS = Object.freeze(['comic', 'tv', 'comic+tv']);
export const PIPELINE_STAGE_STATUS_LABEL = Object.freeze({
diff --git a/data.reference/prompts/stages/pipeline-comic-script.md b/data.reference/prompts/stages/pipeline-comic-script.md
index 4a65a39f42..c3c971bc6b 100644
--- a/data.reference/prompts/stages/pipeline-comic-script.md
+++ b/data.reference/prompts/stages/pipeline-comic-script.md
@@ -27,12 +27,24 @@ Terse roster of the linked Universe Builder's named canon — use as continuity
- **Title:** {{issue.title}}
- **Length profile:** {{lengthTargets.profile}} — target {{lengthTargets.pageTarget}}-page issue
-## Prose source
+## Source material
+
+Adapt the source material below into the comic script. Usually this is the
+issue's prose draft, but it may be a teleplay, beat sheet, or other stage
+content — honor whatever is provided.
+
+{{#sourceMaterials}}
+### {{label}}
```
-{{stages.prose.content}}
+{{content}}
```
+{{/sourceMaterials}}
+{{^sourceMaterials}}
+*(No source material was provided — work from the series bible and issue context above.)*
+{{/sourceMaterials}}
+
## Output format
Return a markdown document with this exact structure. **Do not bold the field labels and do not put `###` in front of `Panel N`** — keep the formatting minimal so the image generator can read the panel content cleanly.
@@ -72,7 +84,7 @@ Panel 2
## Rules
-- **Target a {{lengthTargets.pageTarget}}-page single issue.** Pace the prose source across exactly {{lengthTargets.pageTarget}} pages — inflate quiet beats with reaction shots, environmental panels, and silent panels if the prose is thin; compress dense action across multiple pages with panel-to-panel motion if it is rich. Do not pad for padding's sake, but do not skip pages either.
+- **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.
- **Strong opening (Saga-style):** page 1 lands the reader inside a specific, sensory moment — a striking image plus one line of voice-over or arresting dialogue. No expository "previously on" walls. The first panel should be a hook the reader cannot put down. Page 1 is often a splash or near-splash.
- **Cliffhanger / lead-in ending:** the final page (and ideally the final panel) must do one of: (a) reveal something that flips what we thought we knew, (b) deliver a cliffhanger — character in peril, decision unmade, antagonist arriving — or (c) plant the seed for the next issue with a clear "to be continued" pull. Never end on resolution alone.
diff --git a/data.reference/prompts/stages/pipeline-idea-expansion.md b/data.reference/prompts/stages/pipeline-idea-expansion.md
index d05f348893..5e931d21a0 100644
--- a/data.reference/prompts/stages/pipeline-idea-expansion.md
+++ b/data.reference/prompts/stages/pipeline-idea-expansion.md
@@ -122,6 +122,23 @@ Your closing beat / cliffhanger must hand cleanly into this next issue. The prot
{{seed}}
```
+{{#hasSourceMaterials}}
+## Existing source material to back-fill from
+
+You are reverse-engineering this beat sheet from work that already exists for
+this issue (prose, a comic script, or a teleplay). Extract the beats that are
+already on the page — do NOT invent a different story. Stay faithful to the
+events, characters, and ending the source already commits to.
+{{/hasSourceMaterials}}
+{{#sourceMaterials}}
+### {{label}}
+
+```
+{{content}}
+```
+
+{{/sourceMaterials}}
+
## What to produce
A markdown document with the following sections, in this exact order:
diff --git a/data.reference/prompts/stages/pipeline-prose.md b/data.reference/prompts/stages/pipeline-prose.md
index ef093b56cf..19f35ff27d 100644
--- a/data.reference/prompts/stages/pipeline-prose.md
+++ b/data.reference/prompts/stages/pipeline-prose.md
@@ -29,12 +29,24 @@ A terse roster of the linked Universe Builder's named canon — use these as con
- **Title:** {{issue.title}}
- **Length profile:** {{lengthTargets.profile}} — target {{lengthTargets.pageTarget}} comic pages / {{lengthTargets.minutesTarget}}-minute episode
-## Beat sheet (from the idea stage)
+## Source material
+
+Adapt the source material below into prose. Usually this is the issue's beat
+sheet, but it may be a finished comic script, teleplay, or other stage content
+when you're back-filling the prose from later work — honor whatever is provided.
+
+{{#sourceMaterials}}
+### {{label}}
```
-{{stages.idea.content}}
+{{content}}
```
+{{/sourceMaterials}}
+{{^sourceMaterials}}
+*(No source material was provided — work from the series bible and issue context above.)*
+{{/sourceMaterials}}
+
## 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**.
@@ -42,7 +54,7 @@ A self-contained short-story draft for this issue, **{{lengthTargets.proseWordsM
- 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.
- Show character through action and dialogue, not narration.
-- Hit every beat from the beat sheet, but feel free to inflate one beat into multiple scenes if it has more weight. With {{lengthTargets.pageTarget}} pages downstream, lean toward *more* dramatized texture per beat rather than racing to the climax.
+- Hit every beat from the source material, but feel free to inflate one beat into multiple scenes if it has more weight. With {{lengthTargets.pageTarget}} pages downstream, lean toward *more* dramatized texture per beat rather than racing to the climax.
- **Land the ending on a cliffhanger or strong lead-in to the next issue** — a reveal that flips what the reader thought, a character in unresolved peril, or an antagonist's arrival. The last paragraph is what the comic's final-page panel will render, so make it visually decisive. Resolution-only endings are not acceptable; serialized comics need pull.
- Don't invent contradictions to the character bible. Add details, but match the established ones.
diff --git a/data.reference/prompts/stages/pipeline-teleplay.md b/data.reference/prompts/stages/pipeline-teleplay.md
index a032d959a3..6a82d27efa 100644
--- a/data.reference/prompts/stages/pipeline-teleplay.md
+++ b/data.reference/prompts/stages/pipeline-teleplay.md
@@ -27,12 +27,24 @@ Terse roster of the linked Universe Builder's named canon — use as continuity
- **Title:** {{issue.title}}
- **Length profile:** {{lengthTargets.profile}} — target {{lengthTargets.minutesTarget}}-minute episode
-## Prose source
+## Source material
+
+Adapt the source material below into the teleplay. Usually this is the issue's
+prose draft, but it may be a comic script, beat sheet, or other stage content —
+honor whatever is provided.
+
+{{#sourceMaterials}}
+### {{label}}
```
-{{stages.prose.content}}
+{{content}}
```
+{{/sourceMaterials}}
+{{^sourceMaterials}}
+*(No source material was provided — work from the series bible and issue context above.)*
+{{/sourceMaterials}}
+
## Output format
Return a markdown document with this exact structure:
@@ -76,7 +88,7 @@ CUT TO:
- CAPS character names above their dialogue lines.
- Parentheticals only when the line reading would otherwise be ambiguous.
- Scene transitions in caps: `CUT TO:`, `SMASH CUT TO:`, `FADE TO:`.
-- Cover the same story beats as the prose, but free to add visual texture (establishing shots, silent reaction beats, B-story interludes) the prose only implied — you have {{lengthTargets.minutesTarget}} minutes of screen time, not {{lengthTargets.proseWordsMin}}–{{lengthTargets.proseWordsMax}} words of compressed text.
+- Cover the same story beats as the source material, but free to add visual texture (establishing shots, silent reaction beats, B-story interludes) the source only implied — you have {{lengthTargets.minutesTarget}} minutes of screen time, not {{lengthTargets.proseWordsMin}}–{{lengthTargets.proseWordsMax}} words of compressed text.
- **End every act with a button** — an image, a line, or a reveal that pulls the viewer past the act break. Act-outs are non-negotiable; they're where the audience decides whether to stick around.
- Vary scene length: rapid-fire montage sequences should sit next to one-location dialogue scenes that breathe. Don't let every scene be the same energy.
diff --git a/scripts/migrations/054-source-agnostic-stage-prompts.js b/scripts/migrations/054-source-agnostic-stage-prompts.js
new file mode 100644
index 0000000000..4f583db33e
--- /dev/null
+++ b/scripts/migrations/054-source-agnostic-stage-prompts.js
@@ -0,0 +1,61 @@
+/**
+ * Make the pipeline text-stage prompts source-agnostic.
+ *
+ * Previously each template hardcoded one upstream source slot:
+ * - pipeline-prose → {{stages.idea.content}} (beat sheet only)
+ * - pipeline-comic-script → {{stages.prose.content}} (prose only)
+ * - pipeline-teleplay → {{stages.prose.content}} (prose only)
+ * - pipeline-idea-expansion → {{seed}} only
+ *
+ * They now render a generic `{{#sourceMaterials}}` block so any stage can be
+ * generated FROM any other populated stage (backport: prose from a comic
+ * script, beat sheet back-filled from finished prose, etc.). See
+ * server/services/pipeline/textStages.js (buildStageContext → sourceMaterials).
+ *
+ * `scripts/setup-data.js` only copies *missing* prompts, so existing installs
+ * keep their old templates until this migration rewrites them. Customization-
+ * safe: only installs whose copy still hashes to a known pre-change shipped
+ * version are auto-updated; customized prompts are left intact and warned about.
+ *
+ * Strategy: hash-driven prompt-replace via `./_lib.js`. Idempotent.
+ */
+
+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'],
+ 'pipeline-prose.md': ['d1f8e3f1d214725b5aa67f309a81cd7d'],
+ 'pipeline-comic-script.md': ['133d200d069c2e8173b7c129eea58f53'],
+ 'pipeline-teleplay.md': ['1280ef6b1ad68fa44070ca7478ec2a5f'],
+};
+
+// Post-change shipped hashes (the source-agnostic templates this migration
+// installs). Mirror these into setup-data.js's drift table.
+export const NEW_SHIPPED_MD5 = {
+ 'pipeline-idea-expansion.md': 'b5c47c94ffc74637983c95761ab0c66c',
+ 'pipeline-prose.md': 'bef1bc2767b78f585f2bd89f3d615130',
+ 'pipeline-comic-script.md': 'e530fc76b89cedaef848ad7ec99c934c',
+ 'pipeline-teleplay.md': '2568e14beaa574d43f8018a5def51d04',
+};
+
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'source-agnostic stage prompt',
+ customizedHint: (filename) =>
+ ` To apply the source-agnostic {{#sourceMaterials}} block manually, diff:\n` +
+ ` data.reference/prompts/stages/${filename}\n` +
+ ` against your current:\n` +
+ ` data/prompts/stages/${filename}\n` +
+ ` and replace the hardcoded {{stages.*.content}} / {{seed}}-only source\n` +
+ ` slot with the {{#sourceMaterials}} loop.`,
+ skipFooter: (count) =>
+ `⚠️ ${count} stage prompt(s) could not be auto-updated because they were\n` +
+ ` customized. Generating a stage from a non-default source will still\n` +
+ ` work, but those prompts won't render the chosen source until you merge\n` +
+ ` the {{#sourceMaterials}} block. See data.reference/prompts/stages/.`,
+});
+
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/054-source-agnostic-stage-prompts.test.js b/scripts/migrations/054-source-agnostic-stage-prompts.test.js
new file mode 100644
index 0000000000..01b92bf15c
--- /dev/null
+++ b/scripts/migrations/054-source-agnostic-stage-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 './054-source-agnostic-stage-prompts.js';
+
+describe('migration 054 — source-agnostic stage prompts', () => {
+ runPromptMigrationTests({
+ migration,
+ applyMigration,
+ ACCEPTED_OLD_MD5,
+ NEW_SHIPPED_MD5,
+ prefix: 'migration-054-',
+ });
+});
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index e1559a9efc..413626158d 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -359,6 +359,10 @@ const generateSchema = z.object({
seedInput: z.string().max(issuesSvc.STAGE_INPUT_MAX).optional(),
providerId: z.string().trim().max(80).optional(),
model: z.string().trim().max(200).optional(),
+ // Explicit source stages to feed the generation (backport support: generate
+ // any stage FROM any other populated stage). Omit for the conventional
+ // forward source. The service drops the target itself and empty stages.
+ sourceStageIds: z.array(z.enum(['idea', 'prose', 'comicScript', 'teleplay'])).optional(),
});
const visualGenerateSchema = z.object({
diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.js
index 012bd22d52..d23125cf7f 100644
--- a/server/services/pipeline/textStages.js
+++ b/server/services/pipeline/textStages.js
@@ -31,6 +31,30 @@ const STAGE_TO_TEMPLATE = Object.freeze({
teleplay: 'pipeline-teleplay',
});
+// Human labels for the {{#sourceMaterials}} block so the LLM sees "Comic Script"
+// rather than "comicScript". Mirrors the client's PIPELINE_STAGE_LABELS.
+const STAGE_LABELS = Object.freeze({
+ idea: 'Idea / Beat Sheet',
+ prose: 'Prose Draft',
+ comicScript: 'Comic Script',
+ teleplay: 'Teleplay',
+});
+
+// The stage that conventionally feeds each target when no explicit source is
+// chosen — mirrors the strict forward chain. Idea has no upstream text stage
+// (it derives from the seed); comic/teleplay both adapt prose. Used to compute
+// the default source set so autoRunner and the legacy UI path are unchanged.
+const DEFAULT_FORWARD_SOURCE = Object.freeze({
+ prose: ['idea'],
+ comicScript: ['prose'],
+ teleplay: ['prose'],
+});
+
+// User-edited input takes precedence over raw LLM output — matches how editors
+// actually work the artifact. Exported so backfill paths (storyBuilder) read a
+// stage's content through the same precedence rule.
+export const stageContentOf = (stage) => (stage?.input?.trim() || stage?.output?.trim() || '');
+
// Set exactly one of `beats` / `synopsis` per neighbor so the prompt's
// beat-level guidance doesn't leak into synopsis-only entries (the template
// gates on each field independently).
@@ -131,12 +155,40 @@ async function buildIdeaContextAugment(series, issue) {
};
}
+/**
+ * Resolve the ordered list of stage ids whose content should feed this
+ * generation as source material.
+ *
+ * - When `sourceStageIds` is provided (non-empty), use exactly those — this is
+ * the backport path (e.g. generate prose FROM comicScript). Each id must be a
+ * valid text stage, must not be the target stage itself, and must have
+ * content; anything failing those checks is dropped.
+ * - When omitted/empty, fall back to the conventional forward source(s) that
+ * have content — so the auto-runner and the legacy UI behave exactly as before.
+ *
+ * Returned in TEXT_STAGE_IDS order for stable prompt rendering.
+ */
+function resolveSourceStageIds({ issue, stageId, sourceStageIds }) {
+ const requested = Array.isArray(sourceStageIds)
+ ? sourceStageIds
+ : DEFAULT_FORWARD_SOURCE[stageId] || [];
+ const eligible = new Set(
+ requested.filter((id) =>
+ TEXT_STAGE_IDS.includes(id)
+ && id !== stageId
+ && stageContentOf(issue.stages?.[id])),
+ );
+ return TEXT_STAGE_IDS.filter((id) => eligible.has(id));
+}
+
/**
* Build the variable bag fed into the stage template. Includes the series
- * bible (`series.*`) and every *prior* text stage's content (`stages.*`).
+ * bible (`series.*`) and every *prior* text stage's content (`stages.*`), plus
+ * a source-agnostic `sourceMaterials` array (the stages explicitly chosen as
+ * source, defaulting to the conventional forward source).
* Visual stages aren't included — text templates don't need rendered images.
*/
-function buildStageContext({ series, canon, world, issue, stageId, seedInput }) {
+function buildStageContext({ series, canon, world, issue, stageId, seedInput, sourceStageIds }) {
const stages = {};
for (const id of TEXT_STAGE_IDS) {
if (id === stageId) break; // only include stages BEFORE the current one
@@ -145,9 +197,15 @@ function buildStageContext({ series, canon, world, issue, stageId, seedInput })
status: cur.status || 'empty',
// Prefer the user-edited input over the raw LLM output when present —
// matches how editors actually work the artifact.
- content: (cur.input?.trim() || cur.output?.trim() || ''),
+ content: stageContentOf(cur),
};
}
+ // Source-agnostic block: whichever stages were chosen (or the conventional
+ // default) rendered as labeled blocks. This is what lets a target stage adapt
+ // from ANY other populated stage — generate prose from a comic script, or
+ // backfill the beat sheet from finished prose.
+ const sourceMaterials = resolveSourceStageIds({ issue, stageId, sourceStageIds })
+ .map((id) => ({ stageId: id, label: STAGE_LABELS[id] || id, content: stageContentOf(issue.stages?.[id]) }));
// Compact one-line-per-kind synopsis of the linked universe's canon. Lets
// per-issue text prompts reference named entities without paying the full
// canon-block token cost — `series.characters` already covers the bible-
@@ -174,6 +232,10 @@ function buildStageContext({ series, canon, world, issue, stageId, seedInput })
// (defaults to 'standard') so templates can use the fields unconditionally.
lengthTargets: computeIssueTargets(issue),
stages,
+ sourceMaterials,
+ // Scalar guard for templates that want a one-time header before the
+ // {{#sourceMaterials}} loop — the engine can't nest same-name sections.
+ hasSourceMaterials: sourceMaterials.length > 0,
seed: (seedInput || issue.stages?.[stageId]?.input || '').trim(),
};
}
@@ -213,7 +275,11 @@ export async function generateStage(issueId, stageId, options = {}) {
await updateStage(issueId, stageId, { status: 'generating', errorMessage: '' });
- const ctx = buildStageContext({ series, canon, world, issue, stageId, seedInput: options.seedInput });
+ const ctx = buildStageContext({
+ series, canon, world, issue, stageId,
+ seedInput: options.seedInput,
+ sourceStageIds: options.sourceStageIds,
+ });
if (stageId === 'idea') {
Object.assign(ctx, await buildIdeaContextAugment(series, issue));
}
@@ -274,4 +340,4 @@ export async function generateStage(issueId, stageId, options = {}) {
}
// Export internals for tests.
-export const __testing = { buildStageContext, buildIdeaContextAugment, shapeNeighborForIdeaPrompt, STAGE_TO_TEMPLATE };
+export const __testing = { buildStageContext, buildIdeaContextAugment, shapeNeighborForIdeaPrompt, resolveSourceStageIds, STAGE_TO_TEMPLATE, STAGE_LABELS, DEFAULT_FORWARD_SOURCE };
diff --git a/server/services/pipeline/textStages.test.js b/server/services/pipeline/textStages.test.js
index 2ea688f6a0..ed94508a45 100644
--- a/server/services/pipeline/textStages.test.js
+++ b/server/services/pipeline/textStages.test.js
@@ -392,4 +392,62 @@ describe('pipeline text stage generator', () => {
expect(lt.beatsMin).toBe(16);
expect(lt.beatsMax).toBe(24);
});
+
+ // -- source material (backport) --
+
+ // Seed an issue whose stages already carry content, so we can target one
+ // stage and feed it from any other. Mirrors the user's "started from a comic
+ // script" case.
+ async function seedWithStages() {
+ const { series, issue } = await seed();
+ await issuesSvc.updateStage(issue.id, 'idea', { status: 'ready', output: 'BEATS-CONTENT' });
+ await issuesSvc.updateStage(issue.id, 'prose', { status: 'ready', output: 'PROSE-CONTENT' });
+ await issuesSvc.updateStage(issue.id, 'comicScript', { status: 'ready', output: 'SCRIPT-CONTENT' });
+ return { series, issueId: issue.id };
+ }
+
+ it('default source: prose pulls the idea beat sheet when no sourceStageIds given', async () => {
+ const { issueId } = await seedWithStages();
+ await textStages.generateStage(issueId, 'prose');
+ const ctx = ctxFromCall(llmCalls[0]);
+ expect(ctx.sourceMaterials).toEqual([
+ { stageId: 'idea', label: 'Idea / Beat Sheet', content: 'BEATS-CONTENT' },
+ ]);
+ expect(ctx.hasSourceMaterials).toBe(true);
+ });
+
+ it('backport: generate prose FROM an explicit comic-script source', async () => {
+ const { issueId } = await seedWithStages();
+ await textStages.generateStage(issueId, 'prose', { sourceStageIds: ['comicScript'] });
+ const ctx = ctxFromCall(llmCalls[0]);
+ expect(ctx.sourceMaterials).toEqual([
+ { stageId: 'comicScript', label: 'Comic Script', content: 'SCRIPT-CONTENT' },
+ ]);
+ });
+
+ it('drops the target itself + empty/unknown sources and orders by stage order', async () => {
+ const { issueId } = await seedWithStages();
+ // teleplay is empty; prose === target; bogus is unknown — all dropped.
+ await textStages.generateStage(issueId, 'prose', {
+ sourceStageIds: ['comicScript', 'prose', 'teleplay', 'bogus', 'idea'],
+ });
+ const ctx = ctxFromCall(llmCalls[0]);
+ expect(ctx.sourceMaterials.map((s) => s.stageId)).toEqual(['idea', 'comicScript']);
+ });
+
+ it('backfills the beat sheet (idea) from existing comic-script content', async () => {
+ const { issueId } = await seedWithStages();
+ await textStages.generateStage(issueId, 'idea', { sourceStageIds: ['comicScript'] });
+ const ctx = ctxFromCall(llmCalls[0]);
+ expect(ctx.sourceMaterials.map((s) => s.stageId)).toEqual(['comicScript']);
+ expect(ctx.hasSourceMaterials).toBe(true);
+ });
+
+ it('idea with no explicit source has no default forward source (empty sourceMaterials)', async () => {
+ const { issueId } = await seedWithStages();
+ await textStages.generateStage(issueId, 'idea');
+ const ctx = ctxFromCall(llmCalls[0]);
+ expect(ctx.sourceMaterials).toEqual([]);
+ expect(ctx.hasSourceMaterials).toBe(false);
+ });
});