Skip to content

Commit 2ba4ab6

Browse files
CL-8978: prevent recoverable subagent failures from stalling parent (#1171)
* test(subagent): prove recoverable failure yields continuable wait marker * feat(subagent): mark recoverable failures continuable in wait output * fix(agent): except continuable same-brief from identical-brief refuse Wait output for a recoverable child failure tells the parent to spawn one successor with the same brief. The standing orchestration rule still refused any identical brief, so Skywalker would refuse the spawn the marker asks for.
1 parent 43f0519 commit 2ba4ab6

8 files changed

Lines changed: 406 additions & 5 deletions

File tree

‎docs/ARCHITECTURE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ Two directors, selected by role:
139139
Auto mode is toggled by CLI flags (`--auto` / `--no-auto`); there is currently no in-session key to toggle it (default on; constrained envelope — workspace writes and unconstrained shell auto-allow; installs, recursive rm, force/uncontained worktree changes, sensitive-path and opaque-wrapper shell still ask; contained non-force `git worktree add`/`remove`/`prune` and `list` auto-allow; shell file-mutation denied). It is not a separate edit/plan mode.
140140

141141
- **SubAgentDirector** (delegated work, `src/subagent/index.ts`) — Drives a dispatched worker until a turn arrives with no tool calls, then replies with the final assistant text and ends the run. A tool-less turn **after tools** completes only with the four-heading envelope (Summary, Findings, Blockers, Paths). Assistant text that prints explicit `<tool_call>` markup is treated as attempted tool use, not narration: one **verbatim-tool-call** nudge asks the worker to re-issue a real `tool_call` and does not count toward the tool-less spiral. A missing envelope otherwise nudges once (**incomplete-report**) and a second tool-less turn still without the envelope salvages as **incomplete-report-stop** (once; later tool-less turns wait). Explore/read-only workers that used tools then replied with findings remain normal completes; `requireEvidence` (off by default, set per director) additionally requires at least one read before a tool-less spawn-only reply can complete. `requirePlanSubstance` (counsel or `intent=plan`, not `modelRole === "plan"`) additionally requires Findings to contain files/paths, acceptance criteria, non-goals, risks, and ordered steps with a non-placeholder line each — four headings with stub Findings are incomplete-report, not an attachable plan. After real tool work, wrap-up Findings that are not placeholder or outline-only complete instead of being salvaged as a stub plan. Reads done through `run_shell` count as evidence too — `src/subagent/shell-evidence.ts` classifies shell reads (`cat`, `grep`, `sed` without `-i`, …) over the same subject expansion the auto-shell policy uses — but there is no corresponding shell-write evidence or file-write requirement: a run that never touches a file still completes normally once it replies with the envelope. There is no turn budget. Operator/parent cancel after any progress returns a **cancelled** salvage report (partial findings + tool activity) instead of a bare cancel string; cancel before progress still surfaces as cancelled-by-operator. There is no repetition/no-progress/never-acted/never-edited hard stop and no fingerprint-based re-dispatch block — a genuinely stuck worker runs until it completes, stalls, hits an opt-in wall-clock deadline, or is cancelled.
142-
`spawn_agent` starts each worker and records it in the caller's fleet mailbox. On the TUI primary, mailbox mail is the collect path: occupancy takes uncollected terminals and re-enters the parent as system inbound. Nested orchestrators collect through mailbox mail the same way. A mounted `wait_agents` (exec primary) collects worker reports directly instead. Already-collected waits return status without a second report or error body. Wait JSON includes `stop_reason` from the session when present so a salvage that is wait-`done` is not mistaken for a clean complete, and so parent-initiated interrupt (`interrupted`) is not mistaken for operator-cancel (`cancelled`). Deadline salvage prepends an advisory parent hint suggesting continuation plus a longer deadline if more wall-clock time is warranted. Failed and incomplete-report salvage tell the parent to diagnose from the report or error and MAY spawn one successor with a changed brief. A parent-initiated interrupt is a resumable pause: wait unblocks with `stop_reason: interrupted` (often while the session is still running and has no report); the parent should `resume_agent` or re-wait, and must not spawn a successor against a still-live worker. Successor only if that session is no longer resumable. Operator-cancelled salvage asks the parent to synthesize Findings and Paths and wait for the operator instead of auto-starting another specialist. Identical re-dispatch of the same brief stays refused at the prompt / spawn-handoff layer; there is no fingerprint-based re-dispatch hard-block. Deadline hints are advisory only — an identical re-dispatch is still admitted at runtime. Parent hints are prepended on salvage reports returned to the parent. The runtime does not auto-spawn successors.
142+
`spawn_agent` starts each worker and records it in the caller's fleet mailbox. On the TUI primary, mailbox mail is the collect path: occupancy takes uncollected terminals and re-enters the parent as system inbound. Nested orchestrators collect through mailbox mail the same way. A mounted `wait_agents` (exec primary) collects worker reports directly instead. Already-collected waits return status without a second report or error body. Wait JSON includes `stop_reason` from the session when present so a salvage that is wait-`done` is not mistaken for a clean complete, and so parent-initiated interrupt (`interrupted`) is not mistaken for operator-cancel (`cancelled`). Deadline salvage prepends an advisory parent hint suggesting continuation plus a longer deadline if more wall-clock time is warranted. Failed and incomplete-report salvage tell the parent to diagnose from the report or error and MAY spawn one successor with a changed brief. A parent-initiated interrupt is a resumable pause: wait unblocks with `stop_reason: interrupted` (often while the session is still running and has no report); the parent should `resume_agent` or re-wait, and must not spawn a successor against a still-live worker. Successor only if that session is no longer resumable. Operator-cancelled salvage asks the parent to synthesize Findings and Paths and wait for the operator instead of auto-starting another specialist. Identical re-dispatch of the same brief stays refused at the prompt / spawn-handoff layer, except a recoverable/continuable child failure (`continuable: true`) MAY spawn one successor with the same brief; there is no fingerprint-based re-dispatch hard-block. Deadline hints are advisory only — an identical re-dispatch is still admitted at runtime. Parent hints are prepended on salvage reports returned to the parent. The runtime does not auto-spawn successors.
143143

144144
#### Model-family policy (`src/agent/model-family-policy.ts`)
145145

‎src/agent/prompts.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ Scope and conventions:
223223
Orchestration:
224224
- One focused task per spawned worker. Fan-out width follows independent lanes (one lane per PR/path/ownership). Break multi-step or parallel work into those dispatches with distinct lenses; prefer \`spawn_agent\` (fire several in one turn when jobs are independent), then reply with who is running and end the turn — workers keep running while you are idle. Mailbox mail arrives as inbound when a worker finishes; read it and do not poll. \`list_agents\` shows the fleet without blocking; after a parked ask is surfaced, answer with \`send_input\` and do not poll \`list_agents\`.
225225
- Pass the typed spawn contract and keep it tight: \`intent\`, \`success_criteria\` (done-when; required for implement/review and their default directors), \`do_not\` (scope fence), and \`report_focus\`. Free-form \`prompt\` without \`success_criteria\` fail-closes for implement/review and their default directors.
226-
- After workers return, classify fail / incomplete-report vs parent-initiated interrupt vs operator-cancel vs clean complete. Fail-path (\`status: failed\` or salvage \`incomplete-report\`): diagnose from the report or error and MAY spawn one successor with a changed brief. Parent-initiated interrupt (\`interrupt_agent\` / \`send_input\` with \`interrupt:true\` unblocks wait with \`stop_reason: interrupted\`): the worker is often still running and often has no report — \`resume_agent\`, or idle for its mailbox mail; do not \`spawn_agent\` a successor against a still-live worker. Successor only if that session is no longer resumable. Operator-cancel (\`stop_reason\` cancelled): wait for the operator; do not auto-retry. Identical brief: refuse. Merge Summary/Findings into a coherent answer for the operator; do not paste raw fleet-agent dumps.
226+
- After workers return, classify fail / incomplete-report vs parent-initiated interrupt vs operator-cancel vs clean complete. Fail-path (\`status: failed\` or salvage \`incomplete-report\`): diagnose from the report or error and MAY spawn one successor with a changed brief. Parent-initiated interrupt (\`interrupt_agent\` / \`send_input\` with \`interrupt:true\` unblocks wait with \`stop_reason: interrupted\`): the worker is often still running and often has no report — \`resume_agent\`, or idle for its mailbox mail; do not \`spawn_agent\` a successor against a still-live worker. Successor only if that session is no longer resumable. Operator-cancel (\`stop_reason\` cancelled): wait for the operator; do not auto-retry. Identical brief: refuse. Recoverable/continuable child failure (\`continuable: true\`) MAY spawn one successor with the same brief; identical brief is still refused otherwise. Merge Summary/Findings into a coherent answer for the operator; do not paste raw fleet-agent dumps.
227227
- Use manage_tasks for your own coordination checklist; spawning workers is \`spawn_agent\`, not manage_tasks.
228228
- If context is compacted automatically, do not stop tasks early due to token fear; persist progress via manage_tasks and worker reports.`);
229229
});

