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-1571]): stop autopilot convergence loops early on divergence/oscillation

[._.]/ Adam Eivy724a6c51c583
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d9a77e03be..870aa4e704 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -47,6 +47,7 @@
- **[issue-1349] Series Autopilot now refreshes its scene segmentation before running the scene-based editorial checks, so those checks read the current draft.** The autopilot's scene-aware editorial checks (scene balance, POV justification, cliffhangers, arc transitions) read a cached "reverse outline" of the manuscript's scenes — but the autopilot's own editorial-completeness pass can edit the manuscript earlier in the same run, leaving that segmentation stale. The autopilot now regenerates the reverse outline between the completeness pass and the scene-based checks, so the checks always see the freshly edited draft instead of a pre-edit snapshot. It only spends effort when there's something to do: the refresh is skipped entirely when no scene-based check is enabled, and when the stored segmentation is already current — so a run that doesn't need it costs nothing extra.
- **[issue-1514] A per-stage provider pin now wins over Series Autopilot's run provider on *every* stage, not just script verification.** Pinning a single pipeline stage to a specific provider on the Prompts page already stuck for the script-verification gate, but the autopilot still threaded its run-wide provider as a hard *override* into every other stage it drives — arc generation and verification, episode seeding, prose/comic-script text stages, volume beats, the reverse-outline refresh, the editorial checks and their auto-fixes, and manuscript completeness — so a pin on any of those was silently ignored mid-run. The autopilot now passes its run provider as a soft *default* across all of them: a pinned stage keeps running on its chosen provider, while unpinned stages still follow the run's provider. As a deliberate consequence, when the run's provider is unavailable an unpinned stage now falls through to the active provider instead of failing the run with a "provider unavailable" error. Manual "regenerate with provider X" buttons are unchanged — an explicit per-call pick still wins everywhere.
- **[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.
## Providers
diff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsx
index 9ffb235011..a9f06fdca1 100644
--- a/client/src/components/pipeline/AutopilotPanel.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.jsx
@@ -426,6 +426,14 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
<span className={ap.status === 'paused' ? 'text-port-warning' : ap.status === 'done' ? 'text-port-success' : 'text-port-error'}>
{ap.status === 'paused' ? (ap.currentStep ? `Paused at ${stepLabel(ap.currentStep)}` : 'Paused') : ap.status === 'done' ? 'Last run completed — draft is production-ready' : 'Last run errored'}
</span>
+ {ap.status === 'paused' && ap.pauseKind === 'divergence' ? (
+ <span
+ className="px-1.5 py-0.5 rounded text-[10px] bg-port-warning/15 text-port-warning border border-port-warning/30"
+ title="Auto-resolve stopped reducing blocking findings — needs a human edit, not more rounds"
+ >
+ not converging
+ </span>
+ ) : null}
</div>
{ap.lastError && ap.status !== 'done' ? <p className="text-[11px] text-gray-400 mt-1">{ap.lastError}</p> : null}
<Findings items={ap.residualFindings} />
diff --git a/client/src/components/pipeline/AutopilotPanel.test.jsx b/client/src/components/pipeline/AutopilotPanel.test.jsx
index 0ef3e7cce0..3458ccf9ee 100644
--- a/client/src/components/pipeline/AutopilotPanel.test.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.test.jsx
@@ -130,6 +130,26 @@ describe('AutopilotPanel', () => {
expect(screen.getByRole('button', { name: /resume autopilot/i })).toBeInTheDocument();
});
+ it('flags a divergence pause with a "not converging" badge (#1571)', async () => {
+ renderPanel({
+ id: 's1',
+ targetFormat: 'comic',
+ autopilot: { status: 'paused', currentStep: 'verifyArc', pauseKind: 'divergence' },
+ });
+ await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalled());
+ expect(screen.getByText(/not converging/i)).toBeInTheDocument();
+ });
+
+ it('does not show the "not converging" badge for an ordinary maxRounds pause', async () => {
+ renderPanel({
+ id: 's1',
+ targetFormat: 'comic',
+ autopilot: { status: 'paused', currentStep: 'verifyArc', pauseKind: 'maxRounds' },
+ });
+ await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalled());
+ expect(screen.queryByText(/not converging/i)).not.toBeInTheDocument();
+ });
+
it('ignores a stale terminal frame from a previous run when starting again', async () => {
startPipelineAutopilot.mockResolvedValue({ runId: 'B', mode: 'execute' });
sseLatest = { type: 'complete', runId: 'A' }; // leftover terminal frame from run A
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index 8b2dc538e7..3a54bde36c 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -110,6 +110,12 @@ 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']);
export const sanitizeAutopilot = (raw) => {
if (!raw || typeof raw !== 'object') return null;
@@ -135,6 +141,12 @@ export const sanitizeAutopilot = (raw) => {
currentStep: trimTo(raw.currentStep, AUTOPILOT_STEP_MAX) || null,
residualFindings,
lastError: trimTo(raw.lastError, AUTOPILOT_ERROR_MAX) || null,
+ // No `pipelineSeries` schema-gate bump for this (or any) autopilot field: the
+ // marker is transient, regenerated-every-run status, NOT durable creative
+ // content. Unlike readerMap/styleGuide/characterArcs (gated because an LWW
+ // strip is real data loss), a stale peer that drops pauseKind just briefly
+ // shows a generic "paused" banner until the next run re-stamps it.
+ pauseKind: AUTOPILOT_PAUSE_KINDS.includes(raw.pauseKind) ? raw.pauseKind : null,
updatedAt: isStr(raw.updatedAt) ? raw.updatedAt : null,
};
};
diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.js
index db4b01fb99..b554468f4e 100644
--- a/server/services/pipeline/seriesAutopilot.js
+++ b/server/services/pipeline/seriesAutopilot.js
@@ -150,6 +150,48 @@ function convergencePauseReason(gate, maxRounds, blockingCount) {
+ `paused for review. ${fix}, or raise the ${limit} limit in Options and resume.`;
}
+// Divergence/oscillation guard for the bounded convergence loops (#1571). A
+// verify→resolve round is "profitable" only when the next verify shows STRICTLY
+// FEWER blocking findings. When the count fails to drop (stays equal, or rises —
+// a resolve pass that introduced a new break while fixing another) for
+// DIVERGENCE_PATIENCE consecutive rounds, the loop is no longer converging:
+// stop early and pause with a `divergence` kind instead of burning the rest of
+// the daily cos budget down to maxRounds. The terminal maxRounds pause keeps its
+// own `maxRounds` kind — the two are distinguished in the pause SSE frame so the
+// UI can tell "needs a human" (diverging) from "just ran out of rounds".
+//
+// With the default caps (arc 3 / beat 2 / editorial 2) the loop hits maxRounds
+// before the streak can reach patience, so default runs are unaffected; the
+// guard only bites when a user RAISES a cap and the loop then stalls.
+export const DIVERGENCE_PATIENCE = 2;
+
+// Convergence tracker for one verify→resolve round. `state` is
+// { best, sinceBest }: `best` is the FEWEST blocking findings seen so far this
+// loop (null before the first measured round), `sinceBest` the count of
+// consecutive rounds since that minimum last STRICTLY improved. A round that
+// reaches a new low is progress (sinceBest → 0); a stall, a regression (a fix
+// that introduced a new break), OR an oscillation that merely revisits an old
+// count all accrue sinceBest. The loop diverges once sinceBest reaches
+// DIVERGENCE_PATIENCE. Tracking the running minimum (not just the previous
+// round) is what lets this catch a 2-cycle oscillation — e.g. 5→4→5→4 never
+// sets a new low after round 2, so it's caught — which a naive
+// "compare to the previous round" check would miss. Pure + unit-tested.
+export function trackConvergence(state, curr) {
+ if (state.best === null || curr < state.best) {
+ return { best: curr, sinceBest: 0 };
+ }
+ return { best: state.best, sinceBest: state.sinceBest + 1 };
+}
+
+// Pause reason for a gate that stopped converging early (#1571) — distinct
+// wording from convergencePauseReason's "ran out of rounds".
+function divergencePauseReason(gate, blockingCount, rounds) {
+ const { label, fix } = PAUSE_GATES[gate];
+ const plural = rounds === 1 ? 'round' : 'rounds';
+ return `${label} stopped converging — ${blockingCount} blocking finding(s) and no net progress over `
+ + `${rounds} consecutive ${plural} of auto-resolve. Paused for review. ${fix}, then resume.`;
+}
+
// Dry-run plan note for a bounded gate: "skipped (0 rounds)" or "up to N rounds".
const roundsNote = (rounds) => (rounds === 0 ? 'skipped (0 rounds)' : `up to ${rounds} rounds`);
@@ -561,6 +603,7 @@ async function runArcVerify(seriesId, record) {
record.runState.arcVerified = true;
return {};
}
+ let convergence = { best: null, sinceBest: 0 };
for (let round = 1; round <= maxRounds; round += 1) {
if (record.cancelRequested) return { canceled: true };
const beforeVerify = await budgetPause();
@@ -576,7 +619,13 @@ async function runArcVerify(seriesId, record) {
return {};
}
if (round === maxRounds) {
- return { pause: true, reason: convergencePauseReason('arc', maxRounds, blocking.length), residual: blocking };
+ return { pause: true, pauseKind: 'maxRounds', reason: convergencePauseReason('arc', maxRounds, blocking.length), residual: blocking };
+ }
+ // Divergence guard (#1571): if the resolve passes stop reducing blocking
+ // findings, bail now rather than burning the remaining rounds + budget.
+ convergence = trackConvergence(convergence, blocking.length);
+ if (convergence.sinceBest >= DIVERGENCE_PATIENCE) {
+ return { pause: true, pauseKind: 'divergence', reason: divergencePauseReason('arc', blocking.length, DIVERGENCE_PATIENCE), residual: blocking };
}
if (record.cancelRequested) return { canceled: true };
// resolveVerifyIssues bills another action — recheck the budget so a single
@@ -609,6 +658,7 @@ async function runBeatContinuity(seriesId, record) {
record.runState.beatContinuityChecked = true;
return {};
}
+ let convergence = { best: null, sinceBest: 0 };
for (let round = 1; round <= maxRounds; round += 1) {
if (record.cancelRequested) return { canceled: true };
const beforeVerify = await budgetPause();
@@ -624,7 +674,12 @@ async function runBeatContinuity(seriesId, record) {
return {};
}
if (round === maxRounds) {
- return { pause: true, reason: convergencePauseReason('beatContinuity', maxRounds, blocking.length), residual: blocking };
+ return { pause: true, pauseKind: 'maxRounds', reason: convergencePauseReason('beatContinuity', maxRounds, blocking.length), residual: blocking };
+ }
+ // Divergence guard (#1571): bail when the resolve passes stop reducing blocking findings.
+ convergence = trackConvergence(convergence, blocking.length);
+ if (convergence.sinceBest >= DIVERGENCE_PATIENCE) {
+ return { pause: true, pauseKind: 'divergence', reason: divergencePauseReason('beatContinuity', blocking.length, DIVERGENCE_PATIENCE), residual: blocking };
}
if (record.cancelRequested) return { canceled: true };
// resolveBeatContinuity bills another action — recheck the budget so a
@@ -769,6 +824,7 @@ async function runEditorial(sId, record) {
record.runState.editorialHealthReady = true;
return {};
}
+ let convergence = { best: null, sinceBest: 0 };
for (let round = 1; round <= maxRounds; round += 1) {
if (record.cancelRequested) return { canceled: true };
const beforeAnalyze = await budgetPause();
@@ -792,7 +848,12 @@ async function runEditorial(sId, record) {
return {};
}
if (round === maxRounds) {
- return { pause: true, reason: convergencePauseReason('editorial', maxRounds, blocking.length), residual: blocking };
+ return { pause: true, pauseKind: 'maxRounds', reason: convergencePauseReason('editorial', maxRounds, blocking.length), residual: blocking };
+ }
+ // Divergence guard (#1571): bail when the auto-fix passes stop reducing blocking findings.
+ convergence = trackConvergence(convergence, blocking.length);
+ if (convergence.sinceBest >= DIVERGENCE_PATIENCE) {
+ return { pause: true, pauseKind: 'divergence', reason: divergencePauseReason('editorial', blocking.length, DIVERGENCE_PATIENCE), residual: blocking };
}
// Bounded auto-fix: apply a fix for each open high-severity comment, then
// the loop re-analyzes. Each fix is wrapped so one bad anchor doesn't abort
@@ -944,6 +1005,9 @@ async function runEditorialHealthGate(sId, record) {
}
// Not clean — surface the open blockers (via the shared helper, so the residual
// can't disagree with computeHealth's `ready` verdict) for the human triage.
+ // No pauseKind (#1571): this is a single-pass gate, not a bounded verify→resolve
+ // loop, so it has no maxRounds/divergence distinction — leave it null. If this
+ // ever gains a retry loop, thread pauseKind through trackConvergence then.
const blockers = openBlockers(comments, gate);
return { pause: true, reason: `editorial health not clean (score ${health.score}, ${health.open} open finding(s))`, residual: blockers };
}
@@ -1388,8 +1452,8 @@ export async function startSeriesAutopilot(sId, options = {}) {
if (result?.canceled || record.cancelRequested) break;
if (result?.pause) {
- await persistMarker(sId, { status: 'paused', runId, currentStep: step.kind, residualFindings: result.residual || [], lastError: result.reason });
- broadcast(sId, { type: 'paused', runId, scope: step.kind, reason: result.reason, residualFindings: result.residual || [], completedAt: new Date().toISOString() });
+ await persistMarker(sId, { status: 'paused', runId, currentStep: step.kind, residualFindings: result.residual || [], lastError: result.reason, pauseKind: result.pauseKind || null });
+ broadcast(sId, { type: 'paused', runId, scope: step.kind, reason: result.reason, residualFindings: result.residual || [], pauseKind: result.pauseKind || null, completedAt: new Date().toISOString() });
// Only file the generic stalled task when the step didn't already file
// a more specific gap (canon-undescribed, visual-no-pages, …) — else
// fileGaps would create two CoS tasks for one underlying problem (the
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index caee518818..5f0d7a20a8 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -544,6 +544,45 @@ async function seedComplete({ script = VALID_SCRIPT } = {}) {
return { seriesId: series.id, seasonId, issueId: issue.id };
}
+describe('trackConvergence (pure divergence/oscillation guard — #1571)', () => {
+ const { trackConvergence, DIVERGENCE_PATIENCE } = autopilot;
+
+ // Fold a sequence of per-round blocking counts into the final tracker state.
+ const fold = (counts) => counts.reduce(trackConvergence, { best: null, sinceBest: 0 });
+
+ it('seeds best on the first measured round (nothing to compare yet)', () => {
+ expect(trackConvergence({ best: null, sinceBest: 0 }, 5)).toEqual({ best: 5, sinceBest: 0 });
+ });
+
+ it('resets sinceBest on a new low (a profitable resolve pass)', () => {
+ expect(trackConvergence({ best: 5, sinceBest: 1 }, 3)).toEqual({ best: 3, sinceBest: 0 });
+ });
+
+ it('accrues sinceBest on a stall (equal to the best)', () => {
+ expect(trackConvergence({ best: 4, sinceBest: 0 }, 4)).toEqual({ best: 4, sinceBest: 1 });
+ });
+
+ it('accrues sinceBest on a regression (a fix introduced a new blocker)', () => {
+ expect(trackConvergence({ best: 2, sinceBest: 0 }, 5)).toEqual({ best: 2, sinceBest: 1 });
+ });
+
+ it('a strictly-decreasing run never diverges', () => {
+ expect(fold([4, 3, 2, 1]).sinceBest).toBeLessThan(DIVERGENCE_PATIENCE);
+ });
+
+ it('a flat stall reaches the patience threshold after two non-improving rounds', () => {
+ // round 1 seeds best=3; rounds 2 + 3 don't improve → sinceBest hits patience.
+ expect(fold([3, 3]).sinceBest).toBeLessThan(DIVERGENCE_PATIENCE);
+ expect(fold([3, 3, 3]).sinceBest).toBeGreaterThanOrEqual(DIVERGENCE_PATIENCE);
+ });
+
+ it('catches a 2-cycle oscillation a naive prev-round check would miss (#1571)', () => {
+ // 5→4→5→4: after round 2 sets best=4, no later round beats it, so sinceBest
+ // climbs past patience even though every other round "decreases" vs the prior.
+ expect(fold([5, 4, 5, 4]).sinceBest).toBeGreaterThanOrEqual(DIVERGENCE_PATIENCE);
+ });
+});
+
describe('autopilot conductor', () => {
it('rejects start when the cos domain is off (no run created)', async () => {
cosMode = 'off';
@@ -598,15 +637,64 @@ describe('autopilot conductor', () => {
});
it('uses the persisted maxArcVerifyRounds setting when no per-run override is given', async () => {
- verifyFindings = [{ severity: 'high', problem: 'plot hole', location: 'V1' }];
+ // Strictly-decreasing blocking counts (4→3→2→1) so the loop runs to the cap
+ // WITHOUT tripping the divergence guard (#1571) — this asserts the persisted
+ // *setting* drives the round cap. mockImplementationOnce is self-consuming, so
+ // it can't leak its impl into the next test the way mockImplementation would
+ // (beforeEach's clearAllMocks keeps implementations).
+ const holes = (n) => Array.from({ length: n }, (_, i) => ({ severity: 'high', problem: `hole ${i}`, location: 'V1' }));
+ arcSpies.verifyArc
+ .mockImplementationOnce(async () => ({ issues: holes(4) }))
+ .mockImplementationOnce(async () => ({ issues: holes(3) }))
+ .mockImplementationOnce(async () => ({ issues: holes(2) }))
+ .mockImplementationOnce(async () => ({ issues: holes(1) }));
getSettings.mockImplementation(async () => ({ pipelineEditorialChecks: { maxArcVerifyRounds: 4 } }));
const { seriesId } = await seedComplete();
await autopilot.startSeriesAutopilot(seriesId, {}); // no per-run rounds — settings drives it
await waitFor(runFinished(seriesId));
- // 4 verify rounds (the persisted setting), 3 resolves, then a pause.
+ // 4 verify rounds (the persisted setting), 3 resolves, then a maxRounds pause.
expect(arcSpies.verifyArc).toHaveBeenCalledTimes(4);
expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(3);
- expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('paused');
+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
+ expect(last?.type).toBe('paused');
+ expect(last?.pauseKind).toBe('maxRounds');
+ });
+
+ it('stops early with a divergence pause when a verify gate stops converging (#1571)', async () => {
+ // Raised cap, but the resolve passes never reduce the blocking count, so the
+ // divergence guard bails at round 3 (patience 2) instead of burning all 6
+ // rounds + budget. Distinct pauseKind so the UI can say "needs a human", not
+ // "ran out of rounds".
+ verifyFindings = [{ severity: 'high', problem: 'plot hole', location: 'V1' }];
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 6 });
+ await waitFor(runFinished(seriesId));
+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
+ expect(last?.type).toBe('paused');
+ expect(last?.scope).toBe('verifyArc');
+ expect(last?.pauseKind).toBe('divergence');
+ expect(last?.reason).toMatch(/stopped converging/);
+ // Bailed at round 3 — NOT all 6 rounds (the whole point: budget saved).
+ expect(arcSpies.verifyArc).toHaveBeenCalledTimes(3);
+ expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(2);
+ const series = await seriesSvc.getSeries(seriesId);
+ expect(series.autopilot?.status).toBe('paused');
+ // Persisted through sanitizeAutopilot so the resume banner survives a reload.
+ expect(series.autopilot?.pauseKind).toBe('divergence');
+ });
+
+ it('a default-cap arc run is unaffected by the divergence guard (maxRounds still wins)', async () => {
+ // Default arc cap is 3; the divergence streak can't reach patience (2) before
+ // the loop hits maxRounds at round 3, so a stalled default run still reports
+ // `maxRounds`, not `divergence` — no behavior change for default runs.
+ verifyFindings = [{ severity: 'high', problem: 'plot hole', location: 'V1' }];
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, {}); // default MAX_ARC_VERIFY_ROUNDS = 3
+ await waitFor(runFinished(seriesId));
+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
+ expect(last?.type).toBe('paused');
+ expect(last?.pauseKind).toBe('maxRounds');
+ expect(arcSpies.verifyArc).toHaveBeenCalledTimes(3);
});
it('a per-run override beats the persisted maxArcVerifyRounds setting', async () => {