graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Keep the per-turn miss stop; drop the uncompilable global latch
Cursor Agenta31c439e7d9d
diff --git a/src/agent.zig b/src/agent.zigindex 3532b14d..ac037649 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -335,7 +335,6 @@ pub const Agent = struct {self.read_miss.reset();self.mcp_context.begin(self.io);@import("named_work.zig").beginTurn(self);- if (!self.sub) @import("read_file_miss.zig").resetTurn();try self.ensureRootTools(self.provider.kind);var task_scope = @import("task_intent.zig").State.begin(self);if (!self.sub and !root_turn_prepared.swap(false, .acq_rel)) @import("cancel_source.zig").clear();diff --git a/src/exec.zig b/src/exec.zigindex 1fc1ee2f..d8df1cba 100644--- a/src/exec.zig+++ b/src/exec.zig@@ -51,7 +51,6 @@ 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 loadedconst read_file = @import("read_file.zig");const read_miss = @import("read_miss.zig");-const read_file_miss = @import("read_file_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@@ -292,13 +291,10 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {// #747: same selected-tree absolute path as edit_file (sessionAbs).const resolved = try codedbpro_paths.sessionAbs(gpa, io, ctx.agent_cwd, path);defer gpa.free(resolved);- if (read_file_miss.stopGuess(io, gpa, path, resolved)) |t| return .{ .text = t, .is_error = true };const outcome = read_file.read(io, gpa, .cwd(), resolved, start_line, end_line, contains) catch |err| {- if (fsErrorText(gpa, .read, path, err)) |t|- return .{ .text = read_file_miss.decorateMiss(gpa, path, err, t), .is_error = true };+ if (fsErrorText(gpa, .read, path, err)) |t| return .{ .text = t, .is_error = true };return err;};- read_file_miss.noteHit(path);return switch (outcome) {.text => |text| .{ .text = text },.truncated => |value| blk: {@@ -439,5 +435,4 @@ test { // main.zig is at the 600-line cap; exec.zig is these modules' importer,_ = @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");- _ = @import("read_file_miss.zig"); // #1116: sequential not-found latch}diff --git a/src/read_file_miss.zig b/src/read_file_miss.zigdeleted file mode 100644index b2c19ad1..00000000--- a/src/read_file_miss.zig+++ /dev/null@@ -1,221 +0,0 @@-//! Consecutive not-found `read_file` guesses. Same-prefix misses or an-//! incrementing numbered filename pattern stop after N misses in one turn-//! (#1116). Bounded lexical repetition (ADR 0065) is prose-only; this gate-//! is the tool-path counterpart. REPL, TUI, and ACP share exec.zig.--const std = @import("std");-const Io = std.Io;-const Allocator = std.mem.Allocator;--pub const miss_limit: u8 = 3;-const max_dir = 256;-const max_slots = 8;--const Slot = struct {- dir: [max_dir]u8 = undefined,- dir_len: u8 = 0,- misses: u8 = 0,- last_number: ?u32 = null,- sequential: u8 = 0,- blocked: bool = false,-- fn dirSlice(self: *const Slot) []const u8 {- return self.dir[0..self.dir_len];- }-};--var mutex: std.Thread.Mutex = .{};-var slots: [max_slots]Slot = @splat(.{});-var used: u8 = 0;-/// Off until a root turn arms the tracker so unrelated unit tests cannot trip it.-var armed: bool = false;--pub fn dirOf(path: []const u8) []const u8 {- const trimmed = std.mem.trimRight(u8, path, "/\\");- if (trimmed.len == 0) return ".";- if (std.fs.path.dirname(trimmed)) |d| {- if (d.len == 0 or std.mem.eql(u8, d, ".")) return ".";- return d;- }- return ".";-}--pub fn leadingNumber(name: []const u8) ?u32 {- if (name.len == 0 or !std.ascii.isDigit(name[0])) return null;- var n: u64 = 0;- for (name) |c| {- if (!std.ascii.isDigit(c)) break;- n = n * 10 + (c - '0');- if (n > 1_000_000) return 1_000_000;- }- return @intCast(n);-}--pub fn resetTurn() void {- mutex.lock();- defer mutex.unlock();- used = 0;- armed = true;-}--pub fn resetForTest() void {- mutex.lock();- defer mutex.unlock();- used = 0;- armed = false;-}--fn sameDir(slot: *const Slot, dir: []const u8) bool {- return std.mem.eql(u8, slot.dirSlice(), dir);-}--fn findSlotLocked(dir: []const u8) ?*Slot {- for (slots[0..used]) |*slot| {- if (sameDir(slot, dir)) return slot;- }- return null;-}--fn takeSlotLocked(dir: []const u8) *Slot {- if (findSlotLocked(dir)) |slot| return slot;- const store = if (dir.len > max_dir) dir[0..max_dir] else dir;- if (used < max_slots) {- const slot = &slots[used];- used += 1;- slot.* = .{};- @memcpy(slot.dir[0..store.len], store);- slot.dir_len = @intCast(store.len);- return slot;- }- const slot = &slots[0];- slot.* = .{};- @memcpy(slot.dir[0..store.len], store);- slot.dir_len = @intCast(store.len);- return slot;-}--pub fn blocked(path: []const u8) bool {- mutex.lock();- defer mutex.unlock();- if (!armed) return false;- const slot = findSlotLocked(dirOf(path)) orelse return false;- return slot.blocked;-}--/// Record a not-found. Returns true once this prefix (or incrementing name-/// pattern) has hit the stop.-pub fn noteMiss(path: []const u8) bool {- mutex.lock();- defer mutex.unlock();- if (!armed) return false;- const dir = dirOf(path);- const slot = takeSlotLocked(dir);- if (slot.misses < 255) slot.misses += 1;- const number = leadingNumber(std.fs.path.basename(path));- if (number) |n| {- if (slot.last_number) |prev| {- if (n > prev and slot.sequential < 255) slot.sequential += 1;- } else slot.sequential = 1;- slot.last_number = n;- }- if (slot.misses >= miss_limit or slot.sequential >= miss_limit) slot.blocked = true;- return slot.blocked;-}--pub fn noteHit(path: []const u8) void {- mutex.lock();- defer mutex.unlock();- if (!armed) return;- const slot = findSlotLocked(dirOf(path)) orelse return;- slot.misses = 0;- slot.sequential = 0;- slot.last_number = null;- slot.blocked = false;-}--pub fn message(gpa: Allocator, path: []const u8) ![]u8 {- const dir = dirOf(path);- if (std.mem.eql(u8, dir, ".")) {- return std.fmt.allocPrint(gpa, "read_file: stopped guessing paths in the working directory after {d} missing files — list the directory with codedb list_dir instead of inventing names", .{miss_limit});- }- return std.fmt.allocPrint(gpa, "read_file: stopped guessing paths under {s}/ after {d} missing files — list the directory with codedb list_dir instead of inventing names", .{ dir, miss_limit });-}--fn exists(io: Io, resolved: []const u8) bool {- const file = Io.Dir.cwd().openFile(io, resolved, .{}) catch return false;- file.close(io);- return true;-}--/// Refuse an invented path under a blocked prefix. A file that actually-/// exists still reads.-pub fn stopGuess(io: Io, gpa: Allocator, path: []const u8, resolved: []const u8) ?[]u8 {- if (!blocked(path)) return null;- if (exists(io, resolved)) return null;- return message(gpa, path) catch null;-}--/// On a not-found, record the miss and replace the error once the prefix stops.-pub fn decorateMiss(gpa: Allocator, path: []const u8, err: anyerror, text: []u8) []u8 {- if (err != error.FileNotFound and err != error.NotDir) return text;- if (!noteMiss(path)) return text;- const stop = message(gpa, path) catch return text;- gpa.free(text);- return stop;-}--test "dirOf and leadingNumber: ADR-shaped guesses" {- try std.testing.expectEqualStrings("docs/adr", dirOf("docs/adr/0365-foo.md"));- try std.testing.expectEqualStrings("docs/adr", dirOf("docs/adr/0397-bar.md"));- try std.testing.expectEqualStrings(".", dirOf("README.md"));- try std.testing.expectEqual(@as(?u32, 365), leadingNumber("0365-foo.md"));- try std.testing.expectEqual(@as(?u32, 397), leadingNumber("0397-bar.md"));- try std.testing.expectEqual(@as(?u32, null), leadingNumber("README.md"));-}--test "#1116: three same-prefix misses stop further invented names" {- resetTurn();- defer resetForTest();- try std.testing.expect(!noteMiss("docs/adr/0365-alpha.md"));- try std.testing.expect(!noteMiss("docs/adr/0366-beta.md"));- try std.testing.expect(noteMiss("docs/adr/0367-gamma.md"));- try std.testing.expect(blocked("docs/adr/0368-delta.md"));- try std.testing.expect(!blocked("src/main.zig"));- const gpa = std.testing.allocator;- const text = try message(gpa, "docs/adr/0368-delta.md");- defer gpa.free(text);- try std.testing.expect(std.mem.indexOf(u8, text, "docs/adr/") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "codedb list_dir") != null);-}--test "#1116: a hit on the prefix clears the stop; another directory is independent" {- resetTurn();- defer resetForTest();- _ = noteMiss("tmp/a.txt");- _ = noteMiss("tmp/b.txt");- try std.testing.expect(!blocked("tmp/c.txt"));- noteHit("tmp/real.txt");- try std.testing.expect(!noteMiss("tmp/again.txt"));- try std.testing.expect(!noteMiss("other/x.txt"));- try std.testing.expect(!noteMiss("other/y.txt"));- try std.testing.expect(noteMiss("other/z.txt"));- try std.testing.expect(blocked("other/w.txt"));- try std.testing.expect(!blocked("tmp/again.txt"));-}--test "#1116: incrementing numbered names under one prefix are a storm" {- resetTurn();- defer resetForTest();- try std.testing.expect(!noteMiss("docs/adr/0365-one.md"));- try std.testing.expect(!noteMiss("docs/adr/0366-two.md"));- try std.testing.expect(noteMiss("docs/adr/0397-reshuffle.md"));- try std.testing.expect(blocked("docs/adr/0398-next.md"));-}--test "#1116: unarmed tracker does not record misses" {- resetForTest();- try std.testing.expect(!noteMiss("docs/adr/0365-alpha.md"));- try std.testing.expect(!noteMiss("docs/adr/0366-beta.md"));- try std.testing.expect(!noteMiss("docs/adr/0367-gamma.md"));- try std.testing.expect(!blocked("docs/adr/0368-delta.md"));-}diff --git a/src/read_file_schema_tests.zig b/src/read_file_schema_tests.zigindex 93bdb119..2a4976de 100644--- a/src/read_file_schema_tests.zig+++ b/src/read_file_schema_tests.zig@@ -9,7 +9,7 @@ const Value = std.json.Value;const exec = @import("exec.zig");const tools = @import("tools.zig");-fn testCtx(client: *std.http.Client, cwd: []const u8) tools.ToolCtx {+fn testCtx(client: *std.http.Client, cwd: []const u8, tracker: ?*@import("read_miss.zig").Tracker) tools.ToolCtx {return .{.gpa = std.testing.allocator,.io = std.testing.io,@@ -20,18 +20,25 @@ fn testCtx(client: *std.http.Client, cwd: []const u8) tools.ToolCtx {.approvals = null,.tracer = null,.agent_cwd = cwd,+ .read_miss = tracker,};}fn readFile(cwd: []const u8, input_json: []const u8) !tools.ToolOutput {+ return readFileTracked(cwd, input_json, null);+}++fn readFileTracked(cwd: []const u8, input_json: []const u8, tracker: ?*@import("read_miss.zig").Tracker) !tools.ToolOutput {var parsed = try std.json.parseFromSlice(Value, std.testing.allocator, input_json, .{});defer parsed.deinit();var client: std.http.Client = undefined;- return exec.execTool(testCtx(&client, cwd), .{+ const out = exec.execTool(testCtx(&client, cwd, tracker), .{.id = "call_1",.name = "read_file",.input = parsed.value,});+ if (tracker) |t| t.noteOutput("read_file", parsed.value, out.text, out.is_error);+ return out;}test "read_file (#761): a call with only path is a whole-file read" {@@ -72,9 +79,7 @@ test "#1116: sequential missing reads under one prefix stop and point at list_diif (builtin.os.tag == .windows) return error.SkipZigTest;const gpa = std.testing.allocator;const io = std.testing.io;- const miss = @import("read_file_miss.zig");- miss.resetTurn();- defer miss.resetForTest();+ var tracker: @import("read_miss.zig").Tracker = .{};var tmp = std.testing.tmpDir(.{});defer tmp.cleanup();try tmp.dir.writeFile(io, .{ .sub_path = "real.txt", .data = "kept\n" });@@ -82,33 +87,33 @@ test "#1116: sequential missing reads under one prefix stop and point at list_diconst n = try tmp.dir.realPath(io, &real_buf);const cwd = real_buf[0..n];- const first = try readFile(cwd, "{\"path\":\"docs/adr/0365-one.md\"}");+ const first = try readFileTracked(cwd, "{\"path\":\"docs/adr/0365-one.md\"}", &tracker);defer gpa.free(first.text);try std.testing.expect(first.is_error);try std.testing.expect(std.mem.indexOf(u8, first.text, "does not exist") != null);- const second = try readFile(cwd, "{\"path\":\"docs/adr/0366-two.md\"}");+ const second = try readFileTracked(cwd, "{\"path\":\"docs/adr/0366-two.md\"}", &tracker);defer gpa.free(second.text);try std.testing.expect(second.is_error);try std.testing.expect(std.mem.indexOf(u8, second.text, "does not exist") != null);- const third = try readFile(cwd, "{\"path\":\"docs/adr/0367-three.md\"}");+ const third = try readFileTracked(cwd, "{\"path\":\"docs/adr/0367-three.md\"}", &tracker);defer gpa.free(third.text);try std.testing.expect(third.is_error);- try std.testing.expect(std.mem.indexOf(u8, third.text, "codedb list_dir") != null);- try std.testing.expect(std.mem.indexOf(u8, third.text, "stopped guessing") != null);+ try std.testing.expect(std.mem.indexOf(u8, third.text, "does not exist") != null);- const fourth = try readFile(cwd, "{\"path\":\"docs/adr/0397-reshuffle.md\"}");+ const fourth = try readFileTracked(cwd, "{\"path\":\"docs/adr/0397-reshuffle.md\"}", &tracker);defer gpa.free(fourth.text);try std.testing.expect(fourth.is_error);- try std.testing.expect(std.mem.indexOf(u8, fourth.text, "stopped guessing") != null);+ try std.testing.expect(std.mem.indexOf(u8, fourth.text, "refused") != null);+ try std.testing.expect(std.mem.indexOf(u8, fourth.text, "codedb list_dir") != null);- const other = try readFile(cwd, "{\"path\":\"missing-elsewhere.txt\"}");+ const other = try readFileTracked(cwd, "{\"path\":\"missing-elsewhere.txt\"}", &tracker);defer gpa.free(other.text);try std.testing.expect(other.is_error);try std.testing.expect(std.mem.indexOf(u8, other.text, "does not exist") != null);- const kept = try readFile(cwd, "{\"path\":\"real.txt\"}");+ const kept = try readFileTracked(cwd, "{\"path\":\"real.txt\"}", &tracker);defer gpa.free(kept.text);try std.testing.expect(!kept.is_error);try std.testing.expectEqualStrings("kept\n", kept.text);diff --git a/src/rlm_mcp.zig b/src/rlm_mcp.zigindex 02f7bccc..432c38df 100644--- a/src/rlm_mcp.zig+++ b/src/rlm_mcp.zig@@ -31,15 +31,15 @@ pub fn looksMcp(name: []const u8) bool {pub fn isNativeHost(name: []const u8) bool {if (@import("shell_tool.zig").isFamily(name)) return true;const names = [_][]const u8{- "read_file", "edit_file", "write_file",- "codedb", "webfetch", "sleep_ms",- "llm_query", "subagent", "skill",- "ask_user", "todo_write", "todo_read",- "eval", "note_constraint", "attempt_completion",- "load_tool_schemas", "clock_sleep", "workflow",- "agent_output", "peer_message", "workspace",- "imagegen", "learn_candidate", "rlm",- "read_tool_result", "render_html", "mcp_search_tools",+ "read_file", "edit_file", "write_file",+ "codedb", "webfetch", "sleep_ms",+ "llm_query", "subagent", "skill",+ "ask_user", "todo_write", "todo_read",+ "eval", "note_constraint", "attempt_completion",+ "load_tool_schemas", "clock_sleep", "workflow",+ "agent_output", "peer_message", "workspace",+ "imagegen", "learn_candidate", "rlm",+ "read_tool_result", "render_html", "mcp_search_tools","mcp_select_tool",};for (names) |n| {@@ -312,7 +312,7 @@ test "#1016: native read_file is not remapped to an unloaded MCP short name" {var schema: std.json.ObjectMap = .empty;try schema.put(arena, "type", .{ .string = "object" });try schema.put(arena, "properties", .{ .object = props });- const colliding = [_]mcp.Tool{.{+ var colliding = [_]mcp.Tool{.{.server_index = 0,.original_name = "read_file",.qualified_name = "mcp__wiki__read_file",@@ -321,7 +321,7 @@ test "#1016: native read_file is not remapped to an unloaded MCP short name" {}};var registry = mcp.Registry.empty(gpa, io);defer registry.deinit();- registry.tools = &colliding;+ registry.tools = colliding[0..];var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };defer dummy_client.deinit();const ctx: ToolCtx = .{diff --git a/src/rlm_tests.zig b/src/rlm_tests.zigindex 9105ce3d..195d86a2 100644--- a/src/rlm_tests.zig+++ b/src/rlm_tests.zig@@ -419,7 +419,7 @@ test "#1016: literal read_file stays native when an MCP short name collides" {var schema: std.json.ObjectMap = .empty;try schema.put(arena, "type", .{ .string = "object" });try schema.put(arena, "properties", .{ .object = props });- const colliding = [_]mcp.Tool{.{+ var colliding = [_]mcp.Tool{.{.server_index = 0,.original_name = "read_file",.qualified_name = "mcp__wiki__read_file",@@ -428,7 +428,7 @@ test "#1016: literal read_file stays native when an MCP short name collides" {}};var registry = mcp.Registry.empty(gpa, io);defer registry.deinit();- registry.tools = &colliding;+ registry.tools = colliding[0..];var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };defer dummy_client.deinit();const saved = rlm.available;