lean-pkg 0.25.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. lean_pkg/__init__.py +3 -0
  2. lean_pkg/adapters/__init__.py +148 -0
  3. lean_pkg/adapters/github.py +65 -0
  4. lean_pkg/adapters/leansearch.py +68 -0
  5. lean_pkg/adapters/loogle.py +45 -0
  6. lean_pkg/adapters/palomar.py +170 -0
  7. lean_pkg/adapters/reservoir.py +127 -0
  8. lean_pkg/anchor.py +678 -0
  9. lean_pkg/audit.py +716 -0
  10. lean_pkg/binding_file.py +446 -0
  11. lean_pkg/blueprint.py +213 -0
  12. lean_pkg/build_scope.py +282 -0
  13. lean_pkg/ci_github.py +917 -0
  14. lean_pkg/claim_axioms.py +421 -0
  15. lean_pkg/claims.py +1155 -0
  16. lean_pkg/claims_mark.py +197 -0
  17. lean_pkg/cli.py +5208 -0
  18. lean_pkg/cli_parser.py +768 -0
  19. lean_pkg/command_tree.py +615 -0
  20. lean_pkg/comparator_config.py +990 -0
  21. lean_pkg/comparator_contracts.py +382 -0
  22. lean_pkg/comparator_receipt.py +2854 -0
  23. lean_pkg/comparator_stage.py +623 -0
  24. lean_pkg/comparator_types.py +830 -0
  25. lean_pkg/container.py +172 -0
  26. lean_pkg/core.py +1570 -0
  27. lean_pkg/coverage.py +1278 -0
  28. lean_pkg/data/stacks/lts-2026.10.yaml +73 -0
  29. lean_pkg/data/toolchain-advisories.yaml +77 -0
  30. lean_pkg/data/upgrade-breaking.yaml +20 -0
  31. lean_pkg/data/verify-workflow-pins.yaml +14 -0
  32. lean_pkg/deps_closure.py +512 -0
  33. lean_pkg/deps_fill.py +445 -0
  34. lean_pkg/dup_constants.py +448 -0
  35. lean_pkg/exercise.py +828 -0
  36. lean_pkg/exercise_forbid.py +288 -0
  37. lean_pkg/export_paths.py +77 -0
  38. lean_pkg/extract.py +1172 -0
  39. lean_pkg/extract_decls.py +501 -0
  40. lean_pkg/extract_ledger.py +1408 -0
  41. lean_pkg/extract_summary.py +132 -0
  42. lean_pkg/extract_types.py +502 -0
  43. lean_pkg/extract_write.py +138 -0
  44. lean_pkg/formalization.py +1078 -0
  45. lean_pkg/formalization_kept.py +182 -0
  46. lean_pkg/fresh_repo.py +709 -0
  47. lean_pkg/gate.py +2141 -0
  48. lean_pkg/headline.py +211 -0
  49. lean_pkg/help_topics.py +442 -0
  50. lean_pkg/holes.py +289 -0
  51. lean_pkg/host_routes.py +376 -0
  52. lean_pkg/hypotheses.py +788 -0
  53. lean_pkg/index.py +1749 -0
  54. lean_pkg/json_stdout.py +48 -0
  55. lean_pkg/lake_hygiene.py +289 -0
  56. lean_pkg/lean_diag.py +280 -0
  57. lean_pkg/lean_scan.py +1300 -0
  58. lean_pkg/ledger.py +582 -0
  59. lean_pkg/next_step.py +510 -0
  60. lean_pkg/page.py +1831 -0
  61. lean_pkg/page_html.py +153 -0
  62. lean_pkg/palomar.py +316 -0
  63. lean_pkg/palomar_check.py +1027 -0
  64. lean_pkg/port_modules.py +677 -0
  65. lean_pkg/prior_art.py +286 -0
  66. lean_pkg/producer.py +212 -0
  67. lean_pkg/producer_skew.py +208 -0
  68. lean_pkg/public_safety.py +1487 -0
  69. lean_pkg/publish.py +402 -0
  70. lean_pkg/rebase.py +984 -0
  71. lean_pkg/receipt.py +2385 -0
  72. lean_pkg/receipt_check.py +1064 -0
  73. lean_pkg/receipt_ci.py +660 -0
  74. lean_pkg/receipt_systemd.py +890 -0
  75. lean_pkg/recommended.py +232 -0
  76. lean_pkg/report.py +727 -0
  77. lean_pkg/reservoir.py +203 -0
  78. lean_pkg/scaffold.py +588 -0
  79. lean_pkg/schemas/formalization-0.4.schema.json +344 -0
  80. lean_pkg/schemas/formalization-0.4.schema.source.txt +15 -0
  81. lean_pkg/scripts/ClaimAxioms.lean +47 -0
  82. lean_pkg/scripts/ContractsOnly.lean +300 -0
  83. lean_pkg/scripts/DupConstants.lean +149 -0
  84. lean_pkg/scripts/HypProbe.lean +257 -0
  85. lean_pkg/scripts/comparator-check.sh +396 -0
  86. lean_pkg/scripts/verify-comparator.sh +135 -0
  87. lean_pkg/seal_bundle.py +647 -0
  88. lean_pkg/search.py +865 -0
  89. lean_pkg/site_profiles/easley.yaml +10 -0
  90. lean_pkg/site_profiles/github-actions.yaml +12 -0
  91. lean_pkg/sites.py +225 -0
  92. lean_pkg/stacks.py +373 -0
  93. lean_pkg/statements_module.py +217 -0
  94. lean_pkg/templates/Apache-2.0.txt +202 -0
  95. lean_pkg/toolchain_advisories.py +225 -0
  96. lean_pkg/upgrade.py +706 -0
  97. lean_pkg/verify.py +495 -0
  98. lean_pkg-0.25.0.dist-info/METADATA +93 -0
  99. lean_pkg-0.25.0.dist-info/RECORD +103 -0
  100. lean_pkg-0.25.0.dist-info/WHEEL +5 -0
  101. lean_pkg-0.25.0.dist-info/entry_points.txt +5 -0
  102. lean_pkg-0.25.0.dist-info/licenses/LICENSE +202 -0
  103. lean_pkg-0.25.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,257 @@
