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/scaffold.py ADDED
@@ -0,0 +1,588 @@
1
+ # lean-pkg new -- scaffold a minimal Lean package that the check, verify and page path accepts unchanged
2
+ """`lean-pkg new NAME [--kind paper|library] [--stack NAME|current|none] [--dir DIR] [--module MOD] [--no-mathlib]
3
+ [--author TEXT] [--license Apache-2.0|MIT] [--json]`.
4
+
5
+ Writes a new directory (refused when it exists and is not empty) holding the project of
6
+ docs/getting-started.md, "Start from scratch" (the same files, byte for byte, for NAME my-proof), plus the
7
+ files the rest of the newcomer path reads, then runs `git init` there. Nothing is committed (lake update
8
+ writes lake-manifest.json first), nothing is fetched or built, and no registry is read or written.
9
+
10
+ lean-toolchain the stack's toolchain, else the newest pins (TOOLCHAIN): the newest Lean release
11
+ of RELEASES, a stable one unless a release candidate is newer
12
+ .gitignore /.lake
13
+ lakefile.toml one library MOD (globs MOD and MOD.+), its defaultTargets (a bare `lake build`
14
+ builds it); requires Mathlib (the stack's tag, else MATHLIB_REV) unless --no-mathlib
15
+ MOD.lean the library's root module, empty: import the library's modules from it
16
+ MOD/Challenge.lean the trusted statement, proof `sorry` (module-headed, as Palomar requires)
17
+ MOD/Solution.lean the same theorem, proved
18
+ MOD/Axioms.lean `#print axioms` of the theorem: what the lower-tier receipt reads
19
+ comparator.json the Palomar comparator configuration of that theorem
20
+ claims.yaml claims/1: the theorem as one reusable claim
21
+ coverage.yaml coverage/1 of --kind (below)
22
+ CITATION.cff title NAME, one author (--author, else git config user.name; a name without a
23
+ space is warned about: it looks like a handle)
24
+ LICENSE --license (default Apache-2.0, the official text; MIT with the year and author)
25
+ LICENSES/<SPDX>.txt the same text, where REUSE looks for it
26
+ REUSE.toml every file, present and future (receipts, logs), under that license and the
27
+ author's copyright: `reuse lint` (publish --dry-run) passes on the scaffold
28
+ README.md a title and the lean-pkg credit line `page --check` requires
29
+ verify.sh the lower-tier check, in the log shape `lean-pkg receipt systemd --run` reads
30
+
31
+ --kind paper (the default, as in the 1.0 command tree): the paper is the product. Its coverage.yaml is
32
+ incomplete on purpose: the manuscript block carries `version: unposted` and FILL-ME markers that
33
+ `coverage check` (and so `page`) refuses until the author names the paper and its results; `formalization
34
+ anchor NAME --arxiv <id>v<N> ... --write` then sets the posted version. No manuscript is invented.
35
+ --kind library: the Lean package is the product; coverage.yaml is kind library with one main result
36
+ naming the example claim, and passes `coverage check` as written.
37
+
38
+ --stack (proposal 0004, docs/stacks/): NAME pins a declared LTS stack, `current` the newest declared stack
39
+ whose window covers today, `none` the newest pins with no key; with a stack, coverage.yaml carries `stack: NAME`,
40
+ which doctor NAME, verify and page check against the committed pins. Default: `current` for --kind paper (the
41
+ newest pins, with a warning, when no stack is current), `none` for --kind library (libraries aimed at Mathlib
42
+ follow its newest release). The comparator tools of a stack are the ones its toolchain bundles (mechanism
43
+ toolchain), so the lean-toolchain pin is their pin; the scaffold records no other tool version.
44
+
45
+ --no-mathlib is the same project in core Lean (`Nat` for `ℕ`, no `public import Mathlib`): no Mathlib
46
+ download, but `comparator-receipt` then needs COMPARATOR_RECEIPT_NO_MATHLIB=1, and Palomar expects
47
+ statements in Mathlib's vocabulary."""
48
+
49
+ from __future__ import annotations
50
+
51
+ import argparse
52
+ import datetime as dt
53
+ import json
54
+ import pathlib
55
+ import re
56
+ import shutil
57
+ import subprocess
58
+
59
+ from . import claim_axioms
60
+ from . import hypotheses
61
+ from . import core
62
+ from . import page as page_mod
63
+
64
+ # The newest pins (no --stack): the Lean releases lean-pkg knows, as (Lean tag, the Mathlib tag of that
65
+ # release, or None while Mathlib has not tagged it). `new` reads no network: a lean-pkg release adds rows.
66
+ # The newest by Lean's version order wins (newest_pins), so a stable release beats its own release
67
+ # candidates and every older one; a release candidate is pinned only when no stable release is newer (#327).
68
+ RELEASES = (
69
+ ("v4.35.0-rc2", "v4.35.0-rc2"),
70
+ ("v4.35.0", "v4.35.0"),
71
+ )
72
+ RELEASE_RE = re.compile(r"^v(\d+)\.(\d+)\.(\d+)(?:-rc(\d+))?$")
73
+ THEOREM = "two_mul_le"
74
+ NAME_RE = re.compile(r"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$")
75
+ MODULE_RE = re.compile(r"^[A-Z][A-Za-z0-9]*$")
76
+ NAME_MAX = 64
77
+ RESERVED_MODULES = {"Init", "Std", "Lean", "Lake", "Mathlib", "Batteries", "Aesop", "Qq", "Plausible"}
78
+ LICENSES = ("Apache-2.0", "MIT")
79
+ KINDS = ("paper", "library")
80
+ MIT = """\
81
+ MIT License
82
+
83
+ Copyright (c) {year} {author}
84
+
85
+ Permission is hereby granted, free of charge, to any person obtaining a copy
86
+ of this software and associated documentation files (the "Software"), to deal
87
+ in the Software without restriction, including without limitation the rights
88
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
89
+ copies of the Software, and to permit persons to whom the Software is
90
+ furnished to do so, subject to the following conditions:
91
+
92
+ The above copyright notice and this permission notice shall be included in all
93
+ copies or substantial portions of the Software.
94
+
95
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
96
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
97
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
98
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
99
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
100
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
101
+ SOFTWARE.
102
+ """
103
+
104
+ LAKEFILE = """\
105
+ name = "{name}"
106
+ defaultTargets = ["{module}"]
107
+ {require}
108
+ [[lean_lib]]
109
+ name = "{module}"
110
+ globs = ["{module}", "{module}.+"]
111
+ """
112
+ ROOT_FILE = """\
113
+ module
114
+
115
+ -- The root module of the library {module} (the lakefile.toml glob "{module}" includes it). Import the library's
116
+ -- modules from here (`public import {module}.Basic`), and this module from Solution.lean (`public import
117
+ -- {module}`); never Challenge or Solution, which declare the same theorem.
118
+ """
119
+ REQUIRE_MATHLIB = """
120
+ [[require]]
121
+ name = "mathlib"
122
+ scope = "leanprover-community"
123
+ rev = "{rev}"
124
+ """
125
+ LEAN_FILE = """\
126
+ module
127
+ {imports}
128
+ public section
129
+
130
+ theorem {module}.{theorem} (n : {nat}) : n ≤ 2 * n := by
131
+ {proof}
132
+
133
+ end
134
+ """
135
+ AXIOMS_FILE = """\
136
+ module
137
+
138
+ import {module}.Solution
139
+
140
+ -- The lower-tier receipt reads this output (verify.sh builds this module).
141
+ #print axioms {module}.{theorem}
142
+ """
143
+ COMPARATOR = """\
144
+ {{
145
+ "challenge_module": "{module}.Challenge",
146
+ "solution_module": "{module}.Solution",
147
+ "theorem_names": ["{module}.{theorem}"],
148
+ "definition_names": [],
149
+ "permitted_axioms": ["propext", "Quot.sound", "Classical.choice"],
150
+ "enable_nanoda": true
151
+ }}
152
+ """
153
+ CLAIMS = """\
154
+ schema: claims/1
155
+ package: {name}
156
+ claims:
157
+ - id: {name}/{slug}
158
+ decl: {module}.{theorem}
159
+ kind: theorem
160
+ summary: Every natural number n satisfies n <= 2 * n (the example theorem of lean-pkg new).
161
+ keywords: [example]
162
+ file: {module}/Solution.lean
163
+ status: reusable
164
+ """
165
+ COVERAGE = """\
166
+ schema: coverage/1
167
+ package: {name}
168
+ kind: library
169
+ {stack}summary: "The example theorem n <= 2 * n is formalized and compared against its trusted statement."
170
+ rows:
171
+ - title: "n <= 2 * n for every natural number n"
172
+ claims: [{name}/{slug}]
173
+ """
174
+ # kind paper: honestly incomplete. No manuscript is invented: `unposted` and the FILL-ME markers say the
175
+ # author has not named it yet, and coverage check refuses every marker (a placeholder never reaches a page).
176
+ COVERAGE_PAPER = """\
177
+ schema: coverage/1
178
+ package: {name}
179
+ kind: paper
180
+ {stack}# Incomplete until you name the paper (written by `lean-pkg new`; `lean-pkg coverage check {name}` lists
181
+ # what is missing). Replace each FILL-ME. Once the paper is posted, bind this file to that version:
182
+ # lean-pkg formalization anchor {name} --arxiv <id>v<N> --from-file E-PRINT --compare-tex PAPER.tex --write
183
+ # sets manuscript.version (and eprint_sha256). Until then version stays unposted: a private draft, which
184
+ # `coverage check` and `page` accept only with --allow-private-manuscript, and mark.
185
+ manuscript:
186
+ title: "FILL-ME: the paper's title"
187
+ version: unposted
188
+ summary: "FILL-ME: one sentence on which results of the paper are formalized."
189
+ rows:
190
+ # one row per numbered result of the paper; the example theorem stands in for the first one
191
+ - paper: {{number: "FILL-ME: its number, e.g. Theorem 1.2", title: "FILL-ME: its title"}}
192
+ class: same-assumptions
193
+ claims: [{name}/{slug}]
194
+ # what is not formalized (or drop this row and state nothing_excluded: {{reason: ...}})
195
+ - paper: {{number: "FILL-ME: a result left out", title: "FILL-ME: its title"}}
196
+ class: outside
197
+ """
198
+ CITATION = """\
199
+ cff-version: 1.2.0
200
+ message: "If you use this software, please cite it as below."
201
+ title: {title}
202
+ authors:
203
+ - name: {author}
204
+ """
205
+ README = """\
206
+ # {name}
207
+
208
+ A Lean 4 package, scaffolded with `lean-pkg new`. Replace the example theorem in
209
+ `{module}/Challenge.lean` (the trusted statement) and `{module}/Solution.lean` (its
210
+ proof), and keep `comparator.json`, `claims.yaml` and `coverage.yaml` in step.
211
+ {paper}
212
+ {credit}
213
+ """
214
+ README_PAPER = """
215
+ This package formalizes results of a paper. `coverage.yaml` does not name the paper yet: write its
216
+ title and one row per numbered result in place of the FILL-ME markers (`lean-pkg coverage check {name}`
217
+ lists what is missing), and once the paper is posted bind the file to that version with
218
+ `lean-pkg formalization anchor {name} --arxiv <id>v<N> --from-file E-PRINT --compare-tex PAPER.tex --write`.
219
+ The verification page is rendered only after that.
220
+ """
221
+ REUSE_TOML = """\
222
+ # REUSE (https://reuse.software): every file of this package, including the receipts and logs added later,
223
+ # is under {spdx} with this copyright; `reuse lint` reads it (written by `{tool}`).
224
+ version = 1
225
+ SPDX-PackageName = {name}
226
+
227
+ [[annotations]]
228
+ path = ["**"]
229
+ precedence = "aggregate"
230
+ SPDX-FileCopyrightText = {copyright}
231
+ SPDX-License-Identifier = "{spdx}"
232
+ """
233
+ VERIFY = """\
234
+ #!/bin/bash
235
+ # verify.sh LOG: the lower-tier check of this package (written by `lean-pkg new`). Run it through
236
+ # `lean-pkg receipt systemd --run` from a clean checkout at the commit to certify; see docs/quickstart.md:
237
+ #
238
+ # lean-pkg receipt systemd --unit {name}-verify --commit "$(git rev-parse HEAD)" --log ../{name}-verify/verify.log \\
239
+ # --stdout ../{name}-verify/unit.out --stderr ../{name}-verify/unit.err --run -- bash verify.sh ../{name}-verify/verify.log
240
+ #
241
+ # What the receipt reads; keep these lines as they are:
242
+ # stdout: exactly one line each of pre-manifest-sha256, post-manifest-sha256, verify-log-sha256
243
+ # stderr: empty (every tool writes into the log)
244
+ # the log: checker:, commit:, lean-toolchain:, the build between lean-pkg-build: begin / end (a fresh
245
+ # build: Lake must compile the package's modules, not restore them), sorry-count:, axioms:, and
246
+ # the claim-axioms lines of every claim in claims.yaml, read from the built environment, and
247
+ # the hyp-probe/1 section after them (the Challenge, when built for it, goes to a side log
248
+ # beside LOG, hyp-challenge-build.log, never into LOG)
249
+ set -euo pipefail
250
+ export LC_ALL=C LANG=C
251
+ unset LANGUAGE
252
+ LOG=${{1:?usage: bash verify.sh LOG}}
253
+ # The modules the receipt certifies: the proof and the axioms report (the Challenge's sorry is by design and
254
+ # is judged by comparator-receipt, not here).
255
+ MODULES="{module}.Solution {module}.Axioms"
256
+ {claim_axioms_sh}{hypotheses_sh}echo "pre-manifest-sha256 $(sha256sum lake-manifest.json | cut -d' ' -f1)"
257
+ rm -rf .lake/build
258
+ {{
259
+ echo "commit: $(git rev-parse HEAD)"
260
+ echo "lean-toolchain: $(cat lean-toolchain)"
261
+ {mathlib_line} echo "checker: verify.sh (lake build $MODULES; #print axioms)"
262
+ echo "lean-pkg-build: begin"
263
+ }} >"$LOG"
264
+ lake build $MODULES >>"$LOG" 2>&1
265
+ echo "lean-pkg-build: end" >>"$LOG"
266
+ ca_dir=$(mktemp -d)
267
+ claim_axioms_run "$LOG" "$ca_dir" "$(lake env printenv LEAN_PATH)"
268
+ hypotheses_run "$LOG" "$ca_dir/hyp-probe" "$(lake env printenv LEAN_PATH)" "$(dirname "$LOG")/hyp-challenge-build.log"
269
+ rm -rf "$ca_dir"
270
+ sorry=$(grep -c -E "declaration uses ['\\`]sorry['\\`]" "$LOG" || true)
271
+ axioms=$(tr '\\n' ' ' <"$LOG" | grep -o 'depends on axioms: \\[[^]]*\\]' | sed -e 's/^[^[]*\\[//' -e 's/\\]$//' \\
272
+ | tr ',' '\\n' | tr -d ' ' | grep -v '^$' | sort -u | paste -sd, - || true)
273
+ {{
274
+ echo "sorry-count: $sorry"
275
+ if [ -n "$axioms" ]; then
276
+ echo "axioms: $axioms"
277
+ elif grep -q 'does not depend on any axioms' "$LOG"; then
278
+ echo "axioms: none"
279
+ fi
280
+ echo "generated-at: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
281
+ }} >>"$LOG"
282
+ # The seal: nothing may write to the log after this line.
283
+ echo "post-manifest-sha256 $(sha256sum lake-manifest.json | cut -d' ' -f1)"
284
+ echo "verify-log-sha256 $(sha256sum "$LOG" | cut -d' ' -f1)"
285
+ """
286
+
287
+
288
+ # A receipt names the Mathlib revision it was built against; a package without Mathlib says so in its log
289
+ # (the manifest has no `mathlib` entry to read it from).
290
+ NO_MATHLIB_LINE = ' echo "mathlib-rev: none"\n'
291
+
292
+
293
+ def module_of(name: str) -> str:
294
+ """`my-proof` -> `MyProof`: the library and namespace a name gives by default."""
295
+ return "".join(part[:1].upper() + part[1:] for part in name.split("-"))
296
+
297
+
298
+ def _yaml_str(s: str) -> str:
299
+ return json.dumps(s, ensure_ascii=False) # a JSON string is a YAML double-quoted scalar
300
+
301
+
302
+ def license_text(spdx: str, author: str, year: int) -> str:
303
+ if spdx == "MIT":
304
+ return MIT.format(year=year, author=author)
305
+ return (pathlib.Path(__file__).parent / "templates" / "Apache-2.0.txt").read_text(encoding="utf-8")
306
+
307
+
308
+ def release_key(tag: str) -> tuple[int, int, int, int, int]:
309
+ """Lean's version order: `v4.35.0-rc2` < `v4.35.0` < `v4.36.0-rc1`."""
310
+ m = RELEASE_RE.match(tag)
311
+ if not m:
312
+ raise ValueError(f"not a Lean release tag: {tag!r}")
313
+ major, minor, patch, rc = m.groups()
314
+ return int(major), int(minor), int(patch), 0 if rc else 1, int(rc or 0)
315
+
316
+
317
+ def is_release_candidate(toolchain: str) -> bool:
318
+ """`leanprover/lean4:v4.35.0-rc2` (or `v4.35.0-rc2`) is a release candidate."""
319
+ return "-rc" in toolchain.rsplit(":", 1)[-1]
320
+
321
+
322
+ def newest_pins(releases=None, mathlib: bool = True) -> tuple[str, str | None]:
323
+ """(lean-toolchain, Mathlib tag) of the newest release; with mathlib, the newest that Mathlib has tagged."""
324
+ usable = [r for r in (RELEASES if releases is None else releases) if r[1] is not None or not mathlib]
325
+ if not usable:
326
+ raise ValueError("no Lean release with a Mathlib tag in the table")
327
+ tag, rev = max(usable, key=lambda r: release_key(r[0]))
328
+ return f"leanprover/lean4:{tag}", rev
329
+
330
+
331
+ TOOLCHAIN, MATHLIB_REV = newest_pins()
332
+
333
+
334
+ def pins(stack: dict | None, mathlib: bool = True) -> tuple[str, str | None]:
335
+ """(lean-toolchain, Mathlib rev) the scaffold writes: the stack's, else the newest pins."""
336
+ if stack is None:
337
+ return newest_pins(mathlib=mathlib)
338
+ return stack["lean_toolchain"], stack["mathlib"]["rev"]
339
+
340
+
341
+ def files(name: str, module: str, author: str, mathlib: bool = True, license_spdx: str = "Apache-2.0",
342
+ year: int = 2026, kind: str = "paper", stack: dict | None = None,
343
+ evidence_only: bool = False) -> dict[str, str]:
344
+ """The scaffold, relative path -> text. With mathlib and no stack, the files docs/getting-started.md
345
+ writes by hand (lean-toolchain, .gitignore, lakefile.toml, MOD.lean, Challenge, Solution, comparator.json) are
346
+ byte-identical to that template for NAME my-proof (tests/test_new.py holds them together). With a stack
347
+ (proposal 0004): its lean-toolchain and Mathlib rev, and `stack: NAME` in coverage.yaml. Unless
348
+ evidence_only, lean-pkg-binding.yaml opts in to the docs-only rule (proposal 0002, stage G3): every
349
+ published page is committed after the verified commit."""
350
+ out = _files(name, module, author, mathlib, license_spdx, year, kind, stack)
351
+ if not evidence_only:
352
+ from . import binding_file
353
+ out[binding_file.FILE] = binding_file.render(True)
354
+ return out
355
+
356
+
357
+ def package_files(name: str, author: str, license_spdx: str = "Apache-2.0", year: int = 2026,
358
+ tool: str = "lean-pkg new") -> dict[str, str]:
359
+ """The package-level files of a scaffold, without the example theorem: .gitignore, CITATION.cff,
360
+ LICENSE, LICENSES/<SPDX>.txt and REUSE.toml (whose comment names `tool`, the command that wrote it).
361
+ `new` writes them as part of `files()`; `lean-pkg-extract decls --scaffold` writes them around the
362
+ extracted modules (proposal 0009, stage S3)."""
363
+ return {
364
+ ".gitignore": "/.lake\n",
365
+ "CITATION.cff": CITATION.format(title=_yaml_str(name), author=_yaml_str(author)),
366
+ "LICENSE": license_text(license_spdx, author, year),
367
+ f"LICENSES/{license_spdx}.txt": license_text(license_spdx, author, year),
368
+ "REUSE.toml": REUSE_TOML.format(name=_yaml_str(name), spdx=license_spdx, tool=tool,
369
+ copyright=_yaml_str(f"{year} {author}")),
370
+ }
371
+
372
+
373
+ def _files(name: str, module: str, author: str, mathlib: bool, license_spdx: str, year: int, kind: str,
374
+ stack: dict | None) -> dict[str, str]:
375
+ toolchain, rev = pins(stack, mathlib)
376
+ stack_line = f"stack: {stack['name']}\n" if stack is not None else ""
377
+ imports = "\npublic import Mathlib\n" if mathlib else ""
378
+ nat = "ℕ" if mathlib else "Nat"
379
+ lean = {kind: LEAN_FILE.format(imports=imports, module=module, theorem=THEOREM, nat=nat, proof=proof)
380
+ for kind, proof in (("Challenge", "sorry"), ("Solution", "omega"))}
381
+ slug = THEOREM.replace("_", "-")
382
+ pkg = package_files(name, author, license_spdx, year)
383
+ # the package files in the order `new` has always written them (the dict order is the write order)
384
+ return {
385
+ "lean-toolchain": toolchain + "\n",
386
+ ".gitignore": pkg[".gitignore"],
387
+ "lakefile.toml": LAKEFILE.format(name=name, module=module,
388
+ require=REQUIRE_MATHLIB.format(rev=rev) if mathlib else ""),
389
+ f"{module}.lean": ROOT_FILE.format(module=module),
390
+ f"{module}/Challenge.lean": lean["Challenge"],
391
+ f"{module}/Solution.lean": lean["Solution"],
392
+ f"{module}/Axioms.lean": AXIOMS_FILE.format(module=module, theorem=THEOREM),
393
+ "comparator.json": COMPARATOR.format(module=module, theorem=THEOREM),
394
+ "claims.yaml": CLAIMS.format(name=name, module=module, theorem=THEOREM, slug=slug),
395
+ "coverage.yaml": (COVERAGE_PAPER if kind == "paper" else COVERAGE).format(name=name, slug=slug,
396
+ stack=stack_line),
397
+ "CITATION.cff": pkg["CITATION.cff"],
398
+ "LICENSE": pkg["LICENSE"],
399
+ f"LICENSES/{license_spdx}.txt": pkg[f"LICENSES/{license_spdx}.txt"],
400
+ "REUSE.toml": pkg["REUSE.toml"],
401
+ "README.md": README.format(name=name, module=module, credit=page_mod.CREDIT,
402
+ paper=README_PAPER.format(name=name) if kind == "paper" else ""),
403
+ "verify.sh": VERIFY.format(name=name, module=module, mathlib_line="" if mathlib else NO_MATHLIB_LINE,
404
+ claim_axioms_sh=claim_axioms.job_sh(),
405
+ hypotheses_sh=hypotheses.job_sh()),
406
+ }
407
+
408
+
409
+ def _git_author() -> str | None:
410
+ if shutil.which("git") is None:
411
+ return None
412
+ p = subprocess.run(["git", "config", "user.name"], capture_output=True, text=True, env=core.scrubbed_env(),
413
+ stdin=subprocess.DEVNULL)
414
+ if p.returncode != 0:
415
+ return None
416
+ return p.stdout.strip() or None
417
+
418
+
419
+ def author_warnings(author: str) -> list[str]:
420
+ """A CITATION.cff author is a person's name: one without a space looks like a login or handle."""
421
+ if " " not in author:
422
+ return [f"CITATION.cff author {author!r} has no space: it looks like a handle, not a name; fix it in "
423
+ f"CITATION.cff and REUSE.toml (and LICENSE for MIT), or rerun with --author 'Given Family'"]
424
+ return []
425
+
426
+
427
+ def next_commands(dir_arg: str, module: str, mathlib: bool) -> list[str]:
428
+ fetch = "lake update && lake exe cache get" if mathlib else "lake update"
429
+ return [f"cd {dir_arg}", fetch, f"lake build {module}.Solution {module}.Axioms",
430
+ 'git add -A && git commit -m "new package"']
431
+
432
+
433
+ def choose_stack(kind: str, stack_arg: str | None) -> tuple[dict | None, str, list[str]]:
434
+ """(stack or None, source, notes) for `new`: --stack NAME|current|none, else the default of the kind
435
+ (proposal 0004, open question 7, decided: a paper takes the current stack, a library the newest pins)."""
436
+ from . import stacks
437
+ notes: list[str] = []
438
+ if stack_arg is not None:
439
+ stack = stacks.resolve(stack_arg)
440
+ if stack is not None and stacks.window(stack) != "in":
441
+ notes.append(f"stack {stack['name']} is outside its window on {stacks.today()} (supported "
442
+ f"{stack['published']} to {stack['supported_until']}); pinned as asked")
443
+ return stack, "flag", notes
444
+ if kind != "paper":
445
+ return None, "default", notes
446
+ stack = stacks.current()
447
+ if stack is None:
448
+ notes.append(f"no declared stack covers {stacks.today()} (declared: {stacks.declared_list()}): "
449
+ f"the paper scaffold takes the newest pins instead; --stack NAME pins one")
450
+ return stack, "default", notes
451
+
452
+
453
+ def do_new(name: str, dir_arg: str | None, module: str | None, mathlib: bool, author: str | None,
454
+ license_spdx: str = "Apache-2.0", kind: str = "paper", stack_arg: str | None = None,
455
+ evidence_only: bool = False) -> tuple[list[str], dict]:
456
+ if not NAME_RE.match(name) or len(name) > NAME_MAX:
457
+ raise core.UsageError(f"package name {name!r}: lower-case letters, digits and single hyphens, starting "
458
+ f"with a letter, at most {NAME_MAX} characters (e.g. my-proof)")
459
+ module = module or module_of(name)
460
+ if not MODULE_RE.match(module):
461
+ raise core.UsageError(f"--module {module!r}: one Lean name component, a capital letter then letters and "
462
+ f"digits (e.g. MyProof)")
463
+ if module in RESERVED_MODULES:
464
+ raise core.UsageError(f"library {module!r} is the root namespace of Lean or a Mathlib dependency; choose "
465
+ f"another NAME or pass --module")
466
+ if kind not in KINDS:
467
+ raise core.UsageError(f"--kind {kind!r}: one of {', '.join(KINDS)}")
468
+ stack, stack_source, stack_notes = choose_stack(kind, stack_arg)
469
+ source = "--author" if author is not None else "git config user.name"
470
+ author = (author if author is not None else _git_author() or "").strip()
471
+ if not author or "\n" in author:
472
+ raise core.UsageError("CITATION.cff needs an author: pass --author 'Given Family' (or set git config "
473
+ "user.name)")
474
+ warnings = author_warnings(author) + stack_notes
475
+ if shutil.which("git") is None:
476
+ raise core.Fail("git is not on PATH; lean-pkg binds every receipt to a git commit")
477
+ dir_arg = dir_arg or name
478
+ target = pathlib.Path(dir_arg)
479
+ if target.is_symlink() or (target.exists() and not target.is_dir()):
480
+ raise core.Fail(f"{dir_arg} exists and is not a directory; nothing written")
481
+ if target.is_dir() and any(target.iterdir()):
482
+ raise core.Fail(f"{dir_arg} exists and is not empty; nothing written (choose a new directory with --dir)")
483
+ scaffold = files(name, module, author, mathlib, license_spdx, dt.date.today().year, kind, stack,
484
+ evidence_only=evidence_only)
485
+ toolchain, rev = pins(stack, mathlib)
486
+ rc_pin = is_release_candidate(toolchain)
487
+ target.mkdir(parents=True, exist_ok=True)
488
+ for rel, text in scaffold.items():
489
+ f = target / rel
490
+ f.parent.mkdir(parents=True, exist_ok=True)
491
+ f.write_text(text, encoding="utf-8")
492
+ (target / "verify.sh").chmod(0o755)
493
+ p = subprocess.run(["git", "-c", "init.defaultBranch=main", "init", "-q", str(target)], capture_output=True,
494
+ text=True, env=core.scrubbed_env(), stdin=subprocess.DEVNULL)
495
+ if p.returncode != 0:
496
+ raise core.Fail(f"git init {dir_arg} failed: {(p.stderr or p.stdout).strip()} (the files are written)")
497
+ nxt = next_commands(dir_arg, module, mathlib)
498
+ dep = f"Mathlib {rev}" if mathlib else "no Mathlib"
499
+ on = f" (stack {stack['name']}, supported until {stack['supported_until']})" if stack else ""
500
+ candidate = ((" (a release candidate: no stable Lean release is newer)" if stack is None
501
+ else " (a release candidate)") if rc_pin else "")
502
+ out = [f"created {dir_arg}/: package {name} (kind {kind}), library {module}, {toolchain.split(':')[1]}"
503
+ f"{candidate}, {dep}{on}; {len(scaffold)} files, git initialized, nothing committed, no registry read "
504
+ f"or written",
505
+ f"author: {author} (from {source}; CITATION.cff, REUSE.toml)",
506
+ "next:"] + [f" {c}" for c in nxt]
507
+ if mathlib:
508
+ out.append("(the first `lake exe cache get` downloads Mathlib's build cache: several GB)")
509
+ else:
510
+ out.append("(comparator-receipt on a project without Mathlib needs COMPARATOR_RECEIPT_NO_MATHLIB=1)")
511
+ if kind == "paper":
512
+ out += ["coverage.yaml (kind paper) is incomplete until you name the paper: replace its FILL-ME markers "
513
+ "(the title, one row per numbered result), then, once the paper is posted and the package "
514
+ "registered:",
515
+ f" lean-pkg formalization anchor {name} --arxiv <id>v<N> --from-file E-PRINT "
516
+ f"--compare-tex PAPER.tex --write",
517
+ "(the receipts and the gate do not need it; the page does. No paper? --kind library)"]
518
+ from . import binding_file
519
+ if evidence_only:
520
+ out.append(f"no {binding_file.FILE} (--evidence-only): only evidence may follow the verified commit, so "
521
+ f"the README page needs a new verify run after it is committed")
522
+ else:
523
+ out.append(f"{binding_file.FILE} opts in to the docs-only rule: a later commit that changes only files "
524
+ f"the build does not read (README.md, coverage.yaml) keeps the receipts bound; commit it with "
525
+ f"the package (--evidence-only leaves it out)")
526
+ out.append("then verify and render the page: docs/quickstart.md "
527
+ "(https://lean-pkg.github.io/lean-pkg/quickstart.html)")
528
+ payload = {"ok": True, "name": name, "dir": str(target), "kind": kind, "module": module, "mathlib": mathlib,
529
+ "lean_toolchain": toolchain, "mathlib_rev": rev if mathlib else None, "release_candidate": rc_pin,
530
+ "stack": stack["name"] if stack else None, "stack_source": stack_source,
531
+ "license_spdx": license_spdx, "author": author, "author_source": source,
532
+ "files": sorted(scaffold), "git_init": True, "committed": False, "registry_touched": False,
533
+ "coverage_complete": kind == "library", "next_commands": nxt, "warnings": warnings,
534
+ "binding_file": None if evidence_only else binding_file.FILE}
535
+ return out, payload
536
+
537
+
538
+ def cmd_new(args) -> int:
539
+ out, payload = do_new(args.name, args.dir, args.module, not args.no_mathlib, args.author, args.license,
540
+ args.kind, args.stack, evidence_only=args.evidence_only)
541
+ for w in payload["warnings"]:
542
+ print(f"lean-pkg: warning: {w}", file=core.sys.stderr)
543
+ if args.json_out:
544
+ core.print_json(payload)
545
+ else:
546
+ print("\n".join(out))
547
+ return 0
548
+
549
+
550
+ def add_parsers(sub, add_json) -> None:
551
+ del add_json # writes no registry: no --commit/--push
552
+ s = sub.add_parser("new", help="scaffold a new Lean package (Challenge/Solution, comparator.json, claims, "
553
+ "coverage, verify.sh) in a new directory and git init it; no registry, "
554
+ "no network",
555
+ description="Write a minimal Lean 4 package that comparator-receipt, `receipt systemd`, "
556
+ "gate and reuse lint accept unchanged (and page, for --kind library; a paper's "
557
+ "coverage.yaml waits for the paper), then `git init` it. Nothing is committed, "
558
+ "fetched or built; no registry is read or written. Next steps: "
559
+ "docs/quickstart.md.")
560
+ s.add_argument("name", help="the package name: lower-case letters, digits, single hyphens (e.g. my-proof)")
561
+ s.add_argument("--kind", default="paper", choices=KINDS,
562
+ help="paper (default): the paper is the product; coverage.yaml stays incomplete until you name "
563
+ "the paper and `formalization anchor` binds its posted version. library: the Lean package "
564
+ "is the product; coverage.yaml lists the example as its main result")
565
+ s.add_argument("--stack", default=None, metavar="NAME|current|none",
566
+ help="pin lean-toolchain and the Mathlib require to a declared LTS stack and write `stack: NAME` "
567
+ "into coverage.yaml (docs/stacks/); current: the newest declared stack whose window covers "
568
+ "today; none: the newest pins, no key. Default: current for --kind paper (the newest pins "
569
+ "when no stack is current), none for --kind library. An undeclared name exits 2")
570
+ s.add_argument("--dir", default=None, metavar="DIR",
571
+ help="where to write it (default ./NAME); refused when it exists and is not empty")
572
+ s.add_argument("--module", default=None, metavar="MOD",
573
+ help="the library and namespace (default: NAME in CamelCase, my-proof -> MyProof)")
574
+ s.add_argument("--no-mathlib", action="store_true",
575
+ help="core Lean only: no Mathlib dependency (fast to build; comparator-receipt then needs "
576
+ "COMPARATOR_RECEIPT_NO_MATHLIB=1)")
577
+ s.add_argument("--author", default=None, metavar="TEXT",
578
+ help="the CITATION.cff author (default: git config user.name)")
579
+ s.add_argument("--license", default="Apache-2.0", choices=LICENSES,
580
+ help="the LICENSE written (default Apache-2.0); pass the same id to `update NAME --license-spdx`")
581
+ s.add_argument("--evidence-only", action="store_true",
582
+ help="leave out lean-pkg-binding.yaml, the docs-only opt-in written by default: then only "
583
+ "evidence may follow the verified commit, and committing the README page needs a new "
584
+ "verify run")
585
+ s.add_argument("--json", dest="json_out", action="store_true", default=argparse.SUPPRESS,
586
+ help="machine-readable JSON on stdout")
587
+ s.set_defaults(fn=cmd_new)
588
+