Skip to content

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

Python

A read-only child computes under macOS seatbelt (ADR 0232)

justrach9427a7868f99
diff --git a/docs/adr/0232-sub-agents-at-parity-with-the-codex-route.md b/docs/adr/0232-sub-agents-at-parity-with-the-codex-route.md
index c0aae39b..84ee9c59 100644
--- a/docs/adr/0232-sub-agents-at-parity-with-the-codex-route.md
+++ b/docs/adr/0232-sub-agents-at-parity-with-the-codex-route.md
@@ -23,6 +23,10 @@ five, and the transcripts showed why:
and spent several calls keeping a list no one watched.
- **A wait per child.** `agent_output` took one id, so collecting three
children cost three model calls.
+- **A read-only child that could not compute.** A brief that said "read-only"
+ made the child informational (#1360), and its shell then took only an
+ allowlist of simple commands: no python, awk, gzip or pipes. Four census
+ children reported partial counts, and the parent redid their work.
- **Copying a script's output.** The prompt said to use `write_file` for new
files, so a script that computed a report printed it, and the model typed it
back into `write_file` in another call.
@@ -50,6 +54,13 @@ the brief alone, at the worker default effort, so an effort set with
- A child without a spawn or persona effort pin runs at its parent's live
effort, when the child's model accepts that level. On the codex route an
unset effort already means the catalog default (ADR 0226).
+- On macOS a read-only child's foreground shell runs under seatbelt
+ (`/usr/bin/sandbox-exec`): any command may run and read, writes inside the
+ project and all network access are refused, and the gate admits the
+ command because the sandbox enforces it. A background command, or any
+ command where there is no sandbox, still has to clear the allowlist. If
+ the sandbox cannot be set up, a command outside the allowlist is refused,
+ never run unsandboxed.
- Each finished child writes one `subagent` trace line with its duration,
tool calls, context, cached tokens and effort.
- The prompt says a script that computes a file's content writes that file
@@ -71,6 +82,11 @@ also be tempted past its own task; its prompt and the context header both
say to do only its part. A `-p` run that would have kept a checklist no
longer does unless a goal asks for one.
+A read-only child on macOS can now run anything that does not write to the
+project or the network, so a long computation or a large read is its own
+cost, not a refusal. Writes outside the project, to temporary paths, are
+allowed.
+
Revisit the 8 KiB context cap if long sessions crowd a child's first
request, and the effort inheritance if children of high-effort sessions cost
more than the work they save.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index ce132db3..8b269ba8 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -258,7 +258,7 @@ record only when you need the evidence or the edge cases.
| [0229](0229-every-chatgpt-login-is-chatgpt-new.md) | The Codex client's login no longer works, so every ChatGPT login name (`chatgpt`, `codex`, `openai`, `gpt`, `oai`) and the model picker run the `chatgpt-new` sign-in, and `chatgpt-new` precedes `codex` in the provider table. The `codex` provider stays for an existing Codex CLI `auth.json`. Replaces ADR 0221's "Codex first". |
| [0230](0230-mcp-connects-in-the-background.md) | Every session but `--json` connects MCP servers in the background (interactive after consent, `--yolo`, `-p`, ACP); no request waits for a handshake, finished starts join the next request, and the root request says which server connected or did not. ACP `session/new` waits at most 250 ms; `/mcp` lists without waiting. |
| [0231](0231-no-round-trip-the-model-does-not-need.md) | No call the task did not ask for: a named small MCP server (and subagents, when asked for) loads with the first request, with the slim-shape note; `write_file` refuses to replace an unread file unless `replace: true` and reports created/replaced and JSON validity; inherited child MCP tools are never deferred; a piped bracketed paste is one prompt; unwatched (`-p`, piped) sessions get no `ask_user` and no low-effort reasoning summaries. |
-| [0232](0232-sub-agents-at-parity-with-the-codex-route.md) | Sub-agents measured (`subagents` suite and its `subagents-solo` counterfactual, `subagent_split.py`) and brought to parity: `write_file` creates a new file's directory; unwatched sessions get no `todo_write` nudges; `agent_output` takes `ids` and spawn receipts name the running children; a fresh child starts with the user's prompts and its parent's live effort (`/effort` or Jev) unless pinned; one `subagent` trace line per child; a script that computes a file writes it. |
+| [0232](0232-sub-agents-at-parity-with-the-codex-route.md) | Sub-agents measured (`subagents` suite and its `subagents-solo` counterfactual, `subagent_split.py`) and brought to parity: `write_file` creates a new file's directory; unwatched sessions get no `todo_write` nudges; `agent_output` takes `ids` and spawn receipts name the running children; a fresh child starts with the user's prompts and its parent's live effort (`/effort` or Jev) unless pinned; a read-only child's shell runs under macOS seatbelt instead of an allowlist; one `subagent` trace line per child; a script that computes a file writes it. |
## When to write one
diff --git a/src/agent_tool_batch.zig b/src/agent_tool_batch.zig
index 2b12f2b6..c567b99b 100644
--- a/src/agent_tool_batch.zig
+++ b/src/agent_tool_batch.zig
@@ -94,6 +94,7 @@ pub fn context(self: *Agent) ToolCtx {
.read_miss = &self.read_miss,
.parent_effort = self.reasoning,
.parent_messages = self.messages.items,
+ .read_only_shell = self.read_only,
};
}
diff --git a/src/agent_tool_gate.zig b/src/agent_tool_gate.zig
index f919a99b..a5910aa2 100644
--- a/src/agent_tool_gate.zig
+++ b/src/agent_tool_gate.zig
@@ -163,7 +163,7 @@ fn readOnlyChildAllows(registry: ?*mcp.Registry, call: ToolCall) bool {
const cmd_val = args.get("command") orelse return true; // action=output / kill
if (cmd_val != .string) return true;
const cmd = std.mem.trim(u8, cmd_val.string, " \t");
- return Approvals.readOnlyAllowed(cmd) or Approvals.readOnlyExternal(cmd);
+ return Approvals.readOnlyAllowed(cmd) or Approvals.readOnlyExternal(cmd) or @import("readonly_sandbox.zig").admits(call.input); // ADR 0232
}
test "a read-only child keeps reads and read-only shell, not writes (#1360)" {
@@ -181,7 +181,10 @@ test "a read-only child keeps reads and read-only shell, not writes (#1360)" {
try std.testing.expect(readOnlyChildAllows(null, call(a, "bash", "{\"action\":\"output\",\"id\":3}")));
try std.testing.expect(!readOnlyChildAllows(null, call(a, "write_file", "{\"path\":\"a\",\"content\":\"b\"}")));
try std.testing.expect(!readOnlyChildAllows(null, call(a, "edit_file", "{}")));
- try std.testing.expect(!readOnlyChildAllows(null, call(a, "bash", "{\"command\":\"rm -rf build\"}")));
+ // ADR 0232: on macOS a foreground command runs under the sandbox, which refuses the
+ // write; in the background, or with no sandbox, only the allowlist runs.
+ try std.testing.expectEqual(@import("readonly_sandbox.zig").available, readOnlyChildAllows(null, call(a, "bash", "{\"command\":\"rm -rf build\"}")));
+ try std.testing.expect(!readOnlyChildAllows(null, call(a, "bash", "{\"command\":\"rm -rf build\",\"run_in_background\":true}")));
// ADR 0228: an MCP tool is a read when its server declares it read-only.
var registry = mcp.Registry.empty(std.testing.allocator, std.testing.io);
defer registry.deinit();
diff --git a/src/exec_bash.zig b/src/exec_bash.zig
index e8197fab..ce75bccd 100644
--- a/src/exec_bash.zig
+++ b/src/exec_bash.zig
@@ -422,11 +422,16 @@ fn execUnchecked(ctx: ToolCtx, call: tools.ToolCall) !ToolOutput {
};
}
const sh = jobs.shellArgv(cmd);
+ // ADR 0232: a read-only child's command runs under the sandbox; with none, only the allowlist runs.
+ const ro = @import("readonly_sandbox.zig");
+ var sandboxed: ro.Argv = .{};
+ const argv: []const []const u8 = if (!ctx.read_only_shell) &sh else ro.build(io, ctx.agent_cwd, cmd, &sandboxed) orelse
+ if (ro.allowlisted(cmd)) &sh else return .{ .text = try gpa.dupe(u8, ro.refusal), .is_error = true };
var opts = jobs.toolRunOptions(ctx.agent_cwd);
var live = exec_bash_stream.Ctx{ .io = io };
exec_bash_stream.attach(&opts, false, &live); // subagents stay quiet (#93)
opts.keep_tail = true; // #1271: the ending is where failures land
- const run = try jobs.runCappedWithOptions(gpa, io, &sh, bash_stdout_cap, bash_stderr_cap, subagent_deadline_ms, opts);
+ const run = try jobs.runCappedWithOptions(gpa, io, argv, bash_stdout_cap, bash_stderr_cap, subagent_deadline_ms, opts);
defer gpa.free(run.stdout);
defer gpa.free(run.stderr);
return formatCapped(gpa, cmd, run);
diff --git a/src/readonly_sandbox.zig b/src/readonly_sandbox.zig
new file mode 100644
index 00000000..30e6d09a
--- /dev/null
+++ b/src/readonly_sandbox.zig
@@ -0,0 +1,98 @@
+//! ADR 0232: a read-only child's foreground shell runs under macOS seatbelt.
+//! Any command may run and read; nothing may write inside the project or
+//! reach the network. That is what a read-only child of the codex route gets
+//! from its sandbox. The allowlist alone refused python, awk and gzip, so an
+//! informational child could not compute anything it was asked to report.
+//! Elsewhere, and for a command sent to the background, the read-only gate
+//! keeps its allowlist.
+const std = @import("std");
+const builtin = @import("builtin");
+const Io = std.Io;
+
+/// Part of every macOS install; a missing binary fails the spawn, it never
+/// runs the command unsandboxed.
+pub const exe = "/usr/bin/sandbox-exec";
+pub const available = builtin.os.tag == .macos;
+
+/// The gate's half: a foreground shell command is admitted because it will
+/// run under the sandbox.
+pub fn admits(input: std.json.Value) bool {
+ return available and !@import("json_args.zig").flag(input, "run_in_background");
+}
+
+/// Everything allowed; then every write denied but temp, terminal and
+/// descriptor paths; then every write under `root` denied again (the last
+/// matching rule wins, so a project under /tmp stays read-only); no network.
+pub fn profile(buf: []u8, root: []const u8) ?[]const u8 {
+ var w: Io.Writer = .fixed(buf);
+ w.writeAll("(version 1)(allow default)(deny file-write*)" ++
+ "(allow file-write* (subpath \"/private/tmp\") (subpath \"/private/var/folders\") (literal \"/dev/null\") (regex #\"^/dev/tty\") (regex #\"^/dev/fd/\"))" ++
+ "(deny file-write* (subpath \"") catch return null;
+ for (root) |c| {
+ if (c == '"' or c == '\\') w.writeByte('\\') catch return null;
+ w.writeByte(c) catch return null;
+ }
+ w.writeAll("\"))(deny network*)") catch return null;
+ return w.buffered();
+}
+
+/// Sized only where there is a sandbox: the caller keeps this on its stack.
+const path_cap = if (available) std.fs.max_path_bytes else 1;
+
+pub const Argv = struct {
+ root: [path_cap]u8 = undefined,
+ profile: [path_cap + 512]u8 = undefined,
+ argv: [8][]const u8 = undefined,
+};
+
+/// `cmd` under the sandbox, rooted at the real path of `cwd` (null: the
+/// process cwd). null when there is no sandbox here or the root does not
+/// resolve; the caller then refuses anything the allowlist would not pass.
+pub fn build(io: Io, cwd: ?[]const u8, cmd: []const u8, out: *Argv) ?[]const []const u8 {
+ if (!available) return null;
+ const n = Io.Dir.cwd().realPathFile(io, cwd orelse ".", &out.root) catch return null;
+ const p = profile(&out.profile, out.root[0..n]) orelse return null;
+ // git status would take index.lock, a write the sandbox refuses.
+ out.argv = .{ exe, "-p", p, "/usr/bin/env", "GIT_OPTIONAL_LOCKS=0", "/bin/sh", "-c", cmd };
+ return &out.argv;
+}
+
+/// The allowlist a read-only child keeps where there is no sandbox (the same
+/// predicates plan mode and the read-only gate use).
+pub fn allowlisted(cmd: []const u8) bool {
+ const policy = @import("harness_policy.zig");
+ const c = std.mem.trim(u8, cmd, " \t");
+ return policy.readOnlyAllowed(c) or policy.readOnlyExternal(c);
+}
+
+pub const refusal = "this subagent is read-only (an informational task) and its shell sandbox is unavailable — run read-only commands from the allowlist (ls, cat, head, tail, wc, grep, rg, git status/diff/log/show), and report the change instead of making it";
+
+test "read-only sandbox: the project is the last word on writes, and paths are quoted" {
+ var buf: [512]u8 = undefined;
+ const p = profile(&buf, "/private/tmp/a \"b\"").?;
+ try std.testing.expect(std.mem.endsWith(u8, p, "(deny file-write* (subpath \"/private/tmp/a \\\"b\\\"\"))(deny network*)"));
+ try std.testing.expect(std.mem.indexOf(u8, p, "(allow file-write* (subpath \"/private/tmp\")").? < std.mem.lastIndexOf(u8, p, "(deny file-write*").?);
+ var small: [16]u8 = undefined;
+ try std.testing.expect(profile(&small, "/x") == null);
+}
+
+test "read-only sandbox: python reads and computes, writes in the project fail" {
+ if (!available) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "in.txt", .data = "a b ERROR E401\n" });
+ const dir = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}", .{&tmp.sub_path});
+ defer gpa.free(dir);
+ var out: Argv = .{};
+ const argv = build(io, dir, "python3 -c \"print(open('in.txt').read().split()[3])\" && (echo no > out.txt || echo denied)", &out) orelse return error.SkipZigTest;
+ const jobs = @import("jobs.zig");
+ const run = jobs.runCappedWithOptions(gpa, io, argv, 4096, 4096, 20_000, jobs.toolRunOptions(dir)) catch return error.SkipZigTest;
+ defer gpa.free(run.stdout);
+ defer gpa.free(run.stderr);
+ if (std.mem.indexOf(u8, run.stderr, "python3") != null and std.mem.indexOf(u8, run.stdout, "E401") == null) return error.SkipZigTest; // no python3 here
+ try std.testing.expect(std.mem.indexOf(u8, run.stdout, "E401") != null);
+ try std.testing.expect(std.mem.indexOf(u8, run.stdout, "denied") != null);
+ try std.testing.expectError(error.FileNotFound, tmp.dir.access(io, "out.txt", .{}));
+}
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 087d5712..62bf9ef4 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -336,6 +336,7 @@ test {
_ = @import("subagent_fork.zig"); // ADR 0232
_ = @import("subagent_spawn_job.zig"); // ADR 0232: the spawn receipt's wait hint
_ = @import("ask_user.zig"); // ADR 0232: no todo nudges when nobody watches
+ _ = @import("readonly_sandbox.zig"); // ADR 0232: a read-only child computes under seatbelt
_ = @import("piped_paste.zig"); // ADR 0231
_ = @import("mcp_connect_notice.zig"); // ADR 0230
_ = @import("oauth_callback.zig");
diff --git a/src/tools.zig b/src/tools.zig
index f62c15b1..10d09b66 100644
--- a/src/tools.zig
+++ b/src/tools.zig
@@ -143,6 +143,7 @@ pub const ToolCtx = struct {
parent_effort: ?main_mod.ReasoningEffort = null, // ADR 0232: the caller's live effort (/effort or Jev); an unpinned child runs at it
parent_messages: []const std.json.Value = &.{}, // ADR 0232: the caller's history, read only while its tool batch runs
parent_task: []const u8 = "", // ADR 0232: the user's prompts a spawned child sees as context
+ read_only_shell: bool = false, // ADR 0232: a read-only child's foreground shell runs under the seatbelt sandbox
};
/// Event JSON for a tool lifecycle hook: {"event","tool","input"[,