lean-pkg 0.25.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. lean_pkg/__init__.py +3 -0
  2. lean_pkg/adapters/__init__.py +148 -0
  3. lean_pkg/adapters/github.py +65 -0
  4. lean_pkg/adapters/leansearch.py +68 -0
  5. lean_pkg/adapters/loogle.py +45 -0
  6. lean_pkg/adapters/palomar.py +170 -0
  7. lean_pkg/adapters/reservoir.py +127 -0
  8. lean_pkg/anchor.py +678 -0
  9. lean_pkg/audit.py +716 -0
  10. lean_pkg/binding_file.py +446 -0
  11. lean_pkg/blueprint.py +213 -0
  12. lean_pkg/build_scope.py +282 -0
  13. lean_pkg/ci_github.py +917 -0
  14. lean_pkg/claim_axioms.py +421 -0
  15. lean_pkg/claims.py +1155 -0
  16. lean_pkg/claims_mark.py +197 -0
  17. lean_pkg/cli.py +5208 -0
  18. lean_pkg/cli_parser.py +768 -0
  19. lean_pkg/command_tree.py +615 -0
  20. lean_pkg/comparator_config.py +990 -0
  21. lean_pkg/comparator_contracts.py +382 -0
  22. lean_pkg/comparator_receipt.py +2854 -0
  23. lean_pkg/comparator_stage.py +623 -0
  24. lean_pkg/comparator_types.py +830 -0
  25. lean_pkg/container.py +172 -0
  26. lean_pkg/core.py +1570 -0
  27. lean_pkg/coverage.py +1278 -0
  28. lean_pkg/data/stacks/lts-2026.10.yaml +73 -0
  29. lean_pkg/data/toolchain-advisories.yaml +77 -0
  30. lean_pkg/data/upgrade-breaking.yaml +20 -0
  31. lean_pkg/data/verify-workflow-pins.yaml +14 -0
  32. lean_pkg/deps_closure.py +512 -0
  33. lean_pkg/deps_fill.py +445 -0
  34. lean_pkg/dup_constants.py +448 -0
  35. lean_pkg/exercise.py +828 -0
  36. lean_pkg/exercise_forbid.py +288 -0
  37. lean_pkg/export_paths.py +77 -0
  38. lean_pkg/extract.py +1172 -0
  39. lean_pkg/extract_decls.py +501 -0
  40. lean_pkg/extract_ledger.py +1408 -0
  41. lean_pkg/extract_summary.py +132 -0
  42. lean_pkg/extract_types.py +502 -0
  43. lean_pkg/extract_write.py +138 -0
  44. lean_pkg/formalization.py +1078 -0
  45. lean_pkg/formalization_kept.py +182 -0
  46. lean_pkg/fresh_repo.py +709 -0
  47. lean_pkg/gate.py +2141 -0
  48. lean_pkg/headline.py +211 -0
  49. lean_pkg/help_topics.py +442 -0
  50. lean_pkg/holes.py +289 -0
  51. lean_pkg/host_routes.py +376 -0
  52. lean_pkg/hypotheses.py +788 -0
  53. lean_pkg/index.py +1749 -0
  54. lean_pkg/json_stdout.py +48 -0
  55. lean_pkg/lake_hygiene.py +289 -0
  56. lean_pkg/lean_diag.py +280 -0
  57. lean_pkg/lean_scan.py +1300 -0
  58. lean_pkg/ledger.py +582 -0
  59. lean_pkg/next_step.py +510 -0
  60. lean_pkg/page.py +1831 -0
  61. lean_pkg/page_html.py +153 -0
  62. lean_pkg/palomar.py +316 -0
  63. lean_pkg/palomar_check.py +1027 -0
  64. lean_pkg/port_modules.py +677 -0
  65. lean_pkg/prior_art.py +286 -0
  66. lean_pkg/producer.py +212 -0
  67. lean_pkg/producer_skew.py +208 -0
  68. lean_pkg/public_safety.py +1487 -0
  69. lean_pkg/publish.py +402 -0
  70. lean_pkg/rebase.py +984 -0
  71. lean_pkg/receipt.py +2385 -0
  72. lean_pkg/receipt_check.py +1064 -0
  73. lean_pkg/receipt_ci.py +660 -0
  74. lean_pkg/receipt_systemd.py +890 -0
  75. lean_pkg/recommended.py +232 -0
  76. lean_pkg/report.py +727 -0
  77. lean_pkg/reservoir.py +203 -0
  78. lean_pkg/scaffold.py +588 -0
  79. lean_pkg/schemas/formalization-0.4.schema.json +344 -0
  80. lean_pkg/schemas/formalization-0.4.schema.source.txt +15 -0
  81. lean_pkg/scripts/ClaimAxioms.lean +47 -0
  82. lean_pkg/scripts/ContractsOnly.lean +300 -0
  83. lean_pkg/scripts/DupConstants.lean +149 -0
  84. lean_pkg/scripts/HypProbe.lean +257 -0
  85. lean_pkg/scripts/comparator-check.sh +396 -0
  86. lean_pkg/scripts/verify-comparator.sh +135 -0
  87. lean_pkg/seal_bundle.py +647 -0
  88. lean_pkg/search.py +865 -0
  89. lean_pkg/site_profiles/easley.yaml +10 -0
  90. lean_pkg/site_profiles/github-actions.yaml +12 -0
  91. lean_pkg/sites.py +225 -0
  92. lean_pkg/stacks.py +373 -0
  93. lean_pkg/statements_module.py +217 -0
  94. lean_pkg/templates/Apache-2.0.txt +202 -0
  95. lean_pkg/toolchain_advisories.py +225 -0
  96. lean_pkg/upgrade.py +706 -0
  97. lean_pkg/verify.py +495 -0
  98. lean_pkg-0.25.0.dist-info/METADATA +93 -0
  99. lean_pkg-0.25.0.dist-info/RECORD +103 -0
  100. lean_pkg-0.25.0.dist-info/WHEEL +5 -0
  101. lean_pkg-0.25.0.dist-info/entry_points.txt +5 -0
  102. lean_pkg-0.25.0.dist-info/licenses/LICENSE +202 -0
  103. lean_pkg-0.25.0.dist-info/top_level.txt +1 -0
