Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

feat(escalation): R0d rung — a verifier-gated revision before the fleet

justracha87f1dbbc9ad
diff --git a/src/agent_eval.zig b/src/agent_eval.zig
index bf63c9ca..16c963de 100644
--- a/src/agent_eval.zig
+++ b/src/agent_eval.zig
@@ -26,6 +26,8 @@ const main_mod = @import("main.zig");
const route_policy = @import("route_policy.zig"); // #372 (shape, role, tier) coordinates on the local capture rows
const playbook_reflect = @import("playbook_reflect.zig"); // #383 Reflector: one bounded distillation per process, on a target-met eval
const orch_rows = @import("orchestration_rows.zig"); // the orchestration outcome rides the same score funnel
+const shapes = @import("shapes.zig");
+const failure_evidence = @import("failure_evidence.zig"); // a RED verdict is parked as escalation evidence
test {
_ = @import("agent_eval_tests.zig");
@@ -102,6 +104,14 @@ pub fn runEval(self: *Agent, note: []const u8) !ExecResult {
const met = if (combined) |s| s >= target_f else false;
self.eval_repair_pending = exit_code != 0 or !met;
self.eval_verified = !self.eval_repair_pending;
+ // A RED verdict is harness ground truth about a FAILED attempt: park a
+ // capped excerpt so the next escalation decision carries the evidence
+ // (the R0d revision advisory, or an R3 fleet's briefs).
+ if (exit_code != 0 or !met) {
+ var ev_buf: [256]u8 = undefined;
+ const ev = std.fmt.bufPrint(&ev_buf, "eval RED: score {d:.1}/100 (target {d}, exit {d}) — {s}", .{ combined orelse -1.0, self.eval_target, exit_code, utf8Prefix(note, 128) }) catch "eval RED: scoring command failed";
+ failure_evidence.note(shapes.classOf(shapes.rawAsk()), ev);
+ }
// A green eval refunds the RED-continuation budget (see grantRepairTurn):
// red→repair→green→red progress cycles keep running; only sustained
// failure exhausts it.
@@ -315,6 +325,7 @@ pub fn runJudge(self: *Agent, rubric: []const u8, eval_output: []const u8, note:
.subagent_cross_provider = self.subagent_cross_provider,
.registry = if (self.sub) null else self.registry,
.from_sub = self.sub,
+ .has_eval = self.eval_cmd != null,
.approvals = self.approvals,
.tracer = self.tracer,
.run_budget = self.run_budget,
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index 5c0f45b3..c34d45e1 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -140,6 +140,7 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {
.subagent_cross_provider = self.subagent_cross_provider,
.registry = if (self.sub) null else self.registry,
.from_sub = self.sub,
+ .has_eval = self.eval_cmd != null,
.approvals = self.approvals,
.tracer = self.tracer,
.run_budget = self.run_budget,
@@ -149,9 +150,8 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {
.loop_deadline_ms = self.loop_deadline_ms,
.agent_cwd = self.agent_cwd,
};
- // Esc while tools run: spawn a stdin watcher for the duration of
- // the join (see esc_cancel). Subagents notice the flag mid-flight;
- // the root aborts the turn at its next runTurn iteration.
+ // Esc while tools run: a stdin watcher for the join (esc_cancel);
+ // subagents notice mid-flight, the root aborts at its next runTurn.
const esc_watch = !self.sub and self.in != null and main_mod.use_color and !main_mod.json_mode;
var esc_tio: ?tty.RawState = null;
var esc_fut: ?Io.Future(void) = null;
diff --git a/src/escalation.zig b/src/escalation.zig
index 6f4565e3..961a0ed4 100644
--- a/src/escalation.zig
+++ b/src/escalation.zig
@@ -24,6 +24,12 @@
//! breadth is what they are paying for), or a prior solo/scout
//! attempt already failed — first-attempt failure is the free
//! escalation signal, and the only one worth trusting.
+//! R0d deep between R0 and the fleet: a FIRST failure on a 1-2 file ask
+//! is reasoning-shaped, not coverage-shaped, so the ladder
+//! prescribes one sequential revision carrying the observed
+//! failure evidence — but only where a verifier exists to catch
+//! a second miss (failure_evidence.zig). A second failure, or a
+//! verifier-less class, goes to R3: the judges are the feedback.
//!
//! Where a learned cell has evidence (orchestration_policy.zig) it overrides
//! the hand rung and the row says `source:"learned"`; otherwise the ladder
@@ -49,6 +55,7 @@ const route_policy = @import("route_policy.zig");
const orch = @import("orchestration_policy.zig");
const orch_rows = @import("orchestration_rows.zig");
const pb = @import("phase_budget.zig");
+const fe = @import("failure_evidence.zig");
const brief_diversity = @import("brief_diversity.zig");
const fleet = @import("fleet.zig");
const trace = @import("trace.zig");
@@ -75,6 +82,10 @@ pub const Observables = struct {
plan_estimate: u64 = 0,
audit: bool = false,
prior_failure: bool = false,
+ /// How MANY times this class already declined — 1 opens R0d, 2+ means the
+ /// deep retry was already spent and only the fleet is left.
+ prior_failure_count: u8 = 0,
+ verifier: fe.Verifier = .none,
remaining: u64 = 0,
cap: u64 = 0,
};
@@ -165,6 +176,8 @@ pub fn observe(phases: []const Value, raw: []const u8, shape: route_policy.Shape
.task_class = shapes.classOf(raw),
.audit = shapes.isAuditClass(raw),
.prior_failure = priorAttemptFailed(shapes.classOf(raw)),
+ .prior_failure_count = declineCount(shapes.classOf(raw)),
+ .verifier = fe.verifierFor(shapes.classOf(raw), false),
.remaining = remaining,
.cap = cap,
.plan_estimate = pb.planEstimate(phases),
@@ -202,13 +215,30 @@ pub const solo_advice =
"the files, make the edits, verify — and re-invoke the workflow tool only if verification fails, " ++
"which is the signal that earns a fleet.";
-/// The hand ladder's rung. Ordered by precedence, NOT by cost: the two
-/// escalation signals (an ask that asked for breadth, an attempt that already
-/// failed) are checked first, then the cheap rungs, and R0 is the fallthrough
-/// — so a plan that justifies nothing gets nothing.
+/// The R0d advisory. Same non-error contract as solo_advice; the difference
+/// is the prescription — a REVISION, not a redo: re-derive from the observed
+/// failure, not from the reasoning that already missed once.
+pub const deep_retry_advice =
+ "workflow declined (escalation R0d): the first solo attempt failed, but this is a revision case, " ++
+ "not a fleet case. Redo the work yourself, deeper: re-read the failure evidence, re-derive the " ++
+ "approach from that evidence rather than from your earlier reasoning, and verify against the " ++
+ "same signal before answering. If verification fails again, re-invoke the workflow tool — a " ++
+ "second failure earns the fleet.";
+
+/// The hand ladder's rung. Ordered by precedence, NOT by cost: the revision
+/// rung, then the two escalation signals (an ask that asked for breadth, an
+/// attempt that already failed), then the cheap rungs, and R0 is the
+/// fallthrough — so a plan that justifies nothing gets nothing.
pub fn ladderRung(o: Observables) Rung {
const l = pb.Ledger.init(o.cap);
const fleet_affordable = l.fits(o.remaining, pb.fleetFloor(o.shape));
+ // One deep solo retry before the fleet. Checked BEFORE affordability:
+ // a revision spends no spawns, so a pool too dry for a fleet can still
+ // afford it — and the failure that earns it is reasoning-shaped (small
+ // scope), which parallel sampling cannot fix. Weng's gate applies: no
+ // verifier, no revision loop.
+ if (o.prior_failure and !o.audit and o.prior_failure_count == 1 and
+ o.files < fleet_scope_min and o.verifier != .none) return .R0d;
if ((o.audit or o.prior_failure) and fleet_affordable) return .R3;
// An open-ended question is the one case where delegation pays for itself
// at width ONE: the scout burns its own context on the search and hands
@@ -259,6 +289,7 @@ pub fn verdictFor(rung: Rung, o: Observables, phases: []const Value) Verdict {
const l = pb.Ledger.init(o.cap);
switch (rung) {
.R0 => return .{ .solo = solo_advice },
+ .R0d => return .{ .solo = deep_retry_advice },
// One scout, one synthesis: cap every phase at a single task.
.R1 => return .{ .downsize = 1 },
.R2, .R3 => {
@@ -289,6 +320,10 @@ pub fn priorAttemptFailed(tc: shapes.TaskClass) bool {
return g_declined[@intFromEnum(tc)] > 0;
}
+pub fn declineCount(tc: shapes.TaskClass) u8 {
+ return g_declined[@intFromEnum(tc)];
+}
+
pub fn noteDeclined(tc: shapes.TaskClass) void {
const i = @intFromEnum(tc);
if (g_declined[i] < 255) g_declined[i] += 1;
@@ -298,6 +333,23 @@ pub fn noteDeclined(tc: shapes.TaskClass) void {
pub fn resetSession() void {
g_declined = @splat(0);
g_explore_used = false;
+ fe.reset();
+}
+
+/// R0d's advisory with the class's observed evidence appended. Falls back to
+/// the bare advisory on an empty ledger or OOM — the prescription stands even
+/// when the harness observed nothing concrete.
+pub fn deepRetryAdvice(arena: Allocator, tc: shapes.TaskClass) []const u8 {
+ const ev = fe.evidence(tc);
+ if (ev.len == 0) return deep_retry_advice;
+ return std.fmt.allocPrint(arena, "{s}\n\nPRIOR ATTEMPT EVIDENCE (verify against this, not against your recollection):\n{s}", .{ deep_retry_advice, ev }) catch deep_retry_advice;
+}
+
+/// The evidence for THIS turn's ask class — what workflow prepends to R3
+/// briefs so a post-failure fleet attacks the observed failure rather than a
+/// paraphrase of the original ask.
+pub fn evidenceForAsk() []const u8 {
+ return fe.evidence(shapes.classOf(shapes.rawAsk()));
}
/// A pipeline that could not fit the pool counts as a declined attempt for
@@ -370,6 +422,8 @@ pub const Ctx = struct {
used: u64 = 0,
/// The ROOT's resolved model: this decision's fitness stratum.
stratum: []const u8 = "",
+ /// An --eval loop is configured: the strongest verifier, any class.
+ has_eval: bool = false,
agent_cwd: ?[]const u8 = null,
};
@@ -387,6 +441,7 @@ pub fn ctxFrom(t: anytype, arena: Allocator) Ctx {
.cap = pb.capOf(t.run_budget),
.used = pb.usedOf(t.run_budget),
.stratum = t.provider.model,
+ .has_eval = t.has_eval,
.agent_cwd = t.agent_cwd,
};
}
@@ -427,7 +482,8 @@ fn armsFor(key: orch.Key) []const orch.ArmObs {
/// execWorkflow, before a single future is allocated.
pub fn admit(c: Ctx, phases: []const Value, shape: route_policy.Shape) Decision {
const raw = shapes.rawAsk();
- const o = observe(phases, raw, shape, c.remaining, c.cap);
+ var o = observe(phases, raw, shape, c.remaining, c.cap);
+ if (c.has_eval) o.verifier = .eval;
const key: orch.Key = .{
.task_class = o.task_class,
.budget_band = orch.BudgetBand.of(o.remaining),
@@ -443,6 +499,9 @@ pub fn admit(c: Ctx, phases: []const Value, shape: route_policy.Shape) Decision
d = .{ .rung = learned, .source = .learned, .verdict = verdictFor(learned, o, phases) };
}
}
+ // R0d's advisory carries the observed failure evidence, composed here
+ // because verdictFor is pure and the evidence needs the arena.
+ if (d.rung == .R0d) d.verdict = .{ .solo = deepRetryAdvice(c.arena, o.task_class) };
const collapse = predictedCollapse(c.arena, phases);
orch_rows.emitDecision(.{
.key = key,
@@ -526,6 +585,7 @@ fn predictedCollapse(arena: Allocator, phases: []const Value) CollapsePreview {
// Lives next door (600-line cap) and is re-exported whole, so a call site
// reaches the ladder and the landing guarantee through one import.
pub const edit_contract = @import("edit_contract.zig");
+pub const failure_evidence = fe;
pub const contract_unmet = edit_contract.contract_unmet;
pub const contract_brief_note = edit_contract.contract_brief_note;
pub const isContracted = edit_contract.isContracted;
@@ -535,5 +595,6 @@ pub const contractCheck = edit_contract.contractCheck;
test {
_ = edit_contract;
+ _ = fe;
_ = @import("escalation_tests.zig");
}
diff --git a/src/escalation_tests.zig b/src/escalation_tests.zig
index ba882652..c0af4841 100644
--- a/src/escalation_tests.zig
+++ b/src/escalation_tests.zig
@@ -267,6 +267,82 @@ test "countDistinctFiles: paths, not version numbers or sentence periods" {
try std.testing.expect(n >= escalation.fleet_scope_min);
}
+test "ladder: a first small-scope failure with a verifier is R0d — revision before fleet" {
+ var o = base();
+ o.prior_failure = true;
+ o.prior_failure_count = 1;
+ o.verifier = .diff;
+ try std.testing.expectEqual(Rung.R0d, escalation.ladderRung(o));
+ // R0d spends no spawns, so it stays admissible where a fleet is not.
+ o.remaining = 3;
+ try std.testing.expectEqual(Rung.R0d, escalation.ladderRung(o));
+ // A SECOND failure means the revision was already spent: fleet next.
+ o = base();
+ o.prior_failure = true;
+ o.prior_failure_count = 2;
+ o.verifier = .diff;
+ try std.testing.expectEqual(Rung.R3, escalation.ladderRung(o));
+ // No verifier, no revision loop (Weng's gate): the R3 judges ARE the
+ // external feedback a solo retry would lack.
+ o.prior_failure_count = 1;
+ o.verifier = .none;
+ try std.testing.expectEqual(Rung.R3, escalation.ladderRung(o));
+ // A coverage-shaped failure (3+ files) wants breadth, not revision.
+ o.verifier = .diff;
+ o.files = 4;
+ try std.testing.expectEqual(Rung.R3, escalation.ladderRung(o));
+ // Audit language keeps its precedence over the revision rung.
+ o = base();
+ o.prior_failure = true;
+ o.prior_failure_count = 1;
+ o.verifier = .diff;
+ o.audit = true;
+ try std.testing.expectEqual(Rung.R3, escalation.ladderRung(o));
+}
+
+test "R0d: the advisory prescribes a revision and carries the parked evidence" {
+ escalation.resetSession();
+ defer escalation.resetSession();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ // Bare advisory: a revision prescription with a path to the fleet.
+ const bare = escalation.deepRetryAdvice(a, .bugfix);
+ try std.testing.expect(std.mem.indexOf(u8, bare, "R0d") != null);
+ try std.testing.expect(std.mem.indexOf(u8, bare, "second failure earns the fleet") != null);
+ // With parked evidence the advisory embeds it verbatim — the retry acts
+ // on the observed signal, not on the reasoning that already missed.
+ escalation.failure_evidence.note(.bugfix, "eval RED: score 40.0/100 (target 90, exit 1)");
+ const with_ev = escalation.deepRetryAdvice(a, .bugfix);
+ try std.testing.expect(std.mem.indexOf(u8, with_ev, "PRIOR ATTEMPT EVIDENCE") != null);
+ try std.testing.expect(std.mem.indexOf(u8, with_ev, "eval RED: score 40.0/100") != null);
+ // Another class stays bare — evidence never leaks across classes.
+ try std.testing.expect(std.mem.indexOf(u8, escalation.deepRetryAdvice(a, .research), "PRIOR ATTEMPT EVIDENCE") == null);
+ // resetSession clears the ledger with the rest of the session state.
+ escalation.resetSession();
+ try std.testing.expectEqualStrings("", escalation.failure_evidence.evidence(.bugfix));
+}
+
+test "observe: decline count and the class verifier feed the revision gate" {
+ escalation.resetSession();
+ defer escalation.resetSession();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const phases = phasesFrom(a, "[{\"title\":\"implement the fix\",\"tasks\":[1]}]");
+ escalation.noteDeclined(.bugfix);
+ const o = escalation.observe(phases, "fix the bug in stats.py", .review, 27, 30);
+ try std.testing.expect(o.prior_failure);
+ try std.testing.expectEqual(@as(u8, 1), o.prior_failure_count);
+ try std.testing.expectEqual(escalation.failure_evidence.Verifier.diff, o.verifier);
+ try std.testing.expectEqual(Rung.R0d, escalation.ladderRung(o));
+ // verdictFor(R0d) declines non-error with the revision prescription.
+ switch (escalation.verdictFor(.R0d, o, phases)) {
+ .solo => |advice| try std.testing.expect(std.mem.indexOf(u8, advice, "revision case") != null),
+ else => return error.ExpectedSolo,
+ }
+}
+
test "edit contract: a clean tree is is_error, a tree that moved is ok" {
// The PURE half of §3b, which is the half with the interesting logic — the
// impure half is one `git status --porcelain` and a string compare.
diff --git a/src/failure_evidence.zig b/src/failure_evidence.zig
new file mode 100644
index 00000000..5f342c46
--- /dev/null
+++ b/src/failure_evidence.zig
@@ -0,0 +1,101 @@
+//! The session's memory of what actually FAILED, and the closed list of
+//! verifiers that make a deep solo retry admissible.
+//!
+//! Weng's revision rule, encoded: sequential self-correction pays only when
+//! external feedback exists to catch the second miss — without a verifier a
+//! "think harder" retry converts right answers into wrong ones as often as
+//! the reverse. So the R0d rung (escalation.zig) is gated on `verifierFor`
+//! returning something checkable, and the retry brief carries the concrete
+//! failure the harness itself observed (an all-failed fleet abort, a RED
+//! eval verdict) — never a worker's self-report, per the edit-contract
+//! doctrine that verification reads real signals, not claims.
+//!
+//! A leaf module on purpose: escalation.zig re-exports it, but edit_contract
+//! and agent_eval also write here, and escalation already imports
+//! edit_contract — the ledger has to sit below all three to stay off the
+//! import cycle.
+
+const std = @import("std");
+
+const shapes = @import("shapes.zig");
+const util = @import("util.zig");
+
+const TaskClass = shapes.TaskClass;
+const n_classes = std.enums.values(TaskClass).len;
+
+/// Bytes of evidence kept per task class. One failure's head is worth more
+/// than three failures' tails: the ledger keeps the LATEST note whole rather
+/// than concatenating, because the retry acts on one concrete signal, not a
+/// history.
+pub const evidence_cap = 320;
+
+var g_evidence: [n_classes][evidence_cap]u8 = undefined;
+var g_len: [n_classes]usize = @splat(0);
+
+/// Record harness-observed failure evidence for `tc`, flattened to one line
+/// (the advisory embeds it under a header; a newline would break brief
+/// layout) and capped at a UTF-8 boundary. Latest note wins whole.
+pub fn note(tc: TaskClass, text: []const u8) void {
+ const trimmed = std.mem.trim(u8, text, " \t\r\n");
+ const head = util.utf8Prefix(trimmed, evidence_cap);
+ const slot = &g_evidence[@intFromEnum(tc)];
+ for (slot[0..head.len], head) |*d, s| d.* = if (s == '\n' or s == '\r' or s == '\t') ' ' else s;
+ g_len[@intFromEnum(tc)] = head.len;
+}
+
+pub fn evidence(tc: TaskClass) []const u8 {
+ return g_evidence[@intFromEnum(tc)][0..g_len[@intFromEnum(tc)]];
+}
+
+/// Session reset — escalation.resetSession forwards here so one call clears
+/// every piece of cross-invocation ladder state.
+pub fn reset() void {
+ g_len = @splat(0);
+}
+
+/// What could catch a second miss on this class of ask. `diff` is the edit
+/// contract's porcelain probe: bugfix/refactor/feature work is contracted to
+/// mutate, so "did the tree move, and do the checks pass on it" is checkable
+/// without a model. review/research/other have no free signal — for those the
+/// R3 judges ARE the external feedback, so a solo revision loop is refused.
+pub const Verifier = enum { none, diff, eval };
+
+pub fn verifierFor(tc: TaskClass, has_eval: bool) Verifier {
+ if (has_eval) return .eval;
+ return switch (tc) {
+ .bugfix, .refactor, .feature => .diff,
+ .review, .research, .other => .none,
+ };
+}
+
+test "note/evidence: flattened, capped on a UTF-8 boundary, latest wins whole" {
+ reset();
+ defer reset();
+ note(.bugfix, " line one\nline\ttwo\r\n");
+ try std.testing.expectEqualStrings("line one line two", evidence(.bugfix));
+ // Per class: a bugfix note says nothing about research.
+ try std.testing.expectEqualStrings("", evidence(.research));
+ // Latest wins whole — no concatenation.
+ note(.bugfix, "second failure");
+ try std.testing.expectEqualStrings("second failure", evidence(.bugfix));
+ // Capped, and never mid-codepoint: a multi-byte char straddling the cap
+ // is dropped entirely rather than split into invalid UTF-8.
+ var big: [evidence_cap + 8]u8 = @splat('a');
+ big[evidence_cap - 1] = 0xE2; // first byte of a 3-byte sequence
+ big[evidence_cap] = 0x86;
+ big[evidence_cap + 1] = 0x92;
+ note(.feature, &big);
+ try std.testing.expect(evidence(.feature).len < evidence_cap);
+ try std.testing.expect(std.unicode.utf8ValidateSlice(evidence(.feature)));
+}
+
+test "verifierFor: diff-checkable classes gate open, report-only classes stay shut" {
+ try std.testing.expectEqual(Verifier.diff, verifierFor(.bugfix, false));
+ try std.testing.expectEqual(Verifier.diff, verifierFor(.refactor, false));
+ try std.testing.expectEqual(Verifier.diff, verifierFor(.feature, false));
+ try std.testing.expectEqual(Verifier.none, verifierFor(.review, false));
+ try std.testing.expectEqual(Verifier.none, verifierFor(.research, false));
+ try std.testing.expectEqual(Verifier.none, verifierFor(.other, false));
+ // A configured eval loop is the strongest verifier and covers any class.
+ try std.testing.expectEqual(Verifier.eval, verifierFor(.research, true));
+}
diff --git a/src/fitness_strata_tests.zig b/src/fitness_strata_tests.zig
index bad15bf9..e7831f48 100644
--- a/src/fitness_strata_tests.zig
+++ b/src/fitness_strata_tests.zig
@@ -44,9 +44,10 @@ const mixed_archive =
test "#376: a fitness row's stratum is the resolved model, and a missing one is `unknown`" {
try std.testing.expectEqualStrings("gpt-5.6-luna", policy.stratumOf("gpt-5.6-luna"));
try std.testing.expectEqualStrings("gpt-5.6-terra", policy.stratumOf("gpt-5.6-terra"));
- // The two models scoring.providerClass cannot tell apart (both "frontier")
- // are distinct strata here — that separation is the whole increment.
- try std.testing.expect(!std.mem.eql(u8, policy.stratumOf("gpt-5.6-sol"), policy.stratumOf("gpt-5.6-luna")));
+ // Two models scoring.providerClass still pools (sol and bare gpt-5.6,
+ // both "frontier") are distinct strata here — that separation is the
+ // whole increment.
+ try std.testing.expect(!std.mem.eql(u8, policy.stratumOf("gpt-5.6-sol"), policy.stratumOf("gpt-5.6")));
// A row that names no model is its own bucket, never an empty string that
// would compare equal to another absent one by accident.
try std.testing.expectEqualStrings("unknown", policy.stratumOf(""));
diff --git a/src/orchestration_policy.zig b/src/orchestration_policy.zig
index da7487a5..3f5d0050 100644
--- a/src/orchestration_policy.zig
+++ b/src/orchestration_policy.zig
@@ -44,6 +44,14 @@ pub const TaskClass = shapes.TaskClass;
pub const Rung = enum {
/// Solo: the root does the work; the workflow tool declines and says so.
R0,
+ /// Solo, DEEPER: decline again after a first failure, but prescribe a
+ /// sequential revision — retry carrying the concrete failure evidence,
+ /// think longer, verify against the signal that failed. Admitted only
+ /// when a verifier exists (failure_evidence.verifierFor): without
+ /// external feedback a revision loop converts right answers to wrong
+ /// ones, so a verifier-less failure goes straight to R3, where the
+ /// judges ARE the feedback.
+ R0d,
/// One scout: a single sweep + synthesize, to keep the parent's context
/// clean rather than to parallelize.
R1,
@@ -60,13 +68,16 @@ pub const Rung = enum {
return std.meta.stringToEnum(Rung, s);
}
- /// Ordinal, for the trade-down asymmetry in `override`.
+ /// Ordinal, for the trade-down asymmetry in `override`. R0d sits between
+ /// solo and scout: it spends no spawns, but it does spend a root retry
+ /// the plain R0 decline would not have prescribed.
pub fn level(self: Rung) u8 {
return switch (self) {
.R0 => 0,
- .R1 => 1,
- .R2 => 2,
- .R3 => 3,
+ .R0d => 1,
+ .R1 => 2,
+ .R2 => 3,
+ .R3 => 4,
};
}
};
diff --git a/src/route_phase.zig b/src/route_phase.zig
index c963f2b2..4a1e6e57 100644
--- a/src/route_phase.zig
+++ b/src/route_phase.zig
@@ -7,8 +7,9 @@
//! prompt variants of one phase against each other and files the winner under
//! the prompt fingerprint. A phase whose tasks could differ in model would
//! attribute the model's effect to the genome — and nothing downstream could
-//! have caught it, since scoring.providerClass buckets gpt-5.6-sol, -terra
-//! and -luna identically (route_policy.stratumOf tells that story in full).
+//! have caught it, since scoring.providerClass then bucketed gpt-5.6-sol,
+//! -terra and -luna identically (route_policy.stratumOf tells that story in
+//! full).
//!
//! The confound is PER-TASK variation, not the model. This module applies the
//! #372 policy exactly once for a whole phase:
diff --git a/src/route_policy.zig b/src/route_policy.zig
index 542c5103..c029ec5b 100644
--- a/src/route_policy.zig
+++ b/src/route_policy.zig
@@ -233,9 +233,11 @@ pub fn tierLabelFor(provider_id: []const u8, model: []const u8) []const u8 {
/// model the worker actually ran on.
///
/// Until now the only routing axis a fitness row carried was
-/// scoring.providerClass, whose needle table buckets gpt-5.6-sol, -terra and
-/// -luna IDENTICALLY as "frontier" (the pinned, deliberate disagreement test
-/// in subagent_selection.zig). A rung-only difference was therefore invisible
+/// scoring.providerClass, whose needle table then bucketed gpt-5.6-sol,
+/// -terra and -luna IDENTICALLY as "frontier" (closed since — terra/luna are
+/// tier-distinct needles now — though a class still pools distinct models:
+/// sol and bare gpt-5.6 share "frontier"). A rung-only difference was
+/// therefore invisible
/// to every comparison built on it — which is precisely why #290 had to
/// forbid phase workers from varying their model at all: nothing downstream
/// could have told the model's contribution from the prompt's.
diff --git a/src/scoring.zig b/src/scoring.zig
index 98539d0f..f7bd9517 100644
--- a/src/scoring.zig
+++ b/src/scoring.zig
@@ -39,8 +39,12 @@ pub fn providerClass(model: []const u8) []const u8 {
.{ .needle = "-mini", .tier = "small" }, // -mini suffix, not "minimax"/"gemini"
.{ .needle = "lite", .tier = "small" },
.{ .needle = "nano", .tier = "small" },
+ // gpt-5.x rungs (#291): family-agnostic like "haiku"/"flash" so a
+ // future gpt-5.7-terra keeps its tier; must precede "gpt-5".
+ .{ .needle = "terra", .tier = "mid" },
+ .{ .needle = "luna", .tier = "small" },
.{ .needle = "opus", .tier = "frontier" },
- .{ .needle = "gpt-5", .tier = "frontier" },
+ .{ .needle = "gpt-5", .tier = "frontier" }, // sol and bare gpt-5.x stay frontier
.{ .needle = "deepseek-v4", .tier = "frontier" },
.{ .needle = "grok-4", .tier = "frontier" },
.{ .needle = "glm-5", .tier = "frontier" },
@@ -255,6 +259,9 @@ test "score signing message is canonical and cross-language stable" {
test "providerClass buckets models by capability tier" {
try std.testing.expectEqualStrings("frontier", providerClass("claude-opus-4-8"));
try std.testing.expectEqualStrings("frontier", providerClass("gpt-5.5"));
+ try std.testing.expectEqualStrings("frontier", providerClass("gpt-5.6-sol"));
+ try std.testing.expectEqualStrings("mid", providerClass("gpt-5.6-terra")); // rung needle beats "gpt-5"
+ try std.testing.expectEqualStrings("small", providerClass("gpt-5.6-luna"));
try std.testing.expectEqualStrings("frontier", providerClass("deepseek-v4-pro"));
try std.testing.expectEqualStrings("frontier", providerClass("grok-4.3"));
try std.testing.expectEqualStrings("small", providerClass("claude-haiku-4-5"));
diff --git a/src/subagent.zig b/src/subagent.zig
index e2064802..2e62dbf9 100644
--- a/src/subagent.zig
+++ b/src/subagent.zig
@@ -506,9 +506,10 @@ pub fn scoreVariants(
// A tournament must vary exactly ONE axis: variants that did not all run on
// the same MODEL rank the model as much as the prompt, and filing that under
// the prompt fingerprint writes model effects into the genome archive (#290).
- // #376 tightened the key from the capability class — which cannot tell
- // gpt-5.6-sol from -luna — to the resolved model, catching a rung-only
- // difference too. Bail before a judge: unscoreable round.
+ // #376 tightened the key from the capability class — which pools distinct
+ // models under one label (sol and bare gpt-5.6 are both "frontier") — to
+ // the resolved model, catching a rung-only difference too. Bail before a
+ // judge: unscoreable round.
for (1..vn) |k| {
if (!std.mem.eql(u8, subagent_run.variantStratum(seat.provider, vidx[0]), subagent_run.variantStratum(seat.provider, vidx[k]))) {
if (ctx.tracer) |tr| tr.note("fleet", "tournament skipped: variants span routing strata");
diff --git a/src/subagent_run.zig b/src/subagent_run.zig
index c649359c..3461942d 100644
--- a/src/subagent_run.zig
+++ b/src/subagent_run.zig
@@ -180,13 +180,14 @@ pub fn variantProviderClass(seat: Provider, i: usize) []const u8 {
/// #376 — the routing STRATUM variant `i` was observed in: the resolved model
/// itself, not its capability bucket.
///
-/// providerClass cannot separate gpt-5.6-sol from -terra/-luna (all three are
-/// "frontier"), so the matched-tournament guard in scoreVariants was blind to
-/// a rung-only difference — the documented #291 gap that made phase routing
-/// unsafe. Keyed on this it is not: a phase whose variants somehow spanned two
-/// models is refused as unscoreable, and every fitness row records the same
-/// value so a cross-run comparison can stratify by it (fitness_strata.zig)
-/// rather than averaging over rungs.
+/// providerClass once bucketed gpt-5.6-sol/-terra/-luna identically as
+/// "frontier" (the #291 gap, closed since), and a class stays coarser than a
+/// model regardless — "frontier" pools sol with bare gpt-5.6 — so a
+/// matched-tournament guard keyed on it was blind to a rung-only difference,
+/// which made phase routing unsafe. Keyed on this it is not: a phase whose
+/// variants somehow spanned two models is refused as unscoreable, and every
+/// fitness row records the same value so a cross-run comparison can stratify
+/// by it (fitness_strata.zig) rather than averaging over rungs.
pub fn variantStratum(seat: Provider, i: usize) []const u8 {
_ = i;
return route_policy.stratumOf(seat.model);
diff --git a/src/subagent_selection.zig b/src/subagent_selection.zig
index 0ccfe628..9e28c734 100644
--- a/src/subagent_selection.zig
+++ b/src/subagent_selection.zig
@@ -274,22 +274,24 @@ test "default ladder never crosses a provider boundary implicitly" {
test "ladder rungs vs providerClass: documented, intentional disagreement (#291)" {
// #291 requires ladder tier labels to match scoring.providerClass()
// output for the same models, "or report the discrepancy rather than
- // papering over it." providerClass's needle table buckets the whole
- // gpt-5.x family (sol/terra/luna alike) as "frontier" — it has no
- // name-based way to split terra/luna out — and deepseek-v4-flash as
- // "small" via its "flash" needle, even though the ladder treats flash as
- // deepseek's only cheaper (mid) rung. This test pins that the mismatch
- // is real and known today, not a bug the ladder introduced; it is
- // reported rather than silently patched into scoring.zig's needle
- // table, which other, unrelated callers (DGM fitness scoring/fleet
- // niche gating) also depend on.
+ // papering over it." The gpt family now agrees end-to-end with the
+ // ladder, like claude: "terra"/"luna" are tier-distinct needles in
+ // providerClass (as opus/sonnet/haiku are), so pullElites and fleet
+ // propose events keyed on the class are no longer rung-blind — a terra
+ // root pulls "mid" elites, not elites grown on sol.
try std.testing.expectEqualStrings("frontier", @import("scoring.zig").providerClass("gpt-5.6-sol"));
- try std.testing.expectEqualStrings("frontier", @import("scoring.zig").providerClass("gpt-5.6-terra")); // ladder rung: mid
- try std.testing.expectEqualStrings("frontier", @import("scoring.zig").providerClass("gpt-5.6-luna")); // ladder rung: small
+ try std.testing.expectEqualStrings("mid", @import("scoring.zig").providerClass("gpt-5.6-terra")); // ladder rung: mid
+ try std.testing.expectEqualStrings("small", @import("scoring.zig").providerClass("gpt-5.6-luna")); // ladder rung: small
+ // The one remaining disagreement, still reported rather than papered
+ // over: the ladder treats deepseek-v4-flash as deepseek's only cheaper
+ // rung (mid), while providerClass's "flash" needle states its absolute
+ // capability (small). Relative-vs-absolute semantics, not a bug — the
+ // needle table's other callers (DGM fitness scoring/fleet niche gating)
+ // want the absolute answer.
try std.testing.expectEqualStrings("frontier", @import("scoring.zig").providerClass("deepseek-v4-pro"));
try std.testing.expectEqualStrings("small", @import("scoring.zig").providerClass("deepseek-v4-flash")); // ladder rung: mid
- // Claude already agrees end-to-end (opus/sonnet/haiku are tier-distinct
- // needles in providerClass, matching the ladder one-for-one).
+ // Claude agrees end-to-end (opus/sonnet/haiku are tier-distinct needles
+ // in providerClass, matching the ladder one-for-one).
try std.testing.expectEqualStrings("frontier", @import("scoring.zig").providerClass("claude-opus-4-8"));
try std.testing.expectEqualStrings("mid", @import("scoring.zig").providerClass("claude-sonnet-4-6"));
try std.testing.expectEqualStrings("small", @import("scoring.zig").providerClass("claude-haiku-4-5"));
diff --git a/src/subagent_tier_ladder.zig b/src/subagent_tier_ladder.zig
index 2b7ad1ac..921b1dea 100644
--- a/src/subagent_tier_ladder.zig
+++ b/src/subagent_tier_ladder.zig
@@ -12,8 +12,9 @@
//! `frontier`/`mid`/`small` here are the ladder's OWN rung labels; they are
//! NOT guaranteed to equal scoring.providerClass(name) for that literal
//! model string — see the "ladder rungs vs providerClass" pinned test in
-//! subagent_selection.zig for the documented (intentional, not papered
-//! over) disagreement on the gpt-5.6 family and deepseek-v4-flash.
+//! subagent_selection.zig: the gpt-5.6 family now agrees end-to-end, leaving
+//! deepseek-v4-flash as the documented (intentional, not papered over)
+//! disagreement.
const std = @import("std");
const pricing = @import("pricing.zig");
diff --git a/src/tools.zig b/src/tools.zig
index 4c842bcc..5a9a821b 100644
--- a/src/tools.zig
+++ b/src/tools.zig
@@ -166,6 +166,7 @@ pub const ToolCtx = struct {
subagent_cross_provider: bool = false,
registry: ?*mcp.Registry,
from_sub: bool,
+ has_eval: bool = false, // the root's --eval loop: escalation's strongest verifier
approvals: ?*Approvals,
tracer: ?*Tracer,
run_budget: ?*run_budget_mod.RunBudget = null,
diff --git a/src/workflow.zig b/src/workflow.zig
index c15853fb..08c037f5 100644
--- a/src/workflow.zig
+++ b/src/workflow.zig
@@ -228,6 +228,10 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {
.solo => |advice| return .{ .text = try gpa.dupe(u8, advice) },
else => {},
}
+ // A post-failure fleet attacks the OBSERVED failure: prepend the class's
+ // parked evidence to the shared context so every brief carries it.
+ const evidence = if (admission.rung == .R3) escalation.evidenceForAsk() else "";
+ const run_context = if (evidence.len == 0) context_str else try std.fmt.allocPrint(arena, "{s}{s}PRIOR ATTEMPT EVIDENCE (address this directly):\n{s}", .{ context_str, @as([]const u8, if (context_str.len == 0) "" else "\n\n"), evidence });
// §4-P1: a downsized admission caps every phase's width. Wide phases are
// redundant finders; the landing phase carries one task and a cap of >=1
// never touches it — see escalation.downsizeWidth.
@@ -320,7 +324,7 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {
// §3b, stolen from codex's patch-biased delegation: a contracted
// worker is told to MAKE the edits and to end by listing every
// changed path, so verify and the root review a diff, not a claim.
- const based = try withContext(arena, context_str, if (contracted) try withContext(arena, escalation.contract_brief_note, raw) else raw);
+ const based = try withContext(arena, run_context, if (contracted) try withContext(arena, escalation.contract_brief_note, raw) else raw);
if (phase_no == 1) {
prompt.* = based;
} else if (std.mem.indexOf(u8, based, "{{prev}}") != null) {
@@ -441,6 +445,9 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {
const details = try arena.alloc([]const u8, outputs.len);
for (outputs, details) |out, *d| d.* = failExcerpt(arena, out.text);
const abort_text = try buildAbortText(arena, labels, details, phase_no, phases.len, title);
+ // The all-failed abort is the harness's own observation of a
+ // failed attempt — parked as evidence for the next escalation.
+ escalation.failure_evidence.note(shapes.classOf(shapes.rawAsk()), abort_text);
return .{ .text = try gpa.dupe(u8, abort_text), .is_error = true };
}
diff --git a/src/workflow_progress.zig b/src/workflow_progress.zig
index 539af803..52eec201 100644
--- a/src/workflow_progress.zig
+++ b/src/workflow_progress.zig
@@ -239,6 +239,7 @@ test "workflow_progress (#63): a phase transition emits structured state, not ju
ctx.run_budget = null;
ctx.tracer = null;
ctx.agent_cwd = null;
+ ctx.has_eval = false;
ctx.provider = .{ .id = "", .kind = .anthropic, .auth = .bearer, .url = "", .api_key = "", .model = "", .context = 0 };
const input = try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"phases\":[{\"title\":\"find security bugs\",\"tasks\":[1,2]}]}", .{});
const out = try workflow.execWorkflow(ctx, input);