Skip to content

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

Python

feat(tools): tool results become handles above a size threshold

Rach Pradhan5fbe44fedf2c
diff --git a/README.md b/README.md
index 1c8c7221..4f735ba8 100644
--- a/README.md
+++ b/README.md
@@ -183,7 +183,7 @@ change is held to live in [architecture.md](architecture.md):
| cold start | **~1.8 ms** |
| full agentic turn | **12 MB** peak RSS, ~4% CPU (network-bound) |
| 8 parallel subagents | **+0.4 MB each** (15 MB total) |
-| tool output into history | hard 128 KB cap: a 500 MB python child process never touches the harness's footprint |
+| tool output into history | one 4 KB handle, whatever the result's size: a 500 MB python child process never touches the harness's footprint |
Benchmarked against the Rust codegraff ([justrach/codegraff](https://github.com/justrach/codegraff),
39 MB binary, 934 crates) on the *same model through the same endpoint*,
@@ -1066,14 +1066,19 @@ tool errors, uncached/cache-read tokens, and estimated cost. These records are
the data plane for task-aware recipe comparison; they do not silently switch
models or effort levels.
-Long tool results are stored exactly under `.graff/tool-results/`; model history
-receives a short preview and an inspectable file pointer instead. A result that
-is still over the per-model result cap at send time is spilled the same way
-rather than truncated away: the full bytes go to
-`.graff/sessions/<session>/artifacts/`, and the note left in the transcript
-carries that absolute path and the byte count, so the next turn can read or grep
-the slice it needs. Artifacts are bounded per session and are reclaimed once the
-session file they belong to is gone. Responses
+**Tool results are handles, not payload.** A result over the handle threshold
+(4 KB by default, `GRAFF_TOOL_HANDLE_BYTES`) never enters the conversation
+whole. Its complete bytes are written under `.graff/tool-results/` and what the
+model gets back is a bounded preview, that file's absolute path, the byte count,
+and a one-line shape hint measured from the payload — the line count, or the
+top-level keys of a JSON result. The model then slices what it needs with
+`read_file`, grep-style bash, or `codedb`, so one result costs one threshold of
+context however large it is, and nothing is thrown away to keep it there. The
+tool-time threshold is clamped under the send-time per-model result cap, which
+therefore only ever fires on history graff did not produce (a session resumed
+from an older build); when it does, the full bytes go to
+`.graff/sessions/<session>/artifacts/` the same way, bounded per session and
+reclaimed once the session file they belong to is gone. Responses
requests are explicitly capped at 16k output tokens (4k for compaction and 64
for titles), while compaction carries the latest clean ~8k-token user-turn
suffix forward verbatim. A shared atomic run budget allows at most four model
diff --git a/architecture.md b/architecture.md
index c1d1d398..cf5e82b2 100644
--- a/architecture.md
+++ b/architecture.md
@@ -587,14 +587,18 @@ workflow tool fanning out trivial parallel tasks:
| ---------------------------------------- | --------------- | -------- |
| marginal RSS per parallel subagent | ~0.4 MB | < 2 MB |
| root + 8-way fan-out (max), peak RSS | 15.0 MB | < 64 MB |
-| tool output retained per bash call | ≤ 128 KB + 32 KB stderr (truncated, exit code kept) | hard cap |
+| tool output captured per bash call | ≤ 1 MB + 32 KB stderr (truncated, exit code kept) | hard cap |
+| tool output entering model history | ≤ 4 KB (the #440 handle threshold), whatever the result's size | hard cap |
Child processes a tool spawns (python, make, …) are *outside* the budget by
design: they live in their own process, so their memory never lands in the
harness's RSS — verified with a 500 MB python allocation under an 8-line
-harness that stayed at 12 MB. `runCapped` keeps the first 128 KB of a chatty
-child's output and discards the rest as it streams, so even a 10 MB print
-can't inflate history or retained memory.
+harness that stayed at 12 MB. `runCapped` keeps the first 1 MB of a chatty
+child's output and discards the rest as it streams, so even a 10 MB print can't
+inflate retained memory. History is bounded separately and much harder: past the
+handle threshold a result is written to `.graff/tool-results/` and only a
+preview, a path, a byte count, and a shape hint reach the model (#440), so what
+a tool prints and what a turn pays for are no longer the same number.
### Context: vs the Rust codegraff (justrach/codegraff v0.2.16, same machine)
diff --git a/scripts/test-tool-preview.py b/scripts/test-tool-preview.py
index d99fac93..8a68e03b 100644
--- a/scripts/test-tool-preview.py
+++ b/scripts/test-tool-preview.py
@@ -1,5 +1,9 @@
#!/usr/bin/env python3
-"""Prove large tool output is persisted while model history stays concise."""
+"""Prove a large tool result comes back as a #440 handle, not as payload.
+
+The full bytes land on disk; history gets a bounded preview plus the handle's
+absolute path, the byte count, and a measured shape hint.
+"""
from __future__ import annotations
@@ -16,7 +20,9 @@ from pty_harness import PtySession
_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"
GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg
FINAL_REPLY = "TOOL_PREVIEW_OK"
-PAYLOAD = "large-tool-result:" + "x" * 6000
+# tool_handle.default_threshold_bytes; the payload has to clear it comfortably.
+THRESHOLD = 4096
+PAYLOAD = "large-tool-result:" + "x" * 20000
def message_item(text: str, item_id: str) -> dict:
@@ -133,25 +139,35 @@ def main() -> None:
if len(outputs) != 1 or not isinstance(outputs[0], str):
raise AssertionError(f"missing function_call_output: {second_input!r}")
preview = outputs[0]
- if len(preview) > 2000:
+ if len(preview) > THRESHOLD:
raise AssertionError(f"model-facing preview is {len(preview)} chars")
+ # #440: preview + handle path + byte count + shape hint, in one marker.
match = re.search(
- r"\[full tool result: (\.graff/tool-results/[0-9a-f]+-\d+\.txt) — inspect with read_file\]",
+ r"\[tool result handle: (\d+) bytes, (.+?) — the COMPLETE result is at (.+?)\. Slice",
preview,
)
if match is None:
- raise AssertionError(f"preview has no inspect pointer: {preview!r}")
- detail_path = os.path.join(tmp, match.group(1))
- with open(detail_path, encoding="utf-8") as fh:
+ raise AssertionError(f"preview has no handle marker: {preview!r}")
+ byte_count, shape, handle = int(match.group(1)), match.group(2), match.group(3)
+ if byte_count != len(PAYLOAD):
+ raise AssertionError(f"handle claims {byte_count} bytes, payload is {len(PAYLOAD)}")
+ if shape != "1 lines":
+ raise AssertionError(f"shape hint is not measured from the payload: {shape!r}")
+ if not os.path.isabs(handle):
+ raise AssertionError(f"handle path is not absolute: {handle!r}")
+ with open(handle, encoding="utf-8") as fh:
persisted = fh.read()
if persisted != PAYLOAD:
raise AssertionError(
- f"persisted tool result changed ({len(persisted)} != {len(PAYLOAD)})"
+ f"handle does not hold the full result ({len(persisted)} != {len(PAYLOAD)})"
)
finally:
mock.stop()
- print("ok large tool output persisted exactly; model history received a <=2k preview")
+ print(
+ "ok large tool output became a handle: full bytes on disk, "
+ f"<={THRESHOLD}-byte preview + path + size + shape in history"
+ )
if __name__ == "__main__":
diff --git a/src/agent_compact.zig b/src/agent_compact.zig
index 22170b3d..1be3c27a 100644
--- a/src/agent_compact.zig
+++ b/src/agent_compact.zig
@@ -424,6 +424,12 @@ pub fn trimOldestToolOutputs(self: *Agent) usize {
/// so large-context models keep full results untouched. Preserves every call/output
/// pairing (shrinks strings, never drops a message). Returns bytes reclaimed.
///
+/// #440: a backstop now, not the first line of defense. runTools applies the
+/// handle contract at tool time with a threshold clamped below `cap`, so a
+/// freshly produced result is never oversized by the time it gets here; what
+/// remains for this pass is history this process did not produce (a session
+/// resumed from a pre-#440 build). See tool_handle.effectiveThreshold.
+///
/// #409: the elided bytes are no longer destroyed. When this agent has a durable
/// session, each oversized output is written to that session's artifact dir
/// first and the marker cites the absolute path and the full byte count, so the
diff --git a/src/agent_request.zig b/src/agent_request.zig
index 93da5759..5f1e7a31 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -148,6 +148,14 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
// window past what the in-turn recovery below can reclaim (it keeps the most
// recent outputs verbatim). Window-proportional, so large-context models keep
// full tool results untouched.
+ //
+ // #440 narrowed this to a BACKSTOP. Every tool result this process produced
+ // already met the handle contract at tool time, under a threshold clamped to
+ // this very cap (tool_handle.effectiveThreshold), so nothing from runTools can
+ // reach here oversized. What still can: a session resumed from a build that
+ // predates #440, and any future path that appends a tool output without going
+ // through runTools. Both are exactly the cases where destroying the bytes
+ // would be the alternative, so the pass stays.
const spills_before = tool_spill.spillCount();
const capped = self.capOversizedToolOutputs(self.provider.perOutputCap());
if (capped > 0) {
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index aa7f07a0..00caebef 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -52,31 +52,12 @@ const playbook_glue = @import("playbook_glue.zig"); // #381: the note_constraint
const util = @import("util.zig"); // #225: unixMs, for the clock_sleep interrupted-elapsed measurement
const protocol_seq = @import("protocol_seq.zig"); // #330: monotonic `seq` on every --json event
-const tool_results_dir = ".graff/tool-results";
-pub const tool_preview_chars: usize = 2_000;
-var tool_result_seq: std.atomic.Value(u64) = .init(0);
-
-pub fn toolPreviewText(arena: std.mem.Allocator, text: []const u8, path: ?[]const u8) ![]const u8 {
- if (text.len <= tool_preview_chars) return arena.dupe(u8, text);
- const marker = if (path) |p|
- try std.fmt.allocPrint(arena, "[full tool result: {s} — inspect with read_file]", .{p})
- else
- "[tool result truncated: full-result persistence failed]";
- const head = util.utf8Prefix(text, tool_preview_chars -| (marker.len + 2));
- return std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ head, marker });
-}
-
-fn persistToolResult(self: *Agent, text: []const u8) ?[]const u8 {
- if (text.len <= tool_preview_chars) return null;
- // createDir reports PathAlreadyExists, which is the normal case because
- // trace setup creates `.graff` at launch. createDirPath is idempotent.
- Io.Dir.cwd().createDirPath(self.io, tool_results_dir) catch return null;
- const seq = tool_result_seq.fetchAdd(1, .monotonic);
- const run_id = if (self.tracer) |tr| tr.identity.run_id else "untraced";
- const path = std.fmt.allocPrint(self.arena, "{s}/{s}-{d}.txt", .{ tool_results_dir, run_id, seq }) catch return null;
- Io.Dir.cwd().writeFile(self.io, .{ .sub_path = path, .data = text, .flags = .{ .exclusive = true } }) catch return null;
- return path;
-}
+// #440: the ONE size contract for a tool result — preview + durable handle +
+// byte count + shape hint, applied here at tool time. It replaced this file's
+// old persistToolResult/toolPreviewText pair (a 2000-char head and a bare
+// path), and it clamps itself under the send-time per-output cap so the two are
+// ordered by construction rather than stacked.
+const tool_handle = @import("tool_handle.zig");
// escWatchTask/drainStdin/rawNonblockStdin live in agent_interrupt.zig;
// Agent.esc_watch_done is a struct-level pub var that STAYS declared inside the
@@ -184,11 +165,21 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {
for (ext_idx.items, futures) |i, *fut| fut.* = self.io.async(execTool, .{ ctx, calls[i] });
for (futures, outputs) |*fut, *output| output.* = fut.await(self.io);
defer for (outputs) |output| self.gpa.free(output.text);
+ // #440: one threshold for the whole batch, pinned under this model's
+ // send-time per-output cap so an oversized result is always turned into
+ // a handle HERE rather than truncated later.
+ const handle_threshold = tool_handle.effectiveThreshold(self.provider.perOutputCap());
+ const handle_target: tool_handle.Target = .{
+ .io = self.io,
+ .dir = .cwd(),
+ .run_id = if (self.tracer) |tr| tr.identity.run_id else "untraced",
+ };
for (ext_idx.items, outputs) |i, output| {
- // Keep the model-facing history compact. The exact output remains
- // inspectable on disk and the short preview carries its pointer.
- const detail = persistToolResult(self, output.text);
- results[i] = .{ .text = try toolPreviewText(self.arena, output.text, detail), .is_error = output.is_error, .cancelled = output.cancelled, .ms = output.ms };
+ // A result over the threshold never enters the conversation whole:
+ // the complete bytes go to a durable handle and the model gets a
+ // bounded preview, that path, the byte count, and a shape hint.
+ const handled = try tool_handle.forResult(self.gpa, self.arena, handle_target, output.text, handle_threshold);
+ results[i] = .{ .text = handled.text, .is_error = output.is_error, .cancelled = output.cancelled, .ms = output.ms };
if (self.eval_cmd != null and toolInvalidatesEval(calls[i])) {
self.eval_verified = false;
self.eval_repair_pending = false;
@@ -211,15 +202,6 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {
return results;
}
-test "toolPreviewText caps context and preserves an inspect pointer" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const preview = try toolPreviewText(arena_state.allocator(), &util.repeatBytes("x", 5000), ".graff/tool-results/run-1.txt");
- try std.testing.expect(preview.len <= tool_preview_chars);
- try std.testing.expect(std.mem.indexOf(u8, preview, ".graff/tool-results/run-1.txt") != null);
- try std.testing.expect(std.unicode.utf8ValidateSlice(preview));
-}
-
pub fn rejectToolCall(self: *Agent, call: ToolCall) !?ExecResult {
if (self.sub) return null;
if (self.review_mode) if (try review.rejectTool(self.arena, call)) |denied| {
diff --git a/src/brief_diversity.zig b/src/brief_diversity.zig
index f67278cd..cc2a130d 100644
--- a/src/brief_diversity.zig
+++ b/src/brief_diversity.zig
@@ -466,8 +466,8 @@ pub fn check(arena: Allocator, tracer: ?*trace.Tracer, phase: []const u8, briefs
///
/// The note is prepended to the FIRST sibling's result rather than emitted on
/// its own, because a tool result is the only channel a batch has back to the
-/// root — and prepending puts it above text that toolPreviewText may have
-/// truncated. Best-effort throughout: this must never be able to fail a spawn
+/// root — and prepending puts it above a preview the #440 handle contract may
+/// have bounded. Best-effort throughout: this must never be able to fail a spawn
/// that already succeeded, so every unhappy path is a bare return.
pub fn noteSiblingBatch(arena: Allocator, tracer: ?*trace.Tracer, calls: anytype, ext: []const usize, results: anytype) void {
var briefs: [max_briefs][]const u8 = undefined;
diff --git a/src/exec.zig b/src/exec.zig
index 2e59fabb..ba67b090 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -417,14 +417,12 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
defer gpa.free(text);
return .{ .text = try gpa.dupe(u8, "(codedb returned nothing — try `codedb tree` to confirm the repo is indexed, or refine the query)") };
}
- // Context guard: an unbounded `read <big file>` once dumped 500KB into
- // a subagent's context, ballooning it to 160k tokens and minutes-long
- // API calls. Cap what reaches the model and point it at targeted reads.
- if (text.len > codedb_result_cap) {
- defer gpa.free(text);
- const head = util.utf8Prefix(text, codedb_result_cap);
- return .{ .text = try std.fmt.allocPrint(gpa, "{s}\n[codedb output truncated at {d} KB — prefer targeted queries: outline <path>, symbol <name> --body, or search, instead of whole-file reads]", .{ head, codedb_result_cap / 1024 }) };
- }
+ // #440: this used to truncate anything past 64 KB, because an unbounded
+ // `read <big file>` once dumped 500KB into a subagent's context and
+ // ballooned it to 160k tokens. The guard was right and its method was
+ // destructive: the same 500KB now becomes a handle at tool time, so the
+ // context is bounded harder than it ever was here AND the bytes survive
+ // for a targeted read of the part that mattered.
return .{ .text = text };
}
// #337: the read/splice/write/VERIFY path lives in edit_verify.zig, where
diff --git a/src/prompt_snapshot_tests.zig b/src/prompt_snapshot_tests.zig
index 8249512c..7a00cf98 100644
--- a/src/prompt_snapshot_tests.zig
+++ b/src/prompt_snapshot_tests.zig
@@ -47,6 +47,16 @@ const golden_full_prompt =
\\status first, preserve existing changes, and explain that those edits are
\\not covered by /rewind. Do not claim a relaunch is required. Never extend
\\this exception to an inferred path or to a subagent.
+ \\
+ \\A tool result past the size threshold does not come back in full. What you
+ \\get is a handle: a bounded preview, the path of a file holding the COMPLETE
+ \\result, its byte count, and a one-line shape hint (the line count, or the
+ \\top-level keys of a JSON payload). Treat that path as the result — slice
+ \\what you need out of it with read_file's start_line/end_line, a grep-style
+ \\bash command, or codedb, and do that as many times as the task needs. Never
+ \\re-run the tool just to see more of its output, and never pull the whole
+ \\file back into the conversation; the handle stays readable for the rest of
+ \\the session, so the bytes are not lost by being left on disk.
\\For independent,
\\self-contained chunks of work — exploring several directories, running
\\unrelated checks, summarizing multiple files — fan out: call the
@@ -202,7 +212,9 @@ test "#421: a gated-off capability's tool names disappear from the prompt entire
// #330 embedder mode: bash, read_file, edit_file, write_file and codedb are
// hard-removed from every catalog, so no sentence may still name them.
const embedder = try prompts.composeSegments(a, .{ .local_tools = false });
- for ([_][]const u8{ "read_file", "edit_file", "write_file", "codedb", "bash grep", "/trace", "gh issue create", ".graff/traces" }) |dead|
+ // "Treat that path as the result" is #440's handle contract: a session with
+ // no way to OPEN a path is never told to slice one.
+ for ([_][]const u8{ "read_file", "edit_file", "write_file", "codedb", "bash grep", "/trace", "gh issue create", ".graff/traces", "Treat that path as the result" }) |dead|
try std.testing.expect(std.mem.indexOf(u8, embedder, dead) == null);
const no_subs = try prompts.composeSegments(a, .{ .subagents = false });
diff --git a/src/prompt_text.zig b/src/prompt_text.zig
index c13d5d6d..18ae47a5 100644
--- a/src/prompt_text.zig
+++ b/src/prompt_text.zig
@@ -46,6 +46,24 @@ pub const local_tools_note =
\\this exception to an inferred path or to a subagent.
;
+/// Gate: `caps.local_tools`. #440's handle contract. Gated on the same
+/// capability as the tools that produce a handle AND the ones that can open
+/// one: with read_file/bash/codedb removed, a path is not something this
+/// session can act on, so the paragraph would be pure cost.
+pub const tool_handle_note =
+ \\
+ \\
+ \\A tool result past the size threshold does not come back in full. What you
+ \\get is a handle: a bounded preview, the path of a file holding the COMPLETE
+ \\result, its byte count, and a one-line shape hint (the line count, or the
+ \\top-level keys of a JSON payload). Treat that path as the result — slice
+ \\what you need out of it with read_file's start_line/end_line, a grep-style
+ \\bash command, or codedb, and do that as many times as the task needs. Never
+ \\re-run the tool just to see more of its output, and never pull the whole
+ \\file back into the conversation; the handle stays readable for the rest of
+ \\the session, so the bytes are not lost by being left on disk.
+;
+
/// Gate: `caps.subagents` — the `subagent`/`workflow` tools as the catalog
/// actually reports them, not as this file assumes them.
pub const orchestration_note =
diff --git a/src/prompts.zig b/src/prompts.zig
index 9e768059..2d49406a 100644
--- a/src/prompts.zig
+++ b/src/prompts.zig
@@ -51,6 +51,7 @@ pub const Segment = struct { name: []const u8, text: []const u8, gate: Gate };
pub const segments = [_]Segment{
.{ .name = "intro", .text = text.intro_note, .gate = .always },
.{ .name = "local_tools", .text = text.local_tools_note, .gate = .local_tools },
+ .{ .name = "tool_handle", .text = text.tool_handle_note, .gate = .local_tools }, // #440
.{ .name = "orchestration", .text = text.orchestration_note, .gate = .subagents },
.{ .name = "todo", .text = text.todo_note, .gate = .todos },
.{ .name = "trace", .text = text.trace_note, .gate = .local_tools },
diff --git a/src/session_run.zig b/src/session_run.zig
index 032f5371..f9fc0dc1 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -28,6 +28,7 @@ const http = @import("http.zig");
const ws = @import("ws.zig");
const agent_ws = @import("agent_ws.zig"); // codex_ws_idle_ms override (#codex-ws)
const no_local_tools = @import("no_local_tools.zig"); // #330: GRAFF_NO_LOCAL_TOOLS
+const tool_handle = @import("tool_handle.zig"); // #440: GRAFF_TOOL_HANDLE_BYTES
const provider_mod = @import("provider.zig");
const keys_cli = @import("keys_cli.zig");
const pricing = @import("pricing.zig");
@@ -439,6 +440,7 @@ pub fn setupSkillsAndTheme(io: Io, arena: Allocator, environ_map: anytype, out:
if (n > 0) provider_mod.g_context_override = n;
} else |_| {}
}
+ if (environ_map.get("GRAFF_TOOL_HANDLE_BYTES")) |v| tool_handle.applyEnv(v); // #440: bytes at which a tool result becomes preview + handle
// #204: GRAFF_COMPACT_PCT overrides the auto-compaction threshold as a percent
// of the window (default 80). Clamped to 1..100; ignored if unparseable or 0.
if (environ_map.get("GRAFF_COMPACT_PCT")) |v| {
diff --git a/src/tool_handle.zig b/src/tool_handle.zig
new file mode 100644
index 00000000..ee5f0c4c
--- /dev/null
+++ b/src/tool_handle.zig
@@ -0,0 +1,462 @@
+//! #440: handles by default. A tool result over `threshold_bytes` never enters
+//! the conversation whole. Its bytes are written to `.graff/tool-results/` and
+//! what the model gets back is ONE handle: a bounded preview, the path holding
+//! the complete result, the byte count, and a one-line shape hint (line count,
+//! or the top-level keys of a JSON payload). The model then slices what it
+//! needs with read_file/grep/bash over that path — the filesystem as the
+//! namespace, bash as the REPL — instead of carrying the payload turn after
+//! turn.
+//!
+//! This SUBSUMES the two-step that used to live in agent_tools.zig
+//! (`persistToolResult` + a 2000-char `toolPreviewText`): the bytes were
+//! already durable, but the model was told nothing about them beyond a path,
+//! so it could not decide what to ask for without re-running the tool.
+//!
+//! It also OUTRANKS the send-time per-output cap (#193/#196/#409) by
+//! construction rather than by coincidence: `effectiveThreshold` pins the
+//! tool-time threshold at or below `Provider.perOutputCap()`, so a freshly
+//! produced result is always handled HERE, and the send-time cap is left as the
+//! only thing it still is — a backstop for history this process did not produce
+//! (a session resumed from an older graff, whose stored tool outputs never met
+//! this contract).
+//!
+//! Meta tools never reach this. agent_tools.zig applies it only to the external
+//! (execTool) half of a batch, which is where the bytes are.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const util = @import("util.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
+/// produces oversized results just the same, and its orchestrator may want to
+/// read one.
+pub const handles_dir = ".graff/tool-results";
+
+/// THE knob (#440), in bytes, overridable with `GRAFF_TOOL_HANDLE_BYTES`.
+/// A tool result at or below this reaches the model exactly as the tool
+/// produced it; anything larger comes back as a handle whose preview is bounded
+/// by this same number, so one result costs at most one threshold of context
+/// whatever its size.
+///
+/// 4 KiB is ~1k tokens: a real screenful of head — enough to see a stack trace,
+/// a file header, or the first rows of a table and decide what to ask for —
+/// while still a constant, bounded price. The caps it replaces were not
+/// constant: 128 KiB of bash stdout, 64 KiB of codedb output, and up to 136 KiB
+/// of a single result at send time.
+pub const default_threshold_bytes: usize = 4096;
+pub var threshold_bytes: usize = default_threshold_bytes;
+
+/// Ceiling on what one process may leave in `handles_dir`. Every handle is a
+/// result that ALREADY exceeded the threshold, so a runaway tool loop is
+/// exactly the case that would otherwise fill a disk one oversized result at a
+/// time. Over budget the result is truncated with an honest marker instead:
+/// a handle is written whole or not at all, since a partial one would make the
+/// byte count a lie. `pub var` so a test can shrink it.
+pub var run_cap_bytes: usize = 64 * 1024 * 1024;
+
+var g_seq: std.atomic.Value(u64) = .init(0);
+var g_used: std.atomic.Value(usize) = .init(0);
+
+pub fn resetForTest() void {
+ threshold_bytes = default_threshold_bytes;
+ g_seq.store(0, .monotonic);
+ g_used.store(0, .monotonic);
+}
+
+/// `GRAFF_TOOL_HANDLE_BYTES=<bytes>`. Ignored when unparseable or 0 — a knob
+/// that silently disabled the contract would be worse than no knob.
+pub fn applyEnv(raw: []const u8) void {
+ const n = std.fmt.parseInt(usize, std.mem.trim(u8, raw, " \t"), 10) catch return;
+ if (n > 0) threshold_bytes = n;
+}
+
+/// The threshold this turn actually uses. `per_output_cap` is
+/// `Provider.perOutputCap()` (0 = unknown window, cap disabled).
+///
+/// This one clamp is what makes #440 a single contract instead of a fourth cap
+/// on a stack of three: the tool-time threshold can never sit ABOVE the
+/// send-time cap, so a result big enough to trip the send-time cap has always
+/// already become a handle, and the send-time path cannot fire on anything this
+/// process produced. Without it, a large `GRAFF_TOOL_HANDLE_BYTES` would put
+/// the two caps back in series and re-create exactly the layering #440 removes.
+pub fn effectiveThreshold(per_output_cap: usize) usize {
+ if (per_output_cap == 0) return threshold_bytes;
+ return @min(threshold_bytes, per_output_cap);
+}
+
+/// Where handle bytes are written. Injected rather than assumed so the tests
+/// write into a tmp dir instead of the developer's working tree.
+pub const Target = struct {
+ io: Io,
+ /// The directory `.graff` lives under: the cwd in production.
+ dir: Io.Dir,
+ /// This run's trace id; it names the handle files.
+ run_id: []const u8 = "untraced",
+};
+
+/// What the tool result became.
+pub const Result = struct {
+ /// The model-facing text: the result verbatim below the threshold, or
+ /// preview + handle marker above it.
+ text: []const u8,
+ /// The handle, absolute, or null when the result passed through untouched
+ /// (or when the write failed / the run budget is spent).
+ path: ?[]const u8,
+ /// The FULL size of the tool result, whether or not it became a handle.
+ bytes: usize,
+};
+
+/// At most this many top-level keys are named in a JSON shape hint; a wide
+/// object would otherwise spend the whole preview on its own schema.
+const max_named_keys: usize = 12;
+
+/// Longest single key name reproduced in a shape hint.
+const max_key_len: usize = 48;
+
+/// Apply the contract to one tool result. Never truncates below the threshold,
+/// never claims a handle it did not write.
+pub fn forResult(gpa: Allocator, arena: Allocator, target: Target, text: []const u8, threshold: usize) !Result {
+ if (text.len <= threshold) return .{ .text = try arena.dupe(u8, text), .path = null, .bytes = text.len };
+
+ // The shape hint is measured from the bytes in hand, never inferred from
+ // the tool name: `shapeHint` counts real lines, and only calls a payload
+ // JSON after scanning it end to end.
+ const shape = shapeHint(gpa, arena, text);
+ const path = persist(arena, target, text);
+ const marker = markerText(arena, path, text.len, threshold, shape) catch
+ return .{ .text = try arena.dupe(u8, util.utf8Prefix(text, threshold)), .path = path, .bytes = text.len };
+ // 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 .{
+ .text = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ head, marker }),
+ .path = path,
+ .bytes = text.len,
+ };
+}
+
+fn markerText(arena: Allocator, path: ?[]const u8, total: usize, threshold: usize, shape: []const u8) ![]const u8 {
+ if (path) |p| return std.fmt.allocPrint(
+ arena,
+ "[tool result handle: {d} bytes, {s} — the COMPLETE result is at {s}. Slice what you need out of that file (read_file with start_line/end_line, a grep-style bash command, codedb) instead of re-running the tool (#440).]",
+ .{ total, shape, p },
+ );
+ return std.fmt.allocPrint(
+ arena,
+ "[tool result truncated to {d} bytes: {d} bytes total, {s}. No handle could be written, so the rest is gone — narrow the command and run it again (#440).]",
+ .{ threshold, total, shape },
+ );
+}
+
+/// Write `text` under `handles_dir`; the ABSOLUTE path on success. Null — i.e.
+/// plain truncation — when the run budget is spent or any part of the write
+/// fails. Absolute because a worktree-isolated subagent (#276) runs with a
+/// different cwd than the one this file was created under, and a relative path
+/// would not open there.
+fn persist(arena: Allocator, target: Target, text: []const u8) ?[]const u8 {
+ if (!reserve(text.len)) return null;
+ // createDirPath is idempotent; `.graff` normally already exists (trace setup).
+ target.dir.createDirPath(target.io, handles_dir) catch return refund(text.len);
+ const seq = g_seq.fetchAdd(1, .monotonic);
+ const run_id = if (target.run_id.len > 0) target.run_id else "untraced";
+ const rel = std.fmt.allocPrint(arena, "{s}/{s}-{d}.txt", .{ handles_dir, run_id, seq }) catch return refund(text.len);
+ target.dir.writeFile(target.io, .{ .sub_path = rel, .data = text, .flags = .{ .exclusive = true } }) catch return refund(text.len);
+ return absolute(target, arena, rel);
+}
+
+/// Resolved through the same dir handle the file was written with, so the path
+/// names what actually exists; the relative path is the fallback.
+fn absolute(target: Target, arena: Allocator, rel: []const u8) []const u8 {
+ var buf: [4096]u8 = undefined;
+ if (target.dir.realPathFile(target.io, rel, &buf)) |n| {
+ return arena.dupe(u8, buf[0..n]) catch rel;
+ } else |_| {}
+ return rel;
+}
+
+fn reserve(len: usize) bool {
+ const prev = g_used.fetchAdd(len, .monotonic);
+ if (len > 0 and prev +| len <= run_cap_bytes) return true;
+ _ = g_used.fetchSub(len, .monotonic);
+ return false;
+}
+
+fn refund(len: usize) ?[]const u8 {
+ _ = g_used.fetchSub(len, .monotonic);
+ return null;
+}
+
+/// One line describing the payload's SHAPE, from bytes actually inspected:
+/// the top-level keys of a JSON object, the item count of a JSON array, or the
+/// line count of anything else. A payload that merely starts with `{` is not
+/// called JSON — `jsonShape` scans it to `end_of_document` first — so the hint
+/// never sends the model looking for a key that is not there.
+pub fn shapeHint(gpa: Allocator, arena: Allocator, text: []const u8) []const u8 {
+ if (jsonShape(gpa, arena, text)) |hint| return hint;
+ return std.fmt.allocPrint(arena, "{d} lines", .{lineCount(text)}) catch "shape unknown";
+}
+
+/// Lines as a reader counts them: a trailing newline terminates the last line
+/// rather than starting an empty one.
+pub fn lineCount(text: []const u8) usize {
+ if (text.len == 0) return 0;
+ const nl = std.mem.count(u8, text, "\n");
+ return if (text[text.len - 1] == '\n') nl else nl + 1;
+}
+
+fn jsonShape(gpa: Allocator, arena: Allocator, text: []const u8) ?[]const u8 {
+ const trimmed = std.mem.trim(u8, text, " \t\r\n");
+ if (trimmed.len < 2) return null;
+ if (trimmed[0] != '{' and trimmed[0] != '[') return null;
+ // The scan allocates only key strings and its own depth stack, on scratch
+ // that dies here; the hint itself is copied onto `arena` as it is written.
+ var scratch = std.heap.ArenaAllocator.init(gpa);
+ defer scratch.deinit();
+ const sa = scratch.allocator();
+ var scanner: std.json.Scanner = .initCompleteInput(sa, trimmed);
+ defer scanner.deinit();
+
+ var aw: Io.Writer.Allocating = .init(arena);
+ switch (scanner.next() catch return null) {
+ .object_begin => objectKeys(&scanner, sa, &aw.writer) catch return null,
+ .array_begin => arrayItems(&scanner, &aw.writer) catch return null,
+ else => return null,
+ }
+ // Only a document that ends where it should is called JSON.
+ if ((scanner.next() catch return null) != .end_of_document) return null;
+ return aw.writer.buffered();
+}
+
+fn objectKeys(scanner: *std.json.Scanner, sa: Allocator, w: *Io.Writer) !void {
+ var total: usize = 0;
+ var named: usize = 0;
+ var names: Io.Writer.Allocating = .init(sa);
+ while (true) {
+ switch (try scanner.peekNextTokenType()) {
+ .object_end => {
+ _ = try scanner.next();
+ break;
+ },
+ .string => {},
+ else => return error.NotAnObject,
+ }
+ const key = switch (try scanner.nextAlloc(sa, .alloc_if_needed)) {
+ .string, .allocated_string => |s| s,
+ else => return error.NotAnObject,
+ };
+ total += 1;
+ if (named < max_named_keys) {
+ if (named > 0) try names.writer.writeAll(", ");
+ try names.writer.writeAll(util.utf8Prefix(key, max_key_len));
+ named += 1;
+ }
+ try scanner.skipValue();
+ }
+ if (total == 0) return w.writeAll("JSON object, no top-level keys");
+ try w.print("JSON object, top-level keys: {s}", .{names.writer.buffered()});
+ if (total > named) try w.print(" (+{d} more)", .{total - named});
+}
+
+fn arrayItems(scanner: *std.json.Scanner, w: *Io.Writer) !void {
+ var items: usize = 0;
+ while (true) {
+ switch (try scanner.peekNextTokenType()) {
+ .array_end => {
+ _ = try scanner.next();
+ break;
+ },
+ else => {
+ try scanner.skipValue();
+ items += 1;
+ },
+ }
+ }
+ try w.print("JSON array, {d} items", .{items});
+}
+
+// ── tests ──────────────────────────────────────────────────────────────────
+
+fn testTarget(tmp: *std.testing.TmpDir) Target {
+ return .{ .io = std.testing.io, .dir = tmp.dir, .run_id = "run" };
+}
+
+test "#440: a result at or below the threshold passes through untouched" {
+ 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 small = "wrote 42 bytes to src/main.zig";
+ const r = try forResult(std.testing.allocator, a, testTarget(&tmp), small, 4096);
+ try std.testing.expectEqualStrings(small, r.text);
+ try std.testing.expect(r.path == null);
+ try std.testing.expectEqual(@as(usize, small.len), r.bytes);
+ // Exactly AT the threshold is still untouched, and nothing was written.
+ const exact = try a.alloc(u8, 128);
+ @memset(exact, 'x');
+ const at = try forResult(std.testing.allocator, a, testTarget(&tmp), exact, 128);
+ try std.testing.expectEqualStrings(exact, at.text);
+ try std.testing.expect(at.path == null);
+ try std.testing.expect(tmp.dir.statFile(std.testing.io, handles_dir, .{}) == error.FileNotFound);
+}
+
+test "#440: over the threshold returns preview + handle path + byte count + shape hint, and the handle holds the FULL bytes" {
+ const io = std.testing.io;
+ 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();
+
+ // A needle past the preview: only the handle can still hold it. A STRING,
+ // not a character — the marker embeds a random tmpdir path (see #409's own
+ // test, where a single-character needle failed ~1 run in 5).
+ const needle = "NEEDLE440";
+ const big = try a.alloc(u8, 40_000);
+ @memset(big, 'x');
+ for (0..399) |i| big[(i + 1) * 100 - 1] = '\n'; // 400 lines
+ @memcpy(big[39_000..][0..needle.len], needle);
+
+ const threshold: usize = 4096;
+ const r = try forResult(std.testing.allocator, a, testTarget(&tmp), big, threshold);
+ try std.testing.expectEqual(@as(usize, 40_000), r.bytes);
+ try std.testing.expect(r.path != null);
+ try std.testing.expect(r.text.len <= threshold);
+ try std.testing.expect(std.unicode.utf8ValidateSlice(r.text));
+
+ // (a) the handle holds the complete original bytes
+ const rel = handles_dir ++ "/run-0.txt";
+ const stored = try tmp.dir.readFileAlloc(io, rel, std.testing.allocator, .limited(1 << 20));
+ defer std.testing.allocator.free(stored);
+ try std.testing.expectEqualStrings(big, stored);
+ // (b) the path handed to the model is absolute and names that file
+ try std.testing.expect(std.fs.path.isAbsolute(r.path.?));
+ try std.testing.expect(std.mem.endsWith(u8, r.path.?, "run-0.txt"));
+ try std.testing.expect(std.mem.indexOf(u8, r.text, r.path.?) != null);
+ // (c) the byte count and the shape hint are both in the marker
+ try std.testing.expect(std.mem.indexOf(u8, r.text, "40000 bytes") != null);
+ try std.testing.expect(std.mem.indexOf(u8, r.text, "400 lines") != null);
+ // (d) the payload past the preview left the conversation and lives only on disk
+ try std.testing.expect(std.mem.indexOf(u8, r.text, needle) == null);
+ try std.testing.expect(std.mem.indexOf(u8, stored, needle) != null);
+ // (e) the preview really is the head of the result
+ try std.testing.expect(std.mem.startsWith(u8, r.text, big[0..64]));
+}
+
+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();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ resetForTest();
+ defer resetForTest();
+
+ const payload = try a.alloc(u8, 20_000);
+ @memset(payload, 'a');
+
+ const tight = try forResult(std.testing.allocator, a, testTarget(&tmp), payload, 4096);
+ const roomy = try forResult(std.testing.allocator, a, testTarget(&tmp), payload, 16_384);
+ try std.testing.expect(tight.text.len <= 4096);
+ try std.testing.expect(roomy.text.len <= 16_384);
+ try std.testing.expect(roomy.text.len > tight.text.len);
+ // Raise it past the payload and the handle contract does not apply at all.
+ const off = try forResult(std.testing.allocator, a, testTarget(&tmp), payload, 32_768);
+ try std.testing.expect(off.path == null);
+ try std.testing.expectEqualStrings(payload, off.text);
+
+ // The env knob feeds exactly this number, and refuses to disable the contract.
+ applyEnv("8192");
+ try std.testing.expectEqual(@as(usize, 8192), threshold_bytes);
+ applyEnv("0");
+ try std.testing.expectEqual(@as(usize, 8192), threshold_bytes);
+ applyEnv("not-a-number");
+ try std.testing.expectEqual(@as(usize, 8192), threshold_bytes);
+}
+
+test "#440: the tool-time threshold can never sit above the send-time per-output cap" {
+ resetForTest();
+ defer resetForTest();
+ // Unknown window (cap disabled): the knob stands alone.
+ try std.testing.expectEqual(default_threshold_bytes, effectiveThreshold(0));
+ // Normal case: the knob is far below the cap and wins.
+ try std.testing.expectEqual(default_threshold_bytes, effectiveThreshold(135_000));
+ // A knob set past the cap is clamped, so the send-time cap can never be the
+ // first thing to fire on a result this process produced.
+ threshold_bytes = 1 << 30;
+ try std.testing.expectEqual(@as(usize, 135_000), effectiveThreshold(135_000));
+}
+
+test "#440: shape hints are measured, not guessed — JSON keys, array items, line counts" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const gpa = std.testing.allocator;
+
+ try std.testing.expectEqualStrings(
+ "JSON object, top-level keys: name, version, deps",
+ shapeHint(gpa, a, "{\"name\":\"g\",\"version\":2,\"deps\":{\"a\":[1,2,{\"b\":3}]}}"),
+ );
+ try std.testing.expectEqualStrings("JSON object, no top-level keys", shapeHint(gpa, a, " {}\n"));
+ try std.testing.expectEqualStrings("JSON array, 3 items", shapeHint(gpa, a, "[{\"a\":1},[2],\"three\"]"));
+ // A payload that only LOOKS like JSON is described as the text it is.
+ try std.testing.expectEqualStrings("1 lines", shapeHint(gpa, a, "{\"truncated\": [1, 2"));
+ // ...and so is a document with trailing garbage after a valid value.
+ try std.testing.expectEqualStrings("1 lines", shapeHint(gpa, a, "{\"a\":1} and then some prose"));
+ // Plain text: real line counts, terminator-insensitive.
+ try std.testing.expectEqualStrings("3 lines", shapeHint(gpa, a, "one\ntwo\nthree"));
+ try std.testing.expectEqualStrings("3 lines", shapeHint(gpa, a, "one\ntwo\nthree\n"));
+ try std.testing.expectEqual(@as(usize, 0), lineCount(""));
+
+ // A wide object names a bounded prefix and says how many it left out.
+ var wide: Io.Writer.Allocating = .init(a);
+ try wide.writer.writeByte('{');
+ for (0..20) |i| {
+ if (i > 0) try wide.writer.writeByte(',');
+ try wide.writer.print("\"k{d}\":{d}", .{ i, i });
+ }
+ try wide.writer.writeByte('}');
+ const hint = shapeHint(gpa, a, wide.writer.buffered());
+ try std.testing.expect(std.mem.indexOf(u8, hint, "k0, k1") != null);
+ try std.testing.expect(std.mem.indexOf(u8, hint, "(+8 more)") != null);
+ try std.testing.expect(std.mem.indexOf(u8, hint, "k12") == null);
+}
+
+test "#440: the run byte budget bounds the handle dir, and over it the result is truncated honestly" {
+ const io = std.testing.io;
+ 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();
+ const saved = run_cap_bytes;
+ defer {
+ run_cap_bytes = saved;
+ resetForTest();
+ }
+ run_cap_bytes = 9000;
+
+ const big = try a.alloc(u8, 8192);
+ @memset(big, 'x');
+ const first = try forResult(std.testing.allocator, a, testTarget(&tmp), big, 1024);
+ try std.testing.expect(first.path != null);
+ // The second would overrun the budget whole, so it is truncated rather than
+ // half-written — and it still reports the real size and shape.
+ const second = try forResult(std.testing.allocator, a, testTarget(&tmp), big, 1024);
+ try std.testing.expect(second.path == null);
+ try std.testing.expectEqual(@as(usize, 8192), second.bytes);
+ try std.testing.expect(std.mem.indexOf(u8, second.text, "8192 bytes total") != null);
+ try std.testing.expect(std.mem.indexOf(u8, second.text, "No handle could be written") != null);
+ try std.testing.expect(second.text.len <= 1024);
+ try std.testing.expect(tmp.dir.statFile(io, handles_dir ++ "/run-1.txt", .{}) == error.FileNotFound);
+}
diff --git a/src/tools.zig b/src/tools.zig
index e1f954b0..20593d30 100644
--- a/src/tools.zig
+++ b/src/tools.zig
@@ -355,9 +355,21 @@ pub fn outsideCwd(gpa: Allocator, path: []const u8) !ToolOutput {
};
}
-pub const bash_stdout_cap = 128 * 1024;
+/// How much of a command's output graff will hold at all. #440 demoted this
+/// from a CONTEXT cap to a capture ceiling: the model no longer receives a
+/// tool result in full (tool_handle.zig turns anything past its threshold into
+/// a preview + a durable handle), so the only thing this number still bounds is
+/// harness memory and how much of a chatty command the handle can preserve. At
+/// the old 128 KiB the handle silently lied for exactly the case #440 measured
+/// — a 168 KB log, of which a quarter was already destroyed before anything
+/// could be written down.
+pub const bash_stdout_cap = 1024 * 1024;
pub const bash_stderr_cap = 32 * 1024;
pub const webfetch_cap = 256 * 1024;
+/// Capture ceiling for the `codedb read --compact` fallback (#66). This used to
+/// double as a context cap that truncated any codedb result past 64 KiB; #440
+/// removed that half — the handle preserves those bytes instead of discarding
+/// them, and bounds the context on its own.
pub const codedb_result_cap = 64 * 1024;
/// True when the text carries no real content (empty, or whitespace only) —