Skip to content

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

Python
26.2 KB
Raw Blame
//! Tool dispatch: `execTool` + `execToolInner`. Split out of main.zig.

const std = @import("std");
const builtin = @import("builtin");
const Io = std.Io;
const Value = std.json.Value;
const Allocator = std.mem.Allocator;

const main_mod = @import("main.zig");
const util = @import("util.zig");
const codedbpro_report = @import("codedbpro_report.zig"); // licensed-companion failure → redacted issue filer
const tool_surface = @import("tool_surface.zig"); // companion-write gate + licensed hide
const codedbpro_paths = @import("codedbpro_paths.zig"); // session-cwd paths for the resident companion daemon
const tool_balance = @import("tool_balance.zig"); // session-wide tool-class tally (/tools)
const ToolCall = tools.ToolCall;

const tools = @import("tools.zig");
const ToolCtx = tools.ToolCtx;
const ToolOutput = tools.ToolOutput;
const codedbGuard = tools.codedbGuard;
const companionRoute = tools.companionRoute;
const hookGate = tools.hookGate;
const runPostToolHooks = tools.runPostToolHooks;
const failure = tools.failure;
const strField = tools.strField;
const intField = tools.intField;
const missingArg = tools.missingArg;
const outsideCwd = tools.outsideCwd;
const rawFetch = tools.rawFetch;

const subagent = @import("subagent.zig");
const execSubagent = subagent.execSubagent;
const agentOutput = subagent.agentOutput; // #276 P0-3
const workflow = @import("workflow.zig");
const execWorkflow = workflow.execWorkflow;

const mcp = @import("mcp.zig");
const jev_tool = @import("jev_tool.zig");
const approvals_mod = @import("approvals.zig");
const Approvals = approvals_mod.Approvals;
const confinedPath = approvals_mod.confinedPath;
const noSymlinkEscape = approvals_mod.noSymlinkEscape;
const jobs = @import("jobs.zig");
const runCapped = jobs.runCapped;
const exec_bash = @import("exec_bash.zig");
const shell_tool = @import("shell_tool.zig");
const skill_docs = @import("skill_docs.zig");
const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: refuse an MCP tool whose schema was never loaded
const read_file = @import("read_file.zig");
const read_miss = @import("read_miss.zig");
const result_read = @import("result_read.zig");
const codedb_exec = @import("codedb_exec.zig"); // native codedb dispatch (list_dir / status / one-shots)
// #337: edit_file's verified write path, plus the file-tool helpers that moved
// out with it (this file is at the 600-line ceiling).
const edit_verify = @import("edit_verify.zig");
const edit_batch = @import("edit_batch.zig"); // batched edit_file spans (#476)
const fsErrorText = edit_verify.fsErrorText;
const preserveMode = edit_verify.preserveMode;
const hooks = @import("hooks.zig");
const telemetry = @import("telemetry.zig");
const learning_privacy = @import("learning_privacy.zig");
const no_local_tools = @import("no_local_tools.zig"); // #330: the hard --no-local-tools gate
const native_fold = @import("native_fold.zig"); // folded native power tools: layer-2 refusal until load_tool_schemas unfolds
const stageReadFileImage = @import("read_image.zig").stage;
const input_util = @import("input_util.zig");
const imagegen = @import("imagegen.zig"); // #352: the codex-gated image tool (advertising lives in schema.zig/tool_gates.zig)
const html_view = @import("html_view.zig"); // the model's own drawing surface: one HTML page, rendered inline in the desktop transcript
const local_tools = @import("local_tools.zig");
const write_file = @import("write_file.zig"); // ADR 0231: no-clobber writes that say what they did

fn learningArgv(argv: *[10][]const u8, exe_path: []const u8, contribute: bool) usize {
    var argc: usize = 0;
    for ([_][]const u8{ exe_path, "--learning-privacy", if (contribute) "aggregate" else "local", "learn", "run" }) |arg| {
        argv[argc] = arg;
        argc += 1;
    }
    if (contribute) {
        argv[argc] = "--submit";
        argc += 1;
    }
    return argc;
}

