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/page_html.py ADDED
@@ -0,0 +1,153 @@
1
+ # lean-pkg page --html -- one static HTML file from the page's own Markdown
2
+ """The Markdown `lean-pkg page` writes is a closed subset: `#`/`##`/`###` headings, paragraphs, `- ` bullets,
3
+ `> ` quotes, pipe tables, fenced code, HTML comments, and inline code spans, `*em*`, `**strong**`,
4
+ `[text](url)`, `<br>`, backslash escapes and the entities `&amp;`, `&lt;`, `&gt;` (all user text arrives
5
+ escaped by page._md). This module turns exactly that subset into one HTML document: no script, no
6
+ external asset, a few lines of inline CSS. Every text run is HTML-escaped; a link is kept only when its
7
+ target is https, an in-page anchor or a relative path, and every attribute is quoted and escaped."""
8
+
9
+ from __future__ import annotations
10
+
11
+ import html
12
+ import re
13
+
14
+ CSS = """\
15
+ body{font-family:Georgia,"Times New Roman",serif;font-size:17px;line-height:1.55;max-width:48rem;\
16
+ margin:2rem auto;padding:0 1rem;color:#111;background:#fff}
17
+ h1,h2,h3{line-height:1.25;font-weight:normal}h2{margin-top:2.2rem;border-bottom:1px solid #ddd}\
18
+ h3{margin-top:1.8rem;font-style:italic}
19
+ table{border-collapse:collapse;display:block;overflow-x:auto;font-size:.85em}th,td{border:1px solid #ccc;\
20
+ padding:.3rem .5rem;vertical-align:top;text-align:left}
21
+ code,pre{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.85em;background:#f5f5f2}\
22
+ pre{padding:.6rem .8rem;overflow-x:auto;border-left:3px solid #ccc}pre.lean{border-left-color:#4a7}\
23
+ pre.latex{border-left-color:#47a}
24
+ blockquote{margin:0;padding:0 1rem;border-left:4px solid #ccc}a{color:#0645ad}
25
+ @media (prefers-color-scheme:dark){body{color:#e6e6e6;background:#141414}code,pre{background:#262626}\
26
+ th,td{border-color:#444}h2{border-color:#444}a{color:#8ab4f8}}"""
27
+
28
+ _INLINE = re.compile(
29
+ r"\\(?P<esc>[!-/:-@\[-`{-~])"
30
+ r"|`(?P<code>[^`]+)`"
31
+ r"|\*\*(?P<strong>(?:\\.|[^*\\])+)\*\*"
32
+ r"|\*(?P<em>(?:\\.|[^*\\])+)\*"
33
+ r"|\[(?P<lt>(?:\\.|`[^`]*`|[^\]\\`])+)\]\((?P<lu>[^)\s]+)\)"
34
+ r"|(?P<br><br>)"
35
+ r"|(?P<ent>&(?:amp|lt|gt|quot|#\d{1,6});)")
36
+ _CELL_SPLIT = re.compile(r"(?<!\\)\|")
37
+
38
+
39
+ def _url_ok(url: str) -> bool:
40
+ if url.startswith(("https://", "#")):
41
+ return True
42
+ return not re.match(r"^[A-Za-z][A-Za-z0-9+.-]*:", url) and not url.startswith("//")
43
+
44
+
45
+ def inline(s: str) -> str:
46
+ out, pos = [], 0
47
+ for m in _INLINE.finditer(s):
48
+ out.append(html.escape(s[pos:m.start()], quote=False))
49
+ pos = m.end()
50
+ if m.group("esc") is not None:
51
+ out.append(html.escape(m.group("esc"), quote=False))
52
+ elif m.group("code") is not None:
53
+ out.append(f"<code>{html.escape(m.group('code'), quote=False)}</code>")
54
+ elif m.group("strong") is not None:
55
+ out.append(f"<strong>{inline(m.group('strong'))}</strong>")
56
+ elif m.group("em") is not None:
57
+ out.append(f"<em>{inline(m.group('em'))}</em>")
58
+ elif m.group("lt") is not None:
59
+ url = m.group("lu")
60
+ text = inline(m.group("lt"))
61
+ out.append(f'<a href="{html.escape(url, quote=True)}">{text}</a>' if _url_ok(url) else text)
62
+ elif m.group("br") is not None:
63
+ out.append("<br>")
64
+ else:
65
+ out.append(m.group("ent"))
66
+ out.append(html.escape(s[pos:], quote=False))
67
+ return "".join(out)
68
+
69
+
70
+ def _cells(line: str) -> list[str]:
71
+ inner = line.strip()
72
+ inner = inner[1:] if inner.startswith("|") else inner
73
+ inner = inner[:-1] if inner.endswith("|") and not inner.endswith("\\|") else inner
74
+ return [inline(c.strip().replace("\\|", "|")) for c in _CELL_SPLIT.split(inner)]
75
+
76
+
77
+ def _slug(text: str, seen: dict[str, int]) -> str:
78
+ base = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-") or "section"
79
+ n = seen.get(base, 0)
80
+ seen[base] = n + 1
81
+ return base if n == 0 else f"{base}-{n}"
82
+
83
+
84
+ def body(lines: list[str]) -> list[str]:
85
+ """HTML lines for the Markdown subset described above."""
86
+ out: list[str] = []
87
+ seen: dict[str, int] = {}
88
+ para: list[str] = []
89
+ i = 0
90
+
91
+ def flush():
92
+ if para:
93
+ out.append("<p>" + "\n".join(inline(x) for x in para) + "</p>")
94
+ para.clear()
95
+
96
+ while i < len(lines):
97
+ line = lines[i]
98
+ if not line.strip():
99
+ flush()
100
+ i += 1
101
+ elif line.startswith("<!--") and line.rstrip().endswith("-->"):
102
+ flush()
103
+ i += 1
104
+ elif line.startswith(("# ", "## ", "### ")):
105
+ flush()
106
+ level = len(line) - len(line.lstrip("#"))
107
+ text = line[level + 1:]
108
+ out.append(f'<h{level} id="{_slug(re.sub(r"[`*]", "", text), seen)}">{inline(text)}</h{level}>')
109
+ i += 1
110
+ elif line.startswith("```"):
111
+ flush()
112
+ j = i + 1
113
+ while j < len(lines) and not lines[j].startswith("```"):
114
+ j += 1
115
+ lang = line[3:].strip()
116
+ cls = f' class="{lang}"' if lang in ("lean", "latex", "bash") else ""
117
+ out.append(f"<pre{cls}><code>" + html.escape("\n".join(lines[i + 1:j]), quote=False) + "</code></pre>")
118
+ i = j + 1
119
+ elif line.startswith("- "):
120
+ flush()
121
+ out.append("<ul>")
122
+ while i < len(lines) and lines[i].startswith("- "):
123
+ out.append(f"<li>{inline(lines[i][2:])}</li>")
124
+ i += 1
125
+ out.append("</ul>")
126
+ elif line.startswith("> "):
127
+ flush()
128
+ out.append(f"<blockquote><p>{inline(line[2:])}</p></blockquote>")
129
+ i += 1
130
+ elif line.startswith("|"):
131
+ flush()
132
+ rows = []
133
+ while i < len(lines) and lines[i].startswith("|"):
134
+ rows.append(lines[i])
135
+ i += 1
136
+ head, data = _cells(rows[0]), [_cells(r) for r in rows[2:]]
137
+ out.append("<table>")
138
+ out.append("<thead><tr>" + "".join(f"<th>{c}</th>" for c in head) + "</tr></thead>")
139
+ out.append("<tbody>")
140
+ out += ["<tr>" + "".join(f"<td>{c}</td>" for c in r) + "</tr>" for r in data]
141
+ out.append("</tbody></table>")
142
+ else:
143
+ para.append(line)
144
+ i += 1
145
+ flush()
146
+ return out
147
+
148
+
149
+ def document(title: str, lines: list[str]) -> str:
150
+ return "\n".join(["<!DOCTYPE html>", '<html lang="en">', "<head>", '<meta charset="utf-8">',
151
+ '<meta name="viewport" content="width=device-width, initial-scale=1">',
152
+ f"<title>{html.escape(title, quote=False)}</title>", f"<style>\n{CSS}\n</style>", "</head>",
153
+ "<body>", "<main>", *body(lines), "</main>", "</body>", "</html>"]) + "\n"
lean_pkg/palomar.py ADDED
@@ -0,0 +1,316 @@
1
+ # lean-pkg palomar -- build a Palomar submission bundle (no network)
2
+ """`lean-pkg palomar prepare NAME [--out DIR] [--dry-run] [--json]` (#22.3): collect what a manual
3
+ Palomar submission needs into one directory, check it, and record that it was built. Bundle only:
4
+ lean-pkg makes no HTTP request and submits nothing; the README is the staged handoff checklist.
5
+
6
+ The bundle (default `<checkout>/.lean-receipts/palomar-<HEAD12>/`):
7
+
8
+ - `formalization.yaml`: rendered by the formalization renderer, schema-valid (placeholders warn);
9
+ - `configs/<path>`: every comparator configuration tracked at HEAD, byte-identical, and the headline
10
+ configuration (headline.py) when one is declared: Palomar takes exactly one configuration per
11
+ submission and any repository path, so README.txt names the headline one for the main-results
12
+ entry and says the others are submitted separately;
13
+ - `receipts/<file>`: the recorded gate and comparator receipts, validated against HEAD (bound to it
14
+ or to an ancestor whose difference is evidence only);
15
+ - `README.txt`: the staged handoff checklist (#402): static readiness (what lean-pkg checked, not
16
+ Palomar's full preflight), the pinned full preflight, the approval fields, intake through the live
17
+ agent contract, editorial review, registration on the user's decision, and the `record` command;
18
+ - `MANIFEST.sha256`: `sha256 path` for every other file (`sha256sum -c` checks it).
19
+
20
+ Refusals (exit 1, nothing written): a missing receipt, a receipt not bound to HEAD, no consent
21
+ recorded, a render that fails the schema, any error-severity gap `palomar check` finds at HEAD (each
22
+ listed; its warn gaps are warnings, never a refusal), blocking public-safety hits in the bundle, an
23
+ existing target. The event `palomar-prepared` {commit, bundle, bundle_sha256} (the sha256 of
24
+ MANIFEST.sha256) goes to history and the event log. `--dry-run` runs every check and prints the
25
+ plan; it writes nothing.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import hashlib
31
+ import os
32
+ import pathlib
33
+ import shutil
34
+ import tempfile
35
+
36
+ from . import gate as gate_mod
37
+ from . import core
38
+
39
+ PALOMAR_URL = "https://palomar-registry.org/"
40
+ PALOMAR_SUBMISSION_URL = "https://github.com/PalomarRegistry/PalomarSubmission"
41
+ # Palomar's live agent contract: intake, proof and cleanup are linked, never copied (they change; #402).
42
+ PALOMAR_AGENT_CONTRACT_URL = "https://submit.palomar-registry.org/llms.txt"
43
+ # The full mechanical preflight; its PalomarSubmission commit is pinned by the user, from the live contract.
44
+ PALOMAR_PREFLIGHT_WORKFLOW = "PalomarRegistry/PalomarSubmission/.github/workflows/submission.yml"
45
+ PALOMAR_EXECUTION_PROFILE = "palomar-standard-v1"
46
+ HANDOFF_STAGES = ("static-readiness", "full-preflight", "approval", "intake", "editorial-review",
47
+ "registration", "record")
48
+ EVENT = "palomar-prepared"
49
+
50
+
51
+ def _write(root: pathlib.Path, rel: str, data: bytes) -> None:
52
+ p = root / rel
53
+ p.parent.mkdir(parents=True, exist_ok=True)
54
+ p.write_bytes(data)
55
+
56
+
57
+ def config_path(configs: list[str], headline: str | None) -> str:
58
+ """The configuration a submission names: the headline one, else the first tracked one."""
59
+ return headline or (configs[0] if configs else "comparator.json")
60
+
61
+
62
+ def handoff(pkg: dict, head: str, configs: list[str], headline: str | None) -> dict:
63
+ """The staged handoff checklist as data (#402; JSON `handoff`, additive): the README's stages."""
64
+ return {"stages": list(HANDOFF_STAGES),
65
+ "approval_fields": {"repository": pkg.get("repo"), "commit": head,
66
+ "comparator_config_path": config_path(configs, headline),
67
+ "authorization_relationship": None},
68
+ "agent_contract": PALOMAR_AGENT_CONTRACT_URL,
69
+ "full_preflight": {"workflow": PALOMAR_PREFLIGHT_WORKFLOW, "mode": "full",
70
+ "execution_profile": PALOMAR_EXECUTION_PROFILE}}
71
+
72
+
73
+ def readme_text(pkg: dict, head: str, configs: list[str], files: list[str], placeholders: list[str],
74
+ headline: str | None = None) -> str:
75
+ """README.txt: a staged handoff checklist (#402). lean-pkg did stage 1; the rest are the user's and
76
+ Palomar's, in order. Intake and its proof are linked to the live agent contract, never copied."""
77
+ from . import __version__
78
+ name = pkg["name"]
79
+ repo = pkg.get("repo")
80
+ cfg = config_path(configs, headline)
81
+ others = [c for c in configs if c != cfg]
82
+ lines = [
83
+ f"Palomar submission bundle for {name} at commit {head}",
84
+ f"Built by lean-pkg {__version__} on {core.now_iso()}. Nothing was submitted: lean-pkg makes no",
85
+ "network request and does none of the steps below (consent, sign-in, intake, registration).",
86
+ "Work through the stages in order; each one needs the one before it.",
87
+ "",
88
+ "1. Static readiness (done by lean-pkg)",
89
+ " lean-pkg checked, at the commit above: palomar check (no error gap), the gate and",
90
+ " comparator receipts (bound to that commit), and public-safety on this bundle.",
91
+ " This is NOT Palomar's full preflight: lean-pkg read files and built nothing.",
92
+ f" Make sure commit {head} is pushed to the public repository {repo}.",
93
+ " Check this bundle: sha256sum -c MANIFEST.sha256 (run inside this directory).",
94
+ "",
95
+ "2. Full mechanical preflight (before intake)",
96
+ f" Run the reusable workflow {PALOMAR_PREFLIGHT_WORKFLOW}",
97
+ f" with mode: full and execution_profile: {PALOMAR_EXECUTION_PROFILE}, on the repository,",
98
+ " commit and configuration of stage 3. Pin `uses:` and `pipeline_commit` to the same full",
99
+ " PalomarSubmission commit: the one the live agent contract (stage 4) names.",
100
+ " A local lake build, a repository CI job or a standalone comparator run (lean-pkg's",
101
+ " comparator receipt included) is not equivalent. Continue only on status: pass.",
102
+ "",
103
+ "3. Approval: show the user these fields before intake",
104
+ f" repository: {repo}",
105
+ f" commit: {head}",
106
+ f" comparator_config_path: {cfg}" + (" (headline: the paper's main results;" if headline else ""),
107
+ ]
108
+ if headline:
109
+ lines += [" formalization.yaml status.main_results lists its theorems)"]
110
+ lines += [" authorization_relationship: (the user states it; Palomar records it permanently)",
111
+ " Go on only on the user's explicit agreement to all four."]
112
+ if others:
113
+ lines += [" Palomar takes one configuration per submission: submit each other one separately,",
114
+ " through every stage from 2:"]
115
+ lines += [f" {c}" for c in others]
116
+ lines += [
117
+ "",
118
+ "4. Intake, proof and cleanup",
119
+ f" Follow Palomar's live agent contract: {PALOMAR_AGENT_CONTRACT_URL}",
120
+ " It describes intake, the proof of write access and the cleanup after it. They change,",
121
+ " so they are not copied here.",
122
+ f" Registry: {PALOMAR_URL}",
123
+ f" Submission layout: {PALOMAR_SUBMISSION_URL}",
124
+ "",
125
+ "5. Editorial review",
126
+ " Palomar's editors review the submission. Give the review to the user to read.",
127
+ "",
128
+ "6. Registration",
129
+ " Register only on the user's explicit decision, made after reading the review.",
130
+ "",
131
+ "7. Record the submission",
132
+ " Once Palomar returns a submission id, record it:",
133
+ f" lean-pkg record {name} palomar-submitted --field commit={head} \\",
134
+ f" --field submission_id=ID --field comparator_config={cfg}",
135
+ "",
136
+ "Files:",
137
+ ]
138
+ lines += [f" {f}" for f in files]
139
+ if placeholders:
140
+ lines += ["", "formalization.yaml still has placeholders (fill them in the repository, then rebuild):"]
141
+ lines += [f" {p}" for p in placeholders]
142
+ return "\n".join(lines) + "\n"
143
+
144
+
145
+ def build(pkg: dict, repo: pathlib.Path, stage: pathlib.Path) -> tuple[list[str], dict]:
146
+ """Fill `stage` with the bundle; (warnings, facts). Raises Fail on every refusal."""
147
+ from . import formalization as fz
148
+ from . import publish as publish_mod
149
+ name = pkg["name"]
150
+ head = core.git_head(repo)
151
+ if head is None:
152
+ raise core.Fail(f"{name}: {repo} is not a git checkout with a commit")
153
+ gate = pkg.get("gate") or {}
154
+ if not gate.get("receipt"):
155
+ raise core.Fail(f"{name}: no gate receipt recorded (lean-pkg gate {name} --receipt R)")
156
+ if not gate.get("comparator"):
157
+ raise core.Fail(f"{name}: no comparator receipt recorded (lean-pkg comparator {name} --receipt R)")
158
+ receipt = gate_mod.recorded_json(repo, gate["receipt"])
159
+ if receipt is None:
160
+ raise core.Fail(f"{name}: gate receipt {gate['receipt']} is missing or not JSON in {repo}")
161
+ comp = gate_mod.recorded_json(repo, gate["comparator"])
162
+ if comp is None:
163
+ raise core.Fail(f"{name}: comparator receipt {gate['comparator']} is missing or not JSON in {repo}")
164
+ try:
165
+ gate_mod.validate_receipt(pkg, repo, receipt)
166
+ gate_mod.validate_comparator(pkg, repo, comp, str(receipt.get("commit") or ""))
167
+ except core.Fail as e:
168
+ raise core.Fail(f"{name}: receipts not bound to HEAD {head[:12]}: {e}") from None
169
+ why = gate_mod.recorded_report_log_problem(repo, receipt, gate["receipt"])
170
+ if why:
171
+ raise core.Fail(f"{name}: gate receipt {gate['receipt']}: {why}")
172
+ mark, label = publish_mod.consent_item(pkg)
173
+ if mark != "✓":
174
+ raise core.Fail(f"{name}: {label}")
175
+ text, doc, warnings, _existing = fz.render_for(pkg, repo)
176
+ mode, errors = fz.validate_doc(doc)
177
+ if errors:
178
+ raise core.Fail(f"{name}: the rendered formalization.yaml fails the {fz.SCHEMA_VERSION} schema "
179
+ f"({mode}):\n " + "\n ".join(errors))
180
+ from . import palomar_check # error gaps refuse (#163 follow-up); warn gaps never do
181
+ try:
182
+ policy, source = palomar_check.load_rules(None)
183
+ rep = palomar_check.check(pkg, repo, head, policy, source)
184
+ except (core.Fail, OSError, ValueError) as e:
185
+ raise core.Fail(f"{name}: the Palomar readiness check could not run at HEAD {head[:12]} ({e}); "
186
+ f"nothing written") from None
187
+ if errs := palomar_check.error_gaps(rep):
188
+ raise core.Fail(f"{name}: not Palomar-ready at HEAD {head[:12]}: {len(errs)} error gap(s) need a new "
189
+ f"commit; nothing written (see lean-pkg palomar check {name} --rev {head[:12]}):\n"
190
+ + "\n".join(palomar_check.gap_lines(errs)))
191
+ warnings = list(warnings) + [f"palomar check: {g['code']}: {g['detail']}"
192
+ for g in rep["gaps"] if g["severity"] == "warn"]
193
+ placeholders = fz.find_placeholders(doc)
194
+ warnings = list(warnings) + [f"placeholder at {p} (formalization.yaml is not Palomar-ready)"
195
+ for p in placeholders]
196
+ _write(stage, "formalization.yaml", text.encode())
197
+ configs = gate_mod.head_comparator_configs(repo, "HEAD")
198
+ headline = (rep.get("headline") or {}).get("config")
199
+ if headline and not (rep.get("headline") or {}).get("covered"):
200
+ raise core.Fail(f"{name}: the headline configuration {headline} is not judged a subset of the comparison "
201
+ f"the gate binds at HEAD {head[:12]}; nothing written (see lean-pkg palomar check "
202
+ f"{name} --rev {head[:12]})")
203
+ for c in configs + ([headline] if headline and headline not in configs else []):
204
+ blob = core.git_show_bytes(repo, c, "HEAD")
205
+ _write(stage, f"configs/{c}", blob or b"")
206
+ for rel in (gate["receipt"], gate["comparator"]):
207
+ _write(stage, f"receipts/{pathlib.PurePosixPath(rel).name}", (repo / rel).read_bytes())
208
+ files = sorted(p.relative_to(stage).as_posix() for p in stage.rglob("*") if p.is_file())
209
+ _write(stage, "README.txt", readme_text(pkg, head, configs, files + ["README.txt", "MANIFEST.sha256"],
210
+ placeholders, headline).encode())
211
+ files = sorted(p.relative_to(stage).as_posix() for p in stage.rglob("*") if p.is_file())
212
+ manifest = "".join(f"{hashlib.sha256((stage / f).read_bytes()).hexdigest()} {f}\n" for f in files)
213
+ _write(stage, "MANIFEST.sha256", manifest.encode())
214
+ from . import public_safety as ps
215
+ scan = ps.scan(pkg, stage, export=True, patterns_root=repo, source_repo=repo)
216
+ nblock = scan["block_hits"]
217
+ if nblock:
218
+ hits = "\n".join(ps.hit_line(h) for h in ps.blocking(scan["hits"]))
219
+ raise core.Fail(f"{name}: public-safety: {nblock} blocking hit(s) in the bundle; nothing written:\n"
220
+ + hits)
221
+ if scan["warn_hits"]:
222
+ warnings.append(f"public-safety: {scan['warn_hits']} warning(s) in the bundle "
223
+ f"({ps.warn_families(scan['hits'])}); review them")
224
+ from . import ledger as ledger_mod
225
+ facts = {"commit": head, "configs": configs, "headline_config": headline,
226
+ "handoff": handoff(pkg, head, configs, headline),
227
+ "files": files + ["MANIFEST.sha256"],
228
+ "manuscript_findings": ledger_mod.package_findings(pkg, repo),
229
+ "bundle_sha256": hashlib.sha256(manifest.encode()).hexdigest(), "placeholders": placeholders,
230
+ "palomar_check": {"ready": True, "commit": head, "errors": 0, "warns": rep["counts"]["warn"],
231
+ "codes": sorted({g["code"] for g in rep["gaps"]}),
232
+ "command": f"lean-pkg palomar check {name} --rev {head[:12]}"},
233
+ "public_safety": {"block_hits": nblock, "warn_hits": scan["warn_hits"]}}
234
+ return warnings, facts
235
+
236
+
237
+ def do_prepare(reg_path, reg, events_p, name: str, out: str | None, dry_run: bool) -> tuple[list[str], dict, list[str]]:
238
+ pkg = core.get_pkg(reg, name)
239
+ repo = core.repo_path(pkg)
240
+ if not repo.is_dir():
241
+ raise core.Fail(f"{name}: local_path does not exist: {repo}")
242
+ head = core.git_head(repo)
243
+ if head is None:
244
+ raise core.Fail(f"{name}: {repo} is not a git checkout with a commit")
245
+ target = pathlib.Path(out).expanduser() if out else repo / ".lean-receipts" / f"palomar-{head[:12]}"
246
+ target = pathlib.Path(os.path.abspath(target))
247
+ if target.is_symlink() or (target.exists() and (not target.is_dir() or any(target.iterdir()))):
248
+ raise core.Fail(f"{name}: {target} already exists; a bundle is never overwritten (remove it, or "
249
+ f"pass --out another directory)")
250
+ try:
251
+ shown = target.relative_to(repo).as_posix()
252
+ except ValueError:
253
+ shown = str(target)
254
+ with tempfile.TemporaryDirectory(prefix="lean-pkg-palomar-") as tmp:
255
+ stage = pathlib.Path(tmp) / "bundle"
256
+ stage.mkdir()
257
+ warnings, facts = build(pkg, repo, stage)
258
+ payload = {"ok": True, "name": name, "dry_run": dry_run, "bundle": shown, **facts,
259
+ "warnings": warnings, "event": None}
260
+ lines = [f"{name}: Palomar bundle for commit {head[:12]} -> {shown}"
261
+ + (" (dry run: nothing written)" if dry_run else "")]
262
+ lines += [f" {f}" for f in facts["files"]]
263
+ lines.append(f" bundle sha256 (of MANIFEST.sha256): {facts['bundle_sha256']}")
264
+ from . import ledger as ledger_mod
265
+ fl = ledger_mod.findings_line(facts["manuscript_findings"])
266
+ if fl:
267
+ lines.append(f" {fl}")
268
+ if dry_run:
269
+ lines.append("next: run again without --dry-run, then follow README.txt in the bundle")
270
+ return lines, payload, warnings
271
+ target.parent.mkdir(parents=True, exist_ok=True)
272
+ if target.exists():
273
+ target.rmdir() # empty (checked above)
274
+ shutil.copytree(stage, target)
275
+ core.record(reg, events_p, pkg, EVENT, commit=head, bundle=shown, bundle_sha256=facts["bundle_sha256"])
276
+ core.save_registry(reg_path, reg)
277
+ payload["event"] = EVENT
278
+ lines.append(f"{name}: {EVENT} — bundle written (not committed, never submitted); follow "
279
+ f"{shown}/README.txt to submit by hand")
280
+ return lines, payload, warnings
281
+
282
+
283
+ def cmd_palomar(args) -> int:
284
+ if getattr(args, "palomar_fn", None) is None:
285
+ raise core.UsageError("palomar needs an action: prepare, check, port-modules")
286
+ reg_path, events_p = core.registry_path(args), core.events_path(args)
287
+ lines, payload, warnings = do_prepare(reg_path, core.load_registry(reg_path), events_p, args.name,
288
+ args.out, args.dry_run)
289
+ for w in warnings:
290
+ print(f"lean-pkg: warning: {w}", file=core.sys.stderr)
291
+ if getattr(args, "json_out", False):
292
+ core.print_json(payload)
293
+ else:
294
+ print("\n".join(lines))
295
+ return 0
296
+
297
+
298
+ def add_parsers(sub, add_json) -> None:
299
+ s = sub.add_parser("palomar", help="Palomar: prepare (build a submission bundle), check (read-only readiness), port-modules "
300
+ "(plan or write the module-system port); no network")
301
+ add_json(s)
302
+ s.set_defaults(fn=cmd_palomar, palomar_fn=None)
303
+ psub = s.add_subparsers(dest="palomar_cmd")
304
+ p = psub.add_parser("prepare", help="build the submission bundle (formalization.yaml, comparator configs, "
305
+ "receipts, README.txt, MANIFEST.sha256); event palomar-prepared")
306
+ p.add_argument("name")
307
+ p.add_argument("--out", default=None, metavar="DIR",
308
+ help="bundle directory (default <checkout>/.lean-receipts/palomar-<HEAD12>/); must not exist "
309
+ "or be empty")
310
+ p.add_argument("--dry-run", action="store_true", help="run every check and print the plan; write nothing")
311
+ add_json(p)
312
+ p.set_defaults(fn=cmd_palomar, palomar_fn="prepare")
313
+ from . import palomar_check
314
+ palomar_check.add_parser(psub, add_json)
315
+ from . import port_modules
316
+ port_modules.add_parser(psub, add_json)