Skip to content

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

Python

feat(cache): lock official xAI prompt-cache contract on /cache

Cursor Agentfaef3a5ee4fe
diff --git a/docs/adr/0010-prompt-cache-max-is-visible.md b/docs/adr/0010-prompt-cache-max-is-visible.md
index 4d6fd4a1..74a2b0e1 100644
--- a/docs/adr/0010-prompt-cache-max-is-visible.md
+++ b/docs/adr/0010-prompt-cache-max-is-visible.md
@@ -19,8 +19,9 @@ intentional. `/debug` counted tokens; it did not say why a miss happened.
## Decision
- `/cache` is the content-free cache HUD: prefix hash, last read/write,
- session hit rate, catalog mode, last bust reason, and the remaining max
- levers. No prompt text, paths, or tool bodies.
+ session hit rate, catalog mode, last bust reason, xAI affinity
+ (`x-grok-conv-id` + `prompt_cache_key`, same project id), and the
+ remaining max levers. No prompt text, paths, or tool bodies.
- `/debug` gets one cache row from the same snapshot.
- Named busts (`goal`, `playbook`, `compact`, `persona`, `tools`, `mcp`) are
recorded at the mutation site and counted only when the next request's
@@ -34,3 +35,9 @@ intentional. `/debug` counted tokens; it did not say why a miss happened.
A `/cache` after a miss names the lever. Revisit defaulting stable-catalog
only if a new live measurement shows load-after-load cache-read returning
from 0% without discovery or compaction regressions.
+
+Live Grok 4.6 (Responses, SuperGrok OAuth, 2026-08-19): same-process
+append-only turn 2 cached 3,712 of turn 1's 3,721 input tokens. A new
+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` / `prompt_cache_key`, exact prefix, reasoning replay.
diff --git a/src/agent_request.zig b/src/agent_request.zig
index 0ab1ce74..c2dc32e8 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -206,7 +206,16 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
self.streamed_args = .none;
const body = try self.buildBody(tools, force, live, stream_usage);
defer self.gpa.free(body);
- if (!self.sub) @import("prompt_cache_hud.zig").noteRequest(self.io, self.systemPrompt(), tools orelse "");
+ if (!self.sub) {
+ const hud = @import("prompt_cache_hud.zig");
+ hud.noteRequest(self.io, self.systemPrompt(), tools orelse "");
+ var aff_buf: [96]u8 = undefined;
+ hud.noteAffinity(
+ http_headers.promptCacheKey(self.io, self.label, self, &aff_buf),
+ std.mem.eql(u8, self.provider.id, "xai"),
+ self.provider.kind == .responses,
+ );
+ }
// GRAFF_REQ_STATS=1: per-call request anatomy + body dumps (req_stats.zig).
req_stats.report(self.io, body, tools, self.sys_normal);
const t0: Io.Timestamp = .now(self.io, .awake);
diff --git a/src/grok_spec_conformance.zig b/src/grok_spec_conformance.zig
index 5a139f01..4d783a07 100644
--- a/src/grok_spec_conformance.zig
+++ b/src/grok_spec_conformance.zig
@@ -255,3 +255,123 @@ test "grok spec: held xAI WS chains previous_response_id + delta; drop rebuilds
try std.testing.expect(std.mem.indexOf(u8, rebuilt, "\"first\"") != null);
try std.testing.expect(std.mem.indexOf(u8, rebuilt, "third — not yet sent") != null);
}
+
+// Official xAI prompt-caching contract
+// (docs.x.ai/developers/advanced-api-usage/prompt-caching):
+// Chat always sets x-grok-conv-id; Responses sets prompt_cache_key; same
+// routing id. Cache is an exact messages prefix — append only. Usage is
+// prompt_tokens_details.cached_tokens (Chat) /
+// input_tokens_details.cached_tokens (Responses). xAI must not receive
+// OpenAI prompt_cache_options / prompt_cache_breakpoint (ADR 0009).
+
+test "grok spec: official cache routing — Chat header and Responses body share one id" {
+ const io = std.testing.io;
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var chat = try xaiAgent(a, "main", .openai);
+ var resp = try xaiAgent(a, "main", .responses);
+ var kbuf: [96]u8 = undefined;
+ const key = http_headers.promptCacheKey(io, "main", &resp, &kbuf);
+ try std.testing.expectEqualStrings(http_headers.projectRootId(io), key);
+
+ var hbuf: [12]std.http.Header = undefined;
+ const hdrs = http_headers.providerHeadersWithConv(io, chat.provider, "Bearer k", &hbuf, key);
+ const header = 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, header);
+
+ const chat_body = try chat.buildBody(null, false, false, false);
+ defer std.testing.allocator.free(chat_body);
+ const resp_body = try resp.buildBody(null, false, false, false);
+ defer std.testing.allocator.free(resp_body);
+ try std.testing.expectEqualStrings(key, cacheKeyIn(resp_body) orelse return error.MissingPromptCacheKey);
+ try std.testing.expectEqualStrings(key, cacheKeyIn(chat_body) orelse return error.MissingPromptCacheKey);
+ try std.testing.expect(std.mem.indexOf(u8, resp_body, "prompt_cache_options") == null);
+ try std.testing.expect(std.mem.indexOf(u8, resp_body, "prompt_cache_breakpoint") == null);
+ try std.testing.expect(std.mem.indexOf(u8, chat_body, "prompt_cache_options") == null);
+}
+
+test "grok spec: official cache is an exact prefix — append keeps it, edit breaks it" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = try xaiAgent(a, "main", .responses);
+ const first = try agent.buildBody(null, false, false, false);
+ defer std.testing.allocator.free(first);
+ try agent.messages.append(try textMessage(a, "assistant", "pong"));
+ try agent.messages.append(try textMessage(a, "user", "next"));
+ const appended = try agent.buildBody(null, false, false, false);
+ defer std.testing.allocator.free(appended);
+ try std.testing.expect(std.mem.indexOf(u8, first, "hello") != null);
+ try std.testing.expect(std.mem.indexOf(u8, appended, "hello") != null);
+ try std.testing.expect(std.mem.indexOf(u8, appended, "next") != null);
+ try std.testing.expectEqualStrings(cacheKeyIn(first).?, cacheKeyIn(appended).?);
+
+ var edited = agent.messages.items[0].object;
+ try edited.put(a, "content", .{ .string = "HELLO-EDITED" });
+ agent.messages.items[0] = .{ .object = edited };
+ const miss = try agent.buildBody(null, false, false, false);
+ defer std.testing.allocator.free(miss);
+ try std.testing.expect(std.mem.indexOf(u8, miss, "hello") == null);
+ try std.testing.expect(std.mem.indexOf(u8, miss, "HELLO-EDITED") != null);
+ try std.testing.expectEqualStrings(cacheKeyIn(first).?, cacheKeyIn(miss).?);
+}
+
+test "grok spec: Chat replays reasoning_content (official top cache-miss cause)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = try xaiAgent(a, "main", .openai);
+ var asst: std.json.ObjectMap = .empty;
+ try asst.put(a, "role", .{ .string = "assistant" });
+ try asst.put(a, "content", .{ .string = "pong" });
+ try asst.put(a, "reasoning_content", .{ .string = "think-then-pong" });
+ try agent.messages.append(.{ .object = asst });
+ try agent.messages.append(try textMessage(a, "user", "next"));
+ const body = try agent.buildBody(null, false, false, false);
+ defer std.testing.allocator.free(body);
+ try std.testing.expect(std.mem.indexOf(u8, body, "\"reasoning_content\":\"think-then-pong\"") != null);
+}
+
+test "grok spec: official usage fields become last_cache_read" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = try xaiAgent(a, "main", .openai);
+ agent.last_cache_read = 0;
+ agent.last_context_tokens = 0;
+ agent.context_local_tokens = 0;
+ agent.codex_prev_id = null;
+ agent.strict = false;
+ agent.sys_strict = "";
+ agent.tools_openai = "";
+ agent.tools_responses = "";
+
+ var details: std.json.ObjectMap = .empty;
+ try details.put(a, "cached_tokens", .{ .integer = 98 });
+ var usage: std.json.ObjectMap = .empty;
+ try usage.put(a, "prompt_tokens", .{ .integer = 125 });
+ try usage.put(a, "completion_tokens", .{ .integer = 48 });
+ try usage.put(a, "prompt_tokens_details", .{ .object = details });
+ var response: std.json.ObjectMap = .empty;
+ try response.put(a, "usage", .{ .object = usage });
+ @import("agent_context.zig").recordUsage(&agent, response, 400);
+ try std.testing.expectEqual(@as(u64, 98), agent.last_cache_read);
+
+ agent.provider.kind = .responses;
+ agent.last_cache_read = 0;
+ var in_details: std.json.ObjectMap = .empty;
+ try in_details.put(a, "cached_tokens", .{ .integer = 50 });
+ var rusage: std.json.ObjectMap = .empty;
+ try rusage.put(a, "input_tokens", .{ .integer = 125 });
+ try rusage.put(a, "output_tokens", .{ .integer = 48 });
+ try rusage.put(a, "total_tokens", .{ .integer = 173 });
+ try rusage.put(a, "input_tokens_details", .{ .object = in_details });
+ var rresp: std.json.ObjectMap = .empty;
+ try rresp.put(a, "usage", .{ .object = rusage });
+ @import("agent_context.zig").recordUsageResponses(&agent, rresp, 400);
+ try std.testing.expectEqual(@as(u64, 50), agent.last_cache_read);
+}
diff --git a/src/prompt_cache_hud.zig b/src/prompt_cache_hud.zig
index 7bfed7f6..a0a3fe75 100644
--- a/src/prompt_cache_hud.zig
+++ b/src/prompt_cache_hud.zig
@@ -42,6 +42,10 @@ var lock: std.atomic.Value(bool) = .init(false);
var snap: Snap = .{};
var pending: Bust = .none;
var g_io: ?Io = null;
+var g_aff: [64]u8 = undefined;
+var g_aff_len: usize = 0;
+var g_xai: bool = false;
+var g_responses: bool = false;
fn acquire() void {
while (lock.cmpxchgWeak(false, true, .acquire, .monotonic) != null) std.atomic.spinLoopHint();
@@ -56,6 +60,9 @@ pub fn reset() void {
snap = .{};
pending = .none;
g_io = null;
+ g_aff_len = 0;
+ g_xai = false;
+ g_responses = false;
}
pub fn snapshot() Snap {
@@ -115,6 +122,18 @@ pub fn noteRequest(io: Io, system: []const u8, tools: []const u8) void {
snap.requests += 1;
}
+/// Content-free xAI routing id (`x-grok-conv-id` / `prompt_cache_key`).
+/// Official docs: same value on Chat header and Responses body.
+pub fn noteAffinity(key: []const u8, xai: bool, responses: bool) void {
+ acquire();
+ defer release();
+ g_xai = xai;
+ g_responses = responses;
+ const n = @min(key.len, g_aff.len);
+ @memcpy(g_aff[0..n], key[0..n]);
+ g_aff_len = n;
+}
+
pub fn bustLabel(b: Bust) []const u8 {
return switch (b) {
.none => "none",
@@ -183,11 +202,20 @@ pub fn render(w: *Io.Writer) !void {
try w.print(" busts {d} last: {s}\n", .{ s.busts, bustLabel(s.last_bust) });
}
try w.print(" catalog {s}\n", .{if (mcp_schema_gate.g_stable_catalog) "stable (loads append tail only)" else "mutating (a load rewrites tools JSON)"});
+ if (g_xai and g_aff_len > 0) {
+ try w.print(" xAI {s} (automatic prefix cache)\n", .{if (g_responses) "responses" else "chat"});
+ try w.print(" affinity {s}\n", .{g_aff[0..g_aff_len]});
+ try w.writeAll(" x-grok-conv-id + prompt_cache_key, same value\n");
+ } else {
+ try w.writeAll(" xAI x-grok-conv-id + prompt_cache_key (same project id, automatic)\n");
+ }
try w.writeAll(
\\ remaining max
\\ GRAFF_STABLE_CATALOG=1 opt-in: keep tools JSON byte-identical after load
\\ /goal /never /strict each prefix rewrite is one miss; compaction already pays one
\\ 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
\\
);
}
@@ -272,11 +300,28 @@ test "render stays content-free and names remaining levers" {
try std.testing.expect(contains(text, "prefix"));
try std.testing.expect(contains(text, "GRAFF_STABLE_CATALOG"));
try std.testing.expect(contains(text, "/goal"));
+ try std.testing.expect(contains(text, "x-grok-conv-id"));
+ try std.testing.expect(contains(text, "append-only"));
try std.testing.expect(!contains(text, "SECRET-PROMPT"));
try std.testing.expect(!contains(text, "/Users/me"));
try std.testing.expect(!contains(text, "bash"));
}
+test "render shows xAI affinity without prompt text" {
+ reset();
+ defer reset();
+ noteRequest(std.testing.io, "SECRET-PROMPT", "[]");
+ noteAffinity("b79ad29b-b3f9-463c-bca6-041d5058d366", true, true);
+ var buf: [2048]u8 = undefined;
+ var w: Io.Writer = .fixed(&buf);
+ try render(&w);
+ const text = w.buffered();
+ try std.testing.expect(contains(text, "responses"));
+ try std.testing.expect(contains(text, "b79ad29b-b3f9-463c-bca6-041d5058d366"));
+ try std.testing.expect(contains(text, "prompt_cache_key"));
+ try std.testing.expect(!contains(text, "SECRET-PROMPT"));
+}
+
test "renderLine is one content-free row" {
reset();
defer reset();