graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(#372): learn orchestration + tier policy, not only prompt variants
justrach041f600d3dc7
diff --git a/src/agent_eval.zig b/src/agent_eval.zigindex d406612d..1abb4c96 100644--- a/src/agent_eval.zig+++ b/src/agent_eval.zig@@ -23,6 +23,7 @@ const eval_memory = @import("eval_memory.zig");const trace = @import("trace.zig");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 rowstest {_ = @import("agent_eval_tests.zig");@@ -159,10 +160,17 @@ pub fn runEval(self: *Agent, note: []const u8) !ExecResult {// kind:"eval" row carries the niche tag: promoteAgents reads// niche off non-prompt/non-score records only. Same niche gate// as the backend path — a "" cell is unpromotable either way.+ // #372: the same two rows also carry the (shape, role, tier,+ // model) coordinates the learned tier policy partitions on.+ // An eval loop instantiates no catalog shape, so its cell is+ // (adhoc, <the slot --niche names>); the rung is read back off+ // whatever model this session actually ran.+ const rrole = route_policy.roleOf("", niche);+ const rtier = route_policy.tierLabelFor(self.provider.id, self.provider.model);if (niche.len > 0) if (trace.g_traj) |traj| {traj.capturePrompt(genome_fp, sys);- traj.node(.{ .kind = "eval", .prompt_sha = genome, .niche = niche, .eval_set_hash = esh, .provider_class = pclass, .t = traj.elapsedMs() });- traj.node(.{ .kind = "score", .prompt_sha = genome, .score = s01, .niche = niche, .eval_set_hash = esh, .provider_class = pclass, .t = traj.elapsedMs() });+ traj.node(.{ .kind = "eval", .prompt_sha = genome, .niche = niche, .eval_set_hash = esh, .provider_class = pclass, .shape = "adhoc", .role = rrole, .tier = rtier, .model = self.provider.model, .t = traj.elapsedMs() });+ traj.node(.{ .kind = "score", .prompt_sha = genome, .score = s01, .niche = niche, .eval_set_hash = esh, .provider_class = pclass, .shape = "adhoc", .role = rrole, .tier = rtier, .model = self.provider.model, .t = traj.elapsedMs() });};// Auto-learn: evolution is a default part of the harness, not// a command. A target-met NEW BEST is the learning moment —diff --git a/src/bench_priors.zig b/src/bench_priors.zigindex 51bef186..b1c5a3ca 100644--- a/src/bench_priors.zig+++ b/src/bench_priors.zig@@ -135,8 +135,13 @@ pub fn loadInto(io: Io, arena: Allocator, home: ?[]const u8) void {// front routes on what these models actually did here, not only on a// leaderboard snapshot. Auto-promote's hot-reload re-runs this, so the// front tightens as the session scores work.- g_entries = blend(arena, g_entries, trace.readTrajectoryArchive(io, arena, 8 << 20));+ const archive = trace.readTrajectoryArchive(io, arena, 8 << 20);+ g_entries = blend(arena, g_entries, archive);g_ladders = derive(arena, g_entries);+ // #372: the SAME archive read also folds the (shape, role, tier, model)+ // 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);}fn readSheet(io: Io, arena: Allocator, path: []const u8) ?Sheet {@@ -254,8 +259,10 @@ pub fn foldObservations(arena: Allocator, archive: []const u8) []Obs {}/// The sheet speaks with the weight of this many lived runs: a couple of-/// real scores nudge the front, a season of them owns it.-const sheet_weight: f64 = 3;+/// real scores nudge the front, a season of them owns it. pub since #372 so+/// the per-cell learned policy damps its evidence with the SAME pseudo-count+/// discipline rather than inventing a second one.+pub const sheet_weight: f64 = 3;/// Merge lived observations into the sheet before Pareto seating. A matching/// (model[, effort]) entry gets a pseudo-count-blended score and KEEPS itsdiff --git a/src/route_policy.zig b/src/route_policy.zignew file mode 100644index 00000000..cda80f67--- /dev/null+++ b/src/route_policy.zig@@ -0,0 +1,449 @@+//! #372 — learned orchestration policy, and the per-worker routing trace.+//!+//! Before this module an ultracode run LOOKED learned and was not. The root+//! model picked a shape out of the fixed catalog (shapes.zig), authored the+//! workflow JSON, and every worker it spawned silently inherited the session+//! route; the fleet then scored the prompt genome only. Nobody ever recorded+//! — let alone learned — whether a cheaper rung or another model was the+//! better quality/cost policy for "the researchers of a research sweep".+//!+//! Two things live here, in that order:+//!+//! 1. THE ROUTING TRACE (the mandatory minimum). Every spawned worker emits+//! one line naming the whole decision:+//!+//! shape=research role=sweep tier=mid resolved_model=gpt-5.6-terra+//! source=ladder policy_or_genome_id=ladder:codex+//!+//! on three paths at once — the tracer note stream (`ev:"route"` in+//! .graff/traces), a `kind:"route"` DGM archive row, and an `agent_route`+//! --json event. `source` is the closed vocabulary the issue asks for:+//! explicit-pin > persona > learned-policy > workflow-override >+//! session-default > ladder, highest-precedence layer that actually+//! decided this worker's model. So "which came from the fixed catalog,+//! which the root model authored, which came from fleet fitness" is a+//! grep, not an inference.+//!+//! 2. THE LEARNED TIER POLICY (the first learning increment). Scored runs+//! now record the (shape, role, tier, model) coordinates on their local+//! DGM `kind:"score"` rows, foldCells pools them per cell, and+//! `learnedRung` lets tier→model resolution consult that evidence with a+//! strict hierarchy: exact (shape, role) cell → shape-level pool →+//! nothing (the provider ladder / bench priors answer, exactly as+//! today). A sparse cell therefore cannot move anything, and an install+//! with no archive behaves bit-for-bit like before.+//!+//! WHAT THE POLICY IS ALLOWED TO DO. Only ever replace the ladder's own+//! answer with a candidate that DOMINATES it in bench_priors' sense — at+//! least its quality for strictly less money (bench.dominates/effCost, the+//! same Pareto machinery #373 seats the ladders with; there is deliberately+//! no second scoring scheme). It can never escalate cost, never raise the+//! tier, and never name a model the cell has no lived evidence for. When the+//! ladder's answer is not itself in the cell, the policy has no basis for a+//! comparison and stays silent.+//!+//! #290 FIREWALL. The policy is keyed on (shape, role, tier) and NEVER on a+//! prompt genome, and it is consulted at the tier-resolution layer only —+//! 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.++const std = @import("std");+const Allocator = std.mem.Allocator;++const shapes = @import("shapes.zig");+const tier_ladder = @import("subagent_tier_ladder.zig");+const bench = @import("bench_priors.zig");+const selection = @import("subagent_selection.zig");+const util = @import("util.zig");++pub const Tier = tier_ladder.Tier;++/// The fixed shape catalog (shapes.zig) as a closed identifier: the FIRST+/// component of a policy cell. Derived from the phase titles the root model+/// authored rather than declared by it — the model picks a shape by naming+/// its phases with slot words, so the slots are the ground truth for which+/// catalog entry actually ran. `adhoc` covers a bare `subagent` spawn and any+/// workflow whose titles are off-vocabulary: both still run, they just do not+/// accrue shape-partitioned fitness.+pub const Shape = enum {+ review, // A — find/verify/synthesize+ research, // B — sweep/synthesize+ design, // C — variants/build+ migration, // D — pipeline (transform/verify); never scored, see #296+ feature, // E — scope/implement/review+ adhoc,++ pub fn label(self: Shape) []const u8 {+ return @tagName(self);+ }++ /// Exact, closed vocabulary — anything else is `adhoc`, never a guess.+ pub fn parse(s: []const u8) Shape {+ return std.meta.stringToEnum(Shape, s) orelse .adhoc;+ }+};++/// The highest-precedence layer that CONFIGURED this worker. Listed in+/// precedence order.+///+/// `workflow_override` deserves its own note, because it is the answer to+/// "which decisions did the root model author": the root model wrote this+/// task's inline `system_prompt` genome, and `policy_or_genome_id` carries+/// that genome's fingerprint. Its `resolved_model` is by construction still+/// the session's route — #290 keeps per-task MODEL pins out of a scored+/// phase — and making that visible on every such line is precisely the gap+/// #372 reports: the UX read as if the root model had chosen a route it+/// never had the power to choose.+pub const Source = enum {+ explicit_pin, // `model`/`tier` on the spawn call itself+ persona, // `.harness/agents/<name>.md` frontmatter pin+ learned_policy, // a (shape, role) cell re-seated the tier's rung+ workflow_override, // the root model authored this worker's genome+ session_default, // --subagent-model, or the root the child inherits+ ladder, // the #291/#373 provider tier ladder (bench-derived or compiled)++ /// The wire spelling the issue pins: hyphens, not underscores.+ pub fn label(self: Source) []const u8 {+ return switch (self) {+ .explicit_pin => "explicit-pin",+ .persona => "persona",+ .learned_policy => "learned-policy",+ .workflow_override => "workflow-override",+ .session_default => "session-default",+ .ladder => "ladder",+ };+ }+};++/// The policy partition key: (shape, role). `role` is kept inside shapes.zig's+/// CLOSED slot vocabulary on purpose — free-text roles would mint a fresh cell+/// per run and nothing would ever accumulate, the same reason canonical_slots+/// exists for #290's MAP-Elites key.+pub const Cell = struct {+ shape: Shape = .adhoc,+ role: []const u8 = "",+};++/// One worker's complete routing decision — everything the trace line needs.+pub const Decision = struct {+ shape: Shape = .adhoc,+ role: []const u8 = "",+ tier: ?Tier = null,+ resolved_model: []const u8 = "",+ source: Source = .session_default,+ /// The learned cell id (`research/sweep@mid`) when fleet fitness decided+ /// this, else the genome fingerprint / persona / ladder id that did.+ policy_id: []const u8 = "",+};++/// Free-text fields are model-authored; cap them so one absurd label cannot+/// turn a trace line into a megabyte.+const field_cap = 64;+const line_cap = 320;++fn dash(s: []const u8) []const u8 {+ return if (s.len == 0) "-" else util.utf8Prefix(s, field_cap);+}++fn tierName(t: ?Tier) []const u8 {+ return if (t) |x| x.label() else "";+}++/// The #372 routing-trace line, verbatim in the issue's field order. Every+/// absent field renders `-` rather than an empty `key=` so the line is+/// unambiguous to split on.+pub fn formatDecision(buf: []u8, d: Decision) []const u8 {+ return std.fmt.bufPrint(buf, "shape={s} role={s} tier={s} resolved_model={s} source={s} policy_or_genome_id={s}", .{+ d.shape.label(),+ dash(d.role),+ dash(tierName(d.tier)),+ dash(d.resolved_model),+ d.source.label(),+ dash(d.policy_id),+ }) catch buf[0..0];+}++/// The worker's ROLE inside its shape: the canonical slot its phase title or+/// task description names, else the slot its persona niche names, else "" —+/// uncelled, exactly like an off-vocabulary phase title (shapes.canonicalSlot).+pub fn roleOf(label: []const u8, niche: []const u8) []const u8 {+ const from_label = shapes.canonicalSlot(label);+ return if (from_label.len > 0) from_label else shapes.canonicalSlot(niche);+}++/// The canonical slot of one workflow phase object, "" when off-vocabulary.+pub fn phaseSlot(pv: std.json.Value) []const u8 {+ if (pv != .object) return "";+ const t = pv.object.get("title") orelse return "";+ return if (t == .string) shapes.canonicalSlot(t.string) else "";+}++/// Which catalog shape this workflow actually instantiated, read off the+/// phase titles. Checked most-distinctive first: `sweep` only exists in B,+/// `find` only in A, `variants`/`build` only in C; `scope`/`implement`/+/// `review` are E's. A workflow naming none of them is `adhoc`.+pub fn shapeOfPhases(phases: []const std.json.Value) Shape {+ var research = false;+ var review = false;+ var design = false;+ var feature = false;+ for (phases) |pv| {+ const slot = phaseSlot(pv);+ if (slot.len == 0) continue;+ if (std.mem.eql(u8, slot, "sweep")) research = true;+ if (std.mem.eql(u8, slot, "find")) review = true;+ if (std.mem.eql(u8, slot, "variants") or std.mem.eql(u8, slot, "build")) design = true;+ if (std.mem.eql(u8, slot, "scope") or std.mem.eql(u8, slot, "implement") or std.mem.eql(u8, slot, "review")) feature = true;+ }+ if (research) return .research;+ if (review) return .review;+ if (design) return .design;+ if (feature) return .feature;+ return .adhoc;+}++/// Which rung of its provider's ladder `model` sits on, or null when the+/// model is off-ladder. The inverse of TierLadder.modelFor — needed because a+/// worker that inherited the session default has a model but no stated tier,+/// and the trace (and the policy cell it feeds) is keyed on the rung.+pub fn tierOf(provider_id: []const u8, model: []const u8) ?Tier {+ const l = tier_ladder.forProvider(provider_id) orelse return null;+ if (std.mem.eql(u8, l.frontier, model)) return .frontier;+ if (l.mid) |m| if (std.mem.eql(u8, m, model)) return .mid;+ if (l.small) |s| if (std.mem.eql(u8, s, model)) return .small;+ return null;+}++/// The rung label `model` sits on, for the archive's `tier` column. "" when+/// the model is off-ladder — an uncelled observation, which foldCells skips+/// rather than filing under a rung nobody can compare it against.+pub fn tierLabelFor(provider_id: []const u8, model: []const u8) []const u8 {+ return if (tierOf(provider_id, model)) |t| t.label() else "";+}++// ── the learned tier policy ────────────────────────────────────────────────++/// One (shape, role, tier, model) observation pooled out of the local DGM+/// archive: how well that worker configuration scored, and how often. Quality+/// only — the COST half comes from the bench sheet (bench_priors), whose+/// units are $/task; mixing a second cost notion in here is exactly what the+/// issue rules out.+pub const CellObs = struct {+ shape: []const u8,+ role: []const u8,+ tier: []const u8,+ model: []const u8,+ sum: f64 = 0,+ n: u32 = 0,++ pub fn mean(self: CellObs) f64 {+ return if (self.n == 0) 0 else self.sum / @as(f64, @floatFromInt(self.n));+ }+};++/// Session-arena cells, folded once by bench_priors.loadInto (which already+/// reads the archive) and refreshed by auto-promote's hot reload alongside+/// the ladders. Empty = no lived evidence = today's behavior everywhere.+pub var g_cells: []const CellObs = &.{};++/// A (cell, model) candidate needs at least this many scored runs before the+/// policy will speak for it. Below it the cell is SPARSE and falls through —+/// one lucky run must not reroute a fleet.+pub const min_model_obs: u32 = 2;++/// Cheap ceiling on how many distinct models one cell can offer. A provider+/// ladder is three rungs deep; eight leaves room for retired names without+/// needing an allocator on the hot resolution path.+pub const max_candidates = 8;++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;+}++/// Pool the archive's self-describing `kind:"score"` rows into cells. A score+/// row only counts when it carries ALL the coordinates — the rows written+/// before #372 (and mainloop /score's) simply have no shape, so they are+/// skipped rather than pooled into a cell they were never observed in.+/// Scores are [0,1] by the #168 contract; anything else is junk.+pub fn foldCells(arena: Allocator, archive: []const u8) []CellObs {+ var out: std.ArrayList(CellObs) = .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, "score")) continue;+ const shape = strField(o, "shape") orelse continue;+ const tier = strField(o, "tier") orelse continue;+ const model = strField(o, "model") orelse continue;+ if (shape.len == 0 or tier.len == 0 or model.len == 0) continue;+ const role = strField(o, "role") orelse "";+ const sv = o.get("score") orelse continue;+ const s: f64 = switch (sv) {+ .float => |f| f,+ .integer => |x| @floatFromInt(x),+ else => continue,+ };+ if (!(s >= 0 and s <= 1)) continue;+ const slot: *CellObs = for (out.items) |*c| {+ if (std.mem.eql(u8, c.shape, shape) and std.mem.eql(u8, c.role, role) and+ std.mem.eql(u8, c.tier, tier) and std.mem.eql(u8, c.model, model)) break c;+ } else blk: {+ out.append(arena, .{ .shape = shape, .role = role, .tier = tier, .model = model }) catch return out.items;+ break :blk &out.items[out.items.len - 1];+ };+ slot.sum += s;+ slot.n += 1;+ }+ return out.items;+}++/// Refresh the policy from one archive read. Called by bench_priors.loadInto+/// with the very archive it already blends into the sheet, so the ladders and+/// the cells can never disagree about which runs they have seen.+pub fn loadCells(arena: Allocator, archive: []const u8) void {+ g_cells = foldCells(arena, archive);+}++/// What the bench sheet knows about one model on one provider: its best+/// measured score and best score-per-dollar, i.e. exactly bench.foldProvider+/// restricted to a single name. An unpriced model keeps spd -1, which+/// bench.effCost reads as +inf.+fn sheetCandidate(provider_id: []const u8, model: []const u8, entries: []const bench.Entry) bench.Best {+ var b: bench.Best = .{ .name = model };+ for (entries) |e| {+ const s = bench.normalScore(e.score) orelse continue;+ const r = selection.modelForProvider(provider_id, e.model) orelse continue;+ if (!std.mem.eql(u8, r, model)) continue;+ if (s > b.score) b.score = s;+ if (e.cost > 0 and s / e.cost > b.spd) b.spd = s / e.cost;+ }+ return b;+}++/// This cell's candidates as bench_priors Bests: lived quality blended into+/// the sheet's prior with the SAME pseudo-count damping blend() uses, and the+/// sheet's cost kept verbatim (units stay $/task — blending prices in would+/// poison every domination comparison). `role_exact` false pools the whole+/// shape, which is the second rung of the hierarchy.+fn cellCandidates(+ buf: []bench.Best,+ cells: []const CellObs,+ entries: []const bench.Entry,+ provider_id: []const u8,+ cell: Cell,+ role_exact: bool,+) []bench.Best {+ var n: usize = 0;+ for (cells) |c| {+ if (c.n < min_model_obs) continue;+ if (!std.mem.eql(u8, c.shape, cell.shape.label())) continue;+ if (role_exact and !std.mem.eql(u8, c.role, cell.role)) continue;+ // Deliberately NOT filtered by rung. A model's quality in the "sweep+ // researcher" role does not change because the ladder relabelled it,+ // and filtering to same-rung evidence would make the policy unable to+ // ever learn that the rung BELOW is the better buy — which is the one+ // thing #372 asks it to learn. The rung is still recorded on every+ // observation (provenance, and the cell id a trace line reports), and+ // the ANSWER stays per-tier because each tier's ladder answer — the+ // baseline a challenger must dominate — is different.+ // Provider-local by construction: a name this provider does not serve+ // is not a candidate for its ladder, however well it scored elsewhere.+ const resolved = selection.modelForProvider(provider_id, c.model) orelse continue;+ const sheet = sheetCandidate(provider_id, resolved, entries);+ const cn: f64 = @floatFromInt(c.n);+ // blend() keeps the sheet's COST and re-derives score-per-dollar from+ // the blended score; do the same, or a model that scored badly here+ // would look CHEAPER for it (score/spd with a stale spd) and dominate+ // on an artifact of the arithmetic instead of on its price.+ const cost = bench.effCost(sheet); // +inf when the sheet never priced it+ var cand: bench.Best = .{ .name = sheet.name };+ cand.score = if (sheet.score >= 0)+ (sheet.score * bench.sheet_weight + c.mean() * cn) / (bench.sheet_weight + cn)+ else+ c.mean();+ cand.spd = if (std.math.isInf(cost) or !(cost > 0)) -1 else cand.score / cost;+ // At shape level one model can arrive through several roles; keep the+ // strongest evidence rather than double-counting it as two candidates.+ const seen: ?*bench.Best = for (buf[0..n]) |*b| {+ if (std.mem.eql(u8, b.name, cand.name)) break b;+ } else null;+ if (seen) |b| {+ if (cand.score > b.score) b.* = cand; // score AND its derived spd+ continue;+ }+ if (n == buf.len) continue;+ buf[n] = cand;+ n += 1;+ }+ return buf[0..n];+}++/// One level of the hierarchy's verdict, or null when this level has nothing+/// to say (fewer than two candidates, or no evidence at all for the rung the+/// ladder currently seats — with no measurement of today's answer there is+/// nothing to compare a challenger against).+fn seatFor(cands: []const bench.Best, ladder_answer: []const u8) ?[]const u8 {+ if (cands.len < 2) return null;+ var base: ?bench.Best = null;+ for (cands) |c| if (std.mem.eql(u8, c.name, ladder_answer)) {+ base = c;+ };+ const b = base orelse return null;+ var win = b;+ // Only a strict Pareto improvement may re-seat: >= quality for < money.+ // Among several, the cheapest — the whole point is the efficiency knee.+ for (cands) |c| {+ if (bench.dominates(c, b) and bench.effCost(c) < bench.effCost(win)) win = c;+ }+ return win.name;+}++/// The learned answer for `tier` in `cell` on `provider_id`, or null to keep+/// `ladder_answer` — which is what every sparse, unmeasured or ambiguous case+/// returns, so bootstrap behavior is today's behavior.+pub fn learnedRungIn(+ cells: []const CellObs,+ entries: []const bench.Entry,+ provider_id: []const u8,+ cell: Cell,+ ladder_answer: []const u8,+) ?[]const u8 {+ var buf: [max_candidates]bench.Best = undefined;+ // Strict hierarchy: a cell with real evidence DECIDES, even when it+ // decides to keep the ladder's answer. Only a silent cell falls through+ // to its shape's pooled evidence, and a silent shape to the ladder.+ const exact = seatFor(cellCandidates(&buf, cells, entries, provider_id, cell, true), ladder_answer);+ const answer = exact orelse+ seatFor(cellCandidates(&buf, cells, entries, provider_id, cell, false), ladder_answer) orelse+ return null;+ return if (std.mem.eql(u8, answer, ladder_answer)) null else answer;+}++/// Production entry point: the session's folded cells against the session's+/// live bench sheet. `ladder_answer` is the CATALOG-resolved model the+/// provider ladder seats at the tier being resolved, so the tier is carried+/// implicitly and correctly.+pub fn learnedRung(provider_id: []const u8, cell: Cell, ladder_answer: []const u8) ?[]const u8 {+ return learnedRungIn(g_cells, bench.g_entries, provider_id, cell, ladder_answer);+}++/// `research/sweep@mid` — the id a learned-policy trace line reports, so a+/// user can find the exact cell that moved their worker.+pub fn cellId(buf: []u8, cell: Cell, tier: Tier) []const u8 {+ return std.fmt.bufPrint(buf, "{s}/{s}@{s}", .{ cell.shape.label(), dash(cell.role), tier.label() }) catch buf[0..0];+}++test {+ _ = @import("route_policy_tests.zig");+}diff --git a/src/route_policy_tests.zig b/src/route_policy_tests.zignew file mode 100644index 00000000..1be07eb2--- /dev/null+++ b/src/route_policy_tests.zig@@ -0,0 +1,340 @@+//! Tests for #372 — the routing trace (route_trace.zig) and the learned+//! (shape, role) tier policy (route_policy.zig). Split out so both modules+//! stay under the 600-line cap; wired into the test root by test_hooks.zig.++const std = @import("std");+const Io = std.Io;++const policy = @import("route_policy.zig");+const route_trace = @import("route_trace.zig");+const bench = @import("bench_priors.zig");+const tier_ladder = @import("subagent_tier_ladder.zig");+const pin_mod = @import("subagent_pin.zig");+const provider_mod = @import("provider.zig");+const Provider = provider_mod.Provider;+const trace = @import("trace.zig");++const Cell = policy.Cell;+const Decision = policy.Decision;++fn codex(model: []const u8) Provider {+ return .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = model, .context = 272_000 };+}++/// The synthetic bench sheet the demonstration below runs against. Chosen so+/// the SHEET ALONE keeps the compiled ladder's answer: terra outscores luna+/// (0.60 vs 0.40) and is not dominated by it, so any re-seating that happens+/// 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: terra (the ladder's+/// mid rung) did badly, luna did well. Written in the exact self-describing+/// `kind:"score"` shape route_trace.captureScore emits.+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"}+;++test "#372 trace line: every source kind renders its own attribution, absent fields render -" {+ var buf: [320]u8 = undefined;+ // The line the issue specifies, field for field.+ try std.testing.expectEqualStrings(+ "shape=research role=sweep tier=mid resolved_model=gpt-5.6-terra source=ladder policy_or_genome_id=ladder:codex",+ policy.formatDecision(&buf, .{ .shape = .research, .role = "sweep", .tier = .mid, .resolved_model = "gpt-5.6-terra", .source = .ladder, .policy_id = "ladder:codex" }),+ );+ // Each source kind is spelled with hyphens on the wire, and each is+ // distinguishable — that is the whole point of the field.+ const Case = struct { src: policy.Source, want: []const u8 };+ for ([_]Case{+ .{ .src = .explicit_pin, .want = "source=explicit-pin" },+ .{ .src = .persona, .want = "source=persona" },+ .{ .src = .learned_policy, .want = "source=learned-policy" },+ .{ .src = .workflow_override, .want = "source=workflow-override" },+ .{ .src = .session_default, .want = "source=session-default" },+ .{ .src = .ladder, .want = "source=ladder" },+ }) |case| {+ const line = policy.formatDecision(&buf, .{ .source = case.src });+ try std.testing.expect(std.mem.indexOf(u8, line, case.want) != null);+ }+ // An uncelled worker (off-vocabulary title, off-ladder model) still emits+ // a complete, splittable line rather than empty `key=` fields.+ try std.testing.expectEqualStrings(+ "shape=adhoc role=- tier=- resolved_model=- source=session-default policy_or_genome_id=-",+ policy.formatDecision(&buf, .{}),+ );+ // A model-authored label cannot blow the line up.+ const long: [400]u8 = @splat('x');+ const capped = policy.formatDecision(&buf, .{ .role = &long, .resolved_model = &long, .policy_id = &long });+ try std.testing.expect(capped.len > 0 and capped.len < buf.len);+}++test "#372 trace: the --json agent_route event carries the same six fields" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ var sink: Io.Writer.Allocating = .init(arena_state.allocator());+ route_trace.g_test_sink = &sink;+ defer route_trace.g_test_sink = null;++ route_trace.emitSpawn(std.testing.io, null, "sweep the callers", "codex", "gpt-5.6-terra", .{ .shape = .research, .role = "sweep" }, .ladder, "");+ const line = std.mem.trimEnd(u8, sink.writer.buffered(), "\n");+ try std.testing.expect(std.mem.indexOfScalar(u8, line, '\n') == null); // one complete object per line+ const ev = try std.json.parseFromSliceLeaky(std.json.Value, arena_state.allocator(), line, .{});+ try std.testing.expectEqualStrings("agent_route", ev.object.get("type").?.string);+ try std.testing.expectEqualStrings("research", ev.object.get("shape").?.string);+ try std.testing.expectEqualStrings("sweep", ev.object.get("role").?.string);+ try std.testing.expectEqualStrings("gpt-5.6-terra", ev.object.get("resolved_model").?.string);+ try std.testing.expectEqualStrings("ladder", ev.object.get("source").?.string);+ try std.testing.expectEqualStrings("sweep the callers", ev.object.get("task").?.string);+ // The tier is READ BACK off the resolved model, so an inherited route —+ // the exact case #372 reports as invisible — still names its rung.+ try std.testing.expectEqualStrings("mid", ev.object.get("tier").?.string);+ try std.testing.expectEqualStrings("ladder:codex", ev.object.get("policy_or_genome_id").?.string);+}++test "#372: the shape is read off the phase titles the root model authored" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const parse = struct {+ fn f(alloc: std.mem.Allocator, json: []const u8) []std.json.Value {+ const v = std.json.parseFromSliceLeaky(std.json.Value, alloc, json, .{}) catch unreachable;+ return v.array.items;+ }+ }.f;+ // The real run the issue describes: sweep -> synthesize is shape B.+ try std.testing.expectEqual(policy.Shape.research, policy.shapeOfPhases(parse(a, "[{\"title\":\"sweep the repo\"},{\"title\":\"synthesize\"}]")));+ try std.testing.expectEqual(policy.Shape.review, policy.shapeOfPhases(parse(a, "[{\"title\":\"find security bugs\"},{\"title\":\"verify\"},{\"title\":\"synthesize\"}]")));+ try std.testing.expectEqual(policy.Shape.design, policy.shapeOfPhases(parse(a, "[{\"title\":\"variants\"},{\"title\":\"build it\"}]")));+ try std.testing.expectEqual(policy.Shape.feature, policy.shapeOfPhases(parse(a, "[{\"title\":\"scope\"},{\"title\":\"implement\"},{\"title\":\"review\"}]")));+ // Off-vocabulary titles mint no shape — uncelled, exactly like an+ // off-vocabulary slot (shapes.canonicalSlot's rule).+ try std.testing.expectEqual(policy.Shape.adhoc, policy.shapeOfPhases(parse(a, "[{\"title\":\"ponder\"},{\"title\":\"code review\"}]")));+ try std.testing.expectEqual(policy.Shape.adhoc, policy.shapeOfPhases(parse(a, "[]")));+ // Shape.parse is the closed-vocabulary inverse (an archive row's `shape`+ // column back into the enum); off-vocabulary reads as adhoc, never a guess.+ try std.testing.expectEqual(policy.Shape.research, policy.Shape.parse("research"));+ try std.testing.expectEqual(policy.Shape.adhoc, policy.Shape.parse("Research"));+ try std.testing.expectEqual(policy.Shape.adhoc, policy.Shape.parse(""));+ // The role is the phase's own slot, else the persona niche's slot.+ try std.testing.expectEqualStrings("sweep", policy.roleOf("sweep the repo", "researcher"));+ try std.testing.expectEqualStrings("review", policy.roleOf("do the thing", "review the diff"));+ try std.testing.expectEqualStrings("", policy.roleOf("do the thing", "some-persona"));+ // tierOf is the ladder inverse the trace needs for an unpinned worker.+ try std.testing.expectEqual(tier_ladder.Tier.mid, policy.tierOf("codex", "gpt-5.6-terra").?);+ try std.testing.expectEqual(tier_ladder.Tier.frontier, policy.tierOf("codex", "gpt-5.6-sol").?);+ try std.testing.expect(policy.tierOf("codex", "claude-opus-4-8") == null); // off this ladder+ try std.testing.expectEqualStrings("", policy.tierLabelFor("xai", "grok-4.3")); // no ladder at all+}++test "#372 foldCells: only self-describing score rows become observations" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const archive =+ \\{"kind":"score","prompt_sha":"aa","score":0.5,"shape":"research","role":"sweep","tier":"mid","model":"gpt-5.6-terra"}+ \\{"kind":"score","prompt_sha":"aa","score":0.7,"shape":"research","role":"sweep","tier":"mid","model":"gpt-5.6-terra"}+ \\{"kind":"score","prompt_sha":"zz","score":0.9}+ \\{"kind":"score","prompt_sha":"zz","score":0.9,"shape":"research","role":"sweep","tier":"mid"}+ \\{"kind":"score","prompt_sha":"zz","score":40,"shape":"research","role":"sweep","tier":"mid","model":"gpt-5.6-luna"}+ \\{"kind":"recipe","prompt_sha":"aa","model":"gpt-5.6-luna","effort":"max"}+ \\not json at all+ ;+ const cells = policy.foldCells(a, archive);+ // The bare pre-#372 score row, the coordinate-less one, the 0-100-scale+ // one and the recipe row are all skipped rather than mis-filed.+ try std.testing.expectEqual(@as(usize, 1), cells.len);+ try std.testing.expectEqualStrings("research", cells[0].shape);+ try std.testing.expectEqualStrings("sweep", cells[0].role);+ try std.testing.expectEqualStrings("mid", cells[0].tier);+ try std.testing.expectEqualStrings("gpt-5.6-terra", cells[0].model);+ try std.testing.expectEqual(@as(u32, 2), cells[0].n);+ try std.testing.expectApproxEqAbs(@as(f64, 0.6), cells[0].mean(), 1e-9);+ // An archive with nothing in it is the bootstrap case: zero cells, so+ // every resolution below falls straight through to the ladder.+ try std.testing.expectEqual(@as(usize, 0), policy.foldCells(a, "").len);+}++test "#372 DEMONSTRATION: a dominated mid rung is re-seated, an unobserved cell keeps the ladder answer" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const cells = policy.foldCells(arena_state.allocator(), demo_archive);+ const ladder_mid = tier_ladder.forProvider("codex").?.mid.?; // today's answer: gpt-5.6-terra+ try std.testing.expectEqualStrings("gpt-5.6-terra", ladder_mid);++ // BASELINE — the sheet alone, no lived evidence: terra outscores luna on+ // the sheet, so nothing dominates it and today's ladder answer stands.+ try std.testing.expect(policy.learnedRungIn(&.{}, &demo_sheet, "codex", .{ .shape = .research, .role = "sweep" }, ladder_mid) == null);++ // LEARNED — with the archive folded in, terra blends to (0.60*3 ++ // 0.20*3)/6 = 0.40 while luna blends to (0.40*3 + 0.95*3)/6 = 0.675.+ // luna now matches-and-beats terra's quality for $0.61 against $0.90, so+ // it DOMINATES it and the (research, sweep) mid rung is re-seated.+ const reseated = policy.learnedRungIn(cells, &demo_sheet, "codex", .{ .shape = .research, .role = "sweep" }, ladder_mid);+ try std.testing.expectEqualStrings("gpt-5.6-luna", reseated.?);++ // SPARSE — a cell nobody has ever scored has no basis to move anything,+ // so it falls through the whole hierarchy to today's ladder answer.+ try std.testing.expect(policy.learnedRungIn(cells, &demo_sheet, "codex", .{ .shape = .feature, .role = "implement" }, ladder_mid) == null);+ // ...and so does a role whose shape has evidence but whose SHAPE-level+ // pool still lacks the ladder's own answer to compare against.+ try std.testing.expect(policy.learnedRungIn(cells, &demo_sheet, "codex", .{ .shape = .review, .role = "find" }, ladder_mid) == null);+}++test "#372 hierarchy: exact cell decides, a silent cell borrows its shape, a silent shape keeps the ladder" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const ladder_mid = tier_ladder.forProvider("codex").?.mid.?;++ // A DIFFERENT role in the same shape has no rows of its own, so it+ // borrows the shape-level pool (`sweep`'s evidence) — rung two.+ const cells = policy.foldCells(a, demo_archive);+ try std.testing.expectEqualStrings("gpt-5.6-luna", policy.learnedRungIn(cells, &demo_sheet, "codex", .{ .shape = .research, .role = "synthesize" }, ladder_mid).?);++ // But an exact cell that HAS evidence decides for itself, including+ // deciding to keep the ladder's answer — it must not fall through to a+ // shape-level pool that would have overridden it. Here `synthesize` says+ // terra is excellent and luna is poor, so terra survives.+ const keeps =+ \\{"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":"cc","score":1,"shape":"research","role":"synthesize","tier":"mid","model":"gpt-5.6-terra"}+ \\{"kind":"score","prompt_sha":"cc","score":1,"shape":"research","role":"synthesize","tier":"mid","model":"gpt-5.6-terra"}+ \\{"kind":"score","prompt_sha":"dd","score":0,"shape":"research","role":"synthesize","tier":"small","model":"gpt-5.6-luna"}+ \\{"kind":"score","prompt_sha":"dd","score":0,"shape":"research","role":"synthesize","tier":"small","model":"gpt-5.6-luna"}+ ;+ const split = policy.foldCells(a, keeps);+ try std.testing.expect(policy.learnedRungIn(split, &demo_sheet, "codex", .{ .shape = .research, .role = "synthesize" }, ladder_mid) == null);+ try std.testing.expectEqualStrings("gpt-5.6-luna", policy.learnedRungIn(split, &demo_sheet, "codex", .{ .shape = .research, .role = "sweep" }, ladder_mid).?);++ // A single lucky run is SPARSE (min_model_obs) and moves nothing.+ const one_run =+ \\{"kind":"score","prompt_sha":"aa","score":0.1,"shape":"research","role":"sweep","tier":"mid","model":"gpt-5.6-terra"}+ \\{"kind":"score","prompt_sha":"bb","score":1,"shape":"research","role":"sweep","tier":"small","model":"gpt-5.6-luna"}+ ;+ try std.testing.expect(policy.learnedRungIn(policy.foldCells(a, one_run), &demo_sheet, "codex", .{ .shape = .research, .role = "sweep" }, ladder_mid) == null);+}++test "#372: the learned policy can only ever trade DOWN on cost, never up" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ // The mirror image of the demonstration: luna is the loved model but it+ // is also the CHEAP one, so asking about the `small` rung can never be+ // answered with the pricier terra however well terra scored.+ const archive =+ \\{"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 cells = policy.foldCells(arena_state.allocator(), archive);+ const small = tier_ladder.forProvider("codex").?.small.?;+ try std.testing.expectEqualStrings("gpt-5.6-luna", small);+ try std.testing.expect(policy.learnedRungIn(cells, &demo_sheet, "codex", .{ .shape = .research, .role = "sweep" }, small) == null);+}++test "#372: a learned cell reroutes a TIER pin, and an explicit model pin still outranks it" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();++ // Install the demonstration's evidence as the session's live policy.+ const saved_cells = policy.g_cells;+ const saved_entries = bench.g_entries;+ const saved_ladders = bench.g_ladders;+ defer {+ policy.g_cells = saved_cells;+ bench.g_entries = saved_entries;+ bench.g_ladders = saved_ladders;+ }+ bench.g_ladders = &.{}; // compiled ladder only, so the baseline is pinned+ bench.g_entries = &demo_sheet;+ policy.g_cells = policy.foldCells(arena_state.allocator(), demo_archive);++ const root = codex("gpt-5.6-sol");+ const cell: Cell = .{ .shape = .research, .role = "sweep" };++ // A `tier: mid` ask in this cell now resolves to the model the cell+ // measured as strictly better value, and says so.+ const learned = pin_mod.resolveIn(root, .{ .tier = .mid }, cell);+ try std.testing.expectEqualStrings("gpt-5.6-luna", learned.provider.?.model);+ try std.testing.expectEqual(pin_mod.Source.learned_policy, learned.source);+ try std.testing.expectEqualStrings("codex", learned.provider.?.id); // provider-local, always++ // The SAME ask in an unmeasured cell keeps today's ladder answer.+ const unmeasured = pin_mod.resolveIn(root, .{ .tier = .mid }, .{ .shape = .feature, .role = "implement" });+ try std.testing.expectEqualStrings("gpt-5.6-terra", unmeasured.provider.?.model);+ try std.testing.expectEqual(pin_mod.Source.ladder, unmeasured.source);++ // AN EXPLICIT USER PIN OUTRANKS EVERYTHING LEARNED. Same cell, same+ // session, but the call named a model: the learned layer is never even+ // consulted, and the trace attributes the choice to the human.+ const explicit = pin_mod.resolveIn(root, .{ .model = "gpt-5.6-terra" }, cell);+ try std.testing.expectEqualStrings("gpt-5.6-terra", explicit.provider.?.model);+ try std.testing.expectEqual(pin_mod.Source.explicit_pin, explicit.source);+ // A persona's exact `model:` frontmatter pin likewise wins, and is+ // attributed to the persona rather than to the user's call.+ const persona = pin_mod.resolveIn(root, .{ .model = "gpt-5.6-terra", .from_persona = true }, cell);+ try std.testing.expectEqualStrings("gpt-5.6-terra", persona.provider.?.model);+ try std.testing.expectEqual(pin_mod.Source.persona, persona.source);+ // And the cell-less entry point (every pre-#372 caller) is unchanged.+ try std.testing.expectEqualStrings("gpt-5.6-terra", pin_mod.resolve(root, .{ .tier = .mid }).provider.?.model);+}++test "#372 round trip: what captureVariant writes is exactly what foldCells learns from" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ // A real Trajectory, writing the real rows, into memory.+ var out: Io.Writer.Allocating = .init(a);+ var traj: trace.Trajectory = .{ .io = std.testing.io, .gpa = std.testing.allocator, .out = &out.writer, .start = Io.Timestamp.now(std.testing.io, .awake) };+ defer traj.deinit();+ const saved = trace.g_traj;+ defer trace.g_traj = saved;+ trace.g_traj = &traj;++ // Three judged `sweep` variants on the mid rung, three on the small one —+ // the capture the scoring path makes, with no hand-written JSON anywhere.+ for (0..3) |_| route_trace.captureVariant(codex("gpt-5.6-terra"), .research, "sweep the repo", "sweep", "aa", 0.2);+ for (0..3) |_| route_trace.captureVariant(codex("gpt-5.6-luna"), .research, "sweep the repo", "sweep", "bb", 0.95);++ const cells = policy.foldCells(a, out.writer.buffered());+ try std.testing.expectEqual(@as(usize, 2), cells.len);+ // The rung is derived from the model, not asserted by the caller.+ for (cells) |c| {+ try std.testing.expectEqualStrings("research", c.shape);+ try std.testing.expectEqualStrings("sweep", c.role);+ try std.testing.expectEqual(@as(u32, 3), c.n);+ try std.testing.expectEqualStrings(if (std.mem.eql(u8, c.model, "gpt-5.6-terra")) "mid" else "small", c.tier);+ }+ // ...and the policy reaches the same verdict as the hand-written archive.+ try std.testing.expectEqualStrings(+ "gpt-5.6-luna",+ policy.learnedRungIn(cells, &demo_sheet, "codex", .{ .shape = .research, .role = "sweep" }, "gpt-5.6-terra").?,+ );+}++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.+ 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);+ 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);+}diff --git a/src/route_trace.zig b/src/route_trace.zignew file mode 100644index 00000000..37a4dda0--- /dev/null+++ b/src/route_trace.zig@@ -0,0 +1,205 @@+//! #372 — the observability half of learned orchestration: emitting one+//! worker's routing decision, and capturing a scored one back into the local+//! DGM archive so the policy in route_policy.zig has something to learn from.+//!+//! Split from route_policy.zig (which owns the decision TYPES and the policy+//! itself) both to stay under the 600-line cap and because the two halves+//! have opposite dependency shapes: the policy is a leaf over shapes/bench,+//! while emission reaches the tracer, the trajectory archive, and the --json+//! protocol stream.+//!+//! Three sinks, one call:+//!+//! tracer `{"ev":"route","detail":"shape=… role=… source=…"}` in+//! .graff/traces/<run>.jsonl — the diagnostics path a user+//! greps to answer "why did this worker get that model".+//! trajectory `{"kind":"route", …}` in .graff/trajectories/<run>.jsonl —+//! the same fact as structured columns, so an offline reader can+//! reconstruct which policy ran without parsing the line.+//! --json an additive `agent_route` event on the shared stdout stream,+//! carrying the worker's label so a UI can pair it with the+//! `workflow_progress` task row it belongs to.+//!+//! Best-effort everywhere: a routing trace must never be able to fail a+//! spawn, so every error path is a silent return.++const std = @import("std");+const Io = std.Io;++const policy = @import("route_policy.zig");+const Cell = policy.Cell;+const Decision = policy.Decision;+const Shape = policy.Shape;+const Source = policy.Source;++const trace = @import("trace.zig");+const util = @import("util.zig");+const main_mod = @import("main.zig");+const protocol_seq = @import("protocol_seq.zig");+const scoring = @import("scoring.zig");+const selection = @import("subagent_selection.zig");+const Provider = @import("provider.zig").Provider;++/// Model-authored labels are capped so one absurd description cannot turn a+/// route line into a megabyte of JSONL (workflow_progress.label_cap's rule).+const field_cap = 64;+const line_cap = 320;++pub const RouteEvent = struct {+ type: []const u8 = "agent_route",+ /// The worker's own description/label, so a UI can pair this with the+ /// workflow_progress task row it belongs to.+ task: []const u8,+ shape: []const u8,+ role: []const u8,+ tier: []const u8,+ resolved_model: []const u8,+ provider: []const u8,+ source: []const u8,+ policy_or_genome_id: []const u8,+};++/// Test seam, mirroring workflow_progress.g_test_sink: when set, the --json+/// event renders here instead of stdout.+pub var g_test_sink: ?*Io.Writer.Allocating = null;++fn guiEmit(io: Io, ev: RouteEvent) void {+ if (g_test_sink) |sink| {+ var s: std.json.Stringify = .{ .writer = &sink.writer };+ s.write(ev) catch return;+ sink.writer.writeByte('\n') catch return;+ return;+ }+ if (!main_mod.json_mode) return;+ const w = main_mod.g_out orelse return;+ // The same lock guiEmit/printDelta take: workers emit from pool threads,+ // and a half-written line would corrupt the SDK's JSONL parse.+ main_mod.g_gui_mu.lockUncancelable(io);+ defer main_mod.g_gui_mu.unlock(io);+ protocol_seq.writeEvent(w, ev) catch return;+ w.writeByte('\n') catch return;+ w.flush() catch return;+}++fn tierName(t: ?policy.Tier) []const u8 {+ return if (t) |x| x.label() else "";+}++/// Emit one worker's routing decision on all three paths at once.+pub fn emit(io: Io, tracer: ?*trace.Tracer, label: []const u8, provider_id: []const u8, d: Decision) void {+ var buf: [line_cap]u8 = undefined;+ if (tracer) |tr| tr.note("route", policy.formatDecision(&buf, d));+ if (trace.g_traj) |tj| tj.node(.{+ .kind = "route",+ .label = util.utf8Prefix(label, field_cap),+ .shape = d.shape.label(),+ .role = d.role,+ .tier = tierName(d.tier),+ .model = d.resolved_model,+ .provider = provider_id,+ .source = d.source.label(),+ .policy_or_genome_id = d.policy_id,+ .t = tj.elapsedMs(),+ });+ guiEmit(io, .{+ .task = util.utf8Prefix(label, field_cap),+ .shape = d.shape.label(),+ .role = d.role,+ .tier = tierName(d.tier),+ .resolved_model = d.resolved_model,+ .provider = provider_id,+ .source = d.source.label(),+ .policy_or_genome_id = d.policy_id,+ });+}++/// Build and emit the decision for one spawned worker. `genome` is what+/// `policy_or_genome_id` reports for a decision fleet fitness did NOT make:+/// the root-authored system-prompt fingerprint, the persona niche, or "" for+/// a plain inherit. The tier is read BACK off the resolved model, so a worker+/// that stated no tier still reports the rung it actually landed on — which+/// is the whole point: an inherited route was previously invisible.+pub fn emitSpawn(+ io: Io,+ tracer: ?*trace.Tracer,+ label: []const u8,+ provider_id: []const u8,+ model: []const u8,+ cell: Cell,+ source: Source,+ genome: []const u8,+) void {+ var pbuf: [128]u8 = undefined;+ const tier = policy.tierOf(provider_id, model);+ const policy_id = switch (source) {+ .learned_policy => if (tier) |t| policy.cellId(&pbuf, cell, t) else "",+ .ladder => std.fmt.bufPrint(&pbuf, "ladder:{s}", .{provider_id}) catch "",+ else => util.utf8Prefix(genome, field_cap),+ };+ emit(io, tracer, label, provider_id, .{+ .shape = cell.shape,+ .role = cell.role,+ .tier = tier,+ .resolved_model = model,+ .source = source,+ .policy_id = policy_id,+ });+}++/// What an UNPINNED worker inherited. A session whose worker route came from+/// the #291 ladder descent reports `ladder`; an explicit --subagent-model (or+/// a plain inherit-the-root) reports `session-default`. Conflating the two is+/// exactly the blindness #372 is about.+pub fn sessionSource(session_pinned: bool) Source {+ return if (session_pinned and selection.g_default_from_ladder) .ladder else .session_default;+}++/// emitSpawn for an already-resolved child Provider — the spawn-site+/// convenience. Fingerprints an inline root-authored genome for+/// `policy_or_genome_id`, else names the persona niche the worker ran under.+pub fn emitSpawnProvider(+ io: Io,+ tracer: ?*trace.Tracer,+ label: []const u8,+ child: Provider,+ cell: Cell,+ source: Source,+ sys_override: ?[]const u8,+ niche: []const u8,+) void {+ var fp: [16]u8 = undefined;+ if (sys_override) |so| fp = scoring.promptFingerprint(so);+ emitSpawn(io, tracer, label, child.id, child.model, cell, source, if (sys_override != null) &fp else niche);+}++/// Local DGM capture of one SCORED worker configuration (#372 part 2): the+/// same `kind:"score"` row the eval loop already writes, plus the cell+/// coordinates route_policy.foldCells partitions on. Deliberately OUTSIDE the+/// telemetry gate — a default-local-privacy session must accumulate its own+/// policy evidence with zero egress, exactly like agent_eval's local capture.+pub fn captureScore(prompt_sha: []const u8, niche: []const u8, provider_id: []const u8, d: Decision, score: f64) void {+ const tj = trace.g_traj orelse return;+ tj.node(.{+ .kind = "score",+ .prompt_sha = prompt_sha,+ .score = score,+ .niche = niche,+ .shape = d.shape.label(),+ .role = d.role,+ .tier = tierName(d.tier),+ .model = d.resolved_model,+ .provider = provider_id,+ .t = tj.elapsedMs(),+ });+}++/// One scored variant's policy observation. Role and tier are derived here so+/// the call site (subagent.zig, at the 600-line cap) spends one line on it.+pub fn captureVariant(child: Provider, shape: Shape, title: []const u8, niche: []const u8, genome: []const u8, s01: f64) void {+ captureScore(genome, niche, child.id, .{+ .shape = shape,+ .role = policy.roleOf(title, niche),+ .tier = policy.tierOf(child.id, child.model),+ .resolved_model = child.model,+ }, s01);+}diff --git a/src/subagent.zig b/src/subagent.zigindex 1f768284..3faedd2e 100644--- a/src/subagent.zig+++ b/src/subagent.zig@@ -64,11 +64,18 @@ pub fn execSubagent(ctx: ToolCtx, input: Value) !ToolOutput {// the session default (--subagent-model / the #291 ladder). Resolved// provider-locally here so an unavailable pin degrades to the session// default with a trace note instead of failing the spawn.- const pinned = subagent_pin.forSpawn(childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider), obj, ctx.subagent_provider == null);+ const base = childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider);+ // #372: a bare spawn instantiates no catalog shape, so its cell is+ // (adhoc, <the canonical slot its description or persona niche names>) —+ // the same closed vocabulary a workflow phase files fitness under, so+ // both feed one policy instead of two disjoint ones.+ const cell: route_policy.Cell = .{ .role = route_policy.roleOf(label, niche) };+ const pinned = subagent_pin.forSpawnIn(base, obj, ctx.subagent_provider == null, cell);if (ctx.tracer) |tr| {if (pinned.outcome != .none) tr.note("subagent", pinned.outcome.describe());if (pinned.effort_outcome != .none) tr.note("subagent", pinned.effort_outcome.describe());}+ route_trace.emitSpawnProvider(ctx.io, ctx.tracer, label, pinned.provider orelse base, cell, if (pinned.provider != null) pinned.source else route_trace.sessionSource(ctx.subagent_provider != null), sys_override, niche);if (tools.json_args.flag(input, "run_in_background")) return spawnSubBackground(ctx, label, prompt, sys_override, niche, isolation, isolation_fallback, pinned.provider, pinned.effort);const run = try runSub(ctx, "subagent", label, prompt, sys_override, niche, isolation, isolation_fallback, pinned.provider, pinned.effort);return run.output;@@ -82,6 +89,8 @@ pub const runSub = subagent_run.runSub;const childProvider = subagent_run.childProvider;const variantProviderClass = subagent_run.variantProviderClass;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 traceconst FailKind = subagent_run.FailKind;const classifyFailure = subagent_run.classifyFailure;@@ -484,6 +493,7 @@ pub fn scoreVariants(ctx: ToolCtx,arena: Allocator,title: []const u8,+ shape: route_policy.Shape,prompts: [][]const u8,raws: [][]const u8,overrides: []?[]const u8,@@ -491,7 +501,9 @@ pub fn scoreVariants(outputs: []ToolOutput,) void {if (!main_mod.g_fleet) return;- const t = telemetry.g_telem orelse return;+ // #372: the local (shape, role, tier, model) capture below runs with+ // 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.var vidx: [max_workflow_tasks]usize = undefined;@@ -565,6 +577,10 @@ pub fn scoreVariants(// 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 "";+ // #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);+ 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// scored cell has a servable genome even when runSub never proposed it.diff --git a/src/subagent_pin.zig b/src/subagent_pin.zigindex 6e18562b..3b4f12d6 100644--- a/src/subagent_pin.zig+++ b/src/subagent_pin.zig@@ -64,8 +64,11 @@ const bench_priors = @import("bench_priors.zig");const fleet = @import("fleet.zig");const selection = @import("subagent_selection.zig");const tier_ladder = @import("subagent_tier_ladder.zig");+const route_policy = @import("route_policy.zig"); // #372 learned (shape, role) tier policypub const Tier = tier_ladder.Tier;+pub const Cell = route_policy.Cell;+pub const Source = route_policy.Source;/// Worker reasoning depth (main.zig's ReasoningEffort) — pinnable per persona/// or per spawn since the #292 follow-up; parsed by `parseEffort` below.@@ -85,6 +88,10 @@ pub const Pin = struct {/// same typo discipline as `bad_tier`.effort: ?Effort = null,bad_effort: bool = false,+ /// #372 routing trace: the model/tier axis fell through to the persona's+ /// frontmatter rather than being stated on the call, so the trace can say+ /// `source=persona` instead of claiming the user typed it.+ from_persona: bool = false,pub fn isNone(self: Pin) bool {return self.model == null and self.tier == null and !self.bad_tier and self.effort == null and !self.bad_effort;@@ -138,7 +145,13 @@ pub const EffortOutcome = enum {/// `provider == null` means the spawn keeps whatever it already had; `effort/// == null` likewise (the worker default, not the root's /effort).-pub const Resolved = struct { provider: ?Provider = null, outcome: Outcome = .none, effort: ?Effort = null, effort_outcome: EffortOutcome = .none };+///+/// `source` (#372) names WHICH layer chose the model, for the routing trace:+/// an exact pin reports explicit-pin/persona, a tier reports learned-policy+/// when the (shape, role) cell re-seated the rung and ladder when it did not.+/// A no-opinion Resolved keeps the default, and the caller reports the+/// session-level decision it fell back to.+pub const Resolved = struct { provider: ?Provider = null, outcome: Outcome = .none, effort: ?Effort = null, effort_outcome: EffortOutcome = .none, source: Source = .session_default };fn trimmed(v: std.json.Value) ?[]const u8 {if (v != .string) return null;@@ -193,6 +206,7 @@ pub fn requested(obj: std.json.ObjectMap) Pin {if (call.model == null and call.tier == null and !call.bad_tier) {call.model = persona.model;call.tier = persona.tier;+ call.from_persona = persona.model != null or persona.tier != null;}if (call.effort == null and !call.bad_effort) call.effort = persona.effort;return call;@@ -200,9 +214,22 @@ pub fn requested(obj: std.json.ObjectMap) Pin {/// Resolve `pin` against `base` — the provider the child would otherwise use./// Provider-local: the answer is always `base` with a different model, or no-/// answer at all.+/// answer at all. Cell-less: the learned policy has no partition to consult+/// and the ladder answers alone, exactly as before #372.pub fn resolve(base: Provider, pin: Pin) Resolved {- if (pin.model) |query| return finish(base, selection.modelForProvider(base.id, query));+ return resolveIn(base, pin, .{});+}++/// The same resolution, told WHICH (shape, role) policy cell this spawn+/// belongs to. The cell is consulted at exactly ONE point — choosing which+/// model serves an already-requested tier — and only ever to swap in a+/// candidate that DOMINATES the ladder's own answer on quality-per-dollar.+/// An explicit `model` returns before it, so a user pin still outranks every+/// learned preference; the cost ceiling is re-cleared for the swapped model,+/// so learning can never escalate spend either.+pub fn resolveIn(base: Provider, pin: Pin, cell: Cell) Resolved {+ const pin_src: Source = if (pin.from_persona) .persona else .explicit_pin;+ if (pin.model) |query| return finish(base, selection.modelForProvider(base.id, query), pin_src);if (pin.tier) |tier| {const ladder = tier_ladder.forProvider(base.id) orelse return .{ .outcome = .no_ladder };const rung = ladder.modelFor(tier) orelse return .{ .outcome = .no_rung };@@ -217,7 +244,15 @@ pub fn resolve(base: Provider, pin: Pin) Resolved {// the user chose. Escalation stays possible, but only by naming the// model in the call — visible, never implicit.if (!rungAffordable(base.model, resolved)) return .{ .outcome = .rung_pricier };- return finish(base, resolved);+ // #372: the learned layer sits HERE, below every explicit pin. It is+ // handed the CATALOG-resolved ladder answer and may return a measured+ // improvement on it; a swap that somehow fails the same cost ceiling+ // is dropped rather than failing the spawn, so the worst case is+ // today's ladder answer.+ if (route_policy.learnedRung(base.id, cell, resolved)) |learned| {+ if (rungAffordable(base.model, learned)) return finish(base, learned, .learned_policy);+ }+ return finish(base, resolved, .ladder);}if (pin.bad_tier) return .{ .outcome = .unknown_tier };return .{};@@ -249,7 +284,8 @@ fn subscriptionRung(tier: Tier, base: Provider) ?Resolved {const prov = keys.providerById(sid, resolved) catch continue; // not logged in → not a candidateconst s = bench_priors.scoreFor(sid, resolved) orelse 0;if (best == null or s > best_score) {- best = .{ .provider = prov, .outcome = .sub_routed };+ // source=ladder: it IS a ladder rung, just the subscription's own.+ best = .{ .provider = prov, .outcome = .sub_routed, .source = .ladder };best_score = s;}}@@ -266,10 +302,10 @@ pub fn rungAffordable(base_model: []const u8, rung_model: []const u8) bool {return rp.in + rp.out <= bp.in + bp.out;}-fn finish(base: Provider, name: ?[]const u8) Resolved {+fn finish(base: Provider, name: ?[]const u8, source: Source) Resolved {const resolved = name orelse return .{ .outcome = .unknown_model };- if (std.mem.eql(u8, resolved, base.model)) return .{ .outcome = .same };- return .{ .provider = base.withModel(resolved), .outcome = .pinned };+ if (std.mem.eql(u8, resolved, base.model)) return .{ .outcome = .same, .source = source };+ return .{ .provider = base.withModel(resolved), .outcome = .pinned, .source = source };}/// The whole chain for one spawn: read the pin off the call (or its persona),@@ -279,11 +315,17 @@ fn finish(base: Provider, name: ?[]const u8) Resolved {/// override), else resolve the model axis provider-locally against `base`;/// the effort axis rides through verbatim (it needs no catalog).pub fn forSpawn(base: Provider, obj: std.json.ObjectMap, sub_ok: bool) Resolved {+ return forSpawnIn(base, obj, sub_ok, .{});+}++/// forSpawn with the spawn's #372 policy cell attached — the only difference+/// is which (shape, role) evidence the tier axis may consult.+pub fn forSpawnIn(base: Provider, obj: std.json.ObjectMap, sub_ok: bool, cell: Cell) Resolved {const pin = requested(obj);if (pin.isNone()) return .{};var out: Resolved = blk: {if (sub_ok and pin.model == null) if (pin.tier) |t| if (subscriptionRung(t, base)) |r| break :blk r;- break :blk resolve(base, pin);+ break :blk resolveIn(base, pin, cell);};if (pin.effort) |e| {out.effort = e;diff --git a/src/subagent_selection.zig b/src/subagent_selection.zigindex 32d8602e..0ccfe628 100644--- a/src/subagent_selection.zig+++ b/src/subagent_selection.zig@@ -80,9 +80,17 @@ fn defaultLadderModel(root: provider_mod.Provider) ?[]const u8 {/// pins already enforce).fn defaultLadderProvider(keys: provider_mod.Keys, root: provider_mod.Provider) ?provider_mod.Provider {const target = defaultLadderModel(root) orelse return null;- return subagentProvider(keys, root, null, target, false) catch null;+ const resolved = subagentProvider(keys, root, null, target, false) catch return null;+ g_default_from_ladder = true;+ return resolved;}+/// #372 routing trace: true when the session's worker provider came from the+/// #291 default ladder descent rather than an explicit --subagent-model, so+/// an unpinned spawn can honestly report `source=ladder` vs+/// `source=session-default` instead of conflating the two.+pub var g_default_from_ladder: bool = false;+pub fn subagentProvider(keys: provider_mod.Keys,root: provider_mod.Provider,diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 57982011..ae3bd1dc 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -46,6 +46,10 @@ const subagent_tests = @import("subagent_tests.zig");// Bench score/cost priors → derived tier ladders (.harness/bench.json).const bench_priors = @import("bench_priors.zig");const bench_priors_tests = @import("bench_priors_tests.zig");+// #372 learned orchestration policy + the per-worker routing trace.+const route_policy = @import("route_policy.zig");+const route_policy_tests = @import("route_policy_tests.zig");+const route_trace = @import("route_trace.zig");// `graff serve` resumability (#330): serve.zig imports these, but nothing in// the production graph references their decls, so Zig never analyses them.@@ -84,6 +88,9 @@ test {_ = subagent_tests;_ = bench_priors;_ = bench_priors_tests;+ _ = route_policy;+ _ = route_policy_tests;+ _ = route_trace;_ = serve_events;_ = serve_create;_ = scoring_slot_test;diff --git a/src/workflow.zig b/src/workflow.zigindex f66d635a..3a37a98b 100644--- a/src/workflow.zig+++ b/src/workflow.zig@@ -37,6 +37,8 @@ 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_trace = @import("route_trace.zig"); // #372 per-worker routing traceconst telemetry = @import("telemetry.zig");// #63: stable workflow/phase/task ids + the additive `workflow_progress`// JSONL event, so the REPL can map a run from state instead of scraping the@@ -142,6 +144,7 @@ const StageSpec = struct {niche: []const u8,isolation: Isolation = .shared_cwd, // #276 P0-1isolation_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`@@ -195,6 +198,9 @@ fn pipelineChain(ctx: ToolCtx, item: []const u8, stages: []const StageSpec) Toolvar 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: #292 model pins deliberately do not reach pipeline stages (see subagent_run.variantProviderClass).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) {@@ -297,6 +303,7 @@ fn runPipeline(ctx: ToolCtx, pv: Value, outer_context: []const u8) !ToolOutput {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);@@ -390,6 +397,10 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {// #63 — one stable id per run; every phase/task event below keys to it.const run_id = try wfp.nextRunId(arena);+ // #372 — which catalog shape the root model actually instantiated, read+ // off the phase titles it authored rather than taken on trust. The first+ // component of every worker's policy cell for this run.+ const shape = route_policy.shapeOfPhases(phases);// Telemetry: one "workflow" record per run — phase/task/failure counts// and wall-clock — emitted however the run ends.@@ -472,8 +483,14 @@ 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);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 });}for (futures, outputs, labels, 1..) |*fut, *out, label, task_no| {@@ -545,7 +562,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, prompts, raws, overrides, niches, outputs);+ scoreVariants(ctx, arena, title, shape, 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 };