lean-pkg 0.25.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. lean_pkg/__init__.py +3 -0
  2. lean_pkg/adapters/__init__.py +148 -0
  3. lean_pkg/adapters/github.py +65 -0
  4. lean_pkg/adapters/leansearch.py +68 -0
  5. lean_pkg/adapters/loogle.py +45 -0
  6. lean_pkg/adapters/palomar.py +170 -0
  7. lean_pkg/adapters/reservoir.py +127 -0
  8. lean_pkg/anchor.py +678 -0
  9. lean_pkg/audit.py +716 -0
  10. lean_pkg/binding_file.py +446 -0
  11. lean_pkg/blueprint.py +213 -0
  12. lean_pkg/build_scope.py +282 -0
  13. lean_pkg/ci_github.py +917 -0
  14. lean_pkg/claim_axioms.py +421 -0
  15. lean_pkg/claims.py +1155 -0
  16. lean_pkg/claims_mark.py +197 -0
  17. lean_pkg/cli.py +5208 -0
  18. lean_pkg/cli_parser.py +768 -0
  19. lean_pkg/command_tree.py +615 -0
  20. lean_pkg/comparator_config.py +990 -0
  21. lean_pkg/comparator_contracts.py +382 -0
  22. lean_pkg/comparator_receipt.py +2854 -0
  23. lean_pkg/comparator_stage.py +623 -0
  24. lean_pkg/comparator_types.py +830 -0
  25. lean_pkg/container.py +172 -0
  26. lean_pkg/core.py +1570 -0
  27. lean_pkg/coverage.py +1278 -0
  28. lean_pkg/data/stacks/lts-2026.10.yaml +73 -0
  29. lean_pkg/data/toolchain-advisories.yaml +77 -0
  30. lean_pkg/data/upgrade-breaking.yaml +20 -0
  31. lean_pkg/data/verify-workflow-pins.yaml +14 -0
  32. lean_pkg/deps_closure.py +512 -0
  33. lean_pkg/deps_fill.py +445 -0
  34. lean_pkg/dup_constants.py +448 -0
  35. lean_pkg/exercise.py +828 -0
  36. lean_pkg/exercise_forbid.py +288 -0
  37. lean_pkg/export_paths.py +77 -0
  38. lean_pkg/extract.py +1172 -0
  39. lean_pkg/extract_decls.py +501 -0
  40. lean_pkg/extract_ledger.py +1408 -0
  41. lean_pkg/extract_summary.py +132 -0
  42. lean_pkg/extract_types.py +502 -0
  43. lean_pkg/extract_write.py +138 -0
  44. lean_pkg/formalization.py +1078 -0
  45. lean_pkg/formalization_kept.py +182 -0
  46. lean_pkg/fresh_repo.py +709 -0
  47. lean_pkg/gate.py +2141 -0
  48. lean_pkg/headline.py +211 -0
  49. lean_pkg/help_topics.py +442 -0
  50. lean_pkg/holes.py +289 -0
  51. lean_pkg/host_routes.py +376 -0
  52. lean_pkg/hypotheses.py +788 -0
  53. lean_pkg/index.py +1749 -0
  54. lean_pkg/json_stdout.py +48 -0
  55. lean_pkg/lake_hygiene.py +289 -0
  56. lean_pkg/lean_diag.py +280 -0
  57. lean_pkg/lean_scan.py +1300 -0
  58. lean_pkg/ledger.py +582 -0
  59. lean_pkg/next_step.py +510 -0
  60. lean_pkg/page.py +1831 -0
  61. lean_pkg/page_html.py +153 -0
  62. lean_pkg/palomar.py +316 -0
  63. lean_pkg/palomar_check.py +1027 -0
  64. lean_pkg/port_modules.py +677 -0
  65. lean_pkg/prior_art.py +286 -0
  66. lean_pkg/producer.py +212 -0
  67. lean_pkg/producer_skew.py +208 -0
  68. lean_pkg/public_safety.py +1487 -0
  69. lean_pkg/publish.py +402 -0
  70. lean_pkg/rebase.py +984 -0
  71. lean_pkg/receipt.py +2385 -0
  72. lean_pkg/receipt_check.py +1064 -0
  73. lean_pkg/receipt_ci.py +660 -0
  74. lean_pkg/receipt_systemd.py +890 -0
  75. lean_pkg/recommended.py +232 -0
  76. lean_pkg/report.py +727 -0
  77. lean_pkg/reservoir.py +203 -0
  78. lean_pkg/scaffold.py +588 -0
  79. lean_pkg/schemas/formalization-0.4.schema.json +344 -0
  80. lean_pkg/schemas/formalization-0.4.schema.source.txt +15 -0
  81. lean_pkg/scripts/ClaimAxioms.lean +47 -0
  82. lean_pkg/scripts/ContractsOnly.lean +300 -0
  83. lean_pkg/scripts/DupConstants.lean +149 -0
  84. lean_pkg/scripts/HypProbe.lean +257 -0
  85. lean_pkg/scripts/comparator-check.sh +396 -0
  86. lean_pkg/scripts/verify-comparator.sh +135 -0
  87. lean_pkg/seal_bundle.py +647 -0
  88. lean_pkg/search.py +865 -0
  89. lean_pkg/site_profiles/easley.yaml +10 -0
  90. lean_pkg/site_profiles/github-actions.yaml +12 -0
  91. lean_pkg/sites.py +225 -0
  92. lean_pkg/stacks.py +373 -0
  93. lean_pkg/statements_module.py +217 -0
  94. lean_pkg/templates/Apache-2.0.txt +202 -0
  95. lean_pkg/toolchain_advisories.py +225 -0
  96. lean_pkg/upgrade.py +706 -0
  97. lean_pkg/verify.py +495 -0
  98. lean_pkg-0.25.0.dist-info/METADATA +93 -0
  99. lean_pkg-0.25.0.dist-info/RECORD +103 -0
  100. lean_pkg-0.25.0.dist-info/WHEEL +5 -0
  101. lean_pkg-0.25.0.dist-info/entry_points.txt +5 -0
  102. lean_pkg-0.25.0.dist-info/licenses/LICENSE +202 -0
  103. lean_pkg-0.25.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,990 @@
