graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(spec): BashPolicy kernel + Score deepening + full live/new/never accounting
Rach Pradhan886f151eb637
diff --git a/build.zig b/build.zigindex 8b8746cf..7a66b316 100644--- a/build.zig+++ b/build.zig@@ -100,6 +100,7 @@ pub fn build(b: *std.Build) void {unit_tests.root_module.addAnonymousImport("spec_path_confine", .{ .root_source_file = b.path("spec/kernels/path_confine.json") });unit_tests.root_module.addAnonymousImport("spec_shape", .{ .root_source_file = b.path("spec/kernels/shape.json") });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") });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 ae0444f6..a57f013b 100644--- a/lean-proofs/Graff.lean+++ b/lean-proofs/Graff.lean@@ -5,3 +5,4 @@ import Graff.GoalLoopimport Graff.PathConfineimport Graff.Shapeimport Graff.Score+import Graff.BashPolicydiff --git a/lean-proofs/Graff/BashPolicy.lean b/lean-proofs/Graff/BashPolicy.leannew file mode 100644index 00000000..f7fffffb--- /dev/null+++ b/lean-proofs/Graff/BashPolicy.lean@@ -0,0 +1,129 @@+/-+ Bash / plan-mode policy: isSimple, escapesCwd, readOnlyAllowed.++ The leftover discrete family in `harness_policy.zig`. A command is+ auto-allowed in plan mode only when it is simple, stays in cwd, and+ matches a read-only seed prefix. Metacharacters smuggle a second+ command; absolute/`~`/`..` tokens leave cwd. `readOnlyExternal` is the+ #64 twin: simple + seed verb + escapes cwd (prompt, do not auto-run).++ Not modelled: live argv quoting, Windows cmd.exe, the mutable approvals+ allow-list. Executable port: spec/ref/bash_policy.py.+-/++namespace Graff.BashPolicy++def isHSpace (c : Char) : Bool := c == ' ' || c == '\t'++def dropWhile (p : Char → Bool) : List Char → List Char+ | [] => []+ | c :: rest => if p c then dropWhile p rest else c :: rest++def trimST (s : String) : String :=+ let cs := dropWhile isHSpace s.toList+ String.ofList (dropWhile isHSpace cs.reverse).reverse++def metas : List Char :=+ [';', '|', '&', '>', '<', '`', '$', '\n', '\r', '\t', Char.ofNat 0]++def isSimple (cmd : String) : Bool :=+ cmd.toList.all fun c => !(metas.contains c)++def tokens (s : String) : List String :=+ ((s.replace "\t" " ").splitOn " ").filter (· ≠ "")++def hasInfix (s needle : String) : Bool :=+ decide ((s.splitOn needle).length > 1)++def tokenEscapes (tok : String) : Bool :=+ if tok.isEmpty then false+ else if tok.front == '/' || tok.front == '~' then true+ else if hasInfix tok "=/" || hasInfix tok "=~" then true+ else (tok.splitOn "/").contains ".."++def escapesCwd (cmd : String) : Bool :=+ (tokens cmd).any tokenEscapes++def nth (s : String) (n : Nat) : Option Char := s.toList[n]?++def matchesPrefix (cmd pref : String) : Bool :=+ cmd.startsWith pref &&+ (cmd.length == pref.length || nth cmd pref.length == some ' ')++def readOnlySeed : List String :=+ ["ls", "cat", "head", "tail", "wc", "grep", "rg", "pwd", "which", "file",+ "git status", "git diff", "git log", "git show"]++def isReadOnlyVerb (cmd : String) : Bool :=+ readOnlySeed.any (matchesPrefix cmd)++def readOnlyAllowed (cmd : String) : Bool :=+ let c := trimST cmd+ if isSimple c = false then false+ else if escapesCwd c = true then false+ else isReadOnlyVerb c++def readOnlyExternal (cmd : String) : Bool :=+ let c := trimST cmd+ isSimple c && escapesCwd c && isReadOnlyVerb c++theorem not_simple_not_allowed (c : String) (h : isSimple (trimST c) = false) :+ readOnlyAllowed c = false := by+ unfold readOnlyAllowed; simp [h]++theorem escapes_not_allowed (c : String)+ (h₁ : isSimple (trimST c) = true) (h₂ : escapesCwd (trimST c) = true) :+ readOnlyAllowed c = false := by+ unfold readOnlyAllowed; simp [h₁, h₂]++theorem external_needs_simple (c : String) (h : isSimple (trimST c) = false) :+ readOnlyExternal c = false := by+ unfold readOnlyExternal; simp [h]++def commands : List String :=+ ["ls -la", "git status", "cat src/main.zig", " grep foo bar ",+ "rm -rf x", "cat /etc/passwd", "ls; rm x", "git push",+ "zig build", "zig fmt src", "ls ~/projects", "cat /abs/file",+ "lsof", "echo $(whoami)", "echo `id`", "foo > bar",+ "a && b", "echo $HOME", "cat ../outside", "prog --file=/abs/path",+ "prog --flag=value", "grep foo ./a/b.zig", "", "ls",+ "git status -s", "git statusx", "cat a | sh", " ls ",+ "git log", "zig fmt /x.zig", "ls /x; rm y", "grep foo a/../../b"]++def bashCells : Nat := commands.length+def allowedCells : Nat := (commands.filter readOnlyAllowed).length+def externalCells : Nat := (commands.filter readOnlyExternal).length++theorem bash_cube : bashCells = 32 := by native_decide++theorem cube_allowed_implies_simple :+ commands.all (fun c => !(readOnlyAllowed c) || isSimple (trimST c)) := by native_decide++theorem cube_allowed_stays_cwd :+ commands.all (fun c => !(readOnlyAllowed c) || !(escapesCwd (trimST c))) := by native_decide++theorem cube_allowed_is_verb :+ commands.all (fun c => !(readOnlyAllowed c) || isReadOnlyVerb (trimST c)) := by native_decide++theorem cube_external_never_allowed :+ commands.all (fun c => !(readOnlyAllowed c && readOnlyExternal c)) := by native_decide++example : isSimple "ls -la" = true := by native_decide+example : isSimple "ls; rm x" = false := by native_decide+example : isSimple "echo $HOME" = false := by native_decide+example : escapesCwd "cat src/main.zig" = false := by native_decide+example : escapesCwd "cat /etc/passwd" = true := by native_decide+example : escapesCwd "cat ../outside" = true := by native_decide+example : escapesCwd "prog --file=/abs/path" = true := by native_decide+example : escapesCwd "prog --flag=value" = false := by native_decide+example : readOnlyAllowed "ls -la" = true := by native_decide+example : readOnlyAllowed " grep foo bar " = true := by native_decide+example : readOnlyAllowed "rm -rf x" = false := by native_decide+example : readOnlyAllowed "zig build" = false := by native_decide+example : readOnlyAllowed "cat /etc/passwd" = false := by native_decide+example : readOnlyExternal "ls ~/projects" = true := by native_decide+example : readOnlyExternal "cat src/main.zig" = false := by native_decide+example : matchesPrefix "lsof" "ls" = false := by native_decide+example : matchesPrefix "ls -la" "ls" = true := by native_decide++end Graff.BashPolicydiff --git a/lean-proofs/Graff/Score.lean b/lean-proofs/Graff/Score.leanindex d7efdacc..e8e03ca1 100644--- a/lean-proofs/Graff/Score.lean+++ b/lean-proofs/Graff/Score.lean@@ -8,10 +8,15 @@run, they do not accrue. An all-fail or unreached stage files nothing(a 0 would poison the cell mean).+ `stageScore` is the same function the harness uses (millipoints). The+ Signal cube is just the five counts that function classifies. First-word+ titles and the providerClass needle table pin the other two cell axes;+ the price fallback is out of the cube (those models stay `.unknown`).+Matches `pipeline_score.stageScore` / `captureStage`'s predicates,- `shapes.canonicalSlot` / `route_policy.roleOf`, and- `scoring.normalizeOutboundScore`. HMAC, `observe`, and providerClass- price fallback are out of the cube.+ `shapes.canonicalSlot` / `route_policy.roleOf`,+ `scoring.normalizeOutboundScore`, and the needle half of+ `scoring.providerClass`. HMAC, `observe`, and price fallback are out.Executable port: spec/ref/score.py.-/@@ -57,10 +62,43 @@ theorem role_fallback (n : Slot) : roleOf Slot.none n = n := bytheorem both_none_uncelled : roleOf Slot.none Slot.none = Slot.none := rfl+/-- Zig/Python `stageScore`, in millipoints. None = no signal. -/+def stageScore (attempted ok : Nat) : Option Nat :=+ if attempted == 0 || ok == 0 || decide (ok > attempted) then none+ else some (ok * 1000 / attempted)++/-- The five counts the filing cube feeds `stageScore`. -/+def signalCounts : Signal → Nat × Nat+ | .unreached => (0, 0)+ | .allFail => (1, 0)+ | .overflow => (1, 2)+ | .clean => (2, 2)+ | .someOk => (3, 2)+def hasSignal : Signal → Bool| .clean | .someOk => true| .unreached | .allFail | .overflow => false+theorem signal_is_stageScore (s : Signal) :+ hasSignal s = (stageScore (signalCounts s).1 (signalCounts s).2).isSome := by+ cases s <;> native_decide++theorem stage_unreached : stageScore 0 0 = none := rfl+theorem stage_all_fail : stageScore 1 0 = none := rfl+theorem stage_overflow : stageScore 1 2 = none := by native_decide+theorem stage_clean : stageScore 2 2 = some 1000 := rfl+theorem stage_fraction : stageScore 5 4 = some 800 := rfl++theorem stage_bound {a o : Nat} (_ha : a ≠ 0) (ho : o ≤ a) :+ o * 1000 / a ≤ 1000 := by+ have : o * 1000 ≤ a * 1000 := Nat.mul_le_mul_right 1000 ho+ exact Nat.div_le_of_le_mul this++theorem stage_signals_le (s : Signal) (n : Nat)+ (h : stageScore (signalCounts s).1 (signalCounts s).2 = some n) :+ n ≤ 1000 := by+ cases s <;> simp [stageScore, signalCounts] at h <;> subst h <;> decide+/-- Filed iff fleet on, a canonical slot, and a real signal. -/def files (fleet : Bool) (label niche : Slot) (sig : Signal) : Bool :=fleet = true && decide (roleOf label niche ≠ Slot.none) && hasSignal sig = true@@ -82,6 +120,15 @@ theorem clean_celled_files (l n : Slot) (h : roleOf l n ≠ Slot.none) :files true l n Signal.clean = true := byunfold files hasSignal; simp [h]+/-- The Signal enum is not a second source of truth: filing asks `stageScore`. -/+theorem files_iff_stage (fleet : Bool) (l n : Slot) (s : Signal) :+ files fleet l n s =+ (fleet && decide (roleOf l n ≠ Slot.none) &&+ (stageScore (signalCounts s).1 (signalCounts s).2).isSome) := by+ unfold files+ have h := signal_is_stageScore s+ simp [h]+/-- A comparable MAP-Elites cell needs a slot. Tier/niche name the cell;they do not decide whether a row is filed. -/def celled (slot : Slot) : Bool := decide (slot ≠ Slot.none)@@ -111,10 +158,22 @@ theorem change_tier_breaks_cell (c : Cell)sameCell c { c with tier := Tier.frontier } = false := byunfold sameCell; simp [h₁]+theorem change_niche_breaks_cell (c : Cell)+ (h₁ : c.niche = Niche.reviewer) :+ sameCell c { c with niche := Niche.skeptic } = false := by+ unfold sameCell; simp [h₁]+theorem uncelled_not_comparable (c : Cell) (h : c.slot = Slot.none) :sameCell c c = false := byunfold sameCell celled; simp [h]+/-- A filed row is always celled: maintenance never writes an uncelled mean. -/+theorem files_implies_celled (f : Bool) (l n : Slot) (s : Signal)+ (h : files f l n s = true) : celled (roleOf l n) = true := by+ revert h+ unfold files celled+ cases decide (roleOf l n ≠ Slot.none) <;> simp+/-- Discrete samples of `normalizeOutboundScore`. Result is millipointsin [0,1000] so we stay in Nat. HMAC is out of the model. -/inductive ScaleSample where@@ -145,6 +204,135 @@ theorem accepted_in_unit (s : ScaleSample) (n : Nat) (h : normalize s = some n)n ≤ 1000 := bycases s <;> simp [normalize] at h <;> subst h <;> decide+/-- First-word titles. The scanner itself is in Zig; these are the+ load-bearing cases: first word, not substring, and a leading non-ASCII+ byte aborts (otherwise a later English word would steal the cell). -/+inductive Title where+ | find | findBugs | synthesize | verify | reviewFindings+ | transform | sweepPadded | ponder | codeReview | empty | cjkReview+deriving DecidableEq, Repr, BEq++def titleSlot : Title → Slot+ | .find | .findBugs => .find+ | .synthesize => .synthesize+ | .verify => .verify+ | .reviewFindings => .review+ | .transform => .transform+ | .sweepPadded => .sweep+ | .ponder | .codeReview | .empty | .cjkReview => .none++def allTitles : List Title :=+ [.find, .findBugs, .synthesize, .verify, .reviewFindings,+ .transform, .sweepPadded, .ponder, .codeReview, .empty, .cjkReview]++def titleCells : Nat := allTitles.length++theorem title_cube : titleCells = 11 := rfl++/-- Substring would make this `find`. First word keeps it `review`. -/+theorem first_word_not_substring : titleSlot .reviewFindings = Slot.review := rfl++/-- First word is `code`, which is not a slot — the round stays uncelled. -/+theorem later_slot_word_does_not_cell : titleSlot .codeReview = Slot.none := rfl++/-- A leading non-ASCII byte refuses the scan; the label is uncelled. -/+theorem cjk_leading_uncelled : titleSlot .cjkReview = Slot.none := rfl++theorem off_vocab_titles_uncelled :+ titleSlot .ponder = Slot.none ∧ titleSlot .empty = Slot.none := by native_decide++/-- Needle half of `providerClass`. Most-specific first. Price fallback+ is out: unmatched models stay `.unknown` and are not a maintained tier. -/+inductive Model where+ | opus | gpt55 | sol | terra | luna | deepseekPro | grok43+ | haiku | geminiFlash | sonnet | unknown | grokBuild | mimo+ | minimax | deepseekFlash | gemini3+deriving DecidableEq, Repr, BEq++def modelId : Model → String+ | .opus => "claude-opus-4-8"+ | .gpt55 => "gpt-5.5"+ | .sol => "gpt-5.6-sol"+ | .terra => "gpt-5.6-terra"+ | .luna => "gpt-5.6-luna"+ | .deepseekPro => "deepseek-v4-pro"+ | .grok43 => "grok-4.3"+ | .haiku => "claude-haiku-4-5"+ | .geminiFlash => "gemini-3-flash"+ | .sonnet => "claude-sonnet-4-6"+ | .unknown => "some-unknown-model"+ | .grokBuild => "grok-build"+ | .mimo => "mimo-v2.5"+ | .minimax => "minimax-m3"+ | .deepseekFlash => "deepseek-v4-flash"+ | .gemini3 => "gemini-3"++def needles : List (String × Tier) :=+ [("haiku", .small), ("flash", .small), ("-mini", .small),+ ("lite", .small), ("nano", .small), ("terra", .mid), ("luna", .small),+ ("opus", .frontier), ("gpt-5", .frontier), ("deepseek-v4", .frontier),+ ("grok-4", .frontier), ("glm-5", .frontier), ("kimi-k2", .frontier),+ ("minimax-m", .frontier), ("mimo-v2.5-pro", .frontier), ("fugu", .frontier),+ ("gemini-3", .frontier), ("sonnet", .mid)]++def hasInfix (s needle : String) : Bool :=+ decide ((s.splitOn needle).length > 1)++def needleTier (id : String) : Option Tier :=+ (needles.find? (fun n => hasInfix id n.1)).map (·.2)++def classOf (m : Model) : Tier :=+ (needleTier (modelId m)).getD .unknown++def allModels : List Model :=+ [.opus, .gpt55, .sol, .terra, .luna, .deepseekPro, .grok43,+ .haiku, .geminiFlash, .sonnet, .unknown, .grokBuild, .mimo,+ .minimax, .deepseekFlash, .gemini3]++def classCells : Nat := allModels.length++theorem class_cube : classCells = 16 := rfl++/-- Specific markers precede the families they sit in. -/+theorem flash_beats_family : classOf .geminiFlash = Tier.small := by native_decide+theorem terra_beats_family : classOf .terra = Tier.mid := by native_decide+theorem luna_beats_family : classOf .luna = Tier.small := by native_decide+theorem deepseek_flash_small : classOf .deepseekFlash = Tier.small := by native_decide++theorem fallback_unknown : classOf .unknown = Tier.unknown := by native_decide+theorem fallback_grok_build : classOf .grokBuild = Tier.unknown := by native_decide+theorem fallback_mimo : classOf .mimo = Tier.unknown := by native_decide++def knownTier : Tier → Bool+ | .frontier | .mid | .small => true+ | .unknown => false++/-- Price-fallback models are not a maintained cell in this kernel. -/+theorem fallback_not_known_tier (m : Model) (h : classOf m = Tier.unknown) :+ knownTier (classOf m) = false := by+ simp [h, knownTier]++theorem needle_models_known :+ (allModels.filter (fun m => classOf m != .unknown)).all+ (fun m => knownTier (classOf m)) := by native_decide++/-- A maintained cell needs a known tier. Unknown (price fallback) is+ not comparable here — the live function assigns a price bucket, and+ that assignment is out of the cube. -/+def maintainedCell (c : Cell) : Bool :=+ celled c.slot && knownTier c.tier++theorem uncelled_not_maintained (c : Cell) (h : c.slot = Slot.none) :+ maintainedCell c = false := by+ unfold maintainedCell celled; simp [h]++theorem unknown_tier_not_maintained (c : Cell) (h : c.tier = Tier.unknown) :+ maintainedCell c = false := by+ unfold maintainedCell knownTier; simp [h]++theorem mid_find_maintained :+ maintainedCell {} = true := by native_decide+structure FileCase wherefleet : Boollabel : Slot@@ -176,6 +364,32 @@ def filedCells : Nat :=/-- 2 fleets × 11 slots × 11 niches × 5 signals. -/theorem score_cube : scoreCells = 1210 := by native_decide+/-- Fleet-on × 120 celled (label, niche) pairs × 2 live signals. -/+theorem filed_count : filedCells = 240 := by native_decide++/-- Every filed cell of the cube is celled, fleet-on, and has a stageScore. -/+theorem cube_filed_is_celled :+ allFileCases.all (fun c =>+ !(files c.fleet c.label c.niche c.sig) ||+ celled (roleOf c.label c.niche)) := by native_decide++theorem cube_filed_fleet_on :+ allFileCases.all (fun c =>+ !(files c.fleet c.label c.niche c.sig) || c.fleet) := by native_decide++theorem cube_filed_has_stage :+ allFileCases.all (fun c =>+ !(files c.fleet c.label c.niche c.sig) ||+ (stageScore (signalCounts c.sig).1 (signalCounts c.sig).2).isSome) := by+ native_decide++theorem cube_files_iff_stage :+ allFileCases.all (fun c =>+ files c.fleet c.label c.niche c.sig ==+ (c.fleet && decide (roleOf c.label c.niche ≠ Slot.none) &&+ (stageScore (signalCounts c.sig).1 (signalCounts c.sig).2).isSome)) := by+ native_decide+/-! Concrete cells the harness also checks. -/example : files true Slot.transform Slot.none Signal.clean = true := by native_decide@@ -188,5 +402,11 @@ example : files false Slot.transform Slot.none Signal.clean = false := by nativeexample : roleOf Slot.none Slot.transform = Slot.transform := by native_decideexample : roleOf Slot.review Slot.find = Slot.review := by native_decideexample : sameCell {} { slot := Slot.verify } = false := by native_decide+example : classOf .opus = Tier.frontier := by native_decide+example : classOf .haiku = Tier.small := by native_decide+example : classOf .sonnet = Tier.mid := by native_decide+example : classOf .minimax = Tier.frontier := by native_decide+example : titleSlot .findBugs = Slot.find := by native_decide+example : titleSlot .sweepPadded = Slot.sweep := by native_decideend Graff.Scorediff --git a/lean-proofs/KERNELS.md b/lean-proofs/KERNELS.mdindex 066594a8..d4443fd9 100644--- a/lean-proofs/KERNELS.md+++ b/lean-proofs/KERNELS.md@@ -3,30 +3,57 @@A kernel graduates when (1) Lean builds, (2) the reference model exhauststhe reachable cells, (3) the Zig implementation matches the export.-| Kernel | Status | Reachable cells | What it is *not* |-|---|---|---|---|-| `ToolCatalog` | live | 64 flag cubes | MCP names, descriptions, JSON wrappers |-| `Transport` | live | 96 turns (3 kinds × 5 bools); **1** WS cell | frames, TLS, idle-kill timing of the server |-| `Provider` | live | 18 baked rows | live `/models` overlay, Kimi protocol flip |-| `GoalLoop` | live | 360 gate cells; empty ≠ done; standing does not retire | model wording, whether the work is correct |-| `PathConfine` | live | 16 lexical paths + 80 lease cells; yolo does not free a sub | OS errno, Windows drives |-| `Shape` | live | 1728 ladder cells (derived budget); hand ladder + explicit arm only | `admit`, learned override, ε-explore, `observe` |-| `Score` | live | 1210 filing cells; uncelled/all-fail never accrue; scale is `[0,1]` | HMAC, providerClass price fallback |-| TUI, prompts, SSE bytes | never | — | eval / tier 2 |--The discrete kernels we set out to write are all live. Next additions would-be *new* decision procedures (e.g. `isSimple` shell classification, or-"eval GREEN required before completion"), not more vendors.+## Every harness part++Every part is **live**, **new**, or **never**. Never is a classification,+not a skip: TUI, prompts, and SSE bytes stay out of Lean on purpose.++### Live (already a complete triangle)++| 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 |+| `Provider` | 18 baked rows | live `/models` overlay, Kimi protocol flip |+| `GoalLoop` | 360 gate cells | model wording, whether the work is correct |+| `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 |++### New (this loop)++| Kernel | Cells | What it is *not* |+|---|---|---|+| `BashPolicy` | finite command cube: `isSimple`, `escapesCwd`, `readOnlyAllowed`, `readOnlyExternal` | live argv quoting, Windows cmd.exe |++### Never (accounted for; eval / tier 2)++| Part | Why never |+|---|---|+| TUI (layout, colors, glyphs, hover) | the emulator owns the font and the cell grid |+| Prompts / system text | wording is not a discrete decision |+| SSE / stream bytes | wire framing, not a predicate |+| MCP protocol / tool descriptions | names and schemas, not a flag cube |+| HMAC score signing | crypto, not a discrete gate |+| Learned override / ε-explore | archive-backed, not the compiled prior |+| `observe` file tokenizer / session decline counts | encoder in front of the ladder |+| Live `/models` overlay | network, not the baked table |+| `noSymlinkEscape` on a real FS | OS; modelled lexically in PathConfine |+| Approvals session state (allow-list, yolo persistence) | mutable human session, not a pure function |+| Compaction / HTTP / process runner | I/O and timing |+| "eval GREEN before completion" | no such discrete Zig predicate exists |++The leftover discrete bash/policy family (`isSimple` / `escapesCwd` /+`readOnlyAllowed`, plus the `#64` twin `readOnlyExternal`) is the new+triangle. `isInterpreter`, `isDestructiveGit`, and `planReadMatch` live+in the same module and are covered as tables/cases on that triangle, not+as a ninth kernel.## How a kernel evolves1. Write the axes and the illegal-cell predicates in Lean first.-2. Prove the cheap general facts (`sub` never WS, only `responses` is WS,- unique provider ids, `#330` wins).+2. Prove the cheap general facts.3. Port the same functions to `spec/ref/<kernel>.py`.4. Export `spec/kernels/<kernel>.json`.5. Diff the live Zig function against the export.6. Stop. Do not add a vendor-specific theorem.--When `provider_specs` gains a row, `Provider.lean` and the fixture grow by-one line and the Zig test fails until they do. That is the ratchet.diff --git a/lean-proofs/Main.lean b/lean-proofs/Main.leanindex e8c0842f..31121c39 100644--- a/lean-proofs/Main.lean+++ b/lean-proofs/Main.lean@@ -5,6 +5,7 @@ import Graff.GoalLoopimport Graff.PathConfineimport Graff.Shapeimport Graff.Score+import Graff.BashPolicyopen Graff@@ -19,5 +20,6 @@ def main : IO Unit := doIO.println s!"goal {GoalLoop.goalCells} refuse_open={GoalLoop.refuseOpenCells} refuse_no_plan={GoalLoop.refuseNoPlanCells}"IO.println s!"lease {PathConfine.leaseCells} warns={PathConfine.warnCells}"IO.println s!"shape {Shape.shapeCells} R0={Shape.r0Cells} R3={Shape.r3Cells}"- IO.println s!"score {Score.scoreCells} filed={Score.filedCells}"- IO.println s!"cells_total {ToolCatalog.catalogCells + Transport.transportCells + Provider.providerRows + GoalLoop.goalCells + PathConfine.leaseCells + Shape.shapeCells + Score.scoreCells}"+ 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}"diff --git a/spec/README.md b/spec/README.mdindex d8c18395..3694d370 100644--- a/spec/README.md+++ b/spec/README.md@@ -47,8 +47,9 @@ properties are load-bearing, and a missed combination is a real bug.| `goal_loop` | live | 360 gate cells. Empty ≠ done. Standing does not retire. || `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. Uncelled/all-fail never accrue. Scale is `[0,1]`. |-| TUI, prompts, SSE bytes | never | Eval, don't prove. |+| `score` | live | 1210 filing cells, 240 filed. First-word titles, needle class, `[0,1]` scale. |+| `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`. |## Rundiff --git a/spec/conformance.py b/spec/conformance.pyindex a1f2f901..5a53f8f7 100644--- a/spec/conformance.py+++ b/spec/conformance.py@@ -57,6 +57,8 @@ from 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_propertiesfrom ref.score import payload as score_model_payload+from ref.bash_policy import check_properties as bash_check_properties+from ref.bash_policy import payload as bash_model_payloadROOT = Path(__file__).resolve().parentKERNELS = ROOT / "kernels"@@ -67,6 +69,7 @@ GOAL_FIXTURE = KERNELS / "goal_loop.json"PATH_FIXTURE = KERNELS / "path_confine.json"SHAPE_FIXTURE = KERNELS / "shape.json"SCORE_FIXTURE = KERNELS / "score.json"+BASH_FIXTURE = KERNELS / "bash_policy.json"LEAN_DIR = ROOT.parent / "lean-proofs"@@ -307,6 +310,10 @@ def score_payload() -> dict:return score_model_payload()+def bash_payload() -> dict:+ return bash_model_payload()++def check_provider() -> int:ids = [r["id"] for r in PROVIDER_SPECS]if len(ids) != len(set(ids)):@@ -407,6 +414,15 @@ def check_score() -> int:raise Counterexample(prop, None, detail or msg) from e+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++def prefixes_first(p: str) -> list[str]:parts = [c for c in p.split("/") if c]return [parts[0]] if parts else []@@ -427,6 +443,7 @@ def export() -> list[Path]:_write(PATH_FIXTURE, path_payload()),_write(SHAPE_FIXTURE, shape_payload()),_write(SCORE_FIXTURE, score_payload()),+ _write(BASH_FIXTURE, bash_payload()),]@@ -445,6 +462,7 @@ def check_fixtures() -> None:_same(PATH_FIXTURE, path_payload(), "path_confine")_same(SHAPE_FIXTURE, shape_payload(), "shape")_same(SCORE_FIXTURE, score_payload(), "score")+ _same(BASH_FIXTURE, bash_payload(), "bash_policy")def break_model(kind: str) -> None:@@ -526,15 +544,16 @@ def main() -> int:n_pc = check_path_confine()n_sh = check_shape()n_sc = check_score()+ n_ba = check_bash()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} → {rel}")+ 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} → {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}"+ f"provider {n_pr} goal_loop {n_gl} path_confine {n_pc} shape {n_sh} score {n_sc} bash {n_ba}")if args.lean:try_lean()diff --git a/spec/eval_history.py b/spec/eval_history.pyindex bf91fb14..0f5af14e 100644--- a/spec/eval_history.py+++ b/spec/eval_history.py@@ -21,6 +21,7 @@ KERNELS = {"path": ("src/harness_policy.zig", "src/worktree_lease.zig"),"shape": ("src/escalation.zig", "src/shapes.zig", "src/route_policy.zig"),"score": ("src/scoring.zig", "src/pipeline_score.zig", "src/shapes.zig"),+ "bash": ("src/harness_policy.zig", "src/approvals.zig"),}diff --git a/spec/kernels/bash_policy.json b/spec/kernels/bash_policy.jsonnew file mode 100644index 00000000..2796d76c--- /dev/null+++ b/spec/kernels/bash_policy.json@@ -0,0 +1,284 @@+{+ "kernel": "bash_policy",+ "version": 1,+ "models": "isSimple+escapesCwd+readOnlyAllowed+readOnlyExternal",+ "out": [+ "argv-quoting",+ "cmd.exe",+ "approvals-session"+ ],+ "seed": [+ "ls",+ "cat",+ "head",+ "tail",+ "wc",+ "grep",+ "rg",+ "pwd",+ "which",+ "file",+ "git status",+ "git diff",+ "git log",+ "git show"+ ],+ "cases": [+ {+ "id": "'ls -la'",+ "cmd": "ls -la",+ "simple": true,+ "escapes": false,+ "allowed": true,+ "external": false+ },+ {+ "id": "'git status'",+ "cmd": "git status",+ "simple": true,+ "escapes": false,+ "allowed": true,+ "external": false+ },+ {+ "id": "'cat src/main.zig'",+ "cmd": "cat src/main.zig",+ "simple": true,+ "escapes": false,+ "allowed": true,+ "external": false+ },+ {+ "id": "' grep foo bar '",+ "cmd": " grep foo bar ",+ "simple": true,+ "escapes": false,+ "allowed": true,+ "external": false+ },+ {+ "id": "'rm -rf x'",+ "cmd": "rm -rf x",+ "simple": true,+ "escapes": false,+ "allowed": false,+ "external": false+ },+ {+ "id": "'cat /etc/passwd'",+ "cmd": "cat /etc/passwd",+ "simple": true,+ "escapes": true,+ "allowed": false,+ "external": true+ },+ {+ "id": "'ls; rm x'",+ "cmd": "ls; rm x",+ "simple": false,+ "escapes": false,+ "allowed": false,+ "external": false+ },+ {+ "id": "'git push'",+ "cmd": "git push",+ "simple": true,+ "escapes": false,+ "allowed": false,+ "external": false+ },+ {+ "id": "'zig build'",+ "cmd": "zig build",+ "simple": true,+ "escapes": false,+ "allowed": false,+ "external": false+ },+ {+ "id": "'zig fmt src'",+ "cmd": "zig fmt src",+ "simple": true,+ "escapes": false,+ "allowed": false,+ "external": false+ },+ {+ "id": "'ls ~/projects'",+ "cmd": "ls ~/projects",+ "simple": true,+ "escapes": true,+ "allowed": false,+ "external": true+ },+ {+ "id": "'cat /abs/file'",+ "cmd": "cat /abs/file",+ "simple": true,+ "escapes": true,+ "allowed": false,+ "external": true+ },+ {+ "id": "'lsof'",+ "cmd": "lsof",+ "simple": true,+ "escapes": false,+ "allowed": false,+ "external": false+ },+ {+ "id": "'echo $(whoami)'",+ "cmd": "echo $(whoami)",+ "simple": false,+ "escapes": false,+ "allowed": false,+ "external": false+ },+ {+ "id": "'echo `id`'",+ "cmd": "echo `id`",+ "simple": false,+ "escapes": false,+ "allowed": false,+ "external": false+ },+ {+ "id": "'foo > bar'",+ "cmd": "foo > bar",+ "simple": false,+ "escapes": false,+ "allowed": false,+ "external": false+ },+ {+ "id": "'a && b'",+ "cmd": "a && b",+ "simple": false,+ "escapes": false,+ "allowed": false,+ "external": false+ },+ {+ "id": "'echo $HOME'",+ "cmd": "echo $HOME",+ "simple": false,+ "escapes": false,+ "allowed": false,+ "external": false+ },+ {+ "id": "'cat ../outside'",+ "cmd": "cat ../outside",+ "simple": true,+ "escapes": true,+ "allowed": false,+ "external": true+ },+ {+ "id": "'prog --file=/abs/path'",+ "cmd": "prog --file=/abs/path",+ "simple": true,+ "escapes": true,+ "allowed": false,+ "external": false+ },+ {+ "id": "'prog --flag=value'",+ "cmd": "prog --flag=value",+ "simple": true,+ "escapes": false,+ "allowed": false,+ "external": false+ },+ {+ "id": "'grep foo ./a/b.zig'",+ "cmd": "grep foo ./a/b.zig",+ "simple": true,+ "escapes": false,+ "allowed": true,+ "external": false+ },+ {+ "id": "''",+ "cmd": "",+ "simple": true,+ "escapes": false,+ "allowed": false,+ "external": false+ },+ {+ "id": "'ls'",+ "cmd": "ls",+ "simple": true,+ "escapes": false,+ "allowed": true,+ "external": false+ },+ {+ "id": "'git status -s'",+ "cmd": "git status -s",+ "simple": true,+ "escapes": false,+ "allowed": true,+ "external": false+ },+ {+ "id": "'git statusx'",+ "cmd": "git statusx",+ "simple": true,+ "escapes": false,+ "allowed": false,+ "external": false+ },+ {+ "id": "'cat a | sh'",+ "cmd": "cat a | sh",+ "simple": false,+ "escapes": false,+ "allowed": false,+ "external": false+ },+ {+ "id": "' ls '",+ "cmd": " ls ",+ "simple": true,+ "escapes": false,+ "allowed": true,+ "external": false+ },+ {+ "id": "'git log'",+ "cmd": "git log",+ "simple": true,+ "escapes": false,+ "allowed": true,+ "external": false+ },+ {+ "id": "'zig fmt /x.zig'",+ "cmd": "zig fmt /x.zig",+ "simple": true,+ "escapes": true,+ "allowed": false,+ "external": false+ },+ {+ "id": "'ls /x; rm y'",+ "cmd": "ls /x; rm y",+ "simple": false,+ "escapes": true,+ "allowed": false,+ "external": false+ },+ {+ "id": "'grep foo a/../../b'",+ "cmd": "grep foo a/../../b",+ "simple": true,+ "escapes": true,+ "allowed": false,+ "external": true+ }+ ]+}diff --git a/spec/kernels/bash_policy.md b/spec/kernels/bash_policy.mdnew file mode 100644index 00000000..a161348c--- /dev/null+++ b/spec/kernels/bash_policy.md@@ -0,0 +1,16 @@+# Kernel: bash / plan-mode policy++Source of truth: `lean-proofs/Graff/BashPolicy.lean`.++`readOnlyAllowed` is plan mode's auto-run gate:++1. trim space/tab+2. `isSimple` — no `;|&><\`$` / newlines / tab / NUL+3. not `escapesCwd` — no `/`, `~`, `=/`, `=~`, or `..` component+4. `matchesPrefix` against `read_only_seed` (whole-word, space boundary)++`readOnlyExternal` is the #64 twin: simple + seed verb + escapes cwd.+It is never auto-allowed. `zig build` / `zig fmt` are in `seed` but not+in `read_only_seed`.++Not modelled: argv quoting, cmd.exe, the mutable approvals allow-list.diff --git a/spec/kernels/score.json b/spec/kernels/score.jsonindex baba265b..63934bcf 100644--- a/spec/kernels/score.json+++ b/spec/kernels/score.json@@ -1,7 +1,7 @@{"kernel": "score",- "version": 1,- "models": "stageScore+roleOf+normalizeOutboundScore",+ "version": 2,+ "models": "stageScore+roleOf+normalizeOutboundScore+providerClassNeedles","out": ["HMAC","providerClass-price",@@ -13408,6 +13408,93 @@{"title": "","slot": "none"+ },+ {+ "title": "\u5b89\u5168 review",+ "slot": "none"}- ]+ ],+ "classes": [+ {+ "id": "claude-opus-4-8",+ "tier": "frontier",+ "source": "needle"+ },+ {+ "id": "gpt-5.5",+ "tier": "frontier",+ "source": "needle"+ },+ {+ "id": "gpt-5.6-sol",+ "tier": "frontier",+ "source": "needle"+ },+ {+ "id": "gpt-5.6-terra",+ "tier": "mid",+ "source": "needle"+ },+ {+ "id": "gpt-5.6-luna",+ "tier": "small",+ "source": "needle"+ },+ {+ "id": "deepseek-v4-pro",+ "tier": "frontier",+ "source": "needle"+ },+ {+ "id": "grok-4.3",+ "tier": "frontier",+ "source": "needle"+ },+ {+ "id": "claude-haiku-4-5",+ "tier": "small",+ "source": "needle"+ },+ {+ "id": "gemini-3-flash",+ "tier": "small",+ "source": "needle"+ },+ {+ "id": "claude-sonnet-4-6",+ "tier": "mid",+ "source": "needle"+ },+ {+ "id": "some-unknown-model",+ "tier": "unknown",+ "source": "fallback"+ },+ {+ "id": "grok-build",+ "tier": "unknown",+ "source": "fallback"+ },+ {+ "id": "mimo-v2.5",+ "tier": "unknown",+ "source": "fallback"+ },+ {+ "id": "minimax-m3",+ "tier": "frontier",+ "source": "needle"+ },+ {+ "id": "deepseek-v4-flash",+ "tier": "small",+ "source": "needle"+ },+ {+ "id": "gemini-3",+ "tier": "frontier",+ "source": "needle"+ }+ ],+ "filed": 240}diff --git a/spec/kernels/score.md b/spec/kernels/score.mdindex 097719c6..5fa51d47 100644--- a/spec/kernels/score.md+++ b/spec/kernels/score.md@@ -10,10 +10,18 @@ A fitness row is *maintained* (filed, comparable) iff:Unreached, all-fail, and `ok > attempted` file nothing — a 0 would poisonthe 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. HMAC and the providerClass-price fallback are out of this kernel.+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.+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.diff --git a/spec/manifest.json b/spec/manifest.jsonindex c78a906b..f727f17d 100644--- a/spec/manifest.json+++ b/spec/manifest.json@@ -74,9 +74,19 @@"ref": "spec/ref/score.py","fixture": "spec/kernels/score.json","zig": "src/spec_score_conformance.zig",- "impl": "src/pipeline_score.zig:stageScore+src/route_policy.zig:roleOf+src/scoring.zig:normalizeOutboundScore",+ "impl": "src/pipeline_score.zig:stageScore+src/route_policy.zig:roleOf+src/scoring.zig:normalizeOutboundScore+providerClass","cells_floor": 1210,"cells_key": "cases"+ },+ {+ "id": "bash_policy",+ "lean": "lean-proofs/Graff/BashPolicy.lean",+ "ref": "spec/ref/bash_policy.py",+ "fixture": "spec/kernels/bash_policy.json",+ "zig": "src/spec_bash_policy_conformance.zig",+ "impl": "src/harness_policy.zig:isSimple+escapesCwd+readOnlyAllowed",+ "cells_floor": 32,+ "cells_key": "cases"}]}diff --git a/spec/ref/bash_policy.py b/spec/ref/bash_policy.pynew file mode 100644index 00000000..461b316c--- /dev/null+++ b/spec/ref/bash_policy.py@@ -0,0 +1,162 @@+"""Executable port of lean-proofs/Graff/BashPolicy.lean."""++from __future__ import annotations++METAS = frozenset(";|&><`$\n\r\t\x00")+READ_ONLY_SEED = (+ "ls",+ "cat",+ "head",+ "tail",+ "wc",+ "grep",+ "rg",+ "pwd",+ "which",+ "file",+ "git status",+ "git diff",+ "git log",+ "git show",+)+COMMANDS: tuple[str, ...] = (+ "ls -la",+ "git status",+ "cat src/main.zig",+ " grep foo bar ",+ "rm -rf x",+ "cat /etc/passwd",+ "ls; rm x",+ "git push",+ "zig build",+ "zig fmt src",+ "ls ~/projects",+ "cat /abs/file",+ "lsof",+ "echo $(whoami)",+ "echo `id`",+ "foo > bar",+ "a && b",+ "echo $HOME",+ "cat ../outside",+ "prog --file=/abs/path",+ "prog --flag=value",+ "grep foo ./a/b.zig",+ "",+ "ls",+ "git status -s",+ "git statusx",+ "cat a | sh",+ " ls ",+ "git log",+ "zig fmt /x.zig",+ "ls /x; rm y",+ "grep foo a/../../b",+)+CUBE = 32+++def trim_st(s: str) -> str:+ return s.strip(" \t")+++def is_simple(cmd: str) -> bool:+ return not any(ch in METAS for ch in cmd)+++def tokens(s: str) -> list[str]:+ return [t for t in s.replace("\t", " ").split(" ") if t]+++def token_escapes(tok: str) -> bool:+ if not tok:+ return False+ if tok[0] in "/~":+ return True+ if "=/" in tok or "=~" in tok:+ return True+ return ".." in tok.split("/")+++def escapes_cwd(cmd: str) -> bool:+ return any(token_escapes(t) for t in tokens(cmd))+++def matches_prefix(cmd: str, prefix: str) -> bool:+ if not cmd.startswith(prefix):+ return False+ return len(cmd) == len(prefix) or cmd[len(prefix)] == " "+++def is_read_only_verb(cmd: str) -> bool:+ return any(matches_prefix(cmd, p) for p in READ_ONLY_SEED)+++def read_only_allowed(cmd: str) -> bool:+ c = trim_st(cmd)+ if not is_simple(c) or escapes_cwd(c):+ return False+ return is_read_only_verb(c)+++def read_only_external(cmd: str) -> bool:+ c = trim_st(cmd)+ return is_simple(c) and escapes_cwd(c) and is_read_only_verb(c)+++def check_properties() -> int:+ n = 0+ for cmd in COMMANDS:+ n += 1+ c = trim_st(cmd)+ if read_only_allowed(cmd):+ if not is_simple(c):+ raise ValueError(f"allowed-implies-simple: {cmd!r}")+ if escapes_cwd(c):+ raise ValueError(f"allowed-stays-cwd: {cmd!r}")+ if not is_read_only_verb(c):+ raise ValueError(f"allowed-is-verb: {cmd!r}")+ if read_only_external(cmd):+ raise ValueError(f"allowed-not-external: {cmd!r}")+ if not is_simple(c) and read_only_allowed(cmd):+ raise ValueError(f"not-simple-not-allowed: {cmd!r}")+ if is_simple(c) and escapes_cwd(c) and read_only_allowed(cmd):+ raise ValueError(f"escapes-not-allowed: {cmd!r}")+ ext = read_only_external(cmd)+ want_ext = is_simple(c) and escapes_cwd(c) and is_read_only_verb(c)+ if ext != want_ext:+ raise ValueError(f"external: {cmd!r} got={ext}")+ if n != CUBE:+ raise ValueError(f"bash-cube: n={n} want={CUBE}")+ if is_simple("ls; rm x") or is_simple("echo $HOME"):+ raise ValueError("is-simple: metachar must fail")+ if escapes_cwd("cat src/main.zig") or not escapes_cwd("cat /etc/passwd"):+ raise ValueError("escapes-cwd")+ if matches_prefix("lsof", "ls") or not matches_prefix("ls -la", "ls"):+ raise ValueError("matches-prefix: word boundary")+ if read_only_allowed("zig build") or read_only_allowed("rm -rf x"):+ raise ValueError("seed: zig build / rm are not read-only")+ return n+++def payload() -> dict:+ cases = []+ for cmd in COMMANDS:+ cases.append(+ {+ "id": repr(cmd),+ "cmd": cmd,+ "simple": is_simple(cmd),+ "escapes": escapes_cwd(cmd),+ "allowed": read_only_allowed(cmd),+ "external": read_only_external(cmd),+ }+ )+ return {+ "kernel": "bash_policy",+ "version": 1,+ "models": "isSimple+escapesCwd+readOnlyAllowed+readOnlyExternal",+ "out": ["argv-quoting", "cmd.exe", "approvals-session"],+ "seed": list(READ_ONLY_SEED),+ "cases": cases,+ }diff --git a/spec/ref/score.py b/spec/ref/score.pyindex 1bffadd9..b80d8b74 100644--- a/spec/ref/score.py+++ b/spec/ref/score.py@@ -2,6 +2,8 @@A score is maintained (filed) iff fleet is on, roleOf(label, niche) is acanonical 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)."""from __future__ import annotations@@ -23,6 +25,7 @@ Slot = Literal["none",]Signal = Literal["unreached", "allFail", "overflow", "clean", "someOk"]+Tier = Literal["frontier", "mid", "small", "unknown"]SLOTS: tuple[Slot, ...] = ("find","verify",@@ -47,6 +50,7 @@ SIGNAL_COUNTS: dict[Signal, tuple[int, int]] = {"someOk": (3, 2),}CUBE = 1210 # 2 × 11 × 11 × 5+FILED = 240 # 1 × 120 celled pairs × 2 live signals# normalizeOutboundScore samples: raw float → millipoints or NoneSCALE: tuple[dict, ...] = (@@ -70,6 +74,49 @@ TITLES: tuple[tuple[str, Slot], ...] = (("ponder", "none"),("code review", "none"),("", "none"),+ ("安全 review", "none"),+)++# Most-specific first; matches scoring.providerClass needles.+NEEDLES: tuple[tuple[str, Tier], ...] = (+ ("haiku", "small"),+ ("flash", "small"),+ ("-mini", "small"),+ ("lite", "small"),+ ("nano", "small"),+ ("terra", "mid"),+ ("luna", "small"),+ ("opus", "frontier"),+ ("gpt-5", "frontier"),+ ("deepseek-v4", "frontier"),+ ("grok-4", "frontier"),+ ("glm-5", "frontier"),+ ("kimi-k2", "frontier"),+ ("minimax-m", "frontier"),+ ("mimo-v2.5-pro", "frontier"),+ ("fugu", "frontier"),+ ("gemini-3", "frontier"),+ ("sonnet", "mid"),+)++# id, expected needle tier (unknown = price fallback, out of the cube)+MODELS: tuple[tuple[str, Tier], ...] = (+ ("claude-opus-4-8", "frontier"),+ ("gpt-5.5", "frontier"),+ ("gpt-5.6-sol", "frontier"),+ ("gpt-5.6-terra", "mid"),+ ("gpt-5.6-luna", "small"),+ ("deepseek-v4-pro", "frontier"),+ ("grok-4.3", "frontier"),+ ("claude-haiku-4-5", "small"),+ ("gemini-3-flash", "small"),+ ("claude-sonnet-4-6", "mid"),+ ("some-unknown-model", "unknown"),+ ("grok-build", "unknown"),+ ("mimo-v2.5", "unknown"),+ ("minimax-m3", "frontier"),+ ("deepseek-v4-flash", "small"),+ ("gemini-3", "frontier"),)@@ -92,12 +139,25 @@ def stage_score(attempted: int, ok: int) -> int | None:return (ok * 1000) // attempted+def needle_tier(model: str) -> Tier | None:+ low = model.lower()+ for needle, tier in NEEDLES:+ if needle in low:+ return tier+ return None+++def class_of(model: str) -> Tier:+ return needle_tier(model) or "unknown"++def all_file_cases() -> list[tuple[bool, Slot, Slot, Signal]]:return list(product((False, True), SLOTS, SLOTS, SIGNALS))def check_properties() -> int:n = 0+ filed = 0for fleet, label, niche, sig in all_file_cases():n += 1got = files(fleet, label, niche, sig)@@ -106,14 +166,22 @@ def check_properties() -> int:want = fleet and role_of(label, niche) != "none" and signal_okif got != want:raise ValueError(f"files: fleet={fleet} {label}/{niche} {sig} got={got}")+ if got:+ filed += 1if not fleet and got:raise ValueError(f"fleet-off-never-files: {label} {sig}")if label == "none" and niche == "none" and got:raise ValueError(f"uncelled-never-files: {sig}")if not has_signal(sig) and got:raise ValueError(f"no-signal-never-files: {label} {sig}")+ if got and role_of(label, niche) == "none":+ raise ValueError(f"filed-not-celled: {label}/{niche} {sig}")+ if has_signal(sig) != signal_ok:+ raise ValueError(f"signal-is-stageScore: {sig} has={has_signal(sig)} stage={signal_ok}")if n != CUBE:raise ValueError(f"score-cube: n={n} want={CUBE}")+ if filed != FILED:+ raise ValueError(f"filed-count: filed={filed} want={FILED}")if role_of("none", "transform") != "transform":raise ValueError("role-fallback: niche must supply the slot")if role_of("review", "find") != "review":@@ -126,6 +194,28 @@ def check_properties() -> int:raise ValueError("stage-score: clean fraction")if len(CANONICAL) != 10:raise ValueError(f"ten-slots: {len(CANONICAL)}")+ if len(TITLES) != 11:+ raise ValueError(f"title-cube: {len(TITLES)}")+ if any(slot == "find" for title, slot in TITLES if title == "review the findings"):+ raise ValueError("first-word-not-substring: review the findings must stay review")+ if any(slot != "none" for title, slot in TITLES if title in ("code review", "安全 review")):+ raise ValueError("off-vocab-titles-uncelled")+ if len(MODELS) != 16:+ raise ValueError(f"class-cube: {len(MODELS)}")+ for mid, want in MODELS:+ got = class_of(mid)+ if got != want:+ raise ValueError(f"classOf: {mid} got={got} want={want}")+ if want == "unknown" and needle_tier(mid) is not None:+ raise ValueError(f"fallback-unknown: {mid} hit a needle")+ if want != "unknown" and needle_tier(mid) is None:+ raise ValueError(f"needle-models-known: {mid} missed")+ if class_of("gemini-3-flash") != "small":+ raise ValueError("flash-beats-family")+ if class_of("gpt-5.6-terra") != "mid":+ raise ValueError("terra-beats-family")+ if class_of("deepseek-v4-flash") != "small":+ raise ValueError("deepseek-flash-small")return n@@ -148,11 +238,20 @@ def payload() -> dict:)return {"kernel": "score",- "version": 1,- "models": "stageScore+roleOf+normalizeOutboundScore",+ "version": 2,+ "models": "stageScore+roleOf+normalizeOutboundScore+providerClassNeedles","out": ["HMAC", "providerClass-price", "observe"],"slots": list(CANONICAL),"cases": cases,"scale": [dict(s) for s in SCALE],"titles": [{"title": t, "slot": sl} for t, sl in TITLES],+ "classes": [+ {+ "id": mid,+ "tier": tier,+ "source": "fallback" if tier == "unknown" else "needle",+ }+ for mid, tier in MODELS+ ],+ "filed": FILED,}diff --git a/src/spec_bash_policy_conformance.zig b/src/spec_bash_policy_conformance.zignew file mode 100644index 00000000..927cee40--- /dev/null+++ b/src/spec_bash_policy_conformance.zig@@ -0,0 +1,58 @@+//! Impl half of BashPolicy: live isSimple / escapesCwd / readOnlyAllowed.++const std = @import("std");+const policy = @import("harness_policy.zig");++const fixtures_json = @embedFile("spec_bash_policy");++test "spec/bash_policy: seed table matches read_only_seed" {+ const gpa = std.testing.allocator;+ var parsed = try std.json.parseFromSlice(std.json.Value, gpa, fixtures_json, .{});+ defer parsed.deinit();+ const seed = parsed.value.object.get("seed").?.array.items;+ try std.testing.expectEqual(policy.read_only_seed.len, seed.len);+ for (seed, policy.read_only_seed) |sv, live| {+ if (!std.mem.eql(u8, sv.string, live)) {+ std.debug.print("\ncounterexample seed: want={s} got={s}\n", .{ live, sv.string });+ return error.CatalogMismatch;+ }+ }+}++test "spec/bash_policy: live predicates 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, 32), cases.len);+ for (cases) |case_v| {+ const case = case_v.object;+ const cmd = case.get("cmd").?.string;+ const id = case.get("id").?.string;+ const simple = policy.isSimple(cmd);+ const escapes = policy.escapesCwd(cmd);+ const allowed = policy.readOnlyAllowed(cmd);+ const external = policy.readOnlyExternal(cmd);+ if (simple != case.get("simple").?.bool or+ escapes != case.get("escapes").?.bool or+ allowed != case.get("allowed").?.bool or+ external != case.get("external").?.bool)+ {+ std.debug.print(+ "\ncounterexample {s}: simple {}/{} escapes {}/{} allowed {}/{} external {}/{}\n",+ .{+ id,+ case.get("simple").?.bool,+ simple,+ case.get("escapes").?.bool,+ escapes,+ case.get("allowed").?.bool,+ allowed,+ case.get("external").?.bool,+ external,+ },+ );+ return error.CatalogMismatch;+ }+ }+}diff --git a/src/spec_score_conformance.zig b/src/spec_score_conformance.zigindex 6dfce33b..cc708569 100644--- a/src/spec_score_conformance.zig+++ b/src/spec_score_conformance.zig@@ -1,4 +1,5 @@-//! Impl half of the score kernel: stageScore, roleOf/canonicalSlot, normalize.+//! Impl half of the score kernel: stageScore, roleOf/canonicalSlot,+//! normalizeOutboundScore, and the providerClass needle table.const std = @import("std");const scoring = @import("scoring.zig");@@ -31,6 +32,7 @@ test "spec/score: filing gate matches stageScore + roleOf" {defer parsed.deinit();const cases = parsed.value.object.get("cases").?.array.items;try std.testing.expectEqual(@as(usize, 1210), cases.len);+ var filed: usize = 0;for (cases) |case_v| {const case = case_v.object;const id = case.get("id").?.string;@@ -47,7 +49,11 @@ test "spec/score: filing gate matches stageScore + roleOf" {std.debug.print("\ncounterexample {s}: files want={} got={} role want={s} got={s}\n", .{ id, want, got, case.get("role").?.string, slotName(role) });return error.CatalogMismatch;}+ if (want) filed += 1;}+ const want_filed: usize = @intCast(parsed.value.object.get("filed").?.integer);+ try std.testing.expectEqual(want_filed, filed);+ try std.testing.expectEqual(@as(usize, 240), filed);}test "spec/score: canonical slots and titles match the live scan" {@@ -109,3 +115,26 @@ test "spec/score: normalizeOutboundScore matches the scale samples" {}}}++test "spec/score: providerClass needles match; fallback stays unknown" {+ const gpa = std.testing.allocator;+ var parsed = try std.json.parseFromSlice(std.json.Value, gpa, fixtures_json, .{});+ defer parsed.deinit();+ const classes = parsed.value.object.get("classes").?.array.items;+ try std.testing.expectEqual(@as(usize, 16), classes.len);+ for (classes) |cv| {+ const c = cv.object;+ const id = c.get("id").?.string;+ const want = c.get("tier").?.string;+ const source = c.get("source").?.string;+ if (std.mem.eql(u8, source, "fallback")) {+ try std.testing.expectEqualStrings("unknown", want);+ continue;+ }+ const got = scoring.providerClass(id);+ if (!std.mem.eql(u8, got, want)) {+ std.debug.print("\ncounterexample class {s}: want={s} got={s}\n", .{ id, want, got });+ return error.CatalogMismatch;+ }+ }+}diff --git a/src/tool_gates.zig b/src/tool_gates.zigindex 406f29cc..7c9cc0e0 100644--- a/src/tool_gates.zig+++ b/src/tool_gates.zig@@ -100,6 +100,8 @@ test { // the served catalogs' wire-compatibility guard (an unreferenced module'_ = @import("spec_path_confine_conformance.zig");_ = @import("spec_shape_conformance.zig");_ = @import("spec_score_conformance.zig");+ _ = @import("spec_bash_policy_conformance.zig");+ _ = @import("grok_spec_conformance.zig");}test "#352: an optional tool is advertised only while its flag is set; other names are unaffected" {