lean-pkg 0.25.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. lean_pkg/__init__.py +3 -0
  2. lean_pkg/adapters/__init__.py +148 -0
  3. lean_pkg/adapters/github.py +65 -0
  4. lean_pkg/adapters/leansearch.py +68 -0
  5. lean_pkg/adapters/loogle.py +45 -0
  6. lean_pkg/adapters/palomar.py +170 -0
  7. lean_pkg/adapters/reservoir.py +127 -0
  8. lean_pkg/anchor.py +678 -0
  9. lean_pkg/audit.py +716 -0
  10. lean_pkg/binding_file.py +446 -0
  11. lean_pkg/blueprint.py +213 -0
  12. lean_pkg/build_scope.py +282 -0
  13. lean_pkg/ci_github.py +917 -0
  14. lean_pkg/claim_axioms.py +421 -0
  15. lean_pkg/claims.py +1155 -0
  16. lean_pkg/claims_mark.py +197 -0
  17. lean_pkg/cli.py +5208 -0
  18. lean_pkg/cli_parser.py +768 -0
  19. lean_pkg/command_tree.py +615 -0
  20. lean_pkg/comparator_config.py +990 -0
  21. lean_pkg/comparator_contracts.py +382 -0
  22. lean_pkg/comparator_receipt.py +2854 -0
  23. lean_pkg/comparator_stage.py +623 -0
  24. lean_pkg/comparator_types.py +830 -0
  25. lean_pkg/container.py +172 -0
  26. lean_pkg/core.py +1570 -0
  27. lean_pkg/coverage.py +1278 -0
  28. lean_pkg/data/stacks/lts-2026.10.yaml +73 -0
  29. lean_pkg/data/toolchain-advisories.yaml +77 -0
  30. lean_pkg/data/upgrade-breaking.yaml +20 -0
  31. lean_pkg/data/verify-workflow-pins.yaml +14 -0
  32. lean_pkg/deps_closure.py +512 -0
  33. lean_pkg/deps_fill.py +445 -0
  34. lean_pkg/dup_constants.py +448 -0
  35. lean_pkg/exercise.py +828 -0
  36. lean_pkg/exercise_forbid.py +288 -0
  37. lean_pkg/export_paths.py +77 -0
  38. lean_pkg/extract.py +1172 -0
  39. lean_pkg/extract_decls.py +501 -0
  40. lean_pkg/extract_ledger.py +1408 -0
  41. lean_pkg/extract_summary.py +132 -0
  42. lean_pkg/extract_types.py +502 -0
  43. lean_pkg/extract_write.py +138 -0
  44. lean_pkg/formalization.py +1078 -0
  45. lean_pkg/formalization_kept.py +182 -0
  46. lean_pkg/fresh_repo.py +709 -0
  47. lean_pkg/gate.py +2141 -0
  48. lean_pkg/headline.py +211 -0
  49. lean_pkg/help_topics.py +442 -0
  50. lean_pkg/holes.py +289 -0
  51. lean_pkg/host_routes.py +376 -0
  52. lean_pkg/hypotheses.py +788 -0
  53. lean_pkg/index.py +1749 -0
  54. lean_pkg/json_stdout.py +48 -0
  55. lean_pkg/lake_hygiene.py +289 -0
  56. lean_pkg/lean_diag.py +280 -0
  57. lean_pkg/lean_scan.py +1300 -0
  58. lean_pkg/ledger.py +582 -0
  59. lean_pkg/next_step.py +510 -0
  60. lean_pkg/page.py +1831 -0
  61. lean_pkg/page_html.py +153 -0
  62. lean_pkg/palomar.py +316 -0
  63. lean_pkg/palomar_check.py +1027 -0
  64. lean_pkg/port_modules.py +677 -0
  65. lean_pkg/prior_art.py +286 -0
  66. lean_pkg/producer.py +212 -0
  67. lean_pkg/producer_skew.py +208 -0
  68. lean_pkg/public_safety.py +1487 -0
  69. lean_pkg/publish.py +402 -0
  70. lean_pkg/rebase.py +984 -0
  71. lean_pkg/receipt.py +2385 -0
  72. lean_pkg/receipt_check.py +1064 -0
  73. lean_pkg/receipt_ci.py +660 -0
  74. lean_pkg/receipt_systemd.py +890 -0
  75. lean_pkg/recommended.py +232 -0
  76. lean_pkg/report.py +727 -0
  77. lean_pkg/reservoir.py +203 -0
  78. lean_pkg/scaffold.py +588 -0
  79. lean_pkg/schemas/formalization-0.4.schema.json +344 -0
  80. lean_pkg/schemas/formalization-0.4.schema.source.txt +15 -0
  81. lean_pkg/scripts/ClaimAxioms.lean +47 -0
  82. lean_pkg/scripts/ContractsOnly.lean +300 -0
  83. lean_pkg/scripts/DupConstants.lean +149 -0
  84. lean_pkg/scripts/HypProbe.lean +257 -0
  85. lean_pkg/scripts/comparator-check.sh +396 -0
  86. lean_pkg/scripts/verify-comparator.sh +135 -0
  87. lean_pkg/seal_bundle.py +647 -0
  88. lean_pkg/search.py +865 -0
  89. lean_pkg/site_profiles/easley.yaml +10 -0
  90. lean_pkg/site_profiles/github-actions.yaml +12 -0
  91. lean_pkg/sites.py +225 -0
  92. lean_pkg/stacks.py +373 -0
  93. lean_pkg/statements_module.py +217 -0
  94. lean_pkg/templates/Apache-2.0.txt +202 -0
  95. lean_pkg/toolchain_advisories.py +225 -0
  96. lean_pkg/upgrade.py +706 -0
  97. lean_pkg/verify.py +495 -0
  98. lean_pkg-0.25.0.dist-info/METADATA +93 -0
  99. lean_pkg-0.25.0.dist-info/RECORD +103 -0
  100. lean_pkg-0.25.0.dist-info/WHEEL +5 -0
  101. lean_pkg-0.25.0.dist-info/entry_points.txt +5 -0
  102. lean_pkg-0.25.0.dist-info/licenses/LICENSE +202 -0
  103. lean_pkg-0.25.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1027 @@
