Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: bound the foundation-repair prompt and pause (not kill) the run when its AI call fails

[._.]/ Adam Eivy67d3030a078e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 8cb7fb3c2d..59de103f20 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -108,3 +108,5 @@
- **Autopilot now repairs duplicate volumes before it can waste work filling them.** Resume previously looked for empty volumes before any arc write reached the duplicate-volume self-heal, so malformed empty copies could receive a full issue breakdown only to be absorbed later. A zero-cost structural preflight now runs first, keeps existing issues attached to the canonical volume, and only then considers episode generation. If locks make the repair ambiguous, the run pauses before spending and asks for full edit control. Dry-run estimates mirror the same repair and no longer charge issue-generation calls for copies that will be absorbed.
- **Synchronous Codex TUI stages stay single-agent.** A machine-consumed pipeline prompt could inherit Codex's general multi-agent feature, fan out work it never needed, and then spend its entire timeout waiting on those agents before repeating the same request on a fallback provider. The one-shot TUI runner now disables that feature only for Codex prompt calls; long-running CoS coding agents keep their configured collaboration posture, and other TUI providers are unchanged.
+
+- **A foundation repair no longer sends the entire episode list, and no longer takes the whole autopilot run down with it when it fails.** The foundation-quality gate's repair prompt carried the full synopsis-level plan — every volume *and* every episode synopsis — with no size limit, so it grew with the series forever. On a long-running series that section reached 28KB of a 35KB prompt, and the primary AI provider burned its entire ten-minute timeout on it without producing a single word; the fallback provider then repeated the same request and burned ten more. Twenty minutes spent, nothing written, and the whole autonomous run ended in an error that discarded every step it had already completed. The repair prompt is now bounded the same way the judge prompt beside it always was: the plan spine (arc, volumes, authored character arcs) is always sent in full, and the episode list fills the remaining budget by whole lines, oldest first, saying how many were left out — so the model reads a coherent outline instead of one cut mid-sentence. And a repair whose AI call fails outright now **pauses** the run rather than erroring it: the failure is a provider timeout or a dead CLI, not a verdict on your story, so the run keeps every step it finished, tells you which provider failed, and resumes from where it stopped. Autopilot also stopped quietly losing the reason it paused — "nothing to fix", "budget reached" and this new "provider failed" were all being emitted and then dropped before they reached the screen, leaving a bare "Paused" with no explanation; each now carries its own badge.
diff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsx
index 835baaecb2..9a4bcd395f 100644
--- a/client/src/components/pipeline/AutopilotPanel.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.jsx
@@ -325,7 +325,8 @@ const RUN_ENDED = new Set(['complete', 'canceled', 'error', 'paused']);
// Pause kinds worth calling out beside the status line — the ones where "Paused"
// alone doesn't tell the user what state the draft is in. A kind with no entry
-// (maxRounds, childFailed) is fully explained by the reason text below it.
+// (maxRounds, childFailed, planningOscillation) is fully explained by the reason
+// text below it.
const PAUSE_BADGES = {
divergence: {
label: 'not converging',
@@ -339,6 +340,18 @@ const PAUSE_BADGES = {
label: 'high findings',
title: 'Editorial checks surfaced too many High findings — address them (or raise the threshold) and resume',
},
+ providerFailed: {
+ label: 'provider failed',
+ title: 'An AI repair call failed outright (provider timeout, dead CLI, rate limit) — the run kept everything it had finished; resume to retry, or switch the provider/model first',
+ },
+ inapplicable: {
+ label: 'nothing to fix',
+ title: "The owning service had nothing it was allowed to change — no linked universe, or every target is locked. Auto-resolve can't proceed without a human edit",
+ },
+ budget: {
+ label: 'budget reached',
+ title: 'The daily spend cap was reached mid-run — the run stopped where it was and resumes once the budget resets or is raised',
+ },
};
// #1572 — shared caution tail for a `done` run that filed blocking script-craft
diff --git a/client/src/components/pipeline/AutopilotPanel.test.jsx b/client/src/components/pipeline/AutopilotPanel.test.jsx
index b52cb85835..5876eb55e2 100644
--- a/client/src/components/pipeline/AutopilotPanel.test.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.test.jsx
@@ -408,6 +408,36 @@ describe('AutopilotPanel', () => {
expect(screen.queryByText(/not converging/i)).not.toBeInTheDocument();
});
+ it('flags a failed AI repair call with a "provider failed" badge', async () => {
+ // A provider timeout / dead CLI is transient and says nothing about the
+ // draft — the badge has to separate it from a pause the user must edit for.
+ renderPanel({
+ id: 's1',
+ targetFormat: 'comic',
+ autopilot: { status: 'paused', currentStep: 'foundationGate', pauseKind: 'providerFailed' },
+ });
+ await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalled());
+ expect(screen.getByText(/provider failed/i)).toBeInTheDocument();
+ });
+
+ it('flags an unfixable dimension and a spent budget with their own badges', async () => {
+ const { unmount } = renderPanel({
+ id: 's1',
+ targetFormat: 'comic',
+ autopilot: { status: 'paused', currentStep: 'foundationGate', pauseKind: 'inapplicable' },
+ });
+ await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalled());
+ expect(screen.getByText(/nothing to fix/i)).toBeInTheDocument();
+ unmount();
+
+ renderPanel({
+ id: 's1',
+ targetFormat: 'comic',
+ autopilot: { status: 'paused', currentStep: 'foundationGate', pauseKind: 'budget' },
+ });
+ await waitFor(() => expect(screen.getByText(/budget reached/i)).toBeInTheDocument());
+ });
+
it('flags an editorial-checks pause with a "high findings" badge (#1613)', async () => {
renderPanel({
id: 's1',
diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.js
index 439c20d22d..8e8fecc329 100644
--- a/server/services/pipeline/foundationJudge.js
+++ b/server/services/pipeline/foundationJudge.js
@@ -400,13 +400,31 @@ function coreFoundationCharacters(characters, series, issues = []) {
.map(({ character }) => character);
}
-function renderArc(series, issues = []) {
+const joinedLength = (lines) => lines.reduce((total, line) => total + line.length + 1, 0);
+
+/**
+ * Render the synopsis-level series plan: arc header, per-volume loglines and
+ * synopses, the episode list under each volume, and the authored character arcs.
+ *
+ * `maxChars` bounds the result. The per-episode synopsis list is the ONLY part
+ * that grows without bound — a series gains episodes forever, and everything
+ * else is fixed by the volume count — so the budget is spent by dropping WHOLE
+ * episode lines from the end, keeping the plan spine (arc, volumes, authored
+ * character arcs) intact and naming how many were left out. That degrades to a
+ * coherent outline the model can still reason over, unlike slicing the rendered
+ * text mid-sentence. Earliest episodes survive a tight budget because that's
+ * where a character arc's opening transitions hang.
+ *
+ * Unbudgeted (the default) the output is byte-identical to the pre-budget
+ * render, so the foundation judge's own section-level truncation is unchanged.
+ */
+function renderArc(series, issues = [], { maxChars = Infinity } = {}) {
const arc = series?.arc || {};
const seasons = Array.isArray(series?.seasons) ? [...series.seasons].sort((a, b) => (a.number || 0) - (b.number || 0)) : [];
const orderedIssues = [...(Array.isArray(issues) ? issues : [])]
.sort((a, b) => (a?.number ?? 9999) - (b?.number ?? 9999));
const themes = Array.isArray(arc.themes) ? arc.themes.join(', ') : (arc.themes || '');
- const lines = [
+ const head = [
`Logline: ${arc.logline || '(none)'}`,
`Summary: ${arc.summary || '(none)'}`,
`Themes: ${themes || '(none)'}`,
@@ -415,20 +433,43 @@ function renderArc(series, issues = []) {
'',
`Volumes (${seasons.length}):`,
];
- for (const season of seasons) {
- lines.push(` V${season.number ?? '?'} ${season.title || ''}: ${season.logline || '(no logline)'}`);
- lines.push(` Synopsis: ${season.synopsis || '(none)'}`);
- if (season.endingHook) lines.push(` Ending hook: ${season.endingHook}`);
- const seasonIssues = orderedIssues.filter((issue) => issue?.seasonId === season.id);
- for (const issue of seasonIssues) {
- lines.push(` #${issue.number ?? '?'} ${issue.title || 'Untitled'}: ${issue?.stages?.idea?.input || '(no synopsis)'}`);
- }
- }
+ const volumes = seasons.map((season) => {
+ const spine = [
+ ` V${season.number ?? '?'} ${season.title || ''}: ${season.logline || '(no logline)'}`,
+ ` Synopsis: ${season.synopsis || '(none)'}`,
+ ];
+ if (season.endingHook) spine.push(` Ending hook: ${season.endingHook}`);
+ const episodes = orderedIssues
+ .filter((issue) => issue?.seasonId === season.id)
+ .map((issue) => ` #${issue.number ?? '?'} ${issue.title || 'Untitled'}: ${issue?.stages?.idea?.input || '(no synopsis)'}`);
+ return { spine, episodes };
+ });
const characterArcs = Array.isArray(series?.characterArcs) ? series.characterArcs : [];
- lines.push('', `Authored character arcs (${characterArcs.length}):`);
+ const tail = ['', `Authored character arcs (${characterArcs.length}):`];
for (const characterArc of characterArcs) {
- lines.push(` - ${characterArc.characterName || characterArc.characterId || 'Unnamed'}: ${characterArc.startState || '(no start)'} → ${characterArc.endState || '(no end)'}; want=${characterArc.want || '—'}; need=${characterArc.need || '—'}`);
+ tail.push(` - ${characterArc.characterName || characterArc.characterId || 'Unnamed'}: ${characterArc.startState || '(no start)'} → ${characterArc.endState || '(no end)'}; want=${characterArc.want || '—'}; need=${characterArc.need || '—'}`);
+ }
+
+ // The spine is unconditional; episodes fill whatever is left. `remaining` goes
+ // negative when the spine alone overruns the budget, which drops every episode
+ // rather than throwing — a caller that set a budget wants a smaller prompt, not
+ // a failed render.
+ let remaining = maxChars - joinedLength([...head, ...volumes.flatMap((v) => v.spine), ...tail]);
+ let omitted = 0;
+ const lines = [...head];
+ for (const volume of volumes) {
+ lines.push(...volume.spine);
+ for (const episode of volume.episodes) {
+ if (episode.length + 1 <= remaining) {
+ lines.push(episode);
+ remaining -= episode.length + 1;
+ } else {
+ omitted += 1;
+ }
+ }
}
+ if (omitted > 0) lines.push(` [${omitted} later episode synopsis line${omitted === 1 ? '' : 's'} omitted to fit the prompt budget]`);
+ lines.push(...tail);
return lines.join('\n');
}
@@ -632,6 +673,21 @@ const REPAIRABLE_CHARACTER_FIELDS = Object.freeze([
'secrets',
]);
+// How much of the synopsis-level plan a repair prompt may carry. The judge
+// prompt this mirrors has always been budgeted (`buildFoundationContext` caps
+// each section at a third of the model's usable input); repair alone sent the
+// whole plan raw, so its prompt grew with every episode the series gained. On a
+// long-running series that section reached 28KB of a 35KB prompt and BOTH the
+// primary and the fallback TUI provider burned their full 10-minute timeout on
+// it without emitting a response — which errored the entire autonomous run.
+// ~12K chars (~3K tokens) keeps the arc spine plus the early episodes a
+// character arc's transitions hang off, and still fits alongside the rest of the
+// prompt inside a small local model's window. A fixed cap rather than a
+// window-derived one on purpose: the binding constraint here is how much
+// material a reasoning model will chew through before the wall clock runs out,
+// not how much its context can hold.
+const REPAIR_OUTLINE_MAX_CHARS = 12_000;
+
async function runFoundationRepair(series, issues, dimension, finding, characters, options) {
const result = await runStagedLLM(REPAIR_STAGE, {
dimension,
@@ -644,7 +700,7 @@ async function runFoundationRepair(series, issues, dimension, finding, character
styleGuide: series.styleGuide,
characterArcs: series.characterArcs,
}, null, 2),
- outline: renderArc(series, issues),
+ outline: renderArc(series, issues, { maxChars: REPAIR_OUTLINE_MAX_CHARS }),
charactersJson: JSON.stringify(characters.map((character) => ({
id: character.id,
name: character.name,
@@ -884,6 +940,8 @@ export const __testing = {
contentHash,
isFoundationStale,
buildFoundationContext,
+ renderArc,
renderCharacterLine,
+ REPAIR_OUTLINE_MAX_CHARS,
FRAMEWORK_STRING_FIELDS,
};
diff --git a/server/services/pipeline/foundationJudge.test.js b/server/services/pipeline/foundationJudge.test.js
index 0689efd3b5..2e5656c737 100644
--- a/server/services/pipeline/foundationJudge.test.js
+++ b/server/services/pipeline/foundationJudge.test.js
@@ -244,6 +244,78 @@ describe('rankFoundationCharacters — core-cast repair targets', () => {
});
});
+describe('renderArc — episode-list budget', () => {
+ const bigSeries = {
+ arc: { logline: 'AL', summary: 'AS', themes: ['t1'], protagonistArc: 'PA', shape: 'rise' },
+ seasons: [{ id: 'sea-1', number: 1, title: 'V1', logline: 'VL', synopsis: 'VS', endingHook: 'EH' }],
+ characterArcs: [{ characterId: 'chr-1', characterName: 'Lead', startState: 'a', endState: 'b', want: 'w', need: 'n' }],
+ };
+ const manyIssues = Array.from({ length: 40 }, (_, i) => ({
+ number: i + 1, seasonId: 'sea-1', title: `Ep ${i + 1}`,
+ stages: { idea: { input: 'x'.repeat(400) } },
+ }));
+
+ it('renders every episode when unbudgeted', () => {
+ const out = __testing.renderArc(bigSeries, manyIssues);
+ expect(out).toContain('#1 Ep 1:');
+ expect(out).toContain('#40 Ep 40:');
+ expect(out).not.toContain('omitted to fit the prompt budget');
+ });
+
+ it('drops whole trailing episode lines to fit, keeping the plan spine intact', () => {
+ const out = __testing.renderArc(bigSeries, manyIssues, { maxChars: 4_000 });
+ // Spine survives: arc header, volume logline/synopsis/hook, authored arcs.
+ expect(out).toContain('Logline: AL');
+ expect(out).toContain(' V1 V1: VL');
+ expect(out).toContain(' Synopsis: VS');
+ expect(out).toContain(' Ending hook: EH');
+ expect(out).toContain('Authored character arcs (1):');
+ // Earliest episodes are the ones kept; the tail is dropped by whole lines
+ // (never sliced mid-sentence) and the omitted count is named.
+ expect(out).toContain('#1 Ep 1:');
+ expect(out).not.toContain('#40 Ep 40:');
+ expect(out).toMatch(/\[\d+ later episode synopsis lines omitted to fit the prompt budget\]/);
+ for (const line of out.split('\n')) {
+ if (line.startsWith(' #')) expect(line.endsWith('x'.repeat(20))).toBe(true);
+ }
+ });
+
+ it('drops every episode rather than throwing when the spine alone overruns the budget', () => {
+ const out = __testing.renderArc(bigSeries, manyIssues, { maxChars: 10 });
+ expect(out).toContain('Logline: AL');
+ expect(out).not.toContain('#1 Ep 1:');
+ expect(out).toContain('[40 later episode synopsis lines omitted to fit the prompt budget]');
+ });
+
+ it('keeps the singular form when exactly one episode is dropped', () => {
+ const oneOver = __testing.renderArc(bigSeries, manyIssues.slice(0, 2), { maxChars: 800 });
+ expect(oneOver).toContain('[1 later episode synopsis line omitted to fit the prompt budget]');
+ });
+});
+
+describe('foundation repair prompt — bounded outline', () => {
+ it('caps the synopsis-level plan so the prompt cannot grow without bound with the episode count', async () => {
+ seriesSvc.getSeries.mockResolvedValue({
+ id: 'ser-1', name: 'S', premise: 'P', universeId: 'uni-1',
+ seasons: [{ id: 'sea-1', number: 1, title: 'V1', logline: 'VL', synopsis: 'VS' }],
+ });
+ issuesSvc.listIssues.mockResolvedValue(Array.from({ length: 60 }, (_, i) => ({
+ number: i + 1, seasonId: 'sea-1', title: `Ep ${i + 1}`,
+ stages: { idea: { input: 'y'.repeat(500) } },
+ })));
+ stageRunner.runStagedLLM.mockResolvedValue({ content: {} });
+
+ await applyFoundationFix('ser-1', 'craft', { finding: { gap: 'g', fix: 'f' } });
+
+ const [, vars] = stageRunner.runStagedLLM.mock.calls.at(-1);
+ // 60 × ~500 chars of synopsis would be ~30KB unbudgeted — the exact shape
+ // that burned both the primary and fallback TUI provider's full timeout.
+ expect(vars.outline.length).toBeLessThanOrEqual(__testing.REPAIR_OUTLINE_MAX_CHARS + 200);
+ expect(vars.outline).toContain('omitted to fit the prompt budget');
+ expect(vars.outline).toContain(' V1 V1: VL');
+ });
+});
+
describe('foundation judge context — complete planning altitude', () => {
it('shows the world bible premise and design systems that world repair can change', () => {
const ctx = __testing.buildFoundationContext({
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index eb6f46f5f0..60996b3549 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -124,13 +124,25 @@ const AUTOPILOT_FINDING_SEVERITIES = ['high', 'medium', 'low'];
// 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.
+// reason text. Any other pause (error, a capability gap) leaves this null.
// Editorial checks (#1613): `checkFindings` (the editorial-checks pass surfaced ≥
// the armed high-finding threshold, so the run paused for human review).
// Resolve rollback: `regression` (an auto-resolve round came back with MORE
// blocking findings than it was handed while leaving those standing, so its
// edits were reverted and the run paused on the pre-round residual).
-export const AUTOPILOT_PAUSE_KINDS = Object.freeze(['maxRounds', 'divergence', 'regression', 'childFailed', 'checkFindings']);
+// Dead ends the run can't fix itself: `inapplicable` (the owning service had
+// nothing it was allowed to change — no linked universe, a fully-locked cast),
+// `planningOscillation` (the foundation and arc gates kept handing repairs back
+// to each other without settling), `budget` (the daily spend cap was reached
+// mid-run), `providerFailed` (an LLM repair call failed outright — a provider
+// timeout, a dead CLI, a rate limit — after the prompt runner's own fallback
+// cascade was exhausted). This list must carry EVERY kind the autopilot emits:
+// sanitizeAutopilot drops an unlisted one to null, which silently strips the
+// badge the UI would otherwise show.
+export const AUTOPILOT_PAUSE_KINDS = Object.freeze([
+ 'maxRounds', 'divergence', 'regression', 'childFailed', 'checkFindings',
+ 'inapplicable', 'planningOscillation', 'budget', 'providerFailed',
+]);
export const sanitizeAutopilot = (raw) => {
if (!raw || typeof raw !== 'object') return null;
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index 2013bce4cb..5d4df952a5 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -1571,6 +1571,25 @@ describe('autopilot conductor', () => {
expect(applyFoundationFix).toHaveBeenCalledTimes(1);
});
+ it('foundation gate: a repair that throws pauses the run instead of erroring it away', async () => {
+ foundationScore = 3;
+ applyFoundationFix.mockRejectedValueOnce(new Error('TUI run timed out after 600000ms'));
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, { maxFoundationRounds: 3 });
+ await waitFor(runFinished(seriesId));
+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
+ // The whole point: an LLM transport failure is transient and has nothing to
+ // do with the foundation, so it must NOT discard the run the way `error` does.
+ expect(last?.type).toBe('paused');
+ expect(last?.pauseKind).toBe('providerFailed');
+ expect(last?.reason).toMatch(/TUI run timed out after 600000ms/);
+ const series = await seriesSvc.getSeries(seriesId);
+ expect(series.autopilot?.status).toBe('paused');
+ // Survives the sanitizer — an unlisted kind would be silently nulled and the
+ // UI badge would vanish.
+ expect(series.autopilot?.pauseKind).toBe('providerFailed');
+ });
+
it('foundation gate: disabled via option runs no judge and proceeds', async () => {
foundationScore = 3;
const { seriesId } = await seedComplete();
diff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.js
index f73f0dd5f9..90af1286e2 100644
--- a/server/services/pipeline/seriesAutopilot/childRuns.js
+++ b/server/services/pipeline/seriesAutopilot/childRuns.js
@@ -314,13 +314,41 @@ export async function runFoundationGate(seriesId, record) {
if (record.cancelRequested) return { canceled: true };
const beforeFix = await budgetPause();
if (beforeFix) return beforeFix;
- const fix = await applyFoundationFix(seriesId, weak.dimension, {
- finding: snap.dimensions?.[weak.dimension] || {},
- providerOverride: providerId,
- modelOverride: model,
- ...seasonPreserveOpts(record),
- effortOverride: effort,
- });
+ // Deliberate catch (the one in this module): the repair is an LLM call, and
+ // an LLM call fails for reasons that have nothing to do with the foundation
+ // — a provider timeout, a dead CLI binary, a rate limit. Uncaught, it left
+ // the orchestrator's catch to mark the WHOLE run `error` and stop, throwing
+ // away every step the run had already completed, even though the failure is
+ // transient and the next attempt would very likely succeed. Every other
+ // dead end in this gate (locked arc, fully-locked cast, non-convergence)
+ // pauses instead — a resumable state that keeps the run's position and
+ // names what went wrong. A provider failure is the MOST transient of them,
+ // so it gets the same treatment rather than the harshest one. The
+ // promptRunner has already walked its full fallback cascade by the time
+ // this throws, so there is no retry left to attempt here.
+ let fix;
+ try {
+ fix = await applyFoundationFix(seriesId, weak.dimension, {
+ finding: snap.dimensions?.[weak.dimension] || {},
+ providerOverride: providerId,
+ modelOverride: model,
+ ...seasonPreserveOpts(record),
+ effortOverride: effort,
+ });
+ } catch (err) {
+ const detail = (err?.message || String(err)).slice(0, 300);
+ console.error(`❌ foundation repair failed (${weak.dimension}) — series=${seriesId.slice(0, 12)}: ${detail}`);
+ await recordDomainUsage('cos', { actions: 1 });
+ broadcast(seriesId, {
+ type: 'foundation:fix', round, dimension: weak.dimension, applied: false, reason: detail,
+ });
+ return {
+ pause: true,
+ pauseKind: 'providerFailed',
+ reason: `The foundation repair for ${weak.dimension} could not complete: ${detail}. The run kept everything it had finished — resume to retry, or switch the repair provider/model first.`,
+ residual: residualFindings(snap.dimensions),
+ };
+ }
await recordDomainUsage('cos', { actions: 1 });
broadcast(seriesId, {
type: 'foundation:fix', round, dimension: weak.dimension, applied: fix?.applied === true, reason: fix?.reason || null,
diff --git a/server/services/pipeline/seriesAutopilot/orchestrator.js b/server/services/pipeline/seriesAutopilot/orchestrator.js
index dc69eabcd5..65c843aa2a 100644
--- a/server/services/pipeline/seriesAutopilot/orchestrator.js
+++ b/server/services/pipeline/seriesAutopilot/orchestrator.js
@@ -347,8 +347,8 @@ export async function startSeriesAutopilot(sId, options = {}) {
const budget = await getDomainBudgetStatus('cos');
if (!budget.withinBudget) {
const budgetReason = `daily cos ${budget.exceeded} budget reached`;
- await persistMarker(sId, { status: 'paused', runId, currentStep: step.kind, lastError: budgetReason });
- broadcast(sId, { type: 'paused', runId, reason: budgetReason, completedAt: new Date().toISOString() });
+ await persistMarker(sId, { status: 'paused', runId, currentStep: step.kind, lastError: budgetReason, pauseKind: 'budget' });
+ broadcast(sId, { type: 'paused', runId, reason: budgetReason, pauseKind: 'budget', completedAt: new Date().toISOString() });
await notifyPause(record, sId, { reason: budgetReason, pauseKind: 'budget', currentStep: step.kind });
console.log(`⏸️ autopilot paused (budget) — series=${sId.slice(0, 12)} after ${ordinal} steps`);
return;
diff --git a/server/services/pipeline/seriesAutopilot/session.js b/server/services/pipeline/seriesAutopilot/session.js
index 8b3316eb82..e3eaa65038 100644
--- a/server/services/pipeline/seriesAutopilot/session.js
+++ b/server/services/pipeline/seriesAutopilot/session.js
@@ -231,5 +231,5 @@ export const seasonPreserveOpts = (record) => ({
export async function budgetPause() {
const budget = await getDomainBudgetStatus('cos');
if (budget.withinBudget) return null;
- return { pause: true, gapFiled: true, reason: `daily cos ${budget.exceeded || 'actions'} budget reached` };
+ return { pause: true, gapFiled: true, pauseKind: 'budget', reason: `daily cos ${budget.exceeded || 'actions'} budget reached` };
}