Skip to content

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

Python

Gate rlm host calls and match shell hooks under both names

Rach Pradhan7b8c09c9b0b5
diff --git a/src/adopt.zig b/src/adopt.zig
index 801eb782..82503e95 100644
--- a/src/adopt.zig
+++ b/src/adopt.zig
@@ -277,7 +277,7 @@ fn mapMatcher(arena: Allocator, m: []const u8) []const u8 {
var first = true;
while (it.next()) |raw| {
const p = std.mem.trim(u8, raw, " ");
- const mapped: []const u8 = if (std.mem.eql(u8, p, "Bash")) "bash" else if (std.mem.eql(u8, p, "Read")) "read_file" else if (std.mem.eql(u8, p, "Edit")) "edit_file" else if (std.mem.eql(u8, p, "Write")) "write_file" else p;
+ const mapped: []const u8 = if (std.mem.eql(u8, p, "Bash")) "shell" else if (std.mem.eql(u8, p, "Read")) "read_file" else if (std.mem.eql(u8, p, "Edit")) "edit_file" else if (std.mem.eql(u8, p, "Write")) "write_file" else p;
if (!first) out.append('|') catch {};
first = false;
out.appendSlice(mapped) catch {};
@@ -416,6 +416,12 @@ test "adopt writes missing Claude MCP into graff folders and skips existing name
try testing.expect(again.skipped >= 2);
}
+test "adopted Claude Bash hooks match the advertised shell tool (#1292)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ try std.testing.expectEqualStrings("shell|edit_file", mapMatcher(arena_state.allocator(), "Bash|Edit"));
+}
+
test "first-run adopt writes a marker and does not run again" {
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
diff --git a/src/agent_tool_batch.zig b/src/agent_tool_batch.zig
index 2bf637e5..ebae9f2a 100644
--- a/src/agent_tool_batch.zig
+++ b/src/agent_tool_batch.zig
@@ -42,9 +42,7 @@ test "optional effort selections serialize in model call order" {
try std.testing.expect(!isSequential("shell"));
}
-fn isShellName(name: []const u8) bool {
- return std.mem.eql(u8, name, "shell") or std.mem.eql(u8, name, "bash");
-}
+const isShellName = @import("shell_tool.zig").runsCommand;
/// Preserve the async scheduling policy introduced for #1166. This is not
/// thread affinity: Threaded Io may run async work on its pool too. Safety
@@ -86,6 +84,7 @@ pub fn context(self: *Agent) ToolCtx {
.run_budget = self.run_budget,
.publication_checks = self.publication_checks,
.publication_observer = .{ .context = self, .state = &self.publication_checks, .record = @import("pr_local_checks.zig").observeOutput },
+ .host_gate = .{ .context = self, .check = @import("agent_tool_gate.zig").hostGate },
.depth = self.depth,
.snapshots = self.snapshots,
.tools_used = &self.tools_used,
diff --git a/src/agent_tool_gate.zig b/src/agent_tool_gate.zig
index e8a08502..15bb175a 100644
--- a/src/agent_tool_gate.zig
+++ b/src/agent_tool_gate.zig
@@ -354,6 +354,18 @@ pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {
};
}
+/// ToolCtx.host_gate: a call an rlm script makes (bash, write_file, MCP…)
+/// gets the same gate as the catalog call would (#1292). It runs on a pool
+/// thread, so it holds the lock that already guards this agent's arena there.
+pub fn hostGate(context: *anyopaque, call: ToolCall) ?tools_mod.ToolOutput {
+ const self: *Agent = @ptrCast(@alignCast(context));
+ self.publication_checks.observation_mutex.lockUncancelable(self.io);
+ defer self.publication_checks.observation_mutex.unlock(self.io);
+ const denied = (gateTool(self, call) catch
+ return .{ .text = self.gpa.dupe(u8, "tool gate failed; the call was not run") catch &.{}, .is_error = true }) orelse return null;
+ return .{ .text = self.gpa.dupe(u8, denied.text) catch &.{}, .is_error = true, .cancelled = denied.cancelled };
+}
+
pub fn firstWord(cmd: []const u8) []const u8 {
const end = std.mem.indexOfAny(u8, cmd, " \t") orelse cmd.len;
return cmd[0..end];
diff --git a/src/commands_session.zig b/src/commands_session.zig
index 0f5c7be3..8132c6fa 100644
--- a/src/commands_session.zig
+++ b/src/commands_session.zig
@@ -392,7 +392,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
if (std.mem.eql(u8, line, "/hooks")) {
try out.print("{s}codedb guard{s} (built-in, issue #626): {s} — blocks bash grep/sed/cat/wc on indexed source files and redirects to the codedb tool; GRAFF_NO_CODEDB_GUARD=1 disables.\n", .{ style.bold, style.reset, if (main_mod.g_codedb_guard) "on" else "off" });
if (main_mod.g_hooks.total() == 0) {
- try out.print("no lifecycle hooks. Add them to {s}:\n {s}{{\"hooks\": {{\"pre_tool\": [{{\"match\": \"bash\", \"command\": \"./guard.sh\"}}]}}}}{s}\n events: pre_tool (exit 2 blocks, stderr → model) · post_tool · turn_end; loaded at startup\n", .{ Approvals.settings_path, style.dim, style.reset });
+ try out.print("no lifecycle hooks. Add them to {s}:\n {s}{{\"hooks\": {{\"pre_tool\": [{{\"match\": \"shell\", \"command\": \"./guard.sh\"}}]}}}}{s}\n events: pre_tool (exit 2 blocks, stderr → model) · post_tool · turn_end; loaded at startup\n", .{ Approvals.settings_path, style.dim, style.reset });
try out.flush();
return true;
}
diff --git a/src/exec.zig b/src/exec.zig
index 6105a630..82db1d54 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -358,7 +358,11 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
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)) return @import("rlm.zig").exec(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 id = intField(input, "id") orelse return missingArg(gpa, "id");
diff --git a/src/hooks.zig b/src/hooks.zig
index fde91a2d..ff54e7b0 100644
--- a/src/hooks.zig
+++ b/src/hooks.zig
@@ -18,6 +18,7 @@ const Allocator = std.mem.Allocator;
const root = @import("main.zig");
const harness_policy = @import("harness_policy.zig");
const win = @import("win_api.zig");
+const shell_tool = @import("shell_tool.zig");
/// Lifecycle hooks (codex/Claude-style), loaded once at startup from
/// .harness/settings.json's "hooks" object. Three events:
@@ -32,8 +33,9 @@ const win = @import("win_api.zig");
///
/// Shape: {"hooks": {"pre_tool": [{"match": "bash|edit_file",
/// "command": "./guard.sh", "timeout_ms": 10000}], ...}}. `match` is "*"
-/// (default) or pipe-separated tool names. A hung hook is killed at its
-/// timeout and treated as allow — hooks must never brick the loop.
+/// (default) or pipe-separated tool names; `shell` and its legacy names
+/// (`bash`, `bash_output`, `bash_kill`) match each other. A hung hook is
+/// killed at its timeout and treated as allow — hooks must never brick the loop.
pub const Hook = struct {
match: []const u8,
command: []const u8,
@@ -47,12 +49,23 @@ pub const Hook = struct {
if (std.mem.eql(u8, self.match, "*")) return true;
var it = std.mem.splitScalar(u8, self.match, '|');
while (it.next()) |m| {
- if (std.mem.eql(u8, std.mem.trim(u8, m, " "), tool)) return true;
+ if (sameTool(std.mem.trim(u8, m, " "), tool)) return true;
}
return false;
}
};
+/// #1292: the catalog calls the shell tool `shell`; hooks written for `bash`
+/// (the /hooks example, adopted Claude settings) must still fire, and a
+/// `shell` hook must see a legacy-named call. `shell` covers run, output and
+/// kill, so it pairs with every family name; the aliases don't pair with
+/// each other (`bash` is not `bash_output`).
+fn sameTool(m: []const u8, tool: []const u8) bool {
+ if (std.mem.eql(u8, m, tool)) return true;
+ return (std.mem.eql(u8, m, shell_tool.tool_name) and shell_tool.isFamily(tool)) or
+ (std.mem.eql(u8, tool, shell_tool.tool_name) and shell_tool.isFamily(m));
+}
+
pub const Hooks = struct {
pre_tool: []const Hook = &.{},
post_tool: []const Hook = &.{},
@@ -194,6 +207,26 @@ test "Hook.matches: wildcard, pipe lists, exact" {
try std.testing.expect(!multi.matches("bas")); // no prefix matching
}
+test "Hook.matches: shell and its legacy names match each other (#1292)" {
+ const bash = Hook{ .match = "bash", .command = "", .timeout_ms = 0 };
+ try std.testing.expect(bash.matches("shell"));
+ try std.testing.expect(bash.matches("bash"));
+ try std.testing.expect(!bash.matches("bash_output")); // aliases stay distinct
+ const shell = Hook{ .match = "edit_file|shell", .command = "", .timeout_ms = 0 };
+ try std.testing.expect(shell.matches("bash"));
+ try std.testing.expect(shell.matches("bash_output"));
+ try std.testing.expect(shell.matches("bash_kill"));
+ try std.testing.expect(shell.matches("edit_file"));
+ const output = Hook{ .match = "bash_output", .command = "", .timeout_ms = 0 };
+ try std.testing.expect(output.matches("shell")); // shell may be action=output
+ try std.testing.expect(!output.matches("bash"));
+ try std.testing.expect(!bash.matches("read_file"));
+ try std.testing.expect(!shell.matches("shel")); // no prefix matching
+ try std.testing.expect(!shell.matches("shell_x"));
+ const read = Hook{ .match = "read_file", .command = "", .timeout_ms = 0 };
+ try std.testing.expect(!read.matches("shell"));
+}
+
test "parseHookList: defaults, malformed entries skipped" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
diff --git a/src/rlm.zig b/src/rlm.zig
index 7fd60bb9..fba635c5 100644
--- a/src/rlm.zig
+++ b/src/rlm.zig
@@ -28,7 +28,7 @@ pub const tool_name = "rlm";
pub const tool_desc = "Programmatic tool calling (RLM + sPTC). Functions ARE this session's tools. Leading read_file/codedb/sleep_ms/llm_query calls overlap as it streams; other calls run in order, stopping on error/cancel/pending. Binds persist. subagent(\"task\") is sidecar-only (keep the critical-path next step local). Loaded MCP names are host functions after load_tool_schemas; tools.server.tool(...) is that name; each(arr, tool, field) maps a JSON array; len(x)/project(x, field) slim it. print() is the answer. Prefer one rlm over N tool calls.";
/// --lean catalog desc: same contract, no REPL essay. maybeAppend is after
/// compactLeanSpecs, so this is the one-shot wire text.
-pub const lean_tool_desc = "Batch independent read_file/codedb here. print(read_file(\"p\")) returns the file — do not catalog-read it again. Then edit_file/write_file/bash as catalog tools. Leading reads overlap; other calls run in order, stopping on error/cancel/pending. Binds persist. Loaded MCP names are host functions after load_tool_schemas.";
+pub const lean_tool_desc = "Batch independent read_file/codedb here. print(read_file(\"p\")) returns the file — do not catalog-read it again. Then edit_file/write_file/shell as catalog tools. Leading reads overlap; other calls run in order, stopping on error/cancel/pending. Binds persist. Loaded MCP names are host functions after load_tool_schemas.";
pub const tool_schema =
\\{"type": "object", "properties": {"code": {"type": "string", "description": "Python-like script: name = read_file(\"path\") / codedb(\"command\") / bash(\"cmd\") / sleep_ms(ms) / llm_query(\"prompt\") / subagent(\"task\") / loaded mcp__server__tool() or tools.server.tool(); each(arr, tool, field) maps a JSON array; len(x) and project(x, field) slim it; print(...) is the result. Assignments persist across rlm calls."}}, "required": ["code"]}
;
@@ -248,7 +248,11 @@ fn runHostRaw(ctx: ToolCtx, call: spec_ptc.Call) ToolOutput {
return .{ .text = ctx.gpa.dupe(u8, "rlm: bad args") catch &.{}, .is_error = true };
};
defer parsed.deinit();
- return exec_mod.execTool(ctx, .{ .id = "rlm", .name = ready.name, .input = parsed.value });
+ // #1292: the agent's approval gate, not just the executor's backstops.
+ // A denial is an error result, so the script stops here.
+ const host_call: tools.ToolCall = .{ .id = if (ctx.host_gate) |gate| gate.call_id else "rlm", .name = ready.name, .input = parsed.value };
+ if (ctx.host_gate) |gate| if (gate.check(gate.context, host_call)) |denied| return denied;
+ return exec_mod.execTool(ctx, host_call);
}
fn runSleep(ctx: ToolCtx, args_json: []const u8) ToolOutput {
diff --git a/src/rlm_order_tests.zig b/src/rlm_order_tests.zig
index e95568b0..69ab2557 100644
--- a/src/rlm_order_tests.zig
+++ b/src/rlm_order_tests.zig
@@ -243,3 +243,88 @@ test "rlm print keeps literals known and missing binds and supported reducers" {
try std.testing.expect(!out.is_error);
try std.testing.expectEqualStrings("literal [data]\nquoted\n2\n[1,2]\n2\n[1,2]\nmissing_bind", out.text);
}
+
+const Gate = struct {
+ seen: usize = 0,
+ call_id: []const u8 = "",
+ fn check(context: *anyopaque, call: tools.ToolCall) ?tools.ToolOutput {
+ const self: *Gate = @ptrCast(@alignCast(context));
+ self.seen += 1;
+ self.call_id = call.id;
+ if (!@import("shell_tool.zig").runsCommand(call.name)) return null;
+ return .{ .text = gpa.dupe(u8, "gate denied") catch &.{}, .is_error = true };
+ }
+};
+
+test "rlm host calls pass the agent gate and a denial stops the script (#1292)" {
+ var f = try Fixture.init();
+ defer f.deinit();
+ var gate: Gate = .{};
+ var ctx = f.ctx();
+ ctx.host_gate = .{ .context = &gate, .call_id = "call-rlm", .check = Gate.check };
+ const out = try rlm.runScript(ctx, "r = read_file(\"target.txt\")\nv = bash(\"printf ran > marker\")\nw = write_file(path=\"after\", content=\"x\")\nprint(v)");
+ defer gpa.free(out.text);
+ try std.testing.expect(out.is_error);
+ try std.testing.expectEqualStrings("gate denied", out.text);
+ try std.testing.expectEqual(@as(usize, 2), gate.seen); // read_file, then the denied bash
+ try std.testing.expectEqualStrings("call-rlm", gate.call_id);
+ try std.testing.expectError(error.FileNotFound, f.tmp.dir.openFile(io, "marker", .{}));
+ try std.testing.expectError(error.FileNotFound, f.tmp.dir.openFile(io, "after", .{}));
+}
+
+const Agent = @import("agent.zig").Agent;
+const Approvals = @import("approvals.zig").Approvals;
+const permission = @import("engine_permission.zig");
+
+const Deny = struct {
+ calls: usize = 0,
+ fn ask(ptr: *anyopaque, _: std.Io, req: permission.Request) permission.Decision {
+ const self: *@This() = @ptrCast(@alignCast(ptr));
+ self.calls += 1;
+ std.debug.assert(std.mem.eql(u8, req.call_id, "call-rlm"));
+ return .deny;
+ }
+};
+
+fn rlmCall(arena: std.mem.Allocator, code: []const u8) !tools.ToolCall {
+ var args: std.json.ObjectMap = .empty;
+ try args.put(arena, "code", .{ .string = code });
+ return .{ .id = "call-rlm", .name = rlm.tool_name, .input = .{ .object = args } };
+}
+
+test "rlm bash and write_file at the root ask the permission handler like catalog calls (#1292)" {
+ var f = try Fixture.init();
+ defer f.deinit();
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ for ([_][]const u8{
+ "print(bash(\"printf ran > marker\"))",
+ "w = write_file(path=\"marker\", content=\"ran\")\nprint(w)",
+ }) |code| {
+ var deny: Deny = .{};
+ var approvals: Approvals = .{};
+ var agent: Agent = .{ .gpa = gpa, .arena = arena.allocator(), .io = io, .client = &f.client, .provider = .{ .id = "fixture", .kind = .openai, .auth = .bearer, .url = "", .api_key = "", .model = "fixture", .context = 1000 }, .messages = .init(arena.allocator()), .sub = false, .label = "root", .out = null, .approvals = &approvals, .permission = .{ .ctx = &deny, .request = Deny.ask }, .agent_cwd = f.cwd };
+ defer agent.tools_used.deinit(gpa);
+ const results = try agent.runTools(&.{try rlmCall(arena.allocator(), code)});
+ try std.testing.expectEqual(@as(usize, 1), deny.calls);
+ try std.testing.expect(results[0].is_error);
+ try std.testing.expect(std.mem.indexOf(u8, results[0].text, "declined") != null);
+ try std.testing.expectError(error.FileNotFound, f.tmp.dir.openFile(io, "marker", .{}));
+ }
+}
+
+test "rlm destructive git in a yolo subagent hits the subagent block (#1292)" {
+ var f = try Fixture.init();
+ defer f.deinit();
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ var approvals: Approvals = .{ .yolo = true };
+ var agent: Agent = .{ .gpa = gpa, .arena = arena.allocator(), .io = io, .client = &f.client, .provider = .{ .id = "fixture", .kind = .openai, .auth = .bearer, .url = "", .api_key = "", .model = "fixture", .context = 1000 }, .messages = .init(arena.allocator()), .sub = true, .label = "sub", .out = null, .approvals = &approvals, .agent_cwd = f.cwd };
+ defer agent.tools_used.deinit(gpa);
+ // A missing branch: harmless even if the gate ever regresses.
+ const code = "v = bash(\"git branch -D graff-1294-no-such-branch\")\nw = write_file(path=\"marker\", content=\"ran\")\nprint(v)";
+ const results = try agent.runTools(&.{try rlmCall(arena.allocator(), code)});
+ try std.testing.expect(results[0].is_error);
+ try std.testing.expect(std.mem.indexOf(u8, results[0].text, "destructive git is blocked for subagents") != null);
+ try std.testing.expectError(error.FileNotFound, f.tmp.dir.openFile(io, "marker", .{}));
+}
diff --git a/src/tools.zig b/src/tools.zig
index dd46c1c0..fd48ed40 100644
--- a/src/tools.zig
+++ b/src/tools.zig
@@ -94,6 +94,14 @@ pub const beforeFromRead = snapshots_mod.beforeFromRead;
pub const Snapshots = snapshots_mod.Snapshots;
pub const Rewound = snapshots_mod.Rewound;
+/// The owning agent's tool gate, for calls a tool makes on its own (rlm host
+/// functions). `check` returns a gpa-owned denial, or null to run the call.
+pub const HostGate = struct {
+ context: *anyopaque,
+ call_id: []const u8 = "rlm",
+ check: *const fn (*anyopaque, ToolCall) ?ToolOutput,
+};
+
/// Everything a tool executor may touch from a pool thread. All fields are
/// thread-safe (gpa, io, shared http client, mutex-guarded registry and
/// approvals) or read-only.
@@ -122,6 +130,7 @@ pub const ToolCtx = struct {
run_budget: ?*run_budget_mod.RunBudget = null,
publication_checks: @import("pr_local_checks.zig").State = .{},
publication_observer: ?@import("pr_local_checks.zig").Observer = null,
+ host_gate: ?HostGate = null, // #1292: rlm host calls pass the same gate as catalog calls
depth: u8 = 0,
snapshots: ?*Snapshots = null,
tools_used: ?*ToolSink = null, // the calling agent's tool log (trajectory/process mining)