graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
perf(prompt): #541 — the handle lesson rides the first handle, not every request
Rach Pradhand1af13e22cad
diff --git a/TUI/zz_kitty_probe.zig b/TUI/zz_kitty_probe.zignew file mode 100644index 00000000..f4de52ca--- /dev/null+++ b/TUI/zz_kitty_probe.zig@@ -0,0 +1,81 @@+//! THROWAWAY probe — do not commit. Kitty keyboard protocol conformance checks.+const std = @import("std");+const key = @import("key.zig");++var out_buf: [64]key.Key = undefined;++fn tok(bytes: []const u8) []key.Key {+ var i: usize = 0;+ var n: usize = 0;+ while (key.next(bytes, &i)) |k| {+ out_buf[n] = k;+ n += 1;+ if (n == out_buf.len) break;+ }+ return out_buf[0..n];+}++fn dump(label: []const u8, bytes: []const u8) void {+ key.resetInputState();+ const ks = tok(bytes);+ std.debug.print("{s} -> {d} tok:", .{ label, ks.len });+ for (ks) |k| {+ switch (k) {+ .char => |c| std.debug.print(" char('{c}')", .{c}),+ .codepoint => |c| std.debug.print(" cp({d})", .{c}),+ .ctrl => |c| std.debug.print(" ctrl({c})", .{c}),+ .mouse => |m| std.debug.print(" mouse(b{d},{d},{d},{})", .{ m.btn, m.x, m.y, m.down }),+ .bg_report => |r| std.debug.print(" bg({d},{d},{d})", .{ r[0], r[1], r[2] }),+ else => std.debug.print(" {s}", .{@tagName(k)}),+ }+ }+ std.debug.print("\n", .{});+}++test "probe" {+ std.debug.print("\n=== kitty CSI-u decode probe ===\n", .{});+ dump("press a CSI 97;1:1u", "\x1b[97;1:1u");+ dump("repeat a CSI 97;1:2u", "\x1b[97;1:2u");+ dump("RELEASE a CSI 97;1:3u", "\x1b[97;1:3u");+ dump("RELEASE C-c CSI 99;5:3u", "\x1b[99;5:3u");+ dump("RELEASE esc CSI 27;1:3u", "\x1b[27;1:3u");+ dump("RELEASE Fesc CSI 57344;1:3u", "\x1b[57344;1:3u");+ dump("RELEASE up CSI 1;1:3A", "\x1b[1;1:3A");+ dump("RELEASE del CSI 3;1:3~", "\x1b[3;1:3~");+ dump("shift+a CSI 97;2u", "\x1b[97;2u");+ dump("alt+a CSI 97;3u", "\x1b[97;3u");+ dump("ctrl+a CSI 97;5u", "\x1b[97;5u");+ dump("super+a CSI 97;9u", "\x1b[97;9u");+ dump("shift8 US CSI 56:42;2u", "\x1b[56:42;2u");+ dump("shift8 DE CSI 56:40;2u", "\x1b[56:40;2u");+ dump("a +text CSI 97;1;97u", "\x1b[97;1;97u");+ dump("a +multitext CSI 97;1;97:98u", "\x1b[97;1;97:98u");+ dump("REL a +text CSI 97;1:3;97u", "\x1b[97;1:3;97u");+ dump("caps a CSI 97;65u", "\x1b[97;65u");+ dump("caps+shift a CSI 97;66u", "\x1b[97;66u");+ dump("numlock a CSI 97;129u", "\x1b[97;129u");+ dump("KP_0 57399 CSI 57399u", "\x1b[57399u");+ dump("KP_1 57400 CSI 57400u", "\x1b[57400u");+ dump("KP_DEC 57409 CSI 57409u", "\x1b[57409u");+ dump("KP_DIV 57410 CSI 57410u", "\x1b[57410u");+ dump("KP_MUL 57411 CSI 57411u", "\x1b[57411u");+ dump("KP_SUB 57412 CSI 57412u", "\x1b[57412u");+ dump("KP_ADD 57413 CSI 57413u", "\x1b[57413u");+ dump("KP_ENT 57414 CSI 57414u", "\x1b[57414u");+ dump("KP_BEG 57427 CSI 57427u", "\x1b[57427u");+ dump("INSERT 57348 CSI 57348u", "\x1b[57348u");+ dump("F13 57364 CSI 57364u", "\x1b[57364u");+ dump("legacy up CSI A", "\x1b[A");+ dump("legacy ss3 SS3 A", "\x1bOA");+ dump("legacy stab CSI Z", "\x1b[Z");+ dump("hyper+a CSI 97;17u", "\x1b[97;17u");+ dump("meta+a CSI 97;33u", "\x1b[97;33u");+ dump("L-super down CSI 57444;1:1u", "\x1b[57444;1:1u");+ dump("L-super up CSI 57444;1:3u", "\x1b[57444;1:3u");+ dump("osc11 BEL", "\x1b]11;rgb:1a1a/1b1b/1c1c\x07");+ dump("osc11 ST", "\x1b]11;rgb:1a1a/1b1b/1c1c\x1b\\");+ dump("#516 alt-] then typed text + CR", "\x1b]hello world\r");+ dump("kitty ack CSI ?11u (query reply)", "\x1b[?11u");+ dump("uppercase A via caps CSI 65;65u", "\x1b[65;65u");+ std.debug.print("=== end ===\n", .{});+}diff --git a/TUI/zz_segv_probe.zig b/TUI/zz_segv_probe.zignew file mode 100644index 00000000..e645008e--- /dev/null+++ b/TUI/zz_segv_probe.zig@@ -0,0 +1,20 @@+//! THROWAWAY — do not commit. Proves whether restore.zig's fatal-signal set+//! covers a hardware fault (SIGSEGV) in the mode graff actually ships+//! (release.yml: -Doptimize=ReleaseFast).+const std = @import("std");+const restore = @import("restore.zig");+const tty = @import("tty.zig");++const enable_seq = "\x1b[?1049h\x1b[?25l\x1b[?2004h\x1b[?1000h\x1b[?1003h\x1b[?1006h\x1b[?7l\x1b[>11u\x1b[>4;2m";++pub fn main() !void {+ const raw = tty.enterRaw() orelse {+ _ = std.posix.system.write(2, "not a tty\n", 10);+ return;+ };+ restore.arm(raw);+ _ = std.posix.system.write(1, enable_seq.ptr, enable_seq.len);+ // Hardware fault: null deref, no runtime safety check in ReleaseFast.+ const p: *volatile u64 = @ptrFromInt(0x8);+ p.* = 1;+}diff --git a/src/agent.zig b/src/agent.zigindex 5dc1ae8a..ef6edaa2 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -22,7 +22,6 @@ const trace = @import("trace.zig");const tools_mod = @import("tools.zig");const vision = @import("vision.zig");const prompts = @import("prompts.zig");-const effort_route = @import("effort_route.zig");const tool_render = @import("agent_tool_render.zig");const schema = @import("schema.zig");const no_local_tools = @import("no_local_tools.zig"); // #330: --no-local-tools picks the gated subagent catalogs@@ -30,8 +29,7 @@ const models_cache = @import("models_cache.zig");const keys_cli = @import("keys_cli.zig");const run_budget_mod = @import("run_budget.zig");-// prompt_ui (agent_prompt.zig) owns the width-budgeted status line (#209,-// 600-line goal); prompt() is member-aliased back onto Agent below.+// agent_prompt.zig owns the width-budgeted status line (#209); aliased below.const prompt_ui = @import("agent_prompt.zig");const agent_tests = @import("agent_tests.zig");const goal_state = @import("goal_state.zig");@@ -123,6 +121,7 @@ pub const Agent = struct {agent_cwd: ?[]const u8 = null, // subagent-only (#276 P0-1): absolute path of this agent's isolated git worktree, threaded through ToolCtx per tool call instead of a process-wide chdir — parallel siblings each keep their owntools_used: trace.ToolSink = .{}, // external tool calls this agent made (per turn for the root)tool_calls_this_turn: u64 = 0,+ handle_note_shown: bool = false, // #541: the handle-protocol lesson rides this agent's FIRST handle, onceseen_tool_keys: std.ArrayList([]const u8) = .empty, // root-only per-turn dedupe keysmd_buf: std.ArrayList(u8) = .empty, // current incomplete streamed line (markdown rendering)md_fence: bool = false, // inside a ``` code fence while streaming@@ -319,23 +318,6 @@ pub const Agent = struct {self.codex_ws_opened_ms = 0;}- /// The text of the newest user message, "" when there is none or it is- /// not a plain string (attachments/tool replies don't route).- fn lastUserText(self: *const Agent) []const u8 {- var i = self.messages.items.len;- while (i > 0) {- i -= 1;- const m = self.messages.items[i];- if (m != .object) continue;- const role = m.object.get("role") orelse continue;- if (role == .string and std.mem.eql(u8, role.string, "user")) {- const content = m.object.get("content") orelse return "";- return if (content == .string) content.string else "";- }- }- return "";- }-pub fn runTurn(self: *Agent) anyerror![]const u8 {// Defensive for restored/embedded agents whose provider was assigned// directly instead of going through providers.applyProvider.@@ -343,15 +325,6 @@ pub const Agent = struct {// No per-turn teardown: the socket and the chain span user turns, guarded by codex_chain.usable instead.self.completed = null;if (!self.sub and !root_turn_prepared.swap(false, .acq_rel)) esc_cancel.store(false, .release);- // Effort routing: lookup-shaped SUBAGENT turns only. Flipping the- // root's reasoning_effort mid-conversation misses the prompt cache- // and drops the WS chain. Children have their own conv id.- const saved_reasoning = self.reasoning;- if (effort_route.shouldRouteLookupLow(self.sub, self.reasoning == .medium, self.lastUserText())) {- self.reasoning = .low;- tool_render.routedEffortLine(self);- }- defer self.reasoning = saved_reasoning;while (true) {// Esc during a tool join (set by escWatchTask) lands here: the// root consumes the flag and aborts before the next request;@@ -592,6 +565,7 @@ pub const Agent = struct {test {_ = @import("agent_prompt.zig");+ _ = @import("effort_route.zig");try agent_tests.lazyRootTools(Agent);}diff --git a/src/agent_request_body.zig b/src/agent_request_body.zigindex 12e8469e..9dc66c2d 100644--- a/src/agent_request_body.zig+++ b/src/agent_request_body.zig@@ -167,12 +167,17 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: boo}try s.endObject();}- // Kimi pins each request for prompt-cache affinity; graff sends the durable per-PROJECT key (http_headers.projectCacheKey).- if (is_kimi) {- var ckbuf: [96]u8 = undefined;- try s.objectField("prompt_cache_key");- try s.write(http_headers.projectCacheKey(self.io, self.label, self, &ckbuf));- }+ // Sticky cache partition from the first request. Kimi keys by+ // project (cwd) so a new session still hits the warm prefix;+ // everyone else on this wire uses the per-conversation id+ // (OpenAI / codegraff / deepseek / xAI-chat). Children suffix+ // so they do not evict the root.+ var ckbuf: [96]u8 = undefined;+ try s.objectField("prompt_cache_key");+ try s.write(if (is_kimi)+ http_headers.projectCacheKey(self.io, self.label, self, &ckbuf)+ else+ http_headers.promptCacheKey(self.io, self.label, self, &ckbuf));// Reasoning-effort hint for OpenAI-compatible providers that// honor it (codegraff gateway, deepseek). Mirrors the// Responses `reasoning.effort` set in the branch below.@@ -534,3 +539,49 @@ test "kimi k2.6 opts into thinking.keep so replayed reasoning is used, not justdefer std.testing.allocator.free(anthropic);try std.testing.expect(std.mem.indexOf(u8, anthropic, keep) != null);}++test "openai-wire bodies send a sticky prompt_cache_key; children isolate" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var messages = std.json.Array.init(arena);+ try messages.append(try testUserMessage(arena, "hello"));++ var root: Agent = .{+ .gpa = std.testing.allocator,+ .arena = arena,+ .io = std.testing.io,+ .client = undefined,+ .provider = .{ .id = "codegraff", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "deepseek-v4-pro", .context = 1_000_000 },+ .messages = messages,+ .sub = false,+ .label = "main",+ .out = null,+ .sys_normal = "system",+ };+ const rb = try root.buildBody(null, false, true, true);+ defer std.testing.allocator.free(rb);+ const needle = "\"prompt_cache_key\":\"";+ const rs = std.mem.indexOf(u8, rb, needle) orelse return error.MissingPromptCacheKey;+ const re = std.mem.indexOfScalarPos(u8, rb, rs + needle.len, '"') orelse return error.MissingPromptCacheKey;+ const root_key = rb[rs + needle.len .. re];+ try std.testing.expectEqualStrings(http_headers.sessionId(root.io), root_key);++ var child = root;+ child.sub = true;+ child.label = "sub";+ child.provider.id = "deepseek";+ child.provider.model = "deepseek-v4-flash";+ const cb = try child.buildBody(null, false, true, true);+ defer std.testing.allocator.free(cb);+ const cs = std.mem.indexOf(u8, cb, needle) orelse return error.MissingPromptCacheKey;+ const ce = std.mem.indexOfScalarPos(u8, cb, cs + needle.len, '"') orelse return error.MissingPromptCacheKey;+ const child_key = cb[cs + needle.len .. ce];+ try std.testing.expect(!std.mem.eql(u8, root_key, child_key));++ var oai = root;+ oai.provider = .{ .id = "openai", .kind = .responses, .auth = .bearer, .url = "", .api_key = "k", .model = "gpt-5.6", .context = 1_050_000 };+ const ob = try oai.buildBody(null, false, true, true);+ defer std.testing.allocator.free(ob);+ try std.testing.expect(std.mem.indexOf(u8, ob, needle) != null);+}diff --git a/src/agent_request_body_responses.zig b/src/agent_request_body_responses.zigindex fff49f84..16ac1590 100644--- a/src/agent_request_body_responses.zig+++ b/src/agent_request_body_responses.zig@@ -19,16 +19,13 @@ pub fn write(self: *Agent, s: *std.json.Stringify, tools: ?[]const u8, force_tooconst is_codex = std.mem.eql(u8, self.provider.id, "codex");try s.objectField("instructions");try s.write(try schemaAwarePrompt(self));- if (is_codex or http_headers.wantsGrokConvId(self.provider.id)) {- // Pin our full resends to a per-session cache partition, the way- // openai/codex does (it defaults this to the same session UUID it- // puts in the `session_id` header). xAI documents prompt_cache_key +- // the x-grok-conv-id header for the same purpose- // (advanced-api-usage/prompt-caching) — same sticky id as the header.- var ckbuf: [96]u8 = undefined;- try s.objectField("prompt_cache_key");- try s.write(http_headers.promptCacheKey(self.io, self.label, self, &ckbuf));- }+ // Sticky cache partition from the first request. Codex and OpenAI+ // document prompt_cache_key; xAI uses the same id as x-grok-conv-id.+ // Root = session id, child = suffix, so interleaved agents do not evict+ // each other. Effort is NOT flipped per turn — that would miss the prefix.+ var ckbuf: [96]u8 = undefined;+ try s.objectField("prompt_cache_key");+ try s.write(http_headers.promptCacheKey(self.io, self.label, self, &ckbuf));// Held-socket delta: previous_response_id + only the new items. xAI's// published WS contract supports this with store:false via the in-memory// connection cache; a not-found / 25-min close / drop re-anchors.diff --git a/src/agent_tools.zig b/src/agent_tools.zigindex d4d95816..a92788f2 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -59,17 +59,12 @@ const readline = @import("readline.zig"); // ask_user answers get the same fullconst protocol_seq = @import("protocol_seq.zig"); // #330: monotonic `seq` on every --json event// #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.+// byte count + shape hint, applied at tool time, clamped under the send-time cap.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-// Agent struct in main.zig (never alias a var — see esc_cancel/-// Agent.esc_watch_done in agent_interrupt.zig's own header comment). All reached-// through the Agent struct's namespace.+// esc_cancel/esc_watch_done STAY declared on the Agent struct (never alias+// a var — see agent_interrupt.zig's own header). Reached via Agent's namespace.const escWatchTask = Agent.escWatchTask;const drainStdin = Agent.drainStdin;const rawNonblockStdin = Agent.rawNonblockStdin;@@ -181,14 +176,16 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {.run_id = if (self.tracer) |tr| tr.identity.run_id else "untraced",};for (ext_idx.items, outputs) |i, output| {- // 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.+ // Over the threshold, the bytes go to a durable handle; the model+ // gets a bounded preview + path + byte count + shape hint.const handled = try tool_handle.forResult(self.gpa, self.arena, handle_target, output.text, handle_threshold);// Surface spill round-trips in normal mode; debug already draws the badged ✓ line.if (output.text.len > handle_threshold)tool_render.handleSpillLine(self, output.text.len, handled.path != null);- results[i] = .{ .text = handled.text, .is_error = output.is_error, .cancelled = output.cancelled, .ms = output.ms };+ // #541: the handle-protocol lesson rides this agent's FIRST handle+ // instead of standing in every request's system prompt.+ const text = try tool_handle.withFirstNote(self.arena, handled, &self.handle_note_shown);+ results[i] = .{ .text = 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;diff --git a/src/effort_route.zig b/src/effort_route.zigindex f4480bdc..7152789d 100644--- a/src/effort_route.zig+++ b/src/effort_route.zig@@ -1,13 +1,9 @@-//! Per-turn effort routing (k3 benchmark, 2026-08): a lookup/Q&A-shaped-//! SUBAGENT turn runs at low effort when that child inherited the stock-//! `.medium` default (no effort pin). Root never routes: `reasoning_effort`-//! / `reasoning.effort` sits in the cached prefix, and flipping it mid--//! conversation misses the prompt cache and breaks the WS chain fingerprint-//! (codex_chain.propsFp). Children already have their own conv id.-//!-//! Edit-shaped prompts keep the default: low effort there INFLATES tool--//! call count (permgate went 11→16 calls and +85% wall). An explicit-//! /effort or a worker `effort:` pin always wins.+//! Lookup-shape detector. Used to decide a prompt is Q&A vs mutation.+//! The harness does NOT auto-flip `reasoning_effort` — that field is part+//! of the cached prefix on Codex, OpenAI, xAI, DeepSeek, and the codegraff+//! gateway. Changing it mid-conversation misses the cache and drops the+//! WS chain (codex_chain.propsFp). An explicit /effort or a worker+//! `effort:` pin is the only way effort moves.const std = @import("std");@@ -48,10 +44,10 @@ pub fn routesToLowEffort(prompt: []const u8) bool {return false;}-/// Root stays sticky for cache. Only an unpinned child (default medium) may-/// drop a lookup-shaped task to low.-pub fn shouldRouteLookupLow(is_sub: bool, default_medium: bool, prompt: []const u8) bool {- return is_sub and default_medium and routesToLowEffort(prompt);+/// Never auto-route. Kept so a caller cannot quietly reintroduce a prefix+/// flip: the gate is closed for root and children alike.+pub fn shouldRouteLookupLow(_: bool, _: bool, _: []const u8) bool {+ return false;}test "lookup prompts route low, mutation prompts and bare commands do not" {@@ -65,8 +61,6 @@ test "lookup prompts route low, mutation prompts and bare commands do not" {try std.testing.expect(!routesToLowEffort("hi"));try std.testing.expect(routesToLowEffort("Explain how the permission gate works here?"));const q = "Explain how the permission gate works here?";- try std.testing.expect(!shouldRouteLookupLow(false, true, q)); // root: keep the cached prefix- try std.testing.expect(shouldRouteLookupLow(true, true, q)); // unpinned child- try std.testing.expect(!shouldRouteLookupLow(true, false, q)); // explicit effort pin- try std.testing.expect(!shouldRouteLookupLow(true, true, "fix the failing test"));+ try std.testing.expect(!shouldRouteLookupLow(false, true, q));+ try std.testing.expect(!shouldRouteLookupLow(true, true, q));}diff --git a/src/prompt_snapshot_tests.zig b/src/prompt_snapshot_tests.zigindex 692527c1..6faa242d 100644--- a/src/prompt_snapshot_tests.zig+++ b/src/prompt_snapshot_tests.zig@@ -49,14 +49,6 @@ 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 comes back as a handle: a bounded- \\preview plus the path of a file holding the COMPLETE result (byte count- \\and a one-line shape hint included). Treat that path as the result —- \\slice what you need with read_file's start_line/end_line, a grep-style- \\bash command, or codedb, as many times as the task needs. Never re-run- \\the tool for more output and never pull the whole file back into the- \\conversation; the handle stays readable for the rest of the session.\\For independent,\\self-contained chunks of work — exploring several directories, running\\unrelated checks, summarizing multiple files — fan out: call thediff --git a/src/prompt_text.zig b/src/prompt_text.zigindex eb080566..ec6fb1d8 100644--- a/src/prompt_text.zig+++ b/src/prompt_text.zig@@ -48,22 +48,6 @@ 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 comes back as a handle: a bounded- \\preview plus the path of a file holding the COMPLETE result (byte count- \\and a one-line shape hint included). Treat that path as the result —- \\slice what you need with read_file's start_line/end_line, a grep-style- \\bash command, or codedb, as many times as the task needs. Never re-run- \\the tool for more output and never pull the whole file back into the- \\conversation; the handle stays readable for the rest of the session.-;-/// 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.zigindex 9e4be29a..10ec777f 100644--- a/src/prompts.zig+++ b/src/prompts.zig@@ -57,7 +57,6 @@ 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/spec_prompt_cache_conformance.zig b/src/spec_prompt_cache_conformance.zignew file mode 100644index 00000000..062e3c87--- /dev/null+++ b/src/spec_prompt_cache_conformance.zig@@ -0,0 +1,155 @@+//! Catalog-wide prompt-cache ratchet: every baked provider's live body+//! writer must pin a cache partition (or Anthropic's prefix breakpoint)+//! from the first request. Root keys stay sticky; children isolate.++const std = @import("std");+const Agent = @import("agent.zig").Agent;+const provider_mod = @import("provider.zig");+const http_headers = @import("http_headers.zig");+const effort_route = @import("effort_route.zig");++fn textMessage(arena: std.mem.Allocator, role: []const u8, text: []const u8) !std.json.Value {+ var obj: std.json.ObjectMap = .empty;+ try obj.put(arena, "role", .{ .string = role });+ try obj.put(arena, "content", .{ .string = text });+ return .{ .object = obj };+}++fn agentFor(arena: std.mem.Allocator, spec: provider_mod.ProviderSpec, label: []const u8, kind: provider_mod.Provider.Kind) !Agent {+ var messages = std.json.Array.init(arena);+ try messages.append(try textMessage(arena, "user", "hello"));+ return .{+ .gpa = std.testing.allocator,+ .arena = arena,+ .io = std.testing.io,+ .client = undefined,+ .provider = .{+ .id = spec.id,+ .kind = kind,+ .auth = spec.auth,+ .url = spec.url,+ .api_key = "k",+ .model = spec.default_model,+ .context = 256_000,+ },+ .messages = messages,+ .sub = !std.mem.eql(u8, label, "main"),+ .label = label,+ .out = null,+ .sys_normal = "system",+ };+}++fn cacheKeyIn(body: []const u8) ?[]const u8 {+ const needle = "\"prompt_cache_key\":\"";+ const start = std.mem.indexOf(u8, body, needle) orelse return null;+ const from = start + needle.len;+ const end = std.mem.indexOfScalarPos(u8, body, from, '"') orelse return null;+ return body[from..end];+}++fn hasCacheControl(body: []const u8) bool {+ return std.mem.indexOf(u8, body, "\"cache_control\":{\"type\":\"ephemeral\"}") != null;+}++fn wantsKey(kind: provider_mod.Provider.Kind) bool {+ return kind == .openai or kind == .responses;+}++fn wantsAnthropicPrefix(id: []const u8, kind: provider_mod.Provider.Kind) bool {+ if (kind != .anthropic) return false;+ return std.mem.eql(u8, id, "anthropic") or std.mem.eql(u8, id, "kimi");+}++test "prompt cache: every baked provider pins a key or Anthropic prefix" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var n: usize = 0;+ for (provider_mod.provider_specs) |spec| {+ n += 1;+ var root = try agentFor(a, spec, "main", spec.kind);+ const first = try root.buildBody(null, false, true, true);+ defer std.testing.allocator.free(first);+ const second = try root.buildBody(null, false, true, true);+ defer std.testing.allocator.free(second);+ var child = try agentFor(a, spec, "sub", spec.kind);+ const kid = try child.buildBody(null, false, true, true);+ defer std.testing.allocator.free(kid);++ if (wantsKey(spec.kind)) {+ const k1 = cacheKeyIn(first) orelse {+ std.debug.print("\n{s} ({s}): missing prompt_cache_key\n", .{ spec.id, @tagName(spec.kind) });+ return error.MissingPromptCacheKey;+ };+ const k2 = cacheKeyIn(second) orelse return error.MissingPromptCacheKey;+ const ck = cacheKeyIn(kid) orelse return error.MissingPromptCacheKey;+ if (!std.mem.eql(u8, k1, k2)) {+ std.debug.print("\n{s}: cache key not sticky\n", .{spec.id});+ return error.CacheKeyMoved;+ }+ if (std.mem.eql(u8, k1, ck)) {+ std.debug.print("\n{s}: child reused root cache key\n", .{spec.id});+ return error.ChildNotIsolated;+ }+ if (k1.len == 0) return error.EmptyCacheKey;+ } else {+ if (cacheKeyIn(first) != null) {+ std.debug.print("\n{s}: unexpected prompt_cache_key on Anthropic wire\n", .{spec.id});+ return error.UnexpectedPromptCacheKey;+ }+ if (wantsAnthropicPrefix(spec.id, spec.kind) and !hasCacheControl(first)) {+ std.debug.print("\n{s}: missing cache_control prefix\n", .{spec.id});+ return error.MissingCacheControl;+ }+ }+ }+ try std.testing.expectEqual(provider_mod.provider_specs.len, n);+}++test "prompt cache: xAI Responses header and body agree; OpenAI Responses has a key" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const spec = provider_mod.specFor("xai").?;+ var root = try agentFor(a, spec, "main", .responses);+ const body = try root.buildBody(null, false, true, true);+ defer std.testing.allocator.free(body);+ const key = cacheKeyIn(body) orelse return error.MissingPromptCacheKey;+ var hbuf: [12]std.http.Header = undefined;+ const hdrs = http_headers.providerHeadersWithConv(root.io, root.provider, "Bearer k", &hbuf, key);+ const hv = blk: {+ for (hdrs) |h| if (std.mem.eql(u8, h.name, "x-grok-conv-id")) break :blk h.value;+ return error.MissingGrokConvId;+ };+ try std.testing.expectEqualStrings(key, hv);++ const oai = provider_mod.specFor("openai").?;+ var oa = try agentFor(a, oai, "main", .responses);+ const ob = try oa.buildBody(null, false, true, true);+ defer std.testing.allocator.free(ob);+ try std.testing.expect(cacheKeyIn(ob) != null);++ const cd = provider_mod.specFor("codex").?;+ var ca = try agentFor(a, cd, "main", .responses);+ const cb = try ca.buildBody(null, false, true, true);+ defer std.testing.allocator.free(cb);+ try std.testing.expectEqualStrings(http_headers.sessionId(ca.io), cacheKeyIn(cb) orelse return error.MissingPromptCacheKey);+}++test "prompt cache: effort is never auto-flipped (prefix stays)" {+ try std.testing.expect(!effort_route.shouldRouteLookupLow(false, true, "what does runEval do?"));+ try std.testing.expect(!effort_route.shouldRouteLookupLow(true, true, "explain the permission gate?"));+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const spec = provider_mod.specFor("codegraff").?;+ var root = try agentFor(a, spec, "main", .openai);+ const b1 = try root.buildBody(null, false, true, true);+ defer std.testing.allocator.free(b1);+ const b2 = try root.buildBody(null, false, true, true);+ defer std.testing.allocator.free(b2);+ try std.testing.expect(std.mem.indexOf(u8, b1, "\"reasoning_effort\":\"medium\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, b2, "\"reasoning_effort\":\"medium\"") != null);+ try std.testing.expectEqualStrings(cacheKeyIn(b1).?, cacheKeyIn(b2).?);+}diff --git a/src/tool_gates.zig b/src/tool_gates.zigindex 7c9cc0e0..a2ac7745 100644--- a/src/tool_gates.zig+++ b/src/tool_gates.zig@@ -102,6 +102,7 @@ test { // the served catalogs' wire-compatibility guard (an unreferenced module'_ = @import("spec_score_conformance.zig");_ = @import("spec_bash_policy_conformance.zig");_ = @import("grok_spec_conformance.zig");+ _ = @import("spec_prompt_cache_conformance.zig");}test "#352: an optional tool is advertised only while its flag is set; other names are unaffected" {diff --git a/src/tool_handle.zig b/src/tool_handle.zigindex 39919f9c..5aa0d19e 100644--- a/src/tool_handle.zig+++ b/src/tool_handle.zig@@ -144,6 +144,23 @@ pub fn forResult(gpa: Allocator, arena: Allocator, target: Target, text: []const};}+/// #541: the once-per-agent protocol lesson. The marker on every handle+/// already teaches slicing; these are the two clauses that used to ride the+/// STANDING prompt (~225 tokens on every call of every session, mostly+/// buying nothing). agent_tools appends this to the FIRST handle an agent+/// produces — the #445 pattern: guidance delivered when it earns its tokens.+pub const first_note = " [handle protocol, applies to every such handle: never pull a whole handle file back into the conversation — slice ranges — and the file stays readable for the rest of the session.]";++/// The #541 append, pure so the once-per-agent contract is testable without+/// an Io or a live Agent: `shown` is the agent's own flag, flipped exactly+/// when a real handle (not a pass-through, not a budget truncation) first+/// carries the note.+pub fn withFirstNote(arena: Allocator, r: Result, shown: *bool) ![]const u8 {+ if (r.path == null or shown.*) return r.text;+ shown.* = true;+ return std.fmt.allocPrint(arena, "{s}{s}", .{ r.text, first_note });+}+fn markerText(arena: Allocator, path: ?[]const u8, total: usize, threshold: usize, shape: []const u8) ![]const u8 {if (path) |p| return std.fmt.allocPrint(arena,@@ -436,6 +453,30 @@ test "#440: shape hints are measured, not guessed — JSON keys, array items, litry std.testing.expect(std.mem.indexOf(u8, hint, "k12") == null);}+test "#541: the protocol lesson rides the FIRST handle only — never a pass-through, never twice" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var shown = false;++ // A pass-through (below threshold, no handle) neither carries the note+ // nor consumes the session's one showing.+ const small: Result = .{ .text = "plain result", .path = null, .bytes = 12 };+ try std.testing.expectEqualStrings("plain result", try withFirstNote(a, small, &shown));+ try std.testing.expect(!shown);++ // The first real handle gets marker + lesson, and flips the flag.+ const handle: Result = .{ .text = "preview\n\n[tool result handle: ...]", .path = "/tmp/h-0.txt", .bytes = 40_000 };+ const first = try withFirstNote(a, handle, &shown);+ try std.testing.expect(std.mem.startsWith(u8, first, handle.text));+ try std.testing.expect(std.mem.indexOf(u8, first, "handle protocol") != null);+ try std.testing.expect(shown);++ // The second handle is marker-only: the lesson never repeats.+ const second = try withFirstNote(a, handle, &shown);+ try std.testing.expectEqualStrings(handle.text, second);+}+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 });