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/headline.py ADDED
@@ -0,0 +1,211 @@
1
+ # headline -- the headline comparator configuration: the paper's main results, a subset of what the
2
+ # gate-bound comparator receipt compared. Feeds formalization.yaml status.main_results.
3
+ """Why this exists.
4
+
5
+ A companion can compare far more than the paper's main results (one field package compares 83
6
+ theorems; 12 of them are the paper's main results). Palomar reads ``status.main_results`` from
7
+ formalization.yaml, which by default lists every theorem of every tracked comparator configuration.
8
+ A *headline configuration* names the main results: when it is declared and judged, ``main_results``
9
+ lists its theorems only, while the receipt and the gate still bind the full comparison.
10
+
11
+ Which file (first match wins):
12
+
13
+ 1. ``lean-pkg formalization NAME --headline-config PATH`` for that call (``--write`` records it);
14
+ 2. the registry field ``headline_config`` (``lean-pkg update NAME --headline-config PATH``; ``''``
15
+ clears it);
16
+ 3. the convention: ``comparator.headline.json`` tracked at the package root at HEAD.
17
+
18
+ The file holds only Palomar's six configuration keys (challenge_module, solution_module,
19
+ theorem_names, definition_names, permitted_axioms, enable_nanoda); anything else is refused. It is a
20
+ repository-relative ``.json`` tracked at HEAD. It need not be a comparator configuration path: at
21
+ ``comparator*.json`` / ``comparator/config*.json`` the runner compares it like any other (and the
22
+ receipt must list it); elsewhere it is not compared on its own and needs no receipt entry.
23
+
24
+ The subset rule (judged against the comparator receipt the gate records, validated at HEAD exactly as
25
+ ``gate --check`` validates it): every headline theorem name must be covered, by
26
+ ``comparator_config.covers`` (the same full name, or ``<Prefix>.<name>``), by the theorem_names of a
27
+ receipted configuration with the same challenge_module and solution_module (a different module pair
28
+ compares a different statement). A headline configuration that is itself receipted covers itself.
29
+ Refused otherwise, naming every uncovered name.
30
+
31
+ Definition holes: every headline definition_names entry must carry a sign-off in the sign-off sidecar
32
+ (lean-pkg-signoff.json at the receipt's commit) of a receipted configuration with the same module pair
33
+ that lists it as a hole, the headline's own entry first when it is itself receipted (the receipt
34
+ validator already requires that entry). A main configuration's sign-off covers the same definition in
35
+ the same modules; nothing else does. Refused otherwise, naming every unsigned hole.
36
+
37
+ When no comparator receipt is recorded, or the recorded one does not validate at HEAD (not gated
38
+ yet, or a new commit awaiting a re-gate), the headline cannot be judged: it is not applied, a warning
39
+ says why, and ``main_results`` keeps the default (every tracked configuration). It is never applied
40
+ unjudged.
41
+ """
42
+ from __future__ import annotations
43
+
44
+ import json
45
+ import pathlib
46
+
47
+ from . import gate as gate_mod
48
+ from . import core
49
+ from .holes import CONFIG_RE, SIDECAR, check_definition_holes, summary as signoff_summary
50
+
51
+ CONVENTION = "comparator.headline.json"
52
+ PALOMAR_KEYS = ("challenge_module", "definition_names", "enable_nanoda", "permitted_axioms",
53
+ "solution_module", "theorem_names")
54
+ REGISTRY_FIELD = "headline_config"
55
+
56
+
57
+ def path_error(rel) -> str | None:
58
+ """Why `rel` cannot name a headline configuration, or None."""
59
+ if not isinstance(rel, str) or not rel.strip():
60
+ return "a headline configuration path must be a non-empty string"
61
+ pp = pathlib.PurePosixPath(rel)
62
+ if pp.is_absolute() or ".." in pp.parts or rel.startswith("~") or "\\" in rel:
63
+ return f"headline configuration {rel!r} must be repository-relative (no leading /, ~ or ..)"
64
+ if not rel.endswith(".json"):
65
+ return f"headline configuration {rel!r} must be a .json file"
66
+ if pp.name == SIDECAR:
67
+ return f"headline configuration {rel!r} is the sign-off sidecar, not a configuration"
68
+ return None
69
+
70
+
71
+ def declared(pkg: dict, repo: pathlib.Path, override: str | None = None,
72
+ rev: str = "HEAD") -> tuple[str | None, str | None]:
73
+ """(path, source): source 'flag' | 'registry' | 'convention'; (None, None) when none is declared."""
74
+ for rel, source in ((override, "flag"), ((pkg or {}).get(REGISTRY_FIELD), "registry")):
75
+ if rel:
76
+ err = path_error(rel)
77
+ if err:
78
+ raise core.Fail(f"{err} ({'--headline-config' if source == 'flag' else REGISTRY_FIELD})")
79
+ return rel, source
80
+ if core.git_show_bytes(repo, CONVENTION, rev) is not None:
81
+ return CONVENTION, "convention"
82
+ return None, None
83
+
84
+
85
+ def _strict(pairs):
86
+ out = {}
87
+ for k, v in pairs:
88
+ if k in out:
89
+ raise ValueError(f"duplicate key {k!r}")
90
+ out[k] = v
91
+ return out
92
+
93
+
94
+ def parse(raw: bytes | None, rel: str) -> dict:
95
+ """The headline configuration, strictly: a JSON object of Palomar's six keys only, theorem_names a
96
+ non-empty list of names, both modules named. Raises ValueError naming the first problem."""
97
+ if raw is None:
98
+ raise ValueError(f"headline configuration {rel} is not tracked")
99
+ try:
100
+ cfg = json.loads(raw.decode("utf-8"), object_pairs_hook=_strict)
101
+ except (UnicodeDecodeError, ValueError) as e:
102
+ raise ValueError(f"headline configuration {rel}: not valid strict JSON ({e})") from e
103
+ if not isinstance(cfg, dict):
104
+ raise ValueError(f"headline configuration {rel}: not a JSON object")
105
+ extra = sorted(set(cfg) - set(PALOMAR_KEYS))
106
+ if extra:
107
+ raise ValueError(f"headline configuration {rel}: key(s) outside Palomar's six: {', '.join(extra)} "
108
+ f"(allowed: {', '.join(PALOMAR_KEYS)}; lean-pkg's own metadata lives in {SIDECAR})")
109
+ for k in ("challenge_module", "solution_module"):
110
+ if not isinstance(cfg.get(k), str) or not cfg[k].strip():
111
+ raise ValueError(f"headline configuration {rel}: {k} must be a non-empty module name")
112
+ names = cfg.get("theorem_names")
113
+ if not isinstance(names, list) or not names or not all(isinstance(n, str) and n.strip() for n in names):
114
+ raise ValueError(f"headline configuration {rel}: theorem_names must be a non-empty list of names")
115
+ holes = cfg.get("definition_names")
116
+ if holes is not None and (not isinstance(holes, list) or not all(isinstance(h, str) and h for h in holes)):
117
+ raise ValueError(f"headline configuration {rel}: definition_names must be a list of names")
118
+ return cfg
119
+
120
+
121
+ def load(repo: pathlib.Path, rel: str, rev: str = "HEAD") -> dict:
122
+ try:
123
+ return parse(core.git_show_bytes(repo, rel, rev), rel)
124
+ except ValueError as e:
125
+ raise core.Fail(f"{e} at {rev}" if "is not tracked" in str(e) else str(e)) from None
126
+
127
+
128
+ def judge(pkg: dict, repo: pathlib.Path, rel: str, cfg: dict) -> dict:
129
+ """The subset and sign-off rules against the gate-bound comparator receipt.
130
+
131
+ {judged, reason, receipt, receipt_commit, uncovered[], covered_by{name: [config paths]},
132
+ unsigned[], judged_as}; judged False (with a reason) when no recorded comparator receipt validates
133
+ at HEAD."""
134
+ out = {"judged": False, "reason": None, "receipt": None, "receipt_commit": None, "uncovered": [],
135
+ "covered_by": {}, "unsigned": [], "judged_as": None}
136
+ gate = (pkg or {}).get("gate") or {}
137
+ comp_rel = gate.get("comparator")
138
+ if not comp_rel:
139
+ out["reason"] = "no comparator receipt is recorded (lean-pkg comparator NAME --receipt R)"
140
+ return out
141
+ out["receipt"] = comp_rel
142
+ comp = gate_mod.recorded_json(repo, comp_rel)
143
+ if not isinstance(comp, dict):
144
+ out["reason"] = f"the recorded comparator receipt {comp_rel} is missing or not JSON"
145
+ return out
146
+ lower = gate_mod.recorded_json(repo, gate.get("receipt")) if gate.get("receipt") else None
147
+ try:
148
+ gate_mod.validate_comparator(pkg, repo, comp, str((lower or {}).get("commit") or "") or None)
149
+ except core.Fail as e:
150
+ out["reason"] = f"the recorded comparator receipt {comp_rel} does not validate at HEAD ({e})"
151
+ return out
152
+ commit = str(comp["commit"])
153
+ from .comparator_config import covers, smoke_configs
154
+ try: # a smoke check covers no headline name (lean-pkg-signoff.json)
155
+ smoke = smoke_configs(repo, commit, "HEAD")
156
+ except core.Fail as e:
157
+ out["reason"] = f"{SIDECAR} cannot be read ({e})"
158
+ return out
159
+ out.update(judged=True, receipt_commit=commit)
160
+ same = [c for c in comp["configs"] if c.get("challenge_module") == cfg["challenge_module"]
161
+ and c.get("solution_module") == cfg["solution_module"] and c.get("path") not in smoke]
162
+ same.sort(key=lambda c: (c.get("path") != rel, str(c.get("path")))) # the headline's own entry first
163
+ for name in cfg["theorem_names"]:
164
+ by = [str(c["path"]) for c in same if covers(set(c.get("theorem_names") or []), name, True)]
165
+ if by:
166
+ out["covered_by"][name] = by
167
+ else:
168
+ out["uncovered"].append(name)
169
+ holes = list(cfg.get("definition_names") or [])
170
+ if holes:
171
+ try:
172
+ sidecar = gate_mod.sidecar_at(repo, commit)
173
+ except ValueError as e:
174
+ raise core.Fail(str(e)) from None
175
+ signed: dict = {}
176
+ for c in same:
177
+ path = str(c["path"])
178
+ blob = core.git_show_bytes(repo, path, commit)
179
+ try:
180
+ bc = json.loads(blob or b"")
181
+ so = check_definition_holes(bc, f"comparator config {path}", cfg_rel=path, cfg_bytes=blob,
182
+ sidecar=sidecar)
183
+ except ValueError:
184
+ continue # the receipt validated, so this does not happen; never borrow it
185
+ for h, s in ((so or {}).get("definitions") or {}).items():
186
+ signed.setdefault(h, s)
187
+ out["unsigned"] = [h for h in holes if h not in signed]
188
+ if not out["unsigned"]:
189
+ out["judged_as"] = signoff_summary({"definitions": {h: signed[h] for h in holes}})
190
+ return out
191
+
192
+
193
+ def refusal(rel: str, res: dict) -> str | None:
194
+ """The refusal text for a judged headline that breaks a rule, or None."""
195
+ parts = []
196
+ if res["uncovered"]:
197
+ parts.append(f"{len(res['uncovered'])} theorem name(s) no receipted configuration with the same "
198
+ f"challenge_module and solution_module covers: {', '.join(res['uncovered'])}")
199
+ if res["unsigned"]:
200
+ parts.append(f"{len(res['unsigned'])} definition hole(s) without a sign-off in {SIDECAR} by a "
201
+ f"receipted configuration with the same modules: {', '.join(res['unsigned'])}")
202
+ if not parts:
203
+ return None
204
+ return (f"headline configuration {rel} is not a subset of the comparison the gate binds (comparator "
205
+ f"receipt {res['receipt']} at {str(res['receipt_commit'])[:12]}): " + "; ".join(parts)
206
+ + ". Compare them (add them to a compared configuration, run comparator-receipt, re-gate) or "
207
+ "drop them from the headline configuration")
208
+
209
+
210
+ def is_config_path(rel: str) -> bool:
211
+ return bool(CONFIG_RE.match(rel))
@@ -0,0 +1,442 @@
1
+ # lean-pkg help topics -- `lean-pkg help exit-codes|environment|formatting`
2
+ """Help topics in the manner of `gh help <topic>`: reference text that belongs to no one command.
3
+
4
+ Pure data and rendering: nothing here reads the registry, the environment or the network. The
5
+ environment table is checked against the source by tests/test_help_topics.py, which fails when a
6
+ variable is read anywhere under src/lean_pkg or scripts/ but is not listed in ENVIRONMENT.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import textwrap
12
+
13
+ WIDTH = 100
14
+
15
+ # --------------------------------------------------------------------------
16
+ # environment
17
+
18
+ # (section, [(VARIABLE, meaning, default)]). Every variable lean-pkg, comparator-receipt, lean-exercise, the
19
+ # scripts they run and the repository's maintainer scripts read. A flag always wins over its variable.
20
+ ENVIRONMENT: list[tuple[str, list[tuple[str, str, str]]]] = [
21
+ ("LEAN-PKG: REGISTRY, EVENT LOG, COMMITTED MODE", [
22
+ ("LEAN_PKG_REGISTRY",
23
+ "the registry file, or a directory holding lean-packages.yaml; --registry wins",
24
+ "~/.lean-pkg/registry when it exists, else ./lean-packages.yaml"),
25
+ ("LEAN_PKG_HOME",
26
+ "base directory of the user-level default registry (<base>/registry)",
27
+ "~/.lean-pkg"),
28
+ ("LEAN_PKG_EVENTS",
29
+ "the event log; --events wins, and so does lean-package-events.jsonl beside an explicit --registry",
30
+ "lean-package-events.jsonl beside the registry in use"),
31
+ ("LEAN_PKG_REGISTRY_SNAPSHOT",
32
+ "run read-only against the registry as of this commit, like --registry-snapshot (the flag wins); "
33
+ "every write exits 2",
34
+ "unset (the working-tree registry)"),
35
+ ("LEAN_PKG_COMMIT",
36
+ "1/true/yes/on: committed mode for every write (pull --ff-only, write, commit the registry and "
37
+ "event log together); --no-commit overrides it",
38
+ "off"),
39
+ ("LEAN_PKG_PUSH",
40
+ "1/true/yes/on: committed mode and a push to origin after each write; --no-commit overrides it",
41
+ "off"),
42
+ ("LEAN_PKG_PUSH_RETRIES",
43
+ "retries of a push that failed with a transient transport error (reset, timeout, HTTP 5xx)",
44
+ "4"),
45
+ ("LEAN_PKG_PUSH_RETRY_DELAY",
46
+ "seconds before the first push retry, doubled for each later one",
47
+ "5"),
48
+ ("LEAN_PKG_DEBUG",
49
+ "1/true/yes/on: print the Python traceback of an internal error on stderr",
50
+ "off (a one-line `internal error: ...`)"),
51
+ ("LEAN_PKG_NO_ALIAS_NOTE",
52
+ "1/true/yes/on: no `note: 'lean-pkg OLD' is now 'lean-pkg NEW'` line on stderr when an old spelling "
53
+ "is used (old spellings are permanent aliases; --json never prints the note)",
54
+ "off (one note per old spelling used, text mode only)"),
55
+ ("LEAN_PKG_NOTIFY_CMD",
56
+ "command run (split shell-style, no shell) with a notification on stdin when `publish --yes` "
57
+ "makes a package public",
58
+ "unset (no notification)"),
59
+ ]),
60
+ ("LEAN-PKG: INDEX, AUDIT, SEARCH", [
61
+ ("LEAN_PKG_INDEX",
62
+ "root of the public index catalog (index commands); --index wins",
63
+ "index/ beside the registry when present, else ./index"),
64
+ ("LEAN_PKG_TOOLCHAIN_FLOOR",
65
+ "the lowest Lean toolchain `audit` and `next` accept; --toolchain-floor wins",
66
+ "leanprover/lean4:v4.35.0-rc2"),
67
+ ("LEAN_PKG_GZIP_LIMIT",
68
+ "decoded bytes of one gzip file or blob that `public-safety` (and promote, publish, release "
69
+ "--fresh-repo) decodes and scans; K, M, G suffixes; 0 turns decoding off; --gzip-limit wins",
70
+ "512M"),
71
+ ("LEAN_PKG_RESERVOIR_INDEX",
72
+ "an unpacked Reservoir index directory, used offline by `search` and `reservoir check`",
73
+ "the index tarball fetched with gh into the cache"),
74
+ ("XDG_CACHE_HOME",
75
+ "base of the cache directory <base>/lean-pkg (Palomar snapshots, Reservoir index); "
76
+ "--cache-dir wins",
77
+ "~/.cache"),
78
+ ("TERM",
79
+ "`board` opens the curses TUI only on a terminal whose TERM is not `dumb`",
80
+ "the terminal's"),
81
+ ("USER",
82
+ "a user name `receipt` refuses or warns about when it appears in a receipt (with LOGNAME and "
83
+ "the login name)",
84
+ "the login's"),
85
+ ("LOGNAME",
86
+ "as USER",
87
+ "the login's"),
88
+ ]),
89
+ ("COMPARATOR-RECEIPT", [
90
+ ("COMPARATOR_RECEIPT_ALLOWED_HOSTS",
91
+ "comma-separated host names or labels allowed to run outside Slurm (host policy, recorded in "
92
+ "host_policy by the label); set at all, even empty, it replaces the workstation default",
93
+ "unset: the workstation default"),
94
+ ("COMPARATOR_RECEIPT_WORKSTATION_DEFAULT",
95
+ "0: no workstation default (the host policy then allows only a Slurm job, a listed host or "
96
+ "COMPARATOR_RECEIPT_ALLOW_HOST=1); otherwise, with no allow-list set, a machine without Slurm runs the "
97
+ "comparator as the machine running the command, named by its label",
98
+ "on"),
99
+ ("SLURM_CONF",
100
+ "set: this machine is a Slurm node, so the comparator's workstation default does not apply (as with "
101
+ "sbatch, srun or slurmd on PATH, or a slurm.conf)",
102
+ "unset"),
103
+ ("COMPARATOR_RECEIPT_ALLOW_HOST",
104
+ "1: allow this host whatever its name (an override, visible in the receipt's host_policy)",
105
+ "unset"),
106
+ ("SLURM_JOB_ID",
107
+ "inside a Slurm job: the host policy allows the run and the receipt's job_id is this value",
108
+ "job_id local-<host>-<pid>-<time>"),
109
+ ("COMPARATOR_RECEIPT_HOST_LABEL",
110
+ "label that names the host in the receipt and in the runner's output (the host name never does)",
111
+ "h- + 12 hex of the SHA-256 of the lower-cased host name"),
112
+ ("COMPARATOR_CHECK",
113
+ "comparator-check.sh to run; --check wins",
114
+ "the copy shipped inside the lean_pkg package"),
115
+ ("COMPARATOR_VERIFY",
116
+ "verify-comparator.sh for the toolchain mechanism; --verify wins",
117
+ "the copy shipped inside the lean_pkg package"),
118
+ ("COMPARATOR_LAKE",
119
+ "the lake the setup stages run",
120
+ "lake from elan's bin/, else from PATH"),
121
+ ("COMPARATOR_BWRAP",
122
+ "lean-exercise: the real bwrap its --project wrapper and its --forbid export sandbox run",
123
+ "bwrap on PATH"),
124
+ ("ELAN_HOME",
125
+ "elan's directory: toolchains and bin/ (comparator-receipt, lean-exercise, the types driver)",
126
+ "~/.elan"),
127
+ ("COMPARATOR_RECEIPT_STACK",
128
+ "unlimited or a size in kB: the soft stack limit of the lake/lean children",
129
+ "the inherited limit"),
130
+ ("COMPARATOR_RECEIPT_LEAN_THREADS",
131
+ "a positive integer: LEAN_NUM_THREADS for the lake/lean children",
132
+ "unset (Lean's own default)"),
133
+ ("COMPARATOR_RECEIPT_BUILD_SOURCE",
134
+ "free text naming where the package's oleans were built; recorded in build_provenance",
135
+ "unset"),
136
+ ("COMPARATOR_RECEIPT_NO_MATHLIB",
137
+ "1: the project knowingly has no Mathlib (the toolchain mechanism refuses such a project "
138
+ "otherwise, and with it `lake exe cache get` is skipped)",
139
+ "unset"),
140
+ ("LEAN_PKG_COMPARATOR_JOBS",
141
+ "judge processes run at once; --judges wins",
142
+ "1"),
143
+ ("LEAN_PKG_COMPARATOR_UNIT_SIZE",
144
+ "theorem names per judge unit; --unit-size wins",
145
+ "the whole configuration, cut into --judges shards"),
146
+ ("COMPARATOR_HEARTBEAT_SECONDS",
147
+ "seconds between heartbeat lines while a judge is silent",
148
+ "60"),
149
+ ("COMPARATOR_FAKE_LAKE_OK",
150
+ "tests only: 1/0 replaces the toolchain probe; a receipt written with it carries test_only: true",
151
+ "unset"),
152
+ ("VERIFY_COMPARATOR_SKIP_CACHE_GET",
153
+ "verify-comparator.sh: 1 skips `lake exe cache get` (the runner sets it for a project without "
154
+ "Mathlib)",
155
+ "unset"),
156
+ ]),
157
+ ("COMPARATOR-CHECK.SH (THE SCRIPT COMPARATOR-RECEIPT RUNS)", [
158
+ ("COMPARATOR_COMMIT",
159
+ "commit of leanprover/comparator to build",
160
+ "the pinned commit in the script"),
161
+ ("NANODA_COMMIT",
162
+ "commit of the nanoda kernel checker to build",
163
+ "the pinned commit in the script"),
164
+ ("LANDRUN_COMMIT",
165
+ "commit of landrun to build",
166
+ "the pinned commit in the script"),
167
+ ("LEAN4EXPORT_COMMIT",
168
+ "commit of lean4export to build",
169
+ "the release tag named after the project's Lean version"),
170
+ ("LEAN4EXPORT_ALLOW_TOOLCHAIN_MISMATCH",
171
+ "1, with LEAN4EXPORT_COMMIT: build that source under the project's toolchain (point-release gap)",
172
+ "0"),
173
+ ("TOOLS_DIR",
174
+ "where the checker tools are cloned and built",
175
+ "~/.cache/lean-ci-tools"),
176
+ ("LOG_DIR",
177
+ "where the comparator logs go (comparator-receipt sets it to its stage-log directory)",
178
+ "./.lake/comparator-logs"),
179
+ ]),
180
+ ("COMPARATOR TYPES DRIVER (WRITTEN BY `comparator config --challenge-from-type` / `--emit-script`)", [
181
+ ("LEAN_PKG_TYPES_JOBS",
182
+ "Lean processes the driver runs at once",
183
+ "the driver's configured jobs, else min(2, the CPUs this process may use)"),
184
+ ("LEAN_PKG_TYPES_TIMEOUT",
185
+ "seconds per declaration",
186
+ "the driver's configured timeout"),
187
+ ("LEAN_PKG_TYPES_BACKOFF_SECONDS",
188
+ "pause before a retry with fewer workers after `too many open files`",
189
+ "5"),
190
+ ("LEAN_PKG_TYPES_RESUME",
191
+ "0: ignore OUT.json.checkpoint.jsonl and run every declaration again",
192
+ "1 (resume from a matching checkpoint)"),
193
+ ]),
194
+ ("SHARED", [
195
+ ("HOME",
196
+ "the home directory: `~` in paths, the user-level registry, and the prefix redacted to <home>/~ "
197
+ "in stage logs, receipts and reports",
198
+ "the login's"),
199
+ ("PATH",
200
+ "where git, gh, lake, elan, jq and bwrap are found; comparator-receipt puts elan's bin/ first "
201
+ "for its children",
202
+ "the caller's"),
203
+ ("TMPDIR",
204
+ "temporary files; the prefix redacted to <tmp> in stage logs; lean-exercise's work directory",
205
+ "/tmp"),
206
+ ("XDG_STATE_HOME",
207
+ "lean-exercise's work directory when TMPDIR is unset; `verify`'s work directory (log and unit output) "
208
+ "is $XDG_STATE_HOME/lean-pkg/verify/NAME/...",
209
+ "the system temporary directory; for verify ~/.local/state"),
210
+ ("GIT_DIR",
211
+ "repository-selecting Git variables (also GIT_WORK_TREE, GIT_INDEX_FILE, GIT_OBJECT_DIRECTORY, "
212
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES, GIT_COMMON_DIR, GIT_NAMESPACE): removed from every git call on "
213
+ "a package checkout; comparator-receipt's host check warns when one is set",
214
+ "unset"),
215
+ ("GIT_WORK_TREE", "as GIT_DIR", "unset"),
216
+ ("GIT_INDEX_FILE", "as GIT_DIR", "unset"),
217
+ ("GIT_OBJECT_DIRECTORY", "as GIT_DIR", "unset"),
218
+ ("GIT_ALTERNATE_OBJECT_DIRECTORIES", "as GIT_DIR", "unset"),
219
+ ("GIT_COMMON_DIR", "as GIT_DIR", "unset"),
220
+ ("GIT_NAMESPACE", "as GIT_DIR", "unset"),
221
+ ]),
222
+ ("MAINTAINER SCRIPTS (scripts/ IN A CHECKOUT; NOT INSTALLED)", [
223
+ ("LEAN_PKG_RELEASE_RETRIES",
224
+ "release.sh, cut-release.py, record-doi.py: attempts per network step",
225
+ "4"),
226
+ ("LEAN_PKG_RELEASE_RETRY_DELAY",
227
+ "seconds before the first retry of a release step, doubled for each later one",
228
+ "10"),
229
+ ("LEAN_PKG_COMMIT_TRAILER",
230
+ "cut-release.py, record-doi.py: `Key: value` trailers, one per line, for the commits they make",
231
+ "none"),
232
+ ("LEAN_PKG_RELEASE_DATE",
233
+ "cut-release.py: the YYYY-MM-DD date to stamp in CHANGELOG.md and CITATION.cff (tests only)",
234
+ "today's local date"),
235
+ ("LEAN_PKG_ZENODO_API",
236
+ "record-doi.py: the Zenodo API base",
237
+ "https://zenodo.org/api"),
238
+ ("LEAN_PKG_ZENODO_RECORDS_FILE",
239
+ "record-doi.py: read the Zenodo search pages from JSON files instead (tests)",
240
+ "unset"),
241
+ ("LEAN_PKG_SRC",
242
+ "bootstrap-collaborator.sh: checkout directory, under $HOME",
243
+ "~/src"),
244
+ ("LEAN_PKG_REGISTRY_DIR",
245
+ "bootstrap-collaborator.sh: registry clone directory",
246
+ "~/.lean-pkg/registry"),
247
+ ("LEAN_PKG_GIT_BASE",
248
+ "bootstrap-collaborator.sh: clone URL base",
249
+ "https://github.com"),
250
+ ("PIPX_BIN_DIR",
251
+ "bootstrap-collaborator.sh: where pipx puts lean-pkg, added to PATH",
252
+ "~/.local/bin"),
253
+ ("PRIVATE_BOUNDARY_EXTRA",
254
+ "private-boundary-check.sh: a file of extra patterns to refuse",
255
+ "unset"),
256
+ ]),
257
+ ]
258
+
259
+
260
+ def environment_names() -> list[str]:
261
+ return [name for _, rows in ENVIRONMENT for name, _, _ in rows]
262
+
263
+
264
+ def environment_rows() -> list[dict]:
265
+ """The table as data, for `help environment --json`."""
266
+ return [{"name": name, "section": section, "meaning": meaning, "default": default}
267
+ for section, rows in ENVIRONMENT for name, meaning, default in rows]
268
+
269
+
270
+ def _render_environment() -> str:
271
+ out = [
272
+ "lean-pkg, comparator-receipt and lean-exercise read these environment variables. A command-line",
273
+ "flag always wins over its variable. A boolean variable is on for 1, true, yes or on (any case).",
274
+ "",
275
+ ]
276
+ for section, rows in ENVIRONMENT:
277
+ out.append(section)
278
+ for name, meaning, default in rows:
279
+ body = f"{meaning}. Default: {default}."
280
+ out.append(textwrap.fill(body, WIDTH, initial_indent=f" {name}: ",
281
+ subsequent_indent=" ", break_on_hyphens=False))
282
+ out.append("")
283
+ out.append("Variables read by the programs lean-pkg runs (git, gh, lake, elan, jq) work as those programs")
284
+ out.append("document; for example gh's GH_TOKEN reaches every `gh` call (promote, audit, report, search, ...).")
285
+ return "\n".join(out) + "\n"
286
+
287
+
288
+ # --------------------------------------------------------------------------
289
+ # exit codes
290
+
291
+ EXIT_CODES = """\
292
+ lean-pkg uses three exit codes. They are never renumbered.
293
+
294
+ - 0: success. Dry runs, read-only checks that pass, and no-ops ("already gated", "already recorded")
295
+ also exit 0.
296
+
297
+ - 1: refusal or failure. The reason is one `lean-pkg: ...` line on stderr; with --json, stdout also gets
298
+ {"ok": false, "error": "..."}. Nothing was written unless the message says so. An unexpected internal
299
+ error also exits 1 (`lean-pkg: internal error: ...`; LEAN_PKG_DEBUG=1 adds the traceback).
300
+
301
+ - 2: usage error. An unknown flag, a bad value, a missing argument, an interactive prompt attempted off a
302
+ terminal, or a write under --registry-snapshot. With --json, stdout also gets
303
+ {"ok": false, "error": "...", "usage": true}, argparse's own errors included.
304
+
305
+ Some read-only commands use 1 for a negative answer rather than a refusal:
306
+
307
+ next NAME 1: the package is blocked (`blockers[]` names why)
308
+ doctor 1: the registry is unreadable or its schema version is unsupported
309
+ validate 1: schema, enum or history errors
310
+ gate NAME --check 1: `gate` would refuse this receipt
311
+ comparator host-check 1: this host cannot run the comparator
312
+ publish NAME --dry-run 1: not ready to publish
313
+ public-safety NAME 1: a blocking hit (--strict: any hit)
314
+ reservoir check NAME 1: not eligible for Reservoir
315
+ claims check [NAME] 1: invalid claims, or none synced
316
+ formalization kept --against 1: a kept (hand-written) key changed
317
+ claims ledger NAME 1: the ledger is not ready
318
+ index check / render --check 1: an entry fails its checks / README.md is stale
319
+ search TERM --require-complete 1: a source was skipped or answered in part
320
+ receipt slurm --check 1: a problem with the job's files
321
+ receipt slurm --preflight-deps 1: the staged dependency cache misses a module the entries import
322
+ --fill-plan 1: the donor fill plan is refused (refusals[].code names the check)
323
+ report --yes 1: a blocking public-safety hit left, or gh missing or logged out
324
+
325
+ The other programs:
326
+
327
+ comparator-receipt 0 receipt written (or --prepare / --estimate done); 1 a configuration failed or
328
+ the host policy refuses; 2 usage; 128+N when a signal N stopped the comparator
329
+ stage part-way (a partial receipt may remain: diagnostic only, never evidence)
330
+ lean-exercise check 0 every theorem accepted; 1 a theorem rejected (or the judge failed); 2 usage or
331
+ host refusal
332
+ lean-exercise batch 0 every Solution passed; 1 a Solution failed or was refused; 2 usage or host
333
+ refusal
334
+ types driver 0 every declaration filled; 1 an extraction error; 2 none filled
335
+
336
+ A process killed by a signal N ends with the shell's 128+N (130 for Ctrl-C).
337
+
338
+ Examples:
339
+
340
+ # Gate only when the dry check passes
341
+ $ lean-pkg gate my-lean --receipt r.json --check && lean-pkg gate my-lean --receipt r.json
342
+
343
+ # Tell "blocked" from "lean-pkg failed" in a script
344
+ $ lean-pkg next my-lean --json > next.json; rc=$?
345
+ $ [ "$rc" -eq 2 ] && echo "usage error" || jq -r '.command // .reason' next.json
346
+ """
347
+
348
+
349
+ # --------------------------------------------------------------------------
350
+ # formatting
351
+
352
+ FORMATTING = """\
353
+ By default lean-pkg prints line-based text for people. Every command takes --json, before or after the
354
+ command name (`lean-pkg --json status x` and `lean-pkg status x --json` are the same), and then prints
355
+ one JSON object on stdout: two-space indent, keys sorted. --json never changes the exit code.
356
+
357
+ STDOUT AND STDERR
358
+
359
+ - stdout carries the result: the table, the record, or the JSON payload. With --json, stdout is always
360
+ valid JSON, also on failure: {"ok": false, "error": "..."} (and "usage": true for a usage error).
361
+ - stderr carries everything else: refusals (`lean-pkg: ...`), warnings (`WARN ...`), lease notices,
362
+ committed-mode reports (`committed <sha> on <branch>`, `pushed ...`), `NOT COMMITTED: ...` and progress.
363
+ Read stderr for why; read stdout for what.
364
+
365
+ ESCAPING
366
+
367
+ - Every string is escaped: a control character (U+0000 to U+001F) is always written as \\n, \\t, \\r or
368
+ \\u00XX, also when it came from registry text (notes, history), so a strict parser such as Python's
369
+ json.loads or jq reads every payload.
370
+ - Read the payload from a pipe or a file (`lean-pkg status x --json | jq .`, `> out.json`). To print a
371
+ captured copy, use printf '%s\\n' "$out", never echo: zsh's echo (and bash's echo -e) turns \\n back into
372
+ a raw newline and \\u2014 into a dash, and the result is no longer valid JSON ("Invalid control
373
+ character").
374
+
375
+ THE JSON PAYLOAD
376
+
377
+ - Most payloads carry "ok" (true or false). A payload's own fields are described with its command
378
+ (`lean-pkg COMMAND --help`, `lean-pkg llms`, docs/cli.md).
379
+ - A write in committed mode adds "registry_commit": {sha, pushed, error, push_error, push_attempts,
380
+ rebased} (also as "commit" when the payload has no "commit" of its own).
381
+ - A write outside committed mode that leaves the registry files modified adds "registry_uncommitted".
382
+ - A run under --registry-snapshot adds "registry_snapshot": "<full sha>".
383
+
384
+ NAMED SCHEMAS
385
+
386
+ Payloads and files with a versioned "schema" field:
387
+
388
+ comparator-receipt/2 the receipt comparator-receipt writes (/1 still validates)
389
+ comparator-estimate/2 comparator-receipt --estimate --json
390
+ comparator-types/1 the output file of the comparator types driver
391
+ claims/1 claims.yaml at a package repository's root
392
+ claims-ledger/1 lean-pkg claims ledger NAME --json
393
+ index-entry/2 index/<name>/entry.yaml (/1 still validates)
394
+ exercise-check/1 lean-exercise check --json
395
+ exercise-batch/1 lean-exercise batch --json
396
+
397
+ The lower-tier receipt `gate` reads is described under RECEIPT SCHEMA in `lean-pkg llms`.
398
+
399
+ CHOOSING FIELDS
400
+
401
+ `board`, `list` and `status` take --fields a,b,c to keep only those keys (dotted paths such as
402
+ gate.receipt and lease.agent work; an unknown field exits 2 listing the valid keys). `list --only NAME`
403
+ keeps only that package. The other commands print their whole payload.
404
+
405
+ FILTERING WITH JQ
406
+
407
+ lean-pkg has no --jq flag; pipe --json into jq:
408
+
409
+ # Names of the packages waiting for the gate
410
+ $ lean-pkg list --json | jq -r '.packages | to_entries[] | select(.value.status == "gate-pending") | .key'
411
+
412
+ # One field of one package
413
+ $ lean-pkg status my-lean --json --fields gate.receipt | jq -r '.package.gate.receipt'
414
+
415
+ # The recommended next command, else the blockers
416
+ $ lean-pkg next my-lean --json | jq -r '.command // (.blockers[] | "\\(.kind): \\(.detail)")'
417
+
418
+ # Branch on the payload's ok: refused (exit 1) or usage error (exit 2) both print ok: false
419
+ $ lean-pkg gate my-lean --receipt r.json --json | jq -e '.ok' >/dev/null || echo refused
420
+ """
421
+
422
+
423
+ # --------------------------------------------------------------------------
424
+
425
+ def _command_tree_text(name: str) -> str:
426
+ from . import command_tree
427
+ return command_tree.newcomer_text() if name == "start" else command_tree.aliases_text()
428
+
429
+
430
+ TOPICS: dict[str, tuple[str, object]] = {
431
+ "start": ("New here: the five verbs and the two product tracks",
432
+ lambda: _command_tree_text("start")),
433
+ "aliases": ("Old command and flag spellings: permanent aliases", lambda: _command_tree_text("aliases")),
434
+ "environment": ("Environment variables lean-pkg, comparator-receipt and lean-exercise read",
435
+ _render_environment),
436
+ "exit-codes": ("Exit codes, and what 1 means for the commands that answer yes or no", lambda: EXIT_CODES),
437
+ "formatting": ("--json output, stdout and stderr, named schemas, filtering with jq", lambda: FORMATTING),
438
+ }
439
+
440
+
441
+ def topic_text(name: str) -> str:
442
+ return TOPICS[name][1]()