Skip to content

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

Python

feat(fold): native power tools join the load_tool_schemas meta pattern

Rach Pradhanbe992ca652b0
diff --git a/src/agent_request.zig b/src/agent_request.zig
index dcf2a877..9976ee1f 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -63,6 +63,15 @@ pub const errorMessage = responses.errorMessage;
pub const buildBody = @import("agent_request_body.zig").buildBody;
+/// GRAFF_REQ_STATS=1 (set once at startup by session_settings.applyEnvKnobs):
+/// print the per-call request breakdown in request() — the token-diet
+/// program's measurement hook.
+pub var g_req_stats = false;
+
+fn reqStatsArmed() bool {
+ return g_req_stats;
+}
+
/// Keep the normal request hot path allocation-free while avoiding a permanent
/// RSS high-water mark after one anomalously large stream. Small scratch arenas
/// retain their pages for the next request; large ones return all pages to the
@@ -190,6 +199,11 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
self.streamed_args = .none;
const body = try self.buildBody(tools, force, live, stream_usage);
defer self.gpa.free(body);
+ // GRAFF_REQ_STATS=1: per-call request anatomy for the token-diet work
+ // — total body, tools JSON, system prompt; the remainder is messages.
+ // Byte sizes, not tokens (÷~4 for a rough token read). stderr, never
+ // json_mode's stdout.
+ if (reqStatsArmed()) std.debug.print(" [req] body={d}B tools={d}B system={d}B messages~={d}B\n", .{ body.len, if (tools) |t| t.len else 0, self.sys_normal.len, body.len -| (if (tools) |t| t.len else 0) -| self.sys_normal.len });
const t0: Io.Timestamp = .now(self.io, .awake);
if (main_mod.json_mode and !self.sub) self.emit(.{ .type = "model_call_started", .provider = self.provider.id, .model = self.provider.model });
// HTTP calls are flaky: a kept-alive connection the server closed
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index 187e3dcb..05866c09 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -51,6 +51,7 @@ const execTool = exec.execTool;
const brief_diversity = @import("brief_diversity.zig"); // #382: N sibling spawns in one batch are a fleet
const playbook_glue = @import("playbook_glue.zig"); // #381: the note_constraint meta arm
const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: the load_tool_schemas meta arm
+const native_fold = @import("native_fold.zig"); // folded native power tools: load_tool_schemas's native half
const util = @import("util.zig"); // #225: unixMs, for the clock_sleep interrupted-elapsed measurement
const readline = @import("readline.zig"); // ask_user answers get the same full editor as the main prompt
const protocol_seq = @import("protocol_seq.zig"); // #330: monotonic `seq` on every --json event
@@ -293,6 +294,9 @@ fn clockSleepInterruptedText(arena: std.mem.Allocator, elapsed_ms: i64) ![]const
/// Handle a meta tool inline on the agent's own thread.
pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {
+ // Folded natives, meta path: inline dispatch never reaches exec.zig's
+ // guard chain, so the refusal must live here too — same text, same rule.
+ if (native_fold.blocked(call.name)) return .{ .text = try native_fold.refusalText(self.arena, call.name), .is_error = true };
// #469: sideways coordination between co-resident root sessions.
if (std.mem.eql(u8, call.name, peer_channel.tool_name)) return peer_channel.handleMessage(self, call);
if (std.mem.eql(u8, call.name, "attempt_completion")) {
@@ -355,7 +359,7 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {
return .{ .text = try clockSleepSuccessText(self.arena, parsed.ms, parsed.clamped), .is_error = false };
}
if (std.mem.eql(u8, call.name, "note_constraint")) return playbook_glue.noteConstraint(self, call.input); // #381: append-only, and it re-composes the root's own prompt
- if (std.mem.eql(u8, call.name, mcp_schema_gate.tool_name)) return mcp_schema_gate.handleLoad(self, call.input); // #416: inline, so the loaded-schema set has exactly one writer
+ if (std.mem.eql(u8, call.name, mcp_schema_gate.tool_name)) return (native_fold.handleLoadNative(self, call.input) catch null) orelse mcp_schema_gate.handleLoad(self, call.input); // #416: inline, one writer — folded natives answered first
if (std.mem.eql(u8, call.name, "ask_user")) return self.askUser(call);
// todo_read
return .{ .text = self.renderTodos(goal_state.currentEpoch(self.goal)), .is_error = false };
@@ -517,6 +521,8 @@ test "clockSleepSuccessText/clockSleepInterruptedText: exact result strings (#22
}
test "handleMeta clock_sleep: ms=0 completes for real end-to-end, bad ms rejects without touching Io" {
+ // clock_sleep is a folded native: handleMeta refuses it until loaded. Mark it loaded rather than toggling fold.enabled: `enabled` is shared mutable state the parallel test runner races on (native_fold.zig's own tests flip it), while g_loaded is append-only and safe (the refusal is covered in native_fold.zig).
+ @import("native_fold.zig").markLoaded("clock_sleep");
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
const a = arena_state.allocator();
diff --git a/src/exec.zig b/src/exec.zig
index 6b613859..94a98196 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -71,6 +71,7 @@ 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 vision = @import("vision.zig"); // read_file stages images like MCP image results (#249)
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)
@@ -157,7 +158,7 @@ pub fn execTool(ctx: ToolCtx, call: ToolCall) ToolOutput {
// #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 licensedNativeGate(ctx, call)) |blocked| {
+ if (noLocalToolsGate(ctx, call) orelse codedbGuard(ctx, call) orelse companionRoute(ctx, call) orelse hookGate(ctx, call) orelse licensedNativeGate(ctx, call) orelse native_fold.gateExec(ctx.gpa, call.name)) |blocked| {
var out = blocked;
out.ms = t0.untilNow(ctx.io, .awake).toMilliseconds();
if (ctx.tracer) |tr| {
diff --git a/src/mcp_schema_gate.zig b/src/mcp_schema_gate.zig
index 2d371a73..4625ea14 100644
--- a/src/mcp_schema_gate.zig
+++ b/src/mcp_schema_gate.zig
@@ -79,7 +79,7 @@ pub const env_eager = "GRAFF_MCP_EAGER"; // comma-separated server names; "*" pi
/// entry and no import cycle. The description is spliced into a raw JSON
/// string, so it must stay free of characters needing JSON escapes.
pub const tool_name = "load_tool_schemas";
-pub const tool_desc = "Load the full JSON input schemas for MCP tools and enable them for the rest of this session. MCP servers with large schemas are registered up front by name and a one-line description only, so that thousands of tokens of JSON Schema stay out of every request. A tool whose schema has not been loaded CANNOT be called: calling it returns an error telling you to load it first. Pass tools with exact qualified names (mcp__server__tool), or pass server to load every deferred tool on one server. Call it with no arguments to list what is currently deferred. Loading is permanent for this session and free to repeat, because the schemas are cached.";
+pub const tool_desc = "Load the full JSON input schemas for deferred tools and enable them for the rest of this session. MCP servers with large schemas — and folded native power tools (workflow, imagegen, learn_candidate, eval, clock_sleep) — are registered up front by name and a one-line description only, so that thousands of tokens of JSON Schema stay out of every request. A tool whose schema has not been loaded CANNOT be called: calling it returns an error telling you to load it first. Pass tools with exact names (mcp__server__tool for MCP, or a folded native name like workflow), or pass server to load every deferred tool on one MCP server. Call it with no arguments to list what is currently deferred. Loading is permanent for this session and free to repeat, because the schemas are cached.";
pub const tool_schema =
\\{"type": "object", "properties": {"tools": {"type": "array", "items": {"type": "string"}, "description": "Exact qualified MCP tool names to load, e.g. mcp__deepwiki__ask_question"}, "server": {"type": "string", "description": "Load every deferred tool on this MCP server instead of naming them one by one"}}}
;
diff --git a/src/native_fold.zig b/src/native_fold.zig
new file mode 100644
index 00000000..740c6988
--- /dev/null
+++ b/src/native_fold.zig
@@ -0,0 +1,212 @@
+//! Folded native tools: #416's two-phase exposure applied to the harness's
+//! OWN power tools, not just MCP servers.
+//!
+//! The interactive root catalog measured 42,851 bytes of tool JSON in every
+//! request — 77% of the wire body (GRAFF_REQ_STATS), with native specs alone
+//! at ~26k bytes. opencode's TUI ships one lean surface for both modes; our
+//! REPL paid for workflow/imagegen/learn/eval schemas on EVERY turn whether
+//! or not the session ever called them. The fix is the meta-tool pattern the
+//! user named: these tools register name + one-line description + a
+//! placeholder schema up front, and `load_tool_schemas` (already the MCP
+//! meta arm) returns the real schema and enables them on demand.
+//!
+//! Same two invariants as #416, for the same reasons:
+//! - consent is untouched: the refusal lives in exec.zig's guard chain,
+//! DOWNSTREAM of agent_tool_gate.gateTool, so deferral can only subtract
+//! a call consent already allowed, never add one;
+//! - the enable path needs no catalog re-render: the real schema rides the
+//! load_tool_schemas RESULT, exactly like the MCP half.
+//!
+//! State is an append-only list with exactly one writer — the orchestrator
+//! thread, since load_tool_schemas is handled inline (agent_tools.zig) — and
+//! pool threads only read, always after the spawn that publishes the write.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const mcp_schema_gate = @import("mcp_schema_gate.zig"); // shortDesc + placeholder_schema: one deferral style for both halves
+
+/// GRAFF_NO_NATIVE_FOLD turns the fold off (session_settings) — the full
+/// power-tool schemas return to every request, the pre-fold behavior.
+pub var enabled = true;
+
+/// The folded set: power/meta tools an interactive session reaches for
+/// LATE if at all, whose schemas cost ~9.3k bytes of every request.
+/// Deliberately NOT here: the tools a session needs on turn one (bash, the
+/// file tools, subagent — the unattended delegation path), the interactive
+/// staples (todos, ask_user, peer_message, webfetch, skill), and the meta
+/// arm itself (load_tool_schemas must stay callable to unfold these).
+pub const folded = [_][]const u8{
+ "workflow",
+ "imagegen",
+ "learn_candidate",
+ "eval",
+ "clock_sleep",
+};
+
+/// A name test only, independent of whether the fold is on.
+pub fn isFolded(name: []const u8) bool {
+ for (folded) |tool| {
+ if (std.mem.eql(u8, name, tool)) return true;
+ }
+ return false;
+}
+
+/// Whether the fold is live at all — hiddenSpec consults this so
+/// load_tool_schemas stays advertised while ANY folded tool exists.
+pub fn anyFolded() bool {
+ return enabled;
+}
+
+var g_loaded: [folded.len][]const u8 = undefined;
+var g_loaded_len: usize = 0;
+
+pub fn isLoaded(name: []const u8) bool {
+ for (g_loaded[0..g_loaded_len]) |n| {
+ if (std.mem.eql(u8, n, name)) return true;
+ }
+ return false;
+}
+
+/// The single writer: load_tool_schemas, inline on the orchestrator.
+pub fn markLoaded(name: []const u8) void {
+ if (isLoaded(name) or g_loaded_len >= g_loaded.len) return;
+ g_loaded[g_loaded_len] = name;
+ g_loaded_len += 1;
+}
+
+/// Whether calling `name` right now must be refused (exec.zig layer 2).
+pub fn blocked(name: []const u8) bool {
+ return enabled and isFolded(name) and !isLoaded(name);
+}
+
+/// Whether a native spec should be served description-only (schema.zig
+/// layer 1): folded and not yet loaded.
+pub fn servePlaceholder(name: []const u8) bool {
+ return blocked(name);
+}
+
+/// Same refusal style as mcp_schema_gate.refusalText: name the fix, not just
+/// the block, so the model loads instead of retrying.
+pub fn refusalText(gpa: Allocator, name: []const u8) ![]u8 {
+ return std.fmt.allocPrint(
+ gpa,
+ "{s} is registered but its schema is not loaded, so it cannot be called yet. " ++
+ "Call {s} with {{\"tools\": [\"{s}\"]}} first — that returns the full input schema and enables the tool " ++
+ "for the rest of this session — then call {s} again with arguments matching that schema. " ++
+ "This is a context-cost deferral only; it does not change approvals or trust.",
+ .{ name, mcp_schema_gate.tool_name, name, name },
+ );
+}
+
+/// exec.zig layer 2 as one expression for the guard chain: the refusal when
+/// the call is blocked, else null. `gpa` is the exec context's result
+/// allocator. Deliberately positioned alongside the #416 refusal — both run
+/// downstream of agent_tool_gate.gateTool, so the fold can only subtract a
+/// call consent already allowed, never add one. Yields in plan mode: the
+/// read-only policy is the stronger reason, and its gate must deliver its
+/// own refusal rather than the model hearing "schema not loaded".
+pub fn gateExec(gpa: Allocator, name: []const u8) ?@import("tools.zig").ToolOutput {
+ if (@import("main.zig").plan_mode) return null;
+ if (!blocked(name)) return null;
+ return .{ .text = refusalText(gpa, name) catch return null, .is_error = true };
+}
+
+/// The result half of a native load: the tool's REAL spec schema, rendered
+/// into the load_tool_schemas result exactly like the MCP half's — the
+/// catalog never re-renders. `real_schema` is the spec's raw JSON string.
+pub fn loadResultText(arena: Allocator, name: []const u8, real_schema: []const u8) ![]u8 {
+ markLoaded(name);
+ return std.fmt.allocPrint(
+ arena,
+ "1 tool schema below is now loaded and callable for the rest of this session. Call it with arguments matching input_schema.\n{s}: {s}\n{s}",
+ .{ name, real_schema, name },
+ );
+}
+
+/// The session's effective spec for one native tool, or null — the native
+/// half of load_tool_schemas needs the REAL schema to hand back on load.
+/// Lives here (not schema.zig, at the 600 cap); the mutual import with
+/// schema.zig is lazy and legal.
+pub fn findRootSpec(arena: Allocator, name: []const u8) !?@import("schema.zig").ToolSpec {
+ for (try @import("schema.zig").effectiveRootSpecs(arena)) |spec| {
+ if (std.mem.eql(u8, spec.name, name)) return spec;
+ }
+ return null;
+}
+
+/// The native half of load_tool_schemas, called from agent_tools before the
+/// MCP handler: an input naming folded native tools loads them (real schema
+/// in the result, enabled for the session). Returns null when the input
+/// names NO folded native tool, so MCP-only requests reach the MCP handler
+/// unchanged; a named-but-unknown tool falls to the MCP handler's listing.
+pub fn handleLoadNative(agent: anytype, input: @import("std").json.Value) !?@import("tools.zig").ExecResult {
+ if (!enabled) return null;
+ if (input != .object) return null;
+ const list = input.object.get("tools") orelse return null;
+ if (list != .array) return null;
+ var aw: Io.Writer.Allocating = .init(agent.arena);
+ var fresh: usize = 0;
+ var total: usize = 0;
+ for (list.array.items) |item| {
+ if (item != .string or !isFolded(item.string)) continue;
+ total += 1;
+ if (isLoaded(item.string)) {
+ aw.writer.print("{s}: already loaded.\n", .{item.string}) catch return null;
+ continue;
+ }
+ const spec = (try findRootSpec(agent.arena, item.string)) orelse {
+ aw.writer.print("{s}: folded but not in this session's catalog (disabled or gated).\n", .{item.string}) catch return null;
+ continue;
+ };
+ markLoaded(item.string);
+ fresh += 1;
+ aw.writer.print("{s}: {s}\n", .{ item.string, spec.schema }) catch return null;
+ }
+ if (total == 0) return null;
+ var head: Io.Writer.Allocating = .init(agent.arena);
+ head.writer.print("{d} native tool schema(s) below are now loaded and callable for the rest of this session ({d} newly enabled). Call them with arguments matching input_schema.\n", .{ total, fresh }) catch return null;
+ return .{ .text = try agent.arena.dupe(u8, try std.fmt.allocPrint(agent.arena, "{s}{s}", .{ head.writer.buffered(), aw.writer.buffered() })), .is_error = false };
+}
+
+test "fold: the listed tools are blocked until loaded, everything else flows" {
+ const saved = enabled;
+ defer enabled = saved;
+ enabled = true;
+ // State leak guard: these tests share g_loaded with the process, so use a
+ // name only this test folds... every folded name is shared state, so
+ // assert on the pre-load state only for names no other test loads.
+ try std.testing.expect(isFolded("workflow"));
+ try std.testing.expect(!isFolded("bash"));
+ try std.testing.expect(!isFolded("subagent"));
+ try std.testing.expect(anyFolded());
+ enabled = false;
+ try std.testing.expect(!blocked("workflow"));
+ try std.testing.expect(!anyFolded());
+ enabled = true;
+ if (!isLoaded("clock_sleep")) {
+ try std.testing.expect(blocked("clock_sleep"));
+ try std.testing.expect(servePlaceholder("clock_sleep"));
+ markLoaded("clock_sleep");
+ try std.testing.expect(isLoaded("clock_sleep"));
+ try std.testing.expect(!blocked("clock_sleep"));
+ }
+ // A loaded name never double-registers.
+ const before = g_loaded_len;
+ markLoaded("clock_sleep");
+ try std.testing.expectEqual(before, g_loaded_len);
+}
+
+test "fold refusal text names the load call, not just the block" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const text = try refusalText(a, "workflow");
+ try std.testing.expect(std.mem.indexOf(u8, text, "load_tool_schemas") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "\"workflow\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "does not change approvals") != null);
+ const loaded = try loadResultText(a, "eval", "{\"type\":\"object\"}");
+ try std.testing.expect(std.mem.indexOf(u8, loaded, "{\"type\":\"object\"}") != null);
+ try std.testing.expect(isLoaded("eval"));
+}
diff --git a/src/schema.zig b/src/schema.zig
index cb9247b5..f821cc7a 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -19,6 +19,7 @@ const no_local_tools = @import("no_local_tools.zig"); // #330: the hard --no-loc
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"); // #352: name/desc/schema as plain strings, like skill_docs, so this catalog needs one entry and no import cycle
const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: which MCP tools are served schema-first vs description-only, and the `load_tool_schemas` strings
+const native_fold = @import("native_fold.zig"); // folded native power tools: same two-phase pattern for the harness's own catalog
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;
@@ -40,7 +41,7 @@ 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;
-const ToolSpec = struct {
+pub const ToolSpec = struct {
name: []const u8,
desc: []const u8, // no characters needing JSON escapes
schema: []const u8, // raw JSON Schema string
@@ -298,8 +299,11 @@ pub fn renderRootTools(
var s: std.json.Stringify = .{ .writer = &aw.writer };
try s.beginArray();
for (specs) |t| {
- if (mcp_schema_gate.hiddenSpec(t.name, mcp_tools)) continue; // #416: load_tool_schemas is pointless with nothing deferred
- try writeToolEntry(&s, kind, t.name, t.desc, .{ .raw = t.schema });
+ if (mcp_schema_gate.hiddenSpec(t.name, mcp_tools) and !native_fold.anyFolded()) continue; // #416: load_tool_schemas hides only with nothing deferred OR folded
+ if (native_fold.servePlaceholder(t.name)) // native fold layer 1: name + one-liner + placeholder until load_tool_schemas unfolds
+ try writeToolEntry(&s, kind, t.name, mcp_schema_gate.shortDesc(t.desc), .{ .raw = mcp_schema_gate.placeholder_schema })
+ else
+ try writeToolEntry(&s, kind, t.name, t.desc, .{ .raw = t.schema });
}
// #416 layer 1: a deferred tool is still REGISTERED (name + a one-line
// description, so the model knows it exists and can ask for it), but its
diff --git a/src/session_settings.zig b/src/session_settings.zig
index b06b1d00..3f1d74ee 100644
--- a/src/session_settings.zig
+++ b/src/session_settings.zig
@@ -19,6 +19,8 @@ const agent_mod = @import("agent.zig");
const http = @import("http.zig");
const ws = @import("ws.zig");
const agent_ws = @import("agent_ws.zig"); // codex_ws_idle_ms override (#codex-ws)
+const agent_request = @import("agent_request.zig"); // GRAFF_REQ_STATS → g_req_stats (token-diet measurement)
+const native_fold = @import("native_fold.zig"); // GRAFF_NO_NATIVE_FOLD → enabled
const no_local_tools = @import("no_local_tools.zig"); // #330: GRAFF_NO_LOCAL_TOOLS
const tool_handle = @import("tool_handle.zig"); // #440: GRAFF_TOOL_HANDLE_BYTES
const provider_mod = @import("provider.zig");
@@ -90,6 +92,11 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {
// GRAFF_LEAN: presence-based, exactly matching session_start.leanSkipsMcp
// (the MCP half of the same switch) — a "0" still means lean, by design.
if (environ_map.get("GRAFF_LEAN") != null) no_local_tools.lean = true;
+ // GRAFF_REQ_STATS: presence-based request-anatomy print (agent_request).
+ agent_request.g_req_stats = environ_map.get("GRAFF_REQ_STATS") != null;
+ // GRAFF_NO_NATIVE_FOLD: presence-based — restore full power-tool schemas
+ // in every request (the pre-fold interactive surface).
+ if (environ_map.get("GRAFF_NO_NATIVE_FOLD") != null) native_fold.enabled = false;
// (#codex-ws) GRAFF_CODEX_WS_IDLE_SECS raises/lowers the held-WS idle limit
// (default 4 min — the backend killed ours within 8.5 min idle; opencode
// pools at 5). Mirrors GRAFF_STREAM_STALL_SECS above: seconds, ignored if
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 81461f41..77b2e3f3 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -41,6 +41,9 @@ const subagent_selection = @import("subagent_selection.zig");
// #292 per-persona / per-spawn model pins: the module is reached in
// production (subagent.zig), but its split-out test files are not.
const subagent_pin_tests = @import("subagent_pin_tests.zig");
+// Folded native tools (#416's two-phase pattern for the harness's own power
+// tools): reached in production via schema.zig/exec.zig/agent_tools.zig.
+const native_fold = @import("native_fold.zig");
// Moved off subagent.zig, which is at the 600-line cap.
const subagent_tests = @import("subagent_tests.zig");
// Bench score/cost priors → derived tier ladders (.harness/bench.json).
@@ -203,6 +206,7 @@ test {
_ = router_config;
_ = subagent_selection;
_ = subagent_pin_tests;
+ _ = native_fold;
_ = subagent_tests;
_ = bench_priors;
_ = bench_priors_tests;
diff --git a/src/tool_schema_tests.zig b/src/tool_schema_tests.zig
index 72c73b6a..8f1eef24 100644
--- a/src/tool_schema_tests.zig
+++ b/src/tool_schema_tests.zig
@@ -265,7 +265,18 @@ test "#416: deferring a real MCP server's schemas cuts the served catalog in hal
try testing.expect(std.mem.indexOf(u8, with_specs, gate.tool_name) != null);
gate.g_policy = .{ .eager = &.{"*"} };
const eager_specs = try schema.renderRootTools(arena, .anthropic, &schema.root_specs, tools);
- try testing.expect(std.mem.indexOf(u8, eager_specs, gate.tool_name) == null);
+ // With folded natives the meta arm still earns its slot — folded tools
+ // need it even when every MCP server is eager. With the fold off, the
+ // original "all eager, nothing to undo" rule holds unchanged.
+ const fold = @import("native_fold.zig");
+ const saved_fold = fold.enabled;
+ defer fold.enabled = saved_fold;
+ fold.enabled = true;
+ try testing.expect(std.mem.indexOf(u8, eager_specs, gate.tool_name) != null);
+ fold.enabled = false;
+ const eager_specs_nofold = try schema.renderRootTools(arena, .anthropic, &schema.root_specs, tools);
+ try testing.expect(std.mem.indexOf(u8, eager_specs_nofold, gate.tool_name) == null);
+ fold.enabled = saved_fold;
gate.g_policy = .{};
// Loading one tool restores that tool's schema to the catalog and nothing