1
+ /-
2
+ Copyright 2026 Le Chen. SPDX-License-Identifier: Apache-2.0
3
+ -/
4
+ -- lean_pkg.hypotheses: the Lean half (proposal 0003, the `hyp-probe/1` section of the verify log).
5
+ -- Read-only probe of a compiled environment. Lean prints facts; lean_pkg/hypotheses.py judges them.
6
+ --
7
+ -- Usage (LEAN_PATH=<the package's>):
8
+ -- lean --run HypProbe.lean decl MOD [MOD ...] -- NAME [NAME ...]
9
+ -- imports MOD... and prints, for every NAME, one line
10
+ -- hyp-decl: {"v":1,"theorem":N,"binders":[{"i","head","kind","module","explicit"}...],"data_binders":k}
11
+ -- hyp-missing: {"v":1,"theorem":N} (no constant of that name)
12
+ -- lean --run HypProbe.lean modules CFG [CFG ...]
13
+ -- reads each comparator configuration (JSON) and prints `challenge-module: M` for its `challenge_module`,
14
+ -- each module once (for the job, which builds them outside the sealed log; never part of the log).
15
+ -- lean --run HypProbe.lean challenge CFG [CFG ...]
16
+ -- imports every configuration's Challenge module into one environment and prints
17
+ -- hyp-challenge: {... as hyp-decl ..., "config":C} (once per name of each configuration's theorem_names)
18
+ -- then positive facts only, over the distinct Challenge theorems:
19
+ -- hyp-corollary: {"corollary":T',"of":T,"drops":[H...],"binders":[i...]}
20
+ -- hyp-proof: {"proof":P,"proves":H}
21
+ -- hyp-witness: {"witness":W,"of":T}
22
+ -- hyp-skip: {"theorem":T,"reason":R} (more than MAX_HYPS distinct hypothesis constants)
23
+ -- hyp-error: {"phase":"challenge","message":M} (a configured name that is not in the environment)
24
+ -- The header line and the final `hyp-done` line are written by the job (hypotheses.job_sh), which counts
25
+ -- these lines. A run that fails (exit code not 0) is replaced by one `hyp-error` line there.
26
+ --
27
+ -- Comparison (proposal 0003, open question 4): `Expr.eqv` (`==`: binder names and annotations ignored), plus
28
+ -- equal binder annotations on the outer binders, plus the other theorem's universe parameters renamed
29
+ -- positionally. No unfolding, no `whnf`, no `isDefEq`. Only non-dependent binders are dropped. Core Lean only.
30
+ import Lean
31
+
32
+ open Lean Meta
33
+
34
+ namespace HypProbe
35
+
36
+ /-- Above this many distinct hypothesis constants the 2^m subset search is not run (`hyp-skip`). -/
37
+ def MAX_HYPS : Nat := 12
38
+
39
+ def kindOf : ConstantInfo → String
40
+ | .axiomInfo _ => "axiom"
41
+ | .defnInfo _ => "def"
42
+ | .thmInfo _ => "theorem"
43
+ | .opaqueInfo _ => "opaque"
44
+ | .quotInfo _ => "quot"
45
+ | .inductInfo _ => "inductive"
46
+ | .ctorInfo _ => "constructor"
47
+ | .recInfo _ => "recursor"
48
+
49
+ /-- A JSON string. -/
50
+ def js (s : String) : String := (Json.str s).compress
51
+
52
+ def str (n : Name) : String := js n.toString
53
+
54
+ /-- A JSON object of already rendered values, its keys in the given order, compact. -/
55
+ def obj (pairs : List (String × String)) : String :=
56
+ "{" ++ ",".intercalate (pairs.map fun (k, v) => js k ++ ":" ++ v) ++ "}"
57
+
58
+ def arr (xs : Array String) : String := "[" ++ ",".intercalate xs.toList ++ "]"
59
+
60
+ def line (tag : String) (pairs : List (String × String)) : IO Unit :=
61
+ IO.println s!"{tag}: {obj pairs}"
62
+
63
+ /-- One `Prop` binder headed by a constant: its position, head, the head's kind and module, explicitness. -/
64
+ structure Hyp where
65
+ i : Nat
66
+ head : Name
67
+ explicit : Bool
68
+
69
+ /-- The binders of a type's telescope (not unfolded): the `Prop` binders headed by a constant, and the number
70
+ of binders that are not `Prop`s. -/
71
+ def binders (ty : Expr) : MetaM (Array Hyp × Nat) :=
72
+ forallTelescope ty fun xs _ => do
73
+ let mut out := #[]
74
+ let mut data := 0
75
+ for h : i in [0:xs.size] do
76
+ let d ← xs[i].fvarId!.getDecl
77
+ let t := d.type
78
+ if ← isProp t then
79
+ let f := t.getAppFn
80
+ if f.isConst then
81
+ out := out.push { i, head := f.constName!, explicit := d.binderInfo.isExplicit }
82
+ else
83
+ data := data + 1
84
+ return (out, data)
85
+
86
+ def moduleOf (env : Environment) (c : Name) : String :=
87
+ match env.getModuleIdxFor? c with
88
+ | some idx => (env.allImportedModuleNames[idx.toNat]?.map toString).getD ""
89
+ | none => ""
90
+
91
+ def binderJson (env : Environment) (h : Hyp) : String :=
92
+ let k := (env.find? h.head).map kindOf |>.getD "missing"
93
+ obj [("i", toString h.i), ("head", str h.head), ("kind", js k), ("module", js (moduleOf env h.head)),
94
+ ("explicit", toString h.explicit)]
95
+
96
+ /-- The `hyp-decl` / `hyp-challenge` keys of a constant. -/
97
+ def declPairs (env : Environment) (thm : Name) (ty : Expr) : MetaM (List (String × String)) := do
98
+ let (hs, data) ← binders ty
99
+ return [("v", "1"), ("theorem", str thm), ("binders", arr (hs.map (binderJson env))),
100
+ ("data_binders", toString data)]
101
+
102
+ /-- `ty` without the outer binders at the positions `drop` selects, or none when a kept binder or the body
103
+ mentions a dropped one. -/
104
+ partial def dropAt (drop : Nat → Bool) : Nat → Expr → Option Expr
105
+ | i, .forallE n t b bi =>
106
+ if drop i then
107
+ if b.hasLooseBVar 0 then none else dropAt drop (i + 1) (b.lowerLooseBVars 1 1)
108
+ else (dropAt drop (i + 1) b).map fun b' => .forallE n t b' bi
109
+ | _, e => some e
110
+
111
+ /-- The binder annotations of the outer binders. -/
112
+ def infos : Expr → List BinderInfo
113
+ | .forallE _ _ b bi => bi :: infos b
114
+ | _ => []
115
+
116
+ /-- `Expr.eqv` plus equal outer binder annotations. -/
117
+ def same (a b : Expr) : Bool := a == b && infos a == infos b
118
+
119
+ /-- `ci`'s type with its universe parameters renamed positionally to `us` (same count), else unchanged. -/
120
+ def typeAt (ci : ConstantInfo) (us : List Name) : Expr :=
121
+ if ci.levelParams.length == us.length then ci.instantiateTypeLevelParams (us.map mkLevelParam) else ci.type
122
+
123
+ /-- The expected witness type of `ty`: `∃` over its non-`Prop` binders in order, of the right-nested `∧` of all
124
+ its `Prop` binders in order; none when there is no `Prop` binder or the result would mention a proof. -/
125
+ def witnessType (ty : Expr) : MetaM (Option Expr) :=
126
+ forallTelescope ty fun xs _ => do
127
+ let mut data := #[]
128
+ let mut props := #[]
129
+ for x in xs do
130
+ let t ← inferType x
131
+ if ← isProp t then props := props.push t else data := data.push x
132
+ if props.isEmpty then return none
133
+ let conj := props.pop.foldr (fun p acc => mkAnd p acc) props.back!
134
+ let mut body := conj
135
+ for x in data.reverse do
136
+ body ← mkAppM ``Exists #[← mkLambdaFVars #[x] body]
137
+ body ← instantiateMVars body
138
+ if body.hasAnyFVar (fun f => xs.any (·.fvarId! == f)) then return none
139
+ return some body
140
+
141
+ /-- The subsets of `xs` (as lists, in `xs` order), the empty one first. -/
142
+ def subsets : List Name → List (List Name)
143
+ | [] => [[]]
144
+ | x :: rest => let r := subsets rest; r ++ r.map (x :: ·)
145
+
146
+ def runDecl (names : List String) : MetaM Unit := do
147
+ let env ← getEnv
148
+ for s in names do
149
+ let n := s.toName
150
+ match env.find? n with
151
+ | none => line "hyp-missing" [("v", "1"), ("theorem", js s)]
152
+ | some ci => line "hyp-decl" (← declPairs env n ci.type)
153
+
154
+ structure Config where
155
+ path : String
156
+ challenge : Name
157
+ names : Array Name
158
+
159
+ def readConfig (path : String) : IO Config := do
160
+ let text ← IO.FS.readFile path
161
+ let j ← IO.ofExcept (Json.parse text |>.mapError fun e => s!"{path}: not JSON: {e}")
162
+ let m ← IO.ofExcept (j.getObjValAs? String "challenge_module"
163
+ |>.mapError fun _ => s!"{path}: no string challenge_module")
164
+ let ns ← IO.ofExcept (j.getObjValAs? (Array String) "theorem_names"
165
+ |>.mapError fun _ => s!"{path}: theorem_names is not a list of strings")
166
+ return { path, challenge := m.toName, names := ns.map String.toName }
167
+
168
+ def runChallenge (cfgs : Array Config) : MetaM Unit := do
169
+ let env ← getEnv
170
+ let mut thms : Array Name := #[]
171
+ for c in cfgs do
172
+ for n in c.names do
173
+ match env.find? n with
174
+ | none =>
175
+ line "hyp-error" [("phase", js "challenge"),
176
+ ("message", js s!"{n} (theorem_names of {c.path}) is not in the Challenge environment")]
177
+ | some ci =>
178
+ line "hyp-challenge" ((← declPairs env n ci.type) ++ [("config", js c.path)])
179
+ unless thms.contains n do thms := thms.push n
180
+ -- the binders of every distinct Challenge theorem, and every hypothesis constant
181
+ let mut info : Array (Name × ConstantInfo × Array Hyp) := #[]
182
+ let mut heads : Array Name := #[]
183
+ for n in thms do
184
+ let ci := (env.find? n).get!
185
+ let (hs, _) ← binders ci.type
186
+ info := info.push (n, ci, hs)
187
+ for h in hs do
188
+ unless heads.contains h.head do heads := heads.push h.head
189
+ -- hyp-corollary: T' is T with every binder headed by a constant of S removed (S non-empty)
190
+ for (t, tci, hs) in info do
191
+ let consts := hs.foldl (fun acc h => if acc.contains h.head then acc else acc.push h.head) #[]
192
+ if consts.size > MAX_HYPS then
193
+ line "hyp-skip" [("theorem", str t), ("reason", js
194
+ s!"{consts.size} distinct hypothesis constants, more than {MAX_HYPS}: the corollary search is not run")]
195
+ continue
196
+ for s in subsets consts.toList do
197
+ if s.isEmpty then continue
198
+ let pos := hs.filter (s.contains ·.head) |>.map (·.i)
199
+ let some dropped := dropAt (pos.contains ·) 0 tci.type | continue
200
+ for (c, cci, _) in info do
201
+ if c == t then continue
202
+ if same dropped (typeAt cci tci.levelParams) then
203
+ line "hyp-corollary" [("corollary", str c), ("of", str t),
204
+ ("drops", arr (s.toArray.map str)), ("binders", arr (pos.map toString))]
205
+ -- hyp-proof: a theorem whose type is exactly a hypothesis constant
206
+ for (p, pci, _) in info do
207
+ match pci.type with
208
+ | .const h _ => if heads.contains h then line "hyp-proof" [("proof", str p), ("proves", str h)]
209
+ | _ => pure ()
210
+ -- hyp-witness: a theorem whose type is the expected witness type of a conditional theorem
211
+ for (t, tci, hs) in info do
212
+ if hs.isEmpty then continue
213
+ let some w ← (try witnessType tci.type catch _ => pure none) | continue
214
+ for (c, cci, _) in info do
215
+ if c == t then continue
216
+ if typeAt cci tci.levelParams == w then
217
+ line "hyp-witness" [("witness", str c), ("of", str t)]
218
+
219
+ def runMeta (env : Environment) (x : MetaM Unit) : IO Unit := do
220
+ let ctx : Core.Context := { fileName := "<hypprobe>", fileMap := default }
221
+ let _ ← (x.run' {}).toIO ctx { env := env }
222
+
223
+ def importAll (mods : Array Name) : IO Environment := do
224
+ initSearchPath (← findSysroot)
225
+ importModules (mods.map fun m => ({ module := m } : Import)) {} (loadExts := false)
226
+
227
+ end HypProbe
228
+
229
+ open HypProbe in
230
+ def main (args : List String) : IO UInt32 := do
231
+ match args with
232
+ | "decl" :: rest =>
233
+ let mods := rest.takeWhile (· != "--")
234
+ let names := (rest.dropWhile (· != "--")).drop 1
235
+ if mods.isEmpty || names.isEmpty then
236
+ IO.eprintln "usage: lean --run HypProbe.lean decl MOD [MOD ...] -- NAME [NAME ...]"
237
+ return 2
238
+ let env ← importAll (mods.toArray.map String.toName)
239
+ runMeta env (runDecl names)
240
+ return 0
241
+ | "modules" :: cfgs@(_ :: _) =>
242
+ let mut seen : Array Name := #[]
243
+ for p in cfgs do
244
+ let c ← readConfig p
245
+ unless seen.contains c.challenge do
246
+ seen := seen.push c.challenge
247
+ IO.println s!"challenge-module: {c.challenge}"
248
+ return 0
249
+ | "challenge" :: cfgs@(_ :: _) =>
250
+ let cs ← cfgs.toArray.mapM readConfig
251
+ let mods := cs.foldl (fun acc c => if acc.contains c.challenge then acc else acc.push c.challenge) #[]
252
+ let env ← importAll mods
253
+ runMeta env (runChallenge cs)
254
+ return 0
255
+ | _ =>
256
+ IO.eprintln "usage: lean --run HypProbe.lean (decl MOD... -- NAME... | modules CFG... | challenge CFG...)"
257
+ return 2
@@ -0,0 +1,396 @@
1
+ #!/usr/bin/env bash
2
+ # Canonical copy for the lab (ADR-0058 D2). Vendored 2026-10-05 from the
3
+ # 2026-09-03 spike in Article-Pinning-Correlated-L1-Lean (layer 21694d7).
4
+ # Tool pins below are the Palomar verifier's; change them only via a commit
5
+ # here reviewed against bin/formal-math-watch.py findings.
6
+ # Lab additions (2026-10-07, ADR-0058 amendment D8; byte-identical copy ships
7
+ # inside lean-pkg as src/lean_pkg/scripts/comparator-check.sh):
8
+ # --configs <glob> configuration discovery override (repeatable; relative
9
+ # to the project directory). Default discovery stays
10
+ # comparator*.json and comparator/config*.json.
11
+ # --lint-configs validate the configurations only (axiom subset and the
12
+ # definition-hole sign-off below) and exit 0/1. Needs
13
+ # only jq: no Lean, Lake, Go, cargo, git or build.
14
+ # LEAN4EXPORT_COMMIT=<40-hex> use this lean4export source instead
15
+ # of the toolchain's release tag.
16
+ # LEAN4EXPORT_ALLOW_TOOLCHAIN_MISMATCH=1 with LEAN4EXPORT_COMMIT: when that
17
+ # source pins a different Lean, build it under the PROJECT toolchain in a
18
+ # dedicated checkout and verify the built binary reports the project's
19
+ # Lean version. Needed for point releases lean4export never tagged:
20
+ # verified on v4.34.1 with LEAN4EXPORT_COMMIT=076e8e57707e813375e8f9da8bf989799ace9680
21
+ # (the v4.34.0 tag), which builds and reports version 4.34.1 (verified by
22
+ # hand on a lab host, openai/math family-072 replay, 2026-10-07; the
23
+ # script path itself is not yet exercised end to end). The deviation is printed on
24
+ # its own "== lean4export toolchain override:" line in every log.
25
+ # Tool toolchains (2026-10-17): the comparator and lean4export builds unset
26
+ # ELAN_TOOLCHAIN, so each builds under its own lean-toolchain (printed on an
27
+ # "== <tool> toolchain:" line) even when the caller pins the project's
28
+ # toolchain through ELAN_TOOLCHAIN; the project's own steps keep it.
29
+ # LEAN_PATH shadowing (2026-10-16): before the comparator runs under `lake env`,
30
+ # lake_shadow_check refuses a LEAN_PATH entry other than the project's own
31
+ # .lake/build/lib/lean that holds one of the project's root namespaces (Lake
32
+ # lists the root package last; Lean loads <R>/ from the first entry holding
33
+ # it, so a dependency's copy would be exported and judged instead).
34
+ # Definition holes need a human sign-off. leanprover/comparator compares a
35
+ # name listed in definition_names by name, universes, type and safety only
36
+ # (Comparator/Compare.lean), never by body, and its README says such holes
37
+ # must be checked by an additional, potentially human, verifier. A config
38
+ # with non-empty definition_names is therefore REFUSED unless the sidecar
39
+ # lean-pkg-signoff.json in the project directory (never a comparator*.json:
40
+ # Palomar refuses keys outside its six in a configuration) signs it off:
41
+ # {"schema": "lean-pkg-signoff/1", "configs": {"<config path>": {
42
+ # "config_sha256": "<sha256 of the config's bytes>",
43
+ # "definitions": {"<hole>": {"reviewer": "<human name>",
44
+ # "date": "YYYY-MM-DD", "judged_as": "<text>"}}}}}
45
+ # covering every definition_names entry, where reviewer must not be an
46
+ # agent/model token (claude, codex, gpt, opus, sonnet, fable, agent, bot,
47
+ # opencode, assistant, llm, ai) and config_sha256 binds the sign-off to the
48
+ # config's bytes (a changed config invalidates it). Deprecated fallback: an
49
+ # inline "judged_as": {"reviewer", "date", "definitions": [...], "basis"?}
50
+ # object in the config (warned; `lean-pkg comparator config --migrate-signoff
51
+ # PATH --write` moves it). This records the human verifier; it is a
52
+ # declaration, not a verification. The checked copy strips any inline key.
53
+ # Palomar acceptance bar for one Lake project.
54
+ #
55
+ # leanprover/comparator -- with a lean4export matching the project's toolchain, the independent nanoda
56
+ # kernel, and the landrun sandbox -- must accept every comparator configuration the project declares,
57
+ # i.e. print "Your solution is okay!": each Solution theorem has exactly the statement of its trusted
58
+ # Challenge namesake, uses only the standard axioms, and replays in both kernels.
59
+ #
60
+ # Run from a project directory (the one holding lakefile.toml / lean-toolchain), after `lake exe cache get`:
61
+ # cd <project> && bash ../.github/scripts/comparator-check.sh
62
+ # Needs elan (lean, lake), git, go, cargo and jq; Linux for landrun.
63
+ #
64
+ # Configurations checked, relative to the project directory:
65
+ # comparator*.json (Palomar template layout: comparator.json next to the lakefile)
66
+ # comparator/config*.json (a comparator/ directory of trusted statement files with per-topic configs)
67
+ #
68
+ # Tool pins default to those of the Palomar registry's verifier
69
+ # (https://github.com/PalomarRegistry/PalomarSubmission, .github/workflows/submission.yml); lean4export is
70
+ # taken at the release tag named after the project's Lean version unless LEAN4EXPORT_COMMIT is set.
71
+ set -euo pipefail
72
+
73
+ COMPARATOR_COMMIT="${COMPARATOR_COMMIT:-575674928e239f5bc452aab72d1dd7b0f1326494}"
74
+ NANODA_COMMIT="${NANODA_COMMIT:-68d5ca9db226849b41a6fff59d796ff19d0a8840}"
75
+ LANDRUN_COMMIT="${LANDRUN_COMMIT:-811cfff51ceaf3d9843708aa6d22e9b84ccac8b4}"
76
+ TOOLS_DIR="${TOOLS_DIR:-$HOME/.cache/lean-ci-tools}"
77
+ LOG_DIR="${LOG_DIR:-$PWD/.lake/comparator-logs}"
78
+ ALLOW_MISMATCH="${LEAN4EXPORT_ALLOW_TOOLCHAIN_MISMATCH:-0}"
79
+ STANDARD_AXIOMS='["propext","Quot.sound","Classical.choice"]'
80
+ # Reviewer tokens that name a model or an agent, never a human (whole word or -/_ token, case-insensitive).
81
+ REVIEWER_DENY='^(claude|codex|gpt|opus|sonnet|fable|agent|bot|opencode|assistant|llm|ai)$'
82
+ SIGNOFF_SIDECAR=lean-pkg-signoff.json
83
+
84
+ die() { echo "error: $*" >&2; exit 1; }
85
+
86
+ usage() {
87
+ cat <<'USAGE'
88
+ usage: comparator-check.sh [--configs <glob>]... [--lint-configs] [-h|--help]
89
+
90
+ --configs <glob> configuration files to check, relative to the project directory
91
+ (repeatable; replaces the default comparator*.json / comparator/config*.json)
92
+ --lint-configs only validate the configurations (axiom subset, definition-hole sign-off); no build
93
+ -h, --help this text
94
+
95
+ env: LEAN4EXPORT_COMMIT, LEAN4EXPORT_ALLOW_TOOLCHAIN_MISMATCH=1, COMPARATOR_COMMIT, NANODA_COMMIT,
96
+ LANDRUN_COMMIT, TOOLS_DIR, LOG_DIR (see the header comment of this script)
97
+ USAGE
98
+ }
99
+
100
+ lint_mode=0
101
+ config_globs=()
102
+ while [ $# -gt 0 ]; do
103
+ case "$1" in
104
+ -h|--help) usage; exit 0 ;;
105
+ --lint-configs) lint_mode=1; shift ;;
106
+ --configs) [ $# -ge 2 ] || die "--configs needs a glob argument"; config_globs+=("$2"); shift 2 ;;
107
+ --configs=*) config_globs+=("${1#--configs=}"); shift ;;
108
+ *) die "unknown argument: $1 (see --help)" ;;
109
+ esac
110
+ done
111
+
112
+ command -v jq >/dev/null 2>&1 || die "jq is required"
113
+
114
+ # signoff_entry <cfg>: the config's entry in lean-pkg-signoff.json as compact JSON, `null` when none.
115
+ signoff_entry() {
116
+ local rel="${1#./}"
117
+ if [ -L "$SIGNOFF_SIDECAR" ]; then
118
+ echo "error: $SIGNOFF_SIDECAR is a symlink; refusing to read a sign-off through it" >&2; return 1
119
+ fi
120
+ if [ ! -f "$SIGNOFF_SIDECAR" ]; then echo null; return 0; fi
121
+ jq -e '(type == "object") and (.schema == "lean-pkg-signoff/1") and ((.configs | type) == "object")' \
122
+ "$SIGNOFF_SIDECAR" >/dev/null 2>&1 \
123
+ || { echo "error: $SIGNOFF_SIDECAR: not a lean-pkg-signoff/1 document" >&2; return 1; }
124
+ jq -c --arg rel "$rel" '.configs[$rel] // null' "$SIGNOFF_SIDECAR"
125
+ }
126
+
127
+ # lint_config <cfg>: the configuration-level rules (axiom subset; definition holes need a human
128
+ # sign-off). Prints "error: ..." to stderr and returns 1 on the first failing clause.
129
+ lint_config() {
130
+ local cfg="$1" msg entry sha
131
+ jq -e 'type == "object"' "$cfg" >/dev/null 2>&1 \
132
+ || { echo "error: $cfg: not a JSON object" >&2; return 1; }
133
+ if ! jq -e --argjson std "$STANDARD_AXIOMS" '((.permitted_axioms // []) - $std) == []' "$cfg" >/dev/null; then
134
+ echo "error: $cfg: permitted_axioms must be a subset of propext, Quot.sound, Classical.choice" >&2
135
+ return 1
136
+ fi
137
+ entry="$(signoff_entry "$cfg")" || return 1
138
+ sha="$( (sha256sum "$cfg" 2>/dev/null || shasum -a 256 "$cfg") | cut -d' ' -f1)"
139
+ msg="$(jq -r --arg deny "$REVIEWER_DENY" --argjson entry "$entry" --arg sha "$sha" '
140
+ def holes: (.definition_names // []);
141
+ def blank: (type != "string") or ((gsub("^\\s+|\\s+$"; "") | length) == 0);
142
+ def agent: [ascii_downcase | splits("[^a-z0-9]+") | select(length > 0)] | any(test($deny));
143
+ def iso: (type == "string") and test("^[0-9]{4}-[0-9]{2}-[0-9]{2}$");
144
+ ($entry // {} | .definitions) as $sig
145
+ | if (holes | length) == 0 then empty
146
+ elif ($sig | type) == "object" then
147
+ if ($entry.config_sha256 | tostring) != $sha then
148
+ "the sign-off in lean-pkg-signoff.json is bound to config_sha256 \($entry.config_sha256 | tostring | .[0:12]), but the configuration hashes to \($sha[0:12]): a changed configuration invalidates its sign-off; a human re-judges the bodies, then sets config_sha256 to \($sha)"
149
+ elif ((holes - ($sig | keys)) | length) > 0 then
150
+ "lean-pkg-signoff.json definitions do not cover definition hole(s): \((holes - ($sig | keys)) | join(", "))"
151
+ elif ((($sig | keys) - holes) | length) > 0 then
152
+ "lean-pkg-signoff.json signs off \((($sig | keys) - holes) | join(", ")), not a definition_names entry"
153
+ elif any($sig[]; (.reviewer | blank)) then
154
+ "lean-pkg-signoff.json: every reviewer must be a non-empty human name"
155
+ elif any($sig[]; (.reviewer | agent)) then
156
+ "lean-pkg-signoff.json: a reviewer names an agent/model token, not a human reviewer"
157
+ elif any($sig[]; (.date | iso) | not) then
158
+ "lean-pkg-signoff.json: every date must be an ISO date YYYY-MM-DD"
159
+ elif any($sig[]; (.judged_as | blank)) then
160
+ "lean-pkg-signoff.json: every judged_as must be a non-empty text"
161
+ else empty end
162
+ elif (.judged_as | type) != "object" then
163
+ "definition_names is non-empty (\(holes | length) hole(s)) but there is no sign-off: no entry in lean-pkg-signoff.json and no (deprecated) inline judged_as object"
164
+ elif (.judged_as.reviewer | blank) then
165
+ "judged_as.reviewer must be a non-empty human name"
166
+ elif (.judged_as.reviewer | agent) then
167
+ "judged_as.reviewer \(.judged_as.reviewer | tojson) names an agent/model token, not a human reviewer"
168
+ elif (.judged_as.date | iso) | not then
169
+ "judged_as.date must be an ISO date YYYY-MM-DD"
170
+ elif (.judged_as.definitions | type) != "array" then
171
+ "judged_as.definitions must be an array covering every definition_names entry"
172
+ elif ((holes - .judged_as.definitions) | length) > 0 then
173
+ "judged_as.definitions does not cover definition hole(s): \((holes - .judged_as.definitions) | join(", "))"
174
+ else empty end' "$cfg")"
175
+ if [ -n "$msg" ]; then
176
+ echo "error: $cfg: $msg (comparator checks definition holes by name and type only, never by body; a human must sign off in $SIGNOFF_SIDECAR)" >&2
177
+ return 1
178
+ fi
179
+ if jq -e 'has("judged_as") or has("lean_pkg_scaffold")' "$cfg" >/dev/null; then
180
+ echo "warning: $cfg: inline judged_as/lean_pkg_scaffold is deprecated (Palomar refuses keys outside its six); move it to $SIGNOFF_SIDECAR: lean-pkg comparator config --migrate-signoff ${cfg#./} --write" >&2
181
+ fi
182
+ return 0
183
+ }
184
+
185
+ # hole_summary <cfg>: one line naming the signed-off holes, empty when the config has none.
186
+ hole_summary() {
187
+ local entry
188
+ entry="$(signoff_entry "$1" 2>/dev/null)" || entry=null
189
+ jq -r --argjson entry "$entry" '
190
+ if ((.definition_names // []) | length) == 0 then empty
191
+ elif (($entry // {} | .definitions) | type) == "object" then
192
+ "definition holes: \((.definition_names | length)) signed off by \([$entry.definitions[].reviewer] | unique | join("; ")) in lean-pkg-signoff.json"
193
+ else "definition holes: \((.definition_names | length)) signed off by \(.judged_as.reviewer) on \(.judged_as.date) (inline judged_as, deprecated)" end' "$1"
194
+ }
195
+
196
+ shopt -s nullglob
197
+ if [ "${#config_globs[@]}" -gt 0 ]; then
198
+ configs=()
199
+ for g in "${config_globs[@]}"; do
200
+ for f in $g; do configs+=("$f"); done
201
+ done
202
+ else
203
+ configs=(comparator*.json comparator/config*.json)
204
+ fi
205
+ shopt -u nullglob
206
+ [ "${#configs[@]}" -gt 0 ] || die "no comparator configuration found (comparator*.json, comparator/config*.json, or --configs <glob>)"
207
+
208
+ if [ "$lint_mode" = 1 ]; then
209
+ failures=0
210
+ for cfg in "${configs[@]}"; do
211
+ if lint_config "$cfg"; then
212
+ echo "LINT-OK $cfg$(s=$(hole_summary "$cfg"); [ -n "$s" ] && echo " ($s)")"
213
+ else
214
+ failures=$((failures + 1))
215
+ fi
216
+ done
217
+ [ "$failures" -eq 0 ] || die "$failures configuration(s) refused"
218
+ echo "All ${#configs[@]} configuration(s) lint clean."
219
+ exit 0
220
+ fi
221
+
222
+ [ -f lean-toolchain ] || die "run this from a project directory containing lean-toolchain"
223
+ for tool in git go cargo jq lean lake; do
224
+ command -v "$tool" >/dev/null 2>&1 || die "$tool is required"
225
+ done
226
+
227
+ toolchain="$(tr -d '[:space:]' < lean-toolchain)"
228
+ tag="v${toolchain#*:v}"
229
+ lean4export_release="release $tag"
230
+ if [ -z "${LEAN4EXPORT_COMMIT:-}" ]; then
231
+ refs="$(git ls-remote https://github.com/leanprover/lean4export "refs/tags/$tag" "refs/tags/$tag^{}")"
232
+ LEAN4EXPORT_COMMIT="$(awk -v t="refs/tags/$tag^{}" '$2==t {print $1}' <<<"$refs")"
233
+ [ -n "$LEAN4EXPORT_COMMIT" ] || LEAN4EXPORT_COMMIT="$(awk -v t="refs/tags/$tag" '$2==t {print $1}' <<<"$refs")"
234
+ [ -n "$LEAN4EXPORT_COMMIT" ] || die "leanprover/lean4export has no release $tag for toolchain $toolchain. Point-release gap: set LEAN4EXPORT_COMMIT=<commit of the nearest lower release tag> and LEAN4EXPORT_ALLOW_TOOLCHAIN_MISMATCH=1 to build that source under $toolchain (the built binary's reported Lean version is verified); e.g. for v4.34.1 use LEAN4EXPORT_COMMIT=076e8e57707e813375e8f9da8bf989799ace9680 (the v4.34.0 tag)"
235
+ else
236
+ lean4export_release="commit override"
237
+ fi
238
+
239
+ echo "project $(pwd), toolchain $toolchain, configurations: ${configs[*]}"
240
+
241
+ mkdir -p "$TOOLS_DIR/bin" "$LOG_DIR"
242
+
243
+ checkout_at() { # <url> <dir> <commit>
244
+ if [ ! -d "$2/.git" ]; then
245
+ git clone --quiet --filter=blob:none "$1" "$2"
246
+ fi
247
+ if [ "$(git -C "$2" rev-parse HEAD)" != "$3" ]; then
248
+ git -C "$2" fetch --quiet --depth 1 origin "$3"
249
+ git -C "$2" checkout --quiet --detach "$3"
250
+ fi
251
+ }
252
+
253
+ # Tool builds use the tool's own lean-toolchain, never the project's. A caller (lean-pkg's runner, #41)
254
+ # may export ELAN_TOOLCHAIN=<the project's toolchain> so that the project's `lake`/`lean` resolve to it; an
255
+ # exported ELAN_TOOLCHAIN overrides every directory's lean-toolchain for elan's proxies, so it is unset
256
+ # for the comparator and lean4export builds only (lean4export's file is the project's toolchain anyway,
257
+ # or rewritten to it under LEAN4EXPORT_ALLOW_TOOLCHAIN_MISMATCH). The project's steps below keep it.
258
+ tool_toolchain() { tr -d '[:space:]' 2>/dev/null < "$1/lean-toolchain" || echo "?"; }
259
+
260
+ echo "== comparator @ $COMPARATOR_COMMIT"
261
+ checkout_at https://github.com/leanprover/comparator.git "$TOOLS_DIR/comparator" "$COMPARATOR_COMMIT"
262
+ echo "== comparator toolchain: $(tool_toolchain "$TOOLS_DIR/comparator") (its own lean-toolchain)"
263
+ (cd "$TOOLS_DIR/comparator" && unset ELAN_TOOLCHAIN && lake build comparator)
264
+ comparator_bin="$TOOLS_DIR/comparator/.lake/build/bin/comparator"
265
+
266
+ lean4export_dir="$TOOLS_DIR/lean4export"
267
+ checkout_at https://github.com/leanprover/lean4export.git "$lean4export_dir" "$LEAN4EXPORT_COMMIT"
268
+ export_toolchain="$(tr -d '[:space:]' < "$lean4export_dir/lean-toolchain")"
269
+ override_note=""
270
+ if [ "$export_toolchain" != "$toolchain" ]; then
271
+ if [ "$ALLOW_MISMATCH" = 1 ]; then
272
+ # Dedicated checkout so the shared one stays pristine; its lean-toolchain is rewritten to the
273
+ # project's and the built binary must report the project's Lean version (checked below).
274
+ lean4export_dir="$TOOLS_DIR/lean4export-override-${toolchain#*:v}"
275
+ checkout_at https://github.com/leanprover/lean4export.git "$lean4export_dir" "$LEAN4EXPORT_COMMIT"
276
+ printf '%s\n' "$toolchain" > "$lean4export_dir/lean-toolchain"
277
+ override_note="source pinned $export_toolchain, built under $toolchain"
278
+ lean4export_release="commit override, $override_note"
279
+ else
280
+ die "lean4export $LEAN4EXPORT_COMMIT targets $export_toolchain but the project uses $toolchain; set LEAN4EXPORT_ALLOW_TOOLCHAIN_MISMATCH=1 (with LEAN4EXPORT_COMMIT) to build it under the project toolchain; the built binary's reported Lean version is then verified"
281
+ fi
282
+ fi
283
+ echo "== lean4export @ $LEAN4EXPORT_COMMIT ($lean4export_release)"
284
+ [ -z "$override_note" ] || echo "== lean4export toolchain override: commit $LEAN4EXPORT_COMMIT $override_note"
285
+ echo "== lean4export toolchain: $(tool_toolchain "$lean4export_dir") (its own lean-toolchain)"
286
+ (cd "$lean4export_dir" && unset ELAN_TOOLCHAIN && lake build lean4export)
287
+ lean4export_bin="$lean4export_dir/.lake/build/bin/lean4export"
288
+ if [ -n "$override_note" ]; then
289
+ want="${toolchain#*:v}"
290
+ got="$("$lean4export_bin" --help 2>&1 | head -n 1 | jq -r '.meta.lean.version // empty' 2>/dev/null || true)"
291
+ [ "$got" = "$want" ] \
292
+ || die "lean4export built under $toolchain reports Lean version '${got:-?}', expected '$want'; the override is not usable for this toolchain"
293
+ echo "== lean4export toolchain override verified: binary reports Lean $got"
294
+ fi
295
+
296
+ echo "== nanoda_lib @ $NANODA_COMMIT"
297
+ checkout_at https://github.com/robsimmons/nanoda_lib.git "$TOOLS_DIR/nanoda" "$NANODA_COMMIT"
298
+ cargo build --release --locked --quiet --manifest-path "$TOOLS_DIR/nanoda/Cargo.toml"
299
+ nanoda_bin="$TOOLS_DIR/nanoda/target/release/nanoda_bin"
300
+
301
+ echo "== landrun @ $LANDRUN_COMMIT"
302
+ landrun_bin="$TOOLS_DIR/bin/landrun"
303
+ if [ ! -x "$landrun_bin" ] || [ "$(cat "$landrun_bin.commit" 2>/dev/null)" != "$LANDRUN_COMMIT" ]; then
304
+ GOBIN="$TOOLS_DIR/bin" CGO_ENABLED=0 go install "github.com/zouuup/landrun/cmd/landrun@$LANDRUN_COMMIT"
305
+ echo "$LANDRUN_COMMIT" > "$landrun_bin.commit"
306
+ fi
307
+
308
+ for bin in "$comparator_bin" "$lean4export_bin" "$nanoda_bin" "$landrun_bin"; do
309
+ [ -x "$bin" ] || die "missing tool $bin"
310
+ done
311
+
312
+ # >>> lean-pkg lake_shadow_check (keep identical in every copy; see lean_pkg/lake_hygiene.py)
313
+ lake_root_namespaces() {
314
+ local found
315
+ found=$(
316
+ {
317
+ if [ -f lakefile.toml ]; then
318
+ awk '/^[[:space:]]*\[/ { lib = ($0 ~ /^[[:space:]]*\[\[[[:space:]]*lean_lib[[:space:]]*\]\]/) }
319
+ lib && /^[[:space:]]*(name|roots|globs)[[:space:]]*=/' lakefile.toml | grep -oE '"[^"]+"' | tr -d '"'
320
+ fi
321
+ if [ -f lakefile.lean ]; then
322
+ grep -oE 'lean_lib[[:space:]]+(«[^»]+»|[A-Za-z_][A-Za-z0-9_.]*)' lakefile.lean | awk '{print $2}'
323
+ tr '\n' ' ' < lakefile.lean | grep -oE '(roots|globs)[[:space:]]*:=[[:space:]]*#\[[^]]*\]' \
324
+ | grep -oE '`[^]`[:space:],)]+' | tr -d '`'
325
+ fi
326
+ } 2>/dev/null | sed -e 's/^«\([^»]*\)».*$/\1/' -e 's/[.].*$//' | grep -E '^[A-Za-z_]' | sort -u || true
327
+ )
328
+ if [ -z "$found" ]; then
329
+ found=$(find . -path ./.lake -prune -o -name '*.lean' ! -path ./lakefile.lean -print 2>/dev/null \
330
+ | sed -e 's|^\./||' -e 's|/.*$||' -e 's|\.lean$||' | grep -E '^[A-Za-z_]' | sort -u || true)
331
+ fi
332
+ printf '%s\n' "$found"
333
+ }
334
+ lake_shadow_check() {
335
+ local own entry r n=0 hits=0 roots
336
+ local -a entries
337
+ own="$(pwd -P)/.lake/build/lib/lean"
338
+ roots=$(lake_root_namespaces)
339
+ IFS=: read -r -a entries <<<"${1:-}"
340
+ for entry in "${entries[@]}"; do
341
+ [ -n "$entry" ] || continue
342
+ n=$((n + 1))
343
+ if [ "$(cd "$entry" 2>/dev/null && pwd -P)" = "$own" ]; then continue; fi
344
+ for r in $roots; do
345
+ if [ -d "$entry/$r" ] || [ -e "$entry/$r.olean" ] || [ -e "$entry/$r.ilean" ]; then
346
+ echo "lean-path-shadow: $entry/$r"
347
+ hits=$((hits + 1))
348
+ fi
349
+ done
350
+ done
351
+ if [ "$hits" -gt 0 ]; then return 1; fi
352
+ echo "lean-path-shadow: none ($n entries, roots $(printf '%s' "$roots" | paste -sd, -))"
353
+ }
354
+ # <<< lean-pkg lake_shadow_check
355
+ lean_path="$(lake env printenv LEAN_PATH)"
356
+ lake_shadow_check "$lean_path" \
357
+ || die "a LEAN_PATH entry shadows this project's own modules (lean-path-shadow lines above); a dependency's copy would be judged instead; remove it and rebuild"
358
+
359
+ # Comparator runs `lake build <module>` and lean4export inside landrun sandboxes that may execute only the
360
+ # toolchain directory, so resolve lake/lean to the toolchain's own binaries rather than the elan shims.
361
+ lean_prefix="$(lean --print-prefix)"
362
+ export PATH="$lean_prefix/bin:$PATH"
363
+ export COMPARATOR_LANDRUN="$landrun_bin"
364
+ export COMPARATOR_LEAN4EXPORT="$lean4export_bin"
365
+ export COMPARATOR_NANODA="$nanoda_bin"
366
+ export LEAN_ABORT_ON_PANIC=1
367
+
368
+ failures=0
369
+ for cfg in "${configs[@]}"; do
370
+ name="$(tr '/' '_' <<<"${cfg%.json}")"
371
+ log="$LOG_DIR/$name.log"
372
+ # As in the registry: only the three standard axioms may be permitted, and the nanoda re-check is always
373
+ # on (comparator is handed a copy of the configuration with enable_nanoda forced to true). Definition
374
+ # holes must carry a human sign-off in lean-pkg-signoff.json (lab rule, ADR-0058 D8); no inline
375
+ # lean-pkg key is handed to comparator.
376
+ lint_config "$cfg" || exit 1
377
+ summary="$(hole_summary "$cfg")"
378
+ [ -z "$summary" ] || echo "$cfg: $summary"
379
+ checked_cfg="$LOG_DIR/$name.json"
380
+ jq '.enable_nanoda = true | del(.judged_as, .lean_pkg_scaffold)' "$cfg" > "$checked_cfg"
381
+
382
+ echo "== comparator $cfg (log: $log)"
383
+ set +e
384
+ lake env "$comparator_bin" "$checked_cfg" 2>&1 | tee "$log"
385
+ status="${PIPESTATUS[0]}"
386
+ set -e
387
+ if [ "$status" -eq 0 ] && grep -qxF 'Your solution is okay!' "$log"; then
388
+ echo "PASS $cfg"
389
+ else
390
+ echo "::error::comparator did not accept $cfg (exit status $status)"
391
+ failures=$((failures + 1))
392
+ fi
393
+ done
394
+
395
+ [ "$failures" -eq 0 ] || die "$failures comparator configuration(s) not accepted"
396
+ echo "All ${#configs[@]} comparator configuration(s) accepted."