graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
spec(prompt_stable): prove OpenGauss prompt-cache must-nots
Cursor Agente6a59eadfb14
diff --git a/build.zig b/build.zigindex b8f2a2ba..7856dcb9 100644--- a/build.zig+++ b/build.zig@@ -104,6 +104,7 @@ pub fn build(b: *std.Build) void {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") });+ unit_tests.root_module.addAnonymousImport("spec_prompt_stable", .{ .root_source_file = b.path("spec/kernels/prompt_stable.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 252ee3a8..9007b4e6 100644--- a/lean-proofs/Graff.lean+++ b/lean-proofs/Graff.lean@@ -10,3 +10,4 @@ import Graff.StructuredOutputimport Graff.TerminalModesimport Graff.PromptCacheimport Graff.PromptPrefix+import Graff.PromptStablediff --git a/lean-proofs/Graff/PromptStable.lean b/lean-proofs/Graff/PromptStable.leannew file mode 100644index 00000000..1f0f4eb4--- /dev/null+++ b/lean-proofs/Graff/PromptStable.lean@@ -0,0 +1,174 @@+/-+ Prompt-stable kernel (what may touch the prefix after pin).++ OpenGauss's "Prompt Caching Must Not Break": do not alter past context,+ do not rewrite the toolset, do not reload memory or rebuild the system+ prompt mid-session. The only allowed rewrite is compression.++ We keep that cut and name the two explicit busts we do allow+ (`set_system_prompt`, a `/goal` standing-line change) plus the one+ graff-only keep: an append-only tools tail (#476). Mid-array rewrite+ is still illegal. Skills and folded schemas land in history.++ Anthropic `cache_control` placement is a never-kernel (vendor bytes).++ Executable port: spec/ref/prompt_stable.py.+-/++namespace Graff.PromptStable++/-- Mid-session events that can land in history or the prefix. -/+inductive Event where+ | turn | skillInject | schemaLoad+ | toolsetAppend | toolsetRewrite+ | clockTick | memoryReload+ | setSystemPrompt | standingChange | compact+deriving DecidableEq, Repr, BEq++inductive Land where+ | history | prefix+deriving DecidableEq, Repr, BEq++inductive Verdict where+ | keep | bust | illegal+deriving DecidableEq, Repr, BEq++def land : Event → Land+ | .turn | .skillInject | .schemaLoad => .history+ | _ => .prefix++def verdict : Event → Verdict+ | .turn | .skillInject | .schemaLoad | .toolsetAppend | .compact => .keep+ | .setSystemPrompt | .standingChange => .bust+ | .clockTick | .toolsetRewrite | .memoryReload => .illegal++structure Cell where+ event : Event+ land : Land+deriving Repr, BEq, DecidableEq++/-- Keep only when the event lands in its measured seat and is a keep. -/+def keep (c : Cell) : Bool :=+ decide (land c.event = c.land) && decide (verdict c.event = .keep)++def allEvents : List Event :=+ [.turn, .skillInject, .schemaLoad, .toolsetAppend, .toolsetRewrite,+ .clockTick, .memoryReload, .setSystemPrompt, .standingChange, .compact]++def allCells : List Cell :=+ Id.run do+ let mut acc : List Cell := []+ for e in allEvents do+ for l in [Land.history, .prefix] do+ acc := acc ++ [{ event := e, land := l }]+ return acc++def stableCells : Nat := allCells.length+def keepCells : Nat := (allCells.filter keep).length++theorem stable_cube : stableCells = 20 := by native_decide+theorem keep_count : keepCells = 5 := by native_decide++theorem history_keeps (e : Event) (h : land e = .history) :+ keep { event := e, land := .history } = decide (verdict e = .keep) := by+ simp [keep, h]++theorem skill_in_prefix_misses :+ keep { event := .skillInject, land := .prefix } = false := by native_decide++theorem clock_in_prefix_illegal :+ verdict .clockTick = .illegal ∧+ keep { event := .clockTick, land := .prefix } = false := by native_decide++theorem rewrite_illegal :+ verdict .toolsetRewrite = .illegal := by native_decide++theorem append_keeps_prefix :+ keep { event := .toolsetAppend, land := .prefix } = true := by native_decide++theorem compact_keeps :+ keep { event := .compact, land := .prefix } = true := by native_decide++/-! The machine. Snapshot predicates above; these are the edges. -/++structure State where+ pinned : Bool := false+ frozen : Bool := false+deriving Repr, BEq, DecidableEq++inductive StepEvent where+ | start+ | ev (e : Event)+deriving DecidableEq, Repr, BEq++def isKeep (e : Event) : Bool := decide (verdict e = .keep)++def step (s : State) (e : StepEvent) : State :=+ match e with+ | StepEvent.start =>+ if s.pinned then s else { pinned := true, frozen := true }+ | StepEvent.ev ev =>+ if !s.pinned then s+ else if isKeep ev then+ if decide (ev = Event.compact) then { s with frozen := true } else s+ else { s with frozen := false }++def run (s : State) : List StepEvent → State+ | [] => s+ | e :: es => run (step s e) es++def hitOk (s : State) : Bool := s.pinned && s.frozen++theorem start_pins :+ (step {} .start).pinned = true ∧ (step {} .start).frozen = true := by+ simp [step]++theorem history_id (s : State) :+ step s (.ev .turn) = s ∨ !s.pinned := by+ cases s.pinned <;> simp [step, isKeep, verdict]++theorem skill_id :+ step (step {} .start) (.ev .skillInject) = step {} .start := by+ native_decide++theorem append_id :+ step (step {} .start) (.ev .toolsetAppend) = step {} .start := by+ native_decide++theorem compact_repins :+ hitOk (run {} [.start, .ev .setSystemPrompt, .ev .compact]) = true := by+ native_decide++theorem set_system_busts :+ hitOk (run {} [.start, .ev .setSystemPrompt]) = false := by+ native_decide++theorem standing_busts :+ hitOk (run {} [.start, .ev .standingChange]) = false := by+ native_decide++theorem clock_busts :+ hitOk (run {} [.start, .ev .clockTick]) = false := by+ native_decide++theorem rewrite_busts :+ hitOk (run {} [.start, .ev .toolsetRewrite]) = false := by+ native_decide++theorem memory_reload_busts :+ hitOk (run {} [.start, .ev .memoryReload]) = false := by+ native_decide++/-- Gauss must-nots plus skill/schema/append/turn/compact stay on the HIT. -/+theorem maximizing_walk :+ hitOk (run {} [+ .start, .ev .turn, .ev .skillInject, .ev .schemaLoad,+ .ev .toolsetAppend, .ev .compact]) = true := by+ native_decide++example : verdict .skillInject = .keep := by native_decide+example : land .skillInject = .history := by native_decide+example : verdict .clockTick = .illegal := by native_decide+example : keep { event := .compact, land := .history } = false := by native_decide++end Graff.PromptStablediff --git a/lean-proofs/KERNELS.md b/lean-proofs/KERNELS.mdindex 3438d3e9..7da6056e 100644--- a/lean-proofs/KERNELS.md+++ b/lean-proofs/KERNELS.md@@ -14,7 +14,9 @@ the snapshot of that function.Process kernels: `GoalLoop` (standing has no retire edge; harness-doneneeds a done write), `PromptCache` (sub never spawns; join restores theroot partition), `PromptPrefix` (names + triggers, pinned once; skill-load/list/rescan do not rewrite the prefix — showcase with+load/list/rescan do not rewrite the prefix), `PromptStable` (OpenGauss+must-nots: skills/schemas in history, no clock/toolset-rewrite/memory+reload in the prefix; compact re-pins — 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@@ -50,6 +52,7 @@ not a skip: TUI, prompts, and SSE bytes stay out of Lean on purpose.| `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 |+| `PromptStable` | 20 cells + `Event`/`step` | Anthropic `cache_control` bytes, compact summary wording || `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` |diff --git a/lean-proofs/Main.lean b/lean-proofs/Main.leanindex 2bfb7603..be19dc48 100644--- a/lean-proofs/Main.lean+++ b/lean-proofs/Main.lean@@ -8,6 +8,7 @@ import Graff.Scoreimport Graff.BashPolicyimport Graff.PromptCacheimport Graff.PromptPrefix+import Graff.PromptStableopen Graff@@ -26,4 +27,5 @@ def main : IO Unit := doIO.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!"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}"+ IO.println s!"prompt_stable {PromptStable.stableCells} keep={PromptStable.keepCells}"+ 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 + PromptStable.stableCells}"diff --git a/spec/README.md b/spec/README.mdindex 7c2cc99f..60d327ed 100644--- a/spec/README.md+++ b/spec/README.md@@ -47,6 +47,7 @@ properties are load-bearing, and a missed combination is a real bug.| `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. |+| `prompt_stable` | live | Process kernel. 20 cells. OpenGauss must-nots. 5 keep. Compact re-pins. || `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. |@@ -62,6 +63,7 @@ python3 spec/conformance.py --export # regenerate kernels/*.json and GoalLooppython3 spec/conformance.py --diagram goal_loop # live Event/step projectionpython3 spec/conformance.py --diagram prompt_cachepython3 spec/conformance.py --diagram prompt_prefix+python3 spec/conformance.py --diagram prompt_stablepython3 spec/conformance.py --showcase # prefix cube + maximizing walk + key machinepython3 spec/conformance.py --diagram terminal_modespython3 spec/conformance.py --diagram path_confine@@ -72,7 +74,7 @@ python3 spec/conformance.py --lean # lake build, if installedzig build test --summary none -Dtest-filter="spec/tool_catalog"```-Process kernels (`GoalLoop`, `PromptCache`, `PromptPrefix`, `TerminalModes`,+Process kernels (`GoalLoop`, `PromptCache`, `PromptPrefix`, `PromptStable`, `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 fleetdiff --git a/spec/conformance.py b/spec/conformance.pyindex ec624bce..cbabfd1d 100644--- a/spec/conformance.py+++ b/spec/conformance.py@@ -340,6 +340,8 @@ def _ref(fn, name: str) -> int: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_prompt_stable() -> int:+ return _ref(__import__("ref.prompt_stable", fromlist=["check_properties"]).check_properties, "prompt_stable")def check_path_confine() -> int:@@ -383,24 +385,15 @@ def check_path_confine() -> int:return n-def check_shape() -> int:- return _ref(shape_check_properties, 'shape')+def check_shape() -> int: return _ref(shape_check_properties, "shape")-def check_score() -> int:- return _ref(score_check_properties, 'score')+def check_score() -> int: return _ref(score_check_properties, "score")+def check_bash() -> int: return _ref(bash_check_properties, "bash")-def check_bash() -> int:- return _ref(bash_check_properties, 'bash')---def check_sox() -> int:- return _ref(sox_check_properties, 'sox')---def check_term() -> int:- return _ref(term_check_properties, 'term')+def check_sox() -> int: return _ref(sox_check_properties, "sox")+def check_term() -> int: return _ref(term_check_properties, "term")def prefixes_first(p: str) -> list[str]:@@ -436,6 +429,8 @@ def export() -> list[Path]:write_cache_md(KERNELS / "prompt_cache.md"),_write(PREFIX_FIXTURE, prefix_payload()),write_prefix_md(KERNELS / "prompt_prefix.md"),+ _write(KERNELS / "prompt_stable.json", __import__("ref.prompt_stable", fromlist=["payload"]).payload()),+ __import__("ref.prompt_stable", fromlist=["write_kernel_md"]).write_kernel_md(KERNELS / "prompt_stable.md"),]@@ -459,11 +454,14 @@ def check_fixtures() -> None:_same(TERM_FIXTURE, term_model_payload(), "terminal_modes")_same(CACHE_FIXTURE, cache_payload(), "prompt_cache")_same(PREFIX_FIXTURE, prefix_payload(), "prompt_prefix")+ from ref.prompt_stable import payload as stable_payload, kernel_md as stable_kernel_md+ _same(KERNELS / "prompt_stable.json", stable_payload(), "prompt_stable")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),+ ("prompt_stable.md", stable_kernel_md),("terminal_modes.md", term_kernel_md),("path_confine.md", path_kernel_md),("transport.md", transport_kernel_md),@@ -544,7 +542,8 @@ def main() -> int:if args.diagram:mods = {"goal_loop": "ref.goal_loop", "prompt_cache": "ref.prompt_cache",- "prompt_prefix": "ref.prompt_prefix", "terminal_modes": "ref.terminal_modes",+ "prompt_prefix": "ref.prompt_prefix", "prompt_stable": "ref.prompt_stable",+ "terminal_modes": "ref.terminal_modes","path_confine": "ref.path_confine", "transport": "ref.transport", "score": "ref.score",}path = mods.get(args.diagram)@@ -564,6 +563,7 @@ def main() -> int:n_gl = check_goal_loop()n_ck = check_prompt_cache()n_px = check_prompt_prefix()+ n_ps = check_prompt_stable()n_pc = check_path_confine()n_sh = check_shape()n_sc = check_score()@@ -573,12 +573,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} prefix={n_px} 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} stable={n_ps} 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} prompt_prefix {n_px} path_confine {n_pc} "+ f"provider {n_pr} goal_loop {n_gl} prompt_cache {n_ck} prompt_prefix {n_px} prompt_stable {n_ps} 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_stable.json b/spec/kernels/prompt_stable.jsonnew file mode 100644index 00000000..3da27649--- /dev/null+++ b/spec/kernels/prompt_stable.json@@ -0,0 +1,206 @@+{+ "kernel": "prompt_stable",+ "version": 1,+ "cases": [+ {+ "id": "turn.history",+ "cell": {+ "event": "turn",+ "land": "history"+ },+ "land": "history",+ "verdict": "keep",+ "keep": true+ },+ {+ "id": "turn.prefix",+ "cell": {+ "event": "turn",+ "land": "prefix"+ },+ "land": "history",+ "verdict": "keep",+ "keep": false+ },+ {+ "id": "skill_inject.history",+ "cell": {+ "event": "skill_inject",+ "land": "history"+ },+ "land": "history",+ "verdict": "keep",+ "keep": true+ },+ {+ "id": "skill_inject.prefix",+ "cell": {+ "event": "skill_inject",+ "land": "prefix"+ },+ "land": "history",+ "verdict": "keep",+ "keep": false+ },+ {+ "id": "schema_load.history",+ "cell": {+ "event": "schema_load",+ "land": "history"+ },+ "land": "history",+ "verdict": "keep",+ "keep": true+ },+ {+ "id": "schema_load.prefix",+ "cell": {+ "event": "schema_load",+ "land": "prefix"+ },+ "land": "history",+ "verdict": "keep",+ "keep": false+ },+ {+ "id": "toolset_append.history",+ "cell": {+ "event": "toolset_append",+ "land": "history"+ },+ "land": "prefix",+ "verdict": "keep",+ "keep": false+ },+ {+ "id": "toolset_append.prefix",+ "cell": {+ "event": "toolset_append",+ "land": "prefix"+ },+ "land": "prefix",+ "verdict": "keep",+ "keep": true+ },+ {+ "id": "toolset_rewrite.history",+ "cell": {+ "event": "toolset_rewrite",+ "land": "history"+ },+ "land": "prefix",+ "verdict": "illegal",+ "keep": false+ },+ {+ "id": "toolset_rewrite.prefix",+ "cell": {+ "event": "toolset_rewrite",+ "land": "prefix"+ },+ "land": "prefix",+ "verdict": "illegal",+ "keep": false+ },+ {+ "id": "clock_tick.history",+ "cell": {+ "event": "clock_tick",+ "land": "history"+ },+ "land": "prefix",+ "verdict": "illegal",+ "keep": false+ },+ {+ "id": "clock_tick.prefix",+ "cell": {+ "event": "clock_tick",+ "land": "prefix"+ },+ "land": "prefix",+ "verdict": "illegal",+ "keep": false+ },+ {+ "id": "memory_reload.history",+ "cell": {+ "event": "memory_reload",+ "land": "history"+ },+ "land": "prefix",+ "verdict": "illegal",+ "keep": false+ },+ {+ "id": "memory_reload.prefix",+ "cell": {+ "event": "memory_reload",+ "land": "prefix"+ },+ "land": "prefix",+ "verdict": "illegal",+ "keep": false+ },+ {+ "id": "set_system_prompt.history",+ "cell": {+ "event": "set_system_prompt",+ "land": "history"+ },+ "land": "prefix",+ "verdict": "bust",+ "keep": false+ },+ {+ "id": "set_system_prompt.prefix",+ "cell": {+ "event": "set_system_prompt",+ "land": "prefix"+ },+ "land": "prefix",+ "verdict": "bust",+ "keep": false+ },+ {+ "id": "standing_change.history",+ "cell": {+ "event": "standing_change",+ "land": "history"+ },+ "land": "prefix",+ "verdict": "bust",+ "keep": false+ },+ {+ "id": "standing_change.prefix",+ "cell": {+ "event": "standing_change",+ "land": "prefix"+ },+ "land": "prefix",+ "verdict": "bust",+ "keep": false+ },+ {+ "id": "compact.history",+ "cell": {+ "event": "compact",+ "land": "history"+ },+ "land": "prefix",+ "verdict": "keep",+ "keep": false+ },+ {+ "id": "compact.prefix",+ "cell": {+ "event": "compact",+ "land": "prefix"+ },+ "land": "prefix",+ "verdict": "keep",+ "keep": true+ }+ ]+}diff --git a/spec/kernels/prompt_stable.md b/spec/kernels/prompt_stable.mdnew file mode 100644index 00000000..1711ef7e--- /dev/null+++ b/spec/kernels/prompt_stable.md@@ -0,0 +1,29 @@+# Kernel: prompt stable (OpenGauss must-nots)++Source of truth: `lean-proofs/Graff/PromptStable.lean`.++Process kernel next to PromptCache / PromptPrefix. PromptCache is+the key. PromptPrefix is the catalog bytes. This kernel is what+may touch the prefix after pin — OpenGauss's "Prompt Caching Must+Not Break": no past-context rewrite, no toolset rewrite, no memory+reload or system-prompt rebuild mid-session. Compression is the+allowed rewrite. Skills and folded schemas land in history.++graff keeps two explicit busts (`set_system_prompt`, `/goal` line)+and one append-only tools tail (#476). Mid-array rewrite is still+illegal. Anthropic `cache_control` placement is out of Lean.++20 cells (event × land). Exactly 5 keep. Showcase with+`python3 spec/conformance.py --showcase`.++```mermaid+stateDiagram-v2+ [*] --> Unpinned+ Busted --> Frozen: compact+ Frozen --> Busted: clock_tick+ Frozen --> Busted: memory_reload+ Frozen --> Busted: set_system_prompt+ Frozen --> Busted: standing_change+ Frozen --> Busted: toolset_rewrite+ Unpinned --> Frozen: start+```diff --git a/spec/manifest.json b/spec/manifest.jsonindex b8d98d1b..7aff0815 100644--- a/spec/manifest.json+++ b/spec/manifest.json@@ -120,6 +120,16 @@"impl": "src/skill_docs.zig:promptCatalog+execSkill","cells_floor": 6,"cells_key": "cases"+ },+ {+ "id": "prompt_stable",+ "lean": "lean-proofs/Graff/PromptStable.lean",+ "ref": "spec/ref/prompt_stable.py",+ "fixture": "spec/kernels/prompt_stable.json",+ "zig": "src/spec_prompt_stable_conformance.zig",+ "impl": "src/goal_state.zig:steeringGate+src/prompts.zig:pinStandingGoal+src/skill_docs.zig:execSkill",+ "cells_floor": 20,+ "cells_key": "cases"}]}diff --git a/spec/ref/prompt_showcase.py b/spec/ref/prompt_showcase.pyindex c828c76f..a71cd240 100644--- a/spec/ref/prompt_showcase.py+++ b/spec/ref/prompt_showcase.py@@ -13,6 +13,13 @@ from ref.prompt_cache import run as cache_runfrom ref.prompt_cache import step as cache_stepfrom ref.prompt_prefix import CATALOGS, PINS, Cell, Statefrom ref.prompt_prefix import all_cells, cacheable, hit_ok, run, step+from ref.prompt_stable import Cell as StableCell+from ref.prompt_stable import EVENTS as STABLE_EVENTS+from ref.prompt_stable import keep as stable_keep+from ref.prompt_stable import land as stable_land+from ref.prompt_stable import run as stable_run+from ref.prompt_stable import hit_ok as stable_hit+from ref.prompt_stable import State as StableStateMAX_EVENTS: list[tuple] = (@@ -101,6 +108,34 @@ def cache_lines() -> list[str]:]+def stable_lines() -> list[str]:+ lines = ["PromptStable 20 cells 5 keep (OpenGauss must-nots)", ""]+ keeps = 0+ for ev in STABLE_EVENTS:+ k = stable_keep(StableCell(ev, stable_land(ev)))+ if k:+ keeps += 1+ mark = "keep" if k else "bust"+ lines.append(f" {ev:<20} → {stable_land(ev):<8} {mark}")+ if keeps != 5:+ raise ValueError(f"showcase: stable keep {keeps}, want 5")+ s = stable_run(StableState(), [+ ("start",),+ ("ev", "turn"),+ ("ev", "skill_inject"),+ ("ev", "schema_load"),+ ("ev", "toolset_append"),+ ("ev", "compact"),+ ])+ if not stable_hit(s):+ raise ValueError("showcase: stable maximizing walk left HIT")+ lines.append("")+ lines.append(" start + turn + skill + schema + append + compact HIT")+ lines.append(" clock_tick / toolset_rewrite / memory_reload miss")+ lines.append(" set_system_prompt / standing_change miss (allowed bust)")+ return lines++def live_lines() -> list[str]:return ["live Zig (the impl half)",@@ -110,17 +145,20 @@ def live_lines() -> list[str]:" /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",+ " essay_refresh_turns 0 — standing essay is change-only (ADR 0005)",+ " tools tail append-only after the stable head (#476)",]def verdict() -> str:- return "verdict: maximizing (1/6 prefix cells, sticky key, join restores)"+ return "verdict: maximizing (1/6 prefix, 5/20 stable keep, sticky key, join restores)"def check_maximizing() -> None:cube_lines()walk_lines()cache_lines()+ stable_lines()def showcase(which: str = "prompt") -> str:@@ -128,12 +166,13 @@ def showcase(which: str = "prompt") -> str:blocks = {"prompt_prefix": [cube_lines(), walk_lines()],"prompt_cache": [cache_lines()],- "prompt": [cube_lines(), walk_lines(), cache_lines(), live_lines()],+ "prompt_stable": [stable_lines()],+ "prompt": [cube_lines(), walk_lines(), cache_lines(), stable_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)"+ f"no showcase for {which!r} (try prompt, prompt_prefix, prompt_cache, prompt_stable)")lines = ["prompt-cache max",diff --git a/spec/ref/prompt_stable.py b/spec/ref/prompt_stable.pynew file mode 100644index 00000000..13023182--- /dev/null+++ b/spec/ref/prompt_stable.py@@ -0,0 +1,245 @@+"""Executable port of lean-proofs/Graff/PromptStable.lean."""++from __future__ import annotations++from dataclasses import dataclass+from itertools import product+from pathlib import Path+from typing import Literal++Event = Literal[+ "turn",+ "skill_inject",+ "schema_load",+ "toolset_append",+ "toolset_rewrite",+ "clock_tick",+ "memory_reload",+ "set_system_prompt",+ "standing_change",+ "compact",+]+Land = Literal["history", "prefix"]+Verdict = Literal["keep", "bust", "illegal"]+# ("start",) | ("ev", Event)+StepEvent = tuple++EVENTS: tuple[Event, ...] = (+ "turn",+ "skill_inject",+ "schema_load",+ "toolset_append",+ "toolset_rewrite",+ "clock_tick",+ "memory_reload",+ "set_system_prompt",+ "standing_change",+ "compact",+)+LANDS: tuple[Land, ...] = ("history", "prefix")+KERNEL_MD = Path(__file__).resolve().parents[1] / "kernels" / "prompt_stable.md"+CUBE = 20+KEEP = 5+HISTORY = frozenset({"turn", "skill_inject", "schema_load"})+KEEP_EVENTS = frozenset({"turn", "skill_inject", "schema_load", "toolset_append", "compact"})+BUST_EVENTS = frozenset({"set_system_prompt", "standing_change"})+ILLEGAL_EVENTS = frozenset({"clock_tick", "toolset_rewrite", "memory_reload"})+++@dataclass(frozen=True)+class Cell:+ event: Event+ land: Land++ def case_id(self) -> str:+ return f"{self.event}.{self.land}"+++@dataclass(frozen=True)+class State:+ pinned: bool = False+ frozen: bool = False+++def land(e: Event) -> Land:+ return "history" if e in HISTORY else "prefix"+++def verdict(e: Event) -> Verdict:+ if e in KEEP_EVENTS:+ return "keep"+ if e in BUST_EVENTS:+ return "bust"+ return "illegal"+++def keep(c: Cell) -> bool:+ return land(c.event) == c.land and verdict(c.event) == "keep"+++def all_cells() -> list[Cell]:+ return [Cell(e, l) for e, l in product(EVENTS, LANDS)]+++def step(s: State, e: StepEvent) -> State:+ if e[0] == "start":+ return s if s.pinned else State(pinned=True, frozen=True)+ ev = e[1]+ if not s.pinned:+ return s+ if verdict(ev) == "keep":+ return State(pinned=True, frozen=True) if ev == "compact" else s+ return State(pinned=s.pinned, frozen=False)+++def run(s: State, es: list[StepEvent]) -> State:+ for e in es:+ s = step(s, e)+ return s+++def hit_ok(s: State) -> bool:+ return s.pinned and s.frozen+++def project(s: State) -> str:+ if not s.pinned:+ return "Unpinned"+ return "Frozen" if s.frozen else "Busted"+++def event_label(e: StepEvent) -> str:+ return "start" if e[0] == "start" else e[1]+++def walk(start: State | None = None) -> list[tuple[State, StepEvent, State]]:+ src = start or State()+ events: list[StepEvent] = [("start",)] + [("ev", ev) for ev in EVENTS]+ seen = {src}+ q = [src]+ out: list[tuple[State, StepEvent, 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 mermaid() -> 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))+ lines = ["stateDiagram-v2", " [*] --> Unpinned"]+ for a, lab, b in sorted(found):+ lines.append(f" {a} --> {b}: {lab}")+ return "\n".join(lines) + "\n"+++def kernel_md() -> str:+ body = mermaid().rstrip()+ return (+ "# Kernel: prompt stable (OpenGauss must-nots)\n"+ "\n"+ "Source of truth: `lean-proofs/Graff/PromptStable.lean`.\n"+ "\n"+ "Process kernel next to PromptCache / PromptPrefix. PromptCache is\n"+ "the key. PromptPrefix is the catalog bytes. This kernel is what\n"+ "may touch the prefix after pin — OpenGauss's \"Prompt Caching Must\n"+ "Not Break\": no past-context rewrite, no toolset rewrite, no memory\n"+ "reload or system-prompt rebuild mid-session. Compression is the\n"+ "allowed rewrite. Skills and folded schemas land in history.\n"+ "\n"+ "graff keeps two explicit busts (`set_system_prompt`, `/goal` line)\n"+ "and one append-only tools tail (#476). Mid-array rewrite is still\n"+ "illegal. Anthropic `cache_control` placement is out of Lean.\n"+ "\n"+ "20 cells (event × land). Exactly 5 keep. Showcase with\n"+ "`python3 spec/conformance.py --showcase`.\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": {"event": c.event, "land": c.land},+ "land": land(c.event),+ "verdict": verdict(c.event),+ "keep": keep(c),+ }+ )+ return {"kernel": "prompt_stable", "version": 1, "cases": cases}+++def check_properties() -> int:+ n = 0+ keeps = 0+ for c in all_cells():+ n += 1+ if c.event in HISTORY and land(c.event) != "history":+ raise ValueError(f"history-land: {c.case_id()}")+ if c.event not in HISTORY and land(c.event) != "prefix":+ raise ValueError(f"prefix-land: {c.case_id()}")+ if keep(c):+ keeps += 1+ if land(c.event) != c.land or verdict(c.event) != "keep":+ raise ValueError(f"wrong-keep: {c.case_id()}")+ elif land(c.event) == c.land and verdict(c.event) == "keep":+ raise ValueError(f"missed-keep: {c.case_id()}")+ if n != CUBE:+ raise ValueError(f"stable-cube: n={n} want={CUBE}")+ if keeps != KEEP:+ raise ValueError(f"keep-cells: n={keeps} want={KEEP}")+ idle = State()+ pinned = step(idle, ("start",))+ if not hit_ok(pinned):+ raise ValueError("trace: start should hit")+ for ev in ("turn", "skill_inject", "schema_load", "toolset_append"):+ if step(pinned, ("ev", ev)) != pinned:+ raise ValueError(f"trace: {ev} rewrote the prefix")+ if not hit_ok(run(idle, [("start",), ("ev", "compact")])):+ raise ValueError("trace: compact should re-pin")+ if hit_ok(run(idle, [("start",), ("ev", "set_system_prompt")])):+ raise ValueError("trace: set_system_prompt should bust")+ if hit_ok(run(idle, [("start",), ("ev", "clock_tick")])):+ raise ValueError("trace: clock_tick should bust")+ if hit_ok(run(idle, [("start",), ("ev", "toolset_rewrite")])):+ raise ValueError("trace: toolset_rewrite should bust")+ if hit_ok(run(idle, [("start",), ("ev", "memory_reload")])):+ raise ValueError("trace: memory_reload should bust")+ walk_ok = run(+ idle,+ [+ ("start",),+ ("ev", "turn"),+ ("ev", "skill_inject"),+ ("ev", "schema_load"),+ ("ev", "toolset_append"),+ ("ev", "compact"),+ ],+ )+ if not hit_ok(walk_ok):+ raise ValueError("trace: maximizing walk left the HIT cell")+ if keep(Cell("skill_inject", "prefix")):+ raise ValueError("trace: skill in prefix must miss")+ return ndiff --git a/src/spec_prompt_stable_conformance.zig b/src/spec_prompt_stable_conformance.zignew file mode 100644index 00000000..21f9dab6--- /dev/null+++ b/src/spec_prompt_stable_conformance.zig@@ -0,0 +1,104 @@+//! Impl half of PromptStable: OpenGauss must-nots against live gates.+//! Essay refresh is 0 (ADR 0005). Skills stay out of the prefix. The+//! system prompt has no per-request clock. Standing-line change busts+//! once; the same objective re-composes identically.++const std = @import("std");+const goal_state = @import("goal_state.zig");+const prompts = @import("prompts.zig");+const skill_docs = @import("skill_docs.zig");+const Agent = @import("agent.zig").Agent;++const fixtures_json = @embedFile("spec_prompt_stable");++fn keep(event: []const u8, land: []const u8) bool {+ const hist = std.mem.eql(u8, land, "history");+ const pref = std.mem.eql(u8, land, "prefix");+ if (std.mem.eql(u8, event, "turn") or std.mem.eql(u8, event, "skill_inject") or std.mem.eql(u8, event, "schema_load"))+ return hist;+ if (std.mem.eql(u8, event, "toolset_append") or std.mem.eql(u8, event, "compact"))+ return pref;+ return false;+}++test "spec/prompt_stable: cube matches 5 keep cells" {+ 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, 20), 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 event = cell.get("event").?.string;+ const land = cell.get("land").?.string;+ const want = case.get("keep").?.bool;+ const got = keep(event, land);+ if (want != got) {+ std.debug.print("\ncounterexample {s}: keep want={} got={}\n", .{ id, want, got });+ return error.CatalogMismatch;+ }+ if (got) hits += 1;+ }+ try std.testing.expectEqual(@as(usize, 5), hits);+}++test "spec/prompt_stable: standing essay never refreshes (OpenGauss: no mid-session rebuild)" {+ try std.testing.expectEqual(@as(u32, 0), goal_state.essay_refresh_turns);+ const first = goal_state.steeringGate("[standing goal: x]", 0, 0, 0);+ try std.testing.expect(first.inject);+ const again = goal_state.steeringGate("[standing goal: x]", first.fp, 99, 0);+ try std.testing.expect(!again.inject);+}++test "spec/prompt_stable: system prompt has no per-request clock" {+ const p = prompts.main_system_prompt;+ try std.testing.expect(std.mem.indexOf(u8, p, "Current date") == null);+ try std.testing.expect(std.mem.indexOf(u8, p, "current time") == null);+ try std.testing.expect(std.mem.indexOf(u8, p, "Monday") == null);+}++test "spec/prompt_stable: same standing line re-composes; a change busts" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const playbook = @import("playbook.zig");+ const saved = playbook.g_root_inject;+ playbook.g_root_inject = false;+ defer playbook.g_root_inject = saved;+ var agent: Agent = undefined;+ agent.goal = null;+ defer {+ agent.goal = null;+ prompts.pinStandingGoal(&agent, a);+ }+ try prompts.setSystemPrompts(&agent, "BASE", a);+ agent.goal = .{ .objective = "keep the build green", .status = .active };+ prompts.pinStandingGoal(&agent, a);+ const first = agent.sys_normal;+ prompts.pinStandingGoal(&agent, a);+ try std.testing.expectEqualStrings(first, agent.sys_normal);+ agent.goal = .{ .objective = "ship the release", .status = .active };+ prompts.pinStandingGoal(&agent, a);+ try std.testing.expect(!std.mem.eql(u8, first, agent.sys_normal));+}++test "spec/prompt_stable: skill load lands in history, not the prefix" {+ 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 },+ };+ 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(std.mem.indexOf(u8, loaded.text, "SECRET-BODY") != null);+ 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 c304195a..e381751b 100644--- a/src/tool_gates.zig+++ b/src/tool_gates.zig@@ -106,6 +106,7 @@ test { // the served catalogs' wire-compatibility guard (an unreferenced module'_ = @import("spec_prompt_cache_conformance.zig");_ = @import("spec_prompt_cache_kernel_conformance.zig");_ = @import("spec_prompt_prefix_conformance.zig");+ _ = @import("spec_prompt_stable_conformance.zig");}test "#352: an optional tool is advertised only while its flag is set; other names are unaffected" {