lean_pkg/verify.py ADDED
@@ -0,0 +1,495 @@
1
+ # lean-pkg verify -- both receipts and the gate, in one command, on this machine
2
+ """`lean-pkg verify NAME [--work-dir DIR] [--unit UNIT] [--script FILE] [--judges N] [--agent A] [--reason TEXT]
3
+ [--dry-run] [--json]`: the newcomer's one step from a committed package to `verified-private` (1.0 command tree,
4
+ docs/design/1.0-command-tree.md, decision 4).
5
+
6
+ A pure orchestrator. Each step is the lean-pkg command a person would type, run as its own invocation (its own
7
+ checks, refusals, registry lock and committed mode), and printed before it runs:
8
+
9
+ 0. the preflight (#325), read-only and in-process, also under --dry-run: the claims/1 check `claims check --file`
10
+ runs, on the claims file committed at HEAD, and, when coverage.yaml is committed, the offline `coverage
11
+ check` (coverage.preflight_at_head: schema and length limits, claim ids, comparator theorems mapped to rows,
12
+ against the files and configurations committed at HEAD; placeholder text and an unposted manuscript are
13
+ warnings here, since `coverage check` and `page` refuse them later). A refusal stops verify with that message
14
+ before any receipt work: nothing run, nothing written. Files only in the working tree are never read.
15
+ Step 0 also scans the imports at HEAD (port_modules.non_module_imports, #392): a module-headed file of the
16
+ package that imports a non-module file of the package is a warning naming the files and `lean-pkg palomar
17
+ port-modules NAME --dry-run`, never a refusal (skipped silently when the tree cannot be read);
18
+ 1. the comparator receipt: `lean-pkg receipt comparator --repo CHECKOUT` (the `comparator-receipt` program);
19
+ 2. the lower-tier receipt on this workstation: `lean-pkg receipt systemd --unit U --receipt-commit X --log
20
+ W/verify.log --stdout W/unit.out --stderr W/unit.err --repo CHECKOUT --run -- bash verify.sh W/verify.log`,
21
+ W a work directory outside the checkout;
22
+ 3. for a package still `active`, the status move the gate needs: `lean-pkg update NAME --status gate-pending
23
+ --reason R` (the move the by-hand path makes);
24
+ 4. the gate: `lean-pkg gate NAME --receipt LOWER --comparator COMPARATOR` (`--regate` for a package already
25
+ verified-private or public).
26
+
27
+ It writes nothing these commands would not write, and it commits nothing in the package checkout: the receipts
28
+ are left for the author to commit (`git add .lean-receipts`), which is the next line it prints.
29
+
30
+ The order is the binding: both receipts must bind one commit X, the checkout's HEAD when verify starts, so
31
+ nothing is committed between them. The comparator receipt runs first because `comparator-receipt` refuses any
32
+ untracked file in the checkout, while `receipt systemd` allows the untracked receipts under .lean-receipts/; the
33
+ other order would need a commit between the two receipts, which binds them to two commits (the gate refuses
34
+ that: both tiers must bind to one commit). A receipt of this commit already present (an earlier verify that
35
+ stopped later) is reused, not re-run; the gate validates it as it validates any receipt.
36
+
37
+ Refused before any step runs: an unknown package, a checkout that is not at a clean commit (a modified tracked
38
+ file, or an untracked file other than this commit's receipts under .lean-receipts/), no verify script, no
39
+ comparator configuration, a status the gate cannot reach (scratch, archived, upstreamed), --registry-snapshot.
40
+ A step that fails stops verify with that step's exit code; the steps before it stay done (their receipts are
41
+ reused by the next verify at the same commit).
42
+
43
+ A package whose committed coverage.yaml declares an LTS stack (`stack: NAME`, proposal 0004) is checked against
44
+ it first: lean-toolchain and the Mathlib commit of lake-manifest.json at HEAD, then, once the comparator
45
+ receipt exists, its toolchain digests. verify prints `on stack NAME (supported until DATE)` or one warning per
46
+ difference (a stack past its window, or one this lean-pkg does not declare, is a warning too), and `--json`
47
+ carries `stack` {name, declared, matches, supported_until, window, toolchain, mathlib, comparator_tools,
48
+ lean_pkg, mismatches, warnings} (null without the key). It never refuses on a stack: the proposal says doctor
49
+ and verify "never refuse", and "the stack key never makes a check pass or fail".
50
+ """
51
+
52
+ from __future__ import annotations
53
+
54
+ import contextlib
55
+ import datetime as dt
56
+ import io
57
+ import json
58
+ import os
59
+ import pathlib
60
+ import re
61
+ import shlex
62
+ import sys
63
+
64
+ from . import cli, cli_parser, gate as gate_mod
65
+ from . import core
66
+
67
+ GATE_FROM = ("gate-pending", "active") # a first gate
68
+ REGATE_FROM = ("verified-private", "public") # a re-gate on a new commit (public: evidence, status kept)
69
+ NO_MATHLIB_LINE = re.compile(r"^\s*echo\s+[\"']?mathlib-rev:\s*none[\"']?\s*(?:>>\S+)?\s*$", re.MULTILINE)
70
+ STATE_ENV = "XDG_STATE_HOME"
71
+
72
+
73
+ def work_root() -> pathlib.Path:
74
+ base = os.environ.get(STATE_ENV, "").strip()
75
+ return (pathlib.Path(base) if base else pathlib.Path.home() / ".local" / "state") / "lean-pkg" / "verify"
76
+
77
+
78
+ def _git(repo: pathlib.Path, *a: str) -> str:
79
+ p = core.git(repo, *a)
80
+ return p.stdout if p.returncode == 0 else ""
81
+
82
+
83
+ def tracked_at(repo: pathlib.Path, commit: str, rel: str) -> str | None:
84
+ p = core.git(repo, "show", f"{commit}:{rel}")
85
+ return p.stdout if p.returncode == 0 else None
86
+
87
+
88
+ def own_receipts(rel: str, c12: str) -> bool:
89
+ """An untracked path verify may find in a clean checkout: this commit's receipts and their files."""
90
+ return rel.startswith(f".lean-receipts/{c12}-")
91
+
92
+
93
+ def tree_problems(repo: pathlib.Path, c12: str) -> list[str]:
94
+ """What keeps the checkout from being a clean commit for both receipts (paths only)."""
95
+ status = core.git(repo, "status", "--porcelain", "--untracked-files=all")
96
+ if status.returncode != 0:
97
+ return [f"git status failed: {status.stderr.strip()}"]
98
+ out = []
99
+ for line in status.stdout.splitlines():
100
+ code, rel = line[:2], line[3:].strip('"')
101
+ if code == "??" and own_receipts(rel, c12):
102
+ continue
103
+ out.append(f"{'untracked' if code == '??' else 'modified'} {rel}")
104
+ return out
105
+
106
+
107
+ def lower_receipts(repo: pathlib.Path, c12: str, unit: str) -> list[pathlib.Path]:
108
+ """This commit's lower-tier receipts from unit U, newest first."""
109
+ d = repo / ".lean-receipts"
110
+ if not d.is_dir():
111
+ return []
112
+ slug = re.escape(f"{c12}-systemd-user-{unit}.service-")
113
+ rx = re.compile(rf"^{slug}[0-9a-f]{{32}}-[A-Za-z0-9._-]+\.json$")
114
+ found = [p for p in d.iterdir() if p.is_file() and rx.match(p.name)]
115
+ return sorted(found, key=lambda p: p.stat().st_mtime, reverse=True)
116
+
117
+
118
+ def knowingly_no_mathlib(repo: pathlib.Path, commit: str, script: str) -> bool:
119
+ """The committed verify script declares `mathlib-rev: none` (what `new --no-mathlib` writes) and the
120
+ manifest has no Mathlib: the package knowingly has none, which comparator-receipt needs said explicitly
121
+ (COMPARATOR_RECEIPT_NO_MATHLIB=1)."""
122
+ from . import comparator_receipt as cr
123
+ text = tracked_at(repo, commit, script) or ""
124
+ return bool(NO_MATHLIB_LINE.search(text)) and not cr.manifest_has_mathlib(repo)
125
+
126
+
127
+ def _current(name: str) -> str | None:
128
+ return os.environ.get(name)
129
+
130
+
131
+ def invoke(argv: list[str], capture_json: bool = False, quiet_stdout: bool = False) -> tuple[int, dict | None]:
132
+ """Run one lean-pkg invocation in this process, exactly as `lean-pkg ARGV` would (its own parse, checks,
133
+ registry lock and committed mode). capture_json: ARGV ends in --json and its stdout is parsed, not printed;
134
+ quiet_stdout: its stdout goes to stderr (the caller's stdout carries one JSON object)."""
135
+ saved_json = cli_parser._Parser.json_requested
136
+ buf = io.StringIO()
137
+ try:
138
+ redirect = contextlib.redirect_stdout(buf) if capture_json else \
139
+ contextlib.redirect_stdout(sys.stderr) if quiet_stdout else contextlib.nullcontext()
140
+ with redirect:
141
+ rc = cli.main(list(argv))
142
+ finally:
143
+ cli_parser._Parser.json_requested = saved_json
144
+ payload = None
145
+ if capture_json:
146
+ try:
147
+ payload = json.loads(buf.getvalue())
148
+ except ValueError:
149
+ payload = None
150
+ return rc, payload
151
+
152
+
153
+ class Steps:
154
+ """Runs and records the steps: each a lean-pkg argv, printed first (text mode) and run in-process as its own
155
+ invocation. In --json mode a step's stdout goes to stderr, except the JSON of the steps that print one."""
156
+
157
+ def __init__(self, args, globals_: list[str]):
158
+ self.json_out = bool(getattr(args, "json_out", False))
159
+ self.globals = globals_
160
+ self.done: list[dict] = []
161
+
162
+ def say(self, line: str) -> None:
163
+ print(line, file=sys.stderr if self.json_out else sys.stdout, flush=True)
164
+
165
+ def run(self, label: str, argv: list[str], registry: bool = False, want_json: bool = False,
166
+ env: dict | None = None) -> tuple[int, dict | None]:
167
+ full = (self.globals if registry else []) + argv + (["--json"] if want_json and self.json_out else [])
168
+ shown = "lean-pkg " + shlex.join(full)
169
+ self.say(f"verify: {label}: {shown}")
170
+ saved_env = {k: _current(k) for k in (env or {})}
171
+ try:
172
+ os.environ.update(env or {})
173
+ rc, payload = invoke(full, capture_json=want_json and self.json_out, quiet_stdout=self.json_out)
174
+ finally:
175
+ for k, v in saved_env.items():
176
+ if v is None:
177
+ os.environ.pop(k, None)
178
+ else:
179
+ os.environ[k] = v
180
+ self.done.append({"step": label, "command": shown, "rc": rc, **({"env": env} if env else {}),
181
+ **({"output": payload} if payload is not None else {})})
182
+ return rc, payload
183
+
184
+ def skip(self, label: str, why: str) -> None:
185
+ self.say(f"verify: {label}: skipped: {why}")
186
+ self.done.append({"step": label, "skipped": why})
187
+
188
+
189
+ def global_flags(args) -> list[str]:
190
+ """The registry flags the registry steps repeat (update, gate)."""
191
+ out = []
192
+ for flag, dest in (("--registry", "registry"), ("--events", "events")):
193
+ v = getattr(args, dest, None)
194
+ if v:
195
+ out += [flag, str(v)]
196
+ for flag, dest in (("--no-commit", "no_commit"), ("--push", "push"), ("--commit", "commit")):
197
+ if getattr(args, dest, False):
198
+ out.append(flag)
199
+ return out
200
+
201
+
202
+ def plan(args) -> dict:
203
+ """Everything decided before a step runs; refusals here leave nothing behind."""
204
+ if core.registry_snapshot_arg(args):
205
+ raise core.UsageError("verify writes receipts and the gate; it does not run against --registry-snapshot")
206
+ reg = core.load_registry(core.registry_path(args))
207
+ pkg = core.get_pkg(reg, args.name)
208
+ status = pkg.get("status")
209
+ if status not in GATE_FROM + REGATE_FROM:
210
+ hint = (f"`lean-pkg update {args.name} --status active --reason R` first" if status == "scratch"
211
+ else "a package in this status is not gated again")
212
+ raise core.Fail(f"{args.name}: status {status}: verify gates active, gate-pending, verified-private or "
213
+ f"public packages; {hint}")
214
+ if args.agent:
215
+ core.lease_actor(reg, args.name, args.agent, "verify") # a foreign live lease refuses before any run
216
+ repo = core.repo_path(pkg)
217
+ if not repo.is_dir():
218
+ raise core.Fail(f"{args.name}: local_path does not exist: {repo}")
219
+ head = core.git_head(repo)
220
+ if head is None:
221
+ raise core.Fail(f"{args.name}: {repo} is not a git checkout with a commit")
222
+ c12 = head[:12]
223
+ gate = pkg.get("gate") or {}
224
+ bound = gate_mod.recorded_json(repo, gate.get("receipt"))
225
+ already = None # the gated commit, when HEAD is it or an evidence-only descendant of it
226
+ if isinstance(bound, dict) and gate.get("comparator") and isinstance(bound.get("commit"), str):
227
+ if bound["commit"] == head:
228
+ already = head
229
+ else:
230
+ ok, _note, _docs = gate_mod.package_descendant(repo, bound["commit"], head, pkg, checker=bound.get("checker"))
231
+ already = bound["commit"] if ok else None
232
+ if already:
233
+ return {"reg": reg, "pkg": pkg, "status": status, "repo": repo, "head": head, "c12": c12,
234
+ "already": already, "work": None}
235
+ problems = tree_problems(repo, c12)
236
+ if problems:
237
+ shown = "; ".join(problems[:10]) + (f" (+{len(problems) - 10} more)" if len(problems) > 10 else "")
238
+ raise core.Fail(f"{args.name}: the checkout is not a clean commit ({shown}); both receipts bind HEAD "
239
+ f"{c12}, so commit or remove these first; nothing run")
240
+ script = args.script
241
+ if tracked_at(repo, head, script) is None:
242
+ raise core.Fail(f"{args.name}: no {script} committed at {c12} (the lower-tier check `lean-pkg new` "
243
+ f"writes; --script FILE names another); nothing run")
244
+ from . import comparator_receipt as cr
245
+ if not cr.list_configs(repo):
246
+ raise core.Fail(f"{args.name}: no comparator configuration in {repo} (comparator*.json or "
247
+ f"comparator/config*.json); nothing run")
248
+ unit = args.unit or f"{args.name}-verify"
249
+ if not re.fullmatch(r"[A-Za-z0-9:_.\\-]+", unit):
250
+ raise core.UsageError(f"--unit {unit!r}: a systemd unit name is letters, digits and :_.-\\ only")
251
+ if args.work_dir:
252
+ work = pathlib.Path(args.work_dir).expanduser().resolve()
253
+ else:
254
+ stamp = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
255
+ work = work_root() / args.name / f"{c12}-{stamp}"
256
+ try:
257
+ work.relative_to(repo.resolve())
258
+ raise core.UsageError(f"--work-dir {work} is inside the checkout; the run's log and unit files go outside "
259
+ f"it (the run refuses an untracked file in the package)")
260
+ except ValueError:
261
+ pass
262
+ comparator = repo / ".lean-receipts" / f"{c12}-comparator.json"
263
+ return {"reg": reg, "pkg": pkg, "status": status, "repo": repo, "head": head, "c12": c12, "unit": unit,
264
+ "work": work, "script": script, "already": already, "comparator": comparator,
265
+ "no_mathlib": knowingly_no_mathlib(repo, head, script)}
266
+
267
+
268
+ def stack_check(steps: Steps, repo: pathlib.Path, head: str) -> dict | None:
269
+ """The LTS stack the committed coverage.yaml declares, against the pins at HEAD (proposal 0004): one line
270
+ `on stack S (supported until D)` or a warning per difference. Never a refusal: "they never refuse"
271
+ (proposal 0004, "How a package opts in"); the stack key never makes a check pass or fail ("Trust model")."""
272
+ from . import stacks
273
+ name = stacks.declared_key(repo, head)
274
+ if name is None:
275
+ return None
276
+ res = stacks.check(repo, name, head)
277
+ if res["declared"] and res["matches"]:
278
+ steps.say(f"verify: on stack {name} (supported until {res['supported_until']})")
279
+ for w in res["warnings"]:
280
+ print(f"lean-pkg: warning: {w}", file=sys.stderr)
281
+ return res
282
+
283
+
284
+ def stack_digests(res: dict | None, repo: pathlib.Path, comparator: pathlib.Path) -> None:
285
+ """The comparator receipt's toolchain digests against the stack's (a warning when they differ)."""
286
+ from . import stacks
287
+ if not res or not res["declared"] or not comparator.is_file():
288
+ return
289
+ try:
290
+ comp = json.loads(comparator.read_text())
291
+ except (OSError, ValueError):
292
+ return
293
+ rel = comparator.relative_to(repo).as_posix()
294
+ res["comparator_tools"] = stacks.comparator_check(stacks.declared()[res["name"]], comp, rel)
295
+ if res["comparator_tools"]["differ"]:
296
+ w = (f"the comparator receipt {rel} records tool digests that differ from stack {res['name']}'s "
297
+ f"({', '.join(res['comparator_tools']['differ'])}); the stack's digests are those of Linux x86_64")
298
+ res["warnings"].append(w)
299
+ print(f"lean-pkg: warning: {w}", file=sys.stderr)
300
+
301
+
302
+ def preflight(steps: Steps, name: str, pkg: dict, repo: pathlib.Path, c12: str) -> dict:
303
+ """Step 0 (#325): `claims check --file`'s claims/1 check on the claims file committed at HEAD and, when
304
+ coverage.yaml is committed, the offline `coverage check` (coverage.preflight_at_head). Read-only, run in
305
+ --dry-run too; ok true when nothing refuses. Files only in the working tree are not read: HEAD is judged."""
306
+ from . import coverage as cov
307
+ res = cov.preflight_at_head(name, pkg, repo)
308
+ steps.say(f"verify: 0/3 preflight: claims and coverage files committed at {c12}")
309
+ for line in res["lines"]:
310
+ steps.say(f" {line}")
311
+ hits, warnings = module_import_warnings(name, repo, c12)
312
+ for w in warnings:
313
+ print(f"lean-pkg: warning: {w}", file=sys.stderr)
314
+ steps.done.append({"step": "0/3 preflight", "rc": 0 if res["ok"] else 1,
315
+ "output": {"ok": res["ok"], "claims": res["claims"], "coverage": res["coverage"],
316
+ "module_imports": hits, "warnings": warnings}})
317
+ return res
318
+
319
+
320
+ MODULE_HITS_SHOWN = 10
321
+
322
+
323
+ def module_import_warnings(name: str, repo: pathlib.Path, c12: str) -> tuple[list[dict], list[str]]:
324
+ """Step 0's module-import scan (#392): at HEAD, a module-headed file of the package that imports a
325
+ non-module file of the package fails to build (`cannot import non-module`). port_modules' detection,
326
+ reported as one warning with the next command; never a refusal. Skipped silently ([], []) when HEAD or
327
+ the tree cannot be read."""
328
+ from . import port_modules
329
+ try:
330
+ hits = port_modules.non_module_imports(repo)
331
+ except (core.Fail, OSError, ValueError, UnicodeError):
332
+ return [], []
333
+ if not hits:
334
+ return [], []
335
+ shown = "; ".join(f"{h['file']}:{h['line']} imports {h['module']} ({h['target']})"
336
+ for h in hits[:MODULE_HITS_SHOWN])
337
+ more = f"; and {len(hits) - MODULE_HITS_SHOWN} more" if len(hits) > MODULE_HITS_SHOWN else ""
338
+ files = len({h["file"] for h in hits})
339
+ return hits, [f"{files} module-headed file(s) at {c12} import a non-module file of the package, which "
340
+ f"fails to build (a module cannot import a non-module): {shown}{more}; next: "
341
+ f"lean-pkg palomar port-modules {name} --dry-run"]
342
+
343
+
344
+ def cmd_verify(args) -> int:
345
+ p = plan(args)
346
+ name, repo, head, c12 = args.name, p["repo"], p["head"], p["c12"]
347
+ steps = Steps(args, global_flags(args))
348
+ payload = {"ok": False, "name": name, "commit": head, "checkout": str(repo), "dry_run": bool(args.dry_run),
349
+ "status_before": p["status"], "work_dir": str(p["work"]) if p["work"] else None, "steps": steps.done,
350
+ "receipts": {},
351
+ "next": []}
352
+ payload["stack"] = stack_check(steps, repo, head)
353
+ if p["already"]:
354
+ at = p["already"][:12]
355
+ steps.say(f"{name}: already verified at {at}" + ("" if p["already"] == head else
356
+ f" (HEAD {c12} is an evidence-only descendant)")
357
+ + f": gate receipt {p['pkg']['gate'].get('receipt')}, comparator "
358
+ f"{p['pkg']['gate'].get('comparator')}; nothing to do")
359
+ payload.update(ok=True, already=p["already"], status=p["status"])
360
+ return _finish(args, payload, 0)
361
+ # 0. the preflight: the schema refusals of claims.yaml and coverage.yaml at HEAD, before any receipt work
362
+ pre = preflight(steps, name, p["pkg"], repo, c12)
363
+ if not pre["ok"]:
364
+ bad = pre["claims"] if pre["claims"]["errors"] else pre["coverage"]
365
+ return _finish(args, payload, 1, f"the preflight refused {bad['file']} at {c12}: "
366
+ + "; ".join(bad["errors"][:10])
367
+ + "; fix it in a new commit, then run verify again; nothing run, "
368
+ "nothing written")
369
+ work, unit, script = p["work"], p["unit"], p["script"]
370
+ comp_argv = ["receipt", "comparator", "--repo", str(repo)] + (["--judges", str(args.judges)] if args.judges else [])
371
+ comp_env = {"COMPARATOR_RECEIPT_NO_MATHLIB": "1"} if p["no_mathlib"] else None
372
+ log = work / "verify.log"
373
+ lower_argv = ["receipt", "systemd", "--unit", unit, "--receipt-commit", head, "--log", str(log),
374
+ "--stdout", str(work / "unit.out"), "--stderr", str(work / "unit.err"), "--repo", str(repo),
375
+ "--run", "--", "bash", script, str(log)]
376
+ regate = p["status"] in REGATE_FROM
377
+ if args.dry_run:
378
+ steps.say(f"verify {name}: dry run at {c12}; nothing run, nothing written. The steps:")
379
+ steps.say(" 0/3 preflight: claims/1 and the offline coverage check at HEAD (read-only; its result above)")
380
+ env = "".join(f"{k}={v} " for k, v in (comp_env or {}).items())
381
+ steps.say(f" 1/3 comparator receipt: {env}lean-pkg {shlex.join(comp_argv)}")
382
+ steps.say(f" 2/3 lower-tier receipt: lean-pkg {shlex.join(lower_argv)}")
383
+ if p["status"] == "active":
384
+ steps.say(f" status: lean-pkg update {name} --status gate-pending --reason \"verify: receipts at {c12}\"")
385
+ steps.say(f" 3/3 gate: lean-pkg gate {name} --receipt .lean-receipts/{c12}-systemd-user-{unit}.service-"
386
+ f"<invocation>-<host label>.json --comparator .lean-receipts/{c12}-comparator.json"
387
+ + (" --regate" if regate else ""))
388
+ payload.update(ok=True)
389
+ return _finish(args, payload, 0)
390
+
391
+ # 1. the comparator receipt (first: it refuses any untracked file, and step 2 writes some)
392
+ comparator = p["comparator"]
393
+ if comparator.is_file():
394
+ steps.skip("1/3 comparator receipt", f"{comparator.relative_to(repo)} already binds {c12} (an earlier "
395
+ f"run); the gate checks it")
396
+ else:
397
+ if comp_env:
398
+ steps.say(f"verify: {script} declares `mathlib-rev: none` and lake-manifest.json has no Mathlib: the "
399
+ f"comparator runs with COMPARATOR_RECEIPT_NO_MATHLIB=1")
400
+ rc, _ = steps.run("1/3 comparator receipt", comp_argv, env=comp_env)
401
+ if rc != 0 or not comparator.is_file():
402
+ return _finish(args, payload, rc or 1, f"the comparator receipt failed (exit {rc}); nothing gated")
403
+ payload["receipts"]["comparator"] = comparator.relative_to(repo).as_posix()
404
+ stack_digests(payload["stack"], repo, comparator)
405
+
406
+ # 2. the lower-tier receipt, at the same commit (nothing committed in between)
407
+ lower = lower_receipts(repo, c12, unit)
408
+ if lower:
409
+ steps.skip("2/3 lower-tier receipt", f"{lower[0].relative_to(repo)} already binds {c12} (an earlier "
410
+ f"run); the gate checks it")
411
+ else:
412
+ work.mkdir(parents=True, exist_ok=True)
413
+ rc, _ = steps.run("2/3 lower-tier receipt", lower_argv)
414
+ lower = lower_receipts(repo, c12, unit)
415
+ if rc != 0 or not lower:
416
+ return _finish(args, payload, rc or 1, f"the lower-tier receipt failed (exit {rc}); the comparator "
417
+ f"receipt stays and is reused by the next verify at {c12}")
418
+ payload["receipts"]["lower"] = lower[0].relative_to(repo).as_posix()
419
+
420
+ # 3. the gate (an `active` package first moves to gate-pending, as by hand)
421
+ agent = ["--agent", args.agent] if args.agent else []
422
+ if p["status"] == "active":
423
+ rc, _ = steps.run("status", ["update", name, "--status", "gate-pending", "--reason",
424
+ f"verify: both receipts bind {c12}"] + agent, registry=True, want_json=True)
425
+ if rc != 0:
426
+ return _finish(args, payload, rc, "the status move to gate-pending failed; nothing gated")
427
+ gate_argv = ["gate", name, "--receipt", str(lower[0]), "--comparator", str(comparator)] + agent
428
+ if regate:
429
+ gate_argv.append("--regate")
430
+ if args.reason:
431
+ gate_argv += ["--reason", args.reason]
432
+ rc, out = steps.run("3/3 gate", gate_argv, registry=True, want_json=True)
433
+ if out is not None:
434
+ payload["gate"] = out
435
+ if rc != 0:
436
+ return _finish(args, payload, rc, "the gate refused; the receipts stay and are reused by the next verify "
437
+ f"at {c12}")
438
+ reg = core.load_registry(core.registry_path(args))
439
+ payload["status"] = core.get_pkg(reg, name).get("status")
440
+ payload["ok"] = True
441
+ payload["next"] = [f"git -C {shlex.quote(str(repo))} add .lean-receipts && git -C {shlex.quote(str(repo))} "
442
+ f"commit -m \"evidence: receipts at {c12}\"",
443
+ f"lean-pkg page {name} --write"]
444
+ return _finish(args, payload, 0)
445
+
446
+
447
+ def _finish(args, payload: dict, rc: int, why: str | None = None) -> int:
448
+ if why:
449
+ payload["error"] = why
450
+ if getattr(args, "json_out", False):
451
+ core.print_json(payload)
452
+ return rc
453
+ if rc == 0 and payload.get("receipts", {}).get("lower") and not payload.get("dry_run"):
454
+ print(f"verify {payload['name']}: {payload.get('status')} at {payload['commit'][:12]}: lower-tier "
455
+ f"{payload['receipts']['lower']}, comparator {payload['receipts']['comparator']}")
456
+ print("next:")
457
+ for c in payload["next"]:
458
+ print(f" {c}")
459
+ elif why:
460
+ print(f"verify {payload['name']}: stopped: {why}", file=sys.stderr)
461
+ return rc
462
+
463
+
464
+ def add_parsers(sub, add_json) -> None:
465
+ s = sub.add_parser("verify", help="both receipts and the gate in one step on this machine: the comparator "
466
+ "receipt, the lower-tier receipt (systemd user unit) at the same commit, then "
467
+ "the gate; prints each command it runs",
468
+ description="Run, at the checkout's HEAD, `receipt comparator`, `receipt systemd --run -- bash "
469
+ "verify.sh` and `gate` (an active package first moves to gate-pending; a gated "
470
+ "one is re-gated), each as its own lean-pkg invocation with its own checks. "
471
+ "First (step 0, read-only, also under --dry-run) the claims/1 check on the "
472
+ "claims file committed at HEAD and, when coverage.yaml is committed, the "
473
+ "offline `coverage check`: a refusal stops verify before any receipt; "
474
+ "a module-headed file importing a non-module file of the package at HEAD "
475
+ "is a warning naming `palomar port-modules NAME --dry-run`. "
476
+ "Writes only what those commands write; commits nothing in the checkout. A "
477
+ "package whose committed coverage.yaml declares an LTS stack (`stack: NAME`, "
478
+ "docs/stacks/) is checked against it (lean-toolchain, the Mathlib commit, the "
479
+ "comparator receipt's tool digests): a warning per difference, never a refusal.")
480
+ s.add_argument("name")
481
+ s.add_argument("--work-dir", default=None, metavar="DIR",
482
+ help=f"where the run's log and unit output go, outside the checkout (default "
483
+ f"${STATE_ENV}/lean-pkg/verify/NAME/<commit>-<UTC stamp>, else ~/.local/state/...)")
484
+ s.add_argument("--unit", default=None, metavar="UNIT", help="the systemd user unit (default NAME-verify)")
485
+ s.add_argument("--script", default="verify.sh", metavar="FILE",
486
+ help="the committed lower-tier check, run as `bash FILE LOG` (default verify.sh)")
487
+ s.add_argument("--judges", type=int, default=None, metavar="N",
488
+ help="comparator judge processes (`receipt comparator --judges N`)")
489
+ s.add_argument("--agent", default=None, help="the agent acting: passed to the status move and the gate")
490
+ s.add_argument("--reason", default=None, metavar="TEXT",
491
+ help="re-gate only: accept a commit that does not descend from the gated one (`gate --regate "
492
+ "--reason`)")
493
+ s.add_argument("--dry-run", action="store_true", help="print the steps and their commands; run nothing")
494
+ add_json(s)
495
+ s.set_defaults(fn=cmd_verify)
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.4
2
+ Name: lean-pkg
3
+ Version: 0.25.0
4
+ Summary: Lifecycle registry and trust gate for Lean 4 formalization packages: leases, receipt-bound gates, comparator (Palomar) evidence, one-way promotion.
5
+ Author: Le Chen
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/lean-pkg/lean-pkg
8
+ Project-URL: Documentation, https://lean-pkg.github.io/lean-pkg/
9
+ Project-URL: Source, https://github.com/lean-pkg/lean-pkg
10
+ Project-URL: Changelog, https://github.com/lean-pkg/lean-pkg/blob/main/CHANGELOG.md
11
+ Project-URL: Issues, https://github.com/lean-pkg/lean-pkg/issues
12
+ Project-URL: DOI, https://doi.org/10.5281/zenodo.23272098
13
+ Keywords: lean,lean4,formal verification,theorem proving,mathlib,reproducibility
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Environment :: Console
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Operating System :: POSIX :: Linux
24
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
25
+ Classifier: Topic :: Software Development :: Quality Assurance
26
+ Requires-Python: >=3.11
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ Requires-Dist: pyyaml>=6
30
+ Provides-Extra: test
31
+ Requires-Dist: pytest>=7; extra == "test"
32
+ Requires-Dist: pytest-xdist>=3; extra == "test"
33
+ Requires-Dist: pytest-timeout>=2; extra == "test"
34
+ Requires-Dist: jsonschema>=4; extra == "test"
35
+ Requires-Dist: setuptools>=77; extra == "test"
36
+ Dynamic: license-file
37
+
38
+ # lean-pkg
39
+
40
+ *Lean checks the proofs. You check the statements. lean-pkg checks the receipts.*
41
+
42
+ A registry and trust gate for Lean 4 formalization packages: know which packages exist, who holds each
43
+ one, and what evidence binds it to a verified commit, before anything becomes public.
44
+
45
+ A Lean project that builds with zero `sorry` is not yet a verified theorem. The statement may have
46
+ drifted from the paper's claim, the check ran in the same kernel that elaborated the proof, and "CI was
47
+ green" is a status word nobody can re-derive. lean-pkg requires two receipts before a package goes
48
+ public: a build-and-axioms receipt bound to one commit, and a comparator receipt in which trusted
49
+ statements are checked against the proofs and replayed in an independent kernel. At publication it
50
+ re-derives both from bytes.
51
+
52
+ ## Install
53
+
54
+ ```bash
55
+ pipx install lean-pkg # or: uv tool install lean-pkg, or pip install lean-pkg
56
+ lean-pkg doctor # what this machine has, and what it needs
57
+ ```
58
+
59
+ Python 3.11 or newer on Linux. Lean itself comes from
60
+ [elan](https://github.com/leanprover/elan), as for any Lean project.
61
+
62
+ ## From a new package to a verified page
63
+
64
+ ```bash
65
+ lean-pkg new my-proof --kind library # scaffold a package (Mathlib by default), then lake build it
66
+ lean-pkg registry init # a private registry of your own (~/.lean-pkg/registry)
67
+ lean-pkg register my-proof --url https://github.com/you/my-proof --path src/my-proof --license-spdx Apache-2.0
68
+ lean-pkg verify my-proof # both receipts and the gate, in one step
69
+ lean-pkg page my-proof --write # the verification page in README.md
70
+ lean-pkg publish my-proof --dry-run # the checklist before the repository goes public
71
+ ```
72
+
73
+ The [Quickstart](https://lean-pkg.github.io/lean-pkg/quickstart.html) walks through each step and its
74
+ output.
75
+
76
+ ## Learn more
77
+
78
+ - [Documentation](https://lean-pkg.github.io/lean-pkg/), starting with the
79
+ [Quickstart](https://lean-pkg.github.io/lean-pkg/quickstart.html) and the
80
+ [π-λ tutorial](https://lean-pkg.github.io/lean-pkg/tutorial-pi-lambda.html), Dynkin's π-λ theorem end to
81
+ end for a mathematician who has barely used Lean.
82
+ - [Video series](https://www.youtube.com/playlist?list=PLG2OKUkl58LM): eight short episodes, from why a
83
+ green build is not a verified theorem to a paper with a Lean companion.
84
+ - [Receipts and trust](https://lean-pkg.github.io/lean-pkg/receipts.html): what each receipt binds and
85
+ what it lets you believe.
86
+ - For coding agents: `lean-pkg llms` prints the agent contract
87
+ ([llms.txt](https://github.com/lean-pkg/lean-pkg/blob/main/llms.txt)).
88
+ - [Source](https://github.com/lean-pkg/lean-pkg),
89
+ [changelog](https://github.com/lean-pkg/lean-pkg/blob/main/CHANGELOG.md),
90
+ [issues](https://github.com/lean-pkg/lean-pkg/issues).
91
+
92
+ Cite a release by its Zenodo DOI (concept DOI
93
+ [10.5281/zenodo.23272098](https://doi.org/10.5281/zenodo.23272098)). Apache-2.0.