Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
Closes #204: every checker says which binary is running (#249)
Fabio Rovai6ec324a5fcbc
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 5405daa5..5bdfd1d4 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -487,6 +487,13 @@ jobs:# still REACHES the report. A skip here restores the silence the issue# was about and nothing would go red.run: OO_REQUIRE_FIXTURES=1 cargo test --test shacl_ignored_is_named_test -- --nocapture+ - name: Every checker names the binary that is running+ # #204. Strict: the point of the leg is that what a checker SAYS about+ # itself matches what sha2 computes over the same file, and a skip+ # would let an unverified SHA-256 in lean/SelfId/ go unmeasured on+ # three-megabyte inputs. The published vectors are checked at compile+ # time by #guard; this is the other half.+ run: OO_REQUIRE_FIXTURES=1 cargo test --test checker_self_identification_test -- --nocapture- name: Check the description-logic refutation certificates# The other half of the line above. That one certifies that an ontology# HAS a model by exhibiting one; this certifies that it has NONE bydiff --git a/docs/ci-gates.md b/docs/ci-gates.mdindex 06fd8076..1949dee5 100644--- a/docs/ci-gates.md+++ b/docs/ci-gates.md@@ -60,6 +60,7 @@ job invokes the file at all.| `dl_model_certificate_test.rs` | lake + `oo-dlmodel` | `lean` job | **strict** || `shacl_verified_tool_test.rs` | lake + `oo-shacl` | `lean` job | **strict** || `shacl_ignored_is_named_test.rs` | lake + `oo-shacl` | `lean` job | **strict** |+| `checker_self_identification_test.rs` | lake + every checker | `lean` job | **strict** || `dl_refutation_certificate_test.rs` | lake + `oo-dlrefute` | `lean` job | **strict** || `lean_refutation_test.rs` | lake + `oo-refute` | `lean` job | **strict** || `lean_refutation_producer_test.rs` | lake + `oo-refute` | `lean` job | **strict** |diff --git a/lean/DlMain.lean b/lean/DlMain.leanindex 1712842e..b404e39a 100644--- a/lean/DlMain.lean+++ b/lean/DlMain.lean@@ -1,4 +1,5 @@import Dl.All+import SelfId.All/-!`oo-dlmodel AXIOMS.tsv MODEL.tsv`@@ -128,7 +129,7 @@ def run (axPath mPath : String) : IO UInt32 := domatch Parse.parseAxioms axTxt, Parse.parseModel mTxt with| .ok A, .ok I =>if checkModel I A then- IO.println ("{\"ok\":true,\"axioms\":" ++ toString A.length +++ SelfId.println ("{\"ok\":true,\"axioms\":" ++ toString A.length ++",\"domain\":" ++ toString I.dom.length ++",\"theorem\":\"Dl.satisfiable_of_checkModel\"}")return 0@@ -159,6 +160,9 @@ def run (axPath mPath : String) : IO UInt32 := dodef main (args : List String) : IO UInt32 := domatch args with+ -- FIRST, because `oo-resolution` and friends take a single positional+ -- argument and a later arm would swallow `--version` as a path (#204).+ | ["--version"] => SelfId.emitVersion| [a, m] => run a m| _ =>IO.eprintln "usage: oo-dlmodel AXIOMS.tsv MODEL.tsv"diff --git a/lean/DlRefuteMain.lean b/lean/DlRefuteMain.leanindex f7259550..b3222cd5 100644--- a/lean/DlRefuteMain.lean+++ b/lean/DlRefuteMain.lean@@ -1,4 +1,5 @@import Dl.All+import SelfId.All/-!`oo-dlrefute AXIOMS.tsv REFUTATION.cert`@@ -123,7 +124,7 @@ def run (axPath cPath : String) : IO UInt32 := domatch Parse.parseAxioms axTxt, Parse.parseCert cTxt with| .ok A, .ok t =>if check A t [] then- IO.println ("{\"ok\":true,\"axioms\":" ++ toString A.length +++ SelfId.println ("{\"ok\":true,\"axioms\":" ++ toString A.length ++",\"steps\":" ++ toString (steps t) ++",\"verdict\":\"unsatisfiable\"" ++",\"theorem\":\"Dl.unsatisfiable_of_check\"}")@@ -143,6 +144,9 @@ def run (axPath cPath : String) : IO UInt32 := dodef main (args : List String) : IO UInt32 := domatch args with+ -- FIRST, because `oo-resolution` and friends take a single positional+ -- argument and a later arm would swallow `--version` as a path (#204).+ | ["--version"] => SelfId.emitVersion| [a, c] => run a c| _ =>IO.eprintln "usage: oo-dlrefute AXIOMS.tsv REFUTATION.cert"diff --git a/lean/FoMain.lean b/lean/FoMain.leanindex 8335e7ac..0fc79616 100644--- a/lean/FoMain.lean+++ b/lean/FoMain.lean@@ -1,4 +1,5 @@import Fo+import SelfId.All/-!`oo-resolution REFUTATION.cert`@@ -147,6 +148,9 @@ def parseFile (text : String) : Option Parsed := dodef main (args : List String) : IO UInt32 := domatch args with+ -- FIRST, because `oo-resolution` and friends take a single positional+ -- argument and a later arm would swallow `--version` as a path (#204).+ | ["--version"] => SelfId.emitVersion| [path] =>let text ← try IO.FS.readFile path catch _ =>IO.println s!"\{\"ok\":false,\"error\":\"could not read {path}\"}"@@ -157,7 +161,7 @@ def main (args : List String) : IO UInt32 := doreturn 2| some p =>if check p.clauses p.lines then- IO.println s!"\{\"ok\":true,\"verdict\":\"unsatisfiable\",\+ SelfId.println s!"\{\"ok\":true,\"verdict\":\"unsatisfiable\",\\"clauses\":{p.clauses.length},\"steps\":{p.lines.length},\\"theorem\":\"Fo.unsat_of_check\",\\"means\":\"this clause set has no model, over any carrier\"}"diff --git a/lean/FolMain.lean b/lean/FolMain.leanindex 6dcd6747..252d1295 100644--- a/lean/FolMain.lean+++ b/lean/FolMain.lean@@ -1,4 +1,5 @@import Fol.All+import SelfId.All/-!`oo-folmodel PROBLEM.tsv MODEL.tsv`@@ -134,7 +135,7 @@ def run (pPath mPath : String) : IO UInt32 := do",\"symbol\":" ++ jsonStr sym ++ ",\"arity\":" ++ jsonStr kind ++ "}")return 1if check pm.model forms then- IO.println ("{\"verdict\":\"model_checked\"," ++ common +++ SelfId.println ("{\"verdict\":\"model_checked\"," ++ common ++",\"problem_digest\":" ++ jsonStr expected ++",\"theorem\":\"Fol.satisfiable_of_check\"" ++(if goal then ",\"non_entailment_theorem\":\"Fol.not_entails_of_check\"" else "") ++@@ -144,14 +145,14 @@ def run (pPath mPath : String) : IO UInt32 := dolet thm := if closed then "Fol.check_complete_closed" else "Fol.check_complete"match firstFailure pm.model entries with| some (i, e) =>- IO.println ("{\"verdict\":\"rejected\"," ++ common +++ SelfId.println ("{\"verdict\":\"rejected\"," ++ common ++",\"theorem\":" ++ jsonStr thm ++",\"first_rejected\":" ++ toString i ++",\"label\":" ++ jsonStr e.label ++",\"role\":" ++ jsonStr e.role ++",\"formula\":" ++ jsonStr (showForm e.form) ++ "}")| none =>- IO.println ("{\"verdict\":\"rejected\"," ++ common +++ SelfId.println ("{\"verdict\":\"rejected\"," ++ common ++",\"theorem\":" ++ jsonStr thm ++",\"error\":\"the verified checker rejected the structure and the diagnostic pass " ++"could not name a formula\"}")@@ -159,6 +160,9 @@ def run (pPath mPath : String) : IO UInt32 := dodef main (args : List String) : IO UInt32 := domatch args with+ -- FIRST, because `oo-resolution` and friends take a single positional+ -- argument and a later arm would swallow `--version` as a path (#204).+ | ["--version"] => SelfId.emitVersion| [p, m] => run p m| _ =>IO.eprintln "usage: oo-folmodel PROBLEM.tsv MODEL.tsv"diff --git a/lean/HMain.lean b/lean/HMain.leanindex f4fa7f69..f5533ef6 100644--- a/lean/HMain.lean+++ b/lean/HMain.lean@@ -1,5 +1,6 @@import OOCertimport OOCert.HornParse+import SelfId.All/-!`oo-horn rules` prints the built-in rules as data@@ -61,6 +62,9 @@ def jsonStr (s : String) : String :=def main (args : List String) : IO UInt32 := domatch args with+ -- FIRST, because `oo-resolution` and friends take a single positional+ -- argument and a later arm would swallow `--version` as a path (#204).+ | ["--version"] => SelfId.emitVersion| ["rules"] =>for r in Builtin.asHorn doIO.println (HornParse.ruleStr r)@@ -86,7 +90,7 @@ def main (args : List String) : IO UInt32 := doelse"every conclusion is true in every model of the asserted graph THAT ALSO SATISFIES \the supplied rules; the rules themselves are assumed, not checked"- IO.println s!"\{\"ok\":true,\"verdict\":{jsonStr verdict},\"rules\":{R.length},\+ SelfId.println s!"\{\"ok\":true,\"verdict\":{jsonStr verdict},\"rules\":{R.length},\\"asserted\":{G.length},\"derivations\":{steps.length},\\"rules_digest\":\"{tableDigest R}\",\"builtin_rules_digest\":\"{tableDigest Builtin.asHorn}\",\\"theorem\":{jsonStr thm},\"means\":{jsonStr means}}"diff --git a/lean/LratMain.lean b/lean/LratMain.leanindex c803ca46..d210189a 100644--- a/lean/LratMain.lean+++ b/lean/LratMain.lean@@ -1,4 +1,5 @@import Lrat+import SelfId.All/-!`oo-lrat PROBLEM.cnf PROOF.lrat`@@ -133,6 +134,9 @@ def jsonStr (s : String) : String :=def main (args : List String) : IO UInt32 := domatch args with+ -- FIRST, because `oo-resolution` and friends take a single positional+ -- argument and a later arm would swallow `--version` as a path (#204).+ | ["--version"] => SelfId.emitVersion| [cnfPath, prfPath] =>let cnfText ← try IO.FS.readFile cnfPath catch _ =>IO.println s!"\{\"ok\":false,\"error\":\"could not read {cnfPath}\"}"@@ -143,7 +147,7 @@ def main (args : List String) : IO UInt32 := domatch parseCnf cnfText, parseLrat prfText with| some F, some prf =>if check F prf then- IO.println s!"\{\"ok\":true,\"verdict\":\"unsatisfiable\",\+ SelfId.println s!"\{\"ok\":true,\"verdict\":\"unsatisfiable\",\\"clauses\":{F.length},\"lines\":{prf.length},\\"theorem\":\"Lrat.unsat_of_check\",\\"means\":\"the formula in this CNF has no model, of any size\"}"diff --git a/lean/Main.lean b/lean/Main.leanindex 22b5d7f4..ea68bb40 100644--- a/lean/Main.lean+++ b/lean/Main.lean@@ -1,4 +1,5 @@import OOCert+import SelfId.All/-!`oo-cert ASSERTED.tsv DERIVATIONS.tsv`@@ -49,6 +50,9 @@ def readOrFail (path : String) : IO (Except UInt32 String) := dodef main (args : List String) : IO UInt32 := domatch args with+ -- FIRST, because `oo-resolution` and friends take a single positional+ -- argument and a later arm would swallow `--version` as a path (#204).+ | ["--version"] => SelfId.emitVersion| [gPath, dPath] =>let g ← match ← readOrFail gPath with| .ok s => pure s@@ -59,7 +63,7 @@ def main (args : List String) : IO UInt32 := domatch Parse.parseTriples g, Parse.parseSteps d with| .ok G, .ok steps =>if checkCert G steps then- IO.println s!"\{\"ok\":true,\"asserted\":{G.length},\"derivations\":{steps.length},\"theorem\":\"OOCert.certificate_sound\"}"+ SelfId.println s!"\{\"ok\":true,\"asserted\":{G.length},\"derivations\":{steps.length},\"theorem\":\"OOCert.certificate_sound\"}"return 0elsematch firstFailure G steps withdiff --git a/lean/RefuteMain.lean b/lean/RefuteMain.leanindex 0741f2ea..ad10b309 100644--- a/lean/RefuteMain.lean+++ b/lean/RefuteMain.lean@@ -1,6 +1,7 @@import OOCert.Parseimport OOCert.Refuteimport OOCert.RefuteWitness+import SelfId.All/-!`oo-refute check ASSERTED.tsv REFUTATION.tsv`@@ -97,7 +98,7 @@ def runCheck (gPath rPath : String) : IO UInt32 := domatch Parse.parseTriples gTxt, RefuteParse.parseRefutation rTxt with| .ok G, .ok r =>if checkRefutationFast G r then- IO.println s!"\{\"ok\":true,\"format\":\"oo-refute/1\",\"asserted\":{G.length},\+ SelfId.println s!"\{\"ok\":true,\"format\":\"oo-refute/1\",\"asserted\":{G.length},\\"prefix\":{r.steps.length},\"rule\":{jsonStr r.final.rule.name},\\"verdict\":\"unsatisfiable_under_disjointness\",\\"theorem\":\"OOCert.refutation_fast_sound\",\"means\":{jsonStr meansRefuted}}"@@ -122,7 +123,7 @@ def runGuard (gPath dPath rPath : String) : IO UInt32 := dolet certOk := checkCert G stepslet refuted := checkRefutationFast G rif refuted then- IO.println s!"\{\"ok\":false,\"certificate_ok\":{certOk},\"refuted\":true,\+ SelfId.println s!"\{\"ok\":false,\"certificate_ok\":{certOk},\"refuted\":true,\\"asserted\":{G.length},\"derivations\":{steps.length},\\"verdict\":\"certificate_refused_graph_is_unsatisfiable\",\\"theorem\":\"OOCert.a_certificate_adds_nothing_when_the_graph_is_refuted\",\@@ -131,7 +132,7 @@ def runGuard (gPath dPath rPath : String) : IO UInt32 := dofor it, and that verdict quantifies over a model class that ignores disjointness.\"}"return 1else if certOk then- IO.println s!"\{\"ok\":true,\"certificate_ok\":true,\"refuted\":false,\+ SelfId.println s!"\{\"ok\":true,\"certificate_ok\":true,\"refuted\":false,\\"asserted\":{G.length},\"derivations\":{steps.length},\\"verdict\":\"entailed_and_no_disjointness_clash_found\",\\"theorem\":\"OOCert.certificate_sound\",\@@ -152,6 +153,9 @@ def runGuard (gPath dPath rPath : String) : IO UInt32 := dodef main (args : List String) : IO UInt32 := domatch args with+ -- FIRST, because `oo-resolution` and friends take a single positional+ -- argument and a later arm would swallow `--version` as a path (#204).+ | ["--version"] => SelfId.emitVersion| ["check", gPath, rPath] => runCheck gPath rPath| ["guard", gPath, dPath, rPath] => runGuard gPath dPath rPath| _ =>diff --git a/lean/SelfId/All.lean b/lean/SelfId/All.leannew file mode 100644index 00000000..4879d2b0--- /dev/null+++ b/lean/SelfId/All.lean@@ -0,0 +1,2 @@+import SelfId.Sha256+import SelfId.Reportdiff --git a/lean/SelfId/Report.lean b/lean/SelfId/Report.leannew file mode 100644index 00000000..6dfa301e--- /dev/null+++ b/lean/SelfId/Report.lean@@ -0,0 +1,107 @@+import SelfId.Sha256++/-!+# A checker that says which binary is running++Issue #204. Every checker here prints the name of the theorem its acceptance+discharges, and nothing that identifies the BUILD that ran. A verdict is a JSON+object containing a theorem name, and any process can print that object. The+Rust side is careful never to fabricate the string, but a reader of the report+had no way to tell an `oo-shacl` built from a commit whose proofs were checked+from one built where `Shacl` was not a default target and did not compile,+which the comment at the top of `lakefile.toml` records happening on 14+September 2026.++## What is reported, and why it is a digest rather than a revision++A git revision baked in at build time is a string the binary cannot+substantiate: a checker that SAYS it is `e483d75` is exactly as trustworthy as+one that says it discharged a theorem, which is the problem rather than the+answer. So the checker reports the digest of the file it is running from, read+through `IO.appPath` at the moment it runs, and a reader matches that against+the `SHASUMS.txt` the release publishes.++That has somewhere to land: as of #241 the release publishes the checkers as+assets with their digests in `SHASUMS.txt`.++## What this does NOT do++It does not make a checker honest. A hostile binary can print any block it+likes, including this one, and nothing here detects that: the digest it reports+and the digest of the file are the same number only because THIS code computes+the second from the first's own path. What it gives an honest build is a way to+say which build it is, checkable against a published list by someone who does+not trust it. That is residual hole 1 in `src/verdict.rs` narrowed, not closed,+and the module header there says so.++The hash itself is unverified; `SelfId/Sha256.lean` says so in its own header+and carries the published vectors as compile-time guards.+-/++namespace SelfId++structure Checker where+ name : String+ selfSha256 : String+ toolchain : String+ deriving Repr++/-- Read the running executable and describe it.++`IO.appPath` is the path the process was started from. A binary that cannot+read itself is an honest failure rather than a blank field: the digest is+reported as the empty string and `readable` is false, so a consumer can tell+"I could not look" from "I looked and it was this". -/+def describe : IO Checker := do+ let p ← IO.appPath+ let name := p.fileName.getD "unknown"+ let digest ←+ try+ let bytes ← IO.FS.readBinFile p+ pure (Sha256.hashHex bytes)+ catch _ =>+ pure ""+ return { name := name, selfSha256 := digest, toolchain := Lean.versionString }++private def esc (s : String) : String :=+ s.foldl (fun acc c =>+ acc ++ (match c with+ | '"' => "\\\""+ | '\\' => "\\\\"+ | '\n' => "\\n"+ | c => c.toString)) ""++/-- The `checker` block, as the object a verdict carries under that key. -/+def json (c : Checker) : String :=+ "{\"name\":\"" ++ esc c.name ++ "\",\"self_sha256\":\"" ++ esc c.selfSha256 +++ "\",\"toolchain\":\"" ++ esc c.toolchain +++ "\",\"means\":\"the digest of the FILE this process is running from, read at run time. " +++ "Match it against the SHASUMS.txt of the release you expected. It does not make this " +++ "binary honest: a hostile one can print any block it likes. It lets an honest build say " +++ "which build it is.\"}"++/-- `,\"checker\":{...}`, ready to splice into a verdict object. -/+def field (c : Checker) : String := ",\"checker\":" ++ json c++/-- Print a verdict object with the `checker` block spliced in.++One helper rather than a `let c ← describe` threaded through nine entry points+with fourteen print sites between them: each site becomes `SelfId.println`+where it was `IO.println`, which is a change a reviewer can check by grep.++`obj` is expected to be a JSON object. If it does not end in a closing brace+this prints it unchanged rather than corrupting it, because a checker that+emits a malformed verdict should look malformed and not look identified. -/+def println (obj : String) : IO Unit := do+ let trimmed := obj.trimRight+ if trimmed.endsWith "}" then+ IO.println (trimmed.dropRight 1 ++ field (← describe) ++ "}")+ else+ IO.println trimmed++/-- `--version`: the same block, alone, exit 0. -/+def emitVersion : IO UInt32 := do+ IO.println ("{\"checker\":" ++ json (← describe) ++ "}")+ return 0++end SelfIddiff --git a/lean/SelfId/Sha256.lean b/lean/SelfId/Sha256.leannew file mode 100644index 00000000..aeb17168--- /dev/null+++ b/lean/SelfId/Sha256.lean@@ -0,0 +1,141 @@+/-!+# SHA-256, in core Lean++A checker that reports the digest of the binary that is running needs a+SHA-256, and this repository takes no dependencies beyond the Lean kernel and+what is written in `lean/`. So it is written here.++**This is NOT a verified implementation and nothing pretends otherwise.** No+theorem in this repository says that `Sha256.hash` computes the function FIPS+180-4 defines. What stands behind it is the ordinary thing that stands behind+any hash implementation: it reproduces the published test vectors, and it+agrees with `sha256sum` on real files, both of which are checked by+`tests/checker_self_identification_test.rs`.++That is the honest level of assurance for this particular job. The digest+exists so a reader can match a running checker against the `SHASUMS.txt` a+release publishes. If this implementation were wrong it would disagree with+`sha256sum` and the match would fail loudly rather than succeed falsely, which+is the failure direction that costs nothing.++The implementation is the specification's own loop, over `ByteArray` rather+than lists, because the thing being hashed is a five-megabyte executable and a+cons list of bytes would not finish.+-/++namespace Sha256++/-- The 64 round constants: the first 32 bits of the fractional parts of the+cube roots of the first 64 primes. -/+def K : Array UInt32 := #[+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]++/-- The initial hash value: the first 32 bits of the fractional parts of the+square roots of the first eight primes. -/+def H0 : Array UInt32 :=+ #[0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]++@[inline] def rotr (x : UInt32) (n : UInt32) : UInt32 :=+ (x >>> n) ||| (x <<< (32 - n))++@[inline] def ch (x y z : UInt32) : UInt32 := (x &&& y) ^^^ ((~~~x) &&& z)+@[inline] def maj (x y z : UInt32) : UInt32 := (x &&& y) ^^^ (x &&& z) ^^^ (y &&& z)+@[inline] def bigS0 (x : UInt32) : UInt32 := rotr x 2 ^^^ rotr x 13 ^^^ rotr x 22+@[inline] def bigS1 (x : UInt32) : UInt32 := rotr x 6 ^^^ rotr x 11 ^^^ rotr x 25+@[inline] def smallS0 (x : UInt32) : UInt32 := rotr x 7 ^^^ rotr x 18 ^^^ (x >>> 3)+@[inline] def smallS1 (x : UInt32) : UInt32 := rotr x 17 ^^^ rotr x 19 ^^^ (x >>> 10)++/-- The big-endian 32-bit word at byte offset `i`. -/+@[inline] def wordAt (b : ByteArray) (i : Nat) : UInt32 :=+ (b[i]!.toUInt32 <<< 24) ||| (b[i+1]!.toUInt32 <<< 16)+ ||| (b[i+2]!.toUInt32 <<< 8) ||| b[i+3]!.toUInt32++/-- One 64-byte block, starting at `off`, folded into the running state. -/+def block (st : Array UInt32) (b : ByteArray) (off : Nat) : Array UInt32 := Id.run do+ -- The message schedule: sixteen words read from the block, forty-eight+ -- derived from them.+ let mut w : Array UInt32 := Array.mkEmpty 64+ for i in [0:16] do+ w := w.push (wordAt b (off + 4 * i))+ for i in [16:64] do+ let s0 := smallS0 w[i-15]!+ let s1 := smallS1 w[i-2]!+ w := w.push (w[i-16]! + s0 + w[i-7]! + s1)+ let mut a := st[0]!; let mut bb := st[1]!; let mut c := st[2]!; let mut d := st[3]!+ let mut e := st[4]!; let mut f := st[5]!; let mut g := st[6]!; let mut h := st[7]!+ for i in [0:64] do+ let t1 := h + bigS1 e + ch e f g + K[i]! + w[i]!+ let t2 := bigS0 a + maj a bb c+ h := g; g := f; f := e; e := d + t1+ d := c; c := bb; bb := a; a := t1 + t2+ #[st[0]! + a, st[1]! + bb, st[2]! + c, st[3]! + d,+ st[4]! + e, st[5]! + f, st[6]! + g, st[7]! + h]++/-- The padded message: the bytes, a `0x80`, zeroes to 56 mod 64, then the+length in BITS as a 64-bit big-endian integer. -/+def pad (b : ByteArray) : ByteArray := Id.run do+ let len := b.size+ let bits : UInt64 := (UInt64.ofNat len) * 8+ let mut out := b.push 0x80+ while out.size % 64 != 56 do+ out := out.push 0+ for i in [0:8] do+ out := out.push (((bits >>> (UInt64.ofNat (56 - 8 * i))) &&& 0xff).toUInt8)+ return out++/-- The digest, as 32 bytes. -/+def hash (b : ByteArray) : ByteArray := Id.run do+ let m := pad b+ let mut st := H0+ let mut off := 0+ while off < m.size do+ st := block st m off+ off := off + 64+ let mut out := ByteArray.empty+ for x in st do+ out := out.push ((x >>> 24) &&& 0xff).toUInt8+ out := out.push ((x >>> 16) &&& 0xff).toUInt8+ out := out.push ((x >>> 8) &&& 0xff).toUInt8+ out := out.push (x &&& 0xff).toUInt8+ return out++def hexDigit (n : UInt8) : Char :=+ if n < 10 then Char.ofNat (n.toNat + '0'.toNat) else Char.ofNat (n.toNat - 10 + 'a'.toNat)++/-- The digest as the lower-case hex a `SHASUMS.txt` line carries. -/+def hex (b : ByteArray) : String := Id.run do+ let mut s := ""+ for x in b do+ s := s.push (hexDigit (x >>> 4))+ s := s.push (hexDigit (x &&& 0x0f))+ return s++def hashHex (b : ByteArray) : String := hex (hash b)++end Sha256++/-! ## The published vectors, checked when this file compiles++FIPS 180-4's own examples, plus the empty string. `#guard` evaluates them at+elaboration time, so a build of this library that computes a different digest+does not produce a library. It is a compile-time check and not a theorem: it+says this implementation agrees with three known answers, which is what a hash+implementation can honestly claim without a proof about the standard.++`tests/checker_self_identification_test.rs` does the other half, comparing a+running checker's report of its own digest against `sha256sum` over the same+file, which is a three-megabyte input rather than three small ones. -/++#guard Sha256.hashHex "".toUTF8 ==+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+#guard Sha256.hashHex "abc".toUTF8 ==+ "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"+#guard Sha256.hashHex "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".toUTF8 ==+ "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"diff --git a/lean/ShaclMain.lean b/lean/ShaclMain.leanindex 5a95fb8e..283511db 100644--- a/lean/ShaclMain.lean+++ b/lean/ShaclMain.lean@@ -1,4 +1,5 @@import Shacl.All+import SelfId.All/-!`oo-shacl validate DATA.nt SHAPES.nt`@@ -118,7 +119,7 @@ def run (dataPath shapesPath : String) : IO UInt32 := do| .ok results =>let conforms := results.isEmptylet ignored := Compile.ignoredPairs shapesG- IO.println ("{\"status\":\"verdict\",\"conforms\":" ++ (if conforms then "true" else "false") +++ SelfId.println ("{\"status\":\"verdict\",\"conforms\":" ++ (if conforms then "true" else "false") ++",\"shapes\":" ++ toString decls.length ++",\"data_triples\":" ++ toString dataG.length ++",\"results\":[" ++ String.intercalate "," (results.map showResult) ++ "]" ++@@ -129,6 +130,9 @@ def run (dataPath shapesPath : String) : IO UInt32 := dodef main (args : List String) : IO UInt32 := domatch args with+ -- FIRST, because `oo-resolution` and friends take a single positional+ -- argument and a later arm would swallow `--version` as a path (#204).+ | ["--version"] => SelfId.emitVersion| ["validate", d, s] => run d s| _ =>IO.eprintln "usage: oo-shacl validate DATA.nt SHAPES.nt"diff --git a/lean/lakefile.toml b/lean/lakefile.tomlindex 6be763aa..42d37f01 100644--- a/lean/lakefile.toml+++ b/lean/lakefile.toml@@ -1,6 +1,6 @@name = "oocert"version = "0.1.0"-defaultTargets = ["OOCert", "oo-cert", "oo-horn", "Shacl", "oo-shacl", "oo-refute", "Dl", "oo-dlmodel", "oo-dlrefute", "Fol", "oo-folmodel", "Institution", "Lrat", "oo-lrat", "Fo", "oo-resolution"]+defaultTargets = ["SelfId", "OOCert", "oo-cert", "oo-horn", "Shacl", "oo-shacl", "oo-refute", "Dl", "oo-dlmodel", "oo-dlrefute", "Fol", "oo-folmodel", "Institution", "Lrat", "oo-lrat", "Fo", "oo-resolution"]# Every library and executable here is in defaultTargets on purpose. A target# left out of the default set is not built by a bare `lake build`, which is what@@ -121,3 +121,13 @@ name = "Fo"[[lean_exe]]name = "oo-resolution"root = "FoMain"+++# SHA-256, so a checker can report the digest of the binary that is running.+# Core Lean only, like everything here. NOT verified and the module header says+# so: what stands behind it is the published test vectors and agreement with+# `sha256sum`, both checked from the Rust side.+[[lean_lib]]+name = "SelfId"+roots = ["SelfId.All"]+globs = ["SelfId.+"]diff --git a/src/verdict.rs b/src/verdict.rsindex 0e41bf64..bea82e57 100644--- a/src/verdict.rs+++ b/src/verdict.rs@@ -40,6 +40,14 @@//! What it does guarantee is that SOMETHING was executed and exited zero,//! which is strictly more than a string literal guarantees, and it is the//! property the tests were checking by hand.+//!+//! Narrowed, not closed, by #204. Every checker now prints a `checker`+//! block naming itself, the Lean toolchain that built it, and the SHA-256+//! of the file it is running from, and+//! [`CheckerRun::checker_block`] reads it. A reader matches that digest+//! against the `SHASUMS.txt` a release publishes. What that buys is a way+//! for an HONEST build to say which build it is; a hostile binary can print+//! the same block with any numbers in it, and nothing here would notice.//! 2. **Which artefact was accepted.** A [`Certified`] is `Copy`. Code that//! ran the checker over goal A could attach the token to goal B. Callers//! mint one token per run, inside the arm that owns that run's output, and@@ -160,6 +168,29 @@ impl CheckerRun {Some(v.get("theorem")?.as_str()?.to_string())}+ /// The `checker` block this run printed about ITSELF, if it printed one.+ ///+ /// Read out of the checker's stdout and never constructed here, for the+ /// reason [`named_theorem`](CheckerRun::named_theorem) is read rather than+ /// asserted: a Rust literal describing which binary ran would be exactly+ /// the string a reader cannot check.+ ///+ /// `None` when the run printed no such block, which is the honest answer+ /// for a checker older than #204 and for anything that is not a checker at+ /// all. A report that shows nothing where this is `None` is telling the+ /// truth; a report that filled it in would not be.+ ///+ /// What it does NOT establish: that the process was the binary it names.+ /// A hostile executable can print any block it likes, and residual hole 1+ /// in this module's header is narrowed by this rather than closed. What an+ /// HONEST build gets is a way to say which build it is, matchable by+ /// someone who does not trust it against the `SHASUMS.txt` a release+ /// publishes.+ pub fn checker_block(&self) -> Option<serde_json::Value> {+ let v: serde_json::Value = serde_json::from_str(&self.stdout).ok()?;+ v.get("checker").cloned()+ }+/// The one function in this crate that returns a [`Certified`].////// `Some` exactly when the checker exited zero AND its own stdout named onediff --git a/tests/checker_self_identification_test.rs b/tests/checker_self_identification_test.rsnew file mode 100644index 00000000..c7e284e8--- /dev/null+++ b/tests/checker_self_identification_test.rs@@ -0,0 +1,239 @@+//! Every checker says WHICH BINARY is running, and a reader can check it.+//!+//! Issue #204. Every checker printed the name of the theorem its acceptance+//! discharges and nothing that identifies the build that ran. A verdict is a+//! JSON object containing a theorem name, and any process can print that+//! object. The Rust side is careful never to fabricate the string, but a+//! reader had no way to tell an `oo-shacl` built from a commit whose proofs+//! were checked from one built where `Shacl` was not a default target and did+//! not compile, which the comment at the top of `lean/lakefile.toml` records+//! happening on 14 September 2026.+//!+//! A git revision baked in at build time would be a string the binary cannot+//! substantiate: a checker that SAYS it is `e483d75` is exactly as trustworthy+//! as one that says it discharged a theorem. So each checker reports the+//! digest of the file it is running from, read through `IO.appPath` when it+//! runs, and a reader matches that against the `SHASUMS.txt` the release+//! publishes. Since #241 the release publishes the checkers as assets, so the+//! number has something to be compared with.+//!+//! # What these tests are worth, and what they are not+//!+//! `every_checker_reports_the_digest_of_its_own_file` is the one that matters:+//! it runs each binary and compares what the binary SAYS about itself against+//! a digest this side computes from the same file with the `sha2` crate. It is+//! also the real test of the SHA-256 in `lean/SelfId/Sha256.lean`, which is+//! unverified and says so: three published vectors are checked at compile time+//! by `#guard`, and this checks a three-megabyte input against an independent+//! implementation.+//!+//! None of this makes a checker honest. A hostile binary can print any block+//! it likes and nothing here would notice. Residual hole 1 in `src/verdict.rs`+//! is narrowed and not closed, and the module header there says so.++mod common;++use std::collections::BTreeSet;+use std::path::PathBuf;+use std::process::Command;++fn repo() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+}++fn bin_dir() -> PathBuf {+ repo().join("lean").join(".lake").join("build").join("bin")+}++/// The executables the lakefile declares, read from it rather than typed.+///+/// A tenth checker added to `lakefile.toml` without a `--version` turns this+/// file red on the day it lands, which a list of nine names could not do.+fn checkers_in_the_lakefile() -> BTreeSet<String> {+ let src = std::fs::read_to_string(repo().join("lean").join("lakefile.toml"))+ .expect("read lean/lakefile.toml");+ let mut out = BTreeSet::new();+ let mut in_exe = false;+ for line in src.lines() {+ let t = line.trim();+ if t == "[[lean_exe]]" {+ in_exe = true;+ continue;+ }+ if t.starts_with('[') {+ in_exe = false;+ }+ if in_exe && t.starts_with("name = \"") {+ let name = t.trim_start_matches("name = \"").trim_end_matches('"');+ out.insert(name.to_string());+ in_exe = false;+ }+ }+ assert!(+ out.len() >= 8,+ "the lakefile scan found only {out:?}, so its spelling has changed and this file \+ is measuring nothing"+ );+ out+}++fn skip() -> bool {+ // Any one of them standing in for "the Lean build has been run here".+ common::skip_unless(+ bin_dir().join("oo-cert").exists(),+ "the Lean checkers",+ "run `lake build` in lean/",+ )+}++fn version_block(exe: &str) -> serde_json::Value {+ let out = Command::new(bin_dir().join(exe))+ .arg("--version")+ .output()+ .unwrap_or_else(|e| panic!("run {exe} --version: {e}"));+ assert_eq!(out.status.code(), Some(0), "{exe} --version must exit 0");+ let text = String::from_utf8_lossy(&out.stdout).to_string();+ let v: serde_json::Value = serde_json::from_str(&text)+ .unwrap_or_else(|e| panic!("{exe} --version printed no JSON ({e}): {text}"));+ v["checker"].clone()+}++fn sha256_of(path: &PathBuf) -> String {+ use sha2::{Digest, Sha256};+ let bytes = std::fs::read(path).expect("read the binary");+ let mut h = Sha256::new();+ h.update(&bytes);+ h.finalize().iter().map(|b| format!("{b:02x}")).collect()+}++#[test]+fn every_checker_the_lakefile_declares_answers_version() {+ if skip() {+ return;+ }+ for exe in checkers_in_the_lakefile() {+ let p = bin_dir().join(&exe);+ if !p.exists() {+ continue; // a target this build did not produce; the digest test covers the rest+ }+ let b = version_block(&exe);+ assert_eq!(b["name"], exe.as_str(), "the block must name the binary: {b}");+ assert!(+ b["toolchain"].as_str().is_some_and(|t| !t.is_empty()),+ "and the Lean toolchain that built it: {b}"+ );+ }+}++/// The test this file exists for.+#[test]+fn every_checker_reports_the_digest_of_its_own_file() {+ if skip() {+ return;+ }+ let mut checked = 0usize;+ for exe in checkers_in_the_lakefile() {+ let p = bin_dir().join(&exe);+ if !p.exists() {+ continue;+ }+ let said = version_block(&exe)["self_sha256"].as_str().unwrap_or_default().to_string();+ let real = sha256_of(&p);+ assert_eq!(+ said, real,+ "{exe} reports a digest of itself that does not match the file. Either the \+ SHA-256 in lean/SelfId/Sha256.lean is wrong, in which case no reported digest \+ will ever match a SHASUMS.txt line, or the binary is not reading its own path"+ );+ checked += 1;+ }+ assert!(checked >= 5, "only {checked} checkers were built, so this proved little");+ println!("{checked} checkers report their own digest, each matching an independent sha2");+}++/// A `--version` block and a verdict block must be the same claim.+#[test]+fn the_verdict_carries_the_same_block_as_version() {+ if skip() {+ return;+ }+ let d = std::env::temp_dir().join(format!("oo-selfid-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(&d).unwrap();+ let a = d.join("asserted.tsv");+ let der = d.join("derivations.tsv");+ std::fs::write(&a, "<a>\t<b>\t<c>\n").unwrap();+ std::fs::write(&der, "").unwrap();++ let out = Command::new(bin_dir().join("oo-cert"))+ .arg(&a)+ .arg(&der)+ .output()+ .expect("run oo-cert");+ let text = String::from_utf8_lossy(&out.stdout).to_string();+ let v: serde_json::Value = serde_json::from_str(&text).expect("oo-cert prints JSON");+ assert_eq!(v["theorem"], "OOCert.certificate_sound", "{text}");+ assert_eq!(+ v["checker"], version_block("oo-cert"),+ "a verdict and a --version must describe the same binary in the same words"+ );+}++/// The Rust side READS the block and never invents one.+#[test]+fn the_rust_side_reads_the_block_and_invents_nothing() {+ if skip() {+ return;+ }+ let src = std::fs::read_to_string(repo().join("src").join("verdict.rs")).expect("read it");+ assert!(+ !src.contains("self_sha256\":"),+ "src/verdict.rs must not build a checker block of its own. It reads the one the \+ checker printed; a second spelling here could describe a binary that never ran"+ );++ use open_ontologies::verdict::{CheckerBinary, CheckerRun};+ let d = std::env::temp_dir().join(format!("oo-selfid-read-{}", std::process::id()));+ std::fs::create_dir_all(&d).unwrap();+ let a = d.join("asserted.tsv");+ let der = d.join("derivations.tsv");+ std::fs::write(&a, "<a>\t<b>\t<c>\n").unwrap();+ std::fs::write(&der, "").unwrap();++ let bin = bin_dir().join("oo-cert");+ let mut cmd = Command::new(&bin);+ cmd.arg(&a).arg(&der);+ let run = CheckerRun::spawn(&CheckerBinary::found_at(bin.clone()), cmd).expect("runs");+ let block = run.checker_block().expect("an oo-cert since #204 prints one");+ assert_eq!(block["self_sha256"].as_str().unwrap(), sha256_of(&bin));+}++/// And a process that is not a checker yields no block, rather than a blank one.+#[test]+fn something_that_prints_no_block_yields_none() {+ use open_ontologies::verdict::{CheckerBinary, CheckerRun};+ let d = std::env::temp_dir().join(format!("oo-selfid-none-{}", std::process::id()));+ std::fs::create_dir_all(&d).unwrap();+ let script = d.join(if cfg!(windows) { "fake.cmd" } else { "fake.sh" });+ let body = if cfg!(windows) {+ "@echo off\r\necho {\"ok\":true,\"theorem\":\"OOCert.certificate_sound\"}\r\nexit /b 0\r\n"+ .to_string()+ } else {+ "#!/bin/sh\necho '{\"ok\":true,\"theorem\":\"OOCert.certificate_sound\"}'\nexit 0\n"+ .to_string()+ };+ std::fs::write(&script, body).unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt as _;+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ let cmd = Command::new(&script);+ let run = CheckerRun::spawn(&CheckerBinary::found_at(script), cmd).expect("runs");+ assert_eq!(run.named_theorem().as_deref(), Some("OOCert.certificate_sound"));+ assert!(+ run.checker_block().is_none(),+ "a process that printed no checker block must yield None. Filling it in would let a \+ report describe a binary that never said anything about itself"+ );+}