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
lean_pkg/hypotheses.py ADDED
@@ -0,0 +1,788 @@
1
+ # hypotheses -- the hyp-probe/1 section of the lower-tier verify log (proposal 0003, stages H1 and H3)
2
+ """Facts for conditional claims (proposal 0003, issue #320), read from the BUILT environment into the sealed
3
+ verify log. Stage H1: the probe, the log section and its write-time structure check. Stage H3: `facts` and
4
+ `evaluate`, which the claims ledger calls to judge hypotheses, discharge and witnesses from the section.
5
+
6
+ How: `scripts/HypProbe.lean` (core Lean only; data-only import, `loadExts := false`, as ClaimAxioms.lean) prints
7
+ facts and never a verdict. The verify scripts (`receipt slurm --template`, the `verify.sh` that `lean-pkg new`
8
+ writes) run `hypotheses_run` (`job_sh()` below) after `claim_axioms_run`, appending to the log, before the seal:
9
+
10
+ == lean-pkg hypotheses (hyp-probe/1) ==
11
+ hyp-decl: {...} decl part: every claim decl of claims.yaml (hyp-missing: one not in the build)
12
+ hyp-challenge-build: {...} Challenge part, only when claims.yaml uses hypotheses, discharges or witness:
13
+ hyp-challenge: {...} each Challenge module is built OUTSIDE the sealed log (a side log), so its
14
+ hyp-corollary: {...} `sorry` warnings never reach sorry_count; only its status line enters the log.
15
+ hyp-proof: {...} Then every configured Challenge theorem, and positive facts only.
16
+ hyp-witness: {...}
17
+ hyp-skip: {...} the corollary search not run (more than 12 distinct hypothesis constants)
18
+ hyp-error: {...} a part that could not run (never a refusal: consumers read it as unchecked)
19
+ hyp-done: {...} the last line, written by the job with the counts
20
+
21
+ The line format is docs/formats.md, "The hypotheses section of the verify log". `report_sha256` seals the
22
+ section; the receipt schema does not change (no new key).
23
+
24
+ Write-time structure (`judge_structure`, called by `receipt slurm|systemd` and `--check` through
25
+ `receipt.hypotheses_evidence`): refused are a section without `hyp-done`, counts that do not match it, a line
26
+ printed twice, a malformed line (not one JSON object with the tag's exact keys), a line after `hyp-done`, a tag
27
+ line outside the section, and a redaction that alters a section line. A log without the section (an older
28
+ verify script) is accepted unchanged: the facts are simply absent.
29
+
30
+ Python API: `parse(text)`, `section_lines(text)`, `uses_keys(claims_bytes)`, `judge_structure(text,
31
+ claims_bytes=None, redacted=None)`, `job_sh()`, `probe(repo, toolchain=None, timeout=...)`.
32
+ Command line: `python3 -m lean_pkg.hypotheses --repo DIR [--toolchain TC] [--timeout S] [--json]` runs the
33
+ job's block on a built checkout (it builds the Challenge modules, as the job does) and prints the section (or
34
+ the structure judgement with --json). Exit 0 the section is complete, 1 refused or the probe failed, 2 usage.
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ import argparse
40
+ import json
41
+ import os
42
+ import pathlib
43
+ import re
44
+ import subprocess
45
+ import sys
46
+ import tempfile
47
+
48
+ SCRIPT = pathlib.Path(__file__).with_name("scripts") / "HypProbe.lean"
49
+ FORMAT = "hyp-probe/1"
50
+ HEADER = f"== lean-pkg hypotheses ({FORMAT}) =="
51
+ MAX_HYPS = 12 # HypProbe.MAX_HYPS: above it the corollary search prints hyp-skip
52
+ DEFAULT_TIMEOUT = 1800.0
53
+ SIDE_LOG = "hyp-challenge-build.log"
54
+ # The claims.yaml keys that switch the Challenge part on (the job greps the same pattern).
55
+ KEYS_RE = re.compile(r"^[ \t-]+(hypotheses|discharges|witness):", re.M)
56
+ _TAG_LINE = re.compile(r"^(hyp-[a-z-]+):(.*?)\r?$")
57
+
58
+ _BINDER_KEYS = {"i": int, "head": str, "kind": str, "module": str, "explicit": bool}
59
+ _DECL_KEYS = {"v": int, "theorem": str, "binders": list, "data_binders": int}
60
+ # tag -> {key: type} (exact key sets; `v` must be 1)
61
+ TAGS: dict[str, dict[str, type]] = {
62
+ "hyp-decl": _DECL_KEYS,
63
+ "hyp-missing": {"v": int, "theorem": str},
64
+ "hyp-challenge-build": {"module": str, "ok": bool},
65
+ "hyp-challenge": {**_DECL_KEYS, "config": str},
66
+ "hyp-corollary": {"corollary": str, "of": str, "drops": list, "binders": list},
67
+ "hyp-proof": {"proof": str, "proves": str},
68
+ "hyp-witness": {"witness": str, "of": str},
69
+ "hyp-skip": {"theorem": str, "reason": str},
70
+ "hyp-error": {"phase": str, "message": str},
71
+ "hyp-done": {"v": int, "decls": int, "challenge": int, "configs": list},
72
+ }
73
+ FACT_TAGS = ("hyp-corollary", "hyp-proof", "hyp-witness")
74
+
75
+
76
+ def _is(value, typ) -> bool:
77
+ if typ is int:
78
+ return isinstance(value, int) and not isinstance(value, bool) and value >= 0
79
+ return isinstance(value, typ)
80
+
81
+
82
+ def _shape_problem(tag: str, obj) -> str | None:
83
+ """Why `obj` is not a well-formed `tag` object (None when it is)."""
84
+ if not isinstance(obj, dict):
85
+ return "not a JSON object"
86
+ keys = TAGS[tag]
87
+ if set(obj) != set(keys):
88
+ missing, extra = sorted(set(keys) - set(obj)), sorted(set(obj) - set(keys))
89
+ return "keys " + "; ".join(x for x in (f"missing {missing}" if missing else "",
90
+ f"unexpected {extra}" if extra else "") if x)
91
+ for k, typ in keys.items():
92
+ if not _is(obj[k], typ):
93
+ return f"`{k}` is not a {typ.__name__}"
94
+ if "v" in keys and obj["v"] != 1:
95
+ return f"`v` is {obj['v']!r}, not 1"
96
+ if "binders" in keys and tag != "hyp-corollary":
97
+ for b in obj["binders"]:
98
+ if not isinstance(b, dict) or set(b) != set(_BINDER_KEYS) or not all(
99
+ _is(b[k], t) for k, t in _BINDER_KEYS.items()):
100
+ return "a binder is not {i, head, kind, module, explicit}"
101
+ if tag == "hyp-corollary":
102
+ if not obj["drops"] or not all(isinstance(x, str) and x for x in obj["drops"]):
103
+ return "`drops` is not a non-empty list of names"
104
+ if not obj["binders"] or not all(_is(x, int) for x in obj["binders"]):
105
+ return "`binders` is not a non-empty list of positions"
106
+ if tag == "hyp-error" and obj["phase"] not in ("decl", "challenge"):
107
+ return f"`phase` is {obj['phase']!r}, not decl or challenge"
108
+ if tag == "hyp-done" and not all(isinstance(x, str) for x in obj["configs"]):
109
+ return "`configs` is not a list of paths"
110
+ return None
111
+
112
+
113
+ def _identity(tag: str, obj: dict):
114
+ """What may appear only once per section: one line per decl, per (Challenge theorem, configuration), per
115
+ Challenge module build; any other line only once as written."""
116
+ if tag in ("hyp-decl", "hyp-missing"):
117
+ return ("decl", obj["theorem"])
118
+ if tag == "hyp-challenge":
119
+ return (tag, obj["theorem"], obj["config"])
120
+ if tag == "hyp-challenge-build":
121
+ return (tag, obj["module"])
122
+ return None
123
+
124
+
125
+ def section_lines(text: str) -> list[str]:
126
+ """The section's header and tag lines, as written (a redaction that alters one is refused)."""
127
+ return [line.rstrip("\r") for line in text.splitlines() if line.rstrip("\r") == HEADER or _TAG_LINE.match(line)]
128
+
129
+
130
+ def parse(text: str) -> dict:
131
+ """{present, records [(tag, object)], done (object or None), problems}: the hyp-probe/1 section of a log.
132
+ `present` is False for a log with neither the header nor any `hyp-*:` line (an older verify script)."""
133
+ records: list[tuple[str, dict]] = []
134
+ problems: list[str] = []
135
+ seen_lines: set[str] = set()
136
+ seen_ids: set = set()
137
+ header = False
138
+ done: dict | None = None
139
+ present = False
140
+ for n, raw in enumerate(text.splitlines(), 1):
141
+ line = raw.rstrip("\r")
142
+ if line == HEADER:
143
+ present = True
144
+ if header:
145
+ problems.append(f"verify log line {n}: a second `{HEADER}` header")
146
+ header = True
147
+ continue
148
+ m = _TAG_LINE.match(line)
149
+ if not m:
150
+ continue
151
+ present = True
152
+ tag, payload = m.group(1), m.group(2).strip()
153
+ if tag not in TAGS:
154
+ problems.append(f"verify log line {n}: `{tag}:` is not a {FORMAT} line")
155
+ continue
156
+ if not header:
157
+ problems.append(f"verify log line {n}: a `{tag}:` line before the `{HEADER}` header")
158
+ continue
159
+ if done is not None:
160
+ problems.append(f"verify log line {n}: a `{tag}:` line after `hyp-done:`")
161
+ continue
162
+ if line in seen_lines:
163
+ problems.append(f"verify log line {n}: `{tag}:` printed twice: {payload[:160]}")
164
+ continue
165
+ seen_lines.add(line)
166
+ try:
167
+ obj = json.loads(payload)
168
+ except ValueError:
169
+ problems.append(f"verify log line {n}: `{tag}:` is not followed by one JSON object: {payload[:160]!r}")
170
+ continue
171
+ why = _shape_problem(tag, obj)
172
+ if why:
173
+ problems.append(f"verify log line {n}: malformed `{tag}:` line ({why})")
174
+ continue
175
+ ident = _identity(tag, obj)
176
+ if ident is not None:
177
+ if ident in seen_ids:
178
+ problems.append(f"verify log line {n}: a second `{tag}:` line for {ident[1]}"
179
+ + (f" in {ident[2]}" if len(ident) > 2 else ""))
180
+ continue
181
+ seen_ids.add(ident)
182
+ if tag == "hyp-done":
183
+ done = obj
184
+ continue
185
+ records.append((tag, obj))
186
+ return {"present": present, "records": records, "done": done, "problems": problems}
187
+
188
+
189
+ def uses_keys(claims_bytes: bytes | None) -> bool:
190
+ """Whether a claims.yaml uses `hypotheses`, `discharges` or `witness` (the job's switch for the Challenge
191
+ part, the same pattern)."""
192
+ if not claims_bytes:
193
+ return False
194
+ return KEYS_RE.search(claims_bytes.decode("utf-8", errors="replace")) is not None
195
+
196
+
197
+ def judge_structure(text: str, claims_bytes: bytes | None = None,
198
+ redacted: str | None = None) -> tuple[dict | None, list[str], list[str]]:
199
+ """(summary or None when the log has no section, refusals, check lines): the write-time structure check.
200
+ `redacted`: the published log text, whose section lines must equal the raw log's. Nothing here judges a
201
+ claim (the ledger does, `evaluate`); `hyp-error` and `hyp-skip` are reported, never refused."""
202
+ sec = parse(text)
203
+ keyed = uses_keys(claims_bytes)
204
+ if not sec["present"]:
205
+ lines = []
206
+ if keyed:
207
+ lines.append(f"· hypotheses: no {FORMAT} section in the verify log (a verify script without the "
208
+ f"probe): the claims that use hypotheses, discharges or witness will be unchecked; "
209
+ f"regenerate verify.sh or the sbatch template to get it")
210
+ return None, [], lines
211
+ refusals = list(sec["problems"])
212
+ records, done = sec["records"], sec["done"]
213
+ if redacted is not None and section_lines(text) != section_lines(redacted):
214
+ refusals.append(f"redaction changed the {FORMAT} section of the verify log (its lines differ between the "
215
+ f"raw and the redacted log); narrow the --redact pattern so it leaves those lines intact")
216
+ count = {t: sum(1 for tag, _ in records if tag == t) for t in TAGS}
217
+ decls = count["hyp-decl"] + count["hyp-missing"]
218
+ if done is None:
219
+ refusals.append(f"verify log: a {FORMAT} section without its final `hyp-done:` line: the probe did not "
220
+ f"finish (or the log was cut)")
221
+ else:
222
+ if done["decls"] != decls:
223
+ refusals.append(f"verify log: `hyp-done:` counts {done['decls']} decl line(s) but the section has "
224
+ f"{decls} (hyp-decl and hyp-missing): the output is inconsistent")
225
+ if done["challenge"] != count["hyp-challenge"]:
226
+ refusals.append(f"verify log: `hyp-done:` counts {done['challenge']} hyp-challenge line(s) but the "
227
+ f"section has {count['hyp-challenge']}: the output is inconsistent")
228
+ stray = sorted({o["config"] for t, o in records if t == "hyp-challenge"} - set(done["configs"]))
229
+ if stray:
230
+ refusals.append(f"verify log: hyp-challenge lines name configuration(s) {stray} that `hyp-done:` does "
231
+ f"not list")
232
+ summary = {"decls": decls, "missing": count["hyp-missing"], "challenge": count["hyp-challenge"],
233
+ "facts": sum(count[t] for t in FACT_TAGS), "skipped": count["hyp-skip"],
234
+ "errors": count["hyp-error"],
235
+ "challenge_builds_failed": sum(1 for t, o in records if t == "hyp-challenge-build" and not o["ok"])}
236
+ lines = []
237
+ if not refusals:
238
+ # Stage H4: the ledger judges the facts now. A claims file without the keys keeps the line it had, byte
239
+ # for byte (proposal 0003, open question 8); only a file that uses them gets the current wording.
240
+ judged = ("judged by the claims ledger and `receipt check`, recomputed on every call" if keyed
241
+ else "judged by the claims ledger in a later stage")
242
+ lines.append(f"✓ hypotheses: {FORMAT} section complete: {decls} decl(s), {summary['challenge']} Challenge "
243
+ f"theorem(s), {summary['facts']} fact(s) (sealed by report_sha256; {judged})")
244
+ for tag, obj in records:
245
+ if tag == "hyp-error":
246
+ lines.append(f"· hypotheses: the {obj['phase']} part did not run ({obj['message'][:200]})"
247
+ + ("; the claims that use hypotheses, discharges or witness will be unchecked"
248
+ if keyed else "; claims.yaml uses no hypotheses, discharges or witness"))
249
+ elif tag == "hyp-skip":
250
+ lines.append(f"· hypotheses: corollary search skipped for {obj['theorem']} ({obj['reason'][:200]})")
251
+ elif tag == "hyp-challenge-build" and not obj["ok"]:
252
+ lines.append(f"· hypotheses: the Challenge module {obj['module']} did not build (its output is in "
253
+ f"the job's side log {SIDE_LOG}, outside the sealed log)")
254
+ return summary, refusals, lines
255
+
256
+
257
+ # ---------------------------------------------------------------------------------------------------------
258
+ # The ledger side (stage H3): the sealed facts, judged per claim. Lean printed the facts; this decides.
259
+
260
+ ADMISSIBLE_KINDS = ("def", "inductive") # an assumption is a def or an inductive Prop (never an axiom)
261
+ GATE_STAGE_OPEN = "at the gate stage nothing is discharged (discharge needs the comparator tier: --stage promote)"
262
+
263
+
264
+ def facts(text: str | None) -> dict:
265
+ """The section of a sealed verify log as the facts the ledger reads: {ok, why} and, when ok, `decls`
266
+ {theorem: hyp-decl object}, `missing` (decls not in the build), `challenge` {theorem: [hyp-challenge
267
+ objects]}, `corollaries` {(corollary, of): [drops as a frozenset, ...]}, `proofs` {(proof, proves)},
268
+ `witnesses` {(witness, of)}, `skips` {theorem: reason}, `decl_error` and `challenge_error` (the first
269
+ hyp-error message of each part, else None), `builds_failed` [module] and `configs` (hyp-done's list: empty
270
+ when the Challenge part did not run). Not ok (`why` says which): no log, no section, or a section the
271
+ write-time check would refuse."""
272
+ if text is None:
273
+ return {"ok": False, "why": "no sealed verify log of the gate receipt is readable here"}
274
+ sec = parse(text)
275
+ if not sec["present"]:
276
+ return {"ok": False, "why": f"the sealed verify log has no {FORMAT} section (a verify script without the "
277
+ f"probe): regenerate verify.sh or the sbatch template and re-gate"}
278
+ if sec["problems"] or sec["done"] is None:
279
+ first = sec["problems"][0] if sec["problems"] else "no final `hyp-done:` line"
280
+ return {"ok": False, "why": f"the {FORMAT} section of the sealed verify log is incomplete ({first})"}
281
+ fx: dict = {"ok": True, "why": None, "decls": {}, "missing": set(), "challenge": {}, "corollaries": {},
282
+ "proofs": set(), "witnesses": set(), "skips": {}, "decl_error": None, "challenge_error": None,
283
+ "builds_failed": [], "configs": list(sec["done"]["configs"])}
284
+ for tag, o in sec["records"]:
285
+ if tag == "hyp-decl":
286
+ fx["decls"][o["theorem"]] = o
287
+ elif tag == "hyp-missing":
288
+ fx["missing"].add(o["theorem"])
289
+ elif tag == "hyp-challenge":
290
+ fx["challenge"].setdefault(o["theorem"], []).append(o)
291
+ elif tag == "hyp-corollary":
292
+ fx["corollaries"].setdefault((o["corollary"], o["of"]), []).append(frozenset(o["drops"]))
293
+ elif tag == "hyp-proof":
294
+ fx["proofs"].add((o["proof"], o["proves"]))
295
+ elif tag == "hyp-witness":
296
+ fx["witnesses"].add((o["witness"], o["of"]))
297
+ elif tag == "hyp-skip":
298
+ fx["skips"].setdefault(o["theorem"], o["reason"])
299
+ elif tag == "hyp-error":
300
+ fx[f"{o['phase']}_error"] = fx[f"{o['phase']}_error"] or o["message"]
301
+ elif tag == "hyp-challenge-build" and not o["ok"]:
302
+ fx["builds_failed"].append(o["module"])
303
+ return fx
304
+
305
+
306
+ def _challenge_problem(fx: dict) -> str | None:
307
+ """Why the Challenge part's facts cannot be used (None when they can)."""
308
+ if fx["challenge_error"]:
309
+ return f"the Challenge part of the probe did not run ({fx['challenge_error'][:160]})"
310
+ if fx["builds_failed"]:
311
+ return f"the Challenge module(s) {', '.join(fx['builds_failed'])} did not build"
312
+ if not fx["configs"]:
313
+ return "the Challenge part of the probe did not run (hyp-done lists no configuration)"
314
+ return None
315
+
316
+
317
+ def _binder_problems(obj: dict, hyps: list[str], where: str) -> tuple[list[str], list[str]]:
318
+ """(not-in-type, inadmissible) details for the listed hypotheses against one hyp-decl/hyp-challenge object:
319
+ every binder headed by a listed name must be explicit, at least one must exist, and its head must be a def
320
+ or an inductive Prop."""
321
+ absent, bad = [], []
322
+ for h in hyps:
323
+ bs = [b for b in obj["binders"] if b["head"] == h]
324
+ if not bs:
325
+ absent.append(f"{h} is not the head of a hypothesis binder of {where}")
326
+ elif not all(b["explicit"] for b in bs):
327
+ absent.append(f"{h} is a binder of {where}, but not an explicit one (positions "
328
+ f"{[b['i'] for b in bs if not b['explicit']]})")
329
+ elif bs[0]["kind"] not in ADMISSIBLE_KINDS:
330
+ bad.append(f"{h} is a{'n' if bs[0]['kind'][:1] in 'aeiou' else ''} {bs[0]['kind']}, not a def or an "
331
+ f"inductive Prop (in {where})")
332
+ return absent, bad
333
+
334
+
335
+ def resolve(cid: str, by_id: dict) -> str:
336
+ """A claim id after following superseded_by (as the claims schema does), cycle-safe."""
337
+ seen = [cid]
338
+ while isinstance((by_id.get(seen[-1]) or {}).get("superseded_by"), str) \
339
+ and by_id[seen[-1]]["superseded_by"] in by_id and by_id[seen[-1]]["superseded_by"] not in seen:
340
+ seen.append(by_id[seen[-1]]["superseded_by"])
341
+ return seen[-1]
342
+
343
+
344
+ def evaluate(claims: list[dict], fx: dict, *, stage: str, bound: str | None, comparator_ok: bool,
345
+ credited: dict[str, set[str]], clean: dict[str, bool]) -> dict[str, dict]:
346
+ """Proposal 0003, stage H3: judge every claim that uses `hypotheses`, `discharges` or `witness` (and every
347
+ claim whose hypotheses a corollary discharges) from the sealed facts `fx` (`facts`). Recomputed on every
348
+ call, never stored. `credited` {claim id: the non-smoke comparator names at the gate-bound commit that judge
349
+ it} (empty at the gate stage); `clean` {claim id: no open, failed or unknown diagnostic so far}.
350
+
351
+ {claim id: {"diags": [(code, detail)], "hypotheses": [{decl, state, by, via}] or None, "witness": {claim,
352
+ state} or None}}. A hypothesis A of T is discharged only at the promote stage with a clean comparator tier,
353
+ by a clean claim T' whose `discharges` names T (superseded_by followed) and A, when T, T' and each proof claim
354
+ have exactly one credited Challenge name, the facts hold `hyp-corollary` T' of T dropping exactly the
355
+ discharged names, and, for each proof P, `hyp-proof` P proves A, unless P's Challenge type quantifies over
356
+ data (a parameterized assumption, open question 3: the corollary alone is the evidence and P is attribution).
357
+ Anything the facts cannot settle is `hypotheses-unchecked`, never discharged."""
358
+ from . import claims as claims_mod
359
+ by_id = {str(c.get("id")): c for c in claims}
360
+ out: dict[str, dict] = {}
361
+ c12 = (bound or "")[:12] or "(no gate-bound commit)"
362
+
363
+ def slot(cid):
364
+ return out.setdefault(cid, {"diags": [], "hypotheses": None, "witness": None, "unchecked": []})
365
+
366
+ def name_of(cid) -> tuple[str | None, str | None]:
367
+ """(the one credited name, None) or (None, why not)."""
368
+ ns = credited.get(cid) or set()
369
+ if len(ns) == 1:
370
+ return next(iter(ns)), None
371
+ if not ns:
372
+ return None, "not-compared"
373
+ return None, f"{cid} is judged by more than one comparator name ({', '.join(sorted(ns))}): ambiguous"
374
+
375
+ promote = stage == "promote"
376
+ chal_why = _challenge_problem(fx) if fx.get("ok") and promote else None
377
+ discharge_ok: dict[str, dict] = {} # corollary id -> {target, hyps, proofs}
378
+ witness_state: dict[str, str] = {}
379
+ for c in claims:
380
+ cid = str(c.get("id"))
381
+ keys = claims_mod.uses_conditional_keys(c)
382
+ if not keys:
383
+ continue
384
+ s = slot(cid)
385
+ hyps = [h for h in c.get("hypotheses") or [] if isinstance(h, str)]
386
+ if not fx.get("ok"):
387
+ s["unchecked"].append(fx.get("why") or "no facts")
388
+ continue
389
+ decl = str(c.get("decl") or "")
390
+ if hyps or c.get("witness") is not None:
391
+ if fx["decl_error"]:
392
+ s["unchecked"].append(f"the decl part of the probe did not run ({fx['decl_error'][:160]})")
393
+ elif decl not in fx["decls"]:
394
+ s["unchecked"].append(f"{decl} is not in the probe's decl facts"
395
+ + (" (not in the built environment)" if decl in fx["missing"] else ""))
396
+ else:
397
+ absent, bad = _binder_problems(fx["decls"][decl], hyps, decl)
398
+ s["diags"] += [("hypothesis-not-in-type", d) for d in absent]
399
+ s["diags"] += [("hypothesis-inadmissible", d) for d in bad]
400
+ if c.get("witness") is not None and fx["decls"][decl]["data_binders"] == 0:
401
+ s["diags"].append(("witness-type-mismatch", f"{decl} takes no parameters, so a witness shows "
402
+ f"nothing: prove its hypotheses instead"))
403
+ witness_state[cid] = "mismatch"
404
+ if not promote:
405
+ continue
406
+ if chal_why:
407
+ s["unchecked"].append(chal_why)
408
+ continue
409
+ if hyps:
410
+ n, why = name_of(cid)
411
+ if why and why != "not-compared":
412
+ s["unchecked"].append(why)
413
+ elif n and n not in fx["challenge"]:
414
+ s["unchecked"].append(f"the Challenge theorem {n} is not in the probe's Challenge facts")
415
+ elif n:
416
+ for obj in fx["challenge"][n]:
417
+ absent, _bad = _binder_problems(obj, hyps, f"the Challenge theorem {n} ({obj['config']})")
418
+ s["diags"] += [("hypothesis-not-in-type", d) for d in absent if
419
+ ("hypothesis-not-in-type", d) not in s["diags"]]
420
+ d = c.get("discharges")
421
+ if isinstance(d, dict) and isinstance(d.get("claim"), str):
422
+ tid = resolve(d["claim"], by_id)
423
+ dh = [h for h in d.get("hypotheses") or [] if isinstance(h, str)]
424
+ ps = [p for p in d.get("proofs") or [] if isinstance(p, str)]
425
+ names, missing, ambiguous = {}, [], []
426
+ for who in [cid, tid, *ps]:
427
+ n, why = name_of(who)
428
+ if n:
429
+ names[who] = n
430
+ elif why == "not-compared":
431
+ missing.append(who)
432
+ else:
433
+ ambiguous.append(why)
434
+ if ambiguous:
435
+ s["unchecked"] += ambiguous
436
+ elif missing:
437
+ s["diags"].append(("discharge-not-compared",
438
+ f"{', '.join(dict.fromkeys(missing))}: in no comparator configuration at {c12} "
439
+ f"(not smoke); the corollary {cid}, the claim it discharges ({tid}) and each "
440
+ f"proof claim must be compared in one build"))
441
+ elif names[tid] in fx["skips"]:
442
+ s["unchecked"].append(f"the corollary search was skipped for {names[tid]} "
443
+ f"({fx['skips'][names[tid]][:160]})")
444
+ else:
445
+ ok = True
446
+ got = fx["corollaries"].get((names[cid], names[tid]), [])
447
+ if frozenset(dh) not in got:
448
+ ok = False
449
+ other = sorted(sorted(g) for g in got)
450
+ s["diags"].append(("discharge-type-mismatch",
451
+ f"the Challenge theorem {names[cid]} is not {names[tid]}'s type with exactly "
452
+ f"the binders of {dh} removed (compared strictly: no unfolding, binder order "
453
+ f"and annotations kept)" + (f"; it drops {other} instead" if other else "")))
454
+ params = {}
455
+ for h, p in zip(dh, ps, strict=False):
456
+ pn = names[p]
457
+ if (pn, h) in fx["proofs"]:
458
+ params[h] = False
459
+ elif pn not in fx["challenge"]:
460
+ ok = False
461
+ s["unchecked"].append(f"the Challenge theorem {pn} ({p}) is not in the probe's Challenge "
462
+ f"facts")
463
+ elif all(o["data_binders"] == 0 for o in fx["challenge"][pn]):
464
+ ok = False
465
+ s["diags"].append(("discharge-type-mismatch",
466
+ f"the Challenge theorem {pn} ({p}) does not have exactly the type {h} "
467
+ f"(compared strictly, no unfolding)"))
468
+ else:
469
+ params[h] = True # quantified: a parameterized assumption, attribution only
470
+ if ok and comparator_ok:
471
+ discharge_ok[cid] = {"target": tid, "hyps": dh, "proofs": dict(zip(dh, ps, strict=False))}
472
+ w = c.get("witness")
473
+ if isinstance(w, str) and cid not in witness_state:
474
+ n, _why = name_of(cid)
475
+ wn, _wwhy = name_of(w)
476
+ if not (n and wn and comparator_ok):
477
+ witness_state[cid] = "unchecked"
478
+ elif any(o["data_binders"] == 0 for o in fx["challenge"].get(n, [])):
479
+ s["diags"].append(("witness-type-mismatch", f"the Challenge theorem {n} takes no parameters, so a "
480
+ f"witness shows nothing: prove its hypotheses instead"))
481
+ witness_state[cid] = "mismatch"
482
+ elif (wn, n) in fx["witnesses"]:
483
+ witness_state[cid] = "checked"
484
+ elif wn not in fx["challenge"] or n not in fx["challenge"]:
485
+ witness_state[cid] = "unchecked"
486
+ s["unchecked"].append(f"the Challenge theorem {wn if wn not in fx['challenge'] else n} is not in "
487
+ f"the probe's Challenge facts")
488
+ else:
489
+ s["diags"].append(("witness-type-mismatch",
490
+ f"the Challenge theorem {wn} ({w}) is not the expected witness of {n}: ∃ over its "
491
+ f"parameters, in order, of the ∧ of all its hypotheses, in order"))
492
+ witness_state[cid] = "mismatch"
493
+
494
+ def is_clean(cid) -> bool:
495
+ s = out.get(cid)
496
+ bad = s and (s["unchecked"] or any(code not in ("hypothesis-open",) for code, _ in s["diags"]))
497
+ return bool(clean.get(cid)) and not bad
498
+
499
+ for c in claims: # the hypotheses rows and hypothesis-open, from the discharges
500
+ cid = str(c.get("id"))
501
+ hyps = [h for h in c.get("hypotheses") or [] if isinstance(h, str)]
502
+ if cid not in out and not hyps:
503
+ continue
504
+ s = slot(cid)
505
+ if c.get("witness") is not None:
506
+ s["witness"] = {"claim": c.get("witness"), "state": witness_state.get(cid, "unchecked")}
507
+ if not hyps:
508
+ continue
509
+ rows = []
510
+ for h in hyps:
511
+ cands = [k for k, v in discharge_ok.items() if v["target"] == cid and h in v["hyps"]]
512
+ good = [k for k in cands if is_clean(k) and is_clean(discharge_ok[k]["proofs"][h])]
513
+ if good:
514
+ k = good[0]
515
+ rows.append({"decl": h, "state": "discharged",
516
+ "by": {"proof": discharge_ok[k]["proofs"][h], "corollary": k}, "via": None})
517
+ continue
518
+ rows.append({"decl": h, "state": "open", "by": None, "via": None})
519
+ if s["unchecked"]:
520
+ continue # unchecked says why; hypothesis-open would only repeat it
521
+ claimed = [str(x.get("id")) for x in claims if isinstance(x.get("discharges"), dict)
522
+ and isinstance(x["discharges"].get("claim"), str)
523
+ and resolve(x["discharges"]["claim"], by_id) == cid
524
+ and h in (x["discharges"].get("hypotheses") or [])]
525
+ if not promote:
526
+ why = GATE_STAGE_OPEN
527
+ elif not comparator_ok:
528
+ why = f"the comparator tier is not clean at {c12}, so no discharge counts"
529
+ elif claimed:
530
+ why = (f"{', '.join(claimed)} claim{'s' if len(claimed) == 1 else ''} to discharge it, but the "
531
+ f"evidence does not establish it (see {'their' if len(claimed) > 1 else 'its'} diagnostics)")
532
+ else:
533
+ why = "no claim discharges it"
534
+ s["diags"].append(("hypothesis-open", f"{h}: outstanding at {c12}; {why}"))
535
+ s["hypotheses"] = rows
536
+ for cid, s in out.items():
537
+ if s["unchecked"]:
538
+ s["diags"].append(("hypotheses-unchecked",
539
+ f"{cid} sets {', '.join(claims_mod.uses_conditional_keys(by_id[cid])) or 'hypotheses'}"
540
+ f", but the facts to judge them are missing (proposal 0003): "
541
+ + "; ".join(dict.fromkeys(s["unchecked"]))))
542
+ return out
543
+
544
+
545
+ def judge_at(repo, commit: str, claims: list[dict], text: str | None, *, comparator_ok: bool,
546
+ smoke=None) -> dict:
547
+ """Proposal 0003, stage H4: the conditional keys of `claims` (claims.yaml at `commit`) judged from `text`,
548
+ the sealed verify log, for the readers that have no registry record (`receipt check`, `index add|check`).
549
+ The promote stage when `comparator_ok` (a valid comparator receipt binds `commit`), else the gate stage, where
550
+ nothing is discharged. A claim is clean here when its declaration occurs in its file and, at the promote
551
+ stage, a required theorem or lemma is credited by a non-smoke configuration (the ledger's own per-claim
552
+ checks; the receipts themselves are the caller's checks). Recomputed on every call, never stored.
553
+
554
+ {stage, facts_ok, facts_why, claims {id: {hypotheses, witness, diagnostics}}, conditional [ids], discharged
555
+ [{decl, claim, corollary, proof}], outstanding [decls], failed [{claim, code, detail}], open [{claim, code,
556
+ detail}], credited {id: set}, qualified set}: `conditional` lists the claims with hypotheses, own or
557
+ inherited through depends_on (a claim with every hypothesis discharged stays conditional), `outstanding`
558
+ their open hypotheses, `failed` and `open` the diagnostics of those classes."""
559
+ from . import claims as claims_mod
560
+ from . import comparator_config as cc
561
+ from . import ledger as ledger_mod
562
+ stage = "promote" if comparator_ok else "gate"
563
+ read = claims_mod._reader(repo, commit)
564
+ qualified = cc.qualified_decls(read, claims)
565
+ credited: dict[str, set[str]] = {}
566
+ if comparator_ok:
567
+ names, todo = cc._names(cc._configs_at(repo, commit), cc._sidecar_at(repo, commit), smoke)
568
+ mapped = cc.mapped_names(claims)
569
+ credited = {str(c.get("id")): cc.credited_names(names - todo, c, qualified, mapped) for c in claims}
570
+ clean = {}
571
+ for c in claims:
572
+ cid = str(c.get("id"))
573
+ missing = bool(c.get("decl") and isinstance(c.get("file"), str) and claims_mod.decl_problems(read, [c]))
574
+ needs = (comparator_ok and c.get("status") in ledger_mod.REQUIRED_STATUSES
575
+ and c.get("kind") in cc.CLAIM_KINDS)
576
+ clean[cid] = not missing and (not needs or bool(credited.get(cid)))
577
+ fx = facts(text)
578
+ res = evaluate(claims, fx, stage=stage, bound=commit, comparator_ok=comparator_ok, credited=credited,
579
+ clean=clean)
580
+ rows = []
581
+ for c in claims:
582
+ cid = str(c.get("id"))
583
+ e = res.get(cid) or {}
584
+ row = {"id": cid, "depends_on": [d for d in c.get("depends_on") or [] if isinstance(d, str)],
585
+ "diagnostics": [ledger_mod._diag(code, detail) for code, detail in e.get("diags") or []]}
586
+ if e.get("hypotheses") is not None:
587
+ row["hypotheses"] = e["hypotheses"]
588
+ if e.get("witness") is not None:
589
+ row["witness"] = e["witness"]
590
+ rows.append(row)
591
+ by_id = {r["id"]: r for r in rows}
592
+
593
+ def closes(dep) -> bool: # as the ledger: a conditional-class code never blocks
594
+ return clean.get(dep["id"], False) and not any(
595
+ ledger_mod.CODES[d["code"]][0] != "conditional" for d in dep["diagnostics"])
596
+ ledger_mod._inherit(rows, by_id, closes)
597
+ out: dict = {"stage": stage, "facts_ok": bool(fx.get("ok")), "facts_why": fx.get("why"), "claims": {},
598
+ "conditional": [], "discharged": [], "outstanding": [], "failed": [], "open": [],
599
+ "credited": credited, "qualified": qualified}
600
+ outstanding: set[str] = set()
601
+ for r in rows:
602
+ if r.get("hypotheses") is None and r.get("witness") is None and not r["diagnostics"]:
603
+ continue
604
+ out["claims"][r["id"]] = {"hypotheses": r.get("hypotheses"), "witness": r.get("witness"),
605
+ "diagnostics": r["diagnostics"]}
606
+ if r.get("hypotheses"):
607
+ out["conditional"].append(r["id"])
608
+ for h in r.get("hypotheses") or []:
609
+ if h["state"] == "open":
610
+ outstanding.add(h["decl"])
611
+ elif not h.get("via"):
612
+ out["discharged"].append({"decl": h["decl"], "claim": r["id"], "corollary": h["by"]["corollary"],
613
+ "proof": h["by"]["proof"]})
614
+ for d in r["diagnostics"]:
615
+ cls = ledger_mod.CODES[d["code"]][0]
616
+ if cls in ("failed", "open"):
617
+ out[cls].append({"claim": r["id"], "code": d["code"], "detail": d["detail"]})
618
+ out["outstanding"] = sorted(outstanding)
619
+ return out
620
+
621
+
622
+ def job_sh() -> str:
623
+ """Shell functions for a verify script: `hypotheses_run LOG DIR LEAN_PATH [SIDE_LOG]` appends the hyp-probe/1
624
+ section to LOG (nothing when there is no claims.yaml), writing the Lean program and its scratch files under
625
+ DIR and the Challenge build's output to SIDE_LOG (default DIR/hyp-challenge-build.log), never to LOG. It runs
626
+ `$RUN env LEAN_PATH=... lean --run` like claim_axioms_run and `$RUN lake build` for the Challenge modules,
627
+ reads the claims with `claims_decls` (claim_axioms.job_sh, which must come first), and never fails the job:
628
+ a part that cannot run gives one `hyp-error` line."""
629
+ lean = SCRIPT.read_text(encoding="utf-8")
630
+ return ("# Conditional-claim facts read from the built environment (lean-pkg's HypProbe.lean, core Lean only;\n"
631
+ "# proposal 0003): the `" + HEADER + "` section, one `hyp-*: {json}` line\n"
632
+ "# per fact, then `hyp-done`. The Challenge is built into a side log, never into this log.\n"
633
+ "hyp_json_str() {\n"
634
+ " printf '\"%s\"' \"$(printf '%s' \"$1\" | tr -d '\\000-\\037' | sed -e 's/\\\\/\\\\\\\\/g' "
635
+ "-e 's/\"/\\\\\"/g')\"\n"
636
+ "}\n"
637
+ "hyp_error() { # OUT PHASE EXIT FILE...: one hyp-error line, the first error line without paths\n"
638
+ " local out=$1 phase=$2 rc=$3 msg\n"
639
+ " shift 3\n"
640
+ " msg=$(cat \"$@\" 2>/dev/null | grep -m1 -i 'error' | sed -e 's#[^ ]*/##g' | cut -c1-200 || true)\n"
641
+ " echo \"hyp-error: {\\\"phase\\\":\\\"$phase\\\",\\\"message\\\":$(hyp_json_str \"exit $rc${msg:+: $msg}\")}\""
642
+ " >>\"$out\"\n"
643
+ "}\n"
644
+ "hypotheses_run() {\n"
645
+ " [ -f claims.yaml ] || return 0\n"
646
+ " local dir=$2 side=${4:-$2/" + SIDE_LOG + "} pairs names mods rc cfgs=\"\" cfg m ok built=1 "
647
+ "decls chal list=\"\"\n"
648
+ " mkdir -p \"$dir\"\n"
649
+ " local out=\"$dir/hyp.out\" part=\"$dir/hyp.part\" err=\"$dir/hyp.err\"\n"
650
+ " : >\"$out\"\n"
651
+ " cat >\"$dir/HypProbe.lean\" <<'LEAN_PKG_HYP_PROBE'\n" + lean + "LEAN_PKG_HYP_PROBE\n"
652
+ " pairs=$(claims_decls claims.yaml)\n"
653
+ " if [ -n \"$pairs\" ]; then\n"
654
+ " names=$(printf '%s\\n' \"$pairs\" | cut -f1)\n"
655
+ " mods=$(printf '%s\\n' \"$pairs\" | cut -f2 | grep '\\.lean$' | sed -e 's/\\.lean$//' -e 's|/|.|g'"
656
+ " | sort -u || true)\n"
657
+ " rc=0\n"
658
+ " # shellcheck disable=SC2086 # one word per module and per name\n"
659
+ " ${RUN:-} env LEAN_PATH=\"$3\" lean --run \"$dir/HypProbe.lean\" decl $mods -- $names >\"$part\" "
660
+ "2>\"$err\" || rc=$?\n"
661
+ " if [ \"$rc\" = 0 ]; then grep -E '^hyp-[a-z-]+: ' \"$part\" >>\"$out\" || true\n"
662
+ " else hyp_error \"$out\" decl \"$rc\" \"$part\" \"$err\"; fi\n"
663
+ " fi\n"
664
+ " if grep -Eq '^[[:blank:]-]+(hypotheses|discharges|witness):' claims.yaml; then\n"
665
+ " for cfg in comparator*.json comparator/config*.json; do\n"
666
+ " if [ -f \"$cfg\" ]; then cfgs=\"$cfgs $cfg\"; list=\"$list${list:+,}$(hyp_json_str \"$cfg\")\"; fi\n"
667
+ " done\n"
668
+ " if [ -n \"$cfgs\" ]; then\n"
669
+ " rc=0\n"
670
+ " # shellcheck disable=SC2086 # one word per configuration\n"
671
+ " ${RUN:-} env LEAN_PATH=\"$3\" lean --run \"$dir/HypProbe.lean\" modules $cfgs >\"$part\" "
672
+ "2>\"$err\" || rc=$?\n"
673
+ " if [ \"$rc\" != 0 ]; then hyp_error \"$out\" challenge \"$rc\" \"$part\" \"$err\"\n"
674
+ " else\n"
675
+ " sed -n 's/^challenge-module: //p' \"$part\" >\"$dir/modules\"\n"
676
+ " : >\"$side\"\n"
677
+ " while IFS= read -r m; do\n"
678
+ " ok=true\n"
679
+ " ${RUN:-} lake build \"$m\" </dev/null >>\"$side\" 2>&1 || { ok=false; built=0; }\n"
680
+ " echo \"hyp-challenge-build: {\\\"module\\\":$(hyp_json_str \"$m\"),\\\"ok\\\":$ok}\" >>\"$out\"\n"
681
+ " done <\"$dir/modules\"\n"
682
+ " if [ \"$built\" = 1 ]; then\n"
683
+ " rc=0\n"
684
+ " # shellcheck disable=SC2086 # one word per configuration\n"
685
+ " ${RUN:-} env LEAN_PATH=\"$3\" lean --run \"$dir/HypProbe.lean\" challenge $cfgs >\"$part\" "
686
+ "2>\"$err\" || rc=$?\n"
687
+ " if [ \"$rc\" = 0 ]; then grep -E '^hyp-[a-z-]+: ' \"$part\" >>\"$out\" || true\n"
688
+ " else hyp_error \"$out\" challenge \"$rc\" \"$part\" \"$err\"; fi\n"
689
+ " else\n"
690
+ " echo \"hyp-error: {\\\"phase\\\":\\\"challenge\\\",\\\"message\\\":\\\"a Challenge module did "
691
+ "not build (its output: the side log " + SIDE_LOG + ")\\\"}\" >>\"$out\"\n"
692
+ " fi\n"
693
+ " fi\n"
694
+ " fi\n"
695
+ " fi\n"
696
+ " decls=$(grep -c -E '^hyp-(decl|missing): ' \"$out\" || true)\n"
697
+ " chal=$(grep -c '^hyp-challenge: ' \"$out\" || true)\n"
698
+ " {\n"
699
+ " echo \"" + HEADER + "\"\n"
700
+ " cat \"$out\"\n"
701
+ " echo \"hyp-done: {\\\"v\\\":1,\\\"decls\\\":$decls,\\\"challenge\\\":$chal,\\\"configs\\\":[$list]}\"\n"
702
+ " } >>\"$1\"\n"
703
+ "}\n")
704
+
705
+
706
+ # ---------------------------------------------------------------------------------------------------------
707
+ # The local probe (tests, and an author's own check before a job)
708
+
709
+ class ProbeError(Exception):
710
+ """The probe could not run: refused, never passed."""
711
+
712
+
713
+ def probe(repo, toolchain: str | None = None, timeout: float = DEFAULT_TIMEOUT) -> str:
714
+ """Run the job's block (claim_axioms.job_sh's claims reader, then `hypotheses_run`) on a built checkout with
715
+ its toolchain first on PATH; the section it appends, as a verify log holds it. It builds the Challenge
716
+ modules (`lake build`, into the checkout's .lake, as the job does), so it is not sandboxed."""
717
+ from . import claim_axioms as ca
718
+ from . import dup_constants as dc
719
+ repo = pathlib.Path(repo).resolve()
720
+ try:
721
+ _roots, prefix = dc.project_roots(repo, toolchain)
722
+ except dc.ProbeError as e:
723
+ raise ProbeError(str(e)) from None
724
+ with tempfile.TemporaryDirectory(prefix="lean-pkg-hyp-") as d:
725
+ log = pathlib.Path(d) / "verify.log"
726
+ script = ("set -euo pipefail\n" + ca.job_sh() + job_sh()
727
+ + 'hypotheses_run "$1" "$2/work" "$(lake env printenv LEAN_PATH)" "$2/' + SIDE_LOG + '"\n')
728
+ env = {**os.environ, "PATH": f"{prefix / 'bin'}{os.pathsep}{os.environ.get('PATH', '/usr/bin:/bin')}"}
729
+ env.pop("RUN", None)
730
+ try:
731
+ p = subprocess.run(["bash", "-c", script, "hypotheses_run", str(log), d], cwd=repo, env=env,
732
+ stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=timeout,
733
+ start_new_session=True)
734
+ except subprocess.TimeoutExpired:
735
+ raise ProbeError("the probe did not finish in time (--timeout)") from None
736
+ except OSError as e:
737
+ raise ProbeError(f"cannot run the probe: {e}") from None
738
+ if p.returncode != 0:
739
+ raise ProbeError(f"the probe failed: {(p.stderr.strip().splitlines()[-1:] or [f'exit {p.returncode}'])[0][:400]}")
740
+ return log.read_text(encoding="utf-8") if log.is_file() else ""
741
+
742
+
743
+ PROGRAM = "python3 -m lean_pkg.hypotheses"
744
+
745
+
746
+ def main(argv: list[str] | None = None) -> int:
747
+ ap = argparse.ArgumentParser(
748
+ prog=PROGRAM, formatter_class=argparse.RawDescriptionHelpFormatter,
749
+ description="Print the hyp-probe/1 section the lower-tier verify scripts write (proposal 0003): the "
750
+ "claims' Prop hypotheses read from the built environment and, when claims.yaml uses "
751
+ "hypotheses, discharges or witness, the Challenge facts (corollary, proof, witness). It "
752
+ "builds the Challenge modules, as the job does. Facts only: nothing is judged as a claim.",
753
+ epilog="examples:\n"
754
+ " python3 -m lean_pkg.hypotheses --repo .\n"
755
+ " python3 -m lean_pkg.hypotheses --repo . --json\n"
756
+ "exit codes: 0 the section is complete, 1 refused or the probe failed, 2 usage.\n"
757
+ "docs: https://lean-pkg.github.io/lean-pkg/formats.html")
758
+ ap.add_argument("--repo", required=True, metavar="DIR", help="the package checkout, a built Lake project")
759
+ ap.add_argument("--toolchain", metavar="TC", help="default: the project's lean-toolchain")
760
+ ap.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT, metavar="SECONDS")
761
+ ap.add_argument("--json", dest="json_out", action="store_true", help="the structure judgement as JSON on stdout")
762
+ args = ap.parse_args(sys.argv[1:] if argv is None else list(argv))
763
+ claims = pathlib.Path(args.repo) / "claims.yaml"
764
+ if not claims.is_file():
765
+ print(f"hypotheses: refused: {claims}: no claims.yaml (the probe reads its claims)", file=sys.stderr)
766
+ return 1
767
+ try:
768
+ text = probe(args.repo, args.toolchain, args.timeout)
769
+ except ProbeError as e:
770
+ print(f"hypotheses: refused: {e}", file=sys.stderr)
771
+ return 1
772
+ summary, refusals, lines = judge_structure(text, claims.read_bytes())
773
+ if summary is None:
774
+ refusals = refusals + ["the probe wrote no section"]
775
+ if args.json_out:
776
+ print(json.dumps({"ok": not refusals, "format": FORMAT, "summary": summary, "refusals": refusals,
777
+ "lines": lines, "section": text.splitlines()}, indent=2))
778
+ else:
779
+ sys.stdout.write(text)
780
+ for r in refusals:
781
+ print(f"hypotheses: ✗ {r}", file=sys.stderr)
782
+ for line in lines:
783
+ print(f"hypotheses: {line}", file=sys.stderr)
784
+ return 0 if not refusals else 1
785
+
786
+
787
+ if __name__ == "__main__":
788
+ sys.exit(main())