lean-pkg 0.25.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. lean_pkg/__init__.py +3 -0
  2. lean_pkg/adapters/__init__.py +148 -0
  3. lean_pkg/adapters/github.py +65 -0
  4. lean_pkg/adapters/leansearch.py +68 -0
  5. lean_pkg/adapters/loogle.py +45 -0
  6. lean_pkg/adapters/palomar.py +170 -0
  7. lean_pkg/adapters/reservoir.py +127 -0
  8. lean_pkg/anchor.py +678 -0
  9. lean_pkg/audit.py +716 -0
  10. lean_pkg/binding_file.py +446 -0
  11. lean_pkg/blueprint.py +213 -0
  12. lean_pkg/build_scope.py +282 -0
  13. lean_pkg/ci_github.py +917 -0
  14. lean_pkg/claim_axioms.py +421 -0
  15. lean_pkg/claims.py +1155 -0
  16. lean_pkg/claims_mark.py +197 -0
  17. lean_pkg/cli.py +5208 -0
  18. lean_pkg/cli_parser.py +768 -0
  19. lean_pkg/command_tree.py +615 -0
  20. lean_pkg/comparator_config.py +990 -0
  21. lean_pkg/comparator_contracts.py +382 -0
  22. lean_pkg/comparator_receipt.py +2854 -0
  23. lean_pkg/comparator_stage.py +623 -0
  24. lean_pkg/comparator_types.py +830 -0
  25. lean_pkg/container.py +172 -0
  26. lean_pkg/core.py +1570 -0
  27. lean_pkg/coverage.py +1278 -0
  28. lean_pkg/data/stacks/lts-2026.10.yaml +73 -0
  29. lean_pkg/data/toolchain-advisories.yaml +77 -0
  30. lean_pkg/data/upgrade-breaking.yaml +20 -0
  31. lean_pkg/data/verify-workflow-pins.yaml +14 -0
  32. lean_pkg/deps_closure.py +512 -0
  33. lean_pkg/deps_fill.py +445 -0
  34. lean_pkg/dup_constants.py +448 -0
  35. lean_pkg/exercise.py +828 -0
  36. lean_pkg/exercise_forbid.py +288 -0
  37. lean_pkg/export_paths.py +77 -0
  38. lean_pkg/extract.py +1172 -0
  39. lean_pkg/extract_decls.py +501 -0
  40. lean_pkg/extract_ledger.py +1408 -0
  41. lean_pkg/extract_summary.py +132 -0
  42. lean_pkg/extract_types.py +502 -0
  43. lean_pkg/extract_write.py +138 -0
  44. lean_pkg/formalization.py +1078 -0
  45. lean_pkg/formalization_kept.py +182 -0
  46. lean_pkg/fresh_repo.py +709 -0
  47. lean_pkg/gate.py +2141 -0
  48. lean_pkg/headline.py +211 -0
  49. lean_pkg/help_topics.py +442 -0
  50. lean_pkg/holes.py +289 -0
  51. lean_pkg/host_routes.py +376 -0
  52. lean_pkg/hypotheses.py +788 -0
  53. lean_pkg/index.py +1749 -0
  54. lean_pkg/json_stdout.py +48 -0
  55. lean_pkg/lake_hygiene.py +289 -0
  56. lean_pkg/lean_diag.py +280 -0
  57. lean_pkg/lean_scan.py +1300 -0
  58. lean_pkg/ledger.py +582 -0
  59. lean_pkg/next_step.py +510 -0
  60. lean_pkg/page.py +1831 -0
  61. lean_pkg/page_html.py +153 -0
  62. lean_pkg/palomar.py +316 -0
  63. lean_pkg/palomar_check.py +1027 -0
  64. lean_pkg/port_modules.py +677 -0
  65. lean_pkg/prior_art.py +286 -0
  66. lean_pkg/producer.py +212 -0
  67. lean_pkg/producer_skew.py +208 -0
  68. lean_pkg/public_safety.py +1487 -0
  69. lean_pkg/publish.py +402 -0
  70. lean_pkg/rebase.py +984 -0
  71. lean_pkg/receipt.py +2385 -0
  72. lean_pkg/receipt_check.py +1064 -0
  73. lean_pkg/receipt_ci.py +660 -0
  74. lean_pkg/receipt_systemd.py +890 -0
  75. lean_pkg/recommended.py +232 -0
  76. lean_pkg/report.py +727 -0
  77. lean_pkg/reservoir.py +203 -0
  78. lean_pkg/scaffold.py +588 -0
  79. lean_pkg/schemas/formalization-0.4.schema.json +344 -0
  80. lean_pkg/schemas/formalization-0.4.schema.source.txt +15 -0
  81. lean_pkg/scripts/ClaimAxioms.lean +47 -0
  82. lean_pkg/scripts/ContractsOnly.lean +300 -0
  83. lean_pkg/scripts/DupConstants.lean +149 -0
  84. lean_pkg/scripts/HypProbe.lean +257 -0
  85. lean_pkg/scripts/comparator-check.sh +396 -0
  86. lean_pkg/scripts/verify-comparator.sh +135 -0
  87. lean_pkg/seal_bundle.py +647 -0
  88. lean_pkg/search.py +865 -0
  89. lean_pkg/site_profiles/easley.yaml +10 -0
  90. lean_pkg/site_profiles/github-actions.yaml +12 -0
  91. lean_pkg/sites.py +225 -0
  92. lean_pkg/stacks.py +373 -0
  93. lean_pkg/statements_module.py +217 -0
  94. lean_pkg/templates/Apache-2.0.txt +202 -0
  95. lean_pkg/toolchain_advisories.py +225 -0
  96. lean_pkg/upgrade.py +706 -0
  97. lean_pkg/verify.py +495 -0
  98. lean_pkg-0.25.0.dist-info/METADATA +93 -0
  99. lean_pkg-0.25.0.dist-info/RECORD +103 -0
  100. lean_pkg-0.25.0.dist-info/WHEEL +5 -0
  101. lean_pkg-0.25.0.dist-info/entry_points.txt +5 -0
  102. lean_pkg-0.25.0.dist-info/licenses/LICENSE +202 -0
  103. lean_pkg-0.25.0.dist-info/top_level.txt +1 -0
