Skip to content

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

Python

perf: drop round trips the model does not need (ADR 0231)

justrachde33aba6ec36
diff --git a/docs/adr/0231-no-round-trip-the-model-does-not-need.md b/docs/adr/0231-no-round-trip-the-model-does-not-need.md
new file mode 100644
index 00000000..2f6b1d3c
--- /dev/null
+++ b/docs/adr/0231-no-round-trip-the-model-does-not-need.md
@@ -0,0 +1,81 @@
+# 0231. No round trip the model does not need
+
+Status: accepted 2026-10-01
+
+## Context
+
+Run on the same model and the same tasks as the Codex app server, graff made
+more model calls per task. Every call pays a wait for the first token and
+then for every output token, so a call is seconds of wall time. The
+transcripts showed where the extra calls went, and none of them did work the
+task asked for.
+
+- **Loading what the prompt names.** "The linear server … load its schemas"
+ cost a `load_tool_schemas` call before the first real call, and "split the
+ work across subagents" cost one for the folded `subagent` tool.
+- **Checking that a path is free.** The prompt said `write_file` was "only
+ for new files", so in close to half of the runs that wrote a file the model
+ first ran `test -e`, `cat` or `read_file` on the target.
+- **Reading back what it just wrote.** `write_file` answered only
+ `wrote N bytes`, and the model then parsed the new JSON file in a separate
+ shell call.
+- **Children searching for tools their root loaded.** On the Codex route,
+ hosted tool search deferred every MCP tool, including those a child
+ inherits (ADR 0227), so each child spent its first call on a tool search.
+- **A two-line prompt in a scripted session.** The scripted REPL reads one
+ prompt per line, so a task with a line break ran as two turns.
+- **`ask_user` with nobody there.** In `-p` and piped sessions the model could
+ still ask a question that no one would answer.
+
+## Decision
+
+- Before the first request of a turn, the root loads every deferred tool of a
+ connected MCP server that the latest user message names as a whole word,
+ if that server's schemas fit in 16 KiB (`mcp_preload.zig`). A larger server
+ still waits for an explicit load. A message that asks for subagents loads
+ the folded `subagent` and `agent_output` tools the same way. A note tells the
+ model what loaded, and for MCP tools repeats what a `load_tool_schemas`
+ result says about slimmed result shapes (ADR 0225). Without the shapes, a
+ script written against full rows failed on the slimmed ones.
+- `write_file` creates a file, or replaces one the session has read, edited
+ or written. Replacing any other existing file fails and writes nothing,
+ unless the call passes `replace: true`. The result says `created` or
+ `replaced` and, for a `.json` path, whether the content parses. The prompt
+ says the guard exists, so the model needs no existence check, and that the
+ result is the evidence, so it needs no read-back.
+- The MCP tools a child inherits are sent with `defer_loading: false`, so
+ hosted tool search leaves them callable from the child's first request.
+- A piped REPL treats a bracketed paste (`ESC[200~ … ESC[201~`) as one prompt,
+ newlines included, which is what a terminal sends for a pasted block.
+ Without the frame, each line is still its own prompt.
+- `ask_user` is offered only when someone can answer: never under `-p`, and
+ never in a piped session outside `--json` or ACP. In those sessions a
+ low-effort Codex request also omits reasoning summaries, which only a
+ watcher reads and which arrive before the output. The TUI, ACP and
+ `--json` keep them.
+- With no git identity configured, the model commits with git's defaults
+ instead of asking for one.
+
+Two other changes were measured and dropped. Telling the model that a batch
+with a write runs its calls in order, so an edit and its check could share a
+response, made it split independent edits into separate responses instead.
+Accepting `attempt_completion` in the same response as a write saved
+nothing, because the model never sent them together. Spelling out how the
+slimmed `latest_author` is chosen ("newest by createdAt") made a careful model
+read the full results to reconcile it with a task that said "last in the
+list".
+
+## Consequences
+
+A model that rewrites a file it has never read, or one created by a shell
+command, now spends a call on the refusal or passes `replace: true`. Read
+tracking is per process, so a file read by a subagent counts for its root.
+Naming a small server, or mentioning subagents, loads those schemas for that
+turn even when the message does not mean to use them. Without summaries a
+silent low-effort reasoning phase emits no frames; the stall budget covers
+it at that effort, and higher efforts keep their summaries.
+
+Revisit the 16 KiB budget if named servers routinely exceed it, the write
+guard if refused writes show up in traces more often than the existence
+checks they replaced, and the summary rule if a low-effort request ever
+stalls before its first frame.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 9f613fb1..c6f9d084 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -256,6 +256,7 @@ record only when you need the evidence or the edge cases.
| [0227](0227-children-inherit-the-roots-loaded-mcp-tools.md) | A spawned child's catalog gains the MCP tools its root loaded, with full schemas (`worker_mcp.inherit` into `Agent.worker_tools`, served first by `toolsJson`). Unloaded tools stay out; children still have no load tool. |
| [0228](0228-read-only-child-calls-declared-read-only-mcp-tools.md) | An MCP tool is a read when its server declares `readOnlyHint: true` (`mcp.Tool.read_only`). A read-only (informational) child may call those and inherits only those from its root; undeclared MCP tools stay refused. |
| [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". |
+| [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. |
## When to write one
diff --git a/src/agent_catalog.zig b/src/agent_catalog.zig
index 455a192e..a5c816f2 100644
--- a/src/agent_catalog.zig
+++ b/src/agent_catalog.zig
@@ -26,6 +26,15 @@ fn withExtras(arena: Allocator, base: []const schema.ToolSpec, provider: Provide
return out;
}
+/// ADR 0231: with no human to answer (`-p`, a piped session outside
+/// --json/ACP) the root does not offer ask_user.
+fn withoutAskUser(self: *const Agent, specs: []const schema.ToolSpec) ![]const schema.ToolSpec {
+ if (!@import("ask_user.zig").g_no_human) return specs;
+ var kept: std.ArrayList(schema.ToolSpec) = .empty;
+ for (specs) |spec| if (!std.mem.eql(u8, spec.name, "ask_user")) try kept.append(self.arena, spec);
+ return kept.items;
+}
+
pub fn toolsJson(self: *const Agent) []const u8 {
if (self.sub) {
if (self.worker_tools.len != 0) return self.worker_tools; // ADR 0227
@@ -67,7 +76,7 @@ pub fn ensureRootTools(self: *Agent, kind: Provider.Kind) !void {
const specs = if (self.sub)
try surface.filterSpecs(@TypeOf(schema.base_specs[0]), self.arena, schema.base_specs[0..])
else
- try withExtras(self.arena, try schema.effectiveRootSpecs(self.arena), self.provider);
+ try withExtras(self.arena, try withoutAskUser(self, try schema.effectiveRootSpecs(self.arena)), self.provider);
const connected: []const mcp.Tool = if (self.registry) |registry| blk: {
const snapshot = try registry.snapshotTools(self.arena);
break :blk if (self.sub) try surface.filterWorkerMcp(self.arena, snapshot) else snapshot;
@@ -106,3 +115,25 @@ test "invalidate without ensure leaves toolsJson empty; rebuild is a JSON array"
try std.testing.expect(parsed.value == .array);
try std.testing.expect(parsed.value.array.items.len > 0);
}
+
+test "ask_user is offered only when a human can answer (ADR 0231)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const ask = @import("ask_user.zig");
+ const saved = ask.g_no_human;
+ defer ask.g_no_human = saved;
+ var agent: Agent = undefined;
+ agent.arena = arena;
+ agent.sub = false;
+ agent.registry = null;
+ agent.tools_responses = "";
+ agent.provider = .{ .id = "xai", .kind = .responses, .auth = .bearer, .url = "", .api_key = "k", .model = "grok-4.6", .context = 100_000 };
+ ask.g_no_human = true;
+ try agent.ensureRootTools(.responses);
+ try std.testing.expect(std.mem.indexOf(u8, agent.tools_responses, "\"ask_user\"") == null);
+ ask.g_no_human = false;
+ agent.tools_responses = "";
+ try agent.ensureRootTools(.responses);
+ try std.testing.expect(std.mem.indexOf(u8, agent.tools_responses, "\"ask_user\"") != null);
+}
diff --git a/src/agent_request.zig b/src/agent_request.zig
index 7e283a2c..3352f687 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -102,7 +102,8 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
var tools_now = tools_in;
const stale = self.toolsJson();
const joined = if (self.registry) |reg| @import("mcp_pages.zig").beforeRequest(reg) else false; // joins deferred starts, re-lists changed servers
- if (joined or @import("additional_tools.zig").staleCatalog(self)) {
+ const preloaded = @import("mcp_preload.zig").namedServers(self); // ADR 0231: a named server's schemas ride this request
+ if (joined or preloaded or @import("additional_tools.zig").staleCatalog(self)) {
self.invalidateRootTools();
try self.ensureRootTools(self.provider.kind);
// The caller's snapshot is the catalog that just went stale. Send the
diff --git a/src/agent_request_body_responses.zig b/src/agent_request_body_responses.zig
index 51229aa4..f57b466f 100644
--- a/src/agent_request_body_responses.zig
+++ b/src/agent_request_body_responses.zig
@@ -96,9 +96,12 @@ pub fn write(self: *Agent, s: *std.json.Stringify, tools: ?[]const u8, force_too
try s.objectField("effort");
// #379: compaction summaries run at low — a high-effort reasoner can
// complete with only reasoning items and zero output text.
- try s.write(if ((self.compaction_request or self.server_compaction_request) and !@import("effort_route.zig").mimoRoute(self.provider.id, self.provider.model)) "low" else @import("effort_route.zig").wireEffort(self.provider.id, self.provider.model, @tagName(self.reasoning)));
+ const effort = if ((self.compaction_request or self.server_compaction_request) and !@import("effort_route.zig").mimoRoute(self.provider.id, self.provider.model)) "low" else @import("effort_route.zig").wireEffort(self.provider.id, self.provider.model, @tagName(self.reasoning));
+ try s.write(effort);
// summary:auto streams reasoning_summary_text.delta (reasoningDelta already parses it); without it silent reasoning emits NO frames — the stall watchdog cannot tell thinking from a dead socket.
- if (is_codex or std.mem.eql(u8, self.provider.id, "chatgpt-new")) {
+ // ADR 0231: nobody watches a -p or piped session's reasoning, and at low effort it stays short, so it goes without.
+ const unwatched = @import("ask_user.zig").g_no_human and std.mem.eql(u8, effort, "low");
+ if ((is_codex or std.mem.eql(u8, self.provider.id, "chatgpt-new")) and !unwatched) {
try s.objectField("summary");
try s.write("auto");
}
diff --git a/src/ask_user.zig b/src/ask_user.zig
index ed6e1b31..aa8c1f9f 100644
--- a/src/ask_user.zig
+++ b/src/ask_user.zig
@@ -26,6 +26,12 @@ const acp_elicit = @import("acp_elicit.zig");
const ask_user_args = @import("ask_user_args.zig");
const style = &@import("ansi.zig").style;
+/// Set once at startup (session_start.zig): a `-p` run, or a piped session
+/// outside --json/ACP, has nobody to answer, so the root catalog leaves the
+/// tool out (ADR 0231). The model used to call it and spend a round trip on
+/// "no human is attached".
+pub var g_no_human: bool = false;
+
/// Block the root agent for an ask_user reply; subagents have no stdin.
pub fn askUser(self: *Agent, call: ToolCall) !ExecResult {
// #1308: aliases, a `questions` list, and double-encoded arguments all
diff --git a/src/exec.zig b/src/exec.zig
index a1d22f8b..384036f7 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -26,7 +26,6 @@ const strField = tools.strField;
const intField = tools.intField;
const missingArg = tools.missingArg;
const outsideCwd = tools.outsideCwd;
-const beforeFromRead = tools.beforeFromRead; // /rewind snapshot classifier (snapshots.zig)
const rawFetch = tools.rawFetch;
const subagent = @import("subagent.zig");
@@ -67,6 +66,7 @@ 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)
const html_view = @import("html_view.zig"); // the model's own drawing surface: one HTML page, rendered inline in the desktop transcript
const local_tools = @import("local_tools.zig");
+const write_file = @import("write_file.zig"); // ADR 0231: no-clobber writes that say what they did
fn learningArgv(argv: *[10][]const u8, exe_path: []const u8, contribute: bool) usize {
var argc: usize = 0;
@@ -278,6 +278,10 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
if (fsErrorText(gpa, .read, path, err)) |t| return .{ .text = t, .is_error = true };
return err;
};
+ switch (outcome) { // ADR 0231: write_file may now replace what the model has seen
+ .text, .truncated, .no_match => write_file.noteKnown(resolved),
+ else => {},
+ }
return switch (outcome) {
.text => |text| .{ .text = text },
.truncated => |value| blk: {
@@ -314,38 +318,12 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
// #337: the read/splice/write/VERIFY path lives in edit_verify.zig, where
// the post-edit check sits ON the success path — a write that did not land
// can no longer be reported as `replaced N occurrence(s)`.
- if (std.mem.eql(u8, call.name, "edit_file")) return if (input == .object and input.object.get("edits") != null) edit_batch.execBatch(ctx, input) else edit_verify.execEdit(ctx, input);
- if (std.mem.eql(u8, call.name, "write_file")) {
- const path = strField(input, "path") orelse return missingArg(gpa, "path");
- const content = strField(input, "content") orelse return missingArg(gpa, "content");
- if (!confinedPath(path) or !noSymlinkEscape(io, path, ctx.agent_cwd)) return outsideCwd(gpa, path);
- // #747: share sessionAbs with edit_file so a write cannot land in
- // posix cwd while the next edit looks at a stale display cwd.
- const resolved = try codedbpro_paths.sessionAbs(gpa, io, ctx.agent_cwd, path);
- defer gpa.free(resolved);
- // #337: a write_file racing an edit_file on the same path in the same
- // assistant turn (agent_tools.zig runs them concurrently) would drop
- // one of the two. Same stripe as edit_file, so they take turns.
- const lock = edit_verify.lockPath(io, resolved);
- defer lock.unlock(io);
- if (ctx.snapshots) |snaps| if (!ctx.from_sub) {
- // capture the prior content (or absence) before overwriting, for /rewind.
- // beforeFromRead keeps a merely UNREADABLE file (over the cap, permissions)
- // distinct from a missing one — only the latter is a rewind-deletes-it.
- const before = beforeFromRead(Io.Dir.cwd().readFileAlloc(io, resolved, gpa, .limited(4 * 1024 * 1024)));
- defer if (before == .content) gpa.free(before.content);
- snaps.record(path, before);
- };
- // #179: an existing file keeps its mode (e.g. 0755) across the overwrite;
- // a brand-new file (prev_stat == null) keeps the default.
- const prev_stat = Io.Dir.cwd().statFile(io, resolved, .{}) catch null;
- Io.Dir.cwd().writeFile(io, .{ .sub_path = resolved, .data = content }) catch |err| {
- if (fsErrorText(gpa, .write, path, err)) |t| return .{ .text = t, .is_error = true };
- return err;
- };
- preserveMode(io, resolved, prev_stat);
- return .{ .text = try std.fmt.allocPrint(gpa, "wrote {d} bytes to {s}", .{ content.len, path }) };
+ if (std.mem.eql(u8, call.name, "edit_file")) {
+ const out = try if (input == .object and input.object.get("edits") != null) edit_batch.execBatch(ctx, input) else edit_verify.execEdit(ctx, input);
+ if (!out.is_error) write_file.noteInput(ctx, input); // ADR 0231: an edited file may be rewritten
+ return out;
}
+ if (std.mem.eql(u8, call.name, "write_file")) return write_file.exec(ctx, input); // ADR 0231
// Loads one SKILL.md body (or lists them). Rescans on every call, so a
// skill written this session is loadable without a restart.
if (std.mem.eql(u8, call.name, html_view.tool_name)) return html_view.exec(ctx, input);
diff --git a/src/mcp_preload.zig b/src/mcp_preload.zig
new file mode 100644
index 00000000..82ff3501
--- /dev/null
+++ b/src/mcp_preload.zig
@@ -0,0 +1,134 @@
+//! Load the schemas of an MCP server the user names before the turn's first
+//! request (ADR 0231). A message that says "the linear server" is going to call
+//! it, and a deferred schema makes the model spend a whole round trip on
+//! `load_tool_schemas` before the first call. The named server's deferred
+//! tools load here, after the request path has joined the servers that
+//! finished connecting, and `additional_tools.sync` announces them on the same
+//! request. Servers the message does not name stay deferred, and one whose
+//! schemas exceed `budget_bytes` waits for an explicit load, so naming a large
+//! server in passing does not put all of its schemas in front of the model.
+//! Loading a schema grants nothing: every call still goes through the gate.
+//! A message that asks for subagents loads the folded `subagent` and
+//! `agent_output` natives the same way.
+
+const std = @import("std");
+const Agent = @import("agent.zig").Agent;
+const mcp = @import("mcp.zig");
+const gate = @import("mcp_schema_gate.zig");
+
+/// Total description + schema bytes a named server may load without asking.
+pub const budget_bytes: usize = 16 * 1024;
+
+/// On the root's first request of a turn, load every deferred tool of each
+/// server the latest user message names. True when anything loaded, so the
+/// caller rebuilds the catalog as it does when a server joins.
+pub fn namedServers(self: *Agent) bool {
+ if (self.sub or self.model_calls_this_turn > 1) return false;
+ const text = @import("messages.zig").latestUserText(self.messages.items);
+ if (text.len == 0) return false;
+ const reg_tools: []const mcp.Tool = if (self.registry) |reg| reg.tools else &.{};
+ var loaded: std.ArrayList(u8) = .empty;
+ for (reg_tools, 0..) |tool, i| {
+ const server = tool.serverName();
+ if (!firstOfServer(reg_tools[0..i], server) or !names(text, server)) continue;
+ if (gate.serverCost(reg_tools, server) > budget_bytes) continue;
+ for (reg_tools) |t| if (std.mem.eql(u8, t.serverName(), server) and gate.blocked(reg_tools, t.qualified_name)) {
+ gate.autoLoad(self.arena, reg_tools, t.qualified_name);
+ loaded.print(self.arena, "{s}{s}", .{ if (loaded.items.len == 0) "" else ", ", t.qualified_name }) catch {};
+ };
+ }
+ const mcp_loaded = loaded.items.len > 0;
+ namedNatives(self.arena, text, &loaded);
+ if (loaded.items.len == 0) return false;
+ note(self, loaded.items, mcp_loaded);
+ return true;
+}
+
+/// Folded natives a message asks for outright. A request to split work across
+/// subagents spawns them and waits on what they return, so both load with the
+/// request instead of one load call each.
+const named_natives = [_]struct { words: []const []const u8, tools: []const []const u8 }{
+ .{ .words = &.{ "subagent", "subagents", "sub-agent", "sub-agents" }, .tools = &.{ "subagent", "agent_output" } },
+};
+
+fn namedNatives(arena: std.mem.Allocator, text: []const u8, loaded: *std.ArrayList(u8)) void {
+ const fold = @import("native_fold.zig");
+ for (named_natives) |entry| {
+ const asked = for (entry.words) |w| {
+ if (names(text, w)) break true;
+ } else false;
+ if (!asked) continue;
+ for (entry.tools) |tool| if (fold.blocked(tool)) {
+ fold.markLoaded(tool);
+ loaded.print(arena, "{s}{s}", .{ if (loaded.items.len == 0) "" else ", ", tool }) catch {};
+ };
+ }
+}
+
+/// Tell the model the load already happened. A prompt that says "load its
+/// schemas" otherwise still gets a load_tool_schemas call, and with it the
+/// round trip the preload exists to save. The note carries what that call's
+/// result would have said about result shapes (ADR 0225): without it the
+/// model coded against full rows, met slimmed ones, and spent calls finding
+/// the real shape.
+fn note(self: *Agent, tools: []const u8, mcp_loaded: bool) void {
+ const head = std.fmt.allocPrint(self.arena, "Already loaded for this turn: {s}. Their schemas are attached and the tools are callable now; load_tool_schemas is not needed for them.", .{tools}) catch return;
+ const shaped = if (mcp_loaded) @import("mcp_shapes.zig").annotate(self.gpa, self.arena, self.io, self.agent_cwd, head) catch head else head;
+ // A fetch-then-write task is one rlm step: each() makes the calls, write_file
+ // saves the binds, and bash() builds the file from them.
+ const text = if (mcp_loaded and @import("rlm.zig").available) std.fmt.allocPrint(self.arena, "{s}\n{s}", .{ shaped, rlm_hint }) catch shaped else shaped;
+ var msg = @import("named_work.zig").userNudge(self.arena, self.provider.kind, text) catch return;
+ if (msg != .object) return;
+ msg.object.put(self.arena, @import("session_wake.zig").origin_key, .{ .string = "notification" }) catch return;
+ self.messages.append(msg) catch {};
+}
+
+const rlm_hint = "To fetch from these tools and write a file from the results, one rlm script can do it in one step: each() makes the calls, write_file saves the binds, and bash() builds the file from the saved results.";
+
+fn firstOfServer(before: []const mcp.Tool, server: []const u8) bool {
+ for (before) |t| if (std.mem.eql(u8, t.serverName(), server)) return false;
+ return true;
+}
+
+/// Whether `text` names `server` as a whole word, ignoring case. Words are
+/// runs of letters, digits, `-` and `_`, the characters server names use.
+pub fn names(text: []const u8, server: []const u8) bool {
+ if (server.len == 0) return false;
+ var i: usize = 0;
+ while (i < text.len) {
+ while (i < text.len and !wordChar(text[i])) i += 1;
+ const start = i;
+ while (i < text.len and wordChar(text[i])) i += 1;
+ if (i > start and std.ascii.eqlIgnoreCase(text[start..i], server)) return true;
+ }
+ return false;
+}
+
+fn wordChar(c: u8) bool {
+ return std.ascii.isAlphanumeric(c) or c == '-' or c == '_';
+}
+
+test "asking for subagents loads subagent and agent_output with the request (ADR 0231)" {
+ const fold = @import("native_fold.zig");
+ fold.clearLoadedSession();
+ defer fold.clearLoadedSession();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ var loaded: std.ArrayList(u8) = .empty;
+ namedNatives(arena_state.allocator(), "Fix the parser and run the tests.", &loaded);
+ try std.testing.expectEqual(@as(usize, 0), loaded.items.len);
+ namedNatives(arena_state.allocator(), "Split the 8 issues across two sibling subagents.", &loaded);
+ if (fold.enabled) {
+ try std.testing.expectEqualStrings("subagent, agent_output", loaded.items);
+ try std.testing.expect(fold.isLoaded("subagent") and fold.isLoaded("agent_output"));
+ }
+}
+
+test "a server is named only as a whole word, in any case" {
+ try std.testing.expect(names("This workspace has a Linear-shaped MCP server named linear (stdio).", "linear"));
+ try std.testing.expect(names("check LINEAR for open bugs", "linear"));
+ try std.testing.expect(names("use codedb-pro to search", "codedb-pro"));
+ try std.testing.expect(!names("the linearity of the fit", "linear"));
+ try std.testing.expect(!names("codedb-pro-extra", "codedb-pro"));
+ try std.testing.expect(!names("", "linear"));
+}
diff --git a/src/piped_paste.zig b/src/piped_paste.zig
new file mode 100644
index 00000000..61e7c9f2
--- /dev/null
+++ b/src/piped_paste.zig
@@ -0,0 +1,42 @@
+//! A piped (non-TTY) REPL reads one prompt per line. A driver with a
+//! multi-line prompt frames it the way a terminal frames a paste,
+//! ESC[200~ … ESC[201~, and the whole block is one prompt, newlines kept
+//! (ADR 0231). Without the frame each line is still its own prompt.
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const paste_start = "\x1b[200~";
+const paste_end = "\x1b[201~";
+
+/// The next prompt, or null at EOF. The result lives in `buf` (or the
+/// reader's buffer) until the next call. Text after the end marker on its
+/// line is dropped: a terminal sends only the Enter there. EOF inside an open
+/// paste ends the prompt where the input ended.
+pub fn next(in: *Io.Reader, gpa: Allocator, buf: *std.ArrayList(u8)) !?[]const u8 {
+ const first = (try in.takeDelimiter('\n')) orelse return null;
+ if (!std.mem.startsWith(u8, first, paste_start)) return first;
+ buf.clearRetainingCapacity();
+ var line = first[paste_start.len..];
+ while (true) {
+ if (std.mem.indexOf(u8, line, paste_end)) |end| {
+ try buf.appendSlice(gpa, line[0..end]);
+ return buf.items;
+ }
+ try buf.appendSlice(gpa, line);
+ line = (try in.takeDelimiter('\n')) orelse return buf.items;
+ try buf.append(gpa, '\n');
+ }
+}
+
+test "a bracketed paste on a pipe is one prompt; bare lines stay one each (ADR 0231)" {
+ const gpa = std.testing.allocator;
+ var buf: std.ArrayList(u8) = .empty;
+ defer buf.deinit(gpa);
+ var in: Io.Reader = .fixed("first\n\x1b[200~Create hello.txt\nThen rename it.\x1b[201~\nlast\n\x1b[200~open at EOF\ntail");
+ try std.testing.expectEqualStrings("first", (try next(&in, gpa, &buf)).?);
+ try std.testing.expectEqualStrings("Create hello.txt\nThen rename it.", (try next(&in, gpa, &buf)).?);
+ try std.testing.expectEqualStrings("last", (try next(&in, gpa, &buf)).?);
+ try std.testing.expectEqualStrings("open at EOF\ntail", (try next(&in, gpa, &buf)).?);
+ try std.testing.expect(try next(&in, gpa, &buf) == null);
+}
diff --git a/src/prompt_golden.zig b/src/prompt_golden.zig
index 3fb7fd7d..15073a87 100644
--- a/src/prompt_golden.zig
+++ b/src/prompt_golden.zig
@@ -33,12 +33,14 @@ pub const full_prompt =
\\For changes, retain read-before-edit, root-cause fixes, and verification
\\in the project's own environment. A summary alone does not finish a fix.
\\read_file before editing; prefer
- \\edit_file for changes to existing files and write_file only for new
- \\files or full rewrites. For a read-only exact-key lookup in one known file,
+ \\edit_file for changes to existing files and write_file for new
+ \\files or full rewrites. write_file will not replace a file you have not
+ \\read, so write a new file without first checking that its path is free.
+ \\For a read-only exact-key lookup in one known file,
\\call read_file once with contains set to the exact key and answer from its
\\output; do not request the whole file first. To navigate code — finding symbols,
\\definitions, or where logic lives — prefer the codedb tool (it's indexed
- \\and structural) over bash grep/find/ls. The codedb commands are context <task>, around <name>, callpath A B, list_dir <path>, and status — one call, not a chain. List a folder with codedb list_dir <path> (in-process; no index required). Before an exact edit, read one current uncompressed target span, apply the smallest edit that preserves terminal-newline state, do not verify after success, and reread/retry only on stale source, ambiguity, or failure. Some bash commands need user approval — if one
+ \\and structural) over bash grep/find/ls. The codedb commands are context <task>, around <name>, callpath A B, list_dir <path>, and status — one call, not a chain. List a folder with codedb list_dir <path> (in-process; no index required). Before an exact edit, read one current uncompressed target span, apply the smallest edit that preserves terminal-newline state, do not verify after success, and reread/retry only on stale source, ambiguity, or failure. A successful write_file is its own evidence: its result says what landed and whether a .json file parses, so do not read back or re-parse what you just wrote. Some bash commands need user approval — if one
\\is declined, try another approach or ask. Native file tools deliberately
\\stay inside the current working directory. If the user explicitly names
\\a repository or path outside it, the root agent may inspect and modify
@@ -109,7 +111,9 @@ pub const full_prompt =
\\When making git commits on behalf of the user, commit as the USER's own git
\\identity — do NOT override GIT_AUTHOR_*/GIT_COMMITTER_*; their configured
\\name + email (matching their GitHub account) must be the commit Author, just
- \\as when they commit by hand. Credit the assist with a trailer at the very end
+ \\as when they commit by hand. If none is configured, commit with git's
+ \\defaults; do not ask about or set an identity. Credit the assist with a
+ \\trailer at the very end
\\of the commit message, after a blank line (omit this optional attribution
\\when the user asks; authoring style is user-overridable, safety is not):
\\Co-Authored-By: Codegraff <[email protected]>
diff --git a/src/prompt_text.zig b/src/prompt_text.zig
index c65ca95a..1ed564c6 100644
--- a/src/prompt_text.zig
+++ b/src/prompt_text.zig
@@ -38,12 +38,14 @@ pub const intro_note =
pub const local_tools_note =
\\
\\read_file before editing; prefer
- \\edit_file for changes to existing files and write_file only for new
- \\files or full rewrites. For a read-only exact-key lookup in one known file,
+ \\edit_file for changes to existing files and write_file for new
+ \\files or full rewrites. write_file will not replace a file you have not
+ \\read, so write a new file without first checking that its path is free.
+ \\For a read-only exact-key lookup in one known file,
\\call read_file once with contains set to the exact key and answer from its
\\output; do not request the whole file first. To navigate code — finding symbols,
\\definitions, or where logic lives — prefer the codedb tool (it's indexed
- \\and structural) over bash grep/find/ls. The codedb commands are context <task>, around <name>, callpath A B, list_dir <path>, and status — one call, not a chain. List a folder with codedb list_dir <path> (in-process; no index required). Before an exact edit, read one current uncompressed target span, apply the smallest edit that preserves terminal-newline state, do not verify after success, and reread/retry only on stale source, ambiguity, or failure. Some bash commands need user approval — if one
+ \\and structural) over bash grep/find/ls. The codedb commands are context <task>, around <name>, callpath A B, list_dir <path>, and status — one call, not a chain. List a folder with codedb list_dir <path> (in-process; no index required). Before an exact edit, read one current uncompressed target span, apply the smallest edit that preserves terminal-newline state, do not verify after success, and reread/retry only on stale source, ambiguity, or failure. A successful write_file is its own evidence: its result says what landed and whether a .json file parses, so do not read back or re-parse what you just wrote. Some bash commands need user approval — if one
\\is declined, try another approach or ask. Native file tools deliberately
\\stay inside the current working directory. If the user explicitly names
\\a repository or path outside it, the root agent may inspect and modify
@@ -158,7 +160,9 @@ pub const git_authoring_note =
\\When making git commits on behalf of the user, commit as the USER's own git
\\identity — do NOT override GIT_AUTHOR_*/GIT_COMMITTER_*; their configured
\\name + email (matching their GitHub account) must be the commit Author, just
- \\as when they commit by hand. Credit the assist with a trailer at the very end
+ \\as when they commit by hand. If none is configured, commit with git's
+ \\defaults; do not ask about or set an identity. Credit the assist with a
+ \\trailer at the very end
\\of the commit message, after a blank line (omit this optional attribution
\\when the user asks; authoring style is user-overridable, safety is not):
\\Co-Authored-By: Codegraff <[email protected]>
@@ -368,7 +372,9 @@ pub const parallel_tools_note = parallel_core_note ++ parallel_examples_note ++
pub const lean_local_tools_note =
\\
\\read_file before editing; prefer edit_file for existing files and
- \\write_file only for new files. Use the smallest unique edit spans and
+ \\write_file for new files. write_file never replaces a file you have not
+ \\read, so skip existence checks; its result is the evidence, so skip
+ \\read-backs. Use the smallest unique edit spans and
\\preserve terminal-newline state. Navigate with codedb (context, around,
\\callpath, list_dir, status).
\\Independent reads belong in ONE response, not a chain of turns.
diff --git a/src/readline.zig b/src/readline.zig
index 13b5a809..6159d2c6 100644
--- a/src/readline.zig
+++ b/src/readline.zig
@@ -74,7 +74,7 @@ pub fn readLine(
buf: *std.ArrayList(u8),
prompt_text: ?[]const u8,
) !?[]const u8 {
- const raw_state = tty.enterRaw(true) orelse return in.takeDelimiter('\n');
+ const raw_state = tty.enterRaw(true) orelse return @import("piped_paste.zig").next(in, gpa, buf); // ADR 0231
defer tty.restore(raw_state);
buf.clearRetainingCapacity();
var cur: usize = 0; // cursor index within buf
diff --git a/src/repl_run.zig b/src/repl_run.zig
index 8e4fc286..7bc19997 100644
--- a/src/repl_run.zig
+++ b/src/repl_run.zig
@@ -37,8 +37,10 @@ pub fn runScripted(
m.setup(gpa);
defer m.deinit();
+ var paste_buf: std.ArrayList(u8) = .empty; // ADR 0231: a bracketed paste is one prompt
+ defer paste_buf.deinit(gpa);
while (true) {
- const raw = (in.takeDelimiter('\n') catch null) orelse break; // EOF ends the script
+ const raw = (@import("piped_paste.zig").next(in, gpa, &paste_buf) catch null) orelse break; // EOF ends the script
const line = std.mem.trim(u8, raw, " \t\r\n");
if (line.len == 0) continue;
diff --git a/src/rlm_order_tests.zig b/src/rlm_order_tests.zig
index 69ab2557..068f3aba 100644
--- a/src/rlm_order_tests.zig
+++ b/src/rlm_order_tests.zig
@@ -191,7 +191,7 @@ test "rlm order observes each lexical host output exactly once in execution orde
var state: @import("pr_local_checks.zig").State = .{};
var ctx = f.ctx();
ctx.publication_observer = .{ .context = &observed, .state = &state, .record = Observed.record };
- const out = try rlm.runScript(ctx, "items = read_file(\"items.json\")\nmapped = each(items, \"sleep_ms\", \"id\")\ne = write_file(path=\"target.txt\", content=\"new\")\nr = read_file(\"target.txt\")\nprint(r)");
+ const out = try rlm.runScript(ctx, "items = read_file(\"items.json\")\nmapped = each(items, \"sleep_ms\", \"id\")\ne = write_file(path=\"target.txt\", content=\"new\", replace=true)\nr = read_file(\"target.txt\")\nprint(r)");
defer gpa.free(out.text);
try std.testing.expect(!out.is_error);
try std.testing.expectEqualStrings("new", out.text);
diff --git a/src/schema.zig b/src/schema.zig
index 459efd29..f4e469f6 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -69,9 +69,9 @@ pub const base_specs = [_]ToolSpec{
},
.{
.name = "write_file",
- .desc = "Create or overwrite a file with the given contents.",
+ .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. 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"}}, "required": ["path", "content"]}
+ \\{"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"]}
,
},
.{
@@ -347,6 +347,26 @@ pub fn writeToolEntry(s: *std.json.Stringify, kind: Provider.Kind, name: []const
}
}
+/// 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
diff --git a/src/session_start.zig b/src/session_start.zig
index 542ad2d8..0f36b7b7 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -110,6 +110,13 @@ pub fn setupWorktreeAndBanner(
main_mod.use_color = true;
engine_sink.enableColor();
}
+ // ADR 0231: nobody answers ask_user in `-p` or in a session with no
+ // terminal on either end (piped in and out) outside --json/ACP, so the root
+ // catalog leaves it out. The TUI takes stdin over before this, so its
+ // terminal shows on stdout.
+ const terminal = (Io.File.stdin().isTty(io) catch false) or (Io.File.stdout().isTty(io) catch false);
+ @import("ask_user.zig").g_no_human = flags.oneshot_prompt != null or
+ (!main_mod.json_mode and !@import("mcp_boot.zig").isAcp(flags.positionals.items) and !terminal);
const sink = engine_sink.writerSink(out);
// --add-dir before --worktree chdir so a relative extra root is resolved
// against the launch cwd, not the scratch tree.
diff --git a/src/snapshots_tests.zig b/src/snapshots_tests.zig
index 810434b3..5994526c 100644
--- a/src/snapshots_tests.zig
+++ b/src/snapshots_tests.zig
@@ -40,6 +40,7 @@ fn writeFile(snaps: *snapshots.Snapshots, a: std.mem.Allocator, path: []const u8
var obj: std.json.ObjectMap = .empty;
try obj.put(a, "path", .{ .string = path });
try obj.put(a, "content", .{ .string = content });
+ try obj.put(a, "replace", .{ .bool = true }); // these tests clobber files they never read (ADR 0231)
var client: std.http.Client = undefined;
const out = exec.execTool(testCtx(&client, snaps), .{ .id = "call_1", .name = "write_file", .input = .{ .object = obj } });
defer std.testing.allocator.free(out.text);
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 6ca167a9..45585fbd 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -331,6 +331,9 @@ test {
_ = agent_compact_summary_test;
_ = side_question_tests;
_ = @import("worker_mcp.zig"); // ADR 0227
+ _ = @import("mcp_preload.zig"); // ADR 0231
+ _ = @import("write_file.zig"); // ADR 0231
+ _ = @import("piped_paste.zig"); // ADR 0231
_ = @import("oauth_callback.zig");
_ = @import("cache_key_tests.zig"); // ADR 0223: moved off http_headers.zig (600-line cap)
_ = @import("mcp_shapes_tests.zig"); // ADR 0225: moved off mcp_shapes.zig (600-line cap)
diff --git a/src/worker_mcp.zig b/src/worker_mcp.zig
index 7e625942..45d80355 100644
--- a/src/worker_mcp.zig
+++ b/src/worker_mcp.zig
@@ -38,7 +38,9 @@ pub fn withLoaded(arena: Allocator, kind: Provider.Kind, base: []const u8, tools
for (tools) |t| {
if (mcp_schema_gate.omitMcp(t.qualified_name) or !mcp_schema_gate.isLoaded(t.qualified_name)) continue;
if (read_only and !t.read_only) continue;
- schema.writeToolEntry(&s, kind, t.qualified_name, t.description, .{ .value = t.input_schema }) catch return base;
+ if (kind == .responses) {
+ schema.writeEagerResponsesEntry(&s, t.qualified_name, t.description, .{ .value = t.input_schema }) catch return base;
+ } else schema.writeToolEntry(&s, kind, t.qualified_name, t.description, .{ .value = t.input_schema }) catch return base;
n += 1;
}
s.endArray() catch return base;
@@ -68,6 +70,10 @@ test "a child's catalog gains the MCP tools the root loaded, and only those" {
try std.testing.expectEqual(@as(usize, 2), parsed.array.items.len);
try std.testing.expect(std.mem.indexOf(u8, out, all[1].qualified_name) != null);
try std.testing.expect(std.mem.indexOf(u8, out, all[0].qualified_name) == null);
+ // ADR 0231: eager, so hosted tool search (codex_tool_search.splice) leaves it callable.
+ try std.testing.expect(std.mem.indexOf(u8, out, "\"defer_loading\":false") != null);
+ const spliced = try @import("codex_tool_search.zig").splice(a, out);
+ try std.testing.expect(std.mem.indexOf(u8, spliced, "\"defer_loading\":true") == null);
const alone = withLoaded(a, .responses, "[]", all, false);
try std.testing.expectEqual(@as(usize, 1), (try std.json.parseFromSliceLeaky(std.json.Value, a, alone, .{})).array.items.len);
}
diff --git a/src/write_file.zig b/src/write_file.zig
new file mode 100644
index 00000000..e8c61b98
--- /dev/null
+++ b/src/write_file.zig
@@ -0,0 +1,166 @@
+//! write_file (ADR 0231). Creates a file, or replaces one this session has
+//! already read, edited or written; replacing any other existing file takes
+//! `replace: true`. The guard is what lets a model write a new file straight
+//! away: without it a careful model spent a whole round trip checking that the
+//! path was free. The result says what happened (created or replaced, and for
+//! a .json path whether the content parses), so a successful write needs no
+//! read-back either.
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const tools = @import("tools.zig");
+const approvals = @import("approvals.zig");
+const codedbpro_paths = @import("codedbpro_paths.zig");
+const edit_verify = @import("edit_verify.zig");
+
+const page = std.heap.page_allocator;
+
+/// Absolute paths whose content this process has seen. Process-wide, so a
+/// subagent's read counts for its parent and the other way round.
+var known: std.StringHashMapUnmanaged(void) = .empty;
+var known_lock: std.atomic.Value(bool) = .init(false);
+
+fn lock() void {
+ while (known_lock.cmpxchgWeak(false, true, .acquire, .monotonic) != null) std.atomic.spinLoopHint();
+}
+
+fn unlock() void {
+ known_lock.store(false, .release);
+}
+
+pub fn noteKnown(abs_path: []const u8) void {
+ lock();
+ defer unlock();
+ if (known.contains(abs_path)) return;
+ const key = page.dupe(u8, abs_path) catch return;
+ known.put(page, key, {}) catch page.free(key);
+}
+
+fn isKnown(abs_path: []const u8) bool {
+ lock();
+ defer unlock();
+ return known.contains(abs_path);
+}
+
+/// After a successful read_file or edit_file: the model has seen this path.
+pub fn noteInput(ctx: tools.ToolCtx, input: std.json.Value) void {
+ const path = tools.strField(input, "path") orelse return;
+ const resolved = codedbpro_paths.sessionAbs(ctx.gpa, ctx.io, ctx.agent_cwd, path) catch return;
+ defer ctx.gpa.free(resolved);
+ noteKnown(resolved);
+}
+
+pub fn exec(ctx: tools.ToolCtx, input: std.json.Value) !tools.ToolOutput {
+ const gpa = ctx.gpa;
+ const io = ctx.io;
+ const path = tools.strField(input, "path") orelse return tools.missingArg(gpa, "path");
+ const content = tools.strField(input, "content") orelse return tools.missingArg(gpa, "content");
+ if (!approvals.confinedPath(path) or !approvals.noSymlinkEscape(io, path, ctx.agent_cwd)) return tools.outsideCwd(gpa, path);
+ // #747: share sessionAbs with edit_file so a write cannot land in
+ // posix cwd while the next edit looks at a stale display cwd.
+ const resolved = try codedbpro_paths.sessionAbs(gpa, io, ctx.agent_cwd, path);
+ defer gpa.free(resolved);
+ // #337: a write_file racing an edit_file on the same path in the same
+ // assistant turn (agent_tools.zig runs them concurrently) would drop
+ // one of the two. Same stripe as edit_file, so they take turns.
+ const path_lock = edit_verify.lockPath(io, resolved);
+ defer path_lock.unlock(io);
+ // #179: an existing file keeps its mode (e.g. 0755) across the overwrite;
+ // a brand-new file (prev_stat == null) keeps the default.
+ const prev_stat = Io.Dir.cwd().statFile(io, resolved, .{}) catch null;
+ if (prev_stat) |st| if (st.kind == .file and st.size > 0 and !isKnown(resolved) and !tools.json_args.flag(input, "replace")) return .{
+ .text = try std.fmt.allocPrint(gpa, "{s} already exists ({d} bytes) and has not been read in this session; nothing was written. Read it first, or pass replace: true to overwrite it.", .{ path, st.size }),
+ .is_error = true,
+ };
+ if (ctx.snapshots) |snaps| if (!ctx.from_sub) {
+ // capture the prior content (or absence) before overwriting, for /rewind.
+ // beforeFromRead keeps a merely UNREADABLE file (over the cap, permissions)
+ // distinct from a missing one — only the latter is a rewind-deletes-it.
+ const before = tools.beforeFromRead(Io.Dir.cwd().readFileAlloc(io, resolved, gpa, .limited(4 * 1024 * 1024)));
+ defer if (before == .content) gpa.free(before.content);
+ snaps.record(path, before);
+ };
+ Io.Dir.cwd().writeFile(io, .{ .sub_path = resolved, .data = content }) catch |err| {
+ if (edit_verify.fsErrorText(gpa, .write, path, err)) |t| return .{ .text = t, .is_error = true };
+ return err;
+ };
+ edit_verify.preserveMode(io, resolved, prev_stat);
+ noteKnown(resolved);
+ return .{ .text = try resultText(gpa, path, content, if (prev_stat) |st| st.size else null) };
+}
+
+fn resultText(gpa: Allocator, path: []const u8, content: []const u8, prev_size: ?u64) ![]u8 {
+ var out: std.Io.Writer.Allocating = .init(gpa);
+ errdefer out.deinit();
+ const w = &out.writer;
+ if (prev_size) |was| {
+ try w.print("replaced {s} ({d} bytes; was {d})", .{ path, content.len, was });
+ } else try w.print("created {s} ({d} bytes)", .{ path, content.len });
+ if (std.ascii.endsWithIgnoreCase(path, ".json")) try jsonNote(gpa, w, content);
+ return out.toOwnedSlice();
+}
+
+/// A generated data file is the usual thing a model re-opens to check, so
+/// the parse result rides the write's own result.
+fn jsonNote(gpa: Allocator, w: *std.Io.Writer, content: []const u8) !void {
+ var scanner = std.json.Scanner.initCompleteInput(gpa, content);
+ defer scanner.deinit();
+ var diag: std.json.Diagnostics = .{};
+ scanner.enableDiagnostics(&diag);
+ while (true) {
+ const token = scanner.next() catch |err| {
+ if (err == error.OutOfMemory) return;
+ return w.print("; NOT valid JSON ({t} at line {d}, column {d})", .{ err, diag.getLine(), diag.getColumn() });
+ };
+ if (token == .end_of_document) return w.writeAll("; parses as JSON");
+ }
+}
+
+test "write_file creates, refuses to clobber an unread file, and replaces a known one (ADR 0231)" {
+ if (@import("builtin").os.tag == .windows) return error.SkipZigTest; // same write path as the /rewind tests, which skip there too
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{&tmp.sub_path});
+ const out_json = try std.fmt.allocPrint(a, "{s}/out.json", .{dir});
+ const theirs = try std.fmt.allocPrint(a, "{s}/theirs.txt", .{dir});
+ var client: std.http.Client = undefined;
+ const ctx: tools.ToolCtx = .{ .gpa = gpa, .io = io, .client = &client, .provider = undefined, .registry = null, .from_sub = false, .approvals = null, .tracer = null };
+
+ var args: std.json.ObjectMap = .empty;
+ try args.put(a, "path", .{ .string = out_json });
+ try args.put(a, "content", .{ .string = "{\"n\": 1}" });
+ const created = try exec(ctx, .{ .object = args });
+ defer gpa.free(created.text);
+ try std.testing.expect(!created.is_error);
+ try std.testing.expectEqualStrings(try std.fmt.allocPrint(a, "created {s} (8 bytes); parses as JSON", .{out_json}), created.text);
+
+ // A file this session never saw is refused and left untouched.
+ try tmp.dir.writeFile(io, .{ .sub_path = "theirs.txt", .data = "keep me" });
+ args.getPtr("path").?.* = .{ .string = theirs };
+ args.getPtr("content").?.* = .{ .string = "{\"n\": " };
+ const refused = try exec(ctx, .{ .object = args });
+ defer gpa.free(refused.text);
+ try std.testing.expect(refused.is_error);
+ const kept = try tmp.dir.readFileAlloc(io, "theirs.txt", gpa, .limited(64));
+ defer gpa.free(kept);
+ try std.testing.expectEqualStrings("keep me", kept);
+
+ // replace: true overwrites it; a file this session wrote needs no flag.
+ try args.put(a, "replace", .{ .bool = true });
+ const replaced = try exec(ctx, .{ .object = args });
+ defer gpa.free(replaced.text);
+ try std.testing.expect(!replaced.is_error);
+ try std.testing.expectEqualStrings(try std.fmt.allocPrint(a, "replaced {s} (6 bytes; was 7)", .{theirs}), replaced.text);
+ _ = args.swapRemove("replace");
+ args.getPtr("path").?.* = .{ .string = out_json };
+ const again = try exec(ctx, .{ .object = args });
+ defer gpa.free(again.text);
+ try std.testing.expect(!again.is_error);
+ try std.testing.expect(std.mem.startsWith(u8, again.text, try std.fmt.allocPrint(a, "replaced {s} (6 bytes; was 8); NOT valid JSON (", .{out_json})));
+}