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

fix: validate series arc before episode generation

[._.]/ Adam Eivyd767a6a05cfc
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 128b2d9577..e450d1b600 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -5,5 +5,8 @@
- **Series Autopilot now protects the author’s originating story intent.** The Universe Builder starter idea is included in foundation-cache invalidation, rendered ahead of derived canon for the independent foundation judge, and supplied explicitly to arc generation with a hard rule against replacing its ontology, protagonists, or core story engine. Full-control runs still unlock derived world fields, but they keep the human-authored starter idea locked.
- **Character-first foundation repair gets a quality-first runtime.** Productive ensemble work may run for up to two hours instead of being discarded at ten minutes, while a finite ceiling still stops a genuinely hung provider.
- **Episode synopsis revisions are now restorable.** Text-stage history snapshots preserve input-only stages as well as generated output, so regenerating an episode plan can no longer discard the prior synopsis merely because that planning stage stores its authored text in `input`.
+- **Series Autopilot now validates the arc spine before spending on episodes.** A protected-intent checkpoint runs immediately after the macro arc, uses only canon demonstrably tied to the current series, honors the recommended volume count (including a single 12-issue volume), and blocks or auto-corrects an incompatible premise before issue generation. Existing empty issue placeholders are reused as an exact set so their ids, history, and visual links survive episode seeding.
+- **Stopping Series Autopilot now stops the active AI run.** Direct arc, episode, foundation, correction, and fallback runs publish their concrete run ids to the conductor, so Stop no longer waits for a long provider call to finish. Runs History also exposes Stop for active rows.
+- **Runs History safely displays structured model output.** Prompt and output endpoints are read as plain text, preventing valid JSON completions from crashing React when a run is expanded.
- **Continuing a video carries its prompt forward.** Continuing or extending a clip we generated now prefills the Video Gen prompt (and negative prompt) with the one that produced the source, instead of dropping you into an empty box. This covers both entry points: the **Continue** action on a video card/lightbox, and picking a prior render in Extend mode. Text you typed yourself is never overwritten — only a blank box or a value an earlier pick filled — and a clip we didn't generate (an import, or a legacy render with no stored prompt) leaves the field alone rather than clearing it. The style preset is dropped along with the prefill, since history stores the already-composed prompt and re-applying a preset would prefix it twice.
- **Subscription Usage cards now lay out in four quadrants.** The provider quota grid orders Claude, Antigravity, Codex, Grok — and because Codex and Grok typically report only a single weekly meter, they now share one grid cell stacked vertically instead of each stretching to a full-height card. Cards render at their natural height, so the Image Gen card floats into the fourth quadrant and the whole section fits above the fold on desktop.
diff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsx
index a37fe646f5..803485a051 100644
--- a/client/src/components/pipeline/AutopilotPanel.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.jsx
@@ -241,6 +241,7 @@ const STEP_LABELS = {
generateArc: 'Generating arc',
repairArcStructure: 'Repairing volume structure',
generateEpisodes: 'Generating episodes',
+ verifyArcSpine: 'Checking arc spine',
verifyArc: 'Verifying arc',
foundationGate: 'Judging foundation',
beatSheet: 'Generating beat sheets',
diff --git a/client/src/pages/RunsHistoryPage.jsx b/client/src/pages/RunsHistoryPage.jsx
index bb0efc5fcb..328ba09ed2 100644
--- a/client/src/pages/RunsHistoryPage.jsx
+++ b/client/src/pages/RunsHistoryPage.jsx
@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router';
-import { Trash2, RotateCcw, MessageSquarePlus, ScrollText } from 'lucide-react';
+import { Trash2, RotateCcw, MessageSquarePlus, ScrollText, Square } from 'lucide-react';
import * as api from '../services/api';
import { formatTime, formatRuntime, formatBytes, formatDateTime } from '../utils/formatters';
import BrailleSpinner from '../components/BrailleSpinner';
@@ -25,6 +25,7 @@ export function RunsHistoryPage() {
const [expandedDetails, setExpandedDetails] = useState({});
const [sourceFilter, setSourceFilter] = useState('all');
const [statusFilter, setStatusFilter] = useState('all');
+ const [stoppingIds, setStoppingIds] = useState(() => new Set());
// The failed run whose system logs are open in the log modal, or null.
const [logModalRun, setLogModalRun] = useState(null);
@@ -61,6 +62,28 @@ export function RunsHistoryPage() {
if (expandedId === id) setExpandedId(null);
};
+ const handleStop = async (id, e) => {
+ e.stopPropagation();
+ setStoppingIds((prev) => new Set(prev).add(id));
+ const stopped = await api.stopRun(id).then(() => true).catch(() => false);
+ if (!stopped) {
+ setStoppingIds((prev) => {
+ const next = new Set(prev);
+ next.delete(id);
+ return next;
+ });
+ return;
+ }
+ // Completion metadata lands asynchronously after the child process exits;
+ // refresh once so the row transitions from Running to its terminal state.
+ await loadRuns();
+ setStoppingIds((prev) => {
+ const next = new Set(prev);
+ next.delete(id);
+ return next;
+ });
+ };
+
const toggleExpand = async (id) => {
if (expandedId === id) {
setExpandedId(null);
@@ -307,6 +330,18 @@ export function RunsHistoryPage() {
<RotateCcw size={14} />
</button>
)}
+ {run.success === null && (
+ <button
+ onClick={(e) => handleStop(run.id, e)}
+ disabled={stoppingIds.has(run.id)}
+ className="p-1 text-gray-500 hover:text-port-error transition-colors disabled:opacity-40 sm:opacity-0 sm:group-hover:opacity-100 focus-visible:opacity-100 sm:focus-visible:opacity-100"
+ title={stoppingIds.has(run.id) ? 'Stopping run' : 'Stop run'}
+ aria-label={stoppingIds.has(run.id) ? 'Stopping run' : 'Stop run'}
+ data-testid={`stop-run-${run.id}`}
+ >
+ <Square size={14} fill="currentColor" />
+ </button>
+ )}
<button
onClick={(e) => handleDelete(run.id, e)}
className="p-1 text-gray-500 hover:text-port-error transition-colors sm:opacity-0 sm:group-hover:opacity-100 focus-visible:opacity-100 sm:focus-visible:opacity-100"
diff --git a/client/src/services/apiRuns.js b/client/src/services/apiRuns.js
index 6666bc494a..81d1fe9f0f 100644
--- a/client/src/services/apiRuns.js
+++ b/client/src/services/apiRuns.js
@@ -8,8 +8,11 @@ export const createRun = (data) => request('/runs', {
body: JSON.stringify(data)
});
export const getRun = (id) => request(`/runs/${id}`);
-export const getRunOutput = (id) => request(`/runs/${id}/output`);
-export const getRunPrompt = (id) => request(`/runs/${id}/prompt`);
+// These endpoints deliberately return text/plain. A model response can itself
+// be valid JSON; forcing the shared request helper's default JSON parser turns
+// it into an object that React cannot render inside <pre>.
+export const getRunOutput = (id) => request(`/runs/${id}/output`, { responseType: 'text' });
+export const getRunPrompt = (id) => request(`/runs/${id}/prompt`, { responseType: 'text' });
export const stopRun = (id) => request(`/runs/${id}/stop`, { method: 'POST' });
export const deleteRun = (id) => request(`/runs/${id}`, { method: 'DELETE' });
export const deleteFailedRuns = () => request('/runs?filter=failed', { method: 'DELETE' });
diff --git a/data.reference/prompts/stages/pipeline-arc-overview.md b/data.reference/prompts/stages/pipeline-arc-overview.md
index 3a090f2e5e..34e025094b 100644
--- a/data.reference/prompts/stages/pipeline-arc-overview.md
+++ b/data.reference/prompts/stages/pipeline-arc-overview.md
@@ -1,6 +1,6 @@
# Pipeline — Series Arc Overview
-You are a senior story editor sketching the **top-level multi-season story spine** for a new series. The user has a series bible (name, logline, premise, characters, target format, target issue count). The output gets persisted as `series.arc` + `series.seasons[]` and feeds every downstream per-season + per-episode prompt.
+You are a senior story editor sketching the **top-level whole-series story spine** for a new series. The user has a series bible (name, logline, premise, characters, target format, target issue count). The output gets persisted as `series.arc` + `series.seasons[]` (volumes) and feeds every downstream per-volume + per-episode prompt.
This is the most expensive single call in the pipeline (you reason over the full series scope) so be deliberate.
@@ -32,10 +32,16 @@ No shape pre-picked. Choose the single Vonnegut shape that best matches the prem
{{series.styleNotes}}
```
-- **Target total episode count (rough budget across all seasons):** {{series.issueCountTarget}}
+- **Target total episode count (rough budget across all volumes):** {{series.issueCountTarget}}
+
+- **Recommended volume structure for this target:** {{recommendedStructure}}
+
+Treat that recommendation as the default unless the premise supplies a concrete
+reason to depart from it. In particular, do not inflate a 12-issue limited
+series into three volumes merely because multi-volume fiction is possible.
{{#hasLinkedWorld}}
-## Linked World — canonical entities
+## Linked World — series-scoped canonical entities
The series is grounded in this World Builder world: **{{worldName}}**. The
starter idea is the user's protected originating intent; generated world fields
@@ -60,10 +66,15 @@ starter idea and repair the derived plan around it.
- **Influences to embrace:** {{worldInfluencesEmbrace}}
- **Influences to avoid:** {{worldInfluencesAvoid}}
-When you write season loglines / synopses and the protagonist arc, ground them
-in the canonical entities below by name (not generic placeholders). If a world
-canon entry names a character, place, or object that fits the season's beats,
-prefer it over inventing a new one.
+The named canon below has been scoped to entities demonstrably tied to this
+series' current protected premise and character arcs. Treat those characters as
+the presumed principals. Do not promote omitted world records, abandoned-draft
+antagonists, factions, or institutions into the story merely because they exist
+elsewhere in the shared world. Add supporting entities only when the active
+ensemble cannot carry a necessary function.
+
+When you write volume loglines / synopses and the protagonist arc, ground them
+in the scoped canonical entities below by name (not generic placeholders).
### World canon — named characters, places, objects
@@ -76,17 +87,17 @@ prefer it over inventing a new one.
## How to shape the arc
-1. **Logline (one sentence).** Pitch the whole multi-season arc — not the pilot. Should answer "what is this *show* about" if you only get 20 seconds in an elevator.
-2. **Summary (~500 words).** Act structure across the whole series. Hit the rough turning points: where does the protagonist start, where do they pivot at the end of each season, where do they land at the series finale. Be specific enough that someone writing season 2 can tell whether their idea fits.
+1. **Logline (one sentence).** Pitch the whole-series arc — not the opening issue. It should answer "what is this series about" in 20 seconds.
+2. **Summary (~500 words).** Act structure across the whole series. Hit the rough turning points: where do the principals start, which choices pivot each volume, and where do they land at the series finale. Be specific enough that someone expanding any volume can tell whether an idea fits.
3. **Themes (2–5 short tags).** The recurring concerns — `betrayal`, `legacy`, `the cost of memory`, `class & inheritance`. Keep each tag short (≤80 chars).
-4. **Protagonist arc.** Character growth across all seasons. Where does the protagonist start morally / emotionally, and where do they end. This is the spine for later character-consistency checks.
-5. **Season outlines.** Break the arc into 2–5 seasons. Default to **3 seasons** if `issueCountTarget` is large enough; collapse to 2 if the premise is tight. For each season write:
+4. **Protagonist arc.** Character growth across the complete volume plan. Where does the protagonist start morally / emotionally, and where do they end. This is the spine for later character-consistency checks.
+5. **Volume outlines.** Break the arc into 1–5 volumes, following the recommended structure above unless story weight clearly requires a different division. A single 12-issue volume is a complete valid structure; never add volumes just to reach an arbitrary default. For each volume write:
- **`number`** — 1-indexed, contiguous.
- **`title`** — short noun phrase (e.g. *The Choir Awakens*, *Diaspora*, *Salt at the Root*). Avoid generic ones like "Pilot" or "Season 1".
- - **`logline`** — one sentence; what changes in this season.
- - **`endingHook`** — the image or line that pulls the audience into season N+1. Skippable for the final season (leave empty).
- - **`episodeCountTarget`** — integer. Divide `issueCountTarget` across the seasons roughly proportionally to season weight. Sum of all `episodeCountTarget`s should approximately equal `issueCountTarget`.
-6. **Thread nesting (MICE).** Treat each season as opening and closing narrative threads (a Milieu / Inquiry / Character / Event question). Threads must close in the REVERSE order they open — the last thread opened is the first resolved, like nested brackets. In each season's `logline` (or the `summary`), name the thread this season OPENS and the thread it CLOSES, so the nesting is legible: a season that opens a thread it never closes leaves a dangling question; one that closes a thread out of order breaks the nesting.
+ - **`logline`** — one sentence; what changes in this volume.
+ - **`endingHook`** — the image or line that pulls the audience into volume N+1. Skippable for the final volume (leave empty).
+ - **`episodeCountTarget`** — integer. Divide `issueCountTarget` across the volumes roughly proportionally to story weight. The sum should approximately equal `issueCountTarget`.
+6. **Thread nesting (MICE).** Treat each volume as opening and closing narrative threads (a Milieu / Inquiry / Character / Event question). Threads must close in the REVERSE order they open — the last thread opened is the first resolved, like nested brackets. In each volume's `logline` (or the `summary`), name the thread this volume OPENS and the thread it CLOSES, so the nesting is legible: a volume that opens a thread it never closes leaves a dangling question; one that closes a thread out of order breaks the nesting.
7. **Foreshadowing ledger (2–6 seeds).** Plan the major setups the series plants early and pays off later — a Chekhov's gun, a prophecy, an unexplained scar, a withheld secret. For each seed record:
- **`label`** — a short name for the seed (e.g. *The locked room*, *Mara's limp*, *The recurring bell*).
- **`plantIssue`** — the 1-indexed issue number where it's first planted (subtly introduced, not explained).
@@ -104,7 +115,7 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c
"logline": "string (the whole-series pitch, one sentence)",
"summary": "string (~500 words, multi-paragraph plain text — escape newlines as \\n)",
"themes": ["string", "..."],
- "protagonistArc": "string (character growth across all seasons)",
+ "protagonistArc": "string (character growth across the complete volume plan)",
"shape": "one of: rags-to-riches | tragedy | man-in-hole | icarus | cinderella | oedipus | boy-meets-girl | creation-story",
"seasonOutlines": [
{
diff --git a/data.reference/prompts/stages/pipeline-arc-verify.md b/data.reference/prompts/stages/pipeline-arc-verify.md
index d0b297f19f..5a2462ae97 100644
--- a/data.reference/prompts/stages/pipeline-arc-verify.md
+++ b/data.reference/prompts/stages/pipeline-arc-verify.md
@@ -1,6 +1,6 @@
# Pipeline — Series Arc Verification
-You are a continuity editor doing a cross-season pass on a planned series. The user has authored an arc, seasons, and (at least some) per-episode breakdowns — your job is to surface **structural problems before the production pipeline burns LLM + GPU minutes on broken material**. This is NOT a creative critique — don't suggest "what if we made it darker"; only flag continuity and structural breaks.
+You are a continuity editor doing a cross-volume pass on a planned series. The user has authored an arc and volume plan, and may not yet have per-episode breakdowns — your job is to surface **structural problems before the production pipeline burns LLM + GPU minutes on broken material**. This is NOT a taste-only critique; flag contradictions, protected-intent drift, and structural breaks with the smallest concrete repair.
## Series bible
@@ -16,9 +16,23 @@ You are a continuity editor doing a cross-season pass on a planned series. The u
{{> bible-deference }}
{{#hasLinkedWorld}}
-## Linked World — canonical entities
+## Linked World — protected intent + series-scoped canon
-The series is grounded in this World Builder world: **{{worldName}}**. When you flag continuity findings, address characters/places/objects by their canonical names below. A "character contradiction" finding should reference the canon character; a "dropped subplot" finding should reference a canon place or object when relevant.
+The series is grounded in this World Builder world: **{{worldName}}**.
+
+- **Protected author intent (starter idea):** {{worldStarter}}
+- **World logline:** {{worldLogline}}
+- **World premise:**
+
+```
+{{worldPremise}}
+```
+
+The starter idea is the user's authoritative originating contract. Generated
+world fields, named canon, and the proposed arc may elaborate it but may not
+replace its ontology, protagonists, or central dramatic engine. The named canon
+below is scoped to this series; omitted shared-world records are not evidence
+that an old draft's cast, villain, faction, or institution belongs in this arc.
### World canon — named characters, places, objects
@@ -47,34 +61,43 @@ The series is grounded in this World Builder world: **{{worldName}}**. When you
{{{shapeGuidance}}}
-## Seasons + episodes
+## Volumes + episodes
```json
{{seasonsTreeJson}}
```
+{{#arcSpineOnly}}
+This is the pre-episode **arc-spine checkpoint**. Judge the protected premise,
+active principals, whole-series dramatic engine, character causality, and
+volume allocation. Episode arrays are intentionally empty: do not flag missing
+episodes, episode arc roles, or episode-level continuity. The spine must be safe
+to expand before episode generation begins.
+{{/arcSpineOnly}}
+
## What to look for
-Walk the seasons in order. Score each season + each episode against the arc. Specifically check:
+Walk the volumes in order. Score each volume + each episode against the arc. Specifically check:
-1. **Character contradictions.** Did the protagonist (or a major character) end season N in a state that contradicts season N+1's opening? Did a character die in episode 4 but get dialogue in episode 7?
-2. **Dropped subplots.** A subplot introduced in an early season's `endingHook` or episode `synopsis` that never gets resolved in a later season's `summary` or episode list.
-3. **Episode-count vs. arc-weight mismatch.** A season with `episodeCountTarget: 12` whose synopsis is summarizable in 3 beats. A season with `episodeCountTarget: 4` carrying the weight of a 12-episode arc.
-4. **Unresolved hooks at the series finale.** The final season ends without paying off the whole-arc logline, protagonist arc, or any of the major themes.
-5. **Arc-role imbalance.** A season with 8 episodes and zero `pilot` / `finale` `arcRole` entries (or two `pilot`s / two `finale`s).
-6. **Theme drift.** A theme is named in `arc.themes` but doesn't appear in any season synopsis or episode logline.
-7. **Story-shape adherence.** If a Vonnegut shape was selected (see "Story shape" above — skip this check if none was selected), verify the season-level fortune trajectory traces that curve. Flag volumes whose `endingHook` lands at a fortune level that contradicts the curve (e.g. a "rags-to-riches" volume ending lower than it opened, a "tragedy" volume ending in unambiguous triumph, an "icarus" arc whose crash never comes). The whole-series finale must land at the shape's terminal level.
+1. **Protected-intent drift.** Does the plan replace the originating protagonists, ontology, or core story engine with an incompatible cast, villain, institution, or conflict? Does it demote a living nonhuman principal into a tool when the premise gives it an independent need?
+2. **Character causality and contradictions.** Do the active principals' wants, needs, choices, and relationships cause the major turns? Did a major character end volume N in a state that contradicts volume N+1's opening, or die and later speak without explanation?
+3. **Dropped subplots.** A subplot introduced in an early volume's `endingHook` or episode `synopsis` that never resolves in a later volume or episode.
+4. **Episode-count vs. arc-weight mismatch.** A volume with `episodeCountTarget: 12` whose synopsis carries only 3 meaningful turns, or a short volume carrying a full novel's weight.
+5. **Unresolved hooks at the series finale.** The final volume fails to pay off the whole-arc logline, protagonist arc, or major themes.
+6. **Arc-role imbalance.** Once episodes exist, a volume with 8 episodes and zero `pilot` / `finale` `arcRole` entries (or duplicate pilots/finales).
+7. **Theme drift.** A theme is named in `arc.themes` but does not appear in any volume synopsis or episode logline.
+8. **Story-shape adherence.** If a Vonnegut shape was selected, verify the volume-level fortune trajectory traces that curve. The whole-series finale must land at the shape's terminal level.
## Output contract
-Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary. Each `issues[]` entry must be **actionable** — name the season and (if applicable) the episode that's broken, name the rule it breaks, and propose a concrete fix the user can apply by editing the offending record:
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary. Each `issues[]` entry must be **actionable** — name the volume and (if applicable) the episode that's broken, name the rule it breaks, and propose a concrete fix the user can apply by editing the offending record:
```json
{
"issues": [
{
"severity": "high",
- "location": "season:2 / episode:5",
+ "location": "volume:2 / episode:5",
"problem": "string (what's wrong, with the specific evidence)",
"suggestion": "string (the smallest edit that resolves it)"
}
@@ -85,7 +108,7 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c
`severity` must be one of `high` / `medium` / `low`:
- **`high`** — would break a viewer's understanding of the story (dead character speaking, contradictory protagonist state).
-- **`medium`** — would make the story feel sloppy (dropped subplot, unbalanced season).
+- **`medium`** — would make the story feel sloppy (dropped subplot, unbalanced volume).
- **`low`** — opportunity to tighten (under-used theme, missing arc-role variety).
Return `{ "issues": [] }` if everything checks out. Do NOT pad with low-confidence "consider also..." entries.
diff --git a/scripts/migrations/005-shape-aware-arc-prompts.js b/scripts/migrations/005-shape-aware-arc-prompts.js
index 016038c377..f1a0e9af9b 100644
--- a/scripts/migrations/005-shape-aware-arc-prompts.js
+++ b/scripts/migrations/005-shape-aware-arc-prompts.js
@@ -49,8 +49,8 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-overview.md': '648e11352cd1565aee490de1f662bef0', // post-249 protected author intent
- 'pipeline-arc-verify.md': '36aa70cdfc25d7549573a4d556e7702c', // post-019
+ 'pipeline-arc-overview.md': '5ed760caaf3cf88916ec28b220e2f590', // post-250 arc spine checkpoint
+ 'pipeline-arc-verify.md': '83347e7d923580a3062033ab39b3c14b', // post-250 arc spine checkpoint
'pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940', // post-019
'pipeline-season-episodes.md': 'a88e8e78a949b7aaf500d03314e2ea0b', // post-172 (structure rules)
'pipeline-arc-resolve.md': '8bb134554c122d1583c479ab3010e53d', // post-245 (finding-keyed sparse patches)
diff --git a/scripts/migrations/019-arc-volume-prompts-canon-context.js b/scripts/migrations/019-arc-volume-prompts-canon-context.js
index 0754d46f09..c52e9c698e 100644
--- a/scripts/migrations/019-arc-volume-prompts-canon-context.js
+++ b/scripts/migrations/019-arc-volume-prompts-canon-context.js
@@ -60,8 +60,8 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-overview.md': '648e11352cd1565aee490de1f662bef0', // post-249 protected author intent
- 'pipeline-arc-verify.md': '36aa70cdfc25d7549573a4d556e7702c', // post-019
+ 'pipeline-arc-overview.md': '5ed760caaf3cf88916ec28b220e2f590', // post-250 arc spine checkpoint
+ 'pipeline-arc-verify.md': '83347e7d923580a3062033ab39b3c14b', // post-250 arc spine checkpoint
'pipeline-arc-resolve.md': '8bb134554c122d1583c479ab3010e53d', // post-245 (finding-keyed sparse patches)
'pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940', // post-019
};
diff --git a/scripts/migrations/166-craft-knowledge-prompt-upgrades.js b/scripts/migrations/166-craft-knowledge-prompt-upgrades.js
index f11ae19c81..63c3df8655 100644
--- a/scripts/migrations/166-craft-knowledge-prompt-upgrades.js
+++ b/scripts/migrations/166-craft-knowledge-prompt-upgrades.js
@@ -54,7 +54,7 @@ export const ACCEPTED_OLD_MD5 = {
export const NEW_SHIPPED_MD5 = {
'pipeline-prose.md': '4cb3ef48309f3673570cf80e4d544b54',
'writers-room-continue.md': '458dc5ff4732befc1fb90890bdc885c2', // post-181 (voice exemplars)
- 'pipeline-arc-overview.md': '648e11352cd1565aee490de1f662bef0', // post-249 protected author intent
+ 'pipeline-arc-overview.md': '5ed760caaf3cf88916ec28b220e2f590', // post-250 arc spine checkpoint
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/173-mice-thread-nesting-arc-overview.js b/scripts/migrations/173-mice-thread-nesting-arc-overview.js
index 5709239c79..be17bc9d5b 100644
--- a/scripts/migrations/173-mice-thread-nesting-arc-overview.js
+++ b/scripts/migrations/173-mice-thread-nesting-arc-overview.js
@@ -31,7 +31,7 @@ export const ACCEPTED_OLD_MD5 = {
// Post-change shipped hash (MICE thread-nesting instruction added).
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-overview.md': '648e11352cd1565aee490de1f662bef0', // post-249 protected author intent
+ 'pipeline-arc-overview.md': '5ed760caaf3cf88916ec28b220e2f590', // post-250 arc spine checkpoint
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/249-arc-overview-author-intent.js b/scripts/migrations/249-arc-overview-author-intent.js
index ad3c1e4e8b..e9abd4c600 100644
--- a/scripts/migrations/249-arc-overview-author-intent.js
+++ b/scripts/migrations/249-arc-overview-author-intent.js
@@ -15,7 +15,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-overview.md': '648e11352cd1565aee490de1f662bef0',
+ 'pipeline-arc-overview.md': '5ed760caaf3cf88916ec28b220e2f590',
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/250-arc-spine-checkpoint-prompts.js b/scripts/migrations/250-arc-spine-checkpoint-prompts.js
new file mode 100644
index 0000000000..f31d226109
--- /dev/null
+++ b/scripts/migrations/250-arc-spine-checkpoint-prompts.js
@@ -0,0 +1,30 @@
+/**
+ * Make arc generation honor the recommended volume count and make arc
+ * verification safe to run before episode seeding. The verifier also receives
+ * the protected starter idea explicitly so an internally coherent replacement
+ * premise cannot pass the new pre-episode checkpoint.
+ */
+
+import { makePromptReplaceMigration } from './_lib.js';
+
+export const ACCEPTED_OLD_MD5 = {
+ 'pipeline-arc-overview.md': ['648e11352cd1565aee490de1f662bef0'],
+ 'pipeline-arc-verify.md': ['36aa70cdfc25d7549573a4d556e7702c'],
+};
+
+export const NEW_SHIPPED_MD5 = {
+ 'pipeline-arc-overview.md': '5ed760caaf3cf88916ec28b220e2f590',
+ 'pipeline-arc-verify.md': '83347e7d923580a3062033ab39b3c14b',
+};
+
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'pre-episode arc spine checkpoint',
+ customizedHint: (filename) =>
+ ` To upgrade it manually, diff data.reference/prompts/stages/${filename}\n` +
+ ` against data/prompts/stages/${filename} and add series-scoped canon plus the pre-episode spine contract.`,
+});
+
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/250-arc-spine-checkpoint-prompts.test.js b/scripts/migrations/250-arc-spine-checkpoint-prompts.test.js
new file mode 100644
index 0000000000..98f27db1eb
--- /dev/null
+++ b/scripts/migrations/250-arc-spine-checkpoint-prompts.test.js
@@ -0,0 +1,35 @@
+import { readFileSync } from 'fs';
+import { describe, expect, it } from 'vitest';
+
+import { repoRoot, runPromptMigrationTests } from './_testHelpers.js';
+import migration, {
+ ACCEPTED_OLD_MD5,
+ NEW_SHIPPED_MD5,
+ applyMigration,
+} from './250-arc-spine-checkpoint-prompts.js';
+
+describe('migration 250 — pre-episode arc spine checkpoint prompts', () => {
+ runPromptMigrationTests({
+ migration,
+ applyMigration,
+ ACCEPTED_OLD_MD5,
+ NEW_SHIPPED_MD5,
+ prefix: 'migration-250-arc-spine-',
+ });
+
+ it('renders volume guidance, protected intent, and spine-only rules', () => {
+ const overview = readFileSync(
+ `${repoRoot}/data.reference/prompts/stages/pipeline-arc-overview.md`,
+ 'utf8',
+ );
+ const verify = readFileSync(
+ `${repoRoot}/data.reference/prompts/stages/pipeline-arc-verify.md`,
+ 'utf8',
+ );
+ expect(overview).toContain('{{recommendedStructure}}');
+ expect(overview).toContain('single 12-issue volume');
+ expect(verify).toContain('{{#arcSpineOnly}}');
+ expect(verify).toContain('{{worldStarter}}');
+ expect(verify).toContain('Protected-intent drift');
+ });
+});
diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.js
index fe3dc80efa..9cebe610a8 100644
--- a/scripts/setup-data-drift.test.js
+++ b/scripts/setup-data-drift.test.js
@@ -30,8 +30,8 @@ const EXPECTED_STAGE_OLD = {
'pipeline-comic-script.md': ['133d200d069c2e8173b7c129eea58f53', '1e0af305c27d0c80c4b482d2ebcb4a0d', '40e5fdc1a1e68a7419b7dad936366c1a', '7c05ecde539f04c9fa91e87543057204', 'a4303016c34b65e4b0e641fe71252de3', 'beab031951859ca13579cdb9c4dbe769', 'dea7d497d1cb38e7574f236f4ff8e644', 'e530fc76b89cedaef848ad7ec99c934c', 'e9ee70bf18888492edada6633cd9928a'],
'pipeline-teleplay.md': ['1280ef6b1ad68fa44070ca7478ec2a5f', '2568e14beaa574d43f8018a5def51d04', '376f779f4687b598f1c92ca4e770fd5a', '3f6fecc25573ed054b47db392250034a', 'afa4215330bf856429d70d7e2f856605'],
'pipeline-season-episodes.md': ['6e349ad26bed8a0ccb042571f03f03eb', 'c4928e2a5f833358116b29d2d669888d', '50c68a29c3ebc275db3095d06bd87100'],
- 'pipeline-arc-overview.md': ['6a3ecab43d1f46b7ef9aab6c69ea0326', 'd34d72b8e49ba303d38607845dd87f1c', '0a1f6ffa6908522e3690c5e9e53a6ee0', '612f8b04950e2ff26dd350dd76a062fe', '74d6c26548660d85fc345b2099c63b6c'],
- 'pipeline-arc-verify.md': ['52e31abc93e3105176236fcaa5d1575a', 'ff56d8387162017e08d5d0491060ddd6'],
+ 'pipeline-arc-overview.md': ['6a3ecab43d1f46b7ef9aab6c69ea0326', 'd34d72b8e49ba303d38607845dd87f1c', '0a1f6ffa6908522e3690c5e9e53a6ee0', '612f8b04950e2ff26dd350dd76a062fe', '74d6c26548660d85fc345b2099c63b6c', '648e11352cd1565aee490de1f662bef0'],
+ 'pipeline-arc-verify.md': ['52e31abc93e3105176236fcaa5d1575a', 'ff56d8387162017e08d5d0491060ddd6', '36aa70cdfc25d7549573a4d556e7702c'],
'pipeline-volume-verify.md': ['03f3c874cb80e1c98abcf03168fa7a92', 'c6ea28e972ad6e229bafb2d602b4dda3'],
'pipeline-arc-resolve.md': ['5b340885c6e8f8afc63424d6b5bc7eb7', '87bc5c01f1a8a97b681727a38b05edc6', '8e348f3d1894382889f9f0ee7d5c6792', 'a8677bbe1eb38f871fb152a5b0fec7c6', 'cc27b4da1d1a13c35e35d1c2d6183815'],
'pipeline-script-verify.md': ['ed6c8101644cfe56a100eb6bfe3587f3'],
@@ -60,8 +60,8 @@ const EXPECTED_STAGE_NEW = {
'pipeline-comic-script.md': '49af30c05f008b20f6998a0f113f7d87',
'pipeline-teleplay.md': '2ea9974ac3803658b2314db1f5818b77',
'pipeline-season-episodes.md': 'a88e8e78a949b7aaf500d03314e2ea0b',
- 'pipeline-arc-overview.md': '648e11352cd1565aee490de1f662bef0',
- 'pipeline-arc-verify.md': '36aa70cdfc25d7549573a4d556e7702c',
+ 'pipeline-arc-overview.md': '5ed760caaf3cf88916ec28b220e2f590',
+ 'pipeline-arc-verify.md': '83347e7d923580a3062033ab39b3c14b',
'pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940',
'pipeline-arc-resolve.md': '8bb134554c122d1583c479ab3010e53d',
'pipeline-script-verify.md': '722c62462d05462603cf67ca0ed1dee8',
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index b672f83da1..322d3437f3 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -496,6 +496,11 @@ export function assertVisionRunUsedImages(result, requestedProvider) {
* `text` value — callers receive the full buffered text either way.
* For TUI providers the stripped chunks are emitted; the final `text`
* is the cleaned response with the prompt-echo elided.
+ * @param {(runId:string)=>void} [args.onRunCreated] — called immediately after
+ * each concrete primary/correction/fallback run id is known. Observational;
+ * callback errors are logged and ignored.
+ * @param {(runId:string)=>void} [args.onRunSettled] — called when that concrete
+ * attempt resolves or rejects. Observational; callback errors are ignored.
* @param {string[]} [args.screenshots] — image paths for a vision/multimodal
* call (relative to the runner's screenshots dir, or absolute). API providers
* only: the toolkit's executeApiRun base64-encodes each and sends them as
@@ -1088,7 +1093,20 @@ function stripFallbackContext(err) {
* swapped to a fallback when the requested provider was already marked
* unavailable).
*/
-async function executeProviderRunOnce({ provider, prompt, source, model, effort = null, runId: callerRunId, onData: onDataCallback, timeout: timeoutOverride, cwd: cwdOverride, screenshots = [] }) {
+async function executeProviderRunOnce({
+ provider,
+ prompt,
+ source,
+ model,
+ effort = null,
+ runId: callerRunId,
+ onData: onDataCallback,
+ onRunCreated,
+ onRunSettled,
+ timeout: timeoutOverride,
+ cwd: cwdOverride,
+ screenshots = [],
+}) {
// Resolve the model that'll actually run BEFORE creating the run record
// so the record reflects reality. resolveEffectiveModel handles both
// the override-honored fallback chain AND the args-baked-CLI case
@@ -1147,6 +1165,16 @@ async function executeProviderRunOnce({ provider, prompt, source, model, effort
}
}
+ // Lifecycle hooks let a parent orchestrator expose and stop the concrete
+ // provider run that is active inside a larger workflow. They fire for the
+ // caller-supplied primary run AND for every fresh correction/fallback run.
+ // Hook failures are observational only and must not break provider work.
+ if (typeof onRunCreated === 'function') {
+ try { onRunCreated(runId); } catch (err) {
+ console.error(`❌ run lifecycle start hook failed: ${err.message}`);
+ }
+ }
+
// Compute timeout AFTER the possible fallback switch so it reflects
// the provider that actually runs — providers can have wildly different
// `timeout` settings (a 5-min CLI vs a 30-s API), and using the
@@ -1278,5 +1306,10 @@ async function executeProviderRunOnce({ provider, prompt, source, model, effort
} else {
safeReject(new Error(`Unsupported provider type: ${effectiveProvider.type}`));
}
- }));
+ })).finally(() => {
+ if (typeof onRunSettled !== 'function') return;
+ try { onRunSettled(runId); } catch (err) {
+ console.error(`❌ run lifecycle settle hook failed: ${err.message}`);
+ }
+ });
}
diff --git a/server/lib/promptRunner.test.js b/server/lib/promptRunner.test.js
index 0cd6997a77..f87a10d3a6 100644
--- a/server/lib/promptRunner.test.js
+++ b/server/lib/promptRunner.test.js
@@ -130,6 +130,24 @@ describe('promptRunner — happy paths', () => {
expect(runner.executeCliRun).not.toHaveBeenCalled();
});
+ it('reports the concrete run lifecycle so a parent workflow can stop it', async () => {
+ const events = [];
+ runner.executeApiRun.mockImplementation(async ({ runId, onComplete }) => {
+ events.push(`execute:${runId}`);
+ onComplete({ success: true });
+ });
+
+ await runPromptThroughProvider({
+ provider: apiProvider(),
+ prompt: 'p',
+ source: 'test',
+ onRunCreated: (runId) => events.push(`created:${runId}`),
+ onRunSettled: (runId) => events.push(`settled:${runId}`),
+ });
+
+ expect(events).toEqual(['created:run-xyz', 'execute:run-xyz', 'settled:run-xyz']);
+ });
+
it('forwards screenshots to executeApiRun for a vision/multimodal call', async () => {
runner.executeApiRun.mockImplementation(async ({ onComplete }) => onComplete({ success: true }));
diff --git a/server/lib/stageRunner.js b/server/lib/stageRunner.js
index d9c5faf07e..bcad29fd09 100644
--- a/server/lib/stageRunner.js
+++ b/server/lib/stageRunner.js
@@ -575,6 +575,8 @@ async function executeStagePrompt({ stage, label, prompt, options }) {
// provider's ladder and omits the flag entirely for a provider with no
// effort control, so no capability check is needed here.
effort: resolveEffortHint(stage, options),
+ onRunCreated: options.onRunCreated,
+ onRunSettled: options.onRunSettled,
});
const { text } = runResult2;
let finalRunId = runId;
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index 1c3268414e..63e79eec1e 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -193,7 +193,10 @@ describe('arcPlanner — generateArcOverview', () => {
{ kind: 'reference_sheet', label: 'Rival agencies branding', prompt: 'comparison sheet' },
],
});
- const s = await setupSeries({ universeId: world.id });
+ const s = await setupSeries({
+ universeId: world.id,
+ premise: 'Mira Holt must recover The Tongue before the foundry city goes silent.',
+ });
stageRunnerSpy = vi.fn(async () => ({
content: {
@@ -220,6 +223,44 @@ describe('arcPlanner — generateArcOverview', () => {
expect(ctx.worldInfluencesAvoid).toContain('gritty');
});
+ it('excludes abandoned-draft canon that the protected premise and active cast never reference', async () => {
+ const world = await worldSvc.createUniverse({
+ name: 'Example World',
+ starterPrompt: 'Asha Reed follows a signal through the Glass Harbor.',
+ characters: [
+ { id: 'char-active', name: 'Asha Reed', role: 'lead', relationships: 'Trusts Fen.' },
+ { id: 'char-support', name: 'Fen', role: 'scout' },
+ { id: 'char-stale', name: 'Director Voss', role: 'antagonist' },
+ ],
+ places: [
+ { id: 'place-active', name: 'Glass Harbor', description: 'a flooded observatory' },
+ { id: 'place-stale', name: 'Central Ministry', description: 'an old-draft headquarters' },
+ ],
+ objects: [
+ { id: 'obj-stale', name: 'Compliance Seal', description: 'an old-draft badge' },
+ ],
+ });
+ const s = await setupSeries({
+ universeId: world.id,
+ premise: 'Asha Reed and Fen trace the Glass Harbor signal.',
+ characterArcs: [{ characterId: 'char-active', characterName: 'Asha Reed', startState: 'alone', endState: 'trusting' }],
+ });
+ stageRunnerSpy = vi.fn(async () => ({
+ content: { logline: 'L', summary: 'S', themes: [], protagonistArc: 'A', seasonOutlines: [] },
+ runId: 'r1', providerId: 'p', model: 'm',
+ }));
+
+ await planner.generateArcOverview(s.id);
+
+ const ctx = stageRunnerSpy.mock.calls[0][1];
+ expect(ctx.worldCanonText).toContain('Asha Reed');
+ expect(ctx.worldCanonText).toContain('Fen');
+ expect(ctx.worldCanonText).toContain('Glass Harbor');
+ expect(ctx.worldCanonText).not.toContain('Director Voss');
+ expect(ctx.worldCanonText).not.toContain('Central Ministry');
+ expect(ctx.worldCanonText).not.toContain('Compliance Seal');
+ });
+
it('renders an "(no linked world)" placeholder when the series has no universeId', async () => {
const s = await setupSeries({ universeId: null });
stageRunnerSpy = vi.fn(async () => ({
@@ -425,6 +466,41 @@ describe('arcPlanner — commitEpisodesToIssues', () => {
expect(created).toHaveLength(1);
expect(callCount).toBe(0);
});
+
+ it('reuses an exact set of empty ungrouped placeholders when Autopilot requests it', async () => {
+ const s = await setupSeries();
+ const first = await issuesSvc.createIssue({ seriesId: s.id, title: 'Placeholder A' });
+ const second = await issuesSvc.createIssue({
+ seriesId: s.id,
+ title: 'Placeholder B',
+ stages: { comicPages: { status: 'ready', pages: [{ pageNumber: 1, panels: [] }] } },
+ });
+ const episodes = [
+ { number: 1, title: 'Opening', arcRole: 'pilot', logline: 'L1', synopsis: 'S1', lengthProfile: 'standard' },
+ { number: 2, title: 'Turn', arcRole: 'complication', logline: 'L2', synopsis: 'S2', lengthProfile: 'short' },
+ ];
+
+ const reused = await planner.commitEpisodesToIssues(s.id, 'sea-example', episodes, { reuseUngrouped: true });
+
+ expect(reused.map((issue) => issue.id)).toEqual([first.id, second.id]);
+ expect(reused.map((issue) => issue.title)).toEqual(['Opening', 'Turn']);
+ expect(reused.every((issue) => issue.seasonId === 'sea-example')).toBe(true);
+ expect(reused[1].stages.comicPages.pages).toHaveLength(1);
+ expect(await issuesSvc.listIssues({ seriesId: s.id })).toHaveLength(2);
+ });
+
+ it('refuses to duplicate or partially reuse placeholders when their count differs from the episode plan', async () => {
+ const s = await setupSeries();
+ const placeholder = await issuesSvc.createIssue({ seriesId: s.id, title: 'Placeholder' });
+ const episodes = [
+ { number: 1, title: 'One', logline: 'L1', synopsis: 'S1' },
+ { number: 2, title: 'Two', logline: 'L2', synopsis: 'S2' },
+ ];
+
+ await expect(planner.commitEpisodesToIssues(s.id, null, episodes, { reuseUngrouped: true }))
+ .rejects.toMatchObject({ code: planner.ERR_VALIDATION });
+ expect((await issuesSvc.listIssues({ seriesId: s.id })).map((issue) => issue.id)).toEqual([placeholder.id]);
+ });
});
describe('arcPlanner — verifyArc', () => {
diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.js
index dede1e98b8..43a497e986 100644
--- a/server/services/pipeline/arcPlanner/arcCore.js
+++ b/server/services/pipeline/arcPlanner/arcCore.js
@@ -36,6 +36,8 @@ export async function generateArcOverview(seriesId, options = {}) {
modelOverride: options.modelOverride,
modelDefault: options.modelDefault,
effortDefault: options.effortDefault,
+ onRunCreated: options.onRunCreated,
+ onRunSettled: options.onRunSettled,
returnsJson: true,
source: 'pipeline-arc-overview',
},
@@ -105,6 +107,8 @@ export async function generateReaderMap(seriesId, options = {}) {
modelOverride: options.modelOverride,
modelDefault: options.modelDefault,
effortDefault: options.effortDefault,
+ onRunCreated: options.onRunCreated,
+ onRunSettled: options.onRunSettled,
returnsJson: true,
source: 'story-builder-reader-map',
},
@@ -254,7 +258,7 @@ export async function verifyArc(seriesId, options = {}) {
{ status: 400, code: 'PIPELINE_NO_ARC' },
);
}
- const ctx = await buildVerifyContext(series, options.preloadedWorld);
+ const ctx = await buildVerifyContext(series, options.preloadedWorld, { spineOnly: options.spineOnly === true });
const { content, runId, providerId, model } = await runStagedLLM(
'pipeline-arc-verify',
ctx,
@@ -264,6 +268,8 @@ export async function verifyArc(seriesId, options = {}) {
modelOverride: options.modelOverride,
modelDefault: options.modelDefault,
effortDefault: options.effortDefault,
+ onRunCreated: options.onRunCreated,
+ onRunSettled: options.onRunSettled,
returnsJson: true,
source: 'pipeline-arc-verify',
},
@@ -339,6 +345,8 @@ export async function verifyVolume(seriesId, seasonId, options = {}) {
modelOverride: options.modelOverride,
modelDefault: options.modelDefault,
effortDefault: options.effortDefault,
+ onRunCreated: options.onRunCreated,
+ onRunSettled: options.onRunSettled,
returnsJson: true,
source: 'pipeline-volume-verify',
},
@@ -435,6 +443,8 @@ export async function resolveVerifyIssues(seriesId, options = {}) {
modelOverride: options.modelOverride,
modelDefault: options.modelDefault,
effortDefault: options.effortDefault,
+ onRunCreated: options.onRunCreated,
+ onRunSettled: options.onRunSettled,
returnsJson: true,
source: 'pipeline-arc-resolve',
},
diff --git a/server/services/pipeline/arcPlanner/context.js b/server/services/pipeline/arcPlanner/context.js
index 163541a492..c909b42621 100644
--- a/server/services/pipeline/arcPlanner/context.js
+++ b/server/services/pipeline/arcPlanner/context.js
@@ -15,7 +15,7 @@ import { renderCharacterArcsForPrompt } from '../../../lib/seriesCharacterArc.js
import { describeStructure, recommendStructure } from '../../../lib/seasonStructure.js';
import { DEFAULT_LENGTH_PROFILE, LENGTH_PROFILE_NAMES } from '../../../lib/issueLength.js';
import { getUniverse } from '../../universeBuilder.js';
-import { getSeriesCanon } from '../seriesCanon.js';
+import { getSeriesPlanningCanon, scopeCanonForSeries } from '../seriesCanon.js';
import { renderCanonForPrompt, renderCategoriesForPrompt, renderCompositesForPrompt, renderEntitiesSummary } from '../../../lib/universePromptRenderers.js';
export const ERR_VALIDATION = 'PIPELINE_ARC_VALIDATION';
@@ -109,10 +109,12 @@ export function appendCharacterFirstArcGuidance(shapeGuidance, characterFoundati
// The world is the canonical source for factions, characters, environments,
// etc. — without this, the arc planner would only see the series' own
// characters/places/objects which are usually empty pre-prose.
-export async function loadWorldContext(universeId) {
- if (!universeId) return null;
- const world = await getUniverse(universeId).catch(() => null);
+export async function loadWorldContext(series) {
+ if (!series?.universeId) return null;
+ const world = await getUniverse(series.universeId).catch(() => null);
if (!world) return null;
+ const planningCanon = scopeCanonForSeries(world, series);
+ const scopedWorld = { ...world, ...planningCanon };
const embrace = Array.isArray(world.influences?.embrace) ? world.influences.embrace : [];
const avoid = Array.isArray(world.influences?.avoid) ? world.influences.avoid : [];
@@ -135,13 +137,13 @@ export async function loadWorldContext(universeId) {
// Universe canon — named characters/places/objects the arc references by
// name. Separate from categories because the LLM should treat these as
// first-class entities, not exploratory variations.
- worldCanonText: renderCanonForPrompt(world) || '(none)',
- worldCharacterFoundationText: renderCharacterFoundationForArc(world.characters),
+ worldCanonText: renderCanonForPrompt(scopedWorld) || '(none — no named entities are tied to this series yet)',
+ worldCharacterFoundationText: renderCharacterFoundationForArc(planningCanon.characters),
// Compact one-line-per-kind synopsis of canon — intended for text stages
// (prose/teleplay/comic-script) where the full canon dump would dominate
// the prompt. Arc-level prompts also receive it so a template author can
// pick whichever level of detail fits the section being grounded.
- worldEntitiesSummary: renderEntitiesSummary(world) || '(none)',
+ worldEntitiesSummary: renderEntitiesSummary(scopedWorld) || '(none — no named entities are tied to this series yet)',
};
}
@@ -169,7 +171,7 @@ export const EMPTY_WORLD_CONTEXT = {
// that chain (verify → resolve) don't reload the same world twice.
export async function resolveWorldContext(series, preloaded) {
if (preloaded) return preloaded;
- return (await loadWorldContext(series.universeId)) || EMPTY_WORLD_CONTEXT;
+ return (await loadWorldContext(series)) || EMPTY_WORLD_CONTEXT;
}
// Canonical issue sort: arcPosition first (issues seeded by the season-
@@ -371,7 +373,7 @@ export async function buildArcOverviewContext(series, preloadedWorld) {
const structure = recommendStructure(series.issueCountTarget);
const [world, canon] = await Promise.all([
resolveWorldContext(series, preloadedWorld),
- getSeriesCanon(series),
+ getSeriesPlanningCanon(series),
]);
const arc = series.arc || {};
// Two-mode prompt: when arc.shape is set the prompt's `{{#pickedShapeId}}`
@@ -504,14 +506,14 @@ export function groupIssuesBySeasonTree(seasons, issues, { renderLeaf, seasonFie
return tree;
}
-export async function buildVerifyContext(series, preloadedWorld) {
+export async function buildVerifyContext(series, preloadedWorld, { spineOnly = false } = {}) {
const seasons = sanitizeSeasonList(series.seasons || []);
const [issues, base, canon] = await Promise.all([
listIssues({ seriesId: series.id }),
buildArcBaseContext(series, preloadedWorld),
- getSeriesCanon(series),
+ getSeriesPlanningCanon(series),
]);
- const tree = groupIssuesBySeasonTree(seasons, issues, {
+ const tree = groupIssuesBySeasonTree(seasons, spineOnly ? [] : issues, {
// `synopsis` key (not `beats`) so it matches the prompt's existing
// language; sourced from idea.input which carries the LLM's logline+synopsis.
renderLeaf: (iss) => ({
@@ -534,6 +536,7 @@ export async function buildVerifyContext(series, preloadedWorld) {
});
return {
...base,
+ arcSpineOnly: spineOnly,
seasonsTreeJson: JSON.stringify(tree, null, 2),
existingCharactersJson: JSON.stringify(canon.characters, null, 2),
existingPlacesJson: JSON.stringify(canon.places, null, 2),
@@ -738,7 +741,7 @@ async function buildBeatTree(series, preloadedWorld) {
const [issues, base, canon] = await Promise.all([
listIssues({ seriesId: series.id }),
buildArcBaseContext(series, preloadedWorld),
- getSeriesCanon(series),
+ getSeriesPlanningCanon(series),
]);
const tree = groupIssuesBySeasonTree(seasons, issues, {
renderLeaf: renderVolumeIssue,
diff --git a/server/services/pipeline/arcPlanner/episodeSeedPass.js b/server/services/pipeline/arcPlanner/episodeSeedPass.js
index 115d149d55..70e97e5cac 100644
--- a/server/services/pipeline/arcPlanner/episodeSeedPass.js
+++ b/server/services/pipeline/arcPlanner/episodeSeedPass.js
@@ -5,12 +5,12 @@
import { runStagedLLM } from '../../../lib/stageRunner.js';
import { getSeries } from '../series.js';
-import { createIssue, listIssues } from '../issues.js';
+import { createIssue, listIssues, updateIssue, TEXT_STAGE_IDS } from '../issues.js';
import { renderArcShapeGuidance, renderArcShapePositionSummary } from '../../../lib/storyArc.js';
import { composeStyleNotes } from '../../../lib/styleGuide.js';
import { extractCanonFromProse } from '../../universeCanon.js';
import { resolveSeriesLlmOverride } from '../../../lib/seriesLlmOverride.js';
-import { getSeriesCanon } from '../seriesCanon.js';
+import { getSeriesPlanningCanon } from '../seriesCanon.js';
import { ARC_ROLES, ERR_VALIDATION, SEASON_LENGTH_PRESETS, SHAPE_GUIDANCE_NONE, appendCharacterFirstArcGuidance, appendTickingClock, lengthProfileForArcRole, makeErr, renderPriorSeason, resolveWorldContext } from './context.js';
/**
@@ -26,7 +26,7 @@ export async function buildSeasonEpisodesContext(series, season, priorSeasons, p
: priorSeasons.map((s) => renderPriorSeason(s, priorIssues)).join('\n\n');
const [world, canon] = await Promise.all([
resolveWorldContext(series, preloadedWorld),
- getSeriesCanon(series),
+ getSeriesPlanningCanon(series),
]);
const totalSeasons = (series.seasons || []).length || 1;
const arcGuidance = appendCharacterFirstArcGuidance(
@@ -166,6 +166,8 @@ export async function generateSeasonEpisodes(seriesId, seasonId, options = {}) {
modelOverride: options.modelOverride,
modelDefault: options.modelDefault,
effortDefault: options.effortDefault,
+ onRunCreated: options.onRunCreated,
+ onRunSettled: options.onRunSettled,
returnsJson: true,
source: 'pipeline-season-episodes',
},
@@ -189,15 +191,37 @@ export async function generateSeasonEpisodes(seriesId, seasonId, options = {}) {
* Builder's "generate issues from arc" action so both mint byte-identical
* issue shapes. The episode's logline + synopsis land in `stages.idea.input`.
*/
-export async function commitEpisodesToIssues(seriesId, seasonId, episodes = [], { preloadedSeries = null } = {}) {
+const hasNarrativeWork = (issue) => TEXT_STAGE_IDS.some((stageId) => {
+ const stage = issue?.stages?.[stageId];
+ return Boolean(stage?.input?.trim() || stage?.output?.trim() || stage?.lastRunId || (stage?.runHistory || []).length);
+});
+
+export async function commitEpisodesToIssues(seriesId, seasonId, episodes = [], {
+ preloadedSeries = null,
+ reuseUngrouped = false,
+} = {}) {
// Fetch the series once for the whole batch (unless the caller already holds
// it) and thread it into each createIssue's renumber pass. The series record
// doesn't change as issues are appended, so an N-episode season otherwise
// pays N redundant getSeries reads of an unchanging record.
const series = preloadedSeries || await getSeries(seriesId).catch(() => null);
+ const ungrouped = reuseUngrouped
+ ? (await listIssues({ seriesId })).filter((issue) => !issue.seasonId)
+ : [];
+ const reusable = ungrouped
+ .filter((issue) => !hasNarrativeWork(issue))
+ .sort((a, b) => (a.number || 0) - (b.number || 0));
+ const canReuse = reusable.length === episodes.length && episodes.length > 0;
+ if (reuseUngrouped && episodes.length > 0 && ungrouped.length > 0 && !canReuse) {
+ throw makeErr(
+ `Cannot safely seed ${episodes.length} generated episode(s): the series has ${ungrouped.length} ungrouped issue record(s), and ${reusable.length} are empty narrative placeholders. Reconcile that set before resuming so Autopilot does not duplicate or overwrite issue work.`,
+ ERR_VALIDATION,
+ );
+ }
const created = [];
- for (const ep of episodes) {
- const issue = await createIssue({
+ for (let index = 0; index < episodes.length; index += 1) {
+ const ep = episodes[index];
+ const patch = {
seriesId,
title: ep.title,
// Issue `number` is derived from (volume order, arcPosition) by
@@ -218,7 +242,13 @@ export async function commitEpisodesToIssues(seriesId, seasonId, episodes = [],
input: [ep.logline, ep.synopsis].filter(Boolean).join('\n\n'),
},
},
- }, { preloadedSeries: series });
+ };
+ // Autopilot commonly starts from user-created issue placeholders. Reuse an
+ // exact empty ungrouped set so issue ids, history, and visual/catalog links
+ // survive; manual preview/confirm callers retain create-only semantics.
+ const issue = canReuse
+ ? await updateIssue(reusable[index].id, patch)
+ : await createIssue(patch, { preloadedSeries: series });
created.push(issue);
}
return created;
diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.js
index aca6dc5d05..98acda5c3d 100644
--- a/server/services/pipeline/foundationJudge.js
+++ b/server/services/pipeline/foundationJudge.js
@@ -679,6 +679,8 @@ export async function judgeFoundation(seriesId, {
providerDefault,
modelDefault,
effortDefault,
+ onRunCreated,
+ onRunSettled,
force = false,
} = {}) {
assertValidSeriesId(seriesId);
@@ -732,6 +734,8 @@ export async function judgeFoundation(seriesId, {
providerOverride: judgeProvider.id,
modelOverride: judgeModel,
effortDefault: effort || effortDefault,
+ onRunCreated,
+ onRunSettled,
source: STAGE,
});
@@ -1106,6 +1110,8 @@ async function runFoundationRepair(series, issues, dimension, finding, character
providerDefault: options.providerId,
modelDefault: options.model,
effortDefault: options.effort,
+ onRunCreated: options.onRunCreated,
+ onRunSettled: options.onRunSettled,
source: stage,
...(stage === CHARACTER_FOUNDATION_STAGE ? { timeoutOverride: CHARACTER_FOUNDATION_TIMEOUT_MS } : {}),
});
@@ -1298,6 +1304,8 @@ export async function establishCharacterFoundation(seriesId, {
providerDefault,
modelDefault,
effortDefault,
+ onRunCreated,
+ onRunSettled,
} = {}) {
assertValidSeriesId(seriesId);
const series = await getSeries(seriesId);
@@ -1328,6 +1336,8 @@ export async function establishCharacterFoundation(seriesId, {
providerId: providerDefault,
model: modelDefault,
effort: effortDefault,
+ onRunCreated,
+ onRunSettled,
phase: 'pre-arc character foundation',
});
return { ...result, ran: true };
@@ -1374,7 +1384,7 @@ async function repairCraft(series, issues, finding, options) {
// no-clobber) — then persist through updateUniverse (serialized write queue).
// Mirrors storyBuilder.js's `universeAesthetic` step. Returns false when there's
// no universe to refine.
-async function refineWorld(universeId, { providerId, model, effort, finding = {} }) {
+async function refineWorld(universeId, { providerId, model, effort, onRunCreated, onRunSettled, finding = {} }) {
if (!universeId) return { applied: false, reason: 'no linked universe' };
const universe = await getUniverse(universeId).catch(() => null);
if (!universe) return { applied: false, reason: 'universe not found' };
@@ -1389,6 +1399,8 @@ async function refineWorld(universeId, { providerId, model, effort, finding = {}
providerId,
model,
effort,
+ onRunCreated,
+ onRunSettled,
narrativeOnly: true,
});
// Persist through the write-queue mutator against the FRESHEST record, and
@@ -1449,12 +1461,27 @@ async function refineWorld(universeId, { providerId, model, effort, finding = {}
* `finding` is the judge's `{ gap, fix }` for the targeted dimension, threaded
* into the structure resolve as a synthesized arc finding.
*/
-export async function applyFoundationFix(seriesId, dimension, { finding = {}, providerOverride, modelOverride, effortOverride, preserveDroppedSeasons = false } = {}) {
+export async function applyFoundationFix(seriesId, dimension, {
+ finding = {},
+ providerOverride,
+ modelOverride,
+ effortOverride,
+ preserveDroppedSeasons = false,
+ onRunCreated,
+ onRunSettled,
+} = {}) {
assertValidSeriesId(seriesId);
const series = await getSeries(seriesId);
const issues = await listIssues({ seriesId });
const universeId = series?.universeId || null;
- const provider = { providerId: providerOverride, model: modelOverride, effort: effortOverride, finding };
+ const provider = {
+ providerId: providerOverride,
+ model: modelOverride,
+ effort: effortOverride,
+ finding,
+ onRunCreated,
+ onRunSettled,
+ };
if (dimension === 'worldbuilding') {
const r = await refineWorld(universeId, provider);
@@ -1500,6 +1527,8 @@ export async function applyFoundationFix(seriesId, dimension, { finding = {}, pr
// Carry the same non-deletion guarantee the other two do.
preserveDroppedSeasons,
effortDefault: effortOverride,
+ onRunCreated,
+ onRunSettled,
});
return { dimension, applied: r?.applied !== false };
}
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index 3bf110ee67..728a915432 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -620,17 +620,17 @@ describe('resolveNextStep (pure)', () => {
});
it('asks to generate episodes for a season with no issues', () => {
- const step = resolveNextStep(comic, []);
+ const step = resolveNextStep(comic, [], { arcSpineVerified: true });
expect(step).toMatchObject({ kind: 'generateEpisodes', seasonId: 'se1' });
});
- it('establishes the foundation before arc verification or drafting', () => {
+ it('checks the arc spine before foundation evaluation or drafting', () => {
const step = resolveNextStep(comic, [issue()]);
- expect(step.kind).toBe('foundationGate');
+ expect(step.kind).toBe('verifyArcSpine');
});
it('runs arc verification after the foundation gate, before beats (#2176)', () => {
- const step = resolveNextStep(comic, [issue()], { foundationGated: true });
+ const step = resolveNextStep(comic, [issue()], { arcSpineVerified: true, foundationGated: true });
expect(step.kind).toBe('verifyArc');
});
@@ -1067,7 +1067,7 @@ describe('dry-run plan ↔ resolveNextStep drift guard (#1577)', () => {
const freshRunState = () => ({
locksUnlocked: false,
- characterFoundationEstablished: false, arcAttempted: false, arcVerified: false, foundationGated: false, beatContinuityChecked: false,
+ characterFoundationEstablished: false, arcAttempted: false, arcSpineVerified: false, arcVerified: false, foundationGated: false, beatContinuityChecked: false,
editorialReviewed: false, reverseOutlineRefreshed: false,
editorialChecksReviewed: false, editorialHealthReady: false, canonVerified: false,
episodesAttempted: new Set(), beatsAttempted: new Set(), textAttempted: new Set(),
@@ -1098,6 +1098,9 @@ describe('dry-run plan ↔ resolveNextStep drift guard (#1577)', () => {
case 'verifyArc':
runState.arcVerified = true;
break;
+ case 'verifyArcSpine':
+ runState.arcSpineVerified = true;
+ break;
case 'foundationGate':
runState.foundationGated = true;
break;
@@ -1566,7 +1569,7 @@ describe('autopilot conductor', () => {
await waitFor(runFinished(seriesId));
const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
expect(last?.type).toBe('paused');
- expect(last?.scope).toBe('verifyArc');
+ expect(last?.scope).toBe('verifyArcSpine');
// bounded: verifyArc called exactly maxRounds times, resolve called rounds-1.
expect(arcSpies.verifyArc).toHaveBeenCalledTimes(2);
expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(1);
@@ -1603,7 +1606,7 @@ describe('autopilot conductor', () => {
expect(applyFoundationFix).not.toHaveBeenCalled();
});
- it('re-judges the foundation after arc verification repairs the synopsis plan', async () => {
+ it('repairs the arc spine before the foundation judge sees the synopsis plan', async () => {
arcSpies.verifyArc
.mockImplementationOnce(async () => ({ issues: [{ severity: 'high', problem: 'missing setup', location: 'V1' }] }))
.mockImplementationOnce(async () => ({ issues: [] }));
@@ -1612,7 +1615,7 @@ describe('autopilot conductor', () => {
await waitFor(runFinished(seriesId));
expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('complete');
expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(1);
- expect(judgeFoundation).toHaveBeenCalledTimes(2);
+ expect(judgeFoundation).toHaveBeenCalledTimes(1);
});
it('foundation gate: iterates on the weakest dimension then pauses (maxRounds) when it never clears', async () => {
@@ -1773,7 +1776,7 @@ describe('autopilot conductor', () => {
await waitFor(runFinished(seriesId));
const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
expect(last?.type).toBe('paused');
- expect(last?.scope).toBe('verifyArc');
+ expect(last?.scope).toBe('verifyArcSpine');
});
it('arc gate: a per-series arc:[high] override lets a medium finding pass', async () => {
@@ -1913,7 +1916,7 @@ describe('autopilot conductor', () => {
await waitFor(runFinished(seriesId));
const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
expect(last?.type).toBe('paused');
- expect(last?.scope).toBe('verifyArc');
+ expect(last?.scope).toBe('verifyArcSpine');
expect(last?.pauseKind).toBe('divergence');
expect(last?.reason).toMatch(/stopped converging/);
// Bailed at round 3 — NOT all 6 rounds (the whole point: budget saved).
@@ -1955,7 +1958,7 @@ describe('autopilot conductor', () => {
const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
expect(last?.type).toBe('paused');
- expect(last?.scope).toBe('verifyArc');
+ expect(last?.scope).toBe('verifyArcSpine');
expect(last?.pauseKind).toBe('regression');
expect(last?.reason).toMatch(/reverted/);
// Residual is what the user had BEFORE the round, not the 3 it manufactured.
@@ -2193,6 +2196,29 @@ describe('autopilot conductor', () => {
expect(arcSpies.generateSeasonEpisodes).toHaveBeenCalledTimes(1); // not looping
});
+ it('pauses without duplicating work when issue placeholders cannot be safely reused', async () => {
+ const series = await seriesSvc.createSeries({ name: 'S', logline: 'L', premise: 'P', targetFormat: 'comic' });
+ await seriesSvc.updateSeries(series.id, { arc: { logline: 'A', summary: 'S' } });
+ await seasonsSvc.createSeason(series.id, { number: 1, title: 'V1' });
+ arcSpies.generateSeasonEpisodes.mockResolvedValueOnce({ episodes: [{ number: 1, title: 'I1' }] });
+ const error = Object.assign(new Error('Reconcile the existing issue placeholder set before resuming.'), {
+ code: 'PIPELINE_ARC_VALIDATION',
+ });
+ arcSpies.commitEpisodesToIssues.mockRejectedValueOnce(error);
+
+ await autopilot.startSeriesAutopilot(series.id, { includeVisual: false });
+ await waitFor(runFinished(series.id));
+
+ const last = autopilot.__testing.runs.get(series.id)?.lastPayload;
+ expect(last).toMatchObject({
+ type: 'paused',
+ scope: 'generateEpisodes',
+ pauseKind: 'inapplicable',
+ reason: 'Reconcile the existing issue placeholder set before resuming.',
+ });
+ expect(arcSpies.commitEpisodesToIssues).toHaveBeenCalledTimes(1);
+ });
+
it('pauses (no infinite loop) when arc generation yields no volumes', async () => {
const series = await seriesSvc.createSeries({ name: 'S', logline: 'L', premise: 'P', targetFormat: 'comic' });
await seriesSvc.updateSeries(series.id, { arc: { logline: 'A', summary: 'S' } }); // arc but no seasons
@@ -2740,7 +2766,7 @@ describe('autopilot conductor', () => {
await autopilot.startSeriesAutopilot(seriesId, { fileGaps: true, maxArcVerifyRounds: 1 });
await waitFor(runFinished(seriesId));
expect(addTask).toHaveBeenCalled();
- expect(addTask.mock.calls[0][0].description).toMatch(/verifyArc-stalled/);
+ expect(addTask.mock.calls[0][0].description).toMatch(/verifyArcSpine-stalled/);
});
// `metadata.app` is workspace routing, not a feature tag: it must name a
diff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.js
index 58719ae337..8372f4ea7e 100644
--- a/server/services/pipeline/seriesAutopilot/childRuns.js
+++ b/server/services/pipeline/seriesAutopilot/childRuns.js
@@ -46,13 +46,13 @@ async function waitForChild(isActive, record) {
}
}
-export async function runArcVerify(seriesId, record) {
+export async function runArcVerify(seriesId, record, { spineOnly = false } = {}) {
const maxRounds = Number.isInteger(record.options.maxArcVerifyRounds)
? record.options.maxArcVerifyRounds
: MAX_ARC_VERIFY_ROUNDS;
// maxRounds === 0 means "skip verification entirely" — accept the arc as-is.
if (maxRounds === 0) {
- record.runState.arcVerified = true;
+ record.runState[spineOnly ? 'arcSpineVerified' : 'arcVerified'] = true;
return {};
}
let convergence = { best: null, sinceBest: 0 };
@@ -65,11 +65,14 @@ export async function runArcVerify(seriesId, record) {
if (record.cancelRequested) return { canceled: true };
const beforeVerify = await budgetPause();
if (beforeVerify) return beforeVerify;
- const { issues: arcFindings } = await verifyArc(seriesId, providerOverrideOpts(record, 'judge'));
+ const { issues: arcFindings } = await verifyArc(seriesId, {
+ ...providerOverrideOpts(record, 'judge'),
+ spineOnly,
+ });
await recordDomainUsage('cos', { actions: 1 });
const series = await getSeries(seriesId);
const volumeFindings = [];
- for (const season of series.seasons || []) {
+ for (const season of spineOnly ? [] : (series.seasons || [])) {
if (record.cancelRequested) return { canceled: true };
const beforeVolumeVerify = await budgetPause();
if (beforeVolumeVerify) return beforeVolumeVerify;
@@ -91,12 +94,12 @@ export async function runArcVerify(seriesId, record) {
const findings = [...arcFindings, ...volumeFindings];
const blocking = findings.filter((finding) => record.options.blockingSets.arc.has(finding.severity));
broadcast(seriesId, {
- type: 'verify:round', scope: 'arc', round, findings: findings.length,
- blocking: blocking.length, volumesChecked: (series.seasons || []).length,
+ type: 'verify:round', scope: spineOnly ? 'arcSpine' : 'arc', round, findings: findings.length,
+ blocking: blocking.length, volumesChecked: spineOnly ? 0 : (series.seasons || []).length,
});
if (blocking.length === 0) {
- record.runState.arcVerified = true;
- if (changed && !finishPlanningMutation(record, 'foundationGated')) {
+ record.runState[spineOnly ? 'arcSpineVerified' : 'arcVerified'] = true;
+ if (!spineOnly && changed && !finishPlanningMutation(record, 'foundationGated')) {
return {
pause: true,
pauseKind: 'planningOscillation',
@@ -311,6 +314,8 @@ export async function runFoundationGate(seriesId, record) {
providerDefault: judgeLlm.providerOverride,
modelDefault: judgeLlm.modelOverride,
effortDefault: judgeLlm.effortOverride,
+ onRunCreated: providerOverrideOpts(record, 'judge').onRunCreated,
+ onRunSettled: providerOverrideOpts(record, 'judge').onRunSettled,
});
// A cached (content-hash unchanged) verdict did no LLM work — don't bill it.
if (!snap.cached) await recordDomainUsage('cos', { actions: 1 });
@@ -388,6 +393,8 @@ export async function runFoundationGate(seriesId, record) {
modelOverride: creativeLlm.modelOverride,
...seasonPreserveOpts(record),
effortOverride: creativeLlm.effortOverride,
+ onRunCreated: providerOverrideOpts(record).onRunCreated,
+ onRunSettled: providerOverrideOpts(record).onRunSettled,
});
} catch (err) {
const detail = (err?.message || String(err)).slice(0, 300);
diff --git a/server/services/pipeline/seriesAutopilot/dispatch.js b/server/services/pipeline/seriesAutopilot/dispatch.js
index e136e0e115..7e9296e13b 100644
--- a/server/services/pipeline/seriesAutopilot/dispatch.js
+++ b/server/services/pipeline/seriesAutopilot/dispatch.js
@@ -7,7 +7,7 @@ import { recordDomainUsage } from '../../domainUsage.js';
import { getSeries } from '../series.js';
import {
generateArcOverview, commitSeasonsWithRemap, generateSeasonEpisodes, commitEpisodesToIssues,
- hasDuplicateSeasonNumbers,
+ ERR_VALIDATION, hasDuplicateSeasonNumbers,
} from '../arcPlanner.js';
import { providerOverrideOpts, seasonPreserveOpts } from './session.js';
import { runArcVerify, runBeats, runBeatContinuity, runCharacterFoundation, runFoundationGate, runText } from './childRuns.js';
@@ -83,7 +83,20 @@ export async function dispatchStep(sId, step, record) {
record.runState.episodesAttempted.add(step.seasonId);
const r = await generateSeasonEpisodes(sId, step.seasonId, providerOverrideOpts(record));
const cur = await getSeries(sId);
- const created = await commitEpisodesToIssues(sId, step.seasonId, r.episodes, { preloadedSeries: cur });
+ const commitResult = await commitEpisodesToIssues(sId, step.seasonId, r.episodes, {
+ preloadedSeries: cur,
+ reuseUngrouped: true,
+ }).then((created) => ({ created, error: null })).catch((error) => ({ created: null, error }));
+ if (commitResult.error) {
+ if (commitResult.error.code !== ERR_VALIDATION) throw commitResult.error;
+ return {
+ pause: true,
+ pauseKind: 'inapplicable',
+ reason: commitResult.error.message,
+ residual: [{ severity: 'high', location: 'issue placeholders', problem: commitResult.error.message }],
+ };
+ }
+ const created = commitResult.created;
await recordDomainUsage('cos', { actions: 1 });
if (!Array.isArray(created) || created.length === 0) {
return {
@@ -94,6 +107,8 @@ export async function dispatchStep(sId, step, record) {
}
return {};
}
+ case 'verifyArcSpine':
+ return runArcVerify(sId, record, { spineOnly: true });
case 'verifyArc':
return runArcVerify(sId, record);
case 'beatSheet':
diff --git a/server/services/pipeline/seriesAutopilot/dryRun.js b/server/services/pipeline/seriesAutopilot/dryRun.js
index 8bcd3f089d..89bdbe65ec 100644
--- a/server/services/pipeline/seriesAutopilot/dryRun.js
+++ b/server/services/pipeline/seriesAutopilot/dryRun.js
@@ -97,6 +97,13 @@ export function buildDryRunPlan(series, issues, options, costContext = {}) {
});
}
}
+ const arcRounds = Number.isInteger(options?.maxArcVerifyRounds) ? options.maxArcVerifyRounds : MAX_ARC_VERIFY_ROUNDS;
+ plan.push({
+ kind: 'verifyArcSpine',
+ count: 1,
+ note: `${roundsNote(arcRounds)}; protected intent + macro arc before issue generation`,
+ estActions: convergenceLoopActions(arcRounds),
+ });
const emptySeasons = seasons.filter((s) => !ordered.some((i) => i.seasonId === s.id));
if (emptySeasons.length) plan.push({ kind: 'generateEpisodes', count: emptySeasons.length, estActions: emptySeasons.length });
// Foundation runs first at synopsis altitude. Arc/volume repairs and
@@ -106,7 +113,6 @@ export function buildDryRunPlan(series, issues, options, costContext = {}) {
if (options?.foundationGate !== false && foundationRounds !== 0) {
plan.push({ kind: 'foundationGate', count: 1, note: `${roundsNote(foundationRounds)}; re-checks after arc repairs`, estActions: convergenceLoopActions(foundationRounds) });
}
- const arcRounds = Number.isInteger(options?.maxArcVerifyRounds) ? options.maxArcVerifyRounds : MAX_ARC_VERIFY_ROUNDS;
const verificationActions = arcRounds === 0
? 0
: arcRounds * (1 + seasons.length) + Math.max(0, arcRounds - 1);
diff --git a/server/services/pipeline/seriesAutopilot/orchestrator.js b/server/services/pipeline/seriesAutopilot/orchestrator.js
index 301031a744..2b898f2d5d 100644
--- a/server/services/pipeline/seriesAutopilot/orchestrator.js
+++ b/server/services/pipeline/seriesAutopilot/orchestrator.js
@@ -130,6 +130,7 @@ export async function startSeriesAutopilot(sId, options = {}) {
// cast has causal wants/needs/relationships to drive it.
characterFoundationEstablished: false,
arcAttempted: false,
+ arcSpineVerified: false,
arcVerified: false,
// #2176 — foundation-quality gate satisfied this run (threshold cleared,
// or the gate disabled/0-round). Boolean like arcVerified so the resolver
@@ -178,6 +179,7 @@ export async function startSeriesAutopilot(sId, options = {}) {
observerFindings: [],
},
activeChild: null,
+ activeLlmRunId: null,
};
runs.set(sId, record);
@@ -342,7 +344,7 @@ export async function startSeriesAutopilot(sId, options = {}) {
// runEditorial short-circuit with no LLM spend, so "0 skips the gate" must
// hold even when the budget is exhausted (otherwise the run pauses on
// budget instead of skipping).
- const zeroRoundSkip = (step.kind === 'verifyArc' && runOptions.maxArcVerifyRounds === 0)
+ const zeroRoundSkip = ((step.kind === 'verifyArc' || step.kind === 'verifyArcSpine') && runOptions.maxArcVerifyRounds === 0)
|| (step.kind === 'beatContinuity' && runOptions.maxBeatContinuityRounds === 0)
|| (step.kind === 'editorialReview' && runOptions.maxEditorialRounds === 0)
|| (step.kind === 'foundationGate' && (runOptions.maxFoundationRounds === 0 || runOptions.foundationGate === false));
diff --git a/server/services/pipeline/seriesAutopilot/session.js b/server/services/pipeline/seriesAutopilot/session.js
index 83ccbabcb1..b8a5d7dfb9 100644
--- a/server/services/pipeline/seriesAutopilot/session.js
+++ b/server/services/pipeline/seriesAutopilot/session.js
@@ -11,6 +11,7 @@ import { addNotification, removeByMetadata, NOTIFICATION_TYPES, PRIORITY_LEVELS
import { getSeries, updateSeries } from '../series.js';
import * as volumeBeatsRunner from '../volumeBeatsRunner.js';
import * as autoRunner from '../autoRunner.js';
+import { stopRun } from '../../runner.js';
import { runs, autopilotEvents, noteSignal } from './state.js';
// ---------------------------------------------------------------------------
@@ -53,6 +54,14 @@ export function cancelSeriesAutopilot(seriesId) {
const child = run.activeChild;
if (child?.kind === 'beats') volumeBeatsRunner.cancelVolumeBeatsRun(child.id);
else if (child?.kind === 'text') autoRunner.cancelAutoRun(child.id);
+ // Direct staged-LLM steps (arc, episode plan, foundation judge/repair) do
+ // not have a delegated child coordinator. Stop their concrete run too; the
+ // prompt runner reports fallback run ids through the same lifecycle hook.
+ if (run.activeLlmRunId) {
+ stopRun(run.activeLlmRunId).catch((err) => {
+ console.log(`⚠️ autopilot: active LLM stop failed for ${seriesId.slice(0, 12)}: ${err.message}`);
+ });
+ }
return true;
}
@@ -235,6 +244,15 @@ export const providerOverrideOpts = (record, role = 'creative') => {
providerDefault: llm.providerOverride,
modelDefault: llm.modelOverride,
effortDefault: llm.effortOverride,
+ onRunCreated: (runId) => {
+ record.activeLlmRunId = runId;
+ // Close the race where Stop lands after createRun but before provider
+ // execution registers its child process.
+ if (record.cancelRequested) stopRun(runId).catch(() => {});
+ },
+ onRunSettled: (runId) => {
+ if (record.activeLlmRunId === runId) record.activeLlmRunId = null;
+ },
};
};
export const providerIdOpts = (record, role = 'creative') => {
diff --git a/server/services/pipeline/seriesAutopilot/state.js b/server/services/pipeline/seriesAutopilot/state.js
index 8201e6a0f6..7eac6b2910 100644
--- a/server/services/pipeline/seriesAutopilot/state.js
+++ b/server/services/pipeline/seriesAutopilot/state.js
@@ -11,7 +11,8 @@ import { EventEmitter } from 'events';
import { diagnosisOptedIn } from './diagnosisCore.js';
// runs: Map<seriesId, { runId, clients[], lastPayload, startPayload, cancelRequested,
-// finished, cleanupTimer, startedAt, mode, options, runState, activeChild }>
+// finished, cleanupTimer, startedAt, mode, options, runState, activeChild,
+// activeLlmRunId }>
// `startPayload` is the run's `start` frame, retained so a client attaching
// mid-run can still read it (SSE replay only carries `lastPayload`).
export const runs = new Map();
diff --git a/server/services/pipeline/seriesAutopilot/stepResolver.js b/server/services/pipeline/seriesAutopilot/stepResolver.js
index 436c98cbc5..1b6cf89cc9 100644
--- a/server/services/pipeline/seriesAutopilot/stepResolver.js
+++ b/server/services/pipeline/seriesAutopilot/stepResolver.js
@@ -189,6 +189,15 @@ export function resolveNextStep(series, issues, runState = {}, options = {}) {
return { kind: 'repairArcStructure', reason: 'duplicate volume numbers must be normalized before issue generation' };
}
+ // STEP 1.9 — verify the expensive macro spine before manufacturing episode
+ // plans from it. This gate deliberately ignores issue placeholders and checks
+ // protected intent, active cast, volume structure, and the whole-series arc.
+ // `arcVerified:true` from an in-flight pre-upgrade run already proves the
+ // stronger post-episode gate, so it implies the spine checkpoint too.
+ if (!runState.arcSpineVerified && !runState.arcVerified) {
+ return { kind: 'verifyArcSpine', reason: 'arc spine must pass before issue generation' };
+ }
+
// STEP 2 — a season with zero issues (in season order). Skip volumes already
// attempted this run so an empty episode generation can't re-loop (the
// dispatch pauses when it produces no issues).
diff --git a/server/services/pipeline/seriesCanon.js b/server/services/pipeline/seriesCanon.js
index cd6b7c1944..96a8bced7f 100644
--- a/server/services/pipeline/seriesCanon.js
+++ b/server/services/pipeline/seriesCanon.js
@@ -26,6 +26,75 @@ export const pickCanon = (universe) => ({
objects: Array.isArray(universe?.objects) ? universe.objects : [],
});
+const normalizeReferenceText = (value) => String(value || '').normalize('NFKC').toLocaleLowerCase();
+
+const referencedByName = (entry, referenceText) => {
+ const name = normalizeReferenceText(entry?.name || entry?.slugline);
+ return name.length >= 2 && referenceText.includes(name);
+};
+
+const seriesPlanningText = (series, universe) => normalizeReferenceText(JSON.stringify({
+ protectedWorldIntent: {
+ starterPrompt: universe?.starterPrompt || '',
+ logline: universe?.logline || '',
+ premise: universe?.premise || '',
+ },
+ series: {
+ name: series?.name || '',
+ logline: series?.logline || '',
+ premise: series?.premise || '',
+ arc: series?.arc || null,
+ seasons: series?.seasons || [],
+ characterArcs: series?.characterArcs || [],
+ },
+}));
+
+/**
+ * Scope a shared universe's canon to entities that demonstrably belong to one
+ * series' current planning contract. Universe Builder worlds can retain canon
+ * from abandoned drafts and from sibling series; injecting every old named
+ * entity into a new arc prompt makes those records look equally authoritative
+ * and can resurrect an incompatible plot.
+ *
+ * Stable character-arc ids/names and explicit mentions in protected world or
+ * series fields are the roots. The selected characters' authored records then
+ * provide one bounded relationship hop to supporting characters, places, and
+ * objects. Nothing is deleted from the universe or catalog — this only narrows
+ * generative prompt context. An empty result is intentional: protected premise
+ * text is safer than guessing that unrelated legacy canon belongs to the story.
+ */
+export function scopeCanonForSeries(universe, series) {
+ const canon = pickCanon(universe);
+ let referenceText = seriesPlanningText(series, universe);
+ const arcCharacterIds = new Set((series?.characterArcs || [])
+ .map((arc) => arc?.characterId)
+ .filter(Boolean));
+ const arcCharacterNames = new Set((series?.characterArcs || [])
+ .map((arc) => normalizeReferenceText(arc?.characterName))
+ .filter(Boolean));
+
+ const characters = canon.characters.filter((character) => (
+ arcCharacterIds.has(character?.id)
+ || arcCharacterNames.has(normalizeReferenceText(character?.name))
+ || referencedByName(character, referenceText)
+ ));
+
+ // One relationship hop admits supporting nouns the active principals name,
+ // while avoiding an unbounded graph walk through old draft relationships.
+ referenceText += `\n${normalizeReferenceText(JSON.stringify(characters))}`;
+ const supportingCharacters = canon.characters.filter((character) => (
+ !characters.includes(character) && referencedByName(character, referenceText)
+ ));
+ const scopedCharacters = [...characters, ...supportingCharacters];
+ referenceText += `\n${normalizeReferenceText(JSON.stringify(supportingCharacters))}`;
+
+ return {
+ characters: scopedCharacters,
+ places: canon.places.filter((place) => referencedByName(place, referenceText)),
+ objects: canon.objects.filter((object) => referencedByName(object, referenceText)),
+ };
+}
+
/**
* Async canon read for text/arc-planning stages that don't already have the
* universe record in scope. Returns frozen-empty when the series is orphan
@@ -37,9 +106,11 @@ export const pickCanon = (universe) => ({
* `filterCanonForIssue` / `filterCanonListForIssue` from
* `server/lib/storyBible.js` before injecting it, so a later-reveal secret
* can't leak into an earlier issue. The **judge, editorial checks, canon
- * extraction, arc/scene planning** intentionally consume the full canon (they
- * need the truth and have no single issue number). New prompt-builders that
- * load canon here for a drafting prompt MUST apply the filter; see
+ * extraction, and scene planning** intentionally consume the full canon (they
+ * need the truth and have no single issue number). Arc/episode planning uses
+ * `getSeriesPlanningCanon` below so abandoned sibling-draft entities do not
+ * compete with the active series contract. New prompt-builders that load canon
+ * here for a drafting prompt MUST apply the filter; see
* `textStages.buildStageContext` and `perspectiveRewrite.resolveCast` for the
* reference call sites.
*
@@ -51,3 +122,11 @@ export async function getSeriesCanon(series) {
if (!universe) return EMPTY;
return pickCanon(universe);
}
+
+/** Series-scoped canon for generative planning prompts. */
+export async function getSeriesPlanningCanon(series) {
+ if (!series?.universeId) return EMPTY;
+ const universe = await getUniverse(series.universeId).catch(() => null);
+ if (!universe) return EMPTY;
+ return scopeCanonForSeries(universe, series);
+}
diff --git a/server/services/universeBuilderExpand.js b/server/services/universeBuilderExpand.js
index 094fa78483..3e5e5dfa70 100644
--- a/server/services/universeBuilderExpand.js
+++ b/server/services/universeBuilderExpand.js
@@ -488,6 +488,8 @@ const normalizeCanonArray = (raw, kind) => {
* @param {string} [options.providerId] — optional override; falls back to active.
* @param {string} [options.model] — optional override; falls back to provider default.
* @param {string} [options.effort] — optional reasoning-effort override for capable providers.
+ * @param {(runId:string)=>void} [options.onRunCreated] — parent-workflow lifecycle hook.
+ * @param {(runId:string)=>void} [options.onRunSettled] — parent-workflow lifecycle hook.
* @param {boolean} [options.narrativeOnly] — limit output to the story-bible fields a foundation repair persists.
*/
export async function expandWorldTemplate({
@@ -506,6 +508,8 @@ export async function expandWorldTemplate({
providerId,
model,
effort,
+ onRunCreated,
+ onRunSettled,
narrativeOnly = false,
} = {}) {
if (!starterPrompt || !starterPrompt.trim()) {
@@ -580,6 +584,8 @@ export async function expandWorldTemplate({
provider,
model: selectedModel,
effort,
+ onRunCreated,
+ onRunSettled,
prompt,
source: narrativeOnly ? "universe-builder-narrative-repair" : "universe-builder-expansion",
});