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/rebase.py ADDED
@@ -0,0 +1,984 @@
1
+ # lean-pkg claims rebase -- move claims.yaml and coverage.yaml to a new manuscript version (#6)
2
+ """`lean-pkg claims rebase NAME --from-tex OLD.tex --to-tex NEW.tex --to-aux NEW.aux [...]`.
3
+
4
+ A formalization is bound to one manuscript version: coverage.yaml rows name its theorem numbers and TeX
5
+ labels, manuscript findings name a label, a page and a TeX line. When the paper moves (a private draft
6
+ becomes the arXiv version, v1 becomes v2) the numbers move with it. `claims rebase` compares, for every
7
+ label the package refers to, the statement environment in OLD and in NEW and classifies it:
8
+
9
+ unchanged the normalized statement text is identical: the row is carried and its number,
10
+ page and line are re-keyed from NEW and NEW.aux
11
+ changed the text (or the environment) differs: needs review, the row is left as it was
12
+ missing the label is not in NEW: needs review
13
+ moved-into-proof the label was a statement in OLD and sits inside a proof in NEW: needs review
14
+ not-in-old the package names a label OLD does not define (the ledger was not bound to OLD)
15
+ unsupported the label is not inside a statement or equation environment in OLD
16
+ unnumbered unchanged, but NEW.aux has no number for it (a stale .aux): needs review
17
+
18
+ Nothing is changed in place and no claim status is ever changed: the proposed claims.yaml and
19
+ coverage.yaml, a JSON and a Markdown report with the old and new excerpts of every row that needs
20
+ review, the excerpts and diffs as files, and a MANIFEST.sha256 over all of them are written to a new
21
+ --out-dir (never an existing, non-empty one). Without --out-dir nothing is written. Findings are
22
+ carried with `fixed_in` exactly as it was: rebase never decides that a new version fixes anything.
23
+
24
+ OLD.tex is bound to the package: its SHA-256 must equal the manuscript sha256 coverage.yaml records
25
+ (manuscript.version {repo, commit, sha256}) or, for an arXiv version, a .tex hash of the source-baseline
26
+ record `formalization anchor` committed for it; when none is recorded, --from-sha256 HEX must state it.
27
+ TeX that cannot be read (not UTF-8, unbalanced begin/end) and a label the package refers to that is
28
+ defined twice (in OLD, NEW or NEW.aux) are refused.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import bisect
34
+ import difflib
35
+ import hashlib
36
+ import json
37
+ import os
38
+ import pathlib
39
+ import re
40
+
41
+ import yaml
42
+
43
+ from . import core
44
+ from . import sites
45
+
46
+ REPORT_SCHEMA = "claims-rebase/1"
47
+ STATUSES = ("unchanged", "changed", "missing", "moved-into-proof", "not-in-old", "unsupported", "unnumbered")
48
+ CARRIED = ("unchanged",)
49
+ # Theorem-like environments recognised without a \newtheorem in the file (and their starred forms).
50
+ STATEMENT_ENVS = ("theorem", "lemma", "proposition", "corollary", "definition", "remark", "conjecture",
51
+ "assumption", "hypothesis", "example", "claim", "notation", "problem", "question", "fact",
52
+ "observation", "condition")
53
+ EQUATION_ENVS = ("equation", "align", "gather", "multline", "flalign", "alignat", "eqnarray", "subequations")
54
+ PROOF_ENVS = ("proof",)
55
+ IGNORED_ENVS = ("comment",) # LaTeX never sees a label inside these
56
+ NORMALIZATIONS = (
57
+ "TeX comments removed (an unescaped % to the end of its line)",
58
+ "label commands removed",
59
+ "\\textcolor[model]{colour}{X} and \\colorbox[model]{colour}{X} replaced by X",
60
+ "a group {\\color{colour} X} replaced by X, and every other \\color[model]{colour} removed",
61
+ "each --unwrap-macro NAME: \\NAME{X} replaced by X",
62
+ "an unescaped ~ read as a space",
63
+ "every run of whitespace collapsed to one space; spaces just inside { and } removed",
64
+ "trailing . , ; : at the very end of the statement removed",
65
+ )
66
+ NAME_RE = re.compile(r"^[A-Za-z]+$")
67
+ ARXIV_TO_RE = re.compile(r"^arXiv:(?:\d{4}\.\d{4,5}|[a-z-]+(?:\.[A-Z]{2})?/\d{7})v\d+$")
68
+ HEX40 = re.compile(r"^[0-9a-f]{40}$")
69
+ HEX64 = re.compile(r"^[0-9a-f]{64}$")
70
+ _ENV_TOKEN = re.compile(r"\\(begin|end)\s*\{([^{}]*)\}|\\label\s*\{([^{}]*)\}")
71
+ _NEWTHEOREM = re.compile(r"\\(?:sp)?newtheorem\*?\s*\{([^{}]+)\}\s*(?:\[[^\]]*\]\s*)?\{([^{}]*)\}"
72
+ r"|\\declaretheorem\s*(?:\[[^\]]*\]\s*)?\{([^{}]+)\}")
73
+ _INPUT = re.compile(r"\\(?:input|include)\s*\{")
74
+ _NUM_BOUND_L = r"(?<![A-Za-z0-9.])"
75
+ _NUM_BOUND_R = r"(?![A-Za-z0-9]|\.[A-Za-z0-9])"
76
+ NUM_TOKEN_RE = re.compile(_NUM_BOUND_L + r"(?:[A-Z](?:\.\d+)+|\d+(?:\.\d+)*[a-z]?)" + _NUM_BOUND_R)
77
+ EXCERPT_MD_MAX = 3000
78
+
79
+
80
+ def sha256_bytes(b: bytes) -> str:
81
+ return hashlib.sha256(b).hexdigest()
82
+
83
+
84
+ # --------------------------------------------------------------------------
85
+ # TeX: comments, environments, labels
86
+
87
+ def mask_comments(text: str) -> str:
88
+ """`text` with every TeX comment (an unescaped % to the end of its line) replaced by spaces, so
89
+ offsets and line numbers stay those of the original."""
90
+ out = []
91
+ for line in text.split("\n"):
92
+ i, cut = 0, None
93
+ while i < len(line):
94
+ ch = line[i]
95
+ if ch == "\\":
96
+ i += 2
97
+ continue
98
+ if ch == "%":
99
+ cut = i
100
+ break
101
+ i += 1
102
+ out.append(line if cut is None else line[:cut] + " " * (len(line) - cut))
103
+ return "\n".join(out)
104
+
105
+
106
+ def group_end(s: str, i: int) -> int | None:
107
+ """Index just after the brace group opening at s[i] == '{' (escaped braces skipped), else None."""
108
+ if i >= len(s) or s[i] != "{":
109
+ return None
110
+ depth, j = 0, i
111
+ while j < len(s):
112
+ ch = s[j]
113
+ if ch == "\\":
114
+ j += 2
115
+ continue
116
+ if ch == "{":
117
+ depth += 1
118
+ elif ch == "}":
119
+ depth -= 1
120
+ if depth == 0:
121
+ return j + 1
122
+ j += 1
123
+ return None
124
+
125
+
126
+ class Env:
127
+ __slots__ = ("name", "begin", "body", "end", "after", "line", "parent")
128
+
129
+ def __init__(self, name, begin, body, line, parent):
130
+ self.name, self.begin, self.body, self.line, self.parent = name, begin, body, line, parent
131
+ self.end = self.after = None
132
+
133
+
134
+ class Tex:
135
+ """One manuscript file: its environments, labels and theorem-like environment names."""
136
+
137
+ def __init__(self, raw: bytes, where: str):
138
+ try:
139
+ self.text = raw.decode("utf-8")
140
+ except UnicodeDecodeError as e:
141
+ raise core.Fail(f"{where}: not UTF-8 text ({e.reason} at byte {e.start}); refusing to compare it") from e
142
+ self.where = where
143
+ self.sha256 = sha256_bytes(raw)
144
+ self.masked = mask_comments(self.text)
145
+ self._nl = [i for i, ch in enumerate(self.text) if ch == "\n"]
146
+ self.theorem_names: dict[str, str] = {}
147
+ for m in _NEWTHEOREM.finditer(self.masked):
148
+ env = (m.group(1) or m.group(3) or "").strip()
149
+ if env:
150
+ self.theorem_names[env] = (m.group(2) or env).strip()
151
+ self.inputs = len(_INPUT.findall(self.masked))
152
+ self.labels: dict[str, list[tuple[int, Env | None]]] = {}
153
+ stack: list[Env] = []
154
+ for m in _ENV_TOKEN.finditer(self.masked):
155
+ if m.group(3) is not None:
156
+ self.labels.setdefault(m.group(3).strip(), []).append((m.start(), stack[-1] if stack else None))
157
+ elif m.group(1) == "begin":
158
+ stack.append(Env(m.group(2).strip(), m.start(), m.end(), self.line_of(m.start()),
159
+ stack[-1] if stack else None))
160
+ else:
161
+ name = m.group(2).strip()
162
+ if not stack or stack[-1].name != name:
163
+ opened = f"\\begin{{{stack[-1].name}}} of line {stack[-1].line}" if stack else "no open environment"
164
+ raise core.Fail(f"{where}: line {self.line_of(m.start())}: \\end{{{name}}} closes {opened}; "
165
+ f"refusing unbalanced TeX")
166
+ env = stack.pop()
167
+ env.end, env.after = m.start(), m.end()
168
+ if stack:
169
+ raise core.Fail(f"{where}: \\begin{{{stack[-1].name}}} of line {stack[-1].line} is never closed; "
170
+ f"refusing unbalanced TeX")
171
+
172
+ def line_of(self, pos: int) -> int:
173
+ return bisect.bisect_left(self._nl, pos) + 1
174
+
175
+ def is_statement(self, name: str) -> bool:
176
+ base = name.rstrip("*")
177
+ return base in STATEMENT_ENVS or name in self.theorem_names or base in self.theorem_names
178
+
179
+ @staticmethod
180
+ def is_equation(name: str) -> bool:
181
+ return name.rstrip("*") in EQUATION_ENVS
182
+
183
+ def display_name(self, env: str) -> str:
184
+ return self.theorem_names.get(env) or self.theorem_names.get(env.rstrip("*")) or env.rstrip("*")
185
+
186
+ def defined(self) -> dict[str, list[tuple[int, Env | None]]]:
187
+ """Labels LaTeX would define: those inside an IGNORED_ENVS environment dropped."""
188
+ if getattr(self, "_defined", None) is not None:
189
+ return self._defined
190
+ out = {}
191
+ for lab, lab_sites in self.labels.items():
192
+ keep = [s for s in lab_sites if not any(e.name in IGNORED_ENVS for e in _ancestors(s[1]))]
193
+ if keep:
194
+ out[lab] = keep
195
+ self._defined = out
196
+ return out
197
+
198
+ def site(self, label: str) -> dict | None:
199
+ """The label's single site: {owner env, in_proof, line, label_line, raw, excerpt}; None when absent."""
200
+ sites = self.defined().get(label)
201
+ if not sites:
202
+ return None
203
+ pos, env = sites[0]
204
+ owner = next((e for e in _ancestors(env) if self.is_statement(e.name) or self.is_equation(e.name)), None)
205
+ in_proof = any(e.name.rstrip("*") in PROOF_ENVS for e in _ancestors(env))
206
+ out = {"label_line": self.line_of(pos), "in_proof": in_proof, "env": None, "kind": None,
207
+ "line": None, "end_line": None, "body": None, "masked_body": None, "excerpt": None}
208
+ if owner is not None:
209
+ out.update(env=owner.name, kind="statement" if self.is_statement(owner.name) else "equation",
210
+ line=owner.line, end_line=self.line_of(owner.after),
211
+ body=self.text[owner.body:owner.end], masked_body=self.masked[owner.body:owner.end],
212
+ excerpt=self.text[owner.begin:owner.after])
213
+ elif env is not None: # no statement or equation around it: show the environment it sits in
214
+ out["excerpt"] = self.text[env.begin:env.after]
215
+ return out
216
+
217
+
218
+ def _ancestors(env: Env | None):
219
+ while env is not None:
220
+ yield env
221
+ env = env.parent
222
+
223
+
224
+ # --------------------------------------------------------------------------
225
+ # normalization: exactly NORMALIZATIONS, in that order
226
+
227
+ def _unwrap(s: str, name: str, mode: str) -> str:
228
+ """Rewrite each \\NAME (not followed by a letter): mode 'keep1' keeps the content of its one argument,
229
+ 'drop1keep2' drops the first argument and keeps the second's content, 'drop1' removes the command and
230
+ its argument. An optional [..] argument right after the name is dropped. Malformed uses are left."""
231
+ rx = re.compile(r"\\" + name + r"(?![A-Za-z])")
232
+ for _ in range(10000):
233
+ changed = False
234
+ for m in reversed(list(rx.finditer(s))):
235
+ j = m.end()
236
+ while j < len(s) and s[j] in " \t\n":
237
+ j += 1
238
+ if j < len(s) and s[j] == "[":
239
+ k = s.find("]", j)
240
+ if k < 0:
241
+ continue
242
+ j = k + 1
243
+ while j < len(s) and s[j] in " \t\n":
244
+ j += 1
245
+ e1 = group_end(s, j)
246
+ if e1 is None:
247
+ continue
248
+ if mode == "keep1":
249
+ s = s[:m.start()] + s[j + 1:e1 - 1] + s[e1:]
250
+ elif mode == "drop1":
251
+ s = s[:m.start()] + s[e1:]
252
+ else:
253
+ k = e1
254
+ while k < len(s) and s[k] in " \t\n":
255
+ k += 1
256
+ e2 = group_end(s, k)
257
+ if e2 is None:
258
+ continue
259
+ s = s[:m.start()] + s[k + 1:e2 - 1] + s[e2:]
260
+ changed = True
261
+ break
262
+ if not changed:
263
+ return s
264
+ return s
265
+
266
+
267
+ def _unwrap_color_groups(s: str) -> str:
268
+ rx = re.compile(r"\{\s*\\color(?![A-Za-z])")
269
+ for _ in range(10000):
270
+ hit = None
271
+ for m in rx.finditer(s):
272
+ e = group_end(s, m.start())
273
+ if e is not None:
274
+ hit = (m.start(), e)
275
+ if hit is None:
276
+ return s
277
+ a, e = hit
278
+ s = s[:a] + _unwrap(s[a + 1:e - 1], "color", "drop1") + s[e:]
279
+ return s
280
+
281
+
282
+ def normalize(masked_body: str, unwrap_macros: tuple[str, ...] = ()) -> str:
283
+ """The statement text compared between versions (comments are already masked by Tex)."""
284
+ s = re.sub(r"\\label\s*\{[^{}]*\}", " ", masked_body)
285
+ s = _unwrap(s, "textcolor", "drop1keep2")
286
+ s = _unwrap(s, "colorbox", "drop1keep2")
287
+ s = _unwrap_color_groups(s)
288
+ s = _unwrap(s, "color", "drop1")
289
+ for name in unwrap_macros:
290
+ s = _unwrap(s, name, "keep1")
291
+ s = re.sub(r"(?<!\\)~", " ", s)
292
+ s = " ".join(s.split())
293
+ s = re.sub(r"(?<!\\)\{ ", "{", s)
294
+ s = re.sub(r"(?<!\\) \}", "}", s)
295
+ s = re.sub(r"[\s.,;:]+$", "", s)
296
+ return s.strip()
297
+
298
+
299
+ # --------------------------------------------------------------------------
300
+ # .aux: \newlabel{LABEL}{{NUMBER}{PAGE}...}
301
+
302
+ def parse_aux(raw: bytes, where: str) -> dict[str, list[dict]]:
303
+ try:
304
+ text = raw.decode("utf-8")
305
+ except UnicodeDecodeError:
306
+ text = raw.decode("latin-1")
307
+ out: dict[str, list[dict]] = {}
308
+ for m in re.finditer(r"\\newlabel\s*\{", text):
309
+ a = m.end() - 1
310
+ e1 = group_end(text, a)
311
+ if e1 is None:
312
+ continue
313
+ label = text[a + 1:e1 - 1].strip()
314
+ e2 = group_end(text, e1)
315
+ if e2 is None:
316
+ continue
317
+ inner = text[e1 + 1:e2 - 1]
318
+ fields, j = [], 0
319
+ while j < len(inner) and len(fields) < 4:
320
+ if inner[j] == "{":
321
+ ej = group_end(inner, j)
322
+ if ej is None:
323
+ break
324
+ fields.append(inner[j + 1:ej - 1])
325
+ j = ej
326
+ else:
327
+ j += 1
328
+ if not fields:
329
+ continue
330
+ number = " ".join(re.sub(r"\\relax\b", " ", fields[0]).split())
331
+ page_s = fields[1].strip() if len(fields) > 1 else ""
332
+ out.setdefault(label, []).append({"number": number or None, "page_text": page_s or None,
333
+ "page": int(page_s) if page_s.isdigit() and int(page_s) >= 1 else None,
334
+ "anchor": fields[3].strip() if len(fields) > 3 else None})
335
+ return out
336
+
337
+
338
+ # --------------------------------------------------------------------------
339
+ # what the package refers to
340
+
341
+ def _num_tokens(s: str, exact: str | None = None) -> list[re.Match]:
342
+ rx = re.compile(_NUM_BOUND_L + re.escape(exact) + _NUM_BOUND_R) if exact else NUM_TOKEN_RE
343
+ return list(rx.finditer(s))
344
+
345
+
346
+ def rekey_number(text: str, old: str | None, new: str) -> tuple[str | None, str]:
347
+ """(re-keyed text or None, how): the one number token of `text` (the old .aux number when known)
348
+ replaced by `new`; None when there is not exactly one."""
349
+ toks = _num_tokens(text, old)
350
+ if len(toks) != 1:
351
+ what = f"the old number {old!r}" if old else "a number"
352
+ return None, f"{text!r} holds {len(toks)} occurrence(s) of {what}, not exactly one"
353
+ m = toks[0]
354
+ return text[:m.start()] + new + text[m.end():], "re-keyed"
355
+
356
+
357
+ def resolve_by_number(text: str, old_aux: dict | None, old_tex: Tex) -> tuple[str | None, str]:
358
+ """A TeX label for a reference written as a number ("Lemma 4.2", "(3.7)"), through OLD's .aux: the
359
+ labels whose old number is the one number token, narrowed by the word before it (the environment's
360
+ display name) or by parentheses (an equation). (label, how) or (None, why not)."""
361
+ if old_aux is None:
362
+ return None, "no TeX label, and no --from-aux to look its number up in"
363
+ toks = _num_tokens(text)
364
+ if len(toks) != 1:
365
+ return None, f"{text!r} holds {len(toks)} number(s), not exactly one"
366
+ num = toks[0].group(0)
367
+ cands = sorted(lab for lab, v in old_aux.items() if len(v) == 1 and v[0]["number"] == num
368
+ and old_tex.defined().get(lab))
369
+ if len(cands) > 1:
370
+ word = text[:toks[0].start()].strip().split()
371
+ paren = text[:toks[0].start()].rstrip().endswith("(")
372
+ narrowed = []
373
+ for lab in cands:
374
+ site = old_tex.site(lab)
375
+ if site is None or site["env"] is None:
376
+ continue
377
+ if paren and site["kind"] == "equation":
378
+ narrowed.append(lab)
379
+ elif word and site["kind"] == "statement" and \
380
+ old_tex.display_name(site["env"]).lower() == word[-1].lower():
381
+ narrowed.append(lab)
382
+ cands = narrowed
383
+ if len(cands) != 1:
384
+ return None, f"old number {num!r} matches {len(cands)} label(s) in the old .aux"
385
+ return cands[0], f"number {num} via the old .aux"
386
+
387
+
388
+ def references(claims_doc: dict, cov: dict | None, old_tex: Tex, old_aux: dict | None) -> list[dict]:
389
+ """Every place the package refers to the manuscript, in file order: coverage rows, manuscript
390
+ findings, TeX labels named in a claim's citation."""
391
+ refs = []
392
+ old_labels = sorted(old_tex.defined(), key=lambda x: (-len(x), x))
393
+ for i, r in enumerate((cov or {}).get("rows") or []):
394
+ p = r.get("paper") or {}
395
+ if p.get("label"):
396
+ lab, how = p["label"], "label"
397
+ else:
398
+ lab, how = resolve_by_number(str(p.get("number") or ""), old_aux, old_tex)
399
+ refs.append({"source": "coverage", "where": f"coverage rows[{i}]", "index": i,
400
+ "text": p.get("number"), "label": lab, "resolved": how})
401
+ for ci, c in enumerate(claims_doc.get("claims") or []):
402
+ if not isinstance(c, dict):
403
+ continue
404
+ for fi, f in enumerate(c.get("manuscript_findings") or []):
405
+ if not isinstance(f, dict) or not isinstance(f.get("location"), dict):
406
+ continue
407
+ text = str(f["location"].get("label") or "")
408
+ if text in old_tex.defined():
409
+ lab, how = text, "label"
410
+ else:
411
+ lab, how = resolve_by_number(text, old_aux, old_tex)
412
+ refs.append({"source": "finding", "where": f"{c.get('id')} finding {f.get('id')}", "claim": ci,
413
+ "finding": fi, "text": text, "label": lab, "resolved": how})
414
+ cit = c.get("citation")
415
+ if isinstance(cit, str):
416
+ for lab in old_labels:
417
+ if re.search(r"(?<![\w:.-])" + re.escape(lab) + r"(?![\w:.-])", cit):
418
+ refs.append({"source": "citation", "where": f"{c.get('id')} citation", "claim": ci,
419
+ "text": cit, "label": lab, "resolved": "label"})
420
+ return refs
421
+
422
+
423
+ # --------------------------------------------------------------------------
424
+ # classification
425
+
426
+ def classify(label: str, old: Tex, new: Tex, new_aux: dict, old_aux: dict | None,
427
+ unwrap_macros: tuple[str, ...]) -> dict:
428
+ o, n = old.site(label), new.site(label)
429
+ entry = {"label": label, "status": None, "reasons": [], "old": None, "new": None,
430
+ "old_number": None, "new_number": None, "new_page": None, "new_page_text": None}
431
+ if old_aux and old_aux.get(label):
432
+ entry["old_number"] = old_aux[label][0]["number"]
433
+ if new_aux.get(label):
434
+ a = new_aux[label][0]
435
+ entry.update(new_number=a["number"], new_page=a["page"], new_page_text=a["page_text"])
436
+
437
+ def side(s):
438
+ if s is None:
439
+ return None
440
+ return {"env": s["env"], "kind": s["kind"], "line": s["line"], "end_line": s["end_line"],
441
+ "label_line": s["label_line"], "in_proof": s["in_proof"],
442
+ "normalized_sha256": sha256_bytes(normalize(s["masked_body"], unwrap_macros).encode())
443
+ if s["masked_body"] is not None else None}
444
+ entry["old"], entry["new"] = side(o), side(n)
445
+ if o is None:
446
+ entry["status"] = "not-in-old"
447
+ entry["reasons"].append("the package names this label but the old TeX does not define it")
448
+ elif o["env"] is None:
449
+ entry["status"] = "unsupported"
450
+ entry["reasons"].append("in the old TeX the label is not inside a statement or equation environment")
451
+ elif n is None:
452
+ entry["status"] = "missing"
453
+ entry["reasons"].append("the new TeX does not define this label")
454
+ elif n["in_proof"] and not o["in_proof"]:
455
+ entry["status"] = "moved-into-proof"
456
+ entry["reasons"].append(f"the label now sits inside a proof (new line {n['label_line']})")
457
+ elif n["env"] != o["env"]:
458
+ entry["status"] = "changed"
459
+ entry["reasons"].append(f"environment {o['env']} -> {n['env'] or 'none'}")
460
+ elif normalize(o["masked_body"], unwrap_macros) != normalize(n["masked_body"], unwrap_macros):
461
+ entry["status"] = "changed"
462
+ entry["reasons"].append("the normalized statement text differs")
463
+ elif not entry["new_number"]:
464
+ entry["status"] = "unnumbered"
465
+ entry["reasons"].append("unchanged, but the new .aux has no number for it (rebuild the .aux)")
466
+ else:
467
+ entry["status"] = "unchanged"
468
+ entry["identical"] = o["excerpt"] == n["excerpt"]
469
+ entry.setdefault("identical", False)
470
+ entry["_old"], entry["_new"] = o, n
471
+ return entry
472
+
473
+
474
+ # --------------------------------------------------------------------------
475
+ # the rebase itself: pure, on loaded documents
476
+
477
+ def _duplicates(label_set, *maps) -> list[str]:
478
+ out = []
479
+ for where, m in maps:
480
+ for lab in sorted(label_set):
481
+ k = len(m.get(lab) or [])
482
+ if k > 1:
483
+ out.append(f"{where}: label {lab!r} is defined {k} times")
484
+ return out
485
+
486
+
487
+ def rebase(claims_doc: dict, cov: dict | None, old_raw: bytes, new_raw: bytes, new_aux_raw: bytes,
488
+ old_aux_raw: bytes | None = None, *, from_sha256: str | None = None, to_version=None,
489
+ unwrap_macros: tuple[str, ...] = (), names: dict | None = None,
490
+ baseline_record: dict | None = None) -> dict:
491
+ """Classify every reference and build the proposals. Returns {report, claims, coverage, excerpts}."""
492
+ import copy
493
+ names = names or {}
494
+ old = Tex(old_raw, names.get("from_tex", "OLD.tex"))
495
+ new = Tex(new_raw, names.get("to_tex", "NEW.tex"))
496
+ recorded, accepted, bound_by = None, set(), None
497
+ if cov is not None and isinstance((cov.get("manuscript") or {}).get("version"), dict):
498
+ recorded = cov["manuscript"]["version"].get("sha256")
499
+ accepted, bound_by = {recorded}, "coverage.yaml manuscript.version.sha256"
500
+ elif baseline_record is not None:
501
+ accepted = baseline_tex_hashes(baseline_record)
502
+ recorded = baseline_record.get("main_sha256")
503
+ bound_by = f"the source-baseline record {baseline_record.get('rel')} (its .tex files)"
504
+ if bound_by is not None and old.sha256 not in accepted:
505
+ raise core.Fail(f"baseline mismatch: {names.get('from_tex', 'OLD.tex')} has SHA-256 {old.sha256}, which "
506
+ f"{bound_by} does not record; refusing to rebase from another file")
507
+ if bound_by is None and from_sha256 is None:
508
+ raise core.Fail("no manuscript sha256 is recorded in coverage.yaml (an arXiv or unposted version, or no "
509
+ "coverage.yaml): pass --from-sha256 HEX, the SHA-256 of the TeX file the claims were "
510
+ f"written against (this file's is {old.sha256})")
511
+ if from_sha256 is not None and from_sha256 != old.sha256:
512
+ raise core.Fail(f"baseline mismatch: --from-sha256 {from_sha256} is not the SHA-256 of "
513
+ f"{names.get('from_tex', 'OLD.tex')} ({old.sha256}); refusing")
514
+ new_aux = parse_aux(new_aux_raw, names.get("to_aux", "NEW.aux"))
515
+ old_aux = parse_aux(old_aux_raw, names.get("from_aux", "OLD.aux")) if old_aux_raw is not None else None
516
+ refs = references(claims_doc, cov, old, old_aux)
517
+ labels = sorted({r["label"] for r in refs if r["label"]})
518
+ dups = _duplicates(labels, (names.get("from_tex", "OLD.tex"), old.defined()),
519
+ (names.get("to_tex", "NEW.tex"), new.defined()), (names.get("to_aux", "NEW.aux"), new_aux))
520
+ if old_aux is not None:
521
+ dups += _duplicates(labels, (names.get("from_aux", "OLD.aux"), old_aux))
522
+ if dups:
523
+ raise core.Fail("ambiguous labels, refusing:\n " + "\n ".join(dups))
524
+ entries = {lab: classify(lab, old, new, new_aux, old_aux, unwrap_macros) for lab in labels}
525
+
526
+ claims_out = copy.deepcopy(claims_doc)
527
+ cov_out = copy.deepcopy(cov) if cov is not None else None
528
+ review: list[dict] = []
529
+ rows: list[dict] = []
530
+ findings: list[dict] = []
531
+ citations: list[dict] = []
532
+ for r in refs:
533
+ e = entries.get(r["label"]) if r["label"] else None
534
+ st = e["status"] if e else "unresolved"
535
+ item = {"where": r["where"], "label": r["label"], "status": st, "text": r["text"],
536
+ "resolved": r["resolved"], "proposed": None, "notes": []}
537
+ if e is None:
538
+ item["notes"].append(r["resolved"])
539
+ review.append({"where": r["where"], "label": None, "status": "unresolved",
540
+ "reason": r["resolved"]})
541
+ elif st not in CARRIED:
542
+ review.append({"where": r["where"], "label": r["label"], "status": st,
543
+ "reason": "; ".join(e["reasons"])})
544
+ if r["source"] == "coverage":
545
+ row = cov_out["rows"][r["index"]]
546
+ if e is not None and st in CARRIED:
547
+ new_text, how = rekey_number(str(row["paper"]["number"]), e["old_number"], e["new_number"])
548
+ if new_text is None:
549
+ item["notes"].append(f"number not re-keyed: {how}")
550
+ review.append({"where": r["where"], "label": r["label"], "status": "unchanged",
551
+ "reason": f"statement unchanged but the number was not re-keyed: {how}; "
552
+ f"set it to {e['new_number']} by hand"})
553
+ else:
554
+ row["paper"]["number"] = new_text
555
+ item["proposed"] = new_text
556
+ rows.append(item)
557
+ elif r["source"] == "finding":
558
+ f = claims_out["claims"][r["claim"]]["manuscript_findings"][r["finding"]]
559
+ loc = f["location"]
560
+ item.update(kind=f.get("kind"), fixed_in=f.get("fixed_in"))
561
+ if e is not None and st in CARRIED:
562
+ prop = dict(loc)
563
+ if r["resolved"] != "label":
564
+ t, how = rekey_number(str(loc["label"]), e["old_number"], e["new_number"])
565
+ if t is None:
566
+ item["notes"].append(f"location.label not re-keyed: {how}")
567
+ review.append({"where": r["where"], "label": r["label"], "status": "unchanged",
568
+ "reason": f"statement unchanged but location.label was not re-keyed: {how}"})
569
+ else:
570
+ prop["label"] = t
571
+ if loc.get("page") is not None:
572
+ prop["page"] = e["new_page"]
573
+ if e["new_page"] is None:
574
+ item["notes"].append(f"page set to null: the new .aux page {e['new_page_text']!r} is "
575
+ f"not a positive integer")
576
+ if loc.get("tex_line") is not None:
577
+ o, n = e["_old"], e["_new"]
578
+ if e["identical"] and o["line"] <= loc["tex_line"] <= o["end_line"]:
579
+ prop["tex_line"] = loc["tex_line"] - o["line"] + n["line"]
580
+ else:
581
+ prop["tex_line"] = None
582
+ item["notes"].append("tex_line set to null: the environment is not byte-identical, or "
583
+ "the old line is outside it, so the new line is not known")
584
+ if "location" in f:
585
+ f["location"] = prop
586
+ item["proposed"] = prop
587
+ if f.get("kind") == "misprint":
588
+ item["notes"].append("the statement is unchanged in the new version: the misprint is still "
589
+ "printed (fixed_in left as it was)")
590
+ elif e is not None:
591
+ item["notes"].append("the label's statement changed or moved: check whether the new version "
592
+ "fixes this finding; rebase never sets fixed_in")
593
+ findings.append(item)
594
+ else:
595
+ citations.append(item)
596
+ # claim citations that spell an old number which moved: reported, never rewritten
597
+ by_claim_labels: dict[str, set] = {}
598
+ claim_ids = [c.get("id") for c in claims_doc.get("claims") or [] if isinstance(c, dict)]
599
+ for r in refs:
600
+ if r["source"] == "coverage" and r["label"]:
601
+ for cid in (cov["rows"][r["index"]].get("claims") or []):
602
+ by_claim_labels.setdefault(cid, set()).add(r["label"])
603
+ elif r["source"] in ("finding", "citation") and r["label"]:
604
+ by_claim_labels.setdefault(claims_doc["claims"][r["claim"]].get("id"), set()).add(r["label"])
605
+ for c in claims_doc.get("claims") or []:
606
+ cit = c.get("citation") if isinstance(c, dict) else None
607
+ if not isinstance(cit, str):
608
+ continue
609
+ for lab in sorted(by_claim_labels.get(c.get("id"), ())):
610
+ e = entries[lab]
611
+ olds = {e["old_number"]} if e["old_number"] else set()
612
+ for rr in refs:
613
+ if rr["source"] == "coverage" and rr["label"] == lab and rr["text"]:
614
+ olds |= {m.group(0) for m in _num_tokens(str(rr["text"]))}
615
+ for num in sorted(olds):
616
+ if e["new_number"] and num != e["new_number"] and _num_tokens(cit, num):
617
+ citations.append({"where": f"{c.get('id')} citation", "label": lab, "status": e["status"],
618
+ "text": cit, "resolved": "number", "proposed": None,
619
+ "notes": [f"mentions the old number {num}; the new number is "
620
+ f"{e['new_number']} (citations are never rewritten)"]})
621
+ dropped_eprint = False
622
+ if cov_out is not None and to_version is not None:
623
+ cov_out["manuscript"]["version"] = to_version(new.sha256) if callable(to_version) else to_version
624
+ if cov_out["manuscript"].pop("eprint_sha256", None) is not None:
625
+ dropped_eprint = True
626
+ # the invariant this command exists to keep
627
+ before = [(c.get("id"), c.get("status")) for c in claims_doc.get("claims") or [] if isinstance(c, dict)]
628
+ after = [(c.get("id"), c.get("status")) for c in claims_out.get("claims") or [] if isinstance(c, dict)]
629
+ assert before == after, "claims rebase must never change a claim status"
630
+ assert [f.get("fixed_in") for c in claims_doc.get("claims") or [] for f in (c.get("manuscript_findings") or [])] \
631
+ == [f.get("fixed_in") for c in claims_out.get("claims") or [] for f in (c.get("manuscript_findings") or [])]
632
+ counts = {s: sum(1 for e in entries.values() if e["status"] == s) for s in STATUSES}
633
+ warnings = []
634
+ for t in (old, new):
635
+ if t.inputs:
636
+ warnings.append(f"{t.where}: {t.inputs} \\input/\\include command(s) not followed: labels defined in "
637
+ f"other files count as missing (flatten the manuscript first)")
638
+ if dropped_eprint:
639
+ warnings.append("manuscript.eprint_sha256 named the old e-print and was dropped from the proposal: anchor the "
640
+ "new version with `lean-pkg formalization anchor` once it is posted")
641
+ seen, uniq = set(), []
642
+ for x in review:
643
+ key = (x["where"], x["label"], x["status"], x["reason"])
644
+ if key not in seen:
645
+ seen.add(key)
646
+ uniq.append(x)
647
+ public_entries = []
648
+ for lab in labels:
649
+ e = entries[lab]
650
+ public_entries.append({k: v for k, v in e.items() if not k.startswith("_")})
651
+ report = {"schema": REPORT_SCHEMA, "ok": not uniq, "claim_ids": claim_ids,
652
+ "inputs": {"from_tex": {"name": names.get("from_tex"), "sha256": old.sha256},
653
+ "to_tex": {"name": names.get("to_tex"), "sha256": new.sha256},
654
+ "to_aux": {"name": names.get("to_aux"), "sha256": sha256_bytes(new_aux_raw)},
655
+ "from_aux": None if old_aux_raw is None else
656
+ {"name": names.get("from_aux"), "sha256": sha256_bytes(old_aux_raw)}},
657
+ "baseline": {"bound_by": bound_by, "recorded_sha256": recorded, "from_sha256": from_sha256,
658
+ "matches": True},
659
+ "normalizations": list(NORMALIZATIONS) + ([f"unwrapped macros: {', '.join(unwrap_macros)}"]
660
+ if unwrap_macros else []),
661
+ "counts": counts, "labels": public_entries, "rows": rows, "findings": findings,
662
+ "citations": citations, "needs_review": uniq, "statuses_changed": 0, "warnings": warnings,
663
+ "to_version": cov_out["manuscript"]["version"] if cov_out is not None else None}
664
+ excerpts = []
665
+ for lab in labels:
666
+ e = entries[lab]
667
+ if e["status"] in CARRIED:
668
+ continue
669
+ o, n = e["_old"], e["_new"]
670
+ excerpts.append({"label": lab, "status": e["status"],
671
+ "old": o["excerpt"] if o else None, "new": n["excerpt"] if n else None,
672
+ "new_context": None if n is None or n["excerpt"] is not None else
673
+ _context(new, n["label_line"])})
674
+ return {"report": report, "claims": claims_out, "coverage": cov_out, "excerpts": excerpts}
675
+
676
+
677
+ def baseline_tex_hashes(record: dict) -> set[str]:
678
+ """The SHA-256s a source-baseline/1 record (`formalization anchor`) ties to its arXiv version: every .tex
679
+ file of the e-print, and the local .tex it was compared with when identical or accepted."""
680
+ out = {f.get("sha256") for f in record.get("files") or [] if isinstance(f, dict)
681
+ and str(f.get("path") or "").endswith(".tex") and isinstance(f.get("sha256"), str)}
682
+ cmp = record.get("compare")
683
+ if isinstance(cmp, dict) and isinstance(cmp.get("local_sha256"), str) and \
684
+ (cmp.get("identical") or cmp.get("accepted_diff")):
685
+ out.add(cmp["local_sha256"])
686
+ return out
687
+
688
+
689
+ def _context(tex: Tex, line: int, radius: int = 6) -> str:
690
+ lines = tex.text.split("\n")
691
+ a, b = max(0, line - 1 - radius), min(len(lines), line + radius)
692
+ return "\n".join(lines[a:b])
693
+
694
+
695
+ # --------------------------------------------------------------------------
696
+ # rendering and the packet
697
+
698
+ def _safe(label: str) -> str:
699
+ return re.sub(r"[^A-Za-z0-9._-]+", "_", label).strip("_") or "label"
700
+
701
+
702
+ def claims_text(name: str, doc: dict) -> str:
703
+ from . import claims as claims_mod
704
+ return (f"# Proposed by `lean-pkg claims rebase {name}`: review rebase-report.md first. No claim status was\n"
705
+ f"# changed and no fixed_in was set; copy this over claims.yaml only after the review.\n"
706
+ + claims_mod.dump_claims(doc))
707
+
708
+
709
+ def coverage_text(name: str, doc: dict) -> str:
710
+ return (f"# Proposed by `lean-pkg claims rebase {name}`: review rebase-report.md first; rows that need\n"
711
+ f"# review are left exactly as they were.\n"
712
+ + yaml.safe_dump(doc, sort_keys=False, default_flow_style=False, allow_unicode=True, width=100))
713
+
714
+
715
+ def report_md(name: str, rep: dict, excerpts: list[dict]) -> str:
716
+ c = rep["counts"]
717
+ out = [f"# claims rebase: {name}", "",
718
+ f"- old TeX: `{rep['inputs']['from_tex']['name']}` sha256 `{rep['inputs']['from_tex']['sha256']}`",
719
+ f"- new TeX: `{rep['inputs']['to_tex']['name']}` sha256 `{rep['inputs']['to_tex']['sha256']}`",
720
+ f"- new .aux: `{rep['inputs']['to_aux']['name']}` sha256 `{rep['inputs']['to_aux']['sha256']}`"]
721
+ if rep["inputs"]["from_aux"]:
722
+ out.append(f"- old .aux: `{rep['inputs']['from_aux']['name']}` sha256 `{rep['inputs']['from_aux']['sha256']}`")
723
+ out += ["", "No claim status was changed. No finding's `fixed_in` was set.", "",
724
+ "Labels: " + ", ".join(f"{n} {s}" for s, n in c.items() if n) if any(c.values()) else "Labels: none",
725
+ "", "## Normalization (exactly this, nothing else)", ""]
726
+ out += [f"- {x}" for x in rep["normalizations"]]
727
+ out += ["", f"## Needs review ({len(rep['needs_review'])})", ""]
728
+ out += [f"- `{x['where']}` label `{x['label']}`: **{x['status']}**: {x['reason']}" for x in rep["needs_review"]] \
729
+ or ["Nothing: every reference was carried."]
730
+ out += ["", "## Carried and re-keyed", ""]
731
+ carried = [x for x in rep["rows"] + rep["findings"] if x["proposed"] is not None]
732
+ for x in carried:
733
+ p = x["proposed"]
734
+ shown = p if isinstance(p, str) else json.dumps(p, sort_keys=True)
735
+ out.append(f"- `{x['where']}` (`{x['label']}`): {x['text']!r} -> {shown}")
736
+ if not carried:
737
+ out.append("Nothing was re-keyed.")
738
+ cits = [x for x in rep["citations"] if x["notes"]]
739
+ if cits:
740
+ out += ["", "## Citations (never rewritten)", ""]
741
+ out += [f"- `{x['where']}`: {'; '.join(x['notes'])}" for x in cits]
742
+ notes = [x for x in rep["rows"] + rep["findings"] if x["notes"]]
743
+ if notes:
744
+ out += ["", "## Notes", ""]
745
+ out += [f"- `{x['where']}`: {'; '.join(x['notes'])}" for x in notes]
746
+ if rep["warnings"]:
747
+ out += ["", "## Warnings", ""] + [f"- {w}" for w in rep["warnings"]]
748
+ if excerpts:
749
+ out += ["", "## Excerpts", ""]
750
+ for _i, x in enumerate(excerpts, 1):
751
+ out += [f"### {x['label']} ({x['status']})", ""]
752
+ for side in ("old", "new"):
753
+ body = x[side] if x[side] is not None else (x["new_context"] if side == "new" else None)
754
+ if body is None:
755
+ out += [f"{side}: (not present)", ""]
756
+ continue
757
+ cut = body if len(body) <= EXCERPT_MD_MAX else body[:EXCERPT_MD_MAX] + "\n... (truncated; see review/)"
758
+ out += [f"{side}:", "", "```tex", cut.rstrip("\n"), "```", ""]
759
+ return "\n".join(out).rstrip("\n") + "\n"
760
+
761
+
762
+ def packet_files(name: str, result: dict) -> dict[str, str]:
763
+ """{relative path: text} of everything the out-dir holds except MANIFEST.sha256."""
764
+ rep = result["report"]
765
+ files = {"claims.yaml": claims_text(name, result["claims"]),
766
+ "rebase-report.json": json.dumps(rep, indent=2, sort_keys=True, ensure_ascii=False) + "\n",
767
+ "rebase-report.md": report_md(name, rep, result["excerpts"])}
768
+ if result["coverage"] is not None:
769
+ files["coverage.yaml"] = coverage_text(name, result["coverage"])
770
+ for i, x in enumerate(result["excerpts"], 1):
771
+ stem = f"review/{i:03d}-{_safe(x['label'])}"
772
+ old = x["old"]
773
+ new = x["new"] if x["new"] is not None else x["new_context"]
774
+ if old is not None:
775
+ files[f"{stem}.old.tex"] = old.rstrip("\n") + "\n"
776
+ if new is not None:
777
+ files[f"{stem}.new.tex"] = new.rstrip("\n") + "\n"
778
+ diff = difflib.unified_diff((old or "").splitlines(keepends=True), (new or "").splitlines(keepends=True),
779
+ "old", "new")
780
+ files[f"{stem}.diff"] = "".join(d if d.endswith("\n") else d + "\n" for d in diff)
781
+ return files
782
+
783
+
784
+ def manifest(files: dict[str, str]) -> str:
785
+ return "".join(f"{sha256_bytes(files[p].encode())} {p}\n" for p in sorted(files))
786
+
787
+
788
+ def write_packet(out_dir: pathlib.Path, files: dict[str, str]) -> list[dict]:
789
+ if out_dir.exists() and (not out_dir.is_dir() or any(out_dir.iterdir())):
790
+ raise core.Fail(f"--out-dir {out_dir}: exists and is not an empty directory; a review packet is never "
791
+ f"overwritten (choose a new directory)")
792
+ allf = dict(files)
793
+ allf["MANIFEST.sha256"] = manifest(files)
794
+ for rel in sorted(allf):
795
+ p = out_dir / rel
796
+ p.parent.mkdir(parents=True, exist_ok=True)
797
+ p.write_text(allf[rel], encoding="utf-8")
798
+ for rel in sorted(allf):
799
+ os.chmod(out_dir / rel, 0o444)
800
+ return [{"path": rel, "sha256": sha256_bytes(allf[rel].encode())} for rel in sorted(allf)]
801
+
802
+
803
+ # --------------------------------------------------------------------------
804
+ # CLI
805
+
806
+ def _read(path: str, what: str) -> bytes:
807
+ p = pathlib.Path(path).expanduser()
808
+ if not p.is_file():
809
+ raise core.Fail(f"{what} {path}: no such file")
810
+ try:
811
+ return p.read_bytes()
812
+ except OSError as e:
813
+ raise core.Fail(f"{what} {path}: unreadable ({e.strerror})") from e
814
+
815
+
816
+ def _inputs(pkg: dict, repo: pathlib.Path, claims_file: str | None, coverage_file: str | None):
817
+ from . import claims as claims_mod
818
+ from . import coverage as cov_mod
819
+ name = pkg["name"]
820
+ if claims_file is not None:
821
+ raw = _read(claims_file, "--claims-file")
822
+ cwhere = pathlib.Path(claims_file).name
823
+ else:
824
+ rel = pkg.get("claims_file") or claims_mod.DEFAULT_CLAIMS_FILE
825
+ raw = core.git_show_bytes(repo, rel)
826
+ if raw is None:
827
+ raise core.Fail(f"{name}: {rel} is not committed at HEAD; nothing to rebase")
828
+ cwhere = f"{rel} at HEAD"
829
+ cdoc = claims_mod.load_claims_text(raw.decode("utf-8", errors="replace"), cwhere)
830
+ errors = claims_mod.validate_claims(cdoc, name)
831
+ if errors:
832
+ raise core.Fail(f"{cwhere} is not a valid claims/1 file:\n " + "\n ".join(errors[:10]))
833
+ if coverage_file is None and core.git_show_bytes(repo, cov_mod.DEFAULT_COVERAGE_FILE) is None:
834
+ return cdoc, cwhere, None, None
835
+ cov, vwhere = cov_mod.read_doc(pkg, repo, coverage_file)
836
+ errors = cov_mod.validate(cov, name, sites.for_repo(repo))
837
+ if errors:
838
+ raise core.Fail(f"{vwhere} is not a valid {cov_mod.COVERAGE_SCHEMA} file:\n " + "\n ".join(errors))
839
+ if cov_mod.doc_kind(cov) == "library": # names no manuscript: nothing in it moves with the paper
840
+ return cdoc, cwhere, None, None
841
+ return cdoc, cwhere, cov, vwhere
842
+
843
+
844
+ def baseline_record_at_head(repo: pathlib.Path, cov: dict | None) -> dict | None:
845
+ """The source-baseline record of coverage.yaml's arXiv version committed at HEAD, with its path as `rel`;
846
+ None when the version is not arXiv or no record is committed. An unreadable record refuses."""
847
+ from . import anchor
848
+ v = ((cov or {}).get("manuscript") or {}).get("version")
849
+ m = re.match(r"^arXiv:(.+)v(\d+)$", v) if isinstance(v, str) else None
850
+ if not m:
851
+ return None
852
+ rel = anchor.record_rel(m.group(1), int(m.group(2)))
853
+ raw = core.git_show_bytes(repo, rel)
854
+ if raw is None:
855
+ return None
856
+ try:
857
+ rec = json.loads(raw)
858
+ except ValueError:
859
+ raise core.Fail(f"{rel} at HEAD is not JSON; refusing to guess what the baseline is") from None
860
+ if not isinstance(rec, dict):
861
+ raise core.Fail(f"{rel} at HEAD is not a source-baseline record")
862
+ return {**rec, "rel": rel}
863
+
864
+
865
+ def _to_version(args, cov: dict | None):
866
+ if args.to_version and (args.to_commit or args.to_repo):
867
+ raise core.UsageError("--to-version and --to-commit/--to-repo are alternatives; pass one")
868
+ if args.to_version:
869
+ if not ARXIV_TO_RE.match(args.to_version):
870
+ raise core.UsageError(f"--to-version must be arXiv:<id>v<N>, got {args.to_version!r}")
871
+ return args.to_version
872
+ if args.to_repo and not args.to_commit:
873
+ raise core.UsageError("--to-repo needs --to-commit")
874
+ if args.to_commit:
875
+ if not HEX40.match(args.to_commit):
876
+ raise core.UsageError("--to-commit must be a full 40-hex commit")
877
+ old = ((cov or {}).get("manuscript") or {}).get("version")
878
+ repo = args.to_repo or (old.get("repo") if isinstance(old, dict) else None)
879
+ if not repo:
880
+ raise core.UsageError("--to-commit needs --to-repo URL (coverage.yaml names no manuscript repo)")
881
+ return lambda sha: {"repo": repo, "commit": args.to_commit, "sha256": sha}
882
+ return None
883
+
884
+
885
+ def do_rebase(reg: dict, args) -> tuple[list[str], dict, int]:
886
+ from . import coverage as cov_mod
887
+ pkg, repo = cov_mod.package_checkout(reg, args.name)
888
+ for m in args.unwrap_macro or []:
889
+ if not NAME_RE.match(m) or m in ("label", "begin", "end"):
890
+ raise core.UsageError(f"--unwrap-macro takes a macro name without the backslash (letters only), got {m!r}")
891
+ if args.from_sha256 is not None and not HEX64.match(args.from_sha256):
892
+ raise core.UsageError("--from-sha256 must be 64 lowercase hex characters")
893
+ cdoc, cwhere, cov, vwhere = _inputs(pkg, repo, args.claims_file, args.coverage_file)
894
+ to_version = _to_version(args, cov)
895
+ record = baseline_record_at_head(repo, cov)
896
+ if args.out_dir and cov is not None and to_version is None:
897
+ raise core.UsageError("the proposed coverage.yaml must name the new manuscript: pass --to-version "
898
+ "arXiv:<id>v<N> or --to-commit HEX [--to-repo URL]")
899
+ names = {"from_tex": pathlib.Path(args.from_tex).name, "to_tex": pathlib.Path(args.to_tex).name,
900
+ "to_aux": pathlib.Path(args.to_aux).name,
901
+ "from_aux": pathlib.Path(args.from_aux).name if args.from_aux else None}
902
+ result = rebase(cdoc, cov, _read(args.from_tex, "--from-tex"), _read(args.to_tex, "--to-tex"),
903
+ _read(args.to_aux, "--to-aux"), _read(args.from_aux, "--from-aux") if args.from_aux else None,
904
+ from_sha256=args.from_sha256, to_version=to_version,
905
+ unwrap_macros=tuple(args.unwrap_macro or ()), names=names, baseline_record=record)
906
+ rep = result["report"]
907
+ from . import claims as claims_mod
908
+ proposed_errors = [f"claims.yaml: {e}" for e in claims_mod.validate_claims(result["claims"], args.name)]
909
+ if result["coverage"] is not None:
910
+ proposed_errors += [f"coverage.yaml: {e}" for e in cov_mod.validate(result["coverage"], args.name,
911
+ sites.for_repo(repo))]
912
+ rep["proposed_errors"] = proposed_errors
913
+ rep["inputs"]["claims_file"] = {"where": cwhere}
914
+ if vwhere and args.coverage_file:
915
+ vwhere = pathlib.Path(args.coverage_file).name
916
+ rep["inputs"]["coverage_file"] = {"where": vwhere} if vwhere else None
917
+ ok = rep["ok"] and not proposed_errors
918
+ rep["ok"] = ok
919
+ files = packet_files(args.name, result)
920
+ written = []
921
+ if args.out_dir:
922
+ written = write_packet(pathlib.Path(args.out_dir), files)
923
+ c = rep["counts"]
924
+ payload = {"ok": ok, "name": args.name, "written": bool(args.out_dir), "out_dir": args.out_dir,
925
+ "counts": c, "labels": rep["labels"], "rows": rep["rows"], "findings": rep["findings"],
926
+ "citations": rep["citations"], "needs_review": rep["needs_review"],
927
+ "proposed_errors": proposed_errors, "statuses_changed": 0, "normalizations": rep["normalizations"],
928
+ "inputs": rep["inputs"], "to_version": rep["to_version"], "warnings": rep["warnings"],
929
+ "files": written}
930
+ lines = [f"{args.name}: claims rebase: {len(rep['labels'])} label(s): "
931
+ + (", ".join(f"{n} {s}" for s, n in c.items() if n) or "none")
932
+ + f"; {len(rep['needs_review'])} need review; no status changed"]
933
+ lines += [f" review: {x['where']} ({x['label']}): {x['status']}: {x['reason']}" for x in rep["needs_review"]]
934
+ lines += [f" invalid proposal: {e}" for e in proposed_errors]
935
+ lines += [f" warning: {w}" for w in rep["warnings"]]
936
+ if args.out_dir:
937
+ lines.append(f" wrote {len(written)} file(s) to {args.out_dir} (MANIFEST.sha256; nothing changed in place)")
938
+ else:
939
+ lines.append(" dry run: nothing written (pass --out-dir DIR for the proposed files and the review packet)")
940
+ return lines, payload, 0 if ok else 1
941
+
942
+
943
+ def run_rebase(args) -> int:
944
+ lines, payload, rc = do_rebase(core.load_registry(core.registry_path(args)), args)
945
+ if args.json_out:
946
+ core.print_json(payload)
947
+ else:
948
+ print("\n".join(lines))
949
+ return rc
950
+
951
+
952
+ def add_parser(csub, add_json, cmd_claims) -> None:
953
+ r = csub.add_parser("rebase", help="move claims.yaml and coverage.yaml to a new manuscript version: carry "
954
+ "unchanged statements re-keyed from the new .aux, list the rest for "
955
+ "review; writes only --out-dir; never changes a status")
956
+ r.add_argument("name")
957
+ r.add_argument("--from-tex", required=True, metavar="OLD.tex",
958
+ help="the (flattened) TeX the claims were written against; its SHA-256 must match coverage.yaml's "
959
+ "manuscript sha256 (an arXiv version: a .tex of its source-baseline record), or "
960
+ "--from-sha256 when none is recorded")
961
+ r.add_argument("--to-tex", required=True, metavar="NEW.tex", help="the new version's (flattened) TeX")
962
+ r.add_argument("--to-aux", required=True, metavar="NEW.aux",
963
+ help="the .aux of a full build of NEW.tex: new numbers and pages come from it")
964
+ r.add_argument("--from-aux", default=None, metavar="OLD.aux",
965
+ help="the old .aux: resolves references written as numbers (Lemma 4.2, (3.7)) to TeX labels")
966
+ r.add_argument("--from-sha256", default=None, metavar="HEX",
967
+ help="the SHA-256 of OLD.tex, required when coverage.yaml records none (checked, never trusted)")
968
+ r.add_argument("--to-version", default=None, metavar="arXiv:IDvN",
969
+ help="the new manuscript.version for the proposed coverage.yaml")
970
+ r.add_argument("--to-commit", default=None, metavar="HEX",
971
+ help="or: the manuscript repo commit of NEW.tex (sha256 is NEW.tex's)")
972
+ r.add_argument("--to-repo", default=None, metavar="URL",
973
+ help="with --to-commit: the manuscript repo (default: coverage.yaml's)")
974
+ r.add_argument("--unwrap-macro", action="append", default=None, metavar="NAME",
975
+ help="also read \\NAME{X} as X (a revision-highlight macro); repeatable")
976
+ r.add_argument("--claims-file", default=None, metavar="PATH",
977
+ help="a working-copy claims file instead of the one committed at HEAD")
978
+ r.add_argument("--coverage-file", default=None, metavar="PATH",
979
+ help="a working-copy coverage file instead of coverage.yaml committed at HEAD")
980
+ r.add_argument("--out-dir", default=None, metavar="DIR",
981
+ help="write the proposals, the report and the review packet here (a new or empty directory); "
982
+ "without it nothing is written")
983
+ add_json(r)
984
+ r.set_defaults(fn=cmd_claims, claims_fn=run_rebase)