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
story-builder: start from any step and backfill the idea/arc from drafted issues
[._.]/ Adam Eivy06435f98623b
diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsxindex 20415bdc68..3ed44da691 100644--- a/client/src/pages/StoryBuilder.jsx+++ b/client/src/pages/StoryBuilder.jsx@@ -405,6 +405,14 @@ function StepPanel({ session, universe, series, issues, stepId, locked, onChangeconst [busy, setBusy] = useState(false);const arc = series?.arc || {};+ // True when at least one issue already carries text content — the prerequisite+ // for backfilling an upstream step (idea / arc) FROM the downstream work.+ const issuesHaveContent = useMemo(() => (issues || []).some((iss) => {+ const st = iss.stages || {};+ return ['comicScript', 'teleplay', 'prose', 'idea']+ .some((sid) => (st[sid]?.input?.trim() || st[sid]?.output?.trim()));+ }), [issues]);+const runGenerate = async () => {setBusy(true);const res = await generateStoryStep(session.id, stepId, {}, { silent: true })@@ -412,6 +420,27 @@ function StepPanel({ session, universe, series, issues, stepId, locked, onChangesetBusy(false);if (res) { toast.success('Generated'); onChanged(); }};++ // Backfill: synthesize this upstream step from the series' existing issue+ // content instead of from its conventional upstream (start-from-anywhere).+ const runBackfill = async () => {+ setBusy(true);+ const res = await generateStoryStep(session.id, stepId, { fromDownstream: true }, { silent: true })+ .catch((err) => { toast.error(err?.message || 'Backfill failed'); return null; });+ setBusy(false);+ if (res) { toast.success('Backfilled from existing issues'); onChanged(); }+ };++ const backfillButton = () => (+ <button+ onClick={runBackfill} disabled={busy || locked}+ title="Reverse-engineer this step from the scripts / prose your issues already have"+ className="inline-flex items-center gap-2 bg-port-card border border-port-border hover:border-port-accent disabled:opacity-50 px-3 py-1.5 rounded text-sm"+ >+ {busy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Wand2 className="w-4 h-4" />}+ Backfill from existing issues+ </button>+ );const runRefine = async (feedback, entryId) => {setBusy(true);const res = await refineStoryStep(session.id, stepId, { feedback, entryId }, { silent: true })@@ -440,8 +469,14 @@ function StepPanel({ session, universe, series, issues, stepId, locked, onChange<div className="space-y-3"><FieldBlock label="Working title" value={session.title} /><FieldBlock label="Starter idea" value={session.seedIdea} />- {!locked && genButton('Expand idea with AI', Boolean((universe?.logline || '').trim()))}- <p className="text-xs text-gray-500">Expanding seeds the universe starter prompt and series premise for the next steps.</p>+ <div className="flex items-center gap-2 flex-wrap">+ {!locked && genButton('Expand idea with AI', Boolean((universe?.logline || '').trim()))}+ {!locked && issuesHaveContent && backfillButton()}+ </div>+ <p className="text-xs text-gray-500">+ Expanding seeds the universe starter prompt and series premise for the next steps.+ {issuesHaveContent && ' Already drafted issues? Backfill reverse-engineers the idea from their content.'}+ </p></div>);}@@ -476,14 +511,18 @@ function StepPanel({ session, universe, series, issues, stepId, locked, onChange<FieldBlock label="Protagonist arc" value={arc.protagonistArc} /><FieldBlock label="Themes" value={(arc.themes || []).join(', ')} /><FieldBlock label="Emotional shape (Vonnegut)" value={arc.shape} />- <div className="flex items-center gap-2">+ <div className="flex items-center gap-2 flex-wrap">{!locked && genButton('Generate plot arc', Boolean((arc.logline || arc.summary || '').trim()))}+ {!locked && issuesHaveContent && backfillButton()}{series?.id && (<Link to={`/pipeline/series/${series.id}`} className="inline-flex items-center gap-1 text-sm text-gray-400 hover:text-port-accent"><ExternalLink className="w-4 h-4" /> Deep-edit on the Arc Canvas</Link>)}</div>+ {issuesHaveContent && (+ <p className="text-xs text-gray-500">Started from drafted issues? Backfill extracts the arc from their scripts / prose.</p>+ )}</div>);}@@ -730,19 +769,18 @@ function StoryBuilderDetail({ storyId, stepParam }) {const stepState = session?.steps?.[activeStepId] || { status: 'pending', locked: false };const isStale = staleSteps.includes(activeStepId);- // A step is reachable when every earlier step is locked AND not stale.- // Returns `true` (reachable) or a discriminator string identifying the- // first blocking earlier step's reason, so the caller can render the- // matching toast ("Lock the earlier steps first" vs "Re-review the- // stale earlier step first" — same boolean truthiness, different copy).- const reachable = useCallback((idx) => {- if (idx <= 0) return true;+ // Navigation is advisory, not gated: the user may start from any point and+ // work the steps out of order (e.g. start from a drafted comic script and+ // backfill the idea / arc afterward). `firstUnmetUpstream` reports the first+ // earlier step that is unlocked or stale purely so the rail can show a hint —+ // it never blocks navigation.+ const firstUnmetUpstream = useCallback((idx) => {for (let i = 0; i < idx; i++) {const id = stepIds[i];if (session?.steps?.[id]?.locked !== true) return 'unlocked';if (staleSteps.includes(id)) return 'stale';}- return true;+ return null;}, [stepIds, session, staleSteps]);const lock = useLockToggle({@@ -766,15 +804,10 @@ function StoryBuilderDetail({ storyId, stepParam }) {errorMessage: 'Failed to update lock',});- const goToStep = async (id, idx) => {- const why = reachable(idx);- if (why !== true) {- toast.error(why === 'stale'- ? 'Re-review the stale earlier step first'- : 'Lock the earlier steps first');- return;- }- // Persist the current-step pointer (server re-gates); navigate optimistically.+ const goToStep = async (id) => {+ // Free navigation — any step is reachable. Upstream lock/stale state is+ // surfaced as a warning on the step (not a block), so a user can jump to a+ // later step and backfill the earlier ones.await setStoryCurrentStep(storyId, id, { silent: true }).catch(() => {});navigate(`/story-builder/${storyId}/${id}`);};@@ -821,22 +854,27 @@ function StoryBuilderDetail({ storyId, stepParam }) {const st = session.steps?.[s.id] || { status: 'pending', locked: false };const stale = staleSteps.includes(s.id);const isActive = s.id === activeStepId;- // `reachable` returns `true` or a string discriminator ('unlocked' / 'stale');- // canGo must be strictly boolean — `disabled={!canGo}` would otherwise- // treat the truthy string as "reachable" and re-enable a blocked button.- const canGo = reachable(idx) === true;+ // Navigation is never blocked (start-from-anywhere). The warning+ // icon flags a step whose upstream is unlocked or stale so the+ // user knows the order isn't conventional — but they may proceed.+ const unmet = firstUnmetUpstream(idx);return (<button- key={s.id} onClick={() => goToStep(s.id, idx)} disabled={!canGo}+ key={s.id} onClick={() => goToStep(s.id)}className={`w-full text-left px-3 py-2 rounded border flex items-center justify-between gap-2 ${isActive ? 'border-port-accent bg-port-card' : 'border-transparent hover:bg-port-card'- } ${!canGo ? 'opacity-40 cursor-not-allowed' : ''}`}+ }`}><span className="flex items-center gap-2 text-sm">{st.locked ? <Lock className="w-3.5 h-3.5 text-port-success" /> : <span className="w-3.5 h-3.5 rounded-full border border-gray-600 inline-block" />}{s.label}</span>- {stale && <AlertTriangle className="w-3.5 h-3.5 text-port-warning" title="Stale — re-review" />}+ {(stale || unmet) && (+ <AlertTriangle+ className="w-3.5 h-3.5 text-port-warning"+ title={stale ? 'Stale — re-review' : 'Earlier step not locked yet'}+ />+ )}</button>);})}diff --git a/data.reference/prompts/stages/story-builder-idea-expand.md b/data.reference/prompts/stages/story-builder-idea-expand.mdindex ea4a6e09d7..d6d2a1e9e7 100644--- a/data.reference/prompts/stages/story-builder-idea-expand.md+++ b/data.reference/prompts/stages/story-builder-idea-expand.md@@ -7,6 +7,21 @@ You are a story development partner helping a creator turn a one-line seed idea{{#universeName}}- Working universe name: {{universeName}}{{/universeName}}- Seed idea: {{seedIdea}}+{{#sourceMaterial}}+## Existing work to reverse-engineer the idea from++This story already has drafted issue content (a comic script, teleplay, or+prose). You are back-filling the starting idea from work that already exists —+extract the premise that's actually on the page. Stay faithful to the events,+characters, tone, and conflict the source commits to; do NOT invent a different+concept. The seed above (if any) is secondary context — the source below is+authoritative.++~~~~~~~~~~~~~~~~+{{sourceMaterial}}+~~~~~~~~~~~~~~~~+{{/sourceMaterial}}+## TaskExpand the seed into a concrete launch point:diff --git a/docs/plans/2026-05-30-non-linear-stage-generation.md b/docs/plans/2026-05-30-non-linear-stage-generation.mdnew file mode 100644index 0000000000..7bff15878c--- /dev/null+++ b/docs/plans/2026-05-30-non-linear-stage-generation.md@@ -0,0 +1,232 @@+# Non-linear generation: backport across pipeline stages & Story Builder steps++## Context++Today both the **Create Series Pipeline** and the **Story Builder** are strictly+*forward-only*. Each generation step assumes its source is the conventional+upstream artifact:++- Pipeline text stages (`idea → prose → comicScript → teleplay`) are wired so+ `buildStageContext()` (`server/services/pipeline/textStages.js:53`) only ever+ includes stages *before* the current one (`if (id === stageId) break;`), and+ each prompt template hardcodes one source slot (`{{seed}}`, `{{stages.idea.content}}`,+ `{{stages.prose.content}}`).+- Story Builder gates every step behind `isStepReachable()`+ (`server/services/storyBuilder.js`), which hard-throws `409` unless **every**+ earlier step is locked + not stale; its generators only pull from their+ conventional upstream (seed → idea → aesthetic → arc → readerMap).++The user often has work that was authored out of order — e.g. a series that+*started* as a drafted comic book. They want to **backfill the prior steps** to+evaluate whether the story is complete: generate prose from a comic script,+synthesize the idea/arc from issues that already have comic scripts, etc.++**Goal:**+1. **Pipeline** — each stage's Generate button offers a **multi-select source+ picker** listing only the stages that currently have content (never the target+ itself), with the conventional forward source pre-checked. Generation feeds+ the chosen sources into the LLM.+2. **Story Builder** — relax the hard lock-gate to advisory, and make the+ upstream generators able to **pull from existing downstream content** (the+ series' issues' comic-script/prose) — reusing the importer's extraction+ prompts — so you can start from a comic script and backfill idea/arc.++Decisions confirmed with the user: scope = **Pipeline + Story Builder gating**;+pipeline source picker = **multi-select with smart (conventional-forward)+default**; Story Builder = **generate upstream from downstream** (full backfill,+not just navigation unlock).++---++## Part 1 — Pipeline text-stage source picker++### 1a. Server: source-agnostic context (`server/services/pipeline/textStages.js`)++`buildStageContext({ series, canon, world, issue, stageId, seedInput, sourceStageIds })`:++- **Keep** the existing forward-only `stages` object exactly as-is. Customized+ installs whose prompts still reference `{{stages.idea.content}}` /+ `{{stages.prose.content}}` must keep working (these prompts are NOT migrated for+ customized installs — see 1c).+- **Add** a new `sourceMaterials` array to the returned context:+ ```js+ // selected = explicit sourceStageIds if provided & non-empty, else the+ // conventional forward-prior stages that have content (mirrors today's default)+ sourceMaterials: selected.map((id) => ({+ stageId: id,+ label: STAGE_LABELS[id], // reuse existing STAGE_LABELS map (line 22)+ content: contentOf(issue.stages?.[id]) // input?.trim() || output?.trim() || ''+ })).filter((s) => s.content)+ ```+ - When `sourceStageIds` is omitted/empty → default to the forward-prior stages+ with content (so `autoRunner.js`, which calls `generateStage` with no+ `sourceStageIds`, is byte-for-byte unchanged in behavior).+ - When provided → validate each id is a `TEXT_STAGE_IDS` member, is **not** the+ target `stageId`, and has content; silently drop any that fail (or throw 400 —+ pick throw for explicit user requests).+- `generateStage(issueId, stageId, options)` passes+ `sourceStageIds: options.sourceStageIds` into `buildStageContext`.++### 1b. Server route (`server/routes/pipeline.js`)++Extend `generateSchema` (~line 350):+```js+sourceStageIds: z.array(z.enum(['idea', 'prose', 'comicScript', 'teleplay'])).optional(),+```+The handler already spreads the validated body into `generateStage` — no further+route change. `client/src/services/apiPipeline.js` `generatePipelineStage` already+forwards arbitrary `opts`, so no client-API change.++### 1c. Prompt templates + migration++All four templates (`data.reference/prompts/stages/pipeline-{idea-expansion,prose,+comic-script,teleplay}.md`) currently hardcode one source slot. Replace that slot+with a generic, source-agnostic block and make the task wording source-neutral:++```md+{{#sourceMaterials}}+## Source material — {{label}}+{{content}}++{{/sourceMaterials}}+```+- For `pipeline-idea-expansion.md`: keep the `{{seed}}` block (rough idea) AND add+ the `sourceMaterials` block (so the beat sheet can also be synthesized from an+ existing prose/comic/teleplay).+- Reword task lines from "adapting a beat sheet"/"adapting a prose story" to+ "adapting the provided source material" so the prompt reads correctly whichever+ source(s) are supplied.++Because `scripts/setup-data.js` only copies *missing* prompts, ship a migration+following the canonical pattern in `scripts/migrations/003-update-pipeline-stage-prompts.js`:+new file `scripts/migrations/0NN-pipeline-stage-prompts-source-agnostic.js`+(next free number after the highest in `scripts/migrations/`). For each of the 4+files: if the installed copy's md5 (line-ending-normalized) matches the+**pre-change shipped hash**, overwrite with the new shipped version; otherwise+leave the user's customization untouched. Mirror both `OLD_SHIPPED_MD5` and+`NEW_SHIPPED_MD5` into the drift warning in `scripts/setup-data.js` so it stays+actionable (per CLAUDE.md "Stage-prompt template changes need a migration").++### 1d. Client UI (`client/src/components/pipeline/stages/TextStagePanel.jsx`)++- Compute available sources: iterate the text stage order+ (`['idea','prose','comicScript','teleplay']`), exclude the current `stageId`,+ keep those with `input?.trim() || output?.trim()`.+- Render a compact **multi-select** (checkbox row or chips) labeled "Generate+ from:" above the Generate button, listing only available sources, using+ `PIPELINE_STAGE_LABELS` (`client/src/lib/pipelineStages.js`) for labels.+ - Default-checked = the conventional forward source(s) that exist (e.g. for+ `prose` → `idea`; for `comicScript`/`teleplay` → `prose`). If none of the+ conventional sources exist, leave all unchecked and let the user pick.+ - Hide the picker entirely when no other stage has content (fresh issue) — the+ panel then behaves exactly like today.+- Track selection in local state; pass `sourceStageIds: selected` in the+ `generatePipelineStage(issue.id, stageId, { ... })` call.+- Update `PLACEHOLDERS` / `HELP_TEXT` copy to stop asserting a fixed source+ ("Generated from the prose draft above" → "Generated from the selected source").++### 1e. Tests++`server/services/pipeline/textStages.test.js`:+- Default (no `sourceStageIds`) still produces the forward-only `sourceMaterials`+ and matches prior behavior.+- Backport: target `prose` with `sourceStageIds:['comicScript']` puts the comic+ script content into `sourceMaterials` and omits `idea`.+- Invalid source (target===source, or empty stage) is rejected/dropped.++`server/routes/pipeline.test.js`: `sourceStageIds` accepted by `generateSchema`;+bad enum value 400s.++---++## Part 2 — Story Builder: backfill upstream from downstream++### 2a. Relax the reachability gate (advisory, not hard block)++In `server/services/storyBuilder.js`:+- `generateStep()` currently throws `409` when `!isStepReachable(session, stepId)`.+ Change so the lock check (`step.locked` → 409) **stays**, but the+ upstream-incomplete condition no longer blocks generation. Keep+ `isStepReachable()` and surface its result to the client (already returned in+ session/step payloads) as an advisory `reachable`/`stale` flag the UI renders as+ a warning badge — do **not** throw on it.+- The stepper UI (`client/src/pages/StoryBuilder.jsx`) should allow clicking into+ any non-locked step and show a "upstream not locked / may be stale" warning+ instead of disabling it.++### 2b. Backfill-capable generators (pull from existing issue content)++The Story Builder generators (`STEP_GENERATORS` in `storyBuilder.js`) operate at+universe/series level. Add an optional `fromDownstream` path so `idea` and+`plotArc` can synthesize from the series' existing issue content when upstream is+empty:++- Add a helper that collects source text from the session's series issues via+ `getIssuesForSeries(session.seriesId)` (already imported, line 10): concatenate+ each issue's most-authored text stage (prefer `comicScript`, else `teleplay`,+ else `prose`, else `idea`) with a per-issue label, capped to a sane size.+- **`plotArc` generator:** when `options.fromDownstream` (or when no arc exists yet+ but issues do), feed that collected issue content into arc generation. Reuse the+ importer's arc-extraction prompt (`importer-arc-extract.md`) — the importer+ already reverse-engineers `{logline, summary, seasons[...]}` from a finished+ work; route through the same extraction service the importer uses+ (`server/services/importer.js`) rather than duplicating the prompt call. Persist+ to `series.arc` / `series.seasons` exactly as the forward `generateArcOverview`+ path does.+- **`idea` generator:** when backfilling, include the collected issue content as+ additional source in the `story-builder-idea-expand` prompt input (add an+ optional `sourceMaterial` field to `data.reference/prompts/stages/story-builder-idea-expand.md`,+ rendered only when present — migrate via the same migration mechanism as 1c).+- **characters / readerMap:** `characters` can already be backfilled by the+ importer's canon extraction (`importer-canon-extract.md`); `readerMap` derives+ from the (now backfillable) arc, so it works once arc exists. No new generator+ needed for these in this pass — note in PLAN.md if deeper backfill is wanted.++### 2c. Plumb the option through route + client++- `server/routes/storyBuilder.js`: add `fromDownstream: z.boolean().optional()`+ (and, if exposing source choice, an optional source descriptor) to the+ generate-step request schema; forward into `generateStep` options.+- `client/src/services/apiStoryBuilder.js` + `StoryBuilder.jsx`: when a step's+ conventional upstream is empty but downstream issue content exists, offer a+ "Backfill from existing issues" affordance on that step's generate control that+ sends `fromDownstream: true`.++### 2d. Tests++- `server/services/storyBuilder.test.js`: generating `plotArc` with+ `fromDownstream` on a session whose series has issues-with-comic-scripts but no+ arc produces a persisted arc; the reachability gate no longer throws 409 for an+ unlocked-but-explicitly-requested upstream step (only `locked` throws).+- `server/routes/storyBuilder.test.js`: new schema field accepted/validated.++---++## Compatibility notes (per CLAUDE.md)++- **Migrations required** for every shipped prompt change (1c, 2b idea prompt) —+ other installs/machines run this code and upgrade independently. Use the+ hash-gated rewrite pattern and update the `setup-data.js` drift warning.+- Keep `buildStageContext`'s legacy `stages` object so customized (un-migrated)+ prompts keep resolving.+- `autoRunner.js` must remain behaviorally unchanged (it calls `generateStage`+ with no `sourceStageIds` → default forward sources).+- No sync/schema-version payload changes expected (Story Builder sessions are+ local-only; pipeline issue shape is unchanged — only generation *inputs* change).++## Verification++1. `cd server && npm test` (textStages, pipeline route, storyBuilder service+route).+2. `cd client && npm test` (TextStagePanel / StoryBuilder component tests).+3. Manual via `npm run dev`:+ - Pipeline: open an issue that has only a comic script; on the Prose stage the+ source picker lists "Comic Script" (and Teleplay if present), Idea is absent.+ Generate → prose is produced from the comic script. Verify the Idea stage can+ be generated from prose/comic (backport).+ - Story Builder: import or hand-build a session whose series has issues with+ comic scripts but no arc; confirm you can enter the Plot Arc step despite+ upstream being unlocked, click "Backfill from existing issues", and get a+ populated arc; confirm a locked step still refuses regeneration.+4. Migration: on a copy of `data/` with the pre-change stage prompts, run the+ migration and confirm only unmodified prompts are upgraded; customized ones are+ left intact and flagged by the drift warning.diff --git a/scripts/migrations/055-story-builder-idea-backfill-prompt.js b/scripts/migrations/055-story-builder-idea-backfill-prompt.jsnew file mode 100644index 0000000000..dc4dee4d8d--- /dev/null+++ b/scripts/migrations/055-story-builder-idea-backfill-prompt.js@@ -0,0 +1,47 @@+/**+ * Add the optional `{{sourceMaterial}}` backfill block to the Story Builder+ * idea-expand prompt.+ *+ * The Story Builder can now reverse-engineer the starting idea from a series'+ * existing issue content (the "started from a drafted comic script" case). When+ * the user backfills the idea step, the conductor passes the concatenated issue+ * corpus as `sourceMaterial`; the prompt renders it under a new section and is+ * told to extract the premise already on the page. The forward (seed-only) path+ * is unchanged — the section only renders when `sourceMaterial` is non-empty.+ *+ * `scripts/setup-data.js` only copies *missing* prompts, so existing installs+ * keep their old template until this migration rewrites it. Customization-safe:+ * only an install whose copy still hashes to the known pre-change shipped+ * version is auto-updated; a customized prompt is left intact and warned about.+ *+ * Strategy: hash-driven prompt-replace via `./_lib.js`. Idempotent.+ */++import { makePromptReplaceMigration } from './_lib.js';++export const ACCEPTED_OLD_MD5 = {+ 'story-builder-idea-expand.md': ['a23939626a226f7420cebfb45d47950c'],+};++export const NEW_SHIPPED_MD5 = {+ 'story-builder-idea-expand.md': '778c86e2caa120856c36e4d5a4da3355',+};++const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5,+ current: NEW_SHIPPED_MD5,+ label: 'story-builder idea backfill prompt',+ customizedHint: (filename) =>+ ` To apply the {{sourceMaterial}} backfill block manually, diff:\n` ++ ` data.reference/prompts/stages/${filename}\n` ++ ` against your current:\n` ++ ` data/prompts/stages/${filename}\n` ++ ` and add the {{#sourceMaterial}} … {{/sourceMaterial}} section after the seed.`,+ skipFooter: (count) =>+ `⚠️ ${count} story-builder prompt could not be auto-updated because it was\n` ++ ` customized. Backfilling the idea from existing issues will still run, but\n` ++ ` the prompt won't render the source material until you merge the section.`,+});++export { applyMigration };+export default { up };diff --git a/scripts/migrations/055-story-builder-idea-backfill-prompt.test.js b/scripts/migrations/055-story-builder-idea-backfill-prompt.test.jsnew file mode 100644index 0000000000..330dec5726--- /dev/null+++ b/scripts/migrations/055-story-builder-idea-backfill-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 './055-story-builder-idea-backfill-prompt.js';++describe('migration 055 — story-builder idea backfill prompt', () => {+ runPromptMigrationTests({+ migration,+ applyMigration,+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ prefix: 'migration-055-',+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 5dd3c4c371..e07536dc3f 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1844,6 +1844,10 @@ export const storySessionUpdateSchema = z.object({export const storyStepGenerateSchema = z.object({providerId: storyProviderField,model: storyModelField,+ // Backfill toggle: synthesize this (upstream) step from the series' existing+ // downstream issue content instead of its conventional upstream. Honored by+ // the idea + plotArc generators (see services/storyBuilder.js generateStep).+ fromDownstream: z.boolean().optional(),}).strict();export const storyStepRefineSchema = z.object({diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.jsindex 3c9893fd72..79ca0f9be2 100644--- a/server/services/pipeline/arcPlanner.js+++ b/server/services/pipeline/arcPlanner.js@@ -290,6 +290,67 @@ export async function generateArcOverview(seriesId, options = {}) {};}+/**+ * Reverse-engineer an arc + seasons from EXISTING finished work (a concatenated+ * corpus of the series' issue scripts / prose), rather than forward-generating+ * from the series bible. This is the Story Builder's "backfill the arc from a+ * drafted comic" path — it reuses the importer's `importer-arc-extract` prompt+ * (which is purpose-built to describe the spine already in a text) and returns+ * the SAME `{ arc, seasons, ... }` shape as generateArcOverview so the caller+ * can commit it through the identical commitSeasonsWithRemap path.+ *+ * `contentType` defaults to 'comic-script'; it only tunes the prompt's+ * per-type guidance (issue/volume boundary heuristics).+ */+export async function generateArcFromSource(seriesId, {+ sourceText, contentType = 'comic-script', providerOverride, modelOverride,+} = {}) {+ const series = await getSeries(seriesId);+ if (series.locked?.arc === true) {+ throw makeErr(+ 'Arc is locked — unlock it on the Arc Canvas before regenerating',+ ERR_VALIDATION,+ );+ }+ const source = String(sourceText || '').trim();+ if (!source) throw makeErr('No source content to extract an arc from', ERR_VALIDATION);+ const { content, runId, providerId, model } = await runStagedLLM(+ 'importer-arc-extract',+ {+ seriesName: series.name,+ contentType,+ source,+ // Mirror the importer's per-type Mustache section guards so the prompt's+ // boundary heuristics fire correctly (buildTypeFlags in importer.js).+ isShortStory: contentType === 'short-story',+ isNovel: contentType === 'novel',+ isScreenplay: contentType === 'screenplay',+ isComicScript: contentType === 'comic-script',+ },+ {+ providerOverride,+ modelOverride,+ returnsJson: true,+ source: 'story-builder-arc-backfill',+ },+ );+ const arc = sanitizeArc({+ logline: content?.logline || '',+ summary: content?.summary || '',+ themes: content?.themes,+ protagonistArc: content?.protagonistArc || '',+ // Honor the importer prompt's `shape` pick; fall back to any existing pick.+ shape: content?.shape ?? series.arc?.shape ?? null,+ // Preserve an existing reader map — the extraction doesn't author one.+ readerMap: series.arc?.readerMap ?? null,+ status: 'draft',+ });+ // importer-arc-extract returns `seasons` (number/title/logline/synopsis/+ // endingHook); shapeSeasonOutlines reads the same fields buildSeason needs.+ const seasons = shapeSeasonOutlines(content?.seasons);+ return { arc, seasons, raw: content, runId, providerId, model };+}+// Reader-map context: the protagonist arc + the Vonnegut shape backbone + the// planned volume boundaries (so the LLM can place cliffhangers at issue gaps).// Mirrors buildArcOverviewContext's world+arc projection.diff --git a/server/services/storyBuilder.js b/server/services/storyBuilder.jsindex 96d5c1c78e..23b586caf9 100644--- a/server/services/storyBuilder.js+++ b/server/services/storyBuilder.js@@ -26,7 +26,7 @@ import { sanitizeOrigin } from '../lib/sharingOrigin.js';import { sanitizeSoftDeleteFields } from '../lib/syncWire.js';import { runStagedLLM } from '../lib/stageRunner.js';import {- STEP_IDS, STEP_STATUSES, isValidStepId, stepIndex,+ STEP_IDS, STEP_STATUSES, isValidStepId,} from '../lib/storyBuilderSteps.js';import { hashUpstream, computeStaleSteps } from '../lib/storyBuilderIntegrity.js';import { createUniverse, getUniverse, updateUniverse } from './universeBuilder.js';@@ -37,8 +37,10 @@ import {createSeries, getSeries, updateSeries, setArcFieldLock,} from './pipeline/series.js';import {- generateArcOverview, generateReaderMap, refineReaderMap, commitSeasonsWithRemap,+ generateArcOverview, generateArcFromSource, generateReaderMap, refineReaderMap, commitSeasonsWithRemap,} from './pipeline/arcPlanner.js';+import { listIssues } from './pipeline/issues.js';+import { stageContentOf } from './pipeline/textStages.js';const TYPE_SCHEMA_VERSION = 1;@@ -387,27 +389,17 @@ export async function unlockStep(id, stepId) {}/**- * Set the wizard's current step. Gated: cannot advance to a step unless every- * earlier step is locked AND no earlier locked step is stale.+ * Set the wizard's current step.+ *+ * Advisory, not gated: a user may start from any point and work the steps out+ * of order (e.g. begin from a drafted comic script and backfill the idea / arc+ * afterward). The client surfaces "upstream not locked" / "stale" as warnings+ * (from the `staleSteps` array in the session view) rather than hard blocks.+ * The only enforcement that remains is at the generators themselves — a *locked*+ * underlying record (arc, readerMap, …) still refuses regeneration.*/export async function setCurrentStep(id, stepId) {if (!isValidStepId(stepId)) throw makeErr(`Unknown step: ${stepId}`, ERR_VALIDATION);- const session = await getStorySession(id);- const target = stepIndex(stepId);- const cur = stepIndex(session.currentStep);- if (target > cur) {- const { hashes } = await computeCurrentHashes(session);- const stale = computeStaleSteps(session, hashes);- for (let i = 0; i < target; i++) {- const earlier = STEP_IDS[i];- if (session.steps[earlier]?.locked !== true) {- throw makeErr(`Cannot advance: step "${earlier}" must be locked first`, ERR_VALIDATION);- }- if (stale.includes(earlier)) {- throw makeErr(`Cannot advance: step "${earlier}" is stale — re-review and re-lock it`, ERR_VALIDATION);- }- }- }return updateStorySession(id, { currentStep: stepId });}@@ -429,11 +421,43 @@ export async function setIssueLock(id, issueId, locked) {});}+// ── Backfill (generate upstream from downstream) ───────────────────────────++// Cap the concatenated issue corpus fed into a backfill extraction so a long+// series can't blow past the provider's context budget. The importer enforces+// its own (much larger) source ceiling; this is the Story-Builder-side bound.+const BACKFILL_SOURCE_MAX = 200_000;++// Collect existing issue content for the session's series, newest-authored+// artifact per issue, so an upstream step (idea / plotArc) can be synthesized+// FROM the downstream work that already exists — the user's "started from a+// comic script" case. Prefers the richest stage (comicScript → teleplay →+// prose → idea). Returns '' when no issue has any text content.+async function collectIssueSourceText(seriesId) {+ if (!seriesId) return '';+ const issues = await listIssues({ seriesId }).catch(() => []);+ const ordered = [...issues].sort((a, b) => (a.number || 0) - (b.number || 0));+ const parts = [];+ for (const iss of ordered) {+ const st = iss.stages || {};+ const pick = ['comicScript', 'teleplay', 'prose', 'idea']+ .map((sid) => ({ sid, content: stageContentOf(st[sid]) }))+ .find((x) => x.content);+ if (!pick) continue;+ parts.push(`# Issue ${iss.number}${iss.title ? ` — ${iss.title}` : ''} (${pick.sid})\n\n${pick.content}`);+ }+ return parts.join('\n\n---\n\n').slice(0, BACKFILL_SOURCE_MAX);+}+// ── Generate / refine delegation ──────────────────────────────────────────// Each step's generate delegates to the existing service that owns its content,// then persists into the universe/series record. Returns the LLM result so the// route can surface runId / changes / rationale.+//+// `options.fromDownstream` flips a step from forward-generation to backfill:+// idea / plotArc synthesize themselves from the series' existing issue content+// instead of from their (possibly empty) conventional upstream.export async function generateStep(id, stepId, options = {}) {const session = await getStorySession(id);// Provider/model resolution: an explicit per-call override wins, else fall@@ -442,9 +466,13 @@ export async function generateStep(id, stepId, options = {}) {const reqProviderId = options.providerId || session.llm?.provider || undefined;const reqModel = options.model || session.llm?.model || undefined;if (stepId === 'idea') {+ // Backfill: reverse-engineer the idea from existing issue content when the+ // user started downstream. Rendered only when present, so the forward path+ // (seed-only) is byte-for-byte unchanged.+ const sourceMaterial = options.fromDownstream ? await collectIssueSourceText(session.seriesId) : '';const { content, runId, providerId, model } = await runStagedLLM('story-builder-idea-expand',- { universeName: session.title, seedIdea: session.seedIdea || '' },+ { universeName: session.title, seedIdea: session.seedIdea || '', sourceMaterial },{ providerOverride: reqProviderId, modelOverride: reqModel, returnsJson: true, source: 'story-builder-idea-expand' },);const expandedIdea = isStr(content?.expandedIdea) ? content.expandedIdea.trim() : '';@@ -489,9 +517,26 @@ export async function generateStep(id, stepId, options = {}) {}if (stepId === 'plotArc') {if (!session.seriesId) throw makeErr('No series linked', ERR_VALIDATION);- const { arc, seasons, runId, providerId, model } = await generateArcOverview(session.seriesId, {- providerOverride: reqProviderId, modelOverride: reqModel,- });+ let arc; let seasons; let runId; let providerId; let model;+ if (options.fromDownstream) {+ // Backfill: extract the arc + seasons from the issues that already exist+ // (the user drafted scripts/prose first). Reuses the importer's+ // arc-extraction prompt via arcPlanner.generateArcFromSource.+ const sourceText = await collectIssueSourceText(session.seriesId);+ if (!sourceText) {+ throw makeErr(+ 'No issue content to backfill the arc from — write a comic script, teleplay, or prose on at least one issue first',+ ERR_VALIDATION,+ );+ }+ ({ arc, seasons, runId, providerId, model } = await generateArcFromSource(session.seriesId, {+ sourceText, providerOverride: reqProviderId, modelOverride: reqModel,+ }));+ } else {+ ({ arc, seasons, runId, providerId, model } = await generateArcOverview(session.seriesId, {+ providerOverride: reqProviderId, modelOverride: reqModel,+ }));+ }// A null arc means the LLM returned nothing identifying — refuse rather// than wiping a previously-generated arc with `updateSeries({ arc: null })`.if (!arc) throw makeErr('LLM returned an empty arc — try regenerating', ERR_VALIDATION);diff --git a/server/services/storyBuilder.test.js b/server/services/storyBuilder.test.jsindex 3ea76bc029..6306ac1be4 100644--- a/server/services/storyBuilder.test.js+++ b/server/services/storyBuilder.test.js@@ -31,6 +31,7 @@ vi.mock('../lib/stageRunner.js', () => ({const sb = await import('./storyBuilder.js');const seriesSvc = await import('./pipeline/series.js');const universeSvc = await import('./universeBuilder.js');+const issuesSvc = await import('./pipeline/issues.js');beforeEach(() => {fileStore.clear();@@ -91,15 +92,15 @@ describe('storyBuilder — lock state machine + gating', () => {expect(locked.steps.idea.lockedAt).toBeTruthy();});- it('cannot advance to a step until every earlier step is locked', async () => {+ it('allows jumping to any step out of order (start-from-anywhere)', async () => {const s = await sb.createStorySession({ title: 'X' });- // idea not locked → cannot jump to universeAesthetic- await expect(sb.setCurrentStep(s.id, 'universeAesthetic')).rejects.toMatchObject({ code: sb.ERR_VALIDATION });- await sb.lockStep(s.id, 'idea');- const moved = await sb.setCurrentStep(s.id, 'universeAesthetic');- expect(moved.currentStep).toBe('universeAesthetic');- // plotArc still blocked — universeAesthetic not locked- await expect(sb.setCurrentStep(s.id, 'plotArc')).rejects.toMatchObject({ code: sb.ERR_VALIDATION });+ // Navigation is advisory, not gated: the user may jump straight to a later+ // step and backfill the earlier ones. (Lock/stale state is surfaced as a+ // warning in the session view, enforced only at the generators.)+ const moved = await sb.setCurrentStep(s.id, 'plotArc');+ expect(moved.currentStep).toBe('plotArc');+ // Unknown ids still reject.+ await expect(sb.setCurrentStep(s.id, 'bogus')).rejects.toMatchObject({ code: sb.ERR_VALIDATION });});it('moving backward is always allowed', async () => {@@ -240,3 +241,83 @@ describe('storyBuilder — generate delegation', () => {expect(universe.starterPrompt).toBe('new starter prose');});});++describe('generateStep backfill (fromDownstream)', () => {+ // Record the stage + vars of the most recent staged-LLM call so a test can+ // assert which prompt a backfill routed through.+ let seenStage;+ let seenVars;+ function installSpy() {+ seenStage = null; seenVars = null;+ stageRunnerSpy = async (stage, vars) => {+ seenStage = stage; seenVars = vars;+ let content = {};+ if (stage === 'story-builder-idea-expand') content = { title: 'T', logline: 'L', expandedIdea: 'E' };+ else if (stage === 'importer-arc-extract') {+ content = {+ logline: 'Backfilled arc logline', summary: 'Backfilled summary',+ protagonistArc: 'grows', themes: ['legacy'], shape: 'man-in-hole',+ seasons: [{ number: 1, title: 'Vol 1', logline: 'v1', synopsis: 's1', endingHook: 'hook' }],+ };+ } else if (stage === 'pipeline-arc-overview') {+ content = {+ logline: 'Forward arc logline', summary: 'Forward summary',+ protagonistArc: 'grows', themes: ['legacy'], shape: 'man-in-hole',+ seasonOutlines: [{ number: 1, title: 'Vol 1', episodeCountTarget: 6 }],+ };+ }+ return { content, runId: 'run-x', providerId: 'p', model: 'm' };+ };+ }++ // A seed session mints its own universe + series; attach a drafted comic+ // script to one issue, mirroring the "started from a drafted comic" case.+ async function makeSessionWithDraftedIssue() {+ const s = await sb.createStorySession({ title: 'Backfill' });+ const issue = await issuesSvc.createIssue({ seriesId: s.seriesId, title: 'Issue One' });+ await issuesSvc.updateStage(issue.id, 'comicScript', { status: 'ready', output: 'PAGE 1 ... a drafted comic script ...' });+ return { session: s, issue };+ }++ it('plotArc backfill extracts the arc from issue content via importer-arc-extract', async () => {+ installSpy();+ const { session } = await makeSessionWithDraftedIssue();+ const res = await sb.generateStep(session.id, 'plotArc', { fromDownstream: true });+ expect(seenStage).toBe('importer-arc-extract');+ expect(seenVars.source).toContain('drafted comic script');+ const updated = await seriesSvc.getSeries(session.seriesId);+ expect(updated.arc?.logline).toBe('Backfilled arc logline');+ expect(updated.seasons?.length).toBe(1);+ expect(res.runId).toBe('run-x');+ });++ it('plotArc forward path still uses pipeline-arc-overview (no fromDownstream)', async () => {+ installSpy();+ const { session } = await makeSessionWithDraftedIssue();+ await sb.generateStep(session.id, 'plotArc', {});+ expect(seenStage).toBe('pipeline-arc-overview');+ });++ it('plotArc backfill refuses when no issue has content', async () => {+ installSpy();+ const s = await sb.createStorySession({ title: 'Empty' });+ await expect(sb.generateStep(s.id, 'plotArc', { fromDownstream: true }))+ .rejects.toThrow(/No issue content/);+ });++ it('idea backfill feeds issue content into the idea-expand prompt', async () => {+ installSpy();+ const { session } = await makeSessionWithDraftedIssue();+ await sb.generateStep(session.id, 'idea', { fromDownstream: true });+ expect(seenStage).toBe('story-builder-idea-expand');+ expect(seenVars.sourceMaterial).toContain('drafted comic script');+ });++ it('idea forward path sends an empty sourceMaterial', async () => {+ installSpy();+ const { session } = await makeSessionWithDraftedIssue();+ await sb.generateStep(session.id, 'idea', {});+ expect(seenStage).toBe('story-builder-idea-expand');+ expect(seenVars.sourceMaterial).toBe('');+ });+});