Skip to content

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

Python

Stop consecutive read_file miss storms

Cursor Agent22d707a5c3a8
diff --git a/docs/adr/0148-read-file-miss-storm-stops.md b/docs/adr/0148-read-file-miss-storm-stops.md
new file mode 100644
index 00000000..02f98b40
--- /dev/null
+++ b/docs/adr/0148-read-file-miss-storm-stops.md
@@ -0,0 +1,28 @@
+# 0148. Stop consecutive read_file miss storms
+
+Status: accepted 2026-09-21
+
+## Context
+
+A turn can spend dozens of `read_file` calls on files that do not exist.
+Guessed names increment in lockstep under one directory (ADR-style
+`0365-…` through `0397-…`) or reshuffle the same slug words. Each miss
+returns control to the model. ADR 0065 stops bounded lexical prose, not
+tool-call path guessing. Directory listing is `codedb list_dir` (ADR 0013).
+
+## Decision
+
+Track not-found `read_file` results per directory prefix for the turn.
+After three misses under the same prefix, or an incrementing numbered
+filename pattern of that length, refuse further reads under that prefix
+and point at `codedb list_dir`. A parallel incrementing batch executes
+at most three paths first; the rest run only if those hits, otherwise
+they are refused without opening. A successful read clears that prefix.
+REPL, TUI, GUI, and RLM host calls share the same tracker.
+
+## Consequences
+
+Invented sequential paths stop after a bounded probe. A real multi-file
+read in one directory that is not incrementing-numbered still runs as
+one batch. Three genuine misses in one folder block later reads there
+until a hit or a new turn.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 511edaff..403df3b8 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -167,6 +167,7 @@ record only when you need the evidence or the edge cases.
| [0145](0145-live-claims-are-accord-progress.md) | Claim acquire/release/handoff replicate as replaceable Accord progress; the JSON ledger stays canonical. |
| [0146](0146-concurrent-sessions-auto-isolate.md) | A second live session in the same Git checkout gets its own worktree; concurrent agents never share `index.lock`. |
| [0147](0147-finish-is-not-cleanup-fanout.md) | Finish is not archive: park peer mail until idle, refuse cleanup/fix-it children, cap live fan-out. |
+| [0148](0148-read-file-miss-storm-stops.md) | After N same-prefix or incrementing `read_file` misses, refuse further guesses this turn and point at `codedb list_dir`. |
## When to write one
diff --git a/src/agent.zig b/src/agent.zig
index a6828fd6..ac037649 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -126,6 +126,7 @@ pub const Agent = struct {
agent_cwd: ?[]const u8 = null, // subagent-only (#276 P0-1): absolute path of this agent's isolated git worktree, threaded through ToolCtx per tool call instead of a process-wide chdir — parallel siblings each keep their own
tools_used: trace.ToolSink = .{}, // external tool calls this agent made (per turn for the root)
tool_calls_this_turn: u64 = 0,
+ read_miss: @import("read_miss.zig").Tracker = .{}, // #1116: same-prefix / incrementing read_file misses
model_calls_this_turn: u64 = 0,
handle_note_shown: bool = false, // #541: the handle-protocol lesson rides this agent's FIRST handle, once
seen_tool_keys: std.ArrayList([]const u8) = .empty, // root-only per-turn dedupe keys
@@ -331,6 +332,7 @@ pub const Agent = struct {
var pending_work: empty_completion.PendingWork = .{};
var bounced_answer: empty_completion.BounceAnswer = .{};
self.completed = null;
+ self.read_miss.reset();
self.mcp_context.begin(self.io);
@import("named_work.zig").beginTurn(self);
try self.ensureRootTools(self.provider.kind);
diff --git a/src/agent_tool_batch.zig b/src/agent_tool_batch.zig
index e016b968..9c77ff84 100644
--- a/src/agent_tool_batch.zig
+++ b/src/agent_tool_batch.zig
@@ -71,6 +71,7 @@ pub fn runExternal(self: *Agent, calls: []const ToolCall, ext_idx: []const usize
.loop_deadline_ms = self.loop_deadline_ms,
.agent_cwd = self.agent_cwd,
.subagent_feedback = self.feedback,
+ .read_miss = &self.read_miss,
};
const esc_watch = !self.sub and self.in != null and main_mod.use_color and !main_mod.json_mode;
var esc_tio: ?tty.RawState = null;
@@ -119,6 +120,7 @@ fn aborted() bool {
}
fn takeOutput(self: *Agent, call: ToolCall, output: ToolOutput, handle_threshold: usize, handle_target: tool_handle.Target) !ExecResult {
+ self.read_miss.noteOutput(call.name, call.input, output.text, output.is_error);
try @import("pr_local_checks.zig").record(self, call, .{ .text = output.text, .is_error = output.is_error, .cancelled = output.cancelled });
const handled = try tool_handle.forResult(self.gpa, self.arena, handle_target, output.text, handle_threshold);
const text = try tool_handle.withFirstNote(self.arena, handled, &self.handle_note_shown);
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index 5df23edc..70b1fec1 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -49,6 +49,7 @@ const schedule = @import("schedule.zig");
const util = @import("util.zig"); // #225: unixMs, for the clock_sleep interrupted-elapsed measurement
const cite_markup = @import("cite_markup.zig");
+const read_miss = @import("read_miss.zig");
/// Run a batch of tool calls. Meta tools are handled inline (they mutate
/// agent state); mutating file/shell calls run one at a time, otherwise
@@ -75,6 +76,16 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {
// Collect the indices of external (non-meta) calls for parallel exec.
var ext_idx: std.ArrayList(usize) = .empty;
defer ext_idx.deinit(self.gpa);
+ var hold_idx: std.ArrayList(usize) = .empty;
+ defer hold_idx.deinit(self.gpa);
+ var read_paths: std.ArrayList([]const u8) = .empty;
+ defer read_paths.deinit(self.gpa);
+ for (calls) |call| {
+ if (std.mem.eql(u8, call.name, "read_file")) {
+ if (read_miss.callPath(call.input)) |p| try read_paths.append(self.gpa, p);
+ }
+ }
+ var miss_batch = read_miss.Batch.init(read_paths.items);
for (calls, 0..) |call, i| {
if (eval_index) |verifier| if (i != verifier) {
self.emitToolRejected(call, "verifier_boundary", eval_control.verifier_boundary);
@@ -100,8 +111,10 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {
results[i] = try self.handleMeta(call);
} else if (try self.gateTool(call)) |denied| {
results[i] = denied;
- } else {
- try ext_idx.append(self.gpa, i);
+ } else switch (classifyRead(self, &miss_batch, call)) {
+ .refuse => results[i] = try refuseRead(self, call),
+ .hold => try hold_idx.append(self.gpa, i),
+ .run => try ext_idx.append(self.gpa, i),
}
}
@@ -109,6 +122,25 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {
try @import("agent_tool_batch.zig").runExternal(self, calls, ext_idx.items, results);
brief_diversity.noteSiblingBatch(self.arena, self.tracer, calls, ext_idx.items, results); // #382
}
+ if (hold_idx.items.len > 0) {
+ var wave2: std.ArrayList(usize) = .empty;
+ defer wave2.deinit(self.gpa);
+ for (hold_idx.items) |i| {
+ const path = read_miss.callPath(calls[i].input) orelse {
+ try wave2.append(self.gpa, i);
+ continue;
+ };
+ if (self.read_miss.shouldRefuse(path)) {
+ results[i] = try refuseRead(self, calls[i]);
+ continue;
+ }
+ try wave2.append(self.gpa, i);
+ }
+ if (wave2.items.len > 0) {
+ try @import("agent_tool_batch.zig").runExternal(self, calls, wave2.items, results);
+ brief_diversity.noteSiblingBatch(self.arena, self.tracer, calls, wave2.items, results);
+ }
+ }
if (defer_completion) if (eval_control.completionIndex(calls)) |i| {
var verify_failed = ext_idx.items.len == 0;
for (ext_idx.items) |j| {
@@ -129,11 +161,29 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {
return results;
}
+fn classifyRead(self: *Agent, batch: *read_miss.Batch, call: ToolCall) read_miss.Wave {
+ if (!std.mem.eql(u8, call.name, "read_file")) return .run;
+ const path = read_miss.callPath(call.input) orelse return .run;
+ return batch.classify(&self.read_miss, path);
+}
+
+fn refuseRead(self: *Agent, call: ToolCall) !ExecResult {
+ const path = read_miss.callPath(call.input) orelse ".";
+ const message = try read_miss.refusalText(self.arena, path);
+ self.emitToolRejected(call, "read_miss", message);
+ return .{ .text = message, .is_error = true };
+}
+
pub fn rejectToolCall(self: *Agent, call: ToolCall) !?ExecResult {
if (!call.args_ok) {
self.emitToolRejected(call, "invalid_arguments", tool_call_args.invalid_exec_message);
return .{ .text = tool_call_args.invalid_exec_message, .is_error = true };
}
+ if (std.mem.eql(u8, call.name, "read_file")) {
+ if (read_miss.callPath(call.input)) |path| {
+ if (self.read_miss.shouldRefuse(path)) return try refuseRead(self, call);
+ }
+ }
if (self.sub) return null;
if (self.review_mode) if (try review.rejectTool(self.arena, call)) |denied| {
self.emitToolRejected(call, "review_mode", denied.text);
diff --git a/src/edit_verify.zig b/src/edit_verify.zig
index 3d3644b1..f2a343b3 100644
--- a/src/edit_verify.zig
+++ b/src/edit_verify.zig
@@ -312,7 +312,7 @@ pub fn fsErrorText(gpa: Allocator, op: FileOp, path: []const u8, err: anyerror)
return (switch (err) {
// A missing target, or a non-directory used as a path component.
error.FileNotFound, error.NotDir => switch (op) {
- .read => std.fmt.allocPrint(gpa, "read_file: {s} does not exist (paths are relative to the cwd) — check the name, or list the directory with bash `ls`", .{path}),
+ .read => std.fmt.allocPrint(gpa, "read_file: {s} does not exist (paths are relative to the cwd) — check the name, or list the directory with codedb list_dir", .{path}),
.edit => std.fmt.allocPrint(gpa, "edit_file: {s} does not exist — edit_file only rewrites an existing file; use write_file to create it", .{path}),
.write => std.fmt.allocPrint(gpa, "write_file: cannot create {s} — its parent directory does not exist; create it first with bash `mkdir -p`", .{path}),
},
diff --git a/src/exec.zig b/src/exec.zig
index 5cfd1f5e..d8df1cba 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -50,6 +50,7 @@ const skills = @import("skills.zig");
const skill_docs = @import("skill_docs.zig");
const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: refuse an MCP tool whose schema was never loaded
const read_file = @import("read_file.zig");
+const read_miss = @import("read_miss.zig");
const result_read = @import("result_read.zig");
const codedb_exec = @import("codedb_exec.zig"); // native codedb dispatch (list_dir / status / one-shots)
// #337: edit_file's verified write path, plus the file-tool helpers that moved
@@ -264,6 +265,9 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
if (std.mem.eql(u8, call.name, result_read.tool_name)) return result_read.exec(ctx, call);
if (std.mem.eql(u8, call.name, "read_file")) {
const path = strField(input, "path") orelse return missingArg(gpa, "path");
+ if (ctx.read_miss) |tracker| {
+ if (tracker.shouldRefuse(path)) return .{ .text = try read_miss.refusalText(gpa, path), .is_error = true };
+ }
if (!confinedPath(path) or !noSymlinkEscape(io, path, ctx.agent_cwd)) return outsideCwd(gpa, path);
const start_line = intField(input, "start_line");
const end_line = intField(input, "end_line");
@@ -429,4 +433,6 @@ test { // main.zig is at the 600-line cap; exec.zig is these modules' importer,
_ = @import("spec_ptc.zig");
_ = @import("xai_hosted.zig");
_ = @import("read_file_schema_tests.zig"); // #761: optional read_file fields
+ _ = @import("read_miss.zig"); // #1116: consecutive read_file miss storm
+ _ = @import("read_miss_tests.zig");
}
diff --git a/src/read_miss.zig b/src/read_miss.zig
new file mode 100644
index 00000000..54e265bd
--- /dev/null
+++ b/src/read_miss.zig
@@ -0,0 +1,392 @@
+//! Consecutive `read_file` miss storm (#1116).
+//!
+//! After N not-found reads under the same directory prefix, or an incrementing
+//! numbered filename pattern, further guessed reads this turn are refused and
+//! pointed at `codedb list_dir`. Catalog dispatch and RLM host calls share one
+//! Tracker so REPL / TUI / GUI behave the same. ADR 0065 covers prose only.
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+const Value = std.json.Value;
+const json_args = @import("json_args.zig");
+
+pub const miss_limit: u8 = 3;
+pub const max_prefix_len: usize = 255;
+
+pub const Wave = enum { run, hold, refuse };
+
+const PrefixSlot = struct {
+ buf: [max_prefix_len]u8 = undefined,
+ len: u8 = 0,
+ misses: u8 = 0,
+ last_number: ?u64 = null,
+ incrementing: u8 = 0,
+ latched: bool = false,
+
+ fn prefix(self: *const PrefixSlot) []const u8 {
+ return self.buf[0..self.len];
+ }
+
+ fn setPrefix(self: *PrefixSlot, p: []const u8) void {
+ const n = @min(p.len, max_prefix_len);
+ @memcpy(self.buf[0..n], p[0..n]);
+ self.len = @intCast(n);
+ }
+
+ fn matches(self: *const PrefixSlot, p: []const u8) bool {
+ return self.len > 0 and std.mem.eql(u8, self.prefix(), p);
+ }
+
+ fn reset(self: *PrefixSlot) void {
+ self.* = .{};
+ }
+};
+
+/// Turn-scoped miss state. Fixed slots; no heap. Reset at `runTurn`.
+pub const Tracker = struct {
+ slots: [8]PrefixSlot = @splat(.{}),
+
+ pub fn reset(self: *Tracker) void {
+ self.* = .{};
+ }
+
+ fn slotFor(self: *Tracker, prefix: []const u8) *PrefixSlot {
+ for (&self.slots) |*s| {
+ if (s.matches(prefix)) return s;
+ }
+ for (&self.slots) |*s| {
+ if (s.len == 0) {
+ s.setPrefix(prefix);
+ return s;
+ }
+ }
+ var best = &self.slots[0];
+ for (self.slots[1..]) |*s| {
+ if (s.misses < best.misses) best = s;
+ }
+ best.reset();
+ best.setPrefix(prefix);
+ return best;
+ }
+
+ fn find(self: *const Tracker, prefix: []const u8) ?*const PrefixSlot {
+ for (&self.slots) |*s| {
+ if (s.matches(prefix)) return s;
+ }
+ return null;
+ }
+
+ pub fn shouldRefuse(self: *const Tracker, path: []const u8) bool {
+ const slot = self.find(dirPrefix(path)) orelse return false;
+ return slot.latched;
+ }
+
+ pub fn remaining(self: *const Tracker, path: []const u8) u8 {
+ const slot = self.find(dirPrefix(path)) orelse return miss_limit;
+ if (slot.latched) return 0;
+ if (slot.misses >= miss_limit) return 0;
+ return miss_limit - slot.misses;
+ }
+
+ pub fn noteResult(self: *Tracker, path: []const u8, missed: bool) void {
+ const prefix = dirPrefix(path);
+ const slot = self.slotFor(prefix);
+ if (!missed) {
+ slot.reset();
+ return;
+ }
+ slot.misses +|= 1;
+ if (fileNumber(path)) |n| {
+ if (slot.last_number) |prev| {
+ if (n == prev + 1) slot.incrementing +|= 1 else slot.incrementing = 1;
+ } else slot.incrementing = 1;
+ slot.last_number = n;
+ } else {
+ slot.last_number = null;
+ slot.incrementing = 0;
+ }
+ if (slot.misses >= miss_limit or slot.incrementing >= miss_limit) slot.latched = true;
+ }
+
+ pub fn noteOutput(self: *Tracker, name: []const u8, input: Value, text: []const u8, is_error: bool) void {
+ if (!std.mem.eql(u8, name, "read_file")) return;
+ const path = callPath(input) orelse return;
+ self.noteResult(path, is_error and isMissText(text));
+ }
+};
+
+pub fn callPath(input: Value) ?[]const u8 {
+ const obj = json_args.object(input) orelse return null;
+ const p = json_args.str(obj, "path") orelse return null;
+ const t = std.mem.trim(u8, p, " \t");
+ return if (t.len == 0) null else t;
+}
+
+pub fn pathFromArgsJson(args_json: []const u8) ?[]const u8 {
+ const key = "\"path\"";
+ const start = std.mem.indexOf(u8, args_json, key) orelse return null;
+ var i = start + key.len;
+ while (i < args_json.len and (args_json[i] == ' ' or args_json[i] == ':')) i += 1;
+ if (i >= args_json.len or args_json[i] != '"') return null;
+ i += 1;
+ const from = i;
+ while (i < args_json.len and args_json[i] != '"') i += 1;
+ if (i >= args_json.len) return null;
+ const t = std.mem.trim(u8, args_json[from..i], " \t");
+ return if (t.len == 0) null else t;
+}
+
+pub fn dirPrefix(path: []const u8) []const u8 {
+ const trimmed = std.mem.trim(u8, path, " \t");
+ if (trimmed.len == 0) return ".";
+ const slash = std.mem.lastIndexOfScalar(u8, trimmed, '/') orelse return ".";
+ if (slash == 0) return "/";
+ return trimmed[0..slash];
+}
+
+/// First run of digits in the basename (`0365-foo.md` → 365).
+pub fn fileNumber(path: []const u8) ?u64 {
+ const name = basename(path);
+ var i: usize = 0;
+ while (i < name.len and !std.ascii.isDigit(name[i])) i += 1;
+ if (i == name.len) return null;
+ var n: u64 = 0;
+ var digits: u8 = 0;
+ while (i < name.len and std.ascii.isDigit(name[i])) : (i += 1) {
+ n = n * 10 + (name[i] - '0');
+ digits += 1;
+ if (digits > 18) break;
+ }
+ return if (digits == 0) null else n;
+}
+
+fn basename(path: []const u8) []const u8 {
+ const trimmed = std.mem.trim(u8, path, " \t");
+ if (std.mem.lastIndexOfScalar(u8, trimmed, '/')) |slash| return trimmed[slash + 1 ..];
+ return trimmed;
+}
+
+pub fn isMissText(text: []const u8) bool {
+ return std.mem.indexOf(u8, text, "does not exist") != null;
+}
+
+pub fn refusalText(gpa: Allocator, path: []const u8) ![]u8 {
+ const prefix = dirPrefix(path);
+ return std.fmt.allocPrint(
+ gpa,
+ "read_file: refused further guesses under {s}/ after {d} not-found reads this turn — list the directory with codedb list_dir {s} instead of inventing paths",
+ .{ prefix, miss_limit, prefix },
+ );
+}
+
+/// True when `paths` in call order are same-prefix and lockstep-numbered.
+pub fn incrementingGroup(paths: []const []const u8) bool {
+ if (paths.len < miss_limit) return false;
+ const prefix = dirPrefix(paths[0]);
+ var prev = fileNumber(paths[0]) orelse return false;
+ for (paths[1..]) |p| {
+ if (!std.mem.eql(u8, dirPrefix(p), prefix)) return false;
+ const n = fileNumber(p) orelse return false;
+ if (n != prev + 1) return false;
+ prev = n;
+ }
+ return true;
+}
+
+const BatchQueued = struct {
+ prefix: [max_prefix_len]u8 = undefined,
+ len: u8 = 0,
+ n: u8 = 0,
+
+ fn matches(self: *const BatchQueued, p: []const u8) bool {
+ return self.len > 0 and std.mem.eql(u8, self.prefix[0..self.len], p);
+ }
+};
+
+/// Per-batch cap so a parallel storm does not execute every invented path.
+pub const Batch = struct {
+ queued: [8]BatchQueued = @splat(.{}),
+ used: u8 = 0,
+ incrementing: bool = false,
+
+ pub fn init(paths: []const []const u8) Batch {
+ return .{ .incrementing = incrementingGroup(paths) };
+ }
+
+ fn queuedFor(self: *Batch, prefix: []const u8) *BatchQueued {
+ for (self.queued[0..self.used]) |*q| {
+ if (q.matches(prefix)) return q;
+ }
+ if (self.used == self.queued.len) return &self.queued[0];
+ const q = &self.queued[self.used];
+ self.used += 1;
+ const n = @min(prefix.len, max_prefix_len);
+ @memcpy(q.prefix[0..n], prefix[0..n]);
+ q.len = @intCast(n);
+ q.n = 0;
+ return q;
+ }
+
+ pub fn classify(self: *Batch, tracker: *const Tracker, path: []const u8) Wave {
+ if (tracker.shouldRefuse(path)) return .refuse;
+ const left = tracker.remaining(path);
+ if (left == 0) return .refuse;
+ // Non-incrementing first-wave reads stay uncapped so a real multi-file
+ // read in one directory is not split. Incrementing names, or a prefix
+ // that already missed this turn, are capped at `left`.
+ const cap: u8 = if (self.incrementing or left < miss_limit) left else 255;
+ const q = self.queuedFor(dirPrefix(path));
+ if (q.n >= cap) return .hold;
+ q.n += 1;
+ return .run;
+ }
+};
+
+pub fn classifyPath(tracker: *const Tracker, batch: *Batch, path: []const u8) Wave {
+ return batch.classify(tracker, path);
+}
+
+test "dirPrefix and fileNumber parse ADR-style guesses" {
+ try std.testing.expectEqualStrings("docs/adr", dirPrefix("docs/adr/0365-foo.md"));
+ try std.testing.expectEqualStrings(".", dirPrefix("0365-foo.md"));
+ try std.testing.expectEqualStrings("/", dirPrefix("/abs/0365-foo.md")[0..1]);
+ try std.testing.expectEqual(@as(?u64, 365), fileNumber("docs/adr/0365-foo.md"));
+ try std.testing.expectEqual(@as(?u64, 397), fileNumber("docs/adr/0397-reshuffled-slug.md"));
+ try std.testing.expectEqual(@as(?u64, null), fileNumber("docs/adr/README.md"));
+}
+
+test "same-prefix misses latch after miss_limit and refuse further guesses" {
+ var t: Tracker = .{};
+ t.noteResult("docs/adr/0365-a.md", true);
+ t.noteResult("docs/adr/0366-b.md", true);
+ try std.testing.expect(!t.shouldRefuse("docs/adr/0367-c.md"));
+ t.noteResult("docs/adr/0367-c.md", true);
+ try std.testing.expect(t.shouldRefuse("docs/adr/0368-d.md"));
+ try std.testing.expect(t.shouldRefuse("docs/adr/README.md"));
+ try std.testing.expect(!t.shouldRefuse("src/main.zig"));
+}
+
+test "a hit clears the prefix so a later real read is not blocked" {
+ var t: Tracker = .{};
+ t.noteResult("docs/adr/0365-a.md", true);
+ t.noteResult("docs/adr/0366-b.md", true);
+ t.noteResult("docs/adr/0367-c.md", true);
+ try std.testing.expect(t.shouldRefuse("docs/adr/0368-d.md"));
+ t.noteResult("docs/adr/0001-structured-outputs.md", false);
+ try std.testing.expect(!t.shouldRefuse("docs/adr/0002-xai-defaults.md"));
+}
+
+test "a different prefix does not inherit the latch" {
+ var t: Tracker = .{};
+ t.noteResult("docs/adr/0365-a.md", true);
+ t.noteResult("docs/adr/0366-b.md", true);
+ t.noteResult("docs/adr/0367-c.md", true);
+ t.noteResult("src/missing.zig", true);
+ try std.testing.expect(t.shouldRefuse("docs/adr/0368-d.md"));
+ try std.testing.expect(!t.shouldRefuse("src/other.zig"));
+}
+
+test "incrementingGroup detects lockstep numbered names" {
+ const storm = [_][]const u8{
+ "docs/adr/0365-foo.md",
+ "docs/adr/0366-bar.md",
+ "docs/adr/0367-baz.md",
+ "docs/adr/0368-qux.md",
+ };
+ try std.testing.expect(incrementingGroup(&storm));
+ const mixed = [_][]const u8{ "docs/adr/0365-foo.md", "src/0366.zig", "docs/adr/0367-baz.md" };
+ try std.testing.expect(!incrementingGroup(&mixed));
+ const two = [_][]const u8{ "docs/adr/0365-foo.md", "docs/adr/0366-bar.md" };
+ try std.testing.expect(!incrementingGroup(&two));
+}
+
+test "batch holds incrementing overflow until the first misses latch" {
+ const paths = [_][]const u8{
+ "docs/adr/0365-a.md",
+ "docs/adr/0366-b.md",
+ "docs/adr/0367-c.md",
+ "docs/adr/0368-d.md",
+ "docs/adr/0369-e.md",
+ "docs/adr/0370-f.md",
+ };
+ var t: Tracker = .{};
+ var batch = Batch.init(&paths);
+ var waves: [6]Wave = undefined;
+ for (paths, 0..) |p, i| waves[i] = batch.classify(&t, p);
+ try std.testing.expectEqual(Wave.run, waves[0]);
+ try std.testing.expectEqual(Wave.run, waves[1]);
+ try std.testing.expectEqual(Wave.run, waves[2]);
+ try std.testing.expectEqual(Wave.hold, waves[3]);
+ try std.testing.expectEqual(Wave.hold, waves[4]);
+ try std.testing.expectEqual(Wave.hold, waves[5]);
+
+ t.noteResult(paths[0], true);
+ t.noteResult(paths[1], true);
+ t.noteResult(paths[2], true);
+ try std.testing.expect(t.shouldRefuse(paths[3]));
+ try std.testing.expectEqual(Wave.refuse, Batch.init(&paths[3..]).classify(&t, paths[3]));
+}
+
+test "batch of existing incrementing files is not refused after a hit" {
+ const paths = [_][]const u8{
+ "shots/001.png",
+ "shots/002.png",
+ "shots/003.png",
+ "shots/004.png",
+ };
+ var t: Tracker = .{};
+ var batch = Batch.init(&paths);
+ try std.testing.expectEqual(Wave.run, batch.classify(&t, paths[0]));
+ try std.testing.expectEqual(Wave.run, batch.classify(&t, paths[1]));
+ try std.testing.expectEqual(Wave.run, batch.classify(&t, paths[2]));
+ try std.testing.expectEqual(Wave.hold, batch.classify(&t, paths[3]));
+ t.noteResult(paths[0], false);
+ t.noteResult(paths[1], false);
+ t.noteResult(paths[2], false);
+ try std.testing.expect(!t.shouldRefuse(paths[3]));
+ try std.testing.expectEqual(Wave.run, Batch.init(paths[3..]).classify(&t, paths[3]));
+}
+
+test "non-incrementing same-prefix reads stay uncapped until misses accrue" {
+ const paths = [_][]const u8{ "src/a.zig", "src/b.zig", "src/c.zig", "src/d.zig" };
+ var t: Tracker = .{};
+ var batch = Batch.init(&paths);
+ try std.testing.expect(!batch.incrementing);
+ for (paths) |p| try std.testing.expectEqual(Wave.run, batch.classify(&t, p));
+}
+
+test "refusalText names codedb list_dir and the prefix" {
+ const gpa = std.testing.allocator;
+ const msg = try refusalText(gpa, "docs/adr/0365-foo.md");
+ defer gpa.free(msg);
+ try std.testing.expect(std.mem.indexOf(u8, msg, "codedb list_dir docs/adr") != null);
+ try std.testing.expect(std.mem.indexOf(u8, msg, "refused") != null);
+ try std.testing.expect(isMissText("read_file: docs/adr/0365-foo.md does not exist (paths are relative"));
+ try std.testing.expect(!isMissText("permission denied"));
+}
+
+test "callPath and pathFromArgsJson read the path field" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const v = try std.json.parseFromSliceLeaky(Value, a, "{\"path\":\"docs/adr/0365-a.md\"}", .{});
+ try std.testing.expectEqualStrings("docs/adr/0365-a.md", callPath(v).?);
+ try std.testing.expectEqualStrings("docs/adr/0365-a.md", pathFromArgsJson("{\"path\":\"docs/adr/0365-a.md\"}").?);
+ try std.testing.expect(callPath(.{ .object = .empty }) == null);
+}
+
+test "noteOutput ignores non-read tools and non-miss errors" {
+ var t: Tracker = .{};
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const input = try std.json.parseFromSliceLeaky(Value, a, "{\"path\":\"docs/adr/0365-a.md\"}", .{});
+ t.noteOutput("edit_file", input, "does not exist", true);
+ try std.testing.expect(!t.shouldRefuse("docs/adr/0366-b.md"));
+ t.noteOutput("read_file", input, "permission denied", true);
+ try std.testing.expect(!t.shouldRefuse("docs/adr/0366-b.md"));
+ t.noteOutput("read_file", input, "read_file: docs/adr/0365-a.md does not exist", true);
+ t.noteOutput("read_file", input, "read_file: docs/adr/0365-a.md does not exist", true);
+ t.noteOutput("read_file", input, "read_file: docs/adr/0365-a.md does not exist", true);
+ try std.testing.expect(t.shouldRefuse("docs/adr/0368-d.md"));
+}
diff --git a/src/read_miss_tests.zig b/src/read_miss_tests.zig
new file mode 100644
index 00000000..62e0687f
--- /dev/null
+++ b/src/read_miss_tests.zig
@@ -0,0 +1,212 @@
+//! Integration coverage for #1116: guessed incrementing `read_file` paths
+//! stop after `miss_limit` not-founds and do not keep executing.
+
+const std = @import("std");
+const builtin = @import("builtin");
+const Value = std.json.Value;
+
+const Agent = @import("agent.zig").Agent;
+const exec = @import("exec.zig");
+const read_miss = @import("read_miss.zig");
+const rlm = @import("rlm.zig");
+const tools = @import("tools.zig");
+const ToolCall = tools.ToolCall;
+
+fn jsonCall(arena: std.mem.Allocator, id: []const u8, path: []const u8) !ToolCall {
+ const raw = try std.fmt.allocPrint(arena, "{{\"path\":\"{s}\"}}", .{path});
+ return .{
+ .id = id,
+ .name = "read_file",
+ .input = try std.json.parseFromSliceLeaky(Value, arena, raw, .{}),
+ };
+}
+
+fn testAgent(arena: std.mem.Allocator, cwd: []const u8, client: *std.http.Client) Agent {
+ return .{
+ .gpa = std.testing.allocator,
+ .arena = arena,
+ .io = std.testing.io,
+ .client = client,
+ .provider = undefined,
+ .messages = undefined,
+ .sub = true,
+ .label = "test",
+ .out = null,
+ .agent_cwd = cwd,
+ };
+}
+
+test "runTools: incrementing invented ADR paths stop after miss_limit (#1116)" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const n = try tmp.dir.realPath(io, &real_buf);
+ const cwd = real_buf[0..n];
+
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+ var agent = testAgent(arena, cwd, &client);
+
+ const paths = [_][]const u8{
+ "docs/adr/0365-foo.md",
+ "docs/adr/0366-bar.md",
+ "docs/adr/0367-baz.md",
+ "docs/adr/0368-qux.md",
+ "docs/adr/0369-quux.md",
+ "docs/adr/0370-corge.md",
+ };
+ var calls: [6]ToolCall = undefined;
+ for (paths, 0..) |p, i| calls[i] = try jsonCall(arena, paths[i], p);
+
+ const results = try agent.runTools(&calls);
+ var executed_misses: usize = 0;
+ var refused: usize = 0;
+ for (results) |r| {
+ try std.testing.expect(r.is_error);
+ if (std.mem.indexOf(u8, r.text, "refused") != null) {
+ refused += 1;
+ try std.testing.expect(std.mem.indexOf(u8, r.text, "codedb list_dir") != null);
+ } else if (std.mem.indexOf(u8, r.text, "does not exist") != null) {
+ executed_misses += 1;
+ } else return error.TestUnexpectedResult;
+ }
+ try std.testing.expectEqual(@as(usize, read_miss.miss_limit), executed_misses);
+ try std.testing.expectEqual(@as(usize, paths.len - read_miss.miss_limit), refused);
+ try std.testing.expect(agent.read_miss.shouldRefuse("docs/adr/0371-invented.md"));
+}
+
+test "runTools: sequential same-prefix misses refuse the next guess" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const n = try tmp.dir.realPath(io, &real_buf);
+ const cwd = real_buf[0..n];
+
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+ var agent = testAgent(arena, cwd, &client);
+
+ const first = [_][]const u8{ "docs/adr/a.md", "docs/adr/b.md", "docs/adr/c.md" };
+ var wave1: [3]ToolCall = undefined;
+ for (first, 0..) |p, i| wave1[i] = try jsonCall(arena, p, p);
+ const r1 = try agent.runTools(&wave1);
+ for (r1) |r| {
+ try std.testing.expect(r.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, r.text, "does not exist") != null);
+ }
+
+ const next = try jsonCall(arena, "d", "docs/adr/d.md");
+ const r2 = try agent.runTools(&[_]ToolCall{next});
+ try std.testing.expect(r2[0].is_error);
+ try std.testing.expect(std.mem.indexOf(u8, r2[0].text, "refused") != null);
+ try std.testing.expect(std.mem.indexOf(u8, r2[0].text, "codedb list_dir docs/adr") != null);
+}
+
+test "execTool refuses a latched prefix without opening the path" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tracker: read_miss.Tracker = .{};
+ tracker.noteResult("docs/adr/0365-a.md", true);
+ tracker.noteResult("docs/adr/0366-b.md", true);
+ tracker.noteResult("docs/adr/0367-c.md", true);
+
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+ const call = try jsonCall(arena, "x", "docs/adr/0368-d.md");
+ const out = exec.execTool(.{
+ .gpa = gpa,
+ .io = io,
+ .client = &client,
+ .provider = undefined,
+ .registry = null,
+ .from_sub = false,
+ .approvals = null,
+ .tracer = null,
+ .read_miss = &tracker,
+ }, call);
+ defer gpa.free(out.text);
+ try std.testing.expect(out.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, out.text, "refused") != null);
+ try std.testing.expect(std.mem.indexOf(u8, out.text, "does not exist") == null);
+}
+
+test "rlm host reads refuse incrementing invented paths after miss_limit" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const n = try tmp.dir.realPath(io, &real_buf);
+ const cwd = real_buf[0..n];
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+ var tracker: read_miss.Tracker = .{};
+ const saved = rlm.available;
+ defer {
+ rlm.available = saved;
+ rlm.resetLive(gpa, io);
+ }
+ rlm.available = true;
+ const out = try rlm.runScript(.{
+ .gpa = gpa,
+ .io = io,
+ .client = &client,
+ .provider = undefined,
+ .registry = null,
+ .from_sub = false,
+ .approvals = null,
+ .tracer = null,
+ .agent_cwd = cwd,
+ .read_miss = &tracker,
+ },
+ \\a = read_file("docs/adr/0365-a.md")
+ \\b = read_file("docs/adr/0366-b.md")
+ \\c = read_file("docs/adr/0367-c.md")
+ \\d = read_file("docs/adr/0368-d.md")
+ \\print(d)
+ );
+ defer gpa.free(out.text);
+ try std.testing.expect(out.is_error or std.mem.indexOf(u8, out.text, "refused") != null);
+ try std.testing.expect(tracker.shouldRefuse("docs/adr/0369-e.md"));
+}
+
+test "rejectToolCall refuses a latched prefix before the call counts" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent: Agent = .{
+ .gpa = a,
+ .arena = a,
+ .io = std.testing.io,
+ .client = undefined,
+ .provider = undefined,
+ .messages = undefined,
+ .sub = false,
+ .label = "test",
+ .out = null,
+ };
+ agent.read_miss.noteResult("docs/adr/0365-a.md", true);
+ agent.read_miss.noteResult("docs/adr/0366-b.md", true);
+ agent.read_miss.noteResult("docs/adr/0367-c.md", true);
+ const call = try jsonCall(a, "1", "docs/adr/0368-d.md");
+ const denied = (try @import("agent_tools.zig").rejectToolCall(&agent, call)).?;
+ try std.testing.expect(denied.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, denied.text, "refused") != null);
+ try std.testing.expectEqual(@as(u64, 0), agent.tool_calls_this_turn);
+}
diff --git a/src/rlm.zig b/src/rlm.zig
index 48d5bf4f..34f6b2f9 100644
--- a/src/rlm.zig
+++ b/src/rlm.zig
@@ -22,6 +22,7 @@ const rlm_spec = @import("rlm_spec.zig");
const rlm_mcp = @import("rlm_mcp.zig");
const rlm_reduce = @import("rlm_reduce.zig");
const mcp_shapes = @import("mcp_shapes.zig");
+const read_miss = @import("read_miss.zig");
pub const tool_name = "rlm";
pub const tool_desc = "Programmatic tool calling (RLM + sPTC). Functions ARE this session's tools. Literal read_file/codedb/bash/webfetch/sleep_ms/llm_query/subagent start as the script streams. Binds persist. subagent(\"task\") is sidecar-only (keep the critical-path next step local). Loaded MCP names are host functions after load_tool_schemas; 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.";
@@ -131,18 +132,79 @@ fn speculate(ctx: ToolCtx, arena: Allocator, calls: []const spec_ptc.Call, claim
try uniq.append(arena, c);
}
if (uniq.items.len == 0) return;
- const futs = try arena.alloc(Io.Future(ToolOutput), uniq.items.len);
- const keys = try arena.alloc([]const u8, uniq.items.len);
- for (uniq.items, futs, keys) |c, *fut, *key| {
+ var read_paths: std.ArrayList([]const u8) = .empty;
+ for (uniq.items) |c| {
+ if (std.mem.eql(u8, c.name, "read_file")) {
+ if (read_miss.pathFromArgsJson(c.args_json)) |p| try read_paths.append(arena, p);
+ }
+ }
+ var batch = read_miss.Batch.init(read_paths.items);
+ var wave1: std.ArrayList(spec_ptc.Call) = .empty;
+ var hold: std.ArrayList(spec_ptc.Call) = .empty;
+ for (uniq.items) |c| {
+ if (std.mem.eql(u8, c.name, "read_file")) {
+ if (read_miss.pathFromArgsJson(c.args_json)) |p| {
+ if (ctx.read_miss) |tracker| {
+ switch (batch.classify(tracker, p)) {
+ .refuse => {
+ try claimed.put(try c.key(arena), .{
+ .text = try read_miss.refusalText(ctx.gpa, p),
+ .is_error = true,
+ });
+ continue;
+ },
+ .hold => {
+ try hold.append(arena, c);
+ continue;
+ },
+ .run => {},
+ }
+ }
+ }
+ }
+ try wave1.append(arena, c);
+ }
+ try launchHost(ctx, arena, wave1.items, claimed);
+ if (hold.items.len == 0) return;
+ var wave2: std.ArrayList(spec_ptc.Call) = .empty;
+ for (hold.items) |c| {
+ const p = read_miss.pathFromArgsJson(c.args_json) orelse {
+ try wave2.append(arena, c);
+ continue;
+ };
+ if (ctx.read_miss) |tracker| {
+ if (tracker.shouldRefuse(p)) {
+ try claimed.put(try c.key(arena), .{
+ .text = try read_miss.refusalText(ctx.gpa, p),
+ .is_error = true,
+ });
+ continue;
+ }
+ }
+ try wave2.append(arena, c);
+ }
+ try launchHost(ctx, arena, wave2.items, claimed);
+}
+
+fn launchHost(ctx: ToolCtx, arena: Allocator, calls: []const spec_ptc.Call, claimed: *std.StringHashMap(ToolOutput)) !void {
+ if (calls.len == 0) return;
+ const futs = try arena.alloc(Io.Future(ToolOutput), calls.len);
+ const keys = try arena.alloc([]const u8, calls.len);
+ for (calls, futs, keys) |c, *fut, *key| {
key.* = try c.key(arena);
fut.* = ctx.io.async(runHost, .{ ctx, c });
}
- for (futs, keys) |*fut, key| {
+ for (futs, keys, calls) |*fut, key, c| {
const out = fut.await(ctx.io);
+ if (ctx.read_miss) |tracker| tracker.noteOutput(c.name, pathValue(arena, c.args_json), out.text, out.is_error);
try claimed.put(key, out);
}
}
+fn pathValue(arena: Allocator, args_json: []const u8) Value {
+ return std.json.parseFromSliceLeaky(Value, arena, args_json, .{}) catch .null;
+}
+
fn runHost(ctx: ToolCtx, call: spec_ptc.Call) ToolOutput {
if (std.mem.eql(u8, call.name, "sleep_ms")) return runSleep(ctx, call.args_json);
if (std.mem.eql(u8, call.name, "llm_query")) return rlm_query.run(ctx, call.args_json);
diff --git a/src/tools.zig b/src/tools.zig
index 094782fc..274022ed 100644
--- a/src/tools.zig
+++ b/src/tools.zig
@@ -118,6 +118,7 @@ pub const ToolCtx = struct {
tools_used: ?*ToolSink = null, // the calling agent's tool log (trajectory/process mining)
loop_deadline_ms: ?i64 = null, // the running /loop's wall-clock deadline, copied from the spawning Agent: a child inherits the parent's ABSOLUTE deadline (minus an integration margin), never a slice of it
agent_cwd: ?[]const u8 = null, // #276 P0-1: per-agent isolated worktree (absolute path); null = shared cwd. Set from Agent.agent_cwd, never a process-wide chdir — safe across parallel sibling subagents on the same pool.
+ read_miss: ?*@import("read_miss.zig").Tracker = null, // #1116: turn-scoped consecutive read_file miss latch
};
/// Event JSON for a tool lifecycle hook: {"event","tool","input"[,