pub fn execTool(ctx: ToolCtx, call: ToolCall) ToolOutput {
    if (ctx.run_budget) |budget| if (budget.toolRefusal(ctx.gpa, ctx.tracer)) |denied| return denied;
    const t0: Io.Timestamp = .now(ctx.io, .awake);
    // #255: reserved before any gate/dispatch runs so tool_started/
    // tool_finished bracket the whole call, including a gate denial below.
    const call_id: u64 = if (ctx.tracer) |tr| tr.toolStarted(call.name, call.input) else 0;
    if (noLocalToolsGate(ctx, call) orelse codedbGuard(ctx, call) orelse companionRoute(ctx, call) orelse hookGate(ctx, call) orelse codedbpro_report.licensedGate(ctx, call) orelse tool_surface.gate(ctx, call) orelse native_fold.gateExec(ctx.gpa, call.name, ctx.from_sub)) |blocked| {
        var out = blocked;
        out.ms = t0.untilNow(ctx.io, .awake).toMilliseconds();
        if (ctx.tracer) |tr| {
            tr.tool(call.name, call_id, out.ms, true, out.text.len, ctx.from_sub);
            tr.toolFinished(call.name, call_id, out.ms, true, out.text.len);
        }
        if (ctx.tools_used) |ts| ts.add(ctx.io, ctx.gpa, call.name, true);
        return out;
    }
    var out = execToolInner(ctx, call) catch |err| blk: {
        // Harness-level tool failure (spawn error, OOM, broken pipe) — not a
        // tool that ran and returned is_error; those are normal agent
        // feedback and already counted in the session summary.
        var ebuf: [160]u8 = undefined;
        const detail = std.fmt.bufPrint(&ebuf, "{s}: {t}", .{ call.name, err }) catch @errorName(err);
        if (telemetry.g_telem) |t| t.errorEvent("tool", detail);
        break :blk failure(ctx.gpa, err);
    };
    out.ms = t0.untilNow(ctx.io, .awake).toMilliseconds();
    if (ctx.tracer) |tr| {
        tr.tool(call.name, call_id, out.ms, out.is_error, out.text.len, ctx.from_sub);
        tr.toolFinished(call.name, call_id, out.ms, out.is_error, out.text.len);
    }
    if (ctx.tools_used) |ts| ts.add(ctx.io, ctx.gpa, call.name, out.is_error);
    // Session-wide class tally (/tools) — and when suite usage NEWLY skews,
    // the nudge rides this tool result so the model hears it, not just the
    // user's /tools view. Edge-triggered: a few per session at most. The
    // superseded out.text is deliberately NOT freed (it can be a static
    // empty slice; freeing it would corrupt) — a rare small abandonment.
    if (tool_balance.record(ctx.gpa, call, out.is_error)) |nudge| {
        defer ctx.gpa.free(nudge);
        out.text = std.fmt.allocPrint(ctx.gpa, "{s}\n\n[{s}]", .{ out.text, nudge }) catch out.text;
    }
    runPostToolHooks(ctx, call, out);
    return out;
}

/// #330 layer 2: refuse a host-touching built-in even if a provider hallucinates
/// one that was never advertised (layer 1 is schema.zig). FIRST in the guard
/// chain; an `mcp__*` name never matches, so the sandbox proxy keeps working.
fn noLocalToolsGate(ctx: ToolCtx, call: ToolCall) ?ToolOutput {
    if (no_local_tools.enabled and local_tools.isLocal(call.name)) {
        const text = ctx.gpa.dupe(u8, no_local_tools.refusal_text) catch return .{ .text = &.{}, .is_error = true };
        return .{ .text = text, .is_error = true };
    }
    if (!no_local_tools.blocks(call.name)) return null;
    const text = ctx.gpa.dupe(u8, no_local_tools.refusal_text) catch return .{ .text = &.{}, .is_error = true };
    return .{ .text = text, .is_error = true };
}

fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
    const gpa = ctx.gpa;
    const io = ctx.io;

    // Plan mode backstop: the root gate already denies these with a nicer
    // message; this catches subagents (which skip the gate entirely).
    if (main_mod.plan_mode) {
        if (local_tools.isLocal(call.name) or std.mem.eql(u8, call.name, "learn_candidate") or std.mem.eql(u8, call.name, "write_file") or std.mem.eql(u8, call.name, "edit_file") or std.mem.eql(u8, call.name, imagegen.tool_name) or mcp.Registry.isMcp(call.name)) return .{
            .text = try gpa.dupe(u8, "plan mode is on — read-only; describe the change instead of making it"),
            .is_error = true,
        };
        if (shell_tool.isKill(call)) {
            return .{
                .text = try gpa.dupe(u8, "plan mode is on — only read-only commands run; describe this command in the plan instead"),
                .is_error = true,
            };
        }
        if (shell_tool.runCommand(call)) |cmd| if (!Approvals.readOnlyAllowed(cmd)) {
            // The root may have approved this external read-only path this
            // session (#64); subagents (from_sub) never get the external hatch.
            const ext_ok = !ctx.from_sub and if (ctx.approvals) |ap| ((if (ctx.plan_read_owner) |owner| ap.consumePlanReadOnce(ctx.io, owner, call.id, cmd) else false) or ap.planReadAllowed(ctx.io, cmd)) else false;
            if (!ext_ok) return .{
                .text = try gpa.dupe(u8, "plan mode is on — only read-only commands run; describe this command in the plan instead"),
                .is_error = true,
            };
        };
    }

    if (mcp.Registry.isMcp(call.name)) {
        const reg = ctx.registry orelse return .{
            .text = try gpa.dupe(u8, "MCP not available in this context"),
            .is_error = true,
        };
        // #416 layer 2, auto-load era: a confident call to a deferred tool
        // loads its schema inline and runs — the refusal round trip is gone
        // (same user direction as the native fold). Still downstream of
        // agent_tool_gate.gateTool: consent is already settled.
        const connected = try reg.snapshotTools(gpa);
        defer gpa.free(connected);
        mcp_schema_gate.autoLoad(gpa, connected, call.name);
        var prepared = codedbpro_paths.prepareInput(gpa, io, ctx.agent_cwd, call.name, call.input) catch |err| {
            codedbpro_report.onFailure(ctx, call.name, @errorName(err));
            return failure(gpa, err);
        };
        defer prepared.deinit(gpa);
        const r = reg.call(gpa, call.name, prepared.value) catch |err| {
            codedbpro_report.onFailure(ctx, call.name, @errorName(err));
            return failure(gpa, err);
        };
        if (r.is_error) codedbpro_report.onFailure(ctx, call.name, r.text);
        if (!r.is_error) {
            const shapes = @import("mcp_shapes.zig");
            shapes.remember(ctx, call.name, r.structured_text orelse r.text);
            // ADR 0238: an rlm bind keeps every field. rlm slims only what it
            // prints, so a script can still project or save a dropped field.
            if (ctx.rlm_host) return .{ .text = try r.takeHostText(gpa), .is_error = false, .run_task = r.run_task };
            return .{ .text = shapes.takeSlimKept(gpa, .{ .io = io, .dir = .cwd() }, r.text), .is_error = false, .run_task = r.run_task };
        }
        return .{ .text = r.text, .is_error = r.is_error, .run_task = r.run_task };
    }

    const input = call.input;
    if (std.mem.eql(u8, call.name, jev_tool.name)) return jev_tool.execute(ctx, input);
    if (std.mem.eql(u8, call.name, "learn_candidate")) {
        if (ctx.from_sub) return .{
            .text = try gpa.dupe(u8, "learning is root-only — subagents cannot run mutators, evaluators, or publish grades"),
            .is_error = true,
        };
        const candidates = intField(input, "candidates");
        const repetitions = intField(input, "repetitions");
        if (candidates) |n| if (n < 1 or n > 16) return .{ .text = try gpa.dupe(u8, "candidates must be between 1 and 16"), .is_error = true };
        if (repetitions) |n| if (n < 1 or n > 100) return .{ .text = try gpa.dupe(u8, "repetitions must be between 1 and 100"), .is_error = true };
        const exe_path = try std.process.executablePathAlloc(io, gpa);
        defer gpa.free(exe_path);
        var candidates_buf: [20]u8 = undefined;
        var repetitions_buf: [20]u8 = undefined;
        var argv_buf: [10][]const u8 = undefined;
        const contribute = main_mod.g_fleet and (learning_privacy.allowsAggregate() or learning_privacy.consumeAggregateOnce(io));
        var argc = learningArgv(&argv_buf, exe_path, contribute);
        if (candidates) |n| {
            argv_buf[argc] = "--candidates";
            argv_buf[argc + 1] = try std.fmt.bufPrint(&candidates_buf, "{d}", .{n});
            argc += 2;
        }
        if (repetitions) |n| {
            argv_buf[argc] = "--repetitions";
            argv_buf[argc + 1] = try std.fmt.bufPrint(&repetitions_buf, "{d}", .{n});
            argc += 2;
        }
        const run = try runCapped(gpa, io, argv_buf[0..argc], 256 * 1024, 64 * 1024, 0);
        defer gpa.free(run.stdout);
        defer gpa.free(run.stderr);
        const ok = run.term == .exited and run.term.exited == 0 and !run.timed_out;
        var aw: Io.Writer.Allocating = .init(gpa);
        errdefer aw.deinit();
        if (run.stdout.len > 0) try aw.writer.writeAll(run.stdout);
        if (run.stdout_truncated) try aw.writer.writeAll("\n[learning output truncated]");
        if (run.stderr.len > 0) try aw.writer.print("\n[stderr]\n{s}", .{run.stderr});
        if (run.stderr_truncated) try aw.writer.writeAll("\n[learning stderr truncated]");
        if (run.stdout.len == 0 and run.stderr.len == 0) try aw.writer.writeAll(if (ok) "learning run completed" else "learning run failed without output");
        return .{ .text = try aw.toOwnedSlice(), .is_error = !ok };
    }
    if (shell_tool.isFamily(call.name)) return shell_tool.exec(ctx, call);
    if (std.mem.eql(u8, call.name, "webfetch")) {
        const url = strField(input, "url") orelse return missingArg(gpa, "url");
        if (!std.mem.startsWith(u8, url, "http://") and !std.mem.startsWith(u8, url, "https://")) return .{
            .text = try gpa.dupe(u8, "webfetch only handles absolute http:// and https:// URLs"),
            .is_error = true,
        };
        return rawFetch(gpa, ctx.client, url);
    }
    if (std.mem.eql(u8, call.name, result_read.tool_name)) return result_read.exec(ctx, call);
    if (std.mem.eql(u8, call.name, "read_file")) {
        const path = strField(input, "path") orelse return missingArg(gpa, "path");
        if (ctx.read_miss) |tracker| {
            if (tracker.shouldRefuse(path)) return .{ .text = try read_miss.refusalText(gpa, path), .is_error = true };
        }
        if (!confinedPath(path) or !noSymlinkEscape(io, path, ctx.agent_cwd)) return outsideCwd(gpa, path);
        const start_line = intField(input, "start_line");
        const end_line = intField(input, "end_line");
        // Strict tool calling often sends null/"" for unused optionals (#761).
        // Empty contains is omitted so a whole-file or window read stays legal.
        const contains_raw = strField(input, "contains");
        const contains: ?[]const u8 = if (contains_raw) |n| (if (n.len == 0) null else n) else null;
        const want_compact = tools.json_args.flag(input, "compact");
        if (contains != null and (start_line != null or end_line != null or want_compact))
            return .{ .text = try gpa.dupe(u8, "read_file: contains cannot be combined with start_line, end_line, or compact"), .is_error = true };
        // #66: opt-in compact view routes to `codedb read <path> [-L a-b] --compact`
        // when codedb is present and this file is indexed. Lossy (strips comments/
        // blanks, shows line numbers) so it is NEVER the default and is labeled
        // not-for-editing; any failure falls through to the native byte-exact read.
        // #276: skipped entirely for a worktree-isolated agent — codedb's index is
        // built over the main checkout, not the scratch worktree, so a compact
        // read there could show stale or altogether wrong content.
        if (want_compact) {
            if (try codedb_exec.maybeCompactRead(ctx, path, start_line, end_line)) |out| return out;
        }
        // #747: same selected-tree absolute path as edit_file (sessionAbs).
        const resolved = try codedbpro_paths.sessionAbs(gpa, io, ctx.agent_cwd, path);
        defer gpa.free(resolved);
        const outcome = read_file.read(io, gpa, .cwd(), resolved, start_line, end_line, contains) catch |err| {
            if (fsErrorText(gpa, .read, path, err)) |t| return .{ .text = t, .is_error = true };
            return err;
        };
        switch (outcome) { // ADR 0231: write_file may now replace what the model has seen
            .text, .truncated, .no_match => write_file.noteKnown(io, resolved),
            else => {},
        }
        return switch (outcome) {
            .text => |text| .{ .text = text },
            .truncated => |value| blk: {
                defer gpa.free(value.head);
                break :blk .{ .text = try std.fmt.allocPrint(gpa, "{s}\n\n[read_file preview: {d}-byte file exceeds the {d} KiB whole-file limit; use start_line/end_line for byte-exact windows]", .{ util.utf8Prefix(value.head, value.head.len), value.total_bytes, read_file.max_bytes / 1024 }) };
            },
            .binary => |size| blk: {
                // An image is only "binary" to a text-only model: stage the
                // pixels exactly like an MCP image result (#249) so read_file
                // on a PNG/JPG/GIF/WebP attaches it to the next turn instead
                // of erroring out. Non-images keep the classic guidance.
                if (input_util.isImagePath(path)) {
                    if (try stageReadFileImage(gpa, io, ctx, resolved, path, size)) |out| break :blk out;
                }
                break :blk .{
                    .text = try std.fmt.allocPrint(gpa, "{s} is a binary file ({d} bytes) — read_file only handles text. Use bash instead (e.g. `file`, `strings`, `pdftotext`, `sips`, `unzip -l`).", .{ path, size }),
                    .is_error = true,
                };
            },
            .range_too_large => .{
                .text = try std.fmt.allocPrint(gpa, "read_file: requested range from {s} exceeds {d} KiB — request a narrower start_line/end_line window", .{ path, read_file.max_bytes / 1024 }),
                .is_error = true,
            },
            .start_past_end => .{
                .text = try std.fmt.allocPrint(gpa, "start_line {?d} is past the end of {s}", .{ start_line, path }),
                .is_error = true,
            },
            .no_match => .{
                .text = try std.fmt.allocPrint(gpa, "No lines in {s} contain the exact literal {s}.", .{ path, contains orelse "" }),
            },
        };
    }
    if (std.mem.eql(u8, call.name, "codedb")) return codedb_exec.exec(ctx, input);
    // #337: the read/splice/write/VERIFY path lives in edit_verify.zig, where
    // the post-edit check sits ON the success path — a write that did not land
    // can no longer be reported as `replaced N occurrence(s)`.
    if (std.mem.eql(u8, call.name, "edit_file")) {
        const out = try if (input == .object and input.object.get("edits") != null) edit_batch.execBatch(ctx, input) else edit_verify.execEdit(ctx, input);
        if (!out.is_error) write_file.noteInput(ctx, input); // ADR 0231: an edited file may be rewritten
        return out;
    }
    if (std.mem.eql(u8, call.name, "write_file")) return write_file.exec(ctx, input); // ADR 0231
    // Loads one SKILL.md body (or lists them). Rescans on every call, so a
    // skill written this session is loadable without a restart.
    if (std.mem.eql(u8, call.name, html_view.tool_name)) return html_view.exec(ctx, input);
    if (std.mem.eql(u8, call.name, "skill")) return skill_docs.execSkill(gpa, io, input);
    // #352: codex-gated. execImagegen answers a call that was never advertised
    // (an unavailable session) with the same honest error it gives the model.
    if (std.mem.eql(u8, call.name, imagegen.tool_name)) return imagegen.execImagegen(ctx, input);
    if (std.mem.eql(u8, call.name, "subagent")) {
        var child_ctx = ctx;
        child_ctx.parent_tool_call_id = call.id;
        return execSubagent(child_ctx, input);
    }
    if (std.mem.eql(u8, call.name, "workflow")) return execWorkflow(ctx, input);
    if (std.mem.eql(u8, call.name, @import("rlm.zig").tool_name)) {
        var rlm_ctx = ctx;
        if (rlm_ctx.host_gate) |*gate| gate.call_id = call.id; // consent prompts name this rlm call
        return @import("rlm.zig").exec(rlm_ctx, input);
    }
    if (local_tools.isLocal(call.name)) return local_tools.exec(gpa, io, call.name, input);
    if (std.mem.eql(u8, call.name, "agent_output")) {
        const wait_ms: u64 = @intCast(@max(intField(input, "wait_ms") orelse 0, 0));
        if (input == .object) if (input.object.get("ids")) |ids| if (ids == .array) return @import("subagent_interactive.zig").outputMany(ctx, ids.array.items, wait_ms);
        const id = intField(input, "id") orelse return missingArg(gpa, "id");
        if (id < 0 or id > std.math.maxInt(u32)) return .{ .text = try gpa.dupe(u8, "invalid agent id"), .is_error = true };
        return @import("subagent_interactive.zig").output(ctx, @intCast(id), wait_ms);
    }
    if (std.mem.eql(u8, call.name, "subagent_resume")) return @import("subagent_resume.zig").exec(ctx, input);
    if (std.mem.eql(u8, call.name, "agent_message")) return @import("subagent_messaging.zig").send(ctx, input);
    return .{ .text = try std.fmt.allocPrint(gpa, "unknown tool: {s}", .{call.name}), .is_error = true };
}

