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/audit.py ADDED
@@ -0,0 +1,716 @@
1
+ # lean-pkg -- registry audit and validate
2
+ """`lean-pkg registry audit` (audit_registry: expired leases, GitHub visibility, paths, drift, the toolchain
3
+ floor; --fix reconciles) and `lean-pkg registry validate` (validate_registry: schema, enums, history sanity,
4
+ also run before every registry write).
5
+
6
+ Moved verbatim out of cli.py (#317, stage 3). cli.py re-exports every name defined here for at least one
7
+ release; lean-pkg's own modules import this module (`from . import audit`). It imports core.py and gate.py;
8
+ the field validators and display helpers that stay in cli.py with the commands they belong to (update,
9
+ record, the publication hold) are imported from cli.py inside the two functions that use them, so importing
10
+ this module never imports cli.py.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import collections
16
+ import datetime as dt
17
+ import json
18
+ import os
19
+ import pathlib
20
+ import re
21
+ import shlex
22
+ import subprocess
23
+ import sys
24
+
25
+ import yaml
26
+
27
+ from .core import (
28
+ current_branch, events_path, Fail, gh, gh_nwo, git, git_head, _HEX40, HOME, lease_expiry, LEASE_FIELDS,
29
+ lease_live, LEASE_PARSE_ERRORS, load_registry, local_path_key, namespace_clashes, parse_ts, print_json,
30
+ record, reference_branch, registry_not_found, registry_path, repo_path, REQUIRED_FIELDS,
31
+ retracted_entries, save_registry, scrubbed_env, STATUSES, SUPPORTED_REGISTRY_VERSIONS, TRACKS,
32
+ UPSTREAM_TARGETS, UsageError, V2_PACKAGE_DEFAULTS, V3_PACKAGE_DEFAULTS, VISIBILITIES,
33
+ )
34
+ from .gate import _same_remote, package_descendant, recorded_json
35
+
36
+
37
+ # --------------------------------------------------------------------------
38
+ # audit
39
+
40
+ TOOLCHAIN_FLOOR_ENV = "LEAN_PKG_TOOLCHAIN_FLOOR"
41
+ DEFAULT_TOOLCHAIN_FLOOR = "leanprover/lean4:v4.35.0-rc2" # Palomar's floor (lake comparator)
42
+ FLOOR_EXEMPT_STATUSES = ("scratch", "archived")
43
+ # The floor is the comparator/promotion requirement: it is a warning only for packages that are
44
+ # public (or past it) or already carry comparator evidence, or under `audit --promotion`; elsewhere info.
45
+ FLOOR_WARN_STATUSES = ("public", "upstreamed")
46
+ # Finding levels (JSON `level`): warn unless the check is informational, or note() says otherwise.
47
+ AUDIT_INFO_CHECKS = ("receipt-untracked", "consent-duplicate", "no-github-mirror", "claims-coverage-none")
48
+ # claims-coverage-none skips these: their claims no longer steer search or promotion work.
49
+ CLAIMS_COVERAGE_EXEMPT_STATUSES = ("archived", "upstreamed")
50
+ _TOOLCHAIN_RE = re.compile(r"^(?:leanprover/lean4:)?v(\d+)\.(\d+)\.(\d+)(?:-rc(\d+))?$")
51
+
52
+
53
+ def parse_lean_toolchain(text) -> tuple[int, int, int, int, int] | None:
54
+ """Sort key for a Lean toolchain string `[leanprover/lean4:]vMAJOR.MINOR.PATCH[-rcN]`,
55
+ or None (unparsed: nightlies, channel names, anything else are never compared).
56
+ An rc sorts before the release of the same version: (M, m, p, 0, N) < (M, m, p, 1, 0)."""
57
+ m = _TOOLCHAIN_RE.match(str(text or "").strip())
58
+ if not m:
59
+ return None
60
+ major, minor, patch, rc = m.groups()
61
+ return (int(major), int(minor), int(patch)) + ((0, int(rc)) if rc is not None else (1, 0))
62
+
63
+
64
+ def resolve_toolchain_floor(flag: str | None) -> str:
65
+ # an explicit flag, even an empty one, is used as given; an empty env variable counts as unset
66
+ floor = flag if flag is not None else (os.environ.get(TOOLCHAIN_FLOOR_ENV, "").strip()
67
+ or DEFAULT_TOOLCHAIN_FLOOR)
68
+ if parse_lean_toolchain(floor) is None:
69
+ raise UsageError(f"toolchain floor {floor!r} is not [leanprover/lean4:]vMAJOR.MINOR.PATCH[-rcN]")
70
+ return floor
71
+
72
+
73
+ AUDIT_LEVELS = ("warn", "info")
74
+ AUDIT_LEVEL_WIDTH = 6 # the level column: "warn " / "info "
75
+
76
+
77
+ def render_finding(f: dict, width: int = 20) -> str:
78
+ """One human audit line: the level (warn|info), the check code padded to width, then
79
+ `NAME: DETAIL`. The level column replaces the old trailing ` [info]` suffix (#33)."""
80
+ level = f.get("level") or "warn"
81
+ return f"{level.ljust(AUDIT_LEVEL_WIDTH)}{(f['check'] + ' ').ljust(width)}{f['name']}: {f['detail']}"
82
+
83
+
84
+ def audit_counts(findings: list[dict]) -> dict[str, int]:
85
+ """Findings per level: {"warn": N, "info": M} (a finding without a level counts as warn)."""
86
+ counts = dict.fromkeys(AUDIT_LEVELS, 0)
87
+ for f in findings:
88
+ lvl = f.get("level") or "warn"
89
+ counts[lvl] = counts.get(lvl, 0) + 1
90
+ return counts
91
+
92
+
93
+ NO_GITHUB_MIRROR_DETAIL = "repo is not on GitHub; visibility not mirrored"
94
+
95
+
96
+ def audit_count_line(findings: list[dict]) -> str:
97
+ c = audit_counts(findings)
98
+ return f"{len(findings)} finding(s): {c['warn']} warn, {c['info']} info"
99
+
100
+
101
+ def render_findings(findings: list[dict]) -> list[str]:
102
+ """Human audit output: no-github-mirror and gh-skipped findings collapse into one summary line
103
+ each; the count line ("N finding(s): W warn, I info") comes first (#44: verdict first, so a truncated
104
+ window still shows it) and again last, where scripts read it."""
105
+ mirror = [f["name"] for f in findings if f["check"] == "no-github-mirror"]
106
+ skipped = [f["name"] for f in findings if f["check"] == "gh-skipped"]
107
+ shown = [f for f in findings if f["check"] not in ("no-github-mirror", "gh-skipped")]
108
+ width = max([0] + [len(f["check"]) + 2 for f in shown]) # check column: longest code + 2
109
+ lines = ([audit_count_line(findings)] if findings else []) + [render_finding(f, width) for f in shown]
110
+ if mirror:
111
+ lines.append(f"{len(mirror)} package(s) without a GitHub mirror (visibility not checked): "
112
+ + ", ".join(mirror))
113
+ if skipped:
114
+ lines.append(f"{len(skipped)} package(s): gh checks skipped (--no-gh): " + ", ".join(skipped))
115
+ if findings:
116
+ lines.append(audit_count_line(findings))
117
+ return lines
118
+
119
+
120
+ def status_visibility_mismatch(pkg: dict) -> str | None:
121
+ """Cross-field rule, audited (warn) rather than validated: verified-private means a private
122
+ repository, public/upstreamed a public one. Registries written before the rule may hold a
123
+ mismatch, so `validate` does not refuse it."""
124
+ status, vis = pkg.get("status"), pkg.get("visibility")
125
+ if status == "verified-private" and vis != "private":
126
+ return f"status verified-private but visibility {vis} (expected private)"
127
+ if status in ("public", "upstreamed") and vis != "public":
128
+ return f"status {status} but visibility {vis} (expected public)"
129
+ return None
130
+
131
+
132
+ def floor_applies(pkg: dict, promotion: bool = False) -> bool:
133
+ """Whether the comparator toolchain floor is a warning for this package: under --promotion, for a
134
+ public/upstreamed package, or for one with comparator evidence recorded (gate.comparator, a palomar
135
+ entry, or a cached claim at comparator/palomar trust). Otherwise being below the floor is info: it
136
+ matters only for promote and comparator receipts."""
137
+ if promotion or pkg.get("status") in FLOOR_WARN_STATUSES:
138
+ return True
139
+ if (pkg.get("gate") or {}).get("comparator") or pkg.get("palomar"):
140
+ return True
141
+ return any(isinstance(c, dict) and c.get("trust") in ("comparator", "palomar")
142
+ for c in pkg.get("claims") or [])
143
+
144
+
145
+ def find_moved_checkout(recorded: pathlib.Path, repo_url: str, limit: int = 500) -> pathlib.Path | None:
146
+ """A cheap search for a moved checkout: the directories one level under the recorded path's parent
147
+ that hold a lakefile (lean or toml) and a git remote whose URL is the package's repo. First match
148
+ by name; None when the parent is gone, nothing matches, or repo_url is empty."""
149
+ parent = recorded.parent
150
+ if not repo_url or not parent.is_dir():
151
+ return None
152
+ try:
153
+ kids = sorted(d for d in parent.iterdir() if d.is_dir() and d != recorded)[:limit]
154
+ except OSError:
155
+ return None
156
+ for d in kids:
157
+ if not ((d / "lakefile.lean").is_file() or (d / "lakefile.toml").is_file()):
158
+ continue
159
+ p = git(d, "config", "--get-regexp", r"^remote\..*\.url$")
160
+ urls = [line.split(None, 1)[1] for line in p.stdout.splitlines() if len(line.split(None, 1)) == 2]
161
+ if any(_same_remote(u, repo_url) for u in urls):
162
+ return d
163
+ return None
164
+
165
+
166
+ def missing_path_detail(name: str, pkg: dict, repo: pathlib.Path | None) -> str:
167
+ """missing-path: the recorded path, the fix command, and a sibling checkout found by find_moved_checkout."""
168
+ recorded = pkg.get("local_path")
169
+ if repo is None:
170
+ return f"no local_path recorded; set one with `lean-pkg update {name} --path DIR --reason TEXT --dry-run`"
171
+ found = find_moved_checkout(repo, str(pkg.get("repo") or ""))
172
+ target = "DIR"
173
+ if found is not None:
174
+ try:
175
+ target = "~/" + str(found.relative_to(HOME))
176
+ except ValueError:
177
+ target = str(found)
178
+ cmd = f"lean-pkg update {name} --path {shlex.quote(target) if target != 'DIR' else target} " \
179
+ f"--reason \"checkout moved\" --dry-run"
180
+ head = f"recorded path {recorded} is not a directory"
181
+ if found is not None:
182
+ head += f"; found at {found} (same lakefile and git remote)"
183
+ return f"{head}; fix: `{cmd}`, then again without --dry-run"
184
+
185
+
186
+ _GH_NO_ACCESS_RE = re.compile(r"Resource not accessible|HTTP 403|SAML|must have (?:push|admin|read)", re.I)
187
+ _GH_NOT_FOUND_RE = re.compile(r"Could not resolve to a Repository|HTTP 404|Not Found", re.I)
188
+ _GH_UNAUTH_RE = re.compile(r"HTTP 401|Bad credentials|gh auth login|not logged in|authentication required", re.I)
189
+
190
+
191
+ def remote_reachable(repo: pathlib.Path | None, nwo: str) -> bool | None:
192
+ """Whether a git remote of the checkout that names nwo (by its configured, un-rewritten URL)
193
+ answers `git ls-remote`: True / False, or None when no remote names it. No prompts, 30 s cap."""
194
+ if repo is None or not repo.is_dir():
195
+ return None
196
+ p = git(repo, "config", "--get-regexp", r"^remote\..*\.url$")
197
+ names = [m.group(1) for line in p.stdout.splitlines()
198
+ if (m := re.match(r"remote\.(.+)\.url\s+(\S+)$", line.strip()))
199
+ and (gh_nwo(m.group(2)) or "").lower() == nwo.lower()]
200
+ if not names:
201
+ return None
202
+ env = scrubbed_env()
203
+ env["GIT_TERMINAL_PROMPT"] = "0"
204
+ env.setdefault("GIT_SSH_COMMAND", "ssh -o BatchMode=yes -o ConnectTimeout=15")
205
+ try:
206
+ q = subprocess.run(["git", "-C", str(repo), "ls-remote", "-q", names[0], "HEAD"], capture_output=True,
207
+ text=True, check=False, env=env, timeout=30)
208
+ except (OSError, subprocess.TimeoutExpired):
209
+ return False
210
+ return q.returncode == 0
211
+
212
+
213
+ def classify_gh_failure(p, nwo: str, repo: pathlib.Path | None, auth_ok) -> tuple[str, str]:
214
+ """(outcome, detail) for a failed `gh repo view`: gh-missing | not-authenticated | no-access |
215
+ not-found | error. auth_ok() is `gh auth status` succeeding (asked only when the text is ambiguous).
216
+ GitHub answers not-found for a private repository the token cannot read, so a not-found whose
217
+ checkout remote still answers ls-remote is no-access."""
218
+ text = (p.stderr or p.stdout or "").strip()
219
+ if p.returncode == 127 and "not on PATH" in text:
220
+ return "gh-missing", "gh is not installed: gh checks skipped (install gh, or pass --no-gh)"
221
+ access = (f"token lacks access to {nwo}: re-run `gh auth login` with a token that can read it "
222
+ "(or pass --no-gh)")
223
+ if _GH_UNAUTH_RE.search(text):
224
+ return "not-authenticated", "gh is not authenticated: run `gh auth login` (or pass --no-gh)"
225
+ if _GH_NO_ACCESS_RE.search(text):
226
+ return "no-access", access
227
+ if _GH_NOT_FOUND_RE.search(text):
228
+ if not auth_ok():
229
+ return "not-authenticated", "gh is not authenticated: run `gh auth login` (or pass --no-gh)"
230
+ reach = remote_reachable(repo, nwo)
231
+ if reach:
232
+ return "no-access", access + "; the checkout's git remote reaches it, so it exists"
233
+ if reach is None:
234
+ return "not-found", (f"repository {nwo} not found on GitHub, or the token lacks access to it "
235
+ "(no checkout remote names it to tell which)")
236
+ return "not-found", f"repository {nwo} not found (gh and the checkout's git remote both fail)"
237
+ return "error", f"gh query failed: {(text.splitlines() or [''])[0]}" # whole first line (#21.7)
238
+
239
+
240
+ def gh_check_code(outcome: str) -> str:
241
+ """The audit check code of a failed gh query: gh-missing | gh-not-authenticated | gh-no-access |
242
+ gh-not-found | gh-error (the `gh` key keeps the bare outcome)."""
243
+ return outcome if outcome.startswith("gh-") else f"gh-{outcome}"
244
+
245
+
246
+ def audit_registry(reg_path, reg, events_p, fix: bool = False,
247
+ toolchain_floor: str | None = None, promotion: bool = False,
248
+ use_gh: bool = True) -> list[dict]:
249
+ """Structured findings: {"check", "name", "detail", "fixed", "level"}; level is warn or info.
250
+ Read-only unless fix: lease sweeps and visibility/archive reconciliation both need it (an
251
+ expired lease is reported with fixed=False otherwise).
252
+ toolchain_floor None: the environment's floor, else the default (the TUI path).
253
+ promotion: the floor is a warning for every package (else see floor_applies).
254
+ use_gh False (--no-gh): no gh query; each GitHub package gets a gh-skipped info finding."""
255
+ from .cli import consent_unique, hold_text # update/record helpers; cli imports audit
256
+ findings: list[dict] = []
257
+ if toolchain_floor is None:
258
+ try:
259
+ toolchain_floor = resolve_toolchain_floor(None)
260
+ except UsageError:
261
+ toolchain_floor = DEFAULT_TOOLCHAIN_FLOOR
262
+ floor_key = parse_lean_toolchain(toolchain_floor)
263
+ now = dt.datetime.now(dt.timezone.utc)
264
+ mutated = False
265
+
266
+ def note(check, name, detail, fixed=False, level=None, **extra):
267
+ if level is None:
268
+ level = "info" if check in AUDIT_INFO_CHECKS else "warn"
269
+ findings.append({"check": check, "name": name,
270
+ "detail": detail, "fixed": fixed, "level": level, **extra})
271
+
272
+ auth_cache: list[bool] = []
273
+
274
+ def auth_ok() -> bool:
275
+ if not auth_cache:
276
+ auth_cache.append(gh("auth", "status", "--hostname", "github.com").returncode == 0)
277
+ return auth_cache[0]
278
+
279
+ # Parse every lease before mutating anything: a lease that cannot be read is a finding, not a
280
+ # traceback halfway through a --fix.
281
+ bad_lease: set[str] = set()
282
+ for name in sorted(reg["packages"]):
283
+ lease = (reg["packages"][name] or {}).get("lease")
284
+ if lease:
285
+ try:
286
+ lease_expiry(lease)
287
+ except LEASE_PARSE_ERRORS as e:
288
+ bad_lease.add(name)
289
+ note("lease-invalid", name,
290
+ f"lease cannot be parsed ({type(e).__name__}: {e}); not swept")
291
+
292
+ by_path: dict[str, list[str]] = collections.defaultdict(list)
293
+ for name in sorted(reg["packages"]):
294
+ lpath = (reg["packages"][name] or {}).get("local_path")
295
+ if lpath:
296
+ by_path[local_path_key(lpath)].append(name)
297
+ for names in by_path.values():
298
+ for name in names if len(names) > 1 else ():
299
+ # no path echo: local paths are private, and findings are printed
300
+ note("duplicate-path", name, "local_path resolves to the same checkout as "
301
+ + ", ".join(n for n in names if n != name) + "; one checkout per package")
302
+
303
+ for name in sorted(reg["packages"]): # informational (#22.7): never fixed
304
+ pkg = reg["packages"][name] or {}
305
+ try:
306
+ repo = repo_path(pkg) if pkg.get("local_path") else None
307
+ except (OSError, ValueError, TypeError):
308
+ repo = None
309
+ if repo is None or not repo.is_dir():
310
+ continue
311
+ for ns, others in namespace_clashes(reg, repo, skip=name).items():
312
+ notes = {n: ((reg["packages"].get(n) or {}).get("namespace_notes") or {}).get(ns)
313
+ for n in [name, *others]}
314
+ base = (f"Lean root namespace {ns} is also used by " + ", ".join(others)
315
+ + "; the two cannot be built or imported together")
316
+ if all(isinstance(v, str) and v.strip() for v in notes.values()):
317
+ note("duplicate-namespace", name, f"{base}; noted as intended: {notes[name]}", level="info")
318
+ else:
319
+ missing = [n for n, v in notes.items() if not (isinstance(v, str) and v.strip())]
320
+ note("duplicate-namespace", name, f"{base}; rename one lean_lib, or record the collision as "
321
+ f"intended on both packages: `lean-pkg update {missing[0]} --namespace-note TEXT "
322
+ f"--namespace {ns}` (no note yet: {', '.join(missing)})")
323
+
324
+ for name in sorted(reg["packages"]): # informational (#23.1): never fixed; the history keeps every record
325
+ pkg = reg["packages"][name] or {}
326
+ allc = [c for c in pkg.get("consent") or [] if isinstance(c, dict)]
327
+ uniq = consent_unique(pkg)
328
+ if len(allc) > len(uniq):
329
+ counts = collections.Counter((str(c.get("who")), str(c.get("role"))) for c in allc)
330
+ dups = [f"{w} ({r}) x{n}" for (w, r), n in counts.items() if n > 1]
331
+ note("consent-duplicate", name, "consent recorded more than once for " + ", ".join(dups)
332
+ + "; displayed once (re-recording the same consent is now a no-op)")
333
+
334
+ # informational: never fixed, info even under --promotion. Coverage other than `synced` (empty,
335
+ # unsynced or none) is what `search` treats as "no synced claims" and falls back to declarations.
336
+ from . import claims as claims_mod
337
+ for name in sorted(reg["packages"]):
338
+ pkg = reg["packages"][name] or {}
339
+ if pkg.get("status") in CLAIMS_COVERAGE_EXEMPT_STATUSES:
340
+ continue
341
+ cov = claims_mod.coverage(name, pkg)["coverage"]
342
+ if cov != "synced":
343
+ note("claims-coverage-none", name, f"claims: {cov} (search falls back to declarations; "
344
+ f"run `lean-pkg claims sync {name}`)", coverage=cov)
345
+
346
+ def untracked(name, repo, tip, rel, label) -> None:
347
+ if tip and git(repo, "cat-file", "-e", f"{tip}:./{rel}").returncode != 0:
348
+ note("receipt-untracked", name, f"{rel} exists in the working tree but is not tracked at "
349
+ f"{label} {tip[:12]}; commit it so the evidence travels with the repository")
350
+
351
+ for name in sorted(reg["packages"]):
352
+ pkg = reg["packages"][name]
353
+ mismatch = status_visibility_mismatch(pkg)
354
+ if mismatch:
355
+ note("status-visibility-mismatch", name, mismatch)
356
+ lease = pkg.get("lease")
357
+ if lease and name not in bad_lease and not lease_live(lease, now):
358
+ who = f"{lease.get('agent')}@{lease.get('workspace')} until {lease_expiry(lease).isoformat()}"
359
+ if fix:
360
+ note("lease-expired", name, f"was {who} — cleared", fixed=True)
361
+ record(reg, events_p, pkg, "lease-expired", agent=lease.get("agent"),
362
+ workspace=lease.get("workspace"),
363
+ claimed_at=lease.get("claimed_at"),
364
+ ttl_hours=lease.get("ttl_hours"))
365
+ pkg["lease"] = None
366
+ pkg["workspace"] = None
367
+ pkg["agent"] = None
368
+ mutated = True
369
+ else:
370
+ note("lease-expired", name, f"held by {who} — expired; `audit --fix` clears it")
371
+ if pkg.get("upstream_target") == "palomar" and pkg.get("status") in ("verified-private", "public") \
372
+ and not any(e.get("preflight_run") for e in (pkg.get("palomar") or []) if isinstance(e, dict)):
373
+ note("palomar-preflight-missing", name,
374
+ "upstream_target=palomar but no palomar-preflight-pass recorded "
375
+ "(lean-pkg record NAME palomar-preflight-pass --field commit=… --field run=…)")
376
+ tc_reg = str(pkg.get("lean_toolchain") or "").strip()
377
+ if tc_reg and floor_key and pkg.get("status") not in FLOOR_EXEMPT_STATUSES:
378
+ key = parse_lean_toolchain(tc_reg)
379
+ warn_floor = floor_applies(pkg, promotion)
380
+ if key is None:
381
+ note("toolchain-unparsed", name,
382
+ f"{tc_reg} is not a release or rc toolchain; not compared with the floor {toolchain_floor}",
383
+ level="warn" if warn_floor else "info")
384
+ elif key < floor_key and warn_floor:
385
+ note("below-toolchain-floor", name, f"{tc_reg} is older than the floor {toolchain_floor}")
386
+ elif key < floor_key:
387
+ note("below-toolchain-floor", name, f"toolchain below the comparator floor {toolchain_floor} "
388
+ f"(matters only for promote/comparator); registry has {tc_reg}", level="info")
389
+ repo = repo_path(pkg) if pkg.get("local_path") else None
390
+ if repo is None or not repo.is_dir():
391
+ note("missing-path", name, missing_path_detail(name, pkg, repo))
392
+ continue
393
+ tc = repo / "lean-toolchain"
394
+ if tc.is_file():
395
+ actual = tc.read_text().strip()
396
+ if actual != str(pkg.get("lean_toolchain") or "").strip():
397
+ note("toolchain-drift", name,
398
+ f"registry={pkg.get('lean_toolchain')} file={actual}")
399
+ else:
400
+ note("toolchain-missing", name, str(tc))
401
+ from . import palomar_check # only packages aiming at Palomar (upstream_target palomar or a palomar entry)
402
+ if (pal := palomar_check.audit_finding(pkg, repo)) is not None:
403
+ note("palomar-not-ready", name, pal.pop("detail"), palomar=pal)
404
+ gate_rec = pkg.get("gate") or {}
405
+ ref_branch = ref_tip = None
406
+ off_ref = ""
407
+ if gate_rec.get("receipt") or gate_rec.get("comparator"):
408
+ ref_branch, ref_tip, ref_note = reference_branch(repo)
409
+ here = current_branch(repo) or "detached HEAD"
410
+ at_tip = here == "detached HEAD" and git_head(repo) == ref_tip
411
+ if ref_branch and here != ref_branch and not at_tip:
412
+ off_ref = f"checkout on {here}; judged against {ref_branch}"
413
+ if ref_note:
414
+ off_ref = f"{off_ref}; {ref_note}" if off_ref else ref_note
415
+ if off_ref:
416
+ note("checkout-branch", name, off_ref)
417
+ ref_label = ref_branch or "HEAD"
418
+ suffix = f" ({off_ref})" if off_ref else ""
419
+ receipt_rel = gate_rec.get("receipt")
420
+ if receipt_rel:
421
+ rp = repo / receipt_rel
422
+ if not rp.is_file():
423
+ note("receipt-missing", name, str(receipt_rel))
424
+ else:
425
+ untracked(name, repo, ref_tip, receipt_rel, ref_label)
426
+ try:
427
+ rcommit = json.loads(rp.read_text()).get("commit")
428
+ except Exception:
429
+ rcommit = None
430
+ if rcommit and ref_tip and not package_descendant(repo, rcommit, ref_tip, pkg)[0]:
431
+ note("receipt-drift", name,
432
+ f"receipt={str(rcommit)[:12]} {ref_label}={ref_tip[:12]}{suffix}")
433
+ comp_rel = gate_rec.get("comparator")
434
+ if comp_rel:
435
+ cpth = repo / comp_rel
436
+ if not cpth.is_file():
437
+ note("comparator-missing", name, str(comp_rel))
438
+ else:
439
+ untracked(name, repo, ref_tip, comp_rel, ref_label)
440
+ ccommit = (recorded_json(repo, comp_rel) or {}).get("commit")
441
+ if ccommit and ref_tip and not package_descendant(repo, ccommit, ref_tip, pkg)[0]:
442
+ note("comparator-drift", name,
443
+ f"comparator={str(ccommit)[:12]} {ref_label}={ref_tip[:12]}{suffix}")
444
+ if pkg.get("formalization_yaml"):
445
+ # formalization-missing | formalization-drift | warn: the written
446
+ # formalization.yaml must equal what the generator emits today.
447
+ from . import formalization as formalization_mod
448
+ for check, detail in formalization_mod.audit_findings(pkg, repo):
449
+ note(check, name, detail)
450
+ nwo = gh_nwo(pkg.get("repo") or "")
451
+ if not nwo:
452
+ # no path echo: the repo may be a private local path, and findings are printed
453
+ note("no-github-mirror", name, NO_GITHUB_MIRROR_DETAIL)
454
+ continue
455
+ if not use_gh:
456
+ note("gh-skipped", name, "gh checks skipped (--no-gh)", level="info")
457
+ continue
458
+ p = gh("repo", "view", nwo, "--json", "visibility,isArchived")
459
+ if p.returncode != 0:
460
+ outcome, detail = classify_gh_failure(p, nwo, repo, auth_ok)
461
+ level = "warn"
462
+ if outcome == "not-found" and pkg.get("status") == "archived":
463
+ level = "info"
464
+ detail = ("archived; upstream repo not found — expected if the owner removed it; see notes ("
465
+ + detail + ")")
466
+ note(gh_check_code(outcome), name, detail, level=level, gh=outcome)
467
+ continue
468
+ try:
469
+ info = json.loads(p.stdout)
470
+ except ValueError:
471
+ note("gh-error", name, "gh returned non-JSON", gh="error")
472
+ continue
473
+ gvis = str(info.get("visibility") or "").lower()
474
+ if gvis and gvis != str(pkg.get("visibility")).lower():
475
+ held = bool(pkg.get("publication_hold")) # #5: a held record is never flipped public by --fix
476
+ hint = ""
477
+ if held:
478
+ hint = (f" — {hold_text(pkg['publication_hold'])}: the repository was made public outside "
479
+ f"promote; make it private again, or release the hold (`lean-pkg update {name} "
480
+ f"--release-publication-hold --reason TEXT`); not fixed")
481
+ elif pkg.get("status") == "public" and gvis != "public":
482
+ hint = (f" — the owner made the repository private: record it with `lean-pkg update {name} "
483
+ f"--withdraw-publication --reason TEXT` (status, visibility and a publication hold)")
484
+ note("visibility-mismatch", name,
485
+ f"registry={pkg.get('visibility')} gh={info.get('visibility')}" + hint
486
+ + (" — fixed" if fix and not held else ""), fixed=fix and not held)
487
+ if fix and not held:
488
+ record(reg, events_p, pkg, "audit-fix", field="visibility",
489
+ old=pkg.get("visibility"), new=gvis, source="gh")
490
+ pkg["visibility"] = gvis
491
+ mutated = True
492
+ if info.get("isArchived") and pkg.get("status") != "archived":
493
+ note("archived-upstream", name,
494
+ f"gh isArchived=true, registry status={pkg.get('status')}"
495
+ + (" — fixed" if fix else ""), fixed=fix)
496
+ if fix:
497
+ record(reg, events_p, pkg, "audit-fix", field="status",
498
+ old=pkg.get("status"), new="archived", source="gh")
499
+ pkg["status"] = "archived"
500
+ mutated = True
501
+ if mutated:
502
+ save_registry(reg_path, reg)
503
+ return findings
504
+
505
+
506
+ # --------------------------------------------------------------------------
507
+ # validate
508
+
509
+ def build_inputs_errors(globs, pfx: str) -> list[str]:
510
+ """Schema of the optional build_inputs: a list of non-empty package-relative globs (no leading /,
511
+ no .. component)."""
512
+ if globs is None:
513
+ return []
514
+ if not isinstance(globs, list):
515
+ return [f"{pfx}.build_inputs: must be a list of globs"]
516
+ errs = []
517
+ for g in globs:
518
+ if not isinstance(g, str) or not g.strip():
519
+ errs.append(f"{pfx}.build_inputs: {g!r} is not a non-empty string")
520
+ elif g.startswith("/") or ".." in pathlib.PurePosixPath(g).parts:
521
+ errs.append(f"{pfx}.build_inputs: {g!r} must be package-relative (no leading /, no ..)")
522
+ return errs
523
+
524
+
525
+ def validate_registry(data) -> list[str]:
526
+ from .cli import ( # the field validators of `update` (cli.py); cli imports audit
527
+ ai_assistance_errors, namespace_notes_errors, paper_errors, publication_hold_errors,
528
+ source_paper_errors,
529
+ )
530
+ errors: list[str] = []
531
+ if not isinstance(data, dict):
532
+ return ["top level is not a mapping"]
533
+ version = data.get("version")
534
+ if version not in SUPPORTED_REGISTRY_VERSIONS:
535
+ errors.append(f"version must be one of {SUPPORTED_REGISTRY_VERSIONS}, got {version!r}")
536
+ from .recommended import shape_errors # the top-level lean_pkg key (#388)
537
+ errors += shape_errors(data)
538
+ pkgs = data.get("packages")
539
+ if not isinstance(pkgs, dict):
540
+ errors.append("packages must be a mapping")
541
+ return errors
542
+ for key, pkg in pkgs.items():
543
+ pfx = f"packages.{key}"
544
+ if not isinstance(pkg, dict):
545
+ errors.append(f"{pfx}: not a mapping")
546
+ continue
547
+ for f in REQUIRED_FIELDS:
548
+ if f not in pkg:
549
+ errors.append(f"{pfx}: missing field {f!r}")
550
+ if pkg.get("name") != key:
551
+ errors.append(f"{pfx}: name field {pkg.get('name')!r} != map key {key!r}")
552
+ if version in (2, 3):
553
+ for f in V2_PACKAGE_DEFAULTS:
554
+ if f not in pkg:
555
+ errors.append(f"{pfx}: missing v2 field {f!r} (run `lean-pkg migrate`)")
556
+ if version == 3:
557
+ for f in V3_PACKAGE_DEFAULTS:
558
+ if f not in pkg:
559
+ errors.append(f"{pfx}: missing v3 field {f!r} (run `lean-pkg migrate`)")
560
+ if version == 3 or any(f in pkg for f in V3_PACKAGE_DEFAULTS):
561
+ if "claims" in pkg and not isinstance(pkg["claims"], list):
562
+ errors.append(f"{pfx}.claims: must be a list")
563
+ cf = pkg.get("claims_file", "claims.yaml")
564
+ if not isinstance(cf, str) or not cf.strip():
565
+ errors.append(f"{pfx}.claims_file: must be a non-empty repo-relative path")
566
+ csc = pkg.get("claims_synced_commit")
567
+ if csc is not None and not _HEX40.fullmatch(str(csc)):
568
+ errors.append(f"{pfx}.claims_synced_commit: must be 40 lowercase hex or null")
569
+ if version in (2, 3) or any(f in pkg for f in V2_PACKAGE_DEFAULTS):
570
+ for f in ("palomar", "consent"):
571
+ if f in pkg and not isinstance(pkg[f], list):
572
+ errors.append(f"{pfx}.{f}: must be a list")
573
+ for f in ("doi", "reservoir"):
574
+ if f in pkg and pkg[f] is not None and not isinstance(pkg[f], dict):
575
+ errors.append(f"{pfx}.{f}: must be a mapping or null")
576
+ for f in ("license_spdx", "formalization_yaml"):
577
+ if f in pkg and pkg[f] is not None and not isinstance(pkg[f], str):
578
+ errors.append(f"{pfx}.{f}: must be a string or null")
579
+ doi = pkg.get("doi")
580
+ if isinstance(doi, dict):
581
+ pal_commits = [e.get("commit") for e in (pkg.get("palomar") or []) if isinstance(e, dict)]
582
+ retracted = {(str(h.get("doi")), str(h.get("commit")), str(h.get("tag"))) # ignored versions
583
+ for h in retracted_entries(pkg) if h.get("event") == "doi-minted"}
584
+ for v in doi.get("versions") or []:
585
+ c = str((v or {}).get("commit") or "")
586
+ if isinstance(v, dict) and (str(v.get("doi")), c, str(v.get("tag"))) in retracted:
587
+ continue
588
+ if pkg.get("track") == "doi-only" or (isinstance(v, dict) and v.get("track") == "doi-only"):
589
+ continue # DOI-only track (#51): no palomar entry expected
590
+ if c and c not in pal_commits:
591
+ known = ", ".join(str(x)[:12] for x in pal_commits) or "none"
592
+ errors.append(f"{pfx}: doi {v.get('doi')} commit {c[:12]} matches no "
593
+ f"palomar entry (palomar commits: {known})")
594
+ if "track" in pkg and pkg["track"] not in TRACKS:
595
+ errors.append(f"{pfx}: bad track {pkg.get('track')!r} (allowed: {', '.join(TRACKS)})")
596
+ if "docs_descendants" in pkg and not isinstance(pkg["docs_descendants"], bool):
597
+ errors.append(f"{pfx}.docs_descendants: must be true or false")
598
+ errors += build_inputs_errors(pkg.get("build_inputs"), pfx)
599
+ if pkg.get("headline_config") is not None:
600
+ from .headline import path_error
601
+ if err := path_error(pkg["headline_config"]):
602
+ errors.append(f"{pfx}.headline_config: {err}")
603
+ errors += paper_errors(pkg.get("paper"), pfx)
604
+ errors += namespace_notes_errors(pkg.get("namespace_notes"), pfx)
605
+ errors += source_paper_errors(pkg.get("source_paper"), pfx)
606
+ errors += ai_assistance_errors(pkg.get("ai_assistance"), pfx)
607
+ if pkg.get("status") not in STATUSES:
608
+ errors.append(f"{pfx}: bad status {pkg.get('status')!r} "
609
+ f"(allowed: {', '.join(STATUSES)})")
610
+ if pkg.get("visibility") not in VISIBILITIES:
611
+ errors.append(f"{pfx}: bad visibility {pkg.get('visibility')!r}")
612
+ if pkg.get("upstream_target") not in UPSTREAM_TARGETS:
613
+ errors.append(f"{pfx}: bad upstream_target "
614
+ f"{pkg.get('upstream_target')!r}")
615
+ lease = pkg.get("lease")
616
+ if lease is not None:
617
+ if not isinstance(lease, dict):
618
+ errors.append(f"{pfx}.lease: not a mapping")
619
+ else:
620
+ for f in LEASE_FIELDS:
621
+ if f not in lease:
622
+ errors.append(f"{pfx}.lease: missing field {f!r}")
623
+ if "claimed_at" in lease:
624
+ try:
625
+ parse_ts(lease["claimed_at"])
626
+ except Exception:
627
+ errors.append(f"{pfx}.lease: unparseable claimed_at "
628
+ f"{lease.get('claimed_at')!r}")
629
+ if not isinstance(lease.get("ttl_hours"), int) \
630
+ or lease.get("ttl_hours", 0) <= 0:
631
+ errors.append(f"{pfx}.lease: ttl_hours must be a positive int")
632
+ if "contact" in lease and not isinstance(lease["contact"], str):
633
+ errors.append(f"{pfx}.lease: contact must be a string, got "
634
+ f"{type(lease['contact']).__name__}")
635
+ gate = pkg.get("gate")
636
+ if not isinstance(gate, dict):
637
+ errors.append(f"{pfx}.gate: not a mapping")
638
+ else:
639
+ if "receipt" not in gate:
640
+ errors.append(f"{pfx}.gate: missing key 'receipt'")
641
+ ax = gate.get("axioms_allowed")
642
+ if not isinstance(ax, list) or not all(isinstance(a, str) for a in ax):
643
+ errors.append(f"{pfx}.gate: axioms_allowed must be a list of strings")
644
+ comp = gate.get("comparator")
645
+ if comp is not None and not isinstance(comp, str):
646
+ errors.append(f"{pfx}.gate: comparator must be a string path or null")
647
+ if pkg.get("status") == "verified-private" and not gate.get("receipt"):
648
+ errors.append(f"{pfx}: status verified-private requires gate.receipt "
649
+ f"(only `lean-pkg gate` reaches verified-private)")
650
+ hist = pkg.get("history")
651
+ if not isinstance(hist, list):
652
+ errors.append(f"{pfx}.history: not a list")
653
+ else:
654
+ for i, e in enumerate(hist):
655
+ if not isinstance(e, dict) or not isinstance(e.get("ts"), str) \
656
+ or not isinstance(e.get("event"), str):
657
+ errors.append(f"{pfx}.history[{i}]: needs string ts + event")
658
+ continue
659
+ try:
660
+ parse_ts(e["ts"])
661
+ except Exception:
662
+ errors.append(f"{pfx}.history[{i}]: unparseable ts {e['ts']!r}")
663
+ errors += publication_hold_errors(pkg, pfx)
664
+ ra = pkg.get("reaudit_after")
665
+ if ra is not None:
666
+ try:
667
+ dt.date.fromisoformat(str(ra))
668
+ except ValueError:
669
+ errors.append(f"{pfx}: reaudit_after is not an ISO date: {ra!r}")
670
+ return errors
671
+
672
+
673
+ # --------------------------------------------------------------------------
674
+ # the audit and validate commands
675
+
676
+ def cmd_audit(args) -> int:
677
+ reg_path, events_p = registry_path(args), events_path(args)
678
+ floor = resolve_toolchain_floor(args.toolchain_floor)
679
+ findings = audit_registry(reg_path, load_registry(reg_path), events_p,
680
+ fix=args.fix, toolchain_floor=floor, promotion=args.promotion,
681
+ use_gh=not args.no_gh)
682
+ fixed = [f for f in findings if f.get("fixed")]
683
+ if args.json_out:
684
+ print_json({"ok": True, "fix": args.fix, "findings": findings, "fixed": len(fixed),
685
+ "counts": audit_counts(findings)})
686
+ else:
687
+ if not findings:
688
+ print("no findings")
689
+ else: # --quiet (#44): the count line only
690
+ print(audit_count_line(findings) if args.quiet else "\n".join(render_findings(findings)))
691
+ if fixed:
692
+ print(f"audit --fix wrote {len(fixed)} change(s): commit {reg_path.name} and {events_p.name} together",
693
+ file=sys.stderr)
694
+ return 0
695
+
696
+
697
+ def cmd_validate(args) -> int:
698
+ reg_path = registry_path(args)
699
+ try:
700
+ data = yaml.safe_load(reg_path.read_text())
701
+ except FileNotFoundError:
702
+ raise Fail(registry_not_found(reg_path)) from None
703
+ except yaml.YAMLError as e:
704
+ raise Fail(f"registry is not valid YAML: {e}") from e
705
+ errors = validate_registry(data)
706
+ if args.json_out:
707
+ print_json({"ok": not errors, "valid": not errors, "errors": errors,
708
+ "registry": str(reg_path)})
709
+ elif not errors:
710
+ print("\nVALID")
711
+ else: # #44: the verdict before the list and again last
712
+ print(f"INVALID ({len(errors)} error(s))")
713
+ for e in errors:
714
+ print(f" FAIL {e}")
715
+ print(f"\nINVALID ({len(errors)} error(s))")
716
+ return 1 if errors else 0