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/anchor.py ADDED
@@ -0,0 +1,678 @@
1
+ # lean-pkg formalization anchor -- bind a companion to one posted arXiv version of its paper
2
+ """`lean-pkg formalization anchor NAME --arxiv <id>v<N> (--from-file E-PRINT | --fetch) [--compare-tex LOCAL.tex]
3
+ [--accept-diff REASON] [--main-tex PATH] [--write] [--agent A] [--json]`.
4
+
5
+ A companion released against "the paper" should say which posted version, and show that the TeX the claims
6
+ were written against is that version's source. By hand that means downloading the arXiv e-print, unpacking
7
+ it, diffing its main .tex against the local file and recording hashes. This module does those steps.
8
+
9
+ * The e-print comes from a file the user downloaded (`--from-file`, no network) or, only with `--fetch`,
10
+ from the arXiv e-print URL over HTTPS (timeout, size cap). A gzip'd tar, a gzip'd single .tex and an
11
+ uncompressed tar are read; a PDF-only submission is refused (there is no source to anchor).
12
+ * Nothing is extracted to disk: members are read into memory from the archive, and the archive is refused
13
+ outright when a member has an absolute path, a `..` component, is a link or a device/FIFO, or when the
14
+ member count or the unpacked size passes a cap.
15
+ * The record, `data/source-baselines/arXiv-<id>v<N>.json` in the package repository, is deterministic JSON:
16
+ the id and version, where the bytes came from (`retrieved_at` only when fetched), the e-print SHA-256,
17
+ one SHA-256 per .tex/.bib/.bbl/.sty file, the main .tex (the one with `\\documentclass`), the comparison
18
+ with the local .tex when one was given, and, when fetched, the arXiv API's own `published`/`updated`
19
+ timestamps (submission times; arXiv's announce date is not in the API and is never guessed).
20
+ * `--write` writes the record, sets coverage.yaml `manuscript.version` (+ `eprint_sha256`) and the
21
+ formalization.yaml source entry's `id`. It refuses unless something ties the e-print to the manuscript
22
+ the ledger is bound to: the same version already, a bound `{repo, commit, sha256}` whose SHA-256 is one
23
+ of the e-print's files, or `--compare-tex` (identical after normalisation, or differing with
24
+ `--accept-diff REASON`, which is recorded). It never writes the registry and never commits.
25
+ * Moving to another version prints the `lean-pkg claims rebase` command for the claims ledger.
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import datetime as dt
30
+ import difflib
31
+ import hashlib
32
+ import io
33
+ import json
34
+ import os
35
+ import pathlib
36
+ import re
37
+ import tarfile
38
+ import urllib.request
39
+ import zlib
40
+
41
+ from . import core
42
+ from . import coverage as cov
43
+
44
+ RECORD_SCHEMA = "source-baseline/1"
45
+ BASELINE_DIR = "data/source-baselines"
46
+ EPRINT_URL = "https://arxiv.org/e-print/{vid}"
47
+ API_URL = "https://export.arxiv.org/api/query?id_list={vid}"
48
+ FETCH_TIMEOUT = 60 # seconds, per request
49
+ MAX_EPRINT_BYTES = 64 << 20 # the downloaded (or given) e-print
50
+ MAX_API_BYTES = 1 << 20
51
+ MAX_UNPACKED_BYTES = 256 << 20 # every member together, after gunzip
52
+ MAX_MEMBERS = 5000
53
+ HASHED_SUFFIXES = (".tex", ".bib", ".bbl", ".sty")
54
+ DIFF_SHOW = 60 # diff lines printed at most
55
+ _ID_RE = r"(?:\d{4}\.\d{4,5}|[a-z][a-z-]*(?:\.[A-Z]{2})?/\d{7})"
56
+ VERSIONED_RE = re.compile(rf"^(?:arXiv:)?({_ID_RE})v([1-9]\d*)$")
57
+ UNVERSIONED_RE = re.compile(rf"^(?:arXiv:)?{_ID_RE}$")
58
+ DOCUMENTCLASS_RE = re.compile(r"^[ \t]*\\documentclass\b", re.M)
59
+
60
+
61
+ # --------------------------------------------------------------------------
62
+ # the id
63
+
64
+ def parse_arxiv(value: str) -> tuple[str, int]:
65
+ """(id, version) of `<id>v<N>` or `arXiv:<id>v<N>`; an id without its version is refused."""
66
+ v = (value or "").strip()
67
+ m = VERSIONED_RE.match(v)
68
+ if m:
69
+ return m.group(1), int(m.group(2))
70
+ if UNVERSIONED_RE.match(v):
71
+ raise core.UsageError(f"--arxiv {v}: name the version (<id>v<N>); an unversioned id is whatever arXiv "
72
+ f"serves today, so it cannot anchor anything")
73
+ raise core.UsageError(f"--arxiv: not an arXiv id with its version (<id>v<N>): {v!r}")
74
+
75
+
76
+ def versioned(aid: str, ver: int) -> str:
77
+ return f"{aid}v{ver}"
78
+
79
+
80
+ def record_rel(aid: str, ver: int) -> str:
81
+ return f"{BASELINE_DIR}/arXiv-{versioned(aid, ver).replace('/', '_')}.json"
82
+
83
+
84
+ # --------------------------------------------------------------------------
85
+ # getting the bytes
86
+
87
+ def _read_capped(stream, cap: int, what: str) -> bytes:
88
+ buf = bytearray()
89
+ while True:
90
+ chunk = stream.read(min(1 << 16, cap + 1 - len(buf)))
91
+ if not chunk:
92
+ return bytes(buf)
93
+ buf += chunk
94
+ if len(buf) > cap:
95
+ raise core.Fail(f"{what}: larger than the {cap} byte cap; refusing")
96
+
97
+
98
+ def _http_get(url: str, cap: int, timeout: int = FETCH_TIMEOUT) -> tuple[bytes, str]:
99
+ """(body, final URL) of an HTTPS GET; refuses a non-HTTPS URL, a redirect off HTTPS, a body over cap."""
100
+ from . import __version__
101
+ if not url.startswith("https://"):
102
+ raise core.Fail(f"{url}: only https:// is fetched")
103
+ req = urllib.request.Request(url, headers={"User-Agent": f"lean-pkg/{__version__} (formalization anchor)"})
104
+ try:
105
+ with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310 (https only, checked above)
106
+ final = resp.geturl()
107
+ if not final.startswith("https://"):
108
+ raise core.Fail(f"{url}: redirected off https ({final}); refusing")
109
+ length = resp.headers.get("Content-Length")
110
+ if length and length.isdigit() and int(length) > cap:
111
+ raise core.Fail(f"{url}: Content-Length {length} is over the {cap} byte cap; refusing")
112
+ return _read_capped(resp, cap, url), final
113
+ except core.Fail:
114
+ raise
115
+ except Exception as e: # urllib.error.*, socket timeouts, TLS errors
116
+ raise core.Fail(f"{url}: fetch failed: {e}") from e
117
+
118
+
119
+ def fetch_eprint(vid: str) -> bytes:
120
+ body, _final = _http_get(EPRINT_URL.format(vid=vid), MAX_EPRINT_BYTES)
121
+ return body
122
+
123
+
124
+ def fetch_api_metadata(vid: str) -> tuple[dict | None, str | None]:
125
+ """({published, updated} from the arXiv API entry of exactly this version, None) or (None, why)."""
126
+ import xml.etree.ElementTree as ET
127
+ try:
128
+ body, _final = _http_get(API_URL.format(vid=vid), MAX_API_BYTES)
129
+ except core.Fail as e:
130
+ return None, str(e)
131
+ if b"<!DOCTYPE" in body or b"<!ENTITY" in body:
132
+ return None, "the arXiv API answer declares a DTD or entities; not parsed"
133
+ ns = {"a": "http://www.w3.org/2005/Atom"}
134
+ try:
135
+ root = ET.fromstring(body)
136
+ except ET.ParseError as e:
137
+ return None, f"the arXiv API answer is not XML: {e}"
138
+ for entry in root.findall("a:entry", ns):
139
+ eid = (entry.findtext("a:id", default="", namespaces=ns) or "").strip()
140
+ if not eid.endswith("/" + vid):
141
+ continue
142
+ out = {k: (entry.findtext(f"a:{k}", default="", namespaces=ns) or "").strip()
143
+ for k in ("published", "updated")}
144
+ out = {k: v for k, v in out.items() if v}
145
+ return (out or None), (None if out else "the arXiv API entry has no published/updated")
146
+ return None, f"the arXiv API returned no entry for {vid}"
147
+
148
+
149
+ # --------------------------------------------------------------------------
150
+ # reading the e-print (in memory; nothing is written to disk)
151
+
152
+ def _gunzip(data: bytes, what: str) -> bytes:
153
+ d = zlib.decompressobj(16 + zlib.MAX_WBITS)
154
+ out = bytearray()
155
+ buf = data
156
+ try:
157
+ while buf:
158
+ out += d.decompress(buf, MAX_UNPACKED_BYTES + 1 - len(out))
159
+ if len(out) > MAX_UNPACKED_BYTES:
160
+ raise core.Fail(f"{what}: unpacks to more than {MAX_UNPACKED_BYTES} bytes; refusing")
161
+ buf = d.unconsumed_tail
162
+ if d.eof:
163
+ break
164
+ except zlib.error as e:
165
+ raise core.Fail(f"{what}: not a readable gzip stream: {e}") from e
166
+ if not d.eof:
167
+ raise core.Fail(f"{what}: truncated gzip stream")
168
+ return bytes(out)
169
+
170
+
171
+ def _gzip_name(data: bytes) -> str | None:
172
+ """The original file name in a gzip header (FNAME), if any."""
173
+ if len(data) < 10 or data[3] & 0x08 == 0:
174
+ return None
175
+ i = 10
176
+ if data[3] & 0x04: # FEXTRA
177
+ if len(data) < 12:
178
+ return None
179
+ i = 12 + int.from_bytes(data[10:12], "little")
180
+ end = data.find(b"\0", i)
181
+ if end < 0 or end - i > 255:
182
+ return None
183
+ return data[i:end].decode("latin-1")
184
+
185
+
186
+ def _is_tar(data: bytes) -> bool:
187
+ if len(data) >= 262 and data[257:262] == b"ustar":
188
+ return True
189
+ try:
190
+ with tarfile.open(fileobj=io.BytesIO(data), mode="r:") as t:
191
+ return t.next() is not None
192
+ except tarfile.TarError:
193
+ return False
194
+
195
+
196
+ def _safe_member_name(name: str) -> str:
197
+ """The normalised member path, or Fail for one that could leave a directory."""
198
+ n = name.replace("\\", "/")
199
+ if not n or n.startswith("/") or re.match(r"^[A-Za-z]:", n):
200
+ raise core.Fail(f"e-print: member {name!r} has an absolute path; refusing the archive")
201
+ parts = [p for p in n.split("/") if p not in ("", ".")]
202
+ if any(p == ".." for p in parts):
203
+ raise core.Fail(f"e-print: member {name!r} has a '..' component; refusing the archive")
204
+ if not parts:
205
+ raise core.Fail(f"e-print: member {name!r} has an empty path; refusing the archive")
206
+ return "/".join(parts)
207
+
208
+
209
+ def _tar_members(data: bytes) -> dict[str, bytes]:
210
+ files: dict[str, bytes] = {}
211
+ total = 0
212
+ try:
213
+ with tarfile.open(fileobj=io.BytesIO(data), mode="r:") as t:
214
+ for n, m in enumerate(t):
215
+ if n >= MAX_MEMBERS:
216
+ raise core.Fail(f"e-print: more than {MAX_MEMBERS} members; refusing the archive")
217
+ name = _safe_member_name(m.name)
218
+ if m.issym() or m.islnk():
219
+ raise core.Fail(f"e-print: member {m.name!r} is a link; refusing the archive")
220
+ if m.ischr() or m.isblk() or m.isfifo() or m.isdev():
221
+ raise core.Fail(f"e-print: member {m.name!r} is a device or FIFO; refusing the archive")
222
+ if m.isdir():
223
+ continue
224
+ if not m.isfile():
225
+ raise core.Fail(f"e-print: member {m.name!r} is not a regular file; refusing the archive")
226
+ total += m.size
227
+ if total > MAX_UNPACKED_BYTES:
228
+ raise core.Fail(f"e-print: members add up to more than {MAX_UNPACKED_BYTES} bytes; refusing")
229
+ if name in files:
230
+ raise core.Fail(f"e-print: member {name!r} appears twice; refusing the archive")
231
+ f = t.extractfile(m)
232
+ files[name] = f.read() if f is not None else b""
233
+ except tarfile.TarError as e:
234
+ raise core.Fail(f"e-print: not a readable tar archive: {e}") from e
235
+ return files
236
+
237
+
238
+ def unpack(data: bytes, vid: str) -> tuple[str, dict[str, bytes]]:
239
+ """(format, {path: bytes}) of an arXiv e-print: tar.gz, gz (one file) or tar. PDF-only is refused."""
240
+ pdf = ("arXiv:" + vid + " is a PDF-only submission: there is no TeX source to anchor to. Pin "
241
+ "coverage.yaml manuscript.version to it by hand; the theorem numbers then come from the PDF")
242
+ if data[:2] == b"\x1f\x8b":
243
+ raw = _gunzip(data, "e-print")
244
+ if _is_tar(raw):
245
+ return "tar.gz", _tar_members(raw)
246
+ if raw[:5] == b"%PDF-":
247
+ raise core.Fail(pdf)
248
+ name = _gzip_name(data)
249
+ if not (name and re.fullmatch(r"[A-Za-z0-9._+-]+\.tex", name)):
250
+ name = vid.replace("/", "_") + ".tex"
251
+ return "gz", {name: raw}
252
+ if data[:5] == b"%PDF-":
253
+ raise core.Fail(pdf)
254
+ if _is_tar(data):
255
+ return "tar", _tar_members(data)
256
+ raise core.Fail("e-print: neither gzip, tar nor PDF; refusing (is this the e-print of arXiv:" + vid + "?)")
257
+
258
+
259
+ def sha256(b: bytes) -> str:
260
+ return hashlib.sha256(b).hexdigest()
261
+
262
+
263
+ def _text(b: bytes) -> str:
264
+ try:
265
+ return b.decode("utf-8")
266
+ except UnicodeDecodeError:
267
+ return b.decode("latin-1")
268
+
269
+
270
+ def main_tex_candidates(files: dict[str, bytes]) -> list[str]:
271
+ """The .tex files with a `\\documentclass` line outside a comment, sorted."""
272
+ return sorted(p for p, b in files.items() if p.lower().endswith(".tex") and DOCUMENTCLASS_RE.search(_text(b)))
273
+
274
+
275
+ def pick_main_tex(files: dict[str, bytes], main_tex: str | None, local: pathlib.Path | None,
276
+ warnings: list[str]) -> str | None:
277
+ tex = sorted(p for p in files if p.lower().endswith(".tex"))
278
+ if main_tex is not None:
279
+ want = _safe_member_name(main_tex)
280
+ if want not in files:
281
+ raise core.Fail(f"--main-tex {main_tex}: not in the e-print (its .tex files: {', '.join(tex) or 'none'})")
282
+ return want
283
+ cands = main_tex_candidates(files)
284
+ if len(cands) == 1:
285
+ return cands[0]
286
+ if len(cands) > 1 and local is not None:
287
+ same = [c for c in cands if pathlib.PurePosixPath(c).name == local.name]
288
+ if len(same) == 1:
289
+ return same[0]
290
+ if len(cands) > 1:
291
+ raise core.Fail(f"e-print: {len(cands)} files carry \\documentclass ({', '.join(cands)}); "
292
+ f"name the main one with --main-tex PATH")
293
+ if local is not None:
294
+ raise core.Fail("e-print: no .tex file carries \\documentclass; name the main one with --main-tex PATH")
295
+ warnings.append("no .tex file in the e-print carries \\documentclass; main_tex is null in the record")
296
+ return None
297
+
298
+
299
+ # --------------------------------------------------------------------------
300
+ # comparing with the local .tex
301
+
302
+ def normalise(text: str) -> list[str]:
303
+ """Lines with line endings unified and trailing whitespace dropped; trailing blank lines dropped."""
304
+ lines = [x.rstrip() for x in text.splitlines()]
305
+ while lines and not lines[-1]:
306
+ lines.pop()
307
+ return lines
308
+
309
+
310
+ def compare(local_bytes: bytes, eprint_bytes: bytes, local_name: str, eprint_name: str) -> dict:
311
+ a, b = normalise(_text(local_bytes)), normalise(_text(eprint_bytes))
312
+ sm = difflib.SequenceMatcher(None, a, b, autojunk=False)
313
+ n = sum(max(i2 - i1, j2 - j1) for tag, i1, i2, j1, j2 in sm.get_opcodes() if tag != "equal")
314
+ diff = list(difflib.unified_diff(a, b, fromfile=f"local/{local_name}", tofile=f"e-print/{eprint_name}",
315
+ n=0, lineterm=""))
316
+ return {"identical": n == 0, "differing_lines": n, "local_sha256": sha256(local_bytes),
317
+ "diff": diff[:DIFF_SHOW], "diff_truncated": len(diff) > DIFF_SHOW}
318
+
319
+
320
+ # --------------------------------------------------------------------------
321
+ # the ledger's current binding, and the edits --write makes
322
+
323
+ def coverage_binding(repo: pathlib.Path) -> tuple[str | None, object]:
324
+ """(path, manuscript.version) of the working-tree coverage.yaml; (None, None) without one."""
325
+ p = repo / cov.DEFAULT_COVERAGE_FILE
326
+ if p.is_symlink():
327
+ raise core.Fail(f"{cov.DEFAULT_COVERAGE_FILE} is a symlink; refusing to read or write through it")
328
+ if not p.is_file():
329
+ return None, None
330
+ doc = cov.load_text(p.read_text(encoding="utf-8"), cov.DEFAULT_COVERAGE_FILE)
331
+ m = doc.get("manuscript")
332
+ return cov.DEFAULT_COVERAGE_FILE, (m.get("version") if isinstance(m, dict) else None)
333
+
334
+
335
+ def relation(prior, target: str, files: dict[str, str]) -> tuple[str, str]:
336
+ """(kind, detail): how the e-print relates to the ledger's bound manuscript."""
337
+ if prior is None:
338
+ return "none", "no coverage.yaml manuscript.version to compare with"
339
+ if prior == target:
340
+ return "same", f"coverage.yaml is already bound to {target}"
341
+ if prior == cov.UNPOSTED:
342
+ return "first", "coverage.yaml is bound to an unposted draft"
343
+ if isinstance(prior, dict):
344
+ hit = sorted(p for p, h in files.items() if h == prior.get("sha256"))
345
+ if hit:
346
+ return "bound-sha-match", f"the bound manuscript's sha256 is the e-print's {hit[0]}"
347
+ return "reanchor", (f"coverage.yaml is bound to {prior.get('repo')} at {str(prior.get('commit'))[:12]}, "
348
+ f"whose sha256 is none of the e-print's files")
349
+ return "reanchor", f"coverage.yaml is bound to {prior}"
350
+
351
+
352
+ _TOP_KEY = re.compile(r"^(\S[^:#]*):")
353
+
354
+
355
+ def coverage_edit(text: str, target: str, eprint_sha: str) -> str:
356
+ """coverage.yaml text with manuscript.version set to target and manuscript.eprint_sha256 set, every other
357
+ line (comments included) unchanged. Fail when the manuscript block is not in block style."""
358
+ try:
359
+ library = cov.doc_kind(cov.load_text(text, cov.DEFAULT_COVERAGE_FILE)) == "library"
360
+ except core.Fail:
361
+ library = False
362
+ if library:
363
+ raise core.Fail(f"coverage.yaml is kind library: it names no manuscript, so it is not bound to {target}; "
364
+ f"a package that formalizes a paper's results is kind paper (the default)")
365
+ lines = text.split("\n")
366
+ start = next((i for i, x in enumerate(lines) if re.match(r"^manuscript:\s*(#.*)?$", x)), None)
367
+ if start is None:
368
+ raise core.Fail("coverage.yaml: no block-style `manuscript:` mapping to edit; set manuscript.version "
369
+ f"to {target!r} by hand")
370
+ end = next((i for i in range(start + 1, len(lines)) if lines[i].strip() and not lines[i].startswith((" ", "#"))),
371
+ len(lines))
372
+ body = lines[start + 1:end]
373
+ indents = [len(x) - len(x.lstrip(" ")) for x in body if x.strip() and not x.lstrip().startswith("#")]
374
+ if not indents:
375
+ raise core.Fail("coverage.yaml: the manuscript mapping is empty")
376
+ ind = min(indents)
377
+
378
+ def key_span(key: str) -> tuple[int, int] | None:
379
+ for j, x in enumerate(body):
380
+ if re.match(rf"^ {{{ind}}}{key}\s*:", x):
381
+ k = j + 1
382
+ while k < len(body) and (not body[k].strip() or len(body[k]) - len(body[k].lstrip(" ")) > ind):
383
+ k += 1
384
+ while k > j + 1 and not body[k - 1].strip():
385
+ k -= 1
386
+ return j, k
387
+ return None
388
+
389
+ pad = " " * ind
390
+ v = key_span("version")
391
+ if v is None:
392
+ raise core.Fail("coverage.yaml: manuscript has no version key to edit")
393
+ body[v[0]:v[1]] = [f'{pad}version: "{target}"']
394
+ s = key_span("eprint_sha256")
395
+ if s is not None:
396
+ body[s[0]:s[1]] = [f'{pad}eprint_sha256: "{eprint_sha}"']
397
+ else:
398
+ v = key_span("version")
399
+ body.insert(v[1], f'{pad}eprint_sha256: "{eprint_sha}"')
400
+ out = "\n".join(lines[:start + 1] + body + lines[end:])
401
+ doc = cov.load_text(out, "coverage.yaml (edited)")
402
+ errors: list[str] = []
403
+ cov._manuscript_errors(doc.get("manuscript"), errors)
404
+ m = doc.get("manuscript") or {}
405
+ if errors or m.get("version") != target or m.get("eprint_sha256") != eprint_sha:
406
+ raise core.Fail("coverage.yaml: the edited manuscript block does not read back as intended "
407
+ f"({'; '.join(errors) or 'value mismatch'}); edit it by hand")
408
+ return out
409
+
410
+
411
+ def _arxiv_base(idv) -> str | None:
412
+ """The bare arXiv id an identifier names (arXiv:<id>, <id>v<N>, an arxiv.org/abs URL), else None."""
413
+ if not isinstance(idv, str):
414
+ return None
415
+ s = re.sub(r"^https?://(?:www\.)?(?:export\.)?arxiv\.org/(?:abs|pdf)/", "", idv.strip())
416
+ m = re.match(rf"^(?:arXiv:)?({_ID_RE})(?:v\d+)?(?:\.pdf)?$", s, re.I)
417
+ return m.group(1) if m else None
418
+
419
+
420
+ def formalization_edit(path: pathlib.Path, aid: str, target: str, warnings: list[str]) -> tuple[str, str] | None:
421
+ """(old text, new text) of formalization.yaml with its source entry's id set to target, validated against
422
+ v0.4; None (with a warning) when there is no file or no single entry to set."""
423
+ from . import formalization as fz
424
+ text, doc = fz.load_existing(path)
425
+ if doc is None:
426
+ warnings.append(f"{path.name}: absent; render it (`lean-pkg formalization NAME --write`) and re-run "
427
+ f"the anchor to set its source id")
428
+ return None
429
+ sources = doc.get("sources") if isinstance(doc.get("sources"), list) else []
430
+ same = [s for s in sources if isinstance(s, dict) and _arxiv_base(s.get("id")) == aid]
431
+ open_ = [s for s in sources if isinstance(s, dict) and s.get("relationship") == "formalizes"
432
+ and (not s.get("id") or fz._is_placeholder(s.get("id")))]
433
+ pick = same if same else open_
434
+ if len(pick) != 1:
435
+ warnings.append(f"{path.name}: {len(pick) or 'no'} source entr{'y' if len(pick) == 1 else 'ies'} to anchor "
436
+ f"(one naming arXiv:{aid}, else one `formalizes` entry without an id); set "
437
+ f"sources[].id: {target} by hand")
438
+ return None
439
+ reformatted = fz.dump_doc(doc) != text
440
+ if pick[0].get("id") == target:
441
+ return text, text # already anchored: leave the bytes alone
442
+ pick[0]["id"] = target
443
+ mode, errors = fz.validate_doc(doc)
444
+ if errors:
445
+ raise core.Fail(f"{path.name}: with the anchored source id the file fails the {fz.SCHEMA_VERSION} schema "
446
+ f"({mode}):\n " + "\n ".join(errors))
447
+ new = fz.dump_doc(doc)
448
+ if reformatted:
449
+ warnings.append(f"{path.name}: re-serialised by the renderer's dumper (hand formatting and comments in "
450
+ f"it are not kept)")
451
+ return text, new
452
+
453
+
454
+ def baseline_problems(doc: dict, repo: pathlib.Path) -> tuple[list[str], list[str]]:
455
+ """(errors, warnings) of coverage.yaml manuscript.eprint_sha256 against the source-baseline record tracked
456
+ at HEAD (coverage check calls this)."""
457
+ m = doc.get("manuscript") or {}
458
+ sha = m.get("eprint_sha256")
459
+ v = m.get("version")
460
+ if not sha or not isinstance(v, str):
461
+ return [], []
462
+ parsed = VERSIONED_RE.match(v)
463
+ if not parsed:
464
+ return [], []
465
+ rel = record_rel(parsed.group(1), int(parsed.group(2)))
466
+ raw = core.git_show_bytes(repo, rel)
467
+ if raw is None:
468
+ return [], [f"manuscript.eprint_sha256: no source-baseline record {rel} is committed at HEAD "
469
+ f"(`lean-pkg formalization anchor` writes it)"]
470
+ try:
471
+ rec = json.loads(raw)
472
+ got = rec["eprint"]["sha256"]
473
+ except (ValueError, KeyError, TypeError):
474
+ return [f"{rel} at HEAD is not a {RECORD_SCHEMA} record"], []
475
+ if got != sha:
476
+ return [f"manuscript.eprint_sha256 {sha[:12]} is not the e-print sha256 {str(got)[:12]} in {rel} at HEAD"], []
477
+ return [], []
478
+
479
+
480
+ # --------------------------------------------------------------------------
481
+ # the command
482
+
483
+ def _safe_target(repo: pathlib.Path, rel: str) -> pathlib.Path:
484
+ """repo/rel, refusing a symlink anywhere on the way (the record never lands outside the repository)."""
485
+ p = repo
486
+ for part in pathlib.PurePosixPath(rel).parts:
487
+ p = p / part
488
+ if p.is_symlink():
489
+ raise core.Fail(f"{p.relative_to(repo)} is a symlink; refusing to write through it")
490
+ return p
491
+
492
+
493
+ def _atomic_write(path: pathlib.Path, text: str) -> None:
494
+ path.parent.mkdir(parents=True, exist_ok=True)
495
+ tmp = path.with_name(path.name + ".tmp")
496
+ tmp.write_text(text, encoding="utf-8")
497
+ os.replace(tmp, path)
498
+
499
+
500
+ def do_anchor(reg: dict, name: str, *, arxiv: str, from_file: str | None, fetch: bool,
501
+ compare_tex: str | None, accept_diff: str | None, main_tex: str | None, write: bool,
502
+ agent: str | None) -> tuple[list[str], dict, list[str]]:
503
+ """(stdout lines, payload, stderr warnings)."""
504
+ aid, ver = parse_arxiv(arxiv)
505
+ vid = versioned(aid, ver)
506
+ target = f"arXiv:{vid}"
507
+ if bool(from_file) == bool(fetch):
508
+ raise core.UsageError("formalization anchor: give exactly one source: --from-file E-PRINT (offline) or "
509
+ "--fetch (downloads the e-print from arXiv over HTTPS)")
510
+ if accept_diff is not None and not compare_tex:
511
+ raise core.UsageError("--accept-diff goes with --compare-tex (it accepts the differences shown)")
512
+ if accept_diff is not None and not accept_diff.strip():
513
+ raise core.UsageError("--accept-diff needs a reason")
514
+ pkg = core.get_pkg(reg, name)
515
+ repo = core.repo_path(pkg)
516
+ if not repo.is_dir():
517
+ raise core.Fail(f"{name}: local_path does not exist: {repo}")
518
+ warnings: list[str] = []
519
+ local = pathlib.Path(compare_tex) if compare_tex else None
520
+ if local is not None and not local.is_file():
521
+ raise core.Fail(f"--compare-tex {compare_tex}: no such file")
522
+
523
+ source: dict
524
+ if from_file:
525
+ fp = pathlib.Path(from_file)
526
+ if not fp.is_file():
527
+ raise core.Fail(f"--from-file {from_file}: no such file")
528
+ if fp.stat().st_size > MAX_EPRINT_BYTES:
529
+ raise core.Fail(f"--from-file {from_file}: larger than the {MAX_EPRINT_BYTES} byte cap; refusing")
530
+ data = fp.read_bytes()
531
+ source = {"kind": "file", "file_name": fp.name}
532
+ else:
533
+ data = fetch_eprint(vid)
534
+ source = {"kind": "fetched", "url": EPRINT_URL.format(vid=vid),
535
+ "retrieved_at": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")}
536
+ fmt, members = unpack(data, vid)
537
+ file_hashes = {p: sha256(b) for p, b in members.items()}
538
+ main = pick_main_tex(members, main_tex, local, warnings)
539
+
540
+ record: dict = {
541
+ "schema": RECORD_SCHEMA,
542
+ "arxiv": {"id": aid, "version": ver, "versioned_id": vid},
543
+ "source": source,
544
+ "eprint": {"sha256": sha256(data), "bytes": len(data), "format": fmt, "members": len(members)},
545
+ "files": [{"path": p, "sha256": file_hashes[p], "bytes": len(members[p])}
546
+ for p in sorted(members) if p.lower().endswith(HASHED_SUFFIXES)],
547
+ "main_tex": main,
548
+ }
549
+ if fetch:
550
+ meta, why = fetch_api_metadata(vid)
551
+ if meta:
552
+ record["arxiv_api"] = meta
553
+ else:
554
+ warnings.append(f"arXiv API metadata omitted: {why}")
555
+
556
+ cmp = None
557
+ if local is not None:
558
+ cmp = compare(local.read_bytes(), members[main], local.name, main)
559
+ record["compare"] = {"local_tex": local.name, "local_sha256": cmp["local_sha256"], "eprint_tex": main,
560
+ "identical": cmp["identical"], "differing_lines": cmp["differing_lines"]}
561
+ if not cmp["identical"] and accept_diff is not None:
562
+ record["compare"]["accepted_diff"] = accept_diff.strip()
563
+ elif cmp["identical"] and accept_diff is not None:
564
+ warnings.append("--accept-diff ignored: the files are identical after normalisation")
565
+
566
+ cov_rel, prior = coverage_binding(repo)
567
+ rel_kind, rel_detail = relation(prior, target, file_hashes)
568
+ tied = rel_kind in ("same", "bound-sha-match") or (cmp is not None and (cmp["identical"] or accept_diff))
569
+ rebase = None
570
+ if rel_kind == "reanchor":
571
+ old = prior if isinstance(prior, str) else f"{prior.get('repo')}@{str(prior.get('commit'))[:12]}"
572
+ rebase = (f"lean-pkg claims rebase {name} --from-tex <main .tex of {old}> --to-tex "
573
+ + (str(compare_tex) if compare_tex else f"<main .tex of {target}>"))
574
+
575
+ rrel = record_rel(aid, ver)
576
+ record_text = json.dumps(record, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
577
+ rpath = _safe_target(repo, rrel)
578
+ if rpath.is_file():
579
+ try:
580
+ old = json.loads(rpath.read_text(encoding="utf-8"))
581
+ old_sha = old["eprint"]["sha256"]
582
+ except (ValueError, KeyError, TypeError):
583
+ raise core.Fail(f"{rrel} exists and is not a {RECORD_SCHEMA} record; move it aside first") from None
584
+ if old_sha != record["eprint"]["sha256"]:
585
+ raise core.Fail(f"{rrel} records e-print sha256 {old_sha[:12]}, these bytes are "
586
+ f"{record['eprint']['sha256'][:12]}: an arXiv version does not change, so one of the "
587
+ f"two is not the e-print of {target}; nothing written")
588
+
589
+ payload = {"ok": True, "name": name, "arxiv": target, "eprint_sha256": record["eprint"]["sha256"],
590
+ "format": fmt, "main_tex": main, "files": record["files"], "source": source["kind"],
591
+ "compare": ({k: cmp[k] for k in ("identical", "differing_lines", "diff", "diff_truncated")}
592
+ if cmp else None),
593
+ "ledger": {"coverage": cov_rel, "bound": prior, "relation": rel_kind, "detail": rel_detail},
594
+ "tied": bool(tied), "record_path": rrel, "record": record, "written": [], "write": write,
595
+ "rebase_command": rebase, "registry_source_paper": None, "warnings": warnings}
596
+
597
+ head = (f"{name}: anchor {target}: e-print {fmt}, {len(members)} file(s), sha256 {record['eprint']['sha256'][:12]}"
598
+ f", main tex {main or 'none'}")
599
+ lines = [head]
600
+ if cmp is not None:
601
+ if cmp["identical"]:
602
+ lines.append(f" compare: {local.name} is identical to {main} (normalised: line endings, trailing "
603
+ f"whitespace, trailing blank lines)")
604
+ else:
605
+ lines.append(f" compare: {local.name} differs from {main} in {cmp['differing_lines']} line(s):")
606
+ lines += [f" {x}" for x in cmp["diff"]]
607
+ if cmp["diff_truncated"]:
608
+ lines.append(f" ... (first {DIFF_SHOW} diff lines shown)")
609
+ lines.append(f" ledger: {rel_detail}")
610
+
611
+ sp = pkg.get("source_paper") if isinstance(pkg.get("source_paper"), dict) else {}
612
+ if sp.get("arxiv") != vid:
613
+ payload["registry_source_paper"] = f"lean-pkg update {name} --source-paper-arxiv {vid}"
614
+ lines.append(f" registry: source_paper.arxiv is {sp.get('arxiv')!r}; this command never writes the "
615
+ f"registry: run `{payload['registry_source_paper']}`")
616
+
617
+ if not tied:
618
+ why = ("--compare-tex shows differences; pass --accept-diff REASON to anchor anyway (the reason is "
619
+ "recorded)" if cmp is not None else
620
+ "nothing ties the e-print to the manuscript the ledger is bound to: pass --compare-tex LOCAL.tex "
621
+ "(the .tex the claims were written against)")
622
+ if write:
623
+ raise core.Fail(f"{name}: anchor {target} refused: {why}; nothing written")
624
+ lines.append(f" --write would refuse: {why}")
625
+
626
+ edits: list[tuple[str, pathlib.Path, str]] = [(rrel, rpath, record_text)]
627
+ from . import formalization as fz
628
+ frel = fz.target_rel(pkg)
629
+ try:
630
+ if cov_rel:
631
+ cpath = repo / cov_rel
632
+ edits.append((cov_rel, cpath, coverage_edit(cpath.read_text(encoding="utf-8"), target,
633
+ record["eprint"]["sha256"])))
634
+ else:
635
+ warnings.append(f"no {cov.DEFAULT_COVERAGE_FILE} in the package: set manuscript.version: \"{target}\" "
636
+ f"when you write one")
637
+ fe = formalization_edit(_safe_target(repo, frel), aid, target, warnings)
638
+ if fe is not None:
639
+ edits.append((frel, repo / frel, fe[1]))
640
+ except core.Fail as e:
641
+ if write:
642
+ raise core.Fail(f"{e}; nothing written") from e
643
+ lines.append(f" --write would refuse: {e}")
644
+
645
+ changed = [(r, p, t) for r, p, t in edits if not (p.is_file() and p.read_text(encoding="utf-8") == t)]
646
+ payload["would_write"] = [r for r, _p, _t in changed]
647
+ if not write:
648
+ lines.append(f" dry run: --write would write {', '.join(payload['would_write']) or 'nothing (all current)'}")
649
+ else:
650
+ if changed:
651
+ core.refuse_invalid_lease(name, pkg.get("lease"))
652
+ lease = pkg.get("lease")
653
+ if core.lease_live(lease, dt.datetime.now(dt.timezone.utc)) and agent != lease.get("agent"):
654
+ raise core.Fail(f"{name}: lease held by {lease.get('agent')}; pass --agent {lease.get('agent')}; "
655
+ f"nothing written")
656
+ for _r, p, t in changed:
657
+ _atomic_write(p, t)
658
+ payload["written"] = [r for r, _p, _t in changed]
659
+ lines.append(f" wrote {', '.join(payload['written'])} (not committed; commit it yourself)"
660
+ if changed else " nothing to write: the record and the files are already anchored")
661
+ if rebase:
662
+ lines.append(f" re-anchor: rebase the claims ledger onto the new text: {rebase}")
663
+ return lines, payload, warnings
664
+
665
+
666
+ def cmd_anchor(args) -> int:
667
+ reg = core.load_registry(core.registry_path(args))
668
+ lines, payload, warnings = do_anchor(
669
+ reg, args.package, arxiv=args.arxiv, from_file=args.from_file, fetch=args.fetch,
670
+ compare_tex=args.compare_tex, accept_diff=args.accept_diff, main_tex=args.main_tex,
671
+ write=args.write, agent=args.agent)
672
+ for w in warnings:
673
+ print(f"lean-pkg: warning: {w}", file=core.sys.stderr)
674
+ if getattr(args, "json_out", False):
675
+ core.print_json(payload)
676
+ else:
677
+ print("\n".join(lines))
678
+ return 0