‎src/agent/prompts.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ const GUIDELINE_SUB_BLOCKS: Record<
217217
(ctx.waitAgentsMounted
218218
? " or re-wait"
219219
: ", or idle for its mailbox mail") +
220-
"; do not `spawn_agent` a successor against a still-live worker. Successor only if that session is no longer resumable. Operator-cancel (`stop_reason` cancelled): wait for the operator; do not auto-retry. Identical brief: refuse. Merge Summary/Findings into a coherent answer for the operator; do not paste raw fleet-agent dumps.",
220+
"; do not `spawn_agent` a successor against a still-live worker. Successor only if that session is no longer resumable. Operator-cancel (`stop_reason` cancelled): wait for the operator; do not auto-retry. Identical brief: refuse. Recoverable/continuable child failure (`continuable: true`) MAY spawn one successor with the same brief; identical brief is still refused otherwise. Merge Summary/Findings into a coherent answer for the operator; do not paste raw fleet-agent dumps.",
221221
"- Use manage_tasks for your own coordination checklist; spawning workers is `spawn_agent`, not manage_tasks.",
222222
"- If context is compacted automatically, do not stop tasks early due to token fear; persist progress via manage_tasks and worker reports.",
223223
];

‎src/inference-error-message.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,31 @@ export function classifyInferenceErrorCategory(
6868
: error.category;
6969
}
7070