1
+ # lean-pkg comparator config -- scaffold comparator configuration entries from claims.yaml
2
+ """`lean-pkg comparator config --from-claims NAME [--out comparator.json] [--dry-run]` (#23.6).
3
+
4
+ A package with hundreds of claims and a handful of hand-written comparator entries needs the
5
+ rest listed before anyone can write their Challenge statements. This command adds one
6
+ `theorem_names` entry per claimed theorem or lemma that no tracked comparator configuration
7
+ covers yet, and records what a human still has to do in a `scaffold.todo` list for that configuration
8
+ in the sign-off sidecar `lean-pkg-signoff.json` (holes.py; never in the configuration itself, whose keys
9
+ stay Palomar's six). It never removes, renames or reorders an existing entry or key.
10
+
11
+ The added names are Challenge names, `<Namespace>.<decl>` (default namespace: the package name
12
+ in CamelCase plus `Audit`, as docs/comparator.md recommends). Nothing here writes the Challenge
13
+ or the Solution: until a human states each one in Mathlib vocabulary and bridges it to the
14
+ project theorem, comparator fails on the missing name, which is the intended state. The
15
+ formalization renderer leaves names still listed under `scaffold.todo` out of
16
+ `status.main_results`. A configuration still carrying the deprecated inline `lean_pkg_scaffold` key is
17
+ read as before, but not written: `--migrate-signoff PATH --write` first.
18
+
19
+ Claims come from the registry cache, which must be synced at HEAD (or HEAD an evidence-only
20
+ descendant of the synced commit): `lean-pkg claims sync NAME` first. Or (#13) from a working-copy
21
+ file, `--claims-file PATH`: schema-checked exactly like `claims check --file`, normalized the way
22
+ `claims sync` caches claims (so the generated configuration is the one the registry route would
23
+ produce for the same claims), and never written to the registry. The output names the source.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import hashlib
29
+ import json
30
+ import os
31
+ import pathlib
32
+ import re
33
+ import shlex
34
+
35
+ from . import gate as gate_mod
36
+ from . import core
37
+ from . import holes
38
+ from . import lean_scan
39
+
40
+ SCAFFOLD_KEY = "lean_pkg_scaffold" # deprecated inline key; the scaffold lives in holes.SIDECAR
41
+ NOT_DONE = ["the package lease was not consulted",
42
+ f"the checkout's comparator.json and {holes.SIDECAR} were not written (copy both files there under "
43
+ "the lease, or re-run without --no-registry)",
44
+ "nothing was written to the registry, evidence or receipts"]
45
+ CLAIM_KINDS = ("theorem", "lemma") # propositions a comparator configuration can certify
46
+ STANDARD_AXIOMS = ["propext", "Quot.sound", "Classical.choice"]
47
+ NEW_CONFIG = {"challenge_module": "Challenge", "solution_module": "Solution", "theorem_names": [],
48
+ "definition_names": [], "permitted_axioms": STANDARD_AXIOMS, "enable_nanoda": True}
49
+ NAMESPACE_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_']*(\.[A-Za-z_][A-Za-z0-9_']*)*$")
50
+
51
+
52
+ def default_namespace(name: str) -> str:
53
+ """`rmt-foundations` -> `RmtFoundationsAudit`."""
54
+ parts = [p for p in re.split(r"[^A-Za-z0-9]+", name) if p]
55
+ ns = "".join(p[:1].upper() + p[1:] for p in parts) or "Package"
56
+ return (ns if ns[0].isalpha() else f"P{ns}") + "Audit"
57
+
58
+
59
+ def scaffold_todo_names(cfg: dict, rel: str | None = None, sidecar: dict | None = None) -> set[str]:
60
+ """Theorem names a scaffold still marks TODO (left out of formalization main_results): the sidecar's
61
+ scaffold block for `rel`, else the deprecated inline lean_pkg_scaffold key."""
62
+ block = holes.scaffold_block(cfg, rel, sidecar)
63
+ todo = block.get("todo") if isinstance(block, dict) else None
64
+ return {str(t.get("theorem_name")) for t in todo or [] if isinstance(t, dict) and t.get("theorem_name")}
65
+
66
+
67
+ def _components(name: str) -> list[str] | None:
68
+ """A Lean name's components, a «quoted» plain identifier unquoted (`«foo»` is `foo`); None when malformed."""
69
+ parts = lean_scan.split_name(str(name).strip())
70
+ if parts is None:
71
+ return None
72
+ return [p[1:-1] if p.startswith("«") and re.fullmatch(r"«[A-Za-z_][A-Za-z0-9_'!?]*»", p) else p
73
+ for p in parts]
74
+
75
+
76
+ def qualified_decls(read_file, claims: list[dict]) -> set[str]:
77
+ """The claims' `decl` values that are the fully qualified name of a declaration their `file` declares
78
+ (lean_scan: `namespace`/`section`/`end` tracked, `_root_.` honoured), read with `read_file(rel)`.
79
+ A bare or partial name (`foo` for `Demo.foo`) is not in the set: it does not say which declaration
80
+ it means, so no prefixed configuration name can be credited to it."""
81
+ out: set[str] = set()
82
+ texts: dict[str, set[tuple[str, ...]]] = {}
83
+ for c in claims:
84
+ decl, rel = str(c.get("decl") or ""), c.get("file")
85
+ want = _components(decl)
86
+ if not decl or not rel or want is None:
87
+ continue
88
+ if rel not in texts:
89
+ text = read_file(rel)
90
+ found: set[tuple[str, ...]] = set()
91
+ for row in lean_scan.declarations(text or ""):
92
+ comps = _components(row[2])
93
+ if comps is not None:
94
+ found.add(tuple(comps))
95
+ texts[rel] = found
96
+ if tuple(want) in texts[rel]:
97
+ out.add(decl)
98
+ return out
99
+
100
+
101
+ def covers(names: set[str], decl: str, qualified: bool) -> bool:
102
+ """Does a configured comparator name cover a claim's declaration (#80 ledger, --coverage, next, the
103
+ scaffold)? Only by the full name, and only for a declaration whose fully qualified name the claim
104
+ states (`qualified`, from `qualified_decls`): the name IS the declaration, or it is `<Prefix>.<decl>`,
105
+ the Challenge-namespace form the scaffold writes (`<Package>Audit.<decl>`). A shared last component
106
+ never covers (`A.B.thm` is not `A.C.thm`), and a bare or partial `decl` is covered by nothing."""
107
+ want = _components(decl)
108
+ if not qualified or not want:
109
+ return False
110
+ for n in names:
111
+ have = _components(n)
112
+ if have and len(have) >= len(want) and have[-len(want):] == want:
113
+ return True
114
+ return False
115
+
116
+
117
+ def judged_name(claim) -> str | None:
118
+ """A claim's explicit `judged_as` (claims/1, #CM): the comparator theorem name that judges it; None when unset
119
+ or malformed (the claims schema check reports a malformed one)."""
120
+ j = claim.get("judged_as") if isinstance(claim, dict) else None
121
+ return j.strip() if isinstance(j, str) and j.strip() else None
122
+
123
+
124
+ def mapped_names(claims: list[dict]) -> set[str]:
125
+ """Every name some claim's `judged_as` gives: such a name judges that claim only, so the naming rule never
126
+ credits it to another claim."""
127
+ return {j for c in claims for j in [judged_name(c)] if j}
128
+
129
+
130
+ def claim_covered(names, claim: dict, qualified: set[str], mapped: set[str] | None = None) -> bool:
131
+ """Is `claim` judged by one of the configured `names`? With `judged_as` set: exactly when that name is
132
+ configured, and only for a decl whose fully qualified name the claim states (`qualified`). Without it: the
133
+ naming rule (`covers`) over the names no claim's `judged_as` takes (`mapped`, default from nothing)."""
134
+ decl = str(claim.get("decl") or "")
135
+ j = judged_name(claim)
136
+ if j is not None:
137
+ return decl in qualified and j in set(names)
138
+ return covers(set(names) - set(mapped or ()), decl, decl in qualified)
139
+
140
+
141
+ def credited_names(names, claim: dict, qualified: set[str], mapped: set[str] | None = None) -> set[str]:
142
+ """The configured `names` that judge `claim`, by the rule of `claim_covered` (each name alone): its
143
+ `judged_as` when configured, else every name the naming rule credits to it. The claims ledger reads a
144
+ conditional claim's Challenge facts under exactly one such name (proposal 0003); more than one is
145
+ ambiguous."""
146
+ decl = str(claim.get("decl") or "")
147
+ j = judged_name(claim)
148
+ if j is not None:
149
+ return {j} if decl in qualified and j in set(names) else set()
150
+ return {n for n in set(names) - set(mapped or ()) if covers({n}, decl, decl in qualified)}
151
+
152
+
153
+ def judged_as_problems(claims: list[dict], configured: set[str], qualified: set[str],
154
+ smoke: set[str] | None = None) -> list[str]:
155
+ """What is wrong with the explicit mappings against the configurations at a commit: a `judged_as` that names
156
+ no configured theorem (or only a theorem of a smoke configuration, `smoke`), or that is set on a claim whose
157
+ decl is not the fully qualified name of a declaration its file declares. Each is a false statement about the
158
+ comparator evidence, whatever the claim's status."""
159
+ out = []
160
+ for c in claims:
161
+ j = judged_name(c)
162
+ if j is None:
163
+ continue
164
+ if j not in configured and j in (smoke or ()):
165
+ out.append(f"{c.get('id')}: judged_as {j!r} is a theorem of a smoke configuration only "
166
+ f"({holes.SIDECAR} smoke), which verifies no claim")
167
+ elif j not in configured:
168
+ out.append(f"{c.get('id')}: judged_as {j!r} is in no comparator configuration's theorem_names")
169
+ elif str(c.get("decl") or "") not in qualified:
170
+ out.append(f"{c.get('id')}: judged_as {j!r} is set, but decl {c.get('decl')!r} is not the fully qualified "
171
+ f"name of a declaration in {c.get('file')}")
172
+ return out
173
+
174
+
175
+ COVER_RULE = ("a comparator theorem name covers a claim only when it ends in the claim's whole fully qualified "
176
+ "decl: the decl itself, or <Prefix>.<decl> (FooAudit.Foo.Sec.thm covers the decl Foo.Sec.thm; "
177
+ "FooAudit.Sec.thm, the root Foo dropped, covers nothing)")
178
+
179
+
180
+ def near_miss(name: str, decl: str) -> str | None:
181
+ """How `name` misses `decl` by exactly its leading namespace component, or None (field report #6). Strict
182
+ and explainable: `root-dropped` when the name is the decl without its root (`Sec.thm` for `Foo.Sec.thm`);
183
+ `root-replaced` when the name has the decl's length and differs only in the first component
184
+ (`FooAudit.Sec.thm` for `Foo.Sec.thm`). Every other component must agree, so a different suffix is never
185
+ a near miss. A hint for the user, never a match: `covers` alone decides what is credited."""
186
+ have, want = _components(name), _components(decl)
187
+ if not have or not want or len(want) < 2:
188
+ return None
189
+ if have == want[1:]:
190
+ return "root-dropped"
191
+ if len(have) == len(want) and have[1:] == want[1:] and have[0] != want[0]:
192
+ return "root-replaced"
193
+ return None
194
+
195
+
196
+ def _hint(name: str, decl: str, shape: str) -> dict:
197
+ root = _components(decl)[0]
198
+ if shape == "root-replaced":
199
+ pre = _components(name)[0]
200
+ how, target = f"with its root namespace {root} replaced by {pre}", f"{pre}.{decl}"
201
+ else:
202
+ how, target = f"with its root namespace {root} dropped", f"<Prefix>.{decl}"
203
+ return {"name": name, "decl": decl, "shape": shape, "rename_to": target,
204
+ "hint": (f"{name} looks like the decl {decl} {how}, and covers nothing: the name must end in the "
205
+ f"whole decl, e.g. {target} (rename the Challenge and Solution theorem; never applied "
206
+ f"automatically)")}
207
+
208
+
209
+ def name_hints(names, decls: list[tuple[str, bool]]) -> list[dict]:
210
+ """For each name that covers none of `decls` ((decl, qualified) pairs): the qualified decl it near-misses,
211
+ when exactly one does (an ambiguous near miss gives no hint). [{name, decl, shape, rename_to, hint}]."""
212
+ out = []
213
+ for n in sorted(set(names)):
214
+ if any(covers({n}, d, q) for d, q in decls):
215
+ continue
216
+ cands = sorted({(d, s) for d, q in decls if q for s in [near_miss(n, d)] if s})
217
+ if len(cands) == 1:
218
+ out.append(_hint(n, *cands[0]))
219
+ return out
220
+
221
+
222
+ def decl_hint(names, decl: str, qualified: bool) -> dict | None:
223
+ """The reverse direction (ledger, --coverage): for a qualified decl no name covers, the configured name
224
+ that near-misses it, when exactly one does; else None."""
225
+ if not qualified or covers(set(names), decl, qualified):
226
+ return None
227
+ cands = sorted({(n, s) for n in names for s in [near_miss(n, decl)] if s})
228
+ return _hint(cands[0][0], decl, cands[0][1]) if len(cands) == 1 else None
229
+
230
+
231
+ def hint_lines(hints: list[dict], limit: int = 3, indent: str = " ") -> list[str]:
232
+ """Text lines for name hints: one line when every hint has the same shape and roots, then at most `limit`
233
+ examples and a count of the rest."""
234
+ if not hints:
235
+ return []
236
+ keys = {(h["shape"], _components(h["name"])[0], _components(h["decl"])[0]) for h in hints}
237
+ out = []
238
+ if len(hints) > 1 and len(keys) == 1:
239
+ shape, pre, root = next(iter(keys))
240
+ how, form = ((f"{root} replaced by {pre}", f"{pre}.{root}.<rest>") if shape == "root-replaced" else
241
+ (f"{root} dropped", f"<Prefix>.{root}.<rest>"))
242
+ out.append(f"{indent}hint: all {len(hints)} look like a claim's decl with its root namespace {how}; "
243
+ f"rename them to {form} (the whole decl after the prefix)")
244
+ out += [f"{indent}hint: {h['hint']}" for h in hints[:limit]]
245
+ if len(hints) > limit:
246
+ out.append(f"{indent}hint: ... {len(hints) - limit} more (--json lists every hint)")
247
+ return out
248
+
249
+
250
+ def _load_out(repo: pathlib.Path, rel: str) -> dict | None:
251
+ path = repo / rel
252
+ if path.is_symlink():
253
+ raise core.Fail(f"{rel} is a symlink; refusing to read or write through it")
254
+ if not path.exists():
255
+ return None
256
+ try:
257
+ cfg = json.loads(path.read_text(encoding="utf-8"))
258
+ except ValueError as e:
259
+ raise core.Fail(f"{rel}: not valid JSON ({e}); nothing written") from e
260
+ if not isinstance(cfg, dict):
261
+ raise core.Fail(f"{rel}: not a JSON object; nothing written")
262
+ tn = cfg.get("theorem_names", [])
263
+ if not isinstance(tn, list) or not all(isinstance(n, str) for n in tn):
264
+ raise core.Fail(f"{rel}: theorem_names must be a list of strings; nothing written")
265
+ if SCAFFOLD_KEY in cfg:
266
+ raise core.Fail(f"{rel}: carries the deprecated inline {SCAFFOLD_KEY} key (Palomar refuses it); the "
267
+ f"scaffold now lives in {holes.SIDECAR}: {holes.migrate_command(rel)} first; nothing written")
268
+ return cfg
269
+
270
+
271
+ def load_sidecar(repo: pathlib.Path) -> dict:
272
+ """The working copy's lean-pkg-signoff.json (holes.py), strictly parsed; empty when absent."""
273
+ path = repo / holes.SIDECAR
274
+ if path.is_symlink():
275
+ raise core.Fail(f"{holes.SIDECAR} is a symlink; refusing to read or write through it")
276
+ try:
277
+ return holes.parse_sidecar(path.read_bytes() if path.is_file() else None)
278
+ except ValueError as e:
279
+ raise core.Fail(f"{e}; nothing written") from e
280
+
281
+
282
+ def _atomic_write(path: pathlib.Path, text: str) -> None:
283
+ if path.is_symlink():
284
+ raise core.Fail(f"{path.name} is a symlink; refusing to write through it")
285
+ path.parent.mkdir(parents=True, exist_ok=True)
286
+ tmp = path.with_name(path.name + ".tmp")
287
+ tmp.write_text(text, encoding="utf-8")
288
+ tmp.replace(path)
289
+
290
+
291
+ def synced_claims(pkg: dict, repo: pathlib.Path, checkout: bool = False) -> list[dict]:
292
+ name = pkg["name"]
293
+ rel = pkg.get("claims_file") or "claims.yaml"
294
+ head = core.git_head(repo)
295
+ if head is None:
296
+ raise core.Fail(f"{name}: {repo} is not a git checkout with a commit")
297
+ if not core.tracked_at(repo, rel):
298
+ raise core.Fail(f"{name}: {rel} is not tracked at HEAD {head[:12]}; nothing to scaffold from "
299
+ f"(write claims.yaml, commit it, then `lean-pkg claims sync {name}`)")
300
+ synced = pkg.get("claims_synced_commit")
301
+ if not synced or not pkg.get("claims"):
302
+ raise core.Fail(f"{name}: claims are not synced (`lean-pkg claims sync {name}` first)")
303
+ ok, note, _docs = gate_mod.package_descendant(repo, synced, head, pkg)
304
+ if not ok:
305
+ if checkout: # #31: say how this checkout differs from the commit the claims are bound to
306
+ raise core.Fail(f"{name}: --checkout {repo}: HEAD {head[:12]} is not the claims-synced commit "
307
+ f"{str(synced)[:12]} or an evidence-only descendant of it ({note}); check out "
308
+ f"{synced} there (or `lean-pkg claims sync {name}` at this HEAD)")
309
+ raise core.Fail(f"{name}: claims synced at {str(synced)[:12]}, not at HEAD {head[:12]} "
310
+ f"(`lean-pkg claims sync {name}` first)")
311
+ return [c for c in pkg["claims"] if isinstance(c, dict)]
312
+
313
+
314
+ def file_claims(name: str, path: str) -> tuple[list[dict], dict]:
315
+ """`--claims-file PATH` (#13): the claims of a working-copy claims.yaml, for a worker that cannot run
316
+ `claims sync` (a registry write). Validated exactly like `claims check --file PATH` with NAME (schema,
317
+ and the file's `package` must be NAME), then normalized as `claims sync` caches them. Reads no
318
+ registry and writes nothing. Returns (claims, source)."""
319
+ from .claims import load_claims_text, normalize_claim, schema_check_text
320
+ p = pathlib.Path(str(path)).expanduser()
321
+ if not p.is_file():
322
+ raise core.Fail(f"{name}: --claims-file {path}: claims file not found; nothing written")
323
+ raw = p.read_bytes()
324
+ text = raw.decode("utf-8", errors="replace")
325
+ _n, errors = schema_check_text(text, str(p), name)
326
+ if errors:
327
+ raise core.Fail(f"{name}: --claims-file {p}: {len(errors)} schema error(s) (`lean-pkg claims check --file "
328
+ f"{p} {name}` lists them): " + "; ".join(errors) + "; nothing written")
329
+ claims = [normalize_claim(c) for c in load_claims_text(text, str(p))["claims"]]
330
+ return claims, {"kind": "file", "path": str(p.resolve()), "sha256": hashlib.sha256(raw).hexdigest(),
331
+ "synced_commit": None, "claims": len(claims)}
332
+
333
+
334
+ def _declared_statements(pkg: dict, repo: pathlib.Path, claims_file: str | None) -> str | None:
335
+ """The statements module the claims declare (#369), when lean-pkg accepts it: from --claims-file, else
336
+ from the claims file committed at HEAD; None when none is declared or the module is refused."""
337
+ from . import statements_module as stm
338
+ from .claims import _reader, load_claims_text
339
+ head = core.git_head(repo) or "HEAD"
340
+ if claims_file is None:
341
+ mod, problems = stm.at_commit(repo, pkg.get("claims_file") or "claims.yaml", head)
342
+ return mod if not problems else None
343
+ p = pathlib.Path(str(claims_file)).expanduser()
344
+ mod = stm.declared(load_claims_text(p.read_text(encoding="utf-8", errors="replace"), str(p)))
345
+ return mod if mod is not None and not stm.problems(_reader(repo, head), mod, head) else None
346
+
347
+
348
+ def source_line(src: dict) -> str:
349
+ if src["kind"] == "file":
350
+ return (f"claims source: --claims-file {src['path']} (sha256 {src['sha256']}; schema-checked like "
351
+ f"`claims check --file`; not synced: the registry is unchanged)")
352
+ return f"claims source: registry cache (synced at {str(src['synced_commit'])[:12]})"
353
+
354
+
355
+ def do_config_from_claims(reg: dict, name: str, out: str, dry_run: bool, namespace: str | None,
356
+ agent: str | None, types: dict | None = None, checkout: str | None = None,
357
+ no_registry: bool = False, claims_file: str | None = None
358
+ ) -> tuple[list[str], dict, str | None]:
359
+ """(lines, payload, would-be JSON text or None when nothing changes).
360
+
361
+ `types` (#25), when given: {"mode": "local"|"emit"|"ingest", "emit": F, "from_output": F,
362
+ "lake_env": DIR, "jobs": N, "timeout": S}; see comparator_types.
363
+ `checkout` (#31): the package checkout to use instead of the registry's local_path.
364
+ `no_registry` (#31): scratch mode; `out` is a file outside the checkout, merged from the
365
+ checkout's comparator.json, and the lease is not consulted.
366
+ `claims_file` (#13): read the claims from this working-copy file instead of the synced cache
367
+ (`file_claims`); the payload's claims_source says which was used."""
368
+ pkg = core.get_pkg(reg, name)
369
+ if checkout:
370
+ repo = pathlib.Path(os.path.abspath(pathlib.Path(checkout).expanduser()))
371
+ if not repo.is_dir():
372
+ raise core.Fail(f"{name}: --checkout {checkout}: not a directory")
373
+ else:
374
+ repo = core.repo_path(pkg)
375
+ if not repo.is_dir():
376
+ raise core.Fail(f"{name}: local_path does not exist: {repo}")
377
+ scratch = None
378
+ if no_registry:
379
+ from . import comparator_types as ct
380
+ scratch = ct.emit_path(repo, out, "--out")
381
+ out = "comparator.json"
382
+ rel = gate_mod._safe_rel(out, "--out")
383
+ if not gate_mod.COMPARATOR_CONFIG_RE.match(rel):
384
+ raise core.Fail(f"--out {rel}: not a comparator configuration path (comparator*.json at the "
385
+ f"package root or comparator/config*.json); the runner would not find it")
386
+ from .comparator_receipt import cfg_name_collision
387
+ clash = cfg_name_collision([c for c in gate_mod.head_comparator_configs(repo) if c != rel] + [rel])
388
+ if clash:
389
+ a, b, log = clash
390
+ raise core.Fail(f"--out {rel}: {a} and {b} both map to the log name {log}.log, so "
391
+ f"comparator-receipt would refuse them; choose another --out")
392
+ ns = namespace or default_namespace(name)
393
+ if not NAMESPACE_RE.match(ns):
394
+ raise core.Fail(f"--challenge-namespace {ns!r} is not a Lean name")
395
+ if claims_file is not None:
396
+ if core.git_head(repo) is None:
397
+ raise core.Fail(f"{name}: {repo} is not a git checkout with a commit")
398
+ claims, csource = file_claims(name, claims_file)
399
+ else:
400
+ claims = synced_claims(pkg, repo, checkout=bool(checkout))
401
+ csource = {"kind": "registry", "path": None, "sha256": None,
402
+ "synced_commit": pkg.get("claims_synced_commit"), "claims": len(claims)}
403
+ if checkout and types is not None:
404
+ from . import comparator_types as ct
405
+ ct.lake_dir_rel(repo, types.get("lake_env")) # the Lake package must be there
406
+ existing_cfg = _load_out(repo, rel)
407
+ old_bytes = (repo / rel).read_bytes() if existing_cfg is not None else None
408
+ cfg = dict(existing_cfg) if existing_cfg is not None else json.loads(json.dumps(NEW_CONFIG))
409
+ sidecar = load_sidecar(repo)
410
+ entry = dict(sidecar["configs"].get(rel) or {})
411
+ smoke = set(holes.smoke_paths(sidecar)) | set(smoke_configs(repo, "HEAD"))
412
+ if rel in smoke:
413
+ raise core.Fail(f"--out {rel}: {holes.SIDECAR} marks it as a smoke check, which verifies no claim; "
414
+ f"scaffold the claims into another configuration (--out), or drop the smoke mark; "
415
+ f"nothing written")
416
+ configured: set[str] = set(cfg.get("theorem_names") or [])
417
+ for other in gate_mod.head_comparator_configs(repo):
418
+ if other == rel or other in smoke: # a smoke check's theorems configure no claim
419
+ continue
420
+ try:
421
+ o = json.loads(core.git_show_bytes(repo, f"./{other}") or b"{}")
422
+ except ValueError:
423
+ continue
424
+ if isinstance(o, dict) and isinstance(o.get("theorem_names"), list):
425
+ configured |= {n for n in o["theorem_names"] if isinstance(n, str)}
426
+ block = dict(entry.get("scaffold") or {})
427
+ todo = list(block.get("todo") or [])
428
+ todo_claims = {str(t.get("claim")) for t in todo if isinstance(t, dict)}
429
+ from .claims import _reader
430
+ qualified = qualified_decls(_reader(repo, core.git_head(repo) or "HEAD"), claims)
431
+ existing = skipped = 0
432
+ added: list[dict] = []
433
+ sources: list[dict] = []
434
+ for c in claims:
435
+ decl, cid = str(c.get("decl") or ""), str(c.get("id") or "")
436
+ if c.get("kind") not in CLAIM_KINDS or c.get("status") == "superseded" or not decl:
437
+ skipped += 1
438
+ continue
439
+ if claim_covered(configured, c, qualified, mapped_names(claims)) or f"{ns}.{decl}" in configured \
440
+ or cid in todo_claims:
441
+ existing += 1
442
+ continue
443
+ tname = f"{ns}.{decl}"
444
+ sources.append(c)
445
+ added.append({"theorem_name": tname, "claim": cid, "decl": decl, "file": c.get("file"),
446
+ "challenge": f"TODO: state {tname} in {cfg.get('challenge_module') or 'Challenge'} in "
447
+ f"Mathlib vocabulary, proof `sorry` (what {cid} claims, in the paper's words)",
448
+ "solution": f"TODO: restate {tname} in {cfg.get('solution_module') or 'Solution'} with "
449
+ f"the same type and prove it from {decl} ({c.get('file')})"})
450
+ configured.add(tname)
451
+ counts = {"existing": existing, "added": len(added), "skipped": skipped}
452
+ summary = (f"{name}: {len(claims)} claim(s): {existing} already configured, {len(added)} added, "
453
+ f"{skipped} skipped (not a theorem/lemma, or superseded)")
454
+ payload = {"ok": True, "name": name, "out": str(scratch) if scratch else rel, "dry_run": dry_run, **counts,
455
+ "added_names": [a["theorem_name"] for a in added], "written": False, "claims_source": csource}
456
+ if checkout:
457
+ payload["checkout"] = str(repo)
458
+ if scratch:
459
+ payload["no_registry"] = True
460
+ payload["not_done"] = NOT_DONE
461
+ if not added:
462
+ return [summary, source_line(csource), f"{rel}: nothing to add; nothing written"], payload, None
463
+ lines = [summary, source_line(csource)]
464
+ if types is not None:
465
+ from . import comparator_types as ct
466
+ head = core.git_head(repo) or ""
467
+ cfgd = None
468
+ if types.get("mode") in ("local", "emit"):
469
+ jobs, timeout = ct.check_jobs_timeout(types.get("jobs"), types.get("timeout"))
470
+ cfgd = ct.driver_config(name, head, ct.lake_dir_rel(repo, types.get("lake_env")), sources, jobs, timeout)
471
+ if types.get("mode") == "emit":
472
+ decls = [{k: d[k] for k in ("decl", "claim", "module")} for d in cfgd["decls"]]
473
+ path = ct.emit_path(repo, types["emit"])
474
+ epay = {"ok": True, "name": name, "dry_run": dry_run, "script": str(path), "commit": head,
475
+ "decls": decls, "written": False, "claims_source": csource}
476
+ elines = [summary, source_line(csource), f"{len(decls)} declaration(s) to elaborate at {head[:12]}:"] + \
477
+ [f" {d['decl']} ({d['module'] or 'no module: will be a type_error'})" for d in decls]
478
+ if dry_run:
479
+ return elines + ["dry run: no driver written"], epay, None
480
+ path.parent.mkdir(parents=True, exist_ok=True)
481
+ path.write_text(ct.driver_script(cfgd), encoding="utf-8")
482
+ path.chmod(0o755)
483
+ epay["written"] = True
484
+ return elines + [f"wrote {path}; run: cd {repo} && bash {path} OUT.json, then "
485
+ f"lean-pkg comparator config --from-claims {name} --from-output OUT.json"
486
+ + (f" --claims-file {shlex.quote(csource['path'])}" if csource["kind"] == "file"
487
+ else "")], epay, None
488
+ if types.get("mode") == "local":
489
+ doc, source = ct.run_local(repo, cfgd), "the local run"
490
+ else:
491
+ src = pathlib.Path(types["from_output"]).expanduser()
492
+ doc, source = ct.read_output(src, name, head, types["from_output"]), types["from_output"]
493
+ by_decl = {str(r.get("decl")): r for r in doc["results"]}
494
+ failed = ct.check_partial([by_decl.get(a["decl"]) for a in added], doc,
495
+ "the local run" if types["mode"] == "local" else f"--from-output {source}",
496
+ bool(types.get("allow_partial")))
497
+ statements = _declared_statements(pkg, repo, claims_file)
498
+ for a, c in zip(added, sources, strict=False):
499
+ ct.fill(a, by_decl.get(a["decl"]), str(c.get("summary") or f"what {a['claim']} claims"), source,
500
+ statements)
501
+ ok = sum(1 for a in added if "type" in a)
502
+ nr = sum(1 for a in added if a.get("needs_restatement"))
503
+ rtf = sum(1 for a in added if a.get("restatement_reason") == "round_trip_failed")
504
+ payload["types"] = {"mode": types["mode"], "commit": head, "toolchain": doc.get("toolchain"),
505
+ "prefilled": ok, "type_errors": len(added) - ok, "needs_restatement": nr,
506
+ "extraction_failed": failed, "round_trip_failed": rtf, "allow_partial": bool(types.get("allow_partial")),
507
+ "driver_summary": doc.get("summary") if isinstance(doc.get("summary"), dict) else None}
508
+ lines.append(f"types: {ok} pre-filled from the elaborated type, {len(added) - ok} type error(s) "
509
+ f"(TODO kept, {rtf} of them: printed type failed the round-trip check), "
510
+ f"{nr} marked needs_restatement")
511
+ if failed:
512
+ lines.append(f"types: --allow-partial: {failed} extraction failure(s) kept their TODO lines "
513
+ f"(restatement_reason extraction_failed)")
514
+ cfg["theorem_names"] = list(cfg.get("theorem_names") or []) + [a["theorem_name"] for a in added]
515
+ block.setdefault("generated_by", f"lean-pkg comparator config --from-claims {name}")
516
+ block["note"] = ("comparator fails on each TODO name until its Challenge and Solution exist; remove an "
517
+ "entry from todo once both are written, and this key once todo is empty")
518
+ if types is not None:
519
+ block["types_note"] = ("challenge/solution pre-filled from the elaborated type (Lean pretty-printer); "
520
+ "needs_restatement: true marks entries a human must restate in Mathlib "
521
+ "vocabulary; type_error says why an entry kept its TODO lines")
522
+ block["todo"] = todo + added
523
+ entry["scaffold"] = block
524
+ sidecar["configs"][rel] = entry
525
+ text = json.dumps(cfg, indent=2, ensure_ascii=False) + "\n"
526
+ side_text = holes.dump_sidecar(sidecar)
527
+ payload["signoff_sidecar"] = holes.SIDECAR
528
+ if entry.get("definitions") and old_bytes is not None and \
529
+ entry.get("config_sha256") == holes.sha256_bytes(old_bytes):
530
+ lines.append(f"warning: {rel}'s definition-hole sign-off in {holes.SIDECAR} is bound to its current "
531
+ f"bytes (config_sha256); this change invalidates it until a human re-judges the bodies and "
532
+ f"sets config_sha256 to the new file's sha256")
533
+ if scratch is not None:
534
+ side = scratch.parent / holes.SIDECAR
535
+ payload["sidecar_out"] = str(side)
536
+ if dry_run:
537
+ payload["signoff"] = json.loads(side_text)
538
+ return lines + [f"{scratch} (dry run, nothing written):"], payload, text
539
+ _atomic_write(side, side_text)
540
+ _atomic_write(scratch, text)
541
+ payload["written"] = True
542
+ return lines + [f"wrote {scratch} (scratch: {len(added)} entr{'y' if len(added) == 1 else 'ies'} merged "
543
+ f"into a copy of {rel}) and {side} (its scaffold TODO markers)"] + \
544
+ [f"not done: {n}" for n in NOT_DONE], payload, None
545
+ if dry_run:
546
+ payload["signoff"] = json.loads(side_text)
547
+ return lines + [f"{rel} (dry run, nothing written):"], payload, text
548
+ lease = pkg.get("lease")
549
+ core.refuse_invalid_lease(name, lease)
550
+ if core.lease_live(lease, core.dt.datetime.now(core.dt.timezone.utc)) and agent != lease.get("agent"):
551
+ raise core.Fail(f"{name}: lease held by {lease.get('agent')} — pass --agent {lease.get('agent')}; "
552
+ f"nothing written")
553
+ _atomic_write(repo / holes.SIDECAR, side_text) # the markers first: a config never lacks its TODO list
554
+ _atomic_write(repo / rel, text)
555
+ payload["written"] = True
556
+ return lines + [f"wrote {rel}: {len(added)} theorem name(s), TODO entr{'y' if len(added) == 1 else 'ies'} "
557
+ f"under configs[{rel!r}].scaffold.todo in {holes.SIDECAR} (write each Challenge and "
558
+ f"Solution, then commit both files)"], payload, None
559
+
560
+
561
+ # --------------------------------------------------------------------------
562
+ # --coverage (#26.5): read-only. What the configuration tracked at the gate-bound commit covers, and why a
563
+ # changed or uncommitted configuration cannot certify that tree. Never substitutes a candidate config.
564
+
565
+ def _configs_at(repo: pathlib.Path, rev: str) -> dict[str, bytes]:
566
+ return {c: core.git_show_bytes(repo, f"./{c}", rev) or b"" for c in gate_mod.head_comparator_configs(repo, rev)}
567
+
568
+
569
+ def _worktree_configs(repo: pathlib.Path) -> dict[str, bytes]:
570
+ found = sorted(p for p in repo.glob("comparator*.json") if p.is_file()) + \
571
+ sorted(p for p in (repo / "comparator").glob("config*.json") if p.is_file())
572
+ return {p.relative_to(repo).as_posix(): p.read_bytes() for p in found}
573
+
574
+
575
+ def _sidecar_at(repo: pathlib.Path, rev: str) -> dict:
576
+ """lean-pkg-signoff.json tracked at <rev> (holes.py); empty when not tracked; Fail when malformed."""
577
+ try:
578
+ return gate_mod.sidecar_at(repo, rev)
579
+ except ValueError as e:
580
+ raise core.Fail(str(e)) from e
581
+
582
+
583
+ def smoke_configs(repo: pathlib.Path, *revs: str | None) -> dict[str, str]:
584
+ """{configuration path: reason} of the configurations lean-pkg-signoff.json marks as smoke checks at any
585
+ of `revs` (the receipt's commit and HEAD, say). A mark at either commit takes credit away and nothing
586
+ else, so the union is the safe reading: a mark committed after the receipt removes the smoke theorems'
587
+ credit everywhere it exempts them from the coverage rule. Fail when a sidecar is malformed."""
588
+ out: dict[str, str] = {}
589
+ for rev in dict.fromkeys(r for r in revs if r):
590
+ for rel, why in holes.smoke_paths(_sidecar_at(repo, rev)).items():
591
+ out.setdefault(rel, why)
592
+ return out
593
+
594
+
595
+ def smoke_names(configs: dict[str, bytes], smoke) -> set[str]:
596
+ """The theorem names of the configurations among `configs` whose path is in `smoke`."""
597
+ out: set[str] = set()
598
+ for path, blob in configs.items():
599
+ if path not in set(smoke or ()):
600
+ continue
601
+ try:
602
+ cfg = json.loads(blob or b"{}")
603
+ except ValueError:
604
+ continue
605
+ if isinstance(cfg, dict) and isinstance(cfg.get("theorem_names"), list):
606
+ out |= {n for n in cfg["theorem_names"] if isinstance(n, str)}
607
+ return out
608
+
609
+
610
+ def _names(configs: dict[str, bytes], sidecar: dict | None = None,
611
+ smoke: set[str] | dict | None = None) -> tuple[set[str], set[str]]:
612
+ """(theorem names, of which scaffold TODO names) over a set of configuration blobs; the TODO markers
613
+ from `sidecar` (lean-pkg-signoff.json at the same commit), else a config's deprecated inline key. A
614
+ smoke configuration (the sidecar's `smoke` mark, or a path in `smoke`) contributes no name: a smoke
615
+ check states no result, so its theorems credit no claim."""
616
+ names: set[str] = set()
617
+ todo: set[str] = set()
618
+ skip = set(holes.smoke_paths(sidecar)) | set(smoke or ())
619
+ for path, blob in configs.items():
620
+ if path in skip:
621
+ continue
622
+ try:
623
+ cfg = json.loads(blob or b"{}")
624
+ except ValueError:
625
+ continue
626
+ if isinstance(cfg, dict) and isinstance(cfg.get("theorem_names"), list):
627
+ names |= {n for n in cfg["theorem_names"] if isinstance(n, str)}
628
+ todo |= scaffold_todo_names(cfg, path, sidecar)
629
+ return names, todo
630
+
631
+
632
+ def _classify(claims: list[dict], configs: dict[str, bytes], qualified: set[str],
633
+ sidecar: dict | None = None, smoke: dict | set | None = None) -> dict:
634
+ names, todo = _names(configs, sidecar, smoke)
635
+ real = names - todo
636
+ mapped = mapped_names(claims)
637
+ smoke_thms = smoke_names(configs, set(holes.smoke_paths(sidecar)) | set(smoke or ()))
638
+ out = {"covered": [], "todo": [], "not_covered": [], "not_applicable": 0,
639
+ "judged_as_problems": judged_as_problems(claims, names, qualified, smoke_thms)}
640
+ for c in claims:
641
+ decl = str(c.get("decl") or "")
642
+ if c.get("kind") not in CLAIM_KINDS or c.get("status") == "superseded" or not decl:
643
+ out["not_applicable"] += 1
644
+ elif claim_covered(real, c, qualified, mapped):
645
+ out["covered"].append(c)
646
+ elif claim_covered(todo, c, qualified, mapped):
647
+ out["todo"].append(c)
648
+ else:
649
+ out["not_covered"].append(c)
650
+ return out
651
+
652
+
653
+ def _claims_at(pkg: dict, repo: pathlib.Path, rev: str) -> tuple[list[dict], str]:
654
+ from .claims import load_claims_text
655
+ rel = pkg.get("claims_file") or "claims.yaml"
656
+ raw = core.git_show_bytes(repo, f"./{rel}", rev)
657
+ if raw is not None:
658
+ doc = load_claims_text(raw.decode("utf-8", errors="replace"), f"{rel} at {rev[:12]}")
659
+ return [c for c in doc.get("claims") or [] if isinstance(c, dict)], f"{rel} at {rev[:12]}"
660
+ synced = pkg.get("claims_synced_commit")
661
+ if synced and pkg.get("claims"):
662
+ return ([c for c in pkg["claims"] if isinstance(c, dict)],
663
+ f"the registry cache (synced at {str(synced)[:12]}; {rel} is not tracked at {rev[:12]})")
664
+ raise core.Fail(f"{pkg['name']}: no claims to measure: {rel} is not tracked at the gate-bound commit "
665
+ f"{rev[:12]} and no claims are cached (`lean-pkg claims sync {pkg['name']}`)")
666
+
667
+
668
+ def do_coverage(reg: dict, name: str) -> tuple[list[str], dict]:
669
+ pkg = core.get_pkg(reg, name)
670
+ repo = core.repo_path(pkg)
671
+ if not repo.is_dir():
672
+ raise core.Fail(f"{name}: local_path does not exist: {repo}")
673
+ gate = pkg.get("gate") or {}
674
+ rec = gate_mod.recorded_json(repo, gate.get("receipt"))
675
+ bound = str((rec or {}).get("commit") or "")
676
+ if not core._HEX40.fullmatch(bound):
677
+ raise core.Fail(f"{name}: no gate-bound commit (no readable gate receipt recorded); gate first: "
678
+ f"lean-pkg gate {name} --receipt R")
679
+ if core.git(repo, "cat-file", "-e", f"{bound}^{{commit}}").returncode != 0:
680
+ raise core.Fail(f"{name}: the gate-bound commit {bound[:12]} is not in {repo} (fetch it first)")
681
+ head = core.git_head(repo) or ""
682
+ claims, source = _claims_at(pkg, repo, bound)
683
+ at_bound = _configs_at(repo, bound)
684
+ from .claims import _reader
685
+ qualified = qualified_decls(_reader(repo, bound), claims)
686
+ side_bound = _sidecar_at(repo, bound)
687
+ smoke = smoke_configs(repo, bound, "HEAD")
688
+ cls = _classify(claims, at_bound, qualified, side_bound, smoke)
689
+ work = _worktree_configs(repo)
690
+ at_head = _configs_at(repo, head) if head else {}
691
+ changed: list[dict] = []
692
+ for path in sorted(set(at_bound) | set(work) | set(at_head)):
693
+ b, w, h = at_bound.get(path), work.get(path), at_head.get(path)
694
+ if b == w and b == h:
695
+ continue
696
+ if w is None and b is not None:
697
+ why = "removed from the working tree"
698
+ elif b is None:
699
+ why = "untracked (never committed)" if h is None else f"added after {bound[:12]}"
700
+ elif h != b:
701
+ why = f"changed at HEAD {head[:12]} since {bound[:12]}"
702
+ else:
703
+ why = "modified in the working tree (uncommitted)"
704
+ changed.append({"path": path, "change": why})
705
+ candidate = None
706
+ if changed:
707
+ cc_ = _classify(claims, work, qualified, load_sidecar(repo))
708
+ candidate = {"configs": sorted(work), "covered": len(cc_["covered"]), "todo": len(cc_["todo"]),
709
+ "not_covered": len(cc_["not_covered"]), "certifies": False}
710
+ props = len(cls["covered"]) + len(cls["todo"]) + len(cls["not_covered"])
711
+ statement = (f"Only the comparator configuration tracked at the gate-bound commit {bound[:12]} can certify "
712
+ f"that tree: a comparator receipt binds the configs tracked at its commit. A changed or "
713
+ f"uncommitted config cannot certify {bound[:12]}; a new gate at a commit that tracks the "
714
+ f"config is required.")
715
+ nxt: list[str] = []
716
+ fz = core.formalization_rel(pkg) or "formalization.yaml"
717
+ regate = [("lean-pkg update " + name + " --status gate-pending --reason 'comparator config changed: re-gate'")
718
+ ] if pkg.get("status") == "verified-private" else []
719
+ tail = regate + [
720
+ f"lean-pkg gate {name} --receipt R" + (" --refresh-formalization" if head and core.tracked_at(repo, fz, head)
721
+ else "") + " # R: a lower-tier receipt bound to the new HEAD",
722
+ f"cd {repo} && comparator-receipt --prepare && comparator-receipt",
723
+ f"lean-pkg comparator {name} --receipt .lean-receipts/<new-HEAD-12>-comparator.json"]
724
+ if changed:
725
+ paths = " ".join(c["path"] for c in changed if "removed" not in c["change"])
726
+ if any("working tree" in c["change"] or "untracked" in c["change"] for c in changed):
727
+ nxt.append(f"git -C {repo} add {paths} && git -C {repo} commit -m 'comparator config'")
728
+ nxt += tail
729
+ elif cls["not_covered"]:
730
+ nxt += [f"lean-pkg comparator config --from-claims {name} # scaffold TODO entries, then write each "
731
+ f"Challenge/Solution and commit"] + tail
732
+ elif cls["todo"]:
733
+ nxt += [f"write the Challenge/Solution of each scaffold.todo entry ({holes.SIDECAR}), remove the entry, "
734
+ f"commit, then:"] + tail
735
+ lines = [f"{name}: coverage at the gate-bound commit {bound[:12]} (HEAD {head[:12]}); claims from {source}",
736
+ f" configs tracked at {bound[:12]}: {', '.join(at_bound) or 'none'}",
737
+ f" {props} theorem/lemma claim(s): {len(cls['covered'])} covered, {len(cls['not_covered'])} not "
738
+ f"covered, {len(cls['todo'])} listed only as scaffold TODO; {cls['not_applicable']} other claim(s) not "
739
+ f"compared (definitions, superseded)"]
740
+ if cls["not_covered"]:
741
+ lines.append(" not covered: " + ", ".join(f"{c.get('id')} ({c.get('decl')})" for c in cls["not_covered"][:10])
742
+ + (" ..." if len(cls["not_covered"]) > 10 else ""))
743
+ lines += [f" judged_as: {m}" for m in cls["judged_as_problems"]]
744
+ configured = _names(at_bound, side_bound, smoke)[0]
745
+ hints = [h for c in cls["not_covered"]
746
+ for h in [decl_hint(configured, str(c.get("decl") or ""), str(c.get("decl") or "") in qualified)] if h]
747
+ if hints: # #6: a configured name that misses the decl by its root namespace
748
+ lines.append(f" rule: {COVER_RULE}")
749
+ lines += hint_lines(hints)
750
+ if changed:
751
+ lines += [f" config changed since {bound[:12]}: " + "; ".join(f"{c['path']} {c['change']}" for c in changed),
752
+ f" candidate (working tree; NOT counted above, certifies nothing): {candidate['covered']} covered, "
753
+ f"{candidate['todo']} TODO, {candidate['not_covered']} not covered"]
754
+ else:
755
+ lines.append(f" config unchanged since {bound[:12]} (HEAD and working tree)")
756
+ lines.append(statement)
757
+ lines += ["next:"] + [f" {c}" for c in nxt] if nxt else ["next: nothing to do (every theorem/lemma claim "
758
+ "is covered at the gate-bound commit)"]
759
+ payload = {"ok": True, "name": name, "bound_commit": bound, "head": head, "claims_source": source,
760
+ "configs": sorted(at_bound), "theorem_claims": props, "covered": len(cls["covered"]),
761
+ "not_covered": len(cls["not_covered"]), "todo": len(cls["todo"]),
762
+ "not_applicable": cls["not_applicable"],
763
+ "uncovered": [{"id": c.get("id"), "decl": c.get("decl")} for c in cls["not_covered"]],
764
+ "hints": hints, "judged_as_problems": cls["judged_as_problems"],
765
+ "config_changed": bool(changed), "changed_configs": changed, "candidate": candidate,
766
+ "statement": statement, "next_commands": nxt}
767
+ return lines, payload
768
+
769
+
770
+ # --------------------------------------------------------------------------
771
+ # --migrate-signoff PATH [--write]: move the deprecated inline judged_as / lean_pkg_scaffold keys of one
772
+ # configuration into lean-pkg-signoff.json (holes.py). Dry run by default; never a registry write; the
773
+ # configuration's Palomar keys and their values are never changed.
774
+
775
+ PALOMAR_KEYS = ("challenge_module", "solution_module", "theorem_names", "definition_names", "permitted_axioms",
776
+ "enable_nanoda")
777
+
778
+
779
+ def _locate(path: str) -> tuple[pathlib.Path, str, pathlib.Path]:
780
+ """(package root, config path relative to it, the file) for a comparator configuration path."""
781
+ f = pathlib.Path(os.path.abspath(pathlib.Path(path).expanduser()))
782
+ if f.is_symlink():
783
+ raise core.Fail(f"{path} is a symlink; refusing to read or write through it")
784
+ if not f.is_file():
785
+ raise core.Fail(f"{path}: no such comparator configuration file")
786
+ if f.parent.name == "comparator" and holes.CONFIG_RE.match(f"comparator/{f.name}"):
787
+ return f.parent.parent, f"comparator/{f.name}", f
788
+ if holes.CONFIG_RE.match(f.name):
789
+ return f.parent, f.name, f
790
+ raise core.Fail(f"{path}: not a comparator configuration path (comparator*.json at the package root or "
791
+ f"comparator/config*.json)")
792
+
793
+
794
+ def do_migrate_signoff(path: str, write: bool) -> tuple[list[str], dict, str | None, str | None]:
795
+ """(lines, payload, new config text, new sidecar text); the texts are None when nothing moves."""
796
+ root, rel, f = _locate(path)
797
+ raw = f.read_bytes()
798
+ try:
799
+ cfg = json.loads(raw.decode("utf-8"), object_pairs_hook=holes._strict_pairs)
800
+ except (UnicodeDecodeError, ValueError) as e:
801
+ raise core.Fail(f"{rel}: not valid strict JSON ({e}); nothing written") from e
802
+ if not isinstance(cfg, dict):
803
+ raise core.Fail(f"{rel}: not a JSON object; nothing written")
804
+ before = holes.sha256_bytes(raw)
805
+ payload = {"ok": True, "config": rel, "sidecar": holes.SIDECAR, "dry_run": not write, "written": False,
806
+ "moved": [], "dropped": [], "config_sha256_before": before, "config_sha256_after": before,
807
+ "palomar_keys_unchanged": True, "receipt_impact": None, "next_commands": [], "other_keys": [],
808
+ "config_text": None, "signoff": None} # the would-be files (dry run only)
809
+ inline = [k for k in holes.INLINE_KEYS if k in cfg]
810
+ if not inline:
811
+ return [f"{rel}: no inline {' or '.join(holes.INLINE_KEYS)} key; nothing to migrate; nothing written"], \
812
+ payload, None, None
813
+ sidecar = load_sidecar(root)
814
+ entry = dict(sidecar["configs"].get(rel) or {})
815
+ new_cfg = {k: v for k, v in cfg.items() if k not in holes.INLINE_KEYS}
816
+ new_text = json.dumps(new_cfg, indent=2, ensure_ascii=False) + "\n"
817
+ new_bytes = new_text.encode("utf-8")
818
+ after = holes.sha256_bytes(new_bytes)
819
+ lines: list[str] = []
820
+ hole_names = cfg.get("definition_names") or []
821
+ if "judged_as" in cfg:
822
+ if not isinstance(hole_names, list) or not all(isinstance(h, str) for h in hole_names):
823
+ raise core.Fail(f"{rel}: definition_names must be a list of strings; nothing written")
824
+ if hole_names:
825
+ try:
826
+ defs = holes._inline_check(cfg, hole_names, rel)
827
+ except ValueError as e:
828
+ raise core.Fail(f"{e}; fix the inline judged_as (or write the {holes.SIDECAR} entry by hand); "
829
+ f"nothing written") from e
830
+ have = entry.get("definitions") or {}
831
+ clash = sorted(h for h in defs if h in have and have[h] != defs[h])
832
+ if clash:
833
+ raise core.Fail(f"{rel}: {holes.SIDECAR} already signs off {', '.join(clash)} differently from the "
834
+ f"inline judged_as; reconcile them by hand; nothing written")
835
+ entry["definitions"] = {**have, **defs}
836
+ entry["config_sha256"] = after
837
+ payload["moved"].append({"key": "judged_as", "to": f"configs[{rel!r}].definitions",
838
+ "definitions": list(defs)})
839
+ lines.append(f"judged_as -> {holes.SIDECAR} configs[{rel!r}].definitions: {len(defs)} definition "
840
+ f"hole(s) ({', '.join(defs)}), signed by {holes.summary({'definitions': defs})['reviewer']}; "
841
+ f"config_sha256 bound to the migrated file")
842
+ listed = cfg["judged_as"].get("definitions") or []
843
+ stale = [d for d in listed if d not in hole_names]
844
+ if stale:
845
+ payload["dropped"].append({"key": "judged_as.definitions", "names": stale})
846
+ lines.append(f"judged_as.definitions {', '.join(map(str, stale))}: not a definition_names entry; "
847
+ f"dropped")
848
+ else:
849
+ payload["dropped"].append({"key": "judged_as", "names": []})
850
+ lines.append("judged_as: the configuration has no definition holes, so there is nothing to sign off; "
851
+ "dropped")
852
+ if "lean_pkg_scaffold" in cfg:
853
+ block = cfg["lean_pkg_scaffold"]
854
+ if not isinstance(block, dict) or not isinstance(block.get("todo", []), list):
855
+ raise core.Fail(f"{rel}: {SCAFFOLD_KEY} must be a mapping with a todo list; nothing written")
856
+ block = {k: v for k, v in block.items() if k in holes.SCAFFOLD_KEYS}
857
+ block.setdefault("todo", [])
858
+ if block["todo"]:
859
+ if entry.get("scaffold") not in (None, block):
860
+ raise core.Fail(f"{rel}: {holes.SIDECAR} already holds a different scaffold block for it; "
861
+ f"reconcile them by hand; nothing written")
862
+ entry["scaffold"] = block
863
+ payload["moved"].append({"key": SCAFFOLD_KEY, "to": f"configs[{rel!r}].scaffold",
864
+ "todo": len(block["todo"])})
865
+ lines.append(f"{SCAFFOLD_KEY} -> {holes.SIDECAR} configs[{rel!r}].scaffold: {len(block['todo'])} "
866
+ f"TODO marker(s)")
867
+ else:
868
+ payload["dropped"].append({"key": SCAFFOLD_KEY, "names": []})
869
+ lines.append(f"{SCAFFOLD_KEY}: its todo list is empty; dropped")
870
+ if entry:
871
+ sidecar["configs"][rel] = entry
872
+ side_text = holes.dump_sidecar(sidecar)
873
+ try: # the result must satisfy the rule it feeds
874
+ doc = holes.parse_sidecar(side_text.encode("utf-8"))
875
+ holes.check_definition_holes(new_cfg, rel, cfg_rel=rel, cfg_bytes=new_bytes, sidecar=doc)
876
+ except ValueError as e:
877
+ raise core.Fail(f"{rel}: the migrated sign-off would not pass: {e}; nothing written") from e
878
+ assert all(new_cfg.get(k) == cfg.get(k) for k in PALOMAR_KEYS)
879
+ others = sorted(set(new_cfg) - set(PALOMAR_KEYS))
880
+ impact = (f"the configuration's bytes change (sha256 {before[:12]} -> {after[:12]}): a comparator receipt binds "
881
+ f"each configuration's bytes (configs[].sha256), so once this is committed a recorded comparator "
882
+ f"receipt no longer validates at the new HEAD; a gated package needs a new comparator receipt (and "
883
+ f"a lower-tier receipt at the same commit)")
884
+ payload.update(config_sha256_after=after, receipt_impact=impact, other_keys=others,
885
+ next_commands=[f"git -C {root} add {rel} {holes.SIDECAR} && git -C {root} commit -m "
886
+ f"'comparator: move lean-pkg metadata to {holes.SIDECAR}'",
887
+ f"cd {root} && comparator-receipt --prepare && comparator-receipt",
888
+ "lean-pkg gate NAME --receipt R # R: a lower-tier receipt bound to the new HEAD",
889
+ "lean-pkg comparator NAME --receipt .lean-receipts/<new-HEAD-12>-comparator.json",
890
+ f"lean-pkg palomar check NAME --config {rel}"])
891
+ lines = [f"{rel}: migrate {' and '.join(inline)} to {holes.SIDECAR} (Palomar keys and values unchanged)"] + \
892
+ lines + ([f"warning: {rel} still has key(s) outside Palomar's six: {', '.join(others)} (palomar check "
893
+ f"refuses them; this command moves only lean-pkg's own keys)"] if others else []) + \
894
+ [f"receipt impact: {impact}"]
895
+ if not write:
896
+ payload["config_text"], payload["signoff"] = new_text, json.loads(side_text)
897
+ return lines + ["dry run: nothing written (--write writes both files)"], payload, new_text, side_text
898
+ _atomic_write(root / holes.SIDECAR, side_text) # the sign-off first: the config never loses it
899
+ _atomic_write(f, new_text)
900
+ payload["written"] = True
901
+ return lines + [f"wrote {holes.SIDECAR} and {rel}", "next:"] + \
902
+ [f" {c}" for c in payload["next_commands"]], payload, None, None
903
+
904
+
905
+ USAGE = ("usage: lean-pkg comparator config --from-claims NAME [--out comparator.json] [--dry-run] "
906
+ "[--challenge-namespace NS] [--agent A] [--challenge-from-type | --emit-script F | --from-output F] "
907
+ "[--allow-partial] [--repo DIR] [--claims-file PATH] [--no-registry --out FILE] "
908
+ "[--lake-env DIR] [--jobs N] [--timeout S] | lean-pkg comparator coverage NAME | "
909
+ "lean-pkg comparator migrate-signoff PATH [--write]")
910
+
911
+
912
+ def types_mode(args) -> dict | None:
913
+ emit, frm = getattr(args, "emit_script", None), getattr(args, "from_output", None)
914
+ local = getattr(args, "challenge_from_type", False)
915
+ tuning = [f for f, v in (("--lake-env", getattr(args, "lake_env", None)), ("--jobs", getattr(args, "jobs", None)),
916
+ ("--timeout", getattr(args, "timeout", None))) if v is not None]
917
+ if emit and frm:
918
+ raise core.UsageError("--emit-script and --from-output are two halves of one run; pass one of them")
919
+ if getattr(args, "no_registry", False) and not (frm or local):
920
+ raise core.UsageError("--no-registry: needs --from-output or --challenge-from-type, and --out FILE")
921
+ if getattr(args, "allow_partial", False) and not (frm or local):
922
+ raise core.UsageError("--allow-partial: needs --from-output or --challenge-from-type (it governs ingestion)")
923
+ if frm and tuning:
924
+ raise core.UsageError(f"{', '.join(tuning)}: belong to the driver (--challenge-from-type or --emit-script), "
925
+ f"not to --from-output")
926
+ if not (emit or frm or local):
927
+ if tuning:
928
+ raise core.UsageError(f"{', '.join(tuning)}: need --challenge-from-type or --emit-script")
929
+ return None
930
+ mode = "emit" if emit else "ingest" if frm else "local"
931
+ return {"mode": mode, "emit": emit, "from_output": frm, "lake_env": getattr(args, "lake_env", None),
932
+ "jobs": getattr(args, "jobs", None), "timeout": getattr(args, "timeout", None),
933
+ "allow_partial": bool(getattr(args, "allow_partial", False))}
934
+
935
+
936
+ def cmd_comparator_config(args) -> int:
937
+ if getattr(args, "migrate_signoff", None):
938
+ if args.from_claims or getattr(args, "coverage", None) or args.out or args.dry_run or \
939
+ types_mode(args) is not None or args.agent or getattr(args, "checkout", None) or \
940
+ getattr(args, "claims_file", None) or getattr(args, "no_registry", False):
941
+ raise core.UsageError("--migrate-signoff PATH takes only --write and --json (a dry run without --write)")
942
+ lines, payload, cfg_text, side_text = do_migrate_signoff(args.migrate_signoff, bool(args.write))
943
+ if getattr(args, "json_out", False):
944
+ core.print_json(payload)
945
+ else:
946
+ print("\n".join(lines))
947
+ if cfg_text is not None:
948
+ print(f"--- {payload['config']} (would be):")
949
+ print(cfg_text, end="")
950
+ print(f"--- {holes.SIDECAR} (would be):")
951
+ print(side_text, end="")
952
+ return 0
953
+ if getattr(args, "write", False):
954
+ raise core.UsageError("--write: only with --migrate-signoff PATH")
955
+ if getattr(args, "coverage", None):
956
+ if args.from_claims or args.out or args.dry_run or types_mode(args) is not None or args.agent or \
957
+ getattr(args, "checkout", None) or getattr(args, "claims_file", None):
958
+ raise core.UsageError("--coverage NAME is read-only and takes no other config flag")
959
+ lines, payload = do_coverage(core.load_registry(core.registry_path(args)), args.coverage)
960
+ if getattr(args, "json_out", False):
961
+ core.print_json(payload)
962
+ else:
963
+ print("\n".join(lines))
964
+ return 0
965
+ if not args.from_claims:
966
+ raise core.UsageError(USAGE)
967
+ types = types_mode(args)
968
+ no_registry = bool(getattr(args, "no_registry", False))
969
+ if no_registry and not args.out:
970
+ raise core.UsageError("--no-registry: needs --out FILE (a scratch file outside the checkout)")
971
+ if no_registry and args.agent:
972
+ raise core.UsageError("--no-registry: takes no --agent (the lease is not consulted)")
973
+ reg = core.load_registry(core.registry_path(args))
974
+ lines, payload, text = do_config_from_claims(reg, args.from_claims, args.out or "comparator.json",
975
+ args.dry_run, args.challenge_namespace, args.agent, types,
976
+ getattr(args, "checkout", None), no_registry,
977
+ getattr(args, "claims_file", None))
978
+ if getattr(args, "json_out", False):
979
+ if text is not None:
980
+ payload["config"] = json.loads(text)
981
+ core.print_json(payload)
982
+ else:
983
+ side = payload.pop("signoff", None)
984
+ print("\n".join(lines))
985
+ if text is not None:
986
+ print(text, end="")
987
+ if side is not None:
988
+ print(f"--- {holes.SIDECAR} (dry run, nothing written):")
989
+ print(holes.dump_sidecar(side), end="")
990
+ return 0