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/index.py ADDED
@@ -0,0 +1,1749 @@
1
+ # lean-pkg index -- the public, forkable catalog of trust-graded packages
2
+ """Index entries: `index/<name>/entry.yaml` (schema `index-entry/2`; `index-entry/1`
3
+ still validates) plus verbatim receipt copies under `index/<name>/receipts/`.
4
+ `index-entry/2` adds `claims[]`, one claim per headline item, derived at `index add`.
5
+
6
+ Everything is a file. `index add` writes an entry from a package clone at its
7
+ pin; `index check` re-derives every claim from bytes at the pin; `index render`
8
+ writes the Markdown table. Trust is computed from evidence, never typed.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import contextlib
14
+ import json
15
+ import os
16
+ import pathlib
17
+ import re
18
+ import sys
19
+ import tempfile
20
+ import urllib.error
21
+ import urllib.request
22
+
23
+ import yaml
24
+
25
+ from . import gate as gate_mod
26
+ from . import core
27
+ from . import lean_scan
28
+
29
+
30
+ ENTRY_SCHEMA = "index-entry/2"
31
+ SUPPORTED_ENTRY_SCHEMAS = ("index-entry/1", ENTRY_SCHEMA)
32
+ INDEX_ENV = "LEAN_PKG_INDEX"
33
+ DEFAULT_INDEX_DIR = "index"
34
+ ENTRY_FILE = "entry.yaml"
35
+ RECEIPTS_DIR = "receipts"
36
+ ENTRY_KEYS_V1 = ("schema", "name", "repo", "pin", "lean_toolchain", "mathlib_rev",
37
+ "license_spdx", "trust", "receipts", "headline", "palomar", "doi",
38
+ "reservoir", "formalization_yaml", "fields", "consent", "added", "notes")
39
+ ENTRY_KEYS = ENTRY_KEYS_V1[:10] + ("claims",) + ENTRY_KEYS_V1[10:]
40
+ ENTRY_KEYS_BY_SCHEMA = {"index-entry/1": ENTRY_KEYS_V1, "index-entry/2": ENTRY_KEYS}
41
+ # Optional keys (proposal 0007): absent is valid; when present they sit at this place in the key order.
42
+ ENTRY_OPTIONAL_KEYS = {"index-entry/2": ("built_on",)}
43
+ ENTRY_KEY_ORDER = {"index-entry/1": ENTRY_KEYS_V1,
44
+ "index-entry/2": ENTRY_KEYS[:ENTRY_KEYS.index("formalization_yaml") + 1] + ("built_on",)
45
+ + ENTRY_KEYS[ENTRY_KEYS.index("formalization_yaml") + 1:]}
46
+ BUILT_ON_KEYS = ("name", "url", "authors", "license", "pin", "relation", "note")
47
+ BUILT_ON_REQUIRED = ("name", "url", "authors")
48
+ BUILT_ON_RELATIONS = ("depends-on", "adapted-from")
49
+ INDEX_CLAIM_KEYS = ("id", "decl", "kind", "summary", "judged_as", "trust")
50
+ # Optional derived keys of a claim (proposal 0003): a headline whose claim is conditional. Recomputed by
51
+ # `index check --clone` from the sealed log at the pin, like every derived key; absent on every other claim.
52
+ INDEX_CLAIM_OPTIONAL_KEYS = ("status", "open_hypotheses")
53
+ TRUST_LEVELS = ("lower-tier", "comparator", "palomar")
54
+ TRUST_RANK = {t: i for i, t in enumerate(TRUST_LEVELS, 1)}
55
+ NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*")
56
+ HTTPS_RE = re.compile(r"^https://[A-Za-z0-9.-]+(?::\d+)?/[A-Za-z0-9._~/%+-]+$")
57
+ PALOMAR_ID_RE = re.compile(r"^PALOMAR-\d{4}-\d{2}-\d{2}-\d{6}$")
58
+ FIELD_TAG_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$")
59
+ PRIVATE_PATH_RE = re.compile(r"(^[/~])|(/home/)|(/Users/)|([A-Za-z]:\\)")
60
+
61
+
62
+ # --------------------------------------------------------------------------
63
+ # paths
64
+
65
+ def index_source(args) -> tuple[pathlib.Path, str]:
66
+ """(index root, source): --index "flag", else $LEAN_PKG_INDEX "env", else <registry dir>/index when that
67
+ directory exists "registry-sibling", else ./index "cwd"."""
68
+ if getattr(args, "index", None):
69
+ return pathlib.Path(args.index).expanduser(), "flag"
70
+ env = os.environ.get(INDEX_ENV, "").strip()
71
+ if env:
72
+ return pathlib.Path(env).expanduser(), "env"
73
+ beside = core.registry_home_dir(args) / DEFAULT_INDEX_DIR
74
+ if beside.is_dir():
75
+ return beside, "registry-sibling"
76
+ return pathlib.Path.cwd() / DEFAULT_INDEX_DIR, "cwd"
77
+
78
+
79
+ def index_root(args) -> pathlib.Path:
80
+ """--index, else $LEAN_PKG_INDEX, else <registry dir>/index if it exists, else ./index."""
81
+ return index_source(args)[0]
82
+
83
+
84
+ def existing_index_root(args, *, create: bool = False) -> pathlib.Path:
85
+ """The index root for check / render / migrate: a missing root is a refusal (exit 1), not an empty
86
+ pass; create=True (render with an explicit --index or --out) makes it instead."""
87
+ root = index_root(args)
88
+ if not root.is_dir() and not create:
89
+ raise core.Fail(f"no index at {root} (pass --index or set {INDEX_ENV})")
90
+ return root
91
+
92
+
93
+ def entry_names(root: pathlib.Path) -> list[str]:
94
+ if not root.is_dir():
95
+ return []
96
+ return sorted(p.name for p in root.iterdir() if (p / ENTRY_FILE).is_file())
97
+
98
+
99
+ # --------------------------------------------------------------------------
100
+ # schema: load, validate, dump
101
+
102
+ def load_entry(path: pathlib.Path) -> dict:
103
+ try:
104
+ data = yaml.safe_load(path.read_text(encoding="utf-8"))
105
+ except FileNotFoundError:
106
+ raise core.Fail(f"index entry not found: {path}") from None
107
+ except UnicodeDecodeError as e:
108
+ raise core.Fail(f"{path}: not UTF-8 text ({e.reason} at byte {e.start})") from e
109
+ except OSError as e:
110
+ raise core.Fail(f"{path}: unreadable: {e.strerror or e}") from e
111
+ except yaml.YAMLError as e:
112
+ raise core.Fail(f"{path}: not valid YAML: {e}") from e
113
+ if not isinstance(data, dict):
114
+ raise core.Fail(f"{path}: top level is not a mapping")
115
+ return data
116
+
117
+
118
+ def entry_keys(entry: dict) -> tuple[str, ...]:
119
+ """The key order of the entry's own schema (the current schema when it is unknown)."""
120
+ return ENTRY_KEYS_BY_SCHEMA.get(entry.get("schema"), ENTRY_KEYS)
121
+
122
+
123
+ def index_claims(name: str, headline: list[dict], trust, conditional: dict | None = None) -> list[dict]:
124
+ """claims[] of an index-entry/2: one per headline item, derived, never typed. `conditional` (proposal 0003)
125
+ {headline name: its outstanding hypotheses} adds the optional derived keys `status: conditional` and
126
+ `open_hypotheses` to those items; without it every claim is exactly as before."""
127
+ from .claims import slug_of_decl
128
+ out = []
129
+ for h in headline:
130
+ c = {"id": f"{name}/{slug_of_decl(h['name'])}", "decl": h["name"], "kind": "theorem",
131
+ "summary": h["summary"], "judged_as": h.get("judged_as"), "trust": trust}
132
+ if conditional and h["name"] in conditional:
133
+ c.update(status="conditional", open_hypotheses=list(conditional[h["name"]]))
134
+ out.append(c)
135
+ return out
136
+
137
+
138
+ def _conditional_keys(claims: list) -> dict:
139
+ """{claim decl: {status, open_hypotheses}} of the claims that carry the optional derived keys."""
140
+ return {str(c.get("decl")): {k: c.get(k) for k in INDEX_CLAIM_OPTIONAL_KEYS}
141
+ for c in claims if isinstance(c, dict) and any(k in c for k in INDEX_CLAIM_OPTIONAL_KEYS)}
142
+
143
+
144
+ def trust_text(trust: str, claims: list[dict]) -> str:
145
+ """The rendered trust of an entry or a claim: the tier, and for conditional claims (proposal 0003) the
146
+ assumptions it rests on, "comparator, conditional on 1 assumption". The tier itself never changes: it
147
+ grades the receipts, not the hypotheses."""
148
+ cond = [c for c in claims if isinstance(c, dict) and c.get("status") == "conditional"]
149
+ if not cond:
150
+ return trust
151
+ n = len({h for c in cond for h in c.get("open_hypotheses") or []})
152
+ if not n:
153
+ return f"{trust}, conditional (all assumptions discharged)"
154
+ return f"{trust}, conditional on {n} assumption{'s' if n != 1 else ''}"
155
+
156
+
157
+ def conditional_at(clone: pathlib.Path, pin: str, res: dict, headline: list[dict]) -> dict | None:
158
+ """{headline name: outstanding hypotheses} for the headline items whose claim in claims.yaml at the pin is
159
+ conditional (proposal 0003), judged from the sealed verify log `derive` verified (hypotheses.judge_at; the
160
+ promote stage when the comparator receipt validated). A headline names a claim by its declaration (the
161
+ comparator's naming rule) or by its judged_as. None when no claim at the pin uses hypotheses, discharges or
162
+ witness: entries of every other package carry no new key."""
163
+ from . import claims as claims_mod
164
+ from . import comparator_config as cc
165
+ from . import hypotheses as hyp
166
+ raw = core.git_show_bytes(clone, "./claims.yaml", pin)
167
+ if raw is None:
168
+ return None
169
+ try:
170
+ doc = claims_mod.load_claims_text(raw.decode("utf-8", errors="replace"), f"claims.yaml at {pin[:12]}")
171
+ except core.Fail:
172
+ return None
173
+ claims = [c for c in doc.get("claims") or [] if isinstance(c, dict)]
174
+ if not any(claims_mod.uses_conditional_keys(c) for c in claims):
175
+ return None
176
+ text = None
177
+ if res.get("lower_ok"):
178
+ name = gate_mod.report_log_name(res["lower"])
179
+ for rel, data in res["bytes"].items():
180
+ base = pathlib.PurePosixPath(rel).name
181
+ if base == name:
182
+ text = data.decode("utf-8", "replace")
183
+ elif base == name + gate_mod.REPORT_GZ_SUFFIX and text is None:
184
+ import gzip
185
+ try:
186
+ text = gzip.decompress(data).decode("utf-8", "replace")
187
+ except (OSError, EOFError):
188
+ text = None
189
+ comparator_ok, smoke = bool(res.get("comparator_ok")), None
190
+ if comparator_ok:
191
+ try:
192
+ smoke = smoke_at(clone, pin, res["comparator"])
193
+ except core.Fail: # a malformed sidecar: no discharge counts (fail closed)
194
+ comparator_ok = False
195
+ got = hyp.judge_at(clone, pin, claims, text, comparator_ok=comparator_ok, smoke=smoke)
196
+ out: dict[str, list[str]] = {}
197
+ for h in headline:
198
+ hits = [c for c in claims if str(c.get("id")) in got["conditional"]
199
+ and (cc.covers({h["name"]}, str(c.get("decl") or ""), str(c.get("decl") or "") in got["qualified"])
200
+ or (h.get("judged_as") and h["judged_as"] in got["credited"].get(str(c.get("id")), set())))]
201
+ if hits:
202
+ out[h["name"]] = sorted({x["decl"] for c in hits for x in got["claims"][str(c["id"])]["hypotheses"]
203
+ if x["state"] == "open"})
204
+ return out
205
+
206
+
207
+ def entry_optional_keys(entry: dict) -> tuple[str, ...]:
208
+ return ENTRY_OPTIONAL_KEYS.get(entry.get("schema"), ())
209
+
210
+
211
+ def dump_entry(entry: dict) -> str:
212
+ optional = entry_optional_keys(entry)
213
+ order = ENTRY_KEY_ORDER.get(entry.get("schema"), ENTRY_KEY_ORDER[ENTRY_SCHEMA])
214
+ ordered = {k: entry[k] for k in order if k in entry or k not in optional}
215
+ return yaml.safe_dump(ordered, sort_keys=False, default_flow_style=False,
216
+ allow_unicode=True, width=100)
217
+
218
+
219
+ def _is_rel(p) -> bool:
220
+ if not isinstance(p, str) or not p.strip():
221
+ return False
222
+ pp = pathlib.PurePosixPath(p)
223
+ return not pp.is_absolute() and ".." not in pp.parts and not p.startswith("~")
224
+
225
+
226
+ def _strings(obj, where="entry"):
227
+ if isinstance(obj, str):
228
+ yield where, obj
229
+ elif isinstance(obj, dict):
230
+ for k, v in obj.items():
231
+ yield from _strings(v, f"{where}.{k}")
232
+ elif isinstance(obj, list):
233
+ for i, v in enumerate(obj):
234
+ yield from _strings(v, f"{where}[{i}]")
235
+
236
+
237
+ def _exact_keys(obj, keys, where, errors) -> bool:
238
+ if not isinstance(obj, dict):
239
+ errors.append(f"{where} must be a mapping with keys {list(keys)}")
240
+ return False
241
+ extra = sorted(set(obj) - set(keys))
242
+ missing = [k for k in keys if k not in obj]
243
+ if extra:
244
+ errors.append(f"{where}: unknown key(s) {extra}")
245
+ if missing:
246
+ errors.append(f"{where}: missing key(s) {missing}")
247
+ return not extra and not missing
248
+
249
+
250
+ def validate_entry(entry, dirname: str | None = None) -> list[str]:
251
+ """Every error in an `index-entry/1` or `/2` mapping; [] when valid. Unknown keys are refused."""
252
+ errors: list[str] = []
253
+ if not isinstance(entry, dict):
254
+ return ["entry is not a mapping"]
255
+ keys = entry_keys(entry)
256
+ if entry.get("schema") not in SUPPORTED_ENTRY_SCHEMAS:
257
+ errors.append(f"schema must be one of {SUPPORTED_ENTRY_SCHEMAS}, got {entry.get('schema')!r}")
258
+ optional = entry_optional_keys(entry)
259
+ extra = sorted(set(entry) - set(keys) - set(optional))
260
+ if extra:
261
+ errors.append(f"unknown key(s) {extra} (schema {entry.get('schema')} allows {list(keys)}"
262
+ + (f", optionally {list(optional)}" if optional else "") + ")")
263
+ missing = [k for k in keys if k not in entry]
264
+ if missing:
265
+ errors.append(f"missing key(s) {missing}")
266
+ return errors
267
+ name = entry["name"]
268
+ if not isinstance(name, str) or not NAME_RE.fullmatch(name):
269
+ errors.append(f"name {name!r} must match [A-Za-z0-9][A-Za-z0-9._-]*")
270
+ elif dirname is not None and name != dirname:
271
+ errors.append(f"name {name!r} differs from its directory {dirname!r}")
272
+ if not isinstance(entry["repo"], str) or not HTTPS_RE.match(entry["repo"]):
273
+ errors.append(f"repo must be a public https URL without credentials, got {entry['repo']!r}")
274
+ if _exact_keys(entry["pin"], ("commit", "tag"), "pin", errors):
275
+ if not core._HEX40.fullmatch(str(entry["pin"]["commit"])):
276
+ errors.append(f"pin.commit must be 40 lowercase hex, got {entry['pin']['commit']!r}")
277
+ if entry["pin"]["tag"] is not None and not (isinstance(entry["pin"]["tag"], str)
278
+ and entry["pin"]["tag"].strip()):
279
+ errors.append("pin.tag must be a non-empty string or null")
280
+ for k in ("lean_toolchain", "license_spdx"):
281
+ if not isinstance(entry[k], str) or not entry[k].strip():
282
+ errors.append(f"{k} must be a non-empty string")
283
+ if entry["mathlib_rev"] is not None and not (isinstance(entry["mathlib_rev"], str)
284
+ and entry["mathlib_rev"].strip()):
285
+ errors.append("mathlib_rev must be a non-empty string or null")
286
+ if entry["trust"] not in TRUST_LEVELS:
287
+ errors.append(f"trust must be one of {TRUST_LEVELS}, got {entry['trust']!r}")
288
+ if _exact_keys(entry["receipts"], ("lower", "comparator"), "receipts", errors):
289
+ for k, v in entry["receipts"].items():
290
+ if v is not None and not (_is_rel(v) and v.startswith(".lean-receipts/")
291
+ and v.endswith(".json")):
292
+ errors.append(f"receipts.{k} must be null or a .lean-receipts/*.json path, got {v!r}")
293
+ hl = entry["headline"]
294
+ if not isinstance(hl, list) or not hl:
295
+ errors.append("headline must be a non-empty list")
296
+ else:
297
+ for i, h in enumerate(hl):
298
+ if not isinstance(h, dict):
299
+ errors.append(f"headline[{i}] must be a mapping")
300
+ continue
301
+ extra_h = sorted(set(h) - {"name", "file", "summary", "judged_as"})
302
+ missing_h = [k for k in ("name", "file", "summary") if k not in h]
303
+ if extra_h:
304
+ errors.append(f"headline[{i}]: unknown key(s) {extra_h}")
305
+ if missing_h:
306
+ errors.append(f"headline[{i}]: missing key(s) {missing_h}")
307
+ if extra_h or missing_h:
308
+ continue
309
+ if "judged_as" in h and h["judged_as"] is not None and not (
310
+ isinstance(h["judged_as"], str) and h["judged_as"].strip() and " " not in h["judged_as"]):
311
+ errors.append(f"headline[{i}].judged_as must be null or the Challenge theorem name")
312
+ if not isinstance(h["name"], str) or not h["name"].strip() or " " in h["name"]:
313
+ errors.append(f"headline[{i}].name must be a fully qualified Lean name")
314
+ if not (_is_rel(h["file"]) and h["file"].endswith(".lean")):
315
+ errors.append(f"headline[{i}].file must be a repo-relative .lean path")
316
+ s = h["summary"]
317
+ if not isinstance(s, str) or not s.strip() or "\n" in s.strip() or len(s) > 300:
318
+ errors.append(f"headline[{i}].summary must be one sentence (one line, at most 300 characters)")
319
+ if "claims" in keys:
320
+ errors += _index_claim_errors(entry, errors)
321
+ pal = entry["palomar"]
322
+ if not isinstance(pal, list):
323
+ errors.append("palomar must be a list")
324
+ else:
325
+ for i, p in enumerate(pal):
326
+ if not _exact_keys(p, ("id", "version"), f"palomar[{i}]", errors):
327
+ continue
328
+ if not PALOMAR_ID_RE.match(str(p["id"])):
329
+ errors.append(f"palomar[{i}].id must look like PALOMAR-YYYY-MM-DD-NNNNNN, got {p['id']!r}")
330
+ if isinstance(p["version"], bool) or not isinstance(p["version"], int) or p["version"] < 1:
331
+ errors.append(f"palomar[{i}].version must be a positive integer")
332
+ doi = entry["doi"]
333
+ if doi is not None and _exact_keys(doi, ("concept", "versions"), "doi", errors):
334
+ if not isinstance(doi["versions"], list):
335
+ errors.append("doi.versions must be a list")
336
+ else:
337
+ for i, v in enumerate(doi["versions"]):
338
+ if _exact_keys(v, ("doi", "tag", "commit"), f"doi.versions[{i}]", errors) \
339
+ and not core._HEX40.fullmatch(str(v["commit"])):
340
+ errors.append(f"doi.versions[{i}].commit must be 40 lowercase hex")
341
+ if entry["reservoir"] is not None and not core.RESERVOIR_URL_RE.match(str(entry["reservoir"])):
342
+ errors.append("reservoir must be null or https://reservoir.lean-lang.org/@<owner>/<name>")
343
+ if entry["formalization_yaml"] is not None and not _is_rel(entry["formalization_yaml"]):
344
+ errors.append("formalization_yaml must be null or a repo-relative path")
345
+ if "built_on" in entry and "built_on" in optional:
346
+ errors += built_on_errors(entry["built_on"])
347
+ if not isinstance(entry["fields"], list) or not all(
348
+ isinstance(f, str) and FIELD_TAG_RE.match(f) for f in entry["fields"]):
349
+ errors.append("fields must be a list of lowercase tags ([a-z0-9-])")
350
+ if _exact_keys(entry["consent"], ("recorded",), "consent", errors) \
351
+ and not isinstance(entry["consent"]["recorded"], bool):
352
+ errors.append("consent.recorded must be true or false (pointers stay private)")
353
+ if _exact_keys(entry["added"], ("at", "by"), "added", errors):
354
+ for k in ("at", "by"):
355
+ if not isinstance(entry["added"][k], str) or not entry["added"][k].strip():
356
+ errors.append(f"added.{k} must be a non-empty string")
357
+ if not isinstance(entry["notes"], str):
358
+ errors.append("notes must be a string")
359
+ for where, s in _strings(entry):
360
+ if where in ("entry.repo", "entry.reservoir") or ".doi" in where or \
361
+ (where.startswith("entry.built_on[") and where.endswith("].url")):
362
+ continue
363
+ if PRIVATE_PATH_RE.search(s):
364
+ errors.append(f"{where} looks like a private local path: {s!r}")
365
+ return errors
366
+
367
+
368
+ def _one_line(v, limit: int = 300) -> bool:
369
+ return isinstance(v, str) and bool(v.strip()) and "\n" not in v.strip() and len(v) <= limit
370
+
371
+
372
+ def built_on_errors(credits) -> list[str]:
373
+ """The optional `built_on` list of an index-entry/2 (proposal 0007): third-party Lean code the package
374
+ depends on or adapts. Closed keys; name, url (public https) and authors (non-empty strings) required;
375
+ license, pin (40 hex), relation (depends-on | adapted-from) and note optional, omitted rather than null."""
376
+ if not isinstance(credits, list) or not credits:
377
+ return ["built_on must be a non-empty list of credits (omit the key when there is none)"]
378
+ out: list[str] = []
379
+ names: set[str] = set()
380
+ for i, c in enumerate(credits):
381
+ w = f"built_on[{i}]"
382
+ if not isinstance(c, dict):
383
+ out.append(f"{w} must be a mapping with keys {list(BUILT_ON_REQUIRED)} and optionally "
384
+ f"{[k for k in BUILT_ON_KEYS if k not in BUILT_ON_REQUIRED]}")
385
+ continue
386
+ extra = sorted(set(c) - set(BUILT_ON_KEYS), key=str)
387
+ missing = [k for k in BUILT_ON_REQUIRED if k not in c]
388
+ if extra:
389
+ out.append(f"{w}: unknown key(s) {extra} (allowed: {list(BUILT_ON_KEYS)})")
390
+ if missing:
391
+ out.append(f"{w}: missing key(s) {missing}")
392
+ for k in BUILT_ON_KEYS:
393
+ if k in c and c[k] is None:
394
+ out.append(f"{w}.{k} must not be null (omit an optional key instead)")
395
+ if "name" in c and c["name"] is not None:
396
+ if not _one_line(c["name"], 100):
397
+ out.append(f"{w}.name must be a non-empty one-line string (at most 100 characters)")
398
+ elif c["name"].strip() in names:
399
+ out.append(f"{w}.name {c['name']!r} is listed twice")
400
+ else:
401
+ names.add(c["name"].strip())
402
+ if "url" in c and c["url"] is not None and not (isinstance(c["url"], str) and HTTPS_RE.match(c["url"])):
403
+ out.append(f"{w}.url must be a public https URL without credentials, got {c['url']!r}")
404
+ if "authors" in c and c["authors"] is not None and not (
405
+ isinstance(c["authors"], list) and c["authors"]
406
+ and all(_one_line(a, 200) for a in c["authors"])):
407
+ out.append(f"{w}.authors must be a non-empty list of non-empty one-line strings")
408
+ if c.get("license") is not None and not _one_line(c["license"], 100):
409
+ out.append(f"{w}.license must be a non-empty one-line string (an SPDX expression)")
410
+ if c.get("pin") is not None and not core._HEX40.fullmatch(str(c["pin"])):
411
+ out.append(f"{w}.pin must be a 40-hex commit, got {c['pin']!r}")
412
+ if c.get("relation") is not None and c["relation"] not in BUILT_ON_RELATIONS:
413
+ out.append(f"{w}.relation must be one of {list(BUILT_ON_RELATIONS)}, got {c['relation']!r}")
414
+ if c.get("note") is not None and not _one_line(c["note"]):
415
+ out.append(f"{w}.note must be one line (at most 300 characters)")
416
+ return out
417
+
418
+
419
+ def normalize_built_on(credits) -> list[dict]:
420
+ """Credits with their keys in the documented order (unknown keys kept, so validation reports them)."""
421
+ if not isinstance(credits, list):
422
+ return credits
423
+ out = []
424
+ for c in credits:
425
+ if isinstance(c, dict):
426
+ c = {**{k: c[k] for k in BUILT_ON_KEYS if k in c}, **{k: v for k, v in c.items() if k not in BUILT_ON_KEYS}}
427
+ out.append(c)
428
+ return out
429
+
430
+
431
+ def load_built_on_file(path: str) -> list[dict]:
432
+ """`--built-on-file`: YAML holding a list of credits, or a mapping whose only key is built_on (so a
433
+ block copied from an entry.yaml works). An empty list means no credits."""
434
+ p = pathlib.Path(path).expanduser()
435
+ try:
436
+ data = yaml.safe_load(p.read_text(encoding="utf-8"))
437
+ except OSError as e:
438
+ raise core.Fail(f"--built-on-file {path}: unreadable: {e.strerror or e}") from e
439
+ except (UnicodeDecodeError, yaml.YAMLError) as e:
440
+ raise core.Fail(f"--built-on-file {path}: not valid YAML: {e}") from e
441
+ if isinstance(data, dict) and set(data) == {"built_on"}:
442
+ data = data["built_on"]
443
+ if data is None:
444
+ data = []
445
+ if not isinstance(data, list):
446
+ raise core.Fail(f"--built-on-file {path}: must hold a list of credits (or a mapping with the single "
447
+ f"key built_on)")
448
+ errors = built_on_errors(data) if data else []
449
+ if errors:
450
+ raise core.Fail(f"--built-on-file {path}: " + "; ".join(errors))
451
+ return normalize_built_on(data)
452
+
453
+
454
+ def _git_url_key(url: str) -> str:
455
+ u = str(url).strip().rstrip("/")
456
+ if u.endswith(".git"):
457
+ u = u[:-4]
458
+ return u.lower()
459
+
460
+
461
+ def built_on_manifest_notes(clone: pathlib.Path, entry: dict) -> list[str]:
462
+ """Advisory, never a failure: each credit with a pin, compared with lake-manifest.json at the pin.
463
+ A depends-on (or unlabelled) credit whose url is not a manifest package is reported; an adapted-from
464
+ credit is vendored source, so its absence from the manifest is expected."""
465
+ credits = entry.get("built_on") or []
466
+ if not any(isinstance(c, dict) and c.get("pin") for c in credits):
467
+ return []
468
+ mf = clone / "lake-manifest.json"
469
+ try:
470
+ pkgs = (json.loads(mf.read_text()).get("packages") or []) if mf.is_file() else []
471
+ except ValueError:
472
+ return ["warning: built_on pins not checked: lake-manifest.json at the pin is not valid JSON"]
473
+ revs = {_git_url_key(p.get("url", "")): str(p.get("rev")) for p in pkgs if isinstance(p, dict) and p.get("url")}
474
+ out = []
475
+ for i, c in enumerate(credits):
476
+ if not (isinstance(c, dict) and c.get("pin")):
477
+ continue
478
+ rev = revs.get(_git_url_key(c["url"]))
479
+ if rev is None:
480
+ if c.get("relation") != "adapted-from":
481
+ out.append(f"warning: built_on[{i}] {c['name']}: {c['url']} is not a package in "
482
+ f"lake-manifest.json at the pin (pin not checked)")
483
+ elif rev != c["pin"]:
484
+ out.append(f"warning: built_on[{i}] {c['name']}: pin {c['pin'][:12]} differs from "
485
+ f"lake-manifest.json at the pin ({rev[:12]})")
486
+ return out
487
+
488
+
489
+ # Packages a lake-manifest.json may list that are implicit for `built_on` (docs/index-catalog.md, Credits):
490
+ # Mathlib, the packages Mathlib itself pulls in, and Lean core. Matched on the manifest name and on the URL
491
+ # (case-insensitive, without a trailing .git).
492
+ MATHLIB_FAMILY_NAMES = frozenset(n.lower() for n in (
493
+ "mathlib", "batteries", "std", "aesop", "Qq", "proofwidgets", "importGraph", "LeanSearchClient",
494
+ "plausible", "Cli"))
495
+ MATHLIB_FAMILY_URLS = frozenset(_git_url_key(f"https://github.com/{r}") for r in (
496
+ "leanprover-community/mathlib4", "leanprover-community/mathlib", "leanprover-community/batteries",
497
+ "leanprover/std4", "leanprover-community/aesop", "leanprover-community/quote4",
498
+ "leanprover-community/ProofWidgets4", "leanprover-community/import-graph",
499
+ "leanprover-community/LeanSearchClient", "leanprover-community/plausible", "leanprover/lean4-cli"))
500
+ LEAN_CORE_NAMES = frozenset(("lean", "lean4", "init", "lake"))
501
+ LEAN_CORE_URLS = frozenset((_git_url_key("https://github.com/leanprover/lean4"),))
502
+ # An inherited package from one of these organizations is taken to come in through Mathlib, so a
503
+ # dependency Mathlib adds later is implicit before it is added to the lists above.
504
+ MATHLIB_ORG_PREFIXES = ("https://github.com/leanprover-community/", "https://github.com/leanprover/")
505
+
506
+
507
+ def implicit_lake_package(p: dict) -> bool:
508
+ """True for a lake-manifest.json package that `built_on` never needs to credit."""
509
+ name = str(p.get("name") or "").lower()
510
+ url = _git_url_key(p.get("url") or "")
511
+ if name in MATHLIB_FAMILY_NAMES or url in MATHLIB_FAMILY_URLS:
512
+ return True
513
+ if name in LEAN_CORE_NAMES or url in LEAN_CORE_URLS:
514
+ return True
515
+ return p.get("inherited") is True and url.startswith(MATHLIB_ORG_PREFIXES)
516
+
517
+
518
+ def uncredited_lake_dependencies(clone: pathlib.Path, entry: dict) -> list[dict]:
519
+ """Proposal 0007 (open question 2, decided 2026-10-18): the lake-manifest.json packages at the pin
520
+ that are not implicit and that no `built_on` credit names (by URL, with or without .git, or by name,
521
+ both case-insensitive). Advisory: `index check` warns, never fails. [] without a readable manifest."""
522
+ mf = clone / "lake-manifest.json"
523
+ try:
524
+ pkgs = (json.loads(mf.read_text()).get("packages") or []) if mf.is_file() else []
525
+ except ValueError:
526
+ return []
527
+ credits = [c for c in entry.get("built_on") or [] if isinstance(c, dict)]
528
+ urls = {_git_url_key(c.get("url") or "") for c in credits} - {""}
529
+ names = {str(c.get("name") or "").lower() for c in credits} - {""}
530
+ out = []
531
+ for p in pkgs if isinstance(pkgs, list) else []:
532
+ if not isinstance(p, dict) or implicit_lake_package(p):
533
+ continue
534
+ if _git_url_key(p.get("url") or "") in urls or str(p.get("name") or "").lower() in names:
535
+ continue
536
+ out.append({"name": str(p.get("name") or ""), "url": str(p.get("url") or "")})
537
+ return out
538
+
539
+
540
+ def _index_claim_errors(entry: dict, prior: list[str]) -> list[str]:
541
+ """claims[] of an index-entry/2 must be exactly what index_claims derives from the headline."""
542
+ from .claims import CLAIM_ID_RE
543
+ cs = entry["claims"]
544
+ if not isinstance(cs, list):
545
+ return ["claims must be a list"]
546
+ out: list[str] = []
547
+ cond: dict[str, list] = {}
548
+ for i, c in enumerate(cs):
549
+ base = {k: v for k, v in c.items() if k not in INDEX_CLAIM_OPTIONAL_KEYS} if isinstance(c, dict) else c
550
+ if _exact_keys(base, INDEX_CLAIM_KEYS, f"claims[{i}]", out) and not (
551
+ isinstance(c["id"], str) and CLAIM_ID_RE.match(c["id"])):
552
+ out.append(f"claims[{i}].id must be <name>/<slug>, got {c['id']!r}")
553
+ if not isinstance(c, dict) or not any(k in c for k in INDEX_CLAIM_OPTIONAL_KEYS):
554
+ continue
555
+ hs = c.get("open_hypotheses") # proposal 0003: optional derived keys, both or neither
556
+ if not all(k in c for k in INDEX_CLAIM_OPTIONAL_KEYS):
557
+ out.append(f"claims[{i}]: status and open_hypotheses come together (proposal 0003), or neither")
558
+ elif c["status"] != "conditional":
559
+ out.append(f"claims[{i}].status must be conditional when present, got {c['status']!r}")
560
+ elif not (isinstance(hs, list) and all(isinstance(h, str) and h.strip() for h in hs)
561
+ and hs == sorted(set(hs))):
562
+ out.append(f"claims[{i}].open_hypotheses must be a sorted list of distinct hypothesis names")
563
+ else:
564
+ cond[str(c.get("decl"))] = hs
565
+ if out or any(x.startswith("headline") for x in prior):
566
+ return out
567
+ if cs != index_claims(entry["name"], entry["headline"], entry["trust"], cond):
568
+ out.append("claims[] must be derived from the headline (one per item: id <name>/<slug of the "
569
+ "name>, kind theorem, its summary and judged_as, the entry's trust); nothing is typed "
570
+ "by hand: re-run `lean-pkg index add`")
571
+ return out
572
+
573
+
574
+ # --------------------------------------------------------------------------
575
+ # trust
576
+
577
+ def compute_trust(lower_ok: bool, comparator_ok: bool, palomar: list) -> str | None:
578
+ if palomar:
579
+ return "palomar"
580
+ if comparator_ok:
581
+ return "comparator"
582
+ if lower_ok:
583
+ return "lower-tier"
584
+ return None
585
+
586
+
587
+ def comparator_mechanism(comp: dict | None) -> str | None:
588
+ if not isinstance(comp, dict):
589
+ return None
590
+ if comp.get("schema") == "comparator-receipt/1":
591
+ return "legacy"
592
+ return comp.get("mechanism")
593
+
594
+
595
+ LICENSE_MARKERS = {
596
+ "MIT": "Permission is hereby granted",
597
+ "Apache-2.0": "Apache License",
598
+ "BSD-3-Clause": "Redistribution and use",
599
+ "BSD-2-Clause": "Redistribution and use",
600
+ }
601
+
602
+
603
+ # --------------------------------------------------------------------------
604
+ # the package at its pin
605
+
606
+ def clone_at(source: str, dest: pathlib.Path) -> pathlib.Path:
607
+ p = core.run(["git", "clone", "--quiet", "--no-checkout", str(source), str(dest)])
608
+ if p.returncode != 0:
609
+ raise core.Fail(f"git clone {source} failed: {p.stderr.strip()[:300]}")
610
+ return dest
611
+
612
+
613
+ def checkout_pin(clone: pathlib.Path, commit: str) -> None:
614
+ # core.symlinks=false: a symlink in the tree becomes a plain file, never a link to follow
615
+ p = core.git(clone, "-c", "core.symlinks=false", "checkout", "--quiet", "--detach", commit)
616
+ if p.returncode != 0:
617
+ raise core.Fail(f"pin {commit[:12]} is not in the repository: {p.stderr.strip()[:200]}")
618
+
619
+
620
+ def docs_record(reg: dict | None, name: str, repo: str) -> dict | None:
621
+ """The registry record whose docs_descendants takes part in this entry's docs-only opt-in, or None: the
622
+ entry's own record (the same name and the same public repository) when it sets docs_descendants, true
623
+ (the deprecated grant, used only when the pin has no lean-pkg-binding.yaml) or false (the veto). Index
624
+ applies the opt-in where gate, ledger, promote, publish and comparator read it: lean-pkg-binding.yaml
625
+ committed at the pin and nowhere else (binding_file.resolve_opt_in; a tag or a descendant that adds the
626
+ file grants nothing), with this record's precedence. Without a registry (a public `index check`), or
627
+ with any other record, the file at the pin alone decides."""
628
+ pkg = ((reg or {}).get("packages") or {}).get(name) if isinstance(reg, dict) else None
629
+ if not isinstance(pkg, dict) or not isinstance(pkg.get("docs_descendants"), bool):
630
+ return None
631
+ try:
632
+ if _repo_key(https_repo(pkg.get("repo"))) != _repo_key(repo):
633
+ return None
634
+ except core.Fail:
635
+ return None
636
+ return pkg
637
+
638
+
639
+ REGISTRY_OPT_IN_NOTE = ("docs-only descendants accepted for the tag and the evidence: the registry record opts in "
640
+ "(docs_descendants: true)")
641
+
642
+
643
+ def opt_in(clone: pathlib.Path, pin: str, record: dict | None):
644
+ """The docs-only opt-in that binds evidence at the pin (binding_file.OptIn): lean-pkg-binding.yaml
645
+ committed at the pin, with the precedence of `record` (docs_record) when there is one."""
646
+ from .binding_file import resolve_opt_in
647
+ return resolve_opt_in(clone, pin, record)
648
+
649
+
650
+ def docs_rule(clone: pathlib.Path, pin: str | None, record: dict | None) -> bool:
651
+ """Whether the docs-only rule can bind a descendant of the pin: the opt-in at the pin applies it, or (as
652
+ before the committed file) the record says docs_descendants: true. With no pin yet (index add looking
653
+ for the receipts), the record's say only."""
654
+ if record is not None and record.get("docs_descendants") is True:
655
+ return True
656
+ return pin is not None and opt_in(clone, pin, record).rule == "docs-only"
657
+
658
+
659
+ def opt_in_note(clone: pathlib.Path, pin: str, record: dict | None) -> str | None:
660
+ """The check note saying what decided the docs-only rule at the pin (binding_file.resolve_opt_in, the
661
+ registry precedence of proposal 0002), or None when nothing did (no file at the pin, no record): the
662
+ record's true applies only when the pin has no lean-pkg-binding.yaml; once the file exists there it
663
+ decides; a record's false vetoes."""
664
+ from .binding_file import FILE
665
+ oi = opt_in(clone, pin, record)
666
+ if oi.source == "registry":
667
+ return REGISTRY_OPT_IN_NOTE
668
+ if oi.source == "committed":
669
+ return f"docs-only descendants accepted for the tag and the evidence: {FILE} at {pin[:12]} opts in"
670
+ if oi.file_state == "absent":
671
+ return None
672
+ if oi.file_state == "true": # a record's docs_descendants: false
673
+ return (f"the registry record refuses the docs-only rule (docs_descendants: false), over {FILE} at "
674
+ f"{pin[:12]}; the evidence-only rule binds the tag and the evidence")
675
+ why = "says docs_descendants: false" if oi.file_state == "false" else (
676
+ "does not opt in: " + (oi.problems[0].split(": ", 1)[-1] if oi.problems else "invalid"))
677
+ if record is not None and record.get("docs_descendants") is True:
678
+ return (f"the registry record's docs_descendants: true is overridden by {FILE} at {pin[:12]} ({why}); "
679
+ f"the evidence-only rule binds the tag and the evidence")
680
+ return f"{FILE} at {pin[:12]} {why}; the evidence-only rule binds the tag and the evidence"
681
+
682
+
683
+ def receipt_checker(blob) -> str:
684
+ """The `checker` text of a lower-tier receipt's bytes ('' when absent): the files it names are build
685
+ inputs for the docs-only rule. Index passes it explicitly, so the rule never reads a working tree."""
686
+ try:
687
+ chk = json.loads(blob).get("checker")
688
+ except (ValueError, AttributeError, TypeError):
689
+ return ""
690
+ return chk if isinstance(chk, str) else ""
691
+
692
+
693
+ def descends(clone: pathlib.Path, bound: str, head: str, record: dict | None = None,
694
+ checker: str = "") -> tuple[bool, str, list[str] | None]:
695
+ """The binding rule for the tag and the evidence commits: gate_mod.package_descendant, the rule every
696
+ other consumer applies, when the package opts in (lean-pkg-binding.yaml committed at `bound`, or a
697
+ `record`, docs_record, that says docs_descendants: true); otherwise exactly the evidence-only rule.
698
+ The clone has no registered nested packages, and its formalization.yaml keeps the evidence-only
699
+ rule's stricter reading unless a record opts in. (ok, note, docs_paths)."""
700
+ oi = opt_in(clone, bound, record)
701
+ if oi.rule == "docs-only" or (record is not None and record.get("docs_descendants") is True):
702
+ return gate_mod.package_descendant(clone, bound, head, record or {}, checker=checker or "", nested=(),
703
+ opt_in=oi)
704
+ ok, note = gate_mod.evidence_only_descendant(clone, bound, head)
705
+ return ok, note, None
706
+
707
+
708
+ def find_evidence(clone: pathlib.Path, rel: str, pin: str | None, record: dict | None = None,
709
+ checker: str = "") -> tuple[str, bytes]:
710
+ """(pin, bytes) of the evidence file `rel` as committed in the pin itself or in an
711
+ evidence-only descendant of it (or, when `record` opts in, a docs-only one), searched over every
712
+ ref of the clone. With pin None, the pin is read from the receipt's own `commit` field.
713
+ `checker`: the lower-tier receipt's, unless the blob is a receipt with its own."""
714
+ p = core.git(clone, "log", "--all", "--format=%H", "--", rel)
715
+ for c in [x for x in p.stdout.split() if x]:
716
+ blob = core.git_show_bytes(clone, rel, c)
717
+ if blob is None:
718
+ continue
719
+ bound = pin
720
+ if bound is None:
721
+ try:
722
+ bound = str(json.loads(blob).get("commit") or "")
723
+ except (ValueError, AttributeError):
724
+ continue
725
+ if not core._HEX40.fullmatch(bound):
726
+ continue
727
+ ok, _, _ = descends(clone, bound, c, record, receipt_checker(blob) or checker)
728
+ if ok:
729
+ return bound, blob
730
+ raise core.Fail(f"{rel} is not committed at the pin or in an evidence-only "
731
+ f"{'or docs-only ' if docs_rule(clone, pin, record) else ''}descendant of it "
732
+ f"on any branch; commit and push the evidence first (untracked files do not count)")
733
+
734
+
735
+ def _symlink_components_at(clone: pathlib.Path, commit: str, rel: str) -> list[str]:
736
+ """Path prefixes of `rel` that are symlinks (mode 120000) in the tree at `commit`."""
737
+ parts = pathlib.PurePosixPath(rel).parts
738
+ prefixes = ["/".join(parts[:i]) for i in range(1, len(parts) + 1)]
739
+ p = core.git(clone, "ls-tree", "-r", commit, "--", *prefixes)
740
+ hits = []
741
+ for line in p.stdout.splitlines():
742
+ meta, _, path = line.partition("\t")
743
+ if meta.startswith("120000") and path in prefixes:
744
+ hits.append(path)
745
+ return hits
746
+
747
+
748
+ def _safe_write(clone: pathlib.Path, rel: str, blob: bytes) -> None:
749
+ """Write `blob` at clone/rel, refusing any symlink on the way (never write outside the clone)."""
750
+ if not _is_rel(rel):
751
+ raise core.Fail(f"evidence path {rel!r} is not repository-relative")
752
+ cur = clone
753
+ for part in pathlib.PurePosixPath(rel).parts[:-1]:
754
+ cur = cur / part
755
+ if cur.is_symlink():
756
+ raise core.Fail(f"evidence path {rel!r} crosses a symlink ({cur.relative_to(clone)}); refused")
757
+ if cur.exists() and not cur.is_dir():
758
+ raise core.Fail(f"evidence path {rel!r} crosses a non-directory ({cur.relative_to(clone)}); refused")
759
+ cur.mkdir(exist_ok=True)
760
+ dest = clone / rel
761
+ if dest.is_symlink():
762
+ raise core.Fail(f"evidence path {rel!r} is a symlink; refused")
763
+ if dest.resolve().parent != (clone / rel).parent.resolve() or clone.resolve() not in dest.resolve().parents:
764
+ raise core.Fail(f"evidence path {rel!r} resolves outside the clone; refused")
765
+ dest.write_bytes(blob)
766
+
767
+
768
+ def materialize(clone: pathlib.Path, pin: str, rels: list[str], record: dict | None = None,
769
+ checker: str = "") -> dict[str, bytes]:
770
+ """Check out the pin and write each evidence file from its committed bytes into the
771
+ working tree, so HEAD == pin and the existing validators read exactly those bytes.
772
+ Symlinks are never followed: the tree at the pin is checked for symlink components and
773
+ every write is guarded."""
774
+ checkout_pin(clone, pin)
775
+ out: dict[str, bytes] = {}
776
+ for rel in rels:
777
+ links = _symlink_components_at(clone, pin, rel)
778
+ if links:
779
+ raise core.Fail(f"evidence path {rel!r} crosses a symlink at the pin ({', '.join(links)}); refused")
780
+ _, blob = find_evidence(clone, rel, pin, record, checker)
781
+ _safe_write(clone, rel, blob)
782
+ out[rel] = blob
783
+ return out
784
+
785
+
786
+ def evidence_commit(clone: pathlib.Path, rel: str, pin: str, record: dict | None = None,
787
+ checker: str = "") -> str:
788
+ """The commit (pin, or a descendant under `descends`) whose version of `rel` find_evidence uses."""
789
+ p = core.git(clone, "log", "--all", "--format=%H", "--", rel)
790
+ for c in [x for x in p.stdout.split() if x]:
791
+ blob = core.git_show_bytes(clone, rel, c)
792
+ if blob is None:
793
+ continue
794
+ ok, _, _ = descends(clone, pin, c, record, receipt_checker(blob) or checker)
795
+ if ok:
796
+ return c
797
+ raise core.Fail(f"{rel} is not committed at the pin or in an evidence-only "
798
+ f"{'or docs-only ' if docs_rule(clone, pin, record) else ''}descendant of it")
799
+
800
+
801
+ def reachable_on(clone: pathlib.Path, public_repo: str, shas: list[str]) -> list[str]:
802
+ """Fetch the public repository's branches into refs/remotes/public/ and return the shas
803
+ among `shas` that no public branch contains."""
804
+ p = core.git(clone, "fetch", "--quiet", "--no-tags", public_repo,
805
+ "+refs/heads/*:refs/remotes/public/*")
806
+ if p.returncode != 0:
807
+ raise core.Fail(f"cannot fetch {public_repo} to verify the pin: {p.stderr.strip()[:200]}")
808
+ missing = []
809
+ for sha in shas:
810
+ q = core.git(clone, "for-each-ref", "--contains", sha, "refs/remotes/public")
811
+ if q.returncode != 0 or not q.stdout.strip():
812
+ missing.append(sha)
813
+ return missing
814
+
815
+
816
+ def _private_walk(obj, where):
817
+ """(label, is_key, string) for every mapping key and string value. A key that looks private is
818
+ labelled by position (`<key#i>`), never by its text, both for itself and for what lies below it."""
819
+ if isinstance(obj, str):
820
+ yield where, False, obj
821
+ elif isinstance(obj, dict):
822
+ for i, (k, v) in enumerate(obj.items()):
823
+ k = str(k)
824
+ if PRIVATE_PATH_RE.search(k):
825
+ label = f"{where}.<key#{i}>"
826
+ yield label, True, k
827
+ else:
828
+ label = f"{where}.{k}"
829
+ yield from _private_walk(v, label)
830
+ elif isinstance(obj, list):
831
+ for i, v in enumerate(obj):
832
+ yield from _private_walk(v, f"{where}[{i}]")
833
+
834
+
835
+ def private_string_hits(blob: bytes, where: str) -> list[tuple[str, str, str]]:
836
+ """(field, kind, string) for every mapping key or string value in a JSON document that looks
837
+ private. `field` never contains the private text itself (private keys are positional)."""
838
+ try:
839
+ data = json.loads(blob)
840
+ except ValueError:
841
+ return []
842
+ return [(w, "private local path", s) for w, _key, s in _private_walk(data, where)
843
+ if PRIVATE_PATH_RE.search(s)]
844
+
845
+
846
+ def private_strings_in(blob: bytes, where: str) -> list[str]:
847
+ """String values in a JSON document that look like private local paths."""
848
+ try:
849
+ data = json.loads(blob)
850
+ except ValueError:
851
+ return []
852
+ return [f"{where}: {w} looks like a private local path" + ("" if is_key else f": {s!r}")
853
+ for w, is_key, s in _private_walk(data, where) if PRIVATE_PATH_RE.search(s)]
854
+
855
+
856
+ def mathlib_rev_at(clone: pathlib.Path) -> str | None:
857
+ mf = clone / "lake-manifest.json"
858
+ if not mf.is_file():
859
+ return None
860
+ try:
861
+ data = json.loads(mf.read_text())
862
+ except ValueError:
863
+ raise core.Fail("lake-manifest.json at the pin is not valid JSON") from None
864
+ for p in data.get("packages") or []:
865
+ if str(p.get("name", "")).lower() in ("mathlib", "«mathlib»") and p.get("rev"):
866
+ return str(p["rev"])
867
+ return None
868
+
869
+
870
+ def license_problem(clone: pathlib.Path, spdx: str) -> str | None:
871
+ for n in core.LICENSE_NAMES:
872
+ f = clone / n
873
+ if f.is_file():
874
+ marker = LICENSE_MARKERS.get(spdx)
875
+ if marker and marker not in f.read_text(errors="replace"):
876
+ return f"{n} at the pin does not read like {spdx} (no {marker!r})"
877
+ return None
878
+ return f"no license file ({', '.join(core.LICENSE_NAMES)}) at the pin"
879
+
880
+
881
+ PUBLIC_GATE_PKG = {"gate": {"axioms_allowed": list(core.DEFAULT_AXIOMS)}}
882
+
883
+
884
+ def materialize_report_log(clone: pathlib.Path, pin: str, receipt: dict, lower_rel: str,
885
+ record: dict | None = None, checker: str = "") -> dict[str, bytes]:
886
+ """The lower-tier receipt's sealed verify log (.log or .log.gz beside the receipt) as committed in the
887
+ pin or an evidence-only descendant, written into the clone like every other evidence file so that
888
+ report_log_check hashes those bytes. None committed: refused, as `gate` refuses (a receipt whose
889
+ report_sha256 binds nothing is not evidence; the index keeps the receipts, never the logs)."""
890
+ name = gate_mod.report_log_name(receipt)
891
+ base = pathlib.PurePosixPath(lower_rel).parent
892
+ out: dict[str, bytes] = {}
893
+ for fname in (name, name + gate_mod.REPORT_GZ_SUFFIX):
894
+ rel = str(base / fname)
895
+ try:
896
+ out.update(materialize(clone, pin, [rel], record, checker))
897
+ except core.Fail as e:
898
+ if "is not committed at the pin" not in str(e):
899
+ raise
900
+ if not out:
901
+ raise core.Fail(f"{gate_mod.REPORT_LOG_MISSING}{base / name} (or its {gate_mod.REPORT_GZ_SUFFIX}) is not committed "
902
+ f"at the pin or in an evidence-only descendant of it; without it report_sha256 binds "
903
+ f"nothing. Commit the sealed redacted log byte-exact at that path (a copy kept under "
904
+ f"another name may be copied there when its SHA-256 is the receipt's report_sha256) and "
905
+ f"push it ({gate_mod.REPORT_LOG_RESTORE})")
906
+ return out
907
+
908
+
909
+ def derive(clone: pathlib.Path, pin: str, lower_rel: str | None,
910
+ comp_rel: str | None, record: dict | None = None) -> dict:
911
+ """Validate the receipts at the pin with the registry's own validators. `record`: docs_record's
912
+ opt-in for the evidence lookup (descends). Returns {lower, comparator, lower_ok, comparator_ok,
913
+ mechanism, bytes, failures, checker} (checker: the lower-tier receipt's, for the docs-only rule)."""
914
+ got = materialize(clone, pin, [lower_rel], record) if lower_rel else {}
915
+ checker = receipt_checker(got[lower_rel]) if lower_rel else ""
916
+ if comp_rel:
917
+ got.update(materialize(clone, pin, [comp_rel], record, checker))
918
+ res = {"lower": None, "comparator": None, "lower_ok": False, "comparator_ok": False,
919
+ "mechanism": None, "bytes": got, "failures": [], "checker": checker}
920
+ if lower_rel:
921
+ try:
922
+ res["lower"] = json.loads(got[lower_rel])
923
+ gate_mod.validate_receipt(PUBLIC_GATE_PKG, clone, res["lower"])
924
+ if res["lower"]["commit"] != pin:
925
+ raise core.Fail(f"lower-tier receipt binds {res['lower']['commit'][:12]}, not the pin")
926
+ got.update(materialize_report_log(clone, pin, res["lower"], lower_rel, record, checker))
927
+ gate_mod.report_log_check(clone, res["lower"], clone / lower_rel)
928
+ res["lower_ok"] = True
929
+ except (ValueError, core.Fail) as e:
930
+ res["failures"].append(f"lower-tier receipt {lower_rel}: {e}")
931
+ if comp_rel:
932
+ try:
933
+ res["comparator"] = json.loads(got[comp_rel])
934
+ res["mechanism"] = comparator_mechanism(res["comparator"])
935
+ logs = [c.get("log") for c in res["comparator"].get("configs") or []
936
+ if isinstance(c, dict) and isinstance(c.get("log"), str)]
937
+ got.update(materialize(clone, pin, logs, record, checker))
938
+ lower_commit = res["lower"]["commit"] if res["lower_ok"] else None
939
+ gate_mod.validate_comparator(PUBLIC_GATE_PKG, clone, res["comparator"], lower_commit)
940
+ if res["comparator"]["commit"] != pin:
941
+ raise core.Fail(f"comparator receipt binds {res['comparator']['commit'][:12]}, not the pin")
942
+ res["comparator_ok"] = True
943
+ except (ValueError, core.Fail) as e:
944
+ res["failures"].append(f"comparator receipt {comp_rel}: {e}")
945
+ return res
946
+
947
+
948
+ # --------------------------------------------------------------------------
949
+ # add
950
+
951
+ def https_repo(url: str) -> str:
952
+ url = str(url or "").strip()
953
+ nwo = core.gh_nwo(url)
954
+ if nwo:
955
+ return f"https://github.com/{nwo}"
956
+ if HTTPS_RE.match(url):
957
+ return url[:-4] if url.endswith(".git") else url.rstrip("/")
958
+ raise core.Fail(f"repo {url!r} is not a public https or GitHub URL; pass --repo https://...")
959
+
960
+
961
+ def _repo_key(url: str) -> str:
962
+ u = url.lower().rstrip("/")
963
+ return u[:-4] if u.endswith(".git") else u
964
+
965
+
966
+ def parse_headline(item: str) -> dict:
967
+ parts = [x.strip() for x in str(item).split(" :: ", 3)]
968
+ if len(parts) not in (3, 4) or not all(parts):
969
+ raise core.Fail(f"--headline expects 'Name :: path/File.lean :: One sentence.[ :: ChallengeTheorem]', got {item!r}")
970
+ out = {"name": parts[0], "file": parts[1], "summary": parts[2]}
971
+ if len(parts) == 4:
972
+ out["judged_as"] = parts[3]
973
+ return out
974
+
975
+
976
+ def judged_names(comp, smoke=None) -> set[str]:
977
+ """Theorem and definition names the comparator receipt's configurations judged, leaving out the
978
+ configurations in `smoke` (paths lean-pkg-signoff.json marks as smoke checks: they credit nothing)."""
979
+ names: set[str] = set()
980
+ for c in (comp or {}).get("configs") or []:
981
+ if isinstance(c, dict) and c.get("path") not in set(smoke or ()):
982
+ names.update(str(x) for x in (c.get("theorem_names") or []))
983
+ names.update(str(x) for x in (c.get("definition_names") or []))
984
+ return names
985
+
986
+
987
+ def unjudged_headlines(headline: list[dict], comp, smoke=None) -> list[str]:
988
+ """Headline names whose `judged_as` is missing or not among the judged names (smoke checks excluded)."""
989
+ judged = judged_names(comp, smoke)
990
+ return [h["name"] for h in headline if not (h.get("judged_as") and h["judged_as"] in judged)]
991
+
992
+
993
+ def smoke_at(clone: pathlib.Path, pin: str, comp) -> dict[str, str]:
994
+ """{configuration path: reason} of the smoke checks lean-pkg-signoff.json declares at the pin, at the
995
+ comparator receipt's commit, or at the tip of the clone's default branch (refs/remotes/origin/HEAD): a
996
+ mark at any of them only takes credit away, as for coverage check (comparator_config.smoke_configs).
997
+ Fail when a sidecar there is malformed. A copy-only check (no clone) cannot read the mark."""
998
+ from . import comparator_config as cc
999
+ commit = str((comp or {}).get("commit") or "")
1000
+ return cc.smoke_configs(clone, pin, commit if core._HEX40.fullmatch(commit) else None,
1001
+ "refs/remotes/origin/HEAD")
1002
+
1003
+
1004
+ def headline_problems(clone: pathlib.Path, headline: list[dict]) -> list[str]:
1005
+ out = []
1006
+ for h in headline:
1007
+ f = clone / h["file"]
1008
+ if not f.is_file():
1009
+ out.append(f"headline file {h['file']} is not tracked at the pin")
1010
+ elif not lean_scan.occurs(lean_scan.last_component(h["name"]), f.read_text(errors="replace")):
1011
+ out.append(f"headline {h['name']}: {lean_scan.last_component(h['name'])!r} does not occur in {h['file']}")
1012
+ return out
1013
+
1014
+
1015
+ def at_pin_problems(clone: pathlib.Path, entry: dict, receipts: dict,
1016
+ record: dict | None = None) -> list[str]:
1017
+ """Checks shared by add and check: toolchain, manifest, license, tag, headline. The tag is bound by
1018
+ `descends` (the docs-only rule too when `record`, docs_record, opts in)."""
1019
+ out = []
1020
+ tc = (clone / "lean-toolchain").read_text().strip() if (clone / "lean-toolchain").is_file() else None
1021
+ if tc != entry["lean_toolchain"]:
1022
+ out.append(f"lean_toolchain {entry['lean_toolchain']!r} != lean-toolchain at the pin {tc!r}")
1023
+ try:
1024
+ rev = mathlib_rev_at(clone)
1025
+ except core.Fail as e:
1026
+ rev = None
1027
+ out.append(str(e))
1028
+ if rev != entry["mathlib_rev"]:
1029
+ out.append(f"mathlib_rev {entry['mathlib_rev']!r} != lake-manifest.json at the pin {rev!r}")
1030
+ lower = receipts.get("lower")
1031
+ if lower and rev and str(lower.get("mathlib_rev")) != rev:
1032
+ out.append(f"lower-tier receipt mathlib_rev {lower.get('mathlib_rev')!r} != lake-manifest.json {rev!r}")
1033
+ lp = license_problem(clone, entry["license_spdx"])
1034
+ if lp:
1035
+ out.append(lp)
1036
+ tag = entry["pin"]["tag"]
1037
+ if tag:
1038
+ p = core.git(clone, "rev-parse", "--verify", "--quiet", f"refs/tags/{tag}^{{commit}}")
1039
+ if p.returncode != 0:
1040
+ out.append(f"tag {tag!r} does not exist in the repository")
1041
+ else:
1042
+ pin, head, checker = entry["pin"]["commit"], p.stdout.strip(), receipts.get("checker") or ""
1043
+ ok, note, _ = descends(clone, pin, head, record, checker)
1044
+ if not ok:
1045
+ out.append(f"tag {tag!r} is neither the pin nor an evidence-only descendant of it"
1046
+ + (f" ({note})" if docs_rule(clone, pin, record)
1047
+ else tag_docs_hint(clone, pin, head, checker, entry["name"], record)))
1048
+ out += headline_problems(clone, entry["headline"])
1049
+ return out
1050
+
1051
+
1052
+ def tag_docs_hint(clone: pathlib.Path, pin: str, head: str, checker: str, name: str,
1053
+ record: dict | None = None) -> str:
1054
+ """Without the opt-in: the clauses saying why the docs-only rule did not bind the tag. When it would
1055
+ admit the tag: the routes (lean-pkg-binding.yaml committed at the pin, or the registry record). Always:
1056
+ a lean-pkg-binding.yaml added after the pin (it grants nothing), a file at the pin that does not opt in,
1057
+ the record's veto."""
1058
+ from .binding_file import FILE, SCHEMA
1059
+ if not core._is_ancestor(clone, pin, head):
1060
+ return ""
1061
+ oi = opt_in(clone, pin, record)
1062
+ out = ""
1063
+ ok, note, _ = gate_mod.docs_only_descendant(clone, pin, head, {}, checker, opted="not opted in")
1064
+ if ok and oi.file_state != "absent": # the file at the pin decided: its notes say how
1065
+ out = f"; it is a {note}"
1066
+ elif ok:
1067
+ out = (f"; it is a {note}, which binds only when {FILE} committed at the pin opts in (schema: {SCHEMA}, "
1068
+ f"docs_descendants: true; docs/receipts.md#docs-only-descendants-opt-in), or the package's "
1069
+ f"registry record opts in (docs_descendants: true, `lean-pkg update {name} "
1070
+ f"--accept-docs-descendants --reason R`) and index runs with that registry")
1071
+ out += "".join(f"; {n}" for n in oi.notes)
1072
+ if oi.file_state == "absent" and core.tracked_at(clone, FILE, head):
1073
+ out += f"; {FILE} was added after {pin[:12]}; the opt-in is read at the bound commit only"
1074
+ if record is not None and record.get("docs_descendants") is False and not oi.notes:
1075
+ out += "; the registry record refuses the docs-only rule (docs_descendants: false)"
1076
+ return out
1077
+
1078
+
1079
+ def prior_art_notes(clone: pathlib.Path, headline: list[dict]) -> list[str]:
1080
+ """Advisory: headline items that no prior-art record at the pin names. A record under
1081
+ docs/prior-art/*.md counts for a headline when it contains the last component of its name."""
1082
+ d = clone / "docs" / "prior-art"
1083
+ texts = [p.read_text(errors="replace") for p in sorted(d.glob("*.md"))] if d.is_dir() else []
1084
+ missing = [h["name"] for h in headline
1085
+ if not any(lean_scan.occurs(lean_scan.last_component(h["name"]), t) for t in texts)]
1086
+ if not missing:
1087
+ return []
1088
+ return [f"note: no prior-art record under docs/prior-art/ at the pin names {', '.join(missing)} "
1089
+ f"(advisory; `lean-pkg search TERM --record` writes one)"]
1090
+
1091
+
1092
+ def do_index_add(root: pathlib.Path, events_p: pathlib.Path | None, reg: dict | None,
1093
+ name: str, opts: dict, opt_in_reg: dict | None = None) -> tuple[list[str], dict]:
1094
+ """`opt_in_reg`: the registry docs_record reads the docs-only opt-in from (default: `reg`)."""
1095
+ if not NAME_RE.fullmatch(name):
1096
+ raise core.Fail(f"bad entry name {name!r}")
1097
+ d = root / name
1098
+ replaced = None
1099
+ if (d / ENTRY_FILE).exists():
1100
+ if not opts.get("replace"):
1101
+ raise core.Fail(f"index entry {name!r} already exists at {d / ENTRY_FILE}; to re-pin it, pass "
1102
+ f"--replace (its built_on credits are carried over) and change it by pull request")
1103
+ replaced = load_entry(d / ENTRY_FILE)
1104
+ elif opts.get("replace"):
1105
+ raise core.Fail(f"--replace: there is no index entry {name!r} at {d / ENTRY_FILE} to replace")
1106
+ built_on, built_on_from = None, None
1107
+ if opts.get("built_on_file"):
1108
+ built_on = load_built_on_file(opts["built_on_file"]) or None
1109
+ built_on_from = f"from {opts['built_on_file']}" if built_on else None
1110
+ elif replaced is not None and replaced.get("built_on"):
1111
+ built_on = normalize_built_on(replaced["built_on"])
1112
+ built_on_from = "carried over from the replaced entry"
1113
+ pkg = core.get_pkg(reg, name) if reg is not None else {}
1114
+ gate = pkg.get("gate") or {}
1115
+ repo = https_repo(opts.get("repo") or pkg.get("repo"))
1116
+ lower_rel = opts.get("lower") or gate.get("receipt")
1117
+ comp_rel = opts.get("comparator") or gate.get("comparator")
1118
+ if not lower_rel and not comp_rel:
1119
+ raise core.Fail("no receipt: pass --lower and/or --comparator (repo-relative .lean-receipts/ paths)")
1120
+ license_spdx = opts.get("license") or pkg.get("license_spdx")
1121
+ if not license_spdx:
1122
+ raise core.Fail("license_spdx unknown: pass --license SPDX-ID")
1123
+ if not opts.get("headline"):
1124
+ raise core.Fail("at least one --headline 'Name :: path/File.lean :: One sentence.' is required")
1125
+ headline = [parse_headline(h) for h in opts["headline"]]
1126
+ consent_recorded = bool(opts.get("consent_recorded") or pkg.get("consent"))
1127
+ if not consent_recorded:
1128
+ raise core.Fail("consent not recorded: a public listing needs every coauthor's recorded "
1129
+ "consent (ADR-0070 D4); pass --consent-recorded, or record it first with "
1130
+ "`lean-pkg record NAME consent-recorded ...` and use --from-registry")
1131
+ palomar_rows = [p for p in pkg.get("palomar") or []
1132
+ if p.get("id") and p.get("version") and not p.get("withdrawn_at")]
1133
+ doi = None
1134
+ if pkg.get("doi"):
1135
+ doi = {"concept": pkg["doi"].get("concept"),
1136
+ "versions": [{"doi": v["doi"], "tag": v["tag"], "commit": v["commit"]}
1137
+ for v in pkg["doi"].get("versions") or []]}
1138
+ reservoir = (pkg.get("reservoir") or {}).get("url") if isinstance(pkg.get("reservoir"), dict) else None
1139
+ source = opts.get("repo_dir")
1140
+ if not source and pkg.get("local_path") and core.repo_path(pkg).is_dir():
1141
+ source = str(core.repo_path(pkg))
1142
+ record = docs_record(opt_in_reg if opt_in_reg is not None else reg, name, repo)
1143
+ with tempfile.TemporaryDirectory(prefix="lean-pkg-index-") as tmp:
1144
+ clone = clone_at(source or repo, pathlib.Path(tmp) / "pkg")
1145
+ pin, first = find_evidence(clone, lower_rel or comp_rel, None, record)
1146
+ checker = receipt_checker(first) if lower_rel else ""
1147
+ palomar = [{"id": p["id"], "version": int(p["version"])} for p in palomar_rows
1148
+ if p.get("commit") == pin] # a registration at another commit does not grade this pin
1149
+ for other in entry_names(root):
1150
+ if replaced is not None and other == name:
1151
+ continue # the entry being replaced is not a duplicate
1152
+ try:
1153
+ o = load_entry(root / other / ENTRY_FILE)
1154
+ except core.Fail:
1155
+ continue # a broken sibling is check's business, not add's
1156
+ if _repo_key(str(o.get("repo"))) == _repo_key(repo) and \
1157
+ (o.get("pin") or {}).get("commit") == pin:
1158
+ raise core.Fail(f"duplicate: entry {other!r} already lists {repo} at {pin[:12]}")
1159
+ if source and not opts.get("allow_unpushed"):
1160
+ shas = sorted({pin, *[evidence_commit(clone, r, pin, record, checker)
1161
+ for r in (lower_rel, comp_rel) if r]})
1162
+ missing = reachable_on(clone, repo, shas)
1163
+ if missing:
1164
+ raise core.Fail(f"commit(s) {', '.join(s[:12] for s in missing)} not reachable from any branch "
1165
+ f"of {repo}; push the pin and the evidence first (or pass --allow-unpushed "
1166
+ f"for a provisional entry that `index check --clone` will refuse until pushed)")
1167
+ res = derive(clone, pin, lower_rel, comp_rel, record)
1168
+ if res["failures"]:
1169
+ raise core.Fail("; ".join(res["failures"]))
1170
+ notes = prior_art_notes(clone, headline)
1171
+ leaks = [x for r in (lower_rel, comp_rel) if r for x in private_strings_in(res["bytes"][r], r)]
1172
+ if leaks:
1173
+ raise core.Fail("receipt copies are public; refused: " + "; ".join(leaks)
1174
+ + " (set COMPARATOR_RECEIPT_HOST_LABEL / use public-safe checker strings)")
1175
+ coverage_note = None
1176
+ comparator_covers = res["comparator_ok"]
1177
+ if res["comparator_ok"]:
1178
+ smoke = smoke_at(clone, pin, res["comparator"])
1179
+ unjudged = unjudged_headlines(headline, res["comparator"], smoke)
1180
+ if unjudged:
1181
+ msg = (f"headline theorem(s) {', '.join(unjudged)} not judged by the comparator receipt "
1182
+ f"(judged: {', '.join(sorted(judged_names(res['comparator'], smoke))) or 'none'}"
1183
+ f"{'; smoke checks credit nothing: ' + ', '.join(sorted(smoke)) if smoke else ''}); "
1184
+ f"give each headline its Challenge name as a fourth '::' part")
1185
+ if not res["lower_ok"]:
1186
+ raise core.Fail(msg + "; a comparator-only entry needs every headline judged")
1187
+ comparator_covers = False
1188
+ coverage_note = msg + "; trust is lower-tier"
1189
+ trust = compute_trust(res["lower_ok"], comparator_covers, palomar)
1190
+ entry = {
1191
+ "schema": ENTRY_SCHEMA, "name": name, "repo": repo,
1192
+ "pin": {"commit": pin, "tag": opts.get("tag")},
1193
+ "lean_toolchain": (clone / "lean-toolchain").read_text().strip(),
1194
+ "mathlib_rev": mathlib_rev_at(clone),
1195
+ "license_spdx": license_spdx, "trust": trust,
1196
+ "receipts": {"lower": lower_rel or None, "comparator": comp_rel or None},
1197
+ "headline": headline,
1198
+ "claims": index_claims(name, headline, trust, conditional_at(clone, pin, res, headline)),
1199
+ "palomar": palomar, "doi": doi, "reservoir": reservoir,
1200
+ "formalization_yaml": opts.get("formalization_yaml") or pkg.get("formalization_yaml"),
1201
+ **({"built_on": built_on} if built_on else {}),
1202
+ "fields": list(opts.get("fields") or []),
1203
+ "consent": {"recorded": consent_recorded},
1204
+ "added": {"at": core.now_iso(), "by": opts["by"]},
1205
+ "notes": opts.get("notes") or "",
1206
+ }
1207
+ errors = validate_entry(entry, name)
1208
+ errors += at_pin_problems(clone, entry, res, record)
1209
+ if errors:
1210
+ raise core.Fail("index entry refused: " + "; ".join(errors))
1211
+ if replaced is not None and (d / RECEIPTS_DIR).is_dir():
1212
+ for old in (d / RECEIPTS_DIR).iterdir(): # the replaced entry's copies; the new ones follow
1213
+ if old.is_file():
1214
+ old.unlink()
1215
+ (d / RECEIPTS_DIR).mkdir(parents=True, exist_ok=True)
1216
+ copied = []
1217
+ for rel in (lower_rel, comp_rel):
1218
+ if rel:
1219
+ (d / RECEIPTS_DIR / pathlib.PurePosixPath(rel).name).write_bytes(res["bytes"][rel])
1220
+ copied.append(f"{name}/{RECEIPTS_DIR}/{pathlib.PurePosixPath(rel).name}")
1221
+ (d / ENTRY_FILE).write_text(dump_entry(entry))
1222
+ out = [f"{name}: index entry written at {d / ENTRY_FILE} (trust {trust}, pin {pin[:12]}"
1223
+ + (f", {res['mechanism']} comparator" if res["mechanism"] else "") + ")",
1224
+ f"receipts copied: {', '.join(copied)}"]
1225
+ if replaced is not None:
1226
+ out.append(f"replaced the previous entry (pin {str((replaced.get('pin') or {}).get('commit'))[:12]})")
1227
+ if built_on:
1228
+ out.append(f"built_on: {len(built_on)} credit(s) {built_on_from}: "
1229
+ + ", ".join(c["name"] for c in built_on))
1230
+ elif replaced is not None and opts.get("built_on_file"):
1231
+ out.append("built_on: none (the --built-on-file list is empty)")
1232
+ if coverage_note:
1233
+ out.append(coverage_note)
1234
+ if source and opts.get("allow_unpushed"):
1235
+ out.append("provisional: --allow-unpushed skipped the public-repository check; "
1236
+ "`index check --clone` will fail until the pin and evidence are pushed")
1237
+ if events_p is not None:
1238
+ lock_reg = opts.get("registry_lock") # the clone above runs unlocked; the append under the lock
1239
+ with core.registry_lock(lock_reg) if lock_reg else contextlib.nullcontext():
1240
+ core.append_event(events_p, core.now_iso(), name, "index-added", repo=repo,
1241
+ commit=pin, trust=trust, index=str(root))
1242
+ else:
1243
+ out.append("no event log (no registry here and no --events): index-added not recorded")
1244
+ return out, {"ok": True, "name": name, "event": "index-added", "trust": trust,
1245
+ "commit": pin, "mechanism": res["mechanism"], "entry": str(d / ENTRY_FILE),
1246
+ "receipts": copied, "notes": notes, "replaced": replaced is not None,
1247
+ "built_on": [c["name"] for c in built_on or []]}
1248
+
1249
+
1250
+ # --------------------------------------------------------------------------
1251
+ # CLI glue: lean_pkg.cli.main calls add_parsers(sub, add_json)
1252
+
1253
+ def _emit(args, out: list[str], payload: dict, rc: int = 0) -> int:
1254
+ if args.json_out:
1255
+ core.print_json(payload)
1256
+ else:
1257
+ print("\n".join(out))
1258
+ return rc
1259
+
1260
+
1261
+ def cmd_index(args) -> int:
1262
+ fn = getattr(args, "index_fn", None)
1263
+ if fn is None:
1264
+ raise core.UsageError("index needs an action: add | check | render | migrate")
1265
+ return fn(args)
1266
+
1267
+
1268
+ def opt_in_registry(args) -> dict | None:
1269
+ """The registry docs_record reads the docs-only opt-in from: the one --registry / $LEAN_PKG_REGISTRY /
1270
+ the user default resolves to, when it exists and loads; else None (the evidence-only rule)."""
1271
+ reg_path = core.registry_path(args)
1272
+ if not reg_path.is_file():
1273
+ return None
1274
+ try:
1275
+ return core.load_registry(reg_path)
1276
+ except core.Fail:
1277
+ return None
1278
+
1279
+
1280
+ def run_add(args) -> int:
1281
+ root = index_root(args)
1282
+ reg_path = core.registry_path(args)
1283
+ reg = core.load_registry(reg_path) if args.from_registry else None
1284
+ events_p = core.events_path(args) if (args.events or reg_path.is_file()) else None
1285
+ opts = {"repo": args.repo, "tag": args.tag, "lower": args.lower,
1286
+ "comparator": args.comparator, "license": args.license,
1287
+ "headline": args.headline, "fields": args.field_tag,
1288
+ "formalization_yaml": args.formalization_yaml,
1289
+ "consent_recorded": args.consent_recorded, "by": args.by,
1290
+ "notes": args.notes, "repo_dir": args.repo_dir,
1291
+ "allow_unpushed": args.allow_unpushed,
1292
+ "replace": args.replace, "built_on_file": args.built_on_file,
1293
+ "registry_lock": reg_path if reg_path.is_file() else None}
1294
+ out, payload = do_index_add(root, events_p, reg, args.name, opts,
1295
+ opt_in_reg=reg if reg is not None else opt_in_registry(args))
1296
+ rc = _emit(args, out, payload)
1297
+ if not args.json_out:
1298
+ for note in payload["notes"]: # advisory: stderr, so stdout's last line is the result
1299
+ print(note, file=sys.stderr)
1300
+ return rc
1301
+
1302
+
1303
+ def _parser_add(isub, common) -> None:
1304
+ a = isub.add_parser("add", help="write <index>/<name>/entry.yaml from a clone at the pin")
1305
+ a.add_argument("name")
1306
+ a.add_argument("--from-registry", action="store_true",
1307
+ help="start from the registry row (repo, receipts, license, palomar, doi, reservoir)")
1308
+ a.add_argument("--repo-dir", default=None, help="local clone to read from (never modified)")
1309
+ a.add_argument("--url", dest="repo", metavar="URL", default=None,
1310
+ help="public https URL (a GitHub ssh URL is converted)")
1311
+ a.add_argument("--tag", default=None, help="release tag at the pin or an evidence-only descendant (or a docs-only one "
1312
+ "when lean-pkg-binding.yaml at the pin opts in)")
1313
+ a.add_argument("--lower", default=None, metavar="REL", help="lower-tier receipt, .lean-receipts/...json")
1314
+ a.add_argument("--comparator", default=None, metavar="REL", help="comparator receipt, .lean-receipts/...json")
1315
+ a.add_argument("--license", default=None, metavar="SPDX")
1316
+ a.add_argument("--headline", action="append", metavar="'NAME :: FILE :: SUMMARY'")
1317
+ a.add_argument("--field-tag", action="append", metavar="TAG", help="free field tag (repeatable)")
1318
+ a.add_argument("--formalization-yaml", default=None, metavar="REL")
1319
+ a.add_argument("--consent-recorded", action="store_true",
1320
+ help="every coauthor agreed to the listing (the pointer stays private)")
1321
+ a.add_argument("--by", required=True, help="public handle of the person adding the entry")
1322
+ a.add_argument("--allow-unpushed", action="store_true",
1323
+ help="do not verify that the pin and evidence are on the public repository (provisional entry)")
1324
+ a.add_argument("--notes", default="")
1325
+ a.add_argument("--built-on-file", default=None, metavar="FILE",
1326
+ help="YAML list of credits for third-party Lean code the package builds on "
1327
+ "(name, url, authors; optional license, pin, relation, note); [] for none")
1328
+ a.add_argument("--replace", action="store_true",
1329
+ help="replace an existing entry of this name (a re-pin); its built_on is carried over "
1330
+ "unless --built-on-file is given")
1331
+ common(a, run_add)
1332
+
1333
+
1334
+ def add_parsers(sub, add_json) -> None:
1335
+ s = sub.add_parser("index", help="the public catalog: add | check | render | migrate")
1336
+ add_json(s)
1337
+ s.set_defaults(fn=cmd_index, index_fn=None)
1338
+ isub = s.add_subparsers(dest="index_cmd")
1339
+
1340
+ def common(p, fn) -> None:
1341
+ p.add_argument("--index", default=None,
1342
+ help=f"index root (default: ${INDEX_ENV}, else {DEFAULT_INDEX_DIR}/ beside the "
1343
+ f"registry when present, else ./{DEFAULT_INDEX_DIR})")
1344
+ add_json(p)
1345
+ p.set_defaults(fn=cmd_index, index_fn=fn)
1346
+
1347
+ _parser_add(isub, common)
1348
+ _parser_check(isub, common)
1349
+ _parser_render(isub, common)
1350
+ _parser_migrate(isub, common)
1351
+
1352
+
1353
+ PALOMAR_ENTRY_URL = "https://data.palomar-registry.org/entries/{id}-v{version}.json"
1354
+
1355
+
1356
+ # --------------------------------------------------------------------------
1357
+ # network (tests monkeypatch these; None means unreachable)
1358
+
1359
+ def palomar_entry_fetch(entry_id: str, version: int):
1360
+ """The Palomar entry JSON (dict) on 200, the HTTP status (int) otherwise, None when unreachable.
1361
+ Tests monkeypatch this."""
1362
+ req = urllib.request.Request(PALOMAR_ENTRY_URL.format(id=entry_id, version=version),
1363
+ headers={"User-Agent": "lean-pkg"})
1364
+ try:
1365
+ with urllib.request.urlopen(req, timeout=10) as r:
1366
+ try:
1367
+ return json.loads(r.read().decode("utf-8"))
1368
+ except ValueError:
1369
+ return int(r.status)
1370
+ except urllib.error.HTTPError as e:
1371
+ return int(e.code)
1372
+ except (urllib.error.URLError, TimeoutError, OSError):
1373
+ return None
1374
+
1375
+
1376
+ def network_checks(entry: dict) -> tuple[dict, list[str]]:
1377
+ """({"palomar": state, "reservoir": state}, failures). state: verified | skipped | failed | n/a.
1378
+ Unreachable is `skipped`: never a failure and never a pass."""
1379
+ states = {"palomar": "n/a", "reservoir": "n/a"}
1380
+ failures: list[str] = []
1381
+ if entry.get("palomar"):
1382
+ seen = []
1383
+ for p in entry["palomar"]:
1384
+ got = palomar_entry_fetch(p["id"], p["version"])
1385
+ seen.append(got)
1386
+ if got is None:
1387
+ continue
1388
+ if not isinstance(got, dict):
1389
+ failures.append(f"palomar {p['id']} v{p['version']}: data.palomar-registry.org answered {got}")
1390
+ continue
1391
+ src = got.get("source") or {}
1392
+ commit = str(src.get("commit") or "")
1393
+ url = str(src.get("repository_url") or "")
1394
+ if commit != entry["pin"]["commit"] or (url and _repo_key(url) != _repo_key(entry["repo"])):
1395
+ failures.append(f"palomar {p['id']} v{p['version']} is registered for "
1396
+ f"{url or '?'} at {commit[:12] or '?'}, not {entry['repo']} at "
1397
+ f"{entry['pin']['commit'][:12]}")
1398
+ states["palomar"] = ("skipped" if any(s is None for s in seen) and not failures
1399
+ else "failed" if failures else "verified")
1400
+ if entry.get("reservoir"):
1401
+ m = core.RESERVOIR_URL_RE.match(entry["reservoir"])
1402
+ st = core.reservoir_listing_status(m.group(1), m.group(2)) if m else 404
1403
+ if st is None:
1404
+ states["reservoir"] = "skipped"
1405
+ elif st == 200:
1406
+ states["reservoir"] = "verified"
1407
+ else:
1408
+ states["reservoir"] = "failed"
1409
+ failures.append(f"reservoir {entry['reservoir']}: API answered {st}")
1410
+ return states, failures
1411
+
1412
+
1413
+ # --------------------------------------------------------------------------
1414
+ # check
1415
+
1416
+ def static_problems(root: pathlib.Path, name: str, entry: dict) -> list[str]:
1417
+ errors = validate_entry(entry, name)
1418
+ if errors:
1419
+ return errors
1420
+ rec = entry["receipts"]
1421
+ copies = {}
1422
+ for k in ("lower", "comparator"):
1423
+ if rec[k]:
1424
+ f = root / name / RECEIPTS_DIR / pathlib.PurePosixPath(rec[k]).name
1425
+ if not f.is_file():
1426
+ errors.append(f"receipts.{k}: copy missing at {f.relative_to(root)}")
1427
+ continue
1428
+ try:
1429
+ copies[k] = json.loads(f.read_text())
1430
+ except ValueError:
1431
+ errors.append(f"receipts.{k}: copy is not valid JSON")
1432
+ continue
1433
+ if copies[k].get("commit") != entry["pin"]["commit"]:
1434
+ errors.append(f"receipts.{k}: copy binds {str(copies[k].get('commit'))[:12]}, "
1435
+ f"not the pin {entry['pin']['commit'][:12]}")
1436
+ comparator_covers = "comparator" in copies
1437
+ if comparator_covers:
1438
+ unjudged = unjudged_headlines(entry["headline"], copies["comparator"])
1439
+ if unjudged:
1440
+ comparator_covers = False
1441
+ if entry["trust"] == "comparator":
1442
+ errors.append(f"headline theorem(s) {', '.join(unjudged)} not judged by the comparator "
1443
+ f"receipt copy (judged: {', '.join(sorted(judged_names(copies['comparator']))) or 'none'})")
1444
+ supported = compute_trust("lower" in copies, comparator_covers, entry["palomar"])
1445
+ if supported is None or TRUST_RANK[entry["trust"]] > TRUST_RANK[supported]:
1446
+ errors.append(f"trust {entry['trust']!r} exceeds its evidence ({supported or 'none'})")
1447
+ return errors
1448
+
1449
+
1450
+ def check_entry(root: pathlib.Path, name: str, source: str | None, clone_it: bool,
1451
+ seen: dict, reg: dict | None = None) -> dict:
1452
+ rep = {"name": name, "ok": False, "trust_stated": None, "trust_computed": None,
1453
+ "mechanism": None, "failures": [], "notes": [], "uncredited_dependencies": [],
1454
+ "network": {"palomar": "n/a", "reservoir": "n/a"}}
1455
+ try:
1456
+ entry = load_entry(root / name / ENTRY_FILE)
1457
+ except core.Fail as e:
1458
+ rep["failures"].append(str(e))
1459
+ return rep
1460
+ rep["trust_stated"] = entry.get("trust")
1461
+ rep["failures"] += static_problems(root, name, entry)
1462
+ if rep["failures"]:
1463
+ return rep
1464
+ key = (_repo_key(entry["repo"]), entry["pin"]["commit"])
1465
+ if key in seen:
1466
+ rep["failures"].append(f"duplicate of entry {seen[key]!r} (same repo and commit)")
1467
+ seen.setdefault(key, name)
1468
+ if not entry["consent"]["recorded"]:
1469
+ rep["notes"].append("consent not recorded: every coauthor must agree before this entry is published")
1470
+ if source is None and not clone_it:
1471
+ rep["notes"].append("static check only: pass --clone (or --repo) to re-derive from bytes")
1472
+ rep["ok"] = not rep["failures"]
1473
+ return rep
1474
+ record = docs_record(reg, name, entry["repo"])
1475
+ at = len(rep["notes"])
1476
+ if record is not None and record.get("docs_descendants") is True:
1477
+ rep["notes"].append(REGISTRY_OPT_IN_NOTE)
1478
+ with tempfile.TemporaryDirectory(prefix="lean-pkg-index-") as tmp:
1479
+ try:
1480
+ clone = clone_at(source or entry["repo"], pathlib.Path(tmp) / "pkg")
1481
+ # what decides at the pin: lean-pkg-binding.yaml there, or the record (no note: neither)
1482
+ note = opt_in_note(clone, entry["pin"]["commit"], record)
1483
+ if len(rep["notes"]) > at:
1484
+ rep["notes"][at] = note
1485
+ elif note is not None:
1486
+ rep["notes"].insert(at, note)
1487
+ res = derive(clone, entry["pin"]["commit"], entry["receipts"]["lower"],
1488
+ entry["receipts"]["comparator"], record)
1489
+ except core.Fail as e:
1490
+ rep["failures"].append(str(e))
1491
+ return rep
1492
+ rep["mechanism"] = res["mechanism"]
1493
+ rep["failures"] += res["failures"]
1494
+ for k in ("lower", "comparator"):
1495
+ rel = entry["receipts"][k]
1496
+ if rel and rel in res["bytes"]:
1497
+ copy = (root / name / RECEIPTS_DIR / pathlib.PurePosixPath(rel).name).read_bytes()
1498
+ if copy != res["bytes"][rel]:
1499
+ rep["failures"].append(f"receipts.{k}: index copy differs from the bytes in the repository")
1500
+ rep["failures"] += at_pin_problems(clone, entry, res, record)
1501
+ if isinstance(entry.get("claims"), list): # index-entry/2: the conditional keys are derived, recomputed
1502
+ try:
1503
+ want = index_claims(entry["name"], entry["headline"], entry["trust"],
1504
+ conditional_at(clone, entry["pin"]["commit"], res, entry["headline"]))
1505
+ except core.Fail as e:
1506
+ want = None
1507
+ rep["failures"].append(f"claims[]: the conditional keys cannot be derived at the pin: {e}")
1508
+ if want is not None and _conditional_keys(entry["claims"]) != _conditional_keys(want):
1509
+ rep["failures"].append(
1510
+ f"claims[]: the conditional keys (status, open_hypotheses) are not what the evidence at the pin "
1511
+ f"gives: stated {_conditional_keys(entry['claims'])}, derived {_conditional_keys(want)} "
1512
+ f"(proposal 0003); re-run `lean-pkg index add`")
1513
+ try:
1514
+ smoke = smoke_at(clone, entry["pin"]["commit"], res["comparator"]) if res["comparator_ok"] else {}
1515
+ except core.Fail as e:
1516
+ rep["failures"].append(str(e))
1517
+ smoke = {}
1518
+ rep["notes"] += built_on_manifest_notes(clone, entry)
1519
+ rep["uncredited_dependencies"] = uncredited_lake_dependencies(clone, entry)
1520
+ rep["notes"] += [f"warning: Lake dependency {d['name']} ({d['url'] or 'no url'}) in lake-manifest.json "
1521
+ f"at the pin has no built_on credit" for d in rep["uncredited_dependencies"]]
1522
+ comparator_covers = res["comparator_ok"]
1523
+ if res["comparator_ok"]:
1524
+ unjudged = unjudged_headlines(entry["headline"], res["comparator"], smoke)
1525
+ if unjudged:
1526
+ comparator_covers = False
1527
+ rep["notes"].append(f"headline theorem(s) {', '.join(unjudged)} not judged by the comparator receipt"
1528
+ + (f" (smoke checks credit nothing: {', '.join(sorted(smoke))})" if smoke else ""))
1529
+ computed = compute_trust(res["lower_ok"], comparator_covers, entry["palomar"])
1530
+ rep["trust_computed"] = computed
1531
+ if computed != entry["trust"]:
1532
+ rep["failures"].append(f"stated trust {entry['trust']!r} != computed {computed!r}"
1533
+ + (" (stated trust exceeds its evidence)"
1534
+ if computed is None or TRUST_RANK[entry["trust"]] > TRUST_RANK[computed]
1535
+ else ""))
1536
+ rep["network"], nf = network_checks(entry)
1537
+ rep["failures"] += nf
1538
+ for k, v in rep["network"].items():
1539
+ if v == "skipped":
1540
+ rep["notes"].append(f"{k} verification skipped: network unreachable")
1541
+ rep["ok"] = not rep["failures"]
1542
+ return rep
1543
+
1544
+
1545
+ def do_index_check(root: pathlib.Path, names: list[str], repo_dir: str | None,
1546
+ clone_it: bool, reg: dict | None = None) -> tuple[list[str], dict, int]:
1547
+ """`reg`: the registry whose records may opt an entry in to the docs-only rule (docs_record)."""
1548
+ if repo_dir and len(names) != 1:
1549
+ raise core.UsageError("--repo needs exactly one NAME")
1550
+ all_names = entry_names(root)
1551
+ targets = names or all_names
1552
+ seen: dict = {}
1553
+ reports = []
1554
+ for n in sorted(set(all_names) - set(targets)): # duplicates are judged against the whole index
1555
+ try:
1556
+ e = load_entry(root / n / ENTRY_FILE)
1557
+ except core.Fail:
1558
+ continue # reported when that entry itself is checked
1559
+ if isinstance(e.get("pin"), dict):
1560
+ seen.setdefault((_repo_key(str(e.get("repo"))), e["pin"].get("commit")), n)
1561
+ for n in targets:
1562
+ if n not in all_names:
1563
+ reports.append({"name": n, "ok": False, "failures": [f"no entry {n!r} under {root}"],
1564
+ "notes": [], "uncredited_dependencies": [], "network": {}, "trust_stated": None,
1565
+ "trust_computed": None, "mechanism": None})
1566
+ continue
1567
+ reports.append(check_entry(root, n, repo_dir, clone_it, seen, reg))
1568
+ ok = all(r["ok"] for r in reports)
1569
+ summary = (f"{len(reports)} entr{'y' if len(reports) == 1 else 'ies'} checked: "
1570
+ + ("all pass" if ok else "FAILED"))
1571
+ lines = [summary] # #44: the verdict before the per-entry lines, and again last
1572
+ for r in reports:
1573
+ tag = "PASS" if r["ok"] else "FAIL"
1574
+ what = r.get("trust_computed") or r.get("trust_stated") or "?"
1575
+ mech = f", {r['mechanism']}" if r.get("mechanism") else ""
1576
+ lines.append(f"{tag} {r['name']} ({what}{mech})")
1577
+ lines += [f" fail: {x}" for x in r["failures"]] + [f" note: {x}" for x in r["notes"]]
1578
+ lines.append(summary)
1579
+ mode = "bytes" if (repo_dir or clone_it) else "static"
1580
+ return lines, {"ok": ok, "mode": mode, "index": str(root), "entries": reports}, (0 if ok else 1)
1581
+
1582
+
1583
+ def run_check(args) -> int:
1584
+ out, payload, rc = do_index_check(existing_index_root(args), args.names, args.repo_dir, args.clone,
1585
+ opt_in_registry(args) if (args.repo_dir or args.clone) else None)
1586
+ return _emit(args, out, payload, rc)
1587
+
1588
+
1589
+ def _parser_check(isub, common) -> None:
1590
+ c = isub.add_parser("check", help="static check, or re-derive entries from bytes at the pin; exit 0/1/2")
1591
+ c.add_argument("names", nargs="*", metavar="NAME")
1592
+ c.add_argument("--clone", action="store_true", help="clone each entry's repo at the pin into a temp dir")
1593
+ c.add_argument("--repo", dest="repo_dir", metavar="DIR", default=None,
1594
+ help="local clone for a single NAME (never modified)")
1595
+ common(c, run_check)
1596
+
1597
+
1598
+ RENDER_BANNER = ("<!-- machine-generated by `lean-pkg index render` from index/*/entry.yaml; "
1599
+ "do not hand-edit -->")
1600
+
1601
+
1602
+ # --------------------------------------------------------------------------
1603
+ # render
1604
+
1605
+ def _cell(s: str) -> str:
1606
+ return str(s).replace("|", "\\|").replace("\n", " ")
1607
+
1608
+
1609
+ def _authors(names: list[str]) -> str:
1610
+ names = [_cell(a) for a in names]
1611
+ return names[0] if len(names) == 1 else ", ".join(names[:-1]) + " and " + names[-1]
1612
+
1613
+
1614
+ def render_index(root: pathlib.Path) -> str:
1615
+ rows, claim_rows, credit_rows = [], [], []
1616
+ legacy = False
1617
+ for n in entry_names(root):
1618
+ e = load_entry(root / n / ENTRY_FILE)
1619
+ errors = validate_entry(e, n)
1620
+ if errors:
1621
+ raise core.Fail(f"cannot render: entry {n!r} is invalid: " + "; ".join(errors))
1622
+ trust = e["trust"]
1623
+ if trust == "comparator" and e["receipts"]["comparator"]:
1624
+ f = root / n / RECEIPTS_DIR / pathlib.PurePosixPath(e["receipts"]["comparator"]).name
1625
+ try:
1626
+ mech = comparator_mechanism(json.loads(f.read_text())) if f.is_file() else None
1627
+ except ValueError:
1628
+ raise core.Fail(f"cannot render: receipt copy for {n!r} is not valid JSON") from None
1629
+ if mech in ("legacy", "toolchain"):
1630
+ trust = f"comparator ({mech})"
1631
+ legacy = legacy or mech == "legacy"
1632
+ tc = e["lean_toolchain"].split(":", 1)[-1]
1633
+ head = "<br>".join(f"`{_cell(h['name'])}`: {_cell(h['summary'])}" for h in e["headline"])
1634
+ commit = e["pin"]["commit"]
1635
+ pin = f"`{commit[:12]}`" + (f" ({_cell(e['pin']['tag'])})" if e["pin"]["tag"] else "")
1636
+ tree = f"{e['repo']}/tree/{commit}" if e["repo"].startswith("https://github.com/") else e["repo"]
1637
+ links = [f"[source at pin]({tree})"]
1638
+ links += [f"[{p['id']} v{p['version']}](https://palomar-registry.org/entries/{p['id']})"
1639
+ for p in e["palomar"]]
1640
+ if e["doi"] and e["doi"]["versions"]:
1641
+ links.append(f"[DOI](https://doi.org/{e['doi']['versions'][-1]['doi']})")
1642
+ if e["reservoir"]:
1643
+ links.append(f"[Reservoir]({e['reservoir']})")
1644
+ credits = e.get("built_on") or []
1645
+ built = "<br>".join(f"[{_cell(c['name'])}]({c['url']}) by {_authors(c['authors'])}" for c in credits)
1646
+ for c in credits:
1647
+ credit_rows.append(
1648
+ f"| {_cell(n)} | [{_cell(c['name'])}]({c['url']}) | {_authors(c['authors'])} | "
1649
+ f"{c.get('relation') or ''} | {_cell(c.get('license') or '')} | "
1650
+ + (f"`{c['pin'][:12]}`" if c.get("pin") else "") + f" | {_cell(c.get('note') or '')} |")
1651
+ rows.append(f"| [{_cell(n)}]({e['repo']}) | {trust_text(trust, e.get('claims') or [])} | {_cell(tc)} | "
1652
+ f"{head} | {built} | {pin} | {' · '.join(links)} |")
1653
+ claim_rows += [f"| `{_cell(c['id'])}` | `{_cell(c['decl'])}` | {c['kind']} | {trust_text(c['trust'], [c])} |"
1654
+ for c in e.get("claims") or []]
1655
+ out = [RENDER_BANNER, "", "# lean-pkg index", "",
1656
+ "Generated by `lean-pkg index render` from `index/<name>/entry.yaml`. Do not edit this "
1657
+ "file by hand: change the entry and re-render. Every row can be re-derived with "
1658
+ "`lean-pkg index check --clone NAME`.", ""]
1659
+ if not rows:
1660
+ out.append("No entries yet.")
1661
+ else:
1662
+ out += ["| Package | Trust | Toolchain | Headline theorem | Built on | Pin | Links |",
1663
+ "|---|---|---|---|---|---|---|", *rows]
1664
+ if legacy:
1665
+ out += ["", "`comparator (legacy)`: checked with the pinned comparator stack; it is not "
1666
+ "predictive of Palomar acceptance, which runs the toolchain mechanism."]
1667
+ if credit_rows:
1668
+ out += ["", "## Built on", "",
1669
+ "Third-party Lean code each package depends on (`depends-on`, a Lake dependency) or "
1670
+ "adapts (`adapted-from`, source copied into the package), from the entry's `built_on`. "
1671
+ "Mathlib and its own dependencies are implicit and not listed.", "",
1672
+ "| Package | Library | Authors | Relation | License | Pin | Note |",
1673
+ "|---|---|---|---|---|---|---|", *credit_rows]
1674
+ if claim_rows:
1675
+ out += ["", "## Claims", "",
1676
+ "Derived from each `index-entry/2` headline; `lean-pkg search TERM` finds them.", "",
1677
+ "| Claim | Declaration | Kind | Trust |", "|---|---|---|---|", *claim_rows]
1678
+ out.append("")
1679
+ return "\n".join(out)
1680
+
1681
+
1682
+ def run_render(args) -> int:
1683
+ root = existing_index_root(args, create=bool(getattr(args, "index", None) or args.out))
1684
+ text = render_index(root)
1685
+ dest = pathlib.Path(args.out).expanduser() if args.out else root / "README.md"
1686
+ n = len(entry_names(root))
1687
+ if args.check:
1688
+ current = dest.is_file() and dest.read_text() == text
1689
+ out = [f"{dest}: " + ("current" if current else "STALE; run `lean-pkg index render`")]
1690
+ return _emit(args, out, {"ok": current, "out": str(dest), "current": current}, 0 if current else 1)
1691
+ dest.parent.mkdir(parents=True, exist_ok=True)
1692
+ dest.write_text(text)
1693
+ return _emit(args, [f"index rendered: {dest} ({n} entries)"],
1694
+ {"ok": True, "out": str(dest), "entries": n})
1695
+
1696
+
1697
+ def _parser_render(isub, common) -> None:
1698
+ r = isub.add_parser("render", help="write the Markdown table (default <index>/README.md)")
1699
+ r.add_argument("--out", default=None)
1700
+ r.add_argument("--check", action="store_true", help="exit 1 when the file is stale; write nothing")
1701
+ common(r, run_render)
1702
+
1703
+
1704
+ # --------------------------------------------------------------------------
1705
+ # migrate: rewrite index-entry/1 files as index-entry/2 (claims[] derived from the headline)
1706
+
1707
+ def migrate_entry(name: str, entry: dict) -> dict | None:
1708
+ """The index-entry/2 form of an index-entry/1 entry; None when it is already current."""
1709
+ if entry.get("schema") == ENTRY_SCHEMA:
1710
+ return None
1711
+ if entry.get("schema") != "index-entry/1":
1712
+ raise core.Fail(f"{name}: unknown schema {entry.get('schema')!r}; nothing migrated")
1713
+ new = dict(entry, schema=ENTRY_SCHEMA,
1714
+ claims=index_claims(name, entry.get("headline") or [], entry.get("trust")))
1715
+ errors = validate_entry(new, name)
1716
+ if errors:
1717
+ raise core.Fail(f"{name}: migrated entry would not validate: " + "; ".join(errors))
1718
+ return new
1719
+
1720
+
1721
+ def run_migrate(args) -> int:
1722
+ root = existing_index_root(args)
1723
+ out, stale, done = [], [], []
1724
+ for name in entry_names(root):
1725
+ path = root / name / ENTRY_FILE
1726
+ entry = load_entry(path)
1727
+ new = migrate_entry(name, entry)
1728
+ if new is None:
1729
+ out.append(f"{name}: already {ENTRY_SCHEMA}")
1730
+ continue
1731
+ if args.check:
1732
+ out.append(f"{name}: {entry['schema']} (run `lean-pkg index migrate`)")
1733
+ stale.append(name)
1734
+ continue
1735
+ path.write_text(dump_entry(new))
1736
+ out.append(f"{name}: {entry['schema']} -> {ENTRY_SCHEMA} ({len(new['claims'])} claim(s) derived)")
1737
+ done.append(name)
1738
+ if done:
1739
+ out.append("render the table again: `lean-pkg index render`")
1740
+ if not out:
1741
+ out.append(f"no entries under {root}")
1742
+ rc = 1 if stale else 0
1743
+ return _emit(args, out, {"ok": not stale, "migrated": done, "stale": stale}, rc)
1744
+
1745
+
1746
+ def _parser_migrate(isub, common) -> None:
1747
+ m = isub.add_parser("migrate", help="rewrite index-entry/1 entries as index-entry/2 (claims derived)")
1748
+ m.add_argument("--check", action="store_true", help="exit 1 when an entry is not current; write nothing")
1749
+ common(m, run_migrate)