Skip to content

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

Python
38.0 KB
Raw Blame
//! Tool-schema + provider-tool JSON emission. Split out of main.zig (#123).

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

const mcp = @import("mcp.zig");
const pricing = @import("pricing.zig");
const learn_store = @import("learn_store.zig");
/// #1764: note_constraint advertises the byte ceiling playbook_glue enforces.
const playbook_max_text = std.fmt.comptimePrint("{d}", .{@import("playbook.zig").max_text});
const skill_docs = @import("skill_docs.zig"); // SKILL.md playbooks: the `skill` tool's name/desc/schema live there
const peer_channel = @import("peer_channel.zig");
const workspace_switch = @import("workspace_switch.zig");
const no_local_tools = @import("no_local_tools.zig"); // #330: the hard --no-local-tools gate (layer 1 lives here, layer 2 in exec.zig)
const tool_gates = @import("tool_gates.zig"); // #352: the additive twin — optional tools that only exist when startup found their backing capability
const imagegen = @import("imagegen.zig");
const rlm = @import("rlm.zig");
const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: load_tool_schemas strings
const mcp_select = @import("mcp_select.zig"); // fx search-then-select
const result_read = @import("result_read.zig"); // overflow handle pager
const shell_tool = @import("shell_tool.zig");
const native_fold = @import("native_fold.zig"); // folded native power tools
const render = @import("schema_render.zig"); // the comptime provider-tool renderers moved out when #352's optional-tool catalogs doubled the number held here (600-line ceiling)
const anthropicToolsJson = render.anthropicToolsJson;
const openaiToolsJson = render.openaiToolsJson;
const responsesToolsJson = render.responsesToolsJson;

const root = @import("main.zig");
const provider_mod = @import("provider.zig");
const Provider = provider_mod.Provider;

/// Documentation of the `--json` stdio protocol, embedded verbatim in
/// `--schema` output so SDK generators/users know the request/event contract.
const schema_protocol_json = @import("schema_protocol.zig").json;
/// Documentation of the `harness serve` HTTP bridge, embedded verbatim in
/// `--schema` output. Same request/event contract as the stdio protocol —
/// one POST = one protocol request, streamed back as NDJSON until that
/// request's terminal event (turn/error for user turns; the ack for others) —
/// plus the #330 resumability surface (seq, ?from=N, durable session names).
const schema_serve_json = @import("schema_serve.zig").json;
/// Launch flags for SDK clients (schema_protocol.zig, alongside the protocol
/// doc it is emitted with), re-exported here as the `--schema` field name.
pub const schema_flags_json = @import("schema_protocol.zig").flags;
pub const ToolSpec = struct {
    name: []const u8,
    desc: []const u8, // no characters needing JSON escapes
    schema: []const u8, // raw JSON Schema string
};

const empty_schema =
    \\{"type": "object", "properties": {}}
;

/// attempt_completion's description; gemini_turns.withCompletionBatch extends it per model (ADR 0256).
pub const attempt_completion_desc = "Signal that the task is complete. Put your final answer to the user in the result field. In strict mode use this for completed tasks; use yield_turn instead to stop for missing user input without claiming completion. Completing also closes the standing /goal; if its checklist still has open items you will be asked once to finish or confirm.";

