graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(fleet): bounded worker retry - the resilience the root had, workers now get
justrach168cb0887e52
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex 7ff000f7..217fa61c 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -13,7 +13,7 @@{"id": "review-repeat-failure-gets-anchor-revision", "why": "report_anchors gives review/research a real verifier (cited paths must resolve against the tree), so a review-class repeat failure now earns the R0d revision prescription instead of jumping to the judge fleet — the anchors are the external feedback Weng's gate demands.", "args": [], "prompt": "review the findings in report.py", "script": [{"tool": "workflow", "arguments": {"phases": [{"title": "find problems", "tasks": [{"description": "find", "prompt": "read report.py and list the problems"}]}, {"title": "verify each finding", "tasks": [{"description": "verify", "prompt": "verify the problems in report.py"}]}]}}, {"text": "reviewed solo as told"}, {"tool": "workflow", "arguments": {"phases": [{"title": "find problems", "tasks": [{"description": "find", "prompt": "read report.py and list the problems"}]}, {"title": "verify each finding", "tasks": [{"description": "verify", "prompt": "verify the problems in report.py"}]}]}}, {"text": "re-reviewing against the cited code as prescribed"}], "second_prompt": "that review missed real problems in report.py — go again", "assert": [{"request_contains": {"index": 1, "text": "(escalation R0):"}}, {"request_lacks": {"index": 1, "text": "(escalation R0d):"}}, {"request_contains": {"index": -1, "text": "(escalation R0d):"}}, {"request_contains": {"index": -1, "text": "revision case"}}, {"final_text_contains": "re-reviewing against the cited code"}]}{"id": "budget-final-call-lands-the-answer", "why": "#390: the pool's FINAL admitted model call belongs to the answer. The run's last request must offer no tools and carry the landing note, so the model answers from gathered evidence instead of asking for a tool the budget can never pay for — the audit-smoke run died exactly this way, exhausted mid-tool-loop with the work done and nothing narrated.", "args": ["--max-model-calls", "2"], "prompt": "keep reading the todo list forever", "script": [{"tool": "todo_read", "arguments": {}}, {"text": "landing: the todo list is empty; nothing else was verified"}], "assert": [{"request_contains": {"index": 0, "text": "\"todo_write\""}}, {"request_contains": {"index": -1, "text": "budget landing"}}, {"request_lacks": {"index": -1, "text": "\"todo_write\""}}, {"final_text_contains": "landing: the todo list is empty"}]}{"id": "escalation-third-failure-earns-the-fleet", "why": "GREEN regression lock. Ladder cell prior_failure_count>=2: the one deep retry is spent, so a THIRD ask of the same class must escape R0d and run as an R3 fleet. Guards the `prior_failure_count == 1` gate and the noteDeclined bump on the R0d decline — loosen either and the run loops on solo revisions forever, which is exactly the stuck-task failure the ladder exists to break.", "args": [], "prompt": "fix the crash in stats.py", "second_prompt": "still crashing in stats.py after that fix — go again", "script": [{"tool": "bash", "arguments": {"command": "echo 'def mean(xs): return sum(xs)/len(xs)' > stats.py && echo seeded-stats"}}, {"tool": "workflow", "arguments": {"phases": [{"title": "find the defect", "tasks": [{"description": "find", "prompt": "read stats.py and locate the defect"}]}, {"title": "verify the fix", "tasks": [{"description": "verify", "prompt": "verify the defect report against stats.py"}]}]}}, {"text": "made the edit solo; the test still crashes"}, {"tool": "workflow", "arguments": {"phases": [{"title": "find the defect", "tasks": [{"description": "find", "prompt": "read stats.py and locate the defect"}]}, {"title": "verify the fix", "tasks": [{"description": "verify", "prompt": "verify the defect report against stats.py"}]}]}}, {"tool": "workflow", "arguments": {"phases": [{"title": "find the defect", "tasks": [{"description": "find", "prompt": "read stats.py and locate the defect"}]}, {"title": "verify the fix", "tasks": [{"description": "verify", "prompt": "verify the defect report against stats.py"}]}]}}, {"text": "FLEET-FINDER-REPORT: stats.py divides by len(xs) with no empty-list guard"}, {"text": "FLEET-VERIFY-REPORT: confirmed against stats.py — the guard is missing"}, {"text": "the fleet confirmed the missing empty-list guard in stats.py"}], "assert": [{"event": {"type": "tool_result", "name": "bash", "text": "seeded-stats\n"}}, {"request_contains": {"index": 2, "text": "(escalation R0):"}}, {"request_lacks": {"index": 2, "text": "(escalation R0d):"}}, {"request_contains": {"index": 4, "text": "(escalation R0d):"}}, {"request_contains": {"index": 4, "text": "second failure earns the fleet"}}, {"events_at_least": {"match": {"type": "agent_route"}, "count": 2}}, {"events_at_most": {"match": {"type": "agent_route"}, "count": 2}}, {"request_contains": {"index": 6, "text": "FLEET-FINDER-REPORT"}}, {"request_contains": {"index": -1, "text": "FLEET-VERIFY-REPORT"}}, {"final_text_contains": "missing empty-list guard"}], "timeout_s": 120}-{"id": "child-refused-last-call-root-lands", "why": "#390 hard half (green regression lock): with cap 2, call 1 spawns a child; the child's acquire sees one slot left and is refused BEFORE the network (run_budget.zig depth>0 guard), surfacing as an is_error subagent tool_result classified [model-call-budget failure] with retry ruled out - and the ROOT takes call 2 as the landing call. Deleting the guard lets a worker eat the last slot and the run dies narrating.", "args": ["--max-model-calls", "2"], "prompt": "spawn a subagent to survey the payments module, then summarize what happened", "script": [{"tool": "subagent", "arguments": {"description": "survey payments", "prompt": "read every file under payments/ and list the exported functions"}}, {"text": "landing: the survey child was refused by the run budget; nothing was surveyed and nothing is verified"}], "assert": [{"event": {"type": "tool_call", "name": "subagent"}}, {"event": {"type": "tool_result", "name": "subagent", "is_error": true}}, {"request_contains": {"index": -1, "text": "model-call budget exhausted for this graff run"}}, {"request_contains": {"index": -1, "text": "[model-call-budget failure]"}}, {"request_contains": {"index": -1, "text": "retry is NOT safe as-is"}}, {"request_contains": {"index": -1, "text": "[budget landing]"}}, {"request_lacks": {"index": -1, "text": "\"todo_write\""}}, {"final_text_contains": "the survey child was refused"}]}+{"id": "child-refused-last-call-root-lands", "why": "#390 hard half (green regression lock): with cap 2, call 1 spawns a child; the child's acquire sees one slot left and is refused BEFORE the network (run_budget.zig depth>0 guard), surfacing as an is_error subagent tool_result classified [model-call-budget failure] with retry ruled out - and the ROOT takes call 2 as the landing call. Deleting the guard lets a worker eat the last slot and the run dies narrating. The bracket now also carries the attempt count - 1 attempt locks that a budget refusal is never blind-retried by the worker retry ladder.", "args": ["--max-model-calls", "2"], "prompt": "spawn a subagent to survey the payments module, then summarize what happened", "script": [{"tool": "subagent", "arguments": {"description": "survey payments", "prompt": "read every file under payments/ and list the exported functions"}}, {"text": "landing: the survey child was refused by the run budget; nothing was surveyed and nothing is verified"}], "assert": [{"event": {"type": "tool_call", "name": "subagent"}}, {"event": {"type": "tool_result", "name": "subagent", "is_error": true}}, {"request_contains": {"index": -1, "text": "model-call budget exhausted for this graff run"}}, {"request_contains": {"index": -1, "text": "[model-call-budget failure, 1 attempt]"}}, {"request_contains": {"index": -1, "text": "retry is NOT safe as-is"}}, {"request_contains": {"index": -1, "text": "[budget landing]"}}, {"request_lacks": {"index": -1, "text": "\"todo_write\""}}, {"final_text_contains": "the survey child was refused"}]}{"id": "uncapped-run-never-sees-landing-note", "why": "#390 containment (green regression lock): with no --max-model-calls the landing machinery must be invisible - no [budget landing] on any request and tools still offered on the last one. Guards the max_model_calls != 0 gate in agent_request.zig: a hand-rolled remaining()-style check saturates to 0 under cap 0 and would strip tools from every normal run.", "args": [], "prompt": "check the todo list and report", "script": [{"tool": "todo_read", "arguments": {}}, {"text": "uncapped: the list is checked and empty"}], "assert": [{"request_lacks": {"index": 0, "text": "[budget landing]"}}, {"request_lacks": {"index": -1, "text": "[budget landing]"}}, {"request_contains": {"index": -1, "text": "\"todo_write\""}}, {"final_text_contains": "uncapped: the list is checked"}]}{"id": "repair-ask-review-word-does-not-cross-cell", "why": "Intuition trap (green regression lock): 'fix the bug the review found in report.py' must cell as BUGFIX so its R0 decline parks in the bugfix column; the follow-up 'critique report.py' cells as REVIEW with a clean history and must get the plain R0 advisory, never the R0d revision prescription. Fails if the decline ledger collapses to one counter or classOf lets the word 'review' inside a repair ask steal the cell. Live replay measures whether the model treats the two asks as different kinds of work.", "args": [], "prompt": "ultracode fix the bug the review found in report.py", "script": [{"tool": "workflow", "arguments": {"phases": [{"title": "find the defect", "tasks": [{"description": "find", "prompt": "read report.py and locate the defect"}]}, {"title": "implement the fix", "tasks": [{"description": "fix", "prompt": "fix the defect in report.py"}]}]}}, {"text": "declined, so I repaired report.py myself"}, {"tool": "workflow", "arguments": {"phases": [{"title": "find problems", "tasks": [{"description": "find", "prompt": "read report.py and list the problems"}]}, {"title": "verify each finding", "tasks": [{"description": "verify", "prompt": "verify the problems in report.py"}]}]}}, {"text": "declined again with the plain advisory, so I critiqued report.py solo"}], "second_prompt": "now ultracode critique report.py, the earlier pass missed real problems", "assert": [{"events_at_least": {"match": {"type": "tool_result", "name": "workflow", "is_error": false}, "count": 2}}, {"request_contains": {"index": 1, "text": "(escalation R0):"}}, {"request_contains": {"index": -1, "text": "(escalation R0):"}}, {"request_lacks": {"index": -1, "text": "(escalation R0d):"}}, {"request_lacks": {"index": -1, "text": "revision case"}}, {"final_text_contains": "critiqued report.py solo"}]}{"id": "escalation-audit-fleet-unaffordable-declines", "why": "GREEN regression lock, the affordability boundary: same audit ask as the R3 case, but --max-model-calls 23 leaves 22 calls at admission — spendable 16 after the landing reserve, one short of the review fleetFloor (17) — so even paid-for breadth must decline to R0, non-error. The authored plan itself (6 calls) FITS, so only the fleetFloor+reserve gate stands between decline and spawn: drop the reserve from Ledger.spendable, or the fleet_affordable term from the R3 branch, and this exact case spawns a fleet.", "args": ["--max-model-calls", "23"], "prompt": "run a thorough audit of the error handling across the codebase and report what you find", "script": [{"tool": "workflow", "arguments": {"phases": [{"title": "find problems", "tasks": [{"description": "auditor", "prompt": "audit the error handling and list every problem with evidence"}]}, {"title": "synthesize the findings", "tasks": [{"description": "synthesis", "prompt": "rank the problems most-severe first"}]}]}}, {"text": "pool too dry for a fleet — auditing solo as advised"}], "assert": [{"request_contains": {"index": 1, "text": "workflow declined (escalation R0):"}}, {"request_contains": {"index": 1, "text": "budget and scope fit solo work"}}, {"request_lacks": {"index": 1, "text": "(escalation R0d):"}}, {"no_event": {"type": "agent_route"}}, {"event": {"type": "tool_result", "name": "workflow", "is_error": false}}, {"final_text_contains": "auditing solo"}]}diff --git a/src/agent_request.zig b/src/agent_request.zigindex 5fc7f3bf..c0669a13 100644--- a/src/agent_request.zig+++ b/src/agent_request.zig@@ -267,7 +267,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {if (err == error.RateLimited and main_mod.g_5xx_body_len > 0 andisQuotaExceeded(main_mod.g_5xx_body_buf[0..main_mod.g_5xx_body_len])){- self.last_api_error = std.fmt.allocPrint(self.arena, "rate limited (429): quota/billing cap — {s}", .{main_mod.g_5xx_body_buf[0..main_mod.g_5xx_body_len]}) catch "rate limited (429): quota exceeded";+ self.last_api_error = std.fmt.allocPrint(self.arena, "rate limited (429): {s} — {s}", .{ policy.quota_cap_marker, main_mod.g_5xx_body_buf[0..main_mod.g_5xx_body_len] }) catch "rate limited (429): quota exceeded";if (telemetry.g_telem) |t| t.errorEvent("quota", self.last_api_error orelse "quota exceeded");if (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, 0, body.len, 0, 0, 0, true);return error.ApiError;diff --git a/src/agent_request_policy.zig b/src/agent_request_policy.zigindex 96309d51..f0c3602d 100644--- a/src/agent_request_policy.zig+++ b/src/agent_request_policy.zig@@ -168,6 +168,14 @@ test "isTransientServerError (#opencode-parity): overload/server_error retry; qu/// "exceeded your current quota", "quota exceeded") — a usage limit a retry can't/// clear, unlike transient rate-limit throttling — so we fail fast + fail over rather/// than burning retry attempts.+/// The phrase agent_request stamps into `last_api_error` when a 429 body named+/// a billing/credit cap rather than transient throttling. It is a const, not a+/// literal spelled twice, because a second reader now depends on it: a worker's+/// in-turn retry ladder (subagent_retry.hardQuotaCap) reads this marker back+/// out of the message to tell "the account is capped" — where re-asking is+/// pure waste — from "slow down", where re-asking is the whole point.+pub const quota_cap_marker = "quota/billing cap";+pub fn isQuotaExceeded(body: []const u8) bool {return util.indexOfIgnoreCase(body, "insufficient_quota") != null orutil.indexOfIgnoreCase(body, "insufficient quota") != null ordiff --git a/src/subagent_retry.zig b/src/subagent_retry.zignew file mode 100644index 00000000..4786a244--- /dev/null+++ b/src/subagent_retry.zig@@ -0,0 +1,306 @@+//! Bounded, class-filtered retry for a FLEET WORKER's turn — the resilience+//! the root agent has had all along and a worker had none of.+//!+//! The root gets providers.runTurnWithFallback: on a clear auth/model failure+//! it re-runs the turn, rotating credentials. A WORKER got one shot —+//! subagent_run.runSub called agent.runTurn() exactly once and whatever came+//! back was final. A real fleet run showed the bill: four parallel reviewers+//! sharing ONE credential, one died with "api error: The API Key appears to+//! be invalid or may have expired" and the phase reported "subagent sa-001+//! failed before producing a report" while its three siblings, on that same+//! key, finished normally. A credential serving three concurrent workers is+//! not expired. That response was flaky or model-gated, and one re-ask would+//! very likely have saved the report.+//!+//! So: re-ask the SAME provider, a bounded number of times, only for the+//! failure classes where re-asking can help. That is deliberately the small+//! version (kimi-code's shape): no cross-provider failover for workers.+//! Provider locality is a consent boundary in this codebase+//! (subagent_run.childProvider), and a worker quietly answering from a+//! provider the user did not pick is a worse outcome than an honest failure.+//!+//! Weng gate — no verifier, no blind loop: every ladder here has a fixed+//! ceiling and a class filter, and both are visible to the caller. A hard auth+//! rejection retried ten times is abuse, not resilience, so auth gets exactly+//! ONE extra ask (that is all the sibling-success evidence licenses) before+//! the parent is told, verbatim, what failed and how many times it was tried.+//!+//! Layering: workflow.zig already retries a failed task once at the PHASE+//! level (a whole fresh worker). This sits BENEATH it, so one flaky HTTP+//! response is absorbed here instead of burning that phase-level retry. It+//! also sits ABOVE the request layer's own bounded ladders (http.RetryPlan's+//! 5-6 connection tries, agent_request's 2 stall/drop reconnects,+//! agent_request_policy's 3 in-stream overload retries) — and what it adds+//! that none of those can is RESUMPTION: a worker turn is many requests, and+//! re-entering runTurn re-asks against the history as it stands, so a stall on+//! the sixth request no longer throws away the first five.+//!+//! The cost of that layering, stated rather than hidden: a worker whose stream+//! stalls hopelessly now spends up to 3 asks x (1 + 2 reconnects) instead of+//! 1 x 3 before giving up. That ceiling is fixed, it is the price of not+//! discarding a nearly-finished worker over one bad socket, and a /loop+//! deadline (pastDeadline) cuts it short whenever the run has one.++const std = @import("std");++const subagent_run = @import("subagent_run.zig");+const FailKind = subagent_run.FailKind;+const http = @import("http.zig");+const policy = @import("agent_request_policy.zig");+const Tracer = @import("trace.zig").Tracer;+const util = @import("util.zig");++/// Total asks (the first one included) a transient failure class is worth.+/// Three, not kimi-code's ten: a worker is one of N parallel siblings sharing+/// a credential AND the run's model-call budget, so a long private ladder here+/// multiplies across the whole fleet — and the phase-level retry in+/// workflow.zig still sits above this with a pass of its own.+pub const transient_attempts: u8 = 3;++/// Total asks an auth-shaped rejection is worth: the first, plus ONE.+/// Justified by exactly one observation and no more — siblings succeeding on+/// the same credential at the same moment means the rejection can be flaky. If+/// the key really is dead the second ask says so too, and it stops there.+pub const auth_attempts: u8 = 2;++/// Billing/credit refusals that no amount of waiting clears. Mirrors the two+/// places the rest of the harness already decided this: the marker+/// agent_request stamps on a capped 429 (policy.quota_cap_marker, checked+/// below) and providers.zig's `gateway_billing` needles. Kept as text matching+/// because that is all a worker HAS — by the time a failure reaches here it is+/// a `last_api_error` string, the status code and body are gone.+const hard_cap_needles = [_][]const u8{+ policy.quota_cap_marker,+ "credits exhausted",+ "insufficient credits",+ "credit balance",+ "no credits",+ "out of credits",+ "billing limit",+ "billing_hard_limit_reached",+ "billing hard limit",+};++/// Is this `.quota` failure the account being CAPPED rather than throttled?+/// The classifier folds both into one FailKind (`quota` matches "quota",+/// "billing", "credits", "429", "overloaded" alike), and they want opposite+/// treatment: a cap is as structural as a bad model id, while a throttle is+/// the single case where the server has told us that waiting works.+pub fn hardQuotaCap(detail: ?[]const u8) bool {+ const msg = detail orelse return false;+ if (policy.isQuotaExceeded(msg)) return true;+ for (hard_cap_needles) |n| if (util.indexOfIgnoreCase(msg, n) != null) return true;+ return false;+}++/// How many times this worker may ask, given what the last failure looked+/// like. `1` means "the ask that just failed was the only one worth making".+/// `detail` is the raw `last_api_error`: the CLASS alone is too coarse for+/// `.quota`, so the one class that spans both a retryable and an unretryable+/// failure is split on the text the request layer already wrote.+pub fn attemptBudget(kind: FailKind, detail: ?[]const u8) u8 {+ return switch (kind) {+ // Wire flakes and shapes we could not classify: the classes where the+ // same request can genuinely succeed next time.+ .transport, .unknown => transient_attempts,+ // A throttle or an overload keeps the ladder — that is a server saying+ // "later", and later is exactly what a retry offers. A hard cap does+ // not: agent_request.zig:263 already refused to spend its own 5+ // throttle attempts on one, so spending 3 worker asks here would undo+ // that decision one layer up and bill the user for the privilege.+ .quota => if (hardQuotaCap(detail)) 1 else transient_attempts,+ .auth => auth_attempts,+ // Structural: an unavailable model, a malformed request, or the+ // harness's own dry call budget. Re-asking is guaranteed to fail+ // identically, and is still CHARGED for trying.+ .model, .invalid, .budget_exhausted => 1,+ };+}++/// Which error VALUES are wire failures at all. Classification alone is not+/// enough of a gate: a stale `last_api_error` mentioning "503" must never earn+/// a retry for an error.OutOfMemory or an error.Interrupted, and a user's Esc+/// is a decision, not a flake.+pub fn eligibleError(err: anyerror) bool {+ return switch (err) {+ error.ApiError, error.StreamStalled, error.StreamDropped => true,+ else => false,+ };+}++/// The whole gate: `attempts_done` asks have been made and the last one failed+/// with `err` (classified `kind`, cause text `detail`) — is another warranted?+pub fn shouldRetry(err: anyerror, kind: FailKind, detail: ?[]const u8, attempts_done: u8) bool {+ if (!eligibleError(err)) return false;+ return attempts_done < attemptBudget(kind, detail);+}++/// Backoff before the ask that follows `attempts_done`. Reuses the request+/// layer's own ladder (http.RetryPlan) so there is one backoff policy in the+/// codebase, not two that drift.+pub fn backoffMs(kind: FailKind, attempts_done: u8) u64 {+ const prior: usize = if (attempts_done == 0) 0 else attempts_done - 1;+ return switch (kind) {+ // The sibling-success case: waiting does not un-expire a key, so if+ // this is going to work it works now. Short enough to be honest about+ // being an immediate re-ask, long enough not to hammer.+ .auth => 250,+ // A refusal that named a limit is the one case where the server is+ // telling us to wait; give it the throttle ladder (1s, 2s).+ .quota => http.RetryPlan.delayMs(true, prior),+ // Flake ladder (250ms, 500ms).+ else => http.RetryPlan.delayMs(false, prior),+ };+}++/// A /loop deadline the run has already passed buys nothing by being waited+/// out — the parent will discard the late answer anyway. Pure so the call site+/// stays testable without a clock.+pub fn pastDeadline(now_ms: i64, deadline_ms: ?i64) bool {+ const d = deadline_ms orelse return false;+ return now_ms >= d;+}++/// "attempt" / "attempts" — the failure text names a count, so it has to read+/// like English or it reads like a bug.+pub fn attemptsWord(n: u8) []const u8 {+ return if (n == 1) "attempt" else "attempts";+}++/// One trace line per re-ask, naming the worker, which ask this is, the class+/// that bought it, and the cause. Without this a retried worker looks in the+/// trace exactly like a worker that was simply slow.+pub fn traceAttempt(tracer: ?*Tracer, sub_id: []const u8, attempts_done: u8, kind: FailKind, cause: ?[]const u8) void {+ const tr = tracer orelse return;+ var buf: [320]u8 = undefined;+ const detail = std.fmt.bufPrint(&buf, "{s} retrying (ask {d} of {d}) after a {s} failure: {s}", .{+ sub_id,+ @as(u16, attempts_done) + 1,+ attemptBudget(kind, cause),+ kind.label(),+ util.utf8Prefix(cause orelse "no cause recorded", 160),+ }) catch "worker retry";+ tr.note("subagent_retry", detail);+}++/// The ceiling the module is CLAIMING, written as a literal so the assertions+/// below cannot be satisfied by moving the constant they are meant to police.+const asserted_ceiling: u8 = 3;++test "attemptBudget: transient classes get a bounded ladder, structural ones get none" {+ // The classes where the identical request can succeed next time.+ try std.testing.expectEqual(@as(u8, transient_attempts), attemptBudget(.transport, null));+ try std.testing.expectEqual(@as(u8, transient_attempts), attemptBudget(.quota, "429 too many requests"));+ try std.testing.expectEqual(@as(u8, transient_attempts), attemptBudget(.unknown, null));+ // Auth: the first ask plus exactly one more — never the transient ladder.+ try std.testing.expectEqual(@as(u8, 2), attemptBudget(.auth, null));+ try std.testing.expect(attemptBudget(.auth, null) < attemptBudget(.transport, null));+ // Structural: re-asking cannot help and is still charged for.+ try std.testing.expectEqual(@as(u8, 1), attemptBudget(.model, null));+ try std.testing.expectEqual(@as(u8, 1), attemptBudget(.invalid, null));+ try std.testing.expectEqual(@as(u8, 1), attemptBudget(.budget_exhausted, null));+ // Every ladder is finite and small — the Weng gate, asserted against a+ // LITERAL ceiling. `<= transient_attempts` would have been self-referential:+ // it holds just as well at transient_attempts = 100, which is the exact+ // property the comment claims to rule out.+ try std.testing.expect(transient_attempts <= asserted_ceiling);+ try std.testing.expect(auth_attempts <= asserted_ceiling);+ for ([_]FailKind{ .quota, .transport, .model, .invalid, .auth, .budget_exhausted, .unknown }) |k| {+ for ([_]?[]const u8{ null, "429 too many requests", "insufficient_quota" }) |d| {+ try std.testing.expect(attemptBudget(k, d) >= 1);+ try std.testing.expect(attemptBudget(k, d) <= asserted_ceiling);+ }+ }+}++test "attemptBudget: a hard billing cap gets ONE ask; genuine throttling keeps the ladder" {+ // agent_request.zig:263 already decided a capped 429 is not transient and+ // failed fast rather than burn its own 5 throttle attempts (~23s) on it.+ // A worker ladder that re-asked 3x would silently undo that — same refusal,+ // three times, each one billed.+ try std.testing.expectEqual(@as(u8, 1), attemptBudget(.quota, "rate limited (429): quota/billing cap — {\"error\":{\"code\":\"insufficient_quota\"}}"));+ try std.testing.expect(hardQuotaCap("rate limited (429): " ++ policy.quota_cap_marker ++ " — capped"));+ // The gateway/provider phrasings providers.zig already treats as billing.+ try std.testing.expectEqual(@as(u8, 1), attemptBudget(.quota, "You have run out of credits or need a Grok subscription."));+ try std.testing.expectEqual(@as(u8, 1), attemptBudget(.quota, "Your credit balance is too low to access the Anthropic API"));+ try std.testing.expectEqual(@as(u8, 1), attemptBudget(.quota, "insufficient credits"));+ try std.testing.expectEqual(@as(u8, 1), attemptBudget(.quota, "Billing limit reached for this organization"));+ try std.testing.expectEqual(@as(u8, 1), attemptBudget(.quota, "You exceeded your current quota, please check your plan"));++ // Genuine rate limiting / overload: the server said "later", and later is+ // precisely what a re-ask offers. These keep the full ladder.+ try std.testing.expectEqual(@as(u8, transient_attempts), attemptBudget(.quota, "rate limited (429): Rate limit reached. Please try again in 20s."));+ try std.testing.expectEqual(@as(u8, transient_attempts), attemptBudget(.quota, "429 too many requests"));+ try std.testing.expectEqual(@as(u8, transient_attempts), attemptBudget(.quota, "overloaded"));+ // No cause recorded at all: unknowable, so it keeps the transient default+ // rather than being punished for the harness failing to capture text.+ try std.testing.expectEqual(@as(u8, transient_attempts), attemptBudget(.quota, null));+ try std.testing.expect(!hardQuotaCap(null));++ // And the gate that actually spends it agrees, both ways.+ try std.testing.expect(!shouldRetry(error.ApiError, .quota, "rate limited (429): quota/billing cap — no credits", 1));+ try std.testing.expect(shouldRetry(error.ApiError, .quota, "429 too many requests", 1));+}++test "eligibleError: only wire-level turn failures are retryable at all" {+ try std.testing.expect(eligibleError(error.ApiError));+ try std.testing.expect(eligibleError(error.StreamStalled));+ try std.testing.expect(eligibleError(error.StreamDropped));+ // An Esc is a decision, not a flake.+ try std.testing.expect(!eligibleError(error.Interrupted));+ // The harness's own ceilings and local failures are not wire failures.+ try std.testing.expect(!eligibleError(error.RunBudgetExhausted));+ try std.testing.expect(!eligibleError(error.OutOfMemory));+ try std.testing.expect(!eligibleError(error.FileNotFound));+}++test "shouldRetry: the gate needs BOTH a wire error and unspent budget" {+ // The observed failure: an auth-shaped rejection while siblings succeed.+ // One re-ask, then honest surfacing.+ try std.testing.expect(shouldRetry(error.ApiError, .auth, null, 1));+ try std.testing.expect(!shouldRetry(error.ApiError, .auth, null, 2));+ // A transient class walks the full ladder and then stops. Bounded.+ try std.testing.expect(shouldRetry(error.ApiError, .transport, null, 1));+ try std.testing.expect(shouldRetry(error.StreamDropped, .transport, null, 2));+ try std.testing.expect(!shouldRetry(error.StreamDropped, .transport, null, 3));+ try std.testing.expect(!shouldRetry(error.ApiError, .quota, null, 99));+ // Structural failures never get a second ask, not even the first retry.+ try std.testing.expect(!shouldRetry(error.ApiError, .model, null, 1));+ try std.testing.expect(!shouldRetry(error.ApiError, .invalid, null, 1));+ try std.testing.expect(!shouldRetry(error.ApiError, .budget_exhausted, null, 1));+ // A retryable-looking CLASS cannot rescue a non-wire error value: this is+ // the arm that stops a stale envelope from retrying an interrupt or an OOM.+ try std.testing.expect(!shouldRetry(error.Interrupted, .transport, null, 1));+ try std.testing.expect(!shouldRetry(error.OutOfMemory, .unknown, null, 1));+ try std.testing.expect(!shouldRetry(error.RunBudgetExhausted, .quota, null, 1));+}++test "backoffMs: bounded waits; a named limit waits longer than a flake" {+ // Auth re-asks near-immediately — waiting does not un-expire a key.+ try std.testing.expectEqual(@as(u64, 250), backoffMs(.auth, 1));+ // A throttle gets the server-directed ladder; a flake gets the short one.+ try std.testing.expect(backoffMs(.quota, 1) > backoffMs(.transport, 1));+ try std.testing.expectEqual(@as(u64, 250), backoffMs(.transport, 1));+ try std.testing.expectEqual(@as(u64, 500), backoffMs(.transport, 2));+ // Nothing on any ladder we can actually reach is a long sleep: the whole+ // in-worker budget must stay far under the phase-level retry it sits under.+ for ([_]FailKind{ .transport, .quota, .unknown, .auth }) |k| {+ var a: u8 = 0;+ var total: u64 = 0;+ while (a < attemptBudget(k, null)) : (a += 1) total += backoffMs(k, a);+ try std.testing.expect(total <= 4000);+ }+}++test "pastDeadline: no /loop deadline never blocks a retry; a passed one always does" {+ try std.testing.expect(!pastDeadline(1_000, null));+ try std.testing.expect(!pastDeadline(999, 1_000));+ try std.testing.expect(pastDeadline(1_000, 1_000));+ try std.testing.expect(pastDeadline(1_001, 1_000));+}++test "attemptsWord: the count in the failure text reads like English" {+ try std.testing.expectEqualStrings("attempt", attemptsWord(1));+ try std.testing.expectEqualStrings("attempts", attemptsWord(2));+ try std.testing.expectEqualStrings("attempts", attemptsWord(transient_attempts));+}diff --git a/src/subagent_run.zig b/src/subagent_run.zigindex 3461942d..7daa82eb 100644--- a/src/subagent_run.zig+++ b/src/subagent_run.zig@@ -27,6 +27,7 @@ const cards = @import("cards.zig");const trace = @import("trace.zig");const textMessage = @import("messages.zig").textMessage;const protocol_seq = @import("protocol_seq.zig"); // #330: monotonic `seq` on every --json event+const subagent_retry = @import("subagent_retry.zig"); // bounded in-worker re-ask: the failover the root has and a worker did notfn guiEmit(io: Io, ev: anytype) void {if (!main_mod.json_mode) return;@@ -54,7 +55,7 @@ pub const FailKind = enum {budget_exhausted,unknown,- fn label(self: FailKind) []const u8 {+ pub fn label(self: FailKind) []const u8 {return switch (self) {.quota => "quota/rate-limit",.transport => "transport",@@ -127,14 +128,28 @@ pub const retry_ok_note = "retry is likely safe — re-run the same task (after/// chance of success. failureAllowsRetry keys off this exact string.pub const retry_unsafe_note = "retry is NOT safe as-is — fix the cause first (switch model, correct arguments, or re-auth)";-fn subagentFailure(gpa: Allocator, sub_id: []const u8, err: anyerror, detail: ?[]const u8) ToolOutput {+/// The one text the parent reads when a worker dies. `attempts` is how many+/// asks this worker actually made (subagent_retry's bounded ladder), and it is+/// in the string on purpose: "failed before producing a report" left the+/// parent unable to tell a worker that was never really tried from one that+/// was tried three times and refused every time. Naming the count is the+/// honesty half of adding a retry at all.+///+/// It rides in the CLASS bracket, after the cause, not in the prefix. The+/// prefix is scarce: workflow.zig head-slices this text at fail_excerpt_cap+/// (200 chars) precisely because the cause sits immediately behind+/// "…failed before producing a report: ", so every character spent before the+/// colon is a character of real provider error deleted from the next phase's+/// {{prev}}. "failed after 3 attempts before producing a report:" cost ~17 of+/// them; this ordering keeps the count and the prefix.+fn subagentFailure(gpa: Allocator, sub_id: []const u8, err: anyerror, detail: ?[]const u8, attempts: u8) ToolOutput {const kind = classifyFailure(err, detail);const cause = detail orelse @errorName(err);const retry = if (kind.retrySafe()) retry_ok_note else retry_unsafe_note;const text = std.fmt.allocPrint(gpa,- "subagent {s} failed before producing a report: {s} [{s} failure]. {s}",- .{ sub_id, cause, kind.label(), retry },+ "subagent {s} failed before producing a report: {s} [{s} failure, {d} {s}]. {s}",+ .{ sub_id, cause, kind.label(), attempts, subagent_retry.attemptsWord(attempts), retry },) catch return .{ .is_error = true };return .{ .text = text, .is_error = true };}@@ -332,7 +347,29 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []constconst task_prompt = playbook.rideBrief(ctx.io, arena, try goal_pacing.childTaskPrompt(arena, prompt, ctx.loop_deadline_ms, util.unixMs(ctx.io)));try agent.messages.append(try textMessage(arena, "user", task_prompt));defer agent.tools_used.deinit(gpa);- const report = agent.runTurn();+ // Bounded in-worker re-ask. The ROOT has failover (runTurnWithFallback);+ // a worker had one shot, so a single flaky response cost a whole report+ // while its siblings on the same credential finished. subagent_retry owns+ // the ceiling and the class filter — this loop only spends them, on the+ // SAME provider (no worker cross-provider failover: see that module).+ // Resuming runTurn re-issues a request against the history as it stands,+ // so nothing already executed is replayed; a wire failure lands before any+ // assistant message is appended, which is what keeps that true.+ var attempts: u8 = 0;+ const report: anyerror![]const u8 = ask: {+ while (true) {+ attempts += 1;+ agent.last_api_error = null; // a stale cause must never classify the next ask+ const r = agent.runTurn();+ const err = if (r) |_| break :ask r else |e| e;+ const fail_kind = classifyFailure(err, agent.last_api_error);+ if (!subagent_retry.shouldRetry(err, fail_kind, agent.last_api_error, attempts)) break :ask r;+ // A /loop deadline the run is already past makes waiting pointless.+ if (subagent_retry.pastDeadline(util.unixMs(ctx.io), ctx.loop_deadline_ms)) break :ask r;+ subagent_retry.traceAttempt(ctx.tracer, sub_id, attempts, fail_kind, agent.last_api_error);+ agent.sleepInterruptible(subagent_retry.backoffMs(fail_kind, attempts)) catch break :ask r;+ }+ };const run_ms: i64 = @intCast(@max(0, sub_start.untilNow(ctx.io, .awake).toMilliseconds()));const run_ok = if (report) |r| r.len > 0 else |_| false;if (wf_task) {@@ -375,7 +412,7 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const}if (telemetry.g_telem) |t| t.runEvent(&fp, sys_override != null, run_ok, run_ms, used_tools);const text = report catch |err| {- var out = subagentFailure(gpa, sub_id, err, agent.last_api_error);+ var out = subagentFailure(gpa, sub_id, err, agent.last_api_error, attempts);if (wt) |w| {const combined = std.fmt.allocPrint(gpa, "{s}\n\n[worktree left in place after failure — path: {s}, branch: {s}]", .{ out.text, w.path, w.branch }) catch return .{ .output = out, .usage = usage };gpa.free(out.text);@@ -442,13 +479,13 @@ test "failureAllowsRetry keys off the harness's own retry-safety classification"// A real auth failure: subagentFailure classifies it .auth (retrySafe:// false) and appends retry_unsafe_note — the gate must block a retry.- const auth = subagentFailure(gpa, "sa-001", error.Unexpected, "401 unauthorized: invalid_api_key");+ const auth = subagentFailure(gpa, "sa-001", error.Unexpected, "401 unauthorized: invalid_api_key", 2);defer gpa.free(auth.text);try std.testing.expect(!failureAllowsRetry(auth.text));// A real transport/transient failure: classifies .transport (retrySafe:// true) and appends retry_ok_note — the gate must keep allowing retries.- const transient = subagentFailure(gpa, "sa-002", error.StreamStalled, null);+ const transient = subagentFailure(gpa, "sa-002", error.StreamStalled, null, 3);defer gpa.free(transient.text);try std.testing.expect(failureAllowsRetry(transient.text));@@ -458,6 +495,44 @@ test "failureAllowsRetry keys off the harness's own retry-safety classification"try std.testing.expect(failureAllowsRetry("subagent finished without a report"));}+test "a worker failure names how many asks it actually made (fleet honesty)" {+ const gpa = std.testing.allocator;++ // The observed run: one worker refused with an auth-shaped error while its+ // siblings on the SAME credential succeeded. subagent_retry buys that one+ // extra ask — and the parent must be able to tell "asked twice, refused+ // twice" from "never really tried". The old text said neither.+ const detail = "api error: The API Key appears to be invalid or may have expired.";+ const twice = subagentFailure(gpa, "sa-001-abcd", error.ApiError, detail, subagent_retry.auth_attempts);+ defer gpa.free(twice.text);+ try std.testing.expect(std.mem.indexOf(u8, twice.text, "[auth failure, 2 attempts]") != null);+ try std.testing.expect(std.mem.indexOf(u8, twice.text, detail) != null); // cause still verbatim+ try std.testing.expect(!failureAllowsRetry(twice.text)); // auth still blocks the PHASE retry above++ // The count must NOT push the cause out of workflow.zig's head-slice: the+ // prefix stays exactly as long as it was before retries existed, so the+ // 200-char excerpt still carries the provider's own words.+ try std.testing.expect(std.mem.startsWith(u8, twice.text, "subagent sa-001-abcd failed before producing a report: api error:"));+ const head = twice.text[0..@min(200, twice.text.len)]; // workflow.fail_excerpt_cap+ try std.testing.expect(std.mem.indexOf(u8, head, detail) != null);++ // A structural failure is asked once and says so — no plural implying a+ // ladder that never ran.+ const once = subagentFailure(gpa, "sa-002-abcd", error.ApiError, "model_not_found", 1);+ defer gpa.free(once.text);+ try std.testing.expect(std.mem.indexOf(u8, once.text, "[model-availability failure, 1 attempt]") != null);++ // The ladder runSub's loop can actually spend. Pinned here because these+ // are the numbers the sentence above is claiming to report.+ try std.testing.expectEqual(@as(u8, 2), subagent_retry.attemptBudget(.auth, null));+ try std.testing.expectEqual(@as(u8, 3), subagent_retry.attemptBudget(.transport, null));+ try std.testing.expectEqual(@as(u8, 1), subagent_retry.attemptBudget(.model, null));+ // A billing cap wearing the .quota label gets ONE ask, not the ladder —+ // the request layer already refused to keep paying for that refusal.+ try std.testing.expectEqual(@as(u8, 1), subagent_retry.attemptBudget(.quota, "rate limited (429): quota/billing cap — insufficient_quota"));+ try std.testing.expectEqual(@as(u8, 3), subagent_retry.attemptBudget(.quota, "rate limited (429): please retry shortly"));+}+test "a child's api-error cause reaches the parent verbatim (#287/#299)" {const gpa = std.testing.allocator;var arena_state = std.heap.ArenaAllocator.init(gpa);@@ -490,7 +565,7 @@ test "a child's api-error cause reaches the parent verbatim (#287/#299)" {// This is the wiring runSub depends on: agent.last_api_error ->// subagentFailure -> the string the parent's tool result carries.- const out = subagentFailure(gpa, "sa-001-abcd", error.ApiError, child.last_api_error);+ const out = subagentFailure(gpa, "sa-001-abcd", error.ApiError, child.last_api_error, 1);defer gpa.free(out.text);try std.testing.expect(out.is_error);try std.testing.expect(std.mem.indexOf(u8, out.text, detail) != null); // verbatimdiff --git a/src/subagent_tests.zig b/src/subagent_tests.zigindex aad3031f..36b68f9d 100644--- a/src/subagent_tests.zig+++ b/src/subagent_tests.zig@@ -82,7 +82,7 @@ test "agentStatusText: running/completed/failed shapes carry the usage summary,try std.testing.expect(std.mem.indexOf(u8, ok, "3 tool call") != null);try std.testing.expect(std.mem.indexOf(u8, ok, "final report") != null);- const failed_text = "subagent sa-014-abcd failed before producing a report: connection reset [transport failure]. retry is likely safe";+ const failed_text = "subagent sa-014-abcd failed before producing a report: connection reset [transport failure, 3 attempts]. retry is likely safe";const failed = try subagent.agentStatusText(gpa, 9, true, true, .{ .duration_ms = 300 }, failed_text);defer gpa.free(failed);try std.testing.expect(std.mem.indexOf(u8, failed, "failed") != null); // status names the failure — never silentdiff --git a/src/workflow_test.zig b/src/workflow_test.zigindex d32fbc97..451aa873 100644--- a/src/workflow_test.zig+++ b/src/workflow_test.zig@@ -102,7 +102,10 @@ test "buildAbortText names the phase index and title, and surfaces each failed tconst labels = [_][]const u8{ "scan A", "scan B" };// Parallel per-task excerpts: one real API error, one task that left// nothing to report.- const details = [_][]const u8{ "subagent sa-001 failed before producing a report: 429 rate_limit_exceeded [quota failure].", "" };+ // Mirrors what subagentFailure actually emits today, attempt count and all+ // — a fixture that has drifted from production cannot catch the excerpt+ // regressing, which is the only thing this test is for.+ const details = [_][]const u8{ "subagent sa-001 failed before producing a report: 429 rate_limit_exceeded [quota/rate-limit failure, 3 attempts]. retry is likely safe", "" };const text = try buildAbortText(a, &labels, &details, 2, 3, "Recon");// Every failed task's header survives, so a human can see what was tried.@@ -125,7 +128,7 @@ test "failExcerpt keeps the API error on one capped line, and stays empty when t// A real subagentFailure text: the cause survives, flattened, so it can sit// under a "### label" header without breaking that layout.- const raw = "subagent sa-001 failed before producing a report:\n{\"error\":\"rate_limit_exceeded\"}\t[quota failure].";+ const raw = "subagent sa-001 failed before producing a report:\n{\"error\":\"rate_limit_exceeded\"}\t[quota/rate-limit failure, 3 attempts]. retry is likely safe";const one = failExcerpt(a, raw);try std.testing.expect(std.mem.indexOf(u8, one, "rate_limit_exceeded") != null);try std.testing.expect(std.mem.indexOfAny(u8, one, "\n\r\t") == null);