graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(handle): notable lines on first spill, whole-line query (#578)
Rach06cf903664eb
diff --git a/docs/adr/0012-overflow-handles-named-limits-extra-roots.md b/docs/adr/0012-overflow-handles-named-limits-extra-roots.mdindex 4b78f040..cf91b39e 100644--- a/docs/adr/0012-overflow-handles-named-limits-extra-roots.md+++ b/docs/adr/0012-overflow-handles-named-limits-extra-roots.md@@ -18,7 +18,8 @@ load, and extra roots that are not a `workspace` cwd switch.- A result over the handle threshold is stored as `.graff/tool-results/tr_N.txt`.The model pages it with `read_tool_result` (`offset`/`limit` or `query`).- The full blob does not re-enter history.+ `query` returns the whole matching line. The first payload also includes a+ bounded excerpt of error-shaped lines. The full blob does not re-enter history.- `--context-limit name=N` (and `GRAFF_CONTEXT_LIMIT`) caps`skill_catalog_bytes`, `mcp_schema_bytes`, and `agents_md_bytes`. `apply`never grows. Defaults 4 KiB / 8 KiB / 8 KiB.@@ -30,7 +31,10 @@ load, and extra roots that are not a `workspace` cwd switch.## Consequences-- One fat bash/codedb hit costs one preview plus later slices.+- One fat bash/codedb hit costs one preview plus later slices. The first+ payload includes a bounded excerpt of error-shaped lines (fail / error /+ panic / …) so "what broke?" does not need a pager turn; `query` returns+ the whole matching line, not an 80-byte pad.- Named caps are prompt-cache-stable: shrinking a listing does not rewritetool names or pin policy.- Extra-root absolute paths become `confinedPath` when they stay under adiff --git a/scripts/eval/live-ab/run_eval.py b/scripts/eval/live-ab/run_eval.pyindex 8acb2a72..a7aa437e 100644--- a/scripts/eval/live-ab/run_eval.py+++ b/scripts/eval/live-ab/run_eval.py@@ -105,7 +105,7 @@ TASKS = {}USAGE_RE = re.compile(- r"\[usage\]\s+(\d+)\s+api call\(s\)\s+.\s+(\d+)\s+in\s+\((\d+)\s+cached\)\s*\+\s*(\d+)\s+out tokens"+ r"\[usage\]\s+(\d+)\s+api call\(s\)\s+.\s+(\d+)\s+in\s+\((\d+)\s+cached[^)]*\)\s*\+\s*(\d+)\s+out tokens")diff --git a/src/handle_preview.zig b/src/handle_preview.zignew file mode 100644index 00000000..d1653062--- /dev/null+++ b/src/handle_preview.zig@@ -0,0 +1,109 @@+//! Notable-line excerpt for a #440 handle preview.+//!+//! The first payload a spill returns is the HEAD of the result. A needle in+//! the middle (a single FAILED line in a 168 KiB log) is invisible there, so+//! the model pays a follow-up page. This file pulls a bounded set of+//! error-shaped lines into that first payload so the common "what broke?"+//! question does not need the pager. The full bytes still live only on disk.++const std = @import("std");+const Allocator = std.mem.Allocator;++/// Substrings that mark a line worth surfacing. Matched case-insensitively+/// as a literal, so `fail` hits `FAILED` and `error` hits `level=ERROR`.+pub const notable_needles = [_][]const u8{+ "error",+ "fail",+ "exception",+ "panic",+ "fatal",+ "traceback",+};++pub const max_notable_lines: usize = 8;+pub const max_notable_bytes: usize = 2048;++/// Inclusive-start, exclusive-end of the line that contains `at`.+pub fn lineBounds(text: []const u8, at: usize) struct { lo: usize, hi: usize } {+ const pos = @min(at, text.len);+ const lo = if (std.mem.lastIndexOfScalar(u8, text[0..pos], '\n')) |n| n + 1 else 0;+ const hi = if (std.mem.indexOfScalar(u8, text[pos..], '\n')) |n| pos + n else text.len;+ return .{ .lo = lo, .hi = hi };+}++pub fn indexOfIgnoreCase(hay: []const u8, needle: []const u8) ?usize {+ if (needle.len == 0 or needle.len > hay.len) return null;+ var i: usize = 0;+ while (i + needle.len <= hay.len) : (i += 1) {+ if (std.ascii.eqlIgnoreCase(hay[i..][0..needle.len], needle)) return i;+ }+ return null;+}++fn lineIsNotable(line: []const u8) bool {+ for (notable_needles) |n| {+ if (indexOfIgnoreCase(line, n) != null) return true;+ }+ return false;+}++/// Lines after `skip_before` that look like failures, capped. Empty when+/// nothing qualifies or `budget` cannot hold the header plus one line.+pub fn notableExcerpt(arena: Allocator, text: []const u8, skip_before: usize, budget: usize) ![]const u8 {+ if (budget < 40 or skip_before >= text.len) return "";+ var lines: std.ArrayList([]const u8) = .empty;+ var i = skip_before;+ if (i > 0 and text[i - 1] != '\n') {+ if (std.mem.indexOfScalar(u8, text[i..], '\n')) |n| i += n + 1 else return "";+ }+ while (i < text.len and lines.items.len < max_notable_lines) {+ const nl = std.mem.indexOfScalar(u8, text[i..], '\n');+ const end = if (nl) |n| i + n else text.len;+ const line = text[i..end];+ if (lineIsNotable(line)) try lines.append(arena, line);+ i = if (nl) |n| i + n + 1 else text.len;+ }+ if (lines.items.len == 0) return "";++ var body: std.Io.Writer.Allocating = .init(arena);+ try body.writer.print("[notable lines, {d} match", .{lines.items.len});+ if (lines.items.len != 1) try body.writer.writeByte('e');+ try body.writer.writeAll("]\n");+ for (lines.items) |line| {+ try body.writer.writeAll(line);+ try body.writer.writeByte('\n');+ }+ const out = body.writer.buffered();+ if (out.len > budget) return "";+ return out;+}++test "lineBounds includes the whole line, not an 80-byte pad" {+ const text = "aaa\nrequest_id=req-1 status=FAILED reason=boom\nzzz";+ const at = std.mem.indexOf(u8, text, "FAILED").?;+ const b = lineBounds(text, at);+ try std.testing.expectEqualStrings("request_id=req-1 status=FAILED reason=boom", text[b.lo..b.hi]);+}++test "notableExcerpt pulls a FAILED line that sits past the head" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const head = try a.alloc(u8, 600);+ @memset(head, 'x');+ head[head.len - 1] = '\n';+ const fail = "request_id=req-8c41de07 status=FAILED reason=undefined_symbol\n";+ const text = try std.fmt.allocPrint(a, "{s}{s}tail\n", .{ head, fail });+ const excerpt = try notableExcerpt(a, text, head.len, 512);+ try std.testing.expect(std.mem.indexOf(u8, excerpt, "req-8c41de07") != null);+ try std.testing.expect(std.mem.indexOf(u8, excerpt, "FAILED") != null);+ try std.testing.expect(std.mem.indexOf(u8, excerpt, "1 match") != null);+}++test "notableExcerpt stays empty when nothing looks like a failure" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const excerpt = try notableExcerpt(a, "cache=miss status=OK\nall good\n", 0, 512);+ try std.testing.expectEqualStrings("", excerpt);+}diff --git a/src/result_read.zig b/src/result_read.zigindex 6c2a76b4..5ae07e26 100644--- a/src/result_read.zig+++ b/src/result_read.zig@@ -22,7 +22,8 @@ pub const tool_schema =pub const default_limit: usize = 4096;pub const max_limit: usize = 16384;const max_hits: usize = 8;-const window_pad: usize = 80;+const handle_preview = @import("handle_preview.zig");+const max_hit_bytes: usize = 1024;/// Parse `tr_12` (or `TR_12`) into the sequence number. null when the token/// is not a handle id.@@ -59,9 +60,12 @@ fn search(arena: std.mem.Allocator, text: []const u8, query: []const u8) ![]consconst rest = text[i..];const at = std.mem.indexOf(u8, rest, query) orelse break;const abs = i + at;- const lo = abs -| window_pad;- const hi = @min(text.len, abs + query.len + window_pad);- try aw.writer.print("hit {d} at byte {d}:\n{s}\n---\n", .{ hits + 1, abs, text[lo..hi] });+ // Whole matching line, not an 80-byte pad: a long `status=FAILED`+ // line has request_id before the match, and a pad cut it off.+ const b = handle_preview.lineBounds(text, abs);+ const span = text[b.lo..b.hi];+ const shown = if (span.len > max_hit_bytes) span[0..max_hit_bytes] else span;+ try aw.writer.print("hit {d} at byte {d}:\n{s}\n---\n", .{ hits + 1, abs, shown });hits += 1;i = abs + query.len;}@@ -149,3 +153,13 @@ test "byte-range and query stay bounded" {try std.testing.expect(std.mem.indexOf(u8, hits, "2 hit(s)") != null);try std.testing.expectError(error.EmptyQuery, search(a, big, ""));}++test "query returns the whole matching line, including bytes before the needle" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const line = "request_id=req-8c41de07 stage=link status=FAILED reason=undefined_symbol";+ const hits = try search(a, "ok\n" ++ line ++ "\nzz", "FAILED");+ try std.testing.expect(std.mem.indexOf(u8, hits, "req-8c41de07") != null);+ try std.testing.expect(std.mem.indexOf(u8, hits, "1 hit(s)") != null);+}diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex c3090093..6a2bcd4e 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -128,6 +128,7 @@ const peer_inbox = @import("peer_inbox.zig"); // Claude-style list/inbox pullconst peer_target = @import("peer_target.zig"); // exact DM / goal targetingconst workspace_switch = @import("workspace_switch.zig"); // ADR 0006 mid-session worktree switchconst result_read = @import("result_read.zig"); // overflow handle pager+const handle_preview = @import("handle_preview.zig"); // notable lines on first spillconst context_limits = @import("context_limits.zig"); // named prefix capsconst workspace_roots = @import("workspace_roots.zig"); // --add-dir extra rootsconst mcp_select = @import("mcp_select.zig"); // search-then-select MCPdiff --git a/src/tool_handle.zig b/src/tool_handle.zigindex 90c5d516..63678def 100644--- a/src/tool_handle.zig+++ b/src/tool_handle.zig@@ -28,6 +28,7 @@ const Io = std.Io;const Allocator = std.mem.Allocator;const util = @import("util.zig");+const handle_preview = @import("handle_preview.zig");/// Where a handle's bytes live. Run-scoped rather than session-scoped: a/// subagent has no durable session (that is why the #409 spill skips it) but@@ -136,12 +137,24 @@ pub fn forResult(gpa: Allocator, arena: Allocator, target: Target, text: []const// A marker that cannot fit under the threshold replaces the preview rather// than growing past it: the pointer matters more than the head.if (marker.len + 2 >= threshold) return .{ .text = marker, .path = path, .bytes = text.len };- const head = util.utf8Prefix(text, threshold - (marker.len + 2));- return .{+ // Notable lines past the head (FAILED / ERROR / panic) ride the first+ // payload so a fat log does not cost a pager turn for "what broke?".+ const room = threshold - (marker.len + 2);+ const excerpt_budget = @min(handle_preview.max_notable_bytes, room / 4);+ const skip = if (room > excerpt_budget) room - excerpt_budget else room;+ const excerpt = handle_preview.notableExcerpt(arena, text, skip, excerpt_budget) catch "";+ const used = marker.len + excerpt.len + (if (excerpt.len == 0) @as(usize, 2) else 4);+ const head = util.utf8Prefix(text, if (used < threshold) threshold - used else 0);+ if (excerpt.len == 0) return .{.text = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ head, marker }),.path = path,.bytes = text.len,};+ return .{+ .text = try std.fmt.allocPrint(arena, "{s}\n\n{s}\n{s}", .{ head, excerpt, marker }),+ .path = path,+ .bytes = text.len,+ };}/// #541: the once-per-agent protocol lesson. The marker on every handle@@ -388,6 +401,27 @@ test "#440: over the threshold returns preview + handle path + byte count + shaptry std.testing.expect(std.mem.startsWith(u8, r.text, big[0..64]));}+test "#440: a FAILED line past the head rides the first handle payload" {+ var tmp = std.testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ resetForTest();+ defer resetForTest();++ const fail = "request_id=req-8c41de07 status=FAILED reason=undefined_symbol\n";+ const big = try a.alloc(u8, 40_000);+ @memset(big, 'x');+ for (0..399) |i| big[(i + 1) * 100 - 1] = '\n';+ @memcpy(big[38_000..][0..fail.len], fail);++ const r = try forResult(std.testing.allocator, a, testTarget(&tmp), big, 4096);+ try std.testing.expect(r.text.len <= 4096);+ try std.testing.expect(std.mem.indexOf(u8, r.text, "req-8c41de07") != null);+ try std.testing.expect(std.mem.indexOf(u8, r.text, "notable lines") != null);+}+test "#440: the threshold is a knob — the same payload is bounded by whatever it is set to" {var tmp = std.testing.tmpDir(.{ .iterate = true });defer tmp.cleanup();