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: retry failed beats/text child runs before escalating to a pause (#1574)

[._.]/ Adam Eivy5d0df34e3a82
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 2db8f9c925..795385be02 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -51,6 +51,7 @@
- **[issue-1558] A per-stage *model* pin now also wins over Series Autopilot's run model — completing the #1514 work.** #1514 made a pinned stage keep its chosen *provider* during an autopilot run, but the run's *model* was still threaded as a hard override, so if you launched a run with both a provider and a model and a stage had its own provider+model pin, that stage ran on the pinned provider but with the *run's* model id — which could be wrong (or invalid) for the pinned provider, and ignored the model you deliberately set on the stage. The autopilot now passes its run model as a soft *default* too, with the same precedence as the provider: an explicit per-call model pick wins, then the stage's own model pin, then the run's model, then the provider's default — so a pinned stage now keeps both its provider *and* its model, while unpinned stages still follow the run's model.
- **[issue-1571] Series Autopilot now stops a verify/editorial loop early when it stops making progress, instead of burning the whole daily budget.** The arc-verification, beat-continuity, and editorial convergence loops auto-resolve their blocking findings and re-check, bounded by a round cap. Previously a loop that wasn't actually improving — a fix that re-introduced a different break, or that just oscillated between the same findings — kept spending AI budget round after round until it hit the cap and paused anyway. The autopilot now watches the blocking-finding count across rounds and, if it stops reaching a new low for two rounds running, pauses immediately with a distinct **"not converging"** state (visible as a badge on the paused panel) so you know it needs a human edit rather than more rounds. Loops that are genuinely making progress, and runs on the default round caps, are unaffected — the early stop only kicks in once a raised cap lets a stalled or oscillating loop keep going.
- **[issue-1573] Series Autopilot now flags editorial checks that errored instead of reporting a silent "clean" run.** Each editorial check runs inside a boundary guard so one bad check (a malformed prompt, a provider timeout, a missing context) can't abort the whole pass — but a check that *threw* produced no findings, and the autopilot's per-pass broadcast always reported "0 blocking" and completed as if everything had run. A check that errored every run looked clean until someone inspected the raw per-check results. The editorial-checks round frame now carries an **errored count + the failing check ids**, and a run that finished with any errored check is qualified on the terminal summary and the persisted status banner (a caution, not "production-ready") so the partial failure is visible — the dimension that errored was never actually evaluated. The standalone "run editorial checks" panel surfaces the same errored aggregate on its completion frame. (`server/services/pipeline/seriesAutopilot.js`, `server/services/pipeline/editorial/checkRunner.js`, `server/services/pipeline/series.js`, `client/src/components/pipeline/AutopilotPanel.jsx`)
+- **[issue-1574] Series Autopilot now retries a failed beats/text child run before giving up, instead of marking it attempted and silently skipping it.** When the autopilot delegates to a child runner (volume beats or per-issue text/scripts), the child can finish with its target stage still empty because the underlying LLM call failed. Previously the work was marked *attempted* before the result was inspected, so the resolver skipped it on the next pass — a failed beats run wasn't caught until a downstream stage tripped over the empty `idea`, and a failed text run only paused after the fact. The autopilot now **verifies the child actually produced its output** (every issue in the volume has a beat sheet / the issue's required script stages landed) and, on a miss, **retries the child once** (skip-existing, so the retry only fills the gap) before marking the work attempted. Each attempt is budget-gated and bills one action like any other step; if the output is still missing after the retry the run emits an escalation frame and **pauses for review with the missing stages as residual findings** rather than marching on toward a "done" with no script. A per-run **`maxChildRetries`** option tunes the retry budget (0 restores the legacy single-attempt behavior). (`server/services/pipeline/seriesAutopilot.js`)
## Providers
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index 872865e6ff..b285c9ca20 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -110,12 +110,13 @@ export const AUTOPILOT_STATUSES = Object.freeze(['idle', 'running', 'paused', 'd
export const AUTOPILOT_STEP_MAX = 80;
export const AUTOPILOT_ERROR_MAX = 1000;
const AUTOPILOT_FINDING_SEVERITIES = ['high', 'medium', 'low'];
-// Why a convergence gate paused the run (#1571): `maxRounds` (the verify→resolve
-// loop ran out of rounds) vs `divergence` (it stopped converging early — the
-// blocking count failed to drop). Lets the UI tell "ran out of rounds" from
-// "needs a human" without string-matching the reason text. Any other pause
-// (budget, error, a capability gap) leaves this null.
-export const AUTOPILOT_PAUSE_KINDS = Object.freeze(['maxRounds', 'divergence']);
+// Why a bounded-retry gate paused the run. Convergence gates (#1571):
+// `maxRounds` (the verify→resolve loop ran out of rounds) vs `divergence` (it
+// stopped converging early — the blocking count failed to drop). Child runners
+// (#1574): `childFailed` (a delegated beats/text run produced no output after
+// its retry budget). Lets the UI classify the pause without string-matching the
+// reason text. Any other pause (budget, error, a capability gap) leaves this null.
+export const AUTOPILOT_PAUSE_KINDS = Object.freeze(['maxRounds', 'divergence', 'childFailed']);
export const sanitizeAutopilot = (raw) => {
if (!raw || typeof raw !== 'object') return null;
diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.js
index 564b2c8f19..f9af8e723c 100644
--- a/server/services/pipeline/seriesAutopilot.js
+++ b/server/services/pipeline/seriesAutopilot.js
@@ -118,6 +118,18 @@ export const MAX_EDITORIAL_ROUNDS = 2;
// the residual findings for human review.
export const MAX_BEAT_CONTINUITY_ROUNDS = 2;
+// Bounded retry budget for a delegated child runner (#1574). A child (volume
+// beats / text auto-run) can finish with its target stage(s) still empty when
+// the underlying LLM call failed. Before #1574 the autopilot marked the work
+// attempted and advanced regardless — so a transient failure was caught only
+// later (text) or not at all until a downstream emptiness check (beats). Now a
+// child whose readiness check fails is retried up to MAX_CHILD_RETRIES more
+// times (skip-existing, so a retry only fills the gap) before the work is
+// marked attempted, an escalation frame is emitted, and the run pauses with the
+// residual. 0 = single attempt, no retry (the legacy behavior). A per-run
+// `maxChildRetries` option overrides it (plumbed through runOptions).
+export const MAX_CHILD_RETRIES = 1;
+
// Resolve the effective round bounds for a run: an explicit per-run option wins,
// then the persisted pipelineEditorialChecks setting, then the module default.
// Returns integers only — a non-integer at any layer falls through to the next.
@@ -698,58 +710,112 @@ async function runBeatContinuity(seriesId, record) {
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
-// one action. Shared by the beats and text steps.
-async function runChildToCompletion(record, { attemptedSet, kind, id, start, isActive }) {
+// Resolve the effective retry budget for a delegated child runner this run: a
+// per-run `maxChildRetries` option wins, else the module default. Negative
+// values clamp to 0 (single attempt).
+function childRetryBudget(record) {
+ const v = record.options.maxChildRetries;
+ return Number.isInteger(v) ? Math.max(0, v) : MAX_CHILD_RETRIES;
+}
+
+// Delegate to a child SSE runner, block until it finishes, then VERIFY the child
+// actually produced its target output before advancing (#1574). Shared by the
+// beats and text steps. `checkReady` returns null when the output landed, or a
+// `{ reason, residual }` describing what's still missing. On a miss the child is
+// retried (skip-existing, so a retry only fills the gap) up to the run's retry
+// budget; each attempt is budget-gated and bills one cos action. When the budget
+// is exhausted the retries stop. If the output is still missing after the last
+// attempt the work is marked attempted (so the resolver can't loop back here), an
+// escalation frame is emitted, and a pause result is returned for human review —
+// instead of the pre-#1574 silent skip that let a failed child reach 'done'.
+async function runChildToCompletion(seriesId, record, {
+ attemptedSet, kind, id, start, isActive, checkReady,
+}) {
+ const maxAttempts = childRetryBudget(record) + 1;
+ let miss = null;
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
+ if (record.cancelRequested) return { canceled: true };
+ // Each child run bills one cos action — budget-gate every attempt so a
+ // retry can't overspend the daily cap (mirrors the verify loops).
+ const beforeStart = await budgetPause();
+ if (beforeStart) return beforeStart;
+ await start();
+ record.activeChild = { kind, id };
+ await waitForChild(() => isActive(id), record);
+ record.activeChild = null;
+ await recordDomainUsage('cos', { actions: 1 });
+ if (record.cancelRequested) return { canceled: true };
+ miss = checkReady ? await checkReady() : null;
+ if (!miss) {
+ attemptedSet.add(id);
+ return {};
+ }
+ if (attempt < maxAttempts) {
+ broadcast(seriesId, {
+ type: 'child:retry', kind, id, attempt, maxAttempts, reason: miss.reason,
+ });
+ }
+ }
+ // Output still missing after every attempt — escalate and pause. `pauseKind`
+ // keeps this pause classifiable alongside the verify/editorial loops'
+ // 'maxRounds'/'divergence' kinds (a child runner that couldn't produce output,
+ // distinct from a convergence gate that ran out of rounds).
attemptedSet.add(id);
- await start();
- record.activeChild = { kind, id };
- await waitForChild(() => isActive(id), record);
- record.activeChild = null;
- await recordDomainUsage('cos', { actions: 1 });
- return {};
+ broadcast(seriesId, {
+ type: 'child:escalate', kind, id, attempts: maxAttempts, reason: miss.reason,
+ });
+ return { pause: true, pauseKind: 'childFailed', reason: miss.reason, residual: miss.residual };
}
-const runBeats = (seriesId, seasonId, record) => runChildToCompletion(record, {
+const runBeats = (seriesId, seasonId, record) => runChildToCompletion(seriesId, record, {
attemptedSet: record.runState.beatsAttempted,
kind: 'beats',
id: seasonId,
start: () => volumeBeatsRunner.startVolumeBeatsRun(seriesId, seasonId, { mode: 'skip-existing', ...providerIdOpts(record) }),
isActive: volumeBeatsRunner.isVolumeBeatsRunActive,
+ // Beats succeeded when every issue in the volume has a ready `idea` stage —
+ // the same predicate the resolver uses to decide a volume still needs beats.
+ // Before #1574 a failed beats run was silently marked attempted and only
+ // surfaced (if at all) when a downstream stage found `idea` empty.
+ checkReady: async () => {
+ const inSeason = (await listIssues({ seriesId })).filter((i) => i.seasonId === seasonId);
+ const missing = inSeason.filter((i) => !isStageReady(i.stages?.idea));
+ if (missing.length === 0) return null;
+ return {
+ reason: `beat generation for volume ${seasonId} did not produce beats for ${missing.length} issue(s)`,
+ residual: missing.map((i) => ({ severity: 'high', location: `issue ${i.number ?? '?'} / idea`, problem: 'beat sheet (idea stage) is still empty after the beats run (likely an LLM failure)' })),
+ };
+ },
});
-async function runText(issueId, record) {
- record.runState.textAttempted.add(issueId);
- // Only adapt the target format's script(s) — a single-format series shouldn't
- // spend LLM calls populating the off-target script across every issue.
- const preIssue = await getIssue(issueId);
- const preSeries = await getSeries(preIssue.seriesId).catch(() => null);
- const scripts = requiredScriptStages(preSeries, record.options);
- // Forward the run's provider/model override so prose + scripts honor it like
- // every other step (autoRunner threads these into generateStage).
- await autoRunner.startAutoRunTextStages(issueId, { force: false, scripts, ...providerIdOpts(record) });
- record.activeChild = { kind: 'text', id: issueId };
- await waitForChild(() => autoRunner.isAutoRunActive(issueId), record);
- record.activeChild = null;
- await recordDomainUsage('cos', { actions: 1 });
+const runText = (seriesId, issueId, record) => runChildToCompletion(seriesId, record, {
+ attemptedSet: record.runState.textAttempted,
+ kind: 'text',
+ id: issueId,
+ start: async () => {
+ // Only adapt the target format's script(s) — a single-format series shouldn't
+ // spend LLM calls populating the off-target script across every issue.
+ const preIssue = await getIssue(issueId);
+ const preSeries = await getSeries(preIssue.seriesId).catch(() => null);
+ const scripts = requiredScriptStages(preSeries, record.options);
+ // Forward the run's provider/model override so prose + scripts honor it like
+ // every other step (autoRunner threads these into generateStage).
+ await autoRunner.startAutoRunTextStages(issueId, { force: false, scripts, ...providerIdOpts(record) });
+ },
+ isActive: autoRunner.isAutoRunActive,
// A delegated text run can end with required stages still empty (the child's
- // LLM call failed). The issue is already marked attempted, so the resolver
- // would skip it and the run could reach 'done' with no script — verify the
- // required stages landed and pause for review if they didn't.
- const issue = await getIssue(issueId);
- const series = await getSeries(issue.seriesId).catch(() => null);
- if (!textReady(issue, series, record.options)) {
+ // LLM call failed) — verify the required stages landed before advancing.
+ checkReady: async () => {
+ const issue = await getIssue(issueId);
+ const series = await getSeries(issue.seriesId).catch(() => null);
+ if (textReady(issue, series, record.options)) return null;
const missing = requiredScriptStages(series, record.options).filter((s) => !isStageReady(issue.stages?.[s]));
return {
- pause: true,
reason: `text generation for issue ${issue.number ?? issueId} did not produce required stage(s): ${missing.join(', ')}`,
residual: missing.map((s) => ({ severity: 'high', location: `issue ${issue.number ?? '?'} / ${s}`, problem: 'stage is still empty after the text run (likely an LLM failure)' })),
};
- }
- return {};
-}
+ },
+});
async function runScriptVerify(sId, issueId, record) {
record.runState.scriptChecked.add(issueId);
@@ -1252,7 +1318,7 @@ async function dispatchStep(sId, step, record) {
case 'beatContinuity':
return runBeatContinuity(sId, record);
case 'textStages':
- return runText(step.issueId, record);
+ return runText(sId, step.issueId, record);
case 'scriptVerify':
return runScriptVerify(sId, step.issueId, record);
case 'editorialReview':
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index 62b78b90cb..f3fa938799 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -750,6 +750,90 @@ describe('autopilot conductor', () => {
expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('complete');
});
+ // -------------------------------------------------------------------------
+ // #1574 — delegated child runners (beats/text) retry on a failed run and
+ // escalate to a pause instead of marking the work attempted and silently
+ // skipping it. The runner spies are no-ops by default, so the target stage
+ // never lands unless a test's mock writes it — exactly the "child LLM call
+ // failed" shape the feature guards against.
+ // -------------------------------------------------------------------------
+ // idea ready but no comicScript → the resolver routes to textStages.
+ async function seedNeedsText() {
+ const series = await seriesSvc.createSeries({ name: 'S', logline: 'L', premise: 'P', targetFormat: 'comic' });
+ await seriesSvc.updateSeries(series.id, { arc: { logline: 'A', summary: 'S' } });
+ 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', ready('beats'));
+ return { seriesId: series.id, seasonId: season.id, issueId: issue.id };
+ }
+ // no idea stage → the resolver routes to beatSheet first.
+ async function seedNeedsBeats() {
+ const series = await seriesSvc.createSeries({ name: 'S', logline: 'L', premise: 'P', targetFormat: 'comic' });
+ await seriesSvc.updateSeries(series.id, { arc: { logline: 'A', summary: 'S' } });
+ 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 });
+ return { seriesId: series.id, seasonId: season.id, issueId: issue.id };
+ }
+
+ it('retries a failed text run once, then escalates with a pause + residual (#1574)', async () => {
+ const { seriesId } = await seedNeedsText(); // default text spy never writes comicScript
+ await autopilot.startSeriesAutopilot(seriesId, {}); // default MAX_CHILD_RETRIES = 1 → 2 attempts
+ await waitFor(runFinished(seriesId));
+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
+ expect(last?.type).toBe('paused');
+ expect(last?.scope).toBe('textStages');
+ expect(last?.pauseKind).toBe('childFailed');
+ expect(last?.reason).toMatch(/did not produce required stage/);
+ // one initial attempt + one retry before the escalation pause.
+ expect(autoRunnerSpies.startAutoRunTextStages).toHaveBeenCalledTimes(2);
+ const series = await seriesSvc.getSeries(seriesId);
+ expect(series.autopilot?.status).toBe('paused');
+ // pauseKind survives sanitizeAutopilot so the resume banner can classify it.
+ expect(series.autopilot?.pauseKind).toBe('childFailed');
+ expect(series.autopilot?.residualFindings?.length).toBeGreaterThan(0);
+ });
+
+ it('a text run that succeeds on the retry proceeds without pausing (#1574)', async () => {
+ const { seriesId } = await seedNeedsText();
+ autoRunnerSpies.startAutoRunTextStages
+ .mockImplementationOnce(async () => ({ runId: 'ar', alreadyRunning: false })) // attempt 1: fails
+ .mockImplementationOnce(async (id) => { // attempt 2: the stage lands
+ await issuesSvc.updateStage(id, 'comicScript', ready(VALID_SCRIPT));
+ return { runId: 'ar2', alreadyRunning: false };
+ });
+ await autopilot.startSeriesAutopilot(seriesId, {});
+ await waitFor(runFinished(seriesId));
+ expect(autoRunnerSpies.startAutoRunTextStages).toHaveBeenCalledTimes(2);
+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('complete');
+ });
+
+ it('maxChildRetries:0 makes a single attempt then pauses (legacy no-retry behavior)', async () => {
+ const { seriesId } = await seedNeedsText();
+ await autopilot.startSeriesAutopilot(seriesId, { maxChildRetries: 0 });
+ await waitFor(runFinished(seriesId));
+ expect(autoRunnerSpies.startAutoRunTextStages).toHaveBeenCalledTimes(1);
+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('paused');
+ });
+
+ it('a per-run maxChildRetries override widens the budget (2 retries → 3 attempts)', async () => {
+ const { seriesId } = await seedNeedsText();
+ await autopilot.startSeriesAutopilot(seriesId, { maxChildRetries: 2 });
+ await waitFor(runFinished(seriesId));
+ expect(autoRunnerSpies.startAutoRunTextStages).toHaveBeenCalledTimes(3);
+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('paused');
+ });
+
+ it('retries a failed beats run once, then escalates with a pause (#1574)', async () => {
+ const { seriesId } = await seedNeedsBeats(); // default beats spy never writes idea
+ await autopilot.startSeriesAutopilot(seriesId, {});
+ await waitFor(runFinished(seriesId));
+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
+ expect(last?.type).toBe('paused');
+ expect(last?.scope).toBe('beatSheet');
+ expect(last?.reason).toMatch(/did not produce beats/);
+ expect(volumeBeatsSpies.startVolumeBeatsRun).toHaveBeenCalledTimes(2);
+ });
+
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' } });