graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(fold): defer the deliberate-act natives — subagent, todos, peer, notes
Rach Pradhan2344acf6191a
diff --git a/src/agent_request.zig b/src/agent_request.zigindex 5bc4987a..eae1b2e4 100644--- a/src/agent_request.zig+++ b/src/agent_request.zig@@ -222,6 +222,30 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {pos = name_end;}std.debug.print(" [req] tools split: native={d}B codedbpro={d}B other_mcp={d}B\n", .{ native, cdbp, other_mcp });+ // Top-5 largest native specs — the deferral candidates list.+ var sizes: [64]struct { span: usize, at: usize } = undefined;+ var n_sizes: usize = 0;+ pos = 0;+ while (std.mem.indexOfPos(u8, t, pos, "\"name\":\"")) |n2| {+ const ns = n2 + 8;+ const ne = std.mem.indexOfScalarPos(u8, t, ns, '"') orelse break;+ const nxt = std.mem.indexOfPos(u8, t, ne, "\"name\":\"") orelse t.len;+ if (!std.mem.startsWith(u8, t[ns..ne], "mcp__") and n_sizes < sizes.len) {+ sizes[n_sizes] = .{ .span = nxt - n2, .at = ns };+ n_sizes += 1;+ }+ pos = ne;+ }+ var top: usize = 0;+ while (top < 5 and top < n_sizes) : (top += 1) {+ var bi: usize = 0;+ for (sizes[0..n_sizes], 0..) |sz, j| if (sz.span > sizes[bi].span) {+ bi = j;+ };+ const nm = t[sizes[bi].at .. std.mem.indexOfScalarPos(u8, t, sizes[bi].at, '"') orelse sizes[bi].at];+ std.debug.print(" [req] {s}: {d}B\n", .{ nm, sizes[bi].span });+ sizes[bi].span = 0;+ }}}const t0: Io.Timestamp = .now(self.io, .awake);diff --git a/src/agent_tools.zig b/src/agent_tools.zigindex 05866c09..e738f0ad 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -296,7 +296,7 @@ fn clockSleepInterruptedText(arena: std.mem.Allocator, elapsed_ms: i64) ![]constpub 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 };+ if (!self.sub and 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")) {diff --git a/src/exec.zig b/src/exec.zigindex 94a98196..b945ae25 100644--- a/src/exec.zig+++ b/src/exec.zig@@ -158,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) orelse native_fold.gateExec(ctx.gpa, call.name)) |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, ctx.from_sub)) |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.zigindex 4f3bc757..41f00bbc 100644--- a/src/mcp_schema_gate.zig+++ b/src/mcp_schema_gate.zig@@ -83,7 +83,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 deferred tools and enable them for the rest of this session. Deferred MCP tools — and folded native power tools (workflow, imagegen, learn_candidate, eval, clock_sleep) — ship no schemas up front, so that thousands of tokens of JSON Schema stay out of every request; any deferred servers and their tool names are listed at the end of this description. 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), pass server to load every deferred tool on one MCP server, or pass query with keywords to search deferred tools by name and description (the top 8 matches load). 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. Deferred MCP tools — and folded native tools (workflow, imagegen, learn_candidate, eval, clock_sleep, subagent, todo_write, todo_read, peer_message, note_constraint, agent_output, skill, webfetch) — ship no schemas up front, so that thousands of tokens of JSON Schema stay out of every request; any deferred servers and their tool names are listed at the end of this description. 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), pass server to load every deferred tool on one MCP server, or pass query with keywords to search deferred tools by name and description. 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"}, "query": {"type": "string", "description": "Search deferred tools by keyword (matches name and description, loads the top 8 matches) — use when you know what you need but not the exact tool name"}}};@@ -393,7 +393,7 @@ fn shortName(qualified: []const u8) []const u8 {/// Case-insensitive substring search (std.ascii has no indexOfIgnoreCase in/// this toolchain): windowed eqlIgnoreCase, fine at description sizes.-fn containsIgnoreCase(haystack: []const u8, needle: []const u8) bool {+pub fn containsIgnoreCase(haystack: []const u8, needle: []const u8) bool {if (needle.len > haystack.len) return false;var i: usize = 0;while (i + needle.len <= haystack.len) : (i += 1)diff --git a/src/native_fold.zig b/src/native_fold.zigindex 740c6988..b76a3028 100644--- a/src/native_fold.zig+++ b/src/native_fold.zig@@ -31,18 +31,29 @@ const mcp_schema_gate = @import("mcp_schema_gate.zig"); // shortDesc + placehold/// 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).+/// The folded set: tools an interactive session reaches for LATE if at all,+/// plus the deliberate-act tools whose first use tolerates one load call —+/// measured (GRAFF_REQ_STATS top-5) at ~9.5k bytes of every request, with+/// subagent alone at 5,052 (26% of the tools surface).+/// Deliberately NOT here: the every-turn loop (bash, the file tools, codedb),+/// loop control (ask_user, attempt_completion), and the meta arm itself+/// (load_tool_schemas must stay callable to unfold these). Subagents are+/// exempt at the call gates: their catalogs are comptime-baked full surfaces,+/// so refusing them would be incoherent.pub const folded = [_][]const u8{"workflow","imagegen","learn_candidate","eval","clock_sleep",+ "subagent",+ "todo_write",+ "todo_read",+ "peer_message",+ "note_constraint",+ "agent_output",+ "skill",+ "webfetch",};/// A name test only, independent of whether the fold is on.@@ -76,17 +87,12 @@ pub fn markLoaded(name: []const u8) void {g_loaded_len += 1;}-/// Whether calling `name` right now must be refused (exec.zig layer 2).+/// Whether calling `name` right now must be refused (exec.zig layer 2);+/// schema.zig layer 1 skips the spec entirely while this holds (zero stubs).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 {@@ -107,7 +113,8 @@ pub fn refusalText(gpa: Allocator, name: []const u8) ![]u8 {/// 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 {+pub fn gateExec(gpa: Allocator, name: []const u8, from_sub: bool) ?@import("tools.zig").ToolOutput {+ if (from_sub) return null; // subs are served comptime-baked full catalogs — refusing them would be incoherentif (@import("main.zig").plan_mode) return null;if (!blocked(name)) return null;return .{ .text = refusalText(gpa, name) catch return null, .is_error = true };@@ -144,6 +151,30 @@ pub fn findRootSpec(arena: Allocator, name: []const u8) !?@import("schema.zig").pub fn handleLoadNative(agent: anytype, input: @import("std").json.Value) !?@import("tools.zig").ExecResult {if (!enabled) return null;if (input != .object) return null;+ // query arm: token-match over the folded set's names + descriptions, so+ // keyword discovery covers both deferred halves, not just MCP.+ if (input.object.get("query")) |q| {+ if (q != .string) return null;+ var aw: Io.Writer.Allocating = .init(agent.arena);+ var matched: usize = 0;+ for (folded) |name| {+ if (isLoaded(name)) continue;+ const spec = (try findRootSpec(agent.arena, name)) orelse continue;+ var tok = std.mem.tokenizeAny(u8, q.string, " \t,;:/_-");+ var hits: usize = 0;+ while (tok.next()) |w| {+ if (w.len < 2) continue;+ if (mcp_schema_gate.containsIgnoreCase(name, w) or mcp_schema_gate.containsIgnoreCase(spec.desc, w)) hits += 1;+ }+ if (hits == 0) continue;+ markLoaded(name);+ matched += 1;+ aw.writer.print("{s}: {s}\n", .{ name, spec.schema }) catch return null;+ }+ if (matched == 0) return null; // no native match: the MCP half answers the query+ const head = try std.fmt.allocPrint(agent.arena, "{d} native tool schema(s) below are now loaded and callable for the rest of this session. Call them with arguments matching input_schema.\n", .{matched});+ return .{ .text = try std.fmt.allocPrint(agent.arena, "{s}{s}", .{ head, aw.writer.buffered() }), .is_error = false };+ }const list = input.object.get("tools") orelse return null;if (list != .array) return null;var aw: Io.Writer.Allocating = .init(agent.arena);@@ -178,8 +209,8 @@ test "fold: the listed tools are blocked until loaded, everything else flows" {// 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("subagent")); // the 5 KB schema — biggest single fold wintry std.testing.expect(!isFolded("bash"));- try std.testing.expect(!isFolded("subagent"));try std.testing.expect(anyFolded());enabled = false;try std.testing.expect(!blocked("workflow"));@@ -187,11 +218,12 @@ test "fold: the listed tools are blocked until loaded, everything else flows" {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"));}+ // Subagents are exempt: their catalogs are comptime-baked full surfaces.+ try std.testing.expect(gateExec(std.testing.allocator, "workflow", true) == null);// A loaded name never double-registers.const before = g_loaded_len;markLoaded("clock_sleep");diff --git a/src/schema.zig b/src/schema.zigindex b84775f8..5f0f5b5f 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -300,9 +300,8 @@ pub fn renderRootTools(try s.beginArray();for (specs) |t| {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 if (std.mem.eql(u8, t.name, mcp_schema_gate.tool_name))+ if (native_fold.blocked(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 })elsetry writeToolEntry(&s, kind, t.name, t.desc, .{ .raw = t.schema });