graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(#380): vision-aware subagent routing + a report-time capability-honesty flag
justrach62d5a9d55503
diff --git a/src/route_phase.zig b/src/route_phase.zigindex 21d24ab9..c963f2b2 100644--- a/src/route_phase.zig+++ b/src/route_phase.zig@@ -71,6 +71,10 @@ pub const Seat = struct {/// the #291 descent, `session-default` for an explicit pin or a plain/// inherit. Exactly what #372 reported for these workers.base_source: Source = .session_default,+ /// #380: `pin` was set because a task in this phase names an image and+ /// the seat could not see one — a capability requirement, not a measured+ /// preference, so it must not be reported as `learned-policy`.+ vision: bool = false,/// The (shape, role) cell one worker files its score under. Identical for/// every worker of a routed phase by construction: `uniformRole` only@@ -84,6 +88,7 @@ pub const Seat = struct {/// decision that actually chose their model, and reporting it per worker/// is what keeps the trace honest about a phase-level choice.pub fn sourceFor(self: Seat, has_override: bool) Source {+ if (self.vision) return .vision_ask; // #380 — a capability, not a preferenceif (self.pin != null) return .learned_policy;return if (has_override) .workflow_override else self.base_source;}diff --git a/src/route_phase_tests.zig b/src/route_phase_tests.zigindex 759bd25e..c624042a 100644--- a/src/route_phase_tests.zig+++ b/src/route_phase_tests.zig@@ -256,7 +256,10 @@ test "#376 firewall: the seat is resolved ONCE per phase, outside the task loop"// model — so it is pinned as source text, the same way #372 pinned the// no-per-task-pin invariant it replaces.const src = @embedFile("workflow.zig");- const seat_at = std.mem.indexOf(u8, src, "const seat = route_phase.forPhase(").?;+ // #380 wraps the same one-shot resolution in vision_ask.phaseSeat, which+ // may swap the phase's model but still yields ONE seat for the whole+ // phase — the property this test exists to protect.+ const seat_at = std.mem.indexOf(u8, src, "const seat = vision_ask.phaseSeat(route_phase.forPhase(").?;const loop_at = std.mem.indexOf(u8, src, "for (labels, prompts, overrides, niches, isolations, isolation_fallbacks, futures, 1..)").?;try std.testing.expect(seat_at < loop_at); // resolved before the fan-out// Every spawn in the phase — first attempt and retry alike — receives thatdiff --git a/src/route_policy.zig b/src/route_policy.zigindex a23c05a2..542c5103 100644--- a/src/route_policy.zig+++ b/src/route_policy.zig@@ -103,6 +103,7 @@ pub const Shape = enum {pub const Source = enum {explicit_pin, // `model`/`tier` on the spawn call itselfpersona, // `.harness/agents/<name>.md` frontmatter pin+ vision_ask, // #380: the task names an image and the automatic seat was blindlearned_policy, // a (shape, role) cell re-seated the tier's rungworkflow_override, // the root model authored this worker's genomesession_default, // --subagent-model, or the root the child inherits@@ -113,6 +114,7 @@ pub const Source = enum {return switch (self) {.explicit_pin => "explicit-pin",.persona => "persona",+ .vision_ask => "vision-ask",.learned_policy => "learned-policy",.workflow_override => "workflow-override",.session_default => "session-default",diff --git a/src/subagent.zig b/src/subagent.zigindex ee024777..dcce1145 100644--- a/src/subagent.zig+++ b/src/subagent.zig@@ -59,29 +59,27 @@ pub fn execSubagent(ctx: ToolCtx, input: Value) !ToolOutput {const niche = fleet.resolveNiche(obj);const isolation = fleet.resolveIsolation(obj);const isolation_fallback = fleet.resolveIsolationFallback(obj);- // #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.+ // #292: explicit spawn `model`/`tier` > persona frontmatter > the session+ // default (--subagent-model / the #291 ladder), resolved provider-locally.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;+ // #380: that chain, its notes and its #372 route line in one call (this+ // file is at the cap). A task naming an image is a VISION ASK: a blind+ // AUTOMATIC seat is re-routed to one that sees, a human's pin is kept but+ // flagged, and no vision model anywhere refuses the spawn outright.+ const ask = vision_ask.seat(ctx, base, obj, cell, label, prompt, sys_override, niche);+ if (ask.blocked) return .{ .text = try vision_ask.blockMessage(ctx.gpa, ask), .is_error = true };+ if (tools.json_args.flag(input, "run_in_background")) return spawnSubBackground(ctx, label, prompt, sys_override, niche, isolation, isolation_fallback, ask.pin.provider, ask.pin.effort, ask);+ const run = try runSub(ctx, "subagent", label, prompt, sys_override, niche, isolation, isolation_fallback, ask.pin.provider, ask.pin.effort);+ return vision_ask.flagReport(ctx.gpa, run.output, ask);}const subagent_run = @import("subagent_run.zig");-const subagent_pin = @import("subagent_pin.zig"); // #292 per-persona / per-spawn model pins+const vision_ask = @import("vision_ask.zig"); // #380 vision-aware seat (wraps #292's subagent_pin) + the report honesty flagpub const AgentUsage = subagent_run.AgentUsage;pub const SubRun = subagent_run.SubRun;pub const runSub = subagent_run.runSub;@@ -130,15 +128,16 @@ 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.+ /// #292: resolved per-spawn model pin. Needs no gpa copy, unlike+ /// label/prompt: a Provider's strings come from the spec table, the model+ /// catalog and the credential store, never from this tool call's arena.pin: ?Provider = null,/// #292 follow-up: resolved per-spawn/per-persona effort pin — an enum by/// value, no lifetime to manage.effort: ?main_mod.ReasoningEffort = null,+ /// #380: the vision decision, rebased onto the gpa-owned prompt, so a+ /// backgrounded report earns the same honesty flag a foreground one does.+ ask: vision_ask.Ask = .{},ctx: ToolCtx,admitted: bool = false,done: bool = false,@@ -214,7 +213,7 @@ fn agentJobPump(job: *AgentJob, gpa: Allocator, io: Io) void {.usage = .{ .duration_ms = @intCast(@max(0, t0.untilNow(io, .awake).toMilliseconds())) },};g_agent_jobs.mutex.lockUncancelable(io);- job.result = run.output.text;+ job.result = vision_ask.flagText(gpa, run.output.text, job.ask); // #380 honesty flagjob.is_error = run.output.is_error;job.usage = run.usage;job.done = true;@@ -227,7 +226,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, pin: ?Provider, effort: ?main_mod.ReasoningEffort) !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, effort: ?main_mod.ReasoningEffort, ask: vision_ask.Ask) !ToolOutput {const gpa = ctx.gpa;const label_c = try gpa.dupe(u8, label);errdefer gpa.free(label_c);@@ -249,6 +248,7 @@ fn spawnSubBackground(ctx: ToolCtx, label: []const u8, prompt: []const u8, sys_o.isolation_fallback = isolation_fallback,.pin = pin,.effort = effort,+ .ask = ask.rebased(prompt_c), // the caller's arena dies with this call.ctx = ctx,};diff --git a/src/subagent_pin.zig b/src/subagent_pin.zigindex 3b4f12d6..04110e9f 100644--- a/src/subagent_pin.zig+++ b/src/subagent_pin.zig@@ -261,8 +261,9 @@ pub fn resolveIn(base: Provider, pin: Pin, cell: Cell) Resolved {/// Flat-rate, device-login subscription providers, in fallback preference/// order (bench scores rank them when several are logged in). codegraff's/// license is deliberately absent: it fronts the metered multi-vendor-/// gateway this policy protects the user's wallet FROM.-const subscription_providers = [_][]const u8{ "codex", "kimi" };+/// gateway this policy protects the user's wallet FROM. `pub` since #380:+/// vision_ask.visionSeat searches the same candidates under the same rule.+pub const subscription_providers = [_][]const u8{ "codex", "kimi" };/// SUB-FIRST TIER ROUTING (explicit `tier` asks only — the silent no-tier/// default still inherits the user's chosen family): a logged-in flat-ratediff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 648a69e2..0eaacd19 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -53,6 +53,9 @@ const route_trace = @import("route_trace.zig");// #376 phase-uniform learned routing + the rung-stratified fitness fold.const route_phase = @import("route_phase.zig");const route_check = @import("route_check.zig");+// #380 vision-aware spawn routing + the report-time capability-honesty flag.+const vision_ask = @import("vision_ask.zig");+const vision_ask_tests = @import("vision_ask_tests.zig");const pricing_tests = @import("pricing_tests.zig");const fitness_strata = @import("fitness_strata.zig");@@ -98,6 +101,8 @@ test {_ = route_trace;_ = route_phase;_ = route_check;+ _ = vision_ask;+ _ = vision_ask_tests;_ = pricing_tests;_ = fitness_strata;_ = serve_events;diff --git a/src/vision_ask.zig b/src/vision_ask.zignew file mode 100644index 00000000..2a16ca39--- /dev/null+++ b/src/vision_ask.zig@@ -0,0 +1,400 @@+//! #380 — vision-aware subagent routing, and the report-time capability-+//! honesty flag.+//!+//! THE FAILURE THIS CLOSES. A root spawned "Analyze color palette screenshot"+//! naming a `.png` path. The worker's resolved model could not accept vision+//! input; it said so in its own report ("I couldn't open the image as a+//! vision input"), then improvised eight minutes of pixel quantization,+//! reached a WRONG palette, and returned status ok. The root accepted it and+//! briefed further work on the fabricated colors. One missing capability+//! check cascaded into a confidently wrong run.+//!+//! Two halves, deliberately independent — either alone leaves a hole:+//!+//! 1. SPAWN TIME (`seat`/`forSpawn`). A task whose text names a concrete+//! image path is a VISION ASK. If the seat the routing chain produced+//! cannot see images, an AUTOMATIC seat is re-routed to one that can, a+//! HUMAN's pin is kept but flagged, and a session where no vision-capable+//! model is reachable at all refuses the spawn (`blocked`) rather than+//! handing the work to a model that will have to imagine the pixels.+//!+//! 2. REPORT TIME (`flagReport`). Capability disclaimers happen anyway — a+//! vision model can still be handed a path it cannot read, and a pinned+//! blind model runs by design. When the task was a vision ask AND the+//! report carries one of a tight set of disclaimer markers, the tool+//! result the ROOT sees gains a leading `[vision warning]` line. It is+//! NOT marked is_error: the work may still have value; the point is only+//! that the root can no longer mistake inference for observation.+//!+//! WHERE THE RE-ROUTE SITS IN THE PIN CHAIN. Below every human statement:+//!+//! explicit spawn pin > persona frontmatter > explicit --subagent-model+//! > [vision ask] > learned policy (#372) > ladder (#291/#373)+//! > plain inherit-the-root+//!+//! `subagent_pin.forSpawnIn` runs FIRST and untouched — the #292 precedence,+//! the #372 learned rung and the sub-first flat-rate routing all resolve+//! exactly as they did. Only then, and only when the answer is blind to+//! images, does this module get to move an automatic seat. That is the same+//! discipline #372/#376 apply: evidence may improve a route the harness chose+//! for itself, never one a person chose.+//!+//! CANDIDATE ORDER mirrors subagent_pin's own: a logged-in flat-rate+//! subscription first (marginal cost zero outranks metered spend, and the+//! login is the user's standing consent for that vendor), then the base+//! provider's own catalog under the same `rungAffordable` ceiling every+//! automatic rung clears. Metered cross-provider routing is never done here —+//! that decision stays with --subagent-provider and its consent flag.++const std = @import("std");+const Allocator = std.mem.Allocator;++const Provider = @import("provider.zig").Provider;+const vision = @import("vision.zig");+const pricing = @import("pricing.zig");+const bench_priors = @import("bench_priors.zig");+const selection = @import("subagent_selection.zig");+const tier_ladder = @import("subagent_tier_ladder.zig");+const subagent_pin = @import("subagent_pin.zig");+const route_policy = @import("route_policy.zig");+const route_phase = @import("route_phase.zig");+const route_trace = @import("route_trace.zig");+const util = @import("util.zig");+const tools = @import("tools.zig");++pub const Source = route_policy.Source;++// ── Detection ──────────────────────────────────────────────────────────────+// The contract, stated once: a vision ask is a PLAUSIBLE PATH TOKEN whose+// final extension is one of png/jpg/jpeg/gif/webp, case-insensitive. Not "any+// mention of png" — `png compression`, `.pngx`, a bare `.png` and the glob+// `*.png` are all negatives, because none of them is a file a worker could be+// asked to look at. `http(s)://…/x.png` is a negative too, and that one is a+// judgement call worth spelling out: a remote URL is not a path this harness+// can turn into a vision block (vision.stageImagePath reads local files), so+// re-routing for one would spend a better model to fetch nothing.++pub const image_exts = [_][]const u8{ "png", "jpg", "jpeg", "gif", "webp" };++/// Bytes that may follow an extension without ending the token — `.pngx` is+/// an extension of its own, not a png.+fn wordByte(c: u8) bool {+ return std.ascii.isAlphanumeric(c) or c == '_' or c == '-';+}++/// Where an unquoted path token stops when scanned BACKWARD from its final+/// dot. `/`, `.`, `-`, `_`, `~` and `:` are deliberately absent so relative,+/// absolute and dotted paths survive intact; `*`/`?` are present so a glob+/// yields an empty stem and is rejected rather than treated as a file.+fn pathBreak(c: u8) bool {+ return switch (c) {+ ' ', '\t', '\r', '\n', '"', '\'', '`', '(', '[', '{', '<', ')', ']', '}', '>', ',', ';', '=', '|', '*', '?', '!' => true,+ else => false,+ };+}++/// End index of a known image extension starting at `dot`, or null.+fn extEnd(text: []const u8, dot: usize) ?usize {+ const rest = text[dot + 1 ..];+ for (image_exts) |e| {+ if (rest.len < e.len or !std.ascii.eqlIgnoreCase(rest[0..e.len], e)) continue;+ const end = dot + 1 + e.len;+ // A word byte right after means this was never that extension.+ return if (end < text.len and wordByte(text[end])) null else end;+ }+ return null;+}++/// A quoted path may legitimately contain spaces (`"color palette.png"`).+/// Widened only when the SAME quote closes immediately after the extension —+/// otherwise ordinary prose containing a quote earlier in the line would+/// swallow the whole sentence.+fn quotedToken(text: []const u8, dot: usize, ext_end: usize) ?[]const u8 {+ if (ext_end >= text.len) return null;+ const q = text[ext_end];+ if (q != '"' and q != '\'') return null;+ var start = dot;+ while (start > 0 and text[start - 1] != q and text[start - 1] != '\n') start -= 1;+ if (start == 0 or start == dot or text[start - 1] != q) return null;+ return text[start..ext_end];+}++fn bareToken(text: []const u8, dot: usize, ext_end: usize) ?[]const u8 {+ var start = dot;+ while (start > 0 and !pathBreak(text[start - 1])) start -= 1;+ if (start == dot) return null; // no stem: a bare ".png", or a `*.png` glob+ return text[start..ext_end];+}++/// The first concrete image path `text` names, or null. Text-only by design:+/// the file may not exist yet (a worker is often asked to inspect something a+/// prior phase produced), and the spawn decision cannot wait on the disk.+pub fn imagePathIn(text: []const u8) ?[]const u8 {+ var i: usize = 0;+ while (std.mem.indexOfScalarPos(u8, text, i, '.')) |dot| {+ i = dot + 1;+ const ext_end = extEnd(text, dot) orelse continue;+ const token = quotedToken(text, dot, ext_end) orelse bareToken(text, dot, ext_end) orelse continue;+ if (std.mem.indexOf(u8, token, "://") != null) continue; // remote URL, not a local path+ return token;+ }+ return null;+}++// ── The spawn-time decision ────────────────────────────────────────────────++/// One spawn's vision decision, carried from the routing chain to the tool+/// result so both halves of #380 read the same facts.+pub const Ask = struct {+ /// The image path the task named; "" when it named none (not a vision+ /// ask, and every rule below is a no-op).+ path: []const u8 = "",+ /// #292's answer, untouched — this module never edits an outcome, only+ /// (possibly) the provider an AUTOMATIC seat resolved to.+ pin: subagent_pin.Resolved = .{},+ /// What the #372 route line reports as `source`.+ source: Source = .session_default,+ /// A vision-capable model was seated BECAUSE of the image.+ rerouted: bool = false,+ /// The seat is a human's pin and cannot see images: kept (a pin outranks+ /// evidence), but the run is flagged at both ends.+ pinned_blind: bool = false,+ /// No vision-capable model this spawn may take on its own is reachable.+ blocked: bool = false,+ /// A vision model the seat's provider DOES serve, which the automatic cost+ /// ceiling refused — "" when nothing vision-capable exists there at all.+ /// Kept apart so a blocked spawn says which of the two happened instead of+ /// claiming "none exists" when one does and merely costs more.+ pricier: []const u8 = "",++ pub fn isAsk(self: Ask) bool {+ return self.path.len > 0;+ }++ /// The tracer note this decision owes the user, or null when it made no+ /// decision worth recording.+ pub fn note(self: Ask) ?[]const u8 {+ if (self.blocked) return "vision ask refused: no vision-capable model is reachable with the current credentials";+ if (self.pinned_blind) return "vision warning: this task names an image and the pinned model cannot see images — the pin was kept, the report is flagged";+ if (self.rerouted) return "vision ask: re-routed an automatic seat to a vision-capable model";+ return null;+ }++ /// The same decision with `path` re-derived from `text` — a background+ /// spawn copies the prompt onto the heap and the tool call's arena dies+ /// with it, so the original slice would dangle.+ pub fn rebased(self: Ask, text: []const u8) Ask {+ var out = self;+ out.path = imagePathIn(text) orelse "";+ return out;+ }+};++/// The no-opinion Ask for a caller that only needs the report-time half+/// (workflow phase tasks, which take no per-task pins at all).+pub fn forPrompt(prompt: []const u8) Ask {+ return .{ .path = imagePathIn(prompt) orelse "" };+}++/// Did a HUMAN name this model? The only question a re-route asks, reduced+/// from #372's six-layer `Source`. `session_model_pinned` separates the two+/// meanings `session-default` carries: an explicit --subagent-model (human)+/// from a plain inherit-the-root (the harness's own default).+pub fn userChose(source: Source, session_model_pinned: bool) bool {+ return switch (source) {+ .explicit_pin, .persona => true,+ .session_default => session_model_pinned,+ .learned_policy, .ladder, .workflow_override, .vision_ask => false,+ };+}++/// Cheapest vision-capable model `provider_id` serves: its ladder rungs+/// bottom-up first (descend, never escalate — the #292 cost discipline), then+/// the live catalog's cheapest vision row. Unpriced rows sort as free, which+/// is what a flat-rate subscription model actually costs.+pub fn visionModelFor(provider_id: []const u8) ?[]const u8 {+ if (tier_ladder.forProvider(provider_id)) |l| {+ for ([_]?[]const u8{ l.small, l.mid, l.frontier }) |rung| {+ const name = rung orelse continue;+ if (!vision.visionModel(name)) continue;+ if (selection.modelForProvider(provider_id, name)) |m| return m;+ }+ }+ var best: ?[]const u8 = null;+ var best_cost: f64 = std.math.inf(f64);+ for (pricing.models()) |m| {+ if (!std.mem.eql(u8, m.provider, provider_id) or !vision.visionModel(m.name)) continue;+ const cost = if (pricing.priceFor(m.name)) |p| p.in + p.out else 0;+ if (cost < best_cost) {+ best = m.name;+ best_cost = cost;+ }+ }+ return best;+}++/// A vision-capable seat to replace `base` with, or null when none is+/// reachable. Sub-first, then provider-local under the cost ceiling; see the+/// module doc for why that order, and why nothing metered ever crosses a+/// provider boundary here.+pub fn visionSeat(base: Provider) ?Provider {+ if (bench_priors.g_keys) |keys| {+ var best: ?Provider = null;+ var best_score: f64 = -1;+ for (subagent_pin.subscription_providers) |sid| {+ if (std.mem.eql(u8, sid, base.id)) continue; // handled provider-locally below+ const name = visionModelFor(sid) orelse continue;+ const prov = keys.providerById(sid, name) catch continue; // not logged in → not a candidate+ const score = bench_priors.scoreFor(sid, name) orelse 0;+ if (best == null or score > best_score) {+ best = prov;+ best_score = score;+ }+ }+ if (best) |b| return b;+ }+ const local = visionModelFor(base.id) orelse return null;+ if (!subagent_pin.rungAffordable(base.model, local)) return null;+ return base.withModel(local);+}++/// The vision model `base`'s own provider serves that the cost ceiling+/// refused, or "". An automatic seat may never escalate spend (#292's rule,+/// and unpriced rows cannot PROVE they are not an escalation), but the user+/// can authorize it by name — so the refusal has to say which model that is.+pub fn blockedByCost(base: Provider) []const u8 {+ const name = visionModelFor(base.id) orelse return "";+ return if (subagent_pin.rungAffordable(base.model, name)) "" else name;+}++/// The whole spawn-time decision: run the #292/#372 chain unchanged, then ask+/// the vision question of its answer.+pub fn forSpawn(base: Provider, obj: std.json.ObjectMap, session_pinned: bool, cell: route_policy.Cell, prompt: []const u8) Ask {+ var ask: Ask = .{ .pin = subagent_pin.forSpawnIn(base, obj, !session_pinned, cell) };+ ask.source = if (ask.pin.provider != null) ask.pin.source else route_trace.sessionSource(session_pinned);+ ask.path = imagePathIn(prompt) orelse return ask;+ const current = ask.pin.provider orelse base;+ if (vision.visionModel(current.model)) return ask; // the seat already sees images+ if (userChose(ask.source, session_pinned)) {+ ask.pinned_blind = true;+ return ask;+ }+ ask.pin.provider = visionSeat(current) orelse {+ ask.blocked = true;+ ask.pricier = blockedByCost(current);+ return ask;+ };+ ask.source = .vision_ask;+ ask.rerouted = true;+ return ask;+}++/// forSpawn plus every note and trace line the decision owes — one call+/// because subagent.zig sits at the 600-line cap. The #372 route line is+/// emitted here so a vision re-route reports `source=vision-ask` on exactly+/// the same three sinks (tracer, trajectory, --json) as every other seat.+pub fn seat(ctx: tools.ToolCtx, base: Provider, obj: std.json.ObjectMap, cell: route_policy.Cell, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8) Ask {+ const ask = forSpawn(base, obj, ctx.subagent_provider != null, cell, prompt);+ if (ctx.tracer) |tr| {+ if (ask.pin.outcome != .none) tr.note("subagent", ask.pin.outcome.describe());+ if (ask.pin.effort_outcome != .none) tr.note("subagent", ask.pin.effort_outcome.describe());+ if (ask.note()) |n| tr.note("vision", n);+ }+ route_trace.emitSpawnProvider(ctx.io, ctx.tracer, label, ask.pin.provider orelse base, cell, ask.source, sys_override, niche);+ return ask;+}++/// #376's phase seat, asked the same question. A phase is re-seated as a+/// WHOLE (every worker in it keeps the one model #290 requires) when any of+/// its task prompts names an image and the seat the phase would otherwise+/// have taken is blind to images. A phase whose seat a human chose is left+/// alone, and — unlike the `subagent` tool — a phase with no vision model+/// available is NOT refused: it runs and relies on the report-time flag, so+/// one image-shaped task cannot abort a whole workflow.+pub fn phaseSeat(base: route_phase.Seat, prompts: []const []const u8, session_pinned: bool) route_phase.Seat {+ var out = base;+ if (vision.visionModel(out.provider.model)) return out;+ if (userChose(out.sourceFor(false), session_pinned)) return out;+ for (prompts) |p| {+ if (imagePathIn(p) == null) continue;+ const better = visionSeat(out.provider) orelse return out;+ out.pin = better;+ out.provider = better;+ out.vision = true;+ return out;+ }+ return out;+}++// ── The report-time honesty flag ───────────────────────────────────────────++/// Capability disclaimers, kept TIGHT on purpose: every entry names the image+/// explicitly, so ordinary prose about images ("the image shows three greens")+/// cannot trip it. Curly-apostrophe spellings are listed separately rather+/// than normalized — a model emits one or the other and both must match.+pub const disclaimers = [_][]const u8{+ "couldn't open the image",+ "couldn\u{2019}t open the image",+ "could not open the image",+ "can't view the image",+ "can\u{2019}t view the image",+ "cannot view the image",+ "unable to see the image",+ "not able to view the image",+ "as a vision input",+};++pub fn disclaimed(report: []const u8) bool {+ for (disclaimers) |d| if (util.indexOfIgnoreCase(report, d) != null) return true;+ return false;+}++pub const disclaimer_warning = "[vision warning] worker disclaimed image-viewing capability — visual conclusions below are inferred, not seen.";+pub const pinned_warning = "[vision warning] this task names an image and the worker's pinned model cannot accept vision input — visual conclusions below are inferred, not seen.";++/// The warning line this report earns, or null. Both arms require the task to+/// have BEEN a vision ask: a disclaimer in a report about anything else is+/// prose, not a capability admission.+pub fn warningFor(ask: Ask, report: []const u8) ?[]const u8 {+ if (!ask.isAsk()) return null;+ if (disclaimed(report)) return disclaimer_warning;+ return if (ask.pinned_blind) pinned_warning else null;+}++/// Prepend the warning to a gpa-owned report, transferring ownership. Never+/// fails: on OOM the report is returned unflagged rather than lost, because a+/// missing warning is a smaller harm than a missing report.+pub fn flagText(gpa: Allocator, text: []u8, ask: Ask) []u8 {+ const line = warningFor(ask, text) orelse return text;+ const out = std.fmt.allocPrint(gpa, "{s}\n\n{s}", .{ line, text }) catch return text;+ gpa.free(text);+ return out;+}++/// flagText over a whole ToolOutput. `is_error` is carried through unchanged+/// — a disclaimed report is not a failed one.+pub fn flagReport(gpa: Allocator, out: tools.ToolOutput, ask: Ask) tools.ToolOutput {+ var flagged = out;+ flagged.text = flagText(gpa, out.text, ask);+ return flagged;+}++/// The fast-fail a blocked vision ask returns instead of spawning. Names the+/// reason and every way to fix it, because the alternative — the run that+/// motivated #380 — is a text-only worker inventing what it cannot see.+pub fn blockMessage(gpa: Allocator, ask: Ask) ![]u8 {+ if (ask.pricier.len > 0) return std.fmt.allocPrint(+ gpa,+ "subagent not spawned: this task references an image ({s}) and the only vision-capable model this provider serves ('{s}') is not provably cheaper than the model this worker would have used — an automatic route never escalates spend. Authorize it explicitly by passing model:\"{s}\" on the subagent call, or log in to a flat-rate vision subscription (`graff login codex`, `graff login kimi`). A text-only worker would have to infer the pixels rather than see them, so this spawn is refused instead of returning a confident guess.",+ .{ ask.path, ask.pricier, ask.pricier },+ );+ return std.fmt.allocPrint(+ gpa,+ "subagent not spawned: this task references an image ({s}) and no vision-capable model is reachable with the current credentials. A text-only worker would have to infer the pixels rather than see them, so this spawn is refused instead of returning a confident guess. Fix it with `graff login codex`, `graff login kimi`, `graff login anthropic`, or by setting OPENAI_API_KEY / ANTHROPIC_API_KEY / GEMINI_API_KEY, then retry. Vision-capable families: claude-*, gpt-5*/gpt-4*, gemini-*, grok-4*, kimi/k*. If the image is incidental, drop the path from the task and re-spawn.",+ .{ask.path},+ );+}++test {+ _ = @import("vision_ask_tests.zig");+}diff --git a/src/vision_ask_tests.zig b/src/vision_ask_tests.zignew file mode 100644index 00000000..6f919d85--- /dev/null+++ b/src/vision_ask_tests.zig@@ -0,0 +1,378 @@+//! #380 tests: image-path detection, the vision-ask re-route (and the pins it+//! must NOT override), the no-vision-anywhere fast fail, and the report-time+//! honesty flag. Split out of vision_ask.zig so neither file grows toward the+//! 600-line cap; reached from test_hooks.zig, without which these would be+//! silently skipped.++const std = @import("std");++const va = @import("vision_ask.zig");+const pin_mod = @import("subagent_pin.zig");+const policy = @import("route_policy.zig");+const route_phase = @import("route_phase.zig");+const bench = @import("bench_priors.zig");+const selection = @import("subagent_selection.zig");+const provider_mod = @import("provider.zig");+const Provider = provider_mod.Provider;++fn obj(a: std.mem.Allocator, json: []const u8) std.json.ObjectMap {+ const v = std.json.parseFromSliceLeaky(std.json.Value, a, json, .{ .allocate = .alloc_always }) catch unreachable;+ return v.object;+}++fn deepseek() Provider {+ return .{ .id = "deepseek", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "deepseek-v4-pro", .context = 128_000 };+}++fn codex() Provider {+ return .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "k", .model = "gpt-5.6-sol", .context = 270_000 };+}++/// A Keys table with `logged_in` providers holding a token, installed as the+/// global bench_priors.g_keys the routing code reads. Returns the previous+/// value so the caller can restore it.+fn withKeys(keys: *provider_mod.Keys, logged_in: []const []const u8) void {+ keys.* = .{ .values = @splat(null) };+ for (provider_mod.provider_specs, &keys.values) |spec, *value| {+ for (logged_in) |id| if (std.mem.eql(u8, spec.id, id)) {+ value.* = "test-token";+ };+ }+ bench.g_keys = keys;+}++test "#380 detection: a concrete image path, not any mention of an image format" {+ // POSITIVES — the shapes a root actually writes.+ try std.testing.expectEqualStrings("assets/palette.png", va.imagePathIn("Analyze the color palette in assets/palette.png and report the hex values").?);+ try std.testing.expectEqualStrings("shot.png", va.imagePathIn("open shot.png").?); // bare filename+ try std.testing.expectEqualStrings("/tmp/a.JPEG", va.imagePathIn("read /tmp/a.JPEG").?); // case-insensitive+ try std.testing.expectEqualStrings("docs/x.webp", va.imagePathIn("(see docs/x.webp)").?); // parenthesised+ try std.testing.expectEqualStrings("ui.gif", va.imagePathIn("`ui.gif`").?); // backticked+ try std.testing.expectEqualStrings("out/v2.final.jpg", va.imagePathIn("compare out/v2.final.jpg, then stop").?); // dotted stem, trailing comma+ try std.testing.expectEqualStrings("a.png", va.imagePathIn("the file is a.png.").?); // sentence-final period+ // A quoted path may contain spaces — widened only because the same quote+ // closes right after the extension.+ try std.testing.expectEqualStrings("my shots/color palette.png", va.imagePathIn("open \"my shots/color palette.png\" please").?);+ try std.testing.expectEqualStrings("color palette.png", va.imagePathIn("open 'color palette.png' please").?);++ // NEGATIVES — every one of these used to be the reason a naive substring+ // check could not be shipped.+ try std.testing.expect(va.imagePathIn("explain png compression and why gif is worse") == null);+ try std.testing.expect(va.imagePathIn("the .pngx container format") == null); // a word byte after the ext+ try std.testing.expect(va.imagePathIn("save it as a .png file") == null); // no stem+ try std.testing.expect(va.imagePathIn("delete all *.png artifacts") == null); // a glob is not a concrete path+ try std.testing.expect(va.imagePathIn("fetch https://example.com/a.png") == null); // remote URL, see the module doc+ try std.testing.expect(va.imagePathIn("http://x.io/y/z.jpg") == null);+ try std.testing.expect(va.imagePathIn("") == null);+ try std.testing.expect(va.imagePathIn("no images here at all") == null);+ // An unquoted space still splits: the detection is right (it IS an ask),+ // only the reported token is the tail. Pinned so the behavior is a choice.+ try std.testing.expectEqualStrings("palette.png", va.imagePathIn("open my shots/color palette.png").?);+}++test "#380 re-route: an automatic seat that cannot see images moves to one that can" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const saved = bench.g_keys;+ defer bench.g_keys = saved;+ var keys: provider_mod.Keys = undefined;+ withKeys(&keys, &.{"codex"});++ // A plain inherit-the-root deepseek session (session_pinned = false) is an+ // AUTOMATIC seat: nobody chose deepseek for THIS worker.+ const ask = va.forSpawn(deepseek(), obj(a, "{}"), false, .{}, "Analyze the palette in assets/palette.png");+ try std.testing.expect(ask.isAsk());+ try std.testing.expect(ask.rerouted);+ try std.testing.expect(!ask.blocked);+ try std.testing.expect(!ask.pinned_blind);+ try std.testing.expectEqual(policy.Source.vision_ask, ask.source);+ // Sub-first: the logged-in flat-rate codex subscription, cheapest rung.+ try std.testing.expectEqualStrings("codex", ask.pin.provider.?.id);+ try std.testing.expectEqualStrings("gpt-5.6-luna", ask.pin.provider.?.model);+ try std.testing.expectEqualStrings("vision-ask", ask.source.label());+ try std.testing.expect(ask.note() != null);++ // The SAME session with a task that names no image is left exactly alone.+ const plain = va.forSpawn(deepseek(), obj(a, "{}"), false, .{}, "Summarize the README");+ try std.testing.expect(!plain.isAsk());+ try std.testing.expect(!plain.rerouted);+ try std.testing.expect(plain.pin.provider == null); // session default kept+ try std.testing.expectEqual(policy.Source.session_default, plain.source);++ // A seat that ALREADY sees images is not moved either — no gratuitous+ // model changes just because a path was mentioned.+ const seeing = va.forSpawn(codex(), obj(a, "{}"), false, .{}, "Describe shot.png");+ try std.testing.expect(seeing.isAsk());+ try std.testing.expect(!seeing.rerouted);+ try std.testing.expect(seeing.pin.provider == null);+}++test "#380 re-route: an explicit pin and a persona pin keep priority, and are flagged" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const saved = bench.g_keys;+ defer bench.g_keys = saved;+ var keys: provider_mod.Keys = undefined;+ withKeys(&keys, &.{ "codex", "deepseek" });++ // The call names a text-only model for a task that needs eyes. The pin is+ // HONORED (a human outranks a capability heuristic) and the run is marked+ // so both the trace and the report say what happened.+ const pinned = va.forSpawn(deepseek(), obj(a, "{\"model\":\"deepseek-v4-flash\"}"), false, .{}, "read assets/palette.png");+ try std.testing.expect(pinned.pinned_blind);+ try std.testing.expect(!pinned.rerouted);+ try std.testing.expect(!pinned.blocked);+ try std.testing.expectEqualStrings("deepseek-v4-flash", pinned.pin.provider.?.model); // not overridden+ try std.testing.expectEqual(policy.Source.explicit_pin, pinned.source); // the trace still credits the human+ try std.testing.expect(std.mem.indexOf(u8, pinned.note().?, "pin was kept") != null);++ // An explicit --subagent-model session (session_pinned = true, and the+ // worker model did NOT come from the #291 ladder descent) is the same+ // human decision one level up: warn, never override.+ const saved_ladder = selection.g_default_from_ladder;+ defer selection.g_default_from_ladder = saved_ladder;+ selection.g_default_from_ladder = false;+ const session = va.forSpawn(deepseek(), obj(a, "{}"), true, .{}, "read assets/palette.png");+ try std.testing.expect(session.pinned_blind);+ try std.testing.expect(!session.rerouted);+ try std.testing.expect(session.pin.provider == null);++ // The SAME session_pinned bit with the worker seated by the automatic+ // ladder descent is not a human choice at all — it re-routes. Conflating+ // the two is exactly the blindness #372 named.+ selection.g_default_from_ladder = true;+ try std.testing.expect(va.forSpawn(deepseek(), obj(a, "{}"), true, .{}, "read assets/palette.png").rerouted);++ // userChose is the whole rule, stated once.+ try std.testing.expect(va.userChose(.explicit_pin, false));+ try std.testing.expect(va.userChose(.persona, false));+ try std.testing.expect(va.userChose(.session_default, true)); // --subagent-model+ try std.testing.expect(!va.userChose(.session_default, false)); // plain inherit+ try std.testing.expect(!va.userChose(.ladder, false));+ try std.testing.expect(!va.userChose(.learned_policy, false));+}++test "#380 fast fail: no vision-capable model anywhere refuses the spawn, actionably" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const saved = bench.g_keys;+ defer bench.g_keys = saved;+ var keys: provider_mod.Keys = undefined;+ withKeys(&keys, &.{"deepseek"}); // no sub logged in, and deepseek serves no vision model++ const ask = va.forSpawn(deepseek(), obj(a, "{}"), false, .{}, "extract the hexes from assets/palette.png");+ try std.testing.expect(ask.blocked);+ try std.testing.expect(!ask.rerouted);+ try std.testing.expect(ask.pin.provider == null);++ const msg = try va.blockMessage(std.testing.allocator, ask);+ defer std.testing.allocator.free(msg);+ try std.testing.expect(std.mem.indexOf(u8, msg, "assets/palette.png") != null); // names the trigger+ try std.testing.expect(std.mem.indexOf(u8, msg, "graff login") != null); // names the fix+ try std.testing.expect(std.mem.indexOf(u8, msg, "API_KEY") != null); // …and the other fix+ try std.testing.expect(std.mem.indexOf(u8, msg, "not spawned") != null); // and says nothing ran++ try std.testing.expect(ask.pricier.len == 0); // deepseek serves NO vision model, at any price++ // A task with no image on the same credential-starved session still runs.+ try std.testing.expect(!va.forSpawn(deepseek(), obj(a, "{}"), false, .{}, "refactor util.zig").blocked);++ // The OTHER refusal: a vision model exists on this provider but the cost+ // ceiling refuses it, because an automatic route never escalates spend.+ // Saying "none is reachable" there would be a lie, so it is a distinct+ // message that names the model and how to authorize it.+ withKeys(&keys, &.{"anthropic"});+ const cheap: Provider = .{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "k", .model = "claude-haiku-4-5", .context = 200_000 };+ try std.testing.expectEqualStrings("", va.blockedByCost(cheap)); // haiku IS the cheap vision rung — affordable, so not this case+ const priced_out: Provider = .{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "k", .model = "deepseek-v4-flash", .context = 200_000 };+ try std.testing.expectEqualStrings("claude-haiku-4-5", va.blockedByCost(priced_out));+ const cost_msg = try va.blockMessage(std.testing.allocator, .{ .path = "a.png", .blocked = true, .pricier = "claude-haiku-4-5" });+ defer std.testing.allocator.free(cost_msg);+ try std.testing.expect(std.mem.indexOf(u8, cost_msg, "model:\"claude-haiku-4-5\"") != null); // how to authorize it+ try std.testing.expect(std.mem.indexOf(u8, cost_msg, "escalate") != null); // and why it was not taken+ try std.testing.expect(!std.mem.eql(u8, cost_msg, msg));+}++test "#380 candidate search: sub-first, then provider-local under the cost ceiling" {+ // Ladder rungs bottom-up, so a re-route descends price rather than seizing+ // the frontier model.+ try std.testing.expectEqualStrings("gpt-5.6-luna", va.visionModelFor("codex").?);+ try std.testing.expectEqualStrings("claude-haiku-4-5", va.visionModelFor("anthropic").?);+ try std.testing.expect(va.visionModelFor("deepseek") == null); // no vision model at any rung++ const saved = bench.g_keys;+ defer bench.g_keys = saved;+ var keys: provider_mod.Keys = undefined;++ // Nothing logged in: no sub candidate, and deepseek has nothing local.+ bench.g_keys = null;+ try std.testing.expect(va.visionSeat(deepseek()) == null);++ // codex logged in: the flat-rate sub wins, cross-provider, exactly like+ // subagent_pin.subscriptionRung — the login IS the consent.+ withKeys(&keys, &.{"codex"});+ const seat = va.visionSeat(deepseek()).?;+ try std.testing.expectEqualStrings("codex", seat.id);+ try std.testing.expectEqualStrings("gpt-5.6-luna", seat.model);++ // An anthropic base with no sub logged in resolves provider-locally, and+ // only because haiku is CHEAPER than the opus it replaces.+ withKeys(&keys, &.{"anthropic"});+ const opus_root: Provider = .{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "k", .model = "claude-opus-4-8", .context = 200_000 };+ const local = va.visionSeat(opus_root).?;+ try std.testing.expectEqualStrings("anthropic", local.id);+ try std.testing.expectEqualStrings("claude-haiku-4-5", local.model);+}++test "#380 honesty flag: each disclaimer spelling is caught, ordinary reports are not" {+ const ask: va.Ask = .{ .path = "assets/palette.png" };+ const not_ask: va.Ask = .{};++ // The exact sentence from the trajectory that motivated this issue.+ const real = "I couldn't open the image as a vision input, so I sampled the file bytes instead.";+ try std.testing.expect(va.disclaimed(real));+ try std.testing.expectEqualStrings(va.disclaimer_warning, va.warningFor(ask, real).?);++ for (va.disclaimers) |d| {+ var buf: [256]u8 = undefined;+ const report = try std.fmt.bufPrint(&buf, "Report follows. {s} — here is what I inferred.", .{d});+ try std.testing.expect(va.disclaimed(report));+ try std.testing.expectEqualStrings(va.disclaimer_warning, va.warningFor(ask, report).?);+ // Case-insensitive, since a report may start the sentence.+ var up: [256]u8 = undefined;+ const upper = std.ascii.upperString(up[0..report.len], report);+ try std.testing.expect(va.disclaimed(upper));+ // …but a task that never named an image is never flagged, however the+ // worker phrased itself.+ try std.testing.expect(va.warningFor(not_ask, report) == null);+ }++ // Ordinary reports — including ones that talk about images at length —+ // stay unflagged. This is why the marker list is tight.+ for ([_][]const u8{+ "The image shows three greens and a warm grey; the dominant hue is #2E5B3A.",+ "I opened the image and read the palette directly.",+ "png compression is lossless, unlike jpeg",+ "Could not open the file assets/palette.png — it does not exist.",+ "",+ }) |ok| {+ try std.testing.expect(!va.disclaimed(ok));+ try std.testing.expect(va.warningFor(ask, ok) == null);+ }++ // A kept blind pin flags even a report that made no admission — the root+ // otherwise has no way to know the worker never saw anything.+ const blind: va.Ask = .{ .path = "a.png", .pinned_blind = true };+ try std.testing.expectEqualStrings(va.pinned_warning, va.warningFor(blind, "The palette is #2E5B3A, #C9A227, #8A8F98.").?);+ // The stronger, evidence-backed line wins when both apply.+ try std.testing.expectEqualStrings(va.disclaimer_warning, va.warningFor(blind, "I cannot view the image.").?);+ // And an unflagged, non-ask spawn keeps its blind pin quiet.+ try std.testing.expect(va.warningFor(.{ .pinned_blind = true }, "done") == null);+}++test "#380 flagText: prepends once, transfers ownership, never marks is_error" {+ const gpa = std.testing.allocator;+ const ask: va.Ask = .{ .path = "a.png" };++ const owned = try gpa.dupe(u8, "I couldn't open the image as a vision input; the palette below is inferred.");+ const flagged = va.flagText(gpa, owned, ask);+ defer gpa.free(flagged);+ try std.testing.expect(std.mem.startsWith(u8, flagged, va.disclaimer_warning));+ try std.testing.expect(std.mem.indexOf(u8, flagged, "the palette below is inferred") != null); // report survives verbatim+ try std.testing.expect(std.mem.indexOf(u8, flagged, "not seen.\n\nI couldn't") != null); // one blank line, one warning++ // A clean report is returned byte-identical, with no reallocation.+ const clean = try gpa.dupe(u8, "The palette is #2E5B3A.");+ const unflagged = va.flagText(gpa, clean, ask);+ defer gpa.free(unflagged);+ try std.testing.expectEqual(clean.ptr, unflagged.ptr);++ // flagReport preserves is_error in both directions: a disclaimed report is+ // not a failure, and a failed one does not become a success.+ const err_text = try gpa.dupe(u8, "cannot view the image");+ const out = va.flagReport(gpa, .{ .text = err_text, .is_error = true }, ask);+ defer gpa.free(out.text);+ try std.testing.expect(out.is_error);+ const ok_text = try gpa.dupe(u8, "cannot view the image");+ const ok = va.flagReport(gpa, .{ .text = ok_text, .is_error = false }, ask);+ defer gpa.free(ok.text);+ try std.testing.expect(!ok.is_error); // the work may still have value++ // rebased re-derives the path from a heap copy, so a background job's+ // decision does not point into the dead tool-call arena.+ const heap_prompt = try gpa.dupe(u8, "look at assets/palette.png");+ defer gpa.free(heap_prompt);+ const moved = ask.rebased(heap_prompt);+ try std.testing.expect(moved.isAsk());+ try std.testing.expectEqualStrings("assets/palette.png", moved.path);+ try std.testing.expect(!ask.rebased("no image here").isAsk());+}++test "#380 phase seat: a whole phase moves at once, and only an automatic one" {+ const saved = bench.g_keys;+ defer bench.g_keys = saved;+ var keys: provider_mod.Keys = undefined;+ withKeys(&keys, &.{"codex"});++ const image_tasks = [_][]const u8{ "summarize the notes", "read assets/palette.png" };+ const text_tasks = [_][]const u8{ "summarize the notes", "refactor util.zig" };+ const ladder_seat: route_phase.Seat = .{ .provider = deepseek(), .base_source = .ladder, .title = "sweep", .role = "sweep" };++ // Automatic (ladder) seat + an image somewhere in the phase → re-seated,+ // uniformly, and reported as vision-ask rather than learned-policy.+ const moved = va.phaseSeat(ladder_seat, &image_tasks, false);+ try std.testing.expect(moved.vision);+ try std.testing.expectEqualStrings("gpt-5.6-luna", moved.provider.model);+ try std.testing.expectEqualStrings("gpt-5.6-luna", moved.pin.?.model); // every worker gets it+ try std.testing.expectEqual(policy.Source.vision_ask, moved.sourceFor(false));+ try std.testing.expectEqual(policy.Source.vision_ask, moved.sourceFor(true)); // even with a genome override++ // No image in the phase → untouched.+ const still = va.phaseSeat(ladder_seat, &text_tasks, false);+ try std.testing.expect(!still.vision);+ try std.testing.expect(still.pin == null);+ try std.testing.expectEqual(policy.Source.ladder, still.sourceFor(false));++ // A seat a human chose (explicit --subagent-model) is never moved.+ const human: route_phase.Seat = .{ .provider = deepseek(), .base_source = .session_default };+ try std.testing.expect(!va.phaseSeat(human, &image_tasks, true).vision);++ // A seat that already sees images is left alone too.+ const seeing: route_phase.Seat = .{ .provider = codex(), .base_source = .ladder };+ try std.testing.expect(!va.phaseSeat(seeing, &image_tasks, false).vision);+}++test "#380 trace: the routing line carries source=vision-ask in #372's own format" {+ var buf: [320]u8 = undefined;+ try std.testing.expectEqualStrings(+ "shape=adhoc role=- tier=small resolved_model=gpt-5.6-luna source=vision-ask policy_or_genome_id=-",+ policy.formatDecision(&buf, .{ .tier = .small, .resolved_model = "gpt-5.6-luna", .source = .vision_ask }),+ );+ // The spelling is hyphenated like every other source, and distinct.+ try std.testing.expectEqualStrings("vision-ask", policy.Source.vision_ask.label());+ for ([_]policy.Source{ .explicit_pin, .persona, .learned_policy, .workflow_override, .session_default, .ladder }) |other|+ try std.testing.expect(!std.mem.eql(u8, other.label(), policy.Source.vision_ask.label()));+}++test "#380 does not disturb #292: the pin chain's own outcomes still arrive" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const saved = bench.g_keys;+ defer bench.g_keys = saved;+ var keys: provider_mod.Keys = undefined;+ withKeys(&keys, &.{"codex"});++ // An effort pin rides through a vision ask untouched (independent axes).+ const ask = va.forSpawn(deepseek(), obj(a, "{\"effort\":\"max\"}"), false, .{}, "read a.png");+ try std.testing.expectEqual(pin_mod.EffortOutcome.pinned, ask.pin.effort_outcome);+ try std.testing.expect(ask.pin.effort.? == .max);+ try std.testing.expect(ask.rerouted);++ // An off-vocabulary tier is still reported as a typo, not swallowed.+ const typo = va.forSpawn(codex(), obj(a, "{\"tier\":\"cheap\"}"), false, .{}, "read a.png");+ try std.testing.expectEqual(pin_mod.Outcome.unknown_tier, typo.pin.outcome);+}diff --git a/src/workflow.zig b/src/workflow.zigindex 8644b768..62ce6d02 100644--- a/src/workflow.zig+++ b/src/workflow.zig@@ -40,6 +40,7 @@ const Isolation = fleet.Isolation; // #276 P0-1const route_policy = @import("route_policy.zig"); // #372 (shape, role) policy cellsconst route_phase = @import("route_phase.zig"); // #376 one learned seat per phaseconst route_trace = @import("route_trace.zig"); // #372 per-worker routing trace+const vision_ask = @import("vision_ask.zig"); // #380 vision-aware seating + report honesty flagconst 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@@ -489,14 +490,16 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {// is the session route unless the learned (shape, role) policy found a// strictly better-value model for this phase's cell; either way the// #372 trace names the rung, the cell and the layer that decided.- const seat = route_phase.forPhase(subagent_run.childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider), shape, title, niches, ctx.subagent_provider != null);+ // #380: …then asked whether any task in it names an image the seat+ // cannot see. A re-seat stays phase-UNIFORM, so #290 is untouched.+ const seat = vision_ask.phaseSeat(route_phase.forPhase(subagent_run.childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider), shape, title, niches, ctx.subagent_provider != null), prompts, ctx.subagent_provider != null);for (labels, prompts, overrides, niches, isolations, isolation_fallbacks, futures, 1..) |label, prompt, override, niche, isolation, isolation_fallback, *fut, task_no| {wfp.task(ctx.io, arena, run_id, phase_no, task_no, tasks.len, label, "running"); // #63route_trace.emitSpawnProvider(ctx.io, ctx.tracer, label, seat.provider, seat.cellOf(niche), seat.sourceFor(override != null), override, niche);fut.* = ctx.io.async(workflowTask, .{ ctx, label, prompt, override, niche, isolation, isolation_fallback, seat.pin });}- for (futures, outputs, labels, 1..) |*fut, *out, label, task_no| {- out.* = fut.await(ctx.io);+ for (futures, outputs, labels, prompts, 1..) |*fut, *out, label, prompt, task_no| {+ out.* = vision_ask.flagReport(gpa, fut.await(ctx.io), vision_ask.forPrompt(prompt)); // #380 honesty flag// #63 — terminal per task, so a UI can settle that row without// waiting for the phase (and before the retry pass below reruns it).wfp.task(ctx.io, arena, run_id, phase_no, task_no, tasks.len, label, if (out.is_error) "failed" else "completed");@@ -526,8 +529,8 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {rf.* = ctx.io.async(workflowRetryTask, .{ ctx, labels[i], prompts[i], overrides[i], niches[i], isolations[i], isolation_fallbacks[i], seat.pin });}for (refut, 0..) |*rf, k| {- const retry = rf.await(ctx.io);const i = fidx[k];+ const retry = vision_ask.flagReport(gpa, rf.await(ctx.io), vision_ask.forPrompt(prompts[i])); // #380if (!retry.is_error) {gpa.free(outputs[i].text);outputs[i] = retry;