test "preserveMode restores bits via handle chmod so Windows cannot panic (#179/#606)" {
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try tmp.dir.writeFile(io, .{ .sub_path = "x.sh", .data = "a" });
    if (builtin.os.tag != .windows) {
        try tmp.dir.setFilePermissions(io, "x.sh", Io.File.Permissions.fromMode(0o755), .{});
    }
    const st = try tmp.dir.statFile(io, "x.sh", .{});
    try tmp.dir.writeFile(io, .{ .sub_path = "x.sh", .data = "b" });
    var real_buf: [std.fs.max_path_bytes]u8 = undefined;
    const n = try tmp.dir.realPath(io, &real_buf);
    const path = try std.fmt.allocPrint(std.testing.allocator, "{s}/x.sh", .{real_buf[0..n]});
    defer std.testing.allocator.free(path);
    preserveMode(io, path, st);
    if (builtin.os.tag != .windows) {
        const after = try tmp.dir.statFile(io, "x.sh", .{});
        try std.testing.expectEqual(@as(std.posix.mode_t, 0o755), after.permissions.toMode() & 0o777);
    }
}

test "native Jev dispatch rejects other models and latches off after one failed attempt" {
    const jev = @import("jev_tool.zig");
    jev.configure(struct {
        pub fn get(_: @This(), key: []const u8) ?[]const u8 {
            return if (std.mem.eql(u8, key, "JEV_BACKEND")) "mock-fail" else null;
        }
    }{});
    defer jev.configure(struct {
        pub fn get(_: @This(), _: []const u8) ?[]const u8 {
            return null;
        }
    }{});
    const base: @import("provider.zig").Provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = "gpt-6-sol", .context = 100_000 };
    var pending: @import("jev_effort_state.zig").Pending = .{};
    var ctx: ToolCtx = .{ .gpa = std.testing.allocator, .io = std.testing.io, .client = undefined, .provider = base, .jev_effort_pending = &pending, .registry = null, .from_sub = false, .approvals = null, .tracer = null };
    const parsed = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"task\":\"choose effort for a test fix\"}", .{});
    defer parsed.deinit();
    const call: ToolCall = .{ .id = "1", .name = jev.name, .input = parsed.value };
    const old_call: ToolCall = .{ .id = "old", .name = "jev_judge", .input = parsed.value };
    const old = try execToolInner(ctx, old_call);
    defer std.testing.allocator.free(old.text);
    try std.testing.expect(old.is_error);
    const no_login = try execToolInner(ctx, call);
    defer std.testing.allocator.free(no_login.text);
    try std.testing.expect(no_login.is_error);
    _ = jev.setCodegraffLoginKey(std.testing.io, "synthetic-login");
    try std.testing.expect(jev.available(ctx.provider)); // no upstream attempt before login
    ctx.provider.id = "xai";
    ctx.provider.model = "grok-4.7";
    const other_provider = try execToolInner(ctx, call);
    defer std.testing.allocator.free(other_provider.text);
    try std.testing.expect(other_provider.is_error);
    ctx.provider.id = "codex";
    ctx.provider.model = "gpt-5.6";
    const older_model = try execToolInner(ctx, call);
    defer std.testing.allocator.free(older_model.text);
    try std.testing.expect(older_model.is_error);
    ctx.provider.model = "gpt-6-sol";
    try std.testing.expect(jev.available(ctx.provider)); // ineligible attempts did not trip the circuit
    // ADR 0232: a child asks too. Upstream fails here, so its call is the one
    // attempt and opens the circuit for the whole session.
    ctx.from_sub = true;
    const worker = try execToolInner(ctx, call);
    defer std.testing.allocator.free(worker.text);
    try std.testing.expect(!worker.is_error);
    try std.testing.expect(!jev.available(ctx.provider));
    ctx.from_sub = false;
    const first = try execToolInner(ctx, call);
    defer std.testing.allocator.free(first.text);
    const second = try execToolInner(ctx, call);
    defer std.testing.allocator.free(second.text);
    try std.testing.expect(!first.is_error and !second.is_error);
    try std.testing.expectEqualStrings(first.text, second.text);
}

