graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(spec): GoalLoop and PromptCache as Event/step process kernels
Rach Pradhan99fa8fe02fbf
diff --git a/build.zig b/build.zigindex 8ea7ff4b..b9c077d6 100644--- a/build.zig+++ b/build.zig@@ -102,6 +102,7 @@ pub fn build(b: *std.Build) void {unit_tests.root_module.addAnonymousImport("spec_score", .{ .root_source_file = b.path("spec/kernels/score.json") });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") });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 8414137c..1c721289 100644--- a/lean-proofs/Graff.lean+++ b/lean-proofs/Graff.lean@@ -8,3 +8,4 @@ import Graff.Scoreimport Graff.BashPolicyimport Graff.StructuredOutputimport Graff.TerminalModes+import Graff.PromptCachediff --git a/lean-proofs/Graff/GoalLoop.lean b/lean-proofs/Graff/GoalLoop.leanindex 56f09033..cfc80a74 100644--- a/lean-proofs/Graff/GoalLoop.lean+++ b/lean-proofs/Graff/GoalLoop.lean@@ -7,6 +7,12 @@The checklist is collapsed to what the gate actually reads: none / open /all-completed. Empty is none, never done.+ Process kernel, not a Turing machine (finite `Event` / `step`, no tape).+ The 360-cell cube is the snapshot of that machine: refuse arms, a second+ attempt accepts, standing has no retire edge, and `checklistFinished` is+ unreachable without `write allCompleted`. GoalLoop is the worked example;+ cube kernels stay cubes.+Executable port: spec/ref/goal_loop.py.-/@@ -36,7 +42,7 @@ structure State wherechecklist : Checklist := .nonedirty : Bool := falsearmed : Bool := false-deriving Repr, BEq+deriving Repr, BEq, DecidableEqdef goalActive (s : State) : Bool :=if s.seat ≠ .root then false@@ -118,6 +124,145 @@ theorem armed_accepts (s : State) (h₁ : goalActive s = true) (h₂ : s.armed =unfold completionGatesimp [h₁, h₂]+/-! The machine. Snapshot predicates above; these are the edges. -/++/-- Discrete harness actions. Seat is configuration, not an event.+ Empty `todo_write` is `write .none` and is a no-op. World-done is not here. -/+inductive Event where+ | setGoal (standing : Bool)+ | pause+ | resume+ | clear+ | write (c : Checklist)+ | attempt+deriving DecidableEq, Repr, BEq++/-- Live work being replaced. Complete/none adopt the current checklist. -/+def liveGoal : Goal → Bool+ | .active | .paused | .blocked => true+ | .none | .complete => false++def setActive (s : State) (standing : Bool) (reset : Bool) : State :=+ if reset then+ { seat := s.seat, goal := Goal.active, standing := standing, checklist := Checklist.none, dirty := false, armed := false }+ else+ { s with goal := Goal.active, standing := standing, armed := false }++def step (s : State) (e : Event) : State :=+ match e with+ | Event.setGoal standing => setActive s standing (liveGoal s.goal)+ | Event.pause => if decide (s.goal = Goal.active) then { s with goal := Goal.paused } else s+ | Event.resume => if decide (s.goal = Goal.paused) then { s with goal := Goal.active } else s+ | Event.clear => { seat := s.seat, goal := Goal.none, standing := false, checklist := Checklist.none, dirty := false, armed := false }+ | Event.write c => if decide (c = Checklist.none) then s else { s with checklist := c, dirty := true, armed := false }+ | Event.attempt =>+ match completionGate s with+ | Verdict.refuseOpen => { s with armed := true }+ | Verdict.refuseNoPlan => { s with armed := true }+ | Verdict.accept =>+ if retiresOnAccept s then { s with armed := false, goal := Goal.complete } else { s with armed := false }++def run (s : State) : List Event → State+ | [] => s+ | e :: es => run (step s e) es++def writesDone : Event → Bool+ | Event.write .allCompleted => true+ | _ => false++def noDoneWrite : List Event → Bool+ | [] => true+ | e :: es => !writesDone e && noDoneWrite es++/-! Missing-edge / path facts. Same propositions as the snapshot theorems. -/++theorem write_none_id (s : State) : step s (.write .none) = s := by+ simp [step]++theorem write_open_never_finished (s : State) :+ checklistFinished (step s (.write .open)) = false := by+ simp [step, checklistFinished, allDone]++theorem standing_attempt_preserves_goal (s : State) (h : s.standing = true) :+ (step s .attempt).goal = s.goal := by+ simp [step]+ cases completionGate s <;> simp [standing_does_not_retire s h]++theorem sub_attempt_preserves_goal (s : State) (h : s.seat = .sub) :+ (step s .attempt).goal = s.goal := by+ have hg : completionGate s = .accept := sub_never_refuses s h+ have hr : retiresOnAccept s = false := by simp [retiresOnAccept, goalActive, h]+ simp [step, hg, hr]++theorem review_attempt_preserves_goal (s : State) (h : s.seat = .review) :+ (step s .attempt).goal = s.goal := by+ have hg : completionGate s = .accept := review_never_refuses s h+ have hr : retiresOnAccept s = false := by simp [retiresOnAccept, goalActive, h]+ simp [step, hg, hr]++theorem paused_attempt_preserves_goal (s : State) (h : s.goal = .paused) :+ (step s .attempt).goal = s.goal := by+ have hg : completionGate s = .accept := paused_never_refuses s h+ have hr : retiresOnAccept s = false := by simp [retiresOnAccept, goalActive, h]+ simp [step, hg, hr]++theorem refuse_arms (s : State)+ (h : completionGate s = .refuseOpen ∨ completionGate s = .refuseNoPlan) :+ (step s .attempt).armed = true ∧ (step s .attempt).goal = s.goal := by+ cases h with+ | inl h => simp [step, h]+ | inr h => simp [step, h]++theorem attempt_keeps_list (s : State) :+ (step s .attempt).checklist = s.checklist ∧+ (step s .attempt).dirty = s.dirty := by+ simp [step]+ cases completionGate s <;> simp+ split <;> simp++theorem setGoal_preserves_unfinished (s : State) (standing : Bool)+ (h0 : checklistFinished s = false) :+ checklistFinished (step s (.setGoal standing)) = false := by+ simp [step, setActive]+ cases liveGoal s.goal+ · simpa [checklistFinished] using h0+ · simp [checklistFinished, allDone]++theorem unfinished_step (s : State) (e : Event)+ (h0 : checklistFinished s = false) (hw : writesDone e = false) :+ checklistFinished (step s e) = false := by+ cases e with+ | setGoal b => exact setGoal_preserves_unfinished s b h0+ | pause =>+ simp [step]+ split <;> simpa [checklistFinished] using h0+ | resume =>+ simp [step]+ split <;> simpa [checklistFinished] using h0+ | clear => simp [step, checklistFinished, allDone]+ | write c =>+ match c with+ | .none => simpa [write_none_id] using h0+ | .open => simp [step, checklistFinished, allDone]+ | .allCompleted => simp [writesDone] at hw+ | attempt =>+ have k := attempt_keeps_list s+ simp [checklistFinished] at h0 ⊢+ rw [k.1, k.2]; exact h0++theorem no_done_write_never_finished (s : State) (es : List Event)+ (h0 : checklistFinished s = false) (hw : noDoneWrite es = true) :+ checklistFinished (run s es) = false := by+ induction es generalizing s with+ | nil => simpa [run] using h0+ | cons e rest ih =>+ simp only [run]+ cases hwe : writesDone e+ · have hr : noDoneWrite rest = true := by+ simp [noDoneWrite, hwe] at hw; exact hw+ exact ih (step s e) (unfinished_step s e h0 hwe) hr+ · simp [noDoneWrite, hwe] at hw+/-! Concrete cells the harness also checks. -/example : completionGate {} = .accept := by native_decide@@ -133,6 +278,16 @@ example : checklistFinished { checklist := .allCompleted, dirty := true } = trueexample : retiresOnAccept { goal := .active } = true := by native_decideexample : retiresOnAccept { goal := .active, standing := true } = false := by native_decide+/-! Traces of `step`. Double-check = refuse then accept; standing has no retire. -/++example : (run {} [.setGoal false, .attempt]).armed = true := by native_decide+example : (run {} [.setGoal false, .attempt]).goal = .active := by native_decide+example : (run {} [.setGoal false, .attempt, .attempt]).goal = .complete := by native_decide+example : (run {} [.setGoal true, .attempt, .attempt]).goal = .active := by native_decide+example : (run {} [.setGoal false, .write .allCompleted, .attempt]).goal = .complete := by native_decide+example : (run {} [.setGoal true, .write .allCompleted, .attempt]).goal = .active := by native_decide+example : checklistFinished (run {} [.setGoal false, .write .open, .attempt]) = false := by native_decide+/-! Tiny list model for `allDone` / replace, so empty ≠ done is not just an enum. -/inductive Status wherediff --git a/lean-proofs/Graff/PromptCache.lean b/lean-proofs/Graff/PromptCache.leannew file mode 100644index 00000000..1de9112d--- /dev/null+++ b/lean-proofs/Graff/PromptCache.lean@@ -0,0 +1,203 @@+/-+ Prompt-cache / spawn kernel.++ Process kernel, not a Turing machine: finite `Event` / `step`, no tape.+ Seat is who may spawn. Label is the cache predicate (`main` is the only+ sticky root partition). Isolation is a spawn parameter and does not mint+ a key. Wire/grok say which carrier is on the request; they do not change+ the partition.++ The 48-cell cube is the snapshot. `Event` / `step` is the machine:+ sub never spawns, spawn isolates the child, join restores the root key.++ Executable port: spec/ref/prompt_cache.py.+-/++namespace Graff.PromptCache++inductive Seat where+ | root | sub+deriving DecidableEq, Repr, BEq++/-- `main` is the only sticky root partition. Anything else is a child suffix. -/+inductive Label where+ | main | other+deriving DecidableEq, Repr, BEq++inductive Isolation where+ | sharedCwd | worktree+deriving DecidableEq, Repr, BEq++inductive Wire where+ | openai | responses | anthropic+deriving DecidableEq, Repr, BEq++inductive Partition where+ | root | child+deriving DecidableEq, Repr, BEq++structure Cell where+ wire : Wire := .openai+ label : Label := .main+ isolation : Isolation := .sharedCwd+ grok : Bool := false+ seat : Seat := .root+deriving Repr, BEq, DecidableEq++def emitKey : Wire → Bool+ | .anthropic => false+ | .openai => true+ | .responses => true++/-- Partition depends on label only. Isolation is not an argument that matters. -/+def partitionOf (label : Label) : Isolation → Partition+ | _ => match label with+ | .main => .root+ | .other => .child++def spawnOk (seat : Seat) : Bool := decide (seat = Seat.root)++/-- When both carriers are present they name the same partition. -/+def headerAgrees (c : Cell) : Bool :=+ if !c.grok then true+ else if !emitKey c.wire then true+ else decide (partitionOf c.label c.isolation = partitionOf c.label c.isolation)++def allCells : List Cell :=+ Id.run do+ let mut acc : List Cell := []+ for wire in [Wire.openai, .responses, .anthropic] do+ for label in [Label.main, .other] do+ for isolation in [Isolation.sharedCwd, .worktree] do+ for grok in [false, true] do+ for seat in [Seat.root, .sub] do+ acc := acc ++ [{ wire, label, isolation, grok, seat }]+ return acc++def cacheCells : Nat := allCells.length+def spawnOkCells : Nat := (allCells.filter (fun c => spawnOk c.seat)).length+def keyCells : Nat := (allCells.filter (fun c => emitKey c.wire)).length++theorem cache_cube : cacheCells = 48 := by native_decide+theorem spawn_ok_count : spawnOkCells = 24 := by native_decide+theorem key_count : keyCells = 32 := by native_decide++theorem anthropic_never_key (c : Cell) (h : c.wire = .anthropic) :+ emitKey c.wire = false := by+ simp [emitKey, h]++theorem openai_emits_key (c : Cell) (h : c.wire = .openai) :+ emitKey c.wire = true := by+ simp [emitKey, h]++theorem responses_emits_key (c : Cell) (h : c.wire = .responses) :+ emitKey c.wire = true := by+ simp [emitKey, h]++theorem main_is_root (iso : Isolation) : partitionOf .main iso = .root := by+ cases iso <;> rfl++theorem other_is_child (iso : Isolation) : partitionOf .other iso = .child := by+ cases iso <;> rfl++theorem isolation_does_not_mint_key (label : Label) :+ partitionOf label .sharedCwd = partitionOf label .worktree := by+ cases label <;> rfl++theorem sub_never_spawn_ok (c : Cell) (h : c.seat = .sub) :+ spawnOk c.seat = false := by+ simp [spawnOk, h]++theorem root_spawn_ok (c : Cell) (h : c.seat = .root) :+ spawnOk c.seat = true := by+ simp [spawnOk, h]++theorem header_agrees (c : Cell) : headerAgrees c = true := by+ simp [headerAgrees]++/-! The machine. Snapshot predicates above; these are the edges. -/++structure State where+ seat : Seat := .root+ label : Label := .main+ isolation : Isolation := .sharedCwd+ partition : Partition := .root+deriving Repr, BEq, DecidableEq++inductive Event where+ | turn+ | spawn (bg : Bool) (iso : Isolation)+ | join+deriving DecidableEq, Repr, BEq++def childOf (iso : Isolation) : State :=+ { seat := Seat.sub, label := Label.other, isolation := iso, partition := Partition.child }++def rootOf (iso : Isolation) : State :=+ { seat := Seat.root, label := Label.main, isolation := iso, partition := Partition.root }++def step (s : State) (e : Event) : State :=+ match e with+ | Event.turn => s+ | Event.spawn _ iso =>+ if decide (s.seat = Seat.sub) then s else childOf iso+ | Event.join =>+ if decide (s.seat = Seat.root) then s else rootOf s.isolation++def run (s : State) : List Event → State+ | [] => s+ | e :: es => run (step s e) es++theorem turn_id (s : State) : step s .turn = s := rfl++theorem spawn_mode_irrelevant (s : State) (iso : Isolation) :+ step s (.spawn false iso) = step s (.spawn true iso) := by+ simp [step]++theorem sub_never_spawns (s : State) (bg : Bool) (iso : Isolation)+ (h : s.seat = Seat.sub) :+ step s (.spawn bg iso) = s := by+ simp [step, h]++theorem spawn_isolates (s : State) (bg : Bool) (iso : Isolation)+ (h : s.seat = Seat.root) :+ (step s (.spawn bg iso)).partition = Partition.child ∧+ (step s (.spawn bg iso)).seat = Seat.sub ∧+ (step s (.spawn bg iso)).label = Label.other := by+ simp [step, h, childOf]++theorem join_restores_root (s : State) (h : s.seat = Seat.sub) :+ (step s .join).partition = Partition.root ∧+ (step s .join).seat = Seat.root ∧+ (step s .join).label = Label.main := by+ simp [step, h, rootOf]++theorem join_from_root_id (s : State) (h : s.seat = Seat.root) :+ step s .join = s := by+ simp [step, h]++theorem spawn_isolation_does_not_mint (s : State) (bg : Bool)+ (h : s.seat = Seat.root) :+ (step s (.spawn bg .sharedCwd)).partition =+ (step s (.spawn bg .worktree)).partition := by+ simp [step, h, childOf]++theorem run_spawn_join_restores :+ run {} [.spawn false .sharedCwd, .join] = rootOf .sharedCwd := by+ native_decide++theorem run_sub_spawn_stays :+ run (childOf .sharedCwd) [.spawn true .worktree, .turn] =+ childOf .sharedCwd := by+ native_decide++example : emitKey .anthropic = false := by native_decide+example : emitKey .responses = true := by native_decide+example : partitionOf .main .worktree = .root := by native_decide+example : partitionOf .other .sharedCwd = .child := by native_decide+example : spawnOk .sub = false := by native_decide+example : (step {} (.spawn false .worktree)).partition = .child := by native_decide+example : (step (childOf .sharedCwd) .join).partition = .root := by native_decide+example : step (childOf .sharedCwd) (.spawn false .worktree) = childOf .sharedCwd := by native_decide++end Graff.PromptCachediff --git a/lean-proofs/KERNELS.md b/lean-proofs/KERNELS.mdindex d4443fd9..9d67100e 100644--- a/lean-proofs/KERNELS.md+++ b/lean-proofs/KERNELS.md@@ -3,6 +3,20 @@A kernel graduates when (1) Lean builds, (2) the reference model exhauststhe reachable cells, (3) the Zig implementation matches the export.+## Process vs cube++A kernel is a **cube** (flag or table product; `native_decide` over the cells)+or a **process** (a finite `Event` / `step` state diagram). Process kernels+are not Turing machines: no tape, no halt state, no computability encoding.+The diagram is the transition function. The cube, if the kernel has one, is+the snapshot of that function.++`GoalLoop` and `PromptCache` are the process kernels. GoalLoop: standing+has no retire edge; harness-done needs a done write. PromptCache: sub never+spawns; spawn isolates the child key; join restores the root partition;+isolation does not mint a key. Score, Shape, Provider, and ToolCatalog stay cubes.++## Every harness partEvery part is **live**, **new**, or **never**. Never is a classification,@@ -15,7 +29,8 @@ not a skip: TUI, prompts, and SSE bytes stay out of Lean on purpose.| `ToolCatalog` | 64 flag cubes | MCP names, descriptions, JSON wrappers || `Transport` | 96 turns; **1** WS cell | frames, TLS, idle-kill timing of the server || `Provider` | 18 baked rows | live `/models` overlay, Kimi protocol flip |-| `GoalLoop` | 360 gate cells | model wording, whether the work is correct |+| `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 || `PathConfine` | 16 lexical paths + 80 lease cells | OS errno, Windows drives, live symlink walk || `Shape` | 1728 ladder cells | `admit`, learned override, ε-explore, `observe` || `Score` | 1210 filing cells (240 filed); 11 titles; 16 class samples | HMAC, providerClass price fallback |diff --git a/lean-proofs/Main.lean b/lean-proofs/Main.leanindex 31121c39..4f9d487c 100644--- a/lean-proofs/Main.lean+++ b/lean-proofs/Main.lean@@ -6,6 +6,7 @@ import Graff.PathConfineimport Graff.Shapeimport Graff.Scoreimport Graff.BashPolicy+import Graff.PromptCacheopen Graff@@ -22,4 +23,5 @@ def main : IO Unit := doIO.println s!"shape {Shape.shapeCells} R0={Shape.r0Cells} R3={Shape.r3Cells}"IO.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!"cells_total {ToolCatalog.catalogCells + Transport.transportCells + Provider.providerRows + GoalLoop.goalCells + PathConfine.leaseCells + Shape.shapeCells + Score.scoreCells + BashPolicy.bashCells}"+ 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}"diff --git a/spec/README.md b/spec/README.mdindex 3694d370..8daba05d 100644--- a/spec/README.md+++ b/spec/README.md@@ -44,7 +44,8 @@ properties are load-bearing, and a missed combination is a real bug.| `tool_catalog` | live | 64 catalog cubes. `#330` / `#352` / `--lean`. || `transport` | live | 96 turns, **1** WebSocket cell. `Kind × seat × flags`. || `provider` | live | 18 baked rows over 3 wire kinds. |-| `goal_loop` | live | 360 gate cells. Empty ≠ done. Standing does not retire. |+| `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. || `path_confine` | live | Lexical cwd jail, symlink prefixes, 80 lease verdicts. || `shape` | live | 1728 cells. Hand ladder + explicit arm. Budget from remaining/cap/floor. || `score` | live | 1210 filing cells, 240 filed. First-word titles, needle class, `[0,1]` scale. |@@ -55,12 +56,20 @@ properties are load-bearing, and a missed combination is a real bug.```shpython3 spec/conformance.py # properties + fixture self-check-python3 spec/conformance.py --export # regenerate kernels/tool_catalog.json+python3 spec/conformance.py --export # regenerate kernels/*.json and GoalLoop mermaid+python3 spec/conformance.py --diagram goal_loop # live Event/step projection+python3 spec/conformance.py --diagram prompt_cachepython3 spec/conformance.py --break imagegen-always-on # demo a counterexamplepython3 spec/conformance.py --lean # lake build, if installedzig build test --summary none -Dtest-filter="spec/tool_catalog"```+Process kernels (`GoalLoop`, `PromptCache`) are finite `Event` / `step`+diagrams, not Turing machines. Cube kernels (Score, Shape, Provider,+ToolCatalog) stay cubes. `--diagram goal_loop` / `--diagram prompt_cache`+print the live `step` projection; `--export` writes those fences into+`kernels/*.md`.+The Zig test is the impl half of the harness: it sets the same flags thespec enumerated, asks `effectiveRootSpecs` / `subToolsJson` for names, andfails with the first differing cell as a counterexample.diff --git a/spec/conformance.py b/spec/conformance.pyindex 1555d24e..51927728 100644--- a/spec/conformance.py+++ b/spec/conformance.py@@ -46,13 +46,12 @@ from ref.path_confine import (owner_verdict,warns,)-from ref.goal_loop import (- all_states as all_goal_states,- checklist_finished,- completion_gate,- goal_active,- retires_on_accept,-)+from ref.goal_loop import check_properties as goal_check_properties+from ref.goal_loop import payload as goal_payload+from ref.prompt_cache import check_properties as cache_check_properties+from ref.prompt_cache import payload as cache_payload+from ref.prompt_cache import write_kernel_md as write_cache_md+from ref.prompt_cache import kernel_md as cache_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@@ -76,6 +75,7 @@ SCORE_FIXTURE = KERNELS / "score.json"BASH_FIXTURE = KERNELS / "bash_policy.json"SOX_FIXTURE = KERNELS / "structured_output.json"TERM_FIXTURE = KERNELS / "terminal_modes.json"+CACHE_FIXTURE = KERNELS / "prompt_cache.json"LEAN_DIR = ROOT.parent / "lean-proofs"@@ -264,28 +264,6 @@ def provider_payload() -> dict:return {"kernel": "provider", "version": 1, "rows": PROVIDER_SPECS}-def goal_payload() -> dict:- cases = []- for s in all_goal_states():- cases.append(- {- "id": s.case_id(),- "state": {- "seat": s.seat,- "goal": s.goal,- "standing": s.standing,- "checklist": s.checklist,- "dirty": s.dirty,- "armed": s.armed,- },- "completion_gate": completion_gate(s),- "checklist_finished": checklist_finished(s),- "retires_on_accept": retires_on_accept(s),- }- )- return {"kernel": "goal_loop", "version": 1, "cases": cases}--def path_payload() -> dict:return {"kernel": "path_confine",@@ -337,32 +315,19 @@ def check_provider() -> int:return len(PROVIDER_SPECS)+def _ref(fn, name: str) -> int:+ try:+ return fn()+ except ValueError as e:+ raise Counterexample(name, None, str(e)) from e++def check_goal_loop() -> int:- n = 0- for s in all_goal_states():- n += 1- v = completion_gate(s)- if s.seat != "root" and v != "accept":- raise Counterexample("non-root-never-refuses", s, f"gate={v}")- if s.goal != "active" and v != "accept":- raise Counterexample("inactive-never-refuses", s, f"gate={v}")- if s.checklist == "none" and checklist_finished(s):- raise Counterexample("empty-never-done", s, "empty checklist counted as finished")- if goal_active(s) and not s.armed and s.checklist == "open" and v != "refuse_open":- raise Counterexample("open-refused", s, f"gate={v}")- if goal_active(s) and not s.armed and s.checklist == "none" and v != "refuse_no_plan":- raise Counterexample("empty-refused", s, f"gate={v}")- if goal_active(s) and not s.armed and s.checklist == "all_completed" and v != "accept":- raise Counterexample("done-accepted", s, f"gate={v}")- if s.armed and goal_active(s) and v != "accept":- raise Counterexample("armed-accepts", s, f"gate={v}")- if s.dirty is False and checklist_finished(s):- raise Counterexample("finished-needs-dirty", s, "restored all-[x] counted as done")- if s.standing and retires_on_accept(s):- raise Counterexample("standing-does-not-retire", s, "standing retired")- if goal_active(s) and not s.standing and not retires_on_accept(s):- raise Counterexample("active-retires", s, "active ordinary should retire")- return n+ return _ref(goal_check_properties, "goal_loop")+++def check_prompt_cache() -> int:+ return _ref(cache_check_properties, "prompt_cache")def check_path_confine() -> int:@@ -403,48 +368,23 @@ def check_path_confine() -> int:def check_shape() -> int:- try:- return shape_check_properties()- except ValueError as e:- msg = str(e)- prop, _, detail = msg.partition(": ")- raise Counterexample(prop, None, detail or msg) from e+ return _ref(shape_check_properties, 'shape')def check_score() -> int:- try:- return score_check_properties()- except ValueError as e:- msg = str(e)- prop, _, detail = msg.partition(": ")- raise Counterexample(prop, None, detail or msg) from e+ return _ref(score_check_properties, 'score')def check_bash() -> int:- try:- return bash_check_properties()- except ValueError as e:- msg = str(e)- prop, _, detail = msg.partition(": ")- raise Counterexample(prop, None, detail or msg) from e+ return _ref(bash_check_properties, 'bash')def check_sox() -> int:- try:- return sox_check_properties()- except ValueError as e:- msg = str(e)- prop, _, detail = msg.partition(": ")- raise Counterexample(prop, None, detail or msg) from e+ return _ref(sox_check_properties, 'sox')def check_term() -> int:- try:- return term_check_properties()- except ValueError as e:- msg = str(e)- prop, _, detail = msg.partition(": ")- raise Counterexample(prop, None, detail or msg) from e+ return _ref(term_check_properties, 'term')def prefixes_first(p: str) -> list[str]:@@ -459,17 +399,21 @@ def _write(path: Path, payload: dict) -> Path:def export() -> list[Path]:+ from ref.goal_loop import write_kernel_mdreturn [_write(FIXTURE, cases_payload()),_write(TRANSPORT_FIXTURE, transport_payload()),_write(PROVIDER_FIXTURE, provider_payload()),_write(GOAL_FIXTURE, goal_payload()),+ write_kernel_md(KERNELS / "goal_loop.md"),_write(PATH_FIXTURE, path_payload()),_write(SHAPE_FIXTURE, shape_payload()),_write(SCORE_FIXTURE, score_payload()),_write(BASH_FIXTURE, bash_payload()),_write(SOX_FIXTURE, sox_model_payload()),_write(TERM_FIXTURE, term_model_payload()),+ _write(CACHE_FIXTURE, cache_payload()),+ write_cache_md(KERNELS / "prompt_cache.md"),]@@ -491,6 +435,14 @@ def check_fixtures() -> None:_same(BASH_FIXTURE, bash_payload(), "bash_policy")_same(SOX_FIXTURE, sox_model_payload(), "structured_output")_same(TERM_FIXTURE, term_model_payload(), "terminal_modes")+ _same(CACHE_FIXTURE, cache_payload(), "prompt_cache")+ from ref.goal_loop import kernel_md+ md = KERNELS / "goal_loop.md"+ if not md.is_file() or md.read_text() != kernel_md():+ raise Counterexample("fixtures-stale", None, "goal_loop.md does not match live step; run --export")+ cmd = KERNELS / "prompt_cache.md"+ if not cmd.is_file() or cmd.read_text() != cache_kernel_md():+ raise Counterexample("fixtures-stale", None, "prompt_cache.md does not match live step; run --export")def break_model(kind: str) -> None:@@ -547,6 +499,7 @@ def main() -> int:sys.path.insert(0, str(ROOT))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("--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")@@ -561,6 +514,15 @@ def main() -> int:print(json.dumps(inv, indent=2) if args.json else render(inv))return 0 if inv["ok"] else 1+ if args.diagram:+ mods = {"goal_loop": "ref.goal_loop", "prompt_cache": "ref.prompt_cache"}+ path = mods.get(args.diagram)+ if path is None:+ print(f"no machine projection for {args.diagram}", file=sys.stderr)+ return 2+ sys.stdout.write(__import__(path, fromlist=["mermaid"]).mermaid())+ return 0+if args.mutate:break_model(args.mutate)@@ -569,6 +531,7 @@ def main() -> int:n_tr = check_transport()n_pr = check_provider()n_gl = check_goal_loop()+ n_ck = check_prompt_cache()n_pc = check_path_confine()n_sh = check_shape()n_sc = check_score()@@ -578,12 +541,13 @@ 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} 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} 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} path_confine {n_pc} shape {n_sh} score {n_sc} bash {n_ba} "+ f"provider {n_pr} goal_loop {n_gl} prompt_cache {n_ck} path_confine {n_pc} "+ f"shape {n_sh} score {n_sc} bash {n_ba} "f"structured_output {n_sx} terminal_modes {n_tm}")if args.lean:diff --git a/spec/kernels/goal_loop.md b/spec/kernels/goal_loop.mdindex df910efc..c8ca8d55 100644--- a/spec/kernels/goal_loop.md+++ b/spec/kernels/goal_loop.md@@ -2,7 +2,76 @@Source of truth: `lean-proofs/Graff/GoalLoop.lean`.-Harness-done, not world-done. `completionGate` says whether-`attempt_completion` may be accepted. Empty checklist is never done.-A restored all-`[x]` list is not this-process evidence (`dirty`).-Standing `--goal` records a claim and does not retire.+Process kernel, not a cube and not a Turing machine: finite `Event` / `step`,+no tape, no halt state. The 360-cell cube is the snapshot of that machine.+GoalLoop is the worked example. Standing has no retire edge. Harness-done+is unreachable without a `write allCompleted`. World-done is not an event.++The diagram is the root-seat projection of the live Python `step`+(same function `check_properties` walks). Emit it with+`python3 spec/conformance.py --diagram goal_loop`. `--export` rewrites+the fence below from that function; do not hand-edit the arrows.++```mermaid+stateDiagram-v2+ [*] --> Idle+ Complete --> Idle: clear+ Complete --> Task: setGoal+ Complete --> TaskDone: setGoal+ Complete --> TaskOpen: setGoal+ Complete --> StandDone: setGoal standing+ Complete --> StandOpen: setGoal standing+ Complete --> Standing: setGoal standing+ Idle --> Task: setGoal+ Idle --> TaskDone: setGoal+ Idle --> TaskOpen: setGoal+ Idle --> StandDone: setGoal standing+ Idle --> StandOpen: setGoal standing+ Idle --> Standing: setGoal standing+ Paused --> Idle: clear+ Paused --> Task: resume+ Paused --> TaskArmed: resume+ Paused --> TaskDone: resume+ Paused --> TaskOpen: resume+ StandArmed --> StandOpen: attempt+ StandArmed --> Standing: attempt+ StandArmed --> Idle: clear+ StandArmed --> StandPaused: pause+ StandArmed --> StandDone: write done+ StandArmed --> StandOpen: write open+ StandDone --> Idle: clear+ StandDone --> StandPaused: pause+ StandDone --> StandOpen: write open+ StandOpen --> StandArmed: attempt / refuse_open+ StandOpen --> Idle: clear+ StandOpen --> StandPaused: pause+ StandOpen --> StandDone: write done+ StandPaused --> Idle: clear+ StandPaused --> StandArmed: resume+ StandPaused --> StandDone: resume+ StandPaused --> StandOpen: resume+ StandPaused --> Standing: resume+ Standing --> StandArmed: attempt / refuse_no_plan+ Standing --> Idle: clear+ Standing --> StandPaused: pause+ Standing --> StandDone: write done+ Standing --> StandOpen: write open+ Task --> TaskArmed: attempt / refuse_no_plan+ Task --> Idle: clear+ Task --> Paused: pause+ Task --> TaskDone: write done+ Task --> TaskOpen: write open+ TaskArmed --> Complete: attempt+ TaskArmed --> Idle: clear+ TaskArmed --> Paused: pause+ TaskArmed --> TaskDone: write done+ TaskArmed --> TaskOpen: write open+ TaskDone --> Complete: attempt+ TaskDone --> Idle: clear+ TaskDone --> Paused: pause+ TaskDone --> TaskOpen: write open+ TaskOpen --> TaskArmed: attempt / refuse_open+ TaskOpen --> Idle: clear+ TaskOpen --> Paused: pause+ TaskOpen --> TaskDone: write done+```diff --git a/spec/kernels/prompt_cache.json b/spec/kernels/prompt_cache.jsonnew file mode 100644index 00000000..47f9560b--- /dev/null+++ b/spec/kernels/prompt_cache.json@@ -0,0 +1,678 @@+{+ "kernel": "prompt_cache",+ "version": 1,+ "cases": [+ {+ "id": "openai.main.shared_cwd.g0.root",+ "cell": {+ "wire": "openai",+ "label": "main",+ "isolation": "shared_cwd",+ "grok": false,+ "seat": "root"+ },+ "emit_key": true,+ "partition": "root",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "openai.main.shared_cwd.g0.sub",+ "cell": {+ "wire": "openai",+ "label": "main",+ "isolation": "shared_cwd",+ "grok": false,+ "seat": "sub"+ },+ "emit_key": true,+ "partition": "root",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "openai.main.shared_cwd.g1.root",+ "cell": {+ "wire": "openai",+ "label": "main",+ "isolation": "shared_cwd",+ "grok": true,+ "seat": "root"+ },+ "emit_key": true,+ "partition": "root",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "openai.main.shared_cwd.g1.sub",+ "cell": {+ "wire": "openai",+ "label": "main",+ "isolation": "shared_cwd",+ "grok": true,+ "seat": "sub"+ },+ "emit_key": true,+ "partition": "root",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "openai.main.worktree.g0.root",+ "cell": {+ "wire": "openai",+ "label": "main",+ "isolation": "worktree",+ "grok": false,+ "seat": "root"+ },+ "emit_key": true,+ "partition": "root",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "openai.main.worktree.g0.sub",+ "cell": {+ "wire": "openai",+ "label": "main",+ "isolation": "worktree",+ "grok": false,+ "seat": "sub"+ },+ "emit_key": true,+ "partition": "root",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "openai.main.worktree.g1.root",+ "cell": {+ "wire": "openai",+ "label": "main",+ "isolation": "worktree",+ "grok": true,+ "seat": "root"+ },+ "emit_key": true,+ "partition": "root",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "openai.main.worktree.g1.sub",+ "cell": {+ "wire": "openai",+ "label": "main",+ "isolation": "worktree",+ "grok": true,+ "seat": "sub"+ },+ "emit_key": true,+ "partition": "root",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "openai.other.shared_cwd.g0.root",+ "cell": {+ "wire": "openai",+ "label": "other",+ "isolation": "shared_cwd",+ "grok": false,+ "seat": "root"+ },+ "emit_key": true,+ "partition": "child",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "openai.other.shared_cwd.g0.sub",+ "cell": {+ "wire": "openai",+ "label": "other",+ "isolation": "shared_cwd",+ "grok": false,+ "seat": "sub"+ },+ "emit_key": true,+ "partition": "child",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "openai.other.shared_cwd.g1.root",+ "cell": {+ "wire": "openai",+ "label": "other",+ "isolation": "shared_cwd",+ "grok": true,+ "seat": "root"+ },+ "emit_key": true,+ "partition": "child",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "openai.other.shared_cwd.g1.sub",+ "cell": {+ "wire": "openai",+ "label": "other",+ "isolation": "shared_cwd",+ "grok": true,+ "seat": "sub"+ },+ "emit_key": true,+ "partition": "child",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "openai.other.worktree.g0.root",+ "cell": {+ "wire": "openai",+ "label": "other",+ "isolation": "worktree",+ "grok": false,+ "seat": "root"+ },+ "emit_key": true,+ "partition": "child",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "openai.other.worktree.g0.sub",+ "cell": {+ "wire": "openai",+ "label": "other",+ "isolation": "worktree",+ "grok": false,+ "seat": "sub"+ },+ "emit_key": true,+ "partition": "child",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "openai.other.worktree.g1.root",+ "cell": {+ "wire": "openai",+ "label": "other",+ "isolation": "worktree",+ "grok": true,+ "seat": "root"+ },+ "emit_key": true,+ "partition": "child",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "openai.other.worktree.g1.sub",+ "cell": {+ "wire": "openai",+ "label": "other",+ "isolation": "worktree",+ "grok": true,+ "seat": "sub"+ },+ "emit_key": true,+ "partition": "child",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "responses.main.shared_cwd.g0.root",+ "cell": {+ "wire": "responses",+ "label": "main",+ "isolation": "shared_cwd",+ "grok": false,+ "seat": "root"+ },+ "emit_key": true,+ "partition": "root",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "responses.main.shared_cwd.g0.sub",+ "cell": {+ "wire": "responses",+ "label": "main",+ "isolation": "shared_cwd",+ "grok": false,+ "seat": "sub"+ },+ "emit_key": true,+ "partition": "root",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "responses.main.shared_cwd.g1.root",+ "cell": {+ "wire": "responses",+ "label": "main",+ "isolation": "shared_cwd",+ "grok": true,+ "seat": "root"+ },+ "emit_key": true,+ "partition": "root",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "responses.main.shared_cwd.g1.sub",+ "cell": {+ "wire": "responses",+ "label": "main",+ "isolation": "shared_cwd",+ "grok": true,+ "seat": "sub"+ },+ "emit_key": true,+ "partition": "root",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "responses.main.worktree.g0.root",+ "cell": {+ "wire": "responses",+ "label": "main",+ "isolation": "worktree",+ "grok": false,+ "seat": "root"+ },+ "emit_key": true,+ "partition": "root",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "responses.main.worktree.g0.sub",+ "cell": {+ "wire": "responses",+ "label": "main",+ "isolation": "worktree",+ "grok": false,+ "seat": "sub"+ },+ "emit_key": true,+ "partition": "root",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "responses.main.worktree.g1.root",+ "cell": {+ "wire": "responses",+ "label": "main",+ "isolation": "worktree",+ "grok": true,+ "seat": "root"+ },+ "emit_key": true,+ "partition": "root",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "responses.main.worktree.g1.sub",+ "cell": {+ "wire": "responses",+ "label": "main",+ "isolation": "worktree",+ "grok": true,+ "seat": "sub"+ },+ "emit_key": true,+ "partition": "root",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "responses.other.shared_cwd.g0.root",+ "cell": {+ "wire": "responses",+ "label": "other",+ "isolation": "shared_cwd",+ "grok": false,+ "seat": "root"+ },+ "emit_key": true,+ "partition": "child",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "responses.other.shared_cwd.g0.sub",+ "cell": {+ "wire": "responses",+ "label": "other",+ "isolation": "shared_cwd",+ "grok": false,+ "seat": "sub"+ },+ "emit_key": true,+ "partition": "child",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "responses.other.shared_cwd.g1.root",+ "cell": {+ "wire": "responses",+ "label": "other",+ "isolation": "shared_cwd",+ "grok": true,+ "seat": "root"+ },+ "emit_key": true,+ "partition": "child",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "responses.other.shared_cwd.g1.sub",+ "cell": {+ "wire": "responses",+ "label": "other",+ "isolation": "shared_cwd",+ "grok": true,+ "seat": "sub"+ },+ "emit_key": true,+ "partition": "child",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "responses.other.worktree.g0.root",+ "cell": {+ "wire": "responses",+ "label": "other",+ "isolation": "worktree",+ "grok": false,+ "seat": "root"+ },+ "emit_key": true,+ "partition": "child",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "responses.other.worktree.g0.sub",+ "cell": {+ "wire": "responses",+ "label": "other",+ "isolation": "worktree",+ "grok": false,+ "seat": "sub"+ },+ "emit_key": true,+ "partition": "child",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "responses.other.worktree.g1.root",+ "cell": {+ "wire": "responses",+ "label": "other",+ "isolation": "worktree",+ "grok": true,+ "seat": "root"+ },+ "emit_key": true,+ "partition": "child",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "responses.other.worktree.g1.sub",+ "cell": {+ "wire": "responses",+ "label": "other",+ "isolation": "worktree",+ "grok": true,+ "seat": "sub"+ },+ "emit_key": true,+ "partition": "child",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "anthropic.main.shared_cwd.g0.root",+ "cell": {+ "wire": "anthropic",+ "label": "main",+ "isolation": "shared_cwd",+ "grok": false,+ "seat": "root"+ },+ "emit_key": false,+ "partition": "root",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "anthropic.main.shared_cwd.g0.sub",+ "cell": {+ "wire": "anthropic",+ "label": "main",+ "isolation": "shared_cwd",+ "grok": false,+ "seat": "sub"+ },+ "emit_key": false,+ "partition": "root",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "anthropic.main.shared_cwd.g1.root",+ "cell": {+ "wire": "anthropic",+ "label": "main",+ "isolation": "shared_cwd",+ "grok": true,+ "seat": "root"+ },+ "emit_key": false,+ "partition": "root",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "anthropic.main.shared_cwd.g1.sub",+ "cell": {+ "wire": "anthropic",+ "label": "main",+ "isolation": "shared_cwd",+ "grok": true,+ "seat": "sub"+ },+ "emit_key": false,+ "partition": "root",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "anthropic.main.worktree.g0.root",+ "cell": {+ "wire": "anthropic",+ "label": "main",+ "isolation": "worktree",+ "grok": false,+ "seat": "root"+ },+ "emit_key": false,+ "partition": "root",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "anthropic.main.worktree.g0.sub",+ "cell": {+ "wire": "anthropic",+ "label": "main",+ "isolation": "worktree",+ "grok": false,+ "seat": "sub"+ },+ "emit_key": false,+ "partition": "root",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "anthropic.main.worktree.g1.root",+ "cell": {+ "wire": "anthropic",+ "label": "main",+ "isolation": "worktree",+ "grok": true,+ "seat": "root"+ },+ "emit_key": false,+ "partition": "root",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "anthropic.main.worktree.g1.sub",+ "cell": {+ "wire": "anthropic",+ "label": "main",+ "isolation": "worktree",+ "grok": true,+ "seat": "sub"+ },+ "emit_key": false,+ "partition": "root",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "anthropic.other.shared_cwd.g0.root",+ "cell": {+ "wire": "anthropic",+ "label": "other",+ "isolation": "shared_cwd",+ "grok": false,+ "seat": "root"+ },+ "emit_key": false,+ "partition": "child",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "anthropic.other.shared_cwd.g0.sub",+ "cell": {+ "wire": "anthropic",+ "label": "other",+ "isolation": "shared_cwd",+ "grok": false,+ "seat": "sub"+ },+ "emit_key": false,+ "partition": "child",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "anthropic.other.shared_cwd.g1.root",+ "cell": {+ "wire": "anthropic",+ "label": "other",+ "isolation": "shared_cwd",+ "grok": true,+ "seat": "root"+ },+ "emit_key": false,+ "partition": "child",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "anthropic.other.shared_cwd.g1.sub",+ "cell": {+ "wire": "anthropic",+ "label": "other",+ "isolation": "shared_cwd",+ "grok": true,+ "seat": "sub"+ },+ "emit_key": false,+ "partition": "child",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "anthropic.other.worktree.g0.root",+ "cell": {+ "wire": "anthropic",+ "label": "other",+ "isolation": "worktree",+ "grok": false,+ "seat": "root"+ },+ "emit_key": false,+ "partition": "child",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "anthropic.other.worktree.g0.sub",+ "cell": {+ "wire": "anthropic",+ "label": "other",+ "isolation": "worktree",+ "grok": false,+ "seat": "sub"+ },+ "emit_key": false,+ "partition": "child",+ "spawn_ok": false,+ "header_agrees": true+ },+ {+ "id": "anthropic.other.worktree.g1.root",+ "cell": {+ "wire": "anthropic",+ "label": "other",+ "isolation": "worktree",+ "grok": true,+ "seat": "root"+ },+ "emit_key": false,+ "partition": "child",+ "spawn_ok": true,+ "header_agrees": true+ },+ {+ "id": "anthropic.other.worktree.g1.sub",+ "cell": {+ "wire": "anthropic",+ "label": "other",+ "isolation": "worktree",+ "grok": true,+ "seat": "sub"+ },+ "emit_key": false,+ "partition": "child",+ "spawn_ok": false,+ "header_agrees": true+ }+ ]+}diff --git a/spec/kernels/prompt_cache.md b/spec/kernels/prompt_cache.mdnew file mode 100644index 00000000..17568814--- /dev/null+++ b/spec/kernels/prompt_cache.md@@ -0,0 +1,19 @@+# Kernel: prompt cache / spawn++Source of truth: `lean-proofs/Graff/PromptCache.lean`.++Process kernel, not a cube-only table and not a Turing machine: finite+`Event` / `step`, no tape. Seat is who may spawn. Label is the cache+predicate (`main` is the only sticky root partition). Isolation does+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`.++```mermaid+stateDiagram-v2+ [*] --> Root+ Child --> Root: join+ Root --> Child: spawn+```diff --git a/spec/manifest.json b/spec/manifest.jsonindex f727f17d..9a8c0d1f 100644--- a/spec/manifest.json+++ b/spec/manifest.json@@ -56,7 +56,10 @@"zig": "src/spec_path_confine_conformance.zig","impl": "src/harness_policy.zig:confinedPath+src/worktree_lease.zig:ownerVerdict","cells_floor": 96,- "cells_key": ["paths", "leases"]+ "cells_key": [+ "paths",+ "leases"+ ]},{"id": "shape",@@ -87,6 +90,16 @@"impl": "src/harness_policy.zig:isSimple+escapesCwd+readOnlyAllowed","cells_floor": 32,"cells_key": "cases"+ },+ {+ "id": "prompt_cache",+ "lean": "lean-proofs/Graff/PromptCache.lean",+ "ref": "spec/ref/prompt_cache.py",+ "fixture": "spec/kernels/prompt_cache.json",+ "zig": "src/spec_prompt_cache_kernel_conformance.zig",+ "impl": "src/http_headers.zig:promptCacheKey+src/subagent_spawn.zig:allowed",+ "cells_floor": 48,+ "cells_key": "cases"}]}diff --git a/spec/ref/goal_loop.py b/spec/ref/goal_loop.pyindex bd9aa612..74c749f2 100644--- a/spec/ref/goal_loop.py+++ b/spec/ref/goal_loop.py@@ -2,18 +2,34 @@from __future__ import annotations-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom itertools import product+from pathlib import Pathfrom typing import LiteralSeat = Literal["root", "sub", "review"]Goal = Literal["none", "active", "paused", "blocked", "complete"]Checklist = Literal["none", "open", "all_completed"]Verdict = Literal["accept", "refuse_open", "refuse_no_plan"]+# ("setGoal", standing) | ("pause",) | ("resume",) | ("clear",)+# | ("write", checklist) | ("attempt",)+Event = tupleSEATS: tuple[Seat, ...] = ("root", "sub", "review")GOALS: tuple[Goal, ...] = ("none", "active", "paused", "blocked", "complete")LISTS: tuple[Checklist, ...] = ("none", "open", "all_completed")+LIVE_GOALS = frozenset({"active", "paused", "blocked"})+EVENTS: tuple[Event, ...] = (+ ("setGoal", False),+ ("setGoal", True),+ ("pause",),+ ("resume",),+ ("clear",),+ ("write", "open"),+ ("write", "all_completed"),+ ("attempt",),+)+KERNEL_MD = Path(__file__).resolve().parents[1] / "kernels" / "goal_loop.md"@dataclass(frozen=True)@@ -68,3 +84,265 @@ def all_states() -> list[State]:SEATS, GOALS, bits, LISTS, bits, bits)]+++def live_goal(g: Goal) -> bool:+ return g in LIVE_GOALS+++def step(s: State, e: Event) -> State:+ k = e[0]+ if k == "setGoal":+ standing = e[1]+ if live_goal(s.goal):+ return State(seat=s.seat, goal="active", standing=standing)+ return replace(s, goal="active", standing=standing, armed=False)+ if k == "pause":+ return replace(s, goal="paused") if s.goal == "active" else s+ if k == "resume":+ return replace(s, goal="active") if s.goal == "paused" else s+ if k == "clear":+ return replace(s, goal="none", standing=False, checklist="none", dirty=False, armed=False)+ if k == "write":+ c = e[1]+ if c == "none":+ return s+ return replace(s, checklist=c, dirty=True, armed=False)+ if k == "attempt":+ v = completion_gate(s)+ if v in ("refuse_open", "refuse_no_plan"):+ return replace(s, armed=True)+ s2 = replace(s, armed=False)+ return replace(s2, goal="complete") if retires_on_accept(s) else s2+ 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 writes_done(e: Event) -> bool:+ return e[0] == "write" and e[1] == "all_completed"+++def project(s: State) -> str:+ """Root-seat labels for the diagram. Seat is configuration, not an event."""+ if s.goal == "none":+ return "Idle"+ if s.goal == "complete":+ return "Complete"+ if s.goal == "blocked":+ return "StandBlocked" if s.standing else "TaskBlocked"+ if s.goal == "paused":+ return "StandPaused" if s.standing else "Paused"+ if s.armed:+ return "StandArmed" if s.standing else "TaskArmed"+ if s.checklist == "open":+ return "StandOpen" if s.standing else "TaskOpen"+ if s.checklist == "all_completed":+ return "StandDone" if s.standing else "TaskDone"+ return "Standing" if s.standing else "Task"+++def event_label(s: State, e: Event) -> str:+ k = e[0]+ if k == "setGoal":+ return "setGoal standing" if e[1] else "setGoal"+ if k == "write":+ return "write done" if e[1] == "all_completed" else "write open"+ if k == "attempt":+ v = completion_gate(s)+ return f"attempt / {v}" if v.startswith("refuse") else "attempt"+ return k+++def walk(start: State | None = None) -> list[tuple[State, Event, State]]:+ """Every non-identity `step` reachable from idle under EVENTS."""+ 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 _display(s: State, e: Event, t: State) -> bool:+ """Small projection: lifecycle events, plus setGoal entry and clear exit."""+ a, b = project(s), project(t)+ if a == b:+ return False+ k = e[0]+ if k in ("attempt", "pause", "resume", "write"):+ return True+ if k == "setGoal" and a in ("Idle", "Complete"):+ return True+ if k == "clear" and b == "Idle":+ return True+ return False+++def diagram_edges() -> list[tuple[str, str, str]]:+ found: set[tuple[str, str, str]] = set()+ for s, e, t in walk():+ if _display(s, e, t):+ found.add((project(s), event_label(s, e), project(t)))+ return sorted(found)++++def payload() -> dict:+ cases = []+ for s in all_states():+ cases.append(+ {+ "id": s.case_id(),+ "state": {+ "seat": s.seat,+ "goal": s.goal,+ "standing": s.standing,+ "checklist": s.checklist,+ "dirty": s.dirty,+ "armed": s.armed,+ },+ "completion_gate": completion_gate(s),+ "checklist_finished": checklist_finished(s),+ "retires_on_accept": retires_on_accept(s),+ }+ )+ return {"kernel": "goal_loop", "version": 1, "cases": cases}+++def mermaid() -> str:+ lines = ["stateDiagram-v2", " [*] --> Idle"]+ 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: goal / completion\n"+ "\n"+ "Source of truth: `lean-proofs/Graff/GoalLoop.lean`.\n"+ "\n"+ "Process kernel, not a cube and not a Turing machine: finite `Event` / `step`,\n"+ "no tape, no halt state. The 360-cell cube is the snapshot of that machine.\n"+ "GoalLoop is the worked example. Standing has no retire edge. Harness-done\n"+ "is unreachable without a `write allCompleted`. World-done is not an event.\n"+ "\n"+ "The diagram is the root-seat projection of the live Python `step`\n"+ "(same function `check_properties` walks). Emit it with\n"+ "`python3 spec/conformance.py --diagram goal_loop`. `--export` rewrites\n"+ "the fence below from that function; do not hand-edit the arrows.\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 check_diagram() -> None:+ raw = walk()+ saw_arm = False+ for s, e, t in raw:+ if e[0] != "attempt":+ continue+ if completion_gate(s) in ("refuse_open", "refuse_no_plan"):+ if t.armed and t.goal == s.goal:+ saw_arm = True+ else:+ raise ValueError(f"diagram: refuse did not arm {s.case_id()}")+ if s.standing and t.goal == "complete":+ raise ValueError(f"diagram: standing attempt retired {s.case_id()}")+ if not saw_arm:+ raise ValueError("diagram: missing refuse→arm on live step")+ text = mermaid()+ if "attempt / refuse_no_plan" not in text and "attempt / refuse_open" not in text:+ raise ValueError("diagram: mermaid missing refuse→arm label")+ if "Task --> TaskArmed: attempt / refuse_no_plan" not in text:+ raise ValueError("diagram: mermaid missing Task refuse-no-plan arm")+ for banned in (+ "StandArmed --> Complete",+ "StandDone --> Complete",+ "Standing --> Complete",+ "StandOpen --> Complete",+ "StandPaused --> Complete",+ ):+ if banned in text:+ raise ValueError(f"diagram: standing attempt→complete in mermaid ({banned})")+++def check_properties() -> int:+ n = 0+ for s in all_states():+ n += 1+ v = completion_gate(s)+ if s.seat != "root" and v != "accept":+ raise ValueError(f"non-root-never-refuses: {s.case_id()} gate={v}")+ if s.goal != "active" and v != "accept":+ raise ValueError(f"inactive-never-refuses: {s.case_id()} gate={v}")+ if s.checklist == "none" and checklist_finished(s):+ raise ValueError(f"empty-never-done: {s.case_id()}")+ if goal_active(s) and not s.armed and s.checklist == "open" and v != "refuse_open":+ raise ValueError(f"open-refused: {s.case_id()} gate={v}")+ if goal_active(s) and not s.armed and s.checklist == "none" and v != "refuse_no_plan":+ raise ValueError(f"empty-refused: {s.case_id()} gate={v}")+ if goal_active(s) and not s.armed and s.checklist == "all_completed" and v != "accept":+ raise ValueError(f"done-accepted: {s.case_id()} gate={v}")+ if s.armed and goal_active(s) and v != "accept":+ raise ValueError(f"armed-accepts: {s.case_id()} gate={v}")+ if s.dirty is False and checklist_finished(s):+ raise ValueError(f"finished-needs-dirty: {s.case_id()}")+ if s.standing and retires_on_accept(s):+ raise ValueError(f"standing-does-not-retire: {s.case_id()}")+ if goal_active(s) and not s.standing and not retires_on_accept(s):+ raise ValueError(f"active-retires: {s.case_id()}")+ if step(s, ("write", "none")) != s:+ raise ValueError(f"write-none-id: {s.case_id()}")+ if checklist_finished(step(s, ("write", "open"))):+ raise ValueError(f"write-open-never-finished: {s.case_id()}")+ if s.standing and step(s, ("attempt",)).goal != s.goal:+ raise ValueError(f"standing-attempt-preserves-goal: {s.case_id()}")+ if s.seat != "root" and step(s, ("attempt",)).goal != s.goal:+ raise ValueError(f"non-root-attempt-preserves-goal: {s.case_id()}")+ if s.goal == "paused" and step(s, ("attempt",)).goal != s.goal:+ raise ValueError(f"paused-attempt-preserves-goal: {s.case_id()}")+ if v in ("refuse_open", "refuse_no_plan"):+ a = step(s, ("attempt",))+ if not a.armed or a.goal != s.goal:+ raise ValueError(f"refuse-arms: {s.case_id()}")+ a = step(s, ("attempt",))+ if a.checklist != s.checklist or a.dirty != s.dirty:+ raise ValueError(f"attempt-keeps-list: {s.case_id()}")+ if n != 360:+ raise ValueError(f"goal-cube: n={n} want=360")+ idle = State()+ if run(idle, [("setGoal", False), ("attempt",)]).armed is not True:+ raise ValueError("trace: first attempt on empty must arm")+ if run(idle, [("setGoal", False), ("attempt",), ("attempt",)]).goal != "complete":+ raise ValueError("trace: double-check retires a task goal")+ if run(idle, [("setGoal", True), ("attempt",), ("attempt",)]).goal != "active":+ raise ValueError("trace: standing has no retire edge")+ if run(idle, [("setGoal", False), ("write", "all_completed"), ("attempt",)]).goal != "complete":+ raise ValueError("trace: done write then attempt retires")+ if checklist_finished(run(idle, [("setGoal", False), ("write", "open"), ("attempt",)])):+ raise ValueError("trace: open write never finishes")+ check_diagram()+ return ndiff --git a/spec/ref/prompt_cache.py b/spec/ref/prompt_cache.pynew file mode 100644index 00000000..e0724994--- /dev/null+++ b/spec/ref/prompt_cache.py@@ -0,0 +1,269 @@+"""Executable port of lean-proofs/Graff/PromptCache.lean."""++from __future__ import annotations++from dataclasses import dataclass+from itertools import product+from pathlib import Path+from typing import Literal++Seat = Literal["root", "sub"]+Label = Literal["main", "other"]+Isolation = Literal["shared_cwd", "worktree"]+Wire = Literal["openai", "responses", "anthropic"]+Partition = Literal["root", "child"]+# ("turn",) | ("spawn", bg: bool, iso) | ("join",)+Event = tuple++SEATS: tuple[Seat, ...] = ("root", "sub")+LABELS: tuple[Label, ...] = ("main", "other")+ISOS: tuple[Isolation, ...] = ("shared_cwd", "worktree")+WIRES: tuple[Wire, ...] = ("openai", "responses", "anthropic")+EVENTS: tuple[Event, ...] = (+ ("turn",),+ ("spawn", False, "shared_cwd"),+ ("spawn", True, "shared_cwd"),+ ("spawn", False, "worktree"),+ ("spawn", True, "worktree"),+ ("join",),+)+KERNEL_MD = Path(__file__).resolve().parents[1] / "kernels" / "prompt_cache.md"+CUBE = 48+++@dataclass(frozen=True)+class Cell:+ wire: Wire = "openai"+ label: Label = "main"+ isolation: Isolation = "shared_cwd"+ grok: bool = False+ seat: Seat = "root"++ def case_id(self) -> str:+ return (+ f"{self.wire}.{self.label}.{self.isolation}"+ f".g{int(self.grok)}.{self.seat}"+ )+++@dataclass(frozen=True)+class State:+ seat: Seat = "root"+ label: Label = "main"+ isolation: Isolation = "shared_cwd"+ partition: Partition = "root"+++def emit_key(wire: Wire) -> bool:+ return wire != "anthropic"+++def partition_of(label: Label, isolation: Isolation) -> Partition:+ _ = isolation+ return "root" if label == "main" else "child"+++def spawn_ok(seat: Seat) -> bool:+ return seat == "root"+++def header_agrees(c: Cell) -> bool:+ if not c.grok or not emit_key(c.wire):+ return True+ return partition_of(c.label, c.isolation) == partition_of(c.label, c.isolation)+++def all_cells() -> list[Cell]:+ return [+ Cell(wire, label, isolation, grok, seat)+ for wire, label, isolation, grok, seat in product(+ WIRES, LABELS, ISOS, (False, True), SEATS+ )+ ]+++def child_of(iso: Isolation) -> State:+ return State(seat="sub", label="other", isolation=iso, partition="child")+++def root_of(iso: Isolation) -> State:+ return State(seat="root", label="main", isolation=iso, partition="root")+++def step(s: State, e: Event) -> State:+ k = e[0]+ if k == "turn":+ return s+ if k == "spawn":+ iso = e[2]+ return s if s.seat == "sub" else child_of(iso)+ if k == "join":+ return s if s.seat == "root" else root_of(s.isolation)+ 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 project(s: State) -> str:+ return "Root" if s.seat == "root" else "Child"+++def event_label(e: Event) -> str:+ k = e[0]+ if k == "spawn":+ return "spawn"+ 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 or e[0] == "turn":+ continue+ found.add((a, event_label(e), b))+ return sorted(found)+++def mermaid() -> str:+ lines = ["stateDiagram-v2", " [*] --> Root"]+ 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 cache / spawn\n"+ "\n"+ "Source of truth: `lean-proofs/Graff/PromptCache.lean`.\n"+ "\n"+ "Process kernel, not a cube-only table and not a Turing machine: finite\n"+ "`Event` / `step`, no tape. Seat is who may spawn. Label is the cache\n"+ "predicate (`main` is the only sticky root partition). Isolation does\n"+ "not mint a key. Sub never spawns. Join restores the root partition.\n"+ "\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"+ "\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": {+ "wire": c.wire,+ "label": c.label,+ "isolation": c.isolation,+ "grok": c.grok,+ "seat": c.seat,+ },+ "emit_key": emit_key(c.wire),+ "partition": partition_of(c.label, c.isolation),+ "spawn_ok": spawn_ok(c.seat),+ "header_agrees": header_agrees(c),+ }+ )+ return {"kernel": "prompt_cache", "version": 1, "cases": cases}+++def check_diagram() -> None:+ raw = walk()+ saw_spawn = saw_join = False+ for s, e, t in raw:+ if e[0] == "spawn":+ if s.seat == "sub":+ raise ValueError(f"diagram: sub spawned {s}")+ if t.partition != "child" or t.seat != "sub":+ raise ValueError(f"diagram: spawn did not isolate {s}")+ saw_spawn = True+ if e[0] == "join":+ if t.partition != "root" or t.seat != "root" or t.label != "main":+ raise ValueError(f"diagram: join did not restore root {s}")+ saw_join = True+ if not saw_spawn or not saw_join:+ raise ValueError("diagram: missing spawn or join on live step")+ text = mermaid()+ if "Root --> Child: spawn" not in text:+ raise ValueError("diagram: mermaid missing Root spawn→Child")+ if "Child --> Root: join" not in text:+ raise ValueError("diagram: mermaid missing Child join→Root")+ if "Child --> Child: spawn" in text:+ raise ValueError("diagram: mermaid has Child spawn edge")+++def check_properties() -> int:+ n = 0+ for c in all_cells():+ n += 1+ if c.wire == "anthropic" and emit_key(c.wire):+ raise ValueError(f"anthropic-never-key: {c.case_id()}")+ if c.wire != "anthropic" and not emit_key(c.wire):+ raise ValueError(f"non-anthropic-emits-key: {c.case_id()}")+ if c.label == "main" and partition_of(c.label, c.isolation) != "root":+ raise ValueError(f"main-is-root: {c.case_id()}")+ if c.label == "other" and partition_of(c.label, c.isolation) != "child":+ raise ValueError(f"other-is-child: {c.case_id()}")+ if partition_of(c.label, "shared_cwd") != partition_of(c.label, "worktree"):+ raise ValueError(f"isolation-mints-key: {c.case_id()}")+ if c.seat == "sub" and spawn_ok(c.seat):+ raise ValueError(f"sub-never-spawn-ok: {c.case_id()}")+ if c.seat == "root" and not spawn_ok(c.seat):+ raise ValueError(f"root-spawn-ok: {c.case_id()}")+ if not header_agrees(c):+ raise ValueError(f"header-agrees: {c.case_id()}")+ if n != CUBE:+ raise ValueError(f"cache-cube: n={n} want={CUBE}")+ idle = State()+ child = step(idle, ("spawn", False, "worktree"))+ if child.partition != "child" or child.seat != "sub":+ raise ValueError("trace: spawn did not isolate")+ if step(child, ("spawn", True, "shared_cwd")) != child:+ raise ValueError("trace: sub spawned")+ back = step(child, ("join",))+ if back.partition != "root" or back.label != "main":+ raise ValueError("trace: join did not restore root")+ if step(idle, ("spawn", False, "shared_cwd")).partition != step(+ idle, ("spawn", True, "worktree")+ ).partition:+ raise ValueError("trace: spawn mode/iso minted a key")+ if run(idle, [("spawn", False, "shared_cwd"), ("join",)]).partition != "root":+ raise ValueError("trace: spawn+join lost the root key")+ check_diagram()+ return ndiff --git a/src/spec_prompt_cache_kernel_conformance.zig b/src/spec_prompt_cache_kernel_conformance.zignew file mode 100644index 00000000..a85aed65--- /dev/null+++ b/src/spec_prompt_cache_kernel_conformance.zig@@ -0,0 +1,76 @@+//! Impl half of the PromptCache kernel: every cell in+//! spec/kernels/prompt_cache.json must match promptCacheKey's partition+//! and the one-level spawn gate.++const std = @import("std");+const http_headers = @import("http_headers.zig");+const spawn_gate = @import("subagent_spawn.zig");++const fixtures_json = @embedFile("spec_prompt_cache");++fn labelOf(s: []const u8) []const u8 {+ return if (std.mem.eql(u8, s, "main")) "main" else "sub";+}++fn partitionOf(io: std.Io, label: []const u8, agent: *const anyopaque) []const u8 {+ var buf: [96]u8 = undefined;+ const key = http_headers.promptCacheKey(io, label, agent, &buf);+ const root = http_headers.projectRootId(io);+ if (std.mem.eql(u8, key, root)) return "root";+ return "child";+}++test "spec/prompt_cache: partition and spawn_ok match the export" {+ 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, 48), cases.len);++ const io = std.testing.io;+ var root_slot: usize = 1;+ var child_slot: usize = 2;+ const root_agent: *const anyopaque = @ptrCast(&root_slot);+ const child_agent: *const anyopaque = @ptrCast(&child_slot);++ for (cases) |case_v| {+ const case = case_v.object;+ const id = case.get("id").?.string;+ const cell = case.get("cell").?.object;+ const label = labelOf(cell.get("label").?.string);+ const seat = cell.get("seat").?.string;+ const want_part = case.get("partition").?.string;+ const want_spawn = case.get("spawn_ok").?.bool;+ const agent: *const anyopaque = if (std.mem.eql(u8, label, "main")) root_agent else child_agent;+ const got_part = partitionOf(io, label, agent);+ if (!std.mem.eql(u8, want_part, got_part)) {+ std.debug.print("\ncounterexample {s}: partition want={s} got={s}\n", .{ id, want_part, got_part });+ return error.CatalogMismatch;+ }+ const got_spawn = spawn_gate.allowed(std.mem.eql(u8, seat, "sub"));+ if (want_spawn != got_spawn) {+ std.debug.print("\ncounterexample {s}: spawn_ok want={} got={}\n", .{ id, want_spawn, got_spawn });+ return error.CatalogMismatch;+ }+ }+}++test "spec/prompt_cache: isolation is not a promptCacheKey argument" {+ // The live function is (io, label, agent, buf). Isolation cannot mint a+ // key because it is not an input. Same label ⇒ same partition kind.+ const io = std.testing.io;+ var slot: usize = 7;+ const agent: *const anyopaque = @ptrCast(&slot);+ var a: [96]u8 = undefined;+ var b: [96]u8 = undefined;+ const main_a = http_headers.promptCacheKey(io, "main", agent, &a);+ const main_b = http_headers.promptCacheKey(io, "main", agent, &b);+ try std.testing.expectEqualStrings(main_a, main_b);+ try std.testing.expectEqualStrings(main_a, http_headers.projectRootId(io));+ var c: [96]u8 = undefined;+ var d: [96]u8 = undefined;+ const sub_a = http_headers.promptCacheKey(io, "sub", agent, &c);+ const sub_b = http_headers.promptCacheKey(io, "sub", agent, &d);+ try std.testing.expectEqualStrings(sub_a, sub_b);+ try std.testing.expect(!std.mem.eql(u8, main_a, sub_a));+}diff --git a/src/subagent.zig b/src/subagent.zigindex b2626fc2..52bc5f56 100644--- a/src/subagent.zig+++ b/src/subagent.zig@@ -48,8 +48,10 @@ const orch_rows = @import("orchestration_rows.zig"); // #290: a scored tournamen/// calls fan out further via io.async. `run_in_background:true` (#276 P0-3)/// instead registers the spawn and returns immediately — see/// spawnSubBackground below.+const spawn_gate = @import("subagent_spawn.zig");+pub fn execSubagent(ctx: ToolCtx, input: Value) !ToolOutput {- if (ctx.from_sub) return .{+ if (!spawn_gate.allowed(ctx.from_sub)) return .{.text = try ctx.gpa.dupe(u8, "subagents cannot spawn subagents — do this work yourself"),.is_error = true,};diff --git a/src/subagent_spawn.zig b/src/subagent_spawn.zignew file mode 100644index 00000000..9d93c25b--- /dev/null+++ b/src/subagent_spawn.zig@@ -0,0 +1,11 @@+//! One-level spawn gate. Children cannot spawn children.+const std = @import("std");++pub fn allowed(from_sub: bool) bool {+ return !from_sub;+}++test "spec/prompt_cache: sub never spawns" {+ try std.testing.expect(allowed(false));+ try std.testing.expect(!allowed(true));+}diff --git a/src/tool_gates.zig b/src/tool_gates.zigindex 34f988cc..ce97afd0 100644--- a/src/tool_gates.zig+++ b/src/tool_gates.zig@@ -104,6 +104,7 @@ test { // the served catalogs' wire-compatibility guard (an unreferenced module'_ = @import("spec_structured_output_conformance.zig");_ = @import("grok_spec_conformance.zig");_ = @import("spec_prompt_cache_conformance.zig");+ _ = @import("spec_prompt_cache_kernel_conformance.zig");}test "#352: an optional tool is advertised only while its flag is set; other names are unaffected" {