graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(ultracode): escalate to the smallest rung that fits
justrachdb713f82a027
diff --git a/src/agent.zig b/src/agent.zigindex b152a455..ac89703d 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -83,6 +83,14 @@ pub const Agent = struct {codex_props_fp: u64 = 0, // request properties the server anchored on (model/effort/fast/tools/instructions)codex_ws_used_ms: i64 = 0, // .awake-clock ms of the WS's last successful use; gates the idle preemptive re-anchor (#codex-ws)sub: bool,+ /// This agent is served NO tools at all — the `tools` field is omitted+ /// from the request rather than sent empty, which every provider accepts.+ /// Set for the variant judge: its own design comment says it "only+ /// reads/reasons over text handed to it, never the filesystem", but it was+ /// handed the full subagent catalog anyway and duly spent ~3 calls per+ /// score re-reading files it had already been given. With no tools it must+ /// answer from the excerpt in one call, which is what it was designed for.+ text_only: bool = false,label: []const u8,out: ?*Io.Writer,in: ?*Io.Reader = null, // stdin, root only — backs the ask_user tool@@ -366,7 +374,7 @@ pub const Agent = struct {self.compactOrRecover(self.provider.nearContextLimit(recovery_meter));self.closeCodexWs();}- const root = try self.request(self.toolsJson());+ const root = try self.request(if (self.text_only) null else self.toolsJson());const done = switch (self.provider.kind) {.anthropic => try self.stepAnthropic(root),.openai => try self.stepOpenAI(root),diff --git a/src/agent_eval.zig b/src/agent_eval.zigindex b5570c52..bf63c9ca 100644--- a/src/agent_eval.zig+++ b/src/agent_eval.zig@@ -25,6 +25,7 @@ const fleet = @import("fleet.zig");const main_mod = @import("main.zig");const route_policy = @import("route_policy.zig"); // #372 (shape, role, tier) coordinates on the local capture rowsconst 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 funneltest {_ = @import("agent_eval_tests.zig");@@ -123,6 +124,29 @@ pub fn runEval(self: *Agent, note: []const u8) !ExecResult {// live model call.if (met) playbook_reflect.afterEval(self, note, combined orelse 0, run.stdout);+ // The orchestration outcome (§5). This is the same funnel the DGM score+ // rows use, and for the same reason: an eval verdict is the one place the+ // harness holds ground truth about whether a run WORKED. If this turn made+ // an escalation decision, that decision now gets its measured cost and+ // result — score, calls actually spent, and whether the edit-contract+ // probe ever saw a diff.+ //+ // Gated on `met`, and that gate is load-bearing. An `--until` loop+ // evaluates repeatedly: red, repair, green. Filing on the FIRST verdict+ // recorded score 0 for a run that went on to score 100 — observed, on the+ // very first acceptance run of this feature — which would teach the policy+ // that the rung it chose had failed when it had succeeded. A run that+ // never goes green files nothing here and stays uncelled, which is the+ // same doctrine foldArms applies to every incomplete row: an uncelled+ // observation is honest, a mis-celled one poisons the cell. The one+ // failure that DOES get recorded is the one that matters most, and it is+ // recorded elsewhere — run_budget.exhaustedFatal files score 0,+ // exhausted:true before the process dies.+ if (met) if (orch_rows.pending() != null) if (combined) |s| {+ if (s >= 0 and s <= 100)+ orch_rows.flushPending(s / 100.0, if (self.run_budget) |b| b.used() else 0, 0, false, &promptFingerprint(cmd));+ };+// Feed the eval-driven score into the fleet (docs/hyperagents.md §9.B):// on a NEW BEST, submit the genome (this agent's persona) with its achieved// score on the pinned eval set (the eval command's fingerprint). Without thisdiff --git a/src/bench_priors.zig b/src/bench_priors.zigindex b1c5a3ca..4d5c171e 100644--- a/src/bench_priors.zig+++ b/src/bench_priors.zig@@ -142,6 +142,10 @@ pub fn loadInto(io: Io, arena: Allocator, home: ?[]const u8) void {// policy cells, so the session-wide ladders and the per-cell learned// policy can never disagree about which runs they have seen.@import("route_policy.zig").loadCells(arena, archive);+ // …and the (task_class, budget_band, stratum) orchestration arms, hung on+ // this same pass for the same reason and at no extra I/O: one archive+ // read, three consumers, one consistent view of history.+ @import("orchestration_policy.zig").loadArms(arena, archive);}fn readSheet(io: Io, arena: Allocator, path: []const u8) ?Sheet {diff --git a/src/brief_diversity.zig b/src/brief_diversity.zigindex c1c5537a..f67278cd 100644--- a/src/brief_diversity.zig+++ b/src/brief_diversity.zig@@ -267,14 +267,154 @@ pub fn warningText(arena: Allocator, r: Report) ?[]const u8 {////// A fleet whose personas ARE near-identical still warns, on the persona/// text — which is the right answer, since that fleet really is one concept.+///+/// THE SHA GATE. The original test was "every task carries SOME override",+/// which is presence, not variation — and presence is not what makes the+/// persona the axis. The eval study caught the difference in the worst+/// possible place: three finders that all carried the SAME resolved+/// system_prompt and three genuinely different briefs measured 1.000 on the+/// persona axis and fired the warning, while the text that actually varied+/// was never looked at. A gate that reports 100% similar for a fleet whose+/// briefs are 17% similar is worse than no gate: it is a number that means+/// the opposite of what it says.+///+/// So: all resolved genomes IDENTICAL means the genome is a constant, not an+/// axis, and the answer is null — measure the briefs, which is where the+/// variation has to be if there is any. Shape C (N implementers, one task, a+/// DIFFERENT system_prompt each) is unaffected, because its genomes really do+/// differ and that is exactly the case this function exists for.pub fn personaAxis(arena: Allocator, briefs: []const []const u8, genomes: []const ?[]const u8) ?[]const []const u8 {if (genomes.len != briefs.len) return null;for (genomes) |g| if (g == null or g.?.len == 0) return null;+ // Content equality over the RESOLVED genome (fleet.resolveOverride has+ // already turned `agent:"reviewer"` into that persona's text), which is+ // what a prompt_sha comparison means here.+ const first = genomeSha(genomes[0].?);+ var varied = false;+ for (genomes[1..]) |g| if (genomeSha(g.?) != first) {+ varied = true;+ };+ if (!varied) return null;const out = arena.alloc([]const u8, genomes.len) catch return null;for (genomes, out) |g, *o| o.* = g.?;return out;}+/// The resolved genome's content fingerprint. A 64-bit content hash rather+/// than the 128-bit scoring.promptFingerprint: this is only ever used for+/// EQUALITY between genomes held in one process at one instant, never+/// persisted, never joined against an archive — so importing the signing+/// fingerprint here would buy nothing and add a dependency.+pub fn genomeSha(genome: []const u8) u64 {+ return std.hash.Wyhash.hash(0xf1ee7, genome);+}++// ── collapse ───────────────────────────────────────────────────────────────+// The gate above measures and warns. This DOES something about the one case+// where the measurement is unambiguous: two tasks that carry the same genome+// AND essentially the same brief are the same worker, spawned twice, and the+// second one costs a full model call to produce text the first already+// produced. The study has both halves of the proof — a research phase that+// spawned three sweepers over three small files whose briefs measured 1.000+// similar to each other, and the same task answered identically by one.+//+// Collapsing is safe in a way warning is not, because the duplicate's output+// is not lost: the survivor's result is fanned into every collapsed task's+// {{prev}} slot, so the next phase reads exactly what it would have read.+// What disappears is the redundant CALL.++/// Jaccard at or above which two same-genome briefs are one brief. Higher+/// than warn_threshold (0.55) by a wide margin, and deliberately so: the warn+/// gate is advisory and can afford to be wrong, while this one silently+/// removes a worker, so it fires only on near-copies. On the fixture scale in+/// this file, 0.85 sits ABOVE the near-copies fixture (0.739) — meaning even+/// "one brief with /vN swapped" survives, and only briefs that are the same+/// modulo whitespace and a word collapse.+pub const collapse_threshold: f64 = 0.85;++pub const Collapse = struct {+ /// For each input task, the index of the task that will actually run for+ /// it — itself when it survives, the survivor's index when it collapsed.+ rep: []const usize,+ /// Surviving indices, ascending.+ survivors: []const usize,++ pub fn collapsed(self: Collapse) usize {+ return self.rep.len - self.survivors.len;+ }+};++fn identity(arena: Allocator, n: usize) Collapse {+ const rep = arena.alloc(usize, n) catch return .{ .rep = &.{}, .survivors = &.{} };+ for (rep, 0..) |*r, i| r.* = i;+ return .{ .rep = rep, .survivors = rep };+}++/// Which tasks actually need to be spawned.+///+/// Two tasks are duplicates iff their resolved genomes are byte-identical AND+/// their briefs measure `collapse_threshold` or more similar. Both halves are+/// required: same genome + different brief is a legitimate fan-out (three+/// reviewers, one persona, three dimensions), and same brief + different+/// genome is shape C's whole point.+///+/// FLOORS. A `variants` phase keeps at least 2 tasks even when every brief is+/// identical, because "run the same brief N times and judge the spread" is a+/// legitimate thing to ask for and a tournament of one is not a tournament.+/// Everywhere else the floor is 1.+pub fn collapse(arena: Allocator, briefs: []const []const u8, genomes: []const ?[]const u8, variants_phase: bool) Collapse {+ const n = briefs.len;+ if (n < 2 or n > max_briefs) return identity(arena, n);+ const floor: usize = if (variants_phase) 2 else 1;+ const rep = arena.alloc(usize, n) catch return identity(arena, n);+ const words = arena.alloc(u64, max_words) catch return identity(arena, n);+ const grams = arena.alloc(u64, n * max_words) catch return identity(arena, n);+ const sets = arena.alloc([]const u64, n) catch return identity(arena, n);+ for (briefs, sets, 0..) |brief, *set, k| {+ set.* = gramSet(grams[k * max_words ..][0..max_words], wordHashes(words, brief));+ }+ var alive: usize = n;+ for (rep, 0..) |*r, i| r.* = i;+ for (0..n) |i| {+ if (rep[i] != i) continue; // already collapsed into someone else+ for (i + 1..n) |j| {+ if (rep[j] != j or alive <= floor) continue;+ const gi = genomes[i];+ const gj = genomes[j];+ const same_genome = (gi == null and gj == null) or+ (gi != null and gj != null and genomeSha(gi.?) == genomeSha(gj.?));+ if (!same_genome) continue;+ // An exact brief match always collapses, whatever the shingle+ // metric says — a brief too short to shingle (gramSet folds it to+ // one gram) would otherwise depend on hash luck.+ const exact = std.mem.eql(u8, briefs[i], briefs[j]);+ if (!exact and jaccard(sets[i], sets[j]) < collapse_threshold) continue;+ rep[j] = i;+ alive -= 1;+ }+ }+ const survivors = arena.alloc(usize, alive) catch return identity(arena, n);+ var s: usize = 0;+ for (rep, 0..) |r, i| if (r == i) {+ survivors[s] = i;+ s += 1;+ };+ return .{ .rep = rep, .survivors = survivors[0..s] };+}++/// The manifest line a collapsed phase carries, or "" when nothing collapsed.+/// The root reads the manifest, so this is where "you asked for five workers+/// and got three because two were copies" becomes visible instead of silent.+pub fn collapseNote(arena: Allocator, c: Collapse) []const u8 {+ if (c.collapsed() == 0) return "";+ return std.fmt.allocPrint(+ arena,+ "collapsed {d} duplicate brief(s): same system_prompt and >={d:.0}% identical text, so they " +++ "spawned once and the survivor's result was fanned into every duplicate's slot.",+ .{ c.collapsed(), collapse_threshold * 100 },+ ) catch "";+}+/// Cap on the phase label copied into the trace line, matching/// route_trace.field_cap: a model-authored title must not be able to turn one/// trace record into a megabyte.diff --git a/src/brief_diversity_tests.zig b/src/brief_diversity_tests.zigindex 1c808a1c..c915529a 100644--- a/src/brief_diversity_tests.zig+++ b/src/brief_diversity_tests.zig@@ -163,9 +163,139 @@ test "#382: a fleet whose variation lives in system_prompt is judged on that axitry std.testing.expect(bd.personaAxis(a, &shape_c_prompts, &partial_genomes) == null);try std.testing.expect(bd.check(a, null, "variants", &shape_c_prompts, &partial_genomes).len > 0);- // …and near-identical personas still warn, on the persona text.- const same = [_]?[]const u8{ shape_c_genomes[0], shape_c_genomes[0], shape_c_genomes[0] };- try std.testing.expect(bd.check(a, null, "variants", &shape_c_prompts, &same).len > 0);+ // Personas that DIFFER but only slightly still warn, on the persona text —+ // that fleet really is one concept wearing three hats.+ const near = [_]?[]const u8{+ "You are an implementer. Favour the MVP: ship the smallest thing that works.",+ "You are an implementer. Favour the MVP: ship the smallest thing that works today.",+ "You are an implementer. Favour the MVP: ship the smallest thing that can work.",+ };+ try std.testing.expect(bd.personaAxis(a, &shape_c_prompts, &near) != null);+ try std.testing.expect(bd.check(a, null, "variants", &shape_c_prompts, &near).len > 0);+}++test "personaAxis: identical genomes are a CONSTANT, not an axis — measure the briefs" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ // THE false positive, transcribed from eval run 01-bugfix-B. Three finders+ // carrying ONE resolved system_prompt and three genuinely different briefs.+ // The old rule ("every task has SOME override") moved the axis to the+ // personas, measured them at 1.000, and fired the warning — while the text+ // that actually varied was never looked at. A gate reporting "100% similar"+ // for a fleet whose briefs are ~17% similar is worse than no gate.+ const one_genome = "You are a code reviewer. Report concrete defects with file:line evidence.";+ const genomes = [_]?[]const u8{ one_genome, one_genome, one_genome };+ const briefs = [_][]const u8{+ "Review implementation correctness in stats.py: check each function against its docstring and the behaviour the tests assert.",+ "Analyze boundary cases: empty input, single element, even-length input, and ties between equally frequent values.",+ "Trace tests to functions: map every assertion in test_stats.py back to the function it exercises and note which are unmet.",+ };++ // The axis does NOT move: with one genome there is nothing to measure on it.+ try std.testing.expect(bd.personaAxis(a, &briefs, &genomes) == null);+ // So the gate measures the briefs — and the briefs are varied, so it is+ // silent. This is the exact run that used to warn at 1.00.+ const r = bd.analyze(a, &briefs);+ try std.testing.expect(!r.warn);+ try std.testing.expect(r.mean < bd.warn_threshold);+ try std.testing.expectEqualStrings("", bd.check(a, null, "find", &briefs, &genomes));++ // The same one-genome fleet with COPIED briefs still warns — the fix moves+ // the measurement, it does not silence it.+ const copies = [_][]const u8{ briefs[0], briefs[0], briefs[0] };+ try std.testing.expect(bd.check(a, null, "find", &copies, &genomes).len > 0);++ // genomeSha is content equality over the RESOLVED genome, which is what a+ // prompt_sha comparison means here.+ try std.testing.expectEqual(bd.genomeSha(one_genome), bd.genomeSha("You are a code reviewer. Report concrete defects with file:line evidence."));+ try std.testing.expect(bd.genomeSha(one_genome) != bd.genomeSha("You are a security reviewer."));+}++test "collapse: same genome + same brief spawns once, and the survivor takes the fan-in" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const g = "reviewer persona";+ const genomes = [_]?[]const u8{ g, g, g };++ // Three byte-identical briefs under one genome: one worker, asked thrice.+ const same = [_][]const u8{ near_copies[0], near_copies[0], near_copies[0] };+ const c = bd.collapse(a, &same, &genomes, false);+ try std.testing.expectEqual(@as(usize, 1), c.survivors.len);+ try std.testing.expectEqual(@as(usize, 2), c.collapsed());+ // Every duplicate points at the SURVIVOR, so the fan-in has one source and+ // the next phase's {{prev}} reads exactly what it would have read.+ for (c.rep) |r| try std.testing.expectEqual(@as(usize, 0), r);+ try std.testing.expectEqual(@as(usize, 0), c.survivors[0]);+ // And the manifest says so, rather than the run silently narrowing.+ try std.testing.expect(std.mem.indexOf(u8, bd.collapseNote(a, c), "collapsed 2 duplicate") != null);+}++test "collapse: both halves are required — genome alone or brief alone is not a duplicate" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ // Same genome, DIFFERENT briefs: a legitimate fan-out (three reviewers,+ // one persona, three dimensions). This is the study's find phase.+ const g = "reviewer persona";+ const one_genome = [_]?[]const u8{ g, g, g };+ const varied = bd.collapse(a, &thesis_fleet[0..3].*, &one_genome, false);+ try std.testing.expectEqual(@as(usize, 3), varied.survivors.len);+ try std.testing.expectEqual(@as(usize, 0), varied.collapsed());++ // Same brief, DIFFERENT genomes: shape C's whole point — N implementers,+ // one task, a different system_prompt each. Nothing may collapse.+ const c = bd.collapse(a, &shape_c_prompts, &shape_c_genomes, true);+ try std.testing.expectEqual(@as(usize, 3), c.survivors.len);++ // Near-copies (one brief, /vN swapped) sit at ~0.74 — BELOW the 0.85+ // collapse threshold, so they survive even under one genome. The warn gate+ // can afford to be wrong; a gate that deletes a worker cannot.+ const near = bd.collapse(a, &near_copies, &one_genome, false);+ try std.testing.expectEqual(@as(usize, 3), near.survivors.len);+ try std.testing.expect(bd.analyze(a, &near_copies).warn); // it still WARNS+}++test "collapse: floors — a variants phase keeps a tournament, everywhere else keeps one" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const g = "one persona";+ const genomes = [_]?[]const u8{ g, g, g, g };+ const same = [_][]const u8{ near_copies[0], near_copies[0], near_copies[0], near_copies[0] };++ // "Run the same brief N times and judge the spread" is a legitimate ask,+ // and a tournament of one is not a tournament.+ const variants = bd.collapse(a, &same, &genomes, true);+ try std.testing.expectEqual(@as(usize, 2), variants.survivors.len);+ // Elsewhere there is nothing to rank, so one survivor is the whole answer.+ const ordinary = bd.collapse(a, &same, &genomes, false);+ try std.testing.expectEqual(@as(usize, 1), ordinary.survivors.len);++ // Degenerate inputs pass through as identity rather than guessing.+ const single = [_][]const u8{same[0]};+ const one_g = [_]?[]const u8{g};+ const id = bd.collapse(a, &single, &one_g, false);+ try std.testing.expectEqual(@as(usize, 1), id.survivors.len);+ try std.testing.expectEqual(@as(usize, 0), id.collapsed());+ try std.testing.expectEqualStrings("", bd.collapseNote(a, id));+}++test "collapse: two tasks with no genome at all still collapse on identical text" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ // Both null is "same genome" — an inline fan-out with no persona is still+ // one configuration, and two identical briefs under it are one worker.+ const none = [_]?[]const u8{ null, null, null };+ const same = [_][]const u8{ near_copies[0], near_copies[0], near_copies[2] };+ const c = bd.collapse(a, &same, &none, false);+ try std.testing.expectEqual(@as(usize, 2), c.survivors.len); // 0 and 2 survive, 1 folds into 0+ try std.testing.expectEqual(@as(usize, 0), c.rep[1]);+ try std.testing.expectEqual(@as(usize, 2), c.rep[2]);}test "#382: a fleet smaller than min_fleet is never judged" {diff --git a/src/edit_contract.zig b/src/edit_contract.zignew file mode 100644index 00000000..a05875c9--- /dev/null+++ b/src/edit_contract.zig@@ -0,0 +1,108 @@+//! The work-landing guarantee: a phase contracted to MUTATE must leave a diff.+//!+//! Split from escalation.zig (600-line cap) along a real seam — the ladder+//! decides HOW MUCH orchestration to buy, this decides whether the+//! orchestration produced a patch. They compose (escalation re-exports every+//! symbol here, so call sites see one module) but they answer different+//! questions and fail in different ways.+//!+//! The failure it exists for is stark. Eval run 01-bugfix-B: a two-function+//! bug in one file, a fleet of five workers, three judges, one retry, all 30+//! model calls spent — and `git status` clean at the end. Every worker+//! reported. Nobody edited. Verification read those reports and believed them.+//!+//! So verification stops reading reports. A phase whose canonical slot is+//! implement/build/repair is CONTRACTED, and after it awaits, a+//! `git status --porcelain` probe — no model call, no network — asks the+//! filesystem instead. A tree that did not move converts the result to+//! `is_error`, which makes it eligible for the single retry the workflow loop+//! already runs, with a message that says exactly what was not done.+//! (grok-build's doctrine: edits flow through workers, verification reads real+//! diffs, never worker self-reports.)++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const pb = @import("phase_budget.zig");+const orch_rows = @import("orchestration_rows.zig");+const process_runner = @import("process_runner.zig");++/// The failure text a contracted phase gets when nothing changed on disk.+/// Carries no retry_unsafe_note, so failureAllowsRetry says yes and the+/// existing single retry (workflow.zig) picks it up — which is the point: the+/// worker gets one more attempt, told explicitly what it failed to do.+pub const contract_unmet =+ "edit contract unmet: no files changed. This phase's slot (implement/build/repair) is contracted " +++ "to MUTATE the working tree, and `git status --porcelain` is unchanged, so whatever was reported " +++ "was a plan, not a patch. Make the edits with the file tools and end your reply by listing every " +++ "changed path.";++/// Boilerplate appended to a contracted phase's briefs. Stolen from codex's+/// patch-biased delegation: the worker must name the paths it changed, so the+/// verify phase and the root both review a DIFF rather than a claim.+pub const contract_brief_note =+ "This phase is contracted to change files. Use the file tools to make the edits yourself — do not " +++ "describe them — and end your final message with a `changed:` line listing every path you wrote.";++pub fn isContracted(role: []const u8) bool {+ return pb.isLandingRole(role);+}++/// PURE contract verdict over two `git status --porcelain` snapshots.+///+/// Two distinct failures, both of which mean nothing landed:+/// * the tree is CLEAN after the phase — no edit, no question;+/// * the tree is byte-identical to before the phase — it was already dirty+/// from earlier work, and this phase added nothing to it. Without this+/// second arm any phase run in a workspace with uncommitted changes would+/// pass the contract for free, which is most real workspaces.+/// Anything else (new lines, changed lines) is a real diff and passes.+pub fn contractUnmet(contracted: bool, before: []const u8, after: []const u8) bool {+ if (!contracted) return false;+ const a = std.mem.trim(u8, after, " \t\r\n");+ if (a.len == 0) return true;+ return std.mem.eql(u8, std.mem.trim(u8, before, " \t\r\n"), a);+}++fn porcelain(gpa: Allocator, io: Io, cwd: ?[]const u8) ?[]u8 {+ const r = if (cwd) |p|+ process_runner.runCapped(gpa, io, &.{ "git", "-C", p, "status", "--porcelain" }, 1 << 16, 8192, 15_000) catch return null+ else+ process_runner.runCapped(gpa, io, &.{ "git", "status", "--porcelain" }, 1 << 16, 8192, 15_000) catch return null;+ defer gpa.free(r.stderr);+ if (!process_runner.ranOk(r)) {+ gpa.free(r.stdout);+ return null;+ }+ return r.stdout;+}++/// Snapshot the working tree, arena-owned. Returns "" for an uncontracted+/// phase (no probe is spawned at all) and for any git failure — a repo the+/// probe cannot read must never fail a phase that may well have succeeded.+pub fn treeSnapshot(arena: Allocator, gpa: Allocator, io: Io, cwd: ?[]const u8, contracted: bool) []const u8 {+ if (!contracted) return "";+ const out = porcelain(gpa, io, cwd) orelse return "";+ defer gpa.free(out);+ return arena.dupe(u8, out) catch "";+}++/// Post-await gate: convert a contracted phase that changed nothing into an+/// error the existing retry can act on. `out` is taken by value and returned+/// (possibly rewritten) so the call site stays one statement.+///+/// Never touches a result that is ALREADY an error — that failure has its own+/// cause and its own retry verdict, and overwriting it would throw away the+/// API error #248 works to surface.+pub fn contractCheck(gpa: Allocator, io: Io, cwd: ?[]const u8, contracted: bool, before: []const u8, out: anytype) @TypeOf(out) {+ if (!contracted or out.is_error) return out;+ const after = porcelain(gpa, io, cwd) orelse return out; // unreadable repo: pass+ defer gpa.free(after);+ if (!contractUnmet(true, before, after)) {+ orch_rows.notePendingLanded(true);+ return out;+ }+ gpa.free(out.text);+ return .{ .text = gpa.dupe(u8, contract_unmet) catch "", .is_error = true };+}diff --git a/src/escalation.zig b/src/escalation.zignew file mode 100644index 00000000..6f4565e3--- /dev/null+++ b/src/escalation.zig@@ -0,0 +1,539 @@+//! The ultracode escalation ladder, and the work-landing guarantee.+//!+//! WHAT THIS FIXES. A 16-run eval study ran five ordinary coding tasks three+//! ways: the model solo, the same model with the `ultracode` codeword, and a+//! frontier model solo. Ultracode's ANSWERS were fine — where it finished, it+//! finished correctly. Its PRICE was not: mean 80 against solo's 100, at 3.7x+//! the model calls, two runs killed at the budget ceiling, and one bugfix that+//! spent all 30 calls producing findings and never edited the file at all.+//! That is not a reasoning failure but an ADMISSION failure: nothing ever+//! asked whether the ask deserved a fleet, so the answer was always yes.+//!+//! THE LADDER. `admit()` runs once, before anything spawns, on cheap+//! observables only — no probe call, no model in the loop:+//!+//! R0 solo the ask names 1-2 files, or no higher rung admits. The+//! workflow tool DECLINES, non-error, and says why. This is the+//! floor, and on ordinary work it is the right answer.+//! R1 scout an open-ended exploration ask: one sweep + one synthesis.+//! opencode's context-economy rule — delegate to keep the+//! parent's context clean, not to parallelize.+//! R2 fleet 3+ distinct files/modules named AND the plan plus the landing+//! reserve fits what is left.+//! R3 full audit-class language in the ask (the user asked for breadth,+//! 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.+//!+//! Where a learned cell has evidence (orchestration_policy.zig) it overrides+//! the hand rung and the row says `source:"learned"`; otherwise the ladder+//! decides and says `source:"bootstrap"`. A shape the USER named is+//! `source:"explicit"` and is never overridden, in either direction.+//!+//! THE EDIT CONTRACT. Separately from the ladder: a phase whose canonical+//! slot is implement/build/repair is contracted to MUTATE. After it awaits, a+//! `git status --porcelain` probe (no model call) asks whether anything+//! actually changed; a tree that did not move converts the result to+//! `is_error`, making it eligible for the retry that already exists.+//! grok-build's doctrine, and the direct answer to the 30-calls-no-edit run:+//! verification reads a real diff, never a worker's self-report.++const std = @import("std");+const Io = std.Io;+const Value = std.json.Value;+const Allocator = std.mem.Allocator;++const main_mod = @import("main.zig"); // `unattended`: the -p/eval one-shot flag+const shapes = @import("shapes.zig");+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 brief_diversity = @import("brief_diversity.zig");+const fleet = @import("fleet.zig");+const trace = @import("trace.zig");+const util = @import("util.zig");++pub const Rung = orch.Rung;+pub const Source = orch.Source;++/// A fleet is for INDEPENDENT workstreams, and the cheapest honest proxy for+/// "independent" the harness can compute without a model call is "the ask+/// names this many distinct files". Two files is a pair; three is a fan-out.+pub const fleet_scope_min: usize = 3;++// ── observables ────────────────────────────────────────────────────────────++pub const Observables = struct {+ shape: route_policy.Shape = .adhoc,+ task_class: shapes.TaskClass = .other,+ /// Distinct file paths named across every task brief in the plan.+ files: usize = 0,+ /// Widest phase, i.e. how far this plan actually fans out.+ widest: usize = 0,+ tasks: usize = 0,+ plan_estimate: u64 = 0,+ audit: bool = false,+ prior_failure: bool = false,+ remaining: u64 = 0,+ cap: u64 = 0,+};++/// Bytes that can appear inside a path token. Excludes ':' and ',' so+/// `stats.py:24` and `a.py, b.py` still resolve to one file each.+fn isPathByte(c: u8) bool {+ return std.ascii.isAlphanumeric(c) or c == '_' or c == '-' or c == '.' or c == '/' or c == '\\';+}++/// Does this token look like a file path? It needs an extension: a dot with+/// 1-5 letters after it and an alphanumeric before it. That refuses version+/// numbers ("3.11"), ellipses and sentence-ending periods, and accepts+/// `stats.py`, `src/main.zig` and `settings.json`.+fn looksLikeFile(tok: []const u8) bool {+ const dot = std.mem.lastIndexOfScalar(u8, tok, '.') orelse return false;+ if (dot == 0 or dot + 1 >= tok.len) return false;+ if (!std.ascii.isAlphanumeric(tok[dot - 1])) return false;+ const ext = tok[dot + 1 ..];+ if (ext.len > 5) return false;+ for (ext) |c| if (!std.ascii.isAlphabetic(c)) return false;+ return true;+}++/// Bound on the file set, so a pathological brief cannot make this loop+/// expensive or the scratch large. Well above `fleet_scope_min`, which is the+/// only threshold that reads the count.+pub const max_files_counted = 32;++const FileSet = struct {+ hashes: [max_files_counted]u64 = @splat(0),+ n: usize = 0,++ fn add(self: *FileSet, tok: []const u8) void {+ if (self.n == self.hashes.len) return;+ var buf: [64]u8 = undefined;+ const m = @min(tok.len, buf.len);+ for (buf[0..m], tok[0..m]) |*d, s| d.* = std.ascii.toLower(s);+ const h = std.hash.Wyhash.hash(0, buf[0..m]);+ for (self.hashes[0..self.n]) |x| if (x == h) return;+ self.hashes[self.n] = h;+ self.n += 1;+ }++ fn scan(self: *FileSet, text: []const u8) void {+ var i: usize = 0;+ while (i < text.len) {+ while (i < text.len and !isPathByte(text[i])) : (i += 1) {}+ const start = i;+ while (i < text.len and isPathByte(text[i])) : (i += 1) {}+ if (i == start) continue;+ const tok = std.mem.trim(u8, text[start..i], ".");+ if (tok.len > 0 and looksLikeFile(tok)) self.add(tok);+ }+ }+};++/// Distinct file paths named in `text`. Pure, allocation-free, and bounded.+pub fn countDistinctFiles(text: []const u8) usize {+ var set: FileSet = .{};+ set.scan(text);+ return set.n;+}++fn taskPrompts(pv: Value, set: *FileSet, tasks: *usize, widest: *usize) void {+ if (pv != .object) return;+ const tv = pv.object.get("tasks") orelse return;+ if (tv != .array) return;+ widest.* = @max(widest.*, tv.array.items.len);+ for (tv.array.items) |task_val| {+ tasks.* += 1;+ if (task_val != .object) continue;+ const p = task_val.object.get("prompt") orelse continue;+ if (p == .string) set.scan(p.string);+ }+}++/// Everything the ladder needs, read off the authored plan plus the raw ask.+/// Pure: `raw` is what the user typed (shapes.rawAsk()), `remaining`/`cap`+/// come from the shared RunBudget.+pub fn observe(phases: []const Value, raw: []const u8, shape: route_policy.Shape, remaining: u64, cap: u64) Observables {+ var set: FileSet = .{};+ // The ASK names files too — "fix stats.py" is scope evidence even when+ // the plan's briefs paraphrase it.+ set.scan(raw);+ var o: Observables = .{+ .shape = shape,+ .task_class = shapes.classOf(raw),+ .audit = shapes.isAuditClass(raw),+ .prior_failure = priorAttemptFailed(shapes.classOf(raw)),+ .remaining = remaining,+ .cap = cap,+ .plan_estimate = pb.planEstimate(phases),+ };+ for (phases) |pv| taskPrompts(pv, &set, &o.tasks, &o.widest);+ o.files = set.n;+ return o;+}++// ── the ladder ─────────────────────────────────────────────────────────────++pub const Verdict = union(enum) {+ /// Run the plan as authored.+ proceed,+ /// Run it with every phase capped at this many tasks.+ downsize: usize,+ /// Do not run it; hand the root this advisory instead.+ solo: []const u8,+};++pub const Decision = struct {+ rung: Rung = .R0,+ source: Source = .bootstrap,+ verdict: Verdict = .proceed,+ downsized_from: usize = 0,+};++/// The advisory the workflow tool returns on R0. NON-error on purpose: a+/// declined fleet is not a failed tool call, and returning `is_error` here+/// would burn the retry the edit contract wants to keep, and would read to the+/// model as "the harness is broken" rather than "do this yourself".+pub const solo_advice =+ "workflow declined (escalation R0): budget and scope fit solo work. This ask names 1-2 files, " +++ "or the pool cannot cover a fleet plus the calls needed to land the work. Do it yourself — read " +++ "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.+pub fn ladderRung(o: Observables) Rung {+ const l = pb.Ledger.init(o.cap);+ const fleet_affordable = l.fits(o.remaining, pb.fleetFloor(o.shape));+ 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+ // back a summary, which is the whole benefit. Wider adds cost, not value —+ // measured, in the study's research run: three sweepers over three small+ // files scored identically to one, at 4x the calls, on briefs that+ // measured 1.00 similar to each other.+ if (o.shape == .research and !o.audit) return .R1;+ if (o.files >= fleet_scope_min and o.widest >= 2 and fleet_affordable) return .R2;+ return .R0;+}++/// The widest per-phase task count whose trimmed plan still fits on top of+/// the landing reserve, or 0 when even one worker per phase does not fit.+///+/// Width is the trimming axis because of WHAT it trims. A plan's wide phases+/// are its finders and sweepers — redundant evidence-gathering, the cheapest+/// thing to lose. Its landing phase carries exactly one implementer, so any+/// width cap of 1 or more leaves it completely untouched. That is the+/// ordering §4-P1 asks for (judges first via the P3 gate, redundant finders+/// second, the edit-contract phase never) expressed as one number instead of+/// three special cases.+pub fn downsizeWidth(phases: []const Value, cap: u64, remaining: u64) usize {+ const l = pb.Ledger.init(cap);+ var widest: usize = 1;+ for (phases) |pv| {+ if (pv != .object) continue;+ const tv = pv.object.get("tasks") orelse continue;+ if (tv == .array) widest = @max(widest, tv.array.items.len);+ }+ var w = widest;+ while (w >= 1) : (w -= 1) {+ var total: u64 = 0;+ for (phases) |pv| {+ if (pv != .object) continue;+ const tv = pv.object.get("tasks") orelse continue;+ if (tv != .array) continue;+ total += pb.phaseCost(route_policy.phaseSlot(pv), @min(tv.array.items.len, w));+ }+ if (l.fits(remaining, total)) return w;+ if (w == 1) break;+ }+ return 0;+}++/// Turn a rung into what the workflow loop should actually do.+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 },+ // One scout, one synthesis: cap every phase at a single task.+ .R1 => return .{ .downsize = 1 },+ .R2, .R3 => {+ if (l.fits(o.remaining, o.plan_estimate)) return .proceed;+ const w = downsizeWidth(phases, o.cap, o.remaining);+ // Nothing fits, not even one worker per phase, so a fleet here+ // would be a fan-out that cannot finish. Solo is not a demotion,+ // it is the only rung with a budget.+ if (w == 0) return .{ .solo = solo_advice };+ return .{ .downsize = w };+ },+ }+}++// ── session state: prior failure, explicit choice, exploration ─────────────++/// How many times this session already declined (or scouted) an ask of each+/// class. A SECOND workflow call for the same class of ask is the harness's+/// cheapest evidence that the first, cheaper answer did not stick — which is+/// exactly the "a prior solo/R1 attempt failed verification" signal, observed+/// rather than asked for.+/// std.enums.values rather than @typeInfo(...).fields.len: 0.16 spells that+/// field `fields` and the CI-pinned 0.17-dev spells it `field_names`, and this+/// tree has to compile on both.+var g_declined: [std.enums.values(shapes.TaskClass).len]u8 = @splat(0);++pub fn priorAttemptFailed(tc: shapes.TaskClass) bool {+ return g_declined[@intFromEnum(tc)] > 0;+}++pub fn noteDeclined(tc: shapes.TaskClass) void {+ const i = @intFromEnum(tc);+ if (g_declined[i] < 255) g_declined[i] += 1;+}++/// Test seam / session reset.+pub fn resetSession() void {+ g_declined = @splat(0);+ g_explore_used = false;+}++/// A pipeline that could not fit the pool counts as a declined attempt for+/// every class at once: a pipeline carries items, not an ask, so there is no+/// per-class signal — and under-counting a failed attempt is the error that+/// leaves a genuinely stuck task stuck.+pub fn notePipelineDeclined() void {+ for (&g_declined) |*d| if (d.* < 255) {+ d.* += 1;+ };+}++/// Did the USER choose the shape? Then the ladder advises but never+/// overrules, and the resulting rows are `source:"explicit"` and never fold —+/// the #290 firewall, applied to orchestration the same way it is applied to+/// prompt genomes.+pub fn userChoseShape(raw: []const u8) bool {+ const needles = [_][]const u8{+ "shape a", "shape b", "shape c", "shape d", "shape e", "shape f",+ "fan out", "fan-out", "in parallel", "spawn ", "one agent per", "subagents",+ "use the workflow tool", "run a fleet", "parallel agents",+ };+ for (needles) |n| if (util.indexOfIgnoreCase(raw, n) != null) return true;+ return false;+}++/// ε for the exploration probe. One in ten R0 answers is spent buying an+/// observation of the rung above, because a policy that only ever files rows+/// for the arm it already prefers can never learn it was wrong.+pub const explore_epsilon: u32 = 10;+/// Test seam for the one-shot gate below; production reads the real flag.+pub var g_force_oneshot: bool = false;+var g_explore_used: bool = false;+var g_explore_rng: std.Random.DefaultPrng = .init(0x51ac0de);++/// Exploration runs on one-shot / eval invocations only — `main.unattended`,+/// the flag session_run sets on the `-p` path. An interactive session is+/// somebody's actual work, and spending their turn on a probe they did not+/// ask for is not a trade the harness gets to make.+pub fn exploreAllowed() bool {+ return g_force_oneshot or main_mod.unattended;+}++/// Should this R0 answer be spent on a probe instead? Once per session, only+/// on a one-shot run, and only when the rung above is affordable ON TOP of+/// the landing reserve — an exploration that cannot finish teaches nothing+/// except that the budget was too small, which the ladder already knew.+pub fn shouldExplore(o: Observables) bool {+ if (!exploreAllowed() or g_explore_used) return false;+ const l = pb.Ledger.init(o.cap);+ if (!l.fits(o.remaining, pb.fleetFloor(o.shape))) return false;+ if (g_explore_rng.random().uintLessThan(u32, explore_epsilon) != 0) return false;+ g_explore_used = true;+ return true;+}++// ── the whole gate ─────────────────────────────────────────────────────────++/// Everything `admit` needs from the calling agent, so this module never has+/// to import tools.zig (which would put it on the workflow import cycle).+pub const Ctx = struct {+ gpa: Allocator,+ io: Io,+ arena: Allocator,+ tracer: ?*trace.Tracer = null,+ /// The shared pool's state, read once — it is atomic and shared with+ /// concurrent children, so a cached copy would go stale immediately.+ remaining: u64 = std.math.maxInt(u64),+ cap: u64 = 0,+ used: u64 = 0,+ /// The ROOT's resolved model: this decision's fitness stratum.+ stratum: []const u8 = "",+ agent_cwd: ?[]const u8 = null,+};++/// Build a Ctx from a live ToolCtx, taken as `anytype` so this module stays+/// off tools.zig's import graph (the same trick brief_diversity.noteSiblingBatch+/// uses). Reads the shared pool ONCE, here, so every gate below this point+/// reasons about one consistent snapshot.+pub fn ctxFrom(t: anytype, arena: Allocator) Ctx {+ return .{+ .gpa = t.gpa,+ .io = t.io,+ .arena = arena,+ .tracer = t.tracer,+ .remaining = pb.remainingOf(t.run_budget),+ .cap = pb.capOf(t.run_budget),+ .used = pb.usedOf(t.run_budget),+ .stratum = t.provider.model,+ .agent_cwd = t.agent_cwd,+ };+}++/// The pure decision: ladder, then the learned override, then exploration.+/// Split out of `admit` so the whole threshold matrix is unit-testable with+/// no allocator, no trace file and no process. `arms` is the folded evidence+/// (orch.g_arms in production, fixtures in tests) and `key` is the cell it is+/// consulted under — passed in rather than rebuilt so a test can drive the+/// learned path without a live archive.+pub fn decide(o: Observables, phases: []const Value, explicit: bool, arms: []const orch.ArmObs, key: orch.Key) Decision {+ const ladder = ladderRung(o);+ if (explicit) {+ // The user asked for orchestration. Honour it at R2 or above, mark it+ // explicit, and let nothing learned move it in either direction.+ const rung: Rung = if (ladder.level() >= Rung.R2.level()) ladder else .R2;+ return .{ .rung = rung, .source = .explicit, .verdict = verdictFor(rung, o, phases) };+ }+ const reserve = pb.landingReserve(o.cap);+ if (orch.override(arms, key, ladder, o.remaining, reserve)) |learned| {+ return .{ .rung = learned, .source = .learned, .verdict = verdictFor(learned, o, phases) };+ }+ if (ladder == .R0 and shouldExplore(o)) {+ return .{ .rung = .R1, .source = .explore, .verdict = verdictFor(.R1, o, phases) };+ }+ return .{ .rung = ladder, .source = .bootstrap, .verdict = verdictFor(ladder, o, phases) };+}++/// The learned answer this cell has, falling back to the compiled bootstrap+/// prior — the same two-layer lookup `orch.learnedRung` performs, exposed as+/// a slice so `decide` stays pure.+fn armsFor(key: orch.Key) []const orch.ArmObs {+ for (orch.g_arms) |a| if (a.key.eql(key)) return orch.g_arms;+ return &.{};+}++/// Production entry: observe, decide, record, park. Called once at the top of+/// 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);+ const key: orch.Key = .{+ .task_class = o.task_class,+ .budget_band = orch.BudgetBand.of(o.remaining),+ .stratum = route_policy.stratumOf(c.stratum),+ };+ // The learned lookup is keyed with the REAL stratum; `decide` takes the+ // arms slice so the pure path can be driven with fixtures.+ var d = decide(o, phases, userChoseShape(raw), armsFor(key), key);+ // Nothing learned for this cell? Fall back to the compiled bootstrap+ // prior, which is the study's own measurements as n=2 pseudo-rows.+ if (d.source == .bootstrap and !userChoseShape(raw)) {+ if (orch.learnedRung(key, d.rung, o.remaining, pb.landingReserve(o.cap))) |learned| {+ d = .{ .rung = learned, .source = .learned, .verdict = verdictFor(learned, o, phases) };+ }+ }+ const collapse = predictedCollapse(c.arena, phases);+ orch_rows.emitDecision(.{+ .key = key,+ .arm = d.rung,+ .source = d.source,+ .remaining = o.remaining,+ .scope = orch.ScopeBucket.of(o.files),+ .files = o.files,+ .tasks_authored = o.tasks,+ .tasks_collapsed = collapse.collapsed,+ .downsized_from = switch (d.verdict) {+ .downsize => o.widest,+ else => 0,+ },+ .diversity_mean = collapse.mean,+ .diversity_warn = collapse.warn,+ });+ orch_rows.setPending(key, d.rung, d.source, c.used);+ if (c.tracer) |tr| {+ var buf: [192]u8 = undefined;+ const line = std.fmt.bufPrint(&buf, "arm={s} source={s} class={s} files={d} tasks={d} band={s} plan={d} reserve={d}", .{+ d.rung.label(), d.source.label(), o.task_class.label(), o.files,+ o.tasks, key.budget_band.label(), o.plan_estimate, pb.landingReserve(o.cap),+ }) catch "";+ tr.note("escalation", line);+ }+ // A declined (or scouted) ask is what `prior_failure` reads back if the+ // same class of ask returns — the cheapest honest "the small answer did+ // not stick" signal the harness has.+ switch (d.verdict) {+ .solo => noteDeclined(o.task_class),+ .downsize => |w| {+ if (d.rung == .R1) noteDeclined(o.task_class);+ d.downsized_from = if (w < o.widest) o.widest else 0;+ },+ else => {},+ }+ return d;+}++/// A `variants` phase keeps a collapse floor of 2 (see brief_diversity's+/// floors), read off the same canonical slot everything else keys on.+pub fn isVariantsPhase(pv: Value) bool {+ return std.mem.eql(u8, route_policy.phaseSlot(pv), "variants");+}++const CollapsePreview = struct { collapsed: usize = 0, mean: f64 = 0, warn: bool = false };++/// What the collapse gate WILL do to the widest phase, computed pre-spawn so+/// the decision row can carry it. Cheap: the same bounded Jaccard the gate+/// itself runs, over briefs already in memory.+fn predictedCollapse(arena: Allocator, phases: []const Value) CollapsePreview {+ var best: CollapsePreview = .{};+ for (phases) |pv| {+ if (pv != .object) continue;+ const tv = pv.object.get("tasks") orelse continue;+ if (tv != .array or tv.array.items.len < 2) continue;+ const n = @min(tv.array.items.len, brief_diversity.max_briefs);+ const briefs = arena.alloc([]const u8, n) catch return best;+ const genomes = arena.alloc(?[]const u8, n) catch return best;+ for (tv.array.items[0..n], briefs, genomes) |task_val, *b, *g| {+ b.* = "";+ g.* = null;+ if (task_val != .object) continue;+ const p = task_val.object.get("prompt") orelse continue;+ if (p == .string) b.* = p.string;+ g.* = fleet.resolveOverride(task_val.object);+ }+ const r = brief_diversity.analyze(arena, brief_diversity.personaAxis(arena, briefs, genomes) orelse briefs);+ const c = brief_diversity.collapse(arena, briefs, genomes, isVariantsPhase(pv));+ if (c.collapsed() > best.collapsed or r.mean > best.mean) best = .{+ .collapsed = @max(best.collapsed, c.collapsed()),+ .mean = @max(best.mean, r.mean),+ .warn = best.warn or r.warn,+ };+ }+ return best;+}++// ── the edit contract ──────────────────────────────────────────────────────+// 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 contract_unmet = edit_contract.contract_unmet;+pub const contract_brief_note = edit_contract.contract_brief_note;+pub const isContracted = edit_contract.isContracted;+pub const contractUnmet = edit_contract.contractUnmet;+pub const treeSnapshot = edit_contract.treeSnapshot;+pub const contractCheck = edit_contract.contractCheck;++test {+ _ = edit_contract;+ _ = @import("escalation_tests.zig");+}diff --git a/src/escalation_tests.zig b/src/escalation_tests.zignew file mode 100644index 00000000..ba882652--- /dev/null+++ b/src/escalation_tests.zig@@ -0,0 +1,401 @@+//! Tests for the escalation ladder and the edit contract, split out of+//! escalation.zig (600-line cap; the `<mod>_tests.zig` pattern, wired into the+//! test root by test_hooks.zig).+//!+//! The ladder is deliberately PURE over cheap observables, which is what makes+//! this file possible: the whole threshold matrix — scope x budget x+//! audit-language x prior-failure — is driven here with no allocator, no+//! network, no process and no trace file.++const std = @import("std");+const Value = std.json.Value;++const escalation = @import("escalation.zig");+const orch = @import("orchestration_policy.zig");+const pb = @import("phase_budget.zig");+const shapes = @import("shapes.zig");++const Rung = orch.Rung;++/// The observables the study's cap-30 runs actually presented, as a base to+/// vary one axis at a time from. 27 remaining is what is left after the root+/// has read the task and authored a workflow — the real moment `admit` runs.+fn base() escalation.Observables {+ return .{+ .shape = .review,+ .task_class = .bugfix,+ .files = 1,+ .widest = 3,+ .tasks = 5,+ .plan_estimate = 17,+ .audit = false,+ .prior_failure = false,+ .remaining = 27,+ .cap = 30,+ };+}++fn phasesFrom(a: std.mem.Allocator, src: []const u8) []const Value {+ const v = std.json.parseFromSliceLeaky(Value, a, src, .{}) catch unreachable;+ return v.array.items;+}++test "ladder: the study's cap-30 bugfix is R0 — one file is not a fleet" {+ // THE regression. 01-bugfix-B: two buggy functions in stats.py, given five+ // workers and three judges, 30 calls spent, zero edits. Scope decides, and+ // the scope here is one file.+ var o = base();+ try std.testing.expectEqual(Rung.R0, escalation.ladderRung(o));+ // Note WHY it is R0 and not a budget refusal: a review fleet (17) plus the+ // landing reserve (6) does fit the 27 that remain. The budget said yes.+ try std.testing.expect(pb.Ledger.init(30).fits(27, pb.fleetFloor(.review)));+ // Two files is still a pair, not a fan-out.+ o.files = 2;+ try std.testing.expectEqual(Rung.R0, escalation.ladderRung(o));+}++test "ladder: scope alone opens R2, and only at 3+ files with a plan that fans out" {+ var o = base();+ o.files = 3;+ try std.testing.expectEqual(Rung.R2, escalation.ladderRung(o));+ o.files = 8;+ try std.testing.expectEqual(Rung.R2, escalation.ladderRung(o));+ // A plan that authored ONE task per phase is not a fleet however many+ // files the ask names — there is nothing to run in parallel.+ o.widest = 1;+ try std.testing.expectEqual(Rung.R0, escalation.ladderRung(o));+}++test "ladder: budget vetoes R2 even at full scope" {+ var o = base();+ o.files = 6;+ // 12 left, 6 reserved, a review fleet needs 17: the fleet cannot finish,+ // so the answer is the rung that can.+ o.remaining = 12;+ try std.testing.expectEqual(Rung.R0, escalation.ladderRung(o));+ // Raise the ceiling and the same ask fans out.+ o.remaining = 30;+ try std.testing.expectEqual(Rung.R2, escalation.ladderRung(o));+}++test "ladder: audit-class language buys R3, and a prior failed attempt buys it for free" {+ var o = base();+ // Still one file — but the USER asked for breadth, so breadth is what they+ // are paying for. This is the deliberate escape hatch from R0.+ o.audit = true;+ try std.testing.expectEqual(Rung.R3, escalation.ladderRung(o));+ // …unless it cannot finish. R3 is not exempt from arithmetic.+ o.remaining = 10;+ try std.testing.expectEqual(Rung.R0, escalation.ladderRung(o));+ // First-attempt failure is the free escalation signal: same ask, same+ // scope, but the cheap answer has already been tried and did not stick.+ o = base();+ o.prior_failure = true;+ try std.testing.expectEqual(Rung.R3, escalation.ladderRung(o));+}++test "ladder: an open-ended research ask is R1, one scout — never a sweep fleet" {+ var o = base();+ o.shape = .research;+ o.task_class = .research;+ o.files = 4; // enough files for R2 on any other shape+ // 05-research-B: three sweepers over three small files, briefs measuring+ // 1.000 similar to each other, 24 calls — for an answer one scout reached.+ try std.testing.expectEqual(Rung.R1, escalation.ladderRung(o));+ // Audit language still overrides upward: "exhaustively map every module"+ // is a real fleet ask even though it is research-shaped.+ o.audit = true;+ try std.testing.expectEqual(Rung.R3, escalation.ladderRung(o));+}++test "verdictFor: R0 declines non-error, R1 caps at one scout, R2 downsizes to fit" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const phases = phasesFrom(a,+ \\[{"title":"find bugs","tasks":[1,2,3,4,5,6]},+ \\ {"title":"synthesize","tasks":[1]}]+ );++ var o = base();+ // R0's advisory is a RESULT, not an error: a declined fleet is not a+ // failed tool call, and is_error here would burn a retry and read to the+ // model as a broken harness.+ switch (escalation.verdictFor(.R0, o, phases)) {+ .solo => |advice| {+ try std.testing.expect(std.mem.indexOf(u8, advice, "R0") != null);+ try std.testing.expect(std.mem.indexOf(u8, advice, "Do it yourself") != null);+ // It also says what would earn a fleet, so the model has a path.+ try std.testing.expect(std.mem.indexOf(u8, advice, "verification fails") != null);+ },+ else => return error.ExpectedSolo,+ }+ try std.testing.expectEqual(@as(usize, 1), (escalation.verdictFor(.R1, o, phases)).downsize);++ // 6 finders (24) + 1 synthesis (2) = 26, against 21 spendable → trim.+ o.plan_estimate = 26;+ const w = (escalation.verdictFor(.R2, o, phases)).downsize;+ try std.testing.expect(w >= 1 and w < 6);+ // A plan that already fits is not touched.+ o.plan_estimate = 14;+ try std.testing.expect(escalation.verdictFor(.R2, o, phases) == .proceed);+}++test "downsizeWidth: trims redundant finders and never the landing phase" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ // A-fix at width: 4 finders (16) + 1 implementer (6) + 1 verify (3) = 25,+ // against 21 spendable at cap 30 / 27 remaining.+ const phases = phasesFrom(a,+ \\[{"title":"find the defect","tasks":[1,2,3,4]},+ \\ {"title":"implement the fix","tasks":[1]},+ \\ {"title":"verify the diff","tasks":[1]}]+ );+ const w = escalation.downsizeWidth(phases, 30, 27);+ // 3 finders (12) + 6 + 3 = 21 fits exactly; 4 (16+6+3=25) would not.+ try std.testing.expectEqual(@as(usize, 3), w);+ // Whatever the width, the implement phase carries one task, so the edit+ // contract survives every trim — which is §4-P1's inviolable rule.+ try std.testing.expect(w >= 1);+ // Squeeze until only the skinniest plan fits: 1 finder + 1 implementer ++ // 1 verify = 13, on top of the 6-call reserve, so 19 left is the floor.+ try std.testing.expectEqual(@as(usize, 1), escalation.downsizeWidth(phases, 30, 19));+ // And below that, nothing fits — the caller must fall back to solo. Note+ // WHAT does not fit: the landing phase's own implementer, which is the+ // point at which a fleet stops being able to produce a patch at all.+ try std.testing.expectEqual(@as(usize, 0), escalation.downsizeWidth(phases, 30, 18));+ // An unlimited pool never trims.+ try std.testing.expectEqual(@as(usize, 4), escalation.downsizeWidth(phases, 0, std.math.maxInt(u64)));+}++test "decide: an explicit user shape choice is honoured and never overridden (#290)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const phases = phasesFrom(a, "[{\"title\":\"find bugs\",\"tasks\":[1,2,3]}]");+ const key: orch.Key = .{ .task_class = .bugfix, .budget_band = .b40, .stratum = "m" };++ // A learned cell that would normally trade this run DOWN to R0.+ var arms = [_]orch.ArmObs{+ armWith(key, .R2, 3, 0.2, 30),+ armWith(key, .R0, 4, 0.9, 8),+ };++ // Without an explicit choice, the ladder's R0 stands and the source says+ // which layer decided.+ const implicit = escalation.decide(base(), phases, false, &arms, key);+ try std.testing.expectEqual(Rung.R0, implicit.rung);+ try std.testing.expectEqual(orch.Source.bootstrap, implicit.source);++ // With one, the user's intent wins outright: R2 or above, marked explicit,+ // and no learned arm may move it in either direction.+ const explicit = escalation.decide(base(), phases, true, &arms, key);+ try std.testing.expect(explicit.rung.level() >= Rung.R2.level());+ try std.testing.expectEqual(orch.Source.explicit, explicit.source);+ try std.testing.expect(explicit.verdict != .solo);+}++test "decide: a learned cell overrides the hand ladder and says so" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const phases = phasesFrom(a, "[{\"title\":\"find bugs\",\"tasks\":[1,2,3]}]");+ const key: orch.Key = .{ .task_class = .bugfix, .budget_band = .b40, .stratum = "m" };+ var o = base();+ o.files = 4; // the hand ladder would say R2 here++ var arms = [_]orch.ArmObs{+ armWith(key, .R2, 4, 0.4, 28),+ armWith(key, .R0, 5, 0.95, 9),+ };+ const d = escalation.decide(o, phases, false, &arms, key);+ // Trading DOWN needs only "not worse", and this is much better.+ try std.testing.expectEqual(Rung.R0, d.rung);+ try std.testing.expectEqual(orch.Source.learned, d.source);+}++fn armWith(key: orch.Key, arm: Rung, n: u32, score: f64, calls: u32) orch.ArmObs {+ var a: orch.ArmObs = .{ .key = key, .arm = arm };+ var i: u32 = 0;+ while (i < n) : (i += 1) {+ a.sum_score += score;+ a.n += 1;+ a.landed_n += 1;+ a.calls[a.n_calls] = calls;+ a.n_calls += 1;+ }+ return a;+}++test "userChoseShape: names the fan-out, not merely the codeword" {+ // The codeword alone is NOT an explicit shape choice — that is the whole+ // premise of the redesign: `ultracode` opts into the ladder, not into a+ // fleet. Only naming the structure counts.+ try std.testing.expect(!escalation.userChoseShape("ultracode fix the bug in stats.py"));+ try std.testing.expect(escalation.userChoseShape("ultracode use shape A on this diff"));+ try std.testing.expect(escalation.userChoseShape("fan out three reviewers"));+ try std.testing.expect(escalation.userChoseShape("spawn one agent per module"));+ try std.testing.expect(escalation.userChoseShape("review these IN PARALLEL"));+ try std.testing.expect(!escalation.userChoseShape("summarize the changelog"));+}++test "countDistinctFiles: paths, not version numbers or sentence periods" {+ // The study's five prompts, as scope evidence.+ try std.testing.expectEqual(@as(usize, 2), escalation.countDistinctFiles(+ "This directory contains stats.py and test_stats.py. Two of the three functions in stats.py have bugs.",+ ));+ try std.testing.expectEqual(@as(usize, 2), escalation.countDistinctFiles(+ "Create a command-line tool wordfreq.py in this directory. There is a sample.txt to test against.",+ ));+ try std.testing.expectEqual(@as(usize, 4), escalation.countDistinctFiles(+ "This directory is a small Python project: engine.py, report.py, main.py and settings.json.",+ ));+ // A trailing period, a version number and a bare sentence are not files.+ try std.testing.expectEqual(@as(usize, 0), escalation.countDistinctFiles(+ "The minimum supported Python version is 3.11. Prefer the most recent source.",+ ));+ // Directory-qualified paths count once each, case-insensitively.+ try std.testing.expectEqual(@as(usize, 2), escalation.countDistinctFiles("src/main.zig and SRC/MAIN.ZIG and src/util.zig"));+ // Bounded: a brief naming hundreds of distinct paths still fits the fixed+ // scratch, and the count saturates rather than growing without limit.+ var many: [9 * 300]u8 = @splat(' ');+ for (0..300) |i| _ = std.fmt.bufPrint(many[i * 9 ..][0..8], "f{d:0>4}.py", .{i}) catch unreachable;+ const n = escalation.countDistinctFiles(&many);+ try std.testing.expectEqual(@as(usize, escalation.max_files_counted), n);+ // Which is still far above the only threshold that reads it.+ try std.testing.expect(n >= escalation.fleet_scope_min);+}++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.+ //+ // An uncontracted phase is never judged on the tree at all.+ try std.testing.expect(!escalation.contractUnmet(false, "", ""));+ try std.testing.expect(!escalation.contractUnmet(false, " M stats.py\n", " M stats.py\n"));++ // Contracted + clean tree: nothing landed, period. This is the 30-calls-+ // no-edit run, caught by a probe that costs zero model calls.+ try std.testing.expect(escalation.contractUnmet(true, "", ""));+ try std.testing.expect(escalation.contractUnmet(true, "", " \n \t\n"));++ // Contracted + a tree that moved: the work landed.+ try std.testing.expect(!escalation.contractUnmet(true, "", " M stats.py\n"));+ try std.testing.expect(!escalation.contractUnmet(true, " M stats.py\n", " M stats.py\n M util.py\n"));++ // Contracted + an ALREADY-dirty tree this phase did not touch: also unmet.+ // Without this, any phase run in a workspace with uncommitted work would+ // pass the contract for free, which is most real workspaces.+ try std.testing.expect(escalation.contractUnmet(true, " M stats.py\n", " M stats.py\n"));+ try std.testing.expect(escalation.contractUnmet(true, " M stats.py", " M stats.py\n"));+}++test "the contract's texts say what to DO, not merely that something failed" {+ // The failure text is fed straight back to a worker that gets one retry,+ // so it has to be an instruction.+ try std.testing.expect(std.mem.indexOf(u8, escalation.contract_unmet, "no files changed") != null);+ try std.testing.expect(std.mem.indexOf(u8, escalation.contract_unmet, "changed path") != null);+ // And it must NOT carry the not-retry-safe marker, or the retry the+ // contract depends on would be skipped.+ try std.testing.expect(std.mem.indexOf(u8, escalation.contract_unmet, "retry is NOT safe") == null);+ // The brief boilerplate is codex's changed-path listing requirement.+ try std.testing.expect(std.mem.indexOf(u8, escalation.contract_brief_note, "changed:") != null);+}++test "isContracted / isVariantsPhase read the closed slot vocabulary" {+ try std.testing.expect(escalation.isContracted(shapes.canonicalSlot("implement the fix")));+ try std.testing.expect(escalation.isContracted(shapes.canonicalSlot("build from the winner")));+ try std.testing.expect(!escalation.isContracted(shapes.canonicalSlot("find security bugs")));+ try std.testing.expect(!escalation.isContracted(shapes.canonicalSlot("verify each finding")));++ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const phases = phasesFrom(a,+ \\[{"title":"variants of the landing page","tasks":[1,2]},+ \\ {"title":"find bugs","tasks":[1]}]+ );+ try std.testing.expect(escalation.isVariantsPhase(phases[0]));+ try std.testing.expect(!escalation.isVariantsPhase(phases[1]));+}++test "prior-failure tracking: the second ask of a class carries the escalation signal" {+ escalation.resetSession();+ defer escalation.resetSession();+ try std.testing.expect(!escalation.priorAttemptFailed(.bugfix));+ escalation.noteDeclined(.bugfix);+ try std.testing.expect(escalation.priorAttemptFailed(.bugfix));+ // Per class: declining a bugfix says nothing about a research ask.+ try std.testing.expect(!escalation.priorAttemptFailed(.research));+ // A pipeline that could not fit has no class, so it counts for all.+ escalation.notePipelineDeclined();+ try std.testing.expect(escalation.priorAttemptFailed(.research));+}++test "observe: reads scope off the ask AND the plan, and classifies the ask" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const phases = phasesFrom(a,+ \\[{"title":"find bugs","tasks":[+ \\ {"prompt":"read report.py and settings.json"},+ \\ {"prompt":"read main.py"}]}]+ );+ const o = escalation.observe(phases, "ultracode fix the bug in stats.py", .review, 27, 30);+ // stats.py from the ASK plus three from the briefs: the ask is scope+ // evidence even when the plan paraphrases it.+ try std.testing.expectEqual(@as(usize, 4), o.files);+ try std.testing.expectEqual(@as(usize, 2), o.tasks);+ try std.testing.expectEqual(@as(usize, 2), o.widest);+ try std.testing.expectEqual(shapes.TaskClass.bugfix, o.task_class);+ try std.testing.expect(!o.audit);+ // 2 finders at 4 calls each.+ try std.testing.expectEqual(@as(u64, 8), o.plan_estimate);+}++test "shapes.classOf / isAuditClass: the study's five prompts land where the ladder needs them" {+ try std.testing.expectEqual(shapes.TaskClass.bugfix, shapes.classOf(+ "Two of the three functions in stats.py have bugs. Fix stats.py so that the whole pytest suite passes.",+ ));+ try std.testing.expectEqual(shapes.TaskClass.refactor, shapes.classOf(+ "Refactor it: 1. Rename the class TaxEngine to LevyEngine.",+ ));+ try std.testing.expectEqual(shapes.TaskClass.research, shapes.classOf(+ "Write summary.md answering these four questions, and cite the file each answer comes from.",+ ));+ try std.testing.expectEqual(shapes.TaskClass.feature, shapes.classOf(+ "Create a command-line tool wordfreq.py in this directory.",+ ));+ // A repair ask that MENTIONS review is still a repair — the precedence+ // that stops shape A from being handed a bugfix.+ try std.testing.expectEqual(shapes.TaskClass.bugfix, shapes.classOf("fix the bug the review found"));+ // …and an ordinary feature spec that happens to say "broken" is NOT a+ // bugfix. The bare needle mis-classified the study's own wordfreq task,+ // caught on the first acceptance run: the full prompt says "ties broken by+ // ascending ASCII order", which is a sort rule, not a defect report.+ const wordfreq_full =+ "Create a command-line tool wordfreq.py in this directory. Output: one line per token, " +++ "sorted by count descending, ties broken by ascending ASCII order of the token.";+ try std.testing.expectEqual(shapes.TaskClass.feature, shapes.classOf(wordfreq_full));+ // The qualified forms still read as defects.+ try std.testing.expectEqual(shapes.TaskClass.bugfix, shapes.classOf("the parser is broken on empty input"));+ try std.testing.expectEqual(shapes.TaskClass.bugfix, shapes.classOf("two broken tests in the suite"));+ // Audit language is narrow on purpose: a fleet takes an explicit word.+ try std.testing.expect(shapes.isAuditClass("thoroughly audit the auth layer"));+ try std.testing.expect(shapes.isAuditClass("check every file for this pattern"));+ try std.testing.expect(!shapes.isAuditClass("fix the bug in stats.py"));+ try std.testing.expect(!shapes.isAuditClass("add a --top flag"));+}++test "shapes.rawAsk: captured by value, so a freed per-turn arena cannot dangle" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ const a = arena_state.allocator();+ const typed = try std.fmt.allocPrint(a, "ultracode fix {s}", .{"stats.py"});+ _ = try shapes.applyUltracodeSteering(a, typed, typed, false);+ try std.testing.expectEqualStrings("ultracode fix stats.py", shapes.rawAsk());+ // Free the arena the string came from; the capture must survive it.+ arena_state.deinit();+ try std.testing.expectEqualStrings("ultracode fix stats.py", shapes.rawAsk());+ try std.testing.expectEqual(shapes.TaskClass.bugfix, shapes.classOf(shapes.rawAsk()));+}diff --git a/src/orchestration_policy.zig b/src/orchestration_policy.zignew file mode 100644index 00000000..da7487a5--- /dev/null+++ b/src/orchestration_policy.zig@@ -0,0 +1,428 @@+//! The escalation ladder as a LEARNED policy.+//!+//! escalation.zig's rungs are hand rules, and hand rules are a bootstrap, not+//! an answer: they encode what one 16-run study measured on one machine with+//! one model. This module is how they erode toward measured reality. Every+//! admission decision writes a `kind:"orch"` row naming the rung it chose and+//! WHY (learned | bootstrap | explicit | explore); every scored run writes a+//! `kind:"orch_outcome"` row naming what that rung actually cost and whether+//! it landed the work; `foldArms` pools them per cell; and where a cell has+//! real evidence, the learned arm replaces the hand rung.+//!+//! Sibling of route_policy.zig, deliberately: same archive, same fold-once+//! pass (bench_priors.loadInto), same #290 discipline. The difference is what+//! is being learned — route_policy learns WHICH MODEL serves a (shape, role)+//! seat; this learns HOW MUCH ORCHESTRATION a (task_class, budget_band,+//! stratum) cell is worth buying. Those are orthogonal, and keeping them in+//! two modules keeps a change to one from silently re-weighting the other.+//!+//! THE #290 FIREWALL, inviolable and enforced in foldArms:+//!+//! * `source:"explicit"` rows NEVER fold. When the user names the shape,+//! the arm records user intent, not policy quality; folding it would let+//! a run the policy did not choose vote on what the policy should choose.+//! * Folding is WITHIN A STRATUM only — the stratum is part of the key, so+//! two runs on different models never pool. A rung that is right for a+//! frontier root is not automatically right for a small one.+//! * `variant_free:false` rows are excluded. If scoreVariants mutated the+//! genome mid-run, the score measures a prompt tournament as much as the+//! rung; only champion-genome runs attribute to the arm.+//! * Comparisons are per-cell MEANS gated by `min_arm_obs`, never+//! prompt-level A/B. One lucky run must not move a ladder.++const std = @import("std");+const Allocator = std.mem.Allocator;++const shapes = @import("shapes.zig");++pub const TaskClass = shapes.TaskClass;++// ── the arms ───────────────────────────────────────────────────────────────++/// How much orchestration a run bought. The closed vocabulary both the hand+/// ladder and the learned policy speak.+pub const Rung = enum {+ /// Solo: the root does the work; the workflow tool declines and says so.+ R0,+ /// One scout: a single sweep + synthesize, to keep the parent's context+ /// clean rather than to parallelize.+ R1,+ /// A fleet: the authored shape, possibly downsized to fit the budget.+ R2,+ /// The full shape plus judges — audit-class asks and post-failure retries.+ R3,++ pub fn label(self: Rung) []const u8 {+ return @tagName(self);+ }++ pub fn parse(s: []const u8) ?Rung {+ return std.meta.stringToEnum(Rung, s);+ }++ /// Ordinal, for the trade-down asymmetry in `override`.+ pub fn level(self: Rung) u8 {+ return switch (self) {+ .R0 => 0,+ .R1 => 1,+ .R2 => 2,+ .R3 => 3,+ };+ }+};++/// Which layer produced the rung on a decision row. Named on every row so+/// "why did this run fan out" is a grep, not an inference — the same+/// discipline route_policy.Source applies to model routing.+pub const Source = enum {+ /// A folded cell with enough observations beat the hand ladder.+ learned,+ /// The hand ladder in escalation.zig decided (the default, and what a+ /// fresh install does forever until it has evidence).+ bootstrap,+ /// The USER named the shape/rung. Never folded — see the firewall above.+ explicit,+ /// An ε-greedy probe, taken only where the answer would have been R0.+ explore,++ pub fn label(self: Source) []const u8 {+ return @tagName(self);+ }++ pub fn parse(s: []const u8) ?Source {+ return std.meta.stringToEnum(Source, s);+ }+};++/// `remaining()` bucketed. A rung that is right with 100 calls left is wrong+/// with 15, so the budget has to be part of the key rather than a covariate.+pub const BudgetBand = enum {+ b15,+ b40,+ b100,+ unlimited,++ pub fn of(remaining: u64) BudgetBand {+ if (remaining == std.math.maxInt(u64)) return .unlimited;+ if (remaining <= 15) return .b15;+ if (remaining <= 40) return .b40;+ if (remaining <= 100) return .b100;+ return .unlimited;+ }++ pub fn label(self: BudgetBand) []const u8 {+ return @tagName(self);+ }++ pub fn parse(s: []const u8) BudgetBand {+ return std.meta.stringToEnum(BudgetBand, s) orelse .unlimited;+ }+};++/// How many distinct files the ask names. RECORDED on rows as a signal, never+/// part of the key: three buckets times the key above would quadruple the+/// cell count and no install would ever reach min_arm_obs in any of them.+pub const ScopeBucket = enum {+ s1_2,+ s3_5,+ s6plus,++ pub fn of(files: usize) ScopeBucket {+ if (files <= 2) return .s1_2;+ if (files <= 5) return .s3_5;+ return .s6plus;+ }++ pub fn label(self: ScopeBucket) []const u8 {+ return @tagName(self);+ }+};++/// The niche key. `stratum` is the root's resolved model, per fitness_strata+/// rules (route_policy.stratumOf) — a borrowed slice, valid for the archive+/// read that produced it.+pub const Key = struct {+ task_class: TaskClass = .other,+ budget_band: BudgetBand = .unlimited,+ stratum: []const u8 = "",++ pub fn eql(a: Key, b: Key) bool {+ return a.task_class == b.task_class and a.budget_band == b.budget_band and+ std.mem.eql(u8, a.stratum, b.stratum);+ }+};++// ── folded observations ────────────────────────────────────────────────────++/// A cell needs this many observations of an arm before the policy will speak+/// for it. Three, not two: at n=2 a single outlier is half the evidence.+pub const min_arm_obs: u32 = 3;++/// How much better a learned arm must score before it may ESCALATE past the+/// hand ladder. Trading DOWN is cheaper (see `override`) — the asymmetry is+/// deliberate, because the failure mode this whole redesign exists to fix is+/// over-escalation, and a policy that finds cheaper answers should be able to+/// act on that sooner than one that finds more expensive ones.+pub const override_delta: f64 = 0.05;++/// Call samples kept per arm, for the p90. Bounded so an install with a long+/// history cannot make the fold allocate without limit.+pub const max_call_samples = 64;++pub const ArmObs = struct {+ key: Key = .{},+ arm: Rung = .R0,+ n: u32 = 0,+ sum_score: f64 = 0,+ exhausted_n: u32 = 0,+ landed_n: u32 = 0,+ calls: [max_call_samples]u32 = @splat(0),+ n_calls: usize = 0,++ pub fn mean(self: ArmObs) f64 {+ return if (self.n == 0) 0 else self.sum_score / @as(f64, @floatFromInt(self.n));+ }++ pub fn exhaustRate(self: ArmObs) f64 {+ return if (self.n == 0) 0 else @as(f64, @floatFromInt(self.exhausted_n)) / @as(f64, @floatFromInt(self.n));+ }++ pub fn landRate(self: ArmObs) f64 {+ return if (self.n == 0) 0 else @as(f64, @floatFromInt(self.landed_n)) / @as(f64, @floatFromInt(self.n));+ }++ /// The 90th-percentile call count, by nearest-rank over the retained+ /// samples. Used as the cost half of the override rule: a learned arm may+ /// only be taken when its BAD case still fits, not when its median does.+ pub fn p90Calls(self: ArmObs) u64 {+ if (self.n_calls == 0) return 0;+ var buf: [max_call_samples]u32 = @splat(0);+ @memcpy(buf[0..self.n_calls], self.calls[0..self.n_calls]);+ const s = buf[0..self.n_calls];+ std.mem.sort(u32, s, {}, std.sort.asc(u32));+ // Nearest-rank: ceil(0.9 * n), 1-based, clamped into the slice.+ const rank = (self.n_calls * 9 + 9) / 10;+ return s[@min(rank, s.len) - 1];+ }++ fn note(self: *ArmObs, score: f64, calls: u64, exhausted: bool, landed: bool) void {+ self.sum_score += score;+ self.n += 1;+ if (exhausted) self.exhausted_n += 1;+ if (landed) self.landed_n += 1;+ if (self.n_calls < max_call_samples) {+ self.calls[self.n_calls] = std.math.cast(u32, calls) orelse std.math.maxInt(u32);+ self.n_calls += 1;+ }+ }+};++fn strField(o: std.json.ObjectMap, key: []const u8) ?[]const u8 {+ const v = o.get(key) orelse return null;+ return if (v == .string) v.string else null;+}++fn numField(o: std.json.ObjectMap, key: []const u8) ?f64 {+ const v = o.get(key) orelse return null;+ return switch (v) {+ .float => |f| f,+ .integer => |x| @floatFromInt(x),+ else => null,+ };+}++fn boolField(o: std.json.ObjectMap, key: []const u8, dflt: bool) bool {+ const v = o.get(key) orelse return dflt;+ return if (v == .bool) v.bool else dflt;+}++/// Pool the archive's `kind:"orch_outcome"` rows into (key, arm) cells,+/// applying the #290 firewall. A row missing any coordinate is SKIPPED rather+/// than filed under a default — an uncelled observation is honest, a+/// mis-celled one silently steers every future run in that cell.+pub fn foldArms(arena: Allocator, archive: []const u8) []ArmObs {+ var out: std.ArrayList(ArmObs) = .empty;+ var it = std.mem.splitScalar(u8, archive, '\n');+ while (it.next()) |ln| {+ const t = std.mem.trim(u8, ln, " \t\r");+ if (t.len == 0) continue;+ const v = std.json.parseFromSliceLeaky(std.json.Value, arena, t, .{}) catch continue;+ if (v != .object) continue;+ const o = v.object;+ const kind = strField(o, "kind") orelse continue;+ if (!std.mem.eql(u8, kind, "orch_outcome")) continue;++ // FIREWALL 1 — user intent never votes on policy.+ const source = Source.parse(strField(o, "source") orelse "") orelse continue;+ if (source == .explicit) continue;+ // FIREWALL 2 — only champion-genome runs attribute to the arm.+ if (!boolField(o, "variant_free", true)) continue;++ const arm = Rung.parse(strField(o, "arm") orelse "") orelse continue;+ // FIREWALL 3 — the stratum is part of the key, so a row without one+ // cannot be pooled with rows that have one.+ const stratum = strField(o, "stratum") orelse continue;+ if (stratum.len == 0) continue;+ const tc = strField(o, "task_class") orelse continue;+ const bb = strField(o, "budget_band") orelse continue;+ const score = numField(o, "score") orelse continue;+ if (!(score >= 0 and score <= 1)) continue; // the #168 [0,1] contract+ const calls: u64 = blk: {+ const c = numField(o, "calls_used") orelse break :blk 0;+ break :blk if (c < 0) 0 else @intFromFloat(c);+ };+ const key: Key = .{+ .task_class = TaskClass.parse(tc),+ .budget_band = BudgetBand.parse(bb),+ .stratum = stratum,+ };+ const slot: *ArmObs = for (out.items) |*c| {+ if (c.arm == arm and c.key.eql(key)) break c;+ } else blk: {+ out.append(arena, .{ .key = key, .arm = arm }) catch return out.items;+ break :blk &out.items[out.items.len - 1];+ };+ slot.note(score, calls, boolField(o, "exhausted", false), boolField(o, "landed", false));+ }+ return out.items;+}++/// Session-arena cells, folded once by bench_priors.loadInto off the same+/// archive read that feeds route_policy — so the two policies can never+/// disagree about which runs they have seen. Empty = no evidence = the hand+/// ladder decides, which is what a fresh install does.+pub var g_arms: []const ArmObs = &.{};++pub fn loadArms(arena: Allocator, archive: []const u8) void {+ g_arms = foldArms(arena, archive);+}++// ── the bootstrap prior ────────────────────────────────────────────────────++/// What the study measured, as pseudo-observations. These are the ONLY+/// evidence a fresh install has, and they are deliberately weak (n=2, below+/// min_arm_obs) so three real local rows outvote them completely.+///+/// Read the bugfix/b40 pair as the whole story this redesign exists for: at a+/// cap of 30, solo scored 1.0 in 10 calls and the fleet scored 0.0 in 30 and+/// died exhausted. Given an unbounded pool the fleet does eventually get+/// there (0.8 at 48 calls) — it was never WRONG, it was overpriced.+pub const Pseudo = struct {+ task_class: TaskClass,+ budget_band: BudgetBand,+ arm: Rung,+ score: f64,+ calls: u64,+ exhausted: bool = false,+ landed: bool = true,+ n: u32 = 2,+};++pub const bootstrap_prior = [_]Pseudo{+ .{ .task_class = .bugfix, .budget_band = .b40, .arm = .R0, .score = 1.0, .calls = 10 },+ .{ .task_class = .bugfix, .budget_band = .b40, .arm = .R2, .score = 0.0, .calls = 30, .exhausted = true, .landed = false },+ .{ .task_class = .bugfix, .budget_band = .unlimited, .arm = .R0, .score = 1.0, .calls = 10 },+ .{ .task_class = .bugfix, .budget_band = .unlimited, .arm = .R2, .score = 0.8, .calls = 48 },+ .{ .task_class = .feature, .budget_band = .b40, .arm = .R0, .score = 1.0, .calls = 5 },+ .{ .task_class = .feature, .budget_band = .b40, .arm = .R2, .score = 1.0, .calls = 30, .exhausted = true },+ .{ .task_class = .refactor, .budget_band = .b40, .arm = .R0, .score = 1.0, .calls = 9 },+ .{ .task_class = .refactor, .budget_band = .b40, .arm = .R2, .score = 1.0, .calls = 30, .exhausted = true },+ .{ .task_class = .research, .budget_band = .unlimited, .arm = .R1, .score = 1.0, .calls = 12 },+ .{ .task_class = .research, .budget_band = .unlimited, .arm = .R2, .score = 1.0, .calls = 24 },+};++/// The prior for one cell, as ArmObs, so `override` reads one shape of+/// evidence whether it came from the compiled table or the local archive.+pub fn priorFor(buf: []ArmObs, key: Key) []ArmObs {+ var n: usize = 0;+ for (bootstrap_prior) |p| {+ if (n == buf.len) break;+ if (p.task_class != key.task_class or p.budget_band != key.budget_band) continue;+ var obs: ArmObs = .{ .key = key, .arm = p.arm };+ var k: u32 = 0;+ while (k < p.n) : (k += 1) obs.note(p.score, p.calls, p.exhausted, p.landed);+ buf[n] = obs;+ n += 1;+ }+ return buf[0..n];+}++// ── the override rule ──────────────────────────────────────────────────────++fn findArm(arms: []const ArmObs, key: Key, arm: Rung) ?ArmObs {+ for (arms) |a| if (a.arm == arm and a.key.eql(key)) return a;+ return null;+}++/// The learned rung for `key`, or null to keep `ladder` — which is what every+/// sparse, unmeasured or unaffordable case returns, so bootstrap behavior is+/// the hand ladder's behavior.+///+/// Two asymmetric gates, both requiring n >= min_arm_obs:+///+/// ESCALATE (a higher rung than the ladder chose): must beat the ladder+/// arm's folded mean by `override_delta`, AND its p90 call count plus the+/// landing reserve must still fit what is left. Buying more orchestration+/// is the expensive direction and the one that historically went wrong, so+/// it pays for both a quality margin and a worst-case budget check.+///+/// TRADE DOWN (a lower rung): needs only "not worse". #372 established this+/// asymmetry one level down for model seating — a cheaper answer that+/// matches on quality is strictly better and does not owe a margin — and it+/// lifts cleanly to rungs, where the cheaper arm ALSO reduces exhaustion+/// risk, which is a second win the mean does not price.+pub fn override(arms: []const ArmObs, key: Key, ladder: Rung, remaining: u64, landing_reserve: u64) ?Rung {+ const base = findArm(arms, key, ladder) orelse return null;+ if (base.n < min_arm_obs) return null;+ var best: ?ArmObs = null;+ for (arms) |cand| {+ if (cand.arm == ladder or !cand.key.eql(key)) continue;+ if (cand.n < min_arm_obs) continue;+ const down = cand.arm.level() < ladder.level();+ if (down) {+ if (cand.mean() + 1e-9 < base.mean()) continue;+ } else {+ if (cand.mean() < base.mean() + override_delta) continue;+ // Unlimited pools skip the affordability half — there is nothing+ // to outspend — but a finite one must fit the arm's BAD case.+ if (remaining != std.math.maxInt(u64) and cand.p90Calls() + landing_reserve > remaining) continue;+ }+ // Among qualifying arms prefer the higher mean; tie-break toward the+ // CHEAPER rung, which is the direction this redesign is biased in.+ if (best) |b| {+ const better = cand.mean() > b.mean() + 1e-9 or+ (@abs(cand.mean() - b.mean()) <= 1e-9 and cand.arm.level() < b.arm.level());+ if (!better) continue;+ }+ best = cand;+ }+ const w = best orelse return null;+ return w.arm;+}++/// Production entry point: the session's folded arms, falling back to the+/// compiled prior when the local archive has never seen this cell.+pub fn learnedRung(key: Key, ladder: Rung, remaining: u64, landing_reserve: u64) ?Rung {+ if (override(g_arms, key, ladder, remaining, landing_reserve)) |r| return r;+ var buf: [8]ArmObs = undefined;+ return override(priorFor(&buf, key), key, ladder, remaining, landing_reserve);+}++// ── reporting ──────────────────────────────────────────────────────────────++/// Score per model call — the number the whole redesign is trying to move,+/// and the one the study reported as its headline (ultracode: 80 at 3.7x the+/// calls). Zero calls reads as zero rather than as infinity.+pub fn efficiency(score: f64, api_calls: u64) f64 {+ if (api_calls == 0) return 0;+ return score / @as(f64, @floatFromInt(api_calls));+}++/// The two row shapes this policy learns from live next door (600-line cap);+/// re-exported so a caller reaches the whole policy through one import.+pub const rows = @import("orchestration_rows.zig");++test {+ _ = rows;+ _ = @import("orchestration_policy_tests.zig");+}diff --git a/src/orchestration_policy_tests.zig b/src/orchestration_policy_tests.zignew file mode 100644index 00000000..6a7d0cfd--- /dev/null+++ b/src/orchestration_policy_tests.zig@@ -0,0 +1,324 @@+//! Tests for the learned orchestration policy: row shapes, the fold and its+//! #290 firewall, and the asymmetric override rule.+//!+//! Mirrors route_policy_tests.zig deliberately — same archive, same fold+//! discipline, same "a sparse cell decides nothing" contract. Where that file+//! proves a (shape, role) cell cannot re-seat a model without evidence, this+//! one proves a (task_class, budget_band, stratum) cell cannot re-rung an+//! orchestration without it.++const std = @import("std");++const orch = @import("orchestration_policy.zig");+const rows = @import("orchestration_rows.zig");++const Rung = orch.Rung;+const Source = orch.Source;+const Key = orch.Key;++fn fold(a: std.mem.Allocator, archive: []const u8) []orch.ArmObs {+ return orch.foldArms(a, archive);+}++fn find(arms: []const orch.ArmObs, want: Rung) ?orch.ArmObs {+ for (arms) |x| if (x.arm == want) return x;+ return null;+}++fn arena() std.heap.ArenaAllocator {+ return std.heap.ArenaAllocator.init(std.testing.allocator);+}++test "BudgetBand / ScopeBucket: the buckets the key and the rows are made of" {+ try std.testing.expectEqual(orch.BudgetBand.b15, orch.BudgetBand.of(15));+ try std.testing.expectEqual(orch.BudgetBand.b40, orch.BudgetBand.of(16));+ try std.testing.expectEqual(orch.BudgetBand.b40, orch.BudgetBand.of(27)); // the study's cap-30 runs+ try std.testing.expectEqual(orch.BudgetBand.b100, orch.BudgetBand.of(41));+ try std.testing.expectEqual(orch.BudgetBand.unlimited, orch.BudgetBand.of(101));+ try std.testing.expectEqual(orch.BudgetBand.unlimited, orch.BudgetBand.of(std.math.maxInt(u64)));++ try std.testing.expectEqual(orch.ScopeBucket.s1_2, orch.ScopeBucket.of(1));+ try std.testing.expectEqual(orch.ScopeBucket.s1_2, orch.ScopeBucket.of(2));+ try std.testing.expectEqual(orch.ScopeBucket.s3_5, orch.ScopeBucket.of(3));+ try std.testing.expectEqual(orch.ScopeBucket.s6plus, orch.ScopeBucket.of(6));+}++test "foldArms: pools by (task_class, budget_band, stratum, arm) and reads the stats back" {+ var a = arena();+ defer a.deinit();+ const archive =+ \\{"kind":"orch_outcome","task_class":"bugfix","budget_band":"b40","stratum":"m1","arm":"R0","source":"bootstrap","score":1.0,"calls_used":10,"landed":true,"variant_free":true}+ \\{"kind":"orch_outcome","task_class":"bugfix","budget_band":"b40","stratum":"m1","arm":"R0","source":"bootstrap","score":0.8,"calls_used":12,"landed":true,"variant_free":true}+ \\{"kind":"orch_outcome","task_class":"bugfix","budget_band":"b40","stratum":"m1","arm":"R2","source":"bootstrap","score":0.0,"calls_used":30,"exhausted":true,"landed":false,"variant_free":true}+ \\{"kind":"route","shape":"review","role":"find","tier":"small","model":"x"}+ \\+ ;+ const arms = fold(a.allocator(), archive);+ try std.testing.expectEqual(@as(usize, 2), arms.len); // the route row is not ours++ const r0 = find(arms, .R0).?;+ try std.testing.expectEqual(@as(u32, 2), r0.n);+ try std.testing.expectApproxEqAbs(@as(f64, 0.9), r0.mean(), 1e-9);+ try std.testing.expectApproxEqAbs(@as(f64, 1.0), r0.landRate(), 1e-9);+ try std.testing.expectApproxEqAbs(@as(f64, 0.0), r0.exhaustRate(), 1e-9);++ const r2 = find(arms, .R2).?;+ try std.testing.expectEqual(@as(u32, 1), r2.n);+ try std.testing.expectApproxEqAbs(@as(f64, 1.0), r2.exhaustRate(), 1e-9);+ try std.testing.expectApproxEqAbs(@as(f64, 0.0), r2.landRate(), 1e-9);+ try std.testing.expectEqual(@as(u64, 30), r2.p90Calls());+}++test "#290 firewall: explicit rows never fold, variant-contaminated rows never fold" {+ var a = arena();+ defer a.deinit();+ const archive =+ \\{"kind":"orch_outcome","task_class":"bugfix","budget_band":"b40","stratum":"m1","arm":"R2","source":"explicit","score":1.0,"calls_used":30,"variant_free":true}+ \\{"kind":"orch_outcome","task_class":"bugfix","budget_band":"b40","stratum":"m1","arm":"R2","source":"bootstrap","score":1.0,"calls_used":30,"variant_free":false}+ \\{"kind":"orch_outcome","task_class":"bugfix","budget_band":"b40","stratum":"m1","arm":"R2","source":"bootstrap","score":0.3,"calls_used":29,"variant_free":true}+ \\+ ;+ const arms = fold(a.allocator(), archive);+ // Only the third row survives: the user-intent row would let a run the+ // policy did not choose vote on what the policy should choose, and the+ // variant row measures a prompt tournament as much as the rung.+ try std.testing.expectEqual(@as(usize, 1), arms.len);+ try std.testing.expectEqual(@as(u32, 1), arms[0].n);+ try std.testing.expectApproxEqAbs(@as(f64, 0.3), arms[0].mean(), 1e-9);+ // `variant_free` DEFAULTS to true, so a row written before the field+ // existed still folds rather than being silently dropped.+ const legacy =+ \\{"kind":"orch_outcome","task_class":"bugfix","budget_band":"b40","stratum":"m1","arm":"R0","source":"bootstrap","score":0.5,"calls_used":9}+ \\+ ;+ try std.testing.expectEqual(@as(usize, 1), fold(a.allocator(), legacy).len);+}++test "#290 firewall: folding is within a stratum, never across" {+ var a = arena();+ defer a.deinit();+ const archive =+ \\{"kind":"orch_outcome","task_class":"bugfix","budget_band":"b40","stratum":"frontier-model","arm":"R2","source":"bootstrap","score":1.0,"calls_used":20,"variant_free":true}+ \\{"kind":"orch_outcome","task_class":"bugfix","budget_band":"b40","stratum":"small-model","arm":"R2","source":"bootstrap","score":0.1,"calls_used":30,"variant_free":true}+ \\{"kind":"orch_outcome","task_class":"bugfix","budget_band":"b40","arm":"R2","source":"bootstrap","score":0.9,"calls_used":20,"variant_free":true}+ \\+ ;+ const arms = fold(a.allocator(), archive);+ // Two cells, not one averaged cell — a rung that is right for a frontier+ // root is not automatically right for a small one. The third row names no+ // stratum at all and is uncelled rather than pooled into either.+ try std.testing.expectEqual(@as(usize, 2), arms.len);+ for (arms) |x| try std.testing.expectEqual(@as(u32, 1), x.n);+}++test "foldArms: a row missing a coordinate, or carrying an out-of-range score, is skipped" {+ var a = arena();+ defer a.deinit();+ const archive =+ \\{"kind":"orch_outcome","budget_band":"b40","stratum":"m","arm":"R0","source":"bootstrap","score":1.0}+ \\{"kind":"orch_outcome","task_class":"bugfix","stratum":"m","arm":"R0","source":"bootstrap","score":1.0}+ \\{"kind":"orch_outcome","task_class":"bugfix","budget_band":"b40","stratum":"m","source":"bootstrap","score":1.0}+ \\{"kind":"orch_outcome","task_class":"bugfix","budget_band":"b40","stratum":"m","arm":"R9","source":"bootstrap","score":1.0}+ \\{"kind":"orch_outcome","task_class":"bugfix","budget_band":"b40","stratum":"m","arm":"R0","source":"bootstrap","score":88}+ \\{"kind":"orch_outcome","task_class":"bugfix","budget_band":"b40","stratum":"m","arm":"R0","source":"nonsense","score":1.0}+ \\not json at all+ \\+ ;+ // Every one of these is uncelled rather than filed under a default: a+ // mis-celled observation silently steers every future run in that cell.+ try std.testing.expectEqual(@as(usize, 0), fold(a.allocator(), archive).len);+}++fn samples(cs: []const u32) orch.ArmObs {+ var x: orch.ArmObs = .{};+ for (cs) |c| {+ x.sum_score += 1;+ x.n += 1;+ x.calls[x.n_calls] = c;+ x.n_calls += 1;+ }+ return x;+}++test "p90Calls: reports the expensive tail, not the median and not the max" {+ // Nearest-rank, ceil(0.9 * n), 1-based. Over ten samples that is the 9th+ // smallest — deliberately NOT the max, so one pathological run does not+ // veto an arm forever, and deliberately not the median, so a cheap median+ // with an expensive tail cannot sneak past the affordability gate.+ const mostly_cheap = samples(&.{ 8, 9, 9, 10, 10, 11, 11, 12, 12, 48 });+ try std.testing.expectEqual(@as(u64, 12), mostly_cheap.p90Calls());+ // An arm that is expensive in a FIFTH of its runs reads expensive, which+ // is the case the gate exists to refuse.+ const often_costly = samples(&.{ 8, 9, 9, 10, 10, 11, 11, 12, 44, 48 });+ try std.testing.expectEqual(@as(u64, 44), often_costly.p90Calls());+ // Order-independent: the fold appends in archive order, not sorted order.+ try std.testing.expectEqual(@as(u64, 44), samples(&.{ 48, 8, 44, 9, 10, 9, 11, 12, 10, 11 }).p90Calls());+ try std.testing.expectEqual(@as(u64, 7), samples(&.{7}).p90Calls());+ try std.testing.expectEqual(@as(u64, 0), (orch.ArmObs{}).p90Calls());+}++fn arm(key: Key, r: Rung, n: u32, score: f64, calls: u32) orch.ArmObs {+ var x: orch.ArmObs = .{ .key = key, .arm = r };+ var i: u32 = 0;+ while (i < n) : (i += 1) {+ x.sum_score += score;+ x.n += 1;+ x.calls[x.n_calls] = calls;+ x.n_calls += 1;+ }+ return x;+}++const k: Key = .{ .task_class = .bugfix, .budget_band = .b40, .stratum = "m1" };++test "override: a sparse cell decides nothing" {+ // Below min_arm_obs on either side, the hand ladder keeps its answer —+ // bootstrap behavior is today's behavior, and one lucky run moves nothing.+ var thin_base = [_]orch.ArmObs{ arm(k, .R2, 2, 0.1, 30), arm(k, .R0, 9, 0.9, 9) };+ try std.testing.expect(orch.override(&thin_base, k, .R2, 27, 6) == null);+ var thin_cand = [_]orch.ArmObs{ arm(k, .R2, 9, 0.1, 30), arm(k, .R0, 2, 0.9, 9) };+ try std.testing.expect(orch.override(&thin_cand, k, .R2, 27, 6) == null);+ // No evidence for the ladder's OWN answer means no basis for comparison.+ var no_base = [_]orch.ArmObs{arm(k, .R0, 9, 0.9, 9)};+ try std.testing.expect(orch.override(&no_base, k, .R2, 27, 6) == null);+}++test "override: trading DOWN needs only not-worse; escalating needs a margin AND affordability" {+ // DOWN — R0 merely matches R2's mean, and still wins: a cheaper answer at+ // equal quality is strictly better, and it also cuts exhaustion risk,+ // which the mean does not price. (#372's asymmetry, lifted to rungs.)+ var equal = [_]orch.ArmObs{ arm(k, .R2, 4, 0.9, 28), arm(k, .R0, 4, 0.9, 9) };+ try std.testing.expectEqual(Rung.R0, orch.override(&equal, k, .R2, 27, 6).?);+ // …but not when it is actually worse.+ var worse = [_]orch.ArmObs{ arm(k, .R2, 4, 0.9, 28), arm(k, .R0, 4, 0.7, 9) };+ try std.testing.expect(orch.override(&worse, k, .R2, 27, 6) == null);++ // UP — a 0.04 improvement is inside the noise band and buys nothing.+ var thin = [_]orch.ArmObs{ arm(k, .R0, 4, 0.90, 9), arm(k, .R2, 4, 0.94, 18) };+ try std.testing.expect(orch.override(&thin, k, .R0, 27, 6) == null);+ // A 0.2 improvement clears the margin, and 18 + 6 fits the 27 left.+ var strong = [_]orch.ArmObs{ arm(k, .R0, 4, 0.7, 9), arm(k, .R2, 4, 0.9, 18) };+ try std.testing.expectEqual(Rung.R2, orch.override(&strong, k, .R0, 27, 6).?);+ // Same evidence, less budget: the arm's p90 no longer fits on top of the+ // reserve, so the expensive answer is refused however good it looks.+ try std.testing.expect(orch.override(&strong, k, .R0, 20, 6) == null);+ // An unlimited pool skips the affordability half — nothing to outspend.+ try std.testing.expectEqual(Rung.R2, orch.override(&strong, k, .R0, std.math.maxInt(u64), 6).?);+}++test "override: never crosses a cell boundary" {+ const other: Key = .{ .task_class = .research, .budget_band = .b40, .stratum = "m1" };+ var mixed = [_]orch.ArmObs{ arm(k, .R2, 4, 0.2, 28), arm(other, .R0, 9, 1.0, 5) };+ // A brilliant R0 in the RESEARCH cell says nothing about the bugfix cell.+ try std.testing.expect(orch.override(&mixed, k, .R2, 27, 6) == null);+}++test "override: among qualifying arms, ties break toward the cheaper rung" {+ var tie = [_]orch.ArmObs{+ arm(k, .R3, 4, 0.5, 28),+ arm(k, .R1, 4, 0.9, 12),+ arm(k, .R0, 4, 0.9, 8),+ };+ // Both beat R3 and both are trades DOWN; the bias of this whole redesign+ // picks the cheaper one.+ try std.testing.expectEqual(Rung.R0, orch.override(&tie, k, .R3, 27, 6).?);+}++test "bootstrap prior: the study's own numbers, weak enough for real rows to outvote" {+ // A fresh install has only this. It says: at cap 30 the bugfix fleet+ // scored 0 and exhausted, and solo scored 1.0 in 10 calls.+ var buf: [8]orch.ArmObs = undefined;+ const prior = orch.priorFor(&buf, k);+ try std.testing.expect(prior.len >= 2);+ const p_r0 = find(prior, .R0).?;+ const p_r2 = find(prior, .R2).?;+ try std.testing.expectApproxEqAbs(@as(f64, 1.0), p_r0.mean(), 1e-9);+ try std.testing.expectApproxEqAbs(@as(f64, 0.0), p_r2.mean(), 1e-9);+ try std.testing.expectApproxEqAbs(@as(f64, 1.0), p_r2.exhaustRate(), 1e-9);+ try std.testing.expectApproxEqAbs(@as(f64, 0.0), p_r2.landRate(), 1e-9); // it never landed the fix+ // Every pseudo-observation sits BELOW min_arm_obs, so three real local+ // rows in a cell outvote the compiled table completely.+ for (orch.bootstrap_prior) |p| try std.testing.expect(p.n < orch.min_arm_obs);+ // And with only the prior, a ladder answer of R2 in this cell trades down.+ try std.testing.expect(orch.override(prior, k, .R2, 27, 6) == null); // n=2 < 3: sparse, decides nothing+}++test "efficiency: score per call, the number the redesign moves" {+ // The study's headline, both halves: ultracode 0.8 at 30 calls against+ // solo 1.0 at 10.+ try std.testing.expectApproxEqAbs(@as(f64, 0.1), orch.efficiency(1.0, 10), 1e-9);+ try std.testing.expectApproxEqAbs(@as(f64, 0.0), orch.efficiency(0.0, 30), 1e-9);+ // Zero calls reads as zero, never as infinity.+ try std.testing.expectApproxEqAbs(@as(f64, 0.0), orch.efficiency(1.0, 0), 1e-9);+}++test "rows: a pending decision files exactly one outcome, and carries its flags" {+ rows.clearPending();+ defer rows.clearPending();+ rows.setPending(k, .R2, .bootstrap, 4);+ const p0 = rows.pending().?;+ try std.testing.expectEqual(Rung.R2, p0.arm);+ try std.testing.expectEqual(Source.bootstrap, p0.source);+ try std.testing.expectEqualStrings("m1", p0.key().stratum);+ try std.testing.expect(p0.variant_free);+ try std.testing.expect(!p0.landed);++ // The edit-contract probe and the tournament both write onto it, and both+ // are sticky in the direction that matters.+ rows.notePendingLanded(true);+ rows.notePendingLanded(false);+ rows.notePendingVariants();+ const p1 = rows.pending().?;+ try std.testing.expect(p1.landed);+ try std.testing.expect(!p1.variant_free);++ // Flushing clears, so a second funnel reaching the same decision cannot+ // double-file it. (g_traj is null under test, so emitOutcome is a no-op —+ // what is under test here is the pairing, which is the part with state.)+ rows.flushPending(1.0, 20, 500, false, "esh");+ try std.testing.expect(rows.pending() == null);+ rows.flushPending(1.0, 20, 500, false, "esh");+ try std.testing.expect(rows.pending() == null);+}++test "rows: the pending stratum survives the arena the decision was made in" {+ rows.clearPending();+ defer rows.clearPending();+ var a = arena();+ const owned = try a.allocator().dupe(u8, "gpt-5.6-sol");+ rows.setPending(.{ .task_class = .feature, .budget_band = .b40, .stratum = owned }, .R1, .explore, 0);+ a.deinit(); // exhaustedFatal runs after everything is torn down+ try std.testing.expectEqualStrings("gpt-5.6-sol", rows.pending().?.key().stratum);+}++test "rows: a model-authored stratum cannot turn a row into a megabyte" {+ rows.clearPending();+ defer rows.clearPending();+ // Built with @splat: Zig 0.17.0-dev (what CI pins) rejects the `"m" ** N`+ // repeat form, and @splat over an array compiles on both compilers.+ const huge: [4096]u8 = @splat('m');+ rows.setPending(.{ .task_class = .other, .budget_band = .b15, .stratum = &huge }, .R0, .bootstrap, 0);+ try std.testing.expectEqual(@as(usize, rows.field_cap), rows.pending().?.key().stratum.len);+ try std.testing.expectEqual(@as(usize, rows.field_cap), rows.cappedField(&huge).len);+}++test "round trip: the arm and source spellings a row writes are the ones the fold reads" {+ // The one coupling that would fail silently: emitDecision/emitOutcome+ // write `arm.label()` and `source.label()`, foldArms parses them back with+ // Rung.parse/Source.parse. A rename on either side must break here.+ for ([_]Rung{ .R0, .R1, .R2, .R3 }) |r| {+ try std.testing.expectEqual(r, Rung.parse(r.label()).?);+ }+ for ([_]Source{ .learned, .bootstrap, .explicit, .explore }) |s| {+ try std.testing.expectEqual(s, Source.parse(s.label()).?);+ }+ try std.testing.expect(Rung.parse("R9") == null);+ try std.testing.expect(Source.parse("magic") == null);+ // Same for the key's two enum components.+ for ([_]orch.TaskClass{ .bugfix, .feature, .refactor, .review, .research, .other }) |c| {+ try std.testing.expectEqual(c, orch.TaskClass.parse(c.label()));+ }+ for ([_]orch.BudgetBand{ .b15, .b40, .b100, .unlimited }) |b| {+ try std.testing.expectEqual(b, orch.BudgetBand.parse(b.label()));+ }+}diff --git a/src/orchestration_rows.zig b/src/orchestration_rows.zignew file mode 100644index 00000000..6f6f8c9b--- /dev/null+++ b/src/orchestration_rows.zig@@ -0,0 +1,208 @@+//! The two trajectory rows the orchestration policy learns from, and the+//! parked decision that connects them.+//!+//! Split from orchestration_policy.zig (600-line cap) along the obvious seam:+//! that module owns the ARITHMETIC (fold, override, priors), this one owns the+//! WIRE — what a decision and its outcome look like on disk, and the little+//! bit of session state needed to pair them up.+//!+//! Both are additive to .graff/trajectories/*.jsonl, exactly like #372's+//! `kind:"route"` and #382's `kind:"diversity"`: NEW row shapes rather than+//! extra columns on existing ones, so an offline reader can join orchestration+//! decisions to the runs they produced without a single existing row changing+//! underneath it.++const std = @import("std");++const orch = @import("orchestration_policy.zig");+const trace = @import("trace.zig");+const util = @import("util.zig");++const Key = orch.Key;+const Rung = orch.Rung;+const Source = orch.Source;+const ScopeBucket = orch.ScopeBucket;+const BudgetBand = orch.BudgetBand;++/// Cap on free-text fields copied onto a row, matching route_trace.field_cap:+/// a model-authored label must not be able to turn one row into a megabyte.+pub const field_cap = 64;++pub fn cappedField(s: []const u8) []const u8 {+ return util.utf8Prefix(s, field_cap);+}++/// Everything a decision row says. Built by escalation.admit, which owns the+/// ladder; this module owns the row shape, orchestration_policy the fold that+/// reads it back.+pub const DecisionRow = struct {+ key: Key = .{},+ arm: Rung = .R0,+ source: Source = .bootstrap,+ remaining: u64 = 0,+ scope: ScopeBucket = .s1_2,+ files: usize = 0,+ tasks_authored: usize = 0,+ tasks_collapsed: usize = 0,+ downsized_from: usize = 0,+ /// #382's measurement, carried PRE-SPAWN. Before this the diversity gate+ /// printed to stderr and rode a manifest the root only saw afterwards —+ /// so the one moment the number could still change a decision was the one+ /// moment nothing structured could read it.+ diversity_mean: f64 = 0,+ diversity_warn: bool = false,+};++/// `remaining` as JSON: an unlimited pool is maxInt(u64), and writing that+/// literal into a row would make every offline percentile meaningless. -1 is+/// the honest spelling of "no ceiling".+fn remainingField(remaining: u64) i64 {+ if (remaining == std.math.maxInt(u64)) return -1;+ return std.math.cast(i64, remaining) orelse -1;+}++pub fn emitDecision(d: DecisionRow) void {+ const tj = trace.g_traj orelse return;+ tj.node(.{+ .kind = "orch",+ .task_class = d.key.task_class.label(),+ .budget_band = d.key.budget_band.label(),+ .stratum = cappedField(d.key.stratum),+ .arm = d.arm.label(),+ .source = d.source.label(),+ .remaining = remainingField(d.remaining),+ .scope_bucket = d.scope.label(),+ .files_named = d.files,+ .tasks_authored = d.tasks_authored,+ .tasks_collapsed = d.tasks_collapsed,+ .downsized_from = d.downsized_from,+ .diversity_mean = d.diversity_mean,+ .diversity_warn = d.diversity_warn,+ .t = tj.elapsedMs(),+ });+}++pub const OutcomeRow = struct {+ key: Key = .{},+ arm: Rung = .R0,+ source: Source = .bootstrap,+ /// [0,1], the #168 contract.+ score: f64 = 0,+ calls_used: u64 = 0,+ wall_ms: i64 = 0,+ exhausted: bool = false,+ /// The edit-contract probe's verdict: did anything actually change on disk?+ landed: bool = false,+ /// False when scoreVariants mutated a genome during the run — see the+ /// #290 firewall at the top of orchestration_policy.zig.+ variant_free: bool = true,+ eval_set_hash: []const u8 = "",+};++pub fn emitOutcome(o: OutcomeRow) void {+ const tj = trace.g_traj orelse return;+ tj.node(.{+ .kind = "orch_outcome",+ .task_class = o.key.task_class.label(),+ .budget_band = o.key.budget_band.label(),+ .stratum = cappedField(o.key.stratum),+ .arm = o.arm.label(),+ .source = o.source.label(),+ .score = o.score,+ .calls_used = o.calls_used,+ .wall_ms = o.wall_ms,+ .exhausted = o.exhausted,+ .landed = o.landed,+ .variant_free = o.variant_free,+ .eval_set_hash = cappedField(o.eval_set_hash),+ .efficiency = orch.efficiency(o.score, o.calls_used),+ .t = tj.elapsedMs(),+ });+}++// ── the pending decision ───────────────────────────────────────────────────+// A decision is made at admission and only PAID FOR much later — when a score+// lands, or when the pool runs dry. Nothing in between carries the key, so it+// is parked here.+//+// A fixed stratum buffer rather than a borrowed slice, for the same reason+// shapes.rawAsk() uses one: the decision is made inside a per-turn arena and+// read from `exhaustedFatal`, which runs after everything has been torn down.++var g_pending_stratum: [field_cap]u8 = undefined;+var g_pending: ?Pending = null;++pub const Pending = struct {+ task_class: orch.TaskClass,+ budget_band: BudgetBand,+ stratum_len: usize,+ arm: Rung,+ source: Source,+ calls_at_start: u64,+ variant_free: bool = true,+ landed: bool = false,++ pub fn key(self: Pending) Key {+ return .{+ .task_class = self.task_class,+ .budget_band = self.budget_band,+ .stratum = g_pending_stratum[0..self.stratum_len],+ };+ }+};++pub fn setPending(k: Key, arm: Rung, source: Source, calls_at_start: u64) void {+ const s = cappedField(k.stratum);+ const n = @min(s.len, g_pending_stratum.len);+ @memcpy(g_pending_stratum[0..n], s[0..n]);+ g_pending = .{+ .task_class = k.task_class,+ .budget_band = k.budget_band,+ .stratum_len = n,+ .arm = arm,+ .source = source,+ .calls_at_start = calls_at_start,+ };+}++pub fn pending() ?Pending {+ return g_pending;+}++pub fn clearPending() void {+ g_pending = null;+}++/// The edit-contract probe's verdict, folded into whatever outcome row this+/// decision eventually files. Sticky in the TRUE direction: one phase that+/// really changed files is enough to call the run landed.+pub fn notePendingLanded(landed: bool) void {+ if (g_pending) |*p| p.landed = p.landed or landed;+}++/// A judge tournament ran, so this run's score is no longer attributable to+/// the ARM alone (#290 firewall). Sticky: once contaminated, always.+pub fn notePendingVariants() void {+ if (g_pending) |*p| p.variant_free = false;+}++/// File the outcome for the parked decision and clear it, so one decision+/// files exactly one outcome however many funnels reach this function.+/// `used` is the run budget's current call count; the delta from admission is+/// what this decision actually cost.+pub fn flushPending(score: f64, used: u64, wall_ms: i64, exhausted: bool, eval_set_hash: []const u8) void {+ const p = g_pending orelse return;+ g_pending = null;+ emitOutcome(.{+ .key = p.key(),+ .arm = p.arm,+ .source = p.source,+ .score = score,+ .calls_used = used -| p.calls_at_start,+ .wall_ms = wall_ms,+ .exhausted = exhausted,+ .landed = p.landed,+ .variant_free = p.variant_free,+ .eval_set_hash = eval_set_hash,+ });+}diff --git a/src/phase_budget.zig b/src/phase_budget.zignew file mode 100644index 00000000..96d6b4ee--- /dev/null+++ b/src/phase_budget.zig@@ -0,0 +1,316 @@+//! Per-phase budget scaling: a RESERVATION ledger over the shared RunBudget+//! pool.+//!+//! graff already had accounting — `RunBudget` counts every model call the+//! root, the workers, the retries and the judges take from one atomic+//! ceiling, and `remaining()`/`canAfford()` report it honestly. What it did+//! not have was RESERVATION: nobody ever asked "if I spend this phase, will+//! there still be enough left to land the work?", so a fan-out could spend+//! the pool down to zero on evidence-gathering and die at call 30 with the+//! file it was asked to fix untouched. That is not a hypothetical: it is run+//! 01-bugfix-B of the eval study this module was written for — 30 calls,+//! five workers, three judges, one retry, zero edits.+//!+//! The fix is the one codex converged on for the same problem: one pool,+//! drawn down by everyone, with a reserve carved out UP FRONT for the step+//! that actually produces the artifact. Three gates use it:+//!+//! P1 admission the whole plan plus the landing reserve must fit+//! `remaining()` before anything spawns (escalation.zig).+//! P2 per-phase at each phase head, if what is left cannot cover the+//! remaining phases plus the reserve, stop early and hand+//! back partial evidence with a budget-truncated manifest.+//! A synthesis from three of five finders is worth much+//! more than a process kill after the fourth.+//! P3 optional judges and other nice-to-haves run only when they fit+//! ON TOP of the reserve (subagent.scoreVariants).+//!+//! Everything here is PURE arithmetic over cheap observables — no model call,+//! no I/O — so the whole ladder is unit-testable without a network.++const std = @import("std");+const Value = std.json.Value;++const route_policy = @import("route_policy.zig");+const shapes = @import("shapes.zig");++pub const Shape = route_policy.Shape;++// ── the cost table ─────────────────────────────────────────────────────────+// Calls one worker in a role actually spends, measured off the B-run traces+// of the eval study rather than assumed. A worker's cost is dominated by how+// many tool round-trips its job needs before it can write a report: a finder+// reads and greps (4), a skeptic re-checks one claim (3), a synthesizer reads+// {{prev}} and writes (2), a judge reads handed text and emits one score (1,+// once the judge toolset is emptied), and an implementer reads, edits,+// re-reads and self-checks (6 — the most expensive role, and the one the+// landing reserve exists to protect).++pub const cost_find: u64 = 4;+pub const cost_verify: u64 = 3;+pub const cost_synthesize: u64 = 2;+pub const cost_judge: u64 = 1;+pub const cost_implement: u64 = 6;+/// An off-vocabulary phase title still costs something; charge it the median+/// rather than zero, or an uncelled plan would estimate as free.+pub const cost_default: u64 = 3;++/// What one worker in `role` (a canonical slot from shapes.zig, or "") costs.+pub fn roleCost(role: []const u8) u64 {+ const eql = std.mem.eql;+ if (eql(u8, role, "find") or eql(u8, role, "sweep")) return cost_find;+ if (eql(u8, role, "verify")) return cost_verify;+ if (eql(u8, role, "synthesize")) return cost_synthesize;+ if (eql(u8, role, "judge")) return cost_judge;+ if (eql(u8, role, "implement") or eql(u8, role, "build") or eql(u8, role, "variants")) return cost_implement;+ if (eql(u8, role, "scope") or eql(u8, role, "review")) return cost_verify;+ return cost_default;+}++/// Calls a phase of `n_tasks` workers in `role` costs.+pub fn phaseCost(role: []const u8, n_tasks: usize) u64 {+ return roleCost(role) * @as(u64, @intCast(n_tasks));+}++// ── the landing reserve ────────────────────────────────────────────────────++/// Never reserve less than this, however small the cap: below ~6 calls the+/// root cannot read a result, make an edit and verify it, which is the whole+/// point of reserving anything.+pub const min_landing_reserve: u64 = 6;++/// Calls held back so the ROOT can still land the work after the fleet+/// reports. A fifth of the cap tracks the observed shape of these runs: the+/// study's solo baselines finished five ordinary tasks in 5-10 calls each,+/// so a cap of 30 wants ~6 held back and a cap of 100 wants ~20. An+/// unlimited pool (cap 0) still reserves the floor, so the arithmetic below+/// has one meaning everywhere.+pub fn landingReserve(cap: u64) u64 {+ return @max(min_landing_reserve, cap / 5);+}++/// The cheapest honest instantiation of a catalog shape — what a fleet costs+/// at all, before any scaling to the ask. `admit` compares this (plus the+/// reserve) against `remaining()`: below it a fleet cannot finish, so the+/// answer is solo work rather than a fan-out that dies halfway.+pub fn fleetFloor(shape: Shape) u64 {+ return switch (shape) {+ // 3 finders + 1 skeptic + 1 synthesis+ .review => 3 * cost_find + cost_verify + cost_synthesize,+ // 3 sweepers + 1 map+ .research => 3 * cost_find + cost_synthesize,+ // 2 competing implementers + 1 build from the winner+ .design => 3 * cost_implement,+ // scope + implement + review+ .feature => cost_verify + cost_implement + cost_verify,+ // the smallest pipeline that is a pipeline: 2 items x 2 stages+ .migration => 4 * cost_default,+ .adhoc => 3 * cost_default,+ };+}++// ── plan estimates over the authored workflow ──────────────────────────────++/// This phase's canonical slot, "" when the title is off-vocabulary.+fn phaseRole(pv: Value) []const u8 {+ return route_policy.phaseSlot(pv);+}++fn phaseTaskCount(pv: Value) usize {+ if (pv != .object) return 0;+ const tv = pv.object.get("tasks") orelse return 0;+ return if (tv == .array) tv.array.items.len else 0;+}++/// What the workflow the root model just authored will cost, as authored.+pub fn planEstimate(phases: []const Value) u64 {+ var total: u64 = 0;+ for (phases) |pv| total += phaseCost(phaseRole(pv), phaseTaskCount(pv));+ return total;+}++/// The MINIMUM the phases from `from` onward can cost — one worker each,+/// however many the plan authored. This is what P2 tests against: a phase+/// loop should stop when it cannot afford even the skinniest completion of+/// what is left, not when it cannot afford the plan as written (which would+/// early-exit runs that were about to succeed).+pub fn laterPhasesMin(phases: []const Value, from: usize) u64 {+ var total: u64 = 0;+ var i = from;+ while (i < phases.len) : (i += 1) {+ if (phaseTaskCount(phases[i]) == 0) continue;+ total += roleCost(phaseRole(phases[i]));+ }+ return total;+}++/// Phases whose canonical slot is contracted to MUTATE files. Trimming one of+/// these to pay for evidence-gathering is the exact inversion the study+/// documented, so a downsize must never touch them.+pub fn isLandingRole(role: []const u8) bool {+ const eql = std.mem.eql;+ return eql(u8, role, "implement") or eql(u8, role, "build") or eql(u8, role, "repair");+}++// ── the ledger ─────────────────────────────────────────────────────────────++/// A reservation view over one run's shared pool. Holds no pointer to the+/// RunBudget: callers pass `remaining()` in at each decision, because the+/// real pool is atomic and shared with concurrent children, so a cached copy+/// would be a lie the moment a sibling spawned.+pub const Ledger = struct {+ /// The run's `--max-model-calls`; 0 means unlimited.+ cap: u64,+ /// Calls held back for the root to land the work.+ reserve: u64,+ /// Calls this run's phases have already been charged for by `commit`.+ committed: u64 = 0,++ pub fn init(cap: u64) Ledger {+ return .{ .cap = cap, .reserve = landingReserve(cap) };+ }++ /// An unlimited pool cannot exhaust, so every gate below passes; keeping+ /// that in ONE predicate is what stops the arithmetic from accidentally+ /// treating maxInt(u64) as a number.+ pub fn unlimited(self: Ledger) bool {+ return self.cap == 0;+ }++ /// Calls available for fan-out RIGHT NOW: what is left, minus the reserve.+ pub fn spendable(self: Ledger, remaining: u64) u64 {+ if (self.unlimited()) return std.math.maxInt(u64);+ return remaining -| self.reserve;+ }++ /// Does `cost` fit on top of the landing reserve?+ pub fn fits(self: Ledger, remaining: u64, cost: u64) bool {+ return self.spendable(remaining) >= cost;+ }++ /// P2: should the phase loop stop before running the phase at `from`?+ /// True when what is left cannot cover the skinniest completion of the+ /// remaining phases PLUS the reserve — at which point continuing spends+ /// the reserve on more evidence and lands nothing.+ pub fn earlyExit(self: Ledger, remaining: u64, later_min: u64) bool {+ if (self.unlimited()) return false;+ return remaining < later_min + self.reserve;+ }++ pub fn commit(self: *Ledger, cost: u64) void {+ self.committed += cost;+ }+};++// ── reading the shared pool ────────────────────────────────────────────────+// Taken as `anytype` so this module never imports run_budget.zig, which sits+// under tools.zig on the import graph — and a null budget (tests, the REPL+// before startup) reads as "unlimited", the same answer RunBudget itself+// gives for max_model_calls == 0.++pub fn capOf(rb: anytype) u64 {+ return if (rb) |b| b.max_model_calls else 0;+}++pub fn remainingOf(rb: anytype) u64 {+ return if (rb) |b| b.remaining() else std.math.maxInt(u64);+}++pub fn usedOf(rb: anytype) u64 {+ return if (rb) |b| b.used() else 0;+}++/// The manifest line a budget-truncated run carries. The root reads the+/// manifest (workflow_progress.buildManifest) — so this is where it learns+/// that its evidence is partial BY DESIGN and it should land what it has,+/// rather than having to infer that from silence.+pub const truncated_note = "budget-truncated: stopped before the remaining phase(s) to keep enough calls to land the work — synthesize from the partial evidence above and make the edits yourself";++test "roleCost: the measured table, and an off-vocabulary role is not free" {+ try std.testing.expectEqual(@as(u64, 4), roleCost("find"));+ try std.testing.expectEqual(@as(u64, 4), roleCost("sweep"));+ try std.testing.expectEqual(@as(u64, 3), roleCost("verify"));+ try std.testing.expectEqual(@as(u64, 2), roleCost("synthesize"));+ try std.testing.expectEqual(@as(u64, 1), roleCost("judge"));+ try std.testing.expectEqual(@as(u64, 6), roleCost("implement"));+ try std.testing.expectEqual(@as(u64, 6), roleCost("build"));+ try std.testing.expectEqual(cost_default, roleCost(""));+ try std.testing.expectEqual(cost_default, roleCost("ponder"));+}++test "landingReserve: a floor below cap 30, a fifth above it" {+ try std.testing.expectEqual(@as(u64, 6), landingReserve(0)); // unlimited still has a floor+ try std.testing.expectEqual(@as(u64, 6), landingReserve(12));+ try std.testing.expectEqual(@as(u64, 6), landingReserve(30));+ try std.testing.expectEqual(@as(u64, 8), landingReserve(40));+ try std.testing.expectEqual(@as(u64, 20), landingReserve(100));+}++test "fleetFloor: every shape costs more than the reserve it must clear" {+ for ([_]Shape{ .review, .research, .design, .feature, .migration, .adhoc }) |s| {+ try std.testing.expect(fleetFloor(s) >= min_landing_reserve);+ }+ // The study's cap-30 bugfix: a review fleet (17) plus the reserve (6) is+ // 23 of the ~27 calls left after the root has read the task — affordable+ // on paper, which is exactly why SCOPE, not budget alone, has to gate it.+ try std.testing.expectEqual(@as(u64, 17), fleetFloor(.review));+ try std.testing.expectEqual(@as(u64, 14), fleetFloor(.research));+ try std.testing.expectEqual(@as(u64, 12), fleetFloor(.feature));+}++test "Ledger: spendable, fits and earlyExit all sit ON TOP of the reserve" {+ var l = Ledger.init(30);+ try std.testing.expectEqual(@as(u64, 6), l.reserve);+ try std.testing.expectEqual(@as(u64, 21), l.spendable(27));+ try std.testing.expect(l.fits(27, 21));+ try std.testing.expect(!l.fits(27, 22)); // one call into the reserve is one too many+ // Saturating, never wrapping: below the reserve there is simply nothing+ // to spend, and no gate may read that as "a very large budget".+ try std.testing.expectEqual(@as(u64, 0), l.spendable(4));+ try std.testing.expect(!l.fits(4, 1));+ // P2: 10 left, 6 reserved, the rest of the plan needs at least 5 → stop.+ try std.testing.expect(l.earlyExit(10, 5));+ try std.testing.expect(!l.earlyExit(12, 5));+ l.commit(12);+ try std.testing.expectEqual(@as(u64, 12), l.committed);+}++test "Ledger: an unlimited pool never gates" {+ const l = Ledger.init(0);+ try std.testing.expect(l.unlimited());+ try std.testing.expect(l.fits(std.math.maxInt(u64), 1_000_000));+ try std.testing.expect(!l.earlyExit(0, 1_000_000));+}++test "planEstimate / laterPhasesMin read the authored plan, not a guess" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const src =+ \\[{"title":"find the defect","tasks":[1,2,3]},+ \\ {"title":"implement the fix","tasks":[1]},+ \\ {"title":"verify the diff","tasks":[1]}]+ ;+ const v = try std.json.parseFromSliceLeaky(Value, a, src, .{});+ const phases = v.array.items;+ // 3 finders (12) + 1 implementer (6) + 1 skeptic (3)+ try std.testing.expectEqual(@as(u64, 21), planEstimate(phases));+ // From phase 2 onward, one worker each: implement (6) + verify (3).+ try std.testing.expectEqual(@as(u64, 9), laterPhasesMin(phases, 1));+ try std.testing.expectEqual(@as(u64, 3), laterPhasesMin(phases, 2));+ try std.testing.expectEqual(@as(u64, 0), laterPhasesMin(phases, 3));+}++test "isLandingRole names exactly the phases a downsize may never trim" {+ try std.testing.expect(isLandingRole("implement"));+ try std.testing.expect(isLandingRole("build"));+ try std.testing.expect(isLandingRole("repair"));+ try std.testing.expect(!isLandingRole("find"));+ try std.testing.expect(!isLandingRole("verify"));+ try std.testing.expect(!isLandingRole("judge"));+ // The landing roles the catalog can actually produce are canonical slots,+ // so a plan cannot dodge the protection by titling its edit phase+ // naturally — canonicalSlot still resolves it to the protected word.+ try std.testing.expectEqualStrings("implement", shapes.canonicalSlot("implement the fix"));+ try std.testing.expectEqualStrings("build", shapes.canonicalSlot("build from the winner"));+}diff --git a/src/route_phase_tests.zig b/src/route_phase_tests.zigindex c624042a..28c6c4d5 100644--- a/src/route_phase_tests.zig+++ b/src/route_phase_tests.zig@@ -260,7 +260,9 @@ test "#376 firewall: the seat is resolved ONCE per phase, outside the task loop"// may swap the phase's model but still yields ONE seat for the whole// phase — the property this test exists to protect.const seat_at = std.mem.indexOf(u8, src, "const seat = vision_ask.phaseSeat(route_phase.forPhase(").?;- const loop_at = std.mem.indexOf(u8, src, "for (labels, prompts, overrides, niches, isolations, isolation_fallbacks, futures, 1..)").?;+ // (The loop indexes from 0 rather than 1 since the §2b collapse gate needs+ // the task INDEX to look up its survivor, not a 1-based display number.)+ const loop_at = std.mem.indexOf(u8, src, "for (labels, prompts, overrides, niches, isolations, isolation_fallbacks, futures, 0..)").?;try std.testing.expect(seat_at < loop_at); // resolved before the fan-out// Every spawn in the phase — first attempt and retry alike — receives that// one value verbatim; nothing per task is ever passed as a model pin.diff --git a/src/run_budget.zig b/src/run_budget.zigindex 4a48df79..c6a4fbc2 100644--- a/src/run_budget.zig+++ b/src/run_budget.zig@@ -11,6 +11,9 @@const std = @import("std");const Io = std.Io;+// Only for the mandatory outcome-row flush in exhaustedFatal below — a leaf+// module over shapes/trace/util, so this adds no cycle to the budget path.+const orch_rows = @import("orchestration_rows.zig");pub const default_max_concurrency: u32 = 8;pub const default_max_depth: u8 = 1;@@ -102,7 +105,15 @@ pub const RunBudget = struct {/// failed:" line. The model never gets a concluding call at this point,/// so the HARNESS owns the last line: what ran out, that the work is/// partial and not rolled back, and where the evidence lives.+ ///+ /// It also owns the last ROW. An orchestration decision that ends here is+ /// the single most informative observation the policy can have — the+ /// escalation ladder bought a rung that could not finish — and before this+ /// flush it was the one outcome that never got recorded, because the+ /// process died between the decision and any score. The policy learned+ /// from every run except exactly the failures it exists to prevent.pub fn exhaustedFatal(max_model_calls: u64, run_id: []const u8) noreturn {+ orch_rows.flushPending(0, max_model_calls, 0, true, "");std.process.fatal("model-call budget exhausted (--max-model-calls {d}) before the task completed. Work done so far is PARTIAL and was NOT rolled back; inspect this run under .graff/traces/{s}.jsonl, then raise --max-model-calls or re-run to continue.", .{ max_model_calls, run_id });}diff --git a/src/shapes.zig b/src/shapes.zigindex d75024db..a0089b42 100644--- a/src/shapes.zig+++ b/src/shapes.zig@@ -115,6 +115,9 @@ pub const shape_catalog_note =\\ find one reviewer per dimension (correctness, security, perf, tests), parallel\\ verify one skeptic per finding, told to REFUTE it; gate with when:"FINDING"\\ synthesize one task; findings ranked most-severe first+ \\A-fix repair — the ask is "fix this bug", NOT "review this":+ \\ find → implement (EDITS files, lists every changed path) → verify (reads+ \\ the DIFF, when:"PATCH"). Never shape A: reviewers report, they don't fix.\\B research/understand — the ask is a question about how something works:\\ sweep researchers each searching a DIFFERENT way (by symbol, by callers,\\ by git history, by tests); tell them not to duplicate each other@@ -140,10 +143,10 @@ pub const shape_catalog_note =\\ hue/particle/font pairing is ONE concept, not N. Leave every\\ variant unmerged until the user picks.\\- \\Scale to the ask: "find bugs" is 3 finders + 1 verify; "thoroughly audit" is- \\6 finders + 3-vote adversarial verify + synthesize. Use phases only when a- \\phase genuinely needs ALL of the previous one; per-item work belongs in- \\pipeline.+ \\Scale to the ask: "fix this bug" is 1 finder + 1 implementer + 1 verify;+ \\"thoroughly audit" keeps 6 finders + 3-vote adversarial verify + synthesize.+ \\Use phases only when a phase genuinely needs ALL of the previous one;+ \\per-item work belongs in pipeline.\\\\isolation:"worktree" ONLY for tasks that edit files IN PARALLEL within one\\phase and whose edits nothing downstream has to read. Every task gets its@@ -280,20 +283,118 @@ test "shape catalog never tells a dependent chain to isolate into worktrees" {try std.testing.expect(std.mem.indexOf(u8, shape_catalog_note, "Give file-editing tasks isolation") == null);}+// ── what KIND of ask this is ───────────────────────────────────────────────+// The escalation ladder (escalation.zig) and the learned orchestration policy+// (orchestration_policy.zig) both partition on the class of the ask. The+// lexical mapping already existed implicitly — the catalog above tells the+// model "the ask is review/audit/find bugs" — it was just never exposed as a+// value anything could key on. `classOf` is that exposure, and nothing more:+// a closed enum over the same words, so a policy cell means the same thing in+// two runs a week apart.++pub const TaskClass = enum {+ bugfix,+ feature,+ refactor,+ review,+ research,+ other,++ pub fn label(self: TaskClass) []const u8 {+ return @tagName(self);+ }++ pub fn parse(s: []const u8) TaskClass {+ return std.meta.stringToEnum(TaskClass, s) orelse .other;+ }+};++fn anyOfCI(hay: []const u8, needles: []const []const u8) bool {+ for (needles) |n| if (util.indexOfIgnoreCase(hay, n) != null) return true;+ return false;+}++/// The class of a raw user ask. Order is precedence, most specific first:+/// "fix the bug the review found" is a BUGFIX (there is a defect to repair),+/// not a review, and mapping it to review is precisely the study's worst+/// failure — a repair ask that instantiated shape A, spawned reviewers, and+/// changed no files. Unrecognized asks are `other` rather than a guess: an+/// uncelled observation is honest, a mis-celled one poisons a policy cell.+pub fn classOf(raw: []const u8) TaskClass {+ // "broken" is qualified rather than bare: an ordinary feature spec says+ // "ties broken by ascending order", and the bare word classified the eval+ // study's wordfreq FEATURE task as a bugfix — a mis-celled observation,+ // which is exactly what this function's doc comment forbids.+ if (anyOfCI(raw, &.{ "fix ", "bug", "is broken", "are broken", "broken test", "broken build", "failing", "fails", "regression", "crash", "repair", "make the tests pass", "doesn't work", "does not work" })) return .bugfix;+ if (anyOfCI(raw, &.{ "refactor", "rename", "extract ", "restructure", "deduplicate", "dedupe", "move the", "port the", "migrate" })) return .refactor;+ if (anyOfCI(raw, &.{ "review", "audit", "critique", "find bugs", "security review", "code smell" })) return .review;+ if (anyOfCI(raw, &.{ "how does", "how do ", "why does", "explain", "investigate", "research", "summarize", "summarise", "summary", "understand", "what is the", "which ", "map the", "trace how", "answering", "these questions", "four questions", "cite the" })) return .research;+ if (anyOfCI(raw, &.{ "add ", "implement", "build ", "create ", "write ", "support for", "new feature", "feature" })) return .feature;+ return .other;+}++/// Audit-CLASS language: the ask itself says it wants breadth, so breadth is+/// what the user is paying for (the R3 rung). Deliberately narrow — a fleet+/// is the most expensive thing this harness can do, so it takes an explicit+/// word, never an inference from a long prompt.+pub fn isAuditClass(raw: []const u8) bool {+ return anyOfCI(raw, &.{ "thorough", "exhaustive", "comprehensive", "audit", "every file", "all files", "across the codebase", "across the repo", "systematically", "full sweep", "end-to-end review" });+}++/// The user's raw ask for THIS turn, captured where the harness already reads+/// it (applyUltracodeSteering, the one function both the REPL and the -p path+/// funnel through). The workflow tool runs deep inside a turn with no line+/// back to what was typed, and both call sites sit at the 600-line cap, so a+/// capture here costs those files nothing.+///+/// A fixed buffer rather than a slice: the callers hand an ARENA-scoped+/// string, and holding a pointer into a per-turn arena across the turn that+/// frees it is exactly the class of bug this module should not introduce.+var g_raw_ask_buf: [1024]u8 = undefined;+var g_raw_ask_len: usize = 0;++pub fn noteRawAsk(raw: []const u8) void {+ const n = @min(raw.len, g_raw_ask_buf.len);+ @memcpy(g_raw_ask_buf[0..n], raw[0..n]);+ g_raw_ask_len = n;+}++pub fn rawAsk() []const u8 {+ return g_raw_ask_buf[0..g_raw_ask_len];+}+pub const UltracodeMessage = struct {text: []const u8,explicit: bool,};+// The mandate. It used to read "Use the workflow even if you could do the+// work solo", and a 16-run eval study measured exactly what that buys: on+// five ordinary coding tasks ultracode scored 80 where the same model solo+// scored 100, at 3.7x the model calls — including a bugfix run that+// orchestrated 30 calls, hit the budget ceiling and never edited the file.+//+// So the codeword no longer means "fan out". It means "escalate to the+// smallest rung that fits", and the rungs are stated as CONCRETE+// substitution gates rather than as judgment (opencode's anti-overuse+// doctrine: a rule the model can check against the ask, not a virtue it has+// to feel). Delegation is opt-in policy and stays decline-able even with the+// codeword present (codex's doctrine) — escalation.admit() enforces the same+// ladder in the harness, so this text and the gate agree.const ultracode_explicit_head =\\[harness note: the user invoked the "ultracode" codeword, opting- \\this turn into multi-agent orchestration. Fulfill the request with- \\the workflow tool.+ \\this turn into multi-agent orchestration. The workflow tool is+ \\available for it — available, not mandatory.\\Tell code-exploration subagents to go through the repo with the\\codedb tool (search / symbol / callers / outline / context) before\\reaching for bash grep — it is indexed and structural.- \\Use the workflow even if you could do the work solo; skip it only- \\if the message needs a purely conversational reply.+ \\Escalate to the smallest rung that fits: work solo for a task scoped+ \\to 1-2 known files; spawn ONE scout when exploration would flood your+ \\own context; spawn a fleet only for 3+ genuinely independent+ \\workstreams, or after a solo attempt failed verification.+ \\Substitution gates — a specific file path → Read it; a named symbol →+ \\Grep it; 2-3 known files → read them yourself, no fleet. A fleet that+ \\re-derives what one Read would have told you is pure overhead.;// The explicit-codeword note carries the shape catalog (#293): a one-shot@@ -305,12 +406,15 @@ const ultracode_explicit_note = ultracode_explicit_head ++ "\n\n" ++ shape_catal// on, landing in compaction input every turn. setSystemPrompts() composes// it into sys_ultra/sys_ultra_strict once; this note just points at it.const ultracode_persistent_note =- \\[harness note: ultracode mode is enabled for this session. Use the- \\workflow tool for coding tasks — your system prompt already has the- \\shape catalog; instantiate one of those shapes rather than freeforming- \\a structure. Tell code-exploration subagents to go through the repo- \\with the codedb tool (search / symbol / callers / outline / context)- \\before reaching for bash grep — it is indexed and structural.]+ \\[harness note: ultracode mode is enabled for this session. When a task+ \\is big enough to need the workflow tool — 3+ genuinely independent+ \\workstreams, or a solo attempt that failed verification — your system+ \\prompt already has the shape catalog; instantiate one of those shapes+ \\rather than freeforming a structure. Below that bar, do the work+ \\yourself: 1-2 known files is solo work. Tell code-exploration+ \\subagents to go through the repo with the codedb tool (search /+ \\symbol / callers / outline / context) before reaching for bash grep —+ \\it is indexed and structural.];/// `raw` is what the user actually typed this turn; `msg` is the assembled@@ -321,6 +425,11 @@ const ultracode_persistent_note =/// every turn after /clear bannered as explicit even though the user never/// typed the word (#178).pub fn applyUltracodeSteering(arena: Allocator, msg: []const u8, raw: []const u8, persistent_enabled: bool) !UltracodeMessage {+ // Unconditional, and on `raw` for the same reason the codeword scan is:+ // the escalation gate classifies what the USER asked for, and a harness+ // note replaying a prior goal is not that (#178). Also runs when the+ // codeword is absent — the workflow tool is reachable without it.+ noteRawAsk(raw);const explicit = util.indexOfIgnoreCase(raw, "ultracode") != null;if (explicit) {return .{ .text = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ msg, ultracode_explicit_note }), .explicit = true };diff --git a/src/subagent.zig b/src/subagent.zigindex dcce1145..e2064802 100644--- a/src/subagent.zig+++ b/src/subagent.zig@@ -40,6 +40,8 @@ const cards = @import("cards.zig");const trace = @import("trace.zig");const messages_mod = @import("messages.zig");const textMessage = messages_mod.textMessage;+const brief_diversity = @import("brief_diversity.zig"); // genomeSha: the distinct-genome tournament gate+const orch_rows = @import("orchestration_rows.zig"); // #290: a scored tournament is not variant-free/// Spawn a one-level-deep subagent: fresh arena, fresh history, same shared/// http client and provider. Runs entirely on this pool thread; its own tool@@ -280,7 +282,8 @@ fn spawnSubBackground(ctx: ToolCtx, label: []const u8, prompt: []const u8, sys_o/// completion event" shape (#276 P0-3 design point 3) — running / completed/// / failed, plus the usage summary, plus the full result once done./// Factored out of agentOutput so it's unit-testable without a real Io.-fn agentStatusText(gpa: Allocator, id: u32, done: bool, is_error: bool, usage: AgentUsage, result: []const u8) ![]u8 {+/// pub only so subagent_tests.zig can reach it (this file is at the cap).+pub fn agentStatusText(gpa: Allocator, id: u32, done: bool, is_error: bool, usage: AgentUsage, result: []const u8) ![]u8 {if (!done) return std.fmt.allocPrint(gpa, "[agent {d}: running]", .{id});return std.fmt.allocPrint(gpa,@@ -391,36 +394,6 @@ test "admitOneLocked: admits up to the cap, queues the rest, FIFO order (#276 P0try std.testing.expectEqual(@as(u32, max_concurrent_background_agents + 1), next.id);}-test "agentStatusText: running/completed/failed shapes carry the usage summary, and a failure is never silent (#276 P0-3)" {- const gpa = std.testing.allocator;-- const running = try agentStatusText(gpa, 7, false, false, .{}, "");- defer gpa.free(running);- try std.testing.expectEqualStrings("[agent 7: running]", running);-- const ok = try agentStatusText(gpa, 7, true, false, .{ .duration_ms = 1200, .tool_calls = 3, .context_tokens = 4500, .cache_read_tokens = 100 }, "final report");- defer gpa.free(ok);- try std.testing.expect(std.mem.indexOf(u8, ok, "completed") != null);- try std.testing.expect(std.mem.indexOf(u8, ok, "1200ms") != null);- 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 = try 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 silent- try std.testing.expect(std.mem.indexOf(u8, failed, failed_text) != null); // the child's own diagnostic rides along verbatim-}--test "agentStatusText: composes with isolation:\"worktree\" — a kept-worktree note in the result survives verbatim (#276 P0-3 design point 5)" {- const gpa = std.testing.allocator;- const result_with_worktree = "final report text\n\n[worktree kept (has changes) — path: .graff/worktrees/agent-sa-001-aa11, branch: graff/agents/sa-001-aa11]";- const out = try agentStatusText(gpa, 3, true, false, .{ .duration_ms = 500 }, result_with_worktree);- defer gpa.free(out);- try std.testing.expect(std.mem.indexOf(u8, out, "[worktree kept (has changes) — path:") != null);- try std.testing.expect(std.mem.indexOf(u8, out, "branch: graff/agents/sa-001-aa11") != null);-}-/// One task inside a workflow phase; never throws, suitable for io.async./// `niche` is the task's MAP-Elites cell, threaded through so runSub's/// fleet:propose — and scoreVariants' submit — tag the variant's genome.@@ -503,7 +476,12 @@ pub fn scoreVariants(// telemetry OFF too, so a private session still accrues policy evidence.if (telemetry.g_telem == null and trace.g_traj == null) return;- // Variant tasks that produced a usable result; a tournament needs ≥2.+ // Variant tasks that produced a usable result; a tournament needs ≥2 with+ // DISTINCT genomes. Counting `override != null` counted PRESENCE, and a+ // phase where every worker carries the same resolved system_prompt is one+ // genome run N times — nothing to rank. The study paid for that twice: two+ // single-genome phases each spawned three judges to score a tournament+ // that had exactly one entrant, on a run that then died at the cap.var vidx: [max_workflow_tasks]usize = undefined;var vn: usize = 0;for (overrides, outputs, 0..) |o, out, i| {@@ -513,6 +491,17 @@ pub fn scoreVariants(}}if (vn < 2) return;+ var distinct = false;+ for (1..vn) |k| if (brief_diversity.genomeSha(overrides[vidx[k]].?) != brief_diversity.genomeSha(overrides[vidx[0]].?)) {+ distinct = true;+ };+ if (!distinct) {+ if (ctx.tracer) |tr| tr.note("fleet", "tournament skipped: one genome, no axis to rank");+ return;+ }+ // Any score filed below attributes to the PROMPT, not to the orchestration+ // rung, so this run's orch_outcome row is no longer variant-free (#290).+ orch_rows.notePendingVariants();// 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 underdiff --git a/src/subagent_run.zig b/src/subagent_run.zigindex 44427788..c649359c 100644--- a/src/subagent_run.zig+++ b/src/subagent_run.zig@@ -46,6 +46,12 @@ pub const FailKind = enum {model,invalid,auth,+ /// The shared model-call pool is dry (run_budget.RunBudgetExhausted).+ /// Distinct from `quota`, which is the PROVIDER refusing: this one is the+ /// harness's own ceiling, it is GLOBAL to the run, and no amount of+ /// waiting or retrying changes it — the next attempt is refused before it+ /// reaches the network, and is still charged for trying.+ budget_exhausted,unknown,fn label(self: FailKind) []const u8 {@@ -55,6 +61,7 @@ pub const FailKind = enum {.model => "model-availability",.invalid => "invalid-arguments",.auth => "auth",+ .budget_exhausted => "model-call-budget",.unknown => "unknown",};}@@ -62,11 +69,23 @@ pub const FailKind = enum {pub fn retrySafe(self: FailKind) bool {return switch (self) {.quota, .transport, .unknown => true,- .model, .invalid, .auth => false,+ .model, .invalid, .auth, .budget_exhausted => false,};}};+/// The marker a budget-exhausted failure carries, so a workflow retry pass can+/// tell it apart from any other unretryable failure and abort the WHOLE pass+/// rather than skipping one task. Matches agent_request.zig's message text.+pub const budget_exhausted_marker = "model-call budget exhausted";++/// Did this failure come from the shared pool running dry? Read by the+/// workflow retry sites: the first one of these ends the pass, because every+/// sibling retry would be refused identically and each refusal still costs.+pub fn isBudgetExhausted(text: []const u8) bool {+ return util.indexOfIgnoreCase(text, budget_exhausted_marker) != null;+}+fn containsAnyCI(hay: []const u8, needles: []const []const u8) bool {for (needles) |n| if (util.indexOfIgnoreCase(hay, n) != null) return true;return false;@@ -77,7 +96,13 @@ pub fn classifyFailure(err: anyerror, detail: ?[]const u8) FailKind {error.StreamStalled, error.StreamDropped => return .transport,else => {},}+ if (err == error.RunBudgetExhausted) return .budget_exhausted;const msg = detail orelse return .unknown;+ // Before every other arm, including the 5xx one: the harness's OWN pool+ // running dry says "budget" and "exhausted", and the words in that message+ // ("quota"-adjacent, and it names a limit) would otherwise classify it as+ // a provider rate limit and earn it a retry that cannot possibly succeed.+ if (isBudgetExhausted(msg)) return .budget_exhausted;// 5xx before everything: a server-side outage is the most common transient// failure there is, and "503 Service Unavailable" used to fall through to// the .model arm on the bare word "unavailable". That was harmless while@@ -247,6 +272,10 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []constelse.child,.sys_override = sys_override,+ // §2c: the judge is text-only. It ranks handed excerpts, so a toolset+ // only buys it the chance to go re-read the repo — which is where its+ // ~3 calls per score went. One judge, one call.+ .text_only = std.mem.eql(u8, kind, "judge_task"),.reasoning = effort orelse .medium, // #292 follow-up: effort pin; unpinned workers keep the default depth, not the root's /effort};const sub_start = Io.Timestamp.now(ctx.io, .awake);diff --git a/src/subagent_tests.zig b/src/subagent_tests.zigindex 9253189d..aad3031f 100644--- a/src/subagent_tests.zig+++ b/src/subagent_tests.zig@@ -64,3 +64,36 @@ test "classifyFailure: maps the child's api-error detail to a category + retry-stry std.testing.expect(!FailKind.invalid.retrySafe());try std.testing.expect(!FailKind.auth.retrySafe());}++// Moved off subagent.zig when the §2c tournament gate needed room there — the+// tests are unchanged, and this is the file that exists for exactly that.++test "agentStatusText: running/completed/failed shapes carry the usage summary, and a failure is never silent (#276 P0-3)" {+ const gpa = std.testing.allocator;++ const running = try subagent.agentStatusText(gpa, 7, false, false, .{}, "");+ defer gpa.free(running);+ try std.testing.expectEqualStrings("[agent 7: running]", running);++ const ok = try subagent.agentStatusText(gpa, 7, true, false, .{ .duration_ms = 1200, .tool_calls = 3, .context_tokens = 4500, .cache_read_tokens = 100 }, "final report");+ defer gpa.free(ok);+ try std.testing.expect(std.mem.indexOf(u8, ok, "completed") != null);+ try std.testing.expect(std.mem.indexOf(u8, ok, "1200ms") != null);+ 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 = 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 silent+ try std.testing.expect(std.mem.indexOf(u8, failed, failed_text) != null); // the child's own diagnostic rides along verbatim+}++test "agentStatusText: composes with isolation:\"worktree\" — a kept-worktree note in the result survives verbatim (#276 P0-3 design point 5)" {+ const gpa = std.testing.allocator;+ const result_with_worktree = "final report text\n\n[worktree kept (has changes) — path: .graff/worktrees/agent-sa-001-aa11, branch: graff/agents/sa-001-aa11]";+ const out = try subagent.agentStatusText(gpa, 3, true, false, .{ .duration_ms = 500 }, result_with_worktree);+ defer gpa.free(out);+ try std.testing.expect(std.mem.indexOf(u8, out, "[worktree kept (has changes) — path:") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "branch: graff/agents/sa-001-aa11") != null);+}diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 0512d81a..81575dc3 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -91,6 +91,21 @@ const playbook_reflect = @import("playbook_reflect.zig");// that staying true.const mcp_config = @import("mcp_config.zig");+// The ultracode escalation ladder and the machinery it decides with. The+// production graph reaches escalation.zig/phase_budget.zig through+// workflow.zig, but only through a CALL — nothing references their decls at+// container level, so without these hooks the whole threshold matrix, the+// reservation ledger, the collapse gate and the #290 fold firewall would+// compile and never run a single test.+const escalation = @import("escalation.zig");+const escalation_tests = @import("escalation_tests.zig");+const edit_contract = @import("edit_contract.zig");+const phase_budget = @import("phase_budget.zig");+const orchestration_policy = @import("orchestration_policy.zig");+const orchestration_policy_tests = @import("orchestration_policy_tests.zig");+const orchestration_rows = @import("orchestration_rows.zig");+const workflow_pipeline = @import("workflow_pipeline.zig");+// #364: shutdown-phase timings. Production reaches it from readline.zig,// session.zig, mcp.zig, telemetry.zig and startup_timing.zig, so its coverage// is contingent on those call sites staying — pinned here instead.@@ -132,4 +147,12 @@ test {_ = playbook_glue;_ = playbook_reflect;_ = shutdown_trace;+ _ = escalation;+ _ = escalation_tests;+ _ = edit_contract;+ _ = phase_budget;+ _ = orchestration_policy;+ _ = orchestration_policy_tests;+ _ = orchestration_rows;+ _ = workflow_pipeline;}diff --git a/src/workflow.zig b/src/workflow.zigindex ab583a3f..c15853fb 100644--- a/src/workflow.zig+++ b/src/workflow.zig@@ -1,11 +1,19 @@//! Dynamic workflows as data: sequential phases of parallel subagents (#1/#2/-//! #4/#5), plus pipeline mode (#3) — items mapped through a chain of stages-//! with no inter-item barrier. Split out of main.zig (600-line goal).+//! #4/#5). Split out of main.zig (600-line goal). Pipeline mode (#3) — items+//! mapped through a chain of stages with no inter-item barrier — moved to+//! workflow_pipeline.zig for the same reason, and aliased back below.//! Sibling-imports tools.zig for `ToolCtx`/`ToolOutput`/`failure` and//! subagent.zig for `workflowTask`/`runSub`/`scoreVariants`///! `max_workflow_tasks` (subagent.zig is the lower-level sibling here, so the//! shared task-count cap lives there, not here — avoids a circular import).//! Back-imports main (as `main_mod`) only for `utf8Prefix`.+//!+//! THE ESCALATION GATE. Four thin call sites below implement the ladder in+//! escalation.zig: `admit` before anything spawns, the per-phase budget+//! re-check at the loop head, duplicate-brief collapse before the futures+//! allocate, and the optional-spend gate on the judge tournament. Every rung+//! decision, and every one of its consequences, is decided there; this file+//! only obeys.const std = @import("std");const Io = std.Io;@@ -46,6 +54,17 @@ const telemetry = @import("telemetry.zig");// JSONL event, so the REPL can map a run from state instead of scraping the// std.debug.print lines below. Also holds the run manifest (see below).const wfp = @import("workflow_progress.zig");+// The ultracode escalation ladder (admission, the edit contract) and the+// reservation ledger it decides against.+const escalation = @import("escalation.zig");+const phase_budget = @import("phase_budget.zig");+const shapes = @import("shapes.zig");+const pipeline_mode = @import("workflow_pipeline.zig");++// Pipeline mode moved to workflow_pipeline.zig (600-line cap); aliased back so+// workflow_test.zig and every other caller still reach it here.+pub const pipelinePrompt = pipeline_mode.pipelinePrompt;+pub const pipelineIsolationError = pipeline_mode.pipelineIsolationError;const max_workflow_phases = 5;@@ -129,36 +148,6 @@ pub fn gateAllows(prev: []const u8, when: []const u8) bool {return when.len == 0 or util.indexOfIgnoreCase(prev, when) != null;}-// ── Pipeline mode (#3) ──────────────────────────────────────────────────────-// Phases fan out then synthesize: a barrier between phases, since every-// next-phase task waits on ALL of the previous phase via {{prev}}. Pipeline-// instead maps each ITEM through a chain of STAGES with NO barrier — item A can-// be in stage 3 while item B is still in stage 1, so wall-clock is the slowest-// single chain, not the sum of slowest-per-stage. Use it for per-item work-// (transform/verify each file); use phases for fan-out + synthesis.-const max_pipeline_items = 8;-const max_pipeline_stages = 5;--const StageSpec = struct {- label: []const u8,- prompt: []const u8, // raw; may contain {{item}} / {{prev}}- override: ?[]const u8,- niche: []const u8,- isolation: Isolation = .shared_cwd, // #276 P0-1- isolation_fallback: bool = false,- role: []const u8 = "", // #372: this stage's canonical slot, for its route trace-};--/// Replace every `needle` in `hay` with `repl` (arena-allocated); returns `hay`-/// unchanged when the needle is absent.-fn replacePlaceholder(arena: Allocator, hay: []const u8, needle: []const u8, with: []const u8) ![]const u8 {- if (std.mem.indexOf(u8, hay, needle) == null) return hay;- const size = std.mem.replacementSize(u8, hay, needle, with);- const buf = try arena.alloc(u8, size);- _ = std.mem.replace(u8, hay, needle, with, buf);- return buf;-}-/// Prepend the workflow/pipeline-level shared "context" (if any) to a raw/// task or stage prompt, BEFORE {{prev}}/{{item}} substitution runs on the/// result: context, blank line, raw prompt (U5). Absent/empty context@@ -169,181 +158,6 @@ pub fn withContext(arena: Allocator, context: []const u8, raw: []const u8) ![]coreturn std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ context, raw });}-/// Resolve a pipeline stage prompt for one item: substitute {{item}}, and from-/// stage 2 {{prev}} = this item's bounded previous-stage result. Either is-/// appended when its placeholder is omitted (mirrors phases-mode {{prev}}).-pub fn pipelinePrompt(arena: Allocator, raw: []const u8, item: []const u8, prev: []const u8, stage_no: usize) ![]const u8 {- const cp = if (stage_no > 1) cappedPrevBody(arena, prev, pipeline_prev_cap) else "";- var p = raw;- if (std.mem.indexOf(u8, p, "{{item}}") != null)- p = try replacePlaceholder(arena, p, "{{item}}", item)- else- p = try std.fmt.allocPrint(arena, "{s}\n\nItem: {s}", .{ p, item });- if (std.mem.indexOf(u8, p, "{{prev}}") != null)- p = try replacePlaceholder(arena, p, "{{prev}}", cp)- else if (stage_no > 1)- p = try std.fmt.allocPrint(arena, "{s}\n\nResult from the previous stage:\n\n{s}", .{ p, cp });- return p;-}--/// One item's journey through every stage, run on a pool thread (spawned by-/// runPipeline). Stages run SEQUENTIALLY here via DIRECT runSub calls — never a-/// nested io.async, which on a bounded pool could deadlock; different items run-/// concurrently. A failed stage is retried once (#2); a stage that still fails-/// ends the chain with a terse marker plus a capped one-line excerpt of its-/// error (#248), rather than feeding the whole error downstream.-fn pipelineChain(ctx: ToolCtx, item: []const u8, stages: []const StageSpec) ToolOutput {- const gpa = ctx.gpa;- var arena_state = std.heap.ArenaAllocator.init(gpa);- defer arena_state.deinit();- const arena = arena_state.allocator();- var prev: []const u8 = "";- for (stages, 1..) |st, stage_no| {- const prompt = pipelinePrompt(arena, st.prompt, item, prev, stage_no) catch |e| return failure(gpa, e);- // #372: say out loud which route this stage worker actually got, and- // under which cell — an inherited route was invisible before.- route_trace.emitSpawnProvider(ctx.io, ctx.tracer, st.label, subagent_run.childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider), .{ .shape = .migration, .role = st.role }, if (st.override != null) .workflow_override else route_trace.sessionSource(ctx.subagent_provider != null), st.override, st.niche);- // null pin: neither #292's per-spawn pins nor #376's phase seat reach a pipeline stage — a chain is never scored (#296), so it has no cell to learn from.- var out = if (runSub(ctx, "workflow_task", st.label, prompt, st.override, st.niche, st.isolation, st.isolation_fallback, null, null)) |r| r.output else |e| failure(gpa, e);- if (out.is_error) {- // Only spend the one retry (#2) when the harness's own- // classification hasn't already ruled it out (auth, invalid- // args, an unavailable model) — those stay failed below without- // wasting a second attempt.- if (failureAllowsRetry(out.text)) {- gpa.free(out.text);- out = if (runSub(ctx, "workflow_retry", st.label, prompt, st.override, st.niche, st.isolation, st.isolation_fallback, null, null)) |r| r.output else |e| failure(gpa, e);- }- if (out.is_error) {- // #248 — excerpt the stage's own error BEFORE freeing it, so- // the item's result says why the chain stopped, not just that- // it did.- const detail = failExcerpt(arena, out.text);- gpa.free(out.text);- const msg = if (detail.len > 0)- std.fmt.allocPrint(gpa, "(pipeline stopped at stage {d}/{d} \"{s}\": task failed)\n{s}", .{ stage_no, stages.len, st.label, detail })- else- std.fmt.allocPrint(gpa, "(pipeline stopped at stage {d}/{d} \"{s}\": task failed)", .{ stage_no, stages.len, st.label });- return .{- .text = msg catch (gpa.dupe(u8, "(pipeline stage failed)") catch ""),- .is_error = true,- };- }- }- const duped = arena.dupe(u8, out.text) catch {- gpa.free(out.text);- return failure(gpa, error.OutOfMemory);- };- gpa.free(out.text);- prev = duped;- }- return .{ .text = gpa.dupe(u8, prev) catch "" };-}--/// Comptime-formatted refusal message for a worktree-isolated stage past 0.-fn stageIsoMsg(comptime n: usize) []const u8 {- return std.fmt.comptimePrint("pipeline stage {d} requests worktree isolation, but a pipeline is a dependent chain over one item -- stage {d} must see what earlier stages did, and worktree isolation would silently hide that work. Only stage 0 may isolate with its own worktree. If you wanted real per-item isolation, use phases instead (phases run independently, with no such dependency).", .{ n, n });-}--/// Pure guard-rail predicate for pipeline-stage isolation: a pipeline chains-/// dependent stages over one item, so only stage 0 (index 0) may resolve to-/// worktree isolation -- any later stage in its own worktree cannot see what-/// the prior stage did, and the run would silently produce nonsense (#295-/// territory covers the real per-item-worktree redesign; this only refuses-/// the broken config). Returns the refusal message, or null when allowed.-pub fn pipelineIsolationError(stage_index: usize, iso: Isolation) ?[]const u8 {- if (stage_index == 0 or iso != .worktree) return null;- return switch (stage_index) {- 1 => stageIsoMsg(1),- 2 => stageIsoMsg(2),- 3 => stageIsoMsg(3),- 4 => stageIsoMsg(4),- else => "pipeline stage requests worktree isolation, but a pipeline is a dependent chain over one item -- only stage 0 may isolate with its own worktree. If you wanted real per-item isolation, use phases instead (phases run independently).",- };-}--/// Pipeline mode entry (#3): validate {items, stages}, then run one independent-/// chain per item concurrently (no barrier) and return the labeled final-stage-/// result for each item.-fn runPipeline(ctx: ToolCtx, pv: Value, outer_context: []const u8) !ToolOutput {- const gpa = ctx.gpa;- if (pv != .object) return .{ .text = try gpa.dupe(u8, "pipeline must be an object with items + stages"), .is_error = true };- const items_val = pv.object.get("items") orelse return .{ .text = try gpa.dupe(u8, "pipeline needs an items array"), .is_error = true };- const stages_val = pv.object.get("stages") orelse return .{ .text = try gpa.dupe(u8, "pipeline needs a stages array"), .is_error = true };- if (items_val != .array or stages_val != .array) return .{ .text = try gpa.dupe(u8, "pipeline items and stages must both be arrays"), .is_error = true };- const items = items_val.array.items;- const stage_vals = stages_val.array.items;- if (items.len == 0 or items.len > max_pipeline_items) return .{ .text = try std.fmt.allocPrint(gpa, "pipeline needs 1-{d} items", .{max_pipeline_items}), .is_error = true };- if (stage_vals.len == 0 or stage_vals.len > max_pipeline_stages) return .{ .text = try std.fmt.allocPrint(gpa, "pipeline needs 1-{d} stages", .{max_pipeline_stages}), .is_error = true };- // Shared context slot: one string prepended to every stage prompt below- // (before {{item}}/{{prev}}). Readable in BOTH places the tool schema says- // it is - on the pipeline object, or top-level alongside it - because the- // dispatch to runPipeline happens before the top-level read, so a pipeline- // call silently ignored the documented top-level field.- const context_str: []const u8 = if (pv.object.get("context")) |cv| (if (cv == .string) cv.string else outer_context) else outer_context;-- var arena_state = std.heap.ArenaAllocator.init(gpa);- defer arena_state.deinit();- const arena = arena_state.allocator();-- // Parse stages once — shared (read-only) by every item chain.- const stages = try arena.alloc(StageSpec, stage_vals.len);- for (stage_vals, stages, 0..) |sv, *sp, stage_index| {- if (sv != .object) return .{ .text = try gpa.dupe(u8, "each pipeline stage must be an object"), .is_error = true };- const so = sv.object;- sp.label = if (so.get("description")) |d| (if (d == .string) d.string else "stage") else "stage";- const raw = if (so.get("prompt")) |p| (if (p == .string) p.string else "") else "";- if (raw.len == 0) return .{ .text = try gpa.dupe(u8, "each pipeline stage needs a non-empty \"prompt\""), .is_error = true };- sp.prompt = try withContext(arena, context_str, raw);- sp.override = fleet.resolveOverride(so);- const an = fleet.resolveNiche(so);- sp.niche = if (an.len > 0) an else sp.label;- sp.isolation = fleet.resolveIsolation(so);- // A pipeline is a dependent chain over one item: stage 2+ must see- // what earlier stages did, which worktree isolation would silently- // hide (#295 territory). Reject rather than run the chain wrong.- if (pipelineIsolationError(stage_index, sp.isolation)) |msg|- return .{ .text = try gpa.dupe(u8, msg), .is_error = true };- sp.isolation_fallback = fleet.resolveIsolationFallback(so);- sp.role = route_policy.roleOf(sp.label, sp.niche); // #372- }-- const item_strs = try arena.alloc([]const u8, items.len);- for (items, item_strs) |iv, *is| {- if (iv != .string or iv.string.len == 0) return .{ .text = try gpa.dupe(u8, "pipeline items must be non-empty strings"), .is_error = true };- is.* = iv.string;- }-- const wf_start = Io.Timestamp.now(ctx.io, .awake);- std.debug.print(" [workflow] pipeline: {d} item(s) × {d} stage(s), no barrier\n", .{ items.len, stages.len });- // #63 — same fact, as state: phase_index 0 is the run-level event, since a- // pipeline has stages rather than phases. Per-stage events would have to be- // threaded into pipelineChain (one chain per item, on its own pool thread);- // that is left to the follow-up that renders them.- const run_id = try wfp.nextRunId(arena);- wfp.phase(ctx.io, arena, run_id, 0, stages.len, "pipeline", "started", items.len);-- // Spawn one chain per item — all joined before any fallible work so an early- // return can never abandon a running chain.- const futures = try arena.alloc(Io.Future(ToolOutput), items.len);- const outputs = try arena.alloc(ToolOutput, items.len);- for (item_strs, futures) |item, *fut| fut.* = ctx.io.async(pipelineChain, .{ ctx, item, stages });- for (futures, outputs) |*fut, *out| out.* = fut.await(ctx.io);- defer for (outputs) |out| gpa.free(out.text);-- var failed: usize = 0;- for (outputs) |out| if (out.is_error) {- failed += 1;- };- if (telemetry.g_telem) |t| t.workflowEvent(stages.len, items.len * stages.len, failed, @intCast(@max(0, wf_start.untilNow(ctx.io, .awake).toMilliseconds())));-- var aw: Io.Writer.Allocating = .init(arena);- for (item_strs, outputs) |item, out| {- try aw.writer.print("### {s}{s}\n{s}\n\n", .{ item, if (out.is_error) " (failed)" else "", out.text });- }- return .{ .text = try gpa.dupe(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n")) };-}-// U2's all-failed abort text, the run manifest and PhaseTally moved to// workflow_progress.zig alongside the #63 structured events (this file is at// the 600-line cap and both are "what did this run do" reporting). Aliased@@ -373,7 +187,7 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {.is_error = true,};const outer_context: []const u8 = if (obj.get("context")) |cv| (if (cv == .string) cv.string else "") else "";- if (obj.get("pipeline")) |pv| return runPipeline(ctx, pv, outer_context);+ if (obj.get("pipeline")) |pv| return pipeline_mode.run(ctx, pv, outer_context);const phases_val = obj.get("phases") orelse return .{.text = try gpa.dupe(u8, "workflow needs a \"phases\" array (or a \"pipeline\" object)"),.is_error = true,@@ -404,6 +218,27 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {// component of every worker's policy cell for this run.const shape = route_policy.shapeOfPhases(phases);+ // ADMISSION (escalation §1b). One call, on cheap observables, before a+ // single future is allocated: which rung does this ask actually deserve?+ // R0 hands back a non-error advisory and the root does the work itself —+ // which on ordinary tasks is both cheaper and better, measured.+ const ledger = phase_budget.Ledger.init(phase_budget.capOf(ctx.run_budget));+ const admission = escalation.admit(escalation.ctxFrom(ctx, arena), phases, shape);+ switch (admission.verdict) {+ .solo => |advice| return .{ .text = try gpa.dupe(u8, advice) },+ else => {},+ }+ // §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.+ const width_cap: usize = switch (admission.verdict) {+ .downsize => |w| w,+ else => max_workflow_tasks,+ };+ // P2 set this when it stopped early, so the manifest can say so.+ var truncated = false;+ var phases_ran: usize = 0;+// Telemetry: one "workflow" record per run — phase/task/failure counts// and wall-clock — emitted however the run ends.const wf_start = Io.Timestamp.now(ctx.io, .awake);@@ -419,19 +254,32 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {var prev_results: []const u8 = "";const tallies = try arena.alloc(PhaseTally, phases.len);for (phases, 1..) |phase_val, phase_no| {+ // §4-P2: stop BEFORE a phase whose remaining plan cannot be followed+ // through on. Returning three finders' evidence and enough calls for+ // the root to land the fix beats spending the last call on a fourth+ // finder and dying with the file untouched — which is exactly how the+ // study's cap-30 bugfix run ended.+ if (ledger.earlyExit(phase_budget.remainingOf(ctx.run_budget), phase_budget.laterPhasesMin(phases, phase_no - 1))) {+ truncated = true;+ break;+ }if (phase_val != .object) return .{ .text = try gpa.dupe(u8, "each phase must be an object"), .is_error = true };const phase = phase_val.object;const title = if (phase.get("title")) |t| (if (t == .string) t.string else "phase") else "phase";+ // §3b: this phase's slot is contracted to MUTATE files, so its briefs+ // carry the changed-path contract and its results face a porcelain probe.+ const contracted = escalation.isContracted(shapes.canonicalSlot(title));const tasks_val = phase.get("tasks") orelse return .{.text = try gpa.dupe(u8, "each phase needs a tasks array"),.is_error = true,};if (tasks_val != .array) return .{ .text = try gpa.dupe(u8, "phase tasks must be an array"), .is_error = true };- const tasks = tasks_val.array.items;- if (tasks.len == 0 or tasks.len > max_workflow_tasks) return .{+ const authored = tasks_val.array.items;+ if (authored.len == 0 or authored.len > max_workflow_tasks) return .{.text = try std.fmt.allocPrint(gpa, "each phase needs 1-{d} tasks", .{max_workflow_tasks}),.is_error = true,};+ const tasks = authored[0..@min(authored.len, @max(width_cap, 1))];// #5 — conditional phase: skip when its `when` substring is absent from// the previous phase's results (case-insensitive). Phase 1 has no prev so// its `when` never gates; a skipped phase leaves {{prev}} untouched, so a@@ -440,6 +288,7 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {std.debug.print(" [workflow] phase {d}/{d}: {s} — SKIPPED (when \"{s}\" absent)\n", .{ phase_no, phases.len, title, wv.string });wfp.phase(ctx.io, arena, run_id, phase_no, phases.len, title, "skipped", tasks.len); // #63tallies[phase_no - 1] = .{ .phase_no = phase_no, .total_phases = phases.len, .title = title, .ok = 0, .total = tasks.len, .retried = 0, .skipped_when = wv.string };+ phases_ran = phase_no;continue;};std.debug.print(" [workflow] phase {d}/{d}: {s} ({d} task(s))\n", .{ phase_no, phases.len, title, tasks.len });@@ -468,7 +317,10 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {const raw = if (task.get("prompt")) |p| (if (p == .string) p.string else "") else "";if (raw.len == 0) return .{ .text = try gpa.dupe(u8, "each task needs a non-empty \"prompt\""), .is_error = true };rawp.* = raw;- const based = try withContext(arena, context_str, raw);+ // §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);if (phase_no == 1) {prompt.* = based;} else if (std.mem.indexOf(u8, based, "{{prev}}") != null) {@@ -482,6 +334,14 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {}const diversity = brief_diversity.check(arena, ctx.tracer, title, raws, overrides); // #382: every brief in hand, nothing spawned yet+ // §2b — duplicate-brief collapse, here because this is the last moment+ // every brief is in hand and nothing has spawned. Tasks carrying the+ // same genome AND the same brief are one worker asked twice; the+ // duplicate spawns nothing and reads the survivor's result.+ const dup = brief_diversity.collapse(arena, raws, overrides, escalation.isVariantsPhase(phase_val));+ // The porcelain snapshot the edit contract compares against, taken+ // before any worker can touch the tree. "" for an uncontracted phase.+ const tree_before = escalation.treeSnapshot(arena, gpa, ctx.io, ctx.agent_cwd, contracted);// Join ALL tasks before any fallible work, so an early error return// can never abandon running subagents or free their result slots.const futures = try arena.alloc(Io.Future(ToolOutput), tasks.len);@@ -494,19 +354,31 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {// #380: …then asked whether any task in it names an image the seat// cannot see. A re-seat stays phase-UNIFORM, so #290 is untouched.const seat = vision_ask.phaseSeat(route_phase.forPhase(subagent_run.childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider), shape, title, niches, ctx.subagent_provider != null), prompts, ctx.subagent_provider != null);- for (labels, prompts, overrides, niches, isolations, isolation_fallbacks, futures, 1..) |label, prompt, override, niche, isolation, isolation_fallback, *fut, task_no| {- wfp.task(ctx.io, arena, run_id, phase_no, task_no, tasks.len, label, "running"); // #63+ for (labels, prompts, overrides, niches, isolations, isolation_fallbacks, futures, 0..) |label, prompt, override, niche, isolation, isolation_fallback, *fut, i| {+ if (dup.rep[i] != i) continue; // §2b: a collapsed duplicate spawns nothing+ wfp.task(ctx.io, arena, run_id, phase_no, i + 1, tasks.len, label, "running"); // #63route_trace.emitSpawnProvider(ctx.io, ctx.tracer, label, seat.provider, seat.cellOf(niche), seat.sourceFor(override != null), override, niche);fut.* = ctx.io.async(workflowTask, .{ ctx, label, prompt, override, niche, isolation, isolation_fallback, seat.pin });}- for (futures, outputs, labels, prompts, 1..) |*fut, *out, label, prompt, task_no| {- out.* = vision_ask.flagReport(gpa, fut.await(ctx.io), vision_ask.forPrompt(prompt)); // #380 honesty flag+ for (futures, outputs, labels, prompts, 0..) |*fut, *out, label, prompt, i| {+ if (dup.rep[i] != i) continue;+ // §3b — the edit contract, post-await: a contracted phase whose+ // porcelain never moved becomes is_error, which the retry below+ // then picks up. #380's honesty flag composes inside it.+ out.* = escalation.contractCheck(gpa, ctx.io, ctx.agent_cwd, contracted, tree_before, vision_ask.flagReport(gpa, fut.await(ctx.io), vision_ask.forPrompt(prompt)));// #63 — terminal per task, so a UI can settle that row without// waiting for the phase (and before the retry pass below reruns it).- wfp.task(ctx.io, arena, run_id, phase_no, task_no, tasks.len, label, if (out.is_error) "failed" else "completed");+ wfp.task(ctx.io, arena, run_id, phase_no, i + 1, tasks.len, label, if (out.is_error) "failed" else "completed");}+ // Fan the survivor's result into every slot that collapsed into it, so+ // the next phase's {{prev}} reads exactly what it would have read. Must+ // run before the free-defer below, or a collapsed slot would be freed+ // uninitialized.+ for (outputs, 0..) |*out, i| if (dup.rep[i] != i) {+ out.* = .{ .text = gpa.dupe(u8, outputs[dup.rep[i]].text) catch "", .is_error = outputs[dup.rep[i]].is_error };+ };defer for (outputs) |out| gpa.free(out.text);- wf_tasks += tasks.len;+ wf_tasks += dup.survivors.len;// #2 — Retry transient failures once. A single flaky subagent (an empty// report, a dropped stream) shouldn't fail the phase or poison {{prev}}@@ -517,9 +389,18 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {// invalid argument, an unavailable model — see failureAllowsRetry) are// excluded here: retrying the whole phase would only double the cost// of a broken run for zero chance of success.+ // §4 — a budget-exhausted failure is GLOBAL, not per-task: the shared+ // pool is dry, so every other retry in this pass would fail the same+ // way and each would still be CHARGED for trying. Abort the whole pass+ // and let P2 end the run with partial evidence instead.+ var budget_dry = false;+ for (outputs) |out| if (out.is_error and subagent_run.isBudgetExhausted(out.text)) {+ budget_dry = true;+ };+ if (budget_dry) truncated = true;var fidx: [max_workflow_tasks]usize = undefined;var nf: usize = 0;- for (outputs, 0..) |out, i| if (out.is_error and failureAllowsRetry(out.text)) {+ for (outputs, 0..) |out, i| if (!budget_dry and out.is_error and failureAllowsRetry(out.text)) {fidx[nf] = i;nf += 1;};@@ -568,9 +449,15 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {// fleet can rank and promote the winner (docs/hyperagents.md §9.B). The// propose half already fired in runSub; this closes the loop runEval left// open (it submits niche=""). Gated on the fleet — no judge cost otherwise.- scoreVariants(ctx, arena, seat, prompts, raws, overrides, niches, outputs);+ // §4-P3: and on the budget. A tournament is OPTIONAL spend — one call+ // per surviving variant post-§2c — so it runs only when it fits ON TOP+ // of the landing reserve. This is run_budget.canAfford's documented use+ // case, which until now had zero call sites.+ if (ledger.fits(phase_budget.remainingOf(ctx.run_budget), @as(u64, @intCast(dup.survivors.len)) * phase_budget.cost_judge))+ scoreVariants(ctx, arena, seat, prompts, raws, overrides, niches, outputs);- tallies[phase_no - 1] = .{ .phase_no = phase_no, .total_phases = phases.len, .title = title, .ok = tasks.len - phase_failed, .total = tasks.len, .retried = nf, .diversity = diversity };+ tallies[phase_no - 1] = .{ .phase_no = phase_no, .total_phases = phases.len, .title = title, .ok = tasks.len - phase_failed, .total = tasks.len, .retried = nf, .diversity = wfp.joinNotes(arena, diversity, brief_diversity.collapseNote(arena, dup)) };+ phases_ran = phase_no;// Divide the {{prev}} budget across THIS phase's own task count so a// wide phase's total contribution to the next phase's prompt stays near@@ -594,7 +481,13 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {}prev_results = std.mem.trimEnd(u8, aw.writer.buffered(), "\n");}- const manifest = try buildManifest(arena, tallies);- const final_text = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ prev_results, manifest });+ // Only the phases that actually ran are tallied: P2 can break out of the+ // loop, leaving the rest of `tallies` uninitialized.+ const manifest = try buildManifest(arena, tallies[0..phases_ran]);+ const final_text = try std.fmt.allocPrint(arena, "{s}\n\n{s}{s}", .{+ prev_results,+ manifest,+ if (truncated) "\n" ++ phase_budget.truncated_note else "",+ });return .{ .text = try gpa.dupe(u8, final_text) };}diff --git a/src/workflow_pipeline.zig b/src/workflow_pipeline.zignew file mode 100644index 00000000..a6ee012c--- /dev/null+++ b/src/workflow_pipeline.zig@@ -0,0 +1,290 @@+//! Pipeline mode (#3), split out of workflow.zig (600-line cap).+//!+//! Phases fan out then synthesize: a barrier between phases, since every+//! next-phase task waits on ALL of the previous one via {{prev}}. Pipeline+//! instead maps each ITEM through a chain of STAGES with NO barrier — item A+//! can be in stage 3 while item B is still in stage 1, so wall-clock is the+//! slowest single chain, not the sum of slowest-per-stage. Use it for+//! per-item work (transform/verify each file); use phases for fan-out ++//! synthesis.+//!+//! Why its own file: it is a genuinely separate execution mode that shares+//! only prompt-substitution helpers with the phases loop, and keeping it here+//! is what buys workflow.zig the room for the escalation gate. It also gets+//! its OWN admission check — the phases path's `admit` sits after the+//! pipeline dispatch, so before this split a pipeline was the one way to fan+//! out with no budget gate at all. That is not academic: the eval study's+//! refactor run instantiated a 4-item x 2-stage pipeline, retried all four+//! items, and burned the entire 30-call cap.++const std = @import("std");+const Io = std.Io;+const Value = std.json.Value;+const Allocator = std.mem.Allocator;++const tools = @import("tools.zig");+const ToolCtx = tools.ToolCtx;+const ToolOutput = tools.ToolOutput;+const failure = tools.failure;++const subagent = @import("subagent.zig");+const runSub = subagent.runSub;+const subagent_run = @import("subagent_run.zig");+const failureAllowsRetry = subagent_run.failureAllowsRetry;++const fleet = @import("fleet.zig");+const Isolation = fleet.Isolation;+const route_policy = @import("route_policy.zig");+const route_trace = @import("route_trace.zig");+const telemetry = @import("telemetry.zig");+const wfp = @import("workflow_progress.zig");+const escalation = @import("escalation.zig");+const phase_budget = @import("phase_budget.zig");+const workflow = @import("workflow.zig");++const max_pipeline_items = 8;+const max_pipeline_stages = 5;++// Flat {{prev}} cap for pipeline mode (#3): each pipeline item runs its own+// independent stage chain, so unlike phases there's no fan-in multiplying one+// item's previous-stage text across other items' prompts — no phase-budget+// division needed here, a flat cap is enough.+const pipeline_prev_cap = 6000;++const StageSpec = struct {+ label: []const u8,+ prompt: []const u8, // raw; may contain {{item}} / {{prev}}+ override: ?[]const u8,+ niche: []const u8,+ isolation: Isolation = .shared_cwd, // #276 P0-1+ isolation_fallback: bool = false,+ role: []const u8 = "", // #372: this stage's canonical slot, for its route trace+};++/// Replace every `needle` in `hay` with `repl` (arena-allocated); returns `hay`+/// unchanged when the needle is absent.+fn replacePlaceholder(arena: Allocator, hay: []const u8, needle: []const u8, with: []const u8) ![]const u8 {+ if (std.mem.indexOf(u8, hay, needle) == null) return hay;+ const size = std.mem.replacementSize(u8, hay, needle, with);+ const buf = try arena.alloc(u8, size);+ _ = std.mem.replace(u8, hay, needle, with, buf);+ return buf;+}++/// Resolve a pipeline stage prompt for one item: substitute {{item}}, and from+/// stage 2 {{prev}} = this item's bounded previous-stage result. Either is+/// appended when its placeholder is omitted (mirrors phases-mode {{prev}}).+pub fn pipelinePrompt(arena: Allocator, raw: []const u8, item: []const u8, prev: []const u8, stage_no: usize) ![]const u8 {+ const cp = if (stage_no > 1) workflow.cappedPrevBody(arena, prev, pipeline_prev_cap) else "";+ var p = raw;+ if (std.mem.indexOf(u8, p, "{{item}}") != null)+ p = try replacePlaceholder(arena, p, "{{item}}", item)+ else+ p = try std.fmt.allocPrint(arena, "{s}\n\nItem: {s}", .{ p, item });+ if (std.mem.indexOf(u8, p, "{{prev}}") != null)+ p = try replacePlaceholder(arena, p, "{{prev}}", cp)+ else if (stage_no > 1)+ p = try std.fmt.allocPrint(arena, "{s}\n\nResult from the previous stage:\n\n{s}", .{ p, cp });+ return p;+}++/// One item's journey through every stage, run on a pool thread (spawned by+/// run). Stages run SEQUENTIALLY here via DIRECT runSub calls — never a+/// nested io.async, which on a bounded pool could deadlock; different items run+/// concurrently. A failed stage is retried once (#2); a stage that still fails+/// ends the chain with a terse marker plus a capped one-line excerpt of its+/// error (#248), rather than feeding the whole error downstream.+fn pipelineChain(ctx: ToolCtx, item: []const u8, stages: []const StageSpec) ToolOutput {+ const gpa = ctx.gpa;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var prev: []const u8 = "";+ for (stages, 1..) |st, stage_no| {+ const prompt = pipelinePrompt(arena, st.prompt, item, prev, stage_no) catch |e| return failure(gpa, e);+ // #372: say out loud which route this stage worker actually got, and+ // under which cell — an inherited route was invisible before.+ route_trace.emitSpawnProvider(ctx.io, ctx.tracer, st.label, subagent_run.childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider), .{ .shape = .migration, .role = st.role }, if (st.override != null) .workflow_override else route_trace.sessionSource(ctx.subagent_provider != null), st.override, st.niche);+ // null pin: neither #292's per-spawn pins nor #376's phase seat reach a pipeline stage — a chain is never scored (#296), so it has no cell to learn from.+ var out = if (runSub(ctx, "workflow_task", st.label, prompt, st.override, st.niche, st.isolation, st.isolation_fallback, null, null)) |r| r.output else |e| failure(gpa, e);+ if (out.is_error) {+ // Only spend the one retry (#2) when the harness's own+ // classification hasn't already ruled it out (auth, invalid+ // args, an unavailable model, a dry model-call pool) — those+ // stay failed below without wasting a second attempt.+ if (failureAllowsRetry(out.text)) {+ gpa.free(out.text);+ out = if (runSub(ctx, "workflow_retry", st.label, prompt, st.override, st.niche, st.isolation, st.isolation_fallback, null, null)) |r| r.output else |e| failure(gpa, e);+ }+ if (out.is_error) {+ // #248 — excerpt the stage's own error BEFORE freeing it, so+ // the item's result says why the chain stopped, not just that+ // it did.+ const detail = workflow.failExcerpt(arena, out.text);+ gpa.free(out.text);+ const msg = if (detail.len > 0)+ std.fmt.allocPrint(gpa, "(pipeline stopped at stage {d}/{d} \"{s}\": task failed)\n{s}", .{ stage_no, stages.len, st.label, detail })+ else+ std.fmt.allocPrint(gpa, "(pipeline stopped at stage {d}/{d} \"{s}\": task failed)", .{ stage_no, stages.len, st.label });+ return .{+ .text = msg catch (gpa.dupe(u8, "(pipeline stage failed)") catch ""),+ .is_error = true,+ };+ }+ }+ const duped = arena.dupe(u8, out.text) catch {+ gpa.free(out.text);+ return failure(gpa, error.OutOfMemory);+ };+ gpa.free(out.text);+ prev = duped;+ }+ return .{ .text = gpa.dupe(u8, prev) catch "" };+}++/// Comptime-formatted refusal message for a worktree-isolated stage past 0.+fn stageIsoMsg(comptime n: usize) []const u8 {+ return std.fmt.comptimePrint("pipeline stage {d} requests worktree isolation, but a pipeline is a dependent chain over one item -- stage {d} must see what earlier stages did, and worktree isolation would silently hide that work. Only stage 0 may isolate with its own worktree. If you wanted real per-item isolation, use phases instead (phases run independently, with no such dependency).", .{ n, n });+}++/// Pure guard-rail predicate for pipeline-stage isolation: a pipeline chains+/// dependent stages over one item, so only stage 0 (index 0) may resolve to+/// worktree isolation -- any later stage in its own worktree cannot see what+/// the prior stage did, and the run would silently produce nonsense (#295+/// territory covers the real per-item-worktree redesign; this only refuses+/// the broken config). Returns the refusal message, or null when allowed.+pub fn pipelineIsolationError(stage_index: usize, iso: Isolation) ?[]const u8 {+ if (stage_index == 0 or iso != .worktree) return null;+ return switch (stage_index) {+ 1 => stageIsoMsg(1),+ 2 => stageIsoMsg(2),+ 3 => stageIsoMsg(3),+ 4 => stageIsoMsg(4),+ else => "pipeline stage requests worktree isolation, but a pipeline is a dependent chain over one item -- only stage 0 may isolate with its own worktree. If you wanted real per-item isolation, use phases instead (phases run independently).",+ };+}++/// What a pipeline of `items` x `stages` will cost, at the default per-stage+/// role cost. Pipelines are never scored (#296) so their stages carry no+/// canonical slot to price individually — the flat median is the honest+/// estimate, and it is the one the study's refactor run would have failed.+pub fn pipelineEstimate(items: usize, stage_roles: []const []const u8) u64 {+ var per_item: u64 = 0;+ for (stage_roles) |r| per_item += phase_budget.roleCost(r);+ return per_item * @as(u64, @intCast(items));+}++/// The refusal a pipeline gets when it cannot finish inside the pool. Same+/// doctrine as the R0 advisory: non-error, and it says what to do instead.+pub const too_big_advice =+ "workflow declined (escalation, pipeline): this pipeline's items x stages cannot finish inside the " +++ "remaining model-call budget while leaving enough calls to land the work. Either run it yourself " +++ "(a mechanical edit across a handful of files is solo work), or split it into a pipeline over fewer " +++ "items and re-invoke.";++/// Pipeline mode entry (#3): validate {items, stages}, then run one independent+/// chain per item concurrently (no barrier) and return the labeled final-stage+/// result for each item.+pub fn run(ctx: ToolCtx, pv: Value, outer_context: []const u8) !ToolOutput {+ const gpa = ctx.gpa;+ if (pv != .object) return .{ .text = try gpa.dupe(u8, "pipeline must be an object with items + stages"), .is_error = true };+ const items_val = pv.object.get("items") orelse return .{ .text = try gpa.dupe(u8, "pipeline needs an items array"), .is_error = true };+ const stages_val = pv.object.get("stages") orelse return .{ .text = try gpa.dupe(u8, "pipeline needs a stages array"), .is_error = true };+ if (items_val != .array or stages_val != .array) return .{ .text = try gpa.dupe(u8, "pipeline items and stages must both be arrays"), .is_error = true };+ const items = items_val.array.items;+ const stage_vals = stages_val.array.items;+ if (items.len == 0 or items.len > max_pipeline_items) return .{ .text = try std.fmt.allocPrint(gpa, "pipeline needs 1-{d} items", .{max_pipeline_items}), .is_error = true };+ if (stage_vals.len == 0 or stage_vals.len > max_pipeline_stages) return .{ .text = try std.fmt.allocPrint(gpa, "pipeline needs 1-{d} stages", .{max_pipeline_stages}), .is_error = true };+ // Shared context slot: one string prepended to every stage prompt below+ // (before {{item}}/{{prev}}). Readable in BOTH places the tool schema says+ // it is - on the pipeline object, or top-level alongside it - because the+ // dispatch to run happens before the top-level read, so a pipeline+ // call silently ignored the documented top-level field.+ const context_str: []const u8 = if (pv.object.get("context")) |cv| (if (cv == .string) cv.string else outer_context) else outer_context;++ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ // Parse stages once — shared (read-only) by every item chain.+ const stages = try arena.alloc(StageSpec, stage_vals.len);+ for (stage_vals, stages, 0..) |sv, *sp, stage_index| {+ if (sv != .object) return .{ .text = try gpa.dupe(u8, "each pipeline stage must be an object"), .is_error = true };+ const so = sv.object;+ sp.label = if (so.get("description")) |d| (if (d == .string) d.string else "stage") else "stage";+ const raw = if (so.get("prompt")) |p| (if (p == .string) p.string else "") else "";+ if (raw.len == 0) return .{ .text = try gpa.dupe(u8, "each pipeline stage needs a non-empty \"prompt\""), .is_error = true };+ sp.prompt = try workflow.withContext(arena, context_str, raw);+ sp.override = fleet.resolveOverride(so);+ const an = fleet.resolveNiche(so);+ sp.niche = if (an.len > 0) an else sp.label;+ sp.isolation = fleet.resolveIsolation(so);+ // A pipeline is a dependent chain over one item: stage 2+ must see+ // what earlier stages did, which worktree isolation would silently+ // hide (#295 territory). Reject rather than run the chain wrong.+ if (pipelineIsolationError(stage_index, sp.isolation)) |msg|+ return .{ .text = try gpa.dupe(u8, msg), .is_error = true };+ sp.isolation_fallback = fleet.resolveIsolationFallback(so);+ sp.role = route_policy.roleOf(sp.label, sp.niche); // #372+ }++ // Admission, pipeline flavour. The phases path runs the full escalation+ // ladder; a pipeline is already committed to per-item work, so the only+ // question worth asking is the budget one — and asking it is what stops a+ // chain from spending the pool and landing nothing.+ const cap = phase_budget.capOf(ctx.run_budget);+ const roles = try arena.alloc([]const u8, stages.len);+ for (stages, roles) |st, *r| r.* = st.role;+ const estimate = pipelineEstimate(items.len, roles);+ if (!phase_budget.Ledger.init(cap).fits(phase_budget.remainingOf(ctx.run_budget), estimate)) {+ escalation.notePipelineDeclined();+ return .{ .text = try gpa.dupe(u8, too_big_advice) };+ }++ const item_strs = try arena.alloc([]const u8, items.len);+ for (items, item_strs) |iv, *is| {+ if (iv != .string or iv.string.len == 0) return .{ .text = try gpa.dupe(u8, "pipeline items must be non-empty strings"), .is_error = true };+ is.* = iv.string;+ }++ const wf_start = Io.Timestamp.now(ctx.io, .awake);+ std.debug.print(" [workflow] pipeline: {d} item(s) × {d} stage(s), no barrier\n", .{ items.len, stages.len });+ // #63 — same fact, as state: phase_index 0 is the run-level event, since a+ // pipeline has stages rather than phases. Per-stage events would have to be+ // threaded into pipelineChain (one chain per item, on its own pool thread);+ // that is left to the follow-up that renders them.+ const run_id = try wfp.nextRunId(arena);+ wfp.phase(ctx.io, arena, run_id, 0, stages.len, "pipeline", "started", items.len);++ // Spawn one chain per item — all joined before any fallible work so an early+ // return can never abandon a running chain.+ const futures = try arena.alloc(Io.Future(ToolOutput), items.len);+ const outputs = try arena.alloc(ToolOutput, items.len);+ for (item_strs, futures) |item, *fut| fut.* = ctx.io.async(pipelineChain, .{ ctx, item, stages });+ for (futures, outputs) |*fut, *out| out.* = fut.await(ctx.io);+ defer for (outputs) |out| gpa.free(out.text);++ var failed: usize = 0;+ for (outputs) |out| if (out.is_error) {+ failed += 1;+ };+ if (telemetry.g_telem) |t| t.workflowEvent(stages.len, items.len * stages.len, failed, @intCast(@max(0, wf_start.untilNow(ctx.io, .awake).toMilliseconds())));++ var aw: Io.Writer.Allocating = .init(arena);+ for (item_strs, outputs) |item, out| {+ try aw.writer.print("### {s}{s}\n{s}\n\n", .{ item, if (out.is_error) " (failed)" else "", out.text });+ }+ return .{ .text = try gpa.dupe(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n")) };+}++test "pipelineEstimate prices a chain per item, so a wide pipeline is not free" {+ // The study's refactor run: 4 items x 2 off-vocabulary stages. At the+ // median role cost that is 24 calls, which does not fit a cap-30 pool+ // once the landing reserve (6) is held back from the ~27 that remain.+ const roles = [_][]const u8{ "", "" };+ try std.testing.expectEqual(@as(u64, 24), pipelineEstimate(4, &roles));+ try std.testing.expect(!phase_budget.Ledger.init(30).fits(27, 24));+ // Two items over the same chain does fit, and should.+ try std.testing.expectEqual(@as(u64, 12), pipelineEstimate(2, &roles));+ try std.testing.expect(phase_budget.Ledger.init(30).fits(27, 12));+}diff --git a/src/workflow_progress.zig b/src/workflow_progress.zigindex 1e02035a..539af803 100644--- a/src/workflow_progress.zig+++ b/src/workflow_progress.zig@@ -175,6 +175,17 @@ pub fn buildAbortText(arena: Allocator, labels: []const []const u8, details: []creturn aw.writer.buffered();}+/// Join two optional manifest notes with a newline, dropping empties. The+/// tally carries ONE note slot and a phase can now produce two facts worth+/// reporting (its diversity measurement and its duplicate collapse), so they+/// are composed here rather than growing the struct — the manifest is prose+/// for the root, not a schema.+pub fn joinNotes(arena: Allocator, a: []const u8, b: []const u8) []const u8 {+ if (a.len == 0) return b;+ if (b.len == 0) return a;+ return std.fmt.allocPrint(arena, "{s}\n{s}", .{ a, b }) catch a;+}+/// Build the trailing "## workflow" manifest block from one tally per phase —/// currently the only way the orchestrator learns a phase was skipped, or/// that a synthesis stage is about to work from partial (some-tasks-failed)@@ -211,10 +222,24 @@ test "workflow_progress (#63): a phase transition emits structured state, not ju// A phase whose task entries are not objects returns AFTER the phase-start// emit and BEFORE any subagent is spawned, so this drives the real// execWorkflow call site with no network and no fan-out.+ //+ // The escalation gate now sits in front of that loop and would decline a+ // two-task fan-out for an ask naming no files at all (rung R0, which is+ // the right answer and has its own tests). Give it an audit-class ask so+ // it admits and the phase actually starts — this test is about the #63+ // event, not about the ladder.+ shapes.noteRawAsk("thoroughly audit every file in this repository for security bugs");var ctx: tools.ToolCtx = undefined;ctx.gpa = std.testing.allocator;ctx.io = std.testing.io;ctx.from_sub = false;+ // The escalation gate reads the shared pool, the tracer and the root's+ // model before the phase loop runs, so those have to be real nulls here+ // rather than the `undefined` the rest of this stub relies on.+ ctx.run_budget = null;+ ctx.tracer = null;+ ctx.agent_cwd = null;+ 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);std.testing.allocator.free(out.text);