pub const base_specs = [_]ToolSpec{
    .{ .name = shell_tool.tool_name, .desc = shell_tool.tool_desc, .schema = shell_tool.tool_schema },
    .{
        .name = "read_file",
        .desc = "Read a UTF-8 text file or view a PNG/JPEG/GIF/WebP image up to 5 MiB. Read images one at a time; pixels reach the next model request when vision is supported. Call this before editing an existing text file; a file you are about to create needs no read. For a read-only exact-key lookup, pass contains to return only matching numbered lines instead of the whole file. Whole-file reads over 256 KiB return a short preview; pass start_line/end_line (1-based, inclusive) for a byte-exact window from any size file.",
        .schema =
        \\{"type": "object", "properties": {"path": {"type": "string", "description": "File path, relative to the working directory"}, "start_line": {"type": ["integer", "null"], "description": "Optional 1-based first line to return (byte-exact slice; omit or null for whole file)"}, "end_line": {"type": ["integer", "null"], "description": "Optional 1-based last line to return, inclusive; omit or null for whole file"}, "contains": {"type": ["string", "null"], "description": "Optional exact literal; return only matching lines with line numbers instead of the whole file. Prefer this for exact-key read-only lookups. Omit, null, or empty for a whole-file or window read. Cannot combine a nonempty value with start_line, end_line, or compact."}, "compact": {"type": ["boolean", "null"], "description": "Exploratory only: return a comment/blank-stripped view via codedb (line numbers shown). Omit, null, or false for a byte-exact read. NEVER use before an edit — re-read without compact to copy exact text."}}, "required": ["path"]}
        ,
    },
    .{
        .name = "edit_file",
        .desc = "Replace exact strings in a file. One span: old_string + new_string (old_string must match exactly one spot unless replace_all is set). Many spans: pass edits, an array of {old_string, new_string, replace_all?} applied in order — PREFER one batched call over several edit_file calls to the same file. Prefer this over write_file when changing an existing file.",
        .schema =
        \\{"type": "object", "properties": {"path": {"type": "string"}, "old_string": {"type": "string", "description": "Exact existing text to find (single-span form)"}, "new_string": {"type": "string", "description": "Replacement text (single-span form)"}, "replace_all": {"type": "boolean", "description": "Replace every occurrence (default: require a unique match)"}, "edits": {"type": "array", "items": {"type": "object", "properties": {"old_string": {"type": "string"}, "new_string": {"type": "string"}, "replace_all": {"type": "boolean"}}, "required": ["old_string", "new_string"]}, "description": "Batch form: several spans applied in order in one call"}}}
        ,
    },
    .{
        .name = "write_file",
        .desc = "Create a file, or replace one you have read, edited or written in this session. It will not replace any other existing file unless replace is true, so there is no need to check whether a path exists first, and a missing directory is created. The result says whether it created or replaced the file and, for a .json path, whether the content parses.",
        .schema =
        \\{"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}, "replace": {"type": "boolean", "description": "Overwrite an existing file you have not read in this session"}}, "required": ["path", "content"]}
        ,
    },
    .{
        .name = "webfetch",
        .desc = "Fetch an http(s) URL with a plain HTTP GET and return the raw HTML/text. Output is size-capped.",
        .schema =
        \\{"type": "object", "properties": {"url": {"type": "string", "description": "Absolute http:// or https:// URL to fetch"}}, "required": ["url"]}
        ,
    },
    // Progressive disclosure: the system prompt carries skill names +
    // descriptions, this tool fetches one body on demand (skill_docs.zig).
    .{ .name = skill_docs.tool_name, .desc = skill_docs.tool_desc, .schema = skill_docs.tool_schema },
    .{
        .name = "codedb",
        .desc = "Indexed code nav (github.com/justrach/codedb). ONE command — not a hop chain: context <task> · around <name> · callpath A B · list_dir <path> · status. Prefer over bash grep/find/ls. list_dir is in-process (gitignore, PathConfine; no binary). status reports codedb.snapshot. Paths stay in the cwd. context is on-device (`--local`) by default; pass --hybrid/--semantic only for remote advisory rerank. local_only or repository policy refuse those remote flags before spawn.",
        .schema =
        \\{"type": "object", "properties": {"command": {"type": "string", "description": "One of: \"context how does auth work\", \"around codedbGuard\", \"callpath exec codedbGuard\", \"list_dir src\", \"status\". Bare context is local (on-device); add --hybrid only if you want remote rerank."}, "local_only": {"type": "boolean", "description": "Refuse remote rerank: dispatch `codedb context --local`. Also applied automatically when repository policy requires local-only retrieval. Explicit --hybrid/--semantic under that policy is refused before spawn."}}, "required": ["command"]}
        ,
    },
    .{ .name = result_read.tool_name, .desc = result_read.tool_desc, .schema = result_read.tool_schema },
    @import("html_view.zig").spec,
};

// Meta tools act on the agent's own state, not the outside world; the
// orchestrator handles them inline (never on a pool thread).
const meta_specs = [_]ToolSpec{
    .{
        .name = "todo_write",
        .desc = "Replace the task list for the current standing goal (items from a replaced, cleared or completed goal are parked - kept in the session, but not part of this list and not replaced by this call). An item you already marked completed is kept as history when you leave it out, for as long as the current request is being worked; list it again (with any status) to change or remove it that way. Once every item is completed, the next thing the user asks starts a clean list - finished work is not carried into it. Omitted pending/in_progress items are dropped. Every call needs at least one item: a call with none leaves the list untouched. Use to plan and track multi-step work; skip it for trivial single-step tasks. Each item has content and status (pending|in_progress|completed|cancelled). Use cancelled only for work the user withdrew or handed to someone else, with a short reason (required: who withdrew it or where it went): the item stays on the list with its reason and stops blocking completion, but never counts as done or verified. A verification item can be cancelled only after a newer user message or an ask_user answer changes scope. Write steps small enough to verify individually; keep exactly ONE item in_progress at a time — mark it in_progress when you start and completed as it lands, never a batch flipped at the end.",
        .schema =
        \\{"type": "object", "properties": {"todos": {"type": "array", "items": {"type": "object", "properties": {"content": {"type": "string"}, "status": {"type": "string", "enum": ["pending", "in_progress", "completed", "cancelled"]}, "reason": {"type": "string", "description": "Required when status is cancelled: who withdrew the item or where it was delegated, in a few words."}}, "required": ["content", "status"]}}}, "required": ["todos"]}
        ,
    },
    .{
        .name = "todo_read",
        .desc = "Read your current task list (the current goal's items; work parked by an earlier goal, and finished lists retired by a later request, are not included).",
        .schema = empty_schema,
    },
    .{
        .name = "eval",
        .desc = "Run the configured scoring command (graff --eval) alone and record the result. The HARNESS runs it and logs the score to .graff/eval-log.tsv - do not run it via bash. Returns score, best, target, and gate state. Red drops the current plan and grants a repair turn: make ONE focused repair, then re-evaluate before completion (a repeatedly-red eval eventually surfaces the hard stop). In `note`, describe the focused change and label new CONFIRMED/GUESS/HYPOTHESIS/FACT beliefs.",
        .schema =
        \\{"type": "object", "properties": {"note": {"type": "string", "description": "What you changed since the last eval"}}}
        ,
    },
    // #381: the durable-rejection capture surface. Root-only, and APPEND-ONLY
    // by construction — there is no retire/edit/list operation here at all,
    // so a model that finds a constraint inconvenient has no mechanism to
    // widen it; only the user can, with /never rm <id-or-text> (#638).
    .{ .name = "note_constraint", .desc = "Record an explicit project-wide user rule in this project's playbook (.graff/playbook.jsonl). Do not call for temporary, task/session-limited, or ambiguous steering; follow that locally or ask before persisting. Durable intent must be clear. Pass scope=project and copy text verbatim from the current user message without widening qualifiers; `text` is at most " ++ playbook_max_text ++ " bytes (UTF-8), so a longer rule cannot be recorded and must not be shortened by dropping qualifiers. The visible result includes scope, origin, and text plus /never removal guidance. Project records survive compaction and future sessions. Append-only: only the user can retire one with /never rm <id-or-text> (REPL, TUI, or ACP) or an explicit override. Duplicates are harmless.", .schema = "{\"type\": \"object\", \"properties\": {\"text\": {\"type\": \"string\", \"description\": \"Exact verbatim project-wide constraint from the current user message, at most " ++ playbook_max_text ++ " bytes\"}, \"scope\": {\"type\": \"string\", \"enum\": [\"project\"], \"description\": \"Durable scope; local steering must not be recorded\"}}, \"required\": [\"text\", \"scope\"]}" },
    .{
        .name = "ask_user",
        .desc = "Ask the human a question and wait for typed text or an option selection. Do not request screenshots or images here unless the active interface explicitly supports attachments in question replies; backend vision support alone is not enough. If that support is absent or unknown and an image is essential, use yield_turn to explain the next-prompt attachment handoff and stop without calling ask_user. Do not ask for permission to pause. Keep the conversation open and do not claim the task is complete. For text questions, put choices in options: the harness renders a numbered picker and blocks for the answer. Ending the turn with a menu written in prose does neither.",
        .schema =
        \\{"type": "object", "properties": {"question": {"type": "string", "description": "The question to ask the user"}, "options": {"type": "array", "items": {"type": "string"}, "description": "Optional suggested answers, shown numbered"}}, "required": ["question"]}
        ,
    },
    .{
        .name = "attempt_completion",
        .desc = attempt_completion_desc,
        .schema =
        \\{"type": "object", "properties": {"result": {"type": "string", "description": "Final answer to present to the user"}}, "required": ["result"]}
        ,
    },
    // #416, the MCP half of progressive disclosure: an expensive server is
    // registered by name + one line per tool, and this loads the real schemas
    // (and enables those tools) on demand. Meta because it mutates the root's
    // own tool catalog; renderRootTools drops it while nothing is deferred.
    .{ .name = mcp_schema_gate.tool_name, .desc = mcp_schema_gate.tool_desc, .schema = mcp_schema_gate.tool_schema },
    .{ .name = mcp_select.search_name, .desc = mcp_select.search_desc, .schema = mcp_select.search_schema },
    .{ .name = mcp_select.select_name, .desc = mcp_select.select_desc, .schema = mcp_select.select_schema },
    .{
        .name = "clock_sleep",
        .desc = "Pause the current turn for up to 12 hours of wall-clock time; interruptible by user input, and reported as a normal (non-error) result either way. For autonomous /goal runs that need to wait before re-checking something (e.g. a long external job). Root-only; off unless --clock-sleep/GRAFF_CLOCK_SLEEP=1 is set.",
        .schema =
        \\{"type": "object", "properties": {"ms": {"type": "integer", "description": "Milliseconds to sleep (0 returns immediately; clamped to the 12h/43200000ms cap)"}, "reason": {"type": "string", "description": "Optional: why you're sleeping, for the trace/UX"}}, "required": ["ms"]}
        ,
    },
};

const subagent_spec = @import("schema_agents.zig").subagent_spec;
const agent_output_spec = @import("schema_agents.zig").agent_output_spec;
const workflow_spec = @import("schema_agents.zig").workflow_spec;
const agent_message_spec = @import("schema_agents.zig").agent_message_spec;

const learn_candidate_spec = ToolSpec{
    .name = "learn_candidate",
    .desc = "Bundle the workspace's pinned prompt-policy mutation, paired evaluation, immutable evidence, and signed aggregate grade submission into one action. Grade telemetry excludes prompt/genome text, but configured adapters may send it to their declared model provider. In Local privacy mode this requires a separate one-shot confirmation that --yolo cannot bypass; Aggregate or higher uses normal tool approval. This never promotes or changes the active policy and is root-only.",
    .schema =
    \\{"type": "object", "properties": {"candidates": {"type": "integer", "minimum": 1, "maximum": 16, "description": "Optional candidate count; defaults to the learning config"}, "repetitions": {"type": "integer", "minimum": 1, "maximum": 100, "description": "Optional repetitions per evaluation case; defaults to the learning config"}}}
    ,
};

const peer_spec = ToolSpec{ .name = peer_channel.tool_name, .desc = peer_channel.tool_desc, .schema = peer_channel.tool_schema };
const workspace_spec = ToolSpec{ .name = workspace_switch.tool_name, .desc = workspace_switch.tool_desc, .schema = workspace_switch.tool_schema };
pub const root_specs = base_specs ++ meta_specs ++ [_]ToolSpec{ subagent_spec, workflow_spec, agent_output_spec, agent_message_spec, @import("schema_agents.zig").subagent_resume_spec, learn_candidate_spec, peer_spec, workspace_spec, @import("turn_handoff.zig").spec };
/// The root catalog minus the named optional entries, built once at compile
/// time. The length check is the guard: each name must match EXACTLY one
/// spec, so a rename or a duplicated entry is a compile error rather than a
/// silently-wrong catalog.
fn rootSpecsWithout(comptime drop: []const []const u8) [root_specs.len - drop.len]ToolSpec {
    var out: [root_specs.len - drop.len]ToolSpec = undefined;
    var len: usize = 0;
    entry: for (root_specs) |tool| {
        for (drop) |name| if (std.mem.eql(u8, tool.name, name)) continue :entry;
        out[len] = tool;
        len += 1;
    }
    if (len != out.len) @compileError("root tool catalog optional entries changed");
    return out;
}

const root_specs_without_clock = rootSpecsWithout(&.{"clock_sleep"});
const root_specs_without_learning = rootSpecsWithout(&.{"learn_candidate"});
const root_specs_without_optional = rootSpecsWithout(&.{ "clock_sleep", "learn_candidate" });

pub const meta_names = [_][]const u8{ "todo_write", "todo_read", "ask_user", "eval", "attempt_completion", "yield_turn", "clock_sleep", "note_constraint", mcp_schema_gate.tool_name, mcp_select.search_name, mcp_select.select_name, peer_channel.tool_name, workspace_switch.tool_name };

pub fn isMetaName(name: []const u8) bool {
    for (meta_names) |m| if (std.mem.eql(u8, name, m)) return true;
    return false;
}

// #352: optional built-ins — advertised only while tool_gates says they are
// available. They live in `base_specs`' orbit rather than the root-only block
// because a subagent has to be able to call them: the documented way to make
// several images is one subagent per image, each calling `imagegen` once.
pub const optional_specs = [_]ToolSpec{
    .{ .name = imagegen.tool_name, .desc = imagegen.tool_desc, .schema = imagegen.tool_schema },
};

// Comptime-rendered tool lists for subagents (base only, both formats).
pub const tools_anthropic_sub = anthropicToolsJson(&base_specs);
pub const tools_openai_sub = openaiToolsJson(&base_specs);
pub const tools_responses_sub = responsesToolsJson(&base_specs);

// #330 layer 1, subagent half: the same three catalogs with the host-touching
// tools filtered out at compile time. agent.zig picks between the twins on
// no_local_tools.enabled, so a child is never even told shell exists.
const base_specs_remote = no_local_tools.remoteSpecs(ToolSpec, &base_specs);
pub const tools_anthropic_sub_remote = anthropicToolsJson(base_specs_remote);
pub const tools_openai_sub_remote = openaiToolsJson(base_specs_remote);
pub const tools_responses_sub_remote = responsesToolsJson(base_specs_remote);

// #352 layer 1, subagent half: the same catalogs WITH the optional tools. A
// child's catalog is a comptime constant, so every combination is built once
// at compile time and merely selected at runtime by subToolsJson.
const base_specs_optional = base_specs ++ optional_specs;
const base_specs_optional_remote = no_local_tools.remoteSpecs(ToolSpec, &base_specs_optional);
pub const tools_anthropic_sub_optional = anthropicToolsJson(&base_specs_optional);
pub const tools_openai_sub_optional = openaiToolsJson(&base_specs_optional);
pub const tools_responses_sub_optional = responsesToolsJson(&base_specs_optional);
pub const tools_anthropic_sub_optional_remote = anthropicToolsJson(base_specs_optional_remote);
pub const tools_openai_sub_optional_remote = openaiToolsJson(base_specs_optional_remote);
pub const tools_responses_sub_optional_remote = responsesToolsJson(base_specs_optional_remote);

/// The catalog a SUBAGENT is served. Lives in schema_interactions.zig with the
/// Interactions catalogs (600-line ceiling here); re-exported so every existing
/// `schema.subToolsJson` caller keeps resolving.
pub const subToolsJson = @import("schema_interactions.zig").subToolsJson;

/// Render built-in specs + discovered MCP tools into one provider-specific
/// tools array (allocated with `out`). Used for the root agent at startup.
pub fn renderRootTools(
    out: Allocator,
    kind: Provider.Kind,
    specs: []const ToolSpec,
    mcp_tools: []const mcp.Tool,
) ![]u8 {
    var aw: Io.Writer.Allocating = .init(out);
    errdefer aw.deinit();
    var s: std.json.Stringify = .{ .writer = &aw.writer };
    try s.beginArray();
    for (specs) |t| {
        if (mcp_schema_gate.hiddenSpec(t.name, mcp_tools) and (!native_fold.anyFolded() or no_local_tools.lean)) continue; // lean: no empty load_tool_schemas
        if (native_fold.catalogSkips(t.name)) continue; // zero-stub like the MCP half: folded natives ride the meta tool's listing (#476)
        if (std.mem.eql(u8, t.name, mcp_schema_gate.tool_name))
            try writeToolEntry(&s, kind, t.name, try mcp_schema_gate.descWithListing(out, mcp_tools), .{ .raw = t.schema })
        else
            try writeToolEntry(&s, kind, t.name, t.desc, .{ .raw = t.schema });
    }
    // Deferred tools ship no entries (codex tool_search pattern); the meta
    // tool's desc lists them, exec.zig layer 2 guards premature calls.
    for (mcp_tools) |m| if (!mcp_schema_gate.omitMcp(m.qualified_name) and !mcp_schema_gate.isDeferred(mcp_tools, m) and !(mcp_schema_gate.g_stable_catalog and mcp_schema_gate.policyDeferred(mcp_tools, m)))
        try writeToolEntry(&s, kind, m.qualified_name, m.description, .{ .value = m.input_schema });
    // GRAFF_STABLE_CATALOG (#476): loaded tools append in LOAD ORDER after the
    // stable head, so loads change only tail bytes (see renderLoadedTail for
    // why that alone does not keep an OpenAI cache hit).
    if (mcp_schema_gate.g_stable_catalog) try native_fold.renderLoadedTail(&s, kind, out, mcp_tools);
    try s.endArray();
    return aw.toOwnedSlice();
}

/// Root tool catalog for the current session: optional tools are absent unless
/// enabled and usable, avoiding schema tokens for calls that cannot succeed.
/// #330 drops host-touching tools from the chosen catalog; #352 appends each
/// optional tool whose backing capability startup found. MCP tools are
/// appended afterwards by renderRootTools and stay untouched.
pub fn effectiveRootSpecs(arena: Allocator) ![]const ToolSpec {
    const chosen: []const ToolSpec = if (root.g_clock_sleep)
        (if (learn_store.active_agent_loaded) &root_specs else &root_specs_without_learning)
    else
        (if (learn_store.active_agent_loaded) &root_specs_without_clock else &root_specs_without_optional);
    // Optionals before #330 (optional ≠ exempt); lean + licensed surface filter chain inside assembleRoot.
    return rlm.maybeAppend(ToolSpec, arena, try tool_gates.assembleRoot(ToolSpec, arena, chosen, &optional_specs));
}

const Schema = union(enum) { raw: []const u8, value: Value };

fn writeSchema(s: *std.json.Stringify, schema: Schema) !void {
    switch (schema) {
        .raw => |r| try s.print("{s}", .{r}),
        .value => |v| try s.write(v),
    }
}

pub fn writeToolEntry(s: *std.json.Stringify, kind: Provider.Kind, name: []const u8, desc: []const u8, schema: Schema) !void {
    switch (kind) {
        .anthropic => {
            try s.beginObject();
            try s.objectField("name");
            try s.write(name);
            try s.objectField("description");
            try s.write(desc);
            try s.objectField("input_schema");
            try writeSchema(s, schema);
            try s.endObject();
        },
        // Interactions is the Responses entry without `strict`, which it
        // rejects as an unknown parameter.
        .interactions => {
            try s.beginObject();
            try s.objectField("type");
            try s.write("function");
            try s.objectField("name");
            try s.write(name);
            try s.objectField("description");
            try s.write(desc);
            try s.objectField("parameters");
            try writeSchema(s, schema);
            try s.endObject();
        },
        .openai => {
            try s.beginObject();
            try s.objectField("type");
            try s.write("function");
            try s.objectField("function");
            try s.beginObject();
            try s.objectField("name");
            try s.write(name);
            try s.objectField("description");
            try s.write(desc);
            try s.objectField("parameters");
            try writeSchema(s, schema);
            try s.endObject();
            try s.endObject();
        },
        .responses => {
            // Responses API: flat function tool (no nested "function" object).
            try s.beginObject();
            try s.objectField("type");
            try s.write("function");
            try s.objectField("name");
            try s.write(name);
            try s.objectField("description");
            try s.write(desc);
            try s.objectField("parameters");
            try writeSchema(s, schema);
            try s.objectField("strict");
            try s.write(false);
            try s.endObject();
        },
    }
}

/// A Responses entry hosted tool search must leave eager (ADR 0231): the MCP
/// tools a child inherits were already chosen by its root, and deferring them
/// made every child spend its first call on a tool search.
pub fn writeEagerResponsesEntry(s: *std.json.Stringify, name: []const u8, desc: []const u8, schema: Schema) !void {
    try s.beginObject();
    try s.objectField("type");
    try s.write("function");
    try s.objectField("name");
    try s.write(name);
    try s.objectField("description");
    try s.write(desc);
    try s.objectField("parameters");
    try writeSchema(s, schema);
    try s.objectField("strict");
    try s.write(false);
    try s.objectField("defer_loading");
    try s.write(false);
    try s.endObject();
}

/// Version of the `--schema`/`--json` *interface contract*, embedded in
/// generated SDKs. Deliberately not the build version (`harness_version`,
/// a per-commit git describe) — bump this only when the schema or JSONL
/// protocol changes shape, so SDK regeneration stays byte-stable across
/// commits.
pub const schema_version = "0.13"; // tool lifecycle IDs correlate parallel ACP updates

/// Emit the machine-readable interface description for `harness --schema`:
/// providers, models, built-in tools (name/description/parameters), and the
/// --json protocol contract. This is the single source of truth that SDK
/// codegen consumes. Comptime data only — no keys, network, or MCP needed.
/// Human-facing provider name for the `--schema` providers array (consumed by
/// the GUI settings page so its provider list stays tied to the harness).
fn providerDisplayName(id: []const u8) []const u8 {
    return if (provider_mod.specFor(id)) |spec| spec.display_name else id;
}

/// How a provider's credential is acquired, for the GUI settings page:
/// `codegraff`/`codex` use device/OAuth login flows; everything else is a
/// drop-in API key (env var or `graff key set <id>`).
fn providerLoginKind(id: []const u8) []const u8 {
    return if (provider_mod.specFor(id)) |spec| @tagName(spec.login) else "api_key";
}

/// Whether a model exposes a user-selectable reasoning effort. Kimi maps the
/// setting through its live effort list into `thinking`; the other listed
/// providers use reasoning_effort / Responses reasoning.effort.
/// Native xAI grok honors low|medium|high|xhigh. grok-build and Codegraff-
/// routed grok still reject the hint, so they stay excluded — the reactive
/// drop-and-retry in request() still covers any other model that
/// turns out to reject it.
pub fn providerTakesEffort(kind: Provider.Kind, id: []const u8, model: []const u8) bool {
    // Native Claude discovery must match output_config.effort serialization (ADR 0219).
    if (kind == .anthropic and std.mem.eql(u8, id, "anthropic")) return @import("claude_wire.zig").takesEffort(model);
    if (std.mem.startsWith(u8, model, "grok")) return std.mem.eql(u8, id, "xai");
    if (@import("effort_route.zig").mimoRoute(id, model)) return true;
    return kind == .responses or
        (std.mem.eql(u8, id, "kimi") and pricing.kimiSupportsThinking(model)) or
        (if (provider_mod.specFor(id)) |spec| spec.takes_effort else false);
}

pub fn emitSchema(w: *Io.Writer) !void {
    var s: std.json.Stringify = .{ .writer = w, .options = .{ .whitespace = .indent_2 } };
    try s.beginObject();
    try s.objectField("harness");
    try s.write("simple-harness");
    try s.objectField("version");
    try s.write(schema_version);
    try s.objectField("providers");
    try s.beginArray();
    for (0..provider_mod.specCount()) |i| {
        const p = provider_mod.specAt(i).?;
        try s.beginObject();
        try s.objectField("id");
        try s.write(p.id);
        try s.objectField("name");
        try s.write(p.display_name);
        try s.objectField("kind");
        try s.write(@tagName(p.kind));
        try s.objectField("auth");
        try s.write(@tagName(p.auth));
        try s.objectField("env_key");
        try s.write(p.env_key);
        try s.objectField("login");
        try s.write(@tagName(p.login));
        try s.objectField("default_model");
        try s.write(p.default_model);
        if (p.catalog == .kimi) {
            try s.objectField("protocol_source");
            try s.write("live_model_catalog");
            try s.objectField("anthropic_auth");
            try s.write("x_api_key");
        }
        try s.endObject();
    }
    try s.endArray();
    try s.objectField("models");
    try s.beginArray();
    for (pricing.models()) |m| {
        try s.beginObject();
        try s.objectField("provider");
        try s.write(m.provider);
        try s.objectField("name");
        try s.write(m.name);
        try s.objectField("context");
        try s.write(m.context);
        try s.endObject();
    }
    try s.endArray();
    try s.objectField("dynamic_model_providers");
    try s.beginArray();
    for (0..provider_mod.specCount()) |i| {
        const p = provider_mod.specAt(i).?;
        if (p.catalog != .baked) try s.write(p.id);
    }
    try s.endArray();
    try s.objectField("tools");
    try s.beginArray();
    // Optionals + rlm: SDK dump is unconditional (#352, #868).
    for (root_specs ++ optional_specs ++ [_]ToolSpec{.{ .name = rlm.tool_name, .desc = rlm.tool_desc, .schema = rlm.tool_schema }}) |t| {
        try s.beginObject();
        try s.objectField("name");
        try s.write(t.name);
        try s.objectField("description");
        try s.write(t.desc);
        try s.objectField("parameters");
        try s.print("{s}", .{t.schema});
        try s.endObject();
    }
    try s.endArray();
    try s.objectField("flags");
    try s.print("{s}", .{schema_flags_json});
    try s.objectField("protocol");
    try s.print("{s}", .{schema_protocol_json});
    try s.objectField("serve");
    try s.print("{s}", .{schema_serve_json});
    try s.endObject();
    try w.writeByte('\n');
    try w.flush();
}
test { // #330/#352: each gate's own tests (advertising, dispatch, env) live with it
    _ = no_local_tools;
    _ = tool_gates;
    _ = render;
}
test "providerDisplayName & providerLoginKind: id mapping with sane fallbacks" {
    try std.testing.expectEqualStrings("OpenAI", providerDisplayName("openai"));
    try std.testing.expectEqualStrings("Codex (ChatGPT)", providerDisplayName("codex"));
    try std.testing.expectEqualStrings("mystery", providerDisplayName("mystery")); // unknown -> echoed id
    try std.testing.expectEqualStrings("codegraff_device", providerLoginKind("codegraff"));
    try std.testing.expectEqualStrings("codex_device", providerLoginKind("codex"));
    try std.testing.expectEqualStrings("kimi_device", providerLoginKind("kimi"));
    try std.testing.expectEqualStrings("zai_cli", providerLoginKind("zai"));
    try std.testing.expectEqualStrings("api_key", providerLoginKind("openai"));
}
// isMetaName's own coverage, and #381's note_constraint catalog contract,
// live in tool_schema_tests.zig — this file is at the 600-line ceiling.

test "effectiveRootSpecs: drops clock_sleep from the root tool catalog unless the flag is on (#225)" {
    var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena_state.deinit();
    const a = arena_state.allocator();
    const saved = root.g_clock_sleep;
    const saved_learning = learn_store.active_agent_loaded;
    defer {
        root.g_clock_sleep = saved;
        learn_store.active_agent_loaded = saved_learning;
    }
    learn_store.active_agent_loaded = true;

    root.g_clock_sleep = false;
    const off_specs = try effectiveRootSpecs(a);
    try std.testing.expectEqual(root_specs.len, off_specs.len); // -clock_sleep +rlm
    for (off_specs) |t| try std.testing.expect(!std.mem.eql(u8, t.name, "clock_sleep"));
    try std.testing.expect(arena_state.queryCapacity() > 0); // maybeAppend copies to append rlm

    root.g_clock_sleep = true;
    const on_specs = try effectiveRootSpecs(a);
    try std.testing.expectEqual(root_specs.len + 1, on_specs.len); // +rlm
    var found = false;
    for (on_specs) |t| {
        if (std.mem.eql(u8, t.name, "clock_sleep")) found = true;
    }
    try std.testing.expect(found);

    root.g_clock_sleep = false;
    learn_store.active_agent_loaded = false;
    const minimal_specs = try effectiveRootSpecs(a);
    try std.testing.expectEqual(root_specs.len - 1, minimal_specs.len); // -clock -learn +rlm
    for (minimal_specs) |tool| try std.testing.expect(!std.mem.eql(u8, tool.name, "learn_candidate"));
}
test "learn_candidate is root-only and cannot become a subagent tool" {
    var found = false;
    for (root_specs) |tool| if (std.mem.eql(u8, tool.name, "learn_candidate")) {
        found = true;
    };
    try std.testing.expect(found);
    try std.testing.expect(std.mem.indexOf(u8, learn_candidate_spec.desc, "adapters may send it") != null);
    try std.testing.expect(std.mem.indexOf(u8, tools_openai_sub, "learn_candidate") == null);
}
test "providerTakesEffort: native xAI grok takes effort; gateway grok does not" {
    try std.testing.expect(providerTakesEffort(.responses, "codex", "gpt-5.5"));
    try std.testing.expect(providerTakesEffort(.openai, "codegraff", "deepseek-v4-pro"));
    try std.testing.expect(providerTakesEffort(.openai, "deepseek", "deepseek-v4-pro"));
    try std.testing.expect(providerTakesEffort(.openai, "zai", "glm-5.3"));
    try std.testing.expect(providerTakesEffort(.openai, "vercel", "alibaba/qwen3.8-27b"));
    try std.testing.expect(providerTakesEffort(.openai, "openrouter", "anthropic/claude-sonnet-4.6"));
    try std.testing.expect(providerTakesEffort(.openai, "omlx", "any-downloaded-model"));
    try std.testing.expect(providerTakesEffort(.openai, "kimi", "k3"));
    try std.testing.expect(!providerTakesEffort(.openai, "openai", "gpt-5.5")); // direct openai chat
    try std.testing.expect(providerTakesEffort(.responses, "xai", "grok-4.6"));
    try std.testing.expect(providerTakesEffort(.openai, "xai", "grok-4.6")); // chat opt-out
    try std.testing.expect(!providerTakesEffort(.openai, "codegraff", "grok-build"));
}
test "agent_output: root-only (subagent/workflow's run_in_background has nothing to poll from inside a child), never doubles as a meta tool" {
    var found_root = false;
    for (root_specs) |t| if (std.mem.eql(u8, t.name, "agent_output")) {
        found_root = true;
    };
    try std.testing.expect(found_root);
    try std.testing.expect(!isMetaName("agent_output")); // dispatched like shell action=output, not handled inline

    // Subagents can't spawn subagents (execSubagent's from_sub gate), so they
    // can never mint an agent id to poll — keep it out of their own catalog
    // (tools_anthropic_sub is built from base_specs only).
    try std.testing.expect(std.mem.indexOf(u8, tools_anthropic_sub, "agent_output") == null);
    try std.testing.expect(std.mem.indexOf(u8, tools_anthropic_sub, "subagent") == null);
}

test "subagent_spec: run_in_background is a boolean, optional (not in required), valid JSON alongside the rest of the schema" {
    try std.testing.expect(std.mem.indexOf(u8, subagent_spec.schema, "\"run_in_background\": {\"type\": \"boolean\"") != null);
    var parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, subagent_spec.schema, .{});
    defer parsed.deinit();
    const required = parsed.value.object.get("required").?.array.items;
    for (required) |r| try std.testing.expect(!std.mem.eql(u8, r.string, "run_in_background"));
}

test "subagent_spec: independent fan-out defaults to worktree, not shared_cwd" {
    try std.testing.expect(std.mem.indexOf(u8, subagent_spec.schema, "fan-out children default to") != null);
    try std.testing.expect(std.mem.indexOf(u8, subagent_spec.schema, "worktree") != null);
    try std.testing.expect(std.mem.indexOf(u8, subagent_spec.schema, "Default shared_cwd") == null);
    try std.testing.expect(std.mem.indexOf(u8, workflow_spec.schema, "fan-out tasks default to") != null);
    try std.testing.expect(std.mem.indexOf(u8, workflow_spec.schema, "pipeline stages default to") != null);
}