71+
/**
72+
* Whether a normalized provider-failure category is transient enough that a
73+
* parent may spawn one successor with the same brief (CL-8978). Allowlist:
74+
* retryable/timeout — including 429 overload, which normalizes to retryable.
75+
* Fatal categories win explicitly: credential, quota, and context-overflow
76+
* failures must never read as continuable.
77+
*/
78+
const FATAL_PROVIDER_FAILURE_CATEGORIES: ReadonlySet<string> = new Set([
79+
"credential_failure",
80+
"quota_exhausted",
81+
"context_overflow",
82+
]);
83+
84+
const RECOVERABLE_PROVIDER_FAILURE_CATEGORIES: ReadonlySet<string> = new Set([
85+
"retryable",
86+
"timeout",
87+
]);
88+
89+
export function isRecoverableProviderFailureCategory(
90+
category: string,
91+
): boolean {
92+
if (FATAL_PROVIDER_FAILURE_CATEGORIES.has(category)) return false;
93+
return RECOVERABLE_PROVIDER_FAILURE_CATEGORIES.has(category);
94+
}
95+
7196
function codexUsageLimitLine(error: InferenceErrorLike): string | undefined {
7297
// Match normalizeCodexUsageLimitError: never brand a known non-Codex source.
7398
if (

‎src/prompts.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,9 @@ test("primary chat prompt classifies fail-path successor vs interrupt resume vs
194194
expect(guidelines).toContain("wait for the operator");
195195
expect(guidelines).toContain("do not auto-retry");
196196
expect(guidelines).toContain("Identical brief: refuse");
197+
expect(guidelines).toContain("continuable");
198+
expect(guidelines).toContain("MAY spawn one successor with the same brief");
199+
expect(guidelines).toContain("identical brief is still refused otherwise");
197200
expect(guidelines).toContain("resume_agent");
198201
expect(guidelines).toContain("still-live worker");
199202
expect(guidelines).not.toContain("interrupted-incomplete");

‎src/subagent/agent-fleet.ts‎

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,10 @@ import {
107107
} from "./authority.js";
108108

109109
import { formatSubAgentSpawnAuthFailureMessage } from "./inference-auth-failure.js";
110-
import { isResolvedProviderFailureError } from "../inference-error-message.js";
110+
import {
111+
isRecoverableProviderFailureCategory,
112+
isResolvedProviderFailureError,
113+
} from "../inference-error-message.js";
111114
import { errorMessage } from "../agent/error-message.js";
112115
import { isSubAgentCancelError } from "./dispose.js";
113116
import {
@@ -125,6 +128,8 @@ interface FleetRecord {
125128
error?: string;
126129
stopReason?: string;
127130
providerFailure?: true;
131+
/** CL-8978: transient provider failure — the parent may spawn one successor. */
132+
recoverableFailure?: true;
128133
/** Set once a wait_agents caller has been handed this result. */
129134
collected?: boolean;
130135
/** Set once a waiter or occupancy take handed report/error. */
@@ -158,6 +163,8 @@ interface FleetOverlay {
158163
tombstoned?: boolean;
159164
hint?: string;
160165
providerFailure?: true;
166+
/** CL-8978: transient provider failure — the parent may spawn one successor. */
167+
recoverableFailure?: true;
161168
}
162169

163170
const RECOVERY_HINT =
@@ -265,6 +272,17 @@ class FleetMailbox {
265272
existing.providerFailure = true;
266273
}
267274

275+
/**
276+
* CL-8978: stamp a transient (retryable/timeout/overload) provider failure
277+
* alongside sessions.fail. Survives session eviction like providerFailure —
278+
* snapshot projects it even once the payload is tombstoned.
279+
*/
280+
markRecoverable(id: string): void {
281+
const existing = this.records.get(id);
282+
if (existing === undefined) return;
283+
existing.recoverableFailure = true;
284+
}
285+
268286
markQueued(id: string): void {
269287
const existing = this.records.get(id);
270288
if (existing === undefined || existing.collected === true) return;
@@ -462,6 +480,9 @@ class FleetMailbox {
462480
: {}),
463481
...(stopReason !== undefined ? { stopReason } : {}),
464482
...(overlay.providerFailure === true ? { providerFailure: true } : {}),
483+
...(overlay.recoverableFailure === true
484+
? { recoverableFailure: true }
485+
: {}),
465486
...(ask !== undefined
466487
? { question: ask.question, questionId: ask.questionId }
467488
: {}),
@@ -600,7 +621,10 @@ export const waitAgentsToolDefinition: ToolDefinition = {
600621
`slot), "running", and "awaiting_director". interrupt_agent unblocks this wait immediately with ` +
601622
`status "interrupted" (a parent-initiated pause — resume_agent, do not spawn_agent a successor against the still-live worker). ` +
602623
`close_agent also unblocks with status "interrupted" but is permanent. Terminal JSON includes stop_reason when the session recorded one ` +
603-
`(interrupted, cancelled, incomplete-report, and similar). awaiting_director is not terminal: re-wait while still pending re-delivers the same question. ` +
624+
`(interrupted, cancelled, incomplete-report, and similar). A "failed" entry with "continuable": true is a recoverable transient ` +
625+
`provider failure (retryable/timeout/overload) — terminal, not a timeout and not a stall: do not re-wait it, and you may spawn at most ` +
626+
`one successor with the same brief. "failed" without the marker (auth, quota, context-overflow, or other errors) is not continuable — ` +
627+
`do not respawn it. awaiting_director is not terminal: re-wait while still pending re-delivers the same question. ` +
604628
`Answer with send_input (soft). Do not call this in a tight zero-progress loop: a timeout means the targets are still ` +
605629
`queued, running, or awaiting a director answer, not "try again right away" — do other work, reply to the operator, or change the brief. Calling again with the ` +
606630
`same targets is a real timed wait, not a spin, but wastes turns if nothing has changed. ` +
@@ -1530,6 +1554,17 @@ export function createSpawnAgentTool(deps: AgentFleetDeps): AgentTool {
15301554
if (isProviderFailure || providerFailureObserved) {
15311555
deps.fleetRecords.markProviderFailure(session.id);
15321556
}
1557+
// CL-8978: a classified transient failure stays wait-terminal
1558+
// failed, but carries a continuable marker so the parent can
1559+
// spawn one successor instead of stalling on the failure.
1560+
// Fatal categories (credential/quota/context-overflow) and
1561+
// unclassified throws never mark — no auto-retry is added here.
1562+
if (
1563+
isResolvedProviderFailureError(err) &&
1564+
isRecoverableProviderFailureCategory(err.category)
1565+
) {
1566+
deps.fleetRecords.markRecoverable(session.id);
1567+
}
15331568
deps.sessions.fail(session.id, failReason);
15341569
})
15351570
.finally(() => {

‎src/subagent/fleet-dry-drive.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ export interface FleetDryMailboxRecord {
3434
readonly description?: string;
3535
readonly hint?: string;
3636
readonly providerFailure?: true;
37+
/** CL-8978: transient provider failure — the parent may spawn one successor. */
38+
readonly recoverableFailure?: true;
3739
readonly stopReason?: string;
3840
}
3941

@@ -58,9 +60,25 @@ export interface CollectedWorkerReport {
5860
error?: string;
5961
hint?: string;
6062
provider_failure?: true;
63+
/**
64+
* CL-8978: failed entries from a transient provider failure carry this
65+
* marker plus single-successor guidance in continue_with. Capped affordance:
66+
* at most one respawn with the same brief, never a retry loop.
67+
*/
68+
continuable?: true;
69+
continue_with?: string;
6170
stop_reason?: string;
6271
}
6372

73+
/**
74+
* Single-successor guidance for a failed+continuable entry. The marker is
75+
* advisory only — no runtime auto-retry backs it.
76+
*/
77+
export const RECOVERABLE_FAILURE_CONTINUE_GUIDANCE =
78+
"This worker failed with a transient provider error (retryable/timeout/overload) " +
79+
"and is terminal — do not re-wait it. You may spawn at most one successor with " +
80+
"the same brief; do not retry in a loop.";
81+
6482
export function shouldDriveOpenTasks(input: {
6583
previousRunning?: number | undefined;
6684
running?: number | undefined;
@@ -169,6 +187,12 @@ export function projectMailboxRecord(
169187
...(error !== undefined ? { error } : {}),
170188
...(taken.hint !== undefined ? { hint: taken.hint } : {}),
171189
...(taken.providerFailure === true ? { provider_failure: true } : {}),
190+
...(taken.status === "failed" && taken.recoverableFailure === true
191+
? {
192+
continuable: true as const,
193+
continue_with: RECOVERABLE_FAILURE_CONTINUE_GUIDANCE,
194+
}
195+
: {}),
172196
...(taken.stopReason !== undefined
173197
? { stop_reason: taken.stopReason }
174198
: {}),

0 commit comments

Comments
 (0)