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/ledger.py ADDED
@@ -0,0 +1,582 @@
1
+ # lean-pkg claims ledger -- per-claim closure computed from the recorded evidence, never stored
2
+ """`lean-pkg claims ledger NAME [--stage gate|promote]` (#80).
3
+
4
+ For each claim in the package's claims file (as tracked at the gate-bound commit, else the registry
5
+ cache) the ledger lists named diagnostics, each a reason the recorded evidence does not close it. A
6
+ claim is `verified` only when its diagnostic list is empty. Nothing is written: the ledger is
7
+ re-derived from the registry record, the checkout and the receipts on every call, with the same
8
+ validators `gate` and `promote` use, so it can never accept less than they do.
9
+
10
+ Claim status, first match wins: `out-of-scope` (claims.yaml status superseded, or internal and not
11
+ judged), `blocked` (a depends_on claim in this package is not closed), `unknown` (evidence that cannot
12
+ be read), `open` (an open or failed diagnostic), `conditional` (proposal 0003: the claim lists hypotheses, or
13
+ inherits outstanding ones through depends_on), `verified` (no diagnostics), else `open`.
14
+
15
+ An internal theorem or lemma is judged (`judged_internal`, promote stage) when the comparator tier is
16
+ clean for the package (a valid comparator receipt, bound to the gate-bound commit, every configuration
17
+ passing) and a configuration at that commit names its declaration by the rule that credits a reusable
18
+ claim. A judged internal claim gets every diagnostic a reusable one gets and is verified on the same
19
+ evidence; it is never required, so the package status does not change. What the comparator establishes
20
+ for a theorem does not depend on the claim's status: the status says whether a result is offered for
21
+ reuse, not whether it is true.
22
+
23
+ Required claims are those with claims.yaml status `reusable`. At stage `gate` they need the lower
24
+ tier; at stage `promote` a reusable theorem or lemma also needs the comparator tier, so a lower-tier
25
+ receipt alone never closes a claim promotion needs.
26
+
27
+ Manuscript findings (`manuscript_findings`, #6) never change a status: each claim row lists them, and the
28
+ package-level `manuscript_findings` summary (what the formalization found: open vs fixed in a later arXiv
29
+ version) is what `publish --dry-run` and `palomar prepare` print. Only a lean_evidence declaration missing at
30
+ the gate-bound commit is a diagnostic (`finding-evidence-missing`, like `decl-missing`).
31
+
32
+ Conditional claims (proposal 0003, stage H3): when a claim sets `hypotheses`, `discharges` or `witness`, the
33
+ ledger reads the hyp-probe/1 section of the gate receipt's sealed verify log at the gate-bound commit X
34
+ (`hypotheses.evaluate`): each listed hypothesis must be an explicit binder of the declaration (and of its
35
+ Challenge theorem at the promote stage) headed by a def or an inductive Prop; a hypothesis is discharged only at
36
+ the promote stage, through a corollary claim and its proof claims compared in the same comparator build at X.
37
+ Discharge is recomputed on every call and never stored. A claim with hypotheses is `conditional`, never
38
+ `verified`, even when all are discharged; a claim that depends_on a conditional claim inherits its outstanding
39
+ hypotheses (`depends-on-conditional`). Facts that are missing (no section, a part that did not run, ambiguous
40
+ credit) give `hypotheses-unchecked` (open). A claims file without the keys gets exactly the rows, codes, keys
41
+ and digest it had.
42
+
43
+ Package status fails closed: `unknown` with no claims, no required claim, or a limitation (no
44
+ checkout, unreadable evidence); `failed` when recorded evidence contradicts a required claim;
45
+ `ready` only when every required claim is verified or conditional (open question 1: the qualifier
46
+ `conditional_required` and the `outstanding_hypotheses` are then reported); else `open`.
47
+ """
48
+
49
+ from __future__ import annotations
50
+
51
+ import hashlib
52
+ import json
53
+ import pathlib
54
+
55
+ from . import gate as gate_mod
56
+ from . import core
57
+
58
+ LEDGER_SCHEMA = "claims-ledger/1"
59
+ STAGES = ("gate", "promote")
60
+ REQUIRED_STATUSES = ("reusable",)
61
+ OUT_OF_SCOPE_STATUSES = ("internal", "superseded")
62
+ JUDGED_STATUSES = ("internal",) # out of scope unless a passing comparator judges the declaration
63
+
64
+ # code -> (class, meaning). The class decides the claim status: "open" (evidence missing or stale),
65
+ # "unknown" (evidence that cannot be read), "failed" (recorded evidence contradicts the claim),
66
+ # "blocked" (a dependency is not closed), "conditional" (proposal 0003: closed under outstanding hypotheses).
67
+ # Documented in docs/lifecycle.md (#80).
68
+ CODES = {
69
+ "no-checkout": ("unknown", "the package has no checkout at local_path on this host"),
70
+ "no-gate-receipt": ("open", "no lower-tier gate receipt is recorded"),
71
+ "receipt-unreadable": ("unknown", "the recorded gate receipt cannot be read as JSON"),
72
+ "bound-commit-missing": ("unknown", "the gate receipt's commit is not in the checkout"),
73
+ "receipt-commit-mismatch": ("open", "the gate receipt binds neither HEAD nor an evidence-only ancestor"),
74
+ "receipt-invalid": ("failed", "the gate receipt fails the gate validator (toolchain, sorry count, fields)"),
75
+ "report-log-missing": ("unknown", "the sealed verify log the gate receipt binds (report_sha256) is missing or "
76
+ "unreadable"),
77
+ "axiom-not-allowed": ("failed", "the gate receipt lists an axiom outside gate.axioms_allowed"),
78
+ "decl-missing": ("failed", "the declaration does not occur in its file at the gate-bound commit"),
79
+ "finding-evidence-missing": ("failed", "a manuscript finding's lean_evidence declaration does not occur in "
80
+ "its file at the gate-bound commit"),
81
+ "no-comparator-receipt": ("open", "promote stage: no comparator receipt is recorded"),
82
+ "comparator-unreadable": ("unknown", "the recorded comparator receipt cannot be read as JSON"),
83
+ "comparator-commit-mismatch": ("open", "the comparator receipt binds another commit than the gate receipt, "
84
+ "or neither HEAD nor an evidence-only ancestor"),
85
+ "comparator-invalid": ("failed", "the comparator receipt fails the comparator validator"),
86
+ "no-comparator-config": ("open", "no comparator configuration at the gate-bound commit names the declaration"),
87
+ "comparator-todo": ("open", "the declaration is listed only as a scaffold TODO entry"),
88
+ "depends-on-open": ("blocked", "a depends_on claim in this package is not verified"),
89
+ "depends-on-unknown": ("unknown", "a depends_on claim is in another package or not in this claims file"),
90
+ # proposal 0003 (conditional claims), judged from the hyp-probe/1 section of the sealed verify log
91
+ "hypotheses-unchecked": ("open", "the claim uses hypotheses, discharges or witness, but the sealed verify "
92
+ "log at the gate-bound commit lacks the facts to judge them (no hyp-probe/1 "
93
+ "section, a part of the probe that did not run, ambiguous credit): re-gate"),
94
+ "hypothesis-not-in-type": ("failed", "a listed hypothesis is not an explicit binder of the declaration's type "
95
+ "(or of its Challenge theorem) at the gate-bound commit"),
96
+ "hypothesis-inadmissible": ("failed", "a listed hypothesis is an axiom, opaque or theorem constant, not a def "
97
+ "or an inductive Prop"),
98
+ "hypothesis-open": ("conditional", "a listed hypothesis has no discharge at the gate-bound commit"),
99
+ "discharge-type-mismatch": ("failed", "the corollary's Challenge type is not the discharged claim's type minus "
100
+ "the discharged binders, or a proof's type is not the hypothesis"),
101
+ "discharge-not-compared": ("open", "promote stage: the corollary, the claim it discharges or a proof claim is "
102
+ "in no comparator configuration at the gate-bound commit"),
103
+ "witness-type-mismatch": ("failed", "the witness claim's Challenge type is not the expected witness of the "
104
+ "claim's hypotheses, or the claim takes no parameters"),
105
+ "depends-on-conditional": ("conditional", "a depends_on claim in this package is conditional: its outstanding "
106
+ "hypotheses are inherited"),
107
+ }
108
+ CONDITIONAL_CODES = tuple(c for c, (cls, _) in CODES.items() if cls == "conditional")
109
+
110
+
111
+ def _diag(code: str, detail: str) -> dict:
112
+ assert code in CODES, code
113
+ return {"code": code, "detail": detail}
114
+
115
+
116
+ def _sha256_file(path: pathlib.Path | None) -> str | None:
117
+ try:
118
+ return hashlib.sha256(path.read_bytes()).hexdigest() if path is not None else None
119
+ except OSError:
120
+ return None
121
+
122
+
123
+ def _gate_evidence(pkg: dict, repo: pathlib.Path) -> tuple[list[dict], str | None, dict]:
124
+ """Package-wide lower-tier diagnostics, the gate-bound commit (None when unusable) and the hashes."""
125
+ gate = pkg.get("gate") or {}
126
+ rel = gate.get("receipt")
127
+ hashes = {"receipt_sha256": _sha256_file(repo / rel) if rel else None}
128
+ if not rel:
129
+ return [_diag("no-gate-receipt", f"run `lean-pkg gate {pkg['name']} --receipt R`")], None, hashes
130
+ rec = gate_mod.recorded_json(repo, rel)
131
+ if not isinstance(rec, dict):
132
+ return [_diag("receipt-unreadable", f"{rel} is missing or not a JSON object")], None, hashes
133
+ bound = str(rec.get("commit") or "")
134
+ if not core._HEX40.fullmatch(bound) or core.git(repo, "cat-file", "-e", f"{bound}^{{commit}}").returncode:
135
+ return [_diag("bound-commit-missing", f"{rel}: commit {bound[:12] or '(none)'} is not in the checkout "
136
+ f"(fetch it)")], None, hashes
137
+ diags: list[dict] = []
138
+ head = core.git_head(repo) or ""
139
+ ok, note, _docs = gate_mod.package_descendant(repo, bound, head, pkg, checker=rec.get("checker"))
140
+ if not ok:
141
+ diags.append(_diag("receipt-commit-mismatch", f"receipt {bound[:12]}, HEAD {head[:12]} ({note}); re-gate"))
142
+ allowed = set(gate.get("axioms_allowed") or core.DEFAULT_AXIOMS)
143
+ axioms = rec.get("axioms")
144
+ extra = sorted(set(axioms) - allowed) if isinstance(axioms, list) and all(
145
+ isinstance(a, str) for a in axioms) else []
146
+ if extra:
147
+ diags.append(_diag("axiom-not-allowed", f"axioms {extra} outside {sorted(allowed)}"))
148
+ if ok:
149
+ try:
150
+ gate_mod.validate_receipt(pkg, repo, rec)
151
+ except core.Fail as e:
152
+ if not (extra and str(e).startswith("axioms ")):
153
+ diags.append(_diag("receipt-invalid", str(e)))
154
+ else:
155
+ why = gate_mod.recorded_report_log_problem(repo, rec, rel)
156
+ if why:
157
+ diags.append(_diag("report-log-missing" if why.startswith(gate_mod.REPORT_LOG_MISSING)
158
+ else "receipt-invalid", why))
159
+ return diags, bound, hashes
160
+
161
+
162
+ def _comparator_evidence(pkg: dict, repo: pathlib.Path, bound: str | None) -> tuple[list[dict], dict]:
163
+ """Package-wide comparator-tier diagnostics (promote stage) and the receipt hash."""
164
+ rel = (pkg.get("gate") or {}).get("comparator")
165
+ hashes = {"comparator_sha256": _sha256_file(repo / rel) if rel else None}
166
+ if not rel:
167
+ return [_diag("no-comparator-receipt", f"run comparator-receipt, then `lean-pkg comparator "
168
+ f"{pkg['name']} --receipt C`")], hashes
169
+ comp = gate_mod.recorded_json(repo, rel)
170
+ if not isinstance(comp, dict):
171
+ return [_diag("comparator-unreadable", f"{rel} is missing or not a JSON object")], hashes
172
+ commit = str(comp.get("commit") or "")
173
+ if bound and commit != bound:
174
+ return [_diag("comparator-commit-mismatch", f"comparator {commit[:12] or '(none)'}, gate receipt "
175
+ f"{bound[:12]}: both tiers must bind one commit")], hashes
176
+ head = core.git_head(repo) or ""
177
+ ok, note, _docs = (gate_mod.package_descendant(repo, commit, head, pkg)
178
+ if core._HEX40.fullmatch(commit) else (False, "not a 40-hex commit", None))
179
+ if not ok: # stale, not contradicted: re-run, do not call it invalid
180
+ return [_diag("comparator-commit-mismatch", f"comparator {commit[:12] or '(none)'}, HEAD {head[:12]} "
181
+ f"({note})")], hashes
182
+ try:
183
+ gate_mod.validate_comparator(pkg, repo, comp, bound)
184
+ except core.Fail as e:
185
+ return [_diag("comparator-invalid", str(e))], hashes
186
+ return [], hashes
187
+
188
+
189
+ def _claims_source(pkg: dict, repo: pathlib.Path, bound: str | None) -> tuple[list[dict], str]:
190
+ from . import claims as claims_mod
191
+ rel = pkg.get("claims_file") or claims_mod.DEFAULT_CLAIMS_FILE
192
+ if bound:
193
+ raw = core.git_show_bytes(repo, f"./{rel}", bound)
194
+ if raw is not None:
195
+ doc = claims_mod.load_claims_text(raw.decode("utf-8", errors="replace"), f"{rel} at {bound[:12]}")
196
+ return [c for c in doc.get("claims") or [] if isinstance(c, dict)], f"{rel} at {bound[:12]}"
197
+ cached = [c for c in pkg.get("claims") or [] if isinstance(c, dict)]
198
+ synced = pkg.get("claims_synced_commit")
199
+ if synced:
200
+ return cached, f"the registry cache (synced at {str(synced)[:12]})"
201
+ raw = core.git_show_bytes(repo, f"./{rel}", "HEAD") # no usable gate: the committed file
202
+ if raw is not None:
203
+ doc = claims_mod.load_claims_text(raw.decode("utf-8", errors="replace"), f"{rel} at HEAD")
204
+ return [c for c in doc.get("claims") or [] if isinstance(c, dict)], f"{rel} at HEAD (no usable gate receipt)"
205
+ return cached, "the registry cache (empty)"
206
+
207
+
208
+ def compute_ledger(reg: dict, name: str, stage: str = "promote") -> dict:
209
+ return ledger_for(core.get_pkg(reg, name), stage)
210
+
211
+
212
+ def ledger_for(pkg: dict, stage: str = "promote") -> dict:
213
+ """The ledger of one registry record (what `promote`, `publish --dry-run` and `next` read)."""
214
+ from . import claims as claims_mod
215
+ from . import comparator_config as cc
216
+ if stage not in STAGES:
217
+ raise core.UsageError(f"--stage must be one of {', '.join(STAGES)}")
218
+ name = pkg["name"]
219
+ repo = core.repo_path(pkg) if pkg.get("local_path") else None
220
+ limitations: list[str] = []
221
+ hashes: dict = {"receipt_sha256": None, "comparator_sha256": None}
222
+ bound = None
223
+ if repo is None or not repo.is_dir() or core.git_head(repo) is None:
224
+ limitations.append("no checkout at local_path on this host")
225
+ pkg_diags = [_diag("no-checkout", f"local_path {pkg.get('local_path')!r} is not a git checkout here")]
226
+ comp_diags: list[dict] = []
227
+ claims, source = [c for c in pkg.get("claims") or [] if isinstance(c, dict)], "the registry cache"
228
+ else:
229
+ pkg_diags, bound, h = _gate_evidence(pkg, repo)
230
+ hashes.update(h)
231
+ comp_diags, h = _comparator_evidence(pkg, repo, bound) if stage == "promote" else ([], {})
232
+ hashes.update(h)
233
+ try:
234
+ claims, source = _claims_source(pkg, repo, bound)
235
+ except core.Fail as e:
236
+ limitations.append(f"claims file unreadable: {e}")
237
+ claims, source = [], "unreadable"
238
+ if bound:
239
+ configs = cc._configs_at(repo, bound) if stage == "promote" else {}
240
+ smoke = cc.smoke_configs(repo, bound, "HEAD") if stage == "promote" else {}
241
+ names, todo = (cc._names(configs, cc._sidecar_at(repo, bound), smoke)
242
+ if stage == "promote" else (set(), set()))
243
+ smoke_thms = cc.smoke_names(configs, smoke)
244
+ read = claims_mod._reader(repo, bound)
245
+ qualified = cc.qualified_decls(read, claims) if stage == "promote" else set()
246
+ real, mapped = names - todo, cc.mapped_names(claims)
247
+
248
+ ids = {str(c.get("id")) for c in claims}
249
+ rows: list[dict] = []
250
+ for c in claims:
251
+ cid, decl = str(c.get("id")), str(c.get("decl") or "")
252
+ required = c.get("status") in REQUIRED_STATUSES
253
+ diags = list(pkg_diags)
254
+ if bound and decl and c.get("file"):
255
+ diags += [_diag("decl-missing", p.split(": ", 1)[-1]) for p in claims_mod.decl_problems(read, [c])]
256
+ if bound:
257
+ diags += [_diag("finding-evidence-missing", p) for p in claims_mod.evidence_problems(read, [c])]
258
+ needs_comparator = stage == "promote" and required and c.get("kind") in cc.CLAIM_KINDS
259
+ # an internal theorem/lemma a passing, commit-bound comparator judged: the reusable checks, never required
260
+ judged_internal = bool(stage == "promote" and bound and not comp_diags
261
+ and c.get("status") in JUDGED_STATUSES and c.get("kind") in cc.CLAIM_KINDS
262
+ and cc.claim_covered(real, c, qualified, mapped))
263
+ if needs_comparator:
264
+ diags += comp_diags
265
+ if bound and not comp_diags:
266
+ q = decl in qualified
267
+ if not cc.claim_covered(real, c, qualified, mapped):
268
+ code = ("comparator-todo" if cc.claim_covered(todo, c, qualified, mapped)
269
+ else "no-comparator-config")
270
+ why = "" if q else (f" ({decl} is not the fully qualified name of a declaration in "
271
+ f"{c.get('file')}: a bare or partial name is credited to no "
272
+ f"comparator name)")
273
+ judged = cc.judged_name(c)
274
+ if judged and q and judged not in names:
275
+ why += (f" (judged_as {judged} is a theorem of a smoke configuration only, which verifies "
276
+ f"no claim)" if judged in smoke_thms else
277
+ f" (judged_as {judged} is in no comparator configuration's theorem_names)")
278
+ elif not judged and q and cc.covers(smoke_thms, decl, q):
279
+ why += " (only a smoke configuration names it, and a smoke check verifies no claim)"
280
+ near = cc.decl_hint(names, decl, q) # #6: detail only; the digest covers codes
281
+ why += f"; hint: {near['hint']}" if near else ""
282
+ diags.append(_diag(code, f"{decl} at {bound[:12]}{why}"))
283
+ for d in c.get("depends_on") or []:
284
+ if d not in ids:
285
+ diags.append(_diag("depends-on-unknown", f"{d} is not a claim of {name}'s claims file"))
286
+ rows.append({"id": cid, "decl": decl, "kind": c.get("kind"), "claim_status": c.get("status"),
287
+ "required": required, "judged_internal": judged_internal,
288
+ "depends_on": list(c.get("depends_on") or []),
289
+ "statement_basis": c.get("statement_basis"), "manuscript_findings": claim_findings(c),
290
+ "diagnostics": diags})
291
+
292
+ keyed = any(claims_mod.uses_conditional_keys(c) for c in claims)
293
+ if keyed: # proposal 0003: judge the keys from the sealed facts at X
294
+ _conditional(claims, rows, pkg, repo if bound else None, bound, stage, comp_diags,
295
+ (real, qualified, mapped) if bound and stage == "promote" else None)
296
+
297
+ def own_class(row) -> str:
298
+ classes = {CODES[d["code"]][0] for d in row["diagnostics"] if d["code"] != "depends-on-open"}
299
+ if "unknown" in classes:
300
+ return "unknown"
301
+ if classes - {"conditional"}:
302
+ return "open"
303
+ if row.get("conditional_own") or any(d["code"] == "depends-on-conditional" for d in row["diagnostics"]):
304
+ return "conditional"
305
+ return "verified" if not row["diagnostics"] else "open"
306
+
307
+ def closes(dep) -> bool: # a conditional-class code never blocks a dependent
308
+ return not any(CODES[x["code"]][0] != "conditional" for x in dep["diagnostics"])
309
+
310
+ by_id = {r["id"]: r for r in rows}
311
+ changed = True
312
+ while changed: # propagate open dependencies to a fixed point
313
+ changed = False
314
+ for r in rows:
315
+ for d in r["depends_on"]:
316
+ dep = by_id.get(d)
317
+ if dep is not None and not closes(dep) and not any(
318
+ x["code"] == "depends-on-open" and x["detail"].startswith(d + " ") for x in r["diagnostics"]):
319
+ r["diagnostics"].append(_diag("depends-on-open", f"{d} is not verified"))
320
+ changed = True
321
+ if keyed:
322
+ _inherit(rows, by_id, closes)
323
+ for r in rows:
324
+ if r["claim_status"] in OUT_OF_SCOPE_STATUSES and not r["judged_internal"]:
325
+ r["status"] = "out-of-scope"
326
+ elif any(d["code"] == "depends-on-open" for d in r["diagnostics"]):
327
+ r["status"] = "blocked"
328
+ else:
329
+ r["status"] = own_class(r)
330
+ r["diagnostics"].sort(key=lambda d: (list(CODES).index(d["code"]), d["detail"]))
331
+ r.pop("conditional_own", None)
332
+ r.pop("stale_edge", None)
333
+
334
+ required_rows = [r for r in rows if r["required"]]
335
+ failed = [r["id"] for r in required_rows
336
+ if any(CODES[d["code"]][0] == "failed" for d in r["diagnostics"])]
337
+ reasons: list[str] = list(limitations)
338
+ if not rows:
339
+ reasons.append("no claims: nothing to verify (an empty claims set is not a clean one)")
340
+ elif not required_rows:
341
+ reasons.append("no claim has status reusable: nothing is required, so nothing is established; fix: "
342
+ "mark the results others should rely on as status: reusable (`lean-pkg claims mark "
343
+ f"{name} --from-comparator CONFIG.json --status reusable`, or edit claims.yaml), "
344
+ "commit, claims sync, re-gate")
345
+ if reasons:
346
+ pstatus = "unknown"
347
+ elif failed:
348
+ pstatus = "failed"
349
+ reasons.append(f"recorded evidence contradicts {len(failed)} required claim(s): {', '.join(failed)}")
350
+ elif any(r["status"] == "unknown" for r in required_rows):
351
+ pstatus = "unknown"
352
+ reasons.append("the evidence for a required claim cannot be read")
353
+ elif all(r["status"] in CLOSED for r in required_rows):
354
+ pstatus = "ready" # open question 1: a conditional required claim is closed
355
+ else:
356
+ pstatus = "open"
357
+ n = sum(r["status"] not in CLOSED for r in required_rows)
358
+ reasons.append(f"{n} of {len(required_rows)} required claim(s) not verified"
359
+ + (" or conditional" if keyed else ""))
360
+
361
+ canonical = {"schema": LEDGER_SCHEMA, "package": name, "stage": stage, "bound_commit": bound,
362
+ **hashes, "package_status": pstatus,
363
+ "claims": [_canonical_row(r) for r in rows]}
364
+ digest = hashlib.sha256(json.dumps(canonical, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
365
+ counts = {s: sum(r["status"] == s for r in rows)
366
+ for s in ("verified", *(("conditional",) if keyed else ()), "open", "blocked", "unknown",
367
+ "out-of-scope")}
368
+ cond: dict = {}
369
+ if keyed: # only when a claim uses the keys: other ledgers keep their keys
370
+ creq = [r for r in required_rows if r["status"] == "conditional"]
371
+ cond = {"conditional_required": [r["id"] for r in creq],
372
+ "outstanding_hypotheses": sorted({h["decl"] for r in creq for h in r.get("hypotheses") or []
373
+ if h["state"] == "open"})}
374
+ return {"ok": pstatus == "ready", "schema": LEDGER_SCHEMA, "name": name, "stage": stage,
375
+ "package_status": pstatus, "reasons": reasons, "bound_commit": bound, "claims_source": source,
376
+ **hashes, "counts": counts, "required": len(required_rows), **cond, "claims": rows,
377
+ "manuscript_findings": {**findings_summary(rows), "source": source}, "ledger_digest": f"sha256:{digest}"}
378
+
379
+
380
+ CLOSED = ("verified", "conditional") # the statuses that close a required claim (open question 1)
381
+
382
+
383
+ def _conditional(claims: list[dict], rows: list[dict], pkg: dict, repo, bound, stage: str, comp_diags: list,
384
+ cred) -> None:
385
+ """Proposal 0003: add the hypotheses diagnostics and the `hypotheses`, `discharges` and `witness` row keys,
386
+ from the hyp-probe/1 facts of the gate receipt's sealed log at X (`hypotheses.evaluate`). `cred`: (the
387
+ non-smoke configured names, the qualified decls, the judged_as names) at the promote stage, else None."""
388
+ from . import claims as claims_mod
389
+ from . import comparator_config as cc
390
+ from . import hypotheses as hyp
391
+ text = None
392
+ if repo is not None and bound:
393
+ rel = (pkg.get("gate") or {}).get("receipt")
394
+ rec = gate_mod.recorded_json(repo, rel) if rel else None
395
+ text = gate_mod.sealed_log_text(repo, rec, rel) if isinstance(rec, dict) else None
396
+ fx = hyp.facts(text)
397
+ by_row = {r["id"]: r for r in rows}
398
+ credited = ({str(c.get("id")): cc.credited_names(cred[0], c, cred[1], cred[2]) for c in claims}
399
+ if cred else {})
400
+ clean = {r["id"]: not any(CODES[d["code"]][0] in ("open", "failed", "unknown") for d in r["diagnostics"])
401
+ for r in rows}
402
+ res = hyp.evaluate(claims, fx, stage=stage, bound=bound, comparator_ok=stage == "promote" and not comp_diags,
403
+ credited=credited, clean=clean)
404
+ for c in claims:
405
+ r = by_row[str(c.get("id"))]
406
+ own = [h for h in c.get("hypotheses") or [] if isinstance(h, str)]
407
+ r["conditional_own"] = bool(own)
408
+ e = res.get(r["id"]) or {}
409
+ r["diagnostics"] += [_diag(code, detail) for code, detail in e.get("diags") or []]
410
+ if e.get("hypotheses") is not None:
411
+ r["hypotheses"] = e["hypotheses"]
412
+ d = c.get("discharges")
413
+ if isinstance(d, dict):
414
+ r["discharges"] = {k: d.get(k) for k in claims_mod.DISCHARGE_KEYS}
415
+ if e.get("witness") is not None:
416
+ r["witness"] = e["witness"]
417
+ # proposal 0003: an edge to a conditional claim is stale when Lean proved this claim unconditionally
418
+ decl = fx["decls"].get(r["decl"]) if fx.get("ok") else None
419
+ r["stale_edge"] = bool(not own and decl is not None and not decl["binders"]
420
+ and stage == "promote" and not comp_diags and credited.get(r["id"]))
421
+
422
+
423
+ def _inherit(rows: list[dict], by_id: dict, closes) -> None:
424
+ """depends-on-conditional (proposal 0003): a claim inherits, to a fixed point, the outstanding hypotheses of
425
+ each depends_on claim that is closed but conditional, marked via that claim; only outstanding hypotheses
426
+ pass on (an all-discharged dependency passes on none)."""
427
+ def outstanding(r) -> set[str]:
428
+ return {h["decl"] for h in r.get("hypotheses") or [] if h["state"] == "open"}
429
+
430
+ changed = True
431
+ while changed:
432
+ changed = False
433
+ for r in rows:
434
+ for d in r["depends_on"]:
435
+ dep = by_id.get(d)
436
+ if dep is None or not closes(dep):
437
+ continue
438
+ have = {h["decl"] for h in r.get("hypotheses") or [] if h.get("via") == d}
439
+ new = sorted(outstanding(dep) - have)
440
+ if new:
441
+ r.setdefault("hypotheses", [])
442
+ r["hypotheses"] += [{"decl": h, "state": "open", "by": None, "via": d} for h in new]
443
+ changed = True
444
+ for r in rows:
445
+ for d in dict.fromkeys(r["depends_on"]):
446
+ hs = sorted({h["decl"] for h in r.get("hypotheses") or [] if h.get("via") == d})
447
+ if hs:
448
+ stale = (f"; {r['id']}'s own type takes no hypothesis and the comparator checked it, so this "
449
+ f"depends_on edge looks stale: remove it" if r.get("stale_edge") else "")
450
+ r["diagnostics"].append(_diag("depends-on-conditional",
451
+ f"{d} is conditional: inherits outstanding {', '.join(hs)} via {d}"
452
+ + stale))
453
+
454
+
455
+ def _canonical_row(r: dict) -> dict:
456
+ """A row as the digest covers it; the basis and the findings only when set, so a ledger without them keeps
457
+ the digest it had before #6."""
458
+ out = {"id": r["id"], "decl": r["decl"], "kind": r["kind"], "claim_status": r["claim_status"],
459
+ "depends_on": r["depends_on"], "status": r["status"], "codes": [d["code"] for d in r["diagnostics"]]}
460
+ if r.get("statement_basis") is not None:
461
+ out["statement_basis"] = r["statement_basis"]
462
+ if r.get("manuscript_findings"):
463
+ out["manuscript_findings"] = [{k: f.get(k) for k in ("id", "kind", "location", "lean_evidence", "fixed_in")}
464
+ for f in r["manuscript_findings"]]
465
+ for k in ("hypotheses", "discharges", "witness"): # proposal 0003: only when set
466
+ if r.get(k) is not None:
467
+ out[k] = r[k]
468
+ return out
469
+
470
+
471
+ def claim_findings(c: dict) -> list[dict]:
472
+ """A claim's manuscript findings, normalized, each with `state` open (fixed_in null) or fixed."""
473
+ from . import claims as claims_mod
474
+ out = []
475
+ for f in claims_mod.findings_of(c):
476
+ nf = claims_mod.normalize_finding(f)
477
+ nf["state"] = "fixed" if nf.get("fixed_in") else "open"
478
+ out.append(nf)
479
+ return out
480
+
481
+
482
+ def findings_summary(rows: list[dict]) -> dict:
483
+ """What the formalization found in the manuscript, over the ledger rows (or rows carrying `id`,
484
+ `statement_basis` and `manuscript_findings`): totals by kind and by state, the claims verified for a
485
+ corrected statement, and one entry per finding. Informational: no status reads it."""
486
+ from . import claims as claims_mod
487
+ items = []
488
+ for r in rows:
489
+ for f in r.get("manuscript_findings") or []:
490
+ loc = f.get("location") if isinstance(f.get("location"), dict) else {}
491
+ items.append({"claim": r["id"], "id": f.get("id"), "kind": f.get("kind"), "label": loc.get("label"),
492
+ "summary": f.get("summary"), "fixed_in": f.get("fixed_in"), "state": f.get("state")})
493
+ return {"total": len(items), "open": sum(i["state"] == "open" for i in items),
494
+ "fixed": sum(i["state"] == "fixed" for i in items),
495
+ "by_kind": {k: sum(i["kind"] == k for i in items) for k in claims_mod.FINDING_KINDS},
496
+ "corrected_statements": [r["id"] for r in rows if r.get("statement_basis") == "corrected"],
497
+ "findings": items}
498
+
499
+
500
+ def findings_line(fs: dict | None) -> str | None:
501
+ """One line for publish --dry-run, palomar prepare and the ledger text; None when nothing was found."""
502
+ if not fs or not fs.get("total"):
503
+ return None
504
+ kinds = ", ".join(f"{n} {k}" for k, n in fs["by_kind"].items() if n)
505
+ line = (f"manuscript findings (what the formalization found): {fs['total']} ({kinds}); "
506
+ f"{fs['open']} open, {fs['fixed']} fixed in a later arXiv version")
507
+ if fs["corrected_statements"]:
508
+ line += (f"; verified for the corrected statement: {', '.join(fs['corrected_statements'])}")
509
+ return line + "; statuses unchanged"
510
+
511
+
512
+ def package_findings(pkg: dict, repo) -> dict:
513
+ """findings_summary of the claims file the ledger reads (at the gate receipt's commit, else the cache, else
514
+ HEAD), without re-checking any receipt: for `publish --dry-run` and `palomar prepare`. Unreadable input
515
+ gives an empty summary with `source` saying why."""
516
+ bound = None
517
+ rel = (pkg.get("gate") or {}).get("receipt")
518
+ rec = gate_mod.recorded_json(repo, rel) if rel else None
519
+ if isinstance(rec, dict) and core._HEX40.fullmatch(str(rec.get("commit") or "")) and not core.git(
520
+ repo, "cat-file", "-e", f"{rec['commit']}^{{commit}}").returncode:
521
+ bound = rec["commit"]
522
+ try:
523
+ claims, source = _claims_source(pkg, repo, bound)
524
+ except core.Fail as e:
525
+ claims, source = [], f"unreadable: {e}"
526
+ rows = [{"id": str(c.get("id")), "statement_basis": c.get("statement_basis"),
527
+ "manuscript_findings": claim_findings(c)} for c in claims]
528
+ return {**findings_summary(rows), "source": source}
529
+
530
+
531
+ def ledger_lines(led: dict) -> list[str]:
532
+ verdict = (f"{led['name']}: claims ledger ({led['stage']} stage): {led['package_status'].upper()}; "
533
+ f"{led['required']} required, " + ", ".join(f"{n} {s}" for s, n in led["counts"].items() if n))
534
+ out = [verdict] + [f" reason: {r}" for r in led["reasons"]]
535
+ out.append(f" claims from {led['claims_source']}"
536
+ + (f"; gate-bound commit {led['bound_commit'][:12]}" if led["bound_commit"] else ""))
537
+ fl = findings_line(led.get("manuscript_findings"))
538
+ if fl:
539
+ out.append(f" {fl}")
540
+ for r in led["claims"]:
541
+ basis = " [corrected statement]" if r.get("statement_basis") == "corrected" else ""
542
+ tag = "" if r["required"] else (" [internal, judged by the comparator]" if r.get("judged_internal")
543
+ else f" [{r['claim_status']}]")
544
+ out.append(f" {r['status']:<12} {r['id']} ({r['decl']})" + tag + basis)
545
+ out += [f" {d['code']}: {d['detail']}" for d in r["diagnostics"]]
546
+ for h in r.get("hypotheses") or []:
547
+ how = (f"discharged (proof {h['by']['proof']}, corollary {h['by']['corollary']})"
548
+ if h["state"] == "discharged" else "outstanding" + (f" via {h['via']}" if h.get("via") else ""))
549
+ out.append(f" hypothesis {h['decl']}: {how}")
550
+ if r.get("witness"):
551
+ out.append(f" witness {r['witness']['claim']}: {r['witness']['state']}")
552
+ for f in r.get("manuscript_findings") or []:
553
+ loc = f.get("location") or {}
554
+ where = ", ".join([str(loc.get("label"))] + [f"{k.replace('_', ' ')} {loc[k]}"
555
+ for k in ("page", "tex_line") if loc.get(k)])
556
+ state = f"fixed in {f['fixed_in']}" if f.get("fixed_in") else "open"
557
+ out.append(f" finding {f.get('id')} ({f.get('kind')}; {where}): {state}: {f.get('summary')}")
558
+ out.append(f" ledger_digest: {led['ledger_digest']}")
559
+ if led["claims"]:
560
+ out.append(verdict)
561
+ return out
562
+
563
+
564
+ def first_open(led: dict) -> str | None:
565
+ """`<claim id>: <code>` of the first required claim that is not verified, for a one-line reason."""
566
+ for r in led["claims"]:
567
+ if r["required"] and r["status"] not in CLOSED:
568
+ return f"{r['id']}: {r['diagnostics'][0]['code']}" if r["diagnostics"] else r["id"]
569
+ return None
570
+
571
+
572
+ def summary(led: dict) -> str:
573
+ """One line: the package status and why (the first reason, else the first open claim)."""
574
+ if led["package_status"] == "ready" and led.get("conditional_required"):
575
+ hs = ", ".join(led.get("outstanding_hypotheses") or []) or "none (all discharged)"
576
+ return (f"claims ledger ready: {led['required']} required claim(s) verified or conditional (conditional: "
577
+ f"{len(led['conditional_required'])}; outstanding hypotheses: {hs}) ({led['ledger_digest'][:19]}…)")
578
+ if led["package_status"] == "ready":
579
+ return f"claims ledger ready: {led['required']} required claim(s) verified ({led['ledger_digest'][:19]}…)"
580
+ why = led["reasons"][0] if led["reasons"] else "not ready"
581
+ fo = first_open(led)
582
+ return f"claims ledger {led['package_status']}: {why}" + (f"; first: {fo}" if fo else "")