test "internal learning respects the parent privacy ceiling" {
    var argv: [10][]const u8 = undefined;
    var len = learningArgv(&argv, "graff", false);
    try std.testing.expectEqualSlices([]const u8, &.{ "graff", "--learning-privacy", "local", "learn", "run" }, argv[0..len]);
    len = learningArgv(&argv, "graff", true);
    try std.testing.expectEqualSlices([]const u8, &.{ "graff", "--learning-privacy", "aggregate", "learn", "run", "--submit" }, argv[0..len]);
}

test { // main.zig is at the 600-line cap; exec.zig is these modules' importer, so the compiled-in references live here (the reach check diffs the test binary, not which file holds the line)
    _ = exec_bash;
    _ = shell_tool;
    _ = @import("codedbpro_report.zig");
    _ = @import("tool_balance.zig");
    _ = @import("codedb_exec.zig");
    _ = @import("codedb_around.zig");
    _ = @import("codedb_health.zig");
    _ = @import("list_dir.zig");
    _ = @import("rlm.zig");
    _ = @import("rlm_spec.zig");
    _ = @import("rlm_query.zig");
    _ = @import("rlm_mcp.zig");
    _ = @import("rlm_reduce.zig");
    _ = @import("rlm_tests.zig");
    _ = @import("native_fold_rlm.zig");
    _ = @import("mcp_shapes.zig");
    _ = @import("spec_ptc.zig");
    _ = @import("xai_hosted.zig");
    _ = @import("read_file_schema_tests.zig"); // #761: optional read_file fields
    _ = @import("read_miss.zig"); // #1116: consecutive read_file miss storm
    _ = @import("read_miss_tests.zig");
}