lean_pkg/page.py ADDED
@@ -0,0 +1,1831 @@
1
+ # lean-pkg page -- the generated verification section of a package README
2
+ """`lean-pkg page NAME [--write | --check | --out PATH] [--site DIR] [--html PATH] [--repo DIR]
3
+ [--allow-private-manuscript] [--agent A]`.
4
+
5
+ Mathematics first (docs/design/page-for-mathematicians.md): one line telling the reader which statements to
6
+ compare by eye, then each result with the paper's statement beside the Lean statement, then what the checks
7
+ establish, and the receipts last. A public Lean verification repository needs one section a reader can trust: what is formalized and what
8
+ is not, under which assumptions, what the receipts prove, how to reproduce it, how to cite it and whom to
9
+ credit. Every number and status word in that section is rendered here from data, never typed:
10
+
11
+ * `coverage.yaml` (coverage/1, lean_pkg.coverage): the paper rows, the capsule sentence, the manuscript
12
+ version, the compute declaration; for `kind: library` (a reusable library with no manuscript) the
13
+ library's main results instead, and no section names a manuscript or a paper;
14
+ * `claims.yaml` at HEAD: the declarations of each row;
15
+ * the claims ledger (lean_pkg.ledger, promote stage): a row says `verified` only when the ledger closes
16
+ every claim it names;
17
+ * the Lean sources at the gate-bound commit: each result's Lean statement (lean_scan.statement), from the
18
+ Challenge module when the comparator compared it (or, for an umbrella Challenge, from the one package file
19
+ of its import closure that declares the theorem, linked at its line), else the claim's file; a link when it
20
+ cannot be read;
21
+ * the receipts committed at HEAD under `.lean-receipts/`: what the checks establish, the expected axioms,
22
+ the receipt table (last, under "How this was checked"). Fields are copied from an allow-list only (commit, toolchain, Mathlib revision, sorry
23
+ count, axioms, theorem names, permitted axioms, definition names, date, SHA-256 of the file, a Slurm job
24
+ id, a container engine and image digest); hosts, paths, user names, checker commands and other job ids are never copied;
25
+ * `lean-toolchain`, `lake-manifest.json`, `CITATION.cff` (authors must be non-empty), the registry's
26
+ `repo`, `license_spdx` and `doi`. The registry `status` is not rendered: it changes on promote while
27
+ the page is committed at one commit (it stays in `lean-pkg status` and `--json`).
28
+
29
+ The section lives in the package's README.md between BEGIN and END. `--write` replaces exactly that block
30
+ (appending it when absent) and never touches the prose outside the markers. `--check` exits 1 when the
31
+ block is missing or stale, when the README lacks the lean-pkg credit, or when it carries the Easley
32
+ sentence without a backing Slurm receipt. Every rendered string passes the public-safety scanner with the
33
+ package's `.lean-pkg-private-patterns`; a blocking hit refuses.
34
+
35
+ `--site DIR` also writes DIR/verification.md (the full page) and DIR/coverage.md (every row with its
36
+ claims, declarations, ledger statuses, inputs and notes); `--html PATH` one static HTML file of both
37
+ (page_html: no script, no external asset). All outputs come from one context, are scanned together and
38
+ do not depend on DIR; with `--check` they are compared instead. Text from data is escaped by `_md` in
39
+ every output. `--repo DIR` reads another checkout for one call (CI), never with `--write`.
40
+
41
+ Easley rule, for every site profile (sites.py; Easley is the first). Receipts carry no cluster identity (a
42
+ Slurm receipt says `slurm-<J>`, not where J ran), so a site's sentence needs both an explicit declaration
43
+ and evidence: coverage.yaml `compute: [{cluster: easley, jobs: [slurm-<J>, ...]}]`, every listed job
44
+ matching the `job_id` of a receipt of the site's scheduler committed at HEAD under `.lean-receipts/`
45
+ (coverage.slurm_job_of for Slurm; a comparator receipt's job counts only with its sacct seal,
46
+ `comparator-receipt --seal-sacct`; ci_github.gha_job_of for GitHub Actions). Without both, no sentence.
47
+ And the level: a backed site renders its sentence only when the corroboration level its jobs reached is at
48
+ least its scheduler's sentence_level (sites.py). Offline every job is level 1, which is Slurm's; GitHub
49
+ Actions needs level 2, a corroborated run: only `--corroborate` (here and on the `publish --dry-run` page
50
+ line) asks the public GitHub REST API about each listed run (ci_github.corroborate, against the package's
51
+ repository from the registry's repository URL), and the sentence renders with `{runs}` filled by the runs'
52
+ links only when every listed job reached level 2. Without the flag the sentence is absent and a README
53
+ carrying it fails `--check` with a `--corroborate` hint; with it, a failed corroboration is named. `--attested`
54
+ (level 3; here and on the `publish --dry-run` page line) verifies each listed job's committed Sigstore bundle
55
+ with `gh attestation verify` instead (or as well, with both flags, when level 3 needs both answers), so the
56
+ sentence survives the run's records expiring; `--trusted-root FILE` verifies offline. `page --json` sites.<name>.level and levels then reach 3.
57
+
58
+ Not a registry write: the registry is read, never written (no lock, no --commit), like `formalization
59
+ --write --no-registry`. `--write` honours a live lease held by another agent (pass --agent HOLDER).
60
+ """
61
+
62
+ from __future__ import annotations
63
+
64
+ import json
65
+ import re
66
+
67
+ from . import gate as gate_mod
68
+ from . import core
69
+ from . import coverage as cov
70
+ from . import sites
71
+
72
+ BEGIN = "<!-- lean-pkg:page:begin -->"
73
+ END = "<!-- lean-pkg:page:end -->"
74
+ README = "README.md"
75
+ LEAN_PKG_URL = "https://github.com/lean-pkg/lean-pkg"
76
+ CONCEPT_DOI = "10.5281/zenodo.23272098"
77
+ CREDIT = (f"Developed and verified with [lean-pkg]({LEAN_PKG_URL}) "
78
+ f"([doi:{CONCEPT_DOI}](https://doi.org/{CONCEPT_DOI})).")
79
+ # Kept names (tests and callers since 0.7): the first built-in site profile's sentence and mention. The page
80
+ # itself reads every profile alike (sites.py); no code path below is special to one site.
81
+ _FIRST_SITE = next(iter(sites.builtin().values()))
82
+ EASLEY = _FIRST_SITE.acknowledgement
83
+ EASLEY_RE = _FIRST_SITE.mention_re
84
+ # The legacy top-level `page --json` key of a site, `{backed, jobs}` (since 0.7), kept for the first built-in
85
+ # profile only and dropped at the 1.0 freeze; every profile is under `sites`.
86
+ LEGACY_SITE_KEYS = ("easley",)
87
+ # Offline, the level every backed job reaches: consistency with the commit and the committed files
88
+ # (proposal 0008); corroboration against the run (level 2) needs `--corroborate`.
89
+ OFFLINE_LEVEL = 1
90
+ CORROBORATE_HINT = ("`--corroborate` on page --check and publish --dry-run; GH_TOKEN or GITHUB_TOKEN raises the "
91
+ "API rate limit")
92
+
93
+
94
+ class Corroborator:
95
+ """`--corroborate` and `--attested`: the level of each GitHub Actions job a site lists, asked of the public
96
+ API (level 2, ci_github.corroborate) and of the committed Sigstore bundle through `gh attestation verify`
97
+ (level 3, ci_github.attest) once per job, and kept for the renders of one command. The package's own
98
+ repository is the registry's repository URL (OWNER/REPO on github.com); without one, no job reaches level 2
99
+ or 3. Under both flags level 3 needs both answers (ci_github.level_of)."""
100
+
101
+ def __init__(self, pkg: dict, repo, fetch=None, *, corroborate: bool = True, attested: bool = False,
102
+ trusted_root: str | None = None) -> None:
103
+ self.repo = repo
104
+ self.expect = core.gh_nwo(pkg.get("repo") or "")
105
+ self._fetch = fetch
106
+ self._index: dict[str, str] | None = None
107
+ self.cache: dict[str, dict] = {}
108
+ self.corroborate = corroborate
109
+ self.attested = attested
110
+ self.trusted_root = trusted_root
111
+
112
+ def job(self, job: str) -> dict:
113
+ """{level, rows, link}: link is the run's Markdown link (rendered only at level 2 or 3)."""
114
+ if job in self.cache:
115
+ return self.cache[job]
116
+ from . import ci_github
117
+ if self._index is None:
118
+ self._index = ci_github.jobs_at_head(self.repo)
119
+ rec, raw = cov.receipt_at_head(self.repo, self._index[job])
120
+ if self.expect is None:
121
+ got = {"level": OFFLINE_LEVEL, "link": None, "rows": [
122
+ {"check": "package repository", "verdict": "fail",
123
+ "detail": "the registry's repository URL is not a github.com repository, so the package's "
124
+ "repository id is unknown; no run corroborates"}]}
125
+ else:
126
+ level2, rows = None, []
127
+ if self.corroborate:
128
+ if self._fetch is None:
129
+ self._fetch = ci_github.api_fetch()
130
+ level2, rows = ci_github.corroborate(rec, self.repo, fetch=self._fetch,
131
+ receipt_sha256=core.sha256_bytes(raw), expect_repo=self.expect)
132
+ ok3 = None
133
+ if self.attested:
134
+ name = rec[ci_github.KEY].get("attestation")
135
+ bundle = core.git_show_bytes(self.repo, f".lean-receipts/{name}") if isinstance(name, str) else None
136
+ ok3, rows3 = ci_github.attest(rec, self.repo, receipt_bytes=raw, bundle=bundle,
137
+ expect_repo=self.expect, trusted_root=self.trusted_root)
138
+ rows = rows + rows3
139
+ got = {"level": ci_github.level_of(level2, ok3), "rows": rows,
140
+ "link": ci_github.run_link(rec[ci_github.KEY])}
141
+ self.cache[job] = got
142
+ return got
143
+ GENERATED_NOTE = ("<!-- Generated by `lean-pkg page {name}` from coverage.yaml, claims.yaml, the claims ledger "
144
+ "and the receipts committed under .lean-receipts/. Do not edit between the markers: change "
145
+ "the data and run `lean-pkg page {name} --write`. -->")
146
+ SITE_NOTE = ("<!-- Generated by `lean-pkg page {name}` (site output) from coverage.yaml, claims.yaml, the claims "
147
+ "ledger and the receipts committed under .lean-receipts/. Do not edit: change the data and render "
148
+ "it again. -->")
149
+ SITE_FILES = ("verification.md", "coverage.md")
150
+ HTML_NAME = "verification.html" # the name the scanner sees for --html PATH
151
+ SAFE_TOKEN = re.compile(r"^[^\s`|<>\[\]()*\\]+$") # a Lean name, an axiom, a toolchain: copied only if this
152
+ DATE_RE = re.compile(r"^(\d{4}-\d{2}-\d{2})T")
153
+ LEDGER_WORDS = {
154
+ "ready": "every required claim is closed by the recorded receipts",
155
+ "open": "not every required claim is closed by the recorded receipts",
156
+ "failed": "recorded evidence contradicts a required claim",
157
+ "unknown": "the recorded evidence cannot be read, or establishes nothing yet",
158
+ }
159
+ CONDITIONAL_SENTENCE = "A conditional result says nothing when an outstanding assumption is false."
160
+
161
+
162
+ def _conditional_ready(led: dict) -> tuple[int, list[str]] | None:
163
+ """(conditional required claims, outstanding hypotheses as safe names) when the ledger is ready with
164
+ conditional required claims (proposal 0003, open question 1); None otherwise, so other pages are unchanged."""
165
+ if led.get("package_status") != "ready" or not led.get("conditional_required"):
166
+ return None
167
+ return len(led["conditional_required"]), list(led.get("outstanding_hypotheses") or [])
168
+
169
+
170
+ def _hyp_list(hyps: list) -> str:
171
+ """The outstanding hypotheses as code spans; a name that is not a safe token is counted, never dropped, so
172
+ the list never reads as empty ("all discharged") while one is outstanding."""
173
+ if not hyps:
174
+ return "none, all discharged"
175
+ shown = _names(hyps)
176
+ hidden = len(hyps) - len(shown)
177
+ return ", ".join([f"`{h}`" for h in shown] + ([f"{hidden} more not shown here (see the claims ledger)"]
178
+ if hidden else []))
179
+
180
+
181
+ def _conditional_tag(led: dict) -> str:
182
+ """The qualifier after a ready ledger's status on the coverage pages ('' unless conditional)."""
183
+ cond = _conditional_ready(led)
184
+ return (f", with {cond[0]} conditional required claim(s) (outstanding hypotheses: {_hyp_list(cond[1])})"
185
+ if cond else "")
186
+
187
+
188
+ def _conditional_gloss(led: dict) -> str:
189
+ """The coverage table's gloss of *conditional* (proposal 0003), only when a claim uses the keys."""
190
+ return ("; *conditional* means they close it only under its hypotheses, some of which may be outstanding "
191
+ "(an outstanding assumption is not proved)" if "conditional" in led["counts"] else "")
192
+
193
+
194
+ def _cell(s) -> str:
195
+ return str(s).replace("|", "\\|").replace("\n", " ")
196
+
197
+
198
+ _MD_SPECIAL = re.compile(r"([\\`*_\[\]|~])")
199
+ _MD_LEADING = re.compile(r"^(?:[#+=-]|\d+[.)])")
200
+
201
+
202
+ def _md(s, lead: bool = False) -> str:
203
+ """User text (coverage.yaml, CITATION.cff, the registry) as inert Markdown: one line; `&`, `<` and `>`
204
+ as entities, so no raw HTML reaches a renderer; the inline markup characters backslash-escaped, so no
205
+ emphasis, code span or link is made from data; with lead (text that starts a line) a leading block
206
+ marker escaped too (no heading, no list)."""
207
+ s = _MD_SPECIAL.sub(r"\\\1", str(s).replace("\n", " "))
208
+ s = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
209
+ m = _MD_LEADING.match(s) if lead else None
210
+ return s[:m.end() - 1] + "\\" + s[m.end() - 1:] if m else s
211
+
212
+
213
+ def _code(s) -> str:
214
+ """Text for inside a code span: no backtick, one line, `|` escaped for a table cell."""
215
+ return _cell(str(s).replace("`", "'"))
216
+
217
+
218
+ def _safe(s) -> str | None:
219
+ s = str(s) if s is not None else ""
220
+ return s if s and SAFE_TOKEN.match(s) else None
221
+
222
+
223
+ def _c12(commit) -> str | None:
224
+ return commit[:12] if isinstance(commit, str) and cov.HEX40.match(commit) else None
225
+
226
+
227
+ def _names(items) -> list[str]:
228
+ return [x for x in (_safe(i) for i in items or []) if x]
229
+
230
+
231
+ def _join(names: list[str]) -> str:
232
+ return names[0] if len(names) == 1 else ", ".join(names[:-1]) + " and " + names[-1] if names else ""
233
+
234
+
235
+ def _published_unanchored(ctx: dict) -> bool:
236
+ """An unposted manuscript whose registry record says the paper is published (`update --paper-status
237
+ published`): the paper exists, but no public version of the exact source its numbers refer to is anchored
238
+ (issue 396). The page then never calls it an unposted draft."""
239
+ return ctx["kind"] == "unposted" and _paper_status(ctx["pkg"]) == "published"
240
+
241
+
242
+ def _paper_status(pkg: dict) -> str | None:
243
+ paper = pkg.get("paper")
244
+ status = paper.get("status") if isinstance(paper, dict) else None
245
+ return status if isinstance(status, str) else None
246
+
247
+
248
+ def _manuscript_ref(m: dict, published: bool = False) -> str:
249
+ v = m["version"]
250
+ kind = cov.manuscript_kind(v)
251
+ title = f"*{_md(m['title'])}*"
252
+ if kind == "arxiv":
253
+ ident = v.split(":", 1)[1]
254
+ return f"{title}, [{v}](https://arxiv.org/abs/{ident})"
255
+ if kind == "commit":
256
+ repo = v["repo"].rstrip("/")
257
+ repo = repo[:-4] if repo.endswith(".git") else repo
258
+ return f"{title}, [{_md(repo)} at `{v['commit'][:12]}`]({repo}/tree/{v['commit']}) (file SHA-256 `{v['sha256']}`)"
259
+ if published:
260
+ return f"{title} (published; the exact source the paper numbers refer to is not publicly anchored)"
261
+ return f"{title}, an unposted draft"
262
+
263
+
264
+ # --------------------------------------------------------------------------
265
+ # inputs read at HEAD
266
+
267
+ def _head_text(repo, rel: str) -> str | None:
268
+ raw = core.git_show_bytes(repo, rel)
269
+ return raw.decode("utf-8", errors="replace") if raw is not None else None
270
+
271
+
272
+ def _mathlib_rev(repo) -> str | None:
273
+ text = _head_text(repo, "lake-manifest.json")
274
+ try:
275
+ data = json.loads(text) if text else None
276
+ except ValueError:
277
+ return None
278
+ for p in (data or {}).get("packages") or []:
279
+ if isinstance(p, dict) and str(p.get("name", "")).lower() in ("mathlib", "«mathlib»"):
280
+ rev = str(p.get("rev") or "")
281
+ return rev if re.fullmatch(r"[0-9a-f]{7,40}", rev) else None
282
+ return None
283
+
284
+
285
+ def citation(pkg: dict, repo) -> dict:
286
+ """{authors[], title, version, doi} from CITATION.cff at HEAD; refuses without human authors."""
287
+ import yaml
288
+ name = pkg["name"]
289
+ text = _head_text(repo, "CITATION.cff")
290
+ if text is None:
291
+ raise core.Fail(f"{name}: CITATION.cff is not committed at HEAD; a public page needs one with its "
292
+ f"authors (docs/page.md#citation)")
293
+ try:
294
+ cff = yaml.safe_load(text)
295
+ except yaml.YAMLError as e:
296
+ raise core.Fail(f"{name}: CITATION.cff at HEAD is not valid YAML: {' '.join(str(e).split())}") from e
297
+ if not isinstance(cff, dict):
298
+ raise core.Fail(f"{name}: CITATION.cff at HEAD is not a mapping")
299
+ authors = []
300
+ for a in cff.get("authors") or []:
301
+ if not isinstance(a, dict):
302
+ continue
303
+ given, family, other = (str(a.get(k) or "").strip() for k in ("given-names", "family-names", "name"))
304
+ who = " ".join(x for x in (given, family) if x) or other
305
+ if who:
306
+ authors.append(who)
307
+ if not authors:
308
+ raise core.Fail(f"{name}: CITATION.cff at HEAD has no author with family-names or name: a citation "
309
+ f"needs its human authors")
310
+ title = str(cff.get("title") or "").strip()
311
+ if not title:
312
+ raise core.Fail(f"{name}: CITATION.cff at HEAD has no title")
313
+ doi = str(cff.get("doi") or "").strip() or ((pkg.get("doi") or {}).get("concept") if isinstance(
314
+ pkg.get("doi"), dict) else None)
315
+ version = str(cff.get("version") or "").strip() or None
316
+ return {"authors": authors, "title": title, "version": version, "doi": doi or None}
317
+
318
+
319
+ def license_file(pkg: dict, repo) -> tuple[str, str]:
320
+ """(license_spdx, the license file committed at HEAD); refuses when they disagree or either is absent."""
321
+ from . import index as index_mod
322
+ name, spdx = pkg["name"], pkg.get("license_spdx")
323
+ if not spdx:
324
+ raise core.Fail(f"{name}: license_spdx is unset in the registry (`lean-pkg update {name} --license-spdx ID`)")
325
+ problem = index_mod.license_problem(repo, spdx)
326
+ if problem:
327
+ raise core.Fail(f"{name}: license_spdx {spdx}: {problem.replace(' at the pin', ' in the checkout')}")
328
+ rel = next((n for n in core.LICENSE_NAMES if core.tracked_at(repo, n)), None)
329
+ if rel is None:
330
+ raise core.Fail(f"{name}: the license file is not committed at HEAD")
331
+ return spdx, rel
332
+
333
+
334
+ # --------------------------------------------------------------------------
335
+ # the data every output is rendered from
336
+
337
+ def _evidence_job(rec: dict, repo) -> str | None:
338
+ """The Evidence table's job: a Slurm job (coverage.slurm_job_of) or a GitHub Actions job `gha-<R>-<A>`
339
+ whose `ci` block passes level 1 (ci_github.gha_job_of, the rule that lets it back a compute job), else None.
340
+ Never another job id: those carry host labels (#381)."""
341
+ from . import ci_github
342
+ return cov.slurm_job_of(rec, repo) or ci_github.gha_job_of(rec, repo)
343
+
344
+
345
+ def _evidence(repo, gate: dict) -> tuple[list[dict], dict, dict]:
346
+ """(table rows, gate receipt facts, comparator receipt facts) from receipts committed at HEAD."""
347
+ rows = []
348
+ for rel in cov.tracked_receipts(repo):
349
+ rec, raw = cov.receipt_at_head(repo, rel)
350
+ if rec is None or not _c12(rec.get("commit")):
351
+ continue
352
+ if rec.get("schema") in core.COMPARATOR_SCHEMAS: # /2 is what the runner writes; /1 still validates
353
+ tier = "statement comparison"
354
+ elif "sorry_count" in rec and "axioms" in rec:
355
+ tier = "build"
356
+ else:
357
+ continue
358
+ m = DATE_RE.match(str(rec.get("generated_at") or ""))
359
+ rows.append({"path": rel, "tier": tier, "commit": rec["commit"], "date": m.group(1) if m else None,
360
+ "sha256": core.sha256_bytes(raw), "job": _evidence_job(rec, repo),
361
+ "recorded": rel in (gate.get("receipt"), gate.get("comparator"))})
362
+ lower, _ = cov.receipt_at_head(repo, gate["receipt"]) if gate.get("receipt") else (None, None)
363
+ comp, _ = cov.receipt_at_head(repo, gate["comparator"]) if gate.get("comparator") else (None, None)
364
+ return rows, lower or {}, comp or {}
365
+
366
+
367
+ def _receipt_view(pkg: dict, repo, gate: dict, lower: dict) -> dict:
368
+ """`page --repo DIR` (field report): whether the recorded gate receipt validates at DIR's committed HEAD
369
+ (gate_mod.validate_receipt: bound to HEAD or an evidence-only descendant, as `formalization render --repo`
370
+ decides). {head, receipt, commit, included, binds_head, reason}. Two ways to fail, never confused:
371
+ binds_head False (no receipt, or its commit is not HEAD nor an ancestor HEAD descends from by the binding
372
+ rule, gate_mod.package_descendant): a candidate commit between gate runs, rendered as a preview;
373
+ binds_head True with included False: the receipt binds HEAD but is invalid (axioms, sorry count,
374
+ toolchain, Mathlib, a malformed field): a failed check, never called expected drift."""
375
+ head = core.git_head(repo)
376
+ commit = lower.get("commit") if lower else None
377
+ view = {"head": head, "receipt": gate.get("receipt"), "commit": commit, "included": False,
378
+ "binds_head": False, "reason": None}
379
+ if not gate.get("receipt"):
380
+ view["reason"] = "no gate receipt is recorded in the registry"
381
+ return view
382
+ if not lower:
383
+ view["reason"] = f"the recorded gate receipt {gate['receipt']} is not committed at HEAD (or not JSON)"
384
+ return view
385
+ if head is not None and isinstance(commit, str) and re.fullmatch(r"[0-9a-f]{40}", commit):
386
+ try:
387
+ binds, note, _docs = gate_mod.package_descendant(repo, commit, head, pkg, checker=lower.get("checker"))
388
+ except core.Fail as e:
389
+ binds, note = False, str(e)
390
+ if not binds:
391
+ view["reason"] = (f"the recorded gate receipt {gate['receipt']} binds commit {commit[:12]}, which "
392
+ f"HEAD {head[:12]} is not an evidence-only descendant of ({note})")
393
+ return view
394
+ # the receipt binds HEAD (or its commit is malformed, which is no binding to wait for either): validate it
395
+ view["binds_head"] = True
396
+ try:
397
+ gate_mod.validate_receipt(pkg, repo, lower)
398
+ view["included"] = True
399
+ except core.Fail as e:
400
+ view["reason"] = f"the recorded gate receipt {gate['receipt']} does not validate ({e})"
401
+ return view
402
+
403
+
404
+ def _context(pkg: dict, repo, allow_private: bool, override: dict | None = None) -> dict:
405
+ """override (`page --repo DIR`): the source links and Lean statements are read at the commit the gate
406
+ receipt binds when that receipt validates at DIR's committed HEAD (so a CI checkout renders the
407
+ registered page), else at DIR's committed HEAD, and then no receipt fact is used (field report: a new
408
+ claim was linked at the old bound commit, where its file did not exist)."""
409
+ from . import ledger as ledger_mod
410
+ from . import index as index_mod
411
+ name = pkg["name"]
412
+ doc, claims, warnings = cov.load_checked(pkg, repo, None, allow_private)
413
+ gate = pkg.get("gate") or {}
414
+ ev_rows, lower, comp = _evidence(repo, gate)
415
+ view = _receipt_view(pkg, repo, gate, lower) if override is not None else None
416
+ invalid = view is not None and not view["included"] and view["binds_head"]
417
+ if view is not None and not view["included"]:
418
+ lower, comp = {}, {}
419
+ ev_rows = [{**e, "recorded": False} for e in ev_rows]
420
+ if invalid:
421
+ warnings.append(f"--repo {override.get('path')} at {str(view['head'])[:12]}: receipt facts omitted: "
422
+ f"{view['reason']}; the receipt binds this commit, so this is a failed check, not "
423
+ f"drift between gate runs")
424
+ else:
425
+ warnings.append(f"--repo {override.get('path')} at {str(view['head'])[:12]}: receipt facts omitted: "
426
+ f"{view['reason']}; the source links and Lean statements are read at "
427
+ f"{str(view['head'])[:12]} (the receipts committed there do not bind it)")
428
+ profiles = sites.for_repo(repo)
429
+ backed, _problems = cov.compute_backing(doc, repo, profiles) # load_checked refused any unbacked job
430
+ try:
431
+ https = index_mod.https_repo(pkg.get("repo") or "")
432
+ except core.Fail:
433
+ https = None
434
+ warnings.append(f"registry repo of {name} is not a public https or GitHub URL: the clone command shows "
435
+ f"a placeholder")
436
+ prefix = core.git(repo, "rev-parse", "--show-prefix").stdout.strip().strip("/")
437
+ bound = lower.get("commit") if _c12(lower.get("commit")) else None
438
+ preview = view is not None and not view["included"] and not invalid
439
+ if invalid: # the receipt binds HEAD: read at the commit it names (same build inputs), as without --repo
440
+ anchor = view["commit"] if _c12(view["commit"]) else view["head"]
441
+ else:
442
+ anchor = view["head"] if preview else bound # the commit links and statements are read at
443
+ if view is not None:
444
+ view["anchor_commit"] = anchor
445
+ github = bool(https and https.startswith("https://github.com/"))
446
+ from . import claims as claims_mod
447
+ from . import comparator_config as cc
448
+ configs = [c for c in comp.get("configs") or [] if isinstance(c, dict)] if comp else []
449
+ named = [claims[cid] for r in doc["rows"] for cid in r.get("claims") or [] if cid in claims]
450
+ qualified = cc.qualified_decls(claims_mod._reader(repo, anchor or "HEAD"), named) if configs else set()
451
+ ccommit = str(comp.get("commit") or "") if comp else ""
452
+ smoke = cc.smoke_configs(repo, ccommit if core._HEX40.fullmatch(ccommit) else None, "HEAD") if configs else {}
453
+ return {
454
+ "name": name, "pkg": pkg, "repo": repo, "doc": doc, "claims": claims, "warnings": warnings,
455
+ "led": ledger_mod.ledger_for(pkg, "promote"), "gate": gate, "evidence": ev_rows, "lower": lower,
456
+ "comp": comp, "backed": backed, "sites": profiles, "cite": citation(pkg, repo), "license": license_file(pkg, repo),
457
+ "https": https, "prefix": prefix, "bound": bound, "configs": configs, "qualified": qualified,
458
+ "smoke": smoke,
459
+ "anchor": anchor, "preview": view if preview else None, "invalid": view if invalid else None,
460
+ "repo_view": view,
461
+ "link_base": (f"{https}/blob/{anchor}" + (f"/{prefix}" if prefix else "")) if github and anchor else None,
462
+ "head_base": (f"{https}/blob/HEAD" + (f"/{prefix}" if prefix else "")) if github else None,
463
+ "library": cov.doc_kind(doc) == "library",
464
+ "kind": None if cov.doc_kind(doc) == "library" else cov.manuscript_kind(doc["manuscript"]["version"]),
465
+ }
466
+
467
+
468
+ def _decl_ref(c: dict, cid: str, link_base: str | None) -> str:
469
+ decl = _safe(c.get("decl")) or cid
470
+ path = str(c.get("file") or "")
471
+ if link_base and re.fullmatch(r"[A-Za-z0-9_./«»'-]+\.lean", path) and ".." not in path:
472
+ return f"[`{decl}`]({link_base}/{path})"
473
+ return f"`{_code(decl)}`"
474
+
475
+
476
+ def _row_statuses(r: dict, by_id: dict) -> list[str]:
477
+ return [(by_id.get(cid) or {}).get("status", "not in the ledger") for cid in r.get("claims") or []]
478
+
479
+
480
+ def _status_cells(r: dict, by_id: dict) -> list[str]:
481
+ """Each claim's ledger status for a coverage table, an internal claim marked as such (claims.yaml status
482
+ internal: a step of the formalization, not a result offered for reuse; verified only when the comparator
483
+ judged it, claims ledger)."""
484
+ return [s + (" (internal)" if (by_id.get(cid) or {}).get("claim_status") == "internal" else "")
485
+ for cid, s in zip(r.get("claims") or [], _row_statuses(r, by_id), strict=False)]
486
+
487
+
488
+ def _internal_line(r: dict, by_id: dict) -> list[str]:
489
+ ids = [cid for cid in r.get("claims") or [] if (by_id.get(cid) or {}).get("claim_status") == "internal"]
490
+ if not ids:
491
+ return []
492
+ return [f"**Internal.** {', '.join(f'`{_code(c)}`' for c in ids)}: marked internal in `claims.yaml`, a step of "
493
+ f"the formalization rather than a result offered for reuse. An internal claim counts as verified only "
494
+ f"when the statement comparison judged its declaration, on the same evidence as any other result.", ""]
495
+
496
+
497
+ def _ledger_word(r: dict, statuses: list[str]) -> str:
498
+ if r.get("class") == "outside":
499
+ return "—"
500
+ if statuses and all(s == "verified" for s in statuses):
501
+ return "verified"
502
+ return ", ".join(sorted({s for s in statuses if s != "verified"}))
503
+
504
+
505
+ def _file_ref(ctx: dict, rel: str, target: str) -> str:
506
+ """A link to a file of the package: relative from the README; from a site page (whose directory is the
507
+ caller's choice) the file on GitHub at the default branch, else the name alone."""
508
+ if target == "readme":
509
+ return f"[{rel}]({rel})"
510
+ return f"[{rel}]({ctx['head_base']}/{rel})" if ctx["head_base"] else f"`{rel}`"
511
+
512
+
513
+ def _holes_line(configs: list[dict]) -> str:
514
+ """The definition holes of the comparator receipt, each with the human who judged its body (the
515
+ receipt's signoff copy of lean-pkg-signoff.json, else its deprecated judged_as, ADR-0058 D8):
516
+ comparator compares a hole by name and type only."""
517
+ parts = [_hole_text(c) for c in configs if _names(c.get("definition_names"))]
518
+ return "; ".join(parts) or "none"
519
+
520
+
521
+ def _smoke_line(cfgs: list[dict], smoke: dict) -> str:
522
+ """The theorems of the smoke configurations, each configuration with the reason its smoke mark gives."""
523
+ return "; ".join(", ".join(f"`{_code(t)}`" for t in _names(c.get("theorem_names"))) + f" in `{_code(c['path'])}` "
524
+ f"({_md(smoke[c['path']])})" for c in cfgs)
525
+
526
+
527
+ def _hole_text(c: dict) -> str:
528
+ from .holes import receipt_judged
529
+ holes = _names(c.get("definition_names"))
530
+ judged = receipt_judged(c)
531
+ who = str(judged.get("reviewer") or "").strip()
532
+ date = str(judged.get("date") or "")
533
+ by = (f" (bodies judged by {_md(who)}" + (f" on {date}" if re.fullmatch(r"\d{4}-\d{2}-\d{2}", date) else "")
534
+ + ")") if who else " (no sign-off reviewer recorded)"
535
+ return ", ".join(f"`{d}`" for d in holes) + by
536
+
537
+
538
+ # --------------------------------------------------------------------------
539
+ # the Lean statement of a claim: what the reader compares with the paper
540
+
541
+ def _fence(text: str) -> bool:
542
+ """True when `text` can sit inside a fenced code block unchanged (no line opens or closes a fence)."""
543
+ return not any(x.lstrip().startswith(("```", "~~~")) for x in text.splitlines())
544
+
545
+
546
+ def _lean_statement(ctx: dict, cid: str) -> dict:
547
+ """{decl, file, source ('challenge' | 'declaration'), text or None, config or None} for one claim.
548
+ When the recorded comparator receipt compares the claim, the statement is the one in that
549
+ configuration's Challenge module (what the proof was checked against); otherwise the declaration in
550
+ the claim's own file. Read at the gate-bound commit (HEAD when there is none; under `--repo` DIR's
551
+ committed HEAD when the gate receipt does not validate there)."""
552
+ from . import comparator_config as cc
553
+ from . import lean_scan
554
+ from .formalization import module_path
555
+ c = ctx["claims"][cid]
556
+ decl = str(c.get("decl") or "")
557
+ rev = ctx["anchor"] or "HEAD"
558
+
559
+ def read(rel: str | None) -> str | None:
560
+ raw = core.git_show_bytes(ctx["repo"], rel, rev) if rel else None
561
+ return raw.decode("utf-8", errors="replace") if raw is not None else None
562
+
563
+ for cfg in ctx["configs"]:
564
+ if cfg.get("path") in ctx.get("smoke", {}): # a smoke check states no result
565
+ continue
566
+ for t in cfg.get("theorem_names") or []:
567
+ if isinstance(t, str) and cc.claim_covered({t}, c, ctx["qualified"],
568
+ cc.mapped_names(list(ctx["claims"].values()))):
569
+ rel = module_path(cfg.get("challenge_module"))
570
+ src = read(rel)
571
+ text = lean_scan.statement(src, t) if src else None
572
+ line = None
573
+ if src is not None and text is None:
574
+ # an umbrella Challenge: the theorem is declared in a module it imports, in the package
575
+ found = _challenge_index(ctx, str(cfg.get("challenge_module")).strip(), read).statement(t)
576
+ if found["text"] is not None and found["file"] != rel:
577
+ rel, line, text = found["file"], found["line"], found["text"]
578
+ return {"decl": t, "file": rel, "line": line, "source": "challenge", "config": cfg,
579
+ "found": src is not None, "text": text if text and _fence(text) else None}
580
+ rel = str(c.get("file") or "") or None
581
+ src = read(rel)
582
+ text = lean_scan.statement(src, decl) if src else None
583
+ return {"decl": decl, "file": rel, "line": None, "source": "declaration", "config": None,
584
+ "found": src is not None, "text": text if text and _fence(text) else None}
585
+
586
+
587
+ def _challenge_index(ctx: dict, module: str, read):
588
+ """The declarations of a Challenge module's import closure within the package, at the gate-bound commit;
589
+ read once per module for the whole page (the closure can hold large files)."""
590
+ from . import lean_scan
591
+ cache = ctx.setdefault("challenge_index", {})
592
+ if module not in cache:
593
+ cache[module] = lean_scan.DeclarationIndex(read, module)
594
+ return cache[module]
595
+
596
+
597
+ def _compared(ctx: dict, st: dict) -> bool:
598
+ """True when a passing configuration of the recorded comparator receipt, at the gate-bound commit,
599
+ judged this statement. A claim the comparator is not required to check (an experimental claim, or a
600
+ reusable definition) can be verified without it; the page then does not say that its statement was compared.
601
+ An internal claim is verified only when the comparator judged it (claims ledger)."""
602
+ comp, cfg = ctx["comp"], st.get("config")
603
+ return bool(st["source"] == "challenge" and cfg and cfg.get("result") == "pass" and comp
604
+ and comp.get("result") == "pass" and ctx["bound"] and comp.get("commit") == ctx["bound"])
605
+
606
+
607
+ def _row_compared(ctx: dict, sts: list[dict]) -> bool:
608
+ return bool(sts) and all(_compared(ctx, st) for st in sts)
609
+
610
+
611
+ # the one ledger reason that means "built, only the statement comparison is missing" (issue 398): every gate
612
+ # diagnostic is package-wide and lands on every claim, so a claim whose only diagnostic is this one has a
613
+ # passing, commit-bound gate and comparator receipt, and no comparator configuration names its declaration
614
+ UNCOMPARED_CODES = frozenset({"no-comparator-config"})
615
+
616
+
617
+ def _only_uncompared(r: dict, by_id: dict) -> bool:
618
+ """True when the row is not verified and every claim of it that is not verified is open solely because no
619
+ statement comparison names it (issue 398: display only, the ledger's status stays open). A claim not in the
620
+ ledger, blocked, unknown, failed, conditional or out of scope, or open for any other reason, keeps the
621
+ default wording."""
622
+ pending = [by_id.get(cid) for cid in r.get("claims") or []]
623
+ pending = [x for x in pending if not x or x.get("status") != "verified"]
624
+ return bool(pending) and all(
625
+ x and x.get("status") == "open" and x.get("diagnostics")
626
+ and all(d.get("code") in UNCOMPARED_CODES for d in x["diagnostics"]) for x in pending)
627
+
628
+
629
+ def _status_line(word: str, compared: bool, conditional: str | None = None, uncompared: bool = False) -> str:
630
+ if word == "conditional" and conditional: # proposal 0003: never the word verified alone
631
+ checks = ("every check of this result passed (the build, and the statement comparison)" if compared else
632
+ "every check that applies to this result passed (the build; its statement was not compared by "
633
+ "a second checker)")
634
+ return (f"**Conditional.** {conditional} Lean accepts the proof under these assumptions, and lean-pkg's "
635
+ f"record shows {checks}.")
636
+ if word == "verified" and compared:
637
+ return ("**Verified.** Lean accepts the proof, and lean-pkg's record shows every check of this result "
638
+ "passed (the build, and the statement comparison).")
639
+ if word == "verified":
640
+ return ("**Verified.** Lean accepts the proof, and lean-pkg's record shows every check that applies to "
641
+ "this result passed (the build; its statement was not compared by a second checker).")
642
+ if word == "open" and uncompared:
643
+ return ("**Built, not compared.** Lean accepts the proof (the build passed), but its statement has not "
644
+ "yet been compared by a second checker, which this result requires.")
645
+ return (f"**Not yet verified.** lean-pkg's record of the checks says: {_md(word or 'nothing recorded')}. "
646
+ f"Until it says verified, read the Lean statement below as work in progress.")
647
+
648
+
649
+ def _lean_block(ctx: dict, st: dict) -> list[str]:
650
+ name = _safe(st["decl"]) or st["decl"]
651
+ rel = st["file"] or ""
652
+ line = st.get("line")
653
+ where = (f"[{rel}]({ctx['link_base']}/{rel}" + (f"#L{line}" if line else "") + ")"
654
+ if ctx["link_base"] and re.fullmatch(r"[A-Za-z0-9_./«»'-]+\.lean", rel) and ".." not in rel
655
+ else f"`{_code(rel)}`" + (f" (line {line})" if line else "")) if rel else "its file"
656
+ if st["source"] == "challenge":
657
+ head = (f"**In Lean.** `{_code(name)}` in {where}: the statement the proof was checked against "
658
+ f"(the proof is in a separate file, and a second checker confirmed it proves exactly this).")
659
+ else:
660
+ head = f"**In Lean.** `{_code(name)}` in {where}."
661
+ if st["text"] is None and not st["found"]:
662
+ at = "the commit this page reads" if ctx["preview"] or ctx["invalid"] else "the checked commit"
663
+ return [head + f" The file is not committed at {at}, so its statement is not shown here.", ""]
664
+ if st["text"] is None:
665
+ return [head + " Its statement could not be read reliably from the source; open the file to read it.",
666
+ ""]
667
+ return [head, "", "```lean", st["text"], "```", ""]
668
+
669
+
670
+ def _depends_lines(ctx: dict, sts: list[dict]) -> list[str]:
671
+ out = []
672
+ holes = [_hole_text(s["config"]) for s in sts if s["config"] and _names(s["config"].get("definition_names"))]
673
+ for h in dict.fromkeys(holes):
674
+ out.append(f"**Definitions checked by a person.** {h}. The comparison checks a definition by its name "
675
+ f"and type only, not by what it computes: the named person read the definitions.")
676
+ axioms = _names(ctx["lower"].get("axioms")) if ctx["lower"] else []
677
+ if ctx["lower"]:
678
+ out.append("**Axioms.** At most " + (", ".join(f"`{a}`" for a in axioms) if axioms else "none")
679
+ + " (what the build check records for the whole package).")
680
+ return [x for line in out for x in (line, "")]
681
+
682
+
683
+ def _hyp_modules(ctx: dict) -> dict[str, str]:
684
+ """{hypothesis constant: its module}, from the binders of the hyp-probe/1 facts in the gate receipt's sealed
685
+ log (proposal 0003), read once per page; {} when there is no readable section."""
686
+ if "hyp_modules" not in ctx:
687
+ from . import hypotheses as hyp
688
+ mods: dict[str, str] = {}
689
+ rel = ctx["gate"].get("receipt")
690
+ text = gate_mod.sealed_log_text(ctx["repo"], ctx["lower"], rel) if ctx["lower"] and rel else None
691
+ fx = hyp.facts(text)
692
+ if fx.get("ok"):
693
+ objs = list(fx["decls"].values()) + [o for os in fx["challenge"].values() for o in os]
694
+ for o in objs:
695
+ for b in o["binders"]:
696
+ mods.setdefault(b["head"], b["module"])
697
+ ctx["hyp_modules"] = mods
698
+ return ctx["hyp_modules"]
699
+
700
+
701
+ def _statements(ctx: dict) -> str | None:
702
+ """The statements module the claims file declares at the commit the page reads (#369), read once; None
703
+ when none is declared."""
704
+ if "statements" not in ctx:
705
+ from . import statements_module as stm
706
+ rel = ctx["pkg"].get("claims_file") or "claims.yaml"
707
+ ctx["statements"] = stm.at_commit(ctx["repo"], rel, ctx["anchor"] or "HEAD")[0]
708
+ return ctx["statements"]
709
+
710
+
711
+ def _module_link(ctx: dict, rel: str | None, line: int | None = None) -> str | None:
712
+ """The source link of a package file at the commit the page reads, when the page can form one."""
713
+ if not (ctx["link_base"] and rel and re.fullmatch(r"[A-Za-z0-9_./«»'-]+\.lean", rel) and ".." not in rel):
714
+ return None
715
+ return f"{ctx['link_base']}/{rel}" + (f"#L{line}" if line else "")
716
+
717
+
718
+ def _statements_line(ctx: dict) -> list[str]:
719
+ """The paragraph naming the declared statements module (#369); [] when none is declared."""
720
+ from . import lean_scan
721
+ mod = _statements(ctx)
722
+ safe = _safe(mod) if mod else None
723
+ if safe is None:
724
+ return []
725
+ rel = lean_scan.module_file(safe)
726
+ url = _module_link(ctx, rel)
727
+ ref = f"[`{safe}`]({url})" if url else f"`{safe}`"
728
+ return [f"**Assumptions module.** The assumptions the results below name are Lean definitions in {ref}, the "
729
+ f"one module beyond Mathlib that the Lean statements may use. It is part of the statement: read what "
730
+ f"each assumption says, because an assumption that is trivially true or false changes what a result "
731
+ f"means.", ""]
732
+
733
+
734
+ def _hyp_ref(ctx: dict, name: str) -> str | None:
735
+ """A hypothesis as a code span, linked to its declaration's source at the commit the page reads when the
736
+ page can form the link (its module's file is in the package and declares it); None when the name is not
737
+ a safe token (the caller counts it, never drops it)."""
738
+ from . import lean_scan
739
+ safe = _safe(name)
740
+ if safe is None:
741
+ return None
742
+ rel = lean_scan.module_file(_hyp_modules(ctx).get(safe) or _statements(ctx) or "")
743
+ if _module_link(ctx, rel) is None:
744
+ return f"`{safe}`"
745
+ raw = core.git_show_bytes(ctx["repo"], rel, ctx["anchor"] or "HEAD")
746
+ line = next((d[0] for d in lean_scan.declarations(raw.decode("utf-8", "replace")) if d[2] == safe),
747
+ None) if raw is not None else None
748
+ return f"[`{safe}`]({ctx['link_base']}/{rel}#L{line})" if line else f"`{safe}`"
749
+
750
+
751
+ def _refs(ctx: dict, items: list[tuple[str, str]]) -> str:
752
+ """'ref (detail), ...' for [(hypothesis, detail)]; names that are not safe tokens are counted."""
753
+ shown = [(ref, d) for ref, d in ((_hyp_ref(ctx, h), d) for h, d in items) if ref is not None]
754
+ hidden = len(items) - len(shown)
755
+ return ", ".join([ref + (f" ({d})" if d else "") for ref, d in shown]
756
+ + ([f"{hidden} more not shown here (see the claims ledger)"] if hidden else []))
757
+
758
+
759
+ def _conditional_text(ctx: dict, r: dict, by_id: dict) -> str | None:
760
+ """Proposal 0003: the assumptions of a row whose claims are verified or conditional, from the ledger rows:
761
+ "Verified under assumptions `A`, `B`. Discharged: `A` (proved by P; corollary C, compared at X). Outstanding:
762
+ `B` (its coverage text)." or, with nothing outstanding, "Verified (all assumptions discharged: ...)". None
763
+ when no claim of the row has a hypothesis."""
764
+ hyps: dict[str, dict] = {}
765
+ for cid in r.get("claims") or []:
766
+ row = by_id.get(cid) or {}
767
+ if row.get("status") != "conditional":
768
+ continue
769
+ for h in row.get("hypotheses") or []:
770
+ old = hyps.get(h["decl"])
771
+ if old is None or (old["state"] != "open" and h["state"] == "open"):
772
+ hyps[h["decl"]] = h # outstanding anywhere in the row: outstanding
773
+ if not hyps:
774
+ return None
775
+ texts = {x.get("hypothesis"): x.get("text") for x in r.get("inputs") or [] if isinstance(x, dict)}
776
+ at = _c12(ctx["bound"])
777
+ done = [(d, f"proved by `{_code(h['by']['proof'])}`; corollary `{_code(h['by']['corollary'])}`"
778
+ + (f", compared at `{at}`" if at else ""))
779
+ for d, h in hyps.items() if h["state"] == "discharged"]
780
+ left = [(d, "; ".join(x for x in (_md(texts[d]) if texts.get(d) else "",
781
+ f"inherited from `{_code(h['via'])}`" if h.get("via") else "") if x))
782
+ for d, h in hyps.items() if h["state"] == "open"]
783
+ if not left:
784
+ return f"Verified (all assumptions discharged: {_refs(ctx, done)})."
785
+ out = f"Verified under assumptions {_refs(ctx, [(d, '') for d in hyps])}."
786
+ if done:
787
+ out += f" Discharged: {_refs(ctx, done)}."
788
+ return out + f" Outstanding: {_refs(ctx, left)}."
789
+
790
+
791
+ def _result_block(ctx: dict, r: dict, by_id: dict, heading: str, statement: str | None,
792
+ hypotheses: str | None) -> tuple[list[str], str, bool]:
793
+ word = _ledger_word(r, _row_statuses(r, by_id))
794
+ sts = [_lean_statement(ctx, cid) for cid in r.get("claims") or []]
795
+ compared = _row_compared(ctx, sts)
796
+ cond = _conditional_text(ctx, r, by_id) if word == "conditional" else None
797
+ md = [f"### {heading}", "", _status_line(word, compared, cond, _only_uncompared(r, by_id)), "", *_internal_line(r, by_id)]
798
+ if not ctx["library"]:
799
+ md += ["**In the paper.**" + ("" if statement else " The statement is not quoted here; read it in the "
800
+ "paper."), ""]
801
+ if statement:
802
+ md += ["```latex", statement.rstrip(), "```", ""]
803
+ elif statement:
804
+ md += ["**In words.**", "", "```latex", statement.rstrip(), "```", ""]
805
+ for st in sts:
806
+ md += _lean_block(ctx, st)
807
+ if hypotheses:
808
+ md += [hypotheses, ""]
809
+ md += _depends_lines(ctx, sts)
810
+ if r.get("note"):
811
+ md += [f"**Note.** {_md(r['note'])}", ""]
812
+ return md, word, compared
813
+
814
+
815
+ def _input_md(x) -> str:
816
+ """One coverage input: a string as before; a {hypothesis, text} entry (proposal 0003) as its text and the
817
+ assumption's Lean name."""
818
+ if isinstance(x, dict):
819
+ return f"{_md(x.get('text'))} (`{_code(x.get('hypothesis'))}`)"
820
+ return _md(x)
821
+
822
+
823
+ def _hypotheses(r: dict) -> str:
824
+ if r["class"] == "same-assumptions":
825
+ return "**Hypotheses.** The paper's own: the Lean statement assumes nothing the paper does not."
826
+ return ("**Hypotheses.** The paper's, plus these, which the Lean statement assumes and the paper proves or "
827
+ "assumes elsewhere: " + "; ".join(_input_md(x) for x in r["inputs"]) + ".")
828
+
829
+
830
+ TRUST_LINE = ("**How to read this page.** Lean has checked every step of the proofs listed here. It cannot check "
831
+ "that a Lean statement says what the paper says: that comparison is yours. For each result below, "
832
+ "read the paper's statement beside the Lean statement, and check that the hypotheses match.")
833
+ LIBRARY_TRUST_LINE = ("**How to read this page.** Lean has checked every step of the proofs listed here. Each "
834
+ "result is exactly its Lean statement: read the statements below to see what is proved. The "
835
+ "titles, the words and the notes are the authors' description, which Lean does not check.")
836
+
837
+
838
+ def _body(ctx: dict, target: str) -> tuple[list[str], dict]:
839
+ """Every section, mathematics first, and the facts. target: 'readme' (the README block), 'site'
840
+ (verification.md beside coverage.md) or 'html' (one page holding both)."""
841
+ doc, led = ctx["doc"], ctx["led"]
842
+ by_id = {r["id"]: r for r in led["claims"]}
843
+ keyed = "conditional" in led["counts"] # proposal 0003: a claim uses hypotheses
844
+ trust = LIBRARY_TRUST_LINE if ctx["library"] else TRUST_LINE
845
+ md: list[str] = ["## Verification at a glance", "",
846
+ trust + (f" {CONDITIONAL_SENTENCE}" if keyed and led["counts"]["conditional"] else ""), ""]
847
+ md += _statements_line(ctx)
848
+ if ctx["preview"]:
849
+ pv = ctx["preview"]
850
+ binds = (f"the recorded build check binds commit `{_c12(pv['commit'])}`" if _c12(pv.get("commit"))
851
+ else "no recorded build check is committed here")
852
+ md += [f"> **Preview of commit `{_c12(pv['head'])}`.** The links to the Lean files and the Lean "
853
+ f"statements below are read at `{_c12(pv['head'])}`. No check binds this commit yet ({binds}), "
854
+ f"so no result below is verified and no check is reported for it.", ""]
855
+ if ctx["invalid"]:
856
+ iv = ctx["invalid"]
857
+ md += [f"> **The recorded build check does not validate.** The recorded receipt "
858
+ f"`{_code(str(iv['receipt']))}` binds this commit, but it does not validate: {_md(str(iv['reason']))}. "
859
+ f"No result below is verified and no check is reported for it.", ""]
860
+ if _published_unanchored(ctx):
861
+ md += ["> **Published; source not publicly anchored.** The paper is published, but no public version of "
862
+ "the exact source the paper numbers below refer to is anchored, so a reader cannot check them "
863
+ "against a posted version. To anchor one, pin an arXiv version (`lean-pkg formalization anchor`) "
864
+ "or set `manuscript.version` in coverage.yaml to a public source {repo, commit, sha256}.", ""]
865
+ elif ctx["kind"] == "unposted":
866
+ md += ["> **Manuscript not yet posted.** The paper numbers below refer to an unposted draft; a reader "
867
+ "cannot check them until a version is posted.", ""]
868
+ md += [_md(doc["summary"], lead=True), ""]
869
+ blocks, words, n_compared = [], [], 0
870
+ for r in doc["rows"]:
871
+ if ctx["library"]:
872
+ b, w, c = _result_block(ctx, r, by_id, _md(r["title"], lead=True), r.get("statement"), None)
873
+ elif r["class"] == "outside":
874
+ continue
875
+ else:
876
+ p = r["paper"]
877
+ b, w, c = _result_block(ctx, r, by_id, f"{_md(p['number'], lead=True)}: {_md(p['title'])}",
878
+ p.get("statement"), _hypotheses(r))
879
+ blocks += b
880
+ words.append(w)
881
+ n_compared += w == "verified" and c
882
+ n_verified = sum(w == "verified" for w in words)
883
+ n_cond = sum(w == "conditional" for w in words)
884
+ cond = f"; conditional (proved under the assumptions each names): {n_cond}" if n_cond else ""
885
+ # "verified" is the ledger's word: a claim that is not reusable needs no comparator, so say how many of
886
+ # the verified results also had their statement compared whenever that is not all of them
887
+ also = (f" (for {n_compared} of them a second checker also compared the statement)"
888
+ if n_compared < n_verified else "")
889
+ if target != "readme":
890
+ blocks += [f"Every result with each of its claims, in one table: [Coverage]"
891
+ f"({'coverage.md' if target == 'site' else '#coverage'}).", ""]
892
+ if ctx["library"]:
893
+ counts = None
894
+ n = len(doc["rows"])
895
+ md += [f"- Main results: {n}; verified: {n_verified} of {n}{also}{cond}.", ""]
896
+ md += ["## Main results", "", *blocks]
897
+ else:
898
+ counts = {c: sum(r["class"] == c for r in doc["rows"]) for c in cov.CLASSES}
899
+ formal = len(doc["rows"]) - counts["outside"]
900
+ md += [f"- Paper: {_manuscript_ref(doc['manuscript'], _published_unanchored(ctx))}.",
901
+ f"- Results listed: {len(doc['rows'])}. In Lean with the paper's own hypotheses: "
902
+ f"{counts['same-assumptions']}; in Lean with extra hypotheses, named below: "
903
+ f"{counts['inputs-supplied']}; not formalized: {counts['outside']}.",
904
+ f"- Verified: {n_verified} of the {formal} result(s) in Lean{also}{cond}.", ""]
905
+ md += ["## The paper's results in Lean", "", *blocks]
906
+ md += ["## Not formalized", ""]
907
+ outside = [r for r in doc["rows"] if r["class"] == "outside"]
908
+ if outside:
909
+ md += [f"- {_md(r['paper']['number'])} ({_md(r['paper']['title'])})"
910
+ + (f": {_md(r['note'])}" if r.get("note") else "") for r in outside]
911
+ else:
912
+ md.append(f"Nothing in the manuscript is excluded: {_md(doc['nothing_excluded']['reason'])}")
913
+ md.append("")
914
+ return _body_rest(ctx, target, md, counts, n_verified, n_cond if keyed else None)
915
+
916
+
917
+ def _claim_axioms_lines(value) -> list[str]:
918
+ """One bullet for the receipt's additive `claim_axioms` key (AX1), when present: the axioms of every claim
919
+ were read from the built environment, not only from the `#print axioms` output. Nothing without the key."""
920
+ if not isinstance(value, dict) or not isinstance(value.get("checked"), int):
921
+ return []
922
+ extra = sorted({a for e in value.get("nonstandard") or [] if isinstance(e, dict)
923
+ for a in e.get("axioms") or [] if isinstance(a, str)})
924
+ return [f"- Axioms of every claim: read from the built environment (Lean's `collectAxioms`) for all "
925
+ f"{value['checked']} claim(s) in `claims.yaml`, not only the theorems the build prints; "
926
+ + (f"beyond the standard three, the allowed {', '.join(f'`{_code(a)}`' for a in extra)}."
927
+ if extra else "none uses an axiom beyond `propext`, `Quot.sound` and `Classical.choice`.")]
928
+
929
+
930
+ def _container_clause(value) -> str:
931
+ """`; run in a container (Apptainer), SIF SHA-256 `<hex>`` for a well-formed `container` receipt key (#236),
932
+ else nothing. Only the engine and the digest are copied: never the image ref, which is a path."""
933
+ from . import container as ctr
934
+ if value is None or ctr.problems(value):
935
+ return ""
936
+ kind, digest = ctr.digest_of(value)
937
+ return f"; run in a container ({ctr.LABELS[value['engine']]}), {kind} `{digest}`"
938
+
939
+
940
+ ADVISORIES_URL = "https://github.com/lean-pkg/lean-pkg/blob/main/src/lean_pkg/data/toolchain-advisories.yaml"
941
+
942
+
943
+ ADVISORY_PREFIX = "- Toolchain advisory: "
944
+
945
+
946
+ def _advisory_lines(toolchain, warnings: list[str], ctx: dict | None = None) -> list[str]:
947
+ """One factual line per toolchain advisory (#237) the build check's toolchain is affected by, linked
948
+ to the upstream release notes; each also becomes a page warning for the author. The matches are kept
949
+ in ctx["toolchain_advisories"]; with ctx["advisories"] False (the staleness baseline) no line is made."""
950
+ from . import toolchain_advisories as ta
951
+ tc = _safe(str(toolchain or "").strip())
952
+ found, _problem = ta.lookup(tc)
953
+ if ctx is not None:
954
+ ctx["toolchain_advisories"] = found
955
+ if not ctx.get("advisories", True):
956
+ return []
957
+ out = []
958
+ for v in found:
959
+ out.append(f"{ADVISORY_PREFIX}the build check ran on Lean `{tc}`, which has a known soundness bug "
960
+ f"fixed in `{v['fixed_in']}` ([{v['id']}]({v['links'][0]}); lean-pkg's "
961
+ f"[toolchain advisories]({ADVISORIES_URL})).")
962
+ warnings.append(f"toolchain advisory {v['id']}: the build check ran on {tc}; fixed in {v['fixed_in']}")
963
+ return out
964
+
965
+
966
+ def _stack_lines(doc: dict, repo, warnings: list[str]) -> list[str]:
967
+ """The LTS stack line (proposal 0004): only when coverage.yaml declares a stack this lean-pkg declares and
968
+ the committed lean-toolchain and Mathlib commit match it; otherwise a warning and no line."""
969
+ name = doc.get("stack")
970
+ if not isinstance(name, str):
971
+ return []
972
+ from . import stacks
973
+ res = stacks.check(repo, name)
974
+ warnings += res["warnings"]
975
+ if not (res["declared"] and res["matches"]):
976
+ return []
977
+ return [f"- Built on lean-pkg stack [{name}]({stacks.page_url(name)}) (Lean "
978
+ f"`{stacks.toolchain_version(stacks.declared()[name])}`, Mathlib "
979
+ f"`{stacks.declared()[name]['mathlib']['rev']}`), supported until {res['supported_until']}."]
980
+
981
+
982
+ def _body_rest(ctx: dict, target: str, md: list[str], counts: dict | None, n_verified: int,
983
+ n_conditional: int | None = None) -> tuple[list[str], dict]:
984
+ """What the checks establish, How this was checked, and the citation, license and acknowledgments."""
985
+ name, pkg, repo, doc = (ctx[k] for k in ("name", "pkg", "repo", "doc"))
986
+ lower, comp, gate, cite, led = ctx["lower"], ctx["comp"], ctx["gate"], ctx["cite"], ctx["led"]
987
+ https, prefix, bound, kind = ctx["https"], ctx["prefix"], ctx["bound"], ctx["kind"]
988
+ pstatus = led["package_status"]
989
+ configs = ctx["configs"]
990
+ warnings: list[str] = []
991
+ allowed = _names(gate.get("axioms_allowed") or core.DEFAULT_AXIOMS)
992
+ # what the checks establish, in plain words
993
+ md += ["## What the checks establish", ""]
994
+ if lower:
995
+ axioms = _names(lower.get("axioms"))
996
+ sc = lower.get("sorry_count")
997
+ sorry = ("no `sorry` (an unfinished proof) remains" if sc == 0 else
998
+ f"the `sorry` count is {sc}" if isinstance(sc, int) else "the `sorry` count is not recorded")
999
+ md.append(f"- **Every proof is checked by Lean.** The package builds; {sorry}; the only axioms used are "
1000
+ f"{', '.join(f'`{a}`' for a in axioms) or 'none'} (allowed: "
1001
+ f"{', '.join(f'`{a}`' for a in allowed)}).")
1002
+ else:
1003
+ md.append("- **No build check is recorded yet**: nothing on this page is backed by one.")
1004
+ warnings.append("the recorded gate receipt is not committed at HEAD (or none is recorded)")
1005
+ smoke = ctx.get("smoke") or {}
1006
+ smoke_cfgs = [c for c in configs if c.get("path") in smoke]
1007
+ if comp and len(smoke_cfgs) < len(configs):
1008
+ thms = sum(len(c.get("theorem_names") or []) for c in configs if c.get("path") not in smoke)
1009
+ md.append(f"- **The statements shown are the ones proved.** For {thms} statement(s), a second checker "
1010
+ f"(comparator) confirmed that the proof proves exactly the statement shown, with only the "
1011
+ f"permitted axioms, and independent Lean kernels replayed the proof.")
1012
+ else:
1013
+ md.append("- **No statement comparison is recorded yet**: no Lean statement here has been compared "
1014
+ "with its proof by a second checker.")
1015
+ if ctx["library"]:
1016
+ md.append("- **Not checked by any tool:** that a title or note describes its Lean statement. A "
1017
+ "definition listed under *Definitions checked by a person* is compared by name and type only.")
1018
+ else:
1019
+ md.append("- **Not checked by any tool:** that a Lean statement says what the paper says. That is the "
1020
+ "comparison this page asks you to make. A definition listed under *Definitions checked by a "
1021
+ "person* is compared by name and type only.")
1022
+ md += ["", "The full account of what each check covers and what it takes on trust is lean-pkg's "
1023
+ "[trust model](https://github.com/lean-pkg/lean-pkg/blob/main/docs/trust-model.md).", ""]
1024
+ # how this was checked: the receipts, last
1025
+ md += ["## How this was checked", ""]
1026
+ req = led["required"]
1027
+ n_req_ok = sum(1 for r in led["claims"] if r["required"] and r["status"] == "verified")
1028
+ cond = _conditional_ready(led)
1029
+ if cond: # proposal 0003: a ready ledger with conditional claims never reads as unconditional
1030
+ k, hyps = cond
1031
+ md.append(f"- lean-pkg's claims ledger: **{pstatus}**, every required claim is verified or conditional "
1032
+ f"(proved under its stated hypotheses) by the recorded receipts; {n_req_ok} of {req} required "
1033
+ f"claim(s) verified, {k} conditional (outstanding hypotheses: {_hyp_list(hyps)}) "
1034
+ f"(`{led['ledger_digest'][:23]}…`). {CONDITIONAL_SENTENCE}")
1035
+ else:
1036
+ md.append(f"- lean-pkg's claims ledger: **{pstatus}**, {LEDGER_WORDS.get(pstatus, _md(pstatus))}; "
1037
+ f"{n_req_ok} of {req} required claim(s) verified (`{led['ledger_digest'][:23]}…`).")
1038
+ if lower:
1039
+ sc = lower.get("sorry_count")
1040
+ md.append(f"- Build check (`lean-pkg gate`) at commit `{_c12(lower.get('commit'))}`: `sorry` count "
1041
+ f"{sc if isinstance(sc, int) else '(not recorded)'}; axioms used: "
1042
+ f"{', '.join(f'`{a}`' for a in _names(lower.get('axioms'))) or 'none'}"
1043
+ f"{_container_clause(lower.get('container'))}.")
1044
+ md += _claim_axioms_lines(lower.get("claim_axioms"))
1045
+ md += _advisory_lines(lower.get("lean_toolchain"), warnings, ctx)
1046
+ if comp and configs:
1047
+ thms = sum(len(c.get("theorem_names") or []) for c in configs)
1048
+ permitted = sorted({a for c in configs for a in _names(c.get("permitted_axioms"))})
1049
+ md.append(f"- Statement comparison (comparator) at commit `{_c12(comp.get('commit'))}`: "
1050
+ f"{len(configs)} configuration(s), {thms} theorem(s) compared (each Challenge statement "
1051
+ f"against its Solution proof); permitted axioms: "
1052
+ f"{', '.join(f'`{a}`' for a in permitted) or 'none'}; definitions compared by name only: "
1053
+ f"{_holes_line(configs)}.")
1054
+ if smoke_cfgs:
1055
+ md.append(f"- Smoke checks (not results): {_smoke_line(smoke_cfgs, smoke)}. Each passed the comparison "
1056
+ f"like the others, to show the comparator set-up works; it states nothing of this package "
1057
+ f"and verifies no result on this page.")
1058
+ md += _stack_lines(doc, repo, warnings)
1059
+ md.append("")
1060
+ ev_rows = ctx["evidence"]
1061
+ md += ["### Receipts", ""]
1062
+ if ev_rows:
1063
+ md += ["| Receipt | Check | Commit | Date | Job | SHA-256 |", "|---|---|---|---|---|---|"]
1064
+ for e in ev_rows:
1065
+ md.append(f"| `{_code(e['path'])}`{' (used here)' if e['recorded'] else ''} | {e['tier']} | "
1066
+ f"`{e['commit'][:12]}` | {e['date'] or '—'} | {e['job'] or '—'} | `{e['sha256']}` |")
1067
+ if ctx["preview"]:
1068
+ md += ["", f"None of these receipts binds `{_c12(ctx['anchor'])}`, the commit this page reads: the "
1069
+ f"lines above use none of them. SHA-256 is of the file as committed.", ""]
1070
+ elif ctx["invalid"]:
1071
+ md += ["", "The receipt the lean-pkg registry holds for this package does not validate: the lines "
1072
+ "above use none of these receipts. SHA-256 is of the file as committed.", ""]
1073
+ else:
1074
+ md += ["", "*(used here)*: the receipt the lean-pkg registry holds for this package, which the lines "
1075
+ "above read. SHA-256 is of the file as committed.", ""]
1076
+ else:
1077
+ md += ["No receipt is committed under `.lean-receipts/`.", ""]
1078
+ # reproduce
1079
+ toolchain = _safe((_head_text(repo, "lean-toolchain") or "").strip())
1080
+ rev = _mathlib_rev(repo)
1081
+ md += ["### Reproduce", "",
1082
+ f"- Lean toolchain: `{toolchain or '(lean-toolchain not committed)'}`.",
1083
+ "- Mathlib: " + (f"`{rev}` (lake-manifest.json)." if rev else "not a dependency (lake-manifest.json)."),
1084
+ "", "```bash"]
1085
+ clone = https or "<repository URL>"
1086
+ dirname = (https.rstrip("/").rsplit("/", 1)[-1] if https else "<checkout>")
1087
+ md += [f"git clone {clone}", f"cd {dirname}" + (f"/{prefix}" if prefix else "")]
1088
+ if bound:
1089
+ md.append(f"git checkout {bound} # the commit the build check binds")
1090
+ elif ctx["preview"] and ctx["anchor"]:
1091
+ md.append(f"git checkout {ctx['anchor']} # the commit this page reads; no check binds it yet")
1092
+ elif ctx["invalid"] and ctx["anchor"]:
1093
+ md.append(f"git checkout {ctx['anchor']} # the commit this page reads; its recorded check does not "
1094
+ f"validate")
1095
+ if rev:
1096
+ md.append("lake exe cache get")
1097
+ md += ["lake build", "```", ""]
1098
+ if lower:
1099
+ axioms = _names(lower.get("axioms"))
1100
+ md.append("Expected: `#print axioms` on any declaration above reports a subset of "
1101
+ + ("{" + ", ".join(f"`{a}`" for a in axioms) + "}" if axioms else "no axioms")
1102
+ + " (the union the build check records); `sorryAx` never appears.")
1103
+ md.append("")
1104
+ # citation
1105
+ md += ["## Citation", ""]
1106
+ line = f"{_join([_md(a, lead=not i) for i, a in enumerate(cite['authors'])])}. *{_md(cite['title'])}*."
1107
+ if cite["version"]:
1108
+ line += f" Version {_md(cite['version'])}."
1109
+ if cite["doi"] and re.fullmatch(r"10\.\d{4,9}/[^\s()\[\]<>`]+", cite["doi"]):
1110
+ line += f" [doi:{_md(cite['doi'])}](https://doi.org/{cite['doi']})."
1111
+ formalizes = ("" if ctx["library"] else
1112
+ f"It formalizes results of {_manuscript_ref(doc['manuscript'], _published_unanchored(ctx))}. ")
1113
+ md += [line, "", f"{formalizes}See {_file_ref(ctx, 'CITATION.cff', target)}.", ""]
1114
+ # license
1115
+ spdx, lic_rel = ctx["license"]
1116
+ md += ["## License", "", f"Released under `{_code(spdx)}`; see {_file_ref(ctx, lic_rel, target)}.", ""]
1117
+ # acknowledgments
1118
+ md += ["## Acknowledgments", "", CREDIT]
1119
+ lv = doc.get("lean_pkg_version")
1120
+ if lv:
1121
+ md.append(f"Version used: lean-pkg {lv['version']} ([doi:{lv['doi']}](https://doi.org/{lv['doi']})).")
1122
+ corr = ctx.get("corroborator")
1123
+ site_facts = {n: site_fact(s, ctx["backed"].get(n) or [], corr) for n, s in ctx["sites"].items()}
1124
+ md += [sentence(s, site_facts[n]) for n, s in ctx["sites"].items() if site_facts[n]["sentence"]]
1125
+ facts = {"rows": len(doc["rows"]), "counts": counts, "verified_rows": n_verified,
1126
+ # proposal 0003: only when a claim uses the keys, so every other page's facts are unchanged
1127
+ **({"conditional_rows": n_conditional} if n_conditional is not None else {}),
1128
+ "ledger_status": pstatus, "ledger_digest": led["ledger_digest"],
1129
+ "private_manuscript": kind == "unposted", "manuscript": kind,
1130
+ # issue 396, additive: the record's paper.status, and the note when an unposted manuscript is a
1131
+ # published paper whose exact source is not publicly anchored (else null)
1132
+ "paper_status": _paper_status(ctx["pkg"]),
1133
+ "manuscript_note": "published-unanchored" if _published_unanchored(ctx) else None,
1134
+ "kind": "library" if ctx["library"] else "paper",
1135
+ # the legacy top-level key (`easley` since 0.7, its 0.7 shape) and `sites` for every profile,
1136
+ # the package's own included
1137
+ **{n: {"backed": f["backed"], "jobs": f["jobs"]} for n, f in site_facts.items()
1138
+ if n in LEGACY_SITE_KEYS},
1139
+ "sites": site_facts,
1140
+ "receipts": len(ev_rows),
1141
+ "toolchain_advisories": list(ctx.get("toolchain_advisories") or [])}
1142
+ return md, {"facts": facts, "warnings": warnings}
1143
+
1144
+
1145
+ def site_fact(site, jobs: list[str], corr: Corroborator | None = None) -> dict:
1146
+ """`page --json` sites.<name>: backed, jobs, the corroboration level of each job (`levels`), the lowest
1147
+ (`level`; null when no job is listed) and whether the page carries the site's sentence (backed, and the
1148
+ level at least the scheduler's sentence_level). Under `--corroborate` a GitHub Actions site also carries
1149
+ `corroboration` ({job: rows}) and `runs` (the run links its sentence names)."""
1150
+ sched = sites.scheduler_of(site)
1151
+ asked = corr is not None and sched is sites.GITHUB_ACTIONS and bool(jobs)
1152
+ got = {j: corr.job(j) for j in jobs} if asked else {}
1153
+ levels = {j: got[j]["level"] if asked else OFFLINE_LEVEL for j in jobs}
1154
+ level = min(levels.values()) if levels else None
1155
+ out = {"backed": bool(jobs), "jobs": list(jobs), "level": level, "levels": levels,
1156
+ "sentence": bool(jobs) and level >= sched.sentence_level}
1157
+ if asked:
1158
+ out["corroboration"] = {j: got[j]["rows"] for j in jobs}
1159
+ out["runs"] = [got[j]["link"] for j in jobs if got[j]["link"]] if out["sentence"] else []
1160
+ return out
1161
+
1162
+
1163
+ def sentence(site, fact: dict) -> str:
1164
+ """The site's acknowledgement as the page carries it: `{runs}` filled with the corroborated runs' links."""
1165
+ return site.acknowledgement.replace(sites.RUNS_TOKEN, ", ".join(fact.get("runs") or []))
1166
+
1167
+
1168
+ def corroboration_warnings(facts: dict, attested: bool = False) -> list[str]:
1169
+ """One warning per job `--corroborate` did not bring to level 2, naming why; under `--attested`, one per job
1170
+ that did not reach level 3."""
1171
+ from . import ci_github
1172
+ out = []
1173
+ for name, f in (facts.get("sites") or {}).items():
1174
+ for job, rows in (f.get("corroboration") or {}).items():
1175
+ level = f["levels"].get(job, 0)
1176
+ if attested and level == 2:
1177
+ out.append(f"{name}: {job} is corroborated but not attested (level 2): {ci_github.failures(rows)}")
1178
+ elif attested and level < 2:
1179
+ out.append(f"{name}: {job} is not attested (level {level}): {ci_github.failures(rows)}; the page "
1180
+ f"carries no {name} sentence")
1181
+ elif level < 2:
1182
+ out.append(f"{name}: {job} is not corroborated (level {f['levels'].get(job)}): "
1183
+ f"{ci_github.failures(rows)}; the page carries no {name} sentence")
1184
+ return out
1185
+
1186
+
1187
+ def _coverage_lines(ctx: dict, target: str) -> list[str]:
1188
+ """coverage.md: every row of coverage.yaml, one table line each, with every claim, its declaration and
1189
+ its own ledger status, the inputs and the note (labels stay in coverage.yaml)."""
1190
+ doc, claims, led = ctx["doc"], ctx["claims"], ctx["led"]
1191
+ by_id = {r["id"]: r for r in led["claims"]}
1192
+ md = ["# Coverage", ""]
1193
+ if target == "site":
1194
+ md += [SITE_NOTE.format(name=ctx["name"]), ""]
1195
+ if ctx["library"]:
1196
+ return md + _library_coverage_lines(ctx, target)
1197
+ counts = {c: sum(r["class"] == c for r in doc["rows"]) for c in cov.CLASSES}
1198
+ md += [f"Manuscript: {_manuscript_ref(doc['manuscript'], _published_unanchored(ctx))}.", "",
1199
+ f"- Paper results: {len(doc['rows'])} ({counts['same-assumptions']} same assumptions, "
1200
+ f"{counts['inputs-supplied']} inputs supplied, {counts['outside']} outside this formalization).",
1201
+ f"- lean-pkg's claims ledger: **{led['package_status']}**{_conditional_tag(led)} "
1202
+ f"(`{led['ledger_digest'][:23]}…`).", "",
1203
+ "| Paper | Title | Correspondence | Claims | Lean declarations | Ledger | Inputs | Note |",
1204
+ "|---|---|---|---|---|---|---|---|"]
1205
+ for r in doc["rows"]:
1206
+ ids = list(r.get("claims") or [])
1207
+ md.append(f"| {_md(r['paper']['number'])} | {_md(r['paper']['title'])} | {cov.CLASS_GLOSS[r['class']]} | "
1208
+ f"{'<br>'.join(f'`{_code(c)}`' for c in ids) or '—'} | "
1209
+ f"{'<br>'.join(_decl_ref(claims[c], c, ctx['link_base']) for c in ids) or '—'} | "
1210
+ f"{'<br>'.join(_status_cells(r, by_id)) or '—'} | "
1211
+ f"{'<br>'.join(_input_md(x) for x in r.get('inputs') or []) or '—'} | "
1212
+ f"{_md(r['note']) if r.get('note') else '—'} |")
1213
+ md += ["", "One line per paper result of `coverage.yaml`. *Ledger*: the status `lean-pkg claims ledger` "
1214
+ "gives each claim, in the order of the claims; only *verified* means the "
1215
+ f"recorded receipts close the claim{_conditional_gloss(led)}.", ""]
1216
+ if not any(r["class"] == "outside" for r in doc["rows"]):
1217
+ md += [f"Nothing in the manuscript is excluded: {_md(doc['nothing_excluded']['reason'])}", ""]
1218
+ md.append(f"Back to [Verification]({'verification.md' if target == 'site' else '#verification'}).")
1219
+ return md
1220
+
1221
+
1222
+ def _library_coverage_lines(ctx: dict, target: str) -> list[str]:
1223
+ """coverage.md of a kind: library coverage: every main result with every claim, its declaration and its
1224
+ own ledger status, and the note."""
1225
+ doc, claims, led = ctx["doc"], ctx["claims"], ctx["led"]
1226
+ by_id = {r["id"]: r for r in led["claims"]}
1227
+ md = ["Library: each row is a main result of the library.", "",
1228
+ f"- Main results: {len(doc['rows'])}.",
1229
+ f"- lean-pkg's claims ledger: **{led['package_status']}**{_conditional_tag(led)} "
1230
+ f"(`{led['ledger_digest'][:23]}…`).", "",
1231
+ "| Result | Claims | Lean declarations | Ledger | Note |", "|---|---|---|---|---|"]
1232
+ for r in doc["rows"]:
1233
+ ids = list(r["claims"])
1234
+ md.append(f"| {_md(r['title'])} | {'<br>'.join(f'`{_code(c)}`' for c in ids)} | "
1235
+ f"{'<br>'.join(_decl_ref(claims[c], c, ctx['link_base']) for c in ids)} | "
1236
+ f"{'<br>'.join(_status_cells(r, by_id))} | {_md(r['note']) if r.get('note') else '—'} |")
1237
+ md += ["", "One line per main result of `coverage.yaml`. *Ledger*: the status `lean-pkg claims ledger` gives "
1238
+ "each claim, in the order of the claims; only *verified* means the recorded "
1239
+ f"receipts close the claim{_conditional_gloss(led)}.", "",
1240
+ f"Back to [Verification]({'verification.md' if target == 'site' else '#verification'})."]
1241
+ return md
1242
+
1243
+
1244
+ def _scan(pkg: dict, repo, outputs: dict[str, str]) -> None:
1245
+ """Every generated byte through the public-safety scanner with the package's patterns; a blocking hit
1246
+ in any output refuses them all (nothing is written)."""
1247
+ from . import public_safety as ps
1248
+ sc = ps.Scanner(pkg, repo, repo)
1249
+ hits = []
1250
+ for where, text in outputs.items():
1251
+ hits += [(where, h) for h in sc.scan_text(text, where) if h[1].severity == ps.BLOCK]
1252
+ if hits:
1253
+ fams = sorted({h[1].label for _w, h in hits})
1254
+ raise core.Fail(f"{pkg['name']}: the rendered page carries {len(hits)} private string(s) ({', '.join(fams)}); "
1255
+ f"nothing written. Fix the data it comes from:\n "
1256
+ + "\n ".join(f"{w} line {n}: {ex}" for w, (n, _p, ex) in hits[:10]))
1257
+
1258
+
1259
+ def render_all(pkg: dict, repo, allow_private: bool = False, advisories: bool = True,
1260
+ override: dict | None = None, corroborator: Corroborator | None = None
1261
+ ) -> tuple[dict[str, str], dict, list[str]]:
1262
+ """({'readme': block, 'verification.md', 'coverage.md', 'html'}: every output, each with a final
1263
+ newline; the facts for --json; warnings). One context feeds them all; all are scanned together.
1264
+ advisories=False leaves the toolchain advisory lines out: the baseline `--check` compares against.
1265
+ override (`--repo DIR`): see _context; the facts then carry `repo_view` {head, anchor_commit, receipt,
1266
+ commit, included, reason}. corroborator (`--corroborate`): the level-2 answers of the GitHub Actions jobs."""
1267
+ from . import page_html
1268
+ ctx = _context(pkg, repo, allow_private, override)
1269
+ ctx["advisories"] = advisories
1270
+ ctx["corroborator"] = corroborator
1271
+ name = ctx["name"]
1272
+ body, extra = _body(ctx, "readme")
1273
+ block = "\n".join([BEGIN, GENERATED_NOTE.format(name=name), "", *body, "", END]) + "\n"
1274
+ site_body, _ = _body(ctx, "site")
1275
+ verification = "\n".join(["# Verification", "", SITE_NOTE.format(name=name), "", *site_body]) + "\n"
1276
+ coverage = "\n".join(_coverage_lines(ctx, "site")) + "\n"
1277
+ html_body, _ = _body(ctx, "html")
1278
+ html = page_html.document(f"{name}: verification",
1279
+ ["# Verification", "", *html_body, "", *_coverage_lines(ctx, "html")])
1280
+ outputs = {README: block, SITE_FILES[0]: verification, SITE_FILES[1]: coverage, HTML_NAME: html}
1281
+ _scan(pkg, repo, outputs)
1282
+ facts = extra["facts"] if ctx["repo_view"] is None else {**extra["facts"], "repo_view": ctx["repo_view"]}
1283
+ return ({"readme": block, SITE_FILES[0]: verification, SITE_FILES[1]: coverage, "html": html},
1284
+ facts, ctx["warnings"] + extra["warnings"])
1285
+
1286
+
1287
+ def render(pkg: dict, repo, allow_private: bool = False, corroborator: Corroborator | None = None
1288
+ ) -> tuple[str, dict, list[str]]:
1289
+ """(README block text with markers and a final newline, facts for --json, warnings)."""
1290
+ outputs, facts, warnings = render_all(pkg, repo, allow_private, corroborator=corroborator)
1291
+ return outputs["readme"], facts, warnings
1292
+
1293
+ # --------------------------------------------------------------------------
1294
+ # the README block
1295
+
1296
+ def split_block(text: str) -> tuple[str, str | None, str] | None:
1297
+ """(before, block or None, after): the block with its markers; None when the markers are unbalanced
1298
+ or repeated (refused). (text, None, '') when there is no block."""
1299
+ nb, ne = text.count(BEGIN), text.count(END)
1300
+ if nb == 0 and ne == 0:
1301
+ return text, None, ""
1302
+ if nb != 1 or ne != 1 or text.index(BEGIN) > text.index(END):
1303
+ return None
1304
+ i, j = text.index(BEGIN), text.index(END) + len(END)
1305
+ if j < len(text) and text[j] == "\n":
1306
+ j += 1
1307
+ return text[:i], text[i:j], text[j:]
1308
+
1309
+
1310
+ def backed_sites(facts: dict) -> frozenset[str]:
1311
+ """The site profiles whose sentence the rendered page carries."""
1312
+ return frozenset(n for n, f in facts["sites"].items() if f["sentence"])
1313
+
1314
+
1315
+ def unbacked_site_problems(readme: str, backed: frozenset[str], profiles: dict,
1316
+ facts: dict | None = None) -> list[str]:
1317
+ """One problem per site the README mentions anywhere (inside the markers or not) whose sentence the page
1318
+ does not carry: no backing, or backing below the scheduler's sentence level (facts: the page's)."""
1319
+ out = []
1320
+ for s in profiles.values():
1321
+ if s.mention_re.search(readme) and s.name not in backed:
1322
+ sched = sites.SCHEDULERS[s.scheduler]
1323
+ fact = ((facts or {}).get("sites") or {}).get(s.name) or {}
1324
+ if fact.get("backed"):
1325
+ rows = fact.get("corroboration")
1326
+ if rows is None:
1327
+ tail = (f"run it, or remove the sentence from {README}; the compute job stays backed")
1328
+ else:
1329
+ from . import ci_github
1330
+ why = "; ".join(f"{j}: {ci_github.failures(r)}" for j, r in rows.items()
1331
+ if fact["levels"].get(j, 0) < sched.sentence_level)
1332
+ tail = (f"corroboration failed ({why}); fix the run, or remove the sentence from {README}; the "
1333
+ f"compute job stays backed")
1334
+ out.append(f"{README} acknowledges {s.mention}, but its {sched.label} jobs are corroborated to "
1335
+ f"level {fact.get('level')} only, and its sentence needs level {sched.sentence_level}, a "
1336
+ f"corroborated run ({CORROBORATE_HINT}): {tail}")
1337
+ continue
1338
+ later = (f"; its sentence renders only from a corroborated run (level {sched.sentence_level})"
1339
+ if sched.sentence_level > 1 else "")
1340
+ out.append(f"{README} acknowledges {s.mention}, but no {sched.label} receipt backs it (coverage.yaml "
1341
+ f"compute: [{{cluster: {s.name}, jobs: [{sched.placeholder}]}}] with each job's receipt "
1342
+ f"committed){later}")
1343
+ return out
1344
+
1345
+
1346
+ def readme_problems(readme: str | None, block: str, backed: frozenset[str], profiles: dict,
1347
+ facts: dict | None = None) -> list[str]:
1348
+ """Why `--check` fails, in a fixed order; [] when the README is current. backed: the site profiles
1349
+ whose sentence the page carries (backed_sites); profiles: every profile the package can name; facts:
1350
+ the page's facts (a site backed below its sentence level is named so)."""
1351
+ if readme is None:
1352
+ return [f"{README} is missing (`lean-pkg page NAME --write`)"]
1353
+ problems = []
1354
+ parts = split_block(readme)
1355
+ if parts is None:
1356
+ problems.append(f"{README} has unbalanced or repeated page markers ({BEGIN} / {END})")
1357
+ elif parts[1] is None:
1358
+ problems.append(f"{README} has no page block (`lean-pkg page NAME --write` appends it)")
1359
+ elif strip_advisories(parts[1]) != strip_advisories(block):
1360
+ problems.append(f"{README}: the page block is stale (`lean-pkg page NAME --write`)")
1361
+ if LEAN_PKG_URL not in readme or CONCEPT_DOI not in readme:
1362
+ problems.append(f"{README} lacks the lean-pkg credit ({LEAN_PKG_URL}, doi:{CONCEPT_DOI})")
1363
+ problems += unbacked_site_problems(readme, backed, profiles, facts)
1364
+ return problems
1365
+
1366
+
1367
+ def strip_advisories(text: str) -> str:
1368
+ """The text without its toolchain advisory lines (#237): an advisory added to lean-pkg's list never
1369
+ makes a page stale; the next `--write` shows it."""
1370
+ return "".join(x for x in text.splitlines(keepends=True) if not x.startswith(ADVISORY_PREFIX))
1371
+
1372
+
1373
+ def advisory_notes(facts: dict, readme: str | None) -> list[str]:
1374
+ """The non-failing NOTE lines of `--check`: one per advisory that applies and the README page block
1375
+ does not show yet."""
1376
+ parts = split_block(readme) if readme is not None else None
1377
+ shown = parts[1] if parts and parts[1] is not None else ""
1378
+ return [f"NOTE: toolchain advisory {v['id']} applies; the next page --write will show it"
1379
+ for v in facts.get("toolchain_advisories") or [] if f"[{v['id']}](" not in shown]
1380
+
1381
+
1382
+ def replace_block(readme: str | None, block: str) -> str:
1383
+ if readme is None:
1384
+ return block
1385
+ parts = split_block(readme)
1386
+ if parts is None:
1387
+ raise core.Fail(f"{README} has unbalanced or repeated page markers; fix them by hand first")
1388
+ before, old, after = parts
1389
+ if old is None:
1390
+ sep = "" if not before else ("\n" if before.endswith("\n") else "\n\n")
1391
+ return before + sep + block
1392
+ return before + block + after
1393
+
1394
+
1395
+ def _read_readme(repo):
1396
+ p = repo / README
1397
+ if p.is_symlink():
1398
+ raise core.Fail(f"{p} is a symlink; refusing to read or write through it")
1399
+ return p.read_text(encoding="utf-8") if p.is_file() else None
1400
+
1401
+
1402
+ def _target_problem(p) -> str | None:
1403
+ if p.is_symlink():
1404
+ return f"{p} is a symlink; refusing to write through it"
1405
+ if p.exists() and not p.is_file():
1406
+ return f"{p} exists and is not a regular file"
1407
+ return None
1408
+
1409
+
1410
+ def _site_targets(site: str | None, html: str | None) -> list[tuple[str, "object", str]]:
1411
+ """[(shown path, pathlib.Path, output key)] for --site DIR and --html PATH, in a fixed order."""
1412
+ import pathlib
1413
+ out = []
1414
+ if site is not None:
1415
+ d = pathlib.Path(site)
1416
+ if d.is_symlink():
1417
+ raise core.Fail(f"--site {site} is a symlink; refusing to write through it")
1418
+ if d.exists() and not d.is_dir():
1419
+ raise core.Fail(f"--site {site} exists and is not a directory")
1420
+ out += [(str(pathlib.PurePath(site) / f), d / f, f) for f in SITE_FILES]
1421
+ if html is not None:
1422
+ out.append((html, pathlib.Path(html), "html"))
1423
+ return out
1424
+
1425
+
1426
+ def site_status(targets, outputs: dict[str, str], baseline: dict[str, str] | None = None
1427
+ ) -> list[tuple[str, str, str | None]]:
1428
+ """[(shown path, current|missing|stale|refused, problem or None)] for `--check --site/--html`. A file is
1429
+ current when it equals the output, or the baseline without toolchain advisory lines (#237); a Markdown
1430
+ file is compared with its advisory lines left out."""
1431
+ def same(p, key) -> bool:
1432
+ have = p.read_bytes()
1433
+ cands = [outputs[key]] + ([baseline[key]] if baseline else [])
1434
+ if any(have == c.encode("utf-8") for c in cands):
1435
+ return True
1436
+ if key != "html":
1437
+ text = have.decode("utf-8", "replace")
1438
+ return any(strip_advisories(text) == strip_advisories(c) for c in cands)
1439
+ return False
1440
+ out = []
1441
+ for shown, p, key in targets:
1442
+ problem = _target_problem(p)
1443
+ if problem:
1444
+ out.append((shown, "refused", problem))
1445
+ elif not p.is_file():
1446
+ out.append((shown, "missing", f"{shown} is missing (`lean-pkg page NAME --site DIR` / `--html PATH`)"))
1447
+ elif not same(p, key):
1448
+ out.append((shown, "stale", f"{shown} is stale (`lean-pkg page NAME --site DIR` / `--html PATH`)"))
1449
+ else:
1450
+ out.append((shown, "current", None))
1451
+ return out
1452
+
1453
+
1454
+ def _write_atomic(p, text: str) -> None:
1455
+ import os
1456
+ p.parent.mkdir(parents=True, exist_ok=True)
1457
+ tmp = p.with_name(p.name + ".tmp")
1458
+ tmp.write_text(text, encoding="utf-8")
1459
+ os.replace(tmp, p)
1460
+
1461
+
1462
+ def _write_site(targets, outputs: dict[str, str]) -> list[dict]:
1463
+ for _shown, p, _key in targets: # refuse before writing any of them
1464
+ problem = _target_problem(p)
1465
+ if problem:
1466
+ raise core.Fail(problem)
1467
+ done = []
1468
+ for shown, p, key in targets:
1469
+ if p.is_file() and p.read_bytes() == outputs[key].encode("utf-8"):
1470
+ done.append({"path": shown, "status": "unchanged"})
1471
+ continue
1472
+ _write_atomic(p, outputs[key])
1473
+ done.append({"path": shown, "status": "written"})
1474
+ return done
1475
+
1476
+
1477
+ def do_page(reg: dict, name: str, *, write: bool, check: bool, out: str | None, allow_private: bool,
1478
+ agent: str | None, site: str | None = None, html: str | None = None,
1479
+ repo_arg: str | None = None, strict_preview: bool = False, corroborate: bool = False,
1480
+ fetch=None, attested: bool = False,
1481
+ trusted_root: str | None = None) -> tuple[list[str], dict, list[str], int]:
1482
+ if sum(map(bool, (write, check, out))) > 1:
1483
+ raise core.UsageError("--write, --check and --out are mutually exclusive")
1484
+ from .receipt_check import attested_usage
1485
+ trusted_root = attested_usage(attested, trusted_root)
1486
+ if strict_preview and not (check and repo_arg is not None):
1487
+ raise core.UsageError("--strict-preview applies to `page --check --repo DIR` only (it makes the differences "
1488
+ "of a preview from the receipt-bound files fail the check)")
1489
+ if repo_arg is not None and write:
1490
+ raise core.UsageError("--repo reads another checkout; --write edits the registered checkout's README.md "
1491
+ "(drop one)")
1492
+ override = None
1493
+ if repo_arg is not None:
1494
+ reg, override = gate_mod.repo_override(reg, name, repo_arg)
1495
+ if note := gate_mod.repo_override_note(override):
1496
+ print(note, file=core.sys.stderr)
1497
+ pkg, repo = cov.package_checkout(reg, name)
1498
+ targets = _site_targets(site, html)
1499
+ corr = Corroborator(pkg, repo, fetch, corroborate=corroborate, attested=attested, trusted_root=trusted_root) \
1500
+ if corroborate or attested else None
1501
+ outputs, facts, warnings = render_all(pkg, repo, allow_private, override=override, corroborator=corr)
1502
+ warnings = warnings + corroboration_warnings(facts, attested)
1503
+ if override is not None:
1504
+ rv = facts.pop("repo_view")
1505
+ override = {**override, "head": rv["head"], "anchor_commit": rv["anchor_commit"],
1506
+ "source": "committed-head",
1507
+ "receipt_facts": {k: rv[k] for k in ("receipt", "commit", "included", "binds_head",
1508
+ "reason")}}
1509
+ if core.git(repo, "status", "--porcelain", "--untracked-files=no").stdout.strip():
1510
+ warnings = [f"--repo {override['path']}: uncommitted changes to tracked files are not read (the page "
1511
+ f"uses the committed HEAD only)"] + warnings
1512
+ block = outputs["readme"]
1513
+ rf = (override or {}).get("receipt_facts") or {}
1514
+ preview = override is not None and rf.get("included") is False and not rf.get("binds_head")
1515
+ payload = {"ok": True, "name": name, "readme": README, "markdown": block, "written": False,
1516
+ "unchanged": False, "current": None, "preview": preview, "problems": [], "warnings": warnings,
1517
+ "site_files": [], "repo_override": override, **facts}
1518
+ existing = new = None
1519
+ if write: # a lease refusal comes before any file is written
1520
+ existing = _read_readme(repo)
1521
+ new = replace_block(existing, block)
1522
+ if new != existing:
1523
+ core.refuse_invalid_lease(name, pkg.get("lease"))
1524
+ lease = pkg.get("lease")
1525
+ if core.lease_live(lease, core.dt.datetime.now(core.dt.timezone.utc)) and agent != lease.get("agent"):
1526
+ raise core.Fail(f"{name}: lease held by {lease.get('agent')} — pass --agent {lease.get('agent')}; "
1527
+ f"nothing written")
1528
+ site_lines: list[str] = []
1529
+ if targets and not check:
1530
+ payload["site_files"] = _write_site(targets, outputs)
1531
+ site_lines = [f"{name}: {f['path']}: {'written' if f['status'] == 'written' else 'current; nothing written'}"
1532
+ for f in payload["site_files"]]
1533
+ if out:
1534
+ import pathlib
1535
+ outp = pathlib.Path(out)
1536
+ if outp.is_symlink():
1537
+ raise core.Fail(f"{outp} is a symlink; refusing to write through it")
1538
+ outp.parent.mkdir(parents=True, exist_ok=True)
1539
+ outp.write_text(block)
1540
+ payload.update(written=True, out=str(outp))
1541
+ return site_lines + [f"{name}: wrote the page block to {outp}; {README} untouched"], payload, warnings, 0
1542
+ if check:
1543
+ readme = _read_readme(repo)
1544
+ problems = readme_problems(readme, block, backed_sites(facts), sites.for_repo(repo), facts)
1545
+ baseline = render_all(pkg, repo, allow_private, advisories=False, override=override,
1546
+ corroborator=corr)[0] \
1547
+ if facts.get("toolchain_advisories") \
1548
+ else None
1549
+ status = site_status(targets, outputs, baseline)
1550
+ payload["site_files"] = [{"path": shown, "status": st} for shown, st, _p in status]
1551
+ problems += [x for _s, _st, x in status if x]
1552
+ said = _override_problems(problems, override, [shown for shown, st, _p in status if st == "stale"])
1553
+ # option C (#291): under a preview, a difference that comes only from the preview is a warning (the
1554
+ # committed files are receipt-bound by design) unless --strict-preview; every other problem still fails
1555
+ drift = [x for x, is_drift in said if is_drift and not strict_preview]
1556
+ problems = [x for x, is_drift in said if not (is_drift and not strict_preview)]
1557
+ warnings += drift # the same list object as payload["warnings"]
1558
+ payload.update(ok=not problems, current=None if preview else not problems, problems=problems)
1559
+ where = README + "".join(f", {shown}" for shown, _p, _k in targets)
1560
+ notes = [f" {n}" for n in advisory_notes(facts, readme)] # #237: never a staleness reason
1561
+ if problems:
1562
+ return ([f"{name}: page: STALE ({len(problems)} problem(s))"] + [f" {p}" for p in problems]
1563
+ + notes + [f"{name}: page: STALE"]), payload, warnings, 1
1564
+ if preview:
1565
+ n = len(drift)
1566
+ return ([f"{name}: page: preview of commit {_c12(override.get('head'))} ({where}): "
1567
+ + (f"{n} difference(s) from the receipt-bound files, expected between gate runs (warnings; "
1568
+ f"--strict-preview fails on them)" if n else "no difference from the committed files")]
1569
+ + notes), payload, warnings, 0
1570
+ return [f"{name}: page: current ({where})"] + notes, payload, warnings, 0
1571
+ if not write:
1572
+ if targets:
1573
+ return site_lines, payload, warnings, 0
1574
+ return [block.rstrip("\n")], payload, warnings, 0
1575
+ if new == existing:
1576
+ payload.update(unchanged=True, current=True)
1577
+ return site_lines + [f"{name}: {README} page block is current; nothing written"], payload, warnings, 0
1578
+ _write_atomic(repo / README, new)
1579
+ payload.update(written=True, current=True)
1580
+ return site_lines + [f"{name}: wrote the page block into {repo / README} — not committed; commit it yourself"], \
1581
+ payload, warnings, 0
1582
+
1583
+
1584
+ def _override_problems(problems: list[str], override: dict | None, stale_sites: list[str]
1585
+ ) -> list[tuple[str, bool]]:
1586
+ """[(problem, is preview drift)] for `--check --repo` when the receipt facts were withheld: a stale README
1587
+ block or --site/--html file is reworded to say why. A preview (the receipt does not bind HEAD) names both
1588
+ commits and is expected drift between gate runs (True: do_page makes it a warning unless --strict-preview);
1589
+ a receipt that binds HEAD but does not validate is a failed check, never called drift (False). Every other
1590
+ problem (missing block, markers, credit, an unbacked site sentence, a missing file) is never drift."""
1591
+ rf = (override or {}).get("receipt_facts") or {}
1592
+ if override is None or rf.get("included") is not False:
1593
+ return [(p, False) for p in problems]
1594
+ head = _c12(override.get("head")) or "HEAD"
1595
+ stale = {f"{README}: the page block is stale (`lean-pkg page NAME --write`)": f"{README}: the page block"}
1596
+ stale.update({f"{s} is stale (`lean-pkg page NAME --site DIR` / `--html PATH`)": s for s in stale_sites})
1597
+
1598
+ def why(what: str) -> str:
1599
+ if rf.get("binds_head"):
1600
+ return (f"{what} differs from what --repo renders at commit {head}: the recorded receipt "
1601
+ f"{rf.get('receipt')} binds that commit but does not validate ({rf.get('reason')}), so no receipt "
1602
+ f"fact is shown; this is a failed check, not drift between gate runs (repair or rerun the gate)")
1603
+ return (f"{what} differs from this preview: --repo renders commit {head}, which the receipts (bound to "
1604
+ f"{_c12(rf.get('commit')) or 'none'}) do not cover, while the committed file is the receipt-bound "
1605
+ f"page; expected between gate runs, not a failed gate (`lean-pkg page NAME --check` without --repo "
1606
+ f"checks the official page)")
1607
+ return [(why(stale[p]), not rf.get("binds_head")) if p in stale else (p, False) for p in problems]
1608
+
1609
+
1610
+ def publish_item(pkg: dict, repo, corroborate: bool = False, fetch=None, *, attested: bool = False,
1611
+ trusted_root: str | None = None) -> tuple[tuple[str, str], dict]:
1612
+ """The `publish --dry-run` checklist line for `page --check`, and its JSON. Adopted (coverage.yaml at
1613
+ HEAD or a page block in the README): any problem is ✗. Not adopted: WARN, except a site sentence (Easley's)
1614
+ with no backing, which is ✗ (it states where the evidence was produced). corroborate (`publish --dry-run
1615
+ --corroborate`): the page is rendered as `page --check --corroborate` renders it (level 2 for GitHub
1616
+ Actions jobs). attested (`publish --dry-run --attested [--trusted-root FILE]`): as `page --check --attested`
1617
+ renders it (level 3, which holds after the run's records expire; under both flags level 3 needs both
1618
+ answers); the rendered payload then also carries sites.<name>.{level, levels} and the page's corroboration
1619
+ warnings (`page --json` carries the same)."""
1620
+ name = pkg["name"]
1621
+ try:
1622
+ readme = _read_readme(repo)
1623
+ except core.Fail as e:
1624
+ return ("✗", f"page: {e}"), {"status": "fail", "adopted": None, "problems": [str(e)]}
1625
+ adopted = core.tracked_at(repo, cov.DEFAULT_COVERAGE_FILE) or (readme is not None and BEGIN in readme)
1626
+ if not adopted:
1627
+ try:
1628
+ profiles = sites.for_repo(repo)
1629
+ except core.Fail as e:
1630
+ return ("✗", f"page: {e}"), {"status": "fail", "adopted": False, "problems": [str(e)]}
1631
+ problems = readme_problems(readme, "", frozenset(), profiles)
1632
+ problems = [p for p in problems if "no page block" not in p] or []
1633
+ unbacked = unbacked_site_problems(readme, frozenset(), profiles) if readme is not None else []
1634
+ mark = "✗" if unbacked else "WARN"
1635
+ # The route: adopt the page (coverage.yaml with compute, then --write); committing README.md and
1636
+ # coverage.yaml after the gated commit keeps the receipts binding only under the docs-only opt-in.
1637
+ hint = (f"; README.md and coverage.yaml committed after the gated commit keep the receipts binding only "
1638
+ f"with the docs-only opt-in (`lean-pkg update {name} --accept-docs-descendants --reason TEXT`)"
1639
+ if unbacked and pkg.get("docs_descendants") is not True else "")
1640
+ label = (f"no verification page: `lean-pkg page {name} --write` (docs/page.md)"
1641
+ + (f"; {'; '.join(problems)}" if problems else "") + hint)
1642
+ return (mark, label), {"status": "fail" if unbacked else "warn", "adopted": False, "problems": problems}
1643
+ try:
1644
+ corr = Corroborator(pkg, repo, fetch, corroborate=corroborate, attested=attested, trusted_root=trusted_root) \
1645
+ if corroborate or attested else None
1646
+ block, facts, _w = render(pkg, repo, corroborator=corr)
1647
+ except (core.Fail, core.UsageError) as e:
1648
+ # A multi-line refusal (coverage.yaml's) puts only a count on its first line: show the reasons too.
1649
+ lines = [x.strip() for x in str(e).splitlines() if x.strip()] or [type(e).__name__]
1650
+ reasons = lines[1:] or lines
1651
+ shown = " ".join(lines[:1] + ["; ".join(lines[1:])] if len(lines) > 1 else lines)
1652
+ label = "page cannot be rendered: " + (shown if len(shown) <= 600 else shown[:597] + "...")
1653
+ return ("✗", label), {"status": "fail", "adopted": True, "problems": reasons}
1654
+ problems = readme_problems(readme, block, backed_sites(facts), sites.for_repo(repo), facts)
1655
+ extra = {}
1656
+ if attested: # what `page --json --attested` carries about the levels, and its warnings (additive keys)
1657
+ extra = {"sites": {n: {"level": f.get("level"), "levels": f.get("levels") or {}}
1658
+ for n, f in (facts.get("sites") or {}).items()},
1659
+ "warnings": corroboration_warnings(facts, attested=True)}
1660
+ if problems:
1661
+ return ("✗", f"page: {'; '.join(problems)}"), {"status": "fail", "adopted": True, "problems": problems,
1662
+ **extra}
1663
+ return ("✓", f"page block in {README} is current (`lean-pkg page {name} --check`)"), \
1664
+ {"status": "pass", "adopted": True, "problems": [], **extra}
1665
+
1666
+
1667
+
1668
+
1669
+ def cmd_page(args) -> int:
1670
+ reg = core.load_registry(core.registry_path(args))
1671
+ lines, payload, warnings, rc = do_page(reg, args.name, write=args.write, check=args.check, out=args.out,
1672
+ allow_private=args.allow_private_manuscript, agent=args.agent,
1673
+ site=args.site, html=args.html, repo_arg=args.repo,
1674
+ strict_preview=getattr(args, "strict_preview", False),
1675
+ corroborate=getattr(args, "corroborate", False),
1676
+ attested=getattr(args, "attested", False),
1677
+ trusted_root=getattr(args, "trusted_root", None))
1678
+ for w in warnings:
1679
+ print(f"lean-pkg: warning: {w}", file=core.sys.stderr)
1680
+ if getattr(args, "write_binding_file", False) and not args.write:
1681
+ raise core.UsageError("--write-binding-file goes with --write (it writes lean-pkg-binding.yaml beside the "
1682
+ "README; on its own use `lean-pkg update NAME --write-binding-file`)")
1683
+ if (args.write or args.site or args.html or args.out) and not args.check:
1684
+ # the files this run wrote for the documentation commit (README.md relative to the package directory);
1685
+ # deferred[] (below) is never part of it (#410)
1686
+ first = [payload["out"]] if payload.get("out") else [payload["readme"]] if args.write and payload.get("written") else []
1687
+ payload["outputs"] = first + [f["path"] for f in payload.get("site_files") or [] if f.get("status") == "written"]
1688
+ if args.write and payload.get("written") and rc == 0:
1689
+ lines += docs_only_opt_in(args, reg, payload)
1690
+ if getattr(args, "json_out", False):
1691
+ core.print_json(payload)
1692
+ else:
1693
+ print("\n".join(lines))
1694
+ return rc
1695
+
1696
+
1697
+ def docs_only_opt_in(args, reg: dict, payload: dict) -> list[str]:
1698
+ """After `page --write` changed README.md of a gated package: the docs-only opt-in the page commit needs.
1699
+ Committing the README moves HEAD past the gated commit X, and without the opt-in the receipts stop binding
1700
+ (the gate, publish and `receipt check` refuse a non-evidence descendant).
1701
+
1702
+ lean-pkg-binding.yaml at X decides when it is there (proposal 0002): nothing is done. Without it, the
1703
+ registry route (deprecated) keeps the receipts bound: when the record says nothing either way it is turned
1704
+ on through `lean-pkg update NAME --accept-docs-descendants --reason R`, its own invocation (its lock,
1705
+ committed mode, `updated` event and deprecation WARN); a record `false` (the veto) is left alone. The
1706
+ payload carries the deprecation.
1707
+
1708
+ The file itself is a build input, committed on its own right before the next verify run, never with the
1709
+ README (#410). So it is not written here unless asked (`--write-binding-file`, into the working
1710
+ tree, never staged, never over an existing path): by default the migration is printed as deferred advice.
1711
+ `deferred[]` holds it either way, apart from `outputs[]`, the files of this documentation commit."""
1712
+ from . import binding_file
1713
+ from . import verify as verify_mod
1714
+ pkg = core.get_pkg(reg, args.name)
1715
+ gated = (pkg.get("gate") or {}).get("receipt")
1716
+ if not gated or pkg.get("docs_descendants") is False: # not gated, or the record's veto
1717
+ return []
1718
+ repo = core.repo_path(pkg)
1719
+ bound = gate_mod.recorded_json(repo, gated) or {}
1720
+ x = str(bound.get("commit") or "")
1721
+ c12 = x[:12] or "the gated commit"
1722
+ if x and binding_file.read_at(repo, x).state != "absent": # the committed file at X decides
1723
+ return []
1724
+ lines: list[str] = []
1725
+ dep = binding_file.registry_only_deprecation(args.name, x or None)
1726
+ if pkg.get("docs_descendants") is None:
1727
+ argv = verify_mod.global_flags(args) + ["update", args.name, "--accept-docs-descendants", "--reason",
1728
+ f"page --write: the README verification page is committed after "
1729
+ f"{c12}"]
1730
+ argv += ["--agent", args.agent] if args.agent else []
1731
+ json_out = getattr(args, "json_out", False)
1732
+ rc, out = verify_mod.invoke(argv + (["--json"] if json_out else []), capture_json=json_out)
1733
+ shown = "lean-pkg " + core.shlex.join(argv)
1734
+ payload["docs_descendants"] = {"turned_on": rc == 0, "command": shown, "rc": rc,
1735
+ **({"update": out} if out is not None else {})}
1736
+ if rc != 0:
1737
+ payload["warnings"].append(f"the docs-only exception is not on (`{shown}` exited {rc}); committing "
1738
+ f"README.md moves HEAD past {c12} and the receipts stop binding")
1739
+ return [f"{args.name}: WARN: the docs-only exception is not on: `{shown}` exited {rc}; run it before "
1740
+ f"committing README.md"]
1741
+ lines.append(f"{args.name}: turned on the docs-only exception (`{shown}`): the record now says "
1742
+ f"docs_descendants: true, so a commit after {c12} that changes only non-build files, such as "
1743
+ f"this README, keeps the receipts bound to {c12}; a changed build input (*.lean, lakefile, "
1744
+ f"lake-manifest.json, lean-toolchain, claims.yaml) still needs new receipts. Undo: lean-pkg "
1745
+ f"update {args.name} --no-accept-docs-descendants --reason R")
1746
+ else: # the record already opts in, with no file at X (otherwise the update above printed the WARN)
1747
+ print(binding_file.deprecation_line(dep), file=core.sys.stderr)
1748
+ payload["deprecations"] = [dep]
1749
+ globs = [g for g in (pkg.get("build_inputs") or []) if isinstance(g, str) and g.strip()]
1750
+ path = repo / binding_file.FILE
1751
+ command = f"lean-pkg update {args.name} --write-binding-file"
1752
+ advice = binding_file.commit_advice(c12)
1753
+ if not getattr(args, "write_binding_file", False):
1754
+ payload["binding_file"] = {"path": str(path), "state": "deferred", "written": False}
1755
+ payload["deferred"] = [{"id": "binding-file", "path": str(path), "state": "deferred", "written": False,
1756
+ "command": command, "when": "right before the next verify run", "advice": advice}]
1757
+ lines.append(f"{args.name}: deferred (not part of this documentation commit): {binding_file.FILE}, the "
1758
+ f"committed opt-in that replaces the deprecated registry route, is a build input. Right before "
1759
+ f"the next verify run, run `{command}` and {advice}")
1760
+ return lines
1761
+ state, problem = binding_file.write_into(repo, binding_file.render(True, globs))
1762
+ payload["binding_file"] = {"path": str(path), "state": state, "written": state == "written"}
1763
+ payload["deferred"] = [{"id": "binding-file", "path": str(path), "state": state, "written": state == "written",
1764
+ "command": command, "when": "right before the next verify run", "advice": advice}]
1765
+ if state == "written":
1766
+ lines.append(f"{args.name}: wrote {path} (docs_descendants: true"
1767
+ + (f", build_inputs: {', '.join(globs)}" if globs else "")
1768
+ + f"), the committed opt-in that replaces the deprecated registry route; not staged: {advice}")
1769
+ elif state == "unchanged":
1770
+ lines.append(f"{args.name}: {path} is already in the working tree (not overwritten): {advice}")
1771
+ else:
1772
+ lines.append(f"{args.name}: WARN: {binding_file.FILE} not written: {problem}")
1773
+ return lines
1774
+
1775
+
1776
+ def add_parsers(sub, add_json) -> None:
1777
+ s = sub.add_parser("page", help="render the README verification section from coverage.yaml, claims, the "
1778
+ "ledger and the receipts; stdout unless --write/--check/--out/--site/--html")
1779
+ s.add_argument("name")
1780
+ s.add_argument("--write", action="store_true",
1781
+ help="replace the marked block in the package README.md (append it when absent); prose outside "
1782
+ "the markers is untouched. For a gated package without lean-pkg-binding.yaml at the "
1783
+ "gated commit it then keeps the receipts bound through the deprecated registry route "
1784
+ "(when the record says nothing: `update NAME --accept-docs-descendants`, its own registry "
1785
+ "write; a record false is left alone), with a WARN, and prints the move to "
1786
+ "lean-pkg-binding.yaml as deferred advice (--json deferred[]): the file is a build input, "
1787
+ "committed on its own right before the next verify run")
1788
+ s.add_argument("--write-binding-file", action="store_true",
1789
+ help="with --write: also write that lean-pkg-binding.yaml into the working tree (never staged or "
1790
+ "overwritten); commit it on its own right before the next verify run, never with README.md")
1791
+ s.add_argument("--check", action="store_true",
1792
+ help="exit 1 when the README block is missing or stale, the lean-pkg credit is missing, or a "
1793
+ "site sentence has no backing receipt (or, for GitHub Actions, no corroborated run: "
1794
+ "--corroborate); with --site/--html also when those files are missing or stale; writes "
1795
+ "nothing")
1796
+ s.add_argument("--out", default=None, metavar="PATH", help="write the block here instead; README untouched")
1797
+ s.add_argument("--site", default=None, metavar="DIR",
1798
+ help="also write DIR/verification.md (the full page) and DIR/coverage.md (every row, its "
1799
+ "claims, inputs and notes) for MkDocs; with --check, compare them instead")
1800
+ s.add_argument("--html", default=None, metavar="PATH",
1801
+ help="also write one static HTML file (no script, no external asset) from the same data; "
1802
+ "with --check, compare it instead")
1803
+ s.add_argument("--repo", default=None, metavar="DIR",
1804
+ help="read the checkout DIR instead of the registered local_path, for this call only (never "
1805
+ "saved; for CI): DIR must be a git work tree, and when it has remotes one must be the "
1806
+ "package's repo; not with --write. Its committed HEAD is read: when the recorded gate "
1807
+ "receipt does not bind that HEAD (or an evidence-only descendant), the links and Lean "
1808
+ "statements are read at HEAD, no receipt fact is shown and the page says so; with --check, "
1809
+ "differences of such a preview from the receipt-bound files are warnings (exit 0)")
1810
+ s.add_argument("--strict-preview", action="store_true",
1811
+ help="with --check --repo: a preview's differences from the receipt-bound README block and "
1812
+ "--site/--html files fail the check (exit 1) instead of warning")
1813
+ s.add_argument("--corroborate", action="store_true",
1814
+ help="ask the public GitHub REST API about each GitHub Actions job coverage.yaml lists (level "
1815
+ "2: the run, its job, the pinned verify.yml, the receipt annotation), and render the GitHub "
1816
+ "Actions sentence, with its run links, only when every one reaches it; a failure is named "
1817
+ "and fails closed. GH_TOKEN or GITHUB_TOKEN, when set, only raises the rate limit and is "
1818
+ "never printed")
1819
+ s.add_argument("--attested", action="store_true",
1820
+ help="verify each GitHub Actions job coverage.yaml lists at level 3: its committed Sigstore "
1821
+ "bundle (ci.attestation) with `gh attestation verify`, an optional outside tool, and the "
1822
+ "certificate against the ci block; the sentence renders at level 3, which holds after the "
1823
+ "run's records expire (with --corroborate too, level 2 must also hold); a failure is named")
1824
+ s.add_argument("--trusted-root", default=None, metavar="FILE",
1825
+ help="with --attested: verify offline against this Sigstore trusted root (gh attestation "
1826
+ "verify --custom-trusted-root)")
1827
+ s.add_argument("--allow-private-manuscript", action="store_true",
1828
+ help="render against manuscript.version 'unposted'; the page then says so")
1829
+ s.add_argument("--agent", default=None, help="with --write: the lease holder, when the package is leased")
1830
+ add_json(s)
1831
+ s.set_defaults(fn=cmd_page)