Skip to content

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

Python

spec(prompt_cache): showcase the maximizing walk

Cursor Agent0d84a959f702
diff --git a/lean-proofs/Graff/PromptPrefix.lean b/lean-proofs/Graff/PromptPrefix.lean
index 749d218a..7fa79bb1 100644
--- a/lean-proofs/Graff/PromptPrefix.lean
+++ b/lean-proofs/Graff/PromptPrefix.lean
@@ -62,6 +62,11 @@ theorem only_one_hit_cell : hitCells = 1 := by native_decide
theorem names_once_hits :
cacheable { catalog := .namesOnly, pin := .once } = true := by native_decide
+/-- Maximize iff the measured cell. The other five cells are the busts. -/
+theorem maximize_iff (c : Cell) :
+ cacheable c = true ↔ (c.catalog = .namesOnly ∧ c.pin = .once) := by
+ cases c.catalog <;> cases c.pin <;> native_decide
+
theorem bodies_never_hit (p : Pin) :
cacheable { catalog := .withBodies, pin := p } = false := by
cases p <;> native_decide
@@ -129,6 +134,11 @@ theorem skill_events_keep_prefix (c : Catalog) :
run s [.skillLoad, .skillList, .rescan, .turn] = s := by
native_decide
+/-- The live session: pin names-only, then skill/list/rescan/turn still HIT. -/
+theorem maximizing_walk :
+ hitOk (run {} [.start .namesOnly, .skillLoad, .skillList, .rescan, .turn]) = true := by
+ native_decide
+
theorem names_start_hits :
hitOk (step {} (.start .namesOnly)) = true := by native_decide
diff --git a/lean-proofs/KERNELS.md b/lean-proofs/KERNELS.md
index 8fbad085..3438d3e9 100644
--- a/lean-proofs/KERNELS.md
+++ b/lean-proofs/KERNELS.md
@@ -14,7 +14,8 @@ the snapshot of that function.
Process kernels: `GoalLoop` (standing has no retire edge; harness-done
needs a done write), `PromptCache` (sub never spawns; join restores the
root partition), `PromptPrefix` (names + triggers, pinned once; skill
-load/list/rescan do not rewrite the prefix), `TerminalModes` (`Op`/`step`
+load/list/rescan do not rewrite the prefix — showcase with
+`python3 spec/conformance.py --showcase`), `TerminalModes` (`Op`/`step`
mode map + kitty depth; enable++restore returns to Idle; pop floors;
alt-screen leave is last), `PathConfine` (component walk: Escaped and
Absolute absorb), `Transport` (a sub never takes WS; only one live root
diff --git a/spec/README.md b/spec/README.md
index 9e4cb8a1..7c2cc99f 100644
--- a/spec/README.md
+++ b/spec/README.md
@@ -62,6 +62,7 @@ python3 spec/conformance.py --export # regenerate kernels/*.json and GoalLoop
python3 spec/conformance.py --diagram goal_loop # live Event/step projection
python3 spec/conformance.py --diagram prompt_cache
python3 spec/conformance.py --diagram prompt_prefix
+python3 spec/conformance.py --showcase # prefix cube + maximizing walk + key machine
python3 spec/conformance.py --diagram terminal_modes
python3 spec/conformance.py --diagram path_confine
python3 spec/conformance.py --diagram transport
@@ -78,6 +79,7 @@ BashPolicy stays a command cube this turn. The shape of a subagent fleet
is not a Shape cell — PromptCache / PathConfine / Transport force every
child through a machine; Score files that unbounded fleet as one stage
row after the join. `--diagram` prints a live `step` projection;
+`--showcase` prints the one HIT cell and the session walk that stays on it;
`--export` writes those fences into `kernels/*.md`.
The Zig test is the impl half of the harness: it sets the same flags the
diff --git a/spec/conformance.py b/spec/conformance.py
index 35743e54..ec624bce 100644
--- a/spec/conformance.py
+++ b/spec/conformance.py
@@ -337,16 +337,9 @@ def _ref(fn, name: str) -> int:
raise Counterexample(name, None, str(e)) from e
-def check_goal_loop() -> int:
- return _ref(goal_check_properties, "goal_loop")
-
-
-def check_prompt_cache() -> int:
- return _ref(cache_check_properties, "prompt_cache")
-
-
-def check_prompt_prefix() -> int:
- return _ref(prefix_check_properties, "prompt_prefix")
+def check_goal_loop() -> int: return _ref(goal_check_properties, "goal_loop")
+def check_prompt_cache() -> int: return _ref(cache_check_properties, "prompt_cache")
+def check_prompt_prefix() -> int: return _ref(prefix_check_properties, "prompt_prefix")
def check_path_confine() -> int:
@@ -525,6 +518,7 @@ def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--export", action="store_true", help="write spec/kernels/*.json")
parser.add_argument("--diagram", metavar="KERNEL", help="print live Event/step projection")
+ parser.add_argument("--showcase", nargs="?", const="prompt", metavar="KERNEL", help="prompt-cache maximizing walk")
parser.add_argument("--break", dest="mutate", metavar="KIND", help="mutate the model to demo a counterexample")
parser.add_argument("--lean", action="store_true", help="lake build lean-proofs if lake is installed")
parser.add_argument("--impl", action="store_true", help="run the Zig fixture tests")
@@ -539,15 +533,19 @@ def main() -> int:
print(json.dumps(inv, indent=2) if args.json else render(inv))
return 0 if inv["ok"] else 1
+ if args.showcase:
+ from ref.prompt_showcase import showcase
+ try:
+ sys.stdout.write(showcase(args.showcase))
+ return 0
+ except ValueError as e:
+ print(e, file=sys.stderr)
+ return 2
if args.diagram:
mods = {
- "goal_loop": "ref.goal_loop",
- "prompt_cache": "ref.prompt_cache",
- "prompt_prefix": "ref.prompt_prefix",
- "terminal_modes": "ref.terminal_modes",
- "path_confine": "ref.path_confine",
- "transport": "ref.transport",
- "score": "ref.score",
+ "goal_loop": "ref.goal_loop", "prompt_cache": "ref.prompt_cache",
+ "prompt_prefix": "ref.prompt_prefix", "terminal_modes": "ref.terminal_modes",
+ "path_confine": "ref.path_confine", "transport": "ref.transport", "score": "ref.score",
}
path = mods.get(args.diagram)
if path is None:
diff --git a/spec/kernels/prompt_cache.md b/spec/kernels/prompt_cache.md
index 17568814..eb0069cc 100644
--- a/spec/kernels/prompt_cache.md
+++ b/spec/kernels/prompt_cache.md
@@ -9,7 +9,9 @@ not mint a key. Sub never spawns. Join restores the root partition.
The diagram is the projection of the live Python `step` (same function
`check_properties` walks). Emit it with
-`python3 spec/conformance.py --diagram prompt_cache`.
+`python3 spec/conformance.py --diagram prompt_cache`. The maximizing
+walk (sticky key + join restores) is
+`python3 spec/conformance.py --showcase prompt_cache`.
```mermaid
stateDiagram-v2
diff --git a/spec/kernels/prompt_prefix.md b/spec/kernels/prompt_prefix.md
index 048d6ce0..d4311d7a 100644
--- a/spec/kernels/prompt_prefix.md
+++ b/spec/kernels/prompt_prefix.md
@@ -10,7 +10,26 @@ rebuild that changes the catalog busts the prefix (Codex: the old
prompt must be an exact prefix of the new one).
Wording is out of Lean. The 6-cell cube is catalog kind × pin policy;
-exactly one cell is cacheable (`names_only` × `once`).
+exactly one cell is cacheable (`names_only` × `once`). That is the
+measured path. Showcase it with
+`python3 spec/conformance.py --showcase`.
+
+| catalog \ pin | `once` | `every_rebuild` |
+|---|---|---|
+| `names_only` | **HIT** | miss |
+| `with_bodies` | miss | miss |
+| `with_paths` | miss | miss |
+
+```mermaid
+sequenceDiagram
+ participant P as prefix
+ P->>P: start names_only (HIT)
+ P->>P: skill_load (id, HIT)
+ P->>P: skill_list (id, HIT)
+ P->>P: rescan (id, HIT)
+ P->>P: turn (id, HIT)
+ P->>P: rebuild with_paths (BUST)
+```
```mermaid
stateDiagram-v2
diff --git a/spec/ref/prompt_cache.py b/spec/ref/prompt_cache.py
index e0724994..0c6eabc8 100644
--- a/spec/ref/prompt_cache.py
+++ b/spec/ref/prompt_cache.py
@@ -168,7 +168,9 @@ def kernel_md() -> str:
"\n"
"The diagram is the projection of the live Python `step` (same function\n"
"`check_properties` walks). Emit it with\n"
- "`python3 spec/conformance.py --diagram prompt_cache`.\n"
+ "`python3 spec/conformance.py --diagram prompt_cache`. The maximizing\n"
+ "walk (sticky key + join restores) is\n"
+ "`python3 spec/conformance.py --showcase prompt_cache`.\n"
"\n"
"```mermaid\n"
f"{body}\n"
diff --git a/spec/ref/prompt_prefix.py b/spec/ref/prompt_prefix.py
index b4dd48da..e0be0deb 100644
--- a/spec/ref/prompt_prefix.py
+++ b/spec/ref/prompt_prefix.py
@@ -144,8 +144,34 @@ def mermaid() -> str:
return "\n".join(lines) + "\n"
+def cube_table() -> str:
+ marks = {"HIT": "**HIT**", "miss": "miss"}
+ rows = ["| catalog \\ pin | `once` | `every_rebuild` |", "|---|---|---|"]
+ for cat in CATALOGS:
+ cells = []
+ for pin in PINS:
+ hit = cacheable(Cell(cat, pin))
+ cells.append(marks["HIT"] if hit else marks["miss"])
+ rows.append(f"| `{cat}` | {cells[0]} | {cells[1]} |")
+ return "\n".join(rows)
+
+
+def max_walk_mermaid() -> str:
+ return (
+ "sequenceDiagram\n"
+ " participant P as prefix\n"
+ " P->>P: start names_only (HIT)\n"
+ " P->>P: skill_load (id, HIT)\n"
+ " P->>P: skill_list (id, HIT)\n"
+ " P->>P: rescan (id, HIT)\n"
+ " P->>P: turn (id, HIT)\n"
+ " P->>P: rebuild with_paths (BUST)\n"
+ )
+
+
def kernel_md() -> str:
body = mermaid().rstrip()
+ walk = max_walk_mermaid().rstrip()
return (
"# Kernel: prompt prefix (cache HIT)\n"
"\n"
@@ -159,7 +185,15 @@ def kernel_md() -> str:
"prompt must be an exact prefix of the new one).\n"
"\n"
"Wording is out of Lean. The 6-cell cube is catalog kind × pin policy;\n"
- "exactly one cell is cacheable (`names_only` × `once`).\n"
+ "exactly one cell is cacheable (`names_only` × `once`). That is the\n"
+ "measured path. Showcase it with\n"
+ "`python3 spec/conformance.py --showcase`.\n"
+ "\n"
+ f"{cube_table()}\n"
+ "\n"
+ "```mermaid\n"
+ f"{walk}\n"
+ "```\n"
"\n"
"```mermaid\n"
f"{body}\n"
@@ -232,5 +266,15 @@ def check_properties() -> int:
raise ValueError("trace: rebuild that changes catalog must bust")
if not hit_ok(run(idle, [("start", "names_only"), ("rebuild_into_prefix", "names_only")])):
raise ValueError("trace: same-catalog rebuild should stay")
+ if not hit_ok(run(idle, [
+ ("start", "names_only"),
+ ("skill_load",),
+ ("skill_list",),
+ ("rescan",),
+ ("turn",),
+ ])):
+ raise ValueError("trace: maximizing walk left the HIT cell")
+ from ref.prompt_showcase import check_maximizing
+ check_maximizing()
check_diagram()
return n
diff --git a/spec/ref/prompt_showcase.py b/spec/ref/prompt_showcase.py
new file mode 100644
index 00000000..c828c76f
--- /dev/null
+++ b/spec/ref/prompt_showcase.py
@@ -0,0 +1,153 @@
+"""Showcase: do the prompt-cache kernels actually maximize?
+
+PromptCache is the key (who emits it, spawn/join). PromptPrefix is the
+bytes under that key. Together they are the conditions that keep the old
+prompt an exact prefix of the new one. Provider HIT tokens stay a
+never-kernel — this file prints the walk, not a bill.
+"""
+
+from __future__ import annotations
+
+from ref.prompt_cache import State as CacheState
+from ref.prompt_cache import run as cache_run
+from ref.prompt_cache import step as cache_step
+from ref.prompt_prefix import CATALOGS, PINS, Cell, State
+from ref.prompt_prefix import all_cells, cacheable, hit_ok, run, step
+
+
+MAX_EVENTS: list[tuple] = (
+ ("start", "names_only"),
+ ("skill_load",),
+ ("skill_list",),
+ ("rescan",),
+ ("turn",),
+)
+
+
+def _mark(ok: bool) -> str:
+ return "HIT" if ok else "miss"
+
+
+def cube_lines() -> list[str]:
+ lines = ["PromptPrefix 6 cells 1 HIT (catalog × pin)", ""]
+ head = f" {'catalog':<14} {'once':<8} {'every_rebuild'}"
+ lines.append(head)
+ lines.append(" " + "-" * (len(head) - 2))
+ for cat in CATALOGS:
+ once = _mark(cacheable(Cell(cat, "once")))
+ every = _mark(cacheable(Cell(cat, "every_rebuild")))
+ note = " ← measured" if cat == "names_only" else ""
+ if cat == "with_paths":
+ note = " ← Codex file: paths"
+ lines.append(f" {cat:<14} {once:<8} {every}{note}")
+ hits = sum(1 for c in all_cells() if cacheable(c))
+ if hits != 1:
+ raise ValueError(f"showcase: hit cells {hits}, want 1")
+ return lines
+
+
+def walk_lines() -> list[str]:
+ lines = ["maximizing walk (live session)", ""]
+ s = State()
+ for e in MAX_EVENTS:
+ s = step(s, e)
+ lab = e[0] if e[0] != "start" else f"start {e[1]}"
+ ok = hit_ok(s)
+ lines.append(
+ f" {lab:<22} frozen={int(s.prefix_frozen)} "
+ f"catalog={s.catalog:<12} {_mark(ok)}"
+ )
+ if not ok:
+ raise ValueError(f"showcase: {lab} left the HIT cell")
+ same = run(s, [("rebuild_into_prefix", "names_only")])
+ if not hit_ok(same):
+ raise ValueError("showcase: same-catalog rebuild busted")
+ lines.append(
+ f" {'rebuild names_only':<22} frozen={int(same.prefix_frozen)} "
+ f"catalog={same.catalog:<12} HIT"
+ )
+ bust = run(s, [("rebuild_into_prefix", "with_paths")])
+ if hit_ok(bust):
+ raise ValueError("showcase: path rebuild stayed HIT")
+ lines.append(
+ f" {'rebuild with_paths':<22} frozen={int(bust.prefix_frozen)} "
+ f"catalog={bust.catalog:<12} miss (bust)"
+ )
+ return lines
+
+
+def cache_lines() -> list[str]:
+ idle = CacheState()
+ child = cache_step(idle, ("spawn", False, "worktree"))
+ if child.partition != "child" or child.seat != "sub":
+ raise ValueError("showcase: spawn did not isolate")
+ if cache_step(child, ("spawn", True, "shared_cwd")) != child:
+ raise ValueError("showcase: sub spawned")
+ back = cache_step(child, ("join",))
+ if back.partition != "root" or back.label != "main":
+ raise ValueError("showcase: join lost the root key")
+ if cache_run(idle, [("spawn", False, "shared_cwd"), ("join",)]).partition != "root":
+ raise ValueError("showcase: spawn+join lost the root key")
+ return [
+ "PromptCache 48 cells 32 emit key 24 spawn_ok",
+ "",
+ " openai/responses emit prompt_cache_key; anthropic does not",
+ " label=main → root partition; isolation does not mint a key",
+ " spawn isolates the child; sub never spawns; join restores root",
+ " turn is identity (sticky key)",
+ "",
+ " Root --spawn--> Child --join--> Root (root key restored)",
+ " Child --spawn--> Child (no second partition)",
+ ]
+
+
+def live_lines() -> list[str]:
+ return [
+ "live Zig (the impl half)",
+ "",
+ " promptCatalog names + triggers, sorted, no bodies, no file:",
+ " execSkill list/load do not rewrite the pinned g_skills prefix",
+ " /skills reload updates the tool list; does not rebuild sys_normal",
+ " buildSystemPrompt pins the catalog once at session start",
+ " promptCacheKey sticky per project; child is a suffix",
+ ]
+
+
+def verdict() -> str:
+ return "verdict: maximizing (1/6 prefix cells, sticky key, join restores)"
+
+
+def check_maximizing() -> None:
+ cube_lines()
+ walk_lines()
+ cache_lines()
+
+
+def showcase(which: str = "prompt") -> str:
+ check_maximizing()
+ blocks = {
+ "prompt_prefix": [cube_lines(), walk_lines()],
+ "prompt_cache": [cache_lines()],
+ "prompt": [cube_lines(), walk_lines(), cache_lines(), live_lines()],
+ }
+ picked = blocks.get(which)
+ if picked is None:
+ raise ValueError(
+ f"no showcase for {which!r} (try prompt, prompt_prefix, prompt_cache)"
+ )
+ lines = [
+ "prompt-cache max",
+ "================",
+ "kernels prove the conditions that maximize cache",
+ "(stable key + frozen names-only prefix).",
+ "provider HIT tokens are a never-kernel.",
+ "",
+ ]
+ for i, block in enumerate(picked):
+ if i:
+ lines.append("")
+ lines.extend(block)
+ lines.append("")
+ lines.append(verdict())
+ lines.append("")
+ return "\n".join(lines)
diff --git a/src/spec_prompt_prefix_conformance.zig b/src/spec_prompt_prefix_conformance.zig
index 85a2b71b..68174850 100644
--- a/src/spec_prompt_prefix_conformance.zig
+++ b/src/spec_prompt_prefix_conformance.zig
@@ -78,3 +78,34 @@ test "spec/prompt_prefix: skill list/load do not rewrite the pinned g_skills pre
try std.testing.expectEqualStrings("keep", skill_docs.g_skills[0].name);
try std.testing.expectEqualStrings(before, skill_docs.promptCatalog(arena_state.allocator(), skill_docs.g_skills));
}
+
+test "spec/prompt_prefix: maximizing walk stays on names_only × once" {
+ const prev = skill_docs.g_skills;
+ defer skill_docs.g_skills = prev;
+ const pinned = [_]skill_docs.Skill{
+ .{ .name = "keep", .desc = "stays", .body = "SECRET-BODY", .path = "/tmp/keep/SKILL.md", .source = .builtin },
+ .{ .name = "zeta", .desc = "later", .body = "MORE-SECRET", .path = "file:/tmp/zeta", .source = .plugin },
+ };
+ skill_docs.g_skills = &pinned;
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const start = skill_docs.promptCatalog(arena, skill_docs.g_skills);
+ try std.testing.expect(std.mem.indexOf(u8, start, "SECRET-BODY") == null);
+ try std.testing.expect(std.mem.indexOf(u8, start, "MORE-SECRET") == null);
+ try std.testing.expect(std.mem.indexOf(u8, start, "file:") == null);
+ try std.testing.expect(std.mem.indexOf(u8, start, "/") == null);
+
+ var obj: std.json.ObjectMap = .empty;
+ try obj.put(arena, "name", .{ .string = "keep" });
+ const loaded = try skill_docs.execSkill(std.testing.allocator, std.testing.io, .{ .object = obj });
+ defer std.testing.allocator.free(loaded.text);
+ const listed = try skill_docs.execSkill(std.testing.allocator, std.testing.io, .{ .object = .empty });
+ defer std.testing.allocator.free(listed.text);
+
+ const after = skill_docs.promptCatalog(arena, skill_docs.g_skills);
+ try std.testing.expectEqualStrings(start, after);
+ try std.testing.expectEqual(@as(usize, 2), skill_docs.g_skills.len);
+ try std.testing.expect(std.mem.indexOf(u8, after, "keep") != null);
+ try std.testing.expect(std.mem.indexOf(u8, after, "zeta") != null);
+}