graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
spec(prompt_prefix): prove how the cache prefix is earned
Cursor Agentcde53bc524df
diff --git a/build.zig b/build.zigindex 57c33db2..b8f2a2ba 100644--- a/build.zig+++ b/build.zig@@ -103,6 +103,7 @@ pub fn build(b: *std.Build) void {unit_tests.root_module.addAnonymousImport("spec_bash_policy", .{ .root_source_file = b.path("spec/kernels/bash_policy.json") });unit_tests.root_module.addAnonymousImport("spec_structured_output", .{ .root_source_file = b.path("spec/kernels/structured_output.json") });unit_tests.root_module.addAnonymousImport("spec_prompt_cache", .{ .root_source_file = b.path("spec/kernels/prompt_cache.json") });+ unit_tests.root_module.addAnonymousImport("spec_prompt_prefix", .{ .root_source_file = b.path("spec/kernels/prompt_prefix.json") });const run_tests = b.addRunArtifact(unit_tests);const test_step = b.step("test", "Run unit tests");test_step.dependOn(&run_tests.step);diff --git a/lean-proofs/Graff.lean b/lean-proofs/Graff.leanindex 1c721289..252ee3a8 100644--- a/lean-proofs/Graff.lean+++ b/lean-proofs/Graff.lean@@ -9,3 +9,4 @@ import Graff.BashPolicyimport Graff.StructuredOutputimport Graff.TerminalModesimport Graff.PromptCache+import Graff.PromptPrefixdiff --git a/lean-proofs/Graff/PromptPrefix.lean b/lean-proofs/Graff/PromptPrefix.leannew file mode 100644index 00000000..749d218a--- /dev/null+++ b/lean-proofs/Graff/PromptPrefix.lean@@ -0,0 +1,153 @@+/-+ Prompt-prefix kernel (how the cache HIT is earned).++ PromptCache is the key/spawn machine: who emits `prompt_cache_key`,+ that a sub never spawns, that join restores the root partition.++ This kernel is the bytes that sit under that key. Codex's rule: the+ old prompt must be an exact prefix of the new one. Wording is out of+ Lean. The discrete axes are what kind of catalog rides in the prefix+ and whether it is pinned once.++ Names + triggers only. No bodies. No `file:` paths (they move when a+ plugin version changes and bust the first cache hash). Pin once at+ session start. `skill` load / list / rescan do not rewrite the prefix.++ Executable port: spec/ref/prompt_prefix.py.+-/++namespace Graff.PromptPrefix++/-- What may ride in the cached system-prompt prefix. -/+inductive Catalog where+ | namesOnly | withBodies | withPaths+deriving DecidableEq, Repr, BEq++/-- Rebuild-every-turn is how you bust the prefix. -/+inductive Pin where+ | once | everyRebuild+deriving DecidableEq, Repr, BEq++def prefixOk : Catalog → Bool+ | .namesOnly => true+ | .withBodies => false+ | .withPaths => false++def pinOk : Pin → Bool+ | .once => true+ | .everyRebuild => false++structure Cell where+ catalog : Catalog := .namesOnly+ pin : Pin := .once+deriving Repr, BEq, DecidableEq++/-- The only cacheable cell: names + triggers, pinned once. -/+def cacheable (c : Cell) : Bool := prefixOk c.catalog && pinOk c.pin++def allCells : List Cell :=+ Id.run do+ let mut acc : List Cell := []+ for catalog in [Catalog.namesOnly, .withBodies, .withPaths] do+ for pin in [Pin.once, .everyRebuild] do+ acc := acc ++ [{ catalog, pin }]+ return acc++def prefixCells : Nat := allCells.length+def hitCells : Nat := (allCells.filter cacheable).length++theorem prefix_cube : prefixCells = 6 := by native_decide+theorem only_one_hit_cell : hitCells = 1 := by native_decide++theorem names_once_hits :+ cacheable { catalog := .namesOnly, pin := .once } = true := by native_decide++theorem bodies_never_hit (p : Pin) :+ cacheable { catalog := .withBodies, pin := p } = false := by+ cases p <;> native_decide++theorem paths_never_hit (p : Pin) :+ cacheable { catalog := .withPaths, pin := p } = false := by+ cases p <;> native_decide++theorem rebuild_never_hits (c : Catalog) :+ cacheable { catalog := c, pin := .everyRebuild } = false := by+ cases c <;> native_decide++/-! The machine. Snapshot predicates above; these are the edges. -/++structure State where+ pinned : Bool := false+ catalog : Catalog := .namesOnly+ prefixFrozen : Bool := false+deriving Repr, BEq, DecidableEq++inductive Event where+ | start (cat : Catalog)+ | skillLoad+ | skillList+ | rescan+ | turn+ | rebuildIntoPrefix (cat : Catalog)+deriving DecidableEq, Repr, BEq++def step (s : State) (e : Event) : State :=+ match e with+ | Event.start cat =>+ if s.pinned then s+ else { pinned := true, catalog := cat, prefixFrozen := true }+ | Event.skillLoad | Event.skillList | Event.rescan | Event.turn => s+ | Event.rebuildIntoPrefix cat =>+ if !s.pinned then { pinned := true, catalog := cat, prefixFrozen := true }+ else if decide (cat = s.catalog) then s+ else { s with catalog := cat, prefixFrozen := false }++def run (s : State) : List Event → State+ | [] => s+ | e :: es => run (step s e) es++def hitOk (s : State) : Bool :=+ s.prefixFrozen && prefixOk s.catalog && s.pinned++theorem start_pins (c : Catalog) :+ (step {} (.start c)).pinned = true ∧+ (step {} (.start c)).prefixFrozen = true ∧+ (step {} (.start c)).catalog = c := by+ simp [step]++theorem start_is_once (c d : Catalog) :+ step (step {} (.start c)) (.start d) = step {} (.start c) := by+ simp [step]++theorem skill_load_id (s : State) : step s .skillLoad = s := rfl+theorem skill_list_id (s : State) : step s .skillList = s := rfl+theorem rescan_id (s : State) : step s .rescan = s := rfl+theorem turn_id (s : State) : step s .turn = s := rfl++theorem skill_events_keep_prefix (c : Catalog) :+ let s := step {} (.start c)+ run s [.skillLoad, .skillList, .rescan, .turn] = s := by+ native_decide++theorem names_start_hits :+ hitOk (step {} (.start .namesOnly)) = true := by native_decide++theorem paths_start_misses :+ hitOk (step {} (.start .withPaths)) = false := by native_decide++theorem rebuild_that_changes_busts :+ hitOk (run {} [.start .namesOnly, .rebuildIntoPrefix .withPaths]) = false := by+ native_decide++theorem rebuild_same_catalog_stays :+ hitOk (run {} [.start .namesOnly, .rebuildIntoPrefix .namesOnly]) = true := by+ native_decide++example : prefixOk .namesOnly = true := by native_decide+example : prefixOk .withBodies = false := by native_decide+example : pinOk .once = true := by native_decide+example : cacheable { catalog := .namesOnly, pin := .everyRebuild } = false := by native_decide+example : (step {} (.start .namesOnly)).prefixFrozen = true := by native_decide+example : step (step {} (.start .namesOnly)) .skillLoad = step {} (.start .namesOnly) := by native_decide++end Graff.PromptPrefixdiff --git a/lean-proofs/KERNELS.md b/lean-proofs/KERNELS.mdindex af338162..8fbad085 100644--- a/lean-proofs/KERNELS.md+++ b/lean-proofs/KERNELS.md@@ -13,13 +13,14 @@ the snapshot of that function.Process kernels: `GoalLoop` (standing has no retire edge; harness-doneneeds a done write), `PromptCache` (sub never spawns; join restores the-root partition), `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), and-`Transport` (a sub never takes WS; only one live root Responses cell-does), and `Score` (`attempt` never files; `capture` after the join-files one stage row). They are not Turing machines: no tape, no halt-state.+root partition), `PromptPrefix` (names + triggers, pinned once; skill+load/list/rescan do not rewrite the prefix), `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+Responses cell does), and `Score` (`attempt` never files; `capture`+after the join files one stage row). They are not Turing machines: no+tape, no halt state.The shape of a subagent fleet is not a cube. `Shape` is the observationladder of one turn and stays a cube. How many children spawn, which@@ -47,6 +48,7 @@ not a skip: TUI, prompts, and SSE bytes stay out of Lean on purpose.| `Provider` | 18 baked rows | live `/models` overlay, Kimi protocol flip || `GoalLoop` | 360 gate cells + `Event`/`step` | model wording, whether the work is correct || `PromptCache` | 48 cells + `Event`/`step` | provider cache HIT, uuid5 cwd bytes, vision pin |+| `PromptPrefix` | 6 cells + `Event`/`step` | catalog wording, provider HIT, compaction || `TerminalModes` | 14 named sequences + `Op`/`step` | TUI layout, glyphs, the emulator font || `PathConfine` | 16 lexical paths + 80 lease cells + `Event`/`step` | OS errno, Windows drives, live symlink walk || `Shape` | 1728 ladder cells | `admit`, learned override, ε-explore, `observe` |@@ -63,7 +65,7 @@ not a skip: TUI, prompts, and SSE bytes stay out of Lean on purpose.| Part | Why never ||---|---|| TUI (layout, colors, glyphs, hover) | the emulator owns the font and the cell grid |-| Prompts / system text | wording is not a discrete decision |+| Prompts / system text | wording is not a discrete decision (prefix *kind* is PromptPrefix) || SSE / stream bytes | wire framing, not a predicate || MCP protocol / tool descriptions | names and schemas, not a flag cube || HMAC score signing | crypto, not a discrete gate |diff --git a/lean-proofs/Main.lean b/lean-proofs/Main.leanindex 4f9d487c..2bfb7603 100644--- a/lean-proofs/Main.lean+++ b/lean-proofs/Main.lean@@ -7,6 +7,7 @@ import Graff.Shapeimport Graff.Scoreimport Graff.BashPolicyimport Graff.PromptCache+import Graff.PromptPrefixopen Graff@@ -24,4 +25,5 @@ def main : IO Unit := doIO.println s!"score {Score.scoreCells} filed={Score.filedCells} titles={Score.titleCells} classes={Score.classCells}"IO.println s!"bash {BashPolicy.bashCells} allowed={BashPolicy.allowedCells} external={BashPolicy.externalCells}"IO.println s!"prompt_cache {PromptCache.cacheCells} spawn_ok={PromptCache.spawnOkCells} key={PromptCache.keyCells}"- IO.println s!"cells_total {ToolCatalog.catalogCells + Transport.transportCells + Provider.providerRows + GoalLoop.goalCells + PathConfine.leaseCells + Shape.shapeCells + Score.scoreCells + BashPolicy.bashCells + PromptCache.cacheCells}"+ IO.println s!"prompt_prefix {PromptPrefix.prefixCells} hit={PromptPrefix.hitCells}"+ IO.println s!"cells_total {ToolCatalog.catalogCells + Transport.transportCells + Provider.providerRows + GoalLoop.goalCells + PathConfine.leaseCells + Shape.shapeCells + Score.scoreCells + BashPolicy.bashCells + PromptCache.cacheCells + PromptPrefix.prefixCells}"diff --git a/spec/README.md b/spec/README.mdindex d54c42c8..9e4cb8a1 100644--- a/spec/README.md+++ b/spec/README.md@@ -46,6 +46,7 @@ properties are load-bearing, and a missed combination is a real bug.| `provider` | live | 18 baked rows over 3 wire kinds. || `goal_loop` | live | Process kernel (`Event`/`step`, not a TM). 360 snapshot cells. Standing does not retire. || `prompt_cache` | live | Process kernel. 48 cells. Sub never spawns. Child key isolated. Join restores root. |+| `prompt_prefix` | live | Process kernel. 6 cells. Names-only catalog, pin once. Skill events do not rewrite the prefix. || `terminal_modes` | live | Process kernel. 14 sequences. Enable+restore returns to Idle. Pop floors. Alt last. || `path_confine` | live | Process kernel. Component walk; Escaped/Absolute absorb. 80 leases. || `shape` | live | 1728 cells. Hand ladder + explicit arm. Budget from remaining/cap/floor. |@@ -60,6 +61,7 @@ python3 spec/conformance.py # properties + fixture self-checkpython3 spec/conformance.py --export # regenerate kernels/*.json and GoalLoop mermaidpython3 spec/conformance.py --diagram goal_loop # live Event/step projectionpython3 spec/conformance.py --diagram prompt_cache+python3 spec/conformance.py --diagram prompt_prefixpython3 spec/conformance.py --diagram terminal_modespython3 spec/conformance.py --diagram path_confinepython3 spec/conformance.py --diagram transport@@ -69,9 +71,9 @@ python3 spec/conformance.py --lean # lake build, if installedzig build test --summary none -Dtest-filter="spec/tool_catalog"```-Process kernels (`GoalLoop`, `PromptCache`, `TerminalModes`, `PathConfine`,-`Transport`, `Score`) are finite `Event` / `step` diagrams, not Turing-machines. Cube kernels (Shape, Provider, ToolCatalog) stay cubes.+Process kernels (`GoalLoop`, `PromptCache`, `PromptPrefix`, `TerminalModes`,+`PathConfine`, `Transport`, `Score`) are finite `Event` / `step` diagrams,+not Turing machines. Cube kernels (Shape, Provider, ToolCatalog) stay cubes.BashPolicy stays a command cube this turn. The shape of a subagent fleetis not a Shape cell — PromptCache / PathConfine / Transport force everychild through a machine; Score files that unbounded fleet as one stagediff --git a/spec/conformance.py b/spec/conformance.pyindex d1af5818..35743e54 100644--- a/spec/conformance.py+++ b/spec/conformance.py@@ -58,6 +58,8 @@ from ref.prompt_cache import check_properties as cache_check_propertiesfrom ref.prompt_cache import payload as cache_payloadfrom ref.prompt_cache import write_kernel_md as write_cache_mdfrom ref.prompt_cache import kernel_md as cache_kernel_md+from ref.prompt_prefix import check_properties as prefix_check_properties, payload as prefix_payload+from ref.prompt_prefix import write_kernel_md as write_prefix_md, kernel_md as prefix_kernel_mdfrom ref.shape import check_properties as shape_check_propertiesfrom ref.shape import payload as shape_model_payloadfrom ref.score import check_properties as score_check_properties, payload as score_model_payload@@ -84,6 +86,7 @@ BASH_FIXTURE = KERNELS / "bash_policy.json"SOX_FIXTURE = KERNELS / "structured_output.json"TERM_FIXTURE = KERNELS / "terminal_modes.json"CACHE_FIXTURE = KERNELS / "prompt_cache.json"+PREFIX_FIXTURE = KERNELS / "prompt_prefix.json"LEAN_DIR = ROOT.parent / "lean-proofs"@@ -342,6 +345,10 @@ 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:n = 0for p in PATHS:@@ -434,6 +441,8 @@ def export() -> list[Path]:write_term_md(KERNELS / "terminal_modes.md"),_write(CACHE_FIXTURE, cache_payload()),write_cache_md(KERNELS / "prompt_cache.md"),+ _write(PREFIX_FIXTURE, prefix_payload()),+ write_prefix_md(KERNELS / "prompt_prefix.md"),]@@ -456,10 +465,12 @@ def check_fixtures() -> None:_same(SOX_FIXTURE, sox_model_payload(), "structured_output")_same(TERM_FIXTURE, term_model_payload(), "terminal_modes")_same(CACHE_FIXTURE, cache_payload(), "prompt_cache")+ _same(PREFIX_FIXTURE, prefix_payload(), "prompt_prefix")from ref.goal_loop import kernel_mdfor name, body in (("goal_loop.md", kernel_md),("prompt_cache.md", cache_kernel_md),+ ("prompt_prefix.md", prefix_kernel_md),("terminal_modes.md", term_kernel_md),("path_confine.md", path_kernel_md),("transport.md", transport_kernel_md),@@ -486,15 +497,13 @@ def try_lean() -> int:print("lean: lake not installed (optional; fixtures are the CI surface)")return 0print(f"lean: {lake} build (cwd={LEAN_DIR})")- r = subprocess.run([lake, "build"], cwd=LEAN_DIR)- if r.returncode != 0:+ if subprocess.run([lake, "build"], cwd=LEAN_DIR).returncode != 0:raise Counterexample("lean-build", None, "lake build failed")return 0def shutil_which(name: str) -> str | None:from shutil import which-return which(name)@@ -503,18 +512,9 @@ def try_impl() -> int:if zig is None:print("impl: zig not on PATH; skip")return 0- repo = ROOT.parent- cmd = [- zig,- "build",- "test",- "--summary",- "none",- "-Dtest-filter=spec/",- ]+ cmd = [zig, "build", "test", "--summary", "none", "-Dtest-filter=spec/"]print("impl:", " ".join(cmd))- r = subprocess.run(cmd, cwd=repo)- if r.returncode != 0:+ if subprocess.run(cmd, cwd=ROOT.parent).returncode != 0:raise Counterexample("impl", None, "zig test spec/tool_catalog failed")return 0@@ -543,6 +543,7 @@ def main() -> int: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",@@ -564,6 +565,7 @@ def main() -> int:n_pr = check_provider()n_gl = check_goal_loop()n_ck = check_prompt_cache()+ n_px = check_prompt_prefix()n_pc = check_path_confine()n_sh = check_shape()n_sc = check_score()@@ -573,12 +575,12 @@ def main() -> int:if args.export:paths = export()rel = ", ".join(p.relative_to(ROOT.parent).as_posix() for p in paths)- print(f"exported catalog={n_cat} transport={n_tr} provider={n_pr} goal={n_gl} cache={n_ck} path={n_pc} shape={n_sh} score={n_sc} bash={n_ba} sox={n_sx} term={n_tm} → {rel}")+ print(f"exported catalog={n_cat} transport={n_tr} provider={n_pr} goal={n_gl} cache={n_ck} prefix={n_px} path={n_pc} shape={n_sh} score={n_sc} bash={n_ba} sox={n_sx} term={n_tm} → {rel}")else:check_fixtures()print(f"ok tool_catalog {n_cat} transport {n_tr} (1 ws) "- f"provider {n_pr} goal_loop {n_gl} prompt_cache {n_ck} path_confine {n_pc} "+ f"provider {n_pr} goal_loop {n_gl} prompt_cache {n_ck} prompt_prefix {n_px} path_confine {n_pc} "f"shape {n_sh} score {n_sc} bash {n_ba} "f"structured_output {n_sx} terminal_modes {n_tm}")diff --git a/spec/kernels/prompt_prefix.json b/spec/kernels/prompt_prefix.jsonnew file mode 100644index 00000000..ab9c765e--- /dev/null+++ b/spec/kernels/prompt_prefix.json@@ -0,0 +1,66 @@+{+ "kernel": "prompt_prefix",+ "version": 1,+ "cases": [+ {+ "id": "names_only.once",+ "cell": {+ "catalog": "names_only",+ "pin": "once"+ },+ "prefix_ok": true,+ "pin_ok": true,+ "cacheable": true+ },+ {+ "id": "names_only.every_rebuild",+ "cell": {+ "catalog": "names_only",+ "pin": "every_rebuild"+ },+ "prefix_ok": true,+ "pin_ok": false,+ "cacheable": false+ },+ {+ "id": "with_bodies.once",+ "cell": {+ "catalog": "with_bodies",+ "pin": "once"+ },+ "prefix_ok": false,+ "pin_ok": true,+ "cacheable": false+ },+ {+ "id": "with_bodies.every_rebuild",+ "cell": {+ "catalog": "with_bodies",+ "pin": "every_rebuild"+ },+ "prefix_ok": false,+ "pin_ok": false,+ "cacheable": false+ },+ {+ "id": "with_paths.once",+ "cell": {+ "catalog": "with_paths",+ "pin": "once"+ },+ "prefix_ok": false,+ "pin_ok": true,+ "cacheable": false+ },+ {+ "id": "with_paths.every_rebuild",+ "cell": {+ "catalog": "with_paths",+ "pin": "every_rebuild"+ },+ "prefix_ok": false,+ "pin_ok": false,+ "cacheable": false+ }+ ]+}diff --git a/spec/kernels/prompt_prefix.md b/spec/kernels/prompt_prefix.mdnew file mode 100644index 00000000..048d6ce0--- /dev/null+++ b/spec/kernels/prompt_prefix.md@@ -0,0 +1,23 @@+# Kernel: prompt prefix (cache HIT)++Source of truth: `lean-proofs/Graff/PromptPrefix.lean`.++Process kernel next to PromptCache. PromptCache is the key and the+spawn gate. This kernel is the bytes under that key: names + triggers+only, pinned once. Bodies and `file:` paths are illegal in the prefix.+`skill` load / list / rescan / turn do not rewrite it. A mid-session+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`).++```mermaid+stateDiagram-v2+ [*] --> Unpinned+ Pinned --> Busted: rebuild+ Unpinned --> Busted: rebuild+ Unpinned --> Pinned: rebuild+ Unpinned --> Busted: start+ Unpinned --> Pinned: start+```diff --git a/spec/manifest.json b/spec/manifest.jsonindex 161499ba..b8d98d1b 100644--- a/spec/manifest.json+++ b/spec/manifest.json@@ -110,6 +110,16 @@"impl": "TUI/run.zig:enable_seq+TUI/restore.zig:seq","cells_floor": 14,"cells_key": "cells"+ },+ {+ "id": "prompt_prefix",+ "lean": "lean-proofs/Graff/PromptPrefix.lean",+ "ref": "spec/ref/prompt_prefix.py",+ "fixture": "spec/kernels/prompt_prefix.json",+ "zig": "src/spec_prompt_prefix_conformance.zig",+ "impl": "src/skill_docs.zig:promptCatalog+execSkill",+ "cells_floor": 6,+ "cells_key": "cases"}]}diff --git a/spec/ref/prompt_prefix.py b/spec/ref/prompt_prefix.pynew file mode 100644index 00000000..b4dd48da--- /dev/null+++ b/spec/ref/prompt_prefix.py@@ -0,0 +1,236 @@+"""Executable port of lean-proofs/Graff/PromptPrefix.lean."""++from __future__ import annotations++from dataclasses import dataclass+from itertools import product+from pathlib import Path+from typing import Literal++Catalog = Literal["names_only", "with_bodies", "with_paths"]+Pin = Literal["once", "every_rebuild"]+# ("start", cat) | ("skill_load",) | ("skill_list",) | ("rescan",) | ("turn",)+# | ("rebuild_into_prefix", cat)+Event = tuple++CATALOGS: tuple[Catalog, ...] = ("names_only", "with_bodies", "with_paths")+PINS: tuple[Pin, ...] = ("once", "every_rebuild")+EVENTS: tuple[Event, ...] = (+ ("start", "names_only"),+ ("start", "with_bodies"),+ ("start", "with_paths"),+ ("skill_load",),+ ("skill_list",),+ ("rescan",),+ ("turn",),+ ("rebuild_into_prefix", "names_only"),+ ("rebuild_into_prefix", "with_bodies"),+ ("rebuild_into_prefix", "with_paths"),+)+KERNEL_MD = Path(__file__).resolve().parents[1] / "kernels" / "prompt_prefix.md"+CUBE = 6+HIT = 1+++@dataclass(frozen=True)+class Cell:+ catalog: Catalog = "names_only"+ pin: Pin = "once"++ def case_id(self) -> str:+ return f"{self.catalog}.{self.pin}"+++@dataclass(frozen=True)+class State:+ pinned: bool = False+ catalog: Catalog = "names_only"+ prefix_frozen: bool = False+++def prefix_ok(catalog: Catalog) -> bool:+ return catalog == "names_only"+++def pin_ok(pin: Pin) -> bool:+ return pin == "once"+++def cacheable(c: Cell) -> bool:+ return prefix_ok(c.catalog) and pin_ok(c.pin)+++def all_cells() -> list[Cell]:+ return [Cell(catalog, pin) for catalog, pin in product(CATALOGS, PINS)]+++def step(s: State, e: Event) -> State:+ k = e[0]+ if k == "start":+ if s.pinned:+ return s+ return State(pinned=True, catalog=e[1], prefix_frozen=True)+ if k in ("skill_load", "skill_list", "rescan", "turn"):+ return s+ if k == "rebuild_into_prefix":+ cat = e[1]+ if not s.pinned:+ return State(pinned=True, catalog=cat, prefix_frozen=True)+ if cat == s.catalog:+ return s+ return State(pinned=s.pinned, catalog=cat, prefix_frozen=False)+ raise ValueError(f"unknown event {e!r}")+++def run(s: State, es: list[Event]) -> State:+ for e in es:+ s = step(s, e)+ return s+++def hit_ok(s: State) -> bool:+ return s.prefix_frozen and prefix_ok(s.catalog) and s.pinned+++def project(s: State) -> str:+ if not s.pinned:+ return "Unpinned"+ if s.prefix_frozen and prefix_ok(s.catalog):+ return "Pinned"+ return "Busted"+++def event_label(e: Event) -> str:+ k = e[0]+ if k == "start":+ return "start"+ if k == "rebuild_into_prefix":+ return "rebuild"+ return k+++def walk(start: State | None = None) -> list[tuple[State, Event, State]]:+ src = start or State()+ seen = {src}+ q = [src]+ out: list[tuple[State, Event, State]] = []+ while q:+ s = q.pop()+ for e in EVENTS:+ t = step(s, e)+ if t == s:+ continue+ out.append((s, e, t))+ if t not in seen:+ seen.add(t)+ q.append(t)+ return out+++def diagram_edges() -> list[tuple[str, str, str]]:+ found: set[tuple[str, str, str]] = set()+ for s, e, t in walk():+ a, b = project(s), project(t)+ if a == b:+ continue+ found.add((a, event_label(e), b))+ return sorted(found)+++def mermaid() -> str:+ lines = ["stateDiagram-v2", " [*] --> Unpinned"]+ for a, lab, b in diagram_edges():+ lines.append(f" {a} --> {b}: {lab}")+ return "\n".join(lines) + "\n"+++def kernel_md() -> str:+ body = mermaid().rstrip()+ return (+ "# Kernel: prompt prefix (cache HIT)\n"+ "\n"+ "Source of truth: `lean-proofs/Graff/PromptPrefix.lean`.\n"+ "\n"+ "Process kernel next to PromptCache. PromptCache is the key and the\n"+ "spawn gate. This kernel is the bytes under that key: names + triggers\n"+ "only, pinned once. Bodies and `file:` paths are illegal in the prefix.\n"+ "`skill` load / list / rescan / turn do not rewrite it. A mid-session\n"+ "rebuild that changes the catalog busts the prefix (Codex: the old\n"+ "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"+ "\n"+ "```mermaid\n"+ f"{body}\n"+ "```\n"+ )+++def write_kernel_md(path: Path = KERNEL_MD) -> Path:+ path.write_text(kernel_md())+ return path+++def payload() -> dict:+ cases = []+ for c in all_cells():+ cases.append(+ {+ "id": c.case_id(),+ "cell": {"catalog": c.catalog, "pin": c.pin},+ "prefix_ok": prefix_ok(c.catalog),+ "pin_ok": pin_ok(c.pin),+ "cacheable": cacheable(c),+ }+ )+ return {"kernel": "prompt_prefix", "version": 1, "cases": cases}+++def check_diagram() -> None:+ text = mermaid()+ if "Unpinned --> Pinned: start" not in text:+ raise ValueError("diagram: mermaid missing Unpinned start→Pinned")+ if "Pinned --> Busted: rebuild" not in text:+ raise ValueError("diagram: mermaid missing Pinned rebuild→Busted")+ if "Pinned --> Pinned: skill_load" in text:+ raise ValueError("diagram: skill_load should be id (no edge)")+++def check_properties() -> int:+ n = 0+ hits = 0+ for c in all_cells():+ n += 1+ if c.catalog != "names_only" and prefix_ok(c.catalog):+ raise ValueError(f"bodies-or-paths-ok: {c.case_id()}")+ if c.pin == "every_rebuild" and pin_ok(c.pin):+ raise ValueError(f"rebuild-pin-ok: {c.case_id()}")+ if cacheable(c):+ hits += 1+ if c.catalog != "names_only" or c.pin != "once":+ raise ValueError(f"wrong-hit-cell: {c.case_id()}")+ elif c.catalog == "names_only" and c.pin == "once":+ raise ValueError(f"names-once-miss: {c.case_id()}")+ if n != CUBE:+ raise ValueError(f"prefix-cube: n={n} want={CUBE}")+ if hits != HIT:+ raise ValueError(f"hit-cells: n={hits} want={HIT}")+ idle = State()+ pinned = step(idle, ("start", "names_only"))+ if not hit_ok(pinned):+ raise ValueError("trace: names start should hit")+ if step(pinned, ("start", "with_paths")) != pinned:+ raise ValueError("trace: start is not once")+ for e in (("skill_load",), ("skill_list",), ("rescan",), ("turn",)):+ if step(pinned, e) != pinned:+ raise ValueError(f"trace: {e[0]} rewrote the prefix")+ if hit_ok(step(idle, ("start", "with_paths"))):+ raise ValueError("trace: paths start should miss")+ busted = run(idle, [("start", "names_only"), ("rebuild_into_prefix", "with_paths")])+ if hit_ok(busted) or busted.prefix_frozen:+ 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")+ check_diagram()+ return ndiff --git a/src/spec_prompt_prefix_conformance.zig b/src/spec_prompt_prefix_conformance.zignew file mode 100644index 00000000..85a2b71b--- /dev/null+++ b/src/spec_prompt_prefix_conformance.zig@@ -0,0 +1,80 @@+//! Impl half of PromptPrefix: live `promptCatalog` is names + triggers,+//! sorted, no bodies / `file:` paths, and `skill` events do not rewrite+//! the pinned `g_skills` list that startup spliced into the prefix.++const std = @import("std");+const skill_docs = @import("skill_docs.zig");++const fixtures_json = @embedFile("spec_prompt_prefix");++fn cacheable(catalog: []const u8, pin: []const u8) bool {+ return std.mem.eql(u8, catalog, "names_only") and std.mem.eql(u8, pin, "once");+}++test "spec/prompt_prefix: cube matches names_only × once" {+ const gpa = std.testing.allocator;+ var parsed = try std.json.parseFromSlice(std.json.Value, gpa, fixtures_json, .{});+ defer parsed.deinit();+ const cases = parsed.value.object.get("cases").?.array.items;+ try std.testing.expectEqual(@as(usize, 6), cases.len);+ var hits: usize = 0;+ for (cases) |case_v| {+ const case = case_v.object;+ const id = case.get("id").?.string;+ const cell = case.get("cell").?.object;+ const catalog = cell.get("catalog").?.string;+ const pin = cell.get("pin").?.string;+ const want = case.get("cacheable").?.bool;+ const got = cacheable(catalog, pin);+ if (want != got) {+ std.debug.print("\ncounterexample {s}: cacheable want={} got={}\n", .{ id, want, got });+ return error.CatalogMismatch;+ }+ if (got) hits += 1;+ }+ try std.testing.expectEqual(@as(usize, 1), hits);+}++test "spec/prompt_prefix: live catalog is names + triggers, never bodies or paths" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const shuffled = [_]skill_docs.Skill{+ .{ .name = "zeta", .desc = "z trigger", .body = "SECRET-BODY", .path = "/tmp/zeta/SKILL.md", .source = .personal },+ .{ .name = "alpha", .desc = "a trigger", .body = "MORE-SECRET", .path = "/tmp/alpha/SKILL.md", .source = .plugin },+ };+ const text = skill_docs.promptCatalog(arena, &shuffled);+ try std.testing.expect(std.mem.indexOf(u8, text, "alpha") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "zeta") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "SECRET-BODY") == null);+ try std.testing.expect(std.mem.indexOf(u8, text, "MORE-SECRET") == null);+ try std.testing.expect(std.mem.indexOf(u8, text, "file:") == null);+ try std.testing.expect(std.mem.indexOf(u8, text, "/") == null);+ const alpha_at = std.mem.indexOf(u8, text, "alpha") orelse return error.TestUnexpectedResult;+ const zeta_at = std.mem.indexOf(u8, text, "zeta") orelse return error.TestUnexpectedResult;+ try std.testing.expect(alpha_at < zeta_at);+}++test "spec/prompt_prefix: skill list/load do not rewrite the pinned g_skills prefix" {+ const prev = skill_docs.g_skills;+ defer skill_docs.g_skills = prev;+ const pinned = [_]skill_docs.Skill{+ .{ .name = "keep", .desc = "stays", .body = "", .source = .builtin },+ };+ skill_docs.g_skills = &pinned;+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const before = skill_docs.promptCatalog(arena_state.allocator(), skill_docs.g_skills);++ var obj: std.json.ObjectMap = .empty;+ try obj.put(arena_state.allocator(), "name", .{ .string = "keep" });+ const loaded = try skill_docs.execSkill(std.testing.allocator, std.testing.io, .{ .object = obj });+ defer std.testing.allocator.free(loaded.text);+ try std.testing.expect(!loaded.is_error);+ const listed = try skill_docs.execSkill(std.testing.allocator, std.testing.io, .{ .object = .empty });+ defer std.testing.allocator.free(listed.text);++ try std.testing.expectEqual(@as(usize, 1), skill_docs.g_skills.len);+ 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));+}diff --git a/src/tool_gates.zig b/src/tool_gates.zigindex ce97afd0..c304195a 100644--- a/src/tool_gates.zig+++ b/src/tool_gates.zig@@ -105,6 +105,7 @@ test { // the served catalogs' wire-compatibility guard (an unreferenced module'_ = @import("grok_spec_conformance.zig");_ = @import("spec_prompt_cache_conformance.zig");_ = @import("spec_prompt_cache_kernel_conformance.zig");+ _ = @import("spec_prompt_prefix_conformance.zig");}test "#352: an optional tool is advertised only while its flag is set; other names are unaffected" {