graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(spec): model behavior kernels as state machines
Rach Pradhane5a5de6836b6
diff --git a/lean-proofs/Graff/PathConfine.lean b/lean-proofs/Graff/PathConfine.leanindex ed599413..a3a3fec4 100644--- a/lean-proofs/Graff/PathConfine.lean+++ b/lean-proofs/Graff/PathConfine.lean@@ -1,10 +1,17 @@/-Path / lease kernel.- File tools are confined lexically (`confinedPath`) and then refuse any+ Process kernel, not a Turing machine: finite `Event` / `step`, no tape.+ File tools walk path components (`confinedPath`) and then refuse anysymlink prefix (`noSymlinkEscape`). `--yolo` does not lift either rule.The worktree lease is a separate finite verdict (`ownerVerdict`).+ The 16 lexical paths + 80 lease cells are the snapshot. `Event` / `step`+ is the walk: Empty / Safe / Escaped / Absolute. Escaped and Absolute+ absorb — a subagent does not recover a jail break by taking another+ component. Fleet topology is not a Shape cell; this is the machine+ every child file-tool is forced through.+Not modelled: OS errno, Windows drive letters, live `/proc` reads.Executable port: spec/ref/path_confine.py.-/@@ -124,4 +131,73 @@ theorem yolo_does_not_free_sub (yolo : Bool) :theorem empty_not_confined : confined "" = false := rfl+/-! The machine. Snapshot predicates above; these are the edges. -/++inductive Walk where+ | empty | safe | escaped | absolute+deriving DecidableEq, Repr, BEq++structure WalkState where+ walk : Walk := .empty+deriving Repr, BEq, DecidableEq++inductive Event where+ | startAbs+ | component (c : String)+deriving DecidableEq, Repr, BEq++def step (s : WalkState) (e : Event) : WalkState :=+ match e with+ | Event.startAbs =>+ if decide (s.walk = Walk.empty) then { walk := Walk.absolute } else s+ | Event.component c =>+ if decide (s.walk = Walk.absolute) then s+ else if decide (s.walk = Walk.escaped) then s+ else if c == ".." then { walk := Walk.escaped }+ else { walk := Walk.safe }++def run (s : WalkState) : List Event → WalkState+ | [] => s+ | e :: es => run (step s e) es++def confinedWalk (s : WalkState) : Bool := decide (s.walk = Walk.safe)++def eventsOf (p : String) : List Event :=+ let cs := (components p).map Event.component+ if p.startsWith "/" then Event.startAbs :: cs else cs++def walkPath (p : String) : WalkState := run {} (eventsOf p)++def samplePaths : List String :=+ ["", "src/main.zig", "a/b/c", "/etc/passwd", "../outside", "a/../../b",+ "a/./b", ".", "foo/..", "..", "..hidden", ".graff/settings.json",+ "a//b", "//etc/passwd", "foo\\..\\bar", "foo/bar/baz"]++def agrees (p : String) : Bool := confined p == confinedWalk (walkPath p)++theorem start_abs_from_empty :+ (step {} Event.startAbs).walk = Walk.absolute := rfl++theorem start_abs_not_from_safe (s : WalkState) (h : s.walk = Walk.safe) :+ step s Event.startAbs = s := by+ simp [step, h]++theorem start_abs_not_from_escaped (s : WalkState) (h : s.walk = Walk.escaped) :+ step s Event.startAbs = s := by+ simp [step, h]++theorem abs_absorbs (s : WalkState) (c : String) (h : s.walk = Walk.absolute) :+ step s (Event.component c) = s := by+ simp [step, h]++theorem escaped_absorbs (s : WalkState) (c : String) (h : s.walk = Walk.escaped) :+ step s (Event.component c) = s := by+ simp [step, h]++theorem empty_walk_not_confined : confinedWalk {} = false := by native_decide++theorem safe_is_confined : confinedWalk { walk := Walk.safe } = true := by native_decide++theorem walk_matches_snapshot : (samplePaths.all agrees) = true := by native_decide+end Graff.PathConfinediff --git a/lean-proofs/Graff/Score.lean b/lean-proofs/Graff/Score.leanindex e8e03ca1..79a93f2f 100644--- a/lean-proofs/Graff/Score.lean+++ b/lean-proofs/Graff/Score.lean@@ -1,12 +1,16 @@/-Score maintenance: when a fitness row is filed, and in which cell.- This kernel is the discrete gate in front of the archive, not HMAC and- not the file tokenizer. A score is *maintained* (filed, comparable) iff- the fleet is on, the stage/phase resolves to a canonical slot, and the- run carries a signal. Off-vocabulary titles stay uncelled — they still- run, they do not accrue. An all-fail or unreached stage files nothing- (a 0 would poison the cell mean).+ Process kernel, not a Turing machine: finite `Event` / `step`, no tape.+ The 1210-cell cube (240 filed) is the snapshot. The honest unit is the+ STAGE, never the item: N children do not mint N rows. `attempt` never+ files; `capture` (the post-join gate) files at most once, and only when+ fleet is on, the slot is canonical, and `stageScore` is some. Unreached,+ all-fail, and overflow stay silent — a 0 would poison the cell mean.++ Fleet topology is not a Shape cell. PromptCache isolates the child key;+ PathConfine walks the jail; Transport forbids WS; this kernel is how+ that unbounded fleet is scored.`stageScore` is the same function the harness uses (millipoints). TheSignal cube is just the five counts that function classifies. First-word@@ -409,4 +413,67 @@ example : classOf .minimax = Tier.frontier := by native_decideexample : titleSlot .findBugs = Slot.find := by native_decideexample : titleSlot .sweepPadded = Slot.sweep := by native_decide+/-! The machine. Snapshot predicates above; these are the edges. -/++structure State where+ fleet : Bool := false+ slot : Slot := Slot.none+ attempted : Nat := 0+ ok : Nat := 0+ filed : Bool := false+deriving Repr, BEq, DecidableEq++inductive Event where+ | fleetOn+ | fleetOff+ | setSlot (s : Slot)+ | attempt (ok : Bool)+ | capture+deriving DecidableEq, Repr, BEq++def filesNow (s : State) : Bool :=+ s.fleet && decide (s.slot ≠ Slot.none) && (stageScore s.attempted s.ok).isSome++def step (s : State) (e : Event) : State :=+ match e with+ | Event.fleetOn => { fleet := true, slot := s.slot, attempted := s.attempted, ok := s.ok, filed := s.filed }+ | Event.fleetOff => { fleet := false, slot := s.slot, attempted := s.attempted, ok := s.ok, filed := s.filed }+ | Event.setSlot sl => { fleet := s.fleet, slot := sl, attempted := s.attempted, ok := s.ok, filed := s.filed }+ | Event.attempt good =>+ { fleet := s.fleet, slot := s.slot, attempted := s.attempted + 1,+ ok := if good then s.ok + 1 else s.ok, filed := s.filed }+ | Event.capture =>+ { fleet := s.fleet, slot := s.slot, attempted := s.attempted, ok := s.ok, filed := filesNow s }++def run (s : State) : List Event → State+ | [] => s+ | e :: es => run (step s e) es++theorem attempt_never_files (s : State) (good : Bool) :+ (step s (Event.attempt good)).filed = s.filed := rfl++theorem fleet_off_capture_silent (s : State) (h : s.fleet = false) :+ (step s Event.capture).filed = false := by+ simp [step, filesNow, h]++theorem unreached_capture_silent (s : State) (h : s.attempted = 0) :+ (step s Event.capture).filed = false := by+ simp [step, filesNow, h, stageScore]++theorem all_fail_capture_silent (s : State) (h : s.ok = 0) :+ (step s Event.capture).filed = false := by+ simp [step, filesNow, h, stageScore]++theorem uncelled_capture_silent (s : State) (h : s.slot = Slot.none) :+ (step s Event.capture).filed = false := by+ simp [step, filesNow, h]++theorem items_do_not_file :+ (run {} [Event.fleetOn, Event.setSlot Slot.transform, Event.attempt true, Event.attempt true]).filed = false := by+ native_decide++theorem clean_capture_files :+ (run {} [Event.fleetOn, Event.setSlot Slot.transform, Event.attempt true, Event.attempt true, Event.capture]).filed = true := by+ native_decide+end Graff.Scorediff --git a/lean-proofs/Graff/TerminalModes.lean b/lean-proofs/Graff/TerminalModes.leanindex 48a1c65a..b06b1170 100644--- a/lean-proofs/Graff/TerminalModes.lean+++ b/lean-proofs/Graff/TerminalModes.lean@@ -13,6 +13,11 @@seq) as op lists: their composition is balanced, and restore leaves thealt-screen last.+ Process kernel, not a Turing machine: `Op` is the event, `step` is the+ transition (mode map + kitty depth). The 14 named sequences are the+ snapshot. Enable then restore returns to defaults; restore leaves the+ alt-screen last; kitty pop floors at zero.+Executable port: spec/ref/terminal_modes.py (also the semantics behindscripts/tui-pty-guard.py). Impl anchor: TUI/spec_terminal_modes_conformance.zigparses the real constants and diffs them against the fixture.@@ -24,6 +29,9 @@ inductive Op| set (n : Nat) | reset (n : Nat) | push | popderiving DecidableEq, Repr+/-- Events are the DEC/kitty ops. -/+abbrev Event := Op+def defaultOn : List Nat := [7, 25]/-- Last-op-wins mode map plus the kitty push/pop depth (floored at 0). -/@@ -91,4 +99,10 @@ theorem restore_idempotent :theorem generated_restore_balances :balanced (graffEnable ++ restoreOps graffEnable) = true := by decide+/-- Pop on an untouched terminal stays at depth 0 (Nat floors). -/+theorem pop_from_zero : (step ([], 0) .pop).2 = 0 := by decide++/-- Enable alone is not balanced — restore is what returns to defaults. -/+theorem enable_unbalanced : balanced graffEnable = false := by decide+end Graff.TerminalModesdiff --git a/lean-proofs/Graff/Transport.lean b/lean-proofs/Graff/Transport.leanindex 96a728f0..345be83f 100644--- a/lean-proofs/Graff/Transport.lean+++ b/lean-proofs/Graff/Transport.lean@@ -1,10 +1,17 @@/-Transport kernel.+ Process kernel, not a Turing machine: finite `Event` / `step`, no tape.Vendors are not axes. The program switches on `Kind` (3 wire formats)and a handful of turn flags. WebSocket is legal on exactly one shape:a live root Responses turn that has not fallen back and is not quiet.+ The 96-cell cube is the snapshot. `Event` / `step` is the machine:+ a sub never takes WS; joining a non-responses turn does not grant it.+ PromptCache isolates the child's cache key; this kernel is the pipe+ that child is forbidden from opening. Fleet topology is not a Shape+ cell — Shape stays a cube of one observation.+Matches `transport_gate.eligible` / `agent_ws.wsEligible`.Executable port: spec/ref/transport.py.-/@@ -116,4 +123,73 @@ example : eligible { kind := .anthropic, codexWs := true, hasOut := true } = falexample : idleExpired 100 0 100 = false := by native_decideexample : idleExpired 101 0 100 = true := by native_decide+/-! The machine. Snapshot predicates above; these are the edges. -/++inductive Event where+ | setKind (k : Kind)+ | markSub+ | joinRoot+ | setCodexWs (b : Bool)+ | setWsOff (b : Bool)+ | setHasOut (b : Bool)+ | setQuiet (b : Bool)+deriving DecidableEq, Repr, BEq++def withKind (t : Turn) (k : Kind) : Turn :=+ { kind := k, isSub := t.isSub, codexWs := t.codexWs, wsOff := t.wsOff, hasOut := t.hasOut, quiet := t.quiet }++def withSub (t : Turn) (sub : Bool) : Turn :=+ { kind := t.kind, isSub := sub, codexWs := t.codexWs, wsOff := t.wsOff, hasOut := t.hasOut, quiet := t.quiet }++def withCodexWs (t : Turn) (b : Bool) : Turn :=+ { kind := t.kind, isSub := t.isSub, codexWs := b, wsOff := t.wsOff, hasOut := t.hasOut, quiet := t.quiet }++def withWsOff (t : Turn) (b : Bool) : Turn :=+ { kind := t.kind, isSub := t.isSub, codexWs := t.codexWs, wsOff := b, hasOut := t.hasOut, quiet := t.quiet }++def withHasOut (t : Turn) (b : Bool) : Turn :=+ { kind := t.kind, isSub := t.isSub, codexWs := t.codexWs, wsOff := t.wsOff, hasOut := b, quiet := t.quiet }++def withQuiet (t : Turn) (b : Bool) : Turn :=+ { kind := t.kind, isSub := t.isSub, codexWs := t.codexWs, wsOff := t.wsOff, hasOut := t.hasOut, quiet := b }++def step (t : Turn) (e : Event) : Turn :=+ match e with+ | Event.setKind k => withKind t k+ | Event.markSub => withSub t true+ | Event.joinRoot => withSub t false+ | Event.setCodexWs b => withCodexWs t b+ | Event.setWsOff b => withWsOff t b+ | Event.setHasOut b => withHasOut t b+ | Event.setQuiet b => withQuiet t b++def run (t : Turn) : List Event → Turn+ | [] => t+ | e :: es => run (step t e) es++theorem mark_sub_never_ws (t : Turn) :+ eligible (step t Event.markSub) = false := by+ cases t.kind <;> simp [step, withSub, eligible]++theorem set_anthropic_never_ws (t : Turn) :+ eligible (step t (Event.setKind Kind.anthropic)) = false := by+ simp [step, withKind, eligible]++theorem set_openai_never_ws (t : Turn) :+ eligible (step t (Event.setKind Kind.openai)) = false := by+ simp [step, withKind, eligible]++theorem not_responses_never_ws (t : Turn) (h : t.kind ≠ Kind.responses) :+ eligible t = false := by+ unfold eligible+ simp [h]++theorem join_non_responses_never_ws (t : Turn) (h : t.kind ≠ Kind.responses) :+ eligible (step t Event.joinRoot) = false :=+ not_responses_never_ws (step t Event.joinRoot) (by simpa [step, withSub] using h)++theorem quiet_step_never_ws (t : Turn) :+ eligible (step t (Event.setQuiet true)) = false := by+ cases t.kind <;> simp [step, withQuiet, eligible]+end Graff.Transportdiff --git a/lean-proofs/KERNELS.md b/lean-proofs/KERNELS.mdindex 9d67100e..af338162 100644--- a/lean-proofs/KERNELS.md+++ b/lean-proofs/KERNELS.md@@ -11,10 +11,26 @@ 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, isthe 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.+Process kernels: `GoalLoop` (standing has no retire edge; harness-done+needs a done write), `PromptCache` (sub never spawns; join restores the+root partition), `TerminalModes` (`Op`/`step` mode map + kitty depth;+enable++restore returns to Idle; pop floors; alt-screen leave is last),+`PathConfine` (component walk: Escaped and Absolute absorb), and+`Transport` (a sub never takes WS; only one live root Responses cell+does), and `Score` (`attempt` never files; `capture` after the join+files one stage row). They are not Turing machines: no tape, no halt+state.++The shape of a subagent fleet is not a cube. `Shape` is the observation+ladder of one turn and stays a cube. How many children spawn, which+isolation they take, which paths they walk, and whether they get a+WebSocket are events — PromptCache, PathConfine, and Transport force+every child through a machine. Score is how that unbounded fleet is+filed: N items fold into one stage row; a 0 does not poison the cell.++Shape, Provider, and ToolCatalog stay cubes. Leftover this turn:+BashPolicy (command cube: `isSimple` / `escapesCwd` / `readOnlyAllowed`).+TUI layout/glyphs, prompts, and SSE stay never.## Every harness part@@ -27,13 +43,14 @@ not a skip: TUI, prompts, and SSE bytes stay out of Lean on purpose.| Kernel | Cells | What it is *not* ||---|---|---|| `ToolCatalog` | 64 flag cubes | MCP names, descriptions, JSON wrappers |-| `Transport` | 96 turns; **1** WS cell | frames, TLS, idle-kill timing of the server |+| `Transport` | 96 turns + `Event`/`step`; **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 + `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 |+| `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` |-| `Score` | 1210 filing cells (240 filed); 11 titles; 16 class samples | HMAC, providerClass price fallback |+| `Score` | 1210 filing cells (240 filed) + `Event`/`step`; 11 titles; 16 class samples | HMAC, providerClass price fallback |### New (this loop)diff --git a/spec/README.md b/spec/README.mdindex 8daba05d..d54c42c8 100644--- a/spec/README.md+++ b/spec/README.md@@ -42,13 +42,14 @@ properties are load-bearing, and a missed combination is a real bug.| Kernel | Status | Why ||---|---|---|| `tool_catalog` | live | 64 catalog cubes. `#330` / `#352` / `--lean`. |-| `transport` | live | 96 turns, **1** WebSocket cell. `Kind × seat × flags`. |+| `transport` | live | Process kernel. 96 turns, **1** WebSocket cell. Sub never WS. || `provider` | live | 18 baked rows over 3 wire kinds. || `goal_loop` | live | Process kernel (`Event`/`step`, not a TM). 360 snapshot cells. Standing does not retire. || `prompt_cache` | live | Process kernel. 48 cells. Sub never spawns. Child key isolated. Join restores root. |-| `path_confine` | live | Lexical cwd jail, symlink prefixes, 80 lease verdicts. |+| `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. |-| `score` | live | 1210 filing cells, 240 filed. First-word titles, needle class, `[0,1]` scale. |+| `score` | live | Process kernel. 1210 cells, 240 filed. Attempt never files; capture after join does. || `bash_policy` | live | 32 command cells. Simple + in-cwd + seed. External is never auto-allowed. || TUI, prompts, SSE bytes | never | Eval, don't prove. Every other harness part is listed in `lean-proofs/KERNELS.md`. |@@ -59,16 +60,23 @@ python3 spec/conformance.py # properties + fixture self-checkpython3 spec/conformance.py --export # regenerate kernels/*.json and GoalLoop mermaidpython3 spec/conformance.py --diagram goal_loop # live Event/step projectionpython3 spec/conformance.py --diagram prompt_cache+python3 spec/conformance.py --diagram terminal_modes+python3 spec/conformance.py --diagram path_confine+python3 spec/conformance.py --diagram transport+python3 spec/conformance.py --diagram scorepython3 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`.+Process kernels (`GoalLoop`, `PromptCache`, `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 fleet+is not a Shape cell — PromptCache / PathConfine / Transport force every+child through a machine; Score files that unbounded fleet as one stage+row after the join. `--diagram` prints a live `step` projection;+`--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, anddiff --git a/spec/conformance.py b/spec/conformance.pyindex 51927728..d1af5818 100644--- a/spec/conformance.py+++ b/spec/conformance.py@@ -35,16 +35,22 @@ from ref.tool_catalog import (subsequence,)from ref.transport import all_turns, eligible, idle_expired, pipe+from ref.transport import check_diagram as transport_check_diagram+from ref.transport import kernel_md as transport_kernel_md+from ref.transport import write_kernel_md as write_transport_mdfrom ref.provider import SPECS as PROVIDER_SPECSfrom ref.provider import ws_capablefrom ref.path_confine import (PATHS,all_leases,+ check_diagram as path_check_diagram,confined,destructive_git_allowed,file_tool_ok,+ kernel_md as path_kernel_md,owner_verdict,warns,+ write_kernel_md as write_path_md,)from ref.goal_loop import check_properties as goal_check_propertiesfrom ref.goal_loop import payload as goal_payload@@ -54,14 +60,16 @@ from ref.prompt_cache import write_kernel_md as write_cache_mdfrom 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_payload-from ref.score import check_properties as score_check_properties-from ref.score import payload as score_model_payload+from ref.score import check_properties as score_check_properties, payload as score_model_payload+from ref.score import kernel_md as score_kernel_md, write_kernel_md as write_score_mdfrom ref.bash_policy import check_properties as bash_check_propertiesfrom ref.bash_policy import payload as bash_model_payloadfrom ref.structured_output import check_properties as sox_check_propertiesfrom ref.structured_output import payload as sox_model_payloadfrom ref.terminal_modes import check_properties as term_check_propertiesfrom ref.terminal_modes import payload as term_model_payload+from ref.terminal_modes import write_kernel_md as write_term_md+from ref.terminal_modes import kernel_md as term_kernel_mdROOT = Path(__file__).resolve().parentKERNELS = ROOT / "kernels"@@ -202,6 +210,10 @@ def check_transport() -> int:raise Counterexample("idle-eq-keeps", None, "equal to the limit must keep the socket")if not idle_expired(101, 0, 100):raise Counterexample("idle-past-expires", None, "strictly past the limit must expire")+ try:+ transport_check_diagram()+ except ValueError as e:+ raise Counterexample("transport-diagram", None, str(e)) from ereturn n@@ -364,6 +376,10 @@ def check_path_confine() -> int:raise Counterexample("lease-self", l, v)if v == "live_foreign" and not warns(v):raise Counterexample("lease-warns", l, v)+ try:+ path_check_diagram()+ except ValueError as e:+ raise Counterexample("path-diagram", None, str(e)) from ereturn n@@ -403,15 +419,19 @@ def export() -> list[Path]:return [_write(FIXTURE, cases_payload()),_write(TRANSPORT_FIXTURE, transport_payload()),+ write_transport_md(KERNELS / "transport.md"),_write(PROVIDER_FIXTURE, provider_payload()),_write(GOAL_FIXTURE, goal_payload()),write_kernel_md(KERNELS / "goal_loop.md"),_write(PATH_FIXTURE, path_payload()),+ write_path_md(KERNELS / "path_confine.md"),_write(SHAPE_FIXTURE, shape_payload()),_write(SCORE_FIXTURE, score_payload()),+ write_score_md(KERNELS / "score.md"),_write(BASH_FIXTURE, bash_payload()),_write(SOX_FIXTURE, sox_model_payload()),_write(TERM_FIXTURE, term_model_payload()),+ write_term_md(KERNELS / "terminal_modes.md"),_write(CACHE_FIXTURE, cache_payload()),write_cache_md(KERNELS / "prompt_cache.md"),]@@ -437,12 +457,17 @@ def check_fixtures() -> None:_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")+ for name, body in (+ ("goal_loop.md", kernel_md),+ ("prompt_cache.md", cache_kernel_md),+ ("terminal_modes.md", term_kernel_md),+ ("path_confine.md", path_kernel_md),+ ("transport.md", transport_kernel_md),+ ("score.md", score_kernel_md),+ ):+ md = KERNELS / name+ if not md.is_file() or md.read_text() != body():+ raise Counterexample("fixtures-stale", None, f"{name} does not match live step; run --export")def break_model(kind: str) -> None:@@ -515,7 +540,14 @@ def main() -> int:return 0 if inv["ok"] else 1if args.diagram:- mods = {"goal_loop": "ref.goal_loop", "prompt_cache": "ref.prompt_cache"}+ mods = {+ "goal_loop": "ref.goal_loop",+ "prompt_cache": "ref.prompt_cache",+ "terminal_modes": "ref.terminal_modes",+ "path_confine": "ref.path_confine",+ "transport": "ref.transport",+ "score": "ref.score",+ }path = mods.get(args.diagram)if path is None:print(f"no machine projection for {args.diagram}", file=sys.stderr)diff --git a/spec/kernels/path_confine.md b/spec/kernels/path_confine.mdindex d78d793c..83f37645 100644--- a/spec/kernels/path_confine.md+++ b/spec/kernels/path_confine.md@@ -1,8 +1,22 @@-# Kernel: path confine+# Kernel: path confine / leaseSource of truth: `lean-proofs/Graff/PathConfine.lean`.-File tools: no empty path, no absolute path, no `..` component. A confined-path still fails if any `/`-prefix is a symlink. `--yolo` does not lift-this. The worktree lease is `ownerVerdict`: only a live foreign (or-unverified) process in *this* worktree warns.+Process kernel, not a Turing machine: finite `Event` / `step`, no tape.+A file-tool path is a walk over components. Empty / Safe / Escaped /+Absolute. Escaped and Absolute absorb — a subagent does not recover a+jail break by taking another component. The 16 lexical paths + 80 lease+cells are the snapshot. `--yolo` does not free a sub. Fleet topology is+not a Shape cell; Shape stays the observation ladder of one turn.++The diagram is the projection of the live Python `step`. Emit it with+`python3 spec/conformance.py --diagram path_confine`.++```mermaid+stateDiagram-v2+ [*] --> Empty+ Empty --> Safe: component+ Empty --> Escaped: component ..+ Empty --> Absolute: startAbs+ Safe --> Escaped: component ..+```diff --git a/spec/kernels/score.md b/spec/kernels/score.mdindex 5fa51d47..83adef94 100644--- a/spec/kernels/score.md+++ b/spec/kernels/score.md@@ -2,26 +2,39 @@Source of truth: `lean-proofs/Graff/Score.lean`.-A fitness row is *maintained* (filed, comparable) iff:+Process kernel, not a Turing machine: finite `Event` / `step`, no tape.+The honest unit is the STAGE, never the item. N children do not mint N+rows. `attempt` never files; `capture` (the post-join gate) files only+when fleet is on, the slot is canonical, and `stageScore` is some.+Unreached / all-fail / overflow stay silent — a 0 would poison the mean.+The 1210-cell cube (240 filed) is the snapshot. Shape stays the+observation ladder of one turn.-1. the fleet is on-2. `roleOf(label, niche)` is a canonical slot (label first, niche fallback)-3. the stage carries a signal (`stageScore` is not null)+The diagram is the projection of the live Python `step`. Emit it with+`python3 spec/conformance.py --diagram score`.-Unreached, all-fail, and `ok > attempted` file nothing — a 0 would poison-the cell mean. Off-vocabulary titles still run; they do not accrue.-`stageScore` is the function; the Signal cube is just the five counts it-classifies. Filed rows of the 1210-cell cube stay at 240.--Titles match on the **first word** only. A substring rule would make-`review the findings` collide with `find`. A leading non-ASCII byte-aborts the scan (otherwise a later English word would steal the cell).--Outbound scores are the `[0,1]` contract: values in `[0,1]` pass, `(1,100]`-are percentages, anything else is rejected.--The MAP-Elites cell is niche + tier + slot. Changing any axis is a-different cell (v2). Uncelled rows are not comparable. Tier comes from-the `providerClass` needle table (specific markers before families).-HMAC and the price fallback are out of this kernel — unmatched models-stay `unknown` and are not a maintained cell here.+```mermaid+stateDiagram-v2+ [*] --> Off+ Armed --> Dry: attempt fail+ Armed --> Live: attempt ok+ Armed --> Off: fleetOff+ Armed --> Uncelled: setSlot none+ Dry --> Live: attempt ok+ Dry --> Off: fleetOff+ Dry --> Uncelled: setSlot none+ Filed --> Uncelled: capture+ Filed --> Off: fleetOff+ Live --> Filed: capture+ Live --> Off: fleetOff+ Live --> Uncelled: setSlot none+ Off --> Armed: fleetOn+ Off --> Dry: fleetOn+ Off --> Filed: fleetOn+ Off --> Live: fleetOn+ Off --> Uncelled: fleetOn+ Uncelled --> Off: fleetOff+ Uncelled --> Armed: setSlot+ Uncelled --> Dry: setSlot+ Uncelled --> Live: setSlot+```diff --git a/spec/kernels/terminal_modes.md b/spec/kernels/terminal_modes.mdnew file mode 100644index 00000000..51fd664c--- /dev/null+++ b/spec/kernels/terminal_modes.md@@ -0,0 +1,24 @@+# Kernel: terminal modes++Source of truth: `lean-proofs/Graff/TerminalModes.lean`.++Process kernel, not a Turing machine: `Op` / `step` is the mode map+plus kitty depth. The 14 named sequences are the snapshot. Enable then+restore returns to Idle; restore leaves the alt-screen last; pop floors+at zero. TUI layout, glyphs, and the font stay never.++The diagram is the projection of the live Python `step`. Emit it with+`python3 spec/conformance.py --diagram terminal_modes`.++```mermaid+stateDiagram-v2+ [*] --> Idle+ Active --> Alt: pop+ Alt --> Active: push+ Alt --> Idle: reset 1049+ Deviant --> Idle: reset 2004+ Idle --> Kitty: push+ Idle --> Alt: set 1049+ Idle --> Deviant: set 2004+ Kitty --> Idle: pop+```diff --git a/spec/kernels/transport.md b/spec/kernels/transport.mdindex f946c39c..fc7124fb 100644--- a/spec/kernels/transport.md+++ b/spec/kernels/transport.md@@ -1,5 +1,37 @@# Kernel: transportSource of truth: `lean-proofs/Graff/Transport.lean`.-Vendors are not an axis. WebSocket is legal iff `Kind = responses`, root,-`g_codex_ws`, not fallen back, live `out`, not quiet. That is one cell of 96.++Process kernel, not a Turing machine: finite `Event` / `step`, no tape.+The 96-cell cube is the snapshot. A sub never takes WS; only one cell is+WS (a live root Responses turn). PromptCache isolates the child key; this+kernel is the pipe that child is forbidden from opening. Shape stays a+cube of one observation — fleet topology is not a Shape cell.++The diagram is the projection of the live Python `step`. Emit it with+`python3 spec/conformance.py --diagram transport`.++```mermaid+stateDiagram-v2+ [*] --> Sse+ Blocked --> Sub: markSub+ Blocked --> Ws: setCodexWs 1+ Blocked --> Ws: setHasOut 1+ Blocked --> Sse: setKind anthropic+ Blocked --> Sse: setKind openai+ Blocked --> Ws: setQuiet 0+ Blocked --> Ws: setWsOff 0+ Sse --> Sub: markSub+ Sse --> Blocked: setKind responses+ Sse --> Ws: setKind responses+ Sub --> Blocked: joinRoot+ Sub --> Sse: joinRoot+ Sub --> Ws: joinRoot+ Ws --> Sub: markSub+ Ws --> Blocked: setCodexWs 0+ Ws --> Blocked: setHasOut 0+ Ws --> Sse: setKind anthropic+ Ws --> Sse: setKind openai+ Ws --> Blocked: setQuiet 1+ Ws --> Blocked: setWsOff 1+```diff --git a/spec/manifest.json b/spec/manifest.jsonindex 9a8c0d1f..161499ba 100644--- a/spec/manifest.json+++ b/spec/manifest.json@@ -100,6 +100,16 @@"impl": "src/http_headers.zig:promptCacheKey+src/subagent_spawn.zig:allowed","cells_floor": 48,"cells_key": "cases"+ },+ {+ "id": "terminal_modes",+ "lean": "lean-proofs/Graff/TerminalModes.lean",+ "ref": "spec/ref/terminal_modes.py",+ "fixture": "spec/kernels/terminal_modes.json",+ "zig": "TUI/spec_terminal_modes_conformance.zig",+ "impl": "TUI/run.zig:enable_seq+TUI/restore.zig:seq",+ "cells_floor": 14,+ "cells_key": "cells"}]}diff --git a/spec/ref/path_confine.py b/spec/ref/path_confine.pyindex 50ea2254..a4e902b3 100644--- a/spec/ref/path_confine.py+++ b/spec/ref/path_confine.py@@ -4,6 +4,7 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom itertools import product+from pathlib import Pathfrom typing import LiteralIdentities = Literal["both_empty", "rec_empty", "mine_empty", "same", "differ"]@@ -16,6 +17,10 @@ Verdict = Literal["stale_dead","stale_unverifiable",]+Walk = Literal["empty", "safe", "escaped", "absolute"]+Event = tuple # ("startAbs",) | ("component", str)++KERNEL_MD = Path(__file__).resolve().parents[1] / "kernels" / "path_confine.md"PATHS = ("",@@ -36,6 +41,8 @@ PATHS = ("foo/bar/baz",)+EVENTS: tuple[Event, ...] = (("startAbs",), ("component", ".."), ("component", "x"))+def components(path: str) -> list[str]:out: list[str] = []@@ -120,3 +127,145 @@ def all_leases() -> list[Lease]:(False, True),)]+++@dataclass(frozen=True)+class WalkState:+ walk: Walk = "empty"+++def step(s: WalkState, e: Event) -> WalkState:+ if e[0] == "startAbs":+ return WalkState("absolute") if s.walk == "empty" else s+ c = e[1]+ if s.walk in ("absolute", "escaped"):+ return s+ if c == "..":+ return WalkState("escaped")+ return WalkState("safe")+++def run(s: WalkState, es: list[Event]) -> WalkState:+ for e in es:+ s = step(s, e)+ return s+++def confined_walk(s: WalkState) -> bool:+ return s.walk == "safe"+++def events_of(path: str) -> list[Event]:+ evs: list[Event] = [("startAbs",)] if path.startswith("/") else []+ evs.extend(("component", c) for c in components(path))+ return evs+++def walk_path(path: str) -> WalkState:+ return run(WalkState(), events_of(path))+++def project(s: WalkState) -> str:+ return {"empty": "Empty", "safe": "Safe", "escaped": "Escaped", "absolute": "Absolute"}[s.walk]+++def event_label(e: Event) -> str:+ if e[0] == "startAbs":+ return "startAbs"+ if e[1] == "..":+ return "component .."+ return "component"+++def walk(start: WalkState | None = None) -> list[tuple[WalkState, Event, WalkState]]:+ src = start or WalkState()+ seen = {src}+ q = [src]+ out: list[tuple[WalkState, Event, WalkState]] = []+ while q:+ s = q.pop()+ for e in EVENTS:+ t = step(s, e)+ if t == s:+ continue+ out.append((s, e, t))+ if t not in seen:+ seen.add(t)+ q.append(t)+ return out+++def diagram_edges() -> list[tuple[str, str, str]]:+ found: set[tuple[str, str, str]] = set()+ for s, e, t in walk():+ a, b = project(s), project(t)+ if a == b:+ continue+ found.add((a, event_label(e), b))+ return sorted(found)+++def mermaid() -> str:+ lines = ["stateDiagram-v2", " [*] --> Empty"]+ 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: path confine / lease\n"+ "\n"+ "Source of truth: `lean-proofs/Graff/PathConfine.lean`.\n"+ "\n"+ "Process kernel, not a Turing machine: finite `Event` / `step`, no tape.\n"+ "A file-tool path is a walk over components. Empty / Safe / Escaped /\n"+ "Absolute. Escaped and Absolute absorb — a subagent does not recover a\n"+ "jail break by taking another component. The 16 lexical paths + 80 lease\n"+ "cells are the snapshot. `--yolo` does not free a sub. Fleet topology is\n"+ "not a Shape cell; Shape stays the observation ladder of one turn.\n"+ "\n"+ "The diagram is the projection of the live Python `step`. Emit it with\n"+ "`python3 spec/conformance.py --diagram path_confine`.\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:+ if walk_path("").walk != "empty":+ raise ValueError("diagram: empty path not Empty")+ if walk_path("src/main.zig").walk != "safe":+ raise ValueError("diagram: src/main.zig not Safe")+ if walk_path("/etc/passwd").walk != "absolute":+ raise ValueError("diagram: /etc/passwd not Absolute")+ if walk_path("../outside").walk != "escaped":+ raise ValueError("diagram: ../outside not Escaped")+ if step(walk_path("../outside"), ("component", "src")).walk != "escaped":+ raise ValueError("diagram: escaped did not absorb")+ if step(walk_path("/etc/passwd"), ("component", "..")).walk != "absolute":+ raise ValueError("diagram: absolute did not absorb")+ for p in PATHS:+ if confined(p) != confined_walk(walk_path(p)):+ raise ValueError(f"diagram: walk disagrees on {p!r}")+ text = mermaid()+ if "Empty --> Safe: component" not in text:+ raise ValueError("diagram: mermaid missing Empty component→Safe")+ if "Safe --> Escaped: component .." not in text:+ raise ValueError("diagram: mermaid missing Safe component ..→Escaped")+ if "Empty --> Absolute: startAbs" not in text:+ raise ValueError("diagram: mermaid missing Empty startAbs→Absolute")+ if "Escaped --> Safe: component" in text:+ raise ValueError("diagram: mermaid has escape recovery")+ if "Escaped --> Absolute: startAbs" in text:+ raise ValueError("diagram: mermaid has mid-walk startAbs")+ if "Safe --> Absolute: startAbs" in text:+ raise ValueError("diagram: mermaid has mid-walk startAbs from Safe")diff --git a/spec/ref/score.py b/spec/ref/score.pyindex b80d8b74..056578a5 100644--- a/spec/ref/score.py+++ b/spec/ref/score.py@@ -1,14 +1,17 @@"""Executable port of lean-proofs/Graff/Score.lean.+Process kernel, not a Turing machine: finite Event / step, no tape.A score is maintained (filed) iff fleet is on, roleOf(label, niche) is a-canonical slot, and the stage carries a signal. HMAC is out of the model.-stageScore is the same function; the Signal cube is just its five counts.-providerClass needles are in; the price fallback is out (tier=unknown).+canonical slot, and the stage carries a signal. The honest unit is the+STAGE: attempt never files; capture (post-join) files at most once.+HMAC is out. stageScore is the function; the Signal cube is its five counts."""from __future__ import annotations+from dataclasses import dataclassfrom itertools import product+from pathlib import Pathfrom typing import LiteralSlot = Literal[@@ -50,6 +53,7 @@ SIGNAL_COUNTS: dict[Signal, tuple[int, int]] = {"someOk": (3, 2),}CUBE = 1210 # 2 × 11 × 11 × 5+KERNEL_MD = Path(__file__).resolve().parents[1] / "kernels" / "score.md"FILED = 240 # 1 × 120 celled pairs × 2 live signals# normalizeOutboundScore samples: raw float → millipoints or None@@ -216,6 +220,7 @@ def check_properties() -> int:raise ValueError("terra-beats-family")if class_of("deepseek-v4-flash") != "small":raise ValueError("deepseek-flash-small")+ check_diagram()return n@@ -255,3 +260,168 @@ def payload() -> dict:],"filed": FILED,}+++@dataclass(frozen=True)+class State:+ fleet: bool = False+ slot: Slot = "none"+ attempted: int = 0+ ok: int = 0+ filed: bool = False+++Event = tuple # ("fleetOn",) | ("fleetOff",) | ("setSlot", Slot) | ("attempt", bool) | ("capture",)++EVENTS: tuple[Event, ...] = (+ ("fleetOn",),+ ("fleetOff",),+ ("setSlot", "transform"),+ ("setSlot", "none"),+ ("attempt", True),+ ("attempt", False),+ ("capture",),+)+++def files_now(s: State) -> bool:+ return bool(s.fleet and s.slot != "none" and stage_score(s.attempted, s.ok) is not None)+++def step(s: State, e: Event) -> State:+ k = e[0]+ if k == "fleetOn":+ return State(True, s.slot, s.attempted, s.ok, s.filed)+ if k == "fleetOff":+ return State(False, s.slot, s.attempted, s.ok, s.filed)+ if k == "setSlot":+ return State(s.fleet, e[1], s.attempted, s.ok, s.filed)+ if k == "attempt":+ return State(s.fleet, s.slot, s.attempted + 1, s.ok + (1 if e[1] else 0), s.filed)+ if k == "capture":+ return State(s.fleet, s.slot, s.attempted, s.ok, files_now(s))+ 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:+ if not s.fleet:+ return "Off"+ if s.filed:+ return "Filed"+ if s.slot == "none":+ return "Uncelled"+ if s.attempted == 0:+ return "Armed"+ if stage_score(s.attempted, s.ok) is not None:+ return "Live"+ return "Dry"+++def event_label(e: Event) -> str:+ k = e[0]+ if k == "setSlot":+ return "setSlot" if e[1] != "none" else "setSlot none"+ if k == "attempt":+ return "attempt ok" if e[1] else "attempt fail"+ 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:+ if e[0] == "attempt" and s.attempted >= 2:+ continue+ t = step(s, e)+ if t == s:+ continue+ out.append((s, e, t))+ if t not in seen:+ seen.add(t)+ q.append(t)+ return out+++def diagram_edges() -> list[tuple[str, str, str]]:+ found: set[tuple[str, str, str]] = set()+ for s, e, t in walk():+ a, b = project(s), project(t)+ if a == b:+ continue+ found.add((a, event_label(e), b))+ return sorted(found)+++def mermaid() -> str:+ lines = ["stateDiagram-v2", " [*] --> Off"]+ 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: score maintenance\n"+ "\n"+ "Source of truth: `lean-proofs/Graff/Score.lean`.\n"+ "\n"+ "Process kernel, not a Turing machine: finite `Event` / `step`, no tape.\n"+ "The honest unit is the STAGE, never the item. N children do not mint N\n"+ "rows. `attempt` never files; `capture` (the post-join gate) files only\n"+ "when fleet is on, the slot is canonical, and `stageScore` is some.\n"+ "Unreached / all-fail / overflow stay silent — a 0 would poison the mean.\n"+ "The 1210-cell cube (240 filed) is the snapshot. Shape stays the\n"+ "observation ladder of one turn.\n"+ "\n"+ "The diagram is the projection of the live Python `step`. Emit it with\n"+ "`python3 spec/conformance.py --diagram score`.\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:+ idle = State()+ items = run(idle, [("fleetOn",), ("setSlot", "transform"), ("attempt", True), ("attempt", True)])+ if items.filed or items.attempted != 2 or items.ok != 2:+ raise ValueError("diagram: two items filed or lost the fold")+ filed = step(items, ("capture",))+ if not filed.filed:+ raise ValueError("diagram: clean capture did not file")+ if run(idle, [("fleetOn",), ("setSlot", "transform"), ("capture",)]).filed:+ raise ValueError("diagram: unreached filed")+ if run(idle, [("fleetOn",), ("setSlot", "transform"), ("attempt", False), ("capture",)]).filed:+ raise ValueError("diagram: all-fail filed")+ if run(idle, [("setSlot", "transform"), ("attempt", True), ("capture",)]).filed:+ raise ValueError("diagram: fleet-off filed")+ if run(idle, [("fleetOn",), ("attempt", True), ("capture",)]).filed:+ raise ValueError("diagram: uncelled filed")+ if step(items, ("attempt", True)).filed:+ raise ValueError("diagram: attempt filed")+ text = mermaid()+ if "Live --> Filed: capture" not in text:+ raise ValueError("diagram: mermaid missing Live capture→Filed")+ if "Live --> Filed: attempt ok" in text:+ raise ValueError("diagram: mermaid has attempt file edge")+ if "Dry --> Filed: capture" in text:+ raise ValueError("diagram: mermaid has all-fail file edge")+ if "Armed --> Filed: capture" in text:+ raise ValueError("diagram: mermaid has unreached file edge")diff --git a/spec/ref/terminal_modes.py b/spec/ref/terminal_modes.pyindex 3ad5a3a3..e26f6b69 100644--- a/spec/ref/terminal_modes.py+++ b/spec/ref/terminal_modes.py@@ -7,6 +7,7 @@ one model gates the fixtures AND the live binary.from __future__ import annotationsimport re+from pathlib import PathDEFAULT_ON = (7, 25)@@ -37,19 +38,31 @@ def parse_ops(stream: str) -> list[tuple[str, int]]:return ops-def fold(ops: list[tuple[str, int]]) -> tuple[dict[int, bool], int]:- final: dict[int, bool] = {}- depth = 0- for kind, n in ops:- if kind == "set":- final[n] = True- elif kind == "reset":- final[n] = False- elif kind == "push":- depth += 1- else:- depth = max(depth - 1, 0) # grok-build's floor- return final, depth+# Machine state: last-op-wins mode map + kitty depth (floored at 0).+State = tuple[dict[int, bool], int]+KERNEL_MD = Path(__file__).resolve().parents[1] / "kernels" / "terminal_modes.md"+++def step(s: State, op: tuple[str, int]) -> State:+ final, depth = s+ kind, n = op+ out = dict(final)+ if kind == "set":+ out[n] = True+ elif kind == "reset":+ out[n] = False+ elif kind == "push":+ return out, depth + 1+ else:+ return out, max(depth - 1, 0)+ return out, depth+++def fold(ops: list[tuple[str, int]]) -> State:+ s: State = ({}, 0)+ for op in ops:+ s = step(s, op)+ return sdef deviations(final: dict[int, bool]) -> list[int]:@@ -105,6 +118,7 @@ def check_properties() -> int:last_mode = list(MODE_RE.finditer(GRAFF_RESTORE))[-1]if last_mode.group(1) != "1049" or last_mode.group(2) != "l":raise ValueError("graff restore does not end with the alt-screen leave")+ check_diagram()return n@@ -126,3 +140,108 @@ def payload() -> dict:"graff_restore": GRAFF_RESTORE,"cells": rows,}+++def project(s: State) -> str:+ final, depth = s+ alt = bool(final.get(1049))+ if depth == 0 and not deviations(final):+ return "Idle"+ if alt and depth >= 1:+ return "Active"+ if alt:+ return "Alt"+ if depth > 0:+ return "Kitty"+ return "Deviant"+++def event_label(op: tuple[str, int]) -> str:+ kind, n = op+ if kind in ("push", "pop"):+ return kind+ return f"{kind} {n}"+++def walk_ops(start: State, ops: list[tuple[str, int]]) -> list[tuple[State, tuple[str, int], State]]:+ s = start+ out: list[tuple[State, tuple[str, int], State]] = []+ for op in ops:+ t = step(s, op)+ if t != s:+ out.append((s, op, t))+ s = t+ return out+++def diagram_edges() -> list[tuple[str, str, str]]:+ found: set[tuple[str, str, str]] = set()+ extra: list[tuple[str, int]] = [+ ("pop", 0),+ ("push", 0),+ ("pop", 0),+ ("set", 1049),+ ("reset", 1049),+ ("set", 2004),+ ("reset", 2004),+ ]+ streams = [parse_ops(GRAFF_ENABLE + GRAFF_RESTORE), extra]+ for ops in streams:+ for s, op, t in walk_ops(({}, 0), ops):+ a, b = project(s), project(t)+ if a == b:+ continue+ found.add((a, event_label(op), b))+ return sorted(found)+++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: terminal modes\n"+ "\n"+ "Source of truth: `lean-proofs/Graff/TerminalModes.lean`.\n"+ "\n"+ "Process kernel, not a Turing machine: `Op` / `step` is the mode map\n"+ "plus kitty depth. The 14 named sequences are the snapshot. Enable then\n"+ "restore returns to Idle; restore leaves the alt-screen last; pop floors\n"+ "at zero. TUI layout, glyphs, and the font stay never.\n"+ "\n"+ "The diagram is the projection of the live Python `step`. Emit it with\n"+ "`python3 spec/conformance.py --diagram terminal_modes`.\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:+ s: State = ({}, 0)+ for op in parse_ops(GRAFF_ENABLE + GRAFF_RESTORE):+ s = step(s, op)+ if project(s) != "Idle":+ raise ValueError("diagram: enable+restore did not return to Idle")+ if step(({}, 0), ("pop", 0))[1] != 0:+ raise ValueError("diagram: pop from Idle left depth != 0")+ text = mermaid()+ if "Idle --> Alt: set 1049" not in text:+ raise ValueError("diagram: mermaid missing Idle set-1049→Alt")+ if "Alt --> Idle: reset 1049" not in text:+ raise ValueError("diagram: mermaid missing Alt reset-1049→Idle")+ if "Alt --> Active: push" not in text:+ raise ValueError("diagram: mermaid missing Alt push→Active")+ if "Idle --> Active: pop" in text:+ raise ValueError("diagram: mermaid has Idle pop→Active")diff --git a/spec/ref/transport.py b/spec/ref/transport.pyindex 1996289b..014e9f23 100644--- a/spec/ref/transport.py+++ b/spec/ref/transport.py@@ -4,11 +4,15 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom itertools import product+from pathlib import Pathfrom typing import LiteralKind = Literal["anthropic", "openai", "responses"]Pipe = Literal["ws", "sse"]KINDS: tuple[Kind, ...] = ("anthropic", "openai", "responses")+Event = tuple # ("setKind", kind) | ("markSub",) | ("joinRoot",) | ("setCodexWs", bool) | ...++KERNEL_MD = Path(__file__).resolve().parents[1] / "kernels" / "transport.md"@dataclass(frozen=True)@@ -58,3 +62,158 @@ def all_turns() -> list[Turn]:Turn(kind, is_sub, codex_ws, ws_off, has_out, quiet)for kind, is_sub, codex_ws, ws_off, has_out, quiet in product(KINDS, bits, bits, bits, bits, bits)]+++def step(t: Turn, e: Event) -> Turn:+ k = e[0]+ if k == "setKind":+ return Turn(e[1], t.is_sub, t.codex_ws, t.ws_off, t.has_out, t.quiet)+ if k == "markSub":+ return Turn(t.kind, True, t.codex_ws, t.ws_off, t.has_out, t.quiet)+ if k == "joinRoot":+ return Turn(t.kind, False, t.codex_ws, t.ws_off, t.has_out, t.quiet)+ if k == "setCodexWs":+ return Turn(t.kind, t.is_sub, e[1], t.ws_off, t.has_out, t.quiet)+ if k == "setWsOff":+ return Turn(t.kind, t.is_sub, t.codex_ws, e[1], t.has_out, t.quiet)+ if k == "setHasOut":+ return Turn(t.kind, t.is_sub, t.codex_ws, t.ws_off, e[1], t.quiet)+ if k == "setQuiet":+ return Turn(t.kind, t.is_sub, t.codex_ws, t.ws_off, t.has_out, e[1])+ raise ValueError(f"unknown event {e!r}")+++def run(t: Turn, es: list[Event]) -> Turn:+ for e in es:+ t = step(t, e)+ return t+++EVENTS: tuple[Event, ...] = (+ ("setKind", "anthropic"),+ ("setKind", "openai"),+ ("setKind", "responses"),+ ("markSub",),+ ("joinRoot",),+ ("setCodexWs", False),+ ("setCodexWs", True),+ ("setWsOff", False),+ ("setWsOff", True),+ ("setHasOut", False),+ ("setHasOut", True),+ ("setQuiet", False),+ ("setQuiet", True),+)+++def project(t: Turn) -> str:+ if t.is_sub:+ return "Sub"+ if eligible(t):+ return "Ws"+ if t.kind != "responses":+ return "Sse"+ return "Blocked"+++def event_label(e: Event) -> str:+ k = e[0]+ if k == "setKind":+ return f"setKind {e[1]}"+ if k in ("markSub", "joinRoot"):+ return k+ return f"{k} {int(e[1])}"+++def walk(start: Turn | None = None) -> list[tuple[Turn, Event, Turn]]:+ src = start or Turn()+ seen = {src}+ q = [src]+ out: list[tuple[Turn, Event, Turn]] = []+ while q:+ s = q.pop()+ for e in EVENTS:+ t = step(s, e)+ if t == s:+ continue+ out.append((s, e, t))+ if t not in seen:+ seen.add(t)+ q.append(t)+ return out+++def diagram_edges() -> list[tuple[str, str, str]]:+ found: set[tuple[str, str, str]] = set()+ for s, e, t in walk():+ a, b = project(s), project(t)+ if a == b:+ continue+ found.add((a, event_label(e), b))+ return sorted(found)+++def mermaid() -> str:+ lines = ["stateDiagram-v2", " [*] --> Sse"]+ 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: transport\n"+ "\n"+ "Source of truth: `lean-proofs/Graff/Transport.lean`.\n"+ "\n"+ "Process kernel, not a Turing machine: finite `Event` / `step`, no tape.\n"+ "The 96-cell cube is the snapshot. A sub never takes WS; only one cell is\n"+ "WS (a live root Responses turn). PromptCache isolates the child key; this\n"+ "kernel is the pipe that child is forbidden from opening. Shape stays a\n"+ "cube of one observation — fleet topology is not a Shape cell.\n"+ "\n"+ "The diagram is the projection of the live Python `step`. Emit it with\n"+ "`python3 spec/conformance.py --diagram transport`.\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:+ idle = Turn()+ if project(idle) != "Sse" or eligible(idle):+ raise ValueError("diagram: default turn is not Sse")+ ws = step(idle, ("setKind", "responses"))+ if not eligible(ws) or project(ws) != "Ws":+ raise ValueError("diagram: setKind responses did not reach Ws")+ sub = step(ws, ("markSub",))+ if eligible(sub) or project(sub) != "Sub":+ raise ValueError("diagram: markSub did not block WS")+ if eligible(step(sub, ("setKind", "responses"))):+ raise ValueError("diagram: setKind responses granted a sub WS")+ back = step(sub, ("joinRoot",))+ if not eligible(back) or project(back) != "Ws":+ raise ValueError("diagram: joinRoot did not restore Ws")+ if eligible(step(ws, ("setQuiet", True))):+ raise ValueError("diagram: quiet was WS")+ if eligible(step(ws, ("setKind", "anthropic"))):+ raise ValueError("diagram: anthropic was WS")+ if eligible(run(idle, [("markSub",), ("setKind", "responses")])):+ raise ValueError("diagram: sub then responses was WS")+ text = mermaid()+ if "Sse --> Ws: setKind responses" not in text:+ raise ValueError("diagram: mermaid missing Sse setKind responses→Ws")+ if "Ws --> Sub: markSub" not in text:+ raise ValueError("diagram: mermaid missing Ws markSub→Sub")+ if "Sub --> Ws: joinRoot" not in text:+ raise ValueError("diagram: mermaid missing Sub joinRoot→Ws")+ if "Sub --> Ws: setKind responses" in text:+ raise ValueError("diagram: mermaid has Sub setKind responses→Ws")