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,1064 @@
1
+ # lean-pkg receipt check -- validate a published package's receipts from git alone
2
+ """`lean-pkg receipt check --repo DIR --commit X [--at REF] [--docs-descendants | --evidence-only] [--name NAME]
3
+ [--corroborate] [--attested [--trusted-root FILE]] [--github OWNER/REPO] [--json]`:
4
+ the registry-free receipt verifier an outside referee runs on a clone of a published package. It needs no
5
+ lean-pkg registry, no lab account and no network, and it never runs Lean: everything is read from git, at the
6
+ bound commit X and at the published ref REF (default: the checkout's HEAD), in a private clone of DIR (the
7
+ referee's checkout is never modified; its working tree and untracked files are never read).
8
+
9
+ Re-deriving a run (rebuilding at X, `#print axioms`, re-running the comparator) is a separate step: steps 4
10
+ and 5 of docs/trust-model.md#re-verify-a-page-yourself. This command checks that the published evidence is
11
+ consistent with itself and with the committed tree, nothing more.
12
+
13
+ Checks, each with a verdict pass | fail | skip (skip: the check does not apply, and says why):
14
+
15
+ - receipts: the JSON files tracked directly under .lean-receipts/ at REF; those whose `commit` is X are the
16
+ ones checked (a comparator receipt has a comparator-receipt/N schema; a lower-tier receipt has sorry_count
17
+ and axioms). At least one lower-tier receipt must bind X; a receipt file named for X that binds another
18
+ commit fails. A comparator `.replaced-` copy is history and is skipped. A JSON file named for X that is not
19
+ receipt-shaped fails, unless its `schema` is one of the comparator runner's own non-receipt records
20
+ (NON_RECEIPT_SCHEMAS: stages.json and its kin), which is skipped and printed as skipped.
21
+ - opt-in: lean-pkg-binding.yaml in the package directory as committed at X (proposal 0002), the author's
22
+ docs-only opt-in, read at X and nowhere else (never at REF, never in the referee's working tree). Pass
23
+ when it opts in (docs_descendants: true) and is applied; skip, saying why, when it says false, does not
24
+ validate (the problem is named), or is ignored with --evidence-only; skip when it is absent at X but
25
+ committed at REF (added after X: it grants nothing). No row when no file is at X or at REF.
26
+ - binding: REF is X, or an evidence-only descendant of X (only .lean-receipts/ changed, and formalization.yaml
27
+ at the package root, the renderer's default path, in its derived keys only: gate's own exemption, #23.5,
28
+ applied to the fixed path because the registry pointer is not readable here; the exemption is printed when
29
+ it was needed), or a docs-only descendant of X (no build input changed: the docs-only rule of
30
+ docs/receipts.md) when the docs-only rule applies: by default when lean-pkg-binding.yaml at X opts in;
31
+ with --docs-descendants, for a package without the file, as the referee's choice (printed with the
32
+ result; a file at X that says false or does not validate overrides the flag); never with --evidence-only.
33
+ - per lower-tier receipt: gate's own validator (gate_mod.validate_receipt: the receipt keys, the binding, the
34
+ toolchain and Mathlib pins against lean-toolchain and lake-manifest.json committed at X, no path dependency
35
+ outside the package, sorry_count 0, axioms within propext, Quot.sound, Classical.choice); report_sha256
36
+ against the committed redacted log (gate_mod.report_log_check; a missing log fails here); the additive evidence
37
+ keys when present (manifest_sha256 against lake-manifest.json at X, artifacts_manifest_sha256 and
38
+ unit_properties_sha256 against their committed files; job_stdout_sha256 is not checkable: the job's stdout
39
+ is not published); the `container` key when present (#236: shown with its engine, digest and image ref;
40
+ a malformed one fails; the digest itself is not re-derivable, the image is not published); the
41
+ `slurm_sacct` block when present (`receipt slurm --seal-sacct`): the validator refuses it unless the sealed
42
+ sacct record is committed at REF and still hashes and parses to the block (receipt.sacct_seal_problem, the
43
+ check of a comparator receipt's seal), and a row names the job, the window and the record; the `ci` block
44
+ when present (a GitHub Actions run, proposal 0008): the validator refuses it unless it passes level 1
45
+ (ci_github.level1: offline consistency with the receipt, the commit and the committed log), and a row names
46
+ the run, with a second row for the workflow-file rehash (a skip when ci.workflow_sha is not in the clone).
47
+ A receipt with a gha- job_id and no `ci` block gets a skip row: it gates, but backs no compute job.
48
+ - per lower-tier receipt with the additive `claim_axioms` key (AX1): re-derived from the sealed log's
49
+ claim-axioms lines against claims.yaml at X (every claim checked, none missing, no sorryAx,
50
+ agreeing with the log's `#print axioms` output) and compared with the key.
51
+ - claims: claims.yaml at X, with the claims/1 schema and declaration check gate runs (gate_mod.claims_schema_at).
52
+ - per comparator receipt: gate's validator (gate_mod.validate_comparator: schema, binding, toolchain, the exact
53
+ set of configurations tracked at X, each configuration's sha256 and fields, the sign-off of definition
54
+ holes, each log's sha256 and its PASS line, the same commit as the lower-tier receipt); the olean manifest
55
+ record when present (its lean_toolchain and lake_manifest_sha256 against X; the manifest file itself
56
+ describes the author's build directory and is not published).
57
+ - claimed theorems: every theorem or lemma claim with status reusable in claims.yaml at X is named by a
58
+ comparator configuration tracked at X (the rule `comparator config --coverage` applies): by its explicit
59
+ `judged_as` when set (that exact theorem name, and nothing else), else by the naming rule (the decl, or
60
+ <Prefix>.<decl>). Any `judged_as` that names no configured theorem, or whose claim's decl is not declared in
61
+ its file, fails, whatever the claim's status. claims.yaml is bound to X like the sources (a change after X is
62
+ neither evidence-only nor docs-only), so the mapping is read where the claims are.
63
+ - hypotheses (proposal 0003), only when claims.yaml at X uses hypotheses, discharges or witness: the discharge
64
+ states recomputed from the hyp-probe/1 section of the sealed log of the lower-tier receipt that binds X (the
65
+ promote stage when the comparator tier passed, else nothing is discharged): it names the conditional claims,
66
+ each discharged hypothesis with its corollary and the outstanding ones, and fails on any failed-class code
67
+ (hypothesis-not-in-type, hypothesis-inadmissible, discharge-type-mismatch, witness-type-mismatch), an
68
+ unreadable sealed log or a log without a complete section. `--json` gains `hypotheses` under the same condition.
69
+ - coverage: coverage.yaml at REF, when tracked, passes `coverage check` (schema, claim ids, backed compute
70
+ jobs, R8 to R12: every theorem the comparator receipt compares is the declaration of a claim a row names).
71
+ Its first warning, and the first unlisted assumption (proposal 0003, open question 7, from the hyp-decl lines
72
+ of the sealed log of the lower-tier receipt that binds X: coverage.unlisted_assumption_warnings), are appended
73
+ to the detail; a warning never fails it.
74
+ - page: the README.md verification block at REF, when present, states what the receipts say: the bound
75
+ commit, the toolchain and Mathlib pins, every Evidence row (path, commit, SHA-256 of the committed file), the
76
+ lower-tier sorry count and axioms, the comparator's configuration and theorem counts.
77
+
78
+ --corroborate (proposal 0008, level 2) is a networked check: every lower-tier receipt with a `ci` block
79
+ that passes level 1 is corroborated against the public GitHub REST API (ci_github.corroborate), one row per
80
+ level-2 check, and fails when it does not reach level 2 (a 404, a 403 or 429 naming GH_TOKEN, a network error
81
+ and a redirect off api.github.com each fail closed, named). The package's own repository is --github
82
+ OWNER/REPO; without it, the receipt's ci.repository, and the output says so. A token from GH_TOKEN or
83
+ GITHUB_TOKEN only raises the rate limit; it is never printed or written. The JSON gains `ci: {level, rows}`
84
+ (level: the lowest a corroborated receipt reached; null when none has a `ci` block), `github` and
85
+ `network: true`.
86
+
87
+ --attested (level 3, stage S4): every such receipt's committed Sigstore bundle (`ci.attestation`, beside the
88
+ receipt under .lean-receipts/ at REF) is verified by `gh attestation verify`, an optional outside tool
89
+ (ci_github.attest), one row per level-3 check, and the receipt fails unless it reaches level 3 (with
90
+ --corroborate too, level 2 must hold as well). A missing gh, a bundle not committed, subjects other than the
91
+ committed receipt and log, a verifier that exits non-zero and a certificate naming another repository, commit,
92
+ run or signer each fail, named. --trusted-root FILE verifies offline (gh's --custom-trusted-root). The JSON
93
+ gains `ci`, `github`, `attested: true` and `trusted_root`; `network` is true unless --trusted-root is given and
94
+ --corroborate is not. Without --attested a receipt whose block names a bundle gets a skip row (and the row
95
+ says when gh is not on PATH).
96
+
97
+ Exit 0 only when no check fails; 1 otherwise; 2 on a usage error (DIR is not a git checkout, X or REF does
98
+ not resolve, --github without --corroborate or --attested or not OWNER/REPO, --trusted-root without
99
+ --attested or not a file).
100
+ """
101
+
102
+ from __future__ import annotations
103
+
104
+ import json
105
+ import pathlib
106
+ import re
107
+ import tempfile
108
+
109
+ from . import claim_axioms as ca
110
+ from .binding_file import FILE as BINDING_FILE, referee_opt_in
111
+ from . import gate as gate_mod
112
+ from . import core
113
+ from . import container as ctr
114
+ from . import toolchain_advisories
115
+
116
+ RECEIPTS_DIR = ".lean-receipts"
117
+ DEFAULT_AXIOMS = tuple(core.DEFAULT_AXIOMS)
118
+ RERUN_NOTE = ("this command never runs Lean and never uses the network: rebuilding at the commit and re-running "
119
+ "the comparator are steps 4 and 5 of docs/trust-model.md#re-verify-a-page-yourself")
120
+ # Additive lower-tier keys that bind a file `receipt slurm|systemd` writes beside the receipt as
121
+ # <c12>-<job slug>-<suffix>: the key's value is the file's sha256.
122
+ EVIDENCE_FILE_KEYS = {"artifacts_manifest_sha256": "artifacts.sha256",
123
+ "unit_properties_sha256": "unit.properties"}
124
+ PASS, FAIL, SKIP = "pass", "fail", "skip"
125
+ CORROBORATE_NOTE = ("this command never runs Lean; with --corroborate it asks the public GitHub REST API (level 2) "
126
+ "and nothing else on the network: rebuilding at the commit and re-running the comparator are "
127
+ "steps 4 and 5 of docs/trust-model.md#re-verify-a-page-yourself")
128
+ ATTESTED_NOTE = ("this command never runs Lean; with --attested it runs `gh attestation verify` on each committed "
129
+ "Sigstore bundle (level 3; online unless --trusted-root), and with --corroborate it asks the public "
130
+ "GitHub REST API (level 2): rebuilding at the commit and re-running the comparator are steps 4 and "
131
+ "5 of docs/trust-model.md#re-verify-a-page-yourself")
132
+ REPO_DEFAULT = ("no --github: the package repository is taken to be each receipt's ci.repository (pass --github "
133
+ "OWNER/REPO to name it; a run in another repository, a fork included, then does not back)")
134
+ REPO_NOTE = "the package repository is {where}; a run in another repository (by numeric id) does not back"
135
+ # The one formalization.yaml path the evidence-only rule exempts without a registry: the renderer's default
136
+ # (formalization.DEFAULT_PATH), package-relative. A package whose registry records another path keeps the
137
+ # strict reading here (or the referee's --docs-descendants).
138
+ FORMALIZATION_REL = "formalization.yaml"
139
+ # JSON records the comparator runner writes beside its receipt (comparator_receipt, comparator_stage). One of
140
+ # these under .lean-receipts/ named for X is not a receipt: it is skipped (and printed), never failed. Only an
141
+ # exact `schema` value skips a file, and only a file that is not receipt-shaped (tier_of None): a truncated or
142
+ # hand-edited receipt has no such schema and still fails as unreadable.
143
+ NON_RECEIPT_SCHEMAS = ("comparator-stages/1", "olean-manifest/1", "comparator-attempt/1",
144
+ "comparator-partial/1", "comparator-slot/1", "comparator-estimate/2")
145
+
146
+
147
+ # --------------------------------------------------------------------------
148
+ # the source: a private clone of the referee's checkout, at REF
149
+
150
+ def _resolve(repo: pathlib.Path, rev: str, what: str) -> str:
151
+ p = core.git(repo, "rev-parse", "--verify", "--quiet", f"{rev}^{{commit}}")
152
+ if p.returncode != 0 or not core._HEX40.fullmatch(p.stdout.strip()):
153
+ raise core.UsageError(f"{what} {rev!r} is not a commit in {repo}")
154
+ return p.stdout.strip()
155
+
156
+
157
+ def open_source(repo_dir: str, commit: str, at: str | None, tmp: pathlib.Path) -> dict:
158
+ """{clone (package directory inside the clone), commit, at, prefix}: DIR cloned (local transport only, no
159
+ other protocol allowed) and checked out at REF, detached, symlinks as plain files."""
160
+ src = pathlib.Path(repo_dir).expanduser()
161
+ if not src.is_dir():
162
+ raise core.UsageError(f"--repo {repo_dir}: not a directory (a local clone of the package; this command "
163
+ f"never fetches a URL)")
164
+ top = core.git(src, "rev-parse", "--show-toplevel")
165
+ if top.returncode != 0:
166
+ raise core.UsageError(f"--repo {repo_dir}: not a git checkout")
167
+ prefix = core.git(src, "rev-parse", "--show-prefix").stdout.strip().strip("/")
168
+ x = _resolve(src, commit, "--commit")
169
+ ref = _resolve(src, at or "HEAD", "--at")
170
+ dest = tmp / "pkg"
171
+ p = core.run(["git", "-c", "protocol.allow=never", "-c", "protocol.file.allow=always", "clone", "--quiet",
172
+ "--no-checkout", "--no-hardlinks", top.stdout.strip(), str(dest)], scrub=True)
173
+ if p.returncode != 0:
174
+ raise core.Fail(f"cannot clone {repo_dir}: {p.stderr.strip()[:300]}")
175
+ for sha in (x, ref): # a detached HEAD or a commit on no branch is not cloned: fetch it locally
176
+ if core.git(dest, "cat-file", "-e", f"{sha}^{{commit}}").returncode != 0:
177
+ f = core.run(["git", "-C", str(dest), "-c", "protocol.allow=never", "-c", "protocol.file.allow=always",
178
+ "fetch", "--quiet", "--no-tags", top.stdout.strip(), sha], scrub=True)
179
+ if f.returncode != 0:
180
+ raise core.Fail(f"cannot copy commit {sha[:12]} from {repo_dir}: {f.stderr.strip()[:200]}")
181
+ p = core.git(dest, "-c", "core.symlinks=false", "checkout", "--quiet", "--detach", ref)
182
+ if p.returncode != 0:
183
+ raise core.Fail(f"cannot check out {ref[:12]} in the private clone: {p.stderr.strip()[:200]}")
184
+ clone = dest / prefix if prefix else dest
185
+ if not clone.is_dir():
186
+ raise core.Fail(f"the package directory {prefix}/ does not exist at {ref[:12]}")
187
+ return {"clone": clone, "root": dest, "commit": x, "at": ref, "prefix": prefix}
188
+
189
+
190
+ def referee_pkg(name: str, docs_descendants: bool, comparator_rel: str | None = None,
191
+ evidence_only: bool = False) -> dict:
192
+ """The package record the validators read, built from nothing but the referee's choices: the default
193
+ axioms, the default claims file, the default formalization.yaml path (FORMALIZATION_REL; gate's
194
+ derived-keys rule decides from the file at X and at REF, and a file not tracked at X is never exempt).
195
+ The docs-only opt-in is lean-pkg-binding.yaml at X, which every validator reads through the binding rule
196
+ (binding_file.resolve_opt_in); --docs-descendants stands in for the record's docs_descendants: true (it
197
+ applies only without a file at X), --evidence-only for its false (the veto: the file is not applied)."""
198
+ pkg = {"name": name, "gate": {"axioms_allowed": list(DEFAULT_AXIOMS), "comparator": comparator_rel},
199
+ "formalization_yaml": FORMALIZATION_REL}
200
+ if docs_descendants:
201
+ pkg["docs_descendants"] = True
202
+ elif evidence_only:
203
+ pkg["docs_descendants"] = False
204
+ return pkg
205
+
206
+
207
+ # --------------------------------------------------------------------------
208
+ # reading at REF and at X
209
+
210
+ def _json_at(repo: pathlib.Path, rel: str, rev: str = "HEAD") -> tuple[dict | None, bytes | None]:
211
+ raw = core.git_show_bytes(repo, rel, rev)
212
+ if raw is None:
213
+ return None, None
214
+ try:
215
+ data = json.loads(raw)
216
+ except ValueError:
217
+ return None, raw
218
+ return (data if isinstance(data, dict) else None), raw
219
+
220
+
221
+ def tier_of(rec: dict | None) -> str | None:
222
+ if not isinstance(rec, dict):
223
+ return None
224
+ if rec.get("schema") in core.COMPARATOR_SCHEMAS:
225
+ return "comparator"
226
+ if "sorry_count" in rec and "axioms" in rec:
227
+ return "lower"
228
+ return None
229
+
230
+
231
+ def discover(repo: pathlib.Path, x: str) -> dict:
232
+ """{lower: [view], comparator: [view], other: [view], misnamed: [view], unreadable: [rel], sidecar:
233
+ [{path, schema}]} for the receipt JSON files tracked directly under .lean-receipts/ at HEAD (REF). view:
234
+ {path, sha256, commit, tier, data}. sidecar: files named for X that are a NON_RECEIPT_SCHEMAS record."""
235
+ from . import coverage as cov
236
+ out: dict = {"lower": [], "comparator": [], "other": [], "misnamed": [], "unreadable": [], "sidecar": []}
237
+ for rel in cov.tracked_receipts(repo):
238
+ name = rel.rsplit("/", 1)[-1]
239
+ if ".replaced-" in name: # `comparator --replace` keeps the older receipt beside it: history
240
+ continue
241
+ data, raw = _json_at(repo, rel)
242
+ tier = tier_of(data)
243
+ if raw is None or tier is None:
244
+ if data is not None and tier is None and data.get("schema") in NON_RECEIPT_SCHEMAS:
245
+ if name.startswith(x[:12]):
246
+ out["sidecar"].append({"path": rel, "schema": data["schema"]})
247
+ continue
248
+ if name.startswith(x[:12]):
249
+ out["unreadable"].append(rel)
250
+ continue
251
+ view = {"path": rel, "sha256": core.sha256_bytes(raw), "commit": str(data.get("commit") or ""),
252
+ "tier": tier, "data": data}
253
+ if view["commit"] == x:
254
+ out[tier].append(view)
255
+ elif name.startswith(x[:12]):
256
+ out["misnamed"].append(view)
257
+ else:
258
+ out["other"].append(view)
259
+ return out
260
+
261
+
262
+ def _sha_at(repo: pathlib.Path, rel: str, rev: str) -> str | None:
263
+ raw = core.git_show_bytes(repo, rel, rev)
264
+ return core.sha256_bytes(raw) if raw is not None else None
265
+
266
+
267
+ def toolchain_at(repo: pathlib.Path, rev: str) -> str | None:
268
+ raw = core.git_show_bytes(repo, "./lean-toolchain", rev)
269
+ return raw.decode("utf-8", "replace").strip() if raw is not None else None
270
+
271
+
272
+ # --------------------------------------------------------------------------
273
+ # the checks
274
+
275
+ class Checks:
276
+ def __init__(self, clone: pathlib.Path | None = None, root: pathlib.Path | None = None) -> None:
277
+ self.items: list[dict] = []
278
+ self.exemptions: list[str] = [] # the binding exemptions the verdict needed (formalization.yaml)
279
+ # The private clone lives in a temporary directory that is gone when the command ends: a validator's
280
+ # message that names a path inside it (report_log_missing names where it looked) is rewritten to the
281
+ # package-relative path, so the output shows no temporary path (#213).
282
+ self._paths: list[tuple[str, str]] = []
283
+ for base, label in ((clone, "."), (root, "<repository root>")):
284
+ if base is None:
285
+ continue
286
+ for form in dict.fromkeys((str(base.absolute()), str(base.resolve()))):
287
+ self._paths.append((form, label))
288
+
289
+ def relative(self, text: str) -> str:
290
+ for form, label in self._paths:
291
+ text = text.replace(form + "/", "" if label == "." else label + "/").replace(form, label)
292
+ return text
293
+
294
+ def add(self, cid: str, verdict: str, detail: str) -> None:
295
+ self.items.append({"id": cid, "verdict": verdict, "detail": self.relative(detail)})
296
+
297
+ def run(self, cid: str, fn, ok_detail: str) -> bool:
298
+ """Run fn(); pass with ok_detail, or fail with the refusal's text."""
299
+ try:
300
+ fn()
301
+ except (core.Fail, ValueError, KeyError, TypeError) as e:
302
+ self.add(cid, FAIL, str(e))
303
+ return False
304
+ self.add(cid, PASS, ok_detail)
305
+ return True
306
+
307
+ def failed(self) -> int:
308
+ return sum(i["verdict"] == FAIL for i in self.items)
309
+
310
+
311
+ def opt_in_check(c: Checks, repo: pathlib.Path, x: str, ref: str, oi) -> None:
312
+ """The `opt-in` row: lean-pkg-binding.yaml as committed at X, the only copy that can opt in (proposal
313
+ 0002). No row when the file is neither at X nor at REF, so a package without it reads as before."""
314
+ x12 = x[:12]
315
+ if oi.file_state == "absent":
316
+ if x != ref and core.tracked_at(repo, BINDING_FILE, ref):
317
+ c.add("opt-in", SKIP, f"no {BINDING_FILE} at {x12}; the one at {ref[:12]} was added after {x12}, and "
318
+ f"the opt-in is read at the bound commit only, so it grants nothing")
319
+ return
320
+ if oi.file_state == "true":
321
+ what = (f"{BINDING_FILE} at {x12} opts in to docs-only descendants (build_inputs: "
322
+ f"{len(oi.build_inputs)} glob(s))")
323
+ if oi.rule == "docs-only":
324
+ c.add("opt-in", PASS, what)
325
+ else:
326
+ c.add("opt-in", SKIP, f"{what}; ignored: --evidence-only")
327
+ return
328
+ why = (f"{BINDING_FILE} at {x12} says docs_descendants: false" if oi.file_state == "false" else
329
+ f"{BINDING_FILE} at {x12} does not opt in: " + "; ".join(pr.split(": ", 1)[-1] for pr in oi.problems))
330
+ over = [n for n in oi.notes if n.startswith("--docs-descendants")]
331
+ c.add("opt-in", SKIP, f"{why}; the evidence-only rule binds" + "".join(f"; {n}" for n in over))
332
+
333
+
334
+ def check_binding(c: Checks, repo: pathlib.Path, x: str, ref: str, pkg: dict, checker, oi) -> None:
335
+ ok, note, docs = gate_mod.package_descendant(repo, x, ref, pkg, checker=checker, nested=(), opt_in=oi)
336
+ if ok:
337
+ what = ("the published ref is the bound commit" if x == ref
338
+ else f"{note} (accepted with --docs-descendants)" if docs is not None and oi.source == "referee"
339
+ else note)
340
+ exempt = formalization_exemption(repo, x, ref, pkg)
341
+ if exempt:
342
+ what += f"; exemption applied: {exempt}"
343
+ c.exemptions.append(exempt)
344
+ c.add("binding", PASS, what)
345
+ else:
346
+ c.add("binding", FAIL, f"{ref[:12]} is not {x[:12]} or an evidence-only"
347
+ + (" or docs-only" if oi.rule == "docs-only" else "") + f" descendant of it: {note}; the "
348
+ f"receipts certify {x[:12]}, not this tree (check the tree they bind with --at {x[:12]}, or an "
349
+ f"evidence commit after it)")
350
+
351
+
352
+ def formalization_exemption(repo: pathlib.Path, x: str, ref: str, pkg: dict) -> str | None:
353
+ """The exemption text when the binding passed although formalization.yaml differs between X and REF (gate's
354
+ derived-keys rule admitted it); None when that file did not change."""
355
+ rel = core.formalization_rel(pkg)
356
+ if not rel or x == ref:
357
+ return None
358
+ p = core.git(repo, "diff", "--no-renames", "--name-only", "--relative", x, ref, "--", rel)
359
+ if rel not in p.stdout.splitlines():
360
+ return None
361
+ return (f"{rel} differs from {x[:12]} only in derived keys ({', '.join(fz_derived_keys())}), the keys "
362
+ f"`lean-pkg formalization` regenerates after a receipt; they cannot change what was verified "
363
+ f"(gate's evidence-only rule, #23.5)")
364
+
365
+
366
+ def fz_derived_keys() -> tuple[str, ...]:
367
+ from .formalization import DERIVED_KEYS
368
+ return DERIVED_KEYS
369
+
370
+
371
+ def evidence_file_checks(c: Checks, repo: pathlib.Path, view: dict, x: str) -> None:
372
+ """The additive keys of a lower-tier receipt that bind another file by its sha256."""
373
+ rec, rel = view["data"], view["path"]
374
+ cid = f"lower {rel}: evidence files"
375
+ problems, passed, skipped = [], [], []
376
+ if rec.get("manifest_sha256"):
377
+ got = _sha_at(repo, "./lake-manifest.json", x)
378
+ if got != str(rec["manifest_sha256"]).lower():
379
+ problems.append(f"manifest_sha256 {str(rec['manifest_sha256'])[:12]} != sha256 of lake-manifest.json "
380
+ f"at {x[:12]} ({(got or 'not tracked')[:12]})")
381
+ else:
382
+ passed.append("manifest_sha256 = lake-manifest.json at X")
383
+ try:
384
+ slug = gate_mod.receipt_job_slug(rec.get("job_id"))
385
+ except core.Fail:
386
+ slug = None
387
+ for key, suffix in EVIDENCE_FILE_KEYS.items():
388
+ if not rec.get(key):
389
+ continue
390
+ frel = f"{RECEIPTS_DIR}/{x[:12]}-{slug}-{suffix}"
391
+ got = _sha_at(repo, frel, "HEAD") if slug else None
392
+ if got is None:
393
+ skipped.append(f"{key}: {frel} is not committed")
394
+ elif got != str(rec[key]).lower():
395
+ problems.append(f"{key} {str(rec[key])[:12]} != sha256 of {frel} ({got[:12]})")
396
+ else:
397
+ passed.append(f"{key} = {frel}")
398
+ if rec.get("job_stdout_sha256"):
399
+ skipped.append("job_stdout_sha256: the job's stdout is not published")
400
+ if problems:
401
+ c.add(cid, FAIL, "; ".join(problems))
402
+ elif passed:
403
+ c.add(cid, PASS, "; ".join(passed + skipped))
404
+ else:
405
+ c.add(cid, SKIP, "; ".join(skipped) or "no additive evidence key (manifest_sha256, "
406
+ "artifacts_manifest_sha256, unit_properties_sha256)")
407
+
408
+
409
+ def sacct_seal_check(c: Checks, view: dict) -> None:
410
+ """The additive `slurm_sacct` block (`receipt slurm --seal-sacct`), when present: shown. The validator
411
+ (gate_mod.validate_receipt, run first) already refused a block whose record is missing, uncommitted at the
412
+ published ref, rehashed or edited (receipt.sacct_seal_problem); this row names what it corroborated."""
413
+ rec, rel = view["data"], view["path"]
414
+ if "slurm_sacct" not in rec:
415
+ return
416
+ c.add(f"lower {rel}: sacct seal", PASS, gate_mod.sacct_seal_lines(rec)[0][2:].replace("at HEAD", "at the ref"))
417
+
418
+
419
+ def ci_check(c: Checks, repo: pathlib.Path, view: dict, tier: str = "lower") -> None:
420
+ """The additive `ci` block (a GitHub Actions run, proposal 0008), at level 1: shown. The validator
421
+ (gate_mod.validate_receipt, run first) already refused a block that fails level 1; this row names the run, and
422
+ the workflow-file row says whether the file was rehashed or why not. `tier`: "lower", or "comparator" for a
423
+ comparator receipt written on a GitHub-hosted runner (proposal 0008, S5; validate_comparator refused a failing
424
+ block). A gha- receipt without the block: a skip row (it backs no GitHub Actions compute job)."""
425
+ from . import ci_github
426
+ rec, rel = view["data"], view["path"]
427
+ if ci_github.KEY not in rec:
428
+ job = rec.get("job_id")
429
+ if isinstance(job, str) and ci_github.JOB_RE.match(job):
430
+ c.add(f"{tier} {rel}: ci", SKIP, f"job_id {job} has no ci block: the receipt is a "
431
+ f"{'lower-tier' if tier == 'lower' else tier} receipt "
432
+ f"like any other, but backs no GitHub Actions compute job")
433
+ return
434
+ problems, row = ci_github.level1(rec, repo)
435
+ if problems: # unreachable after the validator; kept so a row never claims a pass it did not check
436
+ c.add(f"{tier} {rel}: ci", FAIL, "; ".join(problems))
437
+ return
438
+ c.add(f"{tier} {rel}: ci", PASS, ci_github.summary(rec))
439
+ if row is not None:
440
+ c.add(f"{tier} {rel}: ci workflow file", PASS if row[0] == "pass" else SKIP, row[1])
441
+
442
+
443
+ def corroborate_check(c: Checks, repo: pathlib.Path, view: dict, fetch, github: str | None,
444
+ attested: bool = False, trusted_root: str | None = None, corroborate: bool = True
445
+ ) -> dict | None:
446
+ """--corroborate: level 2 of a receipt whose `ci` block passed level 1 (ci_github.corroborate), one row per
447
+ check, failed when one fails. --attested: level 3 (ci_github.attest: the committed Sigstore bundle, verified
448
+ by gh attestation verify), one row per check, and the receipt fails unless it reaches level 3. {path, level,
449
+ rows}, or None for a receipt without a valid block."""
450
+ from . import ci_github
451
+ rec, rel = view["data"], view["path"]
452
+ if ci_github.KEY not in rec or ci_github.level1(rec, repo)[0]:
453
+ return None
454
+ level2, rows = None, []
455
+ if corroborate:
456
+ level2, rows = ci_github.corroborate(rec, repo, fetch=fetch, receipt_sha256=view["sha256"],
457
+ expect_repo=github)
458
+ for r in rows:
459
+ c.add(f"lower {rel}: ci level 2 {r['check']}", PASS if r["verdict"] == "pass" else FAIL, r["detail"])
460
+ if not attested:
461
+ c.add(f"lower {rel}: ci level", PASS if level2 >= 2 else FAIL,
462
+ ci_github.LEVEL2_NOTE if level2 >= 2 else
463
+ f"level {level2}: not corroborated, so the GitHub Actions sentence is not earned (the receipt stays a "
464
+ f"valid level-1 receipt and still backs its compute job)")
465
+ return {"path": rel, "level": level2, "rows": rows}
466
+ name = rec[ci_github.KEY].get("attestation")
467
+ bundle = core.git_show_bytes(repo, f"{RECEIPTS_DIR}/{name}") if isinstance(name, str) else None
468
+ raw = core.git_show_bytes(repo, rel) or b""
469
+ ok3, rows3 = ci_github.attest(rec, repo, receipt_bytes=raw, bundle=bundle, expect_repo=github,
470
+ trusted_root=trusted_root)
471
+ for r in rows3:
472
+ c.add(f"lower {rel}: ci level 3 {r['check']}", PASS if r["verdict"] == "pass" else FAIL, r["detail"])
473
+ level = ci_github.level_of(level2, ok3)
474
+ c.add(f"lower {rel}: ci level", PASS if level >= 3 else FAIL,
475
+ ci_github.LEVEL3_NOTE if level >= 3 else
476
+ f"level {level}: not attested, so level 3 is not reached (the receipt stays a valid level-{level} receipt "
477
+ f"and still backs its compute job)")
478
+ return {"path": rel, "level": level, "rows": rows + rows3}
479
+
480
+
481
+ def attestation_skip(c: Checks, repo: pathlib.Path, view: dict) -> None:
482
+ """Without --attested: a receipt whose valid `ci` block names a bundle (ci.attestation) gets a skip row saying
483
+ level 3 was not run (it runs `gh attestation verify`, an optional outside tool, only under --attested)."""
484
+ import shutil
485
+ from . import ci_github
486
+ rec, rel = view["data"], view["path"]
487
+ ci = rec.get(ci_github.KEY)
488
+ if not (isinstance(ci, dict) and "attestation" in ci) or ci_github.level1(rec, repo)[0]:
489
+ return
490
+ committed = core.git_show_bytes(repo, f"{RECEIPTS_DIR}/{ci['attestation']}") is not None
491
+ gh = "" if shutil.which("gh") else f"; {ci_github.GH_MISSING}"
492
+ c.add(f"lower {rel}: ci attestation", SKIP,
493
+ f"ci.attestation names {RECEIPTS_DIR}/{ci['attestation']} ({'committed' if committed else 'not committed'}"
494
+ f"): level 3 is not checked without --attested{gh}")
495
+
496
+
497
+ def container_check(c: Checks, view: dict, tier: str = "lower") -> None:
498
+ """The additive `container` key (#236), when present: shown, and failed when malformed. The digest is what
499
+ the job measured; the image is not published, so it is not re-derived here."""
500
+ rec, rel = view["data"], view["path"]
501
+ if "container" not in rec:
502
+ return
503
+ bad = ctr.problems(rec["container"])
504
+ if bad:
505
+ c.add(f"{tier} {rel}: container", FAIL, "; ".join(bad))
506
+ else:
507
+ c.add(f"{tier} {rel}: container", PASS, f"{ctr.describe(rec['container'])}; recorded by the job, not "
508
+ f"re-derivable from git (the image is not published)")
509
+
510
+
511
+ def _sealed_log_text(repo: pathlib.Path, rec: dict) -> str | None:
512
+ """The receipt's redacted verify log as tracked under .lean-receipts/ (its .gz decompressed), or None."""
513
+ import gzip
514
+ try:
515
+ name = gate_mod.report_log_name(rec)
516
+ except (core.Fail, KeyError):
517
+ return None
518
+ for fname, unpack in ((name, False), (name + gate_mod.REPORT_GZ_SUFFIX, True)):
519
+ path = repo / RECEIPTS_DIR / fname
520
+ if path.is_file() and not path.is_symlink():
521
+ try:
522
+ data = path.read_bytes()
523
+ return (gzip.decompress(data) if unpack else data).decode("utf-8", "replace")
524
+ except (OSError, EOFError, gzip.BadGzipFile):
525
+ return None
526
+ return None
527
+
528
+
529
+ def claim_axioms_check(c: Checks, repo: pathlib.Path, view: dict, x: str) -> None:
530
+ """AX1: a receipt's `claim_axioms` key re-derived from its sealed log (whose sha256 the report-log check
531
+ binds) against claims.yaml at X: every claim checked, none missing, no sorryAx, agreeing with
532
+ the log's `#print axioms` output, and equal to the key. A receipt without the key is not checked here."""
533
+ rec, rel = view["data"], view["path"]
534
+ if "claim_axioms" not in rec:
535
+ return
536
+ cid = f"lower {rel}: claim axioms"
537
+ text = _sealed_log_text(repo, rec)
538
+ if text is None:
539
+ c.add(cid, FAIL, "the sealed verify log is not readable here, so claim_axioms cannot be re-derived")
540
+ return
541
+ required, problems = ca.required_claims(core.git_show_bytes(repo, "./claims.yaml", x))
542
+ summary, refusals, _lines = ca.judge(text, required)
543
+ if summary is None:
544
+ c.add(cid, FAIL, "the receipt has claim_axioms but its sealed log has no claim-axioms line")
545
+ elif problems or refusals:
546
+ c.add(cid, FAIL, "; ".join(problems + refusals))
547
+ elif summary != rec["claim_axioms"]:
548
+ c.add(cid, FAIL, f"claim_axioms {rec['claim_axioms']!r} is not what the sealed log gives: {summary!r}")
549
+ else:
550
+ c.add(cid, PASS, f"{summary['checked']} claim(s) read from the built environment, every claim of "
551
+ f"claims.yaml at {x[:12]} included; re-derived from the sealed log")
552
+
553
+
554
+ def olean_check(c: Checks, repo: pathlib.Path, view: dict, x: str) -> None:
555
+ cid = f"comparator {view['path']}: olean manifest"
556
+ om = view["data"].get("olean_manifest")
557
+ if not isinstance(om, dict):
558
+ c.add(cid, SKIP, "the receipt records no olean_manifest")
559
+ return
560
+ problems = []
561
+ tc = toolchain_at(repo, x)
562
+ if str(om.get("lean_toolchain") or "").strip() != (tc or ""):
563
+ problems.append(f"olean_manifest.lean_toolchain {om.get('lean_toolchain')!r} != lean-toolchain at "
564
+ f"{x[:12]} {tc!r}")
565
+ if om.get("lake_manifest_sha256") is not None:
566
+ got = _sha_at(repo, "./lake-manifest.json", x)
567
+ if got != str(om["lake_manifest_sha256"]).lower():
568
+ problems.append(f"olean_manifest.lake_manifest_sha256 != sha256 of lake-manifest.json at {x[:12]}")
569
+ if problems:
570
+ c.add(cid, FAIL, "; ".join(problems))
571
+ else:
572
+ c.add(cid, PASS, f"toolchain and lake-manifest.json digests agree with {x[:12]} ({om.get('files')} "
573
+ f"module file(s); the manifest file describes the author's build directory and is not published)")
574
+
575
+
576
+ def claimed_theorems_check(c: Checks, repo: pathlib.Path, pkg: dict, x: str, have_comparator: bool) -> None:
577
+ from . import comparator_config as cc
578
+ from .claims import _reader
579
+ cid = "claimed theorems"
580
+ if not have_comparator:
581
+ c.add(cid, SKIP, "no comparator receipt binds the commit: the claims rest on the lower tier only")
582
+ return
583
+ try:
584
+ claims, source = cc._claims_at({**pkg, "claims": None}, repo, x)
585
+ except core.Fail:
586
+ c.add(cid, SKIP, f"no claims.yaml at {x[:12]}: no claimed theorem to match")
587
+ return
588
+ cls = cc._classify(claims, cc._configs_at(repo, x), cc.qualified_decls(_reader(repo, x), claims),
589
+ cc._sidecar_at(repo, x), cc.smoke_configs(repo, x, "HEAD"))
590
+ required = [cl for cl in cls["not_covered"] + cls["todo"] if cl.get("status") == "reusable"]
591
+ problems = []
592
+ if cls["judged_as_problems"]:
593
+ problems.append(f"judged_as mapping(s) not backed by the comparator configurations at {x[:12]}: "
594
+ + "; ".join(cls["judged_as_problems"][:10]))
595
+ if required:
596
+ problems.append(f"reusable theorem/lemma claim(s) named by no comparator configuration at {x[:12]}: "
597
+ + ", ".join(f"{cl.get('id')} ({cl.get('decl')})" for cl in required[:10]))
598
+ if problems:
599
+ c.add(cid, FAIL, "; ".join(problems))
600
+ return
601
+ rest = len(cls["not_covered"]) + len(cls["todo"])
602
+ mapped = sum(1 for cl in cls["covered"] if cc.judged_name(cl))
603
+ c.add(cid, PASS, f"every reusable theorem/lemma claim of {source} is named by a comparator configuration "
604
+ f"({len(cls['covered'])} covered" + (f", {mapped} by an explicit judged_as" if mapped else "")
605
+ + (f"; {rest} not covered, none of them reusable" if rest else "") + ")")
606
+
607
+
608
+ def hypotheses_check(c: Checks, repo: pathlib.Path, x: str, found: dict, comp_ok: bool) -> dict | None:
609
+ """Proposal 0003, stage H4: when claims.yaml at X uses hypotheses, discharges or witness, the discharge
610
+ states recomputed from the hyp-probe/1 section of the sealed log of the lower-tier receipt that binds X
611
+ (hypotheses.judge_at; the promote stage when the comparator tier passed here, else the gate stage, where
612
+ nothing is discharged). FAIL on any failed-class code, on a sealed log that is not readable, or on a log
613
+ without a complete section; SKIP when no lower-tier receipt binds X. No row, and None (no `hypotheses` in
614
+ --json), when no claim uses the keys: the output of every other package is unchanged."""
615
+ from . import claims as claims_mod
616
+ from . import comparator_config as cc
617
+ from . import hypotheses as hyp
618
+ raw = core.git_show_bytes(repo, "./claims.yaml", x)
619
+ if raw is None:
620
+ return None
621
+ try:
622
+ doc = claims_mod.load_claims_text(raw.decode("utf-8", errors="replace"), f"claims.yaml at {x[:12]}")
623
+ except core.Fail:
624
+ return None # the claims check fails it
625
+ claims = [cl for cl in doc.get("claims") or [] if isinstance(cl, dict)]
626
+ if not any(claims_mod.uses_conditional_keys(cl) for cl in claims):
627
+ return None
628
+ cid = "hypotheses"
629
+ view: dict = {"stage": "promote" if comp_ok else "gate", "checked": False}
630
+ if not found["lower"]:
631
+ c.add(cid, SKIP, f"claims.yaml at {x[:12]} uses hypotheses, discharges or witness, but no lower-tier "
632
+ f"receipt binds {x[:12]}: no sealed verify log to read the {hyp.FORMAT} facts from")
633
+ return view
634
+ lower = found["lower"][0]
635
+ text = gate_mod.sealed_log_text(repo, lower["data"], lower["path"]) # hash-checked against report_sha256
636
+ if text is None:
637
+ c.add(cid, FAIL, "the sealed verify log is not readable here (missing, or its bytes are not the receipt's "
638
+ "report_sha256), so the hypotheses cannot be judged")
639
+ return view
640
+ try:
641
+ smoke = cc.smoke_configs(repo, x, "HEAD") if comp_ok else None
642
+ except core.Fail:
643
+ smoke = None
644
+ res = hyp.judge_at(repo, x, claims, text, comparator_ok=comp_ok, smoke=smoke)
645
+ view.update(checked=True, conditional=res["conditional"], discharged=res["discharged"],
646
+ outstanding=res["outstanding"], failed=res["failed"], open=res["open"],
647
+ claims=res["claims"])
648
+ if not res["facts_ok"]:
649
+ c.add(cid, FAIL, f"claims.yaml at {x[:12]} uses hypotheses, discharges or witness: {res['facts_why']}")
650
+ return view
651
+ if res["failed"]:
652
+ c.add(cid, FAIL, "; ".join(f"{f['claim']}: {f['code']} ({f['detail'][:240]})" for f in res["failed"][:10]))
653
+ return view
654
+ disc = ", ".join(f"{d['decl']} ({d['corollary']})" for d in res["discharged"]) or "none"
655
+ detail = (f"{len(res['conditional'])} conditional claim(s); discharged {disc}; outstanding "
656
+ f"{', '.join(res['outstanding']) or 'none'}")
657
+ if view["stage"] == "gate":
658
+ detail += f" (no passing comparator receipt binds {x[:12]}: nothing is discharged at the build tier)"
659
+ if res["open"]:
660
+ detail += ("; not judged: " + "; ".join(f"{o['claim']}: {o['code']}" for o in res["open"][:10]))
661
+ c.add(cid, PASS, detail)
662
+ return view
663
+
664
+
665
+ def coverage_check(c: Checks, repo: pathlib.Path, pkg: dict, found: dict | None = None) -> None:
666
+ """The coverage item; its first warning, and the first unlisted-assumption warning (proposal 0003, open
667
+ question 7, from the sealed log of the lower-tier receipt that binds X) with how many more there are. A
668
+ warning never fails the item."""
669
+ from . import coverage as cov
670
+ cid = "coverage"
671
+ if not core.tracked_at(repo, cov.DEFAULT_COVERAGE_FILE):
672
+ c.add(cid, SKIP, f"no {cov.DEFAULT_COVERAGE_FILE} at the published ref")
673
+ return
674
+ try:
675
+ doc, claims, warnings = cov.load_checked(pkg, repo, None, False)
676
+ except core.Fail as e:
677
+ c.add(cid, FAIL, " ".join(str(e).split()))
678
+ return
679
+ lower = (found or {}).get("lower") or []
680
+ unlisted = cov.unlisted_assumption_warnings(doc, claims, repo, lower[0]["data"], lower[0]["path"]) if lower \
681
+ else []
682
+ c.add(cid, PASS, f"{cov.DEFAULT_COVERAGE_FILE}: {len(doc['rows'])} row(s); every compared theorem is the "
683
+ f"declaration of a claim a row names (R11)" + (f"; warning: {warnings[0]}" if warnings else "")
684
+ + (f"; warning: {unlisted[0]}" + (f" (and {len(unlisted) - 1} more unlisted assumption(s))"
685
+ if len(unlisted) > 1 else "") if unlisted else ""))
686
+
687
+
688
+ # --------------------------------------------------------------------------
689
+ # the page block (README.md at REF)
690
+
691
+ # Both wordings are read: the page of lean-pkg 0.11 and later (docs/design/page-for-mathematicians.md) and
692
+ # the one before it, so a page published with an earlier version is still checked.
693
+ PAGE_CHECKOUT_RE = re.compile(r"^git checkout ([0-9a-f]{40})\s+# the commit the (?:gate receipt|build check) binds$",
694
+ re.M)
695
+ PAGE_TOOLCHAIN_RE = re.compile(r"^- Lean toolchain: `([^`]*)`\.$", re.M)
696
+ PAGE_MATHLIB_RE = re.compile(r"^- Mathlib: (?:`([0-9a-f]{7,40})` \(lake-manifest\.json\)|not a dependency)", re.M)
697
+ PAGE_ROW_RE = re.compile(r"^\| `([^`]+)`( \((?:recorded|used here)\))? \| (lower tier|comparator|build|statement "
698
+ r"comparison) \| `([0-9a-f]{12})` \|"
699
+ r"[^|]*\|[^|]*\| `([0-9a-f]{64})` \|$", re.M)
700
+ PAGE_LOWER_RES = (
701
+ re.compile(r"^- Build check \(`lean-pkg gate`\) at commit `([0-9a-f]{12})`: `sorry` count ([^;\s]+); axioms "
702
+ r"used: (.*?)(?:; run in a container \(\w+\), (?:SIF SHA-256|OCI digest) `([^`]+)`)?\.$", re.M),
703
+ re.compile(r"^- Lower-tier gate receipt at `([0-9a-f]{12})` records: `sorry` count (\S+) after "
704
+ r"the build; axioms used: (.*?); allowed:", re.M))
705
+ PAGE_COMP_RES = (
706
+ re.compile(r"^- Statement comparison \(comparator\) at commit `([0-9a-f]{12})`: (\d+) configuration\(s\), "
707
+ r"(\d+) theorem\(s\) compared", re.M),
708
+ re.compile(r"^- Comparator receipt at `([0-9a-f]{12})`: (\d+) configuration\(s\), (\d+) "
709
+ r"theorem\(s\) compared", re.M))
710
+
711
+
712
+ def _search(patterns, text: str):
713
+ return next((m for m in (p.search(text) for p in patterns) if m), None)
714
+
715
+
716
+ def _names_in(text: str) -> set[str]:
717
+ return set(re.findall(r"`([^`]+)`", text))
718
+
719
+
720
+ def page_checks(c: Checks, repo: pathlib.Path, x: str, found: dict) -> None:
721
+ from . import page as page_mod
722
+ raw = core.git_show_bytes(repo, page_mod.README)
723
+ split = page_mod.split_block(raw.decode("utf-8", "replace")) if raw is not None else None
724
+ if not split or split[1] is None:
725
+ c.add("page", SKIP, f"no lean-pkg page block in {page_mod.README} at the published ref")
726
+ return
727
+ block = split[1]
728
+ m = PAGE_CHECKOUT_RE.search(block)
729
+ if not m:
730
+ c.add("page: commit", FAIL, "the page names no bound commit (no `git checkout <commit>` line)")
731
+ elif m.group(1) != x:
732
+ c.add("page: commit", FAIL, f"the page binds {m.group(1)[:12]}, not {x[:12]}")
733
+ else:
734
+ c.add("page: commit", PASS, f"the page's Reproduce section checks out {x[:12]}")
735
+ problems = []
736
+ tc = toolchain_at(repo, x)
737
+ m = PAGE_TOOLCHAIN_RE.search(block)
738
+ if not m or m.group(1) != tc:
739
+ problems.append(f"toolchain {m.group(1) if m else '(none)'!r} != lean-toolchain at {x[:12]} {tc!r}")
740
+ rev = gate_mod.committed_mathlib_rev(repo, x)
741
+ m = PAGE_MATHLIB_RE.search(block)
742
+ if not m or (m.group(1) or None) != (rev or None):
743
+ problems.append(f"Mathlib {(m.group(1) or 'not a dependency') if m else '(none)'} != lake-manifest.json "
744
+ f"at {x[:12]} ({rev or 'no mathlib'})")
745
+ c.add("page: pins", FAIL if problems else PASS,
746
+ "; ".join(problems) or f"toolchain {tc} and Mathlib {rev or 'none'} as committed at {x[:12]}")
747
+ rows = PAGE_ROW_RE.findall(block)
748
+ problems = []
749
+ listed = set()
750
+ for path, _rec, _tier, c12, sha in rows:
751
+ listed.add(path)
752
+ got = _sha_at(repo, path, "HEAD")
753
+ data, _raw = _json_at(repo, path)
754
+ if got is None:
755
+ problems.append(f"{path} is not committed")
756
+ elif got != sha:
757
+ problems.append(f"{path}: the page says SHA-256 {sha[:12]}, the committed file hashes to {got[:12]}")
758
+ elif not data or str(data.get("commit") or "")[:12] != c12:
759
+ problems.append(f"{path}: the page says commit {c12}, the receipt binds "
760
+ f"{str((data or {}).get('commit') or '?')[:12]}")
761
+ bound = found["lower"] + found["comparator"]
762
+ problems += [f"{v['path']} binds {x[:12]} but is not in the page's Evidence table"
763
+ for v in bound if v["path"] not in listed]
764
+ c.add("page: evidence", FAIL if problems else PASS,
765
+ "; ".join(problems) or f"{len(rows)} Evidence row(s): every path, commit and SHA-256 as committed")
766
+ recorded = {path for path, rec, *_ in rows if rec}
767
+ problems = []
768
+ m = _search(PAGE_LOWER_RES, block)
769
+ lowers = [v for v in found["lower"] if v["path"] in recorded] or found["lower"]
770
+ if m:
771
+ axioms = _names_in(m.group(3))
772
+ if m.group(1) != x[:12]:
773
+ problems.append(f"the trust boundary names the lower-tier receipt at {m.group(1)}, not {x[:12]}")
774
+ elif not any(str(v["data"].get("sorry_count")) == m.group(2) and set(map(str, v["data"].get("axioms") or []))
775
+ == axioms for v in lowers):
776
+ problems.append(f"the trust boundary says sorry count {m.group(2)} and axioms "
777
+ f"{sorted(axioms)}; no lower-tier receipt bound to {x[:12]} says so")
778
+ elif m.re is PAGE_LOWER_RES[0] and m.group(4) and not any(
779
+ isinstance(v["data"].get("container"), dict) and not ctr.problems(v["data"]["container"])
780
+ and ctr.digest_of(v["data"]["container"])[1] == m.group(4) for v in lowers):
781
+ problems.append(f"the trust boundary names the container image {m.group(4)[:19]}…; no lower-tier "
782
+ f"receipt bound to {x[:12]} records it")
783
+ elif found["lower"]:
784
+ problems.append("the page has no lower-tier trust-boundary line, yet a lower-tier receipt binds the commit")
785
+ m = _search(PAGE_COMP_RES, block)
786
+ comps = [v for v in found["comparator"] if v["path"] in recorded] or found["comparator"]
787
+ if m:
788
+ if m.group(1) != x[:12]:
789
+ problems.append(f"the trust boundary names the comparator receipt at {m.group(1)}, not {x[:12]}")
790
+ elif not any(len(v["data"].get("configs") or []) == int(m.group(2)) and sum(
791
+ len(cf.get("theorem_names") or []) for cf in v["data"].get("configs") or [] if isinstance(cf, dict))
792
+ == int(m.group(3)) for v in comps):
793
+ problems.append(f"the trust boundary says {m.group(2)} configuration(s) and {m.group(3)} theorem(s) "
794
+ f"compared; no comparator receipt bound to {x[:12]} says so")
795
+ elif found["comparator"]:
796
+ problems.append("the page says no comparator receipt is committed, yet one binds the commit")
797
+ c.add("page: trust boundary", FAIL if problems else PASS,
798
+ "; ".join(problems) or "sorry count, axioms and comparator counts as the receipts record them")
799
+
800
+
801
+ # --------------------------------------------------------------------------
802
+ # the command
803
+
804
+ def package_name(repo: pathlib.Path, x: str, given: str | None) -> str:
805
+ """--name, else `package` of coverage.yaml at REF, else of claims.yaml at X, else the directory name."""
806
+ import yaml
807
+ if given:
808
+ return given
809
+ for rel, rev in (("coverage.yaml", "HEAD"), ("claims.yaml", x)):
810
+ raw = core.git_show_bytes(repo, rel, rev)
811
+ try:
812
+ doc = yaml.safe_load(raw) if raw is not None else None
813
+ except yaml.YAMLError:
814
+ doc = None
815
+ if isinstance(doc, dict) and isinstance(doc.get("package"), str) and doc["package"].strip():
816
+ return doc["package"].strip()
817
+ return repo.name
818
+
819
+
820
+ def rule_text(oi, x: str, evidence_only: bool = False) -> str:
821
+ """The `rule:` line: which descendants bind, and who chose the docs-only rule. Without a file at X and
822
+ without a flag it reads as before the committed opt-in existed."""
823
+ x12 = x[:12]
824
+ if evidence_only and oi.file_state != "true":
825
+ return "evidence-only descendants (docs-only not accepted: --evidence-only)"
826
+ if oi.source == "committed":
827
+ return (f"evidence-only or docs-only descendants (docs-only: the author's opt-in, {BINDING_FILE} "
828
+ f"committed at {x12}; --evidence-only to refuse them)")
829
+ if oi.source == "referee":
830
+ return "evidence-only or docs-only descendants (docs-only accepted by the referee: --docs-descendants)"
831
+ if oi.file_state == "true": # applied only when --evidence-only did not ignore it
832
+ return f"evidence-only descendants (docs-only not accepted: --evidence-only ignores {BINDING_FILE} at {x12})"
833
+ if oi.file_state in ("false", "invalid"):
834
+ over = "; --docs-descendants overridden" if any(n.startswith("--docs-descendants") for n in oi.notes) else ""
835
+ return f"evidence-only descendants ({BINDING_FILE} at {x12} does not opt in{over})"
836
+ return "evidence-only descendants (docs-only not accepted; --docs-descendants to accept them)"
837
+
838
+
839
+ def opt_in_view(oi) -> dict | None:
840
+ """JSON `opt_in`: {source (committed | referee | null), commit, path, build_inputs, file (absent | true |
841
+ false | invalid), problems}; null when no file is at X and the evidence-only rule applies."""
842
+ if oi.file_state == "absent" and oi.source is None:
843
+ return None
844
+ return {"source": oi.source, "commit": oi.commit, "path": oi.path, "build_inputs": list(oi.build_inputs),
845
+ "file": oi.file_state, "problems": list(oi.problems)}
846
+
847
+
848
+ def attested_usage(attested: bool, trusted_root: str | None) -> str | None:
849
+ """--trusted-root goes with --attested and names a readable file; its absolute path, or None."""
850
+ if trusted_root is None:
851
+ return None
852
+ if not attested:
853
+ raise core.UsageError("--trusted-root FILE is the Sigstore trusted root of an offline --attested check; pass "
854
+ "both")
855
+ p = pathlib.Path(trusted_root).expanduser()
856
+ if not p.is_file():
857
+ raise core.UsageError(f"--trusted-root {trusted_root}: no such file")
858
+ return str(p.resolve())
859
+
860
+
861
+ def _lower_ok(c: Checks, found: dict) -> bool:
862
+ return bool(found["lower"]) and not any(
863
+ i["verdict"] == FAIL for i in c.items if i["id"].startswith(("lower ", "receipts", "binding")))
864
+
865
+
866
+ def _comparator_ok(c: Checks, found: dict) -> bool:
867
+ """The comparator tier passed so far (the tier's own rule; the checks after `claimed theorems` never count)."""
868
+ return _lower_ok(c, found) and bool(found["comparator"]) and not any(
869
+ i["verdict"] == FAIL for i in c.items if i["id"].startswith(("comparator ", "claimed theorems")))
870
+
871
+
872
+ def do_check(repo_dir: str, commit: str, at: str | None = None, docs_descendants: bool = False,
873
+ name: str | None = None, evidence_only: bool = False, corroborate: bool = False,
874
+ github: str | None = None, fetch=None, attested: bool = False,
875
+ trusted_root: str | None = None) -> tuple[list[str], dict, int]:
876
+ from . import index as index_mod
877
+ if docs_descendants and evidence_only:
878
+ raise core.UsageError("--docs-descendants and --evidence-only are mutually exclusive: --docs-descendants "
879
+ f"accepts docs-only descendants for a package without {BINDING_FILE}, "
880
+ "--evidence-only refuses them whatever the package committed")
881
+ from . import ci_github
882
+ if github is not None and not (corroborate or attested):
883
+ raise core.UsageError("--github names the package's repository for --corroborate; pass both")
884
+ trusted_root = attested_usage(attested, trusted_root)
885
+ if github is not None and not ci_github.REPOSITORY_RE.match(github):
886
+ raise core.UsageError(f"--github {github!r}: must be OWNER/REPO")
887
+ corroborated: list[dict] = []
888
+ if corroborate and fetch is None:
889
+ fetch = ci_github.api_fetch()
890
+ with tempfile.TemporaryDirectory(prefix="lean-pkg-receipt-check-") as tmp:
891
+ src = open_source(repo_dir, commit, at, pathlib.Path(tmp))
892
+ repo, x, ref = src["clone"], src["commit"], src["at"]
893
+ pkg_name = package_name(repo, x, name)
894
+ found = discover(repo, x)
895
+ comp_rel = found["comparator"][0]["path"] if found["comparator"] else None
896
+ pkg = referee_pkg(pkg_name, docs_descendants, comp_rel, evidence_only)
897
+ oi = referee_opt_in(repo, x, docs_descendants, evidence_only)
898
+ c = Checks(repo, src["root"])
899
+ bound = len(found["lower"]) + len(found["comparator"])
900
+ if not found["lower"]:
901
+ c.add("receipts", FAIL, f"no lower-tier receipt tracked under {RECEIPTS_DIR}/ at {ref[:12]} binds "
902
+ f"{x[:12]}" + (f" ({len(found['other'])} receipt(s) bind other commits: "
903
+ f"{', '.join(sorted({v['commit'][:12] for v in found['other']}))})"
904
+ if found["other"] else ""))
905
+ else:
906
+ c.add("receipts", PASS, f"{len(found['lower'])} lower-tier and {len(found['comparator'])} comparator "
907
+ f"receipt(s) bind {x[:12]}")
908
+ for v in found["misnamed"]:
909
+ c.add(f"receipt {v['path']}", FAIL, f"named for {x[:12]} but binds {v['commit'][:12] or '?'}")
910
+ for v in found["sidecar"]:
911
+ c.add(f"receipt {v['path']}", SKIP, f"not a receipt: a {v['schema']} record the comparator runner "
912
+ f"writes (only an exact non-receipt schema is skipped; any other non-receipt JSON named for "
913
+ f"the commit fails)")
914
+ for rel in found["unreadable"]:
915
+ c.add(f"receipt {rel}", FAIL, "named for the commit but not a readable receipt (not JSON, or neither "
916
+ "a lower-tier nor a comparator receipt, nor a comparator runner record whose schema is one of "
917
+ f"{', '.join(NON_RECEIPT_SCHEMAS)}); rename a non-receipt file so it does not start with "
918
+ f"{x[:12]}, or keep it outside {RECEIPTS_DIR}/")
919
+ checker = found["lower"][0]["data"].get("checker") if found["lower"] else None
920
+ opt_in_check(c, repo, x, ref, oi)
921
+ check_binding(c, repo, x, ref, pkg, checker, oi)
922
+ for v in found["lower"]:
923
+ rec, rel = v["data"], v["path"]
924
+ if c.run(f"lower {rel}", lambda: gate_mod.validate_receipt(pkg, repo, rec), # noqa: B023 called synchronously, within this iteration
925
+ f"schema, binding, pins (lean-toolchain, lake-manifest.json at {x[:12]}), sorry_count 0, "
926
+ f"axioms {sorted(rec.get('axioms') or [])} within {list(DEFAULT_AXIOMS)}"):
927
+ try:
928
+ line, _view = gate_mod.report_log_check(repo, rec, repo / rel) # a missing log refuses
929
+ c.add(f"lower {rel}: report log", PASS, line[2:])
930
+ except core.Fail as e:
931
+ c.add(f"lower {rel}: report log", FAIL, str(e))
932
+ evidence_file_checks(c, repo, v, x)
933
+ sacct_seal_check(c, v)
934
+ ci_check(c, repo, v)
935
+ if (corroborate or attested) and (got := corroborate_check(
936
+ c, repo, v, fetch, github, attested, trusted_root, corroborate)) is not None:
937
+ corroborated.append(got)
938
+ if not attested:
939
+ attestation_skip(c, repo, v)
940
+ container_check(c, v)
941
+ claim_axioms_check(c, repo, v, x)
942
+ cs = gate_mod.claims_schema_at(pkg_name, pkg, repo, x)
943
+ if not cs["checked"]:
944
+ c.add("claims", SKIP, f"no {cs['file']} at {x[:12]}")
945
+ else:
946
+ c.add("claims", PASS if cs["ok"] else FAIL, gate_mod.claims_schema_line(cs)[2:])
947
+ lower_commit = x if found["lower"] else None
948
+ for v in found["comparator"]:
949
+ rel = v["path"]
950
+ n_cfg = len(v["data"].get("configs") or [])
951
+ c.run(f"comparator {rel}", lambda: gate_mod.validate_comparator(pkg, repo, v["data"], lower_commit), # noqa: B023 called synchronously, within this iteration
952
+ f"{n_cfg} configuration(s) tracked at {x[:12]} re-derived from bytes (sha256, theorem names, "
953
+ f"sign-off), every log's sha256 and PASS line, same commit as the lower tier")
954
+ olean_check(c, repo, v, x)
955
+ container_check(c, v, "comparator")
956
+ ci_check(c, repo, v, "comparator")
957
+ claimed_theorems_check(c, repo, pkg, x, bool(found["comparator"]))
958
+ hyp_view = hypotheses_check(c, repo, x, found, _comparator_ok(c, found))
959
+ coverage_check(c, repo, pkg, found)
960
+ page_checks(c, repo, x, found)
961
+ # #237: the toolchain the receipts bind (else lean-toolchain at X) against the shipped advisories
962
+ toolchains = [v["data"].get("lean_toolchain") for k in ("lower", "comparator") for v in found[k]]
963
+ advisories, advisory_lines = toolchain_advisories.warn_lines(
964
+ [t for t in toolchains if isinstance(t, str) and t.strip()] or [toolchain_at(repo, x)])
965
+ failed = c.failed()
966
+ lower_ok = _lower_ok(c, found)
967
+ comp_ok = _comparator_ok(c, found)
968
+ tier = index_mod.compute_trust(lower_ok, comp_ok, [])
969
+ rule = rule_text(oi, x, evidence_only)
970
+ note = ATTESTED_NOTE if attested else CORROBORATE_NOTE if corroborate else RERUN_NOTE
971
+ ok = failed == 0
972
+ counts = {v: sum(i["verdict"] == v for i in c.items) for v in (PASS, FAIL, SKIP)}
973
+ summary = (f"receipt check: {'PASS' if ok else 'FAIL'} {pkg_name} at {x[:12]} "
974
+ + (f"(tier {tier}; {counts[PASS]} passed, {counts[SKIP]} skipped)" if ok
975
+ else f"({counts[FAIL]} check(s) failed; tier {tier or 'none'})"))
976
+ lines = [summary,
977
+ f" commit {x} (published ref {ref[:12]}{', the same commit' if ref == x else ''})",
978
+ f" rule: {rule}",
979
+ *[f" exemption: {e}" for e in c.exemptions],
980
+ f" note: {note}",
981
+ *([f" repository: {REPO_NOTE.format(where='--github ' + github) if github else REPO_DEFAULT}"]
982
+ if corroborate or attested else []),
983
+ *[f" {w}" for w in advisory_lines]]
984
+ lines += [f" {i['verdict'].upper():4} {i['id']}: {i['detail']}" for i in c.items]
985
+ lines.append(summary)
986
+ receipts = {k: [{"path": v["path"], "sha256": v["sha256"], "commit": v["commit"]} for v in found[k]]
987
+ for k in ("lower", "comparator")}
988
+ receipts["other"] = [{"path": v["path"], "sha256": v["sha256"], "commit": v["commit"]} for v in found["other"]]
989
+ payload = {"ok": ok, "name": pkg_name, "commit": x, "at": ref, "prefix": src["prefix"] or None,
990
+ "docs_descendants": oi.rule == "docs-only", "evidence_only": bool(evidence_only),
991
+ "opt_in": opt_in_view(oi), "rule": rule, "tier": tier, "runs_lean": False,
992
+ "network": bool(corroborate or (attested and trusted_root is None)),
993
+ "note": note, "receipts": receipts, "bound_receipts": bound,
994
+ "counts": counts, "exemptions": c.exemptions,
995
+ "skipped_records": [v["path"] for v in found["sidecar"]], "checks": c.items,
996
+ "toolchain_advisories": advisories}
997
+ if hyp_view is not None: # proposal 0003: only when claims.yaml at X uses the keys
998
+ payload["hypotheses"] = hyp_view
999
+ if attested:
1000
+ payload["attested"] = True
1001
+ payload["trusted_root"] = trusted_root
1002
+ if corroborate or attested:
1003
+ payload["github"] = github
1004
+ payload["ci"] = {"level": min((g["level"] for g in corroborated), default=None),
1005
+ "rows": [{"receipt": g["path"], **r} for g in corroborated for r in g["rows"]]}
1006
+ return lines, payload, 0 if ok else 1
1007
+
1008
+
1009
+ def cmd_receipt_check(args) -> int:
1010
+ lines, payload, rc = do_check(args.repo, args.commit_sha, args.at, args.docs_descendants, args.name,
1011
+ getattr(args, "evidence_only", False),
1012
+ corroborate=args.corroborate, github=args.github,
1013
+ attested=args.attested, trusted_root=args.trusted_root)
1014
+ if getattr(args, "json_out", False):
1015
+ core.print_json(payload)
1016
+ else:
1017
+ print("\n".join(lines))
1018
+ return rc
1019
+
1020
+
1021
+ def add_parser(rsub) -> None:
1022
+ import argparse
1023
+ s = rsub.add_parser("check", help="validate a published package's receipts from git alone: no registry, no "
1024
+ "network, never runs Lean (an outside referee's check; exit 0 only when "
1025
+ "every check passes)")
1026
+ s.add_argument("--repo", required=True, metavar="DIR",
1027
+ help="a local clone of the package (the package directory; cloned privately, never modified)")
1028
+ s.add_argument("--commit", dest="commit_sha", required=True, metavar="SHA",
1029
+ help="the commit the receipts bind (the page's `git checkout <commit>` line)")
1030
+ s.add_argument("--at", default=None, metavar="REF",
1031
+ help="the published ref whose .lean-receipts/, coverage.yaml and README.md are read (default "
1032
+ "HEAD of --repo); it must be the commit or an evidence-only descendant of it (or a docs-only "
1033
+ "one, when the docs-only rule applies)")
1034
+ g = s.add_mutually_exclusive_group()
1035
+ g.add_argument("--docs-descendants", action="store_true",
1036
+ help="for a package without lean-pkg-binding.yaml at the commit: also accept a docs-only "
1037
+ "descendant (no build input changed) as the referee's choice, printed in the result; a "
1038
+ "committed file that says false or does not validate overrides it")
1039
+ g.add_argument("--evidence-only", action="store_true",
1040
+ help="accept only evidence-only descendants: ignore the author's committed opt-in "
1041
+ "(lean-pkg-binding.yaml at the commit, applied by default)")
1042
+ s.add_argument("--name", default=None,
1043
+ help="the package name the claims must carry (default: `package` in coverage.yaml, else "
1044
+ "claims.yaml, else the directory name)")
1045
+ s.add_argument("--corroborate", action="store_true",
1046
+ help="also corroborate every receipt with a ci block (a GitHub Actions run) against the public "
1047
+ "GitHub REST API, level 2, and fail when one does not reach it (404, rate limit, network "
1048
+ "error and a redirect off api.github.com fail closed). GH_TOKEN or GITHUB_TOKEN, when set, "
1049
+ "only raises the rate limit and is never printed. The one networked check")
1050
+ s.add_argument("--github", default=None, metavar="OWNER/REPO",
1051
+ help="with --corroborate or --attested: the package's own GitHub repository, whose numeric id "
1052
+ "the run's must equal (default: the receipt's ci.repository, and the output says so)")
1053
+ s.add_argument("--attested", action="store_true",
1054
+ help="also verify every receipt with a ci block at level 3: its committed Sigstore bundle "
1055
+ "(ci.attestation) with `gh attestation verify`, an optional outside tool (missing: a "
1056
+ "failure), and the certificate's repository, commit, run and signer against the ci block; "
1057
+ "fail when one does not reach level 3")
1058
+ s.add_argument("--trusted-root", default=None, metavar="FILE",
1059
+ help="with --attested: verify offline against this Sigstore trusted root (gh attestation "
1060
+ "verify --custom-trusted-root)")
1061
+ s.add_argument("--json", dest="json_out", action="store_true", default=argparse.SUPPRESS,
1062
+ help="machine-readable JSON on stdout: every check with its verdict")
1063
+ s.set_defaults(fn=cmd_receipt_check)
1064
+