Skip to content

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

Python

feat(subagent): per-persona and per-spawn worker model pins (#292)

justrach8ab8e0953345
diff --git a/README.md b/README.md
index dcc4efe5..ae59347b 100644
--- a/README.md
+++ b/README.md
@@ -896,6 +896,41 @@ graff --model gpt-5.6-sol \
--allow-cross-provider-subagents
```
+Both of those are session-wide. A **persona** can pin itself in its
+`.harness/agents/<name>.md` frontmatter, and a **single spawn** can override
+either, so one fan-out can put reviewers on a frontier model and mechanical
+workers on the cheap one:
+
+```markdown
+---
+name: implementer
+tier: mid # a rung of the current provider's ladder — preferred,
+ # it stays correct when the root model changes
+# model: gpt-5.6-terra # …or pin an exact name instead
+isolation: worktree
+---
+```
+
+```jsonc
+// one subagent call, overriding everything above for that child only
+{"description": "extract imports", "prompt": "…", "agent": "implementer", "tier": "small"}
+```
+
+Precedence, highest first: **`model`/`tier` on the spawn → the persona's
+`model:`/`tier:` frontmatter → `--subagent-model` → the default tier ladder →
+the root model.** Within one level an exact `model` beats a `tier`. Pins are
+provider-local — they pick a different model on the child's *current* provider
+and never move work across a provider boundary, which stays with
+`--subagent-provider` + `--allow-cross-provider-subagents`. A pin that cannot
+be honored (unknown or ambiguous model name, a model this provider does not
+serve, a tier this family has no rung for) is **ignored with a trace note and
+the spawn still runs** on the session default — a fan-out never dies partway
+through because a persona file names a model the catalog has since renamed.
+Workflow phase tasks and pipeline stages deliberately do *not* take pins: the
+fleet judges a phase's variants against each other and files the winner under
+the prompt genome, so a phase with mixed models would attribute model effects
+to the prompt.
+
The consent matters because worker prompts, selected code, and tool results go
to Kimi while root calls continue to go to Codex; telemetry/upload settings are
independent of that model traffic. Omitting the consent flag fails closed. Put
diff --git a/docs/hyperagents.md b/docs/hyperagents.md
index 7015ef3e..d01bce75 100644
--- a/docs/hyperagents.md
+++ b/docs/hyperagents.md
@@ -149,10 +149,16 @@ In the harness the answer to "where do we create the MAP-Elites" is:
evidence / change code / refute claims), not job titles. Finer grids
encode extra dimensions in the name (`reviewer.terse`, `reviewer.deep`).
- **Elites = `.harness/agents/<niche>.md`.** One markdown per cell:
- frontmatter (`name`, `description`, `score`) + body = the elite's system
- prompt. A file shadows the builtin of the same name — promoting a new
- elite is just overwriting the file. `/agents` lists the live grid with
- each cell's fingerprint and score.
+ frontmatter (`name`, `description`, `score`, plus the operational defaults
+ `isolation`, and #292's `model`/`tier`) + body = the elite's system prompt.
+ A file shadows the builtin of the same name — promoting a new elite is just
+ overwriting the file. `/agents` lists the live grid with each cell's
+ fingerprint and score. Only the body is the *genome*: `model`/`tier` are
+ execution policy for the persona (which rung of the provider's ladder its
+ children run on), never mutated or scored, and they apply to `subagent`
+ spawns only — a workflow phase keeps every variant on one model so the
+ judge's ranking stays attributable to the prompt, not to the tier. A
+ promote rewrites the body and preserves those lines.
- **Selection pressure = the driver.** After scoring a variant
(`h.score(...)`), the driver compares against the incumbent's frontmatter
`score`; if the challenger wins its niche, the driver writes the new
diff --git a/src/fleet.zig b/src/fleet.zig
index bdd3a026..a73b1434 100644
--- a/src/fleet.zig
+++ b/src/fleet.zig
@@ -29,7 +29,7 @@ const http = @import("http.zig");
/// A named, reusable subagent persona: the unit the MAP-Elites archive is
/// organized around (docs/hyperagents.md §MAP-Elites). Each niche keeps one
/// elite prompt; builtins ship compiled in, and `.harness/agents/<name>.md`
-/// files (frontmatter: name/description/score, body: the system prompt)
+/// files (frontmatter: name/description/score/isolation/model/tier, body: the system prompt)
/// override or extend them — that's where an evolution driver promotes
/// archive winners. Spawn one with subagent/workflow `agent: "<name>"`.
/// #276 P0-1: per-agent git-worktree isolation. `.shared_cwd` (default) is
@@ -42,13 +42,18 @@ pub const Isolation = enum {
shared_cwd,
worktree,
- fn parse(s: []const u8) ?Isolation {
+ pub fn parse(s: []const u8) ?Isolation {
if (std.mem.eql(u8, s, "worktree")) return .worktree;
if (std.mem.eql(u8, s, "shared_cwd")) return .shared_cwd;
return null;
}
};
+/// #292: the ladder rung vocabulary a persona may pin itself to
+/// (`tier: mid`). Re-exported here so `.harness/agents` readers and the
+/// `subagent` tool schema name the same three rungs.
+pub const Tier = @import("subagent_tier_ladder.zig").Tier;
+
pub const AgentType = struct {
name: []const u8,
desc: []const u8,
@@ -57,6 +62,14 @@ pub const AgentType = struct {
builtin: bool = false,
learned: bool = false,
isolation: ?Isolation = null, // persona default (frontmatter `isolation: worktree`); null = no opinion, falls through to shared_cwd
+ // #292 persona model pin. Both null = no opinion; the spawn keeps the
+ // session default (--subagent-model or the #291 ladder). `model` is an
+ // exact name and wins over `tier` when a persona sets both; neither is
+ // validated here — resolution happens per spawn against the live catalog
+ // (subagent_pin.zig) so an unavailable pin degrades to the session
+ // default instead of failing a persona load or a spawn mid-fleet.
+ model: ?[]const u8 = null, // frontmatter `model: gpt-5.6-terra`
+ tier: ?Tier = null, // frontmatter `tier: mid`
};
/// Preloaded niches: deliberately orthogonal *behavioral* dimensions (what
@@ -136,7 +149,8 @@ pub fn loadAgentTypes(io: Io, arena: Allocator, home: ?[]const u8) []const Agent
}
/// Merge `<dir>/*.md` personas into `list`: YAML-ish frontmatter
-/// (name/description/score) + body as the prompt. A file shadows any existing
+/// (name/description/score/isolation/model/tier) + body as the prompt. A
+/// file shadows any existing
/// type (builtin or earlier tier) of the same name — the elite for a niche is
/// whatever the highest tier last promoted.
fn loadAgentDir(io: Io, arena: Allocator, list: *std.ArrayList(AgentType), dir_path: []const u8) void {
@@ -165,6 +179,11 @@ fn loadAgentDir(io: Io, arena: Allocator, list: *std.ArrayList(AgentType), dir_p
if (std.mem.eql(u8, key, "description")) at.desc = val;
if (std.mem.eql(u8, key, "score")) at.score = std.fmt.parseFloat(f64, val) catch null;
if (std.mem.eql(u8, key, "isolation")) at.isolation = Isolation.parse(val); // #276: e.g. an "implementer" persona opting into worktree isolation by default
+ // #292: a persona's own worker-model pin. An unknown tier
+ // name parses to null (no opinion) rather than failing the
+ // load, and an unknown model name is caught per spawn.
+ if (std.mem.eql(u8, key, "model")) at.model = if (val.len > 0) val else null;
+ if (std.mem.eql(u8, key, "tier")) at.tier = Tier.parse(val);
}
const body_start = fm_end + "\n---".len;
at.prompt = std.mem.trim(u8, data[@min(body_start + 1, data.len)..], " \t\r\n");
@@ -276,7 +295,11 @@ pub fn promoteAgents(io: Io, gpa: Allocator, out: *Io.Writer, home: ?[]const u8,
}
}
const path = std.fmt.allocPrint(arena, "{s}/{s}.md", .{ dir, champ.niche }) catch continue;
- 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---\n{s}\n", .{ champ.niche, champ_mean, champ.n, champ.sha, champ_mean, champ.text }) catch continue;
+ // Promotion ranks GENOMES; the persona's operational frontmatter
+ // (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;
const f = Io.Dir.cwd().createFile(io, path, .{}) catch continue;
defer f.close(io);
var wbuf: [4096]u8 = undefined;
diff --git a/src/provider.zig b/src/provider.zig
index 3adc8b24..a2ad99ae 100644
--- a/src/provider.zig
+++ b/src/provider.zig
@@ -169,6 +169,35 @@ pub const Provider = struct {
const proportional: usize = @intCast(p.context / 2);
return @min(proportional, abs_output_cap_bytes);
}
+
+ /// #292: the same credential and the same provider, a different model.
+ /// Rebuilds exactly the fields Keys.build derives from the model name
+ /// (wire format, auth style, endpoint, context window) while carrying the
+ /// already-resolved api_key/account/source across, so a per-persona or
+ /// per-spawn worker pin needs no `Keys` at the spawn site — and, by
+ /// construction, cannot change provider. Crossing a provider boundary
+ /// still goes through Keys/subagentProvider and its explicit consent flag.
+ pub fn withModel(base: Provider, model: []const u8) Provider {
+ const spec = specFor(base.id) orelse {
+ var out = base;
+ out.model = model;
+ out.context = contextWindowFor(base.id, model);
+ return out;
+ };
+ const is_codex = std.mem.eql(u8, spec.id, "codex");
+ const is_kimi_anthropic = std.mem.eql(u8, spec.id, "kimi") and pricing.kimiProtocol(model) == .anthropic;
+ return .{
+ .id = spec.id,
+ .kind = if (is_kimi_anthropic) .anthropic else spec.kind,
+ .auth = if (is_kimi_anthropic) .x_api_key else spec.auth,
+ .url = if (is_kimi_anthropic) kimi_anthropic_url else if (is_codex) g_codex_url_override orelse spec.url else spec.url,
+ .api_key = base.api_key,
+ .model = model,
+ .context = contextWindowFor(spec.id, model),
+ .account = base.account,
+ .source = base.source,
+ };
+ }
};
/// The catalogued provider ids that serve `model`, in spec order, written into
diff --git a/src/schema.zig b/src/schema.zig
index 71de1a47..d6800439 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -151,9 +151,9 @@ const meta_specs = [_]ToolSpec{
const subagent_spec = ToolSpec{
.name = "subagent",
- .desc = "Delegate a self-contained task to a subagent. It has bash, read_file, edit_file, write_file, codedb (code search), and skill (load an installed playbook); it cannot spawn further subagents and does NOT share your context — the prompt must be self-contained. Returns the subagent final report. Call several times in one response to run tasks in parallel. Pick a persona with agent (builtins: reviewer, researcher, implementer, skeptic — plus any in .harness/agents/), or give the child a custom system_prompt; the trajectory log records the lineage either way. Set run_in_background true to launch it asynchronously instead: you get the agent id back immediately and keep working, then fetch the result with agent_output.",
+ .desc = "Delegate a self-contained task to a subagent. It has bash, read_file, edit_file, write_file, codedb (code search), and skill (load an installed playbook); it cannot spawn further subagents and does NOT share your context — the prompt must be self-contained. Returns the subagent final report. Call several times in one response to run tasks in parallel. Pick a persona with agent (builtins: reviewer, researcher, implementer, skeptic — plus any in .harness/agents/), or give the child a custom system_prompt; the trajectory log records the lineage either way. Set run_in_background true to launch it asynchronously instead: you get the agent id back immediately and keep working, then fetch the result with agent_output. Which model this child runs on is decided in this order: model/tier given on THIS call > the chosen persona's own model:/tier: frontmatter > the session default (--subagent-model, else the default tier ladder) > the root model; within one level an exact model wins over tier. Pins are provider-local — they choose a different model on the child's current provider and never move work to another provider — and a pin that cannot be honored is ignored (the spawn still runs on the session default) rather than failing.",
.schema =
- \\{"type": "object", "properties": {"description": {"type": "string", "description": "Short label for logs, 3-5 words"}, "prompt": {"type": "string", "description": "Complete, self-contained task description"}, "agent": {"type": "string", "description": "Optional: a named agent type (reviewer, researcher, implementer, skeptic, or a .harness/agents/ name) whose persona the child runs with"}, "system_prompt": {"type": "string", "description": "Optional: replace the child's system prompt with a custom one (overrides agent)"}, "isolation": {"type": "string", "enum": ["shared_cwd", "worktree"], "description": "Optional: \"worktree\" gives this child its own scratch git worktree (auto-removed if it finishes with no changes, kept + reported if it has any) instead of the shared working tree — use for parallel agents that edit files. Default shared_cwd (today's behavior), unless the chosen agent persona sets its own default."}, "isolation_fallback": {"type": "boolean", "description": "Optional: if isolation:\"worktree\" fails to set up (not a git repo, git error), run in the shared working tree instead of failing the spawn. Default false (fails the spawn on setup failure)."}, "run_in_background": {"type": "boolean", "description": "Optional: start this subagent asynchronously and return its agent id immediately instead of waiting for it to finish (default false). Poll status/result with agent_output (id, optional wait_ms). A spawn beyond the concurrency cap is queued, never failed."}}, "required": ["description", "prompt"]}
+ \\{"type": "object", "properties": {"description": {"type": "string", "description": "Short label for logs, 3-5 words"}, "prompt": {"type": "string", "description": "Complete, self-contained task description"}, "agent": {"type": "string", "description": "Optional: a named agent type (reviewer, researcher, implementer, skeptic, or a .harness/agents/ name) whose persona the child runs with"}, "system_prompt": {"type": "string", "description": "Optional: replace the child's system prompt with a custom one (overrides agent)"}, "model": {"type": "string", "description": "Optional: run THIS child on an exact model name available on the current provider (e.g. \"gpt-5.6-luna\"). Highest precedence — beats the persona's own pin and the session default. Ignored (spawn still runs on the session default, with a trace note) if the name is unknown, ambiguous, or not served by this provider. Never crosses providers."}, "tier": {"type": "string", "enum": ["frontier", "mid", "small"], "description": "Optional: run THIS child on a rung of the current provider's model ladder instead of an exact name — frontier (planner/judge class), mid (reviewers, implementers, researchers), small (mechanical transform/extract/label). Prefer this over model: it stays correct when the root model changes. Ignored if the provider has no ladder or no model at that rung; model wins if both are given."}, "isolation": {"type": "string", "enum": ["shared_cwd", "worktree"], "description": "Optional: \"worktree\" gives this child its own scratch git worktree (auto-removed if it finishes with no changes, kept + reported if it has any) instead of the shared working tree — use for parallel agents that edit files. Default shared_cwd (today's behavior), unless the chosen agent persona sets its own default."}, "isolation_fallback": {"type": "boolean", "description": "Optional: if isolation:\"worktree\" fails to set up (not a git repo, git error), run in the shared working tree instead of failing the spawn. Default false (fails the spawn on setup failure)."}, "run_in_background": {"type": "boolean", "description": "Optional: start this subagent asynchronously and return its agent id immediately instead of waiting for it to finish (default false). Poll status/result with agent_output (id, optional wait_ms). A spawn beyond the concurrency cap is queued, never failed."}}, "required": ["description", "prompt"]}
,
};
diff --git a/src/subagent.zig b/src/subagent.zig
index 1afd9ab8..d0e14e4e 100644
--- a/src/subagent.zig
+++ b/src/subagent.zig
@@ -60,15 +60,23 @@ pub fn execSubagent(ctx: ToolCtx, input: Value) !ToolOutput {
const niche = fleet.resolveNiche(obj);
const isolation = fleet.resolveIsolation(obj);
const isolation_fallback = fleet.resolveIsolationFallback(obj);
- if (tools.json_args.flag(input, "run_in_background")) return spawnSubBackground(ctx, label, prompt, sys_override, niche, isolation, isolation_fallback);
- const run = try runSub(ctx, "subagent", label, prompt, sys_override, niche, isolation, isolation_fallback);
+ // #292: explicit spawn `model`/`tier` > the persona's frontmatter pin >
+ // 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);
+ if (ctx.tracer) |tr| if (pinned.outcome != .none) tr.note("subagent", pinned.outcome.describe());
+ if (tools.json_args.flag(input, "run_in_background")) return spawnSubBackground(ctx, label, prompt, sys_override, niche, isolation, isolation_fallback, pinned.provider);
+ const run = try runSub(ctx, "subagent", label, prompt, sys_override, niche, isolation, isolation_fallback, pinned.provider);
return run.output;
}
const subagent_run = @import("subagent_run.zig");
+const subagent_pin = @import("subagent_pin.zig"); // #292 per-persona / per-spawn model pins
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 shapes = @import("shapes.zig");
const FailKind = subagent_run.FailKind;
@@ -113,6 +121,12 @@ const AgentJob = struct {
niche: []u8,
isolation: Isolation,
isolation_fallback: bool,
+ /// #292: resolved per-spawn model pin. Stored by value with the same
+ /// lifetime assumption `ctx.provider`/`ctx.subagent_provider` below
+ /// already rely on — a Provider's strings come from the spec table, the
+ /// model catalog and the credential store, none of which are the tool
+ /// call's arena — so unlike label/prompt it needs no gpa copy.
+ pin: ?Provider = null,
ctx: ToolCtx,
admitted: bool = false,
done: bool = false,
@@ -183,7 +197,7 @@ fn admitNext(gpa: Allocator, io: Io) void {
/// shape in jobs.zig.
fn agentJobPump(job: *AgentJob, gpa: Allocator, io: Io) void {
const t0: Io.Timestamp = .now(io, .awake);
- const run = runSub(job.ctx, "subagent", job.label, job.prompt, job.sys_override, job.niche, job.isolation, job.isolation_fallback) catch |err| SubRun{
+ const run = runSub(job.ctx, "subagent", job.label, job.prompt, job.sys_override, job.niche, job.isolation, job.isolation_fallback, job.pin) catch |err| SubRun{
.output = failure(gpa, err),
.usage = .{ .duration_ms = @intCast(@max(0, t0.untilNow(io, .awake).toMilliseconds())) },
};
@@ -201,7 +215,7 @@ fn agentJobPump(job: *AgentJob, gpa: Allocator, io: Io) void {
/// job and return immediately with its id; the child runs on the pool.
/// Never blocks on a free concurrency slot — a spawn beyond the cap is
/// queued, not failed; admitNext drains it once room frees up.
-fn spawnSubBackground(ctx: ToolCtx, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8, isolation: Isolation, isolation_fallback: bool) !ToolOutput {
+fn spawnSubBackground(ctx: ToolCtx, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8, isolation: Isolation, isolation_fallback: bool, pin: ?Provider) !ToolOutput {
const gpa = ctx.gpa;
const label_c = try gpa.dupe(u8, label);
errdefer gpa.free(label_c);
@@ -221,6 +235,7 @@ fn spawnSubBackground(ctx: ToolCtx, label: []const u8, prompt: []const u8, sys_o
.niche = niche_c,
.isolation = isolation,
.isolation_fallback = isolation_fallback,
+ .pin = pin,
.ctx = ctx,
};
@@ -397,14 +412,16 @@ test "agentStatusText: composes with isolation:\"worktree\" — a kept-worktree
/// `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 {
- const run = runSub(ctx, "workflow_task", label, prompt, sys_override, niche, isolation, isolation_fallback) catch |err| return failure(ctx.gpa, err);
+ // No #292 pin: a phase's variants must share a model 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) 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) catch |err| return failure(ctx.gpa, err);
+ const run = runSub(ctx, "workflow_retry", label, prompt, sys_override, niche, isolation, isolation_fallback, null) catch |err| return failure(ctx.gpa, err);
return run.output;
}
@@ -414,14 +431,15 @@ pub fn workflowRetryTask(ctx: ToolCtx, label: []const u8, prompt: []const u8, sy
/// on a pool thread. Never worktree-isolated: a judge only reads/reasons over
/// text handed to it, never the filesystem, so there's nothing to isolate.
pub fn judgeTask(ctx: ToolCtx, prompt: []const u8) ToolOutput {
- const run = runSub(ctx, "judge_task", "judge", prompt, null, "", .shared_cwd, false) catch |err| return failure(ctx.gpa, err);
+ const run = runSub(ctx, "judge_task", "judge", prompt, null, "", .shared_cwd, false, null) catch |err| return failure(ctx.gpa, err);
return run.output;
}
/// Build the judge prompt that scores one workflow variant's output against its
/// task on a 0-100 scale (see scoreVariants). Bounded: the task spec and output
/// tail are truncated so a fat phase can't blow up the judge's context.
-fn variantJudgePrompt(arena: Allocator, title: []const u8, task: []const u8, output: []const u8) ![]const u8 {
+/// pub only so subagent_tests.zig can reach it (this file is at the cap).
+pub fn variantJudgePrompt(arena: Allocator, title: []const u8, task: []const u8, output: []const u8) ![]const u8 {
const spec = util.utf8Prefix(task, 1200);
const work = if (output.len > 2000) output[output.len - 2000 ..] else output;
return std.fmt.allocPrint(arena,
@@ -553,48 +571,3 @@ pub fn scoreVariants(
t.fleetEvent("submit", niche, genome, "", pclass, esh, 0, "");
}
}
-
-test "variantJudgePrompt: bounded, names the phase, keeps the score contract" {
- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena.deinit();
- const a = arena.allocator();
-
- const big_task = util.repeatBytes("T", 4000);
- const big_out = util.repeatBytes("O", 5000);
- const p = try variantJudgePrompt(a, "code-review", &big_task, &big_out);
-
- // Names the shared phase so the judge has the tournament context.
- try std.testing.expect(std.mem.indexOf(u8, p, "\"code-review\" phase") != null);
- // Task is prefix-capped and output tail-capped — neither lands verbatim.
- try std.testing.expect(std.mem.indexOf(u8, p, &big_task) == null);
- try std.testing.expect(std.mem.indexOf(u8, p, &big_out) == null);
- // The `score:` contract parseEvalScore depends on is spelled out…
- try std.testing.expect(std.mem.indexOf(u8, p, "score: <N>") != null);
- // …and it round-trips: a judge tail like this parses back to the score.
- try std.testing.expectEqual(@as(?f64, 87), repl_glue.parseEvalScore("ok\nscore: 87"));
-}
-
-test "classifyFailure: maps the child's api-error detail to a category + retry-safety" {
- // A stream stall/drop names itself via the error kind — its stale envelope
- // (if any) must not override the transport verdict.
- try std.testing.expectEqual(FailKind.transport, classifyFailure(error.StreamStalled, null));
- try std.testing.expectEqual(FailKind.transport, classifyFailure(error.StreamDropped, "api error (some_error): stale"));
- // No detail to go on → unknown (and a retry is still allowed to be tried).
- try std.testing.expectEqual(FailKind.unknown, classifyFailure(error.ApiError, null));
- // Real provider envelopes (the shapes sayApiError formats into last_api_error).
- try std.testing.expectEqual(FailKind.quota, classifyFailure(error.ApiError, "api error (rate_limit_error): Number of requests exceeded"));
- try std.testing.expectEqual(FailKind.quota, classifyFailure(error.ApiError, "api error: You have run out of credits or need a Grok subscription."));
- try std.testing.expectEqual(FailKind.auth, classifyFailure(error.ApiError, "api error: The API Key appears to be invalid or may have expired."));
- // invalid_request_error carries "invalid", but a missing-model message is
- // classified as model-availability because that phrase is checked first.
- try std.testing.expectEqual(FailKind.model, classifyFailure(error.ApiError, "api error (invalid_request_error): The model `gpt-foo` does not exist or you do not have access to it."));
- try std.testing.expectEqual(FailKind.invalid, classifyFailure(error.ApiError, "api error (invalid_request_error): This model's maximum context length is 8192 tokens."));
- try std.testing.expectEqual(FailKind.transport, classifyFailure(error.ApiError, "network error: HttpConnectionClosing (gave up after 6 attempts)"));
-
- // Retry-safety contract: transient failures may retry, structural ones must not.
- try std.testing.expect(FailKind.quota.retrySafe());
- try std.testing.expect(FailKind.transport.retrySafe());
- try std.testing.expect(!FailKind.model.retrySafe());
- try std.testing.expect(!FailKind.invalid.retrySafe());
- try std.testing.expect(!FailKind.auth.retrySafe());
-}
diff --git a/src/subagent_pin.zig b/src/subagent_pin.zig
new file mode 100644
index 00000000..a6c2d149
--- /dev/null
+++ b/src/subagent_pin.zig
@@ -0,0 +1,186 @@
+//! Per-persona and per-spawn worker model pins (#292).
+//!
+//! #291 (4f9e7a7) made the worker model a SESSION-wide decision: absent an
+//! explicit --subagent-model, every child descends one rung of the provider's
+//! tier ladder. That is still the default; this module adds the two finer
+//! grains the issue asks for, on top of it rather than beside it.
+//!
+//! 1. A persona in `.harness/agents/<name>.md` may pin itself in
+//! frontmatter — `model: gpt-5.6-terra` (exact) or `tier: mid` (a rung
+//! of whatever ladder the current provider is on). Parsed in fleet.zig
+//! into AgentType.model/.tier; resolved here.
+//! 2. One `subagent` call may pin `model` / `tier` for that spawn only.
+//!
+//! PRECEDENCE (what the tool schema advertises, implemented by `requested`
+//! and `resolve` below):
+//!
+//! explicit spawn param > persona frontmatter > session default
+//! (--subagent-model / the #291 ladder) > root model
+//!
+//! Within one level an exact `model` beats a `tier`: it is the more specific
+//! statement. Across levels the level wins, so a spawn that says `tier: small`
+//! overrides a persona that says `model: gpt-5.6-sol` — otherwise a per-spawn
+//! override could not lower a persona's pin, which is its whole point.
+//!
+//! PROVIDER LOCALITY. A pin resolves only against the catalog rows of the
+//! provider the child was ALREADY going to use (root, or --subagent-provider
+//! once --allow-cross-provider-subagents consented). So a pin can never move
+//! prompts, code, or billing to a second provider: that decision stays with
+//! the startup flag and its consent gate, exactly as #292 requires, and
+//! Provider.withModel makes it structurally impossible here.
+//!
+//! GRACEFUL FALLBACK. Every failure to honour a pin resolves to a null
+//! provider, which the spawn path reads as "keep the session default".
+//! Unknown model name, a name that is real but not served by this provider,
+//! an ambiguous abbreviation, an off-vocabulary tier, a provider with no
+//! ladder, a rung the family does not have — all of them still produce a
+//! working spawn. A fan-out must never die halfway through because one
+//! persona file names a model the catalog has since renamed; Outcome.describe
+//! supplies the human-readable reason for the trace instead.
+//!
+//! FLEET SAFETY (#290). Pins are wired into the `subagent` tool only, not
+//! workflow phases / pipeline stages. scoreVariants judges the variants of one
+//! phase against each other and files the result under the prompt genome, so
+//! letting phase tasks vary the model would reintroduce exactly the confound
+//! #290 closed. subagent_run.variantProviderClass documents that seam.
+
+const std = @import("std");
+
+const provider_mod = @import("provider.zig");
+const Provider = provider_mod.Provider;
+const fleet = @import("fleet.zig");
+const selection = @import("subagent_selection.zig");
+const tier_ladder = @import("subagent_tier_ladder.zig");
+
+pub const Tier = tier_ladder.Tier;
+
+/// A requested pin, before it has been checked against any catalog. All
+/// fields at their defaults means "no opinion" — keep the session default.
+pub const Pin = struct {
+ model: ?[]const u8 = null,
+ /// A parsed ladder rung. Only consulted when `model` is null.
+ tier: ?Tier = null,
+ /// The request named a `tier` whose value is off-vocabulary. Kept
+ /// distinct from "no tier" so a typo is reported rather than silently
+ /// falling through to a persona pin the caller was trying to override.
+ bad_tier: bool = false,
+
+ pub fn isNone(self: Pin) bool {
+ return self.model == null and self.tier == null and !self.bad_tier;
+ }
+};
+
+/// Why a pin did or did not change the child's model. Carried to the trace so
+/// an ignored pin is visible rather than silent — the failure a hard error
+/// would have made obvious is instead made observable.
+pub const Outcome = enum {
+ none, // no pin was requested
+ pinned, // honored
+ same, // resolved to the model the child already had
+ unknown_model, // not an available model on this provider (or ambiguous)
+ unknown_tier, // `tier` was not one of frontier/mid/small
+ no_ladder, // this provider has no tier ladder
+ no_rung, // the ladder has no model at that rung
+
+ pub fn describe(self: Outcome) []const u8 {
+ return switch (self) {
+ .none => "",
+ .pinned => "model pin applied",
+ .same => "model pin is already the active model",
+ .unknown_model => "model pin ignored: not an available model on this provider — kept the session default",
+ .unknown_tier => "tier pin ignored: expected frontier, mid or small — kept the session default",
+ .no_ladder => "tier pin ignored: this provider has no tier ladder — kept the session default",
+ .no_rung => "tier pin ignored: this provider's ladder has no model at that rung — kept the session default",
+ };
+ }
+};
+
+/// `provider == null` means the spawn keeps whatever it already had.
+pub const Resolved = struct { provider: ?Provider = null, outcome: Outcome = .none };
+
+fn trimmed(v: std.json.Value) ?[]const u8 {
+ if (v != .string) return null;
+ const s = std.mem.trim(u8, v.string, " \t\r\n");
+ return if (s.len == 0) null else s;
+}
+
+/// The persona's own pin, if `name` matches a loaded agent type. An unknown
+/// name is "no opinion", matching resolveOverride/resolveIsolation's
+/// never-fail-a-spawn-on-a-typo contract.
+pub fn personaPin(name: []const u8) Pin {
+ if (name.len == 0) return .{};
+ for (fleet.g_agent_types) |t| {
+ if (std.mem.eql(u8, t.name, name)) return .{ .model = t.model, .tier = t.tier };
+ }
+ return .{};
+}
+
+/// The pin for one spawn, applying the cross-level half of the precedence
+/// rule: an explicit `model`/`tier` on the call replaces the persona's pin
+/// wholesale (it does not merge with it), and only a call that states neither
+/// falls through to the persona.
+pub fn requested(obj: std.json.ObjectMap) Pin {
+ var call: Pin = .{};
+ if (obj.get("model")) |v| call.model = trimmed(v);
+ if (obj.get("tier")) |v| if (trimmed(v)) |raw| {
+ call.tier = Tier.parse(raw);
+ call.bad_tier = call.tier == null;
+ };
+ if (!call.isNone()) return call;
+ if (obj.get("agent")) |v| if (v == .string) return personaPin(v.string);
+ return .{};
+}
+
+/// 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.
+pub fn resolve(base: Provider, pin: Pin) Resolved {
+ if (pin.model) |query| return finish(base, selection.modelForProvider(base.id, query));
+ 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 };
+ // A ladder rung is still checked against the LIVE catalog: `graff
+ // models refresh` can drop a model the compiled ladder names, and a
+ // pin resolving to a model the provider no longer serves must fall
+ // back rather than send a request that 404s mid-fleet.
+ return finish(base, selection.modelForProvider(base.id, rung));
+ }
+ if (pin.bad_tier) return .{ .outcome = .unknown_tier };
+ return .{};
+}
+
+fn finish(base: Provider, name: ?[]const u8) 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 };
+}
+
+/// The whole chain for one spawn: read the pin off the call (or its persona),
+/// then resolve it provider-locally against `base`.
+pub fn forSpawn(base: Provider, obj: std.json.ObjectMap) Resolved {
+ const pin = requested(obj);
+ if (pin.isNone()) return .{};
+ return resolve(base, pin);
+}
+
+/// The live persona's OPERATIONAL frontmatter lines — isolation plus #292's
+/// model/tier — arena-allocated and newline-terminated, or "" when it has
+/// none.
+///
+/// Promotion (fleet.promoteAgents) replaces a niche's genome with a better
+/// scoring one, and rewrites `<niche>.md` from scratch to do it. Without this
+/// the rewrite would silently drop the persona's execution policy, so
+/// `/agents promote` would un-pin every persona that had been given a worktree
+/// default or a model rung — a config change nobody asked for, made by a
+/// command about prompts. Genome and policy are different things; only the
+/// former is what promotion is ranking.
+pub fn personaPolicyFrontmatter(arena: std.mem.Allocator, name: []const u8) []const u8 {
+ for (fleet.g_agent_types) |t| {
+ if (!std.mem.eql(u8, t.name, name)) continue;
+ const iso = if (t.isolation) |i| std.fmt.allocPrint(arena, "isolation: {s}\n", .{@tagName(i)}) catch "" else "";
+ const mdl = if (t.model) |m| std.fmt.allocPrint(arena, "model: {s}\n", .{m}) catch "" else "";
+ const rung = if (t.tier) |x| std.fmt.allocPrint(arena, "tier: {s}\n", .{x.label()}) catch "" else "";
+ return std.fmt.allocPrint(arena, "{s}{s}{s}", .{ iso, mdl, rung }) catch "";
+ }
+ return "";
+}
diff --git a/src/subagent_pin_tests.zig b/src/subagent_pin_tests.zig
new file mode 100644
index 00000000..bf2d3e8d
--- /dev/null
+++ b/src/subagent_pin_tests.zig
@@ -0,0 +1,266 @@
+//! Tests for #292's per-persona / per-spawn worker model pins. Split out of
+//! subagent_pin.zig so the module itself stays comfortably under the 600-line
+//! cap; wired into the test root by test_hooks.zig.
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+const Value = std.json.Value;
+
+const fleet = @import("fleet.zig");
+const pin_mod = @import("subagent_pin.zig");
+const provider_mod = @import("provider.zig");
+const Provider = provider_mod.Provider;
+const Tier = pin_mod.Tier;
+
+fn obj(a: Allocator, s: []const u8) std.json.ObjectMap {
+ return (std.json.parseFromSliceLeaky(Value, a, s, .{}) catch unreachable).object;
+}
+
+/// A codex-provider child on the flagship rung — the base a pin resolves
+/// against. Built by hand rather than through Keys so the tests need no
+/// credentials; withModel only ever reads `id`/`api_key`/`account`/`source`
+/// off it.
+fn codexBase() Provider {
+ return .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "https://example.invalid", .api_key = "k", .model = "gpt-5.6-sol", .context = 272_000 };
+}
+
+test "persona frontmatter parse: model/tier land on AgentType, a bad tier is dropped" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ // This is exactly the shape loadAgentDir produces; parsing itself is
+ // covered end-to-end by the loader, so what is pinned here is the
+ // contract the loader must satisfy: an unknown tier is "no opinion", not
+ // a load failure, and an exact model rides through unvalidated.
+ const saved = fleet.g_agent_types;
+ defer fleet.g_agent_types = saved;
+ fleet.g_agent_types = &.{
+ .{ .name = "implementer", .desc = "", .prompt = "x", .tier = Tier.parse("mid") },
+ .{ .name = "reviewer", .desc = "", .prompt = "x", .model = "gpt-5.6-terra" },
+ .{ .name = "typo", .desc = "", .prompt = "x", .tier = Tier.parse("cheap") }, // off-vocabulary
+ .{ .name = "plain", .desc = "", .prompt = "x" },
+ };
+
+ try std.testing.expectEqual(Tier.mid, pin_mod.personaPin("implementer").tier.?);
+ try std.testing.expect(pin_mod.personaPin("implementer").model == null);
+ try std.testing.expectEqualStrings("gpt-5.6-terra", pin_mod.personaPin("reviewer").model.?);
+ // A persona whose `tier:` did not parse contributes nothing at all — the
+ // spawn keeps the session default rather than inheriting a guess.
+ try std.testing.expect(pin_mod.personaPin("typo").isNone());
+ try std.testing.expect(pin_mod.personaPin("plain").isNone());
+ // An unknown persona name is never an error (matches resolveIsolation).
+ try std.testing.expect(pin_mod.personaPin("not-a-persona").isNone());
+ try std.testing.expect(pin_mod.personaPin("").isNone());
+
+ // …and the pin reaches a spawn that only names the persona.
+ try std.testing.expectEqualStrings("gpt-5.6-terra", pin_mod.forSpawn(codexBase(), obj(a, "{\"agent\":\"implementer\"}")).provider.?.model);
+ try std.testing.expectEqualStrings("gpt-5.6-terra", pin_mod.forSpawn(codexBase(), obj(a, "{\"agent\":\"reviewer\"}")).provider.?.model);
+ try std.testing.expect(pin_mod.forSpawn(codexBase(), obj(a, "{\"agent\":\"typo\"}")).provider == null);
+ try std.testing.expect(pin_mod.forSpawn(codexBase(), obj(a, "{\"agent\":\"plain\"}")).provider == null);
+}
+
+test "spawn override resolution: exact name, alias, ladder rung, and no-op" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const base = codexBase();
+
+ // Exact catalog name.
+ const exact = pin_mod.forSpawn(base, obj(a, "{\"model\":\"gpt-5.6-luna\"}"));
+ try std.testing.expectEqual(pin_mod.Outcome.pinned, exact.outcome);
+ try std.testing.expectEqualStrings("gpt-5.6-luna", exact.provider.?.model);
+ try std.testing.expectEqualStrings("codex", exact.provider.?.id); // provider-local, always
+ try std.testing.expectEqualStrings("k", exact.provider.?.api_key); // same credential
+ // The context window is re-derived for the new model, not inherited.
+ try std.testing.expect(exact.provider.?.context != 0);
+
+ // Abbreviation: the same resolver --subagent-model uses (unique substring).
+ const alias = pin_mod.forSpawn(base, obj(a, "{\"model\":\" 5.6-terra \"}")); // whitespace trimmed
+ try std.testing.expectEqualStrings("gpt-5.6-terra", alias.provider.?.model);
+
+ // Ladder rung instead of a name.
+ const rung = pin_mod.forSpawn(base, obj(a, "{\"tier\":\"small\"}"));
+ try std.testing.expectEqual(pin_mod.Outcome.pinned, rung.outcome);
+ try std.testing.expectEqualStrings("gpt-5.6-luna", rung.provider.?.model);
+ try std.testing.expectEqualStrings("gpt-5.6-terra", pin_mod.forSpawn(base, obj(a, "{\"tier\":\"mid\"}")).provider.?.model);
+
+ // A pin naming the model the child already has changes nothing, and says so.
+ const same = pin_mod.forSpawn(base, obj(a, "{\"tier\":\"frontier\"}"));
+ try std.testing.expectEqual(pin_mod.Outcome.same, same.outcome);
+ try std.testing.expect(same.provider == null);
+
+ // No pin at all: untouched, and cheap — nothing is resolved.
+ const none = pin_mod.forSpawn(base, obj(a, "{\"description\":\"x\",\"prompt\":\"y\"}"));
+ try std.testing.expectEqual(pin_mod.Outcome.none, none.outcome);
+ try std.testing.expect(none.provider == null);
+}
+
+test "precedence: spawn param > persona pin > session default" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ const saved = fleet.g_agent_types;
+ defer fleet.g_agent_types = saved;
+ fleet.g_agent_types = &.{
+ .{ .name = "pinned-frontier", .desc = "", .prompt = "x", .model = "gpt-5.6-sol" },
+ .{ .name = "pinned-mid", .desc = "", .prompt = "x", .tier = .mid },
+ .{ .name = "both", .desc = "", .prompt = "x", .model = "gpt-5.6-terra", .tier = .small },
+ };
+ // The session default is whatever the caller already resolved — here the
+ // #291 ladder's answer for a sol root, i.e. terra.
+ const session_default: Provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "k", .model = "gpt-5.6-terra", .context = 272_000 };
+
+ // 1. An explicit spawn param beats the persona, in BOTH directions —
+ // including lowering a persona that pinned itself to the flagship,
+ // which is the case a merge-instead-of-replace rule would break.
+ try std.testing.expectEqualStrings(
+ "gpt-5.6-luna",
+ pin_mod.forSpawn(session_default, obj(a, "{\"agent\":\"pinned-frontier\",\"tier\":\"small\"}")).provider.?.model,
+ );
+ try std.testing.expectEqualStrings(
+ "gpt-5.6-sol",
+ pin_mod.forSpawn(session_default, obj(a, "{\"agent\":\"pinned-mid\",\"model\":\"gpt-5.6-sol\"}")).provider.?.model,
+ );
+ // 2. No spawn param → the persona's pin applies over the session default.
+ try std.testing.expectEqualStrings(
+ "gpt-5.6-sol",
+ pin_mod.forSpawn(session_default, obj(a, "{\"agent\":\"pinned-frontier\"}")).provider.?.model,
+ );
+ // 3. Neither → the session default is kept untouched.
+ try std.testing.expect(pin_mod.forSpawn(session_default, obj(a, "{\"prompt\":\"y\"}")).provider == null);
+ // Within one level, an exact model beats a tier (both on the call…
+ try std.testing.expectEqualStrings(
+ "gpt-5.6-sol",
+ pin_mod.forSpawn(session_default, obj(a, "{\"model\":\"gpt-5.6-sol\",\"tier\":\"small\"}")).provider.?.model,
+ );
+ // …and both on the persona).
+ try std.testing.expectEqual(pin_mod.Outcome.same, pin_mod.forSpawn(session_default, obj(a, "{\"agent\":\"both\"}")).outcome);
+}
+
+test "graceful fallback: every unhonorable pin keeps the session default, never fails" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const base = codexBase();
+
+ const Case = struct { args: []const u8, want: pin_mod.Outcome };
+ for ([_]Case{
+ // A name no catalog knows.
+ .{ .args = "{\"model\":\"not-a-real-model\"}", .want = .unknown_model },
+ // A real model this provider does not serve (anthropic's, on codex).
+ .{ .args = "{\"model\":\"claude-opus-4-8\"}", .want = .unknown_model },
+ // An abbreviation matching more than one row is ambiguous, not a coin flip.
+ .{ .args = "{\"model\":\"gpt\"}", .want = .unknown_model },
+ // An off-vocabulary tier is reported, and does NOT silently fall
+ // through to the persona the caller was trying to override.
+ .{ .args = "{\"tier\":\"cheap\"}", .want = .unknown_tier },
+ .{ .args = "{\"tier\":\"Mid\"}", .want = .unknown_tier },
+ // Non-string values are simply not a pin.
+ .{ .args = "{\"model\":42}", .want = .none },
+ .{ .args = "{\"model\":\" \"}", .want = .none },
+ }) |case| {
+ const got = pin_mod.forSpawn(base, obj(a, case.args));
+ try std.testing.expectEqual(case.want, got.outcome);
+ try std.testing.expect(got.provider == null); // the spawn still runs
+ // Every non-honored outcome carries a reason for the trace.
+ if (case.want != .none) try std.testing.expect(got.outcome.describe().len > 0);
+ }
+
+ // A provider with no ladder at all: a tier pin is a no-op, not a crash.
+ const xai: Provider = .{ .id = "xai", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "grok-4.3", .context = 256_000 };
+ try std.testing.expectEqual(pin_mod.Outcome.no_ladder, pin_mod.forSpawn(xai, obj(a, "{\"tier\":\"small\"}")).outcome);
+ // A ladder without that rung (deepseek has no `small`) — never rounds to
+ // the nearest rung.
+ const deepseek: Provider = .{ .id = "deepseek", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "deepseek-v4-pro", .context = 128_000 };
+ try std.testing.expectEqual(pin_mod.Outcome.no_rung, pin_mod.forSpawn(deepseek, obj(a, "{\"tier\":\"small\"}")).outcome);
+ try std.testing.expectEqualStrings("deepseek-v4-flash", pin_mod.forSpawn(deepseek, obj(a, "{\"tier\":\"mid\"}")).provider.?.model);
+}
+
+test "a pin never crosses a provider boundary" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ // Whatever the base provider is, the answer is that same provider — the
+ // cross-provider decision stays with --subagent-provider and its consent
+ // flag, which resolved `base` before a pin was ever consulted.
+ const bases = [_]Provider{
+ codexBase(),
+ .{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "k", .model = "claude-opus-4-8", .context = 200_000 },
+ .{ .id = "deepseek", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "deepseek-v4-pro", .context = 128_000 },
+ };
+ for (bases) |base| {
+ for ([_][]const u8{ "{\"tier\":\"mid\"}", "{\"tier\":\"small\"}", "{\"model\":\"gpt-5.6-luna\"}", "{\"model\":\"claude-haiku-4-5\"}" }) |args| {
+ const got = pin_mod.forSpawn(base, obj(a, args));
+ const p = got.provider orelse continue;
+ try std.testing.expectEqualStrings(base.id, p.id);
+ try std.testing.expectEqualStrings(base.api_key, p.api_key);
+ }
+ }
+}
+
+test "promotion carries a persona's model/tier policy, and it round-trips" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ const saved = fleet.g_agent_types;
+ defer fleet.g_agent_types = saved;
+ fleet.g_agent_types = &.{
+ .{ .name = "worker", .desc = "", .prompt = "old genome", .isolation = .worktree, .tier = .mid },
+ .{ .name = "exact", .desc = "", .prompt = "old genome", .model = "gpt-5.6-luna" },
+ .{ .name = "bare", .desc = "", .prompt = "old genome" },
+ };
+
+ // A persona with no policy contributes no lines at all (the frontmatter
+ // promoteAgents wrote before #292 is byte-identical for these).
+ try std.testing.expectEqualStrings("", pin_mod.personaPolicyFrontmatter(a, "bare"));
+ try std.testing.expectEqualStrings("", pin_mod.personaPolicyFrontmatter(a, "not-a-persona"));
+
+ const policy = pin_mod.personaPolicyFrontmatter(a, "worker");
+ try std.testing.expectEqualStrings("isolation: worktree\ntier: mid\n", policy);
+ try std.testing.expectEqualStrings("model: gpt-5.6-luna\n", pin_mod.personaPolicyFrontmatter(a, "exact"));
+
+ // The emitted lines are exactly what the loader parses back — spliced
+ // into a promoted file, `tier: mid` must survive as Tier.mid, so a
+ // promote does not silently un-pin the niche it just rewrote.
+ const promoted = try std.fmt.allocPrint(a, "---\nname: worker\nscore: 0.9\n{s}---\nnew genome\n", .{policy});
+ var round_tripped: ?Tier = null;
+ var round_iso: ?fleet.Isolation = null;
+ var lines = std.mem.tokenizeScalar(u8, promoted, '\n');
+ while (lines.next()) |ln| {
+ const sep = std.mem.indexOfScalar(u8, ln, ':') orelse continue;
+ const key = std.mem.trim(u8, ln[0..sep], " \t");
+ const val = std.mem.trim(u8, ln[sep + 1 ..], " \t\"");
+ if (std.mem.eql(u8, key, "tier")) round_tripped = Tier.parse(val);
+ if (std.mem.eql(u8, key, "isolation")) round_iso = fleet.Isolation.parse(val);
+ }
+ try std.testing.expectEqual(Tier.mid, round_tripped.?);
+ try std.testing.expectEqual(fleet.Isolation.worktree, round_iso.?);
+}
+
+test "withModel: rebuilds the model-derived fields, keeps the credential (#292)" {
+ const base = codexBase();
+ const luna = base.withModel("gpt-5.6-luna");
+ try std.testing.expectEqualStrings("gpt-5.6-luna", luna.model);
+ try std.testing.expectEqualStrings("codex", luna.id);
+ try std.testing.expectEqualStrings("k", luna.api_key);
+ try std.testing.expectEqual(base.kind, luna.kind);
+
+ // kimi routes anthropic-protocol models to a different wire format and
+ // endpoint; withModel must re-derive those, not inherit the old ones.
+ const kimi_native: Provider = .{ .id = "kimi", .kind = .openai, .auth = .bearer, .url = provider_mod.kimi_native_url, .api_key = "k", .model = "k3", .context = 256_000 };
+ const kimi_anth = kimi_native.withModel("kimi-k3-thinking-turbo");
+ if (kimi_anth.kind == .anthropic) {
+ try std.testing.expectEqualStrings(provider_mod.kimi_anthropic_url, kimi_anth.url);
+ try std.testing.expectEqual(Provider.Auth.x_api_key, kimi_anth.auth);
+ }
+
+ // An unknown provider id still yields a usable Provider (no crash), just
+ // without a spec to re-derive from.
+ const alien: Provider = .{ .id = "not-a-provider", .kind = .openai, .auth = .bearer, .url = "u", .api_key = "k", .model = "m", .context = 1234 };
+ try std.testing.expectEqualStrings("m2", alien.withModel("m2").model);
+ try std.testing.expectEqualStrings("u", alien.withModel("m2").url);
+}
diff --git a/src/subagent_run.zig b/src/subagent_run.zig
index d61bb99f..e7de5d1b 100644
--- a/src/subagent_run.zig
+++ b/src/subagent_run.zig
@@ -132,21 +132,27 @@ 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.
///
-/// Today every child in a phase resolves through the same session-level
-/// subagent provider, so this returns the same value for every `i`. It is
-/// written per-variant regardless, because this is exactly the seam that
-/// per-persona / per-spawn model pins (#292) extend: with the class hoisted to
-/// a phase-level constant, the first heterogeneous fan-out would keep reporting
-/// the ROOT's class for every variant and quietly file model effects under the
-/// prompt genome. Keeping the lookup per-variant means #292 changes this one
-/// function instead of having to notice a stale constant.
+/// 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.
+///
+/// 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.
///
/// 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; // per-variant model pins land in #292
+ _ = i; // #292 pins reach `subagent`, not phase tasks — see above
return scoring.providerClass(childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider).model);
}
@@ -180,7 +186,13 @@ fn agentUsageEvent(sub_id: []const u8, ok: bool, usage: AgentUsage) AgentUsageEv
pub const SubRun = struct { output: ToolOutput, usage: AgentUsage };
-pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8, isolation: Isolation, isolation_fallback: bool) !SubRun {
+/// `pin` (#292) is an already-resolved, provider-local per-spawn model
+/// override — subagent_pin.forSpawn's answer for this one call. It replaces
+/// the session-level worker choice for this child only; null keeps it. It is
+/// deliberately a resolved Provider rather than a name: resolution (catalog
+/// lookup, graceful fallback, provider locality) happens once at the call
+/// site, so nothing here can fail a spawn on an unavailable pin.
+pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8, isolation: Isolation, isolation_fallback: bool, pin: ?Provider) !SubRun {
const gpa = ctx.gpa;
if (ctx.run_budget) |budget| if (ctx.depth >= budget.max_depth) return .{
.output = .{
@@ -192,7 +204,11 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
var arena_state = std.heap.ArenaAllocator.init(gpa);
defer arena_state.deinit();
const arena = arena_state.allocator();
- const child_provider = childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider);
+ // #292: a resolved per-spawn/per-persona pin replaces the session-level
+ // worker choice for this child. Already provider-local (see
+ // subagent_pin), so the cross-provider consent check childProvider
+ // enforces has nothing left to decide.
+ const child_provider = pin orelse childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider);
var agent: Agent = .{
.gpa = gpa,
diff --git a/src/subagent_selection.zig b/src/subagent_selection.zig
index ea7fa82a..32d8602e 100644
--- a/src/subagent_selection.zig
+++ b/src/subagent_selection.zig
@@ -30,7 +30,12 @@ fn knownProvider(id: []const u8) bool {
return provider_mod.specFor(id) != null;
}
-fn modelForProvider(provider_id: []const u8, query: []const u8) ?[]const u8 {
+/// Resolve `query` to a catalogued model name served by `provider_id`: exact
+/// match, then alias-equality, then a UNIQUE substring match (ambiguous →
+/// null). Provider-local by construction — this is the one resolver both the
+/// startup pins (--subagent-model, the #291 ladder) and the #292 per-persona /
+/// per-spawn pins go through, so all three agree on what a model name means.
+pub fn modelForProvider(provider_id: []const u8, query: []const u8) ?[]const u8 {
for (pricing.models()) |model| {
if (std.mem.eql(u8, model.provider, provider_id) and
std.mem.eql(u8, model.name, query)) return model.name;
diff --git a/src/subagent_tests.zig b/src/subagent_tests.zig
new file mode 100644
index 00000000..9913b0be
--- /dev/null
+++ b/src/subagent_tests.zig
@@ -0,0 +1,57 @@
+//! Tests split out of subagent.zig, which sits at the 600-line cap (the
+//! `<mod>_tests.zig` pattern, wired into the test root by test_hooks.zig).
+
+const std = @import("std");
+
+const util = @import("util.zig");
+const repl_glue = @import("repl_glue.zig");
+const subagent = @import("subagent.zig");
+const subagent_run = @import("subagent_run.zig");
+
+const FailKind = subagent_run.FailKind;
+const classifyFailure = subagent_run.classifyFailure;
+
+test "variantJudgePrompt: bounded, names the phase, keeps the score contract" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+
+ const big_task = util.repeatBytes("T", 4000);
+ const big_out = util.repeatBytes("O", 5000);
+ const p = try subagent.variantJudgePrompt(a, "code-review", &big_task, &big_out);
+
+ // Names the shared phase so the judge has the tournament context.
+ try std.testing.expect(std.mem.indexOf(u8, p, "\"code-review\" phase") != null);
+ // Task is prefix-capped and output tail-capped — neither lands verbatim.
+ try std.testing.expect(std.mem.indexOf(u8, p, &big_task) == null);
+ try std.testing.expect(std.mem.indexOf(u8, p, &big_out) == null);
+ // The `score:` contract parseEvalScore depends on is spelled out…
+ try std.testing.expect(std.mem.indexOf(u8, p, "score: <N>") != null);
+ // …and it round-trips: a judge tail like this parses back to the score.
+ try std.testing.expectEqual(@as(?f64, 87), repl_glue.parseEvalScore("ok\nscore: 87"));
+}
+
+test "classifyFailure: maps the child's api-error detail to a category + retry-safety" {
+ // A stream stall/drop names itself via the error kind — its stale envelope
+ // (if any) must not override the transport verdict.
+ try std.testing.expectEqual(FailKind.transport, classifyFailure(error.StreamStalled, null));
+ try std.testing.expectEqual(FailKind.transport, classifyFailure(error.StreamDropped, "api error (some_error): stale"));
+ // No detail to go on → unknown (and a retry is still allowed to be tried).
+ try std.testing.expectEqual(FailKind.unknown, classifyFailure(error.ApiError, null));
+ // Real provider envelopes (the shapes sayApiError formats into last_api_error).
+ try std.testing.expectEqual(FailKind.quota, classifyFailure(error.ApiError, "api error (rate_limit_error): Number of requests exceeded"));
+ try std.testing.expectEqual(FailKind.quota, classifyFailure(error.ApiError, "api error: You have run out of credits or need a Grok subscription."));
+ try std.testing.expectEqual(FailKind.auth, classifyFailure(error.ApiError, "api error: The API Key appears to be invalid or may have expired."));
+ // invalid_request_error carries "invalid", but a missing-model message is
+ // classified as model-availability because that phrase is checked first.
+ try std.testing.expectEqual(FailKind.model, classifyFailure(error.ApiError, "api error (invalid_request_error): The model `gpt-foo` does not exist or you do not have access to it."));
+ try std.testing.expectEqual(FailKind.invalid, classifyFailure(error.ApiError, "api error (invalid_request_error): This model's maximum context length is 8192 tokens."));
+ try std.testing.expectEqual(FailKind.transport, classifyFailure(error.ApiError, "network error: HttpConnectionClosing (gave up after 6 attempts)"));
+
+ // Retry-safety contract: transient failures may retry, structural ones must not.
+ try std.testing.expect(FailKind.quota.retrySafe());
+ try std.testing.expect(FailKind.transport.retrySafe());
+ try std.testing.expect(!FailKind.model.retrySafe());
+ try std.testing.expect(!FailKind.invalid.retrySafe());
+ try std.testing.expect(!FailKind.auth.retrySafe());
+}
diff --git a/src/subagent_tier_ladder.zig b/src/subagent_tier_ladder.zig
index a914c68f..c9d2d170 100644
--- a/src/subagent_tier_ladder.zig
+++ b/src/subagent_tier_ladder.zig
@@ -18,11 +18,47 @@ const std = @import("std");
const pricing = @import("pricing.zig");
+/// The ladder's rung vocabulary, shared by #292's persona frontmatter
+/// (`tier: mid`) and the `subagent` tool's `tier` parameter. Spelled the same
+/// way in both places on purpose: a tier survives a root-model change, an
+/// exact `model:` pin does not.
+pub const Tier = enum {
+ frontier,
+ mid,
+ small,
+
+ /// Exact, case-sensitive, closed vocabulary — mirroring
+ /// fleet.Isolation.parse. Anything else is "no opinion" (null), never a
+ /// nearest-rung guess.
+ pub fn parse(s: []const u8) ?Tier {
+ if (std.mem.eql(u8, s, "frontier")) return .frontier;
+ if (std.mem.eql(u8, s, "mid")) return .mid;
+ if (std.mem.eql(u8, s, "small")) return .small;
+ return null;
+ }
+
+ pub fn label(self: Tier) []const u8 {
+ return @tagName(self);
+ }
+};
+
pub const TierLadder = struct {
provider: []const u8,
frontier: []const u8,
mid: ?[]const u8 = null,
small: ?[]const u8 = null,
+
+ /// The model this provider serves at `tier`, or null when the family has
+ /// no such rung (deepseek has no `small`). Never falls through to a
+ /// neighbouring rung — an absent rung means "no opinion", which the
+ /// caller turns into the session default rather than a guess.
+ pub fn modelFor(self: TierLadder, tier: Tier) ?[]const u8 {
+ return switch (tier) {
+ .frontier => self.frontier,
+ .mid => self.mid,
+ .small => self.small,
+ };
+ }
};
pub const ladders = [_]TierLadder{
@@ -65,3 +101,22 @@ test "forProvider: known providers found, others null" {
try std.testing.expect(forProvider("deepseek").?.small == null);
try std.testing.expect(forProvider("xai") == null);
}
+
+test "Tier.parse/modelFor: the rung vocabulary #292 pins against (#291 names)" {
+ try std.testing.expectEqual(Tier.frontier, Tier.parse("frontier").?);
+ try std.testing.expectEqual(Tier.mid, Tier.parse("mid").?);
+ try std.testing.expectEqual(Tier.small, Tier.parse("small").?);
+ // Case-sensitive and closed: anything off-vocabulary is "no opinion", not
+ // a guess — a persona typo must fall through to the session default.
+ try std.testing.expect(Tier.parse("Mid") == null);
+ try std.testing.expect(Tier.parse("cheap") == null);
+ try std.testing.expect(Tier.parse("") == null);
+ try std.testing.expectEqualStrings("small", Tier.small.label());
+
+ const codex = forProvider("codex").?;
+ try std.testing.expectEqualStrings("gpt-5.6-sol", codex.modelFor(.frontier).?);
+ try std.testing.expectEqualStrings("gpt-5.6-terra", codex.modelFor(.mid).?);
+ try std.testing.expectEqualStrings("gpt-5.6-luna", codex.modelFor(.small).?);
+ // A family with no such rung answers null rather than the nearest rung.
+ try std.testing.expect(forProvider("deepseek").?.modelFor(.small) == null);
+}
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 43953f0d..5ba4eb11 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -38,6 +38,11 @@ const repl_parser = @import("repl_parser.zig");
// Routing + worker selection.
const router_config = @import("router_config.zig");
const subagent_selection = @import("subagent_selection.zig");
+// #292 per-persona / per-spawn model pins: the module is reached in
+// production (subagent.zig), but its split-out test files are not.
+const subagent_pin_tests = @import("subagent_pin_tests.zig");
+// Moved off subagent.zig, which is at the 600-line cap.
+const subagent_tests = @import("subagent_tests.zig");
// `graff serve` resumability (#330): serve.zig imports these, but nothing in
// the production graph references their decls, so Zig never analyses them.
@@ -65,6 +70,8 @@ test {
_ = repl_parser;
_ = router_config;
_ = subagent_selection;
+ _ = subagent_pin_tests;
+ _ = subagent_tests;
_ = serve_events;
_ = serve_create;
_ = scoring_slot_test;
diff --git a/src/workflow.zig b/src/workflow.zig
index eca7a616..00b1a2ad 100644
--- a/src/workflow.zig
+++ b/src/workflow.zig
@@ -195,7 +195,8 @@ fn pipelineChain(ctx: ToolCtx, item: []const u8, stages: []const StageSpec) Tool
var prev: []const u8 = "";
for (stages, 1..) |st, stage_no| {
const prompt = pipelinePrompt(arena, st.prompt, item, prev, stage_no) catch |e| return failure(gpa, e);
- var out = if (runSub(ctx, "workflow_task", st.label, prompt, st.override, st.niche, st.isolation, st.isolation_fallback)) |r| r.output else |e| failure(gpa, e);
+ // 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)) |r| r.output else |e| failure(gpa, e);
if (out.is_error) {
// Only spend the one retry (#2) when the harness's own
// classification hasn't already ruled it out (auth, invalid
@@ -203,7 +204,7 @@ fn pipelineChain(ctx: ToolCtx, item: []const u8, stages: []const StageSpec) Tool
// wasting a second attempt.
if (failureAllowsRetry(out.text)) {
gpa.free(out.text);
- out = if (runSub(ctx, "workflow_retry", st.label, prompt, st.override, st.niche, st.isolation, st.isolation_fallback)) |r| r.output else |e| failure(gpa, e);
+ out = if (runSub(ctx, "workflow_retry", st.label, prompt, st.override, st.niche, st.isolation, st.isolation_fallback, null)) |r| r.output else |e| failure(gpa, e);
}
if (out.is_error) {
// #248 — excerpt the stage's own error BEFORE freeing it, so