1
+ # lean-pkg palomar check -- read-only Palomar readiness of one package at one commit (no network)
2
+ """`lean-pkg palomar check NAME [--rev REV] [--config PATH] [--rules FILE] [--repo DIR] [--json]`.
3
+
4
+ Lists every gap between the package, at one commit, and the mechanical rules Palomar's verifier
5
+ applies before it builds anything. Each gap is {code, severity, paths, detail, fix}. Read-only and
6
+ offline: it reads git objects at the commit (never the package's working tree), writes nothing,
7
+ records no event and makes no network request. The one exception is the dependency scan (#404): a
8
+ dependency's checkout under .lake/packages, a local build artifact, is read when its HEAD is the
9
+ revision lake-manifest.json pins at the commit.
10
+
11
+ The commit: `--rev REV`; else the commit the recorded gate receipt binds; else HEAD.
12
+
13
+ Severity: `error` needs a change to the repository content, so a new commit (and a re-gate); `warn`
14
+ is a submission-time step (make the repository public, push the commit) or advice. Exit 0 when there
15
+ is no error (ready), 1 when there is one, 2 on a usage error.
16
+
17
+ The rules and where they come from (Palomar's floor moves, so they are dated):
18
+
19
+ - `PalomarRegistry/PalomarSubmission` at commit RULES_SOURCE["commit"], read on
20
+ RULES_SOURCE["retrieved"]: `browser-preflight-policy.json` (the machine-readable subset of the
21
+ preparation rules: toolchain pattern and minimum, the `.lean` source scope and line cap, the
22
+ comparator configuration keys and standard axioms, source relationships, classification
23
+ cardinality), `toolchains.json` (the minimum), and README.md ("Required source layout", "Lean
24
+ source requirements": the licence file names, the formalization.yaml minimum, the Challenge limits).
25
+ - `--rules FILE` replaces the policy part with a newer `browser-preflight-policy.json` (schema 1)
26
+ downloaded by hand; lean-pkg never fetches it.
27
+
28
+ This is a predictive, non-authoritative check, like Palomar's own browser preflight: the verifier
29
+ repeats every check, confirms headers with Lean's parser, and checks more than this (see
30
+ NOT_CHECKED).
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import json
36
+ import pathlib
37
+ import posixpath
38
+ import re
39
+ import subprocess
40
+
41
+ from . import build_scope
42
+ from . import gate as gate_mod
43
+ from . import core
44
+ from . import lean_scan
45
+ from . import statements_module as stm
46
+ from .holes import INLINE_KEYS, SIDECAR, check_definition_holes, migrate_command, parse_sidecar
47
+ from .holes import summary as signoff_summary
48
+
49
+ RULES_SOURCE = {
50
+ "repository": "https://github.com/PalomarRegistry/PalomarSubmission",
51
+ "commit": "d4e41c1d5b0d114c4859e6e5831dc6d3ad1d0d44",
52
+ "committed": "2026-10-05",
53
+ "retrieved": "2026-10-16",
54
+ "files": ["browser-preflight-policy.json", "toolchains.json", "README.md"],
55
+ }
56
+
57
+ # The parts of browser-preflight-policy.json (schema 1) at RULES_SOURCE["commit"] this check reads.
58
+ DEFAULT_POLICY = {
59
+ "schema_version": 1,
60
+ "limits": {"lean_source_lines": 10000},
61
+ "lean_sources": {"module_required": True, "excluded_directories": [".git", ".lake"],
62
+ "module_exempt_filenames": ["lakefile.lean"], "symlinks_allowed": False},
63
+ "toolchain": {"pattern": r"^leanprover/lean4:v([0-9]+)\.([0-9]+)\.([0-9]+)(?:-rc([0-9]+))?$",
64
+ "minimum": "v4.35.0-rc2"},
65
+ "formalization": {"source_relationship_categories": ["adapts", "background", "formalizes",
66
+ "independently-proves", "other"],
67
+ "classification_cardinality": {"arxiv": [1, 8], "msc2020": [0, 8]}},
68
+ "comparator": {"required_keys": ["challenge_module", "permitted_axioms", "solution_module",
69
+ "theorem_names"],
70
+ "allowed_keys": ["challenge_module", "definition_names", "enable_nanoda",
71
+ "permitted_axioms", "solution_module", "theorem_names"],
72
+ "standard_axioms": ["Classical.choice", "Quot.sound", "propext"]},
73
+ }
74
+
75
+ # From README.md at RULES_SOURCE["commit"] (not in the policy file).
76
+ CHALLENGE_MAX_LINES = 1000
77
+ CHALLENGE_MAX_BYTES = 100 * 1024
78
+ PROJECT_NAME_MAX = 300
79
+ LICENSE_FILE_RE = re.compile(r"^(?:LICENSE|LICENCE|COPYING|UNLICENSE|OFL)(?:\.md|\.markdown|\.txt)?$",
80
+ re.IGNORECASE)
81
+ SOURCE_BASED = ("formalizes", "adapts", "independently-proves")
82
+
83
+ NOT_CHECKED = [
84
+ "the header with Lean's parser (this check reads the first token after comments, as Palomar's "
85
+ "own pre-installation scan does)",
86
+ "the licence text against SPDX with licensee (only a marker for MIT, Apache-2.0, BSD)",
87
+ "arXiv and MSC2020 codes against the taxonomies; ORCID iDs against the ORCID Registry",
88
+ "Challenge imports against the trusted dependencies; a Challenge module root shadowed by a "
89
+ "dependency; declaration names as canonical Lean identifiers",
90
+ "Git LFS pointers; dependency pins and hosts in lake-manifest.json",
91
+ "the build, the export and the comparator run itself",
92
+ ]
93
+ # #404: the shadowing clause of NOT_CHECKED[3], dropped when the dependency scan ran on every dependency
94
+ _SHADOW_CLAUSE = "a Challenge module root shadowed by a dependency"
95
+ # a bare root this generic is likely to be a dependency's top-level module too (#404)
96
+ GENERIC_ROOTS = ("Challenge", "Solution", "Main")
97
+
98
+ USAGE = "usage: lean-pkg palomar check NAME [--rev REV] [--config PATH] [--rules FILE] [--repo DIR] [--json]"
99
+
100
+
101
+ # --------------------------------------------------------------------------
102
+ # rules
103
+
104
+ def load_rules(path: str | None) -> tuple[dict, dict]:
105
+ """(policy, source view). A --rules FILE replaces the policy; its keys must be present."""
106
+ if path is None:
107
+ return DEFAULT_POLICY, {**RULES_SOURCE, "kind": "pinned"}
108
+ p = pathlib.Path(path).expanduser()
109
+ try:
110
+ data = json.loads(p.read_text())
111
+ except OSError as e:
112
+ raise core.UsageError(f"--rules {path}: cannot read: {e.strerror or e}") from e
113
+ except ValueError as e:
114
+ raise core.UsageError(f"--rules {path}: not JSON: {e}") from e
115
+ if not isinstance(data, dict) or data.get("schema_version") != 1:
116
+ raise core.UsageError(f"--rules {path}: not a browser-preflight-policy.json with schema_version 1")
117
+ try:
118
+ policy = {
119
+ "schema_version": 1,
120
+ "limits": {"lean_source_lines": int(data["limits"]["lean_source_lines"])},
121
+ "lean_sources": {k: data["lean_sources"][k] for k in DEFAULT_POLICY["lean_sources"]},
122
+ "toolchain": {k: str(data["toolchain"][k]) for k in ("pattern", "minimum")},
123
+ "formalization": {k: data["formalization"][k] for k in DEFAULT_POLICY["formalization"]},
124
+ "comparator": {k: list(data["comparator"][k]) for k in DEFAULT_POLICY["comparator"]},
125
+ }
126
+ re.compile(policy["toolchain"]["pattern"])
127
+ except (KeyError, TypeError, ValueError, re.error) as e:
128
+ raise core.UsageError(f"--rules {path}: missing or malformed key ({e})") from e
129
+ return policy, {"kind": "file", "path": str(p), "retrieved": None, "commit": None}
130
+
131
+
132
+ # --------------------------------------------------------------------------
133
+ # Lean sources
134
+
135
+ _ID_CONT = re.compile(r"[\w'!?₀-₉ₐ-ₜᵢ-ᵪⱼ]|\.[^\W\d]|\.«")
136
+
137
+
138
+ def has_module_header(text: str) -> bool:
139
+ """Does the file start with the `module` keyword, after blanks and ordinary comments only?
140
+
141
+ The rule (README, "Lean source requirements"): ordinary comments may precede the header;
142
+ module documentation (`/-! -/`) and doc comments (`/-- -/`) are commands, so they must follow
143
+ it. Only space, CR and LF count as blanks (no BOM, no other Unicode space), as in Lean's header
144
+ parser. Block comments nest. `module` must be a whole token (`moduleFoo` is not a header)."""
145
+ i, n = 0, len(text)
146
+ while i < n:
147
+ c = text[i]
148
+ if c in " \r\n":
149
+ i += 1
150
+ elif text.startswith("--", i):
151
+ j = text.find("\n", i + 2)
152
+ i = n if j < 0 else j + 1
153
+ elif text.startswith("/-", i) and not text.startswith(("/--", "/-!"), i):
154
+ i += 3 # Lean reads one character past a plain opener before scanning
155
+ depth = 1
156
+ while depth and i < n:
157
+ if text.startswith("/-", i):
158
+ depth, i = depth + 1, i + 2
159
+ elif text.startswith("-/", i):
160
+ depth, i = depth - 1, i + 2
161
+ else:
162
+ i += 1
163
+ if depth:
164
+ return False # an unterminated comment: no header
165
+ else:
166
+ return text.startswith("module", i) and _ID_CONT.match(text, i + 6) is None
167
+ return False
168
+
169
+
170
+ def physical_lines(text: str) -> int:
171
+ """LF-delimited lines; an unterminated last line counts, a final newline adds none."""
172
+ return text.count("\n") + (1 if text and not text.endswith("\n") else 0)
173
+
174
+
175
+ class Tree:
176
+ """The git tree of one commit, read from the object store (the working tree is never read)."""
177
+
178
+ def __init__(self, repo: pathlib.Path, commit: str, claims_file: str = "claims.yaml"):
179
+ self.repo, self.commit, self.claims_file = repo, commit, claims_file
180
+ self._statements: tuple[str | None, list[str]] | None = None
181
+ self._deps: dict | None = None
182
+ self.module_hint = "MOD" # the package's root module, for a suggested module name (#404)
183
+ p = core.git(repo, "rev-parse", "--show-prefix")
184
+ self.prefix = p.stdout.strip() if p.returncode == 0 else ""
185
+ p = subprocess.run(["git", "-C", str(repo), "ls-tree", "-r", "-z", "--full-tree", commit],
186
+ capture_output=True, env=core.scrubbed_env())
187
+ if p.returncode != 0:
188
+ raise core.Fail(f"cannot list the tree of {commit[:12]} in {repo}")
189
+ self.entries: dict[str, tuple[str, str, str]] = {}
190
+ for rec in p.stdout.split(b"\0"):
191
+ if not rec:
192
+ continue
193
+ meta, path = rec.split(b"\t", 1)
194
+ mode, kind, sha = meta.decode().split()
195
+ self.entries[path.decode("utf-8", "surrogateescape")] = (mode, kind, sha)
196
+
197
+ def project(self, rel: str) -> str:
198
+ """A package-relative path as a repository path."""
199
+ return self.prefix + rel
200
+
201
+ def blob(self, path: str) -> bytes | None:
202
+ e = self.entries.get(path)
203
+ if e is None or e[1] != "blob":
204
+ return None
205
+ p = subprocess.run(["git", "-C", str(self.repo), "cat-file", "blob", e[2]],
206
+ capture_output=True, env=core.scrubbed_env())
207
+ return p.stdout if p.returncode == 0 else None
208
+
209
+ def statements(self) -> tuple[str | None, list[str]]:
210
+ """(the statements module the claims file at this commit declares, or None; its refusals), read once
211
+ (#369)."""
212
+ if self._statements is None:
213
+ self._statements = stm.at_commit(self.repo, self.claims_file, self.commit)
214
+ return self._statements
215
+
216
+ def dependencies(self) -> dict:
217
+ """The dependency scan (#404), read once: dependency_scan(self)."""
218
+ if self._deps is None:
219
+ self._deps = dependency_scan(self)
220
+ return self._deps
221
+
222
+ def blobs(self, paths: list[str]) -> dict[str, bytes]:
223
+ """Many blobs in one `git cat-file --batch` (a package can have thousands of files)."""
224
+ want = [(p, self.entries[p][2]) for p in paths if p in self.entries and self.entries[p][1] == "blob"]
225
+ if not want:
226
+ return {}
227
+ p = subprocess.run(["git", "-C", str(self.repo), "cat-file", "--batch"],
228
+ input="".join(f"{sha}\n" for _p, sha in want).encode(),
229
+ capture_output=True, env=core.scrubbed_env())
230
+ out, data, pos = {}, p.stdout, 0
231
+ for path, _sha in want:
232
+ nl = data.index(b"\n", pos)
233
+ header = data[pos:nl].split()
234
+ size = int(header[2]) if len(header) == 3 else 0
235
+ out[path] = data[nl + 1:nl + 1 + size]
236
+ pos = nl + 1 + size + 1
237
+ return out
238
+
239
+
240
+ def _gap(code: str, severity: str, detail: str, fix: str, paths: list[str] | None = None) -> dict:
241
+ return {"code": code, "severity": severity, "paths": sorted(paths or []), "detail": detail, "fix": fix}
242
+
243
+
244
+ def source_gaps(tree: Tree, policy: dict, name: str = "NAME") -> tuple[list[dict], dict]:
245
+ """Every tracked .lean file in the repository (Palomar scans the whole submitted repository,
246
+ contained projects and unused files included), outside the excluded directories."""
247
+ ls = policy["lean_sources"]
248
+ excluded = set(ls["excluded_directories"])
249
+ exempt = set(ls["module_exempt_filenames"])
250
+ cap = policy["limits"]["lean_source_lines"]
251
+ lean = sorted(p for p in tree.entries
252
+ if p.endswith(".lean") and not excluded.intersection(p.split("/")[:-1]))
253
+ links = [p for p in lean if tree.entries[p][0] == "120000"]
254
+ regular = [p for p in lean if tree.entries[p][0] != "120000" and tree.entries[p][1] == "blob"]
255
+ texts = tree.blobs(regular)
256
+ no_module, too_long, bad_utf8 = [], [], []
257
+ for p in regular:
258
+ try:
259
+ text = texts.get(p, b"").decode("utf-8")
260
+ except UnicodeDecodeError:
261
+ bad_utf8.append(p)
262
+ continue
263
+ if physical_lines(text) > cap:
264
+ too_long.append(p)
265
+ if ls["module_required"] and p.rsplit("/", 1)[-1] not in exempt and not has_module_header(text):
266
+ no_module.append(p)
267
+ gaps = []
268
+ if no_module:
269
+ gaps.append(_gap("source.module_required", "error",
270
+ f"{len(no_module)} of {len(regular)} tracked .lean file(s) do not begin with a `module` "
271
+ f"header (ordinary comments may precede it; lakefile.lean is exempt)",
272
+ f"port the files to the module system (`lean-pkg palomar port-modules {name}` plans the "
273
+ "mechanical part as a diff, `--write` applies it): `module` first, `public import` where "
274
+ "the public interface needs the import, `public`/`@[expose]` for what other modules use; "
275
+ "rebuild, commit, re-gate", no_module))
276
+ if too_long:
277
+ gaps.append(_gap("source.file_too_long", "error",
278
+ f"{len(too_long)} .lean file(s) longer than {cap:,} lines",
279
+ "split them into smaller modules (or reduce generated certificates); commit, re-gate",
280
+ too_long))
281
+ if links and not ls["symlinks_allowed"]:
282
+ gaps.append(_gap("source.symlink_not_allowed", "error", f"{len(links)} .lean symbolic link(s)",
283
+ "commit each as a regular file; commit, re-gate", links))
284
+ if bad_utf8:
285
+ gaps.append(_gap("source.invalid_utf8", "error", f"{len(bad_utf8)} .lean file(s) not valid UTF-8",
286
+ "re-encode them as UTF-8; commit, re-gate", bad_utf8))
287
+ return gaps, {"lean_files": len(regular) + len(links), "missing_module": len(no_module)}
288
+
289
+
290
+ def toolchain_key(text: str, pattern: str) -> tuple | None:
291
+ m = re.match(pattern, text.strip())
292
+ if not m:
293
+ return None
294
+ major, minor, patch, rc = m.groups()
295
+ return (int(major), int(minor), int(patch)) + ((0, int(rc)) if rc is not None else (1, 0))
296
+
297
+
298
+ def toolchain_gaps(tree: Tree, policy: dict) -> tuple[list[dict], str | None]:
299
+ """lean-toolchain in the project, else at the repository root, against the minimum."""
300
+ path = next((p for p in (tree.project("lean-toolchain"), "lean-toolchain") if p in tree.entries), None)
301
+ raw = tree.blob(path) if path else None
302
+ if raw is None:
303
+ return [_gap("toolchain.missing", "error", "no lean-toolchain in the project or at the repository root",
304
+ "commit a lean-toolchain")], None
305
+ tc = raw.decode("utf-8", "replace").strip()
306
+ tcp = policy["toolchain"]
307
+ minimum = tcp["minimum"]
308
+ key = toolchain_key(tc, tcp["pattern"])
309
+ floor = toolchain_key(f"leanprover/lean4:{minimum}", tcp["pattern"])
310
+ if key is None:
311
+ return [_gap("toolchain.unsupported", "error",
312
+ f"lean-toolchain {tc!r} is not a released or rc Lean toolchain (leanprover/lean4:vX.Y.Z[-rcN])",
313
+ f"pin a release or rc at or above {minimum}; rebuild, commit, re-gate", [path])], tc
314
+ if floor is not None and key < floor:
315
+ return [_gap("toolchain.unsupported", "error",
316
+ f"lean-toolchain {tc} is below Palomar's minimum {minimum}",
317
+ f"upgrade to {minimum} or later; rebuild, commit, re-gate", [path])], tc
318
+ return [], tc
319
+
320
+
321
+ def layout_gaps(tree: Tree) -> list[dict]:
322
+ gaps = []
323
+ toml, lean = tree.project("lakefile.toml"), tree.project("lakefile.lean")
324
+ if toml not in tree.entries and lean not in tree.entries:
325
+ gaps.append(_gap("layout.lakefile_missing", "error", "no lakefile.toml or lakefile.lean in the project",
326
+ "commit the Lake configuration"))
327
+ elif toml not in tree.entries and tree.project("lake-manifest.json") not in tree.entries:
328
+ gaps.append(_gap("layout.manifest_missing", "error", "lakefile.lean without lake-manifest.json",
329
+ "commit lake-manifest.json", [lean]))
330
+ subs = [p for p, e in tree.entries.items() if e[1] == "commit"]
331
+ if subs or ".gitmodules" in tree.entries:
332
+ gaps.append(_gap("layout.submodule", "error", "Git submodules (Palomar rejects them in the submitted "
333
+ "repository)", "vendor the content or make it a pinned Lake dependency; commit, re-gate",
334
+ subs or [".gitmodules"]))
335
+ return gaps
336
+
337
+
338
+ def comparator_gaps(tree: Tree, policy: dict, only: str | None) -> tuple[list[dict], list[str]]:
339
+ configs = gate_mod.head_comparator_configs(tree.repo, tree.commit)
340
+ if only is not None:
341
+ if only not in configs:
342
+ return [_gap("comparator.path_missing", "error",
343
+ f"--config {only} is not a comparator configuration tracked at {tree.commit[:12]} "
344
+ f"(tracked: {', '.join(configs) or 'none'})",
345
+ "commit it, or name a tracked one", [only])], configs
346
+ configs = [only]
347
+ if not configs:
348
+ return [_gap("comparator.path_missing", "error", "no comparator configuration tracked "
349
+ "(comparator*.json or comparator/config*.json)",
350
+ "write one (`lean-pkg comparator config --from-claims NAME`), commit, run comparator-receipt")], []
351
+ gaps: list[dict] = []
352
+ for rel in configs:
353
+ gaps += config_gaps(tree, policy, rel)
354
+ return gaps, configs
355
+
356
+
357
+ def config_gaps(tree: Tree, policy: dict, rel: str) -> list[dict]:
358
+ """The gaps of one comparator configuration (package-relative `rel`) at the tree's commit."""
359
+ cp = policy["comparator"]
360
+ required, allowed, standard = set(cp["required_keys"]), set(cp["allowed_keys"]), set(cp["standard_axioms"])
361
+ gaps: list[dict] = []
362
+ path = tree.project(rel)
363
+ try:
364
+ cfg = json.loads(tree.blob(path) or b"")
365
+ except ValueError:
366
+ cfg = None
367
+ if not isinstance(cfg, dict):
368
+ gaps.append(_gap("comparator.invalid", "error", f"{rel} is not a JSON object", "fix the file", [path]))
369
+ return gaps
370
+ missing = sorted(required - cfg.keys())
371
+ if missing:
372
+ gaps.append(_gap("comparator.missing_key", "error", f"{rel} lacks {', '.join(missing)}",
373
+ "add the keys; commit, re-run comparator-receipt, re-gate", [path]))
374
+ unknown = sorted(cfg.keys() - allowed)
375
+ if unknown:
376
+ ours = [k for k in INLINE_KEYS if k in unknown]
377
+ note = (f" ({' and '.join(ours)}: lean-pkg's own metadata, deprecated inside a configuration; it "
378
+ f"belongs in {SIDECAR})" if ours else "")
379
+ fix = (f"`{migrate_command(rel)}` moves {' and '.join(ours)} to {SIDECAR} (the configuration's "
380
+ f"Palomar keys unchanged)" + ("; remove the other key(s)" if set(unknown) - set(ours) else "")
381
+ + "; commit, re-run comparator-receipt (the config's bytes change), re-gate") if ours else \
382
+ "remove them from the configuration you submit; commit, re-run comparator-receipt, re-gate"
383
+ gaps.append(_gap("comparator.unknown_key", "error",
384
+ f"{rel} has key(s) Palomar refuses: {', '.join(unknown)} (allowed: "
385
+ f"{', '.join(sorted(allowed))}){note}", fix, [path]))
386
+ names = cfg.get("theorem_names")
387
+ if not isinstance(names, list) or not names or not all(isinstance(x, str) and x for x in names):
388
+ gaps.append(_gap("comparator.invalid", "error", f"{rel}: theorem_names must be a non-empty list of names",
389
+ "list the theorems the configuration certifies", [path]))
390
+ axioms = cfg.get("permitted_axioms")
391
+ if isinstance(axioms, list) and not set(map(str, axioms)) <= standard:
392
+ gaps.append(_gap("comparator.invalid_axioms", "error",
393
+ f"{rel}: permitted_axioms {sorted(set(map(str, axioms)) - standard)} outside "
394
+ f"{', '.join(sorted(standard))}", "permit only the standard axioms", [path]))
395
+ ch, so = cfg.get("challenge_module"), cfg.get("solution_module")
396
+ if ch and ch == so:
397
+ gaps.append(_gap("comparator.invalid", "error", f"{rel}: challenge_module and solution_module are both "
398
+ f"{ch!r}", "use two distinct modules", [path]))
399
+ for key, mod in (("challenge_module", ch), ("solution_module", so)):
400
+ src = _module_source(mod)
401
+ if src is not None and tree.project(src) not in tree.entries:
402
+ gaps.append(_gap("comparator.path_missing", "error", f"{rel}: {key} {mod} has no source {src} "
403
+ f"tracked in the project", "commit it", [tree.project(src)]))
404
+ gaps += shadow_gaps(tree, rel, path, ch, so)
405
+ csrc = _module_source(ch)
406
+ blob = tree.blob(tree.project(csrc)) if csrc else None
407
+ if blob is not None and (len(blob) > CHALLENGE_MAX_BYTES
408
+ or physical_lines(blob.decode("utf-8", "replace")) > CHALLENGE_MAX_LINES):
409
+ gaps.append(_gap("challenge.too_large", "error",
410
+ f"{csrc} exceeds the Challenge limits ({CHALLENGE_MAX_LINES:,} lines, 100 KiB)",
411
+ "state fewer or shorter declarations in the Challenge", [tree.project(csrc)]))
412
+ if blob is not None:
413
+ gaps += challenge_import_gaps(tree, rel, ch, csrc, blob)
414
+ holes = cfg.get("definition_names") or []
415
+ if isinstance(holes, list) and holes:
416
+ try:
417
+ so = check_definition_holes(cfg, rel, cfg_rel=rel, cfg_bytes=tree.blob(path) or b"",
418
+ sidecar=parse_sidecar(tree.blob(tree.project(SIDECAR))))
419
+ signed = f"; lean-pkg sign-off: {signoff_summary(so)['reviewer']} ({so['source']})"
420
+ except ValueError as e:
421
+ signed = f"; lean-pkg sign-off: none valid ({str(e).split(': ', 1)[-1][:160]})"
422
+ gaps.append(_gap("comparator.definition_holes", "warn",
423
+ f"{rel}: {len(holes)} definition_names entr(y/ies); comparator compares them by name "
424
+ f"and type, never by body, so reviewers must judge the bodies{signed}",
425
+ "keep definition_names empty where you can; otherwise justify each in the submission",
426
+ [path]))
427
+ return gaps
428
+
429
+
430
+ def challenge_import_gaps(tree: Tree, rel: str, ch: str, csrc: str, blob: bytes) -> list[dict]:
431
+ """A warning for each module the Challenge imports beyond Mathlib's vocabulary (#369): the declared
432
+ statements module (trusted by declaration: a reader must read it), and, more strongly, any other module.
433
+ Never an error: Palomar's verifier is what checks Challenge imports against the trusted dependencies."""
434
+ imports = [m for m in dict.fromkeys(lean_scan.header_imports(blob.decode("utf-8", "replace")))
435
+ if not stm.is_vocabulary(m)]
436
+ if not imports:
437
+ return []
438
+ declared, problems = tree.statements()
439
+ path = tree.project(csrc)
440
+ gaps = []
441
+ for m in imports:
442
+ mrel = lean_scan.module_file(m) or m
443
+ if m == declared:
444
+ refused = (f"; lean-pkg refuses the declaration at {tree.commit[:12]}: {problems[0]}"
445
+ + (f" (+{len(problems) - 1} more)" if len(problems) > 1 else "")) if problems else ""
446
+ gaps.append(_gap("challenge.statements_module", "warn",
447
+ f"{rel}: challenge_module {ch} imports {m}, the declared statements module "
448
+ f"({tree.claims_file} {stm.KEY}): trusted by declaration, read it{refused}",
449
+ f"read {mrel} with the Challenge: each hypothesis there is part of what the "
450
+ f"theorems state" + ("; fix the module, commit, re-gate" if problems else ""),
451
+ [path, tree.project(mrel)]))
452
+ else:
453
+ other = (f"the declared statements module is {declared}" if declared
454
+ else f"no statements module is declared ({tree.claims_file} {stm.KEY})")
455
+ gaps.append(_gap("challenge.import", "warn",
456
+ f"{rel}: challenge_module {ch} imports {m}, which is neither Mathlib's vocabulary nor "
457
+ f"the declared statements module ({other}): the statement then rests on {m}, which "
458
+ f"no check here reads",
459
+ "state the Challenge in Mathlib's vocabulary and drop the import; the hypotheses of "
460
+ f"conditional claims go in the one declared statements module ({stm.KEY} in "
461
+ f"{tree.claims_file}); commit, re-gate", [path]))
462
+ return gaps
463
+
464
+
465
+ # --------------------------------------------------------------------------
466
+ # module roots a dependency shadows (#404)
467
+
468
+ _SRC_DIR_TOML = re.compile(r'^\s*srcDir\s*=\s*"([^"\n]*)"', re.MULTILINE)
469
+ _SRC_DIR_LEAN = re.compile(r'\bsrcDir\s*:=\s*"([^"\n]*)"')
470
+
471
+
472
+ def _src_dirs(toml: str | None, lean: str | None) -> list[str]:
473
+ """The package root and every `srcDir` a lakefile states literally (package or lean_lib, each taken
474
+ relative to the package root; nesting a lean_lib srcDir under the package's is not modelled)."""
475
+ found = (_SRC_DIR_TOML.findall(toml) if toml is not None else _SRC_DIR_LEAN.findall(lean or ""))
476
+ out = ["."]
477
+ for d in found:
478
+ d = posixpath.normpath(d.strip() or ".")
479
+ if not d.startswith(("/", "..")) and d not in out:
480
+ out.append(d)
481
+ return out
482
+
483
+
484
+ def _read(p: pathlib.Path) -> str | None:
485
+ try:
486
+ return p.read_text(encoding="utf-8", errors="replace") if p.is_file() else None
487
+ except OSError:
488
+ return None
489
+
490
+
491
+ def dependency_scan(tree: Tree) -> dict:
492
+ """The source trees of the dependencies lake-manifest.json pins at the tree's commit, where the scan can
493
+ read them offline: {complete, reason, scanned: [(name, where, has_root)], pdir}. A git dependency is read
494
+ from its checkout `<project>/<packagesDir>/<name>/` (the working tree's build artifact, by default
495
+ .lake/packages) only when that checkout's HEAD is the pinned rev; a path dependency inside the repository
496
+ from the commit's tree. `complete` is True when every dependency was read; `reason` says why not."""
497
+ mpath = tree.project("lake-manifest.json")
498
+ out: dict = {"complete": False, "reason": None, "scanned": [], "pdir": ".lake/packages"}
499
+ raw = tree.blob(mpath)
500
+ if raw is None:
501
+ out["reason"] = f"no lake-manifest.json at {tree.commit[:12]}"
502
+ return out
503
+ try:
504
+ doc = json.loads(raw.decode("utf-8"))
505
+ except (UnicodeDecodeError, ValueError):
506
+ doc = None
507
+ pkgs = doc.get("packages", []) if isinstance(doc, dict) else None
508
+ if not isinstance(pkgs, list):
509
+ out["reason"] = f"lake-manifest.json at {tree.commit[:12]} is not a manifest with a packages list"
510
+ return out
511
+ pdir = doc.get("packagesDir") if isinstance(doc.get("packagesDir"), str) else ".lake/packages"
512
+ pdir = posixpath.normpath(pdir)
513
+ if pdir.startswith(("/", "..")):
514
+ pdir = ".lake/packages"
515
+ out["pdir"] = pdir
516
+ notes: list[str] = []
517
+ for p in pkgs:
518
+ name = p.get("name") if isinstance(p, dict) else None
519
+ if not isinstance(name, str) or not name:
520
+ notes.append("a package entry without a name")
521
+ continue
522
+ # Lake's directory name for the escaped manifest name (`«dep-x»` is checked out as dep-x)
523
+ dname = build_scope.lake_dir_name(name)
524
+ if dname is None or "/" in dname or "\\" in dname or dname in (".", ".."):
525
+ notes.append(f"{name}: not a Lake package name")
526
+ continue
527
+ name = dname
528
+ if p.get("type") == "path":
529
+ d = posixpath.normpath(posixpath.join(tree.prefix or ".", str(p.get("dir") or "")))
530
+ if d.startswith(("/", "..")) or d == ".":
531
+ notes.append(f"{name}: path dependency {p.get('dir')!r} outside the repository")
532
+ continue
533
+ ent = tree.entries
534
+ srcs = _src_dirs(*((tree.blob(f"{d}/lakefile.toml") or b"").decode("utf-8", "replace")
535
+ if f"{d}/lakefile.toml" in ent else None,
536
+ (tree.blob(f"{d}/lakefile.lean") or b"").decode("utf-8", "replace")
537
+ if f"{d}/lakefile.lean" in ent else None))
538
+ bases = [posixpath.normpath(f"{d}/{s}") for s in srcs]
539
+
540
+ def has(r, bases=bases, ent=ent):
541
+ return any(f"{b}/{r}.lean" in ent or any(k.startswith(f"{b}/{r}/") for k in ent) for b in bases)
542
+ out["scanned"].append((name, d, has))
543
+ continue
544
+ rev = p.get("rev")
545
+ where = f"{pdir}/{name}"
546
+ d = tree.repo / pdir / name
547
+ if not d.is_dir():
548
+ notes.append(f"{name}: not checked out at {where}")
549
+ continue
550
+ top = core.git(d, "rev-parse", "--show-toplevel")
551
+ try:
552
+ own = top.returncode == 0 and pathlib.Path(top.stdout.strip()).resolve() == d.resolve()
553
+ except OSError:
554
+ own = False
555
+ if not own:
556
+ notes.append(f"{name}: {where} is not a git checkout")
557
+ continue
558
+ head = core.git(d, "rev-parse", "HEAD").stdout.strip()
559
+ if not isinstance(rev, str) or head != rev:
560
+ notes.append(f"{name}: {where} is at {head[:12] or 'no commit'}, lake-manifest.json pins "
561
+ f"{str(rev)[:12]}")
562
+ continue
563
+ srcs = _src_dirs(_read(d / "lakefile.toml"), _read(d / "lakefile.lean"))
564
+ bases = [d / s for s in srcs]
565
+
566
+ def has(r, bases=bases):
567
+ return any((b / f"{r}.lean").is_file() or (b / r).is_dir() for b in bases)
568
+ out["scanned"].append((name, where, has))
569
+ out["complete"] = not notes
570
+ if notes:
571
+ what = ("no dependency read" if not out["scanned"]
572
+ else f"{len(notes)} of {len(notes) + len(out['scanned'])} dependencies not read")
573
+ out["reason"] = (f"{what}: " + "; ".join(notes[:5]) + (f"; and {len(notes) - 5} more" if len(notes) > 5
574
+ else "")
575
+ + f" (`lake build` checks them out at the pinned revisions under {pdir}/)")
576
+ return out
577
+
578
+
579
+ def shadow_gaps(tree: Tree, rel: str, path: str, ch, so) -> list[dict]:
580
+ """#404: an error gap for each dependency whose source tree has a top-level `R.lean` or `R/`, R the top-level
581
+ root of challenge_module or solution_module (the resolver may take the dependency's file instead); without
582
+ every dependency's tree, a warn gap for a bare generic root (Challenge, Solution, Main)."""
583
+ gaps: list[dict] = []
584
+ deps = None
585
+ for key, mod in (("challenge_module", ch), ("solution_module", so)):
586
+ if not isinstance(mod, str) or not mod.strip():
587
+ continue
588
+ mod = mod.strip()
589
+ root, _, rest = mod.partition(".")
590
+ kind = key.split("_")[0]
591
+ qual = f"{tree.module_hint}.{rest or root}"
592
+ fix = (f"move the module under a package-qualified root, such as {qual} (the layout `lean-pkg new` "
593
+ f"scaffolds: MOD/Challenge.lean as MOD.Challenge, MOD/Solution.lean as MOD.Solution), and set "
594
+ f"{key} in {rel}; rebuild, commit, re-run comparator-receipt, re-gate")
595
+ deps = deps or tree.dependencies()
596
+ hits = [(name, where) for name, where, has in deps["scanned"] if has(root)]
597
+ for name, where in hits:
598
+ gaps.append(_gap(f"{kind}.module_root_shadowed", "error",
599
+ f"{rel}: {key} {mod}: its top-level name {root!r} is also a top-level entry "
600
+ f"({root}.lean or {root}/) of the dependency {name!r} ({where}), where the resolver "
601
+ f"would look for its source", fix, [path]))
602
+ if not hits and not deps["complete"] and root in GENERIC_ROOTS:
603
+ gaps.append(_gap(f"{kind}.module_root_generic", "warn",
604
+ f"{rel}: {key} {mod} has the bare top-level root {root!r}, a name dependencies also "
605
+ f"use; the dependency scan could not rule out shadowing ({deps['reason']})",
606
+ fix, [path]))
607
+ return gaps
608
+
609
+
610
+ def not_checked(tree: Tree) -> list[str]:
611
+ """NOT_CHECKED, with the shadowing clause dropped when the dependency scan read every dependency and
612
+ carrying the reason when it did not (#404). Unchanged when no configuration asked for the scan."""
613
+ deps = tree._deps
614
+ if deps is None:
615
+ return list(NOT_CHECKED)
616
+ out = list(NOT_CHECKED)
617
+ clause = (f"{_SHADOW_CLAUSE} beyond the dependencies read" if deps["scanned"] else _SHADOW_CLAUSE) \
618
+ + f" (dependency scan incomplete: {deps['reason']})"
619
+ out[3] = out[3].replace(f"; {_SHADOW_CLAUSE};", ";" if deps["complete"] else f"; {clause};")
620
+ return out
621
+
622
+
623
+ def headline_gaps(pkg: dict, tree: Tree, policy: dict, checked: list[str]) -> tuple[list[dict], dict | None]:
624
+ """The headline configuration (headline.py): its own configuration gaps when the loop above did not
625
+ check it, and the subset rule against the comparator receipt the gate records, validated at HEAD as
626
+ `gate --check` validates it (error: uncovered names or unsigned holes; warn: no receipt to judge by)."""
627
+ from . import headline as hl
628
+ try:
629
+ rel, source = hl.declared(pkg, tree.repo, rev=tree.commit)
630
+ except core.Fail as e:
631
+ return [_gap("comparator.headline_invalid", "error", str(e),
632
+ f"lean-pkg update {pkg['name']} --headline-config REL (or '' to clear it)")], None
633
+ if rel is None:
634
+ return [], None
635
+ view = {"config": rel, "source": source, "judged": False, "covered": None}
636
+ path = tree.project(rel)
637
+ if path not in tree.entries:
638
+ return [_gap("comparator.headline_missing", "error",
639
+ f"the headline configuration {rel} ({source}) is not tracked at {tree.commit[:12]}",
640
+ "commit it, or clear the registry field (lean-pkg update NAME --headline-config '')",
641
+ [path])], view
642
+ gaps = [] if rel in checked else config_gaps(tree, policy, rel)
643
+ try:
644
+ cfg = hl.parse(tree.blob(path), rel)
645
+ except ValueError as e:
646
+ if not gaps and rel not in checked: # the loop above already reported a checked one
647
+ gaps.append(_gap("comparator.headline_invalid", "error", str(e),
648
+ "keep only Palomar's six keys and name both modules and the theorems", [path]))
649
+ return gaps, view
650
+ try:
651
+ res = hl.judge(pkg, tree.repo, rel, cfg)
652
+ except core.Fail as e:
653
+ res = {"judged": False, "reason": str(e)}
654
+ if not res["judged"]:
655
+ gaps.append(_gap("comparator.headline_unjudged", "warn",
656
+ f"headline configuration {rel} ({source}) cannot be judged: {res['reason']}; "
657
+ f"formalization.yaml status.main_results falls back to every tracked configuration",
658
+ "run comparator-receipt at the commit, record it (lean-pkg comparator NAME --receipt R) "
659
+ "and re-gate", [path]))
660
+ return gaps, view
661
+ view.update(judged=True, covered=not (res["uncovered"] or res["unsigned"]))
662
+ why = hl.refusal(rel, res)
663
+ if why:
664
+ gaps.append(_gap("comparator.headline_uncovered", "error", why,
665
+ "compare the missing names (a compared configuration, comparator-receipt, re-gate), "
666
+ "or drop them from the headline configuration; commit", [path]))
667
+ return gaps, view
668
+
669
+
670
+ def _module_source(mod) -> str | None:
671
+ if not isinstance(mod, str) or not re.fullmatch(r"[^\s/]+(\.[^\s/]+)*", mod.strip()):
672
+ return None
673
+ return mod.strip().replace(".", "/") + ".lean"
674
+
675
+
676
+ # --------------------------------------------------------------------------
677
+ # formalization.yaml and the licence
678
+
679
+ def _nonempty(v) -> bool:
680
+ return (isinstance(v, str) and v.strip() != "") or (isinstance(v, (list, dict)) and len(v) > 0)
681
+
682
+
683
+ def palomar_minimum(doc: dict, policy: dict) -> list[str]:
684
+ """The mechanical minimum Palomar's README documents (beyond the v0.4 schema): one problem per field."""
685
+ out = []
686
+ proj = doc.get("project") if isinstance(doc.get("project"), dict) else {}
687
+ name = proj.get("name")
688
+ if not _nonempty(name) or (isinstance(name, str) and len(name) > PROJECT_NAME_MAX):
689
+ out.append(f"project.name: non-empty, at most {PROJECT_NAME_MAX} characters")
690
+ for k in ("description", "authors", "license"):
691
+ if not _nonempty(proj.get(k)):
692
+ out.append(f"project.{k}: required, non-empty")
693
+ if not _nonempty(proj.get("responsible_maintainers")) and not _nonempty(proj.get("responsible_maintainer")):
694
+ out.append("project.responsible_maintainers: required, non-empty")
695
+ card = policy["formalization"]["classification_cardinality"]
696
+ cls = doc.get("classification") if isinstance(doc.get("classification"), dict) else {}
697
+ for k in ("arxiv", "msc2020"):
698
+ lo, hi = card[k]
699
+ v = cls.get(k) or []
700
+ if not isinstance(v, list) or not (lo <= len(v) <= hi):
701
+ out.append(f"classification.{k}: {lo} to {hi} codes")
702
+ auto = doc.get("automation") if isinstance(doc.get("automation"), dict) else {}
703
+ if not _nonempty(auto.get("methods")):
704
+ out.append("automation.methods: required, non-empty")
705
+ rv = doc.get("review") if isinstance(doc.get("review"), dict) else {}
706
+ if not _nonempty(rv.get("status")):
707
+ out.append("review.status: required, non-empty")
708
+ sources = doc.get("sources")
709
+ if not isinstance(sources, list) or not sources:
710
+ out.append("sources: required, non-empty")
711
+ return out
712
+ cats = set(policy["formalization"]["source_relationship_categories"])
713
+ rels, original = [], []
714
+ for i, s in enumerate(sources):
715
+ s = s if isinstance(s, dict) else {}
716
+ r = s.get("relationship")
717
+ if r not in cats:
718
+ out.append(f"sources[{i}].relationship: one of {', '.join(sorted(cats))}")
719
+ rels.append(r)
720
+ if s.get("type") == "original-proof":
721
+ original.append((i, r))
722
+ if original:
723
+ if any(r != "other" for _i, r in original) or any(r in SOURCE_BASED for r in rels):
724
+ out.append("sources: an original-proof entry needs relationship other, and the other entries "
725
+ "background or other")
726
+ elif not any(r in SOURCE_BASED for r in rels):
727
+ out.append("sources: no original-proof entry, so at least one relationship must be formalizes, adapts "
728
+ "or independently-proves")
729
+ return out
730
+
731
+
732
+ def formalization_gaps(pkg: dict, tree: Tree, policy: dict) -> tuple[list[dict], dict | None]:
733
+ from . import formalization as fz
734
+ import yaml
735
+ rel = fz.target_rel(pkg)
736
+ path = tree.project(rel)
737
+ raw = tree.blob(path)
738
+ name = pkg["name"]
739
+ if raw is None:
740
+ return [_gap("formalization.missing", "error", f"{rel} is not tracked in the project",
741
+ f"render it (`lean-pkg formalization {name} --write`), fill the placeholders, commit", [path])], None
742
+ try:
743
+ doc = yaml.safe_load(raw.decode("utf-8"))
744
+ except (UnicodeDecodeError, yaml.YAMLError) as e:
745
+ return [_gap("formalization.invalid_yaml", "error", f"{rel}: not valid UTF-8 YAML ({e})",
746
+ "fix the file; commit", [path])], None
747
+ if not isinstance(doc, dict):
748
+ return [_gap("formalization.wrong_root_type", "error", f"{rel}: the top level is not a mapping",
749
+ "fix the file; commit", [path])], None
750
+ gaps = []
751
+ version = doc.get("version")
752
+ if version not in (None, fz.SCHEMA_VERSION):
753
+ gaps.append(_gap("formalization.version", "error", f"{rel}: version {version!r}, Palomar reads {fz.SCHEMA_VERSION}",
754
+ f"re-render with `lean-pkg formalization {name} --write`; commit", [path]))
755
+ mode, errors = fz.validate_doc(doc)
756
+ if errors:
757
+ gaps.append(_gap("formalization.schema", "error",
758
+ f"{rel} fails the {fz.SCHEMA_VERSION} schema ({mode}): " + "; ".join(errors[:10])
759
+ + (f"; and {len(errors) - 10} more" if len(errors) > 10 else ""),
760
+ "fix the fields; commit", [path]))
761
+ holes = fz.find_placeholders(doc)
762
+ if holes:
763
+ gaps.append(_gap("formalization.placeholder", "error",
764
+ f"{rel}: {len(holes)} placeholder value(s): {', '.join(holes)}",
765
+ "replace every [PLACEHOLDER] value; commit", [path]))
766
+ minimum = palomar_minimum(doc, policy)
767
+ if minimum:
768
+ gaps.append(_gap("formalization.palomar_minimum", "error",
769
+ f"{rel} misses Palomar's metadata minimum: " + "; ".join(minimum),
770
+ "fill the fields (PalomarPolicy CONTRIBUTING.md, section 3); commit", [path]))
771
+ return gaps, doc
772
+
773
+
774
+ def license_gaps(pkg: dict, tree: Tree, doc: dict | None) -> list[dict]:
775
+ from . import index as index_mod
776
+ name = pkg["name"]
777
+ root = sorted(p for p in tree.entries if "/" not in p and LICENSE_FILE_RE.match(p))
778
+ gaps = []
779
+ spdx = pkg.get("license_spdx")
780
+ fl = ((doc or {}).get("project") or {}).get("license") if isinstance((doc or {}).get("project"), dict) else None
781
+ if not spdx:
782
+ gaps.append(_gap("license.spdx_unset", "error", "license_spdx is not recorded in the registry",
783
+ f"lean-pkg update {name} --license-spdx ID"))
784
+ if not root:
785
+ gaps.append(_gap("license.missing", "error", "no licence file at the repository root (LICENSE, LICENCE, "
786
+ "COPYING, UNLICENSE or OFL, optionally .md/.markdown/.txt)", "commit one; re-gate"))
787
+ return gaps
788
+ if len(root) > 1:
789
+ gaps.append(_gap("license.ambiguous", "error", f"{len(root)} licence files at the repository root; "
790
+ f"Palomar needs exactly one", "keep one; commit, re-gate", root))
791
+ for p in root:
792
+ if tree.entries[p][0] == "120000":
793
+ gaps.append(_gap("license.not_regular", "error", f"{p} is a symbolic link", "commit a regular file", [p]))
794
+ want = spdx or fl
795
+ text = (tree.blob(root[0]) or b"").decode("utf-8", "replace")
796
+ if not text.strip():
797
+ gaps.append(_gap("license.empty", "error", f"{root[0]} is empty", "commit the licence text", [root[0]]))
798
+ marker = index_mod.LICENSE_MARKERS.get(str(want)) if want else None
799
+ if marker and text.strip() and marker not in text:
800
+ gaps.append(_gap("license.mismatch", "error", f"{root[0]} does not read like {want} (no {marker!r})",
801
+ "commit the licence text the SPDX identifier names", [root[0]]))
802
+ if spdx and fl and str(fl) != str(spdx):
803
+ gaps.append(_gap("license.mismatch", "error",
804
+ f"formalization.yaml project.license {fl} differs from license_spdx {spdx}",
805
+ f"re-render (`lean-pkg formalization {name} --write`); commit"))
806
+ return gaps
807
+
808
+
809
+ def repository_gaps(pkg: dict, tree: Tree) -> list[dict]:
810
+ name = pkg["name"]
811
+ gaps = []
812
+ if not core.gh_nwo(str(pkg.get("repo") or "")):
813
+ gaps.append(_gap("repository.not_github", "error", f"repo {pkg.get('repo')!r} is not a GitHub repository; "
814
+ "Palomar accepts public GitHub repositories only",
815
+ f"lean-pkg update {name} --url git@github.com:OWNER/REPO.git (after creating it)"))
816
+ if pkg.get("visibility") != "public":
817
+ gaps.append(_gap("repository.not_public", "warn",
818
+ f"the registry records visibility {pkg.get('visibility')!r} (not queried)",
819
+ f"lean-pkg publish {name} --dry-run, then lean-pkg promote {name}"))
820
+ p = core.git(tree.repo, "for-each-ref", "--format=%(refname)", "--contains", tree.commit, "refs/remotes/")
821
+ if p.returncode != 0 or not p.stdout.strip():
822
+ gaps.append(_gap("commit.not_pushed", "warn",
823
+ f"commit {tree.commit[:12]} is in no remote-tracking branch (local refs; nothing fetched)",
824
+ "push it; Palomar pins a commit of the public repository"))
825
+ return gaps
826
+
827
+
828
+ # --------------------------------------------------------------------------
829
+ # the check
830
+
831
+ def resolve_commit(pkg: dict, repo: pathlib.Path, rev: str | None) -> tuple[str, str]:
832
+ name = pkg["name"]
833
+ if rev is not None:
834
+ sha = core._rev(repo, rev)
835
+ if not sha:
836
+ raise core.Fail(f"{name}: --rev {rev!r} is not a commit of {repo}")
837
+ return sha, "rev"
838
+ from .fresh_repo import gate_bound_commit
839
+ sha = gate_bound_commit(pkg, repo)
840
+ if sha and core._rev(repo, sha):
841
+ return sha, "gate"
842
+ head = core.git_head(repo)
843
+ if head is None:
844
+ raise core.Fail(f"{name}: {repo} is not a git checkout with a commit")
845
+ return head, "head"
846
+
847
+
848
+ def check(pkg: dict, repo: pathlib.Path, commit: str, policy: dict, source: dict,
849
+ config: str | None = None) -> dict:
850
+ tree = Tree(repo, commit, pkg.get("claims_file") or "claims.yaml")
851
+ # the root module `lean-pkg new` gives the name (scaffold.module_of: my-proof -> MyProof)
852
+ tree.module_hint = "".join(part[:1].upper() + part[1:] for part in str(pkg["name"]).split("-"))
853
+ gaps, facts = source_gaps(tree, policy, pkg["name"])
854
+ tc_gaps, tc = toolchain_gaps(tree, policy)
855
+ gaps += tc_gaps + layout_gaps(tree)
856
+ cg, configs = comparator_gaps(tree, policy, config)
857
+ hg, headline = headline_gaps(pkg, tree, policy, configs)
858
+ fg, doc = formalization_gaps(pkg, tree, policy)
859
+ gaps += cg + hg + fg + license_gaps(pkg, tree, doc) + repository_gaps(pkg, tree)
860
+ errors = sum(g["severity"] == "error" for g in gaps)
861
+ # #237: a warning, never a gap (Palomar's rules have no such list); an unreadable list matches nothing
862
+ from . import toolchain_advisories
863
+ advisories, _problem = toolchain_advisories.lookup(tc)
864
+ return {"ready": errors == 0, "commit": commit, "project_path": tree.prefix.rstrip("/") or ".",
865
+ "lean_toolchain": tc, "toolchain_advisories": advisories, "configs": configs, "headline": headline,
866
+ **facts,
867
+ "counts": {"error": errors, "warn": len(gaps) - errors}, "gaps": gaps,
868
+ "rules": {**source, "toolchain_minimum": policy["toolchain"]["minimum"]},
869
+ "not_checked": not_checked(tree)}
870
+
871
+
872
+ def verdict(name: str, rep: dict) -> str:
873
+ c = rep["counts"]
874
+ head = f"{name}: Palomar check at {rep['commit'][:12]}"
875
+ if rep["ready"]:
876
+ return head + (": READY" + (f" ({c['warn']} warning(s): submission steps or advice)" if c["warn"] else ""))
877
+ return head + f": NOT READY — {c['error'] + c['warn']} gap(s): {c['error']} error, {c['warn']} warn"
878
+
879
+
880
+ def report_lines(name: str, rep: dict, commit_source: str) -> list[str]:
881
+ src = {"gate": "the gate-bound commit", "head": "HEAD", "rev": "--rev"}[commit_source]
882
+ lines = [verdict(name, rep) + f" [{src}]"]
883
+ from .toolchain_advisories import warn_line
884
+ lines += [f" {warn_line(v)}" for v in rep.get("toolchain_advisories") or []]
885
+ for g in rep["gaps"]:
886
+ mark = "✗" if g["severity"] == "error" else "WARN"
887
+ lines.append(f" {mark} {g['code']}: {g['detail']}")
888
+ lines += [f" {p}" for p in g["paths"]]
889
+ lines.append(f" fix: {g['fix']}")
890
+ r = rep["rules"]
891
+ lines.append(f"rules: {'PalomarSubmission@' + r['commit'][:12] + ' (committed ' + r['committed'] + ', read ' + r['retrieved'] + ')' if r.get('kind') == 'pinned' else '--rules ' + str(r.get('path'))}; "
892
+ f"toolchain minimum {r['toolchain_minimum']}; {rep['lean_files']} .lean file(s), "
893
+ f"{rep['missing_module']} without a module header")
894
+ lines.append("not checked (Palomar's verifier does): " + "; ".join(rep["not_checked"]))
895
+ if rep["gaps"]:
896
+ lines.append(verdict(name, rep))
897
+ return lines
898
+
899
+
900
+ def summary(pkg: dict, repo: pathlib.Path, commit: str) -> dict:
901
+ """The hook for `gate --check` and `publish --dry-run`: {ready, commit, errors, warns, codes, command}
902
+ with the pinned rules; {error: TEXT} when the check itself could not run (never a refusal)."""
903
+ name = pkg["name"]
904
+ cmd = f"lean-pkg palomar check {name} --rev {commit[:12]}"
905
+ try:
906
+ policy, source = load_rules(None)
907
+ rep = check(pkg, repo, commit, policy, source)
908
+ except (core.Fail, OSError, ValueError) as e:
909
+ return {"ready": None, "commit": commit, "error": str(e), "command": cmd}
910
+ return {"ready": rep["ready"], "commit": commit, "errors": rep["counts"]["error"],
911
+ "warns": rep["counts"]["warn"], "codes": sorted({g["code"] for g in rep["gaps"]}), "command": cmd}
912
+
913
+
914
+ # why the gate's advisory stays quiet for a package that does not intend Palomar (#387)
915
+ SKIPPED_NOT_AIMING = "not aiming at Palomar"
916
+
917
+
918
+ def hook(reg: dict, name: str, commit: str | None) -> dict | None:
919
+ """summary() for the package NAME at `commit` (None: HEAD), plus `skipped`: None for a package that
920
+ intends Palomar, else SKIPPED_NOT_AIMING (the fields are still filled; the gate prints no WARN, #387).
921
+ None when there is no checkout to read."""
922
+ pkg = core.get_pkg(reg, name)
923
+ repo = core.repo_path(pkg)
924
+ if not repo.is_dir():
925
+ return None
926
+ commit = commit or core.git_head(repo)
927
+ if not commit or not core._rev(repo, commit):
928
+ return None
929
+ return {**summary(pkg, repo, commit), "skipped": None if intends_palomar(pkg) else SKIPPED_NOT_AIMING}
930
+
931
+
932
+ def summary_warning(view: dict) -> str | None:
933
+ if view.get("skipped"):
934
+ return None
935
+ if view.get("ready") is None:
936
+ return f"palomar: the readiness check could not run ({view.get('error')}); run {view['command']}"
937
+ if view["ready"]:
938
+ return None
939
+ return (f"palomar: not submittable at {view['commit'][:12]}: {view['errors']} gap(s) need a new commit "
940
+ f"({', '.join(view['codes'])}); see {view['command']}")
941
+
942
+
943
+ # packages aiming at Palomar: the record says so (upstream_target palomar) or Palomar evidence exists;
944
+ # a scratch, archived or upstreamed package is not judged (audit stays quiet for it)
945
+ AUDIT_EXEMPT_STATUSES = ("scratch", "archived", "upstreamed")
946
+
947
+
948
+ def intends_palomar(pkg: dict) -> bool:
949
+ if pkg.get("status") in AUDIT_EXEMPT_STATUSES:
950
+ return False
951
+ return pkg.get("upstream_target") == "palomar" or any(isinstance(e, dict) for e in pkg.get("palomar") or [])
952
+
953
+
954
+ def error_gaps(rep: dict) -> list[dict]:
955
+ return [g for g in rep["gaps"] if g["severity"] == "error"]
956
+
957
+
958
+ def gap_lines(gaps: list[dict]) -> list[str]:
959
+ return [f" ✗ {g['code']}: {g['detail']}" + "".join(f"\n {p}" for p in g["paths"])
960
+ + f"\n fix: {g['fix']}" for g in gaps]
961
+
962
+
963
+ def audit_finding(pkg: dict, repo: pathlib.Path) -> dict | None:
964
+ """The `palomar-not-ready` audit finding for a package that intends Palomar, judged at the commit
965
+ `palomar check NAME` reads (gate-bound, else HEAD), with the pinned rules; None when it is ready
966
+ (warn gaps are submission steps, never a finding) or does not intend Palomar."""
967
+ if not intends_palomar(pkg):
968
+ return None
969
+ name = pkg["name"]
970
+ cmd = f"lean-pkg palomar check {name}"
971
+ try:
972
+ commit, how = resolve_commit(pkg, repo, None)
973
+ policy, source = load_rules(None)
974
+ rep = check(pkg, repo, commit, policy, source)
975
+ except (core.Fail, OSError, ValueError) as e:
976
+ return {"detail": f"Palomar readiness could not be checked ({e}); run `{cmd}`",
977
+ "errors": None, "codes": [], "commit": None, "command": cmd}
978
+ errs = error_gaps(rep)
979
+ if not errs:
980
+ return None
981
+ codes = sorted({g["code"] for g in errs})
982
+ src = {"gate": "the gate-bound commit", "head": "HEAD"}[how]
983
+ return {"detail": f"{len(errs)} Palomar readiness gap(s) at {src} {commit[:12]} ({', '.join(codes)}); "
984
+ f"run `{cmd}`",
985
+ "errors": len(errs), "codes": codes, "commit": commit, "command": cmd}
986
+
987
+
988
+ def cmd_check(args) -> int:
989
+ reg = core.load_registry(core.registry_path(args))
990
+ override = None
991
+ if getattr(args, "repo", None) is not None:
992
+ reg, override = gate_mod.repo_override(reg, args.name, args.repo)
993
+ if note := gate_mod.repo_override_note(override):
994
+ print(note, file=core.sys.stderr)
995
+ policy, source = load_rules(args.rules)
996
+ pkg = core.get_pkg(reg, args.name)
997
+ repo = core.repo_path(pkg)
998
+ if not repo.is_dir():
999
+ raise core.Fail(f"{args.name}: local_path does not exist: {repo}")
1000
+ commit, how = resolve_commit(pkg, repo, args.rev)
1001
+ rep = check(pkg, repo, commit, policy, source, args.config)
1002
+ if getattr(args, "json_out", False):
1003
+ core.print_json({"ok": rep["ready"], "name": args.name, "commit_source": how, **rep,
1004
+ "repo_override": override})
1005
+ else:
1006
+ print("\n".join(report_lines(args.name, rep, how)))
1007
+ return 0 if rep["ready"] else 1
1008
+
1009
+
1010
+ def add_parser(psub, add_json) -> None:
1011
+ p = psub.add_parser("check", help="read-only, offline: every gap to Palomar's mechanical rules at one commit "
1012
+ "(module headers, toolchain floor, comparator configs, formalization.yaml, "
1013
+ "licence, repository); exit 0 ready / 1 gaps")
1014
+ p.add_argument("name")
1015
+ p.add_argument("--rev", default=None, metavar="REV",
1016
+ help="the commit to judge (default: the gate-bound commit, else HEAD)")
1017
+ p.add_argument("--config", default=None, metavar="PATH",
1018
+ help="judge only this comparator configuration (Palomar verifies the one a submission names); "
1019
+ "default: every configuration tracked at the commit")
1020
+ p.add_argument("--rules", default=None, metavar="FILE",
1021
+ help="a newer PalomarSubmission browser-preflight-policy.json (schema 1) downloaded by hand; "
1022
+ f"default: the rules pinned at PalomarSubmission {RULES_SOURCE['commit'][:12]} "
1023
+ f"(read {RULES_SOURCE['retrieved']})")
1024
+ p.add_argument("--repo", default=None, metavar="DIR",
1025
+ help="judge the checkout DIR instead of the registered local_path (never saved)")
1026
+ add_json(p)
1027
+ p.set_defaults(fn=cmd_check, palomar_fn="check")