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/next_step.py ADDED
@@ -0,0 +1,510 @@
1
+ # lean-pkg next -- the single recommended next command for a package
2
+ """`lean-pkg next NAME [--agent A] [--json]` (#42): read the package's registry record and its
3
+ checkout, decide the one command to run next, and say why in one line.
4
+
5
+ Read-only and offline: nothing is written, the registry is not locked, no `gh` call and no network
6
+ request is made. The decision reuses the validators the writers use (`validate_receipt`,
7
+ `validate_comparator`, `evidence_only_descendant`) and the existing next-command producers
8
+ (`comparator config --coverage`, `publish --dry-run`), so it cannot recommend a command those would
9
+ refuse for a reason this module knows about.
10
+
11
+ Exit 0 when there is a command to run (or nothing left to do), 1 when the package is blocked: a
12
+ foreign live lease (with --agent), an unparseable lease, a missing checkout, a dirty tree where
13
+ evidence is being produced, an unreadable or invalid receipt. `blockers[]` names each one.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import datetime as dt
19
+ import json
20
+ import pathlib
21
+ import re
22
+ import shlex
23
+ import sys
24
+
25
+ from . import audit, cli, gate as gate_mod
26
+ from . import core
27
+
28
+ TERMINAL = ("upstreamed", "archived")
29
+ CLEAN_TREE_STATUSES = ("gate-pending", "verified-private") # evidence is produced from HEAD here
30
+ # Subcommands that read the package checkout (a recommended one ignores `next --repo`).
31
+ READS_CHECKOUT = ("gate", "comparator", "publish", "claims", "palomar", "reservoir", "formalization",
32
+ "public-safety")
33
+
34
+
35
+ def _receipt_candidates(repo: pathlib.Path) -> list[tuple[str, dict | None]]:
36
+ """(relative path, parsed object or None) for every lower-tier receipt candidate on disk:
37
+ .lean-receipts/*.json that is not a comparator receipt (top level only; bundles live in subdirs)."""
38
+ d = repo / ".lean-receipts"
39
+ out: list[tuple[str, dict | None]] = []
40
+ if not d.is_dir():
41
+ return out
42
+ for p in sorted(d.glob("*.json")):
43
+ if "-comparator" in p.name:
44
+ continue
45
+ try:
46
+ obj = json.loads(p.read_text())
47
+ except (OSError, ValueError):
48
+ obj = None
49
+ if obj is not None and not (isinstance(obj, dict) and "report_sha256" in obj):
50
+ continue # some other JSON file, not a lower-tier receipt
51
+ out.append((f".lean-receipts/{p.name}", obj))
52
+ return out
53
+
54
+
55
+ def lower_receipt(pkg: dict, repo: pathlib.Path) -> tuple[dict | None, list[dict]]:
56
+ """The newest lower-tier receipt on disk that `gate` would accept at HEAD, as {path, commit,
57
+ job_id}, and the candidates it rejected [{path, error}] (unparseable, or failing validate_receipt)."""
58
+ good: list[tuple[str, dict]] = []
59
+ bad: list[dict] = []
60
+ for rel, obj in _receipt_candidates(repo):
61
+ if obj is None:
62
+ bad.append({"path": rel, "error": "not valid JSON"})
63
+ continue
64
+ try:
65
+ gate_mod.validate_receipt(pkg, repo, obj)
66
+ why = gate_mod.recorded_report_log_problem(repo, obj, rel) # gate refuses a receipt without its log
67
+ if why:
68
+ raise core.Fail(why)
69
+ except core.Fail as e:
70
+ bad.append({"path": rel, "error": str(e), "commit": str(obj.get("commit") or "")})
71
+ continue
72
+ good.append((rel, obj))
73
+ if not good:
74
+ return None, bad
75
+ rel, obj = max(good, key=lambda g: (str(g[1].get("generated_at")), g[0]))
76
+ return {"path": rel, "commit": obj["commit"], "job_id": str(obj.get("job_id"))}, bad
77
+
78
+
79
+ def comparator_on_disk(pkg: dict, repo: pathlib.Path, commit: str) -> tuple[str | None, str | None]:
80
+ """(path, None) when .lean-receipts/<commit12>-comparator.json validates against `commit` at HEAD,
81
+ (path, error) when it exists but does not, (None, None) when there is none."""
82
+ rel = f".lean-receipts/{commit[:12]}-comparator.json"
83
+ obj = gate_mod.recorded_json(repo, rel)
84
+ if obj is None:
85
+ return (rel, "not valid JSON") if (repo / rel).exists() else (None, None)
86
+ try:
87
+ gate_mod.validate_comparator(pkg, repo, obj, commit)
88
+ except core.Fail as e:
89
+ return rel, str(e)
90
+ return rel, None
91
+
92
+
93
+ def _lease_view(lease, now: dt.datetime) -> dict | None:
94
+ if not lease:
95
+ return None
96
+ view = dict(lease) if isinstance(lease, dict) else {"raw": lease}
97
+ exp = core.lease_expiry_or_none(lease) if isinstance(lease, dict) else None
98
+ view["expires_at"] = exp.isoformat() if exp else None
99
+ view["live"] = core.lease_live_or_none(lease, now) if isinstance(lease, dict) else None
100
+ return view
101
+
102
+
103
+ def _q(s: str) -> str:
104
+ return shlex.quote(str(s))
105
+
106
+
107
+ def decide(reg: dict, name: str, agent: str | None = None) -> dict:
108
+ """The decision as the --json payload: {ok, name, command, reason, blockers[], notes[], state{}}."""
109
+ pkg = core.get_pkg(reg, name)
110
+ status = pkg.get("status")
111
+ now = dt.datetime.now(dt.timezone.utc)
112
+ lease = pkg.get("lease")
113
+ state: dict = {"status": status, "visibility": pkg.get("visibility"), "lease": _lease_view(lease, now),
114
+ "gate_commit": None, "comparator_commit": None, "head": None, "checkout": None,
115
+ "dirty": [], "receipt_candidate": None, "rejected_receipts": [], "comparator_configs": [],
116
+ "claims_ledger": None, "publication_hold": pkg.get("publication_hold")}
117
+ notes: list[str] = []
118
+ ag = agent or "A"
119
+ as_agent = f" --agent {_q(agent)}" if agent else ""
120
+
121
+ def out(command, reason, blockers=()):
122
+ blockers = list(blockers)
123
+ return {"ok": not blockers, "name": name, "command": command, "reason": reason,
124
+ "blockers": blockers, "notes": notes, "state": state}
125
+
126
+ def blocked(kind, detail, command=None, reason=None):
127
+ return out(command, reason or detail, [{"kind": kind, "detail": detail}])
128
+
129
+ if status in TERMINAL:
130
+ return out(None, f"status {status}: nothing left to do (terminal status)")
131
+
132
+ # The checkout.
133
+ try:
134
+ repo = core.repo_path(pkg)
135
+ except (KeyError, TypeError, ValueError):
136
+ repo = None
137
+ state["checkout"] = str(repo) if repo is not None else None
138
+ if repo is None or not repo.is_dir():
139
+ detail = audit.missing_path_detail(name, pkg, repo)
140
+ cmd = detail.split("`")[1] if detail.count("`") >= 2 else None # its `lean-pkg update ... --dry-run`
141
+ return blocked("missing-checkout", f"missing checkout: {detail}", cmd)
142
+ head = core.git_head(repo)
143
+ state["head"] = head
144
+ if head is None:
145
+ return blocked("no-commit", f"{repo} is not a git checkout with a commit",
146
+ None, f"missing checkout: {repo} is not a git checkout with a commit; commit the "
147
+ f"package there (or fix local_path with `lean-pkg update {name} --path DIR "
148
+ f"--reason TEXT`)")
149
+ notice = core.branch_notice(repo)
150
+ if notice: # #48: HEAD is still what is judged; the note only says it is not the default branch
151
+ notes.append(notice)
152
+
153
+ # The lease.
154
+ if core.lease_invalid(lease):
155
+ return blocked("invalid-lease", f"lease fields unparseable (claimed_at={lease.get('claimed_at')!r}, "
156
+ f"ttl_hours={lease.get('ttl_hours')!r})",
157
+ f"lean-pkg release {name} --force --reason \"unparseable lease\"",
158
+ "lease fields are unparseable: every write refuses until it is cleared")
159
+ live = bool(lease) and core.lease_live(lease, now)
160
+ holder = lease.get("agent") if live else None
161
+ if live and agent and holder != agent:
162
+ return blocked("foreign-lease",
163
+ f"foreign live lease: held by {holder} (workspace {lease.get('workspace')}) until "
164
+ f"{core.lease_expiry(lease).isoformat()}",
165
+ None, f"foreign live lease: {holder} holds {name} until "
166
+ f"{core.lease_expiry(lease).isoformat()}; wait for its release or expiry, or "
167
+ f"coordinate with the holder (do not --force without a human reason)")
168
+ if live and not agent:
169
+ notes.append(f"leased by {holder} (workspace {lease.get('workspace')}); pass --agent A to check "
170
+ f"the lease is yours")
171
+ if lease and not live:
172
+ notes.append(f"lease of {lease.get('agent')} has expired; `claim` takes it over")
173
+ holder_flag = f" --agent {_q(holder)}" if live else as_agent
174
+
175
+ # Recorded evidence.
176
+ gate = pkg.get("gate") or {}
177
+ rec = gate_mod.recorded_json(repo, gate.get("receipt"))
178
+ comp = gate_mod.recorded_json(repo, gate.get("comparator"))
179
+ state["gate_commit"] = (rec or {}).get("commit") if isinstance(rec, dict) else None
180
+ state["comparator_commit"] = (comp or {}).get("commit") if isinstance(comp, dict) else None
181
+ state["comparator_configs"] = gate_mod.head_comparator_configs(repo)
182
+ if status in CLEAN_TREE_STATUSES:
183
+ state["dirty"] = gate_mod.dirty_tracked(repo)
184
+
185
+ if status in ("scratch", "active") and not live:
186
+ return out(f"lean-pkg lease claim {name} --workspace W --agent {_q(ag)} --reason \"...\"",
187
+ f"status {status} and no live lease: claim the package before working on it")
188
+ if status == "scratch":
189
+ return out(f"lean-pkg update {name} --status active --reason \"work started\"{holder_flag}",
190
+ "scratch and claimed: name the work (scratch -> active needs owner_project named; "
191
+ f"owner_project is {pkg.get('owner_project')!r})")
192
+
193
+ if status in ("active", "gate-pending"):
194
+ cand, bad = lower_receipt(pkg, repo)
195
+ state["receipt_candidate"] = cand
196
+ state["rejected_receipts"] = bad
197
+ if status == "active":
198
+ if cand:
199
+ return out(f"lean-pkg update {name} --status gate-pending --reason "
200
+ f"\"check job {cand['job_id']} submitted\"{holder_flag}",
201
+ f"a lower-tier receipt bound to HEAD {head[:12]} exists ({cand['path']}): move to "
202
+ f"gate-pending, then gate it")
203
+ return out(f"lean-pkg gate {name} --check --receipt R",
204
+ f"produce the lower-tier receipt: no receipt in .lean-receipts/ binds HEAD {head[:12]}; "
205
+ f"run the checker job on HEAD (R: the receipt it writes) and validate it read-only "
206
+ f"with this command" + (f"; rejected: {bad[0]['path']}: {bad[0]['error']}" if bad else ""))
207
+ # gate-pending
208
+ if state["dirty"]:
209
+ return _dirty(name, repo, state, out)
210
+ if cand:
211
+ crel, cerr = comparator_on_disk(pkg, repo, cand["commit"])
212
+ comp_flag = f" --comparator {_q(repo / crel)}" if crel and not cerr else ""
213
+ if crel and cerr:
214
+ notes.append(f"comparator receipt {crel} not usable: {cerr}")
215
+ return out(f"lean-pkg gate {name} --receipt {_q(repo / cand['path'])}{comp_flag}{as_agent}",
216
+ f"gate-pending with a lower-tier receipt bound to HEAD {head[:12]}; validate first: "
217
+ f"`lean-pkg gate {name} --check --receipt {_q(repo / cand['path'])}{comp_flag}`")
218
+ at_head = [b for b in bad if b.get("commit") and gate_mod.package_descendant(
219
+ repo, b["commit"], head, pkg)[0]] if bad else []
220
+ if at_head:
221
+ b = at_head[0]
222
+ return blocked("invalid-receipt", f"invalid receipt {b['path']}: {b['error']}",
223
+ f"lean-pkg gate {name} --check --receipt {_q(repo / b['path'])}",
224
+ f"unreadable receipt: {b['path']} binds HEAD {head[:12]} but `gate` would refuse "
225
+ f"it: {b['error']}")
226
+ return out(f"lean-pkg gate {name} --check --receipt R",
227
+ f"gate-pending but no lower-tier receipt in .lean-receipts/ binds HEAD {head[:12]}: produce "
228
+ f"it (checker job on HEAD), validate it with this command, then `lean-pkg gate {name} "
229
+ f"--receipt R`")
230
+
231
+ if status == "verified-private":
232
+ if state["dirty"]:
233
+ return _dirty(name, repo, state, out)
234
+ if not isinstance(rec, dict):
235
+ return blocked("unreadable-receipt",
236
+ f"unreadable receipt: gate receipt {gate.get('receipt')!r} is missing or not JSON in "
237
+ f"{repo}", None,
238
+ f"unreadable receipt: gate receipt {gate.get('receipt')!r} is missing or not JSON; "
239
+ f"restore it from git, or re-gate (`lean-pkg update {name} --status gate-pending "
240
+ f"--reason TEXT`)")
241
+ try:
242
+ gate_mod.validate_receipt(pkg, repo, rec)
243
+ except core.Fail as e:
244
+ # #67: one step (`gate --regate`), not `update --status gate-pending` then `gate`.
245
+ cand, bad = lower_receipt(pkg, repo)
246
+ state["receipt_candidate"] = cand
247
+ state["rejected_receipts"] = bad
248
+ prev = str(rec.get("commit") or "")
249
+ lineage = ""
250
+ if cand and prev and not core._is_ancestor(repo, prev, cand["commit"]):
251
+ lineage = f" --reason \"HEAD {head[:12]} does not descend from {prev[:12]}\""
252
+ if cand:
253
+ crel, cerr = comparator_on_disk(pkg, repo, cand["commit"])
254
+ comp_flag = f" --comparator {_q(repo / crel)}" if crel and not cerr else ""
255
+ return out(f"lean-pkg gate {name} --receipt {_q(repo / cand['path'])}{comp_flag} --regate"
256
+ f"{lineage}{as_agent}",
257
+ f"the gate receipt no longer binds HEAD ({e}): re-gate the new commit in one step; "
258
+ f"validate first: `lean-pkg gate {name} --check --regate --receipt "
259
+ f"{_q(repo / cand['path'])}{comp_flag}`")
260
+ return out(f"lean-pkg gate {name} --check --regate --receipt R",
261
+ f"the gate receipt no longer binds HEAD ({e}): produce a lower-tier receipt for HEAD "
262
+ f"{head[:12]} (checker job on HEAD), validate it with this command, then "
263
+ f"`lean-pkg gate {name} --receipt R --regate`")
264
+ why = gate_mod.recorded_report_log_problem(repo, rec, gate["receipt"])
265
+ if why: # gate would refuse this receipt today: its sealed log is gone or differs
266
+ rp = _q(repo / gate["receipt"])
267
+ return blocked("invalid-receipt", f"invalid receipt {gate['receipt']}: {why}",
268
+ f"lean-pkg gate {name} --check --receipt {rp}",
269
+ f"invalid receipt: the recorded gate receipt {gate['receipt']} has no sealed log to "
270
+ f"check report_sha256 against: restore it (docs/receipts.md, \"Restoring preserved "
271
+ f"evidence\"), then validate with this command; a lost log needs a new run and "
272
+ f"`gate --regate`")
273
+ bound = str(rec["commit"])
274
+ if gate.get("comparator"):
275
+ if not isinstance(comp, dict):
276
+ return blocked("unreadable-receipt",
277
+ f"unreadable receipt: comparator receipt {gate.get('comparator')!r} is missing "
278
+ f"or not JSON in {repo}")
279
+ try:
280
+ gate_mod.validate_comparator(pkg, repo, comp, bound)
281
+ except core.Fail as e:
282
+ notes.append(f"recorded comparator receipt is not valid at HEAD: {e}")
283
+ else:
284
+ return _ledger_step(reg, pkg, name, state, notes, out)
285
+ crel, cerr = comparator_on_disk(pkg, repo, bound)
286
+ if crel and not cerr:
287
+ return out(f"lean-pkg comparator {name} --receipt {_q(repo / crel)}{as_agent}",
288
+ f"a comparator receipt for {bound[:12]} is on disk and validates: attach it")
289
+ if crel and cerr:
290
+ notes.append(f"comparator receipt {crel} not usable: {cerr}")
291
+ if state["comparator_configs"]:
292
+ return _comparator_step(pkg, repo, head, out, f"comparator-receipt --repo {_q(repo)}",
293
+ f"no comparator evidence; {len(state['comparator_configs'])} comparator config(s) "
294
+ f"tracked at HEAD: run comparator-receipt on a host its policy allows (`lean-pkg "
295
+ f"comparator host-check`), then attach the receipt with `lean-pkg comparator {name} "
296
+ f"--receipt {_q(repo / '.lean-receipts' / (bound[:12] + '-comparator.json'))}`")
297
+ try: # reuse the coverage producer: it names the scaffold step and the re-gate tail
298
+ from . import comparator_config as cc
299
+ _lines, cov = cc.do_coverage(reg, name)
300
+ nxt = cov.get("next_commands") or []
301
+ except core.Fail as e:
302
+ nxt = []
303
+ notes.append(f"comparator coverage: {e}")
304
+ if nxt:
305
+ return _comparator_step(pkg, repo, head, out, nxt[0].split(" #")[0],
306
+ "no comparator config tracked at HEAD: scaffold one from the synced claims (committing "
307
+ "it moves HEAD, so re-gate afterwards: " + "; ".join(c.split(" #")[0] for c in nxt[1:3])
308
+ + ")")
309
+ return out(f"lean-pkg claims sync {name}",
310
+ f"no comparator config tracked at HEAD and no claims to scaffold one from: sync claims.yaml, "
311
+ f"then `lean-pkg comparator config --from-claims {name}` (or write comparator.json by hand)")
312
+
313
+ if status == "public":
314
+ return _public(pkg, repo, head, out)
315
+
316
+ return out(None, f"status {status!r}: no rule for it")
317
+
318
+
319
+ def _ledger_step(reg: dict, pkg: dict, name: str, state: dict, notes: list[str], out):
320
+ """Both tiers bind HEAD: `promote` still refuses unless the claims ledger is ready (#80), so
321
+ recommend `publish --dry-run` only then; otherwise the ledger's first fix."""
322
+ if pkg.get("publication_hold"): # #5: the owner withdrew publication; next never recommends undoing it
323
+ return out(None, f"{cli.hold_text(pkg['publication_hold'])}: both tiers bind HEAD, and nothing is "
324
+ f"published while the hold is set (promote refuses); lifting it is the owner's decision: "
325
+ f"`lean-pkg update {name} --release-publication-hold --reason TEXT`")
326
+ from . import ledger
327
+ led = ledger.ledger_for(pkg, "promote")
328
+ state["claims_ledger"] = {"package_status": led["package_status"], "counts": led["counts"],
329
+ "required": led["required"], "ledger_digest": led["ledger_digest"]}
330
+ if led["package_status"] == "ready":
331
+ cond = ""
332
+ if led.get("conditional_required"): # proposal 0003: a possible next formalization step, not an error
333
+ hs = led.get("outstanding_hypotheses") or []
334
+ cond = (f"; {len(led['conditional_required'])} required claim(s) are conditional"
335
+ + (f", outstanding hypotheses {', '.join(hs)}: proving {hs[0]} (a proof claim and a corollary "
336
+ f"that discharges it) is a possible next formalization step, not an error" if hs
337
+ else " with every hypothesis discharged"))
338
+ return out(f"lean-pkg publish {name} --dry-run",
339
+ f"verified-private with comparator evidence bound to HEAD and the claims ledger ready{cond}: run "
340
+ f"the read-only publish checklist, then `lean-pkg publish {name} --yes --dry-run` (a dry run; a human reads "
341
+ f"it before --yes)")
342
+ why = ledger.summary(led)
343
+ codes = {d["code"] for r in led["claims"] if r["required"] for d in r["diagnostics"]}
344
+ if codes & {"no-comparator-config", "comparator-todo"}:
345
+ try: # the coverage producer names the scaffold step and the re-gate tail
346
+ from . import comparator_config as cc
347
+ nxt = cc.do_coverage(reg, name)[1].get("next_commands") or []
348
+ except core.Fail as e:
349
+ nxt = []
350
+ notes.append(f"comparator coverage: {e}")
351
+ if nxt:
352
+ return _comparator_step(pkg, core.repo_path(pkg), state["head"], out, nxt[0].split(" #")[0],
353
+ f"promote would refuse: {why}; extend the comparator configuration to the uncovered claims "
354
+ f"(committing it moves HEAD, so re-gate afterwards: "
355
+ + "; ".join(c.split(" #")[0] for c in nxt[1:3]) + ")")
356
+ hint = ""
357
+ if not led["claims"]: # nothing to verify: say how to get claims (write, migrate or sync them)
358
+ from . import claims as claims_mod
359
+ h = claims_mod.coverage(name, pkg).get("hint")
360
+ hint = f"; {h}, then re-gate the commit that tracks it" if h else ""
361
+ return out(f"lean-pkg claims ledger {name}",
362
+ f"promote would refuse: {why}{hint}; the ledger lists each open claim and why")
363
+
364
+
365
+ def toolchain_below_floor(pkg: dict, repo: pathlib.Path, head: str | None) -> tuple[str, str] | None:
366
+ """(toolchain, floor) when the lean-toolchain committed at HEAD (else the registry's) is below the
367
+ comparator floor `audit` checks (below-toolchain-floor); None when it is not, or is not comparable."""
368
+ raw = core.git_show_bytes(repo, "lean-toolchain", head) if head else None
369
+ lines = raw.decode("utf-8", "replace").splitlines() if raw else []
370
+ tc = (lines[0].strip() if lines else "") or str(pkg.get("lean_toolchain") or "").strip()
371
+ try:
372
+ floor = audit.resolve_toolchain_floor(None)
373
+ except core.UsageError:
374
+ floor = audit.DEFAULT_TOOLCHAIN_FLOOR
375
+ key, floor_key = audit.parse_lean_toolchain(tc), audit.parse_lean_toolchain(floor)
376
+ return (tc, floor) if key and floor_key and key < floor_key else None
377
+
378
+
379
+ def _comparator_step(pkg, repo, head, out, command, reason):
380
+ """A comparator step (scaffold a config, run comparator-receipt) under the comparator toolchain floor
381
+ is blocked first (field report): the toolchain mechanism, what Palomar runs, needs the floor."""
382
+ below = toolchain_below_floor(pkg, repo, head)
383
+ if below is None:
384
+ return out(command, reason)
385
+ tc, floor = below
386
+ detail = f"toolchain {tc} is below the comparator floor {floor}"
387
+ return out(None, f"{detail}: bump lean-toolchain (and Mathlib) to {floor} or later, commit, re-gate, then "
388
+ f"`{command}`; a legacy-mechanism comparator receipt (`comparator-receipt --mechanism "
389
+ f"legacy`) works below the floor but is not what Palomar runs, and `lean-pkg audit` warns "
390
+ f"below-toolchain-floor once comparator evidence is recorded",
391
+ [{"kind": "below-toolchain-floor", "detail": detail, "lean_toolchain": tc, "floor": floor,
392
+ "deferred_command": command}])
393
+
394
+
395
+ def _dirty(name, repo, state, out):
396
+ shown = ", ".join(state["dirty"][:5]) + (", ..." if len(state["dirty"]) > 5 else "")
397
+ detail = f"dirty tree: {len(state['dirty'])} tracked file(s) modified ({shown})"
398
+ res = out(f"git -C {_q(repo)} status --short",
399
+ f"{detail}; evidence binds commits and comparator-receipt needs a clean tree: commit or stash "
400
+ f"them first", [{"kind": "dirty-tree", "detail": detail}])
401
+ return res
402
+
403
+
404
+ def _public(pkg: dict, repo: pathlib.Path, head: str, out):
405
+ from . import publish as publish_mod
406
+ name = pkg["name"]
407
+ ups = cli.upstream_evidence(pkg)
408
+ if ups:
409
+ return out(f"lean-pkg update {name} --status upstreamed --reason \"{ups[0]}\"",
410
+ f"upstream evidence recorded ({ups[0]}): public -> upstreamed")
411
+ tags = publish_mod.tags_at_head(repo)
412
+ cmds = publish_mod.next_commands(pkg, repo, True, tags) # the publish producer's tag/record commands
413
+ if not tags:
414
+ return out(cmds[0].split(" #")[0], f"public, no tag at HEAD {head[:12]}: tag the release "
415
+ f"(Reservoir and doi-minted need one)")
416
+ if not pkg.get("reservoir"):
417
+ rec = next((c for c in cmds if "reservoir-listed" in c), "")
418
+ return out(f"lean-pkg reservoir check {name}",
419
+ f"public and tagged, not recorded as listed on Reservoir: check eligibility; once listed: "
420
+ f"`{rec.split(' #')[0]}`")
421
+ if pkg.get("upstream_target") == "palomar" and not pkg.get("palomar"):
422
+ mark, label = publish_mod.consent_item(pkg)
423
+ if mark != "✓":
424
+ return out(f"lean-pkg record {name} consent-recorded --field who=W --field role=R --field pointer=P",
425
+ f"upstream_target palomar: palomar prepare refuses without consent ({label})")
426
+ prepared = [h for h in core.live_history(pkg) if h.get("event") == "palomar-prepared"
427
+ and str(h.get("commit") or "") == head]
428
+ if not prepared:
429
+ return out(f"lean-pkg palomar prepare {name}",
430
+ f"upstream_target palomar and no bundle prepared at HEAD {head[:12]}: build it (no "
431
+ f"network; submits nothing)")
432
+ sub = next((c for c in cmds if "palomar-submitted" in c), "")
433
+ return out(sub.split(" #")[0].replace("<40hex>", head),
434
+ f"bundle prepared at HEAD {head[:12]}: submit it to Palomar by hand, then record the submission")
435
+ if pkg.get("upstream_target") == "mathlib" and not any(
436
+ h.get("event") == "mathlib-pr-opened" for h in core.live_history(pkg)):
437
+ return out(f"lean-pkg record {name} mathlib-pr-opened --field url=https://github.com/OWNER/REPO/pull/N",
438
+ "upstream_target mathlib and no Mathlib PR recorded: open it, then record its URL")
439
+ return out(None, "public, tagged and listed; nothing to do until upstream evidence arrives "
440
+ "(`lean-pkg record NAME mathlib-pr-merged` / `palomar-registered`)".replace("NAME", name))
441
+
442
+
443
+ def render(payload: dict) -> list[str]:
444
+ name, st = payload["name"], payload["state"]
445
+ lines = [f"{name} ({st.get('status')}): " + (payload["command"] or "nothing to run")]
446
+ for b in payload["blockers"]:
447
+ lines.append(f" blocked: {b['kind']}: {b['detail']}")
448
+ lines.append(f" why: {payload['reason']}")
449
+ for n in payload["notes"]:
450
+ lines.append(f" note: {n}")
451
+ return lines
452
+
453
+
454
+ def _with_repo(cmd: str, repo: str) -> str:
455
+ """`gate --check` takes --repo too: carry it into that recommended command."""
456
+ if cmd.startswith("lean-pkg gate ") and " --check" in cmd and " --repo " not in cmd:
457
+ return f"{cmd} --repo {_q(repo)}"
458
+ return cmd
459
+
460
+
461
+ def _carry_repo(payload: dict, repo: str) -> None:
462
+ """--repo DIR is for `next` and `gate --check` only: fill it into those, and say that any other
463
+ lean-pkg command recommended still reads the registered local_path."""
464
+ cmd = payload.get("command")
465
+ if cmd:
466
+ payload["command"] = _with_repo(cmd, repo)
467
+ payload["reason"] = re.sub(r"`(lean-pkg gate [^`]*)`", lambda m: f"`{_with_repo(m.group(1), repo)}`",
468
+ payload["reason"])
469
+ words = (payload.get("command") or "").split()
470
+ if words[:1] == ["lean-pkg"] and len(words) > 1 and words[1] in READS_CHECKOUT and "--repo" not in words:
471
+ payload["notes"].append("the recommended command reads the registered local_path, not --repo: run it "
472
+ "where that checkout is current, or move the record with `lean-pkg update "
473
+ f"{payload['name']} --path DIR --reason TEXT`")
474
+
475
+
476
+ def cmd_next(args) -> int:
477
+ reg = core.load_registry(core.registry_path(args))
478
+ if args.agent is not None:
479
+ core.require_nonempty("--agent", args.agent)
480
+ override = None
481
+ if getattr(args, "repo", None) is not None:
482
+ reg, override = gate_mod.repo_override(reg, args.name, args.repo)
483
+ if note := gate_mod.repo_override_note(override):
484
+ print(note, file=sys.stderr)
485
+ payload = decide(reg, args.name, args.agent)
486
+ payload["repo_override"] = override
487
+ if override:
488
+ _carry_repo(payload, override["path"])
489
+ if getattr(args, "json_out", False):
490
+ core.print_json(payload)
491
+ else:
492
+ print("\n".join(render(payload)))
493
+ return 0 if payload["ok"] else 1
494
+
495
+
496
+ def add_parsers(sub, add_json) -> None:
497
+ s = sub.add_parser("next", help="read-only: the single recommended next command for a package, with a "
498
+ "one-line reason (exit 0 a command to run, 1 blocked)")
499
+ s.add_argument("name")
500
+ s.add_argument("--agent", default=None, metavar="A",
501
+ help="who is asking: a live lease held by another agent blocks (exit 1); without it a live "
502
+ "lease is only noted; also filled into the recommended command")
503
+ s.add_argument("--repo", default=None, metavar="DIR",
504
+ help="evaluate the checkout DIR instead of the registered local_path, for this call only "
505
+ "(never saved; stderr note, JSON repo_override): for a host whose registered path "
506
+ "holds another branch. DIR must be a git work tree, and when it has remotes one must "
507
+ "be the package's repo (Host:/p matches a local-path repo /p; the registered "
508
+ "local_path itself needs no remote)")
509
+ add_json(s)
510
+ s.set_defaults(fn=cmd_next)