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

feat([issue-1510]): whole-manuscript beat-continuity pass before full-script generation

Adam Eivycb69a5528799
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c54bea02f8..66c39d7078 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -24,6 +24,10 @@
- **[issue-1511] Per-issue prose and comic-script generation now sees only the characters that issue involves.** Generating an issue used to load the entire series character bible into every prose and comic-script prompt — on a large-cast series that's tens of thousands of tokens of character detail (including one-off bit players from unrelated issues) re-sent on every issue and every stage. Generation now sends full character records only for the cast named in that issue's beats, synopsis, and source material, with a compact one-line roster of everyone else kept for continuity. This sharply cuts token cost on big-cast series and, on context-bounded providers, leaves more room for the actual draft. The series' lead/recurring characters stay in context for every issue, so the core cast is never dropped — generation just stops carrying the full record of every bit player from unrelated issues.
- **[issue-1529] A character whose name is a common word (Will, May, Grace) is no longer pulled into a prompt by an incidental word.** When scoping an issue's character bible, an ordinary phrase like "the team **will** regroup" could be mistaken for naming a cast member called "Will" — incidentally scoping the prompt down to that one character. A single-word character name now only counts as named when it appears capitalized as a proper noun ("Will entered"), so common-word names match the same way every other name does. Multi-word names and nicknames are unaffected.
+## Series Autopilot
+
+- **[issue-1510] Series Autopilot now catches whole-book continuity problems at the cheap beat stage, before it generates full scripts.** The autopilot reviewed continuity at two altitudes — the cross-volume synopsis pass (before beats exist) and the full-text editorial pass (after every issue's script is written, the most expensive stage) — leaving a gap in between. So structural defects spanning the whole book (a cliffhanger raised in one issue and never resolved, a finale that drifts onto a new subplot instead of landing the arc's intended ending, a promised through-line that never pays off, an event staged as the "first" in two different issues, a broken volume-to-volume hand-off) were only caught *after* all the scripts already existed — or not until a human read it. The autopilot now runs a **whole-manuscript beat-continuity pass over every issue's beat sheet, between beat generation and script generation**. Blocking findings are auto-resolved by rewriting just the affected issues' beats and re-checking (bounded, then it pauses for review with the residual findings), so the fix lands before any script is generated. The full-text editorial pass is unchanged and still catches what only the verbatim script can show (pacing, repeated/looping passages, dialogue craft). A new **Beat continuity rounds** control in the autopilot Options tunes how many auto-resolve rounds it attempts (0 skips the pass), saved as a per-install default like the existing Arc-verify and Editorial round knobs.
+
## Fixed
- **Client test suite no longer floods CI with React "not wrapped in act(...)" warnings.** Across eight component/page suites, state updates were being driven outside `act()` — hand-fired mock-EventSource frames (`emit`/`fail`), raw DOM `.blur()` calls, manually-invoked tracker callbacks, and resolved in-flight gates whose follow-up `setState` landed after the test body returned (plus a few synchronous tests whose mount-time fetches resolved late). These surfaced only under CI's verbose reporter (the default reporter hides console output), so they were invisible locally. Each driving call is now wrapped in `act()` (or switched to `fireEvent`, which wraps internally), and synchronous tests that mount components with async effects now flush inside `act()`. The full client suite (2497 tests) runs clean with zero act warnings. (`PipelineManuscriptEditor`, `Layout`, `WidgetSuggestions`, `ApiAccessTab`, `PitchTuner`, `SongTraining`, `AudioStage`, `LocalLlmPlayground` test suites)
diff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsx
index 8bb87edf0e..0f5f5d76fd 100644
--- a/client/src/components/pipeline/AutopilotPanel.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.jsx
@@ -24,6 +24,7 @@ const ROUND_MIN = 0;
const ROUND_MAX = 20;
const DEFAULT_ARC_ROUNDS = 3;
const DEFAULT_EDITORIAL_ROUNDS = 2;
+const DEFAULT_BEAT_CONTINUITY_ROUNDS = 2;
const clampRound = (n, fallback) => {
// A blank/cleared field falls back to the default — NOT 0. (Number('') === 0,
// and 0 means "skip the gate", so without this a cleared input would silently
@@ -142,6 +143,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
const [fileGaps, setFileGaps] = useState(false);
const [arcRounds, setArcRounds] = useState(DEFAULT_ARC_ROUNDS);
const [editorialRounds, setEditorialRounds] = useState(DEFAULT_EDITORIAL_ROUNDS);
+ const [beatContinuityRounds, setBeatContinuityRounds] = useState(DEFAULT_BEAT_CONTINUITY_ROUNDS);
// Per-field dirty flags. Until a field is edited its input shows a display
// default we must NOT persist (that would clobber a higher saved setting on
// the untouched gate). Tracked per-field so editing one gate never discards
@@ -149,6 +151,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
// untouched ones keep their on-disk value via patchSettingsSlice's merge.
const arcEditedRef = useRef(false);
const editorialEditedRef = useRef(false);
+ const beatContinuityEditedRef = useRef(false);
const [canon, setCanon] = useState(null);
const [canonLoading, setCanonLoading] = useState(false);
@@ -165,6 +168,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
const pec = s?.pipelineEditorialChecks || {};
if (!arcEditedRef.current) setArcRounds(Number.isInteger(pec.maxArcVerifyRounds) ? pec.maxArcVerifyRounds : DEFAULT_ARC_ROUNDS);
if (!editorialEditedRef.current) setEditorialRounds(Number.isInteger(pec.maxEditorialRounds) ? pec.maxEditorialRounds : DEFAULT_EDITORIAL_ROUNDS);
+ if (!beatContinuityEditedRef.current) setBeatContinuityRounds(Number.isInteger(pec.maxBeatContinuityRounds) ? pec.maxBeatContinuityRounds : DEFAULT_BEAT_CONTINUITY_ROUNDS);
})
.catch(() => null); // load failed → inputs keep defaults but start() only persists EDITED fields
return () => { canceled = true; };
@@ -189,6 +193,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
// overwrite it and so start() knows to persist it.
const editArcRounds = useCallback((v) => { arcEditedRef.current = true; setArcRounds(v); }, []);
const editEditorialRounds = useCallback((v) => { editorialEditedRef.current = true; setEditorialRounds(v); }, []);
+ const editBeatContinuityRounds = useCallback((v) => { beatContinuityEditedRef.current = true; setBeatContinuityRounds(v); }, []);
const { latest, frames } = usePipelineProgress(pipelineAutopilotSseUrl, [seriesId], { enabled: active });
@@ -255,6 +260,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
const roundOverrides = {};
if (arcEditedRef.current) roundOverrides.maxArcVerifyRounds = clampRound(arcRounds, DEFAULT_ARC_ROUNDS);
if (editorialEditedRef.current) roundOverrides.maxEditorialRounds = clampRound(editorialRounds, DEFAULT_EDITORIAL_ROUNDS);
+ if (beatContinuityEditedRef.current) roundOverrides.maxBeatContinuityRounds = clampRound(beatContinuityRounds, DEFAULT_BEAT_CONTINUITY_ROUNDS);
if (Object.keys(roundOverrides).length) await persistRounds(roundOverrides);
const res = await startPipelineAutopilot(seriesId, { includeVisual, fileGaps, ...roundOverrides }, { silent: true })
.catch((err) => { toast.error(err.message || 'Could not start autopilot'); return null; });
@@ -266,7 +272,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
// effect can reject a stale terminal frame from the previous run.
activeRunIdRef.current = res.runId || null;
setActive(true);
- }, [seriesId, includeVisual, fileGaps, arcRounds, editorialRounds, persistRounds]);
+ }, [seriesId, includeVisual, fileGaps, arcRounds, editorialRounds, beatContinuityRounds, persistRounds]);
const cancel = useCallback(async () => {
await cancelPipelineAutopilot(seriesId).catch(() => null);
@@ -349,6 +355,15 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
defaultValue={DEFAULT_ARC_ROUNDS}
persist={persistRounds}
/>
+ <RoundInput
+ id="autopilot-beat-continuity-rounds"
+ label="Beat continuity rounds"
+ settingKey="maxBeatContinuityRounds"
+ value={beatContinuityRounds}
+ setValue={editBeatContinuityRounds}
+ defaultValue={DEFAULT_BEAT_CONTINUITY_ROUNDS}
+ persist={persistRounds}
+ />
<RoundInput
id="autopilot-editorial-rounds"
label="Editorial rounds"
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 987070831f..e3cc7041e7 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -373,6 +373,20 @@
"returnsJson": true,
"variables": []
},
+ "pipeline-beat-continuity": {
+ "name": "Pipeline — Whole-Manuscript Beat Continuity",
+ "description": "Whole-book beat-level continuity pass over every issue's beat sheet — the altitude between cross-volume synopsis verify and the full scripts. Catches dropped cliffhangers/unresolved setups, finale drift from the arc's intended ending, promised through-lines that never land, duplicated 'firsts', volume-to-volume hand-off breaks, and cross-issue character-state contradictions BEFORE the expensive full-script stage. Returns actionable { severity, location, problem, suggestion } issues — empty list means the beats cohere.",
+ "model": "heavy",
+ "returnsJson": true,
+ "variables": []
+ },
+ "pipeline-beat-continuity-resolve": {
+ "name": "Pipeline — Beat Continuity Auto-Resolve",
+ "description": "Auto-resolve whole-manuscript beat-continuity findings by rewriting the BEATS of the specific issues that caused each finding (idea.output) — the beat altitude, not the arc. Returns a sparse episodes[] of full corrected beat sheets keyed by series-global episodeNumber (+ seasonNumber), plus optional notes for anything needing an arc-level restructure.",
+ "model": "heavy",
+ "returnsJson": true,
+ "variables": []
+ },
"pipeline-script-verify": {
"name": "Pipeline — Comic Script Verification",
"description": "Craft pass over ONE issue's comic script before art: catches un-renderable panels, missing/malformed page-panel structure, panel-to-panel flow breaks, dialogue/art imbalance, within-issue continuity, and page-turn/beat placement. Used by Series Autopilot's per-issue script gate (advisory — surfaces findings, doesn't auto-rewrite). Returns actionable { severity, location, problem, suggestion } issues — empty list means sound.",
diff --git a/data.reference/prompts/stages/pipeline-beat-continuity-resolve.md b/data.reference/prompts/stages/pipeline-beat-continuity-resolve.md
new file mode 100644
index 0000000000..354499cf2b
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-beat-continuity-resolve.md
@@ -0,0 +1,93 @@
+# Pipeline — Beat Continuity Auto-Resolve
+
+You are a senior story editor cleaning up a planned series so it passes the whole-manuscript **beat-continuity** check. A continuity pass over the per-issue **beat sheets** returned a list of cross-issue structural findings. Your job is to rewrite the **beats of the specific issues that caused each finding** so every finding is resolved — while preserving as much of the author's original beats as possible.
+
+Every series is published as both a graphic novel (issues → volumes) AND a TV series (episodes → seasons). One issue == one episode. Your edits are at the **beat** layer (no script has been generated yet), so editing them is safe and cheap — that is the whole point of fixing here instead of after the full scripts exist.
+
+## Series bible
+
+- **Name:** {{series.name}}
+- **Logline:** {{series.logline}}
+- **Premise:**
+
+```
+{{series.premise}}
+```
+
+{{#hasLinkedWorld}}
+## Linked World — canonical entities
+
+The series is grounded in this World Builder world: **{{worldName}}**. Ground rewritten beats in these entities by name.
+
+```
+{{worldCanonText}}
+```
+{{/hasLinkedWorld}}
+
+{{> bible-deference }}
+
+## Intended whole-series shape
+
+- **Whole-series logline:** {{arc.logline}}
+- **Themes:** {{arc.themesCsv}}
+- **Protagonist arc:**
+
+```
+{{arc.protagonistArc}}
+```
+
+- **Arc summary:**
+
+```
+{{arc.summary}}
+```
+
+## Story shape (Vonnegut)
+
+{{{shapeGuidance}}}
+
+Preserve the picked shape — the issue-level beats must still trace this curve after your edits.
+
+## Volumes + issues (current beats)
+
+Each issue carries its current `beats` (or a `synopsis` if not yet expanded). The `number` is the series-global episode number you will key corrections to.
+
+```json
+{{seasonsTreeJson}}
+```
+
+## Findings to resolve
+
+Resolve **every** one of these:
+
+```json
+{{findingsJson}}
+```
+
+## How to resolve
+
+1. **Edit beats, not the arc.** This pass only rewrites per-issue beat sheets. Do NOT propose arc/volume synopsis changes here — if a finding could ONLY be fixed by restructuring volumes, say so in `notes` and leave the beats untouched.
+2. **Anchor each fix in the issue that *originates* the problem.** A dropped cliffhanger is fixed by adding the payoff beat to the issue that should carry it (or removing the dangling setup); a duplicated "first" is fixed by demoting the later occurrence in that issue's beats; a finale that drifts is fixed by rewriting the final issue's beats to land the arc. Make the **smallest** change that removes the contradiction while preserving the issue's dramatic purpose.
+3. **Read each finding's `problem` + `suggestion`.** The suggestion is a hint, not gospel — but the resulting beats MUST make the finding go away.
+4. **Only rewrite issues that already have beats.** An issue still at synopsis depth has no beats to edit — skip it (omit it from `episodes[]`); it'll be expanded later from the corrected arc.
+5. **Never delete an issue** — omit it from `episodes[]` to leave its beats exactly as they are.
+6. **Preserve cross-issue consistency.** When you change a beat that another issue depends on, make sure your set of edits is internally consistent across all the issues you touch.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
+
+```json
+{
+ "episodes": [
+ {
+ "seasonNumber": 3,
+ "episodeNumber": 23,
+ "beats": "string (the FULL corrected beat sheet for this issue — escape newlines as \\n)"
+ }
+ ],
+ "notes": "string (optional — flag any finding you could only partially resolve at the beat layer, or that needs an arc-level restructure. Empty string if every finding is fully addressed.)"
+}
+```
+
+The `episodes[]` array is a SPARSE list of beat rewrites — include only the issues you actually changed. Each `beats` value REPLACES that issue's current beat sheet in full, so write the complete corrected beats, not a delta. Issues you don't list are left exactly as they are.
diff --git a/data.reference/prompts/stages/pipeline-beat-continuity.md b/data.reference/prompts/stages/pipeline-beat-continuity.md
new file mode 100644
index 0000000000..6c7d504606
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-beat-continuity.md
@@ -0,0 +1,94 @@
+# Pipeline — Whole-Manuscript Beat Continuity
+
+You are a continuity editor doing a **whole-book beat-level pass** on a planned series — the altitude **between** the cross-volume synopsis review (already done) and the full scripts (not yet written). The author has expanded most issues into per-issue **beat sheets**; your job is to catch cross-issue structural defects **now, at the cheap beat altitude, before the pipeline burns LLM + GPU minutes generating ~24 full scripts** from broken beats.
+
+This is NOT a creative critique and NOT a craft/prose pass — don't suggest "make it darker", don't flag dialogue quality, pacing-within-a-page, or panel repetition (the full-text editorial pass owns those, reading verbatim script). Flag **only** cross-issue continuity and structural breaks that are visible in the beats.
+
+## Series bible
+
+- **Name:** {{series.name}}
+- **Target format:** {{series.targetFormat}}
+- **Logline:** {{series.logline}}
+- **Premise:**
+
+```
+{{series.premise}}
+```
+
+{{> bible-deference }}
+
+{{#hasLinkedWorld}}
+## Linked World — canonical entities
+
+The series is grounded in this World Builder world: **{{worldName}}**. When you flag continuity findings, address characters/places/objects by their canonical names below.
+
+```
+{{worldCanonText}}
+```
+{{/hasLinkedWorld}}
+
+## Full arc — the intended whole-series shape
+
+- **Whole-series logline:** {{arc.logline}}
+- **Themes:** {{arc.themesCsv}}
+- **Protagonist arc:**
+
+```
+{{arc.protagonistArc}}
+```
+
+- **Arc summary:**
+
+```
+{{arc.summary}}
+```
+
+## Story shape (Vonnegut)
+
+{{{shapeGuidance}}}
+
+## Volumes + issues (beats where expanded)
+
+Each issue carries either a `beats` field (the expanded beat sheet — the real corpus for this pass) or, if not yet expanded, a `synopsis` field. Review issues at whichever depth they're at; weight your findings toward the beat-bearing issues.
+
+```json
+{{seasonsTreeJson}}
+```
+
+There are **{{beatBearingCount}}** beat-bearing issue(s) in this corpus.
+
+## What to look for
+
+Read the beats **in series order, as one continuous manuscript**. Specifically check for:
+
+1. **Unresolved setups / dropped cliffhangers.** A beat raises a question, plants a gun, or ends an issue on a cliffhanger that no later issue's beats pay off. Name both the issue that sets it up and the absence of a payoff.
+2. **Arc-ending fidelity.** The final issue's beats must land the whole-series logline, the protagonist arc's intended end-state, and the picked story shape's terminal level. Flag a finale whose beats drift onto a new subplot or end on a different image than the arc intends.
+3. **Promised through-lines that never land.** A relationship, theme, or character goal the arc summary promises must actually be dramatized across the issue beats — flag one that's named in the arc but absent from (or under-served by) the beats that should carry it.
+4. **Duplicated "firsts" / staging contradictions.** An event the beats stage as the *first* occurrence (first meeting, first reveal, first use of a power) that an earlier issue's beats already staged — or any beat that contradicts an established earlier beat (a character knows something they shouldn't yet, an object that was destroyed reappears intact).
+5. **Volume-to-volume hand-offs.** The state a volume's last issue leaves the story in must match the state its next volume's first issue assumes. Flag a beat-level discontinuity across a volume boundary.
+6. **Character-state contradictions across issues.** A character dies / leaves / changes allegiance in one issue's beats but acts as before in a later issue's beats with no bridging beat.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary. Each `issues[]` entry must be **actionable**: name the issue(s) by series-global episode number (and volume), name the rule it breaks, and propose the smallest beat-level edit that resolves it.
+
+```json
+{
+ "issues": [
+ {
+ "severity": "high",
+ "location": "issue:23 (volume 3)",
+ "problem": "string (what's wrong, citing the specific beats)",
+ "suggestion": "string (the smallest beat edit that resolves it)"
+ }
+ ]
+}
+```
+
+`severity` must be one of `high` / `medium` / `low`:
+
+- **`high`** — would break a reader's understanding of the story (a dropped cliffhanger, a finale that doesn't pay off the arc, a hard character-state contradiction).
+- **`medium`** — would make the book feel structurally sloppy (an under-served through-line, a soft duplicated "first").
+- **`low`** — opportunity to tighten (a theme that could land harder).
+
+Return `{ "issues": [] }` if the beats cohere across the whole book. Do NOT pad with low-confidence "consider also..." entries, and do NOT flag anything that needs the verbatim script to see (prose craft, in-page repetition) — that is the full-text pass's job.
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 38fe90ee96..bf4172b3fb 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1093,6 +1093,9 @@ export const pipelineEditorialChecksSettingsSchema = z.object({
readinessGate: z.enum(['noOpenHigh', 'noOpenHighOrMedium', 'none']).optional(),
maxArcVerifyRounds: z.number().int().min(0).max(MAX_CONVERGENCE_ROUNDS).optional(),
maxEditorialRounds: z.number().int().min(0).max(MAX_CONVERGENCE_ROUNDS).optional(),
+ // Whole-manuscript beat-continuity convergence (#1510) — same bound + 0-skip
+ // semantics. Optional + additive so older peers fall through to the default.
+ maxBeatContinuityRounds: z.number().int().min(0).max(MAX_CONVERGENCE_ROUNDS).optional(),
}).strict();
// Cursor-context payload for the CD-bridge suggest route — identical shape to
diff --git a/server/routes/pipeline/autopilot.js b/server/routes/pipeline/autopilot.js
index 65dd7a8dd7..10f2d47c50 100644
--- a/server/routes/pipeline/autopilot.js
+++ b/server/routes/pipeline/autopilot.js
@@ -37,11 +37,12 @@ const autopilotStartSchema = z.object({
targetFormats: z.array(z.enum(['comic', 'tv'])).optional(),
// Per-run convergence bounds for the verify/review loops (0 = skip that gate).
// When omitted, the autopilot falls back to the persisted
- // pipelineEditorialChecks.{maxArcVerifyRounds,maxEditorialRounds} setting, then
- // to the module default. Cap mirrors the settings schema so the UI knob and a
- // direct API call agree on the ceiling.
+ // pipelineEditorialChecks.{maxArcVerifyRounds,maxEditorialRounds,maxBeatContinuityRounds}
+ // setting, then to the module default. Cap mirrors the settings schema so the
+ // UI knob and a direct API call agree on the ceiling.
maxArcVerifyRounds: z.number().int().min(0).max(MAX_CONVERGENCE_ROUNDS).optional(),
maxEditorialRounds: z.number().int().min(0).max(MAX_CONVERGENCE_ROUNDS).optional(),
+ maxBeatContinuityRounds: z.number().int().min(0).max(MAX_CONVERGENCE_ROUNDS).optional(),
});
router.post('/series/:id/autopilot/start', asyncHandler(async (req, res) => {
diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.js
index 4eec3c29c7..f82d30858c 100644
--- a/server/services/pipeline/arcPlanner.js
+++ b/server/services/pipeline/arcPlanner.js
@@ -25,6 +25,7 @@
export * from './arcPlanner/context.js';
export * from './arcPlanner/arcCore.js';
+export * from './arcPlanner/beatContinuity.js';
export * from './arcPlanner/episodeSeedPass.js';
export * from './arcPlanner/completenessPass.js';
export * from './arcPlanner/manuscriptDerive.js';
@@ -33,8 +34,9 @@ export * from './arcPlanner/coverConcepts.js';
// Internals surfaced for tests (was an inline `export const __testing` before
// the split). Pulled back together here from their new home modules so the
// existing `__testing` import contract is preserved.
-import { buildArcOverviewContext, shapeSeasonOutlines, buildVerifyContext, buildResolveContext, shapeVerifyIssues, shapeFindings, renderVolumeIssue, buildNeighborVolumes } from './arcPlanner/context.js';
+import { buildArcOverviewContext, shapeSeasonOutlines, buildVerifyContext, buildResolveContext, shapeVerifyIssues, shapeFindings, renderVolumeIssue, buildNeighborVolumes, buildBeatContinuityContext, shapeBeatResolutions } from './arcPlanner/context.js';
import { buildVolumeVerifyContext, mergeArcWithLocks, mergeSeasonsWithLocks } from './arcPlanner/arcCore.js';
+import { applyBeatResolutions } from './arcPlanner/beatContinuity.js';
import { buildSeasonEpisodesContext, shapeEpisodes } from './arcPlanner/episodeSeedPass.js';
import { shapeCompletenessFindings, buildCompletenessContext } from './arcPlanner/completenessPass.js';
import { issueSynopsisFromSeason } from './arcPlanner/manuscriptDerive.js';
@@ -56,4 +58,7 @@ export const __testing = {
buildNeighborVolumes,
mergeArcWithLocks,
mergeSeasonsWithLocks,
+ buildBeatContinuityContext,
+ shapeBeatResolutions,
+ applyBeatResolutions,
};
diff --git a/server/services/pipeline/arcPlanner/beatContinuity.js b/server/services/pipeline/arcPlanner/beatContinuity.js
new file mode 100644
index 0000000000..263b630654
--- /dev/null
+++ b/server/services/pipeline/arcPlanner/beatContinuity.js
@@ -0,0 +1,171 @@
+/**
+ * arcPlanner/beatContinuity.js — whole-manuscript BEAT-level continuity pass
+ * (#1510).
+ *
+ * The series autopilot caught arc/continuity problems at two altitudes with a
+ * gap in the middle: `verifyArc` reviews episode SYNOPSES across the whole arc
+ * (before beats exist), and the full-text completeness pass reads VERBATIM
+ * scripts (after the expensive text stage). So whole-BOOK beat defects — a
+ * cliffhanger raised in one issue and never resolved, a finale that drifts from
+ * the arc's intended ending, a promised through-line that never lands, an event
+ * staged as "first" in two issues — only surfaced AFTER 24 full scripts were
+ * generated, by the full-text pass (or not until a human read it).
+ *
+ * This pass closes the gap: it runs over the per-issue beat sheets (idea.output)
+ * for the whole series — a compact corpus that fits a normal window cheaply (no
+ * chunking) — BETWEEN beat generation and full-script generation. On blocking
+ * findings the resolver rewrites the offending issues' BEATS directly
+ * (idea.output) — the right altitude for a beat-level finding — so the fix lands
+ * before any script is generated. The full-text completeness pass stays as-is
+ * for what genuinely needs verbatim text (pacing, looping/repetition, dialogue
+ * craft); this is an additional, earlier, cheaper pass, not a replacement.
+ *
+ * Mirrors arcCore.js's verifyArc / resolveVerifyIssues / applyEpisodeResolutions
+ * trio — same LLM-call + shape + apply structure, one altitude down.
+ */
+
+import { runStagedLLM } from '../../../lib/stageRunner.js';
+import { ServerError } from '../../../lib/errorHandler.js';
+import { getSeries } from '../series.js';
+import { listIssues, updateStageWithLatest } from '../issues.js';
+import {
+ buildBeatContinuityContext,
+ buildBeatContinuityResolveContext,
+ shapeVerifyIssues,
+ shapeFindings,
+ shapeBeatResolutions,
+} from './context.js';
+
+// Cross-issue BEAT continuity pass over the whole series. Read-only — returns
+// `{ issues }` shaped like verifyArc. Issues without beats are reviewed at
+// synopsis depth (renderVolumeIssue falls back), so a partially-expanded series
+// is still checkable.
+export async function analyzeBeatContinuity(seriesId, options = {}) {
+ const series = await getSeries(seriesId);
+ if (!series.arc) {
+ throw new ServerError(
+ 'Series has no arc — run /arc/generate first before checking beat continuity',
+ { status: 400, code: 'PIPELINE_NO_ARC' },
+ );
+ }
+ const ctx = await buildBeatContinuityContext(series, options.preloadedWorld);
+ const { content, runId, providerId, model } = await runStagedLLM(
+ 'pipeline-beat-continuity',
+ ctx,
+ {
+ providerOverride: options.providerOverride,
+ modelOverride: options.modelOverride,
+ returnsJson: true,
+ source: 'pipeline-beat-continuity',
+ },
+ );
+ const issues = shapeVerifyIssues(content?.issues);
+ return { issues, raw: content, runId, providerId, model };
+}
+
+/**
+ * Auto-resolve beat-continuity findings by rewriting the offending issues'
+ * BEATS in place. Unlike `resolveVerifyIssues` (which rewrites the arc + season
+ * synopses and clears beats for regeneration), this edits only `idea.output`,
+ * the right altitude for a beat-level finding — so it converges WITHOUT
+ * re-running the beat-sheet generation step and never touches the arc/seasons.
+ *
+ * `options.findings` empty/omitted → run analyzeBeatContinuity first and resolve
+ * whatever it returns.
+ */
+export async function resolveBeatContinuity(seriesId, options = {}) {
+ const series = await getSeries(seriesId);
+ if (!series.arc) {
+ throw new ServerError(
+ 'Series has no arc to resolve — run /arc/generate first',
+ { status: 400, code: 'PIPELINE_NO_ARC' },
+ );
+ }
+
+ let findings = shapeFindings(options.findings);
+ if (!findings.length) {
+ const fresh = await analyzeBeatContinuity(seriesId, options);
+ findings = fresh.issues || [];
+ if (!findings.length) {
+ return { series, applied: false, notes: 'No findings to resolve', episodesResolved: [] };
+ }
+ }
+
+ const ctx = await buildBeatContinuityResolveContext(series, findings, options.preloadedWorld);
+ const { content, runId, providerId, model } = await runStagedLLM(
+ 'pipeline-beat-continuity-resolve',
+ ctx,
+ {
+ providerOverride: options.providerOverride,
+ modelOverride: options.modelOverride,
+ returnsJson: true,
+ source: 'pipeline-beat-continuity-resolve',
+ },
+ );
+
+ const episodesResolved = await applyBeatResolutions(
+ seriesId,
+ series,
+ shapeBeatResolutions(content?.episodes),
+ );
+ const notes = typeof content?.notes === 'string' ? content.notes.trim().slice(0, 2000) : '';
+ return { series, applied: true, notes, findings, episodesResolved, runId, providerId, model };
+}
+
+/**
+ * Apply the resolver's per-issue beat rewrites to the canonical issue records.
+ * Each correction targets one issue by its series-global episode number (with
+ * `seasonNumber` as a disambiguating cross-check, mirroring
+ * `applyEpisodeResolutions`). Writes the new beats to `idea.output` while
+ * preserving the existing `idea.input` synopsis.
+ *
+ * Three guards: a locked `idea` stage is left untouched (the user froze it); an
+ * issue that has NO beats yet is skipped (the corpus is beat-level — fabricating
+ * beats for a still-synopsis-only issue would be out of band, and a later
+ * beat-sheet run would overwrite them anyway); an unmatched correction is
+ * dropped with a log so a number-scheme mismatch is diagnosable. Never throws.
+ * Returns `[{ issueId, number, seasonNumber, corrected, skipped }]`.
+ */
+export async function applyBeatResolutions(seriesId, series, episodes) {
+ if (!Array.isArray(episodes) || episodes.length === 0) return [];
+ const issues = await listIssues({ seriesId });
+ const seasonIdByNumber = new Map(
+ (series?.seasons || []).filter((s) => Number.isInteger(s?.number)).map((s) => [s.number, s.id]),
+ );
+ const applied = [];
+ for (const edit of episodes) {
+ const wantSeasonId = edit.seasonNumber != null ? seasonIdByNumber.get(edit.seasonNumber) : null;
+ // Require the season match when a resolvable season was named — a bare
+ // number fallback could rewrite the wrong season's issue (see the same
+ // reasoning in applyEpisodeResolutions). Fail safe to `no-match`.
+ const issue = wantSeasonId
+ ? issues.find((i) => i.number === edit.episodeNumber && i.seasonId === wantSeasonId)
+ : issues.find((i) => i.number === edit.episodeNumber);
+ if (!issue) {
+ console.log(`⚠️ beat-continuity: no issue matched beat correction (season ${edit.seasonNumber}, episode ${edit.episodeNumber})`);
+ applied.push({ seasonNumber: edit.seasonNumber, episodeNumber: edit.episodeNumber, skipped: 'no-match' });
+ continue;
+ }
+ if (issue.stages?.idea?.locked === true) {
+ applied.push({ issueId: issue.id, number: issue.number, seasonNumber: edit.seasonNumber, skipped: 'locked' });
+ continue;
+ }
+ if (!(issue.stages?.idea?.output && issue.stages.idea.output.trim())) {
+ applied.push({ issueId: issue.id, number: issue.number, seasonNumber: edit.seasonNumber, skipped: 'no-beats' });
+ continue;
+ }
+ await updateStageWithLatest(issue.id, 'idea', () => ({
+ output: edit.beats,
+ status: 'ready',
+ errorMessage: '',
+ })).catch((err) => {
+ console.log(`⚠️ beat-continuity: episode ${edit.episodeNumber} beat edit failed: ${err.message}`);
+ });
+ applied.push({ issueId: issue.id, number: issue.number, seasonNumber: edit.seasonNumber, corrected: true });
+ }
+ if (applied.length) {
+ const fixed = applied.filter((a) => a.corrected).length;
+ console.log(`📝 beat-continuity: corrected ${fixed} episode beat sheet(s) for series ${seriesId.slice(0, 12)}`);
+ }
+ return applied;
+}
diff --git a/server/services/pipeline/arcPlanner/context.js b/server/services/pipeline/arcPlanner/context.js
index 425e13d9d7..a736937bfc 100644
--- a/server/services/pipeline/arcPlanner/context.js
+++ b/server/services/pipeline/arcPlanner/context.js
@@ -579,6 +579,109 @@ export async function buildResolveContext(series, findings, preloadedWorld) {
};
}
+// ---------------------------------------------------------------------------
+// Whole-manuscript BEAT-level continuity pass (#1510).
+//
+// verifyArc checks SYNOPSIS depth across the whole arc; verifyVolume checks
+// BEAT depth within ONE volume. The missing altitude was a whole-BOOK beat
+// pass — cross-issue beat defects (an unresolved cliffhanger, a finale that
+// drifts from the arc's intended ending, a promised through-line that never
+// lands, an event staged as "first" in two issues) only surfaced AFTER full
+// scripts existed (the most expensive stage). These builders feed the per-issue
+// beat sheets (idea.output) for the whole series as the corpus — compact enough
+// that the whole book fits a normal window, so no chunking. Leaves carry `beats`
+// where present (via renderVolumeIssue) and fall back to `synopsis`, so a
+// partially-expanded series is still checkable mid-workflow.
+// ---------------------------------------------------------------------------
+
+// Render the season→issue tree with beat-bearing leaves and report how many
+// issues actually carry beats, so the conductor/prompt can tell a real beat
+// corpus from a synopsis-only one. Shared by the verify and resolve contexts.
+async function buildBeatTree(series, preloadedWorld) {
+ const seasons = sanitizeSeasonList(series.seasons || []);
+ const [issues, base, canon] = await Promise.all([
+ listIssues({ seriesId: series.id }),
+ buildArcBaseContext(series, preloadedWorld),
+ getSeriesCanon(series),
+ ]);
+ const issuesBySeason = new Map();
+ for (const iss of issues) {
+ const key = iss.seasonId || null;
+ if (!issuesBySeason.has(key)) issuesBySeason.set(key, []);
+ issuesBySeason.get(key).push(iss);
+ }
+ let beatBearing = 0;
+ const renderList = (list) => list
+ .slice()
+ .sort(compareIssuesByPosition)
+ .map((iss) => {
+ const leaf = renderVolumeIssue(iss);
+ if (leaf.beats) beatBearing += 1;
+ return leaf;
+ });
+ const tree = seasons.map((s) => ({
+ number: s.number,
+ title: s.title,
+ logline: s.logline,
+ synopsis: s.synopsis,
+ endingHook: s.endingHook,
+ episodeCountTarget: s.episodeCountTarget,
+ themes: s.themes,
+ episodes: renderList(issuesBySeason.get(s.id) || []),
+ }));
+ const ungrouped = issuesBySeason.get(null) || [];
+ if (ungrouped.length) {
+ tree.push({ number: null, title: '(ungrouped issues)', episodes: renderList(ungrouped) });
+ }
+ return { base, canon, tree, beatBearing };
+}
+
+export async function buildBeatContinuityContext(series, preloadedWorld) {
+ const { base, canon, tree, beatBearing } = await buildBeatTree(series, preloadedWorld);
+ return {
+ ...base,
+ seasonsTreeJson: JSON.stringify(tree, null, 2),
+ beatBearingCount: beatBearing,
+ existingCharactersJson: JSON.stringify(canon.characters, null, 2),
+ existingPlacesJson: JSON.stringify(canon.places, null, 2),
+ existingObjectsJson: JSON.stringify(canon.objects, null, 2),
+ };
+}
+
+export async function buildBeatContinuityResolveContext(series, findings, preloadedWorld) {
+ const ctx = await buildBeatContinuityContext(series, preloadedWorld);
+ return { ...ctx, findingsJson: JSON.stringify(findings, null, 2) };
+}
+
+// Max beat corrections an auto-resolve pass may apply in one round (mirrors
+// RESOLVE_EPISODE_MAX) so a runaway LLM response can't rewrite every issue's
+// beats in a single convergence step.
+export const RESOLVE_BEAT_MAX = 50;
+
+/**
+ * Shape the beat-continuity resolver's `episodes[]` output — a SPARSE list of
+ * per-issue BEAT rewrites (vs `shapeEpisodeResolutions`'s synopsis rewrites).
+ * Each entry needs an integer `episodeNumber` and non-empty `beats`;
+ * `seasonNumber` is optional disambiguation. Malformed entries are dropped.
+ */
+export function shapeBeatResolutions(rawEpisodes) {
+ if (!Array.isArray(rawEpisodes)) return [];
+ const out = [];
+ for (const raw of rawEpisodes) {
+ const beats = typeof raw?.beats === 'string' ? raw.beats.trim() : '';
+ const episodeNumber = Number(raw?.episodeNumber);
+ if (!beats || !Number.isInteger(episodeNumber)) continue;
+ const seasonNumberRaw = Number(raw?.seasonNumber);
+ out.push({
+ seasonNumber: Number.isInteger(seasonNumberRaw) ? seasonNumberRaw : null,
+ episodeNumber,
+ beats: beats.slice(0, STAGE_INPUT_MAX),
+ });
+ if (out.length >= RESOLVE_BEAT_MAX) break;
+ }
+ return out;
+}
+
export const RESOLVE_FINDING_MAX = 50;
export function shapeFindings(rawFindings) {
diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.js
index f623951b99..768db6698f 100644
--- a/server/services/pipeline/seriesAutopilot.js
+++ b/server/services/pipeline/seriesAutopilot.js
@@ -85,6 +85,8 @@ import {
commitEpisodesToIssues,
verifyArc,
resolveVerifyIssues,
+ analyzeBeatContinuity,
+ resolveBeatContinuity,
analyzeManuscriptCompleteness,
} from './arcPlanner.js';
import * as volumeBeatsRunner from './volumeBeatsRunner.js';
@@ -109,6 +111,11 @@ const runs = new Map();
// run can override per-run through the autopilot start options).
export const MAX_ARC_VERIFY_ROUNDS = 3;
export const MAX_EDITORIAL_ROUNDS = 2;
+// Whole-manuscript beat-continuity convergence (#1510). The corpus is the
+// compact per-issue beat sheets, so this gate sits between beat generation and
+// the expensive text/script stage — bounded like the others, then pauses with
+// the residual findings for human review.
+export const MAX_BEAT_CONTINUITY_ROUNDS = 2;
// Resolve the effective round bounds for a run: an explicit per-run option wins,
// then the persisted pipelineEditorialChecks setting, then the module default.
@@ -124,6 +131,7 @@ export function resolveAutopilotRounds(options = {}, settings = null) {
return {
maxArcVerifyRounds: pick('maxArcVerifyRounds', 'maxArcVerifyRounds', MAX_ARC_VERIFY_ROUNDS),
maxEditorialRounds: pick('maxEditorialRounds', 'maxEditorialRounds', MAX_EDITORIAL_ROUNDS),
+ maxBeatContinuityRounds: pick('maxBeatContinuityRounds', 'maxBeatContinuityRounds', MAX_BEAT_CONTINUITY_ROUNDS),
};
}
@@ -131,6 +139,7 @@ export function resolveAutopilotRounds(options = {}, settings = null) {
// editorial loops so the two messages can't drift.
const PAUSE_GATES = {
arc: { label: 'Arc verification', fix: 'Edit the arc/volumes to address them', limit: 'verify-rounds' },
+ beatContinuity: { label: 'Beat continuity', fix: 'Edit the affected issue beats', limit: 'beat-continuity-rounds' },
editorial: { label: 'Editorial review', fix: 'Address them in the manuscript editor', limit: 'editorial-rounds' },
};
function convergencePauseReason(gate, maxRounds, blockingCount) {
@@ -149,6 +158,10 @@ export const VISUAL_DRAFT_ENABLED = true;
// Severities that block a verify/review gate (low is informational).
const ARC_BLOCKING = new Set(['high', 'medium']);
+// Beat continuity is the same class of structural continuity gate as arc verify
+// (a cross-issue continuity break, not a craft note), so it blocks at the same
+// altitude — high + medium.
+const BEAT_CONTINUITY_BLOCKING = ARC_BLOCKING;
const EDITORIAL_BLOCKING = new Set(['high']);
// Poll cadence while awaiting a delegated child runner (volume beats / auto-run).
@@ -235,6 +248,14 @@ function textReady(issue, series, options = {}) {
return requiredScriptStages(series, options).every((stageId) => isStageReady(issue.stages?.[stageId]));
}
+// An issue "has beats" once its idea stage carries expanded beat text
+// (idea.output) — the unit the whole-manuscript beat-continuity pass (#1510)
+// reads. isStageReady(idea) is exactly that: status ready/edited AND non-empty
+// output.
+function issueHasBeats(issue) {
+ return isStageReady(issue?.stages?.idea);
+}
+
// Structural script gate (pure): does the comic script parse into >=1 page with
// >=1 panel? Cheap, no LLM — this is the Phase-1 "verify the scripts work".
export function scriptStructurallyReady(issue) {
@@ -328,6 +349,18 @@ export function resolveNextStep(series, issues, runState = {}, options = {}) {
}
}
+ // STEP 4a.5 — whole-manuscript beat continuity (#1510). Once every volume's
+ // beats exist (the 4a loop above is exhausted), run ONE cross-issue beat-level
+ // pass BEFORE the expensive text/script generation — catching dropped
+ // cliffhangers, finale drift, unlanded through-lines, and duplicated "firsts"
+ // at the cheap beat altitude instead of after 24 full scripts exist. Only
+ // meaningful when at least one issue actually carries beats; a synopsis-only
+ // run has nothing beat-level to check (and would just duplicate arc verify),
+ // so it's skipped without ever marking the gate.
+ if (!runState.beatContinuityChecked && ordered.some(issueHasBeats)) {
+ return { kind: 'beatContinuity', reason: 'whole-manuscript beat continuity not yet checked this run' };
+ }
+
// STEP 4b — per-issue text stages (prose + required scripts).
for (const issue of ordered) {
if (setHas(runState.textAttempted, issue.id)) continue;
@@ -532,6 +565,56 @@ async function runArcVerify(seriesId, record) {
return {};
}
+// Whole-manuscript beat-continuity convergence loop (#1510). Mirrors
+// runArcVerify one altitude down: verify the whole-book beat corpus, and on
+// blocking findings resolve them by rewriting the offending issues' beats in
+// place (resolveBeatContinuity → applyBeatResolutions, no beat-sheet
+// regeneration), then re-verify. Bounded; pauses with the residual on
+// non-convergence. Each verify + each resolve is budget-gated and bills one cos
+// action, like the arc loop.
+async function runBeatContinuity(seriesId, record) {
+ const maxRounds = Number.isInteger(record.options.maxBeatContinuityRounds)
+ ? record.options.maxBeatContinuityRounds
+ : MAX_BEAT_CONTINUITY_ROUNDS;
+ // maxRounds === 0 means "skip the beat-continuity gate entirely".
+ if (maxRounds === 0) {
+ record.runState.beatContinuityChecked = true;
+ return {};
+ }
+ for (let round = 1; round <= maxRounds; round += 1) {
+ if (record.cancelRequested) return { canceled: true };
+ const beforeVerify = await budgetPause();
+ if (beforeVerify) return beforeVerify;
+ const { issues } = await analyzeBeatContinuity(seriesId, providerOverrideOpts(record));
+ await recordDomainUsage('cos', { actions: 1 });
+ const blocking = issues.filter((i) => BEAT_CONTINUITY_BLOCKING.has(i.severity));
+ broadcast(seriesId, {
+ type: 'verify:round', scope: 'beatContinuity', round, findings: issues.length, blocking: blocking.length,
+ });
+ if (blocking.length === 0) {
+ record.runState.beatContinuityChecked = true;
+ return {};
+ }
+ if (round === maxRounds) {
+ return { pause: true, reason: convergencePauseReason('beatContinuity', maxRounds, blocking.length), residual: blocking };
+ }
+ if (record.cancelRequested) return { canceled: true };
+ // resolveBeatContinuity bills another action — recheck the budget so a
+ // single step can't overspend the daily cap mid-loop.
+ const beforeResolve = await budgetPause();
+ if (beforeResolve) return beforeResolve;
+ const resolved = await resolveBeatContinuity(seriesId, { findings: blocking, ...providerOverrideOpts(record) });
+ await recordDomainUsage('cos', { actions: 1 });
+ broadcast(seriesId, {
+ type: 'resolve:round', scope: 'beatContinuity', round,
+ episodesEdited: Array.isArray(resolved?.episodesResolved)
+ ? resolved.episodesResolved.filter((e) => e?.corrected).length
+ : 0,
+ });
+ }
+ return {};
+}
+
// Delegate to a child SSE runner and block until it finishes: mark the work as
// attempted (so a perpetually-failing child can't loop the resolver), start it,
// expose it as activeChild for responsive cancel, poll to completion, then bill
@@ -998,6 +1081,8 @@ async function dispatchStep(sId, step, record) {
return runArcVerify(sId, record);
case 'beatSheet':
return runBeats(sId, step.seasonId, record);
+ case 'beatContinuity':
+ return runBeatContinuity(sId, record);
case 'textStages':
return runText(step.issueId, record);
case 'scriptVerify':
@@ -1040,6 +1125,16 @@ function buildDryRunPlan(series, issues, options) {
const beatsNeeded = seasons.filter((s) =>
ordered.some((i) => i.seasonId === s.id && !isStageReady(i.stages?.idea))).length;
if (beatsNeeded) plan.push({ kind: 'beatSheet', count: beatsNeeded });
+ // beatContinuity (#1510) runs once when the run will have a beat corpus to
+ // check: beats already exist, OR beatSheet will generate them this run. Mirror
+ // the resolver's `ordered.some(issueHasBeats)` gate (post-generation), so a
+ // synopsis-only run that produces no beats doesn't advertise a pass it skips.
+ if (ordered.some(issueHasBeats) || beatsNeeded) {
+ const bcRounds = Number.isInteger(options?.maxBeatContinuityRounds)
+ ? options.maxBeatContinuityRounds
+ : MAX_BEAT_CONTINUITY_ROUNDS;
+ plan.push({ kind: 'beatContinuity', count: 1, note: roundsNote(bcRounds) });
+ }
const textNeeded = ordered.filter((i) => !textReady(i, series, options)).length;
if (textNeeded) plan.push({ kind: 'textStages', count: textNeeded });
if (wantsComic(series, options)) plan.push({ kind: 'scriptVerify', count: ordered.length });
@@ -1111,6 +1206,7 @@ export async function startSeriesAutopilot(sId, options = {}) {
runState: {
arcAttempted: false,
arcVerified: false,
+ beatContinuityChecked: false,
editorialReviewed: false,
editorialChecksReviewed: false,
editorialHealthReady: false,
@@ -1180,6 +1276,7 @@ export async function startSeriesAutopilot(sId, options = {}) {
// hold even when the budget is exhausted (otherwise the run pauses on
// budget instead of skipping).
const zeroRoundSkip = (step.kind === 'verifyArc' && runOptions.maxArcVerifyRounds === 0)
+ || (step.kind === 'beatContinuity' && runOptions.maxBeatContinuityRounds === 0)
|| (step.kind === 'editorialReview' && runOptions.maxEditorialRounds === 0);
if (step.kind !== 'editorialChecks' && step.kind !== 'editorialHealthGate' && !zeroRoundSkip) {
const budget = await getDomainBudgetStatus('cos');
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index a653853c8a..a7eb90afb8 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -37,6 +37,7 @@ vi.mock('../domainUsage.js', () => ({
// arcPlanner: keep the REAL barrel (for compareIssuesByPosition) and override
// only the LLM-calling passes with spies whose return values the tests drive.
let verifyFindings = [];
+let beatContinuityFindings = [];
let editorialFindings = [];
const arcSpies = {
generateArcOverview: vi.fn(async () => ({ arc: { logline: 'A', summary: 'S' }, seasons: [] })),
@@ -45,6 +46,8 @@ const arcSpies = {
commitEpisodesToIssues: vi.fn(async () => []),
verifyArc: vi.fn(async () => ({ issues: verifyFindings })),
resolveVerifyIssues: vi.fn(async () => ({ applied: true })),
+ analyzeBeatContinuity: vi.fn(async () => ({ issues: beatContinuityFindings })),
+ resolveBeatContinuity: vi.fn(async () => ({ applied: true, episodesResolved: [] })),
analyzeManuscriptCompleteness: vi.fn(async () => ({ issues: editorialFindings, runId: 'run-comp' })),
};
vi.mock('./arcPlanner.js', async (importOriginal) => {
@@ -117,6 +120,7 @@ const seriesSvc = await import('./series.js');
const seasonsSvc = await import('./seasons.js');
const issuesSvc = await import('./issues.js');
const autopilot = await import('./seriesAutopilot.js');
+const arcPlanner = await import('./arcPlanner.js');
const { resolveNextStep, requiredScriptStages, scriptStructurallyReady, visualReady, wantsComic } = autopilot;
// A comic script string that parseComicScript turns into >=1 page/panel.
@@ -141,6 +145,7 @@ beforeEach(() => {
cosMode = 'execute';
budgetStatus = { withinBudget: true, exceeded: null };
verifyFindings = [];
+ beatContinuityFindings = [];
editorialFindings = [];
scriptVerifyFindings = [];
canonReady = true;
@@ -176,19 +181,20 @@ describe('resolveNextStep (pure)', () => {
});
it('resolveAutopilotRounds: per-run option wins, else setting, else default', () => {
- const { resolveAutopilotRounds, MAX_ARC_VERIFY_ROUNDS, MAX_EDITORIAL_ROUNDS } = autopilot;
+ const { resolveAutopilotRounds, MAX_ARC_VERIFY_ROUNDS, MAX_EDITORIAL_ROUNDS, MAX_BEAT_CONTINUITY_ROUNDS } = autopilot;
// per-run option wins (including an explicit 0 = skip)
expect(resolveAutopilotRounds(
- { maxArcVerifyRounds: 7, maxEditorialRounds: 0 },
- { pipelineEditorialChecks: { maxArcVerifyRounds: 4, maxEditorialRounds: 4 } },
- )).toEqual({ maxArcVerifyRounds: 7, maxEditorialRounds: 0 });
+ { maxArcVerifyRounds: 7, maxEditorialRounds: 0, maxBeatContinuityRounds: 5 },
+ { pipelineEditorialChecks: { maxArcVerifyRounds: 4, maxEditorialRounds: 4, maxBeatContinuityRounds: 1 } },
+ )).toEqual({ maxArcVerifyRounds: 7, maxEditorialRounds: 0, maxBeatContinuityRounds: 5 });
// persisted setting fills in when no per-run override
- const fromSetting = resolveAutopilotRounds({}, { pipelineEditorialChecks: { maxArcVerifyRounds: 6 } });
+ const fromSetting = resolveAutopilotRounds({}, { pipelineEditorialChecks: { maxArcVerifyRounds: 6, maxBeatContinuityRounds: 3 } });
expect(fromSetting.maxArcVerifyRounds).toBe(6);
expect(fromSetting.maxEditorialRounds).toBe(MAX_EDITORIAL_ROUNDS);
+ expect(fromSetting.maxBeatContinuityRounds).toBe(3);
// module default when neither is set
expect(resolveAutopilotRounds({}, null)).toEqual({
- maxArcVerifyRounds: MAX_ARC_VERIFY_ROUNDS, maxEditorialRounds: MAX_EDITORIAL_ROUNDS,
+ maxArcVerifyRounds: MAX_ARC_VERIFY_ROUNDS, maxEditorialRounds: MAX_EDITORIAL_ROUNDS, maxBeatContinuityRounds: MAX_BEAT_CONTINUITY_ROUNDS,
});
// a non-integer at any layer falls through
expect(resolveAutopilotRounds(
@@ -245,8 +251,24 @@ describe('resolveNextStep (pure)', () => {
expect(step).toMatchObject({ kind: 'textStages', issueId: 'iss1' });
});
- it('asks for text stages once beats exist but scripts do not', () => {
+ it('runs whole-manuscript beat continuity once beats exist, before text (#1510)', () => {
const step = resolveNextStep(comic, [issue({ stages: { idea: ready() } })], { arcVerified: true });
+ expect(step).toMatchObject({ kind: 'beatContinuity' });
+ });
+
+ it('skips beat continuity for a synopsis-only run (no beats anywhere)', () => {
+ // idea has input (synopsis) but no ready output → no beats → fall through to
+ // text without a beat-continuity pass (it would just duplicate arc verify).
+ const step = resolveNextStep(
+ comic,
+ [issue({ stages: { idea: { status: 'empty', input: 'syn', output: '' }, comicScript: ready(VALID_SCRIPT) } })],
+ { arcVerified: true },
+ );
+ expect(step.kind).not.toBe('beatContinuity');
+ });
+
+ it('asks for text stages once beats are continuity-checked but scripts do not exist', () => {
+ const step = resolveNextStep(comic, [issue({ stages: { idea: ready() } })], { arcVerified: true, beatContinuityChecked: true });
expect(step).toMatchObject({ kind: 'textStages', issueId: 'iss1' });
});
@@ -254,7 +276,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
- { arcVerified: true },
+ { arcVerified: true, beatContinuityChecked: true },
);
expect(step).toMatchObject({ kind: 'scriptVerify', issueId: 'iss1' });
});
@@ -263,7 +285,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
- { arcVerified: true, scriptChecked: new Set(['iss1']) },
+ { arcVerified: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']) },
);
expect(step.kind).toBe('editorialReview');
});
@@ -272,7 +294,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
- { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true },
+ { arcVerified: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']), editorialReviewed: true },
{ includeVisual: false },
);
expect(step.kind).toBe('editorialChecks');
@@ -282,7 +304,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
- { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true },
+ { arcVerified: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true },
{ includeVisual: false },
);
expect(step.kind).toBe('editorialHealthGate');
@@ -292,7 +314,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
- { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true, editorialHealthReady: true },
+ { arcVerified: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true, editorialHealthReady: true },
{ includeVisual: false },
);
expect(step.kind).toBe('done');
@@ -302,7 +324,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
- { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true, editorialHealthReady: true },
+ { arcVerified: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true, editorialHealthReady: true },
{ includeVisual: true, target: 'text' },
);
expect(step.kind).toBe('done');
@@ -312,7 +334,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
- { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true, editorialHealthReady: true },
+ { arcVerified: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true, editorialHealthReady: true },
{ includeVisual: true },
);
expect(step.kind).toBe('canonVerify');
@@ -322,7 +344,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
- { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true, editorialHealthReady: true, canonVerified: true },
+ { arcVerified: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true, editorialHealthReady: true, canonVerified: true },
{ includeVisual: true },
);
expect(step).toMatchObject({ kind: 'visualDraft', issueId: 'iss1' });
@@ -341,7 +363,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: renderedStages })],
- { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true, editorialHealthReady: true, canonVerified: true },
+ { arcVerified: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true, editorialHealthReady: true, canonVerified: true },
{ includeVisual: true },
);
expect(step.kind).toBe('done');
@@ -352,7 +374,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
tv,
[issue({ stages: { idea: ready(), teleplay: ready() } })],
- { arcVerified: true },
+ { arcVerified: true, beatContinuityChecked: true },
);
expect(step.kind).toBe('editorialReview');
});
@@ -532,6 +554,39 @@ describe('autopilot conductor', () => {
expect(arcSpies.resolveVerifyIssues).not.toHaveBeenCalled();
});
+ it('runs whole-manuscript beat continuity before text, then proceeds when clean (#1510)', async () => {
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, {});
+ await waitFor(runFinished(seriesId));
+ expect(arcSpies.analyzeBeatContinuity).toHaveBeenCalled();
+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('complete');
+ });
+
+ it('pauses for review when beat continuity never converges (#1510)', async () => {
+ beatContinuityFindings = [{ severity: 'high', problem: 'dropped cliffhanger', location: 'issue:1' }];
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, { maxBeatContinuityRounds: 2 });
+ await waitFor(runFinished(seriesId));
+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
+ expect(last?.type).toBe('paused');
+ expect(last?.scope).toBe('beatContinuity');
+ // bounded: analyze called maxRounds times, resolve called rounds-1.
+ expect(arcSpies.analyzeBeatContinuity).toHaveBeenCalledTimes(2);
+ expect(arcSpies.resolveBeatContinuity).toHaveBeenCalledTimes(1);
+ expect(last?.residualFindings?.[0]?.problem).toBe('dropped cliffhanger');
+ // never reached the text stage — the gate is upstream of it.
+ expect(autoRunnerSpies.startAutoRunTextStages).not.toHaveBeenCalled();
+ });
+
+ it('maxBeatContinuityRounds:0 skips the beat-continuity gate (no LLM spend)', async () => {
+ beatContinuityFindings = [{ severity: 'high', problem: 'dropped cliffhanger', location: 'issue:1' }];
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, { maxBeatContinuityRounds: 0 });
+ await waitFor(runFinished(seriesId));
+ expect(arcSpies.analyzeBeatContinuity).not.toHaveBeenCalled();
+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('complete');
+ });
+
it('pauses (no infinite loop) when episode generation produces no issues', async () => {
const series = await seriesSvc.createSeries({ name: 'S', logline: 'L', premise: 'P', targetFormat: 'comic' });
await seriesSvc.updateSeries(series.id, { arc: { logline: 'A', summary: 'S' } });
@@ -591,15 +646,16 @@ describe('autopilot conductor', () => {
it('a zero-round gate skips even when the budget is exhausted (no budget pause at that gate)', async () => {
budgetStatus = { withinBudget: false, exceeded: 'actions' };
const { seriesId } = await seedComplete();
- // maxArcVerifyRounds:0 ⇒ runArcVerify short-circuits with no spend, so the
- // budget gate must NOT pause at verifyArc — the run advances to the next
- // non-exempt step (scriptVerify) and pauses there on budget instead.
- await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 0 });
+ // maxArcVerifyRounds:0 + maxBeatContinuityRounds:0 ⇒ both gates short-circuit
+ // with no spend, so the budget gate must NOT pause at either — the run
+ // advances to the next non-exempt step (scriptVerify) and pauses there.
+ await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 0, maxBeatContinuityRounds: 0 });
await waitFor(runFinished(seriesId));
expect(arcSpies.verifyArc).not.toHaveBeenCalled();
+ expect(arcSpies.analyzeBeatContinuity).not.toHaveBeenCalled();
const series = await seriesSvc.getSeries(seriesId);
expect(series.autopilot?.status).toBe('paused');
- expect(series.autopilot?.currentStep).toBe('scriptVerify'); // not 'verifyArc'
+ expect(series.autopilot?.currentStep).toBe('scriptVerify'); // not 'verifyArc'/'beatContinuity'
expect(series.autopilot?.lastError).toMatch(/budget/);
});
@@ -798,3 +854,84 @@ describe('autopilot conductor', () => {
expect(fresh.autopilot?.status).toBe('paused');
});
});
+
+// ---------------------------------------------------------------------------
+// Beat-continuity resolve internals (#1510) — pure shaper + the beat-rewrite
+// apply pass (real issues service against the file store, like the conductor).
+// ---------------------------------------------------------------------------
+describe('beat-continuity resolve (#1510)', () => {
+ const { shapeBeatResolutions, applyBeatResolutions, buildBeatContinuityContext } = arcPlanner.__testing;
+
+ it('buildBeatContinuityContext renders beats into the tree and counts beat-bearing issues', async () => {
+ const series = await seriesSvc.createSeries({ name: 'S', logline: 'L', premise: 'P', targetFormat: 'comic' });
+ await seriesSvc.updateSeries(series.id, { arc: { logline: 'A', summary: 'Sum' } });
+ const season = await seasonsSvc.createSeason(series.id, { number: 1, title: 'V1' });
+ const withBeats = await issuesSvc.createIssue({ seriesId: series.id, seasonId: season.id, title: 'I1', number: 1 });
+ const synOnly = await issuesSvc.createIssue({ seriesId: series.id, seasonId: season.id, title: 'I2', number: 2 });
+ await issuesSvc.updateStage(withBeats.id, 'idea', { status: 'ready', input: 'syn1', output: 'BEATS-A' });
+ await issuesSvc.updateStage(synOnly.id, 'idea', { status: 'empty', input: 'syn2', output: '' });
+ const fresh = await seriesSvc.getSeries(series.id);
+ const ctx = await buildBeatContinuityContext(fresh);
+ expect(ctx.beatBearingCount).toBe(1); // only the one expanded issue
+ expect(ctx.seasonsTreeJson).toContain('BEATS-A');
+ expect(ctx.seasonsTreeJson).toContain('syn2'); // synopsis fallback for the un-expanded issue
+ });
+
+ it('shapeBeatResolutions keeps valid entries, drops malformed, caps the count', () => {
+ const out = shapeBeatResolutions([
+ { episodeNumber: 1, beats: ' new beats ', seasonNumber: 2 },
+ { episodeNumber: 3, beats: '' }, // empty beats → dropped
+ { episodeNumber: 'x', beats: 'b' }, // non-integer number → dropped
+ { beats: 'no number' }, // missing number → dropped
+ { episodeNumber: 4, beats: 'b4' }, // seasonNumber absent → null
+ ]);
+ expect(out).toEqual([
+ { seasonNumber: 2, episodeNumber: 1, beats: 'new beats' },
+ { seasonNumber: null, episodeNumber: 4, beats: 'b4' },
+ ]);
+ expect(shapeBeatResolutions('nope')).toEqual([]);
+ });
+
+ // A single issue in a fresh series gets the recomputed series-global number 1.
+ async function seedIssueWithBeats(over = {}) {
+ const series = await seriesSvc.createSeries({ name: 'S', logline: 'L', premise: 'P', targetFormat: 'comic' });
+ const season = await seasonsSvc.createSeason(series.id, { number: 1, title: 'V1' });
+ const issue = await issuesSvc.createIssue({ seriesId: series.id, seasonId: season.id, title: 'I1', number: 1 });
+ await issuesSvc.updateStage(issue.id, 'idea', { status: 'ready', input: 'synopsis', output: 'old beats', ...over });
+ const fresh = await seriesSvc.getSeries(series.id);
+ return { series: fresh, issueId: issue.id };
+ }
+
+ it('rewrites beats in place and preserves the synopsis input', async () => {
+ const { series, issueId } = await seedIssueWithBeats();
+ const applied = await applyBeatResolutions(series.id, series, [{ seasonNumber: 1, episodeNumber: 1, beats: 'corrected beats' }]);
+ expect(applied).toEqual([expect.objectContaining({ issueId, number: 1, corrected: true })]);
+ const issue = await issuesSvc.getIssue(issueId);
+ expect(issue.stages.idea.output).toBe('corrected beats');
+ expect(issue.stages.idea.input).toBe('synopsis'); // synopsis preserved
+ expect(issue.stages.idea.status).toBe('ready');
+ });
+
+ it('skips a locked idea stage', async () => {
+ const { series, issueId } = await seedIssueWithBeats({ locked: true });
+ const applied = await applyBeatResolutions(series.id, series, [{ seasonNumber: 1, episodeNumber: 1, beats: 'corrected' }]);
+ expect(applied[0]).toMatchObject({ skipped: 'locked' });
+ const issue = await issuesSvc.getIssue(issueId);
+ expect(issue.stages.idea.output).toBe('old beats'); // untouched
+ });
+
+ it('skips an issue that has no beats yet (corpus is beat-level)', async () => {
+ const { series } = await seedIssueWithBeats({ status: 'empty', output: '' });
+ const applied = await applyBeatResolutions(series.id, series, [{ seasonNumber: 1, episodeNumber: 1, beats: 'corrected' }]);
+ expect(applied[0]).toMatchObject({ skipped: 'no-beats' });
+ });
+
+ it('drops an unmatched correction rather than rewriting the wrong issue', async () => {
+ const { series, issueId } = await seedIssueWithBeats();
+ // Only episode 1 exists; a correction for episode 99 matches nothing.
+ const applied = await applyBeatResolutions(series.id, series, [{ seasonNumber: 1, episodeNumber: 99, beats: 'corrected' }]);
+ expect(applied[0]).toMatchObject({ skipped: 'no-match' });
+ const issue = await issuesSvc.getIssue(issueId);
+ expect(issue.stages.idea.output).toBe('old beats'); // untouched
+ });
+});