Skip to content

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

Python

feat(#376): route workflow phases with the learned policy, one seat per phase

justrachd556690a4e26
diff --git a/src/agent_eval.zig b/src/agent_eval.zig
index 1abb4c96..ab2ea51a 100644
--- a/src/agent_eval.zig
+++ b/src/agent_eval.zig
@@ -208,7 +208,10 @@ pub fn runEval(self: *Agent, note: []const u8) !ExecResult {
const sig = signScore(genome, "", s01, run_id, "", "", esh, niche, pclass);
const sig_s: []const u8 = if (scoring.g_score_key != null) &sig else "";
var provbuf: [512]u8 = undefined;
- const prov = std.fmt.bufPrint(&provbuf, "{s}\t{s}\t{s}\t{s}\t{s}", .{ "", "", esh, pclass, niche }) catch "";
+ // #376: the 7th component is the routing STRATUM (index 5
+ // is the phase slot an eval loop never has). Same layout
+ // as scoreVariants' tuple, so one collector reads both.
+ const prov = std.fmt.bufPrint(&provbuf, "{s}\t{s}\t{s}\t{s}\t{s}\t{s}\t{s}", .{ "", "", esh, pclass, niche, "", route_policy.stratumOf(self.provider.model) }) catch "";
t.scoreEvent(genome, "", s01, run_id, sig_s, prov);
t.fleetEvent("submit", niche, genome, "", pclass, esh, 0, "");
}
diff --git a/src/fitness_strata.zig b/src/fitness_strata.zig
new file mode 100644
index 00000000..e57e59ee
--- /dev/null
+++ b/src/fitness_strata.zig
@@ -0,0 +1,189 @@
+//! #376 — rung-stratified fitness folding over the local DGM archive.
+//!
+//! `/agents promote` (fleet.promoteAgents) is the one CROSS-RUN comparison of
+//! prompt genomes the harness makes locally: for each MAP-Elites niche it
+//! pools every `kind:"score"` row filed under a genome's fingerprint, means
+//! them, and crowns the highest. Until #376 that pooling ignored WHICH model
+//! produced each score, which was safe only because #290 froze the model
+//! inside a scored phase — a genome could not have been measured on a
+//! different rung than its rival.
+//!
+//! #376 lifts that freeze one level up (route_phase.zig seats a whole phase
+//! at once), so two genomes in the same niche CAN come from runs that sat on
+//! different rungs. Pooling them would credit the cheaper/stronger model's
+//! advantage to the prompt — the exact attribution error #290 exists to
+//! prevent. This module is the other half of that trade: it ranks genomes
+//! only against genomes measured in the SAME stratum, i.e. on the same
+//! resolved model (route_policy.stratumOf).
+//!
+//! WHICH STRATUM SPEAKS FOR A NICHE. The one that is actually a comparison:
+//! most distinct genomes ranked, then most observations behind the winner,
+//! then first seen. A stratum with a single genome is not evidence that its
+//! prompt is better than anything, so it only wins a niche nobody else
+//! measured.
+//!
+//! PRE-#376 ROWS. A score row that names no model — everything written
+//! before #372's self-describing rows, and mainloop /score's, which never
+//! recorded one — folds into the `unknown` stratum and is ranked only against
+//! other unknowns. It is never merged into a measured stratum: an unrecorded
+//! model is missing information, not agreement.
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+
+const util = @import("util.zig");
+const strFieldObj = util.strFieldObj;
+const policy = @import("route_policy.zig");
+
+/// One niche's promotable winner: the best genome inside the best-evidenced
+/// stratum, plus the stratum it was measured in (so the persona file can say
+/// what its score actually means).
+pub const Champion = struct {
+ niche: []const u8,
+ stratum: []const u8,
+ sha: []const u8,
+ text: []const u8,
+ mean: f64 = 0,
+ /// Observations behind THIS genome in that stratum.
+ n: u32 = 0,
+ /// Distinct genomes ranked in that stratum — 1 means "no comparison was
+ /// available", which is why the stratum tie-break prefers a bigger field.
+ rivals: u32 = 0,
+};
+
+/// What the archive knows about one prompt fingerprint, independent of the
+/// model it ran on: its captured text and its MAP-Elites niche.
+const Genome = struct { sha: []const u8, text: []const u8 = "", niche: []const u8 = "" };
+
+/// Pooled score for one (genome, stratum) pair — the unit that may be meaned.
+const Obs = struct { sha: []const u8, stratum: []const u8, sum: f64 = 0, n: u32 = 0 };
+
+/// Per-(niche, stratum) leader, built in one pass over `Obs`.
+const Group = struct {
+ niche: []const u8,
+ stratum: []const u8,
+ sha: []const u8 = "",
+ text: []const u8 = "",
+ mean: f64 = 0,
+ n: u32 = 0,
+ rivals: u32 = 0,
+};
+
+fn genomeAt(a: Allocator, list: *std.ArrayList(Genome), sha: []const u8) *Genome {
+ for (list.items) |*g| if (std.mem.eql(u8, g.sha, sha)) return g;
+ list.append(a, .{ .sha = a.dupe(u8, sha) catch sha }) catch {};
+ return &list.items[list.items.len - 1];
+}
+
+fn obsAt(a: Allocator, list: *std.ArrayList(Obs), sha: []const u8, stratum: []const u8) *Obs {
+ for (list.items) |*o| {
+ if (std.mem.eql(u8, o.sha, sha) and std.mem.eql(u8, o.stratum, stratum)) return o;
+ }
+ list.append(a, .{ .sha = a.dupe(u8, sha) catch sha, .stratum = a.dupe(u8, stratum) catch stratum }) catch {};
+ return &list.items[list.items.len - 1];
+}
+
+fn groupAt(a: Allocator, list: *std.ArrayList(Group), niche: []const u8, stratum: []const u8) *Group {
+ for (list.items) |*g| {
+ if (std.mem.eql(u8, g.niche, niche) and std.mem.eql(u8, g.stratum, stratum)) return g;
+ }
+ list.append(a, .{ .niche = niche, .stratum = stratum }) catch {};
+ return &list.items[list.items.len - 1];
+}
+
+/// A stratum outranks another for the same niche when it ranked more distinct
+/// genomes (a real tournament beats a walkover), then on the evidence behind
+/// its winner. Deliberately NOT on the winning mean: a lucky single run on a
+/// stronger model must not outrank a measured field on a weaker one — that is
+/// the confound this module exists to keep out.
+fn betterStratum(a: Group, b: Group) bool {
+ if (a.rivals != b.rivals) return a.rivals > b.rivals;
+ return a.n > b.n;
+}
+
+/// Fold `archive` (concatenated .graff/trajectories JSONL) into one champion
+/// per niche. Genome text comes from `kind:"prompt"` rows, scores from
+/// `kind:"score"` rows stratified by their `model` column, and the niche from
+/// any other row that names one — the same three sources fleet.promoteAgents
+/// read before #376, with the score axis split by stratum.
+pub fn champions(arena: Allocator, archive: []const u8) []Champion {
+ var genomes: std.ArrayList(Genome) = .empty;
+ var obs: std.ArrayList(Obs) = .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, .{ .allocate = .alloc_always }) catch continue;
+ if (v != .object) continue;
+ const o = v.object;
+ const kind = strFieldObj(o, "kind") orelse continue;
+ const sha = strFieldObj(o, "prompt_sha") orelse "";
+ if (sha.len == 0) continue;
+ if (std.mem.eql(u8, kind, "prompt")) {
+ if (strFieldObj(o, "text")) |txt| genomeAt(arena, &genomes, sha).text = arena.dupe(u8, txt) catch "";
+ } else if (std.mem.eql(u8, kind, "score")) {
+ const sv = o.get("score") orelse continue;
+ const val: f64 = switch (sv) {
+ .float => sv.float,
+ .integer => @floatFromInt(sv.integer),
+ else => continue,
+ };
+ const slot = obsAt(arena, &obs, sha, policy.stratumOf(strFieldObj(o, "model") orelse ""));
+ slot.sum += val;
+ slot.n += 1;
+ } else if (strFieldObj(o, "niche")) |nz| {
+ if (nz.len > 0) genomeAt(arena, &genomes, sha).niche = arena.dupe(u8, nz) catch "";
+ }
+ }
+
+ // Pass A — the leader of every (niche, stratum) pair. A genome with no
+ // captured text is unpromotable (nothing to write into the persona file)
+ // and an uncelled one has no niche to promote into, exactly as before.
+ var groups: std.ArrayList(Group) = .empty;
+ for (obs.items) |ob| {
+ if (ob.n == 0) continue;
+ const g = for (genomes.items) |*x| {
+ if (std.mem.eql(u8, x.sha, ob.sha)) break x;
+ } else continue;
+ if (g.text.len == 0 or g.niche.len == 0) continue;
+ const mean = ob.sum / @as(f64, @floatFromInt(ob.n));
+ const slot = groupAt(arena, &groups, g.niche, ob.stratum);
+ slot.rivals += 1;
+ if (slot.sha.len == 0 or mean > slot.mean) {
+ slot.sha = ob.sha;
+ slot.text = g.text;
+ slot.mean = mean;
+ slot.n = ob.n;
+ }
+ }
+
+ // Pass B — one stratum per niche, and with it one champion.
+ var out: std.ArrayList(Champion) = .empty;
+ for (groups.items) |seed| {
+ if (seed.sha.len == 0) continue;
+ var done = false;
+ for (out.items) |c| if (std.mem.eql(u8, c.niche, seed.niche)) {
+ done = true;
+ };
+ if (done) continue;
+ var win = seed;
+ for (groups.items) |other| {
+ if (other.sha.len == 0 or !std.mem.eql(u8, other.niche, seed.niche)) continue;
+ if (betterStratum(other, win)) win = other;
+ }
+ out.append(arena, .{
+ .niche = win.niche,
+ .stratum = win.stratum,
+ .sha = win.sha,
+ .text = win.text,
+ .mean = win.mean,
+ .n = win.n,
+ .rivals = win.rivals,
+ }) catch return out.items;
+ }
+ return out.items;
+}
+
+test {
+ _ = @import("fitness_strata_tests.zig");
+}
diff --git a/src/fitness_strata_tests.zig b/src/fitness_strata_tests.zig
new file mode 100644
index 00000000..bad15bf9
--- /dev/null
+++ b/src/fitness_strata_tests.zig
@@ -0,0 +1,152 @@
+//! Tests for #376 increment 1 — rung stratification of the local fitness
+//! archive. Split out of fitness_strata.zig for the 600-line cap; wired into
+//! the test root through fitness_strata.zig's own `test {}` block and
+//! test_hooks.zig.
+
+const std = @import("std");
+
+const strata = @import("fitness_strata.zig");
+const policy = @import("route_policy.zig");
+
+/// One niche ("reviewer"), four genomes, three routing strata.
+///
+/// A, B — ranked against each other on gpt-5.6-luna (a real comparison)
+/// C — a lone genome that happened to run on the DEARER gpt-5.6-terra
+/// D — pre-#376 rows: scored, but naming no model at all
+///
+/// Pooling every score under a prompt_sha (what promoteAgents did before
+/// #376) crowns D (1.00), then C (0.95) — i.e. the two rows that were never
+/// compared to anything. Stratified, the only stratum that actually ran a
+/// tournament is luna's, and A wins it on 0.90.
+const mixed_archive =
+ \\{"kind":"prompt","prompt_sha":"aa","text":"genome A"}
+ \\{"kind":"workflow_task","prompt_sha":"aa","niche":"reviewer"}
+ \\{"kind":"score","prompt_sha":"aa","score":0.9,"model":"gpt-5.6-luna"}
+ \\{"kind":"score","prompt_sha":"aa","score":0.9,"model":"gpt-5.6-luna"}
+ \\{"kind":"score","prompt_sha":"aa","score":0.9,"model":"gpt-5.6-luna"}
+ \\{"kind":"prompt","prompt_sha":"bb","text":"genome B"}
+ \\{"kind":"workflow_task","prompt_sha":"bb","niche":"reviewer"}
+ \\{"kind":"score","prompt_sha":"bb","score":0.6,"model":"gpt-5.6-luna"}
+ \\{"kind":"score","prompt_sha":"bb","score":0.6,"model":"gpt-5.6-luna"}
+ \\{"kind":"score","prompt_sha":"bb","score":0.6,"model":"gpt-5.6-luna"}
+ \\{"kind":"prompt","prompt_sha":"cc","text":"genome C"}
+ \\{"kind":"workflow_task","prompt_sha":"cc","niche":"reviewer"}
+ \\{"kind":"score","prompt_sha":"cc","score":0.95,"model":"gpt-5.6-terra"}
+ \\{"kind":"score","prompt_sha":"cc","score":0.95,"model":"gpt-5.6-terra"}
+ \\{"kind":"score","prompt_sha":"cc","score":0.95,"model":"gpt-5.6-terra"}
+ \\{"kind":"prompt","prompt_sha":"dd","text":"genome D"}
+ \\{"kind":"workflow_task","prompt_sha":"dd","niche":"reviewer"}
+ \\{"kind":"score","prompt_sha":"dd","score":1}
+ \\{"kind":"score","prompt_sha":"dd","score":1}
+ \\{"kind":"score","prompt_sha":"dd","score":1}
+;
+
+test "#376: a fitness row's stratum is the resolved model, and a missing one is `unknown`" {
+ try std.testing.expectEqualStrings("gpt-5.6-luna", policy.stratumOf("gpt-5.6-luna"));
+ try std.testing.expectEqualStrings("gpt-5.6-terra", policy.stratumOf("gpt-5.6-terra"));
+ // The two models scoring.providerClass cannot tell apart (both "frontier")
+ // are distinct strata here — that separation is the whole increment.
+ try std.testing.expect(!std.mem.eql(u8, policy.stratumOf("gpt-5.6-sol"), policy.stratumOf("gpt-5.6-luna")));
+ // A row that names no model is its own bucket, never an empty string that
+ // would compare equal to another absent one by accident.
+ try std.testing.expectEqualStrings("unknown", policy.stratumOf(""));
+ try std.testing.expectEqualStrings(policy.stratum_unknown, policy.stratumOf(""));
+}
+
+test "#376: genomes are ranked inside one stratum, never across rungs" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const champs = strata.champions(arena_state.allocator(), mixed_archive);
+
+ try std.testing.expectEqual(@as(usize, 1), champs.len); // one champion per niche
+ const c = champs[0];
+ try std.testing.expectEqualStrings("reviewer", c.niche);
+ // The stratum that actually ran a tournament speaks for the niche...
+ try std.testing.expectEqualStrings("gpt-5.6-luna", c.stratum);
+ try std.testing.expectEqual(@as(u32, 2), c.rivals);
+ // ...and its winner is the better PROMPT, not the higher raw number: both
+ // the 0.95 (dearer model) and the 1.00 (unrecorded model) lose to 0.90
+ // because neither was ever compared to anything.
+ try std.testing.expectEqualStrings("aa", c.sha);
+ try std.testing.expectEqualStrings("genome A", c.text);
+ try std.testing.expectApproxEqAbs(@as(f64, 0.9), c.mean, 1e-9);
+ try std.testing.expectEqual(@as(u32, 3), c.n);
+}
+
+test "#376: pre-#376 rows form their own `unknown` stratum, never merged into a measured one" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ // The exact rows every archive written before #372's self-describing
+ // capture contains: a score with no model column at all. Alone, they still
+ // promote (nothing changes for a legacy-only archive) — and they say so,
+ // rather than claiming a rung nobody recorded.
+ const legacy =
+ \\{"kind":"prompt","prompt_sha":"aa","text":"legacy genome"}
+ \\{"kind":"child","prompt_sha":"aa","niche":"researcher"}
+ \\{"kind":"score","prompt_sha":"aa","score":0.4}
+ \\{"kind":"score","prompt_sha":"aa","score":0.6}
+ ;
+ const only_legacy = strata.champions(a, legacy);
+ try std.testing.expectEqual(@as(usize, 1), only_legacy.len);
+ try std.testing.expectEqualStrings("unknown", only_legacy[0].stratum);
+ try std.testing.expectApproxEqAbs(@as(f64, 0.5), only_legacy[0].mean, 1e-9);
+
+ // Mixed with measured rows for the SAME genome, the two never pool: the
+ // unknown half cannot inflate (or deflate) the luna half's mean.
+ const mixed =
+ \\{"kind":"prompt","prompt_sha":"aa","text":"legacy genome"}
+ \\{"kind":"child","prompt_sha":"aa","niche":"researcher"}
+ \\{"kind":"score","prompt_sha":"aa","score":0}
+ \\{"kind":"score","prompt_sha":"aa","score":0}
+ \\{"kind":"score","prompt_sha":"aa","score":1,"model":"gpt-5.6-luna"}
+ \\{"kind":"score","prompt_sha":"aa","score":1,"model":"gpt-5.6-luna"}
+ ;
+ const both = strata.champions(a, mixed);
+ try std.testing.expectEqual(@as(usize, 1), both.len);
+ // Pooled, this genome would read 0.5. Each stratum keeps its own truth,
+ // and the tie between two one-genome strata is broken by first-seen order,
+ // which is the unknown one here — so the reported mean is 0, not 0.5.
+ try std.testing.expectEqualStrings("unknown", both[0].stratum);
+ try std.testing.expectApproxEqAbs(@as(f64, 0), both[0].mean, 1e-9);
+ try std.testing.expectEqual(@as(u32, 2), both[0].n);
+}
+
+test "#376: an unscoreable or uncelled genome still promotes nothing" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ // No captured text → nothing to write into a persona file. No niche → no
+ // cell to write it into. Both were already true before #376.
+ const no_text =
+ \\{"kind":"child","prompt_sha":"aa","niche":"reviewer"}
+ \\{"kind":"score","prompt_sha":"aa","score":0.9,"model":"gpt-5.6-luna"}
+ ;
+ try std.testing.expectEqual(@as(usize, 0), strata.champions(a, no_text).len);
+ const no_niche =
+ \\{"kind":"prompt","prompt_sha":"aa","text":"g"}
+ \\{"kind":"score","prompt_sha":"aa","score":0.9,"model":"gpt-5.6-luna"}
+ ;
+ try std.testing.expectEqual(@as(usize, 0), strata.champions(a, no_niche).len);
+ try std.testing.expectEqual(@as(usize, 0), strata.champions(a, "").len);
+ try std.testing.expectEqual(@as(usize, 0), strata.champions(a, "not json\n{}\n").len);
+}
+
+test "#376: separate niches promote separately, each inside its own stratum" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const two =
+ \\{"kind":"prompt","prompt_sha":"aa","text":"A"}
+ \\{"kind":"child","prompt_sha":"aa","niche":"reviewer"}
+ \\{"kind":"score","prompt_sha":"aa","score":0.7,"model":"gpt-5.6-luna"}
+ \\{"kind":"prompt","prompt_sha":"bb","text":"B"}
+ \\{"kind":"child","prompt_sha":"bb","niche":"researcher"}
+ \\{"kind":"score","prompt_sha":"bb","score":0.8,"model":"gpt-5.6-terra"}
+ ;
+ const champs = strata.champions(arena_state.allocator(), two);
+ try std.testing.expectEqual(@as(usize, 2), champs.len);
+ for (champs) |c| {
+ try std.testing.expectEqualStrings(if (std.mem.eql(u8, c.niche, "reviewer")) "gpt-5.6-luna" else "gpt-5.6-terra", c.stratum);
+ }
+}
diff --git a/src/fleet.zig b/src/fleet.zig
index 8ccca9fd..6ae10ef8 100644
--- a/src/fleet.zig
+++ b/src/fleet.zig
@@ -13,9 +13,8 @@ const Allocator = std.mem.Allocator;
const ansi = @import("ansi.zig");
const style = &ansi.style;
-const util = @import("util.zig");
-const strFieldObj = util.strFieldObj;
const learn_store = @import("learn_store.zig");
+const fitness_strata = @import("fitness_strata.zig"); // #376 rung-stratified promotion fold
const root = @import("main.zig");
const trace = @import("trace.zig");
@@ -212,7 +211,9 @@ fn loadAgentDir(io: Io, arena: Allocator, list: *std.ArrayList(AgentType), dir_p
/// highest-mean-scoring genome that has captured text into the chosen tier
/// (personal ~/.harness/agents or private ./.harness/agents) as <niche>.md. No
/// backend: your own scored runs become your built-in personas. Returns the
-/// number of niches promoted.
+/// number of niches promoted. Since #376 the ranking happens inside one
+/// routing stratum (fitness_strata.zig), so a genome measured on a cheaper
+/// rung is never scored against one measured on a dearer one.
pub fn promoteAgents(io: Io, gpa: Allocator, out: *Io.Writer, home: ?[]const u8, personal: bool, auto: bool) usize {
var arena_state = std.heap.ArenaAllocator.init(gpa);
defer arena_state.deinit();
@@ -224,42 +225,14 @@ pub fn promoteAgents(io: Io, gpa: Allocator, out: *Io.Writer, home: ?[]const u8,
return 0;
}
- const Cell = struct { sha: []const u8, text: []const u8, niche: []const u8, sum: f64, n: u32 };
- var cells: std.ArrayList(Cell) = .empty;
- const cell = struct {
- fn at(a: Allocator, list: *std.ArrayList(Cell), sha: []const u8) *Cell {
- for (list.items) |*c| if (std.mem.eql(u8, c.sha, sha)) return c;
- list.append(a, .{ .sha = a.dupe(u8, sha) catch sha, .text = "", .niche = "", .sum = 0, .n = 0 }) catch {};
- return &list.items[list.items.len - 1];
- }
- }.at;
-
- var it = std.mem.splitScalar(u8, data, '\n');
- while (it.next()) |ln| {
- const t = std.mem.trim(u8, ln, " \t\r");
- if (t.len == 0) continue;
- const v = std.json.parseFromSliceLeaky(Value, arena, t, .{ .allocate = .alloc_always }) catch continue;
- if (v != .object) continue;
- const o = v.object;
- const kind = strFieldObj(o, "kind") orelse continue;
- const sha = strFieldObj(o, "prompt_sha") orelse "";
- if (sha.len == 0) continue;
- if (std.mem.eql(u8, kind, "prompt")) {
- if (strFieldObj(o, "text")) |txt| cell(arena, &cells, sha).text = arena.dupe(u8, txt) catch "";
- } else if (std.mem.eql(u8, kind, "score")) {
- const sv = o.get("score") orelse continue;
- const val: f64 = switch (sv) {
- .float => sv.float,
- .integer => @floatFromInt(sv.integer),
- else => continue,
- };
- const c = cell(arena, &cells, sha);
- c.sum += val;
- c.n += 1;
- } else if (strFieldObj(o, "niche")) |nz| {
- if (nz.len > 0) cell(arena, &cells, sha).niche = arena.dupe(u8, nz) catch "";
- }
- }
+ // #376 — one champion per niche, ranked WITHIN a routing stratum. Phase
+ // workers may now be seated on a learned model (route_phase.zig), so two
+ // genomes in one niche can come from runs on different rungs; pooling them
+ // would credit the model's advantage to the prompt, which is exactly the
+ // attribution #290 protects. fitness_strata.champions does the fold that
+ // used to live here, split by the resolved model each score was measured
+ // on (rows that name none are their own `unknown` stratum, never merged).
+ const champs = fitness_strata.champions(arena, data);
// Resolve + create the target tier dir (createDir is one level).
const dir = if (personal) blk: {
@@ -275,28 +248,11 @@ pub fn promoteAgents(io: Io, gpa: Allocator, out: *Io.Writer, home: ?[]const u8,
};
Io.Dir.cwd().createDir(io, dir, .default_dir) catch {};
- // For each niche, write the genome with the best mean score (text required).
- var done: std.ArrayList([]const u8) = .empty;
+ // Write each niche's stratified champion (text and a niche are required,
+ // which champions() has already enforced).
var promoted: usize = 0;
- for (cells.items) |*seed| {
- if (seed.niche.len == 0 or seed.text.len == 0 or seed.n == 0) continue;
- var already = false;
- for (done.items) |d| if (std.mem.eql(u8, d, seed.niche)) {
- already = true;
- break;
- };
- if (already) continue;
- var champ = seed;
- var champ_mean = seed.sum / @as(f64, @floatFromInt(seed.n));
- for (cells.items) |*other| {
- if (other.text.len == 0 or other.n == 0) continue;
- if (!std.mem.eql(u8, other.niche, seed.niche)) continue;
- const m = other.sum / @as(f64, @floatFromInt(other.n));
- if (m > champ_mean) {
- champ = other;
- champ_mean = m;
- }
- }
+ for (champs) |champ| {
+ const champ_mean = champ.mean;
const path = std.fmt.allocPrint(arena, "{s}/{s}.md", .{ dir, champ.niche }) catch continue;
// Auto (green-eval) promotion never clobbers a hand-written persona:
// only a file promotion itself wrote is fair game. Manual /agents
@@ -308,15 +264,16 @@ pub fn promoteAgents(io: Io, gpa: Allocator, out: *Io.Writer, home: ?[]const u8,
// (isolation, #292's model/tier) is policy, not something the judge
// scored, so carry it across the rewrite instead of dropping it.
const policy = @import("subagent_pin.zig").personaPolicyFrontmatter(arena, champ.niche);
- const content = std.fmt.allocPrint(arena, "---\nname: {s}\ndescription: promoted local champion (mean {d:.2} over {d} run(s), sha {s})\nscore: {d:.4}\n{s}---\n{s}\n", .{ champ.niche, champ_mean, champ.n, champ.sha, champ_mean, policy, champ.text }) catch continue;
+ // #376: the stratum is part of what the score MEANS — "best on this
+ // model", not "best in the abstract" — so the persona records it.
+ const content = std.fmt.allocPrint(arena, "---\nname: {s}\ndescription: promoted local champion (mean {d:.2} over {d} run(s) on {s}, sha {s})\nscore: {d:.4}\n{s}---\n{s}\n", .{ champ.niche, champ_mean, champ.n, champ.stratum, champ.sha, champ_mean, policy, champ.text }) catch continue;
const f = Io.Dir.cwd().createFile(io, path, .{}) catch continue;
defer f.close(io);
var wbuf: [4096]u8 = undefined;
var fw = f.writer(io, &wbuf);
fw.interface.writeAll(content) catch continue;
fw.interface.flush() catch {};
- out.print(" {s}✓{s} {s}{s}{s} → {s} {s}(mean {d:.2}, n={d}){s}\n", .{ style.green, style.reset, style.accent, champ.niche, style.reset, path, style.dim, champ_mean, champ.n, style.reset }) catch {};
- done.append(arena, champ.niche) catch {};
+ out.print(" {s}✓{s} {s}{s}{s} → {s} {s}(mean {d:.2}, n={d}, on {s}){s}\n", .{ style.green, style.reset, style.accent, champ.niche, style.reset, path, style.dim, champ_mean, champ.n, champ.stratum, style.reset }) catch {};
promoted += 1;
}
if (promoted == 0) out.print(" {s}nothing to promote — need scored, niche-tagged genomes (spawn personas via subagent agent:\"<niche>\", then score them){s}\n", .{ style.dim, style.reset }) catch {};
diff --git a/src/route_phase.zig b/src/route_phase.zig
new file mode 100644
index 00000000..21d24ab9
--- /dev/null
+++ b/src/route_phase.zig
@@ -0,0 +1,144 @@
+//! #376 — ONE learned seat per workflow phase.
+//!
+//! #372 gave every phase worker full routing visibility, and made it
+//! CONTRIBUTE observations to the learned (shape, role) tier policy. It
+//! deliberately changed none of their models: #290's firewall ("workflow
+//! tasks take no per-task pins") stood, because scoreVariants ranks the
+//! prompt variants of one phase against each other and files the winner under
+//! the prompt fingerprint. A phase whose tasks could differ in model would
+//! attribute the model's effect to the genome — and nothing downstream could
+//! have caught it, since scoring.providerClass buckets gpt-5.6-sol, -terra
+//! and -luna identically (route_policy.stratumOf tells that story in full).
+//!
+//! The confound is PER-TASK variation, not the model. This module applies the
+//! #372 policy exactly once for a whole phase:
+//!
+//! * every worker in the phase resolves to the SAME model, so within-phase
+//! prompt comparability — the thing #290 protects — is untouched;
+//! * across runs the rung is now recorded on every fitness row and the
+//! cross-run genome comparison stratifies on it (fitness_strata.zig), so
+//! the axis this module varies is exactly the axis that became visible.
+//!
+//! WHAT MAY MOVE A PHASE, AND WHAT MAY NOT.
+//!
+//! explicit user pin > persona > session default > learned policy
+//!
+//! So the seat is offered ONLY when this session's worker model came from the
+//! automatic #291 ladder descent (`source=ladder`). An explicit
+//! --subagent-model / --subagent-provider, or a plain inherit-the-root, is a
+//! human decision about which model does the work and is never overridden by
+//! evidence. Within that opening the #372 guardrails all still apply: the
+//! learned answer must DOMINATE the model the phase would otherwise have used
+//! (bench_priors' Pareto sense — at least its quality for strictly less
+//! money), the cost ceiling is re-cleared for the swapped model, and the swap
+//! is provider-local by construction (Provider.withModel), so cross-provider
+//! consent and the sub-first flat-rate routing in subagent_pin are reached by
+//! nothing here.
+//!
+//! A phase with no single role — an off-vocabulary title whose tasks name
+//! different persona slots — has no cell to consult and keeps today's
+//! behavior exactly, as does every phase in an archive with no evidence.
+
+const std = @import("std");
+
+const Provider = @import("provider.zig").Provider;
+const policy = @import("route_policy.zig");
+const route_trace = @import("route_trace.zig");
+const pin_mod = @import("subagent_pin.zig");
+const shapes = @import("shapes.zig");
+
+pub const Cell = policy.Cell;
+pub const Shape = policy.Shape;
+pub const Source = policy.Source;
+
+/// One phase's routing decision, resolved once and shared by every worker in
+/// it. `pin` is what the spawn path receives: non-null ONLY when the learned
+/// policy re-seated the phase, so an unobserved phase still hands runSub the
+/// null it handed it before #376.
+pub const Seat = struct {
+ /// The model every worker in this phase runs on.
+ provider: Provider,
+ /// The re-seat, or null to keep the session default.
+ pin: ?Provider = null,
+ shape: Shape = .adhoc,
+ /// The phase title the root model authored — the trace's role source, and
+ /// the label scoreVariants judges against.
+ title: []const u8 = "",
+ /// The one canonical slot every worker in this phase reports, "" when the
+ /// phase has no single role (and therefore no cell to route on).
+ role: []const u8 = "",
+ /// What decided the model when the learned policy did not: `ladder` for
+ /// the #291 descent, `session-default` for an explicit pin or a plain
+ /// inherit. Exactly what #372 reported for these workers.
+ base_source: Source = .session_default,
+
+ /// The (shape, role) cell one worker files its score under. Identical for
+ /// every worker of a routed phase by construction: `uniformRole` only
+ /// yields a role when policy.roleOf agrees on it for every task.
+ pub fn cellOf(self: Seat, niche: []const u8) Cell {
+ return .{ .shape = self.shape, .role = policy.roleOf(self.title, niche) };
+ }
+
+ /// The #372 `source` for one worker of this phase. A phase the policy
+ /// moved reports `learned-policy` for ALL of its workers — that is the
+ /// decision that actually chose their model, and reporting it per worker
+ /// is what keeps the trace honest about a phase-level choice.
+ pub fn sourceFor(self: Seat, has_override: bool) Source {
+ if (self.pin != null) return .learned_policy;
+ return if (has_override) .workflow_override else self.base_source;
+ }
+};
+
+/// The one role a whole phase can be routed under: the phase title's own
+/// canonical slot when it names one (policy.roleOf then reports it for every
+/// task regardless of niche), else the slot every task's niche agrees on,
+/// else "" — no single role, no phase cell, no re-seating.
+pub fn uniformRole(title: []const u8, niches: []const []const u8) []const u8 {
+ const from_title = shapes.canonicalSlot(title);
+ if (from_title.len > 0) return from_title;
+ if (niches.len == 0) return "";
+ const first = shapes.canonicalSlot(niches[0]);
+ if (first.len == 0) return "";
+ for (niches[1..]) |n| {
+ if (!std.mem.eql(u8, shapes.canonicalSlot(n), first)) return "";
+ }
+ return first;
+}
+
+/// Resolve the seat for one workflow phase. `base` is the provider every
+/// worker would have used before #376 (subagent_run.childProvider's answer);
+/// `session_pinned` is whether the session named a worker provider at all,
+/// the same bit route_trace.sessionSource reads.
+pub fn forPhase(
+ base: Provider,
+ shape: Shape,
+ title: []const u8,
+ niches: []const []const u8,
+ session_pinned: bool,
+) Seat {
+ var seat: Seat = .{
+ .provider = base,
+ .shape = shape,
+ .title = title,
+ .role = uniformRole(title, niches),
+ .base_source = route_trace.sessionSource(session_pinned),
+ };
+ // Only the automatic ladder descent is the policy's to improve on; an
+ // explicit pin and a plain inherit are the user's own choice.
+ if (seat.base_source != .ladder or seat.role.len == 0) return seat;
+ // The baseline a challenger must dominate is the model this phase would
+ // otherwise have run — so the comparison is against reality, not against
+ // a rung nobody was going to use.
+ const learned = policy.learnedRung(base.id, .{ .shape = shape, .role = seat.role }, base.model) orelse return seat;
+ // Re-clear the cost ceiling for the swapped model: learning may descend
+ // price, never escalate it, and a swap that somehow fails the ceiling is
+ // dropped rather than failing the phase.
+ if (!pin_mod.rungAffordable(base.model, learned)) return seat;
+ seat.pin = base.withModel(learned);
+ seat.provider = seat.pin.?;
+ return seat;
+}
+
+test {
+ _ = @import("route_phase_tests.zig");
+}
diff --git a/src/route_phase_tests.zig b/src/route_phase_tests.zig
new file mode 100644
index 00000000..759bd25e
--- /dev/null
+++ b/src/route_phase_tests.zig
@@ -0,0 +1,266 @@
+//! Tests for #376 increment 2 — one learned seat per workflow phase.
+//! Split out of route_phase.zig for the 600-line cap; reached from its
+//! `test {}` block and from test_hooks.zig.
+
+const std = @import("std");
+const Io = std.Io;
+
+const phase = @import("route_phase.zig");
+const policy = @import("route_policy.zig");
+const route_trace = @import("route_trace.zig");
+const bench = @import("bench_priors.zig");
+const selection = @import("subagent_selection.zig");
+const pin_mod = @import("subagent_pin.zig");
+const tier_ladder = @import("subagent_tier_ladder.zig");
+const Provider = @import("provider.zig").Provider;
+
+fn codex(model: []const u8) Provider {
+ return .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "sk-test", .model = model, .context = 272_000 };
+}
+
+/// The same synthetic sheet #372's demonstration uses: on the SHEET ALONE
+/// terra outscores luna and is not dominated by it, so anything that moves
+/// below is provably the lived evidence talking, not the priors.
+const demo_sheet = [_]bench.Entry{
+ .{ .model = "gpt-5.6-terra", .effort = "medium", .score = 0.60, .cost = 0.9 }, // effective $0.90
+ .{ .model = "gpt-5.6-luna", .effort = "max", .score = 0.40, .cost = 0.61 }, // effective $0.61
+};
+
+/// Lived scores from a `research` shape's `sweep` phase: the ladder's mid rung
+/// (terra) did badly there, the cheap rung (luna) did well. Exactly the rows
+/// route_trace.captureScore writes — no recipe rows, so bench_priors' own
+/// #374 sheet feedback is deliberately NOT what is being exercised here.
+const demo_archive =
+ \\{"kind":"score","prompt_sha":"aa","score":0.2,"shape":"research","role":"sweep","tier":"mid","model":"gpt-5.6-terra"}
+ \\{"kind":"score","prompt_sha":"aa","score":0.2,"shape":"research","role":"sweep","tier":"mid","model":"gpt-5.6-terra"}
+ \\{"kind":"score","prompt_sha":"aa","score":0.2,"shape":"research","role":"sweep","tier":"mid","model":"gpt-5.6-terra"}
+ \\{"kind":"score","prompt_sha":"bb","score":0.95,"shape":"research","role":"sweep","tier":"small","model":"gpt-5.6-luna"}
+ \\{"kind":"score","prompt_sha":"bb","score":0.95,"shape":"research","role":"sweep","tier":"small","model":"gpt-5.6-luna"}
+ \\{"kind":"score","prompt_sha":"bb","score":0.95,"shape":"research","role":"sweep","tier":"small","model":"gpt-5.6-luna"}
+;
+
+/// Install `demo_archive` + `demo_sheet` as the session's live policy, with
+/// the session's worker route coming from the #291 ladder descent (the one
+/// opening #376 gives the policy). Returns a restorer for `defer`.
+const Env = struct {
+ cells: []const policy.CellObs,
+ entries: []const bench.Entry,
+ ladders: []const tier_ladder.TierLadder,
+ from_ladder: bool,
+
+ fn install(arena: std.mem.Allocator, archive: []const u8, from_ladder: bool) Env {
+ const saved: Env = .{
+ .cells = policy.g_cells,
+ .entries = bench.g_entries,
+ .ladders = bench.g_ladders,
+ .from_ladder = selection.g_default_from_ladder,
+ };
+ bench.g_ladders = &.{}; // compiled ladder only, so the baseline is pinned
+ bench.g_entries = &demo_sheet;
+ policy.g_cells = policy.foldCells(arena, archive);
+ selection.g_default_from_ladder = from_ladder;
+ return saved;
+ }
+
+ fn restore(self: Env) void {
+ policy.g_cells = self.cells;
+ bench.g_entries = self.entries;
+ bench.g_ladders = self.ladders;
+ selection.g_default_from_ladder = self.from_ladder;
+ }
+};
+
+/// The two workers of a `sweep` phase, as workflow.zig hands them over: the
+/// niche is the persona name (or the phase title for an inline variant).
+const sweep_niches = [_][]const u8{ "researcher", "skeptic" };
+
+test "#376 uniformRole: a phase routes only when all of its workers agree on one role" {
+ // The phase title's own canonical slot is the role every worker reports
+ // (policy.roleOf reads the title first), whatever their niches are.
+ try std.testing.expectEqualStrings("sweep", phase.uniformRole("sweep the repo", &sweep_niches));
+ try std.testing.expectEqualStrings("sweep", phase.uniformRole("sweep the repo", &.{}));
+ // An off-vocabulary title falls back to the niches — and only when they
+ // agree, since a phase whose workers file under different cells has no
+ // single cell to route on.
+ try std.testing.expectEqualStrings("review", phase.uniformRole("do the thing", &.{ "review the diff", "review again" }));
+ try std.testing.expectEqualStrings("", phase.uniformRole("do the thing", &.{ "review the diff", "sweep the repo" }));
+ try std.testing.expectEqualStrings("", phase.uniformRole("do the thing", &.{"some-persona"}));
+ try std.testing.expectEqualStrings("", phase.uniformRole("do the thing", &.{}));
+ // Whatever it answers, it agrees with what every worker's trace reports.
+ for (sweep_niches) |n| {
+ try std.testing.expectEqualStrings(phase.uniformRole("sweep the repo", &sweep_niches), policy.roleOf("sweep the repo", n));
+ }
+}
+
+test "#376 DEMONSTRATION: an observed phase re-seats EVERY worker; an unobserved one keeps today's route" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const env = Env.install(arena_state.allocator(), demo_archive, true);
+ defer env.restore();
+
+ // The session descended the #291 ladder to terra; the (research, sweep)
+ // cell has measured luna as strictly better value there.
+ const base = codex("gpt-5.6-terra");
+ const seat = phase.forPhase(base, .research, "sweep the repo", &sweep_niches, true);
+ try std.testing.expect(seat.pin != null);
+ try std.testing.expectEqualStrings("gpt-5.6-luna", seat.provider.model);
+ try std.testing.expectEqualStrings("gpt-5.6-luna", seat.pin.?.model);
+
+ // PHASE-UNIFORM: one seat, so every worker of the phase resolves to the
+ // same model and files under the same cell — with or without a
+ // root-authored genome. That is the property #290 needs preserved.
+ for (sweep_niches) |niche| {
+ try std.testing.expectEqualStrings("gpt-5.6-luna", seat.provider.model);
+ const cell = seat.cellOf(niche);
+ try std.testing.expectEqual(policy.Shape.research, cell.shape);
+ try std.testing.expectEqualStrings("sweep", cell.role);
+ try std.testing.expectEqual(policy.Source.learned_policy, seat.sourceFor(false));
+ try std.testing.expectEqual(policy.Source.learned_policy, seat.sourceFor(true));
+ }
+
+ // An UNOBSERVED phase in the same session is untouched: same session, same
+ // ladder, no evidence for its cell — so it keeps exactly today's behavior,
+ // including today's `source` attribution.
+ const quiet = phase.forPhase(base, .feature, "implement the fix", &.{"implementer"}, true);
+ try std.testing.expect(quiet.pin == null);
+ try std.testing.expectEqualStrings("gpt-5.6-terra", quiet.provider.model);
+ try std.testing.expectEqual(policy.Source.ladder, quiet.sourceFor(false));
+ try std.testing.expectEqual(policy.Source.workflow_override, quiet.sourceFor(true));
+}
+
+test "#376: the re-seated phase's trace says learned-policy on every worker" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const env = Env.install(a, demo_archive, true);
+ defer env.restore();
+
+ var sink: Io.Writer.Allocating = .init(a);
+ route_trace.g_test_sink = &sink;
+ defer route_trace.g_test_sink = null;
+
+ // Drive the exact emission workflow.zig makes, once per worker.
+ const seat = phase.forPhase(codex("gpt-5.6-terra"), .research, "sweep the repo", &sweep_niches, true);
+ for (sweep_niches) |niche| {
+ route_trace.emitSpawnProvider(std.testing.io, null, niche, seat.provider, seat.cellOf(niche), seat.sourceFor(false), null, niche);
+ }
+
+ var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, sink.writer.buffered(), "\n"), '\n');
+ var n: usize = 0;
+ while (lines.next()) |ln| : (n += 1) {
+ const ev = try std.json.parseFromSliceLeaky(std.json.Value, a, ln, .{});
+ try std.testing.expectEqualStrings("agent_route", ev.object.get("type").?.string);
+ try std.testing.expectEqualStrings("gpt-5.6-luna", ev.object.get("resolved_model").?.string);
+ try std.testing.expectEqualStrings("learned-policy", ev.object.get("source").?.string);
+ try std.testing.expectEqualStrings("research", ev.object.get("shape").?.string);
+ try std.testing.expectEqualStrings("sweep", ev.object.get("role").?.string);
+ // The rung is read back off the seated model, and the id names the
+ // exact cell that moved the phase.
+ try std.testing.expectEqualStrings("small", ev.object.get("tier").?.string);
+ try std.testing.expectEqualStrings("research/sweep@small", ev.object.get("policy_or_genome_id").?.string);
+ try std.testing.expectEqualStrings("codex", ev.object.get("provider").?.string);
+ }
+ try std.testing.expectEqual(sweep_niches.len, n);
+}
+
+test "#376: an explicitly chosen worker model outranks the phase policy" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const base = codex("gpt-5.6-terra");
+
+ // --subagent-model: the session named the worker model, so the route is
+ // `session-default`, not the ladder's, and evidence never overrides a
+ // human's stated choice.
+ {
+ const env = Env.install(arena_state.allocator(), demo_archive, false);
+ defer env.restore();
+ const seat = phase.forPhase(base, .research, "sweep the repo", &sweep_niches, true);
+ try std.testing.expect(seat.pin == null);
+ try std.testing.expectEqualStrings("gpt-5.6-terra", seat.provider.model);
+ try std.testing.expectEqual(policy.Source.session_default, seat.sourceFor(false));
+ }
+ // A plain inherit-the-root (no worker provider at all) is the same story:
+ // `session-default` is a choice, not a default the policy may improve on.
+ {
+ const env = Env.install(arena_state.allocator(), demo_archive, true);
+ defer env.restore();
+ const seat = phase.forPhase(base, .research, "sweep the repo", &sweep_niches, false);
+ try std.testing.expect(seat.pin == null);
+ try std.testing.expectEqual(policy.Source.session_default, seat.sourceFor(false));
+ }
+}
+
+test "#376: the phase seat can only trade DOWN on cost, and never leaves the provider" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ // The mirror image of the demonstration: terra is the loved model but it
+ // is also the DEARER one, so a phase already seated on luna can never be
+ // moved up to it however well terra scored in the cell.
+ const upward =
+ \\{"kind":"score","prompt_sha":"aa","score":1,"shape":"research","role":"sweep","tier":"mid","model":"gpt-5.6-terra"}
+ \\{"kind":"score","prompt_sha":"aa","score":1,"shape":"research","role":"sweep","tier":"mid","model":"gpt-5.6-terra"}
+ \\{"kind":"score","prompt_sha":"bb","score":0,"shape":"research","role":"sweep","tier":"small","model":"gpt-5.6-luna"}
+ \\{"kind":"score","prompt_sha":"bb","score":0,"shape":"research","role":"sweep","tier":"small","model":"gpt-5.6-luna"}
+ ;
+ const env = Env.install(a, upward, true);
+ defer env.restore();
+ const seat = phase.forPhase(codex("gpt-5.6-luna"), .research, "sweep the repo", &sweep_niches, true);
+ try std.testing.expect(seat.pin == null);
+ try std.testing.expectEqualStrings("gpt-5.6-luna", seat.provider.model);
+
+ // And whatever it decides, the seat is provider-local by construction: the
+ // id, the credential and the account all ride across unchanged, so no
+ // phase can move prompts or billing to a second vendor. Cross-provider
+ // workers keep needing --subagent-provider + the consent flag, and the
+ // sub-first flat-rate routing in subagent_pin is reached only by an
+ // explicit `tier` ask, which a phase task never makes.
+ const env2 = Env.install(a, demo_archive, true);
+ defer env2.restore();
+ const base = codex("gpt-5.6-terra");
+ const moved = phase.forPhase(base, .research, "sweep the repo", &sweep_niches, true);
+ try std.testing.expect(moved.pin != null);
+ try std.testing.expectEqualStrings(base.id, moved.provider.id);
+ try std.testing.expectEqualStrings(base.api_key, moved.provider.api_key);
+ try std.testing.expect(pin_mod.rungAffordable(base.model, moved.provider.model));
+ try std.testing.expect(std.mem.indexOf(u8, @embedFile("route_phase.zig"), "subscriptionRung") == null);
+}
+
+test "#376: an uncelled phase, and a bootstrap install, keep today's behavior exactly" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const base = codex("gpt-5.6-terra");
+ {
+ const env = Env.install(a, demo_archive, true);
+ defer env.restore();
+ // Off-vocabulary title, niches that disagree → no single role, so the
+ // evidence that WOULD have moved a `sweep` phase moves nothing.
+ const seat = phase.forPhase(base, .research, "ponder", &.{ "researcher", "review the diff" }, true);
+ try std.testing.expect(seat.pin == null);
+ try std.testing.expectEqualStrings("gpt-5.6-terra", seat.provider.model);
+ }
+ {
+ // An install with no archive at all: zero cells, nothing to say.
+ const env = Env.install(a, "", true);
+ defer env.restore();
+ const seat = phase.forPhase(base, .research, "sweep the repo", &sweep_niches, true);
+ try std.testing.expect(seat.pin == null);
+ try std.testing.expectEqual(policy.Source.ladder, seat.sourceFor(false));
+ }
+}
+
+test "#376 firewall: the seat is resolved ONCE per phase, outside the task loop" {
+ // The property is about the CALL SITE — that no task can influence its own
+ // model — so it is pinned as source text, the same way #372 pinned the
+ // no-per-task-pin invariant it replaces.
+ const src = @embedFile("workflow.zig");
+ const seat_at = std.mem.indexOf(u8, src, "const seat = route_phase.forPhase(").?;
+ const loop_at = std.mem.indexOf(u8, src, "for (labels, prompts, overrides, niches, isolations, isolation_fallbacks, futures, 1..)").?;
+ 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.
+ try std.testing.expect(std.mem.indexOf(u8, src, "isolation_fallback, seat.pin }") != null);
+ try std.testing.expect(std.mem.indexOf(u8, src, "isolation_fallbacks[i], seat.pin }") != null);
+}
diff --git a/src/route_policy.zig b/src/route_policy.zig
index cda80f67..a23c05a2 100644
--- a/src/route_policy.zig
+++ b/src/route_policy.zig
@@ -47,11 +47,11 @@
//! below every explicit pin (subagent_pin's precedence is untouched: an
//! explicit `model` bypasses this module entirely, and an explicit `tier`
//! only chooses WHICH model serves that rung). Workflow PHASE tasks still
-//! take no per-task pins at all, so scoreVariants keeps comparing prompt
-//! variants that ran on one identical configuration; the model axis never
-//! enters a genome's fitness. What #372 adds there is VISIBILITY, not a new
-//! lever: every phase worker now says out loud that its model came from the
-//! session, and under which (shape, role) its score is being filed.
+//! take no PER-TASK pins at all: #376 applies this policy once for a whole
+//! phase (route_phase.zig), so every worker in it runs the SAME model and
+//! scoreVariants keeps ranking prompt variants that ran on one identical
+//! configuration. What varies across RUNS is now recorded instead of being
+//! averaged over — see `stratumOf` below and fitness_strata.zig.
const std = @import("std");
const Allocator = std.mem.Allocator;
@@ -227,6 +227,32 @@ pub fn tierLabelFor(provider_id: []const u8, model: []const u8) []const u8 {
return if (tierOf(provider_id, model)) |t| t.label() else "";
}
+/// #376 — the fitness STRATUM one scored observation belongs to: the resolved
+/// model the worker actually ran on.
+///
+/// Until now the only routing axis a fitness row carried was
+/// scoring.providerClass, whose needle table buckets gpt-5.6-sol, -terra and
+/// -luna IDENTICALLY as "frontier" (the pinned, deliberate disagreement test
+/// in subagent_selection.zig). A rung-only difference was therefore invisible
+/// to every comparison built on it — which is precisely why #290 had to
+/// forbid phase workers from varying their model at all: nothing downstream
+/// could have told the model's contribution from the prompt's.
+///
+/// Recording the resolved model per row removes that blindness. A cross-run
+/// comparison of two prompt genomes can then be restricted to rows that ran
+/// on the same model (fitness_strata.zig) instead of pooling across rungs,
+/// which is what makes the phase-uniform routing in route_phase.zig safe.
+///
+/// A row that names no model — every fitness row written before #372, and
+/// mainloop /score's, which never recorded one — reads as `unknown`: its own
+/// bucket, ranked only against other unknowns, never silently merged into a
+/// measured one.
+pub const stratum_unknown = "unknown";
+
+pub fn stratumOf(model: []const u8) []const u8 {
+ return if (model.len == 0) stratum_unknown else model;
+}
+
// ── the learned tier policy ────────────────────────────────────────────────
/// One (shape, role, tier, model) observation pooled out of the local DGM
diff --git a/src/route_policy_tests.zig b/src/route_policy_tests.zig
index 1be07eb2..64b33053 100644
--- a/src/route_policy_tests.zig
+++ b/src/route_policy_tests.zig
@@ -323,18 +323,24 @@ test "#372 round trip: what captureVariant writes is exactly what foldCells lear
);
}
-test "#372 firewall: a workflow phase task still carries no per-task pin (#290)" {
- // The trace makes routing VISIBLE; it must not make it VARIABLE inside a
- // scored phase. workflowTask/workflowRetryTask are the only doors a phase
- // task goes through, and both hand runSub a null pin AND a null effort —
- // so scoreVariants keeps ranking prompt genomes that ran on one identical
- // configuration. Pinned as source text because the property is about the
- // call site, not about any value a unit test could observe at runtime.
+test "#372/#376 firewall: a phase task takes the PHASE's seat, and still no per-task pin (#290)" {
+ // The trace makes routing VISIBLE; #376 lets the policy make it VARY —
+ // but only per PHASE, never per task inside one. workflowTask and
+ // workflowRetryTask are the only doors a phase task goes through, and
+ // both hand runSub the `seat` their caller resolved once for the whole
+ // phase (route_phase.forPhase), plus a null EFFORT: no axis of a phase
+ // task's configuration is readable off the task itself, so scoreVariants
+ // keeps ranking prompt genomes that ran on one identical configuration.
+ // Pinned as source text because the property is about the call site, not
+ // about any value a unit test could observe at runtime.
const src = @embedFile("subagent.zig");
const wf = std.mem.indexOf(u8, src, "pub fn workflowTask(").?;
const wf_end = std.mem.indexOf(u8, src[wf..], "\n}").?;
- try std.testing.expect(std.mem.indexOf(u8, src[wf .. wf + wf_end], "isolation_fallback, null, null)") != null);
+ try std.testing.expect(std.mem.indexOf(u8, src[wf .. wf + wf_end], "isolation_fallback, seat, null)") != null);
const rt = std.mem.indexOf(u8, src, "pub fn workflowRetryTask(").?;
const rt_end = std.mem.indexOf(u8, src[rt..], "\n}").?;
- try std.testing.expect(std.mem.indexOf(u8, src[rt .. rt + rt_end], "isolation_fallback, null, null)") != null);
+ try std.testing.expect(std.mem.indexOf(u8, src[rt .. rt + rt_end], "isolation_fallback, seat, null)") != null);
+ // `seat` is a parameter of both, never derived from the task's own fields.
+ try std.testing.expect(std.mem.indexOf(u8, src[wf .. wf + wf_end], "isolation_fallback: bool, seat: ?Provider)") != null);
+ try std.testing.expect(std.mem.indexOf(u8, src[rt .. rt + rt_end], "isolation_fallback: bool, seat: ?Provider)") != null);
}
diff --git a/src/subagent.zig b/src/subagent.zig
index 3faedd2e..ee024777 100644
--- a/src/subagent.zig
+++ b/src/subagent.zig
@@ -6,8 +6,7 @@
//! tools.zig for `ToolCtx`/`ToolOutput`/`failure`; back-imports main (as
//! `main_mod`) for `Agent` (whose `runTurn`/`systemPrompt` are pub-flipped for
//! this cross-module call), `parseEvalScore`, `utf8Prefix`, `json_mode`,
-//! `g_out`/`g_gui_mu` (pub-flipped — guiEmit serializes --json stdout with
-//! them), and `g_fleet`.
+//! `g_out`/`g_gui_mu` (guiEmit serializes --json stdout), and `g_fleet`.
const std = @import("std");
const Io = std.Io;
@@ -87,7 +86,7 @@ pub const AgentUsage = subagent_run.AgentUsage;
pub const SubRun = subagent_run.SubRun;
pub const runSub = subagent_run.runSub;
const childProvider = subagent_run.childProvider;
-const variantProviderClass = subagent_run.variantProviderClass;
+const route_phase = @import("route_phase.zig"); // #376 one learned seat per phase
const shapes = @import("shapes.zig");
const route_policy = @import("route_policy.zig"); // #372 (shape, role) policy cells
const route_trace = @import("route_trace.zig"); // #372 per-worker routing trace
@@ -101,11 +100,10 @@ const classifyFailure = subagent_run.classifyFailure;
// on `subagent` returns a stable agent id immediately (spawnSubBackground);
// the child runs on io.concurrent, never io.async — io.async may run inline
// and block the spawning call forever on a long-lived child, same reason
-// spawnJob avoids it for bash. Completion is polled non-destructively via
-// the new `agent_output` tool (agentOutput), mirroring bash_output's
-// id/wait_ms shape and its 30s wait cap — except a subagent's report is a
-// one-shot value, not a stream, so a completed fetch always replays the
-// FULL result rather than consuming a cursor (design point 4).
+// spawnJob avoids it for bash. Completion is polled non-destructively via the
+// `agent_output` tool (agentOutput), mirroring bash_output's id/wait_ms shape
+// and 30s wait cap — except a subagent's report is a one-shot value, not a
+// stream, so a completed fetch replays the FULL result (design point 4).
/// Concurrency ceiling on background subagents actually RUNNING (i.e. past
/// admission, inside their own runSub call) at once. Deliberately a counter
@@ -113,18 +111,17 @@ const classifyFailure = subagent_run.classifyFailure;
/// background job's admission slot would otherwise have to stay held for its
/// entire — possibly minutes-long — lifetime, while its OWN internal turns
/// separately acquire per-model-call permits from that very same pool; once
-/// enough jobs queued up, every held outer slot would starve the inner
-/// acquires each job needs to ever finish and release it — a deadlock. Same
-/// admission SHAPE as RunBudget.acquireConcurrency (spin-wait, no failure on
-/// saturation) and the same default value, but an independent resource.
+/// enough jobs queued up, every held outer slot would starve the inner acquires
+/// each job needs to ever finish and release it — a deadlock. Same admission
+/// SHAPE as RunBudget.acquireConcurrency (spin-wait, no failure on saturation)
+/// and the same default value, but an independent resource.
const max_concurrent_background_agents: u32 = run_budget.default_max_concurrency;
/// One background subagent spawn: the runSub arguments (gpa-owned copies —
/// the caller's ToolCtx.arena-backed strings do not outlive this tool call's
/// return, the whole point of fire-and-forget) plus its outcome once done.
/// `admitted` is false while queued behind max_concurrent_background_agents;
-/// jobs.zig's Job mirrors this shape closely (id/cmd there ~ id/label+prompt
-/// here).
+/// jobs.zig's Job mirrors this shape (id/cmd there ~ id/label+prompt here).
const AgentJob = struct {
id: u32,
label: []u8,
@@ -427,18 +424,19 @@ test "agentStatusText: composes with isolation:\"worktree\" — a kept-worktree
/// 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.
-pub fn workflowTask(ctx: ToolCtx, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8, isolation: Isolation, isolation_fallback: bool) ToolOutput {
- // No #292 pin (model or effort): a phase's variants must share one
- // configuration or scoreVariants would file model effects under the
- // prompt genome (#290).
- const run = runSub(ctx, "workflow_task", label, prompt, sys_override, niche, isolation, isolation_fallback, null, null) catch |err| return failure(ctx.gpa, err);
+pub fn workflowTask(ctx: ToolCtx, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8, isolation: Isolation, isolation_fallback: bool, seat: ?Provider) ToolOutput {
+ // `seat` is the PHASE's one model (route_phase.forPhase, resolved once and
+ // handed to every task alike), never a per-task pin: the variants still
+ // share one configuration (#290). The effort axis stays unpinned.
+ const run = runSub(ctx, "workflow_task", label, prompt, sys_override, niche, isolation, isolation_fallback, seat, null) catch |err| return failure(ctx.gpa, err);
return run.output;
}
/// A second workflow attempt has its own explicit budget kind. It still shares
/// the same invocation-wide atomic ceiling and concurrency limiter.
-pub fn workflowRetryTask(ctx: ToolCtx, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8, isolation: Isolation, isolation_fallback: bool) ToolOutput {
- const run = runSub(ctx, "workflow_retry", label, prompt, sys_override, niche, isolation, isolation_fallback, null, null) catch |err| return failure(ctx.gpa, err);
+pub fn workflowRetryTask(ctx: ToolCtx, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8, isolation: Isolation, isolation_fallback: bool, seat: ?Provider) ToolOutput {
+ // The SAME phase seat: a retry that changed model would break uniformity.
+ const run = runSub(ctx, "workflow_retry", label, prompt, sys_override, niche, isolation, isolation_fallback, seat, null) catch |err| return failure(ctx.gpa, err);
return run.output;
}
@@ -485,15 +483,15 @@ pub const max_workflow_tasks = 8;
/// the fleet, turning every ultracode tournament into a DGM scoring round. Each
/// surviving variant task is judged 0-100 against its task; the score is signed
/// and submitted under the task's niche so a MAP-Elites cell accrues real fitness
-/// and the promote pass can crown a winner. Mirrors runEval's submit exactly but
-/// with a NON-EMPTY niche — the gap that previously forced bootstrap seeding.
+/// and the promote pass can crown a winner. Mirrors runEval's submit but with a
+/// NON-EMPTY niche — the gap that previously forced bootstrap seeding.
/// Best-effort and gated: no judge runs unless ≥2 variants competed and the
-/// fleet (telemetry) is on, so ordinary fan-outs pay nothing.
+/// fleet (telemetry) is on, so ordinary fan-outs pay nothing. `seat` (#376) is
+/// this phase's shape/title/model — the configuration every variant shared.
pub fn scoreVariants(
ctx: ToolCtx,
arena: Allocator,
- title: []const u8,
- shape: route_policy.Shape,
+ seat: route_phase.Seat,
prompts: [][]const u8,
raws: [][]const u8,
overrides: []?[]const u8,
@@ -516,13 +514,15 @@ pub fn scoreVariants(
}
if (vn < 2) return;
- // A tournament must vary exactly ONE axis: if the variants did not all run on
- // the same capability tier, the ranking reflects the model as much as the
- // prompt, and filing it under the prompt fingerprint writes model effects into
- // the genome archive (#290). Bail before spawning a judge — unscoreable round.
+ // A tournament must vary exactly ONE axis: variants that did not all run on
+ // the same MODEL rank the model as much as the prompt, and filing that under
+ // the prompt fingerprint writes model effects into the genome archive (#290).
+ // #376 tightened the key from the capability class — which cannot tell
+ // gpt-5.6-sol from -luna — to the resolved model, catching a rung-only
+ // difference too. Bail before a judge: unscoreable round.
for (1..vn) |k| {
- if (!std.mem.eql(u8, variantProviderClass(ctx, vidx[0]), variantProviderClass(ctx, vidx[k]))) {
- if (ctx.tracer) |tr| tr.note("fleet", "tournament skipped: variants span provider classes");
+ if (!std.mem.eql(u8, subagent_run.variantStratum(seat.provider, vidx[0]), subagent_run.variantStratum(seat.provider, vidx[k]))) {
+ if (ctx.tracer) |tr| tr.note("fleet", "tournament skipped: variants span routing strata");
return;
}
}
@@ -532,14 +532,14 @@ pub fn scoreVariants(
const jprompts = arena.alloc([]const u8, vn) catch return;
for (jprompts, 0..) |*jp, k| {
const i = vidx[k];
- jp.* = variantJudgePrompt(arena, title, prompts[i], outputs[i].text) catch return;
+ jp.* = variantJudgePrompt(arena, seat.title, prompts[i], outputs[i].text) catch return;
}
const jfuts = arena.alloc(Io.Future(ToolOutput), vn) catch return;
for (jfuts, jprompts) |*jf, jp| jf.* = ctx.io.async(judgeTask, .{ ctx, jp });
const run_id: []const u8 = &scoring.g_run_id;
// This phase's MAP-Elites slot (#290/#293); "" off-vocabulary. See telemetrySlot.
- const slot = scoring.telemetrySlot(shapes.canonicalSlot(title));
+ const slot = scoring.telemetrySlot(shapes.canonicalSlot(seat.title));
for (jfuts, 0..) |*jf, k| {
const i = vidx[k];
const jout = jf.await(ctx.io);
@@ -560,7 +560,7 @@ pub fn scoreVariants(
// above; every score that leaves the client is [0,1], so divide at
// the emission boundary — s01 is what gets signed and sent.
const s01 = s / 100.0;
- const pclass = variantProviderClass(ctx, i);
+ const pclass = subagent_run.variantProviderClass(seat.provider, i);
const genome_fp = promptFingerprint(overrides[i].?);
const esh_fp = promptFingerprint(raws[i]);
const genome: []const u8 = &genome_fp;
@@ -573,13 +573,15 @@ pub fn scoreVariants(
const sig = signScore(genome, "", s01, run_id, "", "", esh, niche, pclass);
const sig_s: []const u8 = if (scoring.g_score_key != null) &sig else "";
var provbuf: [512]u8 = undefined;
- // Slot is APPENDED as a 6th component, so a collector indexing 0..4 is
- // unaffected. Advisory like the rest of `prov` (signScore holds the
- // authoritative copies); signing it would need a collector-first deploy.
- const prov = std.fmt.bufPrint(&provbuf, "{s}\t{s}\t{s}\t{s}\t{s}\t{s}", .{ "", "", esh, pclass, niche, slot }) catch "";
+ // Slot (6th) and #376's routing STRATUM (7th) are APPENDED, so a
+ // collector indexing 0..4 is unaffected; both stay advisory like the
+ // rest of `prov` (signing them needs a collector-first deploy). The
+ // stratum is what lets a cross-run comparison of two genomes stay
+ // inside one rung instead of averaging over the phase's seat.
+ const prov = std.fmt.bufPrint(&provbuf, "{s}\t{s}\t{s}\t{s}\t{s}\t{s}\t{s}", .{ "", "", esh, pclass, niche, slot, subagent_run.variantStratum(seat.provider, i) }) catch "";
// #372: the policy observation — this cell's (shape, role, tier,
// model) plus the judged score — filed locally, never on the genome.
- route_trace.captureVariant(childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider), shape, title, niche, genome, s01);
+ route_trace.captureVariant(seat.provider, seat.shape, seat.title, niche, genome, s01);
const t = telemetry.g_telem orelse continue;
// Genome-send (issue #168 Gap 5), mirroring runEval: ride the variant's
// text over on a propose (deduped by fingerprint server-side) so the
diff --git a/src/subagent_run.zig b/src/subagent_run.zig
index 3dbd3138..3d3644e7 100644
--- a/src/subagent_run.zig
+++ b/src/subagent_run.zig
@@ -7,7 +7,8 @@ const Allocator = std.mem.Allocator;
const main_mod = @import("main.zig");
const Agent = @import("agent.zig").Agent;
-const Provider = @import("provider.zig").Provider;
+pub const Provider = @import("provider.zig").Provider;
+const route_policy = @import("route_policy.zig"); // #376 rung stratification
const util = @import("util.zig");
const goal_pacing = @import("goal_pacing.zig");
const tools = @import("tools.zig");
@@ -132,28 +133,37 @@ pub fn childProvider(root: Provider, pinned: ?Provider, allow_cross_provider: bo
/// Capability tier ("frontier" | "mid" | "small") of the model that ran variant
/// `i` of a workflow phase — the provider-class axis of the MAP-Elites cell.
///
-/// Every child in a WORKFLOW PHASE still resolves through the same
-/// session-level subagent provider, so this returns the same value for every
-/// `i`. #292 landed per-persona / per-spawn model pins on the `subagent` tool
-/// deliberately WITHOUT extending them to workflow phase tasks or pipeline
-/// stages, for the reason #290 exists: scoreVariants ranks the variants of one
-/// phase against each other and files the winner under the prompt fingerprint,
-/// so a phase whose tasks could differ in model would attribute model effects
-/// to the genome. The matched-tournament guard below catches a class-level
-/// difference, but not a rung-only one (see the #291 note), so the safe
-/// position is that phase tasks do not carry pins at all.
+/// `seat` is the PHASE's resolved provider (#376). It used to be derived from
+/// `ctx` here, on the standing assumption that a phase always ran the session
+/// default; route_phase.forPhase may now re-seat a whole phase, so the model
+/// a variant actually ran on has to be passed in or every row this feeds would
+/// name a model that never ran.
///
-/// The lookup stays per-variant regardless: whenever pins DO reach a phase,
-/// this one function is the seam that has to learn about them, instead of a
-/// phase-level constant silently going stale.
+/// It is still the same value for every `i`, and that is the #290 property,
+/// not an accident: a phase takes ONE seat for all of its workers, so
+/// scoreVariants keeps ranking prompt variants that shared a configuration.
+/// #292's per-spawn pins likewise still reach `subagent` only, never a phase
+/// task or a pipeline stage. The lookup stays per-variant so that whenever a
+/// finer grain does reach a phase, this pair of functions is the seam that has
+/// to learn about it instead of a phase-level constant going stale.
+pub fn variantProviderClass(seat: Provider, i: usize) []const u8 {
+ _ = i; // phase-uniform by construction — route_phase.forPhase
+ return scoring.providerClass(seat.model);
+}
+
+/// #376 — the routing STRATUM variant `i` was observed in: the resolved model
+/// itself, not its capability bucket.
///
-/// NOTE (#291): providerClass cannot currently distinguish gpt-5.6-sol from
-/// gpt-5.6-terra/-luna — all three classify as "frontier". Until that is
-/// resolved this axis cannot separate ladder rungs, and the matched-tournament
-/// guard in scoreVariants is correspondingly blind to a rung-only difference.
-pub fn variantProviderClass(ctx: tools.ToolCtx, i: usize) []const u8 {
- _ = i; // #292 pins reach `subagent`, not phase tasks — see above
- return scoring.providerClass(childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider).model);
+/// providerClass cannot separate gpt-5.6-sol from -terra/-luna (all three are
+/// "frontier"), so the matched-tournament guard in scoreVariants was blind to
+/// a rung-only difference — the documented #291 gap that made phase routing
+/// unsafe. Keyed on this it is not: a phase whose variants somehow spanned two
+/// models is refused as unscoreable, and every fitness row records the same
+/// value so a cross-run comparison can stratify by it (fitness_strata.zig)
+/// rather than averaging over rungs.
+pub fn variantStratum(seat: Provider, i: usize) []const u8 {
+ _ = i;
+ return route_policy.stratumOf(seat.model);
}
pub const AgentUsage = struct {
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index ae3bd1dc..8cf34930 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -50,6 +50,9 @@ const bench_priors_tests = @import("bench_priors_tests.zig");
const route_policy = @import("route_policy.zig");
const route_policy_tests = @import("route_policy_tests.zig");
const route_trace = @import("route_trace.zig");
+// #376 phase-uniform learned routing + the rung-stratified fitness fold.
+const route_phase = @import("route_phase.zig");
+const fitness_strata = @import("fitness_strata.zig");
// `graff serve` resumability (#330): serve.zig imports these, but nothing in
// the production graph references their decls, so Zig never analyses them.
@@ -91,6 +94,8 @@ test {
_ = route_policy;
_ = route_policy_tests;
_ = route_trace;
+ _ = route_phase;
+ _ = fitness_strata;
_ = serve_events;
_ = serve_create;
_ = scoring_slot_test;
diff --git a/src/workflow.zig b/src/workflow.zig
index 3a37a98b..8644b768 100644
--- a/src/workflow.zig
+++ b/src/workflow.zig
@@ -38,6 +38,7 @@ const failureAllowsRetry = subagent_run.failureAllowsRetry;
const fleet = @import("fleet.zig");
const Isolation = fleet.Isolation; // #276 P0-1
const route_policy = @import("route_policy.zig"); // #372 (shape, role) policy cells
+const route_phase = @import("route_phase.zig"); // #376 one learned seat per phase
const route_trace = @import("route_trace.zig"); // #372 per-worker routing trace
const telemetry = @import("telemetry.zig");
// #63: stable workflow/phase/task ids + the additive `workflow_progress`
@@ -201,7 +202,7 @@ fn pipelineChain(ctx: ToolCtx, item: []const u8, stages: []const StageSpec) Tool
// #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: #292 model pins deliberately do not reach pipeline stages (see subagent_run.variantProviderClass).
+ // 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
@@ -483,15 +484,16 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {
// can never abandon running subagents or free their result slots.
const futures = try arena.alloc(Io.Future(ToolOutput), tasks.len);
const outputs = try arena.alloc(ToolOutput, tasks.len);
- // #372 — every phase worker inherits the SESSION route (workflow
- // tasks take no per-task pins, #290); the trace says so explicitly,
- // names the rung it landed on, and names the cell its score is filed
- // under, instead of leaving all three to be inferred.
- const wp = subagent_run.childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider);
+ // #376 — ONE seat for the whole phase, resolved once here and shared by
+ // every worker below (never per task, which is what #290 forbids). It
+ // is the session route unless the learned (shape, role) policy found a
+ // strictly better-value model for this phase's cell; either way the
+ // #372 trace names the rung, the cell and the layer that decided.
+ const seat = route_phase.forPhase(subagent_run.childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider), shape, title, niches, 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
- route_trace.emitSpawnProvider(ctx.io, ctx.tracer, label, wp, .{ .shape = shape, .role = route_policy.roleOf(title, niche) }, if (override != null) .workflow_override else route_trace.sessionSource(ctx.subagent_provider != null), override, niche);
- fut.* = ctx.io.async(workflowTask, .{ ctx, label, prompt, override, niche, isolation, isolation_fallback });
+ route_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, 1..) |*fut, *out, label, task_no| {
out.* = fut.await(ctx.io);
@@ -521,7 +523,7 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {
const refut = try arena.alloc(Io.Future(ToolOutput), nf);
for (refut, 0..) |*rf, k| {
const i = fidx[k];
- rf.* = ctx.io.async(workflowRetryTask, .{ ctx, labels[i], prompts[i], overrides[i], niches[i], isolations[i], isolation_fallbacks[i] });
+ rf.* = ctx.io.async(workflowRetryTask, .{ ctx, labels[i], prompts[i], overrides[i], niches[i], isolations[i], isolation_fallbacks[i], seat.pin });
}
for (refut, 0..) |*rf, k| {
const retry = rf.await(ctx.io);
@@ -562,7 +564,7 @@ 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, title, shape, prompts, raws, overrides, niches, outputs);
+ 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 };