graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(cache): show prompt-cache max posture on /cache
Cursor Agentbb17057e6893
diff --git a/TUI/catalog.zig b/TUI/catalog.zigindex 71cde7b1..3ed02ab6 100644--- a/TUI/catalog.zig+++ b/TUI/catalog.zig@@ -17,6 +17,7 @@ pub const items = [_]Item{.{ .name = "/session-info", .desc = "Session details", .aliases = &.{ "/status", "/info" } },.{ .name = "/usage", .desc = "Token usage and cost", .aliases = &.{"/cost"} },.{ .name = "/debug", .desc = "Live observability HUD" },+ .{ .name = "/cache", .desc = "Prompt-cache posture and remaining max levers" },.{ .name = "/rewind", .desc = "Undo the last turn", .aliases = &.{"/undo"} },.{ .name = "/quit", .desc = "Quit", .aliases = &.{ "/exit", "/q" } },.{ .name = "/rename", .desc = "Rename this session", .aliases = &.{"/title"} },@@ -96,6 +97,7 @@ test "filter: slash prefix and alias" {try std.testing.expect(lookup("/undo") != null);try std.testing.expect(lookup("/yolo") != null);try std.testing.expect(lookup("/debug") != null);+ try std.testing.expect(lookup("/cache") != null);try std.testing.expect(lookup("/cost") != null);try std.testing.expect(lookup("/not-a-cmd") == null);}diff --git a/TUI/dispatch.zig b/TUI/dispatch.zigindex 65ecbc58..357a9c81 100644--- a/TUI/dispatch.zig+++ b/TUI/dispatch.zig@@ -158,7 +158,7 @@ pub fn runCommand(self: *Model, line: []const u8) Effect {self.pushFmt(.system, "session: {s}", .{self.session_name orelse "untitled"}) catch {};} else if (std.mem.eql(u8, canon, "/session-info")) {meters.sessionInfo(self);- } else if (std.mem.eql(u8, canon, "/debug")) {+ } else if (std.mem.eql(u8, canon, "/debug") or std.mem.eql(u8, canon, "/cache")) {self.openOverlay(.debug);} else if (std.mem.eql(u8, canon, "/usage")) {var buf: [512]u8 = undefined;@@ -379,6 +379,14 @@ test "/debug opens the observability overlay" {try std.testing.expectEqual(app.Overlay.debug, m.overlay);}+test "/cache opens the same observability overlay" {+ var m: Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();+ _ = applyLine(&m, "/cache");+ try std.testing.expectEqual(app.Overlay.debug, m.overlay);+}+test "/usage is not a char-count view" {var m: Model = undefined;m.setup(std.testing.allocator);diff --git a/TUI/overlaypane.zig b/TUI/overlaypane.zigindex cda328b7..280fc66d 100644--- a/TUI/overlaypane.zig+++ b/TUI/overlaypane.zig@@ -249,6 +249,7 @@ const help_body =\\ /settings model · effort · mode · theme\\ /usage /cost live token/cost line\\ /debug observability HUD+ \\ /cache prompt-cache posture\\ /plan toggle plan mode\\ /always-approve skip permission prompts\\ /import-claude copy Claude and Cursor MCP + skills@@ -269,7 +270,7 @@ test "help overlay names the advertised pager commands" {defer arena.deinit();const text = try overlay(&m, arena.allocator(), 80);for ([_][]const u8{- "/quit", "/help", "/new", "/home", "/model", "/settings", "/usage", "/debug", "/plan", "/always-approve",+ "/quit", "/help", "/new", "/home", "/model", "/settings", "/usage", "/debug", "/cache", "/plan", "/always-approve","Shift+Tab", "PgUp", "PgDn","←","→",diff --git a/TUI/sim.zig b/TUI/sim.zigindex 7e2ca307..1a3f7ea5 100644--- a/TUI/sim.zig+++ b/TUI/sim.zig@@ -277,6 +277,15 @@ test "type /help then enter opens the help overlay" {try std.testing.expect(std.mem.indexOf(u8, paged, "/quit") != null);}+test "type /cache then enter opens the observability overlay" {+ var term: Term = undefined;+ term.init(std.testing.allocator, 80, 24);+ defer term.deinit();+ _ = term.typeText("/cache");+ _ = term.enter();+ try std.testing.expectEqual(app.Overlay.debug, term.model.overlay);+}+test "hoverText on an image chip opens the preview" {var term: Term = undefined;term.init(std.testing.allocator, 80, 24);diff --git a/docs/adr/0010-prompt-cache-max-is-visible.md b/docs/adr/0010-prompt-cache-max-is-visible.mdnew file mode 100644index 00000000..4d6fd4a1--- /dev/null+++ b/docs/adr/0010-prompt-cache-max-is-visible.md@@ -0,0 +1,36 @@+# 0010. Prompt-cache max is a visible posture, not a new default++Status: accepted 2026-08-19++## Context++v0.0.266 already earned the cacheable prefix: sticky `prompt_cache_key`,+names-only skill catalog pinned once, standing goal as one prefix line,+Anthropic `cache_control`, GPT-5.6 explicit breakpoint (ADR 0009), per-agent+partitions, no timestamps. #476 still listed cache-rate as the remaining gap+(~45–58% vs opencode ~85%). The leftover automatic bust is `load_tool_schemas`+rewriting tools JSON. `GRAFF_STABLE_CATALOG=1` exists for that and **measured+empty** on the v0.0.246 audit, so it stays off.++What you could not see: whether this session's prefix was still the same+bytes, which named mutation last moved it, or which remaining levers are+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.+- `/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+ system+tools hash actually changes. Startup compose is not a bust.+- 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.++## Consequences++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.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex af0aea93..8fe92c11 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -20,6 +20,7 @@ record only when you need the evidence or the edge cases.| [0007](0007-plugins-are-read-in-place.md) | Cursor/Claude/Grok/Codex plugins and MCP are read in place (Claude/Cursor cache via installed_plugins.json, Codex via config.toml PluginStore, never walked); skills stay on-demand; MCP stays consent-gated. || [0008](0008-synthetic-evals-use-external-verifiers.md) | Synthetic coding evals promote only external-verifier passes; model judges may tiebreak correctness, never decide it. || [0009](0009-gpt-5-6-explicit-prompt-cache-boundary.md) | GPT-5.6 OpenAI Platform marks the stable prefix explicitly; Codex and xAI stay on their supported keyed automatic-cache paths. |+| [0010](0010-prompt-cache-max-is-visible.md) | Prompt-cache max is `/cache` posture, not a new default; `GRAFF_STABLE_CATALOG` stays opt-in. |## When to write onediff --git a/src/agent.zig b/src/agent.zigindex b2a0fd97..042d5f2a 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -292,6 +292,7 @@ pub const Agent = struct {/// active format is immediately rebuilt; inactive formats remain lazy.pub fn invalidateRootTools(self: *Agent) void {if (self.sub) return;+ @import("prompt_cache_hud.zig").noteBust(.tools);self.tools_anthropic = "";self.tools_openai = "";self.tools_responses = "";diff --git a/src/agent_context.zig b/src/agent_context.zigindex 619cfd8d..8a83bcc7 100644--- a/src/agent_context.zig+++ b/src/agent_context.zig@@ -192,6 +192,7 @@ pub fn usageInt(obj: std.json.ObjectMap, name: []const u8) i64 {/// $0, while an env key on that same provider is metered like any other.pub fn recordCost(self: *Agent, ordinary_in: i64, cache_in: i64, cache_write_in: i64, out: i64) void {g_cost.add(self.io, billing.forProvider(self.provider), self.provider.model, ordinary_in, cache_in, cache_write_in, out);+ if (!self.sub) @import("prompt_cache_hud.zig").noteUsage(@intCast(@max(cache_in, 0)), @intCast(@max(cache_write_in, 0)));}/// #174: ~4-bytes/token estimate of the FULL history serialized as Responsesdiff --git a/src/agent_request.zig b/src/agent_request.zigindex 2cd6d546..0ab1ce74 100644--- a/src/agent_request.zig+++ b/src/agent_request.zig@@ -206,6 +206,7 @@ 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 "");// 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/command_catalog.zig b/src/command_catalog.zigindex 268f8428..8705d1ee 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -71,6 +71,7 @@ pub const commands = [_]Item{.{ .name = "/cost", .desc = "session token usage and cost" },.{ .name = "/usage", .desc = "alias for /cost" },.{ .name = "/debug", .desc = "live content-free observability HUD (turns, tokens, tools, last events)" },+ .{ .name = "/cache", .desc = "prompt-cache posture: prefix hash, hit rate, last bust, remaining max levers" },.{ .name = "/tools", .desc = "session tool balance: codedb-pro vs zigrep vs native usage, gate refusals, skew" },.{ .name = "/animation", .desc = "pick the thinking animation; persists to settings" },.{ .name = "/theme", .usage = "/theme [name]", .desc = "pick a color theme; /theme off resets to your terminal default; persists" },diff --git a/src/commands_misc.zig b/src/commands_misc.zigindex b13fe977..347f12d3 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -1,7 +1,4 @@-//! Misc slash commands + the unknown-command/help fallback, split out of-//! main.zig's handleCommand (600-line goal, issue #123): /todo /jobs /cost-//! /mcp /models /yolo /trace /fleet /save /resume /sessions, plus the-//! terminal handleRest() stage (unknown command → error, or /help dump).+//! Misc slash commands + handleRest() fallback (600-line goal, #123).const std = @import("std");const Io = std.Io;@@ -45,6 +42,7 @@ test { // main.zig is the test root, so this reference is what runs its tests}const pricing = @import("pricing.zig");const obs = @import("obs.zig");+const cache_hud = @import("prompt_cache_hud.zig");const default_context = pricing.default_context;const g_cost = &pricing.g_cost;const pricing_db = @import("pricing_db.zig"); // #557: price-DB age for the /models footer@@ -235,8 +233,8 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,try out.flush();return true;}- if (std.mem.eql(u8, line, "/debug")) {- try obs.renderHud(out);+ if (std.mem.eql(u8, line, "/debug") or std.mem.eql(u8, line, "/cache")) {+ if (std.mem.eql(u8, line, "/debug")) try obs.renderHud(out) else try cache_hud.render(out);try out.flush();return true;}@@ -306,6 +304,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,// Re-render the active catalog so the new tools reach the model;// inactive provider formats stay lazy until a later switch.root.invalidateRootTools();+ @import("prompt_cache_hud.zig").noteBust(.mcp);try root.ensureRootTools(root.provider.kind);root.rebaseContextMeter();const persisted = if (is_remote)diff --git a/src/commands_model.zig b/src/commands_model.zigindex 719a20e0..afb2f006 100644--- a/src/commands_model.zig+++ b/src/commands_model.zig@@ -353,6 +353,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,return true;};root.ultracode_mode = next;+ @import("prompt_cache_hud.zig").noteBust(.mode);const saved = saveThinkingSettings(root.io, root.gpa, root.reasoning, root.fast, root.ultracode_mode, root.show_thinking, root.ai_title);try out.print("ultracode mode: {s}{s}\n", .{ if (root.ultracode_mode) "on" else "off", if (saved) "" else " (not persisted)" });try out.flush();@@ -587,6 +588,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,}if (std.mem.eql(u8, line, "/strict")) {root.strict = !root.strict;+ @import("prompt_cache_hud.zig").noteBust(.mode);root.rebaseContextMeter();try out.print("strict mode {s} — {s}\n", .{if (root.strict) "ON" else "off",diff --git a/src/compact_note_glue.zig b/src/compact_note_glue.zigindex bee843e0..cfe5411f 100644--- a/src/compact_note_glue.zig+++ b/src/compact_note_glue.zig@@ -91,6 +91,7 @@ pub fn maybeWrite(self: *Agent) Decision {// be re-composed to reach the next request — the same refresh a mid-// session `/never` performs, and for the same reason.prompts.armCompactNotes(self.session_name);+ @import("prompt_cache_hud.zig").noteBust(.compact);playbook_glue.refreshRoot(self, self.arena);if (!main_mod.json_mode) self.say(" 📝 wrote a pre-compaction note to self ({d} chars)\n", .{reply.len}) catch {};if (self.tracer) |tr| tr.note("compact", "wrote a pre-compaction note to self (#391)");diff --git a/src/help.zig b/src/help.zigindex ba9586e3..7dce5330 100644--- a/src/help.zig+++ b/src/help.zig@@ -33,7 +33,7 @@ pub const sections = [_]Section{.{ .title = "working autonomously", .names = &.{ "/goal", "/loop", "/review", "/plan", "/todo", "/jobs", "/ultracode", "/strict", "/yolo", "/never" } },.{ .title = "talking to other graffs", .names = &.{ "/tell", "/peek" }, .blurb = peers_blurb },.{ .title = "your setup", .names = &.{ "/login", "/key", "/cost", "/usage", "/privacy", "/mcp", "/import-claude", "/skills", "/plugins", "/agents", "/hooks", "/tools", "/fleet" } },- .{ .title = "context & history", .names = &.{ "/compact", "/btw", "/doctor", "/debug", "/trace", "/trajectory" } },+ .{ .title = "context & history", .names = &.{ "/compact", "/btw", "/doctor", "/debug", "/cache", "/trace", "/trajectory" } },.{ .title = "shell & images", .names = &.{ "/bash", "/image", "/images", "/paste" } },.{ .title = "look & feel", .names = &.{ "/theme", "/animation", "/title" } },.{ .title = "this list", .names = &.{"/help"} },diff --git a/src/mainloop.zig b/src/mainloop.zigindex fd5ba01a..f5d36644 100644--- a/src/mainloop.zig+++ b/src/mainloop.zig@@ -1,5 +1,4 @@-//! Root interactive/JSON event loop. `main` owns setup and storage; `Ctx` holds-//! borrowed pointers valid until `run` returns for final session cleanup.+//! Root interactive/JSON event loop. `main` owns setup; `Ctx` is borrowed until `run` returns.const std = @import("std");const Io = std.Io;@@ -26,7 +25,7 @@ const goal_state = @import("goal_state.zig");const goal_flow = @import("goal_flow.zig");const goal_pacing = @import("goal_pacing.zig");const eval_memory = @import("eval_memory.zig");-const json_controls = @import("json_controls.zig"); // #415: the --json controls that never become a turn+const json_controls = @import("json_controls.zig");const json_inbox = @import("json_inbox.zig");const mainloop_score = @import("mainloop_score.zig");const mainloop_trace = @import("mainloop_trace.zig");@@ -73,7 +72,6 @@ pub fn run(ctx: *Ctx) !void {// Trajectory spine: each turn's parent is the previous; a changed prompt fingerprint marks a set_system_prompt edge.var prev_turn_id: u64 = 0;var prev_prompt_fp: [16]u8 = scoring.promptFingerprint(ctx.root.systemPrompt());-// Armed only after a clean /loop turn and consumed by the next read (#226).const loop_iter_cap: u32 = 25; // hard per-/loop iteration bound (never-completing-model guard)var loop_iters_left: u32 = 0; // continuation turns still authorized this /loop run@@ -217,7 +215,8 @@ pub fn run(ctx: *Ctx) !void {if (std.mem.eql(u8, rtype, "set_agent")) {const id = if (parsed.object.get("id")) |v| (if (v == .string) v.string else "") else "";if (id.len == 0) {- try prompts.setSystemPrompts(ctx.root, ctx.sys_normal, ctx.arena); // #326: reset to the startup base, all four variants+ @import("prompt_cache_hud.zig").noteBust(.persona);+ try prompts.setSystemPrompts(ctx.root, ctx.sys_normal, ctx.arena); // #326: reset to the startup base, all four variantsctx.root.rebaseContextMeter();ctx.root.emit(.{ .type = "agent", .ok = true, .id = id, .chars = ctx.root.sys_normal.len });continue;@@ -228,6 +227,7 @@ pub fn run(ctx: *Ctx) !void {continue;};const persona_base = try std.fmt.allocPrint(ctx.arena, "{s}\n\n{s}", .{ ctx.sys_normal, prompt });+ @import("prompt_cache_hud.zig").noteBust(.persona);try prompts.setSystemPrompts(ctx.root, persona_base, ctx.arena); // #326: recomputes strict + ultra tooctx.root.rebaseContextMeter();ctx.root.emit(.{ .type = "agent", .ok = true, .id = id, .chars = ctx.root.sys_normal.len });@@ -277,6 +277,7 @@ pub fn run(ctx: *Ctx) !void {try std.fmt.allocPrint(ctx.arena, "{s}\n\n{s}", .{ ctx.root.sys_normal, text })elsetry ctx.arena.dupe(u8, text);+ @import("prompt_cache_hud.zig").noteBust(.persona);try prompts.setSystemPrompts(ctx.root, new_base, ctx.arena); // #326: recomputes strict + ultra tooctx.root.rebaseContextMeter();ctx.root.emit(.{ .type = "system_prompt", .ok = true, .append = append, .chars = ctx.root.sys_normal.len });diff --git a/src/obs.zig b/src/obs.zigindex 6015db28..a6be2a03 100644--- a/src/obs.zig+++ b/src/obs.zig@@ -333,6 +333,7 @@ pub fn renderHud(w: *Io.Writer) !void {try w.writeByte('\n');}}+ try @import("prompt_cache_hud.zig").renderLine(w);try w.writeAll(" last events\n");var recs: [ring_cap]Record = undefined;const n = recent(&recs);@@ -456,13 +457,14 @@ test "note: session and prompt never store paths or prompt text" {try std.testing.expectEqual(EventName.user_prompt, recs[1].name);try std.testing.expectEqualStrings("grok-4", recs[1].modelSlice());try std.testing.expectEqual(@as(u32, 7), recs[1].prompt_len);- var buf: [1024]u8 = undefined;+ var buf: [2048]u8 = undefined;var w: Io.Writer = .fixed(&buf);try renderHud(&w);const text = w.buffered();try std.testing.expect(!contains(text, "/Users/secret"));try std.testing.expect(!contains(text, "traces/x"));try std.testing.expect(contains(text, "session_start"));+ try std.testing.expect(contains(text, "cache"));}test "note: tool decision and result stay content-free" {@@ -492,7 +494,7 @@ test "note: tool decision and result stay content-free" {try std.testing.expectEqual(@as(u64, 1), s.decisions_allow);try std.testing.expectEqual(@as(u64, 1), s.decisions_deny);try std.testing.expectEqual(@as(u64, 1), s.tool_calls);- var buf: [1024]u8 = undefined;+ var buf: [2048]u8 = undefined;var w: Io.Writer = .fixed(&buf);try renderHud(&w);const text = w.buffered();diff --git a/src/obs_cost_test.zig b/src/obs_cost_test.zigindex cf070aa0..5607017b 100644--- a/src/obs_cost_test.zig+++ b/src/obs_cost_test.zig@@ -66,6 +66,7 @@ test "usage/debug match the cost-tally renderer and add turn/decision extras" {try std.testing.expect(contains(usage, cost));try std.testing.expect(contains(debug, cost));try std.testing.expect(contains(debug, "turns"));+ try std.testing.expect(contains(debug, "cache"));try std.testing.expect(contains(debug, "deny"));try std.testing.expect(contains(debug, "completed"));try std.testing.expect(!contains(usage, "chars sent"));diff --git a/src/playbook_glue.zig b/src/playbook_glue.zigindex 1a98b523..bda9062b 100644--- a/src/playbook_glue.zig+++ b/src/playbook_glue.zig@@ -65,6 +65,7 @@ pub fn noteConstraint(agent: *Agent, input: std.json.Value) ExecResult {// retrying or apologising for a ledger that is already correct..is_error = !std.mem.eql(u8, r.reason, "already recorded (same normalized text)"),};+ @import("prompt_cache_hud.zig").noteBust(.playbook);refreshRoot(agent, agent.arena);agent.say(" {s}⛔ constraint recorded ({s}){s} {s}\n", .{ style.yellow, r.id, style.reset, text }) catch {};return .{ .text = std.fmt.allocPrint(agent.arena, "constraint recorded as {s}. It is now in {s} and rides every subagent, workflow and pipeline brief from here on, in this session and in later ones — you do not need to restate it.", .{ r.id, playbook.path }) catch "constraint recorded", .is_error = false };@@ -102,6 +103,7 @@ pub fn command(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Writerif (std.mem.startsWith(u8, arg, "rm ") or std.mem.startsWith(u8, arg, "remove ")) {const id = std.mem.trim(u8, arg[if (arg[0] == 'r' and arg[1] == 'm') 3 else 7..], " \t");if (playbook.retire(root.io, arena, id)) {+ @import("prompt_cache_hud.zig").noteBust(.playbook);refreshRoot(root, arena);try out.print("retired {s} — it no longer rides new briefs (the record stays in the log as a tombstone)\n", .{id});} else try out.print("no live playbook item with id '{s}' — /never lists them\n", .{id});@@ -112,6 +114,7 @@ pub fn command(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Writerconst provenance = std.fmt.bufPrint(&prov_buf, "user:{d}", .{@import("util.zig").unixMs(root.io)}) catch "user";const r = playbook.add(root.io, arena, arg, .user, provenance);if (r.ok) {+ @import("prompt_cache_hud.zig").noteBust(.playbook);refreshRoot(root, arena);try out.print("{s}⛔ recorded {s}{s} — this now rides every brief, in this session and later ones\n", .{ style.yellow, r.id, style.reset });} else try out.print("not recorded: {s}\n", .{r.reason});diff --git a/src/prompt_cache_hud.zig b/src/prompt_cache_hud.zignew file mode 100644index 00000000..7bfed7f6--- /dev/null+++ b/src/prompt_cache_hud.zig@@ -0,0 +1,309 @@+//! Content-free prompt-cache posture: `/cache` and a one-line `/debug` row.+//!+//! Stores lengths, a prefix hash, and named bust reasons — never prompt text,+//! paths, or tool bodies. Codex's rule is still the product rule: the old+//! prompt must be an exact prefix of the new one. This module is how you see+//! whether this session is still earning that.++const std = @import("std");+const Io = std.Io;++const pricing = @import("pricing.zig");+const mcp_schema_gate = @import("mcp_schema_gate.zig");++pub const Bust = enum {+ none,+ start,+ goal,+ playbook,+ compact,+ transcript,+ persona,+ tools,+ mcp,+ mode,+ other,+};++pub const Snap = struct {+ prefix: u32 = 0,+ prev: u32 = 0,+ sys_bytes: u32 = 0,+ tools_bytes: u32 = 0,+ same: bool = true,+ requests: u32 = 0,+ busts: u32 = 0,+ last_bust: Bust = .none,+ last_read: u64 = 0,+ last_write: u64 = 0,+};++var lock: std.atomic.Value(bool) = .init(false);+var snap: Snap = .{};+var pending: Bust = .none;+var g_io: ?Io = null;++fn acquire() void {+ while (lock.cmpxchgWeak(false, true, .acquire, .monotonic) != null) std.atomic.spinLoopHint();+}+fn release() void {+ lock.store(false, .release);+}++pub fn reset() void {+ acquire();+ defer release();+ snap = .{};+ pending = .none;+ g_io = null;+}++pub fn snapshot() Snap {+ acquire();+ defer release();+ return snap;+}++/// Hash of the bytes the provider prefixes. First 32 bits of SHA-256 — enough+/// to see a change, not enough to recover the prompt.+pub fn prefixHash(system: []const u8, tools: []const u8) u32 {+ var digest: [32]u8 = undefined;+ var h = std.crypto.hash.sha2.Sha256.init(.{});+ h.update(system);+ h.update("\x1e");+ h.update(tools);+ h.final(&digest);+ return std.mem.readInt(u32, digest[0..4], .big);+}++/// Startup compose is not a bust. After the first request, a named reason+/// waits for the next `noteRequest` and only counts if the hash actually moved.+pub fn noteBust(reason: Bust) void {+ acquire();+ defer release();+ if (snap.requests == 0) return;+ pending = reason;+}++pub fn noteUsage(read: u64, write: u64) void {+ acquire();+ defer release();+ snap.last_read = read;+ snap.last_write = write;+}++pub fn noteRequest(io: Io, system: []const u8, tools: []const u8) void {+ const hash = prefixHash(system, tools);+ acquire();+ defer release();+ g_io = io;+ const prev = snap.prefix;+ const had = snap.requests > 0;+ const changed = had and hash != prev;+ if (changed) {+ snap.busts += 1;+ snap.last_bust = if (pending != .none) pending else .other;+ } else if (!had) {+ snap.last_bust = .start;+ }+ pending = .none;+ snap.prev = prev;+ snap.prefix = hash;+ snap.sys_bytes = std.math.cast(u32, system.len) orelse std.math.maxInt(u32);+ snap.tools_bytes = std.math.cast(u32, tools.len) orelse std.math.maxInt(u32);+ snap.same = !changed;+ snap.requests += 1;+}++pub fn bustLabel(b: Bust) []const u8 {+ return switch (b) {+ .none => "none",+ .start => "start",+ .goal => "goal",+ .playbook => "playbook",+ .compact => "compact",+ .transcript => "transcript",+ .persona => "persona",+ .tools => "tools",+ .mcp => "mcp",+ .mode => "mode",+ .other => "other",+ };+}++fn kib(n: u32) u32 {+ return n / 1024;+}++fn hitPct(cached: u64, billed_in: u64) u64 {+ const den = billed_in +| cached;+ if (den == 0) return 0;+ return @min((cached *| 100) / den, 100);+}++/// One row for `/debug`. Content-free.+pub fn renderLine(w: *Io.Writer) !void {+ const s = snapshot();+ if (s.requests == 0) {+ try w.writeAll(" cache (no API call yet — /cache shows the remaining max levers)\n");+ return;+ }+ try w.print(" cache {d}% hit · prefix {s} · {d} bust{s}", .{+ sessionHitPct(),+ if (s.same) "same" else "changed",+ s.busts,+ if (s.busts == 1) "" else "s",+ });+ if (s.busts > 0) try w.print(" ({s})", .{bustLabel(s.last_bust)});+ try w.writeByte('\n');+}++/// The `/cache` HUD: current posture plus the remaining product levers.+pub fn render(w: *Io.Writer) !void {+ const s = snapshot();+ try w.writeAll("prompt cache\n");+ if (s.requests == 0) {+ try w.writeAll(" prefix (no request yet)\n");+ } else {+ try w.print(" prefix {x:0>8} (sys {d}kB · tools {d}kB) {s}\n", .{+ s.prefix,+ kib(s.sys_bytes),+ kib(s.tools_bytes),+ if (s.same) "same" else "changed",+ });+ try w.print(" last {d} read · {d} write\n", .{ s.last_read, s.last_write });+ try w.print(" session {d}% hit", .{sessionHitPct()});+ if (g_io) |io| {+ const c = pricing.g_cost.snap(io);+ try w.print(" ({d} cached / {d} in) · {d} writes", .{+ c.cache_tokens, c.in_tokens +| c.cache_tokens, c.cache_write_tokens,+ });+ }+ try w.writeByte('\n');+ 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)"});+ 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)+ \\+ );+}++fn sessionHitPct() u64 {+ const io = g_io orelse return 0;+ const c = pricing.g_cost.snap(io);+ return hitPct(c.cache_tokens, c.in_tokens);+}++fn contains(hay: []const u8, needle: []const u8) bool {+ return std.mem.indexOf(u8, hay, needle) != null;+}++test "first prefix is start, not a bust" {+ reset();+ defer reset();+ noteRequest(std.testing.io, "system", "[]");+ const s = snapshot();+ try std.testing.expectEqual(@as(u32, 1), s.requests);+ try std.testing.expectEqual(@as(u32, 0), s.busts);+ try std.testing.expectEqual(Bust.start, s.last_bust);+ try std.testing.expect(s.same);+}++test "identical prefix stays same" {+ reset();+ defer reset();+ noteRequest(std.testing.io, "system", "[]");+ const first = snapshot().prefix;+ noteRequest(std.testing.io, "system", "[]");+ const s = snapshot();+ try std.testing.expectEqual(first, s.prefix);+ try std.testing.expectEqual(@as(u32, 0), s.busts);+ try std.testing.expect(s.same);+}++test "changed prefix without a named reason is other" {+ reset();+ defer reset();+ noteRequest(std.testing.io, "system", "[]");+ noteRequest(std.testing.io, "system-b", "[]");+ const s = snapshot();+ try std.testing.expectEqual(@as(u32, 1), s.busts);+ try std.testing.expectEqual(Bust.other, s.last_bust);+ try std.testing.expect(!s.same);+}++test "named bust waits for a real hash change" {+ reset();+ defer reset();+ noteRequest(std.testing.io, "system", "[]");+ noteBust(.goal);+ noteRequest(std.testing.io, "system", "[]");+ try std.testing.expectEqual(@as(u32, 0), snapshot().busts);+ noteBust(.playbook);+ noteRequest(std.testing.io, "system-2", "[]");+ const s = snapshot();+ try std.testing.expectEqual(@as(u32, 1), s.busts);+ try std.testing.expectEqual(Bust.playbook, s.last_bust);+}++test "startup noteBust is ignored" {+ reset();+ defer reset();+ noteBust(.persona);+ noteRequest(std.testing.io, "system", "[]");+ try std.testing.expectEqual(@as(u32, 0), snapshot().busts);+ try std.testing.expectEqual(Bust.start, snapshot().last_bust);+}++test "render stays content-free and names remaining levers" {+ reset();+ defer reset();+ noteRequest(std.testing.io, "SECRET-PROMPT /Users/me/repo", "[{\"name\":\"bash\"}]");+ noteUsage(6002, 0);+ var buf: [2048]u8 = undefined;+ var w: Io.Writer = .fixed(&buf);+ try render(&w);+ const text = w.buffered();+ try std.testing.expect(contains(text, "prompt cache"));+ 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, "SECRET-PROMPT"));+ try std.testing.expect(!contains(text, "/Users/me"));+ try std.testing.expect(!contains(text, "bash"));+}++test "renderLine is one content-free row" {+ reset();+ defer reset();+ var empty_buf: [256]u8 = undefined;+ var empty_w: Io.Writer = .fixed(&empty_buf);+ try renderLine(&empty_w);+ try std.testing.expect(contains(empty_w.buffered(), "no API call"));++ noteRequest(std.testing.io, "system", "[]");+ noteRequest(std.testing.io, "system-2", "[]");+ var buf: [256]u8 = undefined;+ var w: Io.Writer = .fixed(&buf);+ try renderLine(&w);+ const text = w.buffered();+ try std.testing.expect(contains(text, "cache"));+ try std.testing.expect(contains(text, "changed"));+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, text, "\n"));+}++test "hitPct saturates and handles zero" {+ try std.testing.expectEqual(@as(u64, 0), hitPct(0, 0));+ try std.testing.expectEqual(@as(u64, 50), hitPct(50, 50));+ try std.testing.expectEqual(@as(u64, 100), hitPct(200, 0));+}++test "bustLabel covers every tag" {+ try std.testing.expectEqualStrings("goal", bustLabel(.goal));+ try std.testing.expectEqualStrings("tools", bustLabel(.tools));+ try std.testing.expectEqualStrings("start", bustLabel(.start));+}diff --git a/src/prompts.zig b/src/prompts.zigindex 9680dc2c..ef3df401 100644--- a/src/prompts.zig+++ b/src/prompts.zig@@ -340,6 +340,7 @@ pub fn pinStandingGoal(agent: *Agent, arena: Allocator) void {}}if (agent.sys_base.len == 0) return;+ @import("prompt_cache_hud.zig").noteBust(.goal);setSystemPrompts(agent, agent.sys_base, arena) catch {};}diff --git a/src/repl_model_commands.zig b/src/repl_model_commands.zigindex 0917cdd4..3de44a36 100644--- a/src/repl_model_commands.zig+++ b/src/repl_model_commands.zig@@ -113,8 +113,8 @@ pub fn runCommand(self: *Model, line: []const u8) void {self.push(.info, "hooks run around the agent loop, not the chat repl") catch {};} else if (std.mem.eql(u8, cmd, "/loop")) {self.push(.info, "`/loop` schedules repeated runs in the main session, not the chat repl") catch {};- } else if (eqlAny(cmd, &.{ "/trace", "/trajectory" })) {- self.push(.info, "trace/trajectory logging is a main-session feature") catch {};+ } else if (eqlAny(cmd, &.{ "/trace", "/trajectory", "/cache" })) {+ self.push(.info, "trace/trajectory/cache logging is a main-session feature") catch {};} else if (eqlAny(cmd, &.{ "/save", "/resume", "/sessions", "/workspace", "/ws", "/plugins" })) {self.push(.info, "the chat repl is ephemeral — session save/resume/list/workspace/plugins lives in the main `graff` session") catch {};} else if (std.mem.eql(u8, cmd, "/images")) {diff --git a/src/session_start.zig b/src/session_start.zigindex 7e3ee858..ea08f093 100644--- a/src/session_start.zig+++ b/src/session_start.zig@@ -345,6 +345,7 @@ pub fn initTelemetry(io: Io, gpa: Allocator, client: *std.http.Client, environ_mdefault_telemetry_endpoint;const telem_home = keys_cli.homeEnv(environ_map) orelse "";obs.reset();+ @import("prompt_cache_hud.zig").reset();obs.attach(io);obs.export_endpoint = telem_endpoint;return .{