Skip to content

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

Python

feat(btw): ride the parent prompt-cache prefix like grok-build

Cursor Agentac058d5120de
diff --git a/README.md b/README.md
index 297cb12d..9b71a586 100644
--- a/README.md
+++ b/README.md
@@ -517,7 +517,7 @@ gateway rollouts appear without a restart.
/plugins list Cursor/Claude/Grok/Codex plugin trees graff is reading in place
/hooks list lifecycle hooks and the built-in codedb guard
/doctor read-only health check: goal/todo invariants, and why steering will or will not be appended
-/btw <question> ask one side question about this conversation: no tools, billed, never added to the session
+/btw <question> ask one side question about this conversation: billed, never added, rides the parent cache prefix
/compact compact history into a fresh context (OpenAI server-side when available)
/rewind [n] list past prompts; /rewind <n> drops prompt n+after & reverts its file edits
/image <path> attach an image to your next message (vision models only)
diff --git a/docs/adr/0010-prompt-cache-max-is-visible.md b/docs/adr/0010-prompt-cache-max-is-visible.md
index 094789f1..ff573360 100644
--- a/docs/adr/0010-prompt-cache-max-is-visible.md
+++ b/docs/adr/0010-prompt-cache-max-is-visible.md
@@ -29,6 +29,9 @@ intentional. `/debug` counted tokens; it did not say why a miss happened.
- Do not default `GRAFF_STABLE_CATALOG`. Do not move playbook / compact notes
/ standing goal off the prefix — those ride the system prompt on purpose
(ADR 0005, #381, #391) and already share the compaction boundary.
+- `/btw` is a grok-build side-call: same system prompt, same tools JSON, same
+ `prompt_cache_key` as the parent. The side-question note is appended as a
+ user message. Tools are advertised for the prefix and not executed.
## Consequences
@@ -42,4 +45,6 @@ process in the same folder started cold at 128 — the official first-request
write, not a routing miss. That is the xAI contract working: sticky
`x-grok-conv-id` / `x-grok-session-id` / `prompt_cache_key`, exact prefix,
reasoning replay. Session-id is grok-build's extra sticky header: always
-the project id, even when a child isolates `x-grok-conv-id`.
+the project id, even when a child isolates `x-grok-conv-id`. `/btw` shares
+that key and the parent tools/system so a side question can hit the warm
+prefix instead of evicting it.
diff --git a/src/command_catalog.zig b/src/command_catalog.zig
index 8705d1ee..d1996144 100644
--- a/src/command_catalog.zig
+++ b/src/command_catalog.zig
@@ -54,7 +54,7 @@ pub const commands = [_]Item{
.{ .name = "/plugins", .usage = "/plugins [list|load <name>]", .desc = "list Claude/Cursor/Grok/Codex plugin trees graff is reading in place; load names one" },
.{ .name = "/hooks", .desc = "list lifecycle hooks and the built-in codedb guard" },
.{ .name = "/doctor", .desc = "read-only health check: goal/todo invariants, and why steering will or will not be appended" },
- .{ .name = "/btw", .usage = "/btw <question>", .desc = "ask one side question about this conversation — no tools, billed, never added to the session" },
+ .{ .name = "/btw", .usage = "/btw <question>", .desc = "ask one side question about this conversation — billed, never added, rides the parent cache prefix" },
.{ .name = "/compact", .desc = "compact history into a fresh context (OpenAI server-side when available)" },
.{ .name = "/rewind", .usage = "/rewind [n|<snapshot>]", .desc = "list past prompts; /rewind <n> drops prompt n+after & reverts its file edits; /rewind <snapshot id> restores a sandbox filesystem instead, never the conversation" },
.{ .name = "/snapshot", .usage = "/snapshot [attach [image]|detach|list]", .desc = "capture the attached sandbox's filesystem under .graff/sessions/<session>/snapshots; attach puts this session in a Docker sandbox, list shows what it has captured" },
diff --git a/src/http_headers.zig b/src/http_headers.zig
index 42fc527f..9443358f 100644
--- a/src/http_headers.zig
+++ b/src/http_headers.zig
@@ -53,7 +53,7 @@ pub fn promptCacheKey(io: Io, label: []const u8, agent: *const anyopaque, buf: [
/// OpenAI's documented ~15 requests/minute cache-routing guidance during fanout.
pub fn promptPrefixCacheKey(io: Io, label: []const u8, buf: []u8) []const u8 {
const base = projectRootId(io);
- if (std.mem.eql(u8, label, "main")) return std.fmt.bufPrint(buf, "{s}", .{base}) catch base;
+ if (std.mem.eql(u8, label, "main") or sharesParentCache(label)) return std.fmt.bufPrint(buf, "{s}", .{base}) catch base;
const lane = std.hash.Wyhash.hash(0, label) & 3;
return std.fmt.bufPrint(buf, "{s}-child-{d}", .{ base, lane }) catch base;
}
@@ -105,9 +105,16 @@ pub fn projectRootId(io: Io) []const u8 {
return project_id_buf[0..project_id_len];
}
+/// Side-calls that replay the parent history (`/btw`) share the root
+/// partition. Concurrent workers stay isolated. grok-build's recap does the
+/// same: same `prompt_cache_key` as the parent so the prefix stays warm.
+pub fn sharesParentCache(label: []const u8) bool {
+ return std.mem.eql(u8, label, "btw");
+}
+
pub fn projectCacheKey(io: Io, label: []const u8, agent: *const anyopaque, buf: []u8) []const u8 {
const base = projectRootId(io);
- if (std.mem.eql(u8, label, "main")) {
+ if (std.mem.eql(u8, label, "main") or sharesParentCache(label)) {
if (buf.len >= base.len) {
@memcpy(buf[0..base.len], base);
return buf[0..base.len];
@@ -256,6 +263,9 @@ test "project and prefix cache keys preserve conversation and sharing boundaries
const sibling_sub = projectCacheKey(std.testing.io, "sub", sibling, &buf4);
try std.testing.expect(!std.mem.eql(u8, sub, sibling_sub));
+ var btw_buf: [96]u8 = undefined;
+ try std.testing.expectEqualStrings(a, projectCacheKey(std.testing.io, "btw", sibling, &btw_buf));
+
// OpenAI/Codex prefix affinity is stable for a workflow role, but spreads
// different roles over four lanes to stay below the per-key traffic guide.
var pbuf1: [96]u8 = undefined;
diff --git a/src/json_controls.zig b/src/json_controls.zig
index 7b01db71..c46abe54 100644
--- a/src/json_controls.zig
+++ b/src/json_controls.zig
@@ -24,7 +24,7 @@ const side_question = @import("side_question.zig");
pub fn sideQuestion(root: *Agent, arena: Allocator, rtype: []const u8, text: []const u8) bool {
if (!std.mem.eql(u8, rtype, "btw")) return false;
if (side_question.ask(root, arena, text)) |answer| {
- root.emit(.{ .type = "btw", .ok = true, .text = answer, .persisted = false });
+ root.emit(.{ .type = "btw", .ok = true, .text = answer.text, .persisted = false, .cache_read_tokens = answer.cache_read });
} else {
root.emit(.{ .type = "error", .message = "side question failed; the conversation is unchanged" });
}
diff --git a/src/mainloop.zig b/src/mainloop.zig
index 182d62e6..c792fb05 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -285,7 +285,7 @@ pub fn run(ctx: *Ctx) !void {
}
if (std.mem.eql(u8, rtype, "review")) review_prompt = text;
// #415: a side question is ANSWERED here and never becomes a turn —
- // no tools, billed, and nothing added to the session or its transcript.
+ // billed, parent-prefix cached, nothing added to the session.
if (json_controls.sideQuestion(ctx.root, ctx.arena, rtype, text)) continue;
json_controls.applyToolKnobs(parsed.object);
break :blk text;
diff --git a/src/prompt_cache_hud.zig b/src/prompt_cache_hud.zig
index 53cc0ebd..d8413628 100644
--- a/src/prompt_cache_hud.zig
+++ b/src/prompt_cache_hud.zig
@@ -216,6 +216,7 @@ pub fn render(w: *Io.Writer) !void {
\\ leave skill bodies and file: paths out of the prefix (already the default)
\\ append-only messages official xAI prefix; edit/remove/reorder is a miss
\\ replay reasoning Chat reasoning_content · Responses encrypted_content
+ \\ /btw parent tools + system + cache key; note is the user message
\\
);
}
diff --git a/src/side_question.zig b/src/side_question.zig
index 485ce4ed..d1baa074 100644
--- a/src/side_question.zig
+++ b/src/side_question.zig
@@ -1,5 +1,6 @@
//! #415 — `/btw`: a throwaway side question, answered from the LIVE
-//! conversation with tools disabled, rendered once, and then dropped.
+//! conversation, rendered once, and then dropped. Tools stay on the wire
+//! so the parent prompt-cache prefix hits; they are not executed.
//!
//! THE POINT. "what did that error actually mean?" is a question ABOUT the work
//! in progress, not a step of it. Asking it the ordinary way costs the session
@@ -25,11 +26,12 @@
//! agent's messages live in an arena the root holds no pointer to, and its
//! `sub = true` makes `record` refuse it outright at the first line.
//!
-//! NO TOOLS, GENUINELY. `Agent.request(null)` omits the `tools` field from the
-//! body entirely rather than sending an empty array, for all three wire
-//! formats — the same trick compaction and the title task use. `text_only` is
-//! set too, so the agent stays tool-less if it is ever driven through
-//! `runTurn` instead.
+//! PARENT PREFIX, grok-build side-call shape. The request keeps the root
+//! system prompt, the root tools JSON, and the root `prompt_cache_key` so
+//! the provider's prefix cache stays warm. The side-question note is a new
+//! user message (append-only), not a system rewrite. `text_only` stays set
+//! so `runTurn` cannot execute a tool if the model ignores the note; `ask`
+//! is still a single `request`, so a tool call is never run.
//!
//! IT IS STILL BILLED. The request goes through `Agent.request` like any
//! other, so recordUsage/recordCost bank it in `pricing.g_cost` — the tally the
@@ -57,11 +59,11 @@ pub const output_limit: u32 = 1024;
/// Shown when `/btw` arrives with nothing to ask. Says what the command is for,
/// because an empty one is nearly always a half-typed line.
pub const usage_hint = "/btw <question> — ask one side question about this conversation; " ++
- "it runs with no tools and is never added to the session";
+ "it rides the parent cache prefix and is never added to the session";
-/// Appended to the ROOT's own system prompt for this one call. The model keeps
-/// its identity and its project context — the question is about the work in
-/// front of it — and is told the two things that are only true here.
+/// Appended as a USER message (not a system rewrite) so the cached prefix
+/// stays byte-identical. The model is told the two things that are only true
+/// here; tools stay on the wire for the prefix and must not be used.
pub const side_note =
\\[side question: the user has asked something ALONGSIDE the conversation
\\above, not as the next step of it. Answer it from what is already in this
@@ -99,7 +101,8 @@ pub fn questionFromLine(line: []const u8) ?[]const u8 {
/// allocate out of the session's.
pub fn build(self: *Agent, arena: Allocator, question: []const u8) !Agent {
var messages = try agent_compact.cloneJsonArray(arena, self.messages);
- try messages.append(try textMessage(arena, "user", question));
+ const asked = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ side_note, question });
+ try messages.append(try textMessage(arena, "user", asked));
return .{
.gpa = self.gpa,
.arena = arena,
@@ -108,8 +111,8 @@ pub fn build(self: *Agent, arena: Allocator, question: []const u8) !Agent {
.provider = self.provider,
.messages = messages,
.sub = true, // never touches stdout, the root's state, or the transcript
- .text_only = true, // and could not be handed tools even through runTurn
- .label = "btw",
+ .text_only = true, // runTurn must not execute a tool if the model ignores the note
+ .label = "btw", // shares the root prompt_cache_key (http_headers.sharesParentCache)
.out = null,
.tracer = self.tracer,
.run_budget = self.run_budget,
@@ -119,26 +122,38 @@ pub fn build(self: *Agent, arena: Allocator, question: []const u8) !Agent {
.call_kind = .judge, // an auxiliary, bounded, non-recursive call
.responses_output_limit = output_limit,
.message_mutation_arena = arena,
- .sys_override = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ self.systemPrompt(), side_note }),
+ .sys_override = self.systemPrompt(), // exact parent prefix; note is the user message
+ .tools_anthropic = self.tools_anthropic,
+ .tools_openai = self.tools_openai,
+ .tools_responses = self.tools_responses,
};
}
-/// One tool-less request over a clone of the live history. The answer is duped
-/// into `out_arena` (the caller's turn arena, not the session's) and everything
-/// else — the clone, the reply tree, the side agent — dies with the scratch
-/// arena before this returns. Null on any failure: a side question that could
-/// not be answered must still leave the conversation exactly as it found it.
-pub fn ask(self: *Agent, out_arena: Allocator, question: []const u8) ?[]const u8 {
+pub const Reply = struct {
+ text: []const u8,
+ cache_read: u64,
+};
+
+/// One request over a clone of the live history, parent tools on the wire.
+/// The answer is duped into `out_arena` (the caller's turn arena, not the
+/// session's) and everything else dies with the scratch arena. Null on any
+/// failure: a side question that could not be answered must still leave the
+/// conversation exactly as it found it.
+pub fn ask(self: *Agent, out_arena: Allocator, question: []const u8) ?Reply {
var arena_state = std.heap.ArenaAllocator.init(self.gpa);
defer arena_state.deinit();
const arena = arena_state.allocator();
var agent = build(self, arena, question) catch return null;
defer agent.tools_used.deinit(self.gpa);
defer agent.closeCodexWs(); // its own socket + response-id anchor, gpa-owned
- const root = agent.request(null) catch return null;
+ const tools = self.toolsJson();
+ const root = agent.request(if (tools.len > 0) tools else null) catch return null;
const text = std.mem.trim(u8, title.assistantText(self.provider.kind, root), " \t\r\n");
if (text.len == 0) return null;
- return out_arena.dupe(u8, text) catch null;
+ return .{
+ .text = out_arena.dupe(u8, text) catch return null,
+ .cache_read = agent.last_cache_read,
+ };
}
/// The `/btw` slash command. Returns false when `line` is not one, so it can sit
@@ -157,7 +172,9 @@ pub fn command(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Writer
try out.flush();
return true;
};
- try out.print("{s}\n{s}(side question — not added to this session){s}\n", .{ answer, style.dim, style.reset });
+ try out.print("{s}\n{s}(side question — not added · {d} cached){s}\n", .{
+ answer.text, style.dim, answer.cache_read, style.reset,
+ });
try out.flush();
return true;
}
diff --git a/src/side_question_tests.zig b/src/side_question_tests.zig
index b8b9a70e..24bf31f4 100644
--- a/src/side_question_tests.zig
+++ b/src/side_question_tests.zig
@@ -76,42 +76,69 @@ fn serialize(arena: Allocator, msgs: std.json.Array) ![]const u8 {
return aw.writer.buffered();
}
-test "/btw (#415): the side request carries the live context and the question, with NO tools" {
+test "/btw (#415): the side request is the parent prefix plus an appended user note" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
- // Every wire format, because "no tools" is written three times in buildBody
- // and a fourth caller getting one of them wrong is exactly how a `/btw`
- // would quietly grow the ability to edit files.
+ // Every wire format: the parent tools JSON must ride the body so the
+ // prefix matches, and the side note must be a user message, not a system
+ // rewrite. runTurn still cannot execute a tool (`text_only`).
for ([_]Provider.Kind{ .anthropic, .openai, .responses }) |kind| {
var r = try root(arena, kind);
var agent = try side_question.build(&r, arena, question);
defer agent.tools_used.deinit(std.testing.allocator);
- const body = try agent.buildBody(null, false, false, false);
+ const tools = r.toolsJson();
+ const parent_body = try r.buildBody(tools, false, false, false);
+ defer std.testing.allocator.free(parent_body);
+ const body = try agent.buildBody(tools, false, false, false);
defer std.testing.allocator.free(body);
- // The answer is produced FROM the existing context: the conversation so
- // far is in the request, with the question appended after it.
try std.testing.expect(std.mem.indexOf(u8, body, "undefined symbol _graff_main") != null);
const asked = std.mem.indexOf(u8, body, "what did that linker error") orelse
return error.TestUnexpectedResult;
try std.testing.expect(asked > std.mem.indexOf(u8, body, "undefined symbol _graff_main").?);
- // No toolset, and not an empty one either — the key is absent.
- try std.testing.expect(std.mem.indexOf(u8, body, "\"tools\"") == null);
- try std.testing.expect(std.mem.indexOf(u8, body, "\"bash\"") == null);
- try std.testing.expect(std.mem.indexOf(u8, body, "tool_choice") == null);
- try std.testing.expect(agent.text_only); // and runTurn could not add any
+ try std.testing.expect(std.mem.indexOf(u8, body, "\"tools\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, body, "\"bash\"") != null);
+ try std.testing.expect(agent.text_only);
- // The root's own prompt, plus the note that says why this turn is odd.
try std.testing.expect(std.mem.indexOf(u8, body, "ROOT-BASE") != null);
try std.testing.expect(std.mem.indexOf(u8, body, "You have NO tools on this turn") != null);
- // It is a subagent for every root-only path, the transcript included.
try std.testing.expect(agent.sub);
+ try std.testing.expectEqualStrings("btw", agent.label);
}
}
+test "/btw shares the parent prompt_cache_key and does not rewrite instructions" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var r = try root(arena, .responses);
+ r.provider.id = "xai";
+ r.provider.model = "grok-4.6";
+ r.label = "main";
+ var agent = try side_question.build(&r, arena, question);
+ defer agent.tools_used.deinit(std.testing.allocator);
+ const tools = r.toolsJson();
+ const parent_body = try r.buildBody(tools, false, false, false);
+ defer std.testing.allocator.free(parent_body);
+ const body = try agent.buildBody(tools, false, false, false);
+ defer std.testing.allocator.free(body);
+
+ const needle = "\"prompt_cache_key\":\"";
+ const p_start = std.mem.indexOf(u8, parent_body, needle) orelse return error.MissingParentKey;
+ const b_start = std.mem.indexOf(u8, body, needle) orelse return error.MissingSideKey;
+ const p_from = p_start + needle.len;
+ const b_from = b_start + needle.len;
+ const p_end = std.mem.indexOfScalarPos(u8, parent_body, p_from, '"') orelse return error.MissingParentKey;
+ const b_end = std.mem.indexOfScalarPos(u8, body, b_from, '"') orelse return error.MissingSideKey;
+ try std.testing.expectEqualStrings(parent_body[p_from..p_end], body[b_from..b_end]);
+ try std.testing.expect(std.mem.indexOf(u8, parent_body, "\"instructions\":\"ROOT-BASE\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, body, "\"instructions\":\"ROOT-BASE\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, parent_body, "You have NO tools on this turn") == null);
+}
+
test "/btw (#415): root.messages is byte-identical before and after, and the clone is deep" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();