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.
- lean_pkg/__init__.py +3 -0
- lean_pkg/adapters/__init__.py +148 -0
- lean_pkg/adapters/github.py +65 -0
- lean_pkg/adapters/leansearch.py +68 -0
- lean_pkg/adapters/loogle.py +45 -0
- lean_pkg/adapters/palomar.py +170 -0
- lean_pkg/adapters/reservoir.py +127 -0
- lean_pkg/anchor.py +678 -0
- lean_pkg/audit.py +716 -0
- lean_pkg/binding_file.py +446 -0
- lean_pkg/blueprint.py +213 -0
- lean_pkg/build_scope.py +282 -0
- lean_pkg/ci_github.py +917 -0
- lean_pkg/claim_axioms.py +421 -0
- lean_pkg/claims.py +1155 -0
- lean_pkg/claims_mark.py +197 -0
- lean_pkg/cli.py +5208 -0
- lean_pkg/cli_parser.py +768 -0
- lean_pkg/command_tree.py +615 -0
- lean_pkg/comparator_config.py +990 -0
- lean_pkg/comparator_contracts.py +382 -0
- lean_pkg/comparator_receipt.py +2854 -0
- lean_pkg/comparator_stage.py +623 -0
- lean_pkg/comparator_types.py +830 -0
- lean_pkg/container.py +172 -0
- lean_pkg/core.py +1570 -0
- lean_pkg/coverage.py +1278 -0
- lean_pkg/data/stacks/lts-2026.10.yaml +73 -0
- lean_pkg/data/toolchain-advisories.yaml +77 -0
- lean_pkg/data/upgrade-breaking.yaml +20 -0
- lean_pkg/data/verify-workflow-pins.yaml +14 -0
- lean_pkg/deps_closure.py +512 -0
- lean_pkg/deps_fill.py +445 -0
- lean_pkg/dup_constants.py +448 -0
- lean_pkg/exercise.py +828 -0
- lean_pkg/exercise_forbid.py +288 -0
- lean_pkg/export_paths.py +77 -0
- lean_pkg/extract.py +1172 -0
- lean_pkg/extract_decls.py +501 -0
- lean_pkg/extract_ledger.py +1408 -0
- lean_pkg/extract_summary.py +132 -0
- lean_pkg/extract_types.py +502 -0
- lean_pkg/extract_write.py +138 -0
- lean_pkg/formalization.py +1078 -0
- lean_pkg/formalization_kept.py +182 -0
- lean_pkg/fresh_repo.py +709 -0
- lean_pkg/gate.py +2141 -0
- lean_pkg/headline.py +211 -0
- lean_pkg/help_topics.py +442 -0
- lean_pkg/holes.py +289 -0
- lean_pkg/host_routes.py +376 -0
- lean_pkg/hypotheses.py +788 -0
- lean_pkg/index.py +1749 -0
- lean_pkg/json_stdout.py +48 -0
- lean_pkg/lake_hygiene.py +289 -0
- lean_pkg/lean_diag.py +280 -0
- lean_pkg/lean_scan.py +1300 -0
- lean_pkg/ledger.py +582 -0
- lean_pkg/next_step.py +510 -0
- lean_pkg/page.py +1831 -0
- lean_pkg/page_html.py +153 -0
- lean_pkg/palomar.py +316 -0
- lean_pkg/palomar_check.py +1027 -0
- lean_pkg/port_modules.py +677 -0
- lean_pkg/prior_art.py +286 -0
- lean_pkg/producer.py +212 -0
- lean_pkg/producer_skew.py +208 -0
- lean_pkg/public_safety.py +1487 -0
- lean_pkg/publish.py +402 -0
- lean_pkg/rebase.py +984 -0
- lean_pkg/receipt.py +2385 -0
- lean_pkg/receipt_check.py +1064 -0
- lean_pkg/receipt_ci.py +660 -0
- lean_pkg/receipt_systemd.py +890 -0
- lean_pkg/recommended.py +232 -0
- lean_pkg/report.py +727 -0
- lean_pkg/reservoir.py +203 -0
- lean_pkg/scaffold.py +588 -0
- lean_pkg/schemas/formalization-0.4.schema.json +344 -0
- lean_pkg/schemas/formalization-0.4.schema.source.txt +15 -0
- lean_pkg/scripts/ClaimAxioms.lean +47 -0
- lean_pkg/scripts/ContractsOnly.lean +300 -0
- lean_pkg/scripts/DupConstants.lean +149 -0
- lean_pkg/scripts/HypProbe.lean +257 -0
- lean_pkg/scripts/comparator-check.sh +396 -0
- lean_pkg/scripts/verify-comparator.sh +135 -0
- lean_pkg/seal_bundle.py +647 -0
- lean_pkg/search.py +865 -0
- lean_pkg/site_profiles/easley.yaml +10 -0
- lean_pkg/site_profiles/github-actions.yaml +12 -0
- lean_pkg/sites.py +225 -0
- lean_pkg/stacks.py +373 -0
- lean_pkg/statements_module.py +217 -0
- lean_pkg/templates/Apache-2.0.txt +202 -0
- lean_pkg/toolchain_advisories.py +225 -0
- lean_pkg/upgrade.py +706 -0
- lean_pkg/verify.py +495 -0
- lean_pkg-0.25.0.dist-info/METADATA +93 -0
- lean_pkg-0.25.0.dist-info/RECORD +103 -0
- lean_pkg-0.25.0.dist-info/WHEEL +5 -0
- lean_pkg-0.25.0.dist-info/entry_points.txt +5 -0
- lean_pkg-0.25.0.dist-info/licenses/LICENSE +202 -0
- lean_pkg-0.25.0.dist-info/top_level.txt +1 -0
lean_pkg/claims.py
ADDED
|
@@ -0,0 +1,1155 @@
|
|
|
1
|
+
# lean-pkg claims -- named, reusable results declared next to the Lean source
|
|
2
|
+
"""Claims: `claims.yaml` (schema `claims/1`) at a package repository's root.
|
|
3
|
+
|
|
4
|
+
A claim is a named mathematical object or result someone might reuse. The file
|
|
5
|
+
travels with the commit; the registry only caches the last synced copy (with
|
|
6
|
+
the commit it was read at) so search works offline. `claims sync` reads the
|
|
7
|
+
file at HEAD, `claims list` prints the cache, `claims check` re-validates it.
|
|
8
|
+
Nothing derived is typed by hand; nothing hand-authored is inferred.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import pathlib
|
|
14
|
+
import re
|
|
15
|
+
import sys
|
|
16
|
+
|
|
17
|
+
import yaml
|
|
18
|
+
|
|
19
|
+
from . import core
|
|
20
|
+
from . import index as idx
|
|
21
|
+
from . import lean_scan
|
|
22
|
+
from . import statements_module as stm
|
|
23
|
+
|
|
24
|
+
CLAIMS_SCHEMA = "claims/1"
|
|
25
|
+
SUPPORTED_CLAIMS_SCHEMAS = (CLAIMS_SCHEMA,)
|
|
26
|
+
DEFAULT_CLAIMS_FILE = "claims.yaml"
|
|
27
|
+
CLAIMS_TOP_KEYS = ("schema", "package", "claims")
|
|
28
|
+
# `statements_module` (proposal 0003, #369): the one module of Prop definitions a Challenge may import, so a
|
|
29
|
+
# hypothesis can be named in the Challenge type (statements_module.py). Optional; absent means none.
|
|
30
|
+
OPTIONAL_TOP_KEYS = ("statements_module",)
|
|
31
|
+
CLAIM_KEYS = ("id", "decl", "kind", "summary", "aliases", "keywords", "file", "status",
|
|
32
|
+
"superseded_by", "citation", "depends_on")
|
|
33
|
+
REQUIRED_CLAIM_KEYS = ("id", "decl", "kind", "summary", "file", "status")
|
|
34
|
+
CLAIM_DEFAULTS = {"aliases": [], "keywords": [], "superseded_by": None, "citation": None,
|
|
35
|
+
"depends_on": []}
|
|
36
|
+
CLAIM_KINDS = ("definition", "lemma", "theorem", "construction", "library")
|
|
37
|
+
CLAIM_STATUSES = ("reusable", "internal", "experimental", "superseded")
|
|
38
|
+
# Optional claim keys (#6 field report): accepted by claims/1, kept in the normalized claim only when set, so
|
|
39
|
+
# a claims file without them normalizes (and caches) exactly as before. `manuscript_findings` records what the
|
|
40
|
+
# formalization found in the manuscript (a misprint, a proof gap) without lowering any status;
|
|
41
|
+
# `statement_basis: corrected` says the claim is verified for the corrected statement (required with a misprint).
|
|
42
|
+
# `judged_as` (#CM): the comparator theorem name that judges this claim, when the Challenge theorem is not named
|
|
43
|
+
# after the claim's decl (`Audit.exit_mean` for `Pkg.integral_eval_exitTimeTrunc_Ioo`). It replaces the naming
|
|
44
|
+
# rule for that claim: the claim is covered by exactly that `theorem_names` entry and by nothing else, and the
|
|
45
|
+
# name credits no other claim (comparator_config.claim_covered).
|
|
46
|
+
# `hypotheses`, `discharges`, `witness` (proposal 0003, stage H2, #320): a conditional claim names the assumptions
|
|
47
|
+
# its declaration takes as explicit binders; a corollary claim says which hypotheses of another claim it removes,
|
|
48
|
+
# and with which proof claims; a witness claim shows that the hypotheses can hold together. Same package only
|
|
49
|
+
# (open question 2). The ledger does not evaluate them yet: a claim using any of them is `hypotheses-unchecked`.
|
|
50
|
+
OPTIONAL_CLAIM_KEYS = ("statement_basis", "manuscript_findings", "judged_as", "hypotheses", "discharges", "witness")
|
|
51
|
+
CONDITIONAL_KEYS = ("hypotheses", "discharges", "witness")
|
|
52
|
+
DISCHARGE_KEYS = ("claim", "hypotheses", "proofs")
|
|
53
|
+
CROSS_PACKAGE_DISCHARGE = "cross-package discharge is not implemented (proposal 0003, open question 2)"
|
|
54
|
+
JUDGED_KINDS = ("theorem", "lemma") # comparator_config.CLAIM_KINDS: what a configuration can judge
|
|
55
|
+
STATEMENT_BASES = ("as-printed", "corrected")
|
|
56
|
+
FINDING_KEYS = ("id", "kind", "location", "summary", "lean_evidence", "fixed_in")
|
|
57
|
+
FINDING_KINDS = ("misprint", "proof-gap")
|
|
58
|
+
LOCATION_KEYS = ("label", "tex_line", "page")
|
|
59
|
+
REQUIRED_LOCATION_KEYS = ("label",)
|
|
60
|
+
EVIDENCE_KEYS = ("decl", "file")
|
|
61
|
+
FIXED_IN_RE = re.compile(r"^arXiv:(\d{4}\.\d{4,5}|[a-z][a-z-]*(\.[A-Z]{2})?/\d{7})v[1-9][0-9]*$")
|
|
62
|
+
SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$")
|
|
63
|
+
CLAIM_ID_RE = re.compile(r"^([A-Za-z0-9][A-Za-z0-9._-]*)/([a-z0-9][a-z0-9-]*)$")
|
|
64
|
+
KEYWORD_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def slug_of_decl(decl: str) -> str:
|
|
68
|
+
"""Kebab-case slug of a Lean name: `Demo.foo_le_bar` -> `demo-foo-le-bar`."""
|
|
69
|
+
s = re.sub(r"[^a-z0-9]+", "-", str(decl).lower()).strip("-")
|
|
70
|
+
return s or "claim"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def package_trust(pkg: dict) -> str:
|
|
74
|
+
"""The package's trust as the index computes it from the registry's evidence pointers:
|
|
75
|
+
palomar (a registered, not withdrawn id), comparator, lower-tier, else none."""
|
|
76
|
+
if any(p.get("id") and p.get("version") and not p.get("withdrawn_at")
|
|
77
|
+
for p in (pkg.get("palomar") or []) if isinstance(p, dict)):
|
|
78
|
+
return "palomar"
|
|
79
|
+
gate = pkg.get("gate") or {}
|
|
80
|
+
if gate.get("comparator"):
|
|
81
|
+
return "comparator"
|
|
82
|
+
if gate.get("receipt"):
|
|
83
|
+
return "lower-tier"
|
|
84
|
+
return "none"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
# --------------------------------------------------------------------------
|
|
88
|
+
# schema: load, validate, dump
|
|
89
|
+
|
|
90
|
+
def load_claims_text(text: str, where: str) -> dict:
|
|
91
|
+
try:
|
|
92
|
+
data = yaml.safe_load(text)
|
|
93
|
+
except yaml.YAMLError as e:
|
|
94
|
+
raise core.Fail(f"{where}: not valid YAML: {e}") from e
|
|
95
|
+
if not isinstance(data, dict):
|
|
96
|
+
raise core.Fail(f"{where}: top level is not a mapping")
|
|
97
|
+
return data
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def normalize_finding(f: dict) -> dict:
|
|
101
|
+
"""A manuscript finding in FINDING_KEYS order, its location with every LOCATION_KEYS key (null filled)."""
|
|
102
|
+
out = {k: f.get(k) for k in FINDING_KEYS}
|
|
103
|
+
loc = f.get("location")
|
|
104
|
+
if isinstance(loc, dict):
|
|
105
|
+
out["location"] = {k: loc.get(k) for k in LOCATION_KEYS}
|
|
106
|
+
return out
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def normalize_claim(c: dict) -> dict:
|
|
110
|
+
"""A claim with every key present, in CLAIM_KEYS order (defaults filled), then each OPTIONAL_CLAIM_KEYS key
|
|
111
|
+
that is set (a null basis or an empty findings list is left out, so older caches compare equal)."""
|
|
112
|
+
out = {k: (c[k] if k in c else CLAIM_DEFAULTS.get(k)) for k in CLAIM_KEYS}
|
|
113
|
+
if c.get("statement_basis") is not None:
|
|
114
|
+
out["statement_basis"] = c["statement_basis"]
|
|
115
|
+
if c.get("judged_as") is not None:
|
|
116
|
+
out["judged_as"] = c["judged_as"]
|
|
117
|
+
if c.get("manuscript_findings"):
|
|
118
|
+
fs = c["manuscript_findings"]
|
|
119
|
+
out["manuscript_findings"] = [normalize_finding(f) if isinstance(f, dict) else f for f in fs] \
|
|
120
|
+
if isinstance(fs, list) else fs
|
|
121
|
+
if c.get("hypotheses"): # [] or absent: not conditional, normalized exactly as before
|
|
122
|
+
out["hypotheses"] = c["hypotheses"]
|
|
123
|
+
if c.get("discharges") is not None:
|
|
124
|
+
d = c["discharges"]
|
|
125
|
+
out["discharges"] = {k: d.get(k) for k in DISCHARGE_KEYS} if isinstance(d, dict) and set(d) == set(
|
|
126
|
+
DISCHARGE_KEYS) else d
|
|
127
|
+
if c.get("witness") is not None:
|
|
128
|
+
out["witness"] = c["witness"]
|
|
129
|
+
return out
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def uses_conditional_keys(c) -> list[str]:
|
|
133
|
+
"""The CONDITIONAL_KEYS a claim sets: a non-empty hypotheses list, a discharges, a witness ([] for none)."""
|
|
134
|
+
if not isinstance(c, dict):
|
|
135
|
+
return []
|
|
136
|
+
return [k for k in CONDITIONAL_KEYS if (c.get(k) if k == "hypotheses" else c.get(k) is not None)]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def findings_of(c) -> list[dict]:
|
|
140
|
+
"""A claim's manuscript findings that are mappings ([] when the key is absent or malformed)."""
|
|
141
|
+
fs = c.get("manuscript_findings") if isinstance(c, dict) else None
|
|
142
|
+
return [f for f in fs if isinstance(f, dict)] if isinstance(fs, list) else []
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _evidence_ref(e, claim_file) -> tuple[str, str] | None:
|
|
146
|
+
"""(decl, file) of one lean_evidence entry: a Lean name (looked up in the claim's file) or {decl, file}."""
|
|
147
|
+
if isinstance(e, str):
|
|
148
|
+
return e, claim_file
|
|
149
|
+
if isinstance(e, dict) and set(e) == set(EVIDENCE_KEYS):
|
|
150
|
+
return e.get("decl"), e.get("file")
|
|
151
|
+
return None
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _finding_errors(f, where: str, claim_file) -> list[str]:
|
|
155
|
+
if not isinstance(f, dict):
|
|
156
|
+
return [f"{where} must be a mapping with keys {list(FINDING_KEYS)}"]
|
|
157
|
+
extra = sorted(set(f) - set(FINDING_KEYS))
|
|
158
|
+
missing = [k for k in FINDING_KEYS if k not in f]
|
|
159
|
+
errors = []
|
|
160
|
+
if extra:
|
|
161
|
+
errors.append(f"{where}: unknown key(s) {extra} (a manuscript finding has exactly {list(FINDING_KEYS)})")
|
|
162
|
+
if missing:
|
|
163
|
+
errors.append(f"{where}: missing key(s) {missing}")
|
|
164
|
+
if extra or missing:
|
|
165
|
+
return errors
|
|
166
|
+
if not (isinstance(f["id"], str) and SLUG_RE.match(f["id"])):
|
|
167
|
+
errors.append(f"{where}.id must be a slug [a-z0-9][a-z0-9-]*, got {f['id']!r}")
|
|
168
|
+
if f["kind"] not in FINDING_KINDS:
|
|
169
|
+
errors.append(f"{where}.kind must be one of {FINDING_KINDS}, got {f['kind']!r}")
|
|
170
|
+
loc = f["location"]
|
|
171
|
+
if not isinstance(loc, dict):
|
|
172
|
+
errors.append(f"{where}.location must be a mapping with keys {list(LOCATION_KEYS)} (label required)")
|
|
173
|
+
else:
|
|
174
|
+
lx = sorted(set(loc) - set(LOCATION_KEYS))
|
|
175
|
+
lm = [k for k in REQUIRED_LOCATION_KEYS if k not in loc]
|
|
176
|
+
if lx:
|
|
177
|
+
errors.append(f"{where}.location: unknown key(s) {lx} (allowed {list(LOCATION_KEYS)})")
|
|
178
|
+
if lm:
|
|
179
|
+
errors.append(f"{where}.location: missing key(s) {lm} (the manuscript's label, e.g. a "
|
|
180
|
+
f"theorem or equation number)")
|
|
181
|
+
if "label" in loc and not _one_line(loc["label"], 120):
|
|
182
|
+
errors.append(f"{where}.location.label must be one line of at most 120 characters; "
|
|
183
|
+
f"{_line_why(loc['label'], 120)}")
|
|
184
|
+
for k in ("tex_line", "page"):
|
|
185
|
+
v = loc.get(k)
|
|
186
|
+
if v is not None and not (isinstance(v, int) and not isinstance(v, bool) and v >= 1):
|
|
187
|
+
errors.append(f"{where}.location.{k} must be null or a positive integer, got {v!r}")
|
|
188
|
+
if not _one_line(f["summary"]):
|
|
189
|
+
errors.append(f"{where}.summary must be one sentence (one line, at most 300 characters); "
|
|
190
|
+
f"{_line_why(f['summary'])}")
|
|
191
|
+
ev = f["lean_evidence"]
|
|
192
|
+
if not isinstance(ev, list):
|
|
193
|
+
errors.append(f"{where}.lean_evidence must be a list of Lean declaration names or {{decl, file}} mappings")
|
|
194
|
+
else:
|
|
195
|
+
for j, e in enumerate(ev):
|
|
196
|
+
ref = _evidence_ref(e, claim_file)
|
|
197
|
+
if ref is None:
|
|
198
|
+
errors.append(f"{where}.lean_evidence[{j}] must be a Lean declaration name or a mapping with "
|
|
199
|
+
f"exactly {list(EVIDENCE_KEYS)}, got {e!r}")
|
|
200
|
+
continue
|
|
201
|
+
decl, rel = ref
|
|
202
|
+
if not lean_scan.is_name(decl) or decl == TODO:
|
|
203
|
+
errors.append(f"{where}.lean_evidence[{j}] must name a Lean declaration, got {decl!r}")
|
|
204
|
+
if isinstance(e, dict) and not (idx._is_rel(rel) and str(rel).endswith(".lean")):
|
|
205
|
+
errors.append(f"{where}.lean_evidence[{j}].file must be a repo-relative .lean path, got {rel!r}")
|
|
206
|
+
fx = f["fixed_in"]
|
|
207
|
+
if fx is not None and not (isinstance(fx, str) and FIXED_IN_RE.match(fx)):
|
|
208
|
+
errors.append(f"{where}.fixed_in must be null or arXiv:<id>v<N> (e.g. arXiv:2501.01234v2), got {fx!r}")
|
|
209
|
+
return errors
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _optional_errors(c: dict, where: str) -> list[str]:
|
|
213
|
+
"""statement_basis and manuscript_findings (both optional). A claim with a misprint finding is verified only
|
|
214
|
+
for the corrected statement, so it must say `statement_basis: corrected`; `corrected` without a recorded
|
|
215
|
+
misprint names no correction and is refused too."""
|
|
216
|
+
errors = []
|
|
217
|
+
basis = c.get("statement_basis")
|
|
218
|
+
if basis is not None and basis not in STATEMENT_BASES:
|
|
219
|
+
errors.append(f"{where}.statement_basis must be null or one of {STATEMENT_BASES}, got {basis!r}")
|
|
220
|
+
fs = c.get("manuscript_findings")
|
|
221
|
+
if fs is None:
|
|
222
|
+
fs = []
|
|
223
|
+
if not isinstance(fs, list):
|
|
224
|
+
return errors + [f"{where}.manuscript_findings must be a list of findings"]
|
|
225
|
+
for j, f in enumerate(fs):
|
|
226
|
+
errors += _finding_errors(f, f"{where}.manuscript_findings[{j}]", c.get("file"))
|
|
227
|
+
judged = c.get("judged_as")
|
|
228
|
+
if judged is not None:
|
|
229
|
+
if not (isinstance(judged, str) and lean_scan.is_name(judged)) or judged == TODO:
|
|
230
|
+
errors.append(f"{where}.judged_as must be null or the full Lean name of a comparator theorem (a "
|
|
231
|
+
f"theorem_names entry), got {judged!r}")
|
|
232
|
+
elif c.get("kind") not in JUDGED_KINDS:
|
|
233
|
+
errors.append(f"{where} ({c.get('id')}): judged_as is set but kind is {c.get('kind')!r}; a comparator "
|
|
234
|
+
f"configuration judges only {' and '.join(JUDGED_KINDS)} claims")
|
|
235
|
+
errors += _conditional_errors(c, where)
|
|
236
|
+
misprints = [f.get("id") for f in fs if isinstance(f, dict) and f.get("kind") == "misprint"]
|
|
237
|
+
if misprints and basis != "corrected":
|
|
238
|
+
errors.append(f"{where} ({c.get('id')}): misprint finding(s) {misprints} need statement_basis: corrected "
|
|
239
|
+
f"(the claim is verified for the corrected statement, not the printed one), got {basis!r}")
|
|
240
|
+
if basis == "corrected" and not misprints:
|
|
241
|
+
errors.append(f"{where} ({c.get('id')}): statement_basis corrected needs a misprint finding naming the "
|
|
242
|
+
f"correction")
|
|
243
|
+
return errors
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _name_list_errors(v, where: str, what: str) -> list[str]:
|
|
247
|
+
"""A list of distinct fully qualified Lean names (the decl grammar), never the TODO placeholder."""
|
|
248
|
+
if not isinstance(v, list):
|
|
249
|
+
return [f"{where} must be a list of fully qualified Lean names ({what}), got {v!r}"]
|
|
250
|
+
errors = []
|
|
251
|
+
for j, x in enumerate(v):
|
|
252
|
+
if x == TODO:
|
|
253
|
+
errors.append(f"{where}[{j}] is the placeholder {TODO}; name the declaration of {what}")
|
|
254
|
+
elif not (isinstance(x, str) and lean_scan.is_name(x)):
|
|
255
|
+
errors.append(f"{where}[{j}] must be the fully qualified Lean name of {what}, got {x!r}")
|
|
256
|
+
dups = sorted({x for x in v if isinstance(x, str) and v.count(x) > 1})
|
|
257
|
+
if dups:
|
|
258
|
+
errors.append(f"{where} repeats {dups} (list each name once)")
|
|
259
|
+
return errors
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _conditional_errors(c: dict, where: str) -> list[str]:
|
|
263
|
+
"""hypotheses, discharges and witness on one claim (proposal 0003, stage H2); the rules that read another
|
|
264
|
+
claim of the file are in _conditional_cross_errors."""
|
|
265
|
+
errors = []
|
|
266
|
+
cid, kind = c.get("id"), c.get("kind")
|
|
267
|
+
hyps = c.get("hypotheses")
|
|
268
|
+
if hyps is not None:
|
|
269
|
+
errors += _name_list_errors(hyps, f"{where}.hypotheses", "an assumption (a def or inductive Prop)")
|
|
270
|
+
if hyps and kind not in JUDGED_KINDS:
|
|
271
|
+
errors.append(f"{where} ({cid}): hypotheses is set but kind is {kind!r}; only "
|
|
272
|
+
f"{' and '.join(JUDGED_KINDS)} claims take hypotheses")
|
|
273
|
+
d = c.get("discharges")
|
|
274
|
+
if d is not None:
|
|
275
|
+
if not isinstance(d, dict) or set(d) != set(DISCHARGE_KEYS):
|
|
276
|
+
got = sorted(map(str, d)) if isinstance(d, dict) else repr(d)
|
|
277
|
+
errors.append(f"{where}.discharges must be a mapping with exactly the keys {list(DISCHARGE_KEYS)}, "
|
|
278
|
+
f"got {got}")
|
|
279
|
+
else:
|
|
280
|
+
if kind not in JUDGED_KINDS:
|
|
281
|
+
errors.append(f"{where} ({cid}): discharges is set but kind is {kind!r}; a corollary is a "
|
|
282
|
+
f"{' or '.join(JUDGED_KINDS)} claim")
|
|
283
|
+
t = d["claim"]
|
|
284
|
+
if not (isinstance(t, str) and CLAIM_ID_RE.match(t)):
|
|
285
|
+
errors.append(f"{where}.discharges.claim must be a claim id <package>/<slug>, got {t!r}")
|
|
286
|
+
elif t == cid:
|
|
287
|
+
errors.append(f"{where} ({cid}): discharges.claim names the claim itself; a corollary discharges "
|
|
288
|
+
f"hypotheses of another claim")
|
|
289
|
+
dh = d["hypotheses"]
|
|
290
|
+
errors += _name_list_errors(dh, f"{where}.discharges.hypotheses", "a discharged assumption")
|
|
291
|
+
if isinstance(dh, list) and not dh:
|
|
292
|
+
errors.append(f"{where}.discharges.hypotheses must name at least one hypothesis of "
|
|
293
|
+
f"discharges.claim")
|
|
294
|
+
ps = d["proofs"]
|
|
295
|
+
if not isinstance(ps, list) or not all(isinstance(x, str) and CLAIM_ID_RE.match(x) for x in ps):
|
|
296
|
+
errors.append(f"{where}.discharges.proofs must be a list of claim ids <package>/<slug>, one per "
|
|
297
|
+
f"discharged hypothesis, got {ps!r}")
|
|
298
|
+
else:
|
|
299
|
+
if isinstance(dh, list) and len(ps) != len(dh):
|
|
300
|
+
errors.append(f"{where} ({cid}): discharges.proofs has {len(ps)} claim id(s) and "
|
|
301
|
+
f"discharges.hypotheses {len(dh)}; give one proof claim per discharged "
|
|
302
|
+
f"hypothesis, in the same order")
|
|
303
|
+
if cid in ps:
|
|
304
|
+
errors.append(f"{where} ({cid}): discharges.proofs names the claim itself; a proof claim "
|
|
305
|
+
f"proves the hypothesis, the corollary removes it")
|
|
306
|
+
w = c.get("witness")
|
|
307
|
+
if w is not None:
|
|
308
|
+
if not (isinstance(w, str) and CLAIM_ID_RE.match(w)):
|
|
309
|
+
errors.append(f"{where}.witness must be a claim id <package>/<slug>, got {w!r}")
|
|
310
|
+
elif w == cid:
|
|
311
|
+
errors.append(f"{where} ({cid}): witness names the claim itself; a witness is another claim showing "
|
|
312
|
+
f"that the hypotheses can hold together")
|
|
313
|
+
if not (isinstance(hyps, list) and hyps):
|
|
314
|
+
errors.append(f"{where} ({cid}): witness is set but the claim has no hypotheses; a witness shows "
|
|
315
|
+
f"that the hypotheses of a conditional claim can hold together")
|
|
316
|
+
return errors
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _conditional_cross_errors(claims: list, by_id: dict, pkg_name: str | None) -> list[str]:
|
|
320
|
+
"""The hypotheses rules that read another claim of the file: the discharges target, after following
|
|
321
|
+
superseded_by, its proof claims and the witness claim."""
|
|
322
|
+
errors: list[str] = []
|
|
323
|
+
|
|
324
|
+
def _local(ref: str, cid: str, key: str) -> dict | None:
|
|
325
|
+
if pkg_name and not ref.startswith(pkg_name + "/"):
|
|
326
|
+
errors.append(f"{cid}: {key} {ref!r} is a claim of another package: {CROSS_PACKAGE_DISCHARGE}")
|
|
327
|
+
return None
|
|
328
|
+
if ref not in by_id:
|
|
329
|
+
errors.append(f"{cid}: {key} {ref!r} is not a claim in this file")
|
|
330
|
+
return None
|
|
331
|
+
return by_id[ref]
|
|
332
|
+
|
|
333
|
+
for c in claims:
|
|
334
|
+
if not isinstance(c, dict) or not isinstance(c.get("id"), str):
|
|
335
|
+
continue
|
|
336
|
+
cid = c["id"]
|
|
337
|
+
d = c.get("discharges")
|
|
338
|
+
if isinstance(d, dict) and set(d) == set(DISCHARGE_KEYS):
|
|
339
|
+
t = d["claim"]
|
|
340
|
+
target = _local(t, cid, "discharges.claim") if (
|
|
341
|
+
isinstance(t, str) and CLAIM_ID_RE.match(t) and t != cid) else None
|
|
342
|
+
seen = [t]
|
|
343
|
+
while target is not None and isinstance(target.get("superseded_by"), str) \
|
|
344
|
+
and target["superseded_by"] in by_id and target["superseded_by"] not in seen:
|
|
345
|
+
seen.append(target["superseded_by"]) # a superseded target: follow superseded_by
|
|
346
|
+
target = by_id[seen[-1]]
|
|
347
|
+
tid = seen[-1]
|
|
348
|
+
via = f" (superseded by {tid})" if tid != t else ""
|
|
349
|
+
if target is not None and tid == cid:
|
|
350
|
+
errors.append(f"{cid}: discharges.claim {t!r} is superseded by the claim itself")
|
|
351
|
+
elif target is not None:
|
|
352
|
+
th = target.get("hypotheses")
|
|
353
|
+
th = [x for x in th if isinstance(x, str)] if isinstance(th, list) else []
|
|
354
|
+
dh = [x for x in d["hypotheses"] if isinstance(x, str)] if isinstance(d["hypotheses"], list) \
|
|
355
|
+
else []
|
|
356
|
+
if target.get("kind") not in JUDGED_KINDS:
|
|
357
|
+
errors.append(f"{cid}: discharges.claim {t!r}{via} has kind {target.get('kind')!r}; only a "
|
|
358
|
+
f"{' or '.join(JUDGED_KINDS)} claim has hypotheses to discharge")
|
|
359
|
+
missing = [x for x in dh if x not in th]
|
|
360
|
+
if missing:
|
|
361
|
+
errors.append(f"{cid}: discharges.hypotheses {missing} are not hypotheses of {tid}{via} "
|
|
362
|
+
f"(its hypotheses: {th})")
|
|
363
|
+
own = c.get("hypotheses")
|
|
364
|
+
own = [x for x in own if isinstance(x, str)] if isinstance(own, list) else []
|
|
365
|
+
rest = [x for x in th if x not in dh]
|
|
366
|
+
if not missing and set(own) != set(rest):
|
|
367
|
+
errors.append(f"{cid}: hypotheses {own} must equal the hypotheses of {tid}{via} minus the "
|
|
368
|
+
f"discharged ones, {rest}")
|
|
369
|
+
ps = d["proofs"]
|
|
370
|
+
for p in ps if isinstance(ps, list) else []:
|
|
371
|
+
if isinstance(p, str) and CLAIM_ID_RE.match(p) and p != cid:
|
|
372
|
+
pc = _local(p, cid, "discharges.proofs entry")
|
|
373
|
+
if pc is not None and pc.get("kind") not in JUDGED_KINDS:
|
|
374
|
+
errors.append(f"{cid}: discharges.proofs entry {p!r} has kind {pc.get('kind')!r}; a "
|
|
375
|
+
f"proof claim is a {' or '.join(JUDGED_KINDS)} claim")
|
|
376
|
+
w = c.get("witness")
|
|
377
|
+
if isinstance(w, str) and CLAIM_ID_RE.match(w) and w != cid:
|
|
378
|
+
wc = _local(w, cid, "witness")
|
|
379
|
+
if wc is not None and wc.get("kind") not in JUDGED_KINDS:
|
|
380
|
+
errors.append(f"{cid}: witness {w!r} has kind {wc.get('kind')!r}; a witness is a "
|
|
381
|
+
f"{' or '.join(JUDGED_KINDS)} claim")
|
|
382
|
+
return errors
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def dump_claims(doc: dict) -> str:
|
|
386
|
+
ordered = {"schema": doc["schema"], "package": doc["package"],
|
|
387
|
+
"claims": [normalize_claim(c) for c in doc["claims"]]}
|
|
388
|
+
return yaml.safe_dump(ordered, sort_keys=False, default_flow_style=False,
|
|
389
|
+
allow_unicode=True, width=100)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
SUMMARY_LIMIT = 300 # a longer claim or finding summary is refused (_one_line)
|
|
393
|
+
SUMMARY_WARN = 280 # #412: above this, `claims check` warns before the refusal
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def summary_length_warnings(doc) -> list[str]:
|
|
397
|
+
"""WARN (never a failure) for each claim and manuscript-finding summary of SUMMARY_WARN + 1 to SUMMARY_LIMIT
|
|
398
|
+
characters (counted as _one_line counts them): still accepted, one small edit away from the refusal."""
|
|
399
|
+
out: list[str] = []
|
|
400
|
+
claims = doc.get("claims") if isinstance(doc, dict) else None
|
|
401
|
+
if not isinstance(claims, list):
|
|
402
|
+
return out
|
|
403
|
+
|
|
404
|
+
def check(s, where: str) -> None:
|
|
405
|
+
if isinstance(s, str) and s.strip() and "\n" not in s.strip() and SUMMARY_WARN < len(s) <= SUMMARY_LIMIT:
|
|
406
|
+
out.append(f"{where}.summary is {len(s)} characters, close to the {SUMMARY_LIMIT}-character limit "
|
|
407
|
+
f"(a longer one is refused); shorten it to {SUMMARY_WARN} or fewer")
|
|
408
|
+
|
|
409
|
+
for i, c in enumerate(claims):
|
|
410
|
+
if not isinstance(c, dict):
|
|
411
|
+
continue
|
|
412
|
+
where = f"claims[{i}]" + (f" ({c['id']})" if isinstance(c.get("id"), str) else "")
|
|
413
|
+
check(c.get("summary"), where)
|
|
414
|
+
findings = c.get("manuscript_findings")
|
|
415
|
+
for j, f in enumerate(findings if isinstance(findings, list) else []):
|
|
416
|
+
if isinstance(f, dict):
|
|
417
|
+
check(f.get("summary"), f"{where}.manuscript_findings[{j}]")
|
|
418
|
+
return out
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def _one_line(s, limit: int = 300) -> bool:
|
|
422
|
+
return isinstance(s, str) and bool(s.strip()) and "\n" not in s.strip() and len(s) <= limit
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _line_why(s, limit: int = 300) -> str:
|
|
426
|
+
"""Why `s` fails _one_line, for the error message (field report: a 301-character single-line citation was
|
|
427
|
+
told only "must be null or one line")."""
|
|
428
|
+
if not isinstance(s, str):
|
|
429
|
+
return f"got {type(s).__name__}"
|
|
430
|
+
if not s.strip():
|
|
431
|
+
return "it is empty"
|
|
432
|
+
if "\n" in s.strip():
|
|
433
|
+
return f"it spans {len(s.strip().splitlines())} lines"
|
|
434
|
+
return f"it is {len(s)} characters, over the {limit}-character limit"
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _claim_errors(c, i: int, package: str | None) -> list[str]:
|
|
438
|
+
where = f"claims[{i}]"
|
|
439
|
+
if not isinstance(c, dict):
|
|
440
|
+
return [f"{where} must be a mapping"]
|
|
441
|
+
errors = []
|
|
442
|
+
extra = sorted(set(c) - set(CLAIM_KEYS) - set(OPTIONAL_CLAIM_KEYS))
|
|
443
|
+
missing = [k for k in REQUIRED_CLAIM_KEYS if k not in c]
|
|
444
|
+
if extra:
|
|
445
|
+
errors.append(f"{where}: unknown key(s) {extra} (schema {CLAIMS_SCHEMA} allows "
|
|
446
|
+
f"{list(CLAIM_KEYS) + list(OPTIONAL_CLAIM_KEYS)})")
|
|
447
|
+
if missing:
|
|
448
|
+
errors.append(f"{where}: missing key(s) {missing}")
|
|
449
|
+
if extra or missing:
|
|
450
|
+
return errors
|
|
451
|
+
errors += _optional_errors(c, where) # on the claim as written: normalizing drops unknown keys
|
|
452
|
+
c = normalize_claim(c)
|
|
453
|
+
m = CLAIM_ID_RE.match(str(c["id"])) if isinstance(c["id"], str) else None
|
|
454
|
+
if not m:
|
|
455
|
+
errors.append(f"{where}.id must be <package>/<slug> with slug [a-z0-9][a-z0-9-]*, got {c['id']!r}")
|
|
456
|
+
elif package is not None and m.group(1) != package:
|
|
457
|
+
errors.append(f"{where}.id {c['id']!r} must start with the package name {package!r}/")
|
|
458
|
+
if not lean_scan.is_name(c["decl"]):
|
|
459
|
+
errors.append(f"{where}.decl must be a Lean declaration name (dotted; no spaces outside «»), "
|
|
460
|
+
f"got {c['decl']!r}")
|
|
461
|
+
elif c["decl"] == TODO:
|
|
462
|
+
errors.append(f"{where} ({c['id']}): decl is the `claims migrate` placeholder {TODO}; name the declaration")
|
|
463
|
+
if isinstance(c["summary"], str) and c["summary"].strip().startswith(TODO):
|
|
464
|
+
errors.append(f"{where} ({c['id']}): summary is the `claims migrate` placeholder "
|
|
465
|
+
f"{c['summary'].strip()[:40]!r}; write the one-sentence summary")
|
|
466
|
+
if c["kind"] not in CLAIM_KINDS:
|
|
467
|
+
errors.append(f"{where}.kind must be one of {CLAIM_KINDS}, got {c['kind']!r}")
|
|
468
|
+
if c["status"] not in CLAIM_STATUSES:
|
|
469
|
+
errors.append(f"{where}.status must be one of {CLAIM_STATUSES}, got {c['status']!r}")
|
|
470
|
+
if not _one_line(c["summary"]):
|
|
471
|
+
errors.append(f"{where}.summary must be one sentence (one line, at most 300 characters); "
|
|
472
|
+
f"{_line_why(c['summary'])}")
|
|
473
|
+
if not (idx._is_rel(c["file"]) and str(c["file"]).endswith(".lean")):
|
|
474
|
+
errors.append(f"{where}.file must be a repo-relative .lean path, got {c['file']!r}")
|
|
475
|
+
if not isinstance(c["aliases"], list):
|
|
476
|
+
errors.append(f"{where}.aliases must be a list of one-line phrases (at most 120 characters each)")
|
|
477
|
+
else:
|
|
478
|
+
for j, a in enumerate(c["aliases"]):
|
|
479
|
+
if not _one_line(a, 120):
|
|
480
|
+
errors.append(f"{where}.aliases[{j}] must be a one-line phrase (at most 120 characters); "
|
|
481
|
+
f"{_line_why(a, 120)}")
|
|
482
|
+
if not isinstance(c["keywords"], list) or not all(
|
|
483
|
+
isinstance(k, str) and KEYWORD_RE.match(k) for k in c["keywords"]):
|
|
484
|
+
errors.append(f"{where}.keywords must be a list of lowercase tags ([a-z0-9-])")
|
|
485
|
+
if c["citation"] is not None and not _one_line(c["citation"]):
|
|
486
|
+
errors.append(f"{where}.citation must be null or one line of at most 300 characters; "
|
|
487
|
+
f"{_line_why(c['citation'])}")
|
|
488
|
+
sb = c["superseded_by"]
|
|
489
|
+
if sb is not None and not (isinstance(sb, str) and CLAIM_ID_RE.match(sb)):
|
|
490
|
+
errors.append(f"{where}.superseded_by must be null or a claim id, got {sb!r}")
|
|
491
|
+
if c["status"] == "superseded" and sb is None:
|
|
492
|
+
errors.append(f"{where}: status superseded needs superseded_by (claims are never deleted)")
|
|
493
|
+
if c["status"] != "superseded" and sb is not None:
|
|
494
|
+
errors.append(f"{where}: superseded_by is set but status is {c['status']!r}, not superseded")
|
|
495
|
+
if sb is not None and sb == c["id"]:
|
|
496
|
+
errors.append(f"{where}: a claim cannot supersede itself")
|
|
497
|
+
deps = c["depends_on"]
|
|
498
|
+
if not isinstance(deps, list) or not all(isinstance(d, str) and CLAIM_ID_RE.match(d) for d in deps):
|
|
499
|
+
errors.append(f"{where}.depends_on must be a list of claim ids <package>/<slug>")
|
|
500
|
+
elif c["id"] in deps:
|
|
501
|
+
errors.append(f"{where}: a claim cannot depend on itself")
|
|
502
|
+
return errors
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def validate_claims(doc, package: str | None = None) -> list[str]:
|
|
506
|
+
"""Every error in a `claims/1` document; [] when valid. Unknown keys are refused."""
|
|
507
|
+
if not isinstance(doc, dict):
|
|
508
|
+
return ["claims file is not a mapping"]
|
|
509
|
+
errors: list[str] = []
|
|
510
|
+
extra = sorted(set(doc) - set(CLAIMS_TOP_KEYS) - set(OPTIONAL_TOP_KEYS))
|
|
511
|
+
missing = [k for k in CLAIMS_TOP_KEYS if k not in doc]
|
|
512
|
+
if extra:
|
|
513
|
+
errors.append(f"unknown key(s) {extra} (schema {CLAIMS_SCHEMA} allows "
|
|
514
|
+
f"{list(CLAIMS_TOP_KEYS) + list(OPTIONAL_TOP_KEYS)})")
|
|
515
|
+
if missing:
|
|
516
|
+
errors.append(f"missing key(s) {missing}")
|
|
517
|
+
return errors
|
|
518
|
+
if stm.KEY in doc:
|
|
519
|
+
errors += stm.key_errors(doc[stm.KEY])
|
|
520
|
+
if doc["schema"] not in SUPPORTED_CLAIMS_SCHEMAS:
|
|
521
|
+
errors.append(f"schema must be one of {SUPPORTED_CLAIMS_SCHEMAS}, got {doc['schema']!r}")
|
|
522
|
+
pkg_name = doc["package"]
|
|
523
|
+
if not isinstance(pkg_name, str) or not idx.NAME_RE.fullmatch(pkg_name):
|
|
524
|
+
errors.append(f"package {pkg_name!r} must be a registry name")
|
|
525
|
+
pkg_name = None
|
|
526
|
+
elif package is not None and pkg_name != package:
|
|
527
|
+
errors.append(f"package {pkg_name!r} differs from {package!r}")
|
|
528
|
+
claims = doc["claims"]
|
|
529
|
+
if not isinstance(claims, list):
|
|
530
|
+
return errors + ["claims must be a list"]
|
|
531
|
+
for i, c in enumerate(claims):
|
|
532
|
+
errors += _claim_errors(c, i, pkg_name)
|
|
533
|
+
ids = [c.get("id") for c in claims if isinstance(c, dict)]
|
|
534
|
+
dups = sorted({i for i in ids if isinstance(i, str) and ids.count(i) > 1})
|
|
535
|
+
if dups:
|
|
536
|
+
errors.append(f"duplicate claim id(s) {dups}")
|
|
537
|
+
judged = [(c.get("judged_as"), c.get("id")) for c in claims if isinstance(c, dict)
|
|
538
|
+
and isinstance(c.get("judged_as"), str)]
|
|
539
|
+
for name in sorted({j for j, _ in judged if [k for k, _ in judged].count(j) > 1}):
|
|
540
|
+
ids = ", ".join(str(i) for k, i in judged if k == name)
|
|
541
|
+
errors.append(f"judged_as {name!r} is set on more than one claim ({ids}): a comparator theorem judges "
|
|
542
|
+
f"exactly one claim")
|
|
543
|
+
fids = [f.get("id") for c in claims for f in findings_of(c)]
|
|
544
|
+
fdups = sorted({i for i in fids if isinstance(i, str) and fids.count(i) > 1})
|
|
545
|
+
if fdups:
|
|
546
|
+
errors.append(f"duplicate manuscript finding id(s) {fdups} (a finding id is unique in the package)")
|
|
547
|
+
by_id = {c["id"]: c for c in claims if isinstance(c, dict) and isinstance(c.get("id"), str)}
|
|
548
|
+
for cid, c in by_id.items():
|
|
549
|
+
sb = c.get("superseded_by")
|
|
550
|
+
if isinstance(sb, str) and pkg_name and sb.startswith(pkg_name + "/") and sb not in by_id:
|
|
551
|
+
errors.append(f"{cid}: superseded_by {sb!r} is not a claim in this file")
|
|
552
|
+
seen = [cid]
|
|
553
|
+
while isinstance(sb, str) and sb in by_id:
|
|
554
|
+
if sb in seen:
|
|
555
|
+
errors.append(f"supersession cycle: {' -> '.join(seen + [sb])}")
|
|
556
|
+
break
|
|
557
|
+
seen.append(sb)
|
|
558
|
+
sb = by_id[sb].get("superseded_by")
|
|
559
|
+
errors += _conditional_cross_errors(claims, by_id, pkg_name)
|
|
560
|
+
for where, s in idx._strings(claims, "claims"):
|
|
561
|
+
if idx.PRIVATE_PATH_RE.search(s):
|
|
562
|
+
errors.append(f"{where} looks like a private local path: {s!r}")
|
|
563
|
+
return sorted(set(errors), key=errors.index)
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
def schema_check_text(text: str, where: str, package: str | None = None) -> tuple[int | None, list[str]]:
|
|
567
|
+
"""(claim count, errors) for a claims file's text: YAML load plus `validate_claims`, the same
|
|
568
|
+
schema check `claims sync` and `claims check` apply. The count is None when `claims` is not a list."""
|
|
569
|
+
try:
|
|
570
|
+
doc = load_claims_text(text, where)
|
|
571
|
+
except core.Fail as e:
|
|
572
|
+
return None, [str(e)]
|
|
573
|
+
claims = doc.get("claims")
|
|
574
|
+
return (len(claims) if isinstance(claims, list) else None), validate_claims(doc, package)
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
def decl_problems(read_file, claims: list[dict]) -> list[str]:
|
|
578
|
+
"""Each claim's declaration (its last name component, a «quoted» one kept whole) must occur in its file.
|
|
579
|
+
`read_file(rel) -> str | None` reads the file at the commit being checked."""
|
|
580
|
+
out = []
|
|
581
|
+
for c in claims:
|
|
582
|
+
text = read_file(c["file"])
|
|
583
|
+
last = lean_scan.last_component(str(c["decl"]))
|
|
584
|
+
if text is None:
|
|
585
|
+
out.append(f"{c['id']}: file {c['file']} is not tracked at that commit")
|
|
586
|
+
elif not lean_scan.occurs(last, text):
|
|
587
|
+
out.append(f"{c['id']}: {last!r} does not occur in {c['file']}")
|
|
588
|
+
return out
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def evidence_problems(read_file, claims: list[dict]) -> list[str]:
|
|
592
|
+
"""`decl_problems` for every manuscript finding's lean_evidence entry: a Lean name is looked up in the
|
|
593
|
+
claim's file, a {decl, file} entry in its own file, both read with `read_file` at the commit being checked.
|
|
594
|
+
Malformed entries are skipped (the schema check reports them)."""
|
|
595
|
+
refs = []
|
|
596
|
+
for c in claims:
|
|
597
|
+
for f in findings_of(c):
|
|
598
|
+
ev = f.get("lean_evidence")
|
|
599
|
+
for j, e in enumerate(ev if isinstance(ev, list) else []):
|
|
600
|
+
ref = _evidence_ref(e, c.get("file"))
|
|
601
|
+
if ref is None or not lean_scan.is_name(ref[0]) or not (
|
|
602
|
+
idx._is_rel(ref[1]) and str(ref[1]).endswith(".lean")):
|
|
603
|
+
continue
|
|
604
|
+
refs.append({"id": f"{c.get('id')} finding {f.get('id')} lean_evidence[{j}]",
|
|
605
|
+
"decl": ref[0], "file": ref[1]})
|
|
606
|
+
return decl_problems(read_file, refs)
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def _reader(repo: pathlib.Path, rev: str):
|
|
610
|
+
def read(rel: str) -> str | None:
|
|
611
|
+
b = core.git_show_bytes(repo, rel, rev)
|
|
612
|
+
return None if b is None else b.decode("utf-8", errors="replace")
|
|
613
|
+
return read
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
# --------------------------------------------------------------------------
|
|
617
|
+
# coverage: is anything synced, and is there a legacy claims.json to migrate?
|
|
618
|
+
|
|
619
|
+
LEGACY_SUFFIX = "claims.json"
|
|
620
|
+
LEGACY_PRUNE = {".git", ".lake", "lake-packages", "node_modules", ".venv", "venv", "__pycache__", "build"}
|
|
621
|
+
LEGACY_LIMIT = 10
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
def find_legacy_claims(repo: pathlib.Path) -> list[str]:
|
|
625
|
+
"""Repo-relative paths of legacy `*claims.json` files in the working tree (build and VCS
|
|
626
|
+
directories pruned; at most LEGACY_LIMIT, sorted). lean-pkg never reads them as claims."""
|
|
627
|
+
import os
|
|
628
|
+
found = []
|
|
629
|
+
for d, dirs, files in os.walk(repo):
|
|
630
|
+
dirs[:] = sorted(x for x in dirs if x not in LEGACY_PRUNE and not x.startswith("."))
|
|
631
|
+
for f in files:
|
|
632
|
+
if f.lower().endswith(LEGACY_SUFFIX):
|
|
633
|
+
found.append(pathlib.Path(d, f).relative_to(repo).as_posix())
|
|
634
|
+
return sorted(found)[:LEGACY_LIMIT]
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
def coverage(name: str, pkg: dict) -> dict:
|
|
638
|
+
"""What claims coverage a package has: `synced` (cached claims), `empty` (an empty list was
|
|
639
|
+
synced), `unsynced` (claims.yaml committed at HEAD, nothing cached) or `none` (no cached claims
|
|
640
|
+
and no claims.yaml at HEAD). claims_yaml is present|absent|unknown (no checkout)."""
|
|
641
|
+
claims, commit = pkg.get("claims") or [], pkg.get("claims_synced_commit")
|
|
642
|
+
rel = pkg.get("claims_file") or DEFAULT_CLAIMS_FILE
|
|
643
|
+
repo = core.repo_path(pkg) if pkg.get("local_path") else None
|
|
644
|
+
checkout = repo is not None and repo.is_dir() and core.git_head(repo) is not None
|
|
645
|
+
if not checkout:
|
|
646
|
+
yaml_state = "unknown"
|
|
647
|
+
else:
|
|
648
|
+
yaml_state = "present" if idx._is_rel(rel) and core.git_show_bytes(repo, rel, "HEAD") is not None \
|
|
649
|
+
else "absent"
|
|
650
|
+
legacy = find_legacy_claims(repo) if checkout and not claims else []
|
|
651
|
+
if claims:
|
|
652
|
+
cov = "synced"
|
|
653
|
+
elif commit is not None:
|
|
654
|
+
cov = "empty"
|
|
655
|
+
elif yaml_state == "present":
|
|
656
|
+
cov = "unsynced"
|
|
657
|
+
else:
|
|
658
|
+
cov = "none"
|
|
659
|
+
hint = None
|
|
660
|
+
if cov == "unsynced":
|
|
661
|
+
hint = f"{rel} is committed at HEAD but not synced: lean-pkg claims sync {name}"
|
|
662
|
+
elif cov == "none" and legacy:
|
|
663
|
+
hint = (f"legacy {legacy[0]} is not read as claims: lean-pkg claims migrate {name} --from "
|
|
664
|
+
f"{legacy[0]} --dry-run, then without --dry-run, finish the TODOs, commit {rel} and run "
|
|
665
|
+
f"lean-pkg claims sync {name}")
|
|
666
|
+
elif cov == "none" and checkout:
|
|
667
|
+
hint = (f"write {rel} (schema {CLAIMS_SCHEMA}) at the repo root, commit it, then "
|
|
668
|
+
f"lean-pkg claims sync {name}")
|
|
669
|
+
elif cov == "none":
|
|
670
|
+
hint = f"no checkout at local_path; sync from one: lean-pkg claims sync {name}"
|
|
671
|
+
return {"coverage": cov, "cached_claims": len(claims), "claims_yaml": yaml_state,
|
|
672
|
+
"claims_file": rel, "legacy_claims": legacy, "hint": hint}
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
def coverage_lines(name: str, c: dict) -> list[str]:
|
|
676
|
+
out = [f"{name}: coverage: {c['coverage']} (cached_claims: {c['cached_claims']}, "
|
|
677
|
+
f"{c['claims_file']}: {c['claims_yaml']})"]
|
|
678
|
+
out += [f" legacy: {x} (not read by lean-pkg; migrate it)" for x in c["legacy_claims"]]
|
|
679
|
+
if c["hint"]:
|
|
680
|
+
out.append(f" next: {c['hint']}")
|
|
681
|
+
return out
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
# --------------------------------------------------------------------------
|
|
685
|
+
# claims sync | list | check
|
|
686
|
+
|
|
687
|
+
def _tolerate_v2(pkg: dict) -> None:
|
|
688
|
+
for k, d in core.V3_PACKAGE_DEFAULTS.items():
|
|
689
|
+
pkg.setdefault(k, list(d) if isinstance(d, list) else d)
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
def pin_published(repo, commit: str) -> bool | None:
|
|
693
|
+
"""Is `commit` on a remote-tracking branch of the checkout (as of its last fetch)? None when the checkout
|
|
694
|
+
has no remote. A claim pinned to an unpushed commit cannot be inspected by anyone reading the registered
|
|
695
|
+
repository (field report)."""
|
|
696
|
+
if not core.git(repo, "remote").stdout.strip():
|
|
697
|
+
return None
|
|
698
|
+
p = core.git(repo, "for-each-ref", "--count=1", "--contains", commit, "--format=%(refname)", "refs/remotes")
|
|
699
|
+
return p.returncode == 0 and bool(p.stdout.strip())
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
def _unpublished_warning(name: str, head: str) -> None:
|
|
703
|
+
print(f"lean-pkg: WARN: {name}: claims are pinned at {head[:12]}, which is on no remote-tracking branch of the "
|
|
704
|
+
f"checkout (as of its last fetch): readers of the registered repository cannot inspect them; push it, "
|
|
705
|
+
f"then claims sync {name}", file=sys.stderr)
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
def do_claims_sync(reg_path, reg, events_p, name: str) -> tuple[list[str], dict]:
|
|
709
|
+
pkg = core.get_pkg(reg, name)
|
|
710
|
+
_tolerate_v2(pkg)
|
|
711
|
+
repo = core.repo_path(pkg)
|
|
712
|
+
head = core.git_head(repo) if repo.is_dir() else None
|
|
713
|
+
if head is None:
|
|
714
|
+
raise core.Fail(f"{name}: no git checkout at local_path ({repo})")
|
|
715
|
+
rel = pkg.get("claims_file") or DEFAULT_CLAIMS_FILE
|
|
716
|
+
if not idx._is_rel(rel):
|
|
717
|
+
raise core.Fail(f"{name}: claims_file must be repo-relative, got {rel!r}")
|
|
718
|
+
blob = core.git_show_bytes(repo, rel, "HEAD")
|
|
719
|
+
if blob is None:
|
|
720
|
+
if not (repo / rel).exists():
|
|
721
|
+
raise core.Fail(f"{name}: {rel} is missing in {repo} (write it at the repo root, schema "
|
|
722
|
+
f"claims/1, and commit it)")
|
|
723
|
+
raise core.Fail(f"{name}: {rel} is not committed at HEAD {head[:12]} "
|
|
724
|
+
f"(untracked files do not count; commit it first)")
|
|
725
|
+
doc = load_claims_text(blob.decode("utf-8", errors="replace"), rel)
|
|
726
|
+
if isinstance(doc.get("package"), str) and doc["package"] != name:
|
|
727
|
+
raise core.Fail(f"{name}: {rel} declares package {doc['package']!r}, not {name!r}")
|
|
728
|
+
errors = validate_claims(doc, name)
|
|
729
|
+
statements = stm.declared(doc)
|
|
730
|
+
if not errors:
|
|
731
|
+
read = _reader(repo, head)
|
|
732
|
+
errors = decl_problems(read, doc["claims"]) + evidence_problems(read, doc["claims"])
|
|
733
|
+
if statements is not None:
|
|
734
|
+
errors += stm.problems(read, statements, head)
|
|
735
|
+
if errors:
|
|
736
|
+
raise core.Fail(f"{name}: {rel} refused: " + "; ".join(errors))
|
|
737
|
+
extra = {stm.KEY: statements} if statements is not None else {}
|
|
738
|
+
claims = [normalize_claim(c) for c in doc["claims"]]
|
|
739
|
+
published = pin_published(repo, head)
|
|
740
|
+
if published is False:
|
|
741
|
+
_unpublished_warning(name, head)
|
|
742
|
+
if pkg.get("claims") == claims and pkg.get("claims_synced_commit") == head:
|
|
743
|
+
return ([f"{name}: claims already synced at {head[:12]}; nothing written"],
|
|
744
|
+
{"ok": True, "name": name, "event": "claims-noop", "commit": head,
|
|
745
|
+
"claims": len(claims), "pin_published": published, **extra})
|
|
746
|
+
pkg["claims_file"] = rel
|
|
747
|
+
pkg["claims"] = claims
|
|
748
|
+
pkg["claims_synced_commit"] = head
|
|
749
|
+
core.record(reg, events_p, pkg, "claims-synced", commit=head, file=rel, claims=len(claims))
|
|
750
|
+
core.save_registry(reg_path, reg)
|
|
751
|
+
return ([f"{name}: {len(claims)} claim(s) synced from {rel} at {head[:12]}"]
|
|
752
|
+
+ ([f"{name}: statements module {statements} ({lean_scan.module_file(statements)}): the one module a "
|
|
753
|
+
f"Challenge may import beyond Mathlib; trusted by declaration, read it"] if statements else []),
|
|
754
|
+
{"ok": True, "name": name, "event": "claims-synced", "commit": head,
|
|
755
|
+
"claims": len(claims), "pin_published": published, **extra})
|
|
756
|
+
|
|
757
|
+
|
|
758
|
+
def _targets(reg: dict, name: str | None) -> list[str]:
|
|
759
|
+
if name is not None:
|
|
760
|
+
core.get_pkg(reg, name)
|
|
761
|
+
return [name]
|
|
762
|
+
return sorted(reg.get("packages") or {})
|
|
763
|
+
|
|
764
|
+
|
|
765
|
+
def do_claims_list(reg: dict, name: str | None) -> tuple[list[str], dict]:
|
|
766
|
+
rows = []
|
|
767
|
+
for n in _targets(reg, name):
|
|
768
|
+
pkg = reg["packages"][n]
|
|
769
|
+
trust = package_trust(pkg)
|
|
770
|
+
for c in pkg.get("claims") or []:
|
|
771
|
+
row = {"package": n, "id": c.get("id"), "decl": c.get("decl"),
|
|
772
|
+
"kind": c.get("kind"), "status": c.get("status"), "trust": trust,
|
|
773
|
+
"summary": c.get("summary"),
|
|
774
|
+
"pin": pkg.get("claims_synced_commit")}
|
|
775
|
+
if c.get("hypotheses"): # proposal 0003: a claim with hypotheses is conditional, always
|
|
776
|
+
row["conditional"] = True
|
|
777
|
+
rows.append(row)
|
|
778
|
+
cov = coverage(name, reg["packages"][name]) if name is not None else None
|
|
779
|
+
if not rows:
|
|
780
|
+
if cov is not None:
|
|
781
|
+
return coverage_lines(name, cov), {"ok": True, "claims": [], **cov}
|
|
782
|
+
return (["no cached claims for any package; run `lean-pkg claims sync NAME`"],
|
|
783
|
+
{"ok": True, "claims": []})
|
|
784
|
+
head = ("ID", "KIND", "STATUS", "TRUST", "PIN", "DECL")
|
|
785
|
+
table = [head] + [(r["id"], r["kind"], str(r["status"]) + (" (conditional)" if r.get("conditional") else ""),
|
|
786
|
+
r["trust"], str(r["pin"] or "")[:12], r["decl"]) for r in rows]
|
|
787
|
+
widths = [max(len(str(t[i])) for t in table) for i in range(len(head) - 1)]
|
|
788
|
+
lines = [" ".join(str(t[i]).ljust(widths[i]) for i in range(len(head) - 1)) + " " + str(t[-1])
|
|
789
|
+
for t in table]
|
|
790
|
+
return [x.rstrip() for x in lines], {"ok": True, "claims": rows, **(cov or {})}
|
|
791
|
+
|
|
792
|
+
|
|
793
|
+
def do_claims_check(reg: dict, name: str | None) -> tuple[list[str], dict, int]:
|
|
794
|
+
reports = []
|
|
795
|
+
for n in _targets(reg, name):
|
|
796
|
+
pkg = reg["packages"][n]
|
|
797
|
+
claims = pkg.get("claims") or []
|
|
798
|
+
commit = pkg.get("claims_synced_commit")
|
|
799
|
+
rep = {"name": n, "ok": True, "claims": len(claims), "failures": [], "notes": [],
|
|
800
|
+
"warnings": summary_length_warnings({"claims": claims})}
|
|
801
|
+
if not claims and commit is None and name is None:
|
|
802
|
+
continue
|
|
803
|
+
if name is not None:
|
|
804
|
+
rep.update(coverage(n, pkg))
|
|
805
|
+
if rep["coverage"] in ("none", "unsynced"):
|
|
806
|
+
rep["failures"].append(f"no claims coverage: coverage {rep['coverage']}, cached_claims 0, "
|
|
807
|
+
f"{rep['claims_file']} {rep['claims_yaml']} at HEAD")
|
|
808
|
+
rep["failures"] += validate_claims({"schema": CLAIMS_SCHEMA, "package": n, "claims": claims}, n)
|
|
809
|
+
if claims and not core._HEX40.fullmatch(str(commit or "")):
|
|
810
|
+
rep["failures"].append(f"claims_synced_commit must be 40 lowercase hex, got {commit!r}")
|
|
811
|
+
repo = core.repo_path(pkg) if pkg.get("local_path") else None
|
|
812
|
+
if not rep["failures"] and claims:
|
|
813
|
+
if repo is None or not repo.is_dir() or core.git(repo, "cat-file", "-e", f"{commit}^{{commit}}").returncode:
|
|
814
|
+
rep["notes"].append(f"decl check skipped: no checkout holding {str(commit)[:12]}")
|
|
815
|
+
else:
|
|
816
|
+
read = _reader(repo, commit)
|
|
817
|
+
rep["failures"] += decl_problems(read, claims) + evidence_problems(read, claims)
|
|
818
|
+
rel = pkg.get("claims_file") or DEFAULT_CLAIMS_FILE
|
|
819
|
+
statements, sproblems = stm.at_commit(repo, rel, commit)
|
|
820
|
+
if statements is not None:
|
|
821
|
+
rep[stm.KEY] = statements
|
|
822
|
+
rep["failures"] += sproblems
|
|
823
|
+
if core.git_show_bytes(repo, rel, "HEAD") != core.git_show_bytes(repo, rel, commit):
|
|
824
|
+
rep["notes"].append(f"{rel} changed since {commit[:12]}; run `lean-pkg claims sync {n}`")
|
|
825
|
+
rep["ok"] = not rep["failures"]
|
|
826
|
+
reports.append(rep)
|
|
827
|
+
ok = all(r["ok"] for r in reports)
|
|
828
|
+
lines = []
|
|
829
|
+
for r in reports:
|
|
830
|
+
lines.append(f"{'PASS' if r['ok'] else 'FAIL'} {r['name']} ({r['claims']} claim(s))")
|
|
831
|
+
lines += [f" fail: {x}" for x in r["failures"]] + [f" warn: {x}" for x in r["warnings"]] \
|
|
832
|
+
+ [f" note: {x}" for x in r["notes"]]
|
|
833
|
+
if r.get("coverage") in ("none", "unsynced"):
|
|
834
|
+
lines += coverage_lines(r["name"], r)
|
|
835
|
+
lines.append(f"{len(reports)} package(s) checked: " + ("all pass" if ok else "FAILED"))
|
|
836
|
+
warnings = [f"{r['name']}: {w}" for r in reports for w in r["warnings"]]
|
|
837
|
+
return lines, {"ok": ok, "packages": reports, "warnings": warnings}, (0 if ok else 1)
|
|
838
|
+
|
|
839
|
+
|
|
840
|
+
def do_claims_check_file(path: str, name: str | None = None) -> tuple[list[str], dict, int]:
|
|
841
|
+
"""`claims check --file PATH`: the schema check on a working-copy file, before it is committed.
|
|
842
|
+
Reads no registry; NAME, when given, must be the file's `package`."""
|
|
843
|
+
p = pathlib.Path(str(path)).expanduser()
|
|
844
|
+
if not p.is_file():
|
|
845
|
+
raise core.Fail(f"claims file not found: {p}")
|
|
846
|
+
return do_claims_check_text(p.read_text(encoding="utf-8", errors="replace"), str(p), name)
|
|
847
|
+
|
|
848
|
+
|
|
849
|
+
def do_claims_check_text(text: str, where: str, name: str | None = None) -> tuple[list[str], dict, int]:
|
|
850
|
+
"""The schema check of `claims check --file` on a claims file's text read from `where` (a path, or
|
|
851
|
+
`claims.yaml at <commit>` for verify's preflight)."""
|
|
852
|
+
n, errors = schema_check_text(text, where, name)
|
|
853
|
+
count = "?" if n is None else n
|
|
854
|
+
try:
|
|
855
|
+
warnings = summary_length_warnings(load_claims_text(text, where))
|
|
856
|
+
except core.Fail: # unreadable: the schema check already says why
|
|
857
|
+
warnings = []
|
|
858
|
+
if errors:
|
|
859
|
+
lines = [f"FAIL {where}: {len(errors)} schema error(s) ({count} claim(s))"]
|
|
860
|
+
lines += [f" fail: {e}" for e in errors] + [f" warn: {w}" for w in warnings]
|
|
861
|
+
lines.append(f"FAIL {where}: fix the errors above before you commit the file you will gate")
|
|
862
|
+
else:
|
|
863
|
+
lines = [f"PASS {where}: schema ok ({count} claim(s))" + (f", {len(warnings)} warning(s)" if warnings else "")]
|
|
864
|
+
lines += [f" warn: {w}" for w in warnings]
|
|
865
|
+
return lines, {"ok": not errors, "path": where, "claims": n, "errors": errors, "warnings": warnings}, \
|
|
866
|
+
(1 if errors else 0)
|
|
867
|
+
|
|
868
|
+
|
|
869
|
+
# --------------------------------------------------------------------------
|
|
870
|
+
# claims migrate: a legacy claims.json -> a claims/1 skeleton in the checkout (never the registry)
|
|
871
|
+
|
|
872
|
+
LEGACY_FIELDS = {
|
|
873
|
+
"id": ("id", "claim_id", "key", "slug", "label", "name"),
|
|
874
|
+
"decl": ("decl", "lean_decl", "declaration", "lean_name", "lean_theorem", "lean", "theorem"),
|
|
875
|
+
"kind": ("kind", "claim_kind", "type"),
|
|
876
|
+
"summary": ("summary", "statement", "description", "title", "text", "claim"),
|
|
877
|
+
"file": ("file", "lean_file", "lean_path", "path", "source"),
|
|
878
|
+
"status": ("status",),
|
|
879
|
+
"citation": ("citation", "paper_ref", "manuscript_ref", "reference", "ref", "locator", "paper"),
|
|
880
|
+
"keywords": ("keywords", "tags"),
|
|
881
|
+
"aliases": ("aliases",),
|
|
882
|
+
"depends_on": ("depends_on", "dependencies", "deps"),
|
|
883
|
+
}
|
|
884
|
+
KIND_ALIASES = {"def": "definition", "proposition": "theorem", "prop": "theorem", "corollary": "theorem",
|
|
885
|
+
"lem": "lemma", "thm": "theorem", "structure": "construction"}
|
|
886
|
+
TODO = "TODO"
|
|
887
|
+
|
|
888
|
+
|
|
889
|
+
def legacy_rows(data) -> list:
|
|
890
|
+
"""The rows of a legacy claims JSON: a list, a list under claims|rows|items|entries, or a
|
|
891
|
+
mapping id -> row (the id is kept as `id`)."""
|
|
892
|
+
if isinstance(data, list):
|
|
893
|
+
return data
|
|
894
|
+
if isinstance(data, dict):
|
|
895
|
+
for k in ("claims", "rows", "items", "entries"):
|
|
896
|
+
if isinstance(data.get(k), list):
|
|
897
|
+
return data[k]
|
|
898
|
+
if data and all(isinstance(v, dict) for v in data.values()):
|
|
899
|
+
return [{"id": k, **v} for k, v in data.items()]
|
|
900
|
+
raise core.Fail("legacy claims JSON: expected a list of rows, or rows under claims|rows|items|entries")
|
|
901
|
+
|
|
902
|
+
|
|
903
|
+
def _first(row: dict, keys) -> tuple[str | None, object]:
|
|
904
|
+
for k in keys:
|
|
905
|
+
if row.get(k) not in (None, "", []):
|
|
906
|
+
return k, row[k]
|
|
907
|
+
return None, None
|
|
908
|
+
|
|
909
|
+
|
|
910
|
+
def _clean(v, limit: int = 300) -> str | None:
|
|
911
|
+
"""A one-line string, or None when it is missing, multi-line-only or names a local path."""
|
|
912
|
+
if not isinstance(v, str) or not v.strip():
|
|
913
|
+
return None
|
|
914
|
+
line = " ".join(v.split())
|
|
915
|
+
if idx.PRIVATE_PATH_RE.search(line):
|
|
916
|
+
return None
|
|
917
|
+
return line if len(line) <= limit else line[: limit - 3].rstrip() + "..."
|
|
918
|
+
|
|
919
|
+
|
|
920
|
+
def migrate_rows(name: str, rows: list) -> tuple[dict, list[dict], list[str], int]:
|
|
921
|
+
"""(claims/1 document, per-claim TODO list, unmapped legacy keys, rows skipped). Mapped fields
|
|
922
|
+
are copied; anything that cannot be mapped is a TODO marker sync will refuse (file TODO.lean)."""
|
|
923
|
+
claims, todos, used, unmapped, skipped, ids = [], [], set(), set(), 0, {}
|
|
924
|
+
for i, row in enumerate(rows):
|
|
925
|
+
if not isinstance(row, dict):
|
|
926
|
+
skipped += 1
|
|
927
|
+
continue
|
|
928
|
+
got = {}
|
|
929
|
+
for field, keys in LEGACY_FIELDS.items():
|
|
930
|
+
k, v = _first(row, keys)
|
|
931
|
+
if k is not None:
|
|
932
|
+
got[field] = v
|
|
933
|
+
used.add(k)
|
|
934
|
+
unmapped.update(k for k in row if k not in used and k not in
|
|
935
|
+
{x for keys in LEGACY_FIELDS.values() for x in keys})
|
|
936
|
+
todo = []
|
|
937
|
+
decl = got.get("decl") if isinstance(got.get("decl"), str) and got["decl"].strip() and \
|
|
938
|
+
not any(ch.isspace() for ch in got["decl"].strip()) else None
|
|
939
|
+
legacy_id = str(got.get("id")) if got.get("id") not in (None, "") else None
|
|
940
|
+
base = slug_of_decl(legacy_id.rsplit("/", 1)[-1]) if legacy_id else \
|
|
941
|
+
(slug_of_decl(decl) if decl else f"claim-{i + 1}")
|
|
942
|
+
slug, n = base, 2
|
|
943
|
+
while slug in ids.values():
|
|
944
|
+
slug, n = f"{base}-{n}", n + 1
|
|
945
|
+
if legacy_id:
|
|
946
|
+
ids[legacy_id] = slug
|
|
947
|
+
cid = f"{name}/{slug}"
|
|
948
|
+
kind = str(got.get("kind") or "").strip().lower()
|
|
949
|
+
kind = KIND_ALIASES.get(kind, kind)
|
|
950
|
+
if kind not in CLAIM_KINDS:
|
|
951
|
+
todo.append("kind (defaulted to theorem)")
|
|
952
|
+
kind = "theorem"
|
|
953
|
+
f = got.get("file")
|
|
954
|
+
f = f if isinstance(f, str) and f.endswith(".lean") and idx._is_rel(f) else None
|
|
955
|
+
summary = _clean(got.get("summary"))
|
|
956
|
+
status = got.get("status") if got.get("status") in CLAIM_STATUSES and got.get("status") != "superseded" \
|
|
957
|
+
else None
|
|
958
|
+
if decl is None:
|
|
959
|
+
todo.append("decl")
|
|
960
|
+
if f is None:
|
|
961
|
+
todo.append("file")
|
|
962
|
+
if summary is None:
|
|
963
|
+
todo.append("summary")
|
|
964
|
+
if status is None:
|
|
965
|
+
todo.append("status (defaulted to experimental)")
|
|
966
|
+
kw = got.get("keywords") if isinstance(got.get("keywords"), list) else []
|
|
967
|
+
kw = sorted({slug_of_decl(k) for k in kw if isinstance(k, str) and slug_of_decl(k) != "claim"})
|
|
968
|
+
al = [a for a in (_clean(x, 120) for x in got.get("aliases") or [] if isinstance(x, str)) if a]
|
|
969
|
+
claims.append({"id": cid, "decl": decl or TODO, "kind": kind,
|
|
970
|
+
"summary": summary or f"{TODO}: one sentence.", "aliases": al, "keywords": kw,
|
|
971
|
+
"file": f or f"{TODO}.lean", "status": status or "experimental",
|
|
972
|
+
"superseded_by": None, "citation": _clean(got.get("citation")),
|
|
973
|
+
"depends_on": [d for d in got.get("depends_on") or [] if isinstance(d, str)]})
|
|
974
|
+
if todo:
|
|
975
|
+
todos.append({"id": cid, "todo": todo})
|
|
976
|
+
for c in claims: # depends_on: keep only references to rows migrated here
|
|
977
|
+
c["depends_on"] = sorted({f"{name}/{ids[d]}" for d in c["depends_on"] if d in ids} - {c["id"]})
|
|
978
|
+
return ({"schema": CLAIMS_SCHEMA, "package": name, "claims": claims}, todos, sorted(unmapped), skipped)
|
|
979
|
+
|
|
980
|
+
|
|
981
|
+
def do_claims_migrate(reg: dict, name: str, src: str, out: str | None, dry_run: bool,
|
|
982
|
+
agent: str | None) -> tuple[list[str], dict, str]:
|
|
983
|
+
import json
|
|
984
|
+
pkg = core.get_pkg(reg, name)
|
|
985
|
+
repo = core.repo_path(pkg) if pkg.get("local_path") else None
|
|
986
|
+
if repo is None or not repo.is_dir():
|
|
987
|
+
raise core.Fail(f"{name}: no checkout at local_path; nothing to migrate into")
|
|
988
|
+
rel = out or pkg.get("claims_file") or DEFAULT_CLAIMS_FILE
|
|
989
|
+
if not idx._is_rel(rel):
|
|
990
|
+
raise core.UsageError(f"--out must be repo-relative, got {rel!r}")
|
|
991
|
+
path = pathlib.Path(src).expanduser()
|
|
992
|
+
path = path if path.is_absolute() else repo / path
|
|
993
|
+
if not path.is_file():
|
|
994
|
+
raise core.Fail(f"{name}: --from {src} is not a file (relative paths are read from the checkout)")
|
|
995
|
+
try:
|
|
996
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
997
|
+
except (ValueError, UnicodeDecodeError) as e:
|
|
998
|
+
raise core.Fail(f"{name}: --from {src} is not JSON: {e}") from e
|
|
999
|
+
doc, todos, unmapped, skipped = migrate_rows(name, legacy_rows(data))
|
|
1000
|
+
header = [f"# Migrated by `lean-pkg claims migrate {name}` from a legacy claims JSON. A skeleton:",
|
|
1001
|
+
f"# fix every TODO (sync refuses each {TODO} placeholder), delete these comments, commit, then run",
|
|
1002
|
+
f"# `lean-pkg claims sync {name}`. Nothing here is verified; trust comes from receipts."]
|
|
1003
|
+
header += [f"# TODO {t['id']}: {', '.join(t['todo'])}" for t in todos]
|
|
1004
|
+
if unmapped:
|
|
1005
|
+
header.append("# legacy keys not mapped: " + ", ".join(unmapped))
|
|
1006
|
+
text = "\n".join(header) + "\n" + dump_claims(doc)
|
|
1007
|
+
n, k = len(doc["claims"]), len(todos)
|
|
1008
|
+
payload = {"ok": True, "name": name, "from": src, "out": rel, "dry_run": dry_run, "written": False,
|
|
1009
|
+
"claims": n, "todo": k, "todos": todos, "unmapped_keys": unmapped, "rows_skipped": skipped,
|
|
1010
|
+
"next": [f"edit {rel}: resolve the TODO markers", f"git add {rel} && git commit",
|
|
1011
|
+
f"lean-pkg claims sync {name}"]}
|
|
1012
|
+
summary = (f"{name}: {n} claim(s) from {src}, {k} with TODO markers"
|
|
1013
|
+
+ (f", {skipped} non-mapping row(s) skipped" if skipped else ""))
|
|
1014
|
+
exists = (repo / rel).exists()
|
|
1015
|
+
if dry_run:
|
|
1016
|
+
note = f" ({rel} already exists: the real run will refuse; pass --out)" if exists else ""
|
|
1017
|
+
return [summary, f"{rel} (dry run, nothing written){note}:"], payload, text
|
|
1018
|
+
if exists:
|
|
1019
|
+
raise core.Fail(f"{name}: {rel} already exists in the checkout; refusing to overwrite "
|
|
1020
|
+
f"(pass --out another path, or --dry-run to print)")
|
|
1021
|
+
lease = pkg.get("lease")
|
|
1022
|
+
core.refuse_invalid_lease(name, lease)
|
|
1023
|
+
if core.lease_live(lease, core.dt.datetime.now(core.dt.timezone.utc)) and agent != lease.get("agent"):
|
|
1024
|
+
raise core.Fail(f"{name}: lease held by {lease.get('agent')} — pass --agent {lease.get('agent')}; "
|
|
1025
|
+
f"nothing written")
|
|
1026
|
+
dest = repo / rel
|
|
1027
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
1028
|
+
tmp = dest.with_name(dest.name + ".tmp")
|
|
1029
|
+
tmp.write_text(text, encoding="utf-8")
|
|
1030
|
+
tmp.replace(dest)
|
|
1031
|
+
payload["written"] = True
|
|
1032
|
+
return [summary, f"wrote {rel} (not committed, not synced; the registry is unchanged)",
|
|
1033
|
+
"next: " + "; ".join(payload["next"])], payload, text
|
|
1034
|
+
|
|
1035
|
+
|
|
1036
|
+
# --------------------------------------------------------------------------
|
|
1037
|
+
# CLI glue: lean_pkg.cli.main calls add_parsers(sub, add_json)
|
|
1038
|
+
|
|
1039
|
+
def _emit(args, out: list[str], payload: dict, rc: int = 0) -> int:
|
|
1040
|
+
if args.json_out:
|
|
1041
|
+
core.print_json(payload)
|
|
1042
|
+
else:
|
|
1043
|
+
print("\n".join(out))
|
|
1044
|
+
return rc
|
|
1045
|
+
|
|
1046
|
+
|
|
1047
|
+
def cmd_claims(args) -> int:
|
|
1048
|
+
fn = getattr(args, "claims_fn", None)
|
|
1049
|
+
if fn is None:
|
|
1050
|
+
raise core.UsageError("claims needs an action: sync | list | check | migrate | ledger | mark | rebase")
|
|
1051
|
+
return fn(args)
|
|
1052
|
+
|
|
1053
|
+
|
|
1054
|
+
def run_sync(args) -> int:
|
|
1055
|
+
reg_path, events_p = core.registry_path(args), core.events_path(args)
|
|
1056
|
+
reg = core.load_registry(reg_path)
|
|
1057
|
+
core.warn_lease(core.lease_actor(reg, args.name, args.agent, "claims sync"))
|
|
1058
|
+
out, payload = do_claims_sync(reg_path, reg, events_p, args.name)
|
|
1059
|
+
return _emit(args, *_with_reusable_warning(reg, [args.name], out, payload))
|
|
1060
|
+
|
|
1061
|
+
|
|
1062
|
+
def run_list(args) -> int:
|
|
1063
|
+
out, payload = do_claims_list(core.load_registry(core.registry_path(args)), args.name)
|
|
1064
|
+
return _emit(args, out, payload)
|
|
1065
|
+
|
|
1066
|
+
|
|
1067
|
+
def run_migrate(args) -> int:
|
|
1068
|
+
out, payload, text = do_claims_migrate(core.load_registry(core.registry_path(args)), args.name,
|
|
1069
|
+
args.from_path, args.out, args.dry_run, args.agent)
|
|
1070
|
+
if args.json_out:
|
|
1071
|
+
core.print_json({**payload, "yaml": text if args.dry_run else None})
|
|
1072
|
+
return 0
|
|
1073
|
+
print("\n".join(out + ([text.rstrip("\n")] if args.dry_run else [])))
|
|
1074
|
+
return 0
|
|
1075
|
+
|
|
1076
|
+
|
|
1077
|
+
def run_check(args) -> int:
|
|
1078
|
+
name = args.name
|
|
1079
|
+
if getattr(args, "file", None) is None and name and name.endswith((".yaml", ".yml", ".json")) \
|
|
1080
|
+
and pathlib.Path(name).is_file():
|
|
1081
|
+
raise core.UsageError(f"claims check takes a package NAME, and {name!r} is a file: to schema-check it, "
|
|
1082
|
+
f"run `lean-pkg claims check --file {name}`")
|
|
1083
|
+
if getattr(args, "file", None) is not None:
|
|
1084
|
+
out, payload, rc = do_claims_check_file(args.file, args.name)
|
|
1085
|
+
return _emit(args, out, payload, rc)
|
|
1086
|
+
reg = core.load_registry(core.registry_path(args))
|
|
1087
|
+
out, payload, rc = do_claims_check(reg, args.name)
|
|
1088
|
+
out, payload = _with_reusable_warning(reg, [r["name"] for r in payload["packages"]], out, payload, last=True)
|
|
1089
|
+
return _emit(args, out, payload, rc)
|
|
1090
|
+
|
|
1091
|
+
|
|
1092
|
+
def _with_reusable_warning(reg: dict, names: list, out: list[str], payload: dict,
|
|
1093
|
+
last: bool = False) -> tuple[list[str], dict]:
|
|
1094
|
+
"""#6: WARN (never a failure) for each gated package with claims and none reusable."""
|
|
1095
|
+
from .claims_mark import no_reusable_warning
|
|
1096
|
+
warns = [w for n in names for w in [no_reusable_warning(n, reg["packages"][n])] if w]
|
|
1097
|
+
payload = {**payload, "warnings": list(payload.get("warnings") or []) + warns}
|
|
1098
|
+
lines = [f"WARN {w}" for w in warns]
|
|
1099
|
+
return ((out[:-1] + lines + out[-1:]) if last and out else out + lines), payload
|
|
1100
|
+
|
|
1101
|
+
|
|
1102
|
+
def run_ledger(args) -> int:
|
|
1103
|
+
from . import ledger
|
|
1104
|
+
led = ledger.compute_ledger(core.load_registry(core.registry_path(args)), args.name, args.stage)
|
|
1105
|
+
return _emit(args, ledger.ledger_lines(led), led, 0 if led["ok"] else 1)
|
|
1106
|
+
|
|
1107
|
+
|
|
1108
|
+
def add_parsers(sub, add_json) -> None:
|
|
1109
|
+
s = sub.add_parser("claims", help="claims.yaml: sync | list | check | migrate | ledger | mark | rebase (named reusable "
|
|
1110
|
+
"results)")
|
|
1111
|
+
add_json(s)
|
|
1112
|
+
s.set_defaults(fn=cmd_claims, claims_fn=None)
|
|
1113
|
+
csub = s.add_subparsers(dest="claims_cmd")
|
|
1114
|
+
a = csub.add_parser("sync", help="read claims.yaml at HEAD of the checkout; validate (TODO placeholders refused); "
|
|
1115
|
+
"cache; event")
|
|
1116
|
+
a.add_argument("name")
|
|
1117
|
+
a.add_argument("--agent", default=None,
|
|
1118
|
+
help="the agent acting (recorded as the event's actor); another agent's live lease then refuses")
|
|
1119
|
+
add_json(a)
|
|
1120
|
+
a.set_defaults(fn=cmd_claims, claims_fn=run_sync)
|
|
1121
|
+
b = csub.add_parser("list", help="table of cached claims with status and trust")
|
|
1122
|
+
b.add_argument("name", nargs="?", default=None)
|
|
1123
|
+
add_json(b)
|
|
1124
|
+
b.set_defaults(fn=cmd_claims, claims_fn=run_list)
|
|
1125
|
+
c = csub.add_parser("check", help="re-validate cached claims; exit 0/1 (--file: a working-copy file)")
|
|
1126
|
+
c.add_argument("name", nargs="?", default=None)
|
|
1127
|
+
c.add_argument("--file", default=None, metavar="PATH",
|
|
1128
|
+
help="schema-check this claims file (e.g. claims.yaml before you commit it) instead of the "
|
|
1129
|
+
"registry cache; schema only (no checkout, so declarations are not looked up: "
|
|
1130
|
+
"`claims sync` and `gate` do that); reads no registry; NAME, if given, must be "
|
|
1131
|
+
"its package")
|
|
1132
|
+
add_json(c)
|
|
1133
|
+
c.set_defaults(fn=cmd_claims, claims_fn=run_check)
|
|
1134
|
+
m = csub.add_parser("migrate", help="legacy claims.json -> a claims/1 skeleton in the checkout "
|
|
1135
|
+
"(never the registry)")
|
|
1136
|
+
m.add_argument("name")
|
|
1137
|
+
m.add_argument("--from", dest="from_path", required=True, metavar="PATH",
|
|
1138
|
+
help="the legacy JSON (relative paths are read from the checkout)")
|
|
1139
|
+
m.add_argument("--out", default=None, help="repo-relative output (default: claims_file, else claims.yaml)")
|
|
1140
|
+
m.add_argument("--dry-run", action="store_true", help="print the skeleton; write nothing")
|
|
1141
|
+
m.add_argument("--agent", default=None, help="your lease agent, when the package is leased")
|
|
1142
|
+
add_json(m)
|
|
1143
|
+
m.set_defaults(fn=cmd_claims, claims_fn=run_migrate)
|
|
1144
|
+
led = csub.add_parser("ledger", help="per-claim closure from the recorded evidence: verified only with zero "
|
|
1145
|
+
"diagnostics; read-only; exit 0 only when the package is ready")
|
|
1146
|
+
led.add_argument("name")
|
|
1147
|
+
led.add_argument("--stage", choices=("gate", "promote"), default="promote",
|
|
1148
|
+
help="the authority required: gate (lower tier) or promote (also the comparator tier for "
|
|
1149
|
+
"every reusable theorem and lemma; the default)")
|
|
1150
|
+
add_json(led)
|
|
1151
|
+
led.set_defaults(fn=cmd_claims, claims_fn=run_ledger)
|
|
1152
|
+
from .claims_mark import add_parser as add_mark_parser # #6: lives in claims_mark.py
|
|
1153
|
+
add_mark_parser(csub, add_json, cmd_claims)
|
|
1154
|
+
from . import rebase
|
|
1155
|
+
rebase.add_parser(csub, add_json, cmd_claims)
|