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,382 @@
1
+ # comparator_contracts -- `comparator check NAME --contracts-only`: the compare step of every configuration,
2
+ # no kernel, no receipt
3
+ """A contracts-only diagnostic over every comparator configuration of a checkout at once (#280).
4
+
5
+ Why: Lake v4.35.0 has no compare-only mode. `lake comparator` exports the Challenge and the Solution,
6
+ compares them and, only when they match, runs the kernels; a statement mismatch (typically a private
7
+ helper or a generated `_proof_N` whose module-dependent name differs between a copied reference and
8
+ production, docs/comparator.md "Private helpers and copied references") is found only after a gate's
9
+ worth of work, one configuration at a time.
10
+
11
+ How: every distinct module the configurations name is exported ONCE with the toolchain's own
12
+ `leanexport` (the exporter `lake comparator` runs), over the union of the export targets of the
13
+ configurations that use it (Lake's `compareIt` list: the Quot constants when `Quot.sound` is permitted,
14
+ the theorem names, the permitted axioms, the kernel's primitive constants, the definition holes), with
15
+ --ignore-missing, in the bwrap sandbox `lean-exercise` uses (`exercise_forbid.run_export`) unless
16
+ --no-sandbox. A configuration whose targets are not all in both exports is an `error` (Lake's own
17
+ export of it would fail), never compared. Then
18
+ `scripts/ContractsOnly.lean` runs Lake's own public `Lake.Check.compareAt` and `Lake.Check.checkAxioms`
19
+ on each configuration's pair of exports, exactly as `verifyMatch.verifyCompare` does; their result is the
20
+ verdict, nothing here re-implements the comparison. A failing configuration also gets a diagnosis that
21
+ is display only: the breadcrumb (the chain of declarations from the target to the constant Lake refused,
22
+ from a walk that mirrors `Compare.loop`), the first differing ConstantInfo field (with Expr's BEq, as
23
+ Lake compares) and the first differing subterm as a short descriptor. A `hint` may name a private
24
+ module or a generated auxiliary; it is text for the reader and never changes a verdict.
25
+
26
+ Never acceptance: no kernel runs, no receipt, registry entry or event is written, and nothing in the
27
+ checkout is written. The exports live in a temporary directory that is removed afterwards. A match here is
28
+ not a pass, and a difference is a reason to fix the configuration before a gate, not the gate's
29
+ verdict; only `lake comparator` judges, inside a gate.
30
+
31
+ Python API: `run(repo, configs=None, exports=None, sandboxed=True) -> report` (schema
32
+ lean-pkg-comparator-contracts/1). Documented in docs/comparator.md, "A contracts-only diagnostic".
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import json
38
+ import os
39
+ import pathlib
40
+ import shutil
41
+ import subprocess
42
+ import tempfile
43
+
44
+ from . import dup_constants as dc
45
+ from . import exercise_forbid as fb
46
+
47
+ SCHEMA = "lean-pkg-comparator-contracts/1"
48
+ SCRIPT = pathlib.Path(__file__).with_name("scripts") / "ContractsOnly.lean"
49
+ NEVER = ("never acceptance: no kernel ran and nothing was written (no receipt, no registry entry, no file in "
50
+ "the checkout); only `lake comparator` in a gate judges")
51
+ DOCS = "docs/comparator.md#a-contracts-only-diagnostic"
52
+ PRIVATE_DOCS = "docs/comparator.md#private-helpers-and-copied-references"
53
+ LET_DOCS = "docs/comparator.md#a-let-kept-on-one-side"
54
+ PREFLIGHT_DOCS = "docs/comparator.md#before-receipt-work"
55
+
56
+ # Lake v4.35.0 `Lake.CLI.Check.primitiveTargets` (also in scripts/ContractsOnly.lean; the test compares
57
+ # both with the toolchain's source when it is installed).
58
+ PRIMITIVE_TARGETS = (
59
+ "Nat.add", "Nat.sub", "Nat.mul", "Nat.pow", "Nat.gcd", "Nat.div", "Nat.mod", "Nat.beq", "Nat.ble",
60
+ "Nat.land", "Nat.lor", "Nat.xor", "Nat.shiftLeft", "Nat.shiftRight", "String.ofList", "Char.ofNat",
61
+ "List", "eagerReduce", "Nat", "String", "String.mk", "Char", "optParam", "autoParam", "semiOutParam",
62
+ "outParam")
63
+ QUOT_TARGETS = ("Quot", "Quot.mk", "Quot.lift", "Quot.ind") # `builtinTargets`, when Quot.sound is permitted
64
+
65
+
66
+ class ContractsError(Exception):
67
+ """The diagnostic could not run at all (no toolchain, no configuration, a helper failure)."""
68
+
69
+
70
+ def discover(repo: pathlib.Path) -> list[str]:
71
+ """The configurations the runner compares: comparator*.json at the root, comparator/config*.json."""
72
+ found = sorted(p for p in repo.glob("comparator*.json") if p.is_file()) + \
73
+ sorted(p for p in (repo / "comparator").glob("config*.json") if p.is_file())
74
+ return [p.relative_to(repo).as_posix() for p in found]
75
+
76
+
77
+ def load_slot(repo: pathlib.Path, rel: str) -> dict:
78
+ """{config, challenge_module, solution_module, theorems, definitions, axioms} or {config, error}."""
79
+ slot: dict = {"config": rel}
80
+ try:
81
+ cfg = json.loads((repo / rel).read_text(encoding="utf-8"))
82
+ except (OSError, ValueError) as e:
83
+ return {**slot, "error": f"cannot read the configuration: {e}"}
84
+ if not isinstance(cfg, dict):
85
+ return {**slot, "error": "the configuration is not a JSON object"}
86
+
87
+ def names(key: str, required: bool) -> list[str] | None:
88
+ v = cfg.get(key)
89
+ if v is None and not required:
90
+ return []
91
+ if not isinstance(v, list) or not all(isinstance(x, str) and x for x in v):
92
+ return None
93
+ return v
94
+
95
+ ch, so = cfg.get("challenge_module"), cfg.get("solution_module")
96
+ thms, defs, axs = names("theorem_names", True), names("definition_names", False), names("permitted_axioms", True)
97
+ if not (isinstance(ch, str) and ch and isinstance(so, str) and so) or thms is None or defs is None or axs is None:
98
+ return {**slot, "error": "malformed configuration (challenge_module, solution_module, theorem_names, "
99
+ "permitted_axioms, definition_names as Lake reads them)"}
100
+ if not thms and not defs:
101
+ return {**slot, "error": "nothing to check: the configuration names no theorems or definitions"}
102
+ for m in (ch, so):
103
+ if m.startswith("-") or any(c.isspace() for c in m):
104
+ return {**slot, "error": f"not a module name: {m!r}"}
105
+ return {**slot, "challenge_module": ch, "solution_module": so, "theorems": thms, "definitions": defs,
106
+ "axioms": axs}
107
+
108
+
109
+ def export_targets(slot: dict) -> list[str]:
110
+ """Lake's `compareIt` export list for one configuration, in its order."""
111
+ quot = list(QUOT_TARGETS) if "Quot.sound" in slot["axioms"] else []
112
+ return list(dict.fromkeys(quot + slot["theorems"] + slot["axioms"] + list(PRIMITIVE_TARGETS)
113
+ + slot["definitions"]))
114
+
115
+
116
+ def parse_exports(items: list[str]) -> dict[str, pathlib.Path]:
117
+ """--export MODULE=FILE (repeatable): an existing export to read for MODULE instead of exporting it."""
118
+ out: dict[str, pathlib.Path] = {}
119
+ for it in items:
120
+ mod, sep, path = it.partition("=")
121
+ if not sep or not mod or not path:
122
+ raise ValueError(f"--export {it!r}: expected MODULE=FILE")
123
+ if mod in out:
124
+ raise ValueError(f"--export: {mod} given twice")
125
+ p = pathlib.Path(os.path.expanduser(path)).resolve()
126
+ if not p.is_file():
127
+ raise ValueError(f"--export {it!r}: {p} is not a file")
128
+ out[mod] = p
129
+ return out
130
+
131
+
132
+ def _built(roots: dc.Roots, module: str) -> bool:
133
+ rel = pathlib.Path(*module.split(".")).with_suffix(".olean")
134
+ return any((d / rel).is_file() for d in roots.lean_path())
135
+
136
+
137
+ def private_module(desc: str) -> tuple[str, str] | None:
138
+ """('A.B', 'rest') for the descriptor `const _private.A.B.0.rest`, else None (display only)."""
139
+ name = desc.removeprefix("const ").split(".{", 1)[0]
140
+ if not name.startswith("_private.") or ".0." not in name:
141
+ return None
142
+ mod, rest = name.removeprefix("_private.").split(".0.", 1)
143
+ return mod, rest
144
+
145
+
146
+ def hint(entry: dict) -> str | None:
147
+ """A reading aid for a failing configuration; never part of the verdict."""
148
+ f = entry.get("first_field") or {}
149
+ # a `let` on one side only (ContractsOnly.lean's descriptor of an Expr.letE node is "let"): definitionally
150
+ # equal after unfolding it, but Lake compares the stored terms with Expr's ==, so it never matches
151
+ lets = [side for side in ("challenge", "solution") if str(f.get(side, "")) == "let"]
152
+ if f.get("field") in ("type", "value") and len(lets) == 1:
153
+ side, other = lets[0], ("solution" if lets[0] == "challenge" else "challenge")
154
+ at = ".".join(str(x) for x in f.get("path") or []) or "its root"
155
+ return (f"the {side.capitalize()} keeps a `let` in its {f['field']} (at {at}) where the {other.capitalize()} "
156
+ f"has {f.get(other)}: Lake compares the stored terms, not their unfolding, so a `let` one side keeps "
157
+ f"and the other unfolds never matches, however equal the two are definitionally; write the two the "
158
+ f"same way, for example by inlining the alias on the {side.capitalize()} side (see {LET_DOCS})")
159
+ a, b = private_module(str(f.get("challenge", ""))), private_module(str(f.get("solution", "")))
160
+ if a and b and a[1] == b[1] and a[0] != b[0]:
161
+ return (f"the same private name {a[1]} is owned by module {a[0]} on the Challenge side and {b[0]} on the "
162
+ f"Solution side: a private name embeds its module, so a copy under another module never matches "
163
+ f"(see {PRIVATE_DOCS})")
164
+ seen = [str(x) for x in entry.get("breadcrumb") or []] + [str(f.get("challenge", "")), str(f.get("solution", ""))]
165
+ if any("_private." in x or "._proof_" in x for x in seen):
166
+ return (f"a private or generated auxiliary (_private..., _proof_N) is involved; its name depends on the "
167
+ f"module that declares it (see {PRIVATE_DOCS})")
168
+ return None
169
+
170
+
171
+ def _run_helper(prefix: pathlib.Path, plan: pathlib.Path, readable: list[pathlib.Path], sandboxed: bool) -> str:
172
+ cwd = plan.parent # the helper reads the plan and the exports, never the checkout
173
+ env = {"PATH": f"{prefix / 'bin'}:/usr/bin:/bin", "LEAN_ABORT_ON_PANIC": "1"}
174
+ cmd = [str(prefix / "bin" / "lean")]
175
+ lake_lib = prefix / "lib" / "lean" / "libLake_shared.so"
176
+ if lake_lib.is_file(): # Lake's compiled code instead of interpreting it (same functions)
177
+ cmd.append(f"--load-dynlib={lake_lib}")
178
+ cmd += ["--run", str(SCRIPT), str(plan)]
179
+ if sandboxed:
180
+ cmd = fb.bwrap_args([prefix, SCRIPT.parent, plan.parent] + readable, env, cwd) + cmd
181
+ run_env: dict[str, str] = {}
182
+ else:
183
+ run_env = {**os.environ, **env}
184
+ try:
185
+ p = subprocess.run(cmd, cwd=cwd, env=run_env, stdin=subprocess.DEVNULL, capture_output=True)
186
+ except OSError as e:
187
+ raise ContractsError(f"cannot run the compare helper: {e}") from None
188
+ if p.returncode != 0:
189
+ err = p.stderr.decode("utf-8", "replace").strip() or p.stdout.decode("utf-8", "replace").strip()
190
+ tail = [ln for ln in err.splitlines() if "error" in ln.lower()][:1] or err.splitlines()[-1:] \
191
+ or [f"exit {p.returncode}"]
192
+ raise ContractsError(f"the compare helper failed: {tail[0][:400]}")
193
+ return p.stdout.decode("utf-8", "replace")
194
+
195
+
196
+ def parse_helper(text: str, expected: int) -> list[dict]:
197
+ """The helper's slot lines; refused unless the final `done` line counts exactly `expected` slots."""
198
+ lines, done = [], None
199
+ for n, line in enumerate(text.splitlines(), 1):
200
+ if not line.strip():
201
+ continue
202
+ try:
203
+ obj = json.loads(line)
204
+ except ValueError:
205
+ raise ContractsError(f"helper output line {n} is not JSON: {line[:200]}") from None
206
+ if not isinstance(obj, dict) or done is not None:
207
+ raise ContractsError(f"helper output line {n} is not a slot record")
208
+ if obj.get("done") is True:
209
+ done = obj
210
+ else:
211
+ lines.append(obj)
212
+ if done is None or done.get("slots") != expected or len(lines) != expected:
213
+ raise ContractsError("the compare helper's output is incomplete (no final line, or a wrong count): "
214
+ "nothing is reported")
215
+ return lines
216
+
217
+
218
+ def run(repo, configs: list[str] | None = None, exports: dict[str, pathlib.Path] | None = None,
219
+ sandboxed: bool = True, toolchain: str | None = None) -> dict:
220
+ """The report for the configurations `configs` (default: all) of the built checkout `repo`."""
221
+ repo = pathlib.Path(repo).resolve()
222
+ exports = exports or {}
223
+ rels = configs if configs else discover(repo)
224
+ if not rels:
225
+ raise ContractsError("no comparator configuration in the checkout (comparator*.json or "
226
+ "comparator/config*.json)")
227
+ for rel in rels:
228
+ p = (repo / rel).resolve()
229
+ if not p.is_relative_to(repo) or not p.is_file():
230
+ raise ContractsError(f"--config {rel}: not a file inside the checkout")
231
+ try:
232
+ roots, prefix = dc.project_roots(repo, toolchain)
233
+ except dc.ProbeError as e:
234
+ raise ContractsError(str(e)) from None
235
+ if not os.access(prefix / "bin" / "leanexport", os.X_OK):
236
+ raise ContractsError(f"the toolchain at {prefix.name} has no leanexport (Lean v4.35.0 or later ships it)")
237
+ if sandboxed and not (os.environ.get("COMPARATOR_BWRAP") or shutil.which("bwrap")):
238
+ raise ContractsError("bwrap is not installed: install it, or pass --no-sandbox to export unsandboxed")
239
+ slots = [load_slot(repo, rel) for rel in rels]
240
+ for s in slots:
241
+ if "error" not in s:
242
+ missing = [m for m in (s["challenge_module"], s["solution_module"])
243
+ if m not in exports and not _built(roots, m)]
244
+ if missing:
245
+ s["error"] = f"module {', '.join(missing)} is not built: run `lake build {' '.join(missing)}` first"
246
+ live = [s for s in slots if "error" not in s]
247
+ readable = [d for d in roots.packages.values() if d.is_dir()] + sorted({p.parent for p in exports.values()})
248
+ export_log: list[dict] = []
249
+ results: dict[str, dict] = {}
250
+ work = pathlib.Path(tempfile.mkdtemp(prefix="lean-pkg-contracts-"))
251
+ try:
252
+ # one export per module, over the union of the targets of the configurations that use it
253
+ users: dict[str, list[dict]] = {}
254
+ for s in live:
255
+ for m in dict.fromkeys((s["challenge_module"], s["solution_module"])):
256
+ users.setdefault(m, []).append(s)
257
+ files: dict[str, pathlib.Path] = {}
258
+ for i, (m, ss) in enumerate(sorted(users.items())):
259
+ cfgs = [s["config"] for s in ss]
260
+ if m in exports:
261
+ export_log.append({"module": m, "supplied": True, "configs": cfgs})
262
+ files[m] = exports[m]
263
+ continue
264
+ # --ignore-missing: a name one configuration lacks must not fail the others; the helper reports
265
+ # every configuration whose targets are not all in the export as an error, as Lake's export would
266
+ names = list(dict.fromkeys(n for s in ss for n in export_targets(s)))
267
+ out = work / f"{i}.export"
268
+ try:
269
+ fb.run_export(prefix, roots.lean_path(), readable, repo, [m], names, out, sandboxed, None,
270
+ ignore_missing=True)
271
+ export_log.append({"module": m, "supplied": False, "configs": cfgs, "names": len(names)})
272
+ files[m] = out
273
+ except fb.ExportError as e:
274
+ export_log.append({"module": m, "supplied": False, "configs": cfgs, "error": str(e)})
275
+ for s in ss:
276
+ s["error"] = f"export of {m}: {e}"
277
+ live = [s for s in live if "error" not in s]
278
+ if live:
279
+ plan = work / "plan.json"
280
+ plan.write_text(json.dumps({"slots": [
281
+ {"config": s["config"], "challenge": str(files[s["challenge_module"]]),
282
+ "solution": str(files[s["solution_module"]]), "targets": export_targets(s),
283
+ "theorems": s["theorems"],
284
+ "definitions": s["definitions"], "axioms": s["axioms"]} for s in live]}))
285
+ for rec in parse_helper(_run_helper(prefix, plan, readable, sandboxed), len(live)):
286
+ results[str(rec.get("config"))] = rec
287
+ finally:
288
+ shutil.rmtree(work, ignore_errors=True)
289
+
290
+ entries = []
291
+ for s in slots:
292
+ e = {"config": s["config"], "challenge_module": s.get("challenge_module"),
293
+ "solution_module": s.get("solution_module")}
294
+ if "error" in s:
295
+ e.update(verdict="error", detail=s["error"])
296
+ else:
297
+ r = results.get(s["config"])
298
+ if r is None:
299
+ e.update(verdict="error", detail="the compare helper reported nothing for this configuration")
300
+ elif r.get("verdict") == "error":
301
+ e.update(verdict="error", missing=r.get("missing") or [],
302
+ detail="not in the export (lake comparator's exporter would fail): "
303
+ + ", ".join(r.get("missing") or []))
304
+ elif r.get("verdict") == "match":
305
+ e.update(verdict="match", detail="Lake's compareAt and checkAxioms pass on the two exports")
306
+ else:
307
+ e.update(verdict="differs", detail=r.get("lake_message"), stage=r.get("stage"),
308
+ constant=r.get("constant"), reason=r.get("reason"), breadcrumb=r.get("breadcrumb") or [],
309
+ first_field=r.get("first_field"), consistent=bool(r.get("consistent")))
310
+ e["hint"] = hint(e)
311
+ entries.append(e)
312
+ counts = {k: sum(e["verdict"] == k for e in entries) for k in ("match", "differs", "error")}
313
+ ok = counts["match"] == len(entries)
314
+ return {"schema": SCHEMA, "ok": ok, "acceptance": False, "evidence": False,
315
+ "verdict": "match" if ok else ("differs" if counts["differs"] else "error"),
316
+ "toolchain": prefix.name, "sandboxed": sandboxed, "counts": counts, "configs": entries,
317
+ "exports": export_log, "note": NEVER, "docs": DOCS}
318
+
319
+
320
+ def summary_line(name: str, res: dict) -> str:
321
+ c, n = res["counts"], len(res["configs"])
322
+ word = "every configuration matches" if res["ok"] else \
323
+ f"{c['differs']} differ, {c['error']} error(s), {c['match']} match"
324
+ return f"{name}: contracts-only diagnostic, {n} configuration(s): {word} (never acceptance; no kernel, no receipt)"
325
+
326
+
327
+ def text_lines(name: str, res: dict) -> list[str]:
328
+ out = [summary_line(name, res)]
329
+ for e in res["configs"]:
330
+ if e["verdict"] == "match":
331
+ out.append(f" match: {e['config']}")
332
+ continue
333
+ out.append(f" {e['verdict'].upper()}: {e['config']}: {e['detail']}")
334
+ if e["verdict"] != "differs":
335
+ continue
336
+ if e.get("breadcrumb"):
337
+ out.append(f" breadcrumb: {' -> '.join(e['breadcrumb'])}")
338
+ f = e.get("first_field")
339
+ if isinstance(f, dict):
340
+ at = f" at {'.'.join(f['path'])}" if f.get("path") else ""
341
+ sides = "; ".join(f"{k} {f[k]}" for k in ("challenge", "solution") if k in f)
342
+ out.append(f" first differing field: {f.get('field')}{at}" + (f": {sides}" if sides else ""))
343
+ elif e.get("reason"):
344
+ out.append(f" reason: {e['reason']}")
345
+ if not e.get("consistent"):
346
+ out.append(" note: the diagnosis walk did not end at the constant Lake's message names; the "
347
+ "breadcrumb is a guess")
348
+ if e.get("hint"):
349
+ out.append(f" hint: {e['hint']}")
350
+ out.append(f" {res['note']}")
351
+ out.append(summary_line(name, res))
352
+ return out
353
+
354
+
355
+ def preflight(repo) -> dict:
356
+ """`--contracts-preflight` of `receipt systemd --run` and `receipt slurm` (#409): the contracts-only
357
+ diagnostic of every comparator configuration of REPO, before any receipt work. {ok, refusals, checks, report}:
358
+ ok only when every configuration matches. A difference, an `error` (among them a configured module that is not
359
+ built: its detail names the `lake build` to run) and a diagnostic that cannot run all refuse. Never acceptance
360
+ (a match is not a pass) and nothing is written, as for `comparator check --contracts-only`."""
361
+ try:
362
+ res = run(pathlib.Path(repo))
363
+ except ContractsError as e:
364
+ why = str(e)
365
+ if why.startswith("bwrap is not installed"):
366
+ why = ("bwrap is not installed, and the preflight exports only in its sandbox; on this host run "
367
+ "`lean-pkg comparator check NAME --contracts-only --no-sandbox` by hand instead")
368
+ return {"ok": False, "checks": [], "report": None,
369
+ "refusals": [f"--contracts-preflight: the contracts-only diagnostic could not run ({why}); "
370
+ f"nothing was run"]}
371
+ bad = [e for e in res["configs"] if e["verdict"] != "match"]
372
+ n = len(res["configs"])
373
+ if not bad:
374
+ return {"ok": True, "refusals": [], "report": res,
375
+ "checks": [f"✓ contracts preflight: {n} comparator configuration(s) match (never acceptance: "
376
+ f"only lake comparator in a gate judges)"]}
377
+ refusals = [f"--contracts-preflight: {e['config']}: {e['verdict']}: {e['detail']}"
378
+ + (f" (hint: {e['hint']})" if e.get("hint") else "") for e in bad]
379
+ refusals.append(f"--contracts-preflight: {len(bad)} of {n} comparator configuration(s) do not match; nothing "
380
+ f"was run. Fix them first: `lean-pkg comparator check NAME --contracts-only` shows each "
381
+ f"breadcrumb ({PREFLIGHT_DOCS})")
382
+ return {"ok": False, "checks": [], "report": res, "refusals": refusals}