graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(tools): target exact-key file lookups
Rach Pradhanffa89853af5b
diff --git a/docs/releases/v0.0.248.md b/docs/releases/v0.0.248.mdnew file mode 100644index 00000000..28f87d55--- /dev/null+++ b/docs/releases/v0.0.248.md@@ -0,0 +1,9 @@+# v0.0.248 (2026-08-11)++A focused exact-key lookup latency hotfix.++- **One targeted file read instead of a whole-file loop.** `read_file` now accepts an optional `contains` literal and returns only matching numbered lines, so keyed lookups can avoid reading a large file and then searching it in a later model round.+- **Fewer provider round trips.** The root policy steers read-only exact-key requests to one targeted read while preserving byte-exact reads before edits. In five matched GPT-5.6 Luna runs, Graff moved from three model calls and two tools to two model calls and one tool, reducing its measured median from 10.10s to 5.12s.+- **Bounded and regression-tested.** Literal matching streams through the file, keeps output under the existing read cap, rejects incompatible range/compact combinations, and has both unit and model-backed behavior coverage.++No GUI or general REPL behavior changes are included.diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex a707a02b..7d337f9f 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -48,3 +48,4 @@{"id": "peer-checkpoint-blocks-file-writes", "why": "#469: the once-per-peer checkpoint must guard the files themselves, not only git - the incident's other vector was one session moving/editing files the other had open. A live peer makes the first write_file come back un-executed, and the identical retry lands.", "live_peer": true, "args": [], "prompt": "create notes.txt with hello in it", "script": [{"tool": "write_file", "arguments": {"path": "notes.txt", "content": "hello"}}, {"tool": "write_file", "arguments": {"path": "notes.txt", "content": "hello"}}, {"text": "created, after the checkpoint told me about the peer"}], "assert": [{"event": {"type": "tool_call", "name": "write_file"}}, {"request_contains": {"index": 1, "text": "shared-tree checkpoint (#469)"}}, {"request_contains": {"index": 1, "text": "another graff session already owns this worktree"}}]}{"id": "peer-message-all-broadcasts-device-wide", "why": "#469: session 'all' must reach every live session on the device, not only same-folder peers. The regression is a broadcast silently scoped to one worktree.", "live_peer": true, "args": [], "prompt": "tell everyone the freeze starts at five", "script": [{"tool": "peer_message", "arguments": {"session": "all", "text": "freeze starts at five"}}, {"text": "broadcast sent"}], "assert": [{"event": {"type": "tool_call", "name": "peer_message"}}, {"request_contains": {"index": 1, "text": "device-wide room"}}]}{"id": "peer-awareness-precedes-first-reply", "why": "#469: the model can only auto-decide to coordinate with sessions it knows about - with a live peer, the FIRST request must already carry the presence note (who else is live, with goals), before any collision forces the issue.", "live_peer": true, "args": [], "prompt": "just checking in", "script": [{"text": "acknowledged"}], "assert": [{"request_contains": {"index": 0, "text": "other live graff session"}}, {"request_contains": {"index": 0, "text": "peer_message"}}]}+{"id": "readonly-exact-key-prefers-one-search", "why": "Named-file guidance forced a whole-file read before an exact-key search, adding avoidable context and a provider round trip. A read-only keyed lookup should call read_file once with contains set to the exact key, answer from the numbered match, and never read the entire file.", "args": [], "workspace_seed": {"catalog.py": "SKU0001 = {'price': 100, 'stock': 1}\nSKU0002 = {'price': 200, 'stock': 2}\nSKU0420 = {'price': 31415, 'stock': 27}\nSKU0900 = {'price': 900, 'stock': 9}\n"}, "prompt": "Read catalog.py without editing it. Find SKU0420. Reply with exactly one line in the format SKU0420|price=<price>|stock=<stock> and nothing else.", "script": [{"tool": "read_file", "arguments": {"path": "catalog.py", "contains": "SKU0420"}}, {"text": "SKU0420|price=31415|stock=27"}], "assert": [{"request_contains": {"index": 0, "text": "contains set to the exact key"}}, {"event": {"type": "tool_call", "name": "read_file"}}, {"events_at_most": {"match": {"type": "tool_call"}, "count": 1}}, {"final_text_contains": "SKU0420|price=31415|stock=27"}]}diff --git a/src/exec.zig b/src/exec.zigindex 26860f4e..8f73b76e 100644--- a/src/exec.zig+++ b/src/exec.zig@@ -395,7 +395,12 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {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");+ const contains = strField(input, "contains");const want_compact = tools.json_args.flag(input, "compact");+ if (contains) |needle| {+ if (needle.len == 0) return .{ .text = try gpa.dupe(u8, "read_file: contains must not be empty"), .is_error = true };+ if (start_line != null or end_line != null or want_compact) return .{ .text = try gpa.dupe(u8, "read_file: contains cannot be combined with start_line, end_line, or compact"), .is_error = true };+ }// #66: opt-in compact view routes to `codedb read <path> [-L a-b] --compact`// when codedb is present and this file is indexed. Lossy (strips comments/// blanks, shows line numbers) so it is NEVER the default and is labeled@@ -415,7 +420,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {// absolute path.const resolved: []const u8 = if (ctx.agent_cwd) |base| try std.fmt.allocPrint(gpa, "{s}/{s}", .{ base, path }) else path;defer if (ctx.agent_cwd != null) gpa.free(resolved);- const outcome = read_file.read(io, gpa, .cwd(), resolved, start_line, end_line) catch |err| {+ 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 = t, .is_error = true };return err;};@@ -446,6 +451,9 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {.text = try std.fmt.allocPrint(gpa, "start_line {?d} is past the end of {s}", .{ start_line, path }),.is_error = true,},+ .no_match => .{+ .text = try std.fmt.allocPrint(gpa, "No lines in {s} contain the exact literal {s}.", .{ path, contains orelse "" }),+ },};}if (std.mem.eql(u8, call.name, "codedb")) {diff --git a/src/prompt_snapshot_tests.zig b/src/prompt_snapshot_tests.zigindex b38b54bf..2bd68780 100644--- a/src/prompt_snapshot_tests.zig+++ b/src/prompt_snapshot_tests.zig@@ -37,7 +37,9 @@ const golden_full_prompt =\\say so and finish the task with what is here.\\read_file before editing; prefer\\edit_file for changes to existing files and write_file only for new- \\files or full rewrites. To navigate code — finding symbols, callers,+ \\files or full rewrites. 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. 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\\is declined, try another approach or ask. Native file tools deliberately@@ -107,9 +109,8 @@ const golden_full_prompt =\\chasing gone. Never stop at a plan, a half-applied edit, or an untested\\guess, and never leave the last step for the user. If a real ambiguity\\blocks you, ask; otherwise decide and go. When a task names files or- \\failing tests, start there — read them before any search, and search- \\only when what you need is not where you looked; probing the index- \\first is a dice roll that makes every run of the same task different.+ \\failing tests, use the named target directly instead of probing unrelated+ \\indexes first; that dice roll makes every run of the same task different.\\Match the verification to the\\ask: make the requested thing work and prove it — do not add unrequested\\tests, coverage, or review passes; thoroughness past the ask is turns,diff --git a/src/prompt_text.zig b/src/prompt_text.zigindex 77445478..54bba8c5 100644--- a/src/prompt_text.zig+++ b/src/prompt_text.zig@@ -34,7 +34,9 @@ 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. To navigate code — finding symbols, callers,+ \\files or full rewrites. 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. 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\\is declined, try another approach or ask. Native file tools deliberately@@ -151,9 +153,8 @@ pub const work_note =\\chasing gone. Never stop at a plan, a half-applied edit, or an untested\\guess, and never leave the last step for the user. If a real ambiguity\\blocks you, ask; otherwise decide and go. When a task names files or- \\failing tests, start there — read them before any search, and search- \\only when what you need is not where you looked; probing the index- \\first is a dice roll that makes every run of the same task different.+ \\failing tests, use the named target directly instead of probing unrelated+ \\indexes first; that dice roll makes every run of the same task different.\\Match the verification to the\\ask: make the requested thing work and prove it — do not add unrequested\\tests, coverage, or review passes; thoroughness past the ask is turns,diff --git a/src/read_file.zig b/src/read_file.zigindex 5868661a..3304e962 100644--- a/src/read_file.zig+++ b/src/read_file.zig@@ -22,6 +22,7 @@ pub const Result = union(enum) {binary: u64,range_too_large,start_past_end,+ no_match,};fn normalizedBounds(start_opt: ?i64, end_opt: ?i64) ?struct { start: usize, end: usize } {@@ -69,9 +70,51 @@ fn readWindow(io: Io, gpa: Allocator, file: Io.File, size: u64, start_opt: ?i64,return .{ .text = try output.toOwnedSlice(gpa) };}-/// Reads from `dir` without ever retaining more than `max_bytes`. The caller-/// owns `text` and `truncated.head` results.-pub fn read(io: Io, gpa: Allocator, dir: Io.Dir, path: []const u8, start_line: ?i64, end_line: ?i64) !Result {+fn appendLiteralMatch(gpa: Allocator, output: *std.ArrayList(u8), line_bytes: []const u8, line_number: usize, needle: []const u8) !bool {+ if (std.mem.indexOf(u8, line_bytes, needle) == null) return true;+ var prefix_buffer: [48]u8 = undefined;+ const prefix = std.fmt.bufPrint(&prefix_buffer, "{d}: ", .{line_number}) catch return false;+ const needed = prefix.len + line_bytes.len;+ if (needed > max_bytes or output.items.len > max_bytes - needed) return false;+ try output.appendSlice(gpa, prefix);+ try output.appendSlice(gpa, line_bytes);+ return true;+}++fn readMatches(io: Io, gpa: Allocator, file: Io.File, size: u64, needle: []const u8) !Result {+ if (needle.len == 0 or size == 0) return .no_match;++ var output: std.ArrayList(u8) = .empty;+ defer output.deinit(gpa);+ var current_line: std.ArrayList(u8) = .empty;+ defer current_line.deinit(gpa);+ var buffer: [16 * 1024]u8 = undefined;+ var offset: u64 = 0;+ var line_number: usize = 1;++ while (offset < size) {+ const want: usize = @intCast(@min(@as(u64, buffer.len), size - offset));+ const got = try file.readPositionalAll(io, buffer[0..want], offset);+ if (got != want) return error.UnexpectedEndOfFile;+ offset += got;+ for (buffer[0..got]) |byte| {+ if (current_line.items.len == max_bytes) return .range_too_large;+ try current_line.append(gpa, byte);+ if (byte != '\n') continue;+ if (!try appendLiteralMatch(gpa, &output, current_line.items, line_number, needle)) return .range_too_large;+ current_line.clearRetainingCapacity();+ line_number +|= 1;+ }+ }+ if (current_line.items.len > 0 and !try appendLiteralMatch(gpa, &output, current_line.items, line_number, needle))+ return .range_too_large;+ if (output.items.len == 0) return .no_match;+ return .{ .text = try output.toOwnedSlice(gpa) };+}++/// Reads from `dir` with bounded buffers. The caller owns `text` and+/// `truncated.head` results.+pub fn read(io: Io, gpa: Allocator, dir: Io.Dir, path: []const u8, start_line: ?i64, end_line: ?i64, contains: ?[]const u8) !Result {const file = try dir.openFile(io, path, .{});defer file.close(io);const before = try file.stat(io);@@ -82,6 +125,7 @@ pub fn read(io: Io, gpa: Allocator, dir: Io.Dir, path: []const u8, start_line: ?const prefix = try readPrefix(io, file, before.size, &prefix_buffer);if (std.mem.indexOfScalar(u8, prefix, 0) != null) return .{ .binary = before.size };+ if (contains) |needle| return readMatches(io, gpa, file, before.size, needle);if (start_line != null or end_line != null)return readWindow(io, gpa, file, before.size, start_line, end_line);@@ -108,7 +152,7 @@ test "large whole reads preview while line windows stream byte-exactly" {@memcpy(large[large.len - 12 ..], "target\nlast\n");try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "large.txt", .data = large });- const whole = try read(std.testing.io, gpa, tmp.dir, "large.txt", null, null);+ const whole = try read(std.testing.io, gpa, tmp.dir, "large.txt", null, null, null);switch (whole) {.truncated => |value| {defer gpa.free(value.head);@@ -118,7 +162,7 @@ test "large whole reads preview while line windows stream byte-exactly" {else => return error.TestExpectedTruncated,}- const window = try read(std.testing.io, gpa, tmp.dir, "large.txt", 2, 3);+ const window = try read(std.testing.io, gpa, tmp.dir, "large.txt", 2, 3, null);switch (window) {.text => |text| {defer gpa.free(text);@@ -142,7 +186,7 @@ test "streamed windows preserve the original line-slice semantics" {.{ .start = 99, .end = 100, .expected = null },};for (cases) |case| {- const outcome = try read(std.testing.io, gpa, tmp.dir, "small.txt", case.start, case.end);+ const outcome = try read(std.testing.io, gpa, tmp.dir, "small.txt", case.start, case.end, null);if (case.expected) |expected| switch (outcome) {.text => |text| {defer gpa.free(text);@@ -153,7 +197,7 @@ test "streamed windows preserve the original line-slice semantics" {}try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "unterminated.txt", .data = "x\ny" });- const final_line = try read(std.testing.io, gpa, tmp.dir, "unterminated.txt", 2, 2);+ const final_line = try read(std.testing.io, gpa, tmp.dir, "unterminated.txt", 2, 2, null);switch (final_line) {.text => |text| {defer gpa.free(text);@@ -171,5 +215,22 @@ test "oversized requested line fails bounded instead of StreamTooLong" {defer gpa.free(large);@memset(large, 'x');try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "one-line.txt", .data = large });- try std.testing.expect((try read(std.testing.io, gpa, tmp.dir, "one-line.txt", 1, 1)) == .range_too_large);+ try std.testing.expect((try read(std.testing.io, gpa, tmp.dir, "one-line.txt", 1, 1, null)) == .range_too_large);+}++test "literal matching streams only numbered target lines" {+ const gpa = std.testing.allocator;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "catalog.txt", .data = "alpha\nSKU0420 price=685 stock=105\nomega SKU0420\nlast" });++ const matches = try read(std.testing.io, gpa, tmp.dir, "catalog.txt", null, null, "SKU0420");+ switch (matches) {+ .text => |text| {+ defer gpa.free(text);+ try std.testing.expectEqualStrings("2: SKU0420 price=685 stock=105\n3: omega SKU0420\n", text);+ },+ else => return error.TestExpectedText,+ }+ try std.testing.expect((try read(std.testing.io, gpa, tmp.dir, "catalog.txt", null, null, "missing")) == .no_match);}diff --git a/src/schema.zig b/src/schema.zigindex 72e5d202..23847bbc 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -75,9 +75,9 @@ const base_specs = [_]ToolSpec{},.{.name = "read_file",- .desc = "Read a UTF-8 text file. Call this before editing any file. Whole-file reads over 256 KiB return a short preview; pass start_line/end_line (1-based, inclusive) for a byte-exact window from any size file.",+ .desc = "Read a UTF-8 text file. Call this before editing any file. For a read-only exact-key lookup, pass contains to return only matching numbered lines instead of the whole file. Whole-file reads over 256 KiB return a short preview; pass start_line/end_line (1-based, inclusive) for a byte-exact window from any size file.",.schema =- \\{"type": "object", "properties": {"path": {"type": "string", "description": "File path, relative to the working directory"}, "start_line": {"type": "integer", "description": "Optional 1-based first line to return (byte-exact slice; omit for whole file)"}, "end_line": {"type": "integer", "description": "Optional 1-based last line to return, inclusive"}, "compact": {"type": "boolean", "description": "Exploratory only: return a comment/blank-stripped view via codedb (line numbers shown). NEVER use before an edit — re-read without compact to copy exact text."}}, "required": ["path"]}+ \\{"type": "object", "properties": {"path": {"type": "string", "description": "File path, relative to the working directory"}, "start_line": {"type": "integer", "description": "Optional 1-based first line to return (byte-exact slice; omit for whole file)"}, "end_line": {"type": "integer", "description": "Optional 1-based last line to return, inclusive"}, "contains": {"type": "string", "description": "Optional exact literal; return only matching lines with line numbers instead of the whole file. Prefer this for exact-key read-only lookups. Cannot combine with start_line, end_line, or compact."}, "compact": {"type": "boolean", "description": "Exploratory only: return a comment/blank-stripped view via codedb (line numbers shown). NEVER use before an edit — re-read without compact to copy exact text."}}, "required": ["path"]},},.{