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
@@ -0,0 +1,1078 @@
1
+ # lean-pkg formalization -- render a formalization.yaml (mathlib-initiative v0.4)
2
+ # for a registered package from the registry and the package repository at HEAD.
3
+ """Why this exists.
4
+
5
+ Palomar reads a repo-root ``formalization.yaml`` (the mathlib-initiative
6
+ self-reporting standard, schema v0.4). The registry's ``formalization_yaml``
7
+ field only stores a path; nothing generated or validated the file. This
8
+ module renders it from facts the tool already holds and refuses to invent the
9
+ rest.
10
+
11
+ Two kinds of keys:
12
+
13
+ * **Derived** keys are regenerated on every run from the registry and the
14
+ repository at HEAD (tracked bytes, never the working tree): ``version``,
15
+ ``project.name``, ``project.license`` (``license_spdx``),
16
+ ``automation.notes`` (the registry's ``automation`` disclosure),
17
+ ``status.sorry_count`` / ``status.axioms`` / ``status.evidence`` (the
18
+ lower-tier gate receipt), ``status.main_results`` (every tracked comparator
19
+ configuration: one entry per ``theorem_names`` item, ``judged_as`` carried
20
+ for definition holes; or, when a headline configuration is declared and
21
+ judged, its theorems only: headline.py), and ``alignment`` when ``claims.yaml`` is tracked.
22
+ * **Kept** keys are read from the existing file and preserved verbatim
23
+ (``project.description``, ``project.authors``, ``sources``,
24
+ ``related_formalizations``, ``classification``, ``automation.methods``,
25
+ ``status.scope``, ``fidelity``, ``review``, ``acknowledgements``,
26
+ ``repository`` and any extra key). Inside ``acknowledgements`` the lines
27
+ starting ``Formalizes results of `` / ``AI assistance: `` are the
28
+ renderer's own, rebuilt from the registry's ``source_paper`` and
29
+ ``ai_assistance`` on every run (#22.6); every other line is kept. On a first render they are seeded from
30
+ registry data where it exists (authors from ``consent[]`` entries with role
31
+ owner or author, a Mathlib ``builds-on`` row from ``mathlib_pin``) and
32
+ otherwise with a value starting ``[PLACEHOLDER]``, each reported on stderr.
33
+
34
+ So ``--write`` is idempotent, hand edits in kept keys survive, and
35
+ ``audit`` can report ``formalization-drift`` when a derived key changed.
36
+ Nothing here is a verification: the file reports what the registry and the
37
+ receipts record.
38
+
39
+ ``render NAME --repo DIR`` (read-only, never with ``--write``) renders from another checkout of the
40
+ package for one call, as ``page --repo`` does: the registry record (consent, licence, gate pointers)
41
+ is read as is and never saved, while everything taken from the repository (claims, comparator
42
+ configurations, the kept keys of formalization.yaml, the receipts) is read at DIR's committed HEAD,
43
+ from a private shared clone of it, never DIR's working tree. The gate receipt the registry records
44
+ feeds ``status.sorry_count`` / ``axioms`` / ``evidence`` only when the copy committed at that HEAD
45
+ validates against it (bound to HEAD or an evidence-only descendant); otherwise those facts are
46
+ omitted and a warning says why.
47
+ """
48
+ from __future__ import annotations
49
+
50
+ import contextlib
51
+ import importlib.resources
52
+ import json
53
+ import os
54
+ import pathlib
55
+ import tempfile
56
+
57
+ import yaml
58
+
59
+ from . import cli, cli_parser, gate as gate_mod
60
+ from . import core
61
+ from . import claims as claims_mod
62
+ from .holes import check_definition_holes, smoke_paths as holes_smoke, summary as signoff_summary
63
+
64
+ SCHEMA_VERSION = "v0.4"
65
+ SCHEMA_FILE = "formalization-0.4.schema.json"
66
+ SCHEMA_URL = ("https://raw.githubusercontent.com/mathlib-initiative/formalization.yaml/"
67
+ "main/schema/formalization.schema.json")
68
+ DEFAULT_PATH = "formalization.yaml"
69
+ PLACEHOLDER = "[PLACEHOLDER]"
70
+ MATHLIB_URL = "https://github.com/leanprover-community/mathlib4"
71
+ AUTHOR_ROLES = ("owner", "author")
72
+ METHOD_ENUM = ("manual", "copilot", "agent", "autonomous", "other")
73
+ SOURCE_RELATIONSHIPS = ("", "formalizes", "adapts", "independently-proves", "background", "other")
74
+ RELATED_RELATIONSHIPS = ("", "builds-on", "adapts", "independent", "supersedes", "other")
75
+ ENDORSEMENTS = ("", "participated", "endorsed", "no-response", "not-contacted", "declined",
76
+ "n/a", "other")
77
+
78
+ DERIVED_KEYS = ("version", "project.name", "project.license", "automation.notes",
79
+ "status.sorry_count", "status.axioms", "status.evidence",
80
+ "status.main_results", "alignment (when claims.yaml is tracked at HEAD)")
81
+
82
+ # The same split as data (#23.5): the key paths the renderer owns. A diff confined to these is what
83
+ # regenerating the file after a new receipt produces; the evidence-only descendant rule admits it.
84
+ DERIVED_PATHS = (("version",), ("project", "name"), ("project", "license"), ("automation", "notes"),
85
+ ("status", "sorry_count"), ("status", "axioms"), ("status", "evidence"),
86
+ ("status", "main_results"), ("alignment",))
87
+
88
+
89
+ # #22.6: the renderer's own sentences inside the kept `acknowledgements` string, one per line, each
90
+ # starting with one of these markers. A re-render replaces exactly these lines and keeps every other
91
+ # line (hand-written credits) as it is.
92
+ ACK_MARKERS = ("Formalizes results of ", "AI assistance: ")
93
+
94
+
95
+ def _join_names(names: list[str]) -> str:
96
+ names = [n for n in names if n]
97
+ return names[0] if len(names) == 1 else ", ".join(names[:-1]) + " and " + names[-1] if names else ""
98
+
99
+
100
+ def own_ack_sentences(pkg: dict) -> list[str]:
101
+ """The acknowledgements lines derived from the registry's source_paper and ai_assistance."""
102
+ out = []
103
+ sp = pkg.get("source_paper") if isinstance(pkg.get("source_paper"), dict) else None
104
+ if sp and any(sp.get(k) for k in ("title", "arxiv", "doi")):
105
+ ids = ([f"arXiv:{sp['arxiv']}"] if sp.get("arxiv") else []) + ([f"doi:{sp['doi']}"] if sp.get("doi") else [])
106
+ subject = sp.get("title") or ids[0]
107
+ by = _join_names([a for a in sp.get("authors") or [] if isinstance(a, str)])
108
+ line = ACK_MARKERS[0] + subject + (f" by {by}" if by else "")
109
+ if sp.get("title") and ids:
110
+ line += f" ({' / '.join(ids)})"
111
+ out.append(line + ".")
112
+ ai = pkg.get("ai_assistance") if isinstance(pkg.get("ai_assistance"), dict) else None
113
+ if ai and ai.get("tools"):
114
+ roles = _join_names([r for r in ai.get("roles") or [] if isinstance(r, str)])
115
+ out.append(ACK_MARKERS[1] + _join_names(list(ai["tools"])) + (f" for {roles}" if roles else "") + ".")
116
+ return out
117
+
118
+
119
+ def strip_own_ack(text) -> str:
120
+ """The hand-written part of an acknowledgements string: every line not starting with a marker."""
121
+ lines = str(text).split("\n")
122
+ return "\n".join(x for x in lines if not x.startswith(ACK_MARKERS)).strip("\n")
123
+
124
+
125
+ def render_acknowledgements(existing, pkg: dict):
126
+ """The acknowledgements value: the kept hand-written text, then the renderer's sentences (each on
127
+ its own line, refreshed on every run, never duplicated). None: leave the key as it is."""
128
+ own = own_ack_sentences(pkg)
129
+ if existing is not None and not isinstance(existing, str):
130
+ return None # not a string: a schema problem the validator reports
131
+ had_own = isinstance(existing, str) and any(x.startswith(ACK_MARKERS) for x in existing.split("\n"))
132
+ if not own and not had_own:
133
+ return None
134
+ manual = strip_own_ack(existing) if existing else ""
135
+ return "\n".join(([manual] if manual.strip() else []) + own)
136
+
137
+
138
+ def kept_view(doc) -> dict:
139
+ """The document with every derived key removed: what a hand edit can change. The renderer's own
140
+ acknowledgements lines (#22.6) count as derived."""
141
+ import copy
142
+ out = copy.deepcopy(doc) if isinstance(doc, dict) else {}
143
+ for path in DERIVED_PATHS:
144
+ node = out
145
+ for k in path[:-1]:
146
+ node = node.get(k) if isinstance(node, dict) else None
147
+ if isinstance(node, dict):
148
+ node.pop(path[-1], None)
149
+ if isinstance(out.get("acknowledgements"), str):
150
+ manual = strip_own_ack(out["acknowledgements"])
151
+ if manual.strip():
152
+ out["acknowledgements"] = manual
153
+ else:
154
+ out.pop("acknowledgements")
155
+ return out
156
+
157
+
158
+ def changed_kept_keys(old, new) -> list[str]:
159
+ """Dotted paths (top level, and one level down inside a mapping) of kept keys that differ."""
160
+ a, b = kept_view(old), kept_view(new)
161
+ out: list[str] = []
162
+ for k in list(a) + [k for k in b if k not in a]:
163
+ va, vb = a.get(k), b.get(k)
164
+ if va == vb:
165
+ continue
166
+ if isinstance(va, dict) and isinstance(vb, dict):
167
+ out += [f"{k}.{j}" for j in list(va) + [j for j in vb if j not in va] if va.get(j) != vb.get(j)]
168
+ else:
169
+ out.append(str(k))
170
+ return out
171
+
172
+
173
+ _ABSENT = object()
174
+
175
+
176
+ def _at(doc, path: tuple[str, ...]):
177
+ node = doc
178
+ for k in path:
179
+ if not isinstance(node, dict) or k not in node:
180
+ return _ABSENT
181
+ node = node[k]
182
+ return node
183
+
184
+
185
+ def _own_ack_lines(doc) -> list[str]:
186
+ ack = doc.get("acknowledgements") if isinstance(doc, dict) else None
187
+ return [x for x in ack.split("\n") if x.startswith(ACK_MARKERS)] if isinstance(ack, str) else []
188
+
189
+
190
+ def compare_with_file(existing_text: str, text: str) -> dict:
191
+ """How the file on disk differs from the render (#341): {"kept": dotted kept keys that differ (the kept
192
+ view of `formalization kept`, compared by its canonical SHA-256; named by changed_kept_keys, "(kept
193
+ view)" when only the bytes show it), "derived": dotted DERIVED_PATHS that differ (plus the renderer's
194
+ acknowledgements lines), "comments": line numbers of YAML comments below the header that the render
195
+ would drop}. Empty "kept" and "comments" mean a rewrite loses no hand-written content."""
196
+ from .formalization_kept import kept_digest, load_text # imports this module: resolve at call time
197
+ try:
198
+ old, new = load_text(existing_text), load_text(text)
199
+ same = kept_digest(old)[2] == kept_digest(new)[2]
200
+ except (core.Fail, yaml.YAMLError) as e:
201
+ return {"kept": [f"(kept view: {str(e).splitlines()[0]})"], "derived": [], "comments": []}
202
+ kept = [] if same else (changed_kept_keys(old, new) or ["(kept view)"])
203
+ derived = [".".join(p) for p in DERIVED_PATHS if _at(old, p) != _at(new, p)]
204
+ if _own_ack_lines(old) != _own_ack_lines(new):
205
+ derived.append("acknowledgements (the renderer's lines)")
206
+ rendered = set(text.splitlines())
207
+ comments, body = [], False
208
+ for i, line in enumerate(existing_text.splitlines(), 1):
209
+ bare = line.strip()
210
+ if bare and not bare.startswith("#"):
211
+ body = True # the leading comment block is the renderer's header
212
+ elif body and bare.startswith("#") and line not in rendered:
213
+ comments.append(i)
214
+ return {"kept": kept, "derived": derived, "comments": comments}
215
+
216
+
217
+ def hand_written_changes(cmp: dict) -> str:
218
+ """The hand-written content a rewrite would replace, as one phrase ('' when none)."""
219
+ parts = []
220
+ if cmp["kept"]:
221
+ parts.append("kept key(s) " + ", ".join(cmp["kept"]))
222
+ if cmp["comments"]:
223
+ parts.append("YAML comment(s) at line(s) " + ", ".join(map(str, cmp["comments"]))
224
+ + " (comments are not kept)")
225
+ return " and ".join(parts)
226
+
227
+
228
+ def stale_hint(name: str, existing_text: str, text: str) -> str:
229
+ """What differs and the complete repair command (#341): `render NAME --write` when only derived keys
230
+ differ; --force, named with what it replaces, only when hand-written content differs."""
231
+ cmp = compare_with_file(existing_text, text)
232
+ hand = hand_written_changes(cmp)
233
+ if hand:
234
+ return (f"it differs from the render in {hand}; read `lean-pkg formalization render {name}`, then "
235
+ f"`lean-pkg formalization render {name} --write --force` writes the render, these included")
236
+ what = ", ".join(cmp["derived"]) or "the generator's layout"
237
+ return (f"only derived keys differ ({what}); `lean-pkg formalization render {name} --write` refreshes "
238
+ f"them and keeps every kept key (or `lean-pkg gate {name} --receipt R --refresh-formalization` "
239
+ f"after a new receipt)")
240
+
241
+
242
+ TOP_ORDER = ("version", "project", "repository", "sources", "related_formalizations",
243
+ "classification", "status", "automation", "fidelity", "review", "alignment",
244
+ "acknowledgements")
245
+ PROJECT_ORDER = ("name", "description", "authors", "responsible_maintainers", "license")
246
+ STATUS_ORDER = ("scope", "sorry_count", "sorry_in_definitions", "axioms", "evidence",
247
+ "main_results")
248
+ AUTOMATION_ORDER = ("methods", "spend_usd", "notes")
249
+
250
+ HEADER = f"""\
251
+ # yaml-language-server: $schema={SCHEMA_URL}
252
+ # Rendered by `lean-pkg formalization <name>` from the lean-pkg registry and the package
253
+ # repository at HEAD (formalization.yaml {SCHEMA_VERSION}, mathlib-initiative). Paths are
254
+ # repository-relative. Derived keys are regenerated on every run: version, project.name,
255
+ # project.license, automation.notes, status.sorry_count, status.axioms, status.evidence,
256
+ # status.main_results, and alignment when claims.yaml is tracked. Every other key is kept
257
+ # from this file. A value starting "{PLACEHOLDER}" is data the registry does not hold:
258
+ # fill it in by hand (it is kept) or set the registry field it names.
259
+ """
260
+
261
+
262
+ # --------------------------------------------------------------------------
263
+ # helpers
264
+
265
+ def _ordered(d: dict, order: tuple[str, ...]) -> dict:
266
+ """Known keys first in template order, then the rest in their own order."""
267
+ out = {k: d[k] for k in order if k in d}
268
+ out.update({k: v for k, v in d.items() if k not in out})
269
+ return out
270
+
271
+
272
+ def _section(existing: dict | None, key: str) -> dict:
273
+ v = (existing or {}).get(key)
274
+ return dict(v) if isinstance(v, dict) else {}
275
+
276
+
277
+ def _is_placeholder(v) -> bool:
278
+ return isinstance(v, str) and v.startswith(PLACEHOLDER)
279
+
280
+
281
+ def module_path(module) -> str | None:
282
+ """Lean module name -> conventional source path: `A.B.C` -> `A/B/C.lean`."""
283
+ if not isinstance(module, str) or not module.strip():
284
+ return None
285
+ return module.strip().replace(".", "/") + ".lean"
286
+
287
+
288
+ def consent_authors(pkg: dict) -> list[str]:
289
+ """`consent[]` entries whose role is owner or author, in record order, deduplicated."""
290
+ out: list[str] = []
291
+ for c in pkg.get("consent") or []:
292
+ if isinstance(c, dict) and c.get("role") in AUTHOR_ROLES:
293
+ who = str(c.get("who") or "").strip()
294
+ if who and who not in out:
295
+ out.append(who)
296
+ return out
297
+
298
+
299
+ def find_placeholders(obj, path: str = "") -> list[str]:
300
+ """Dotted paths of every placeholder value in the document."""
301
+ found: list[str] = []
302
+ if isinstance(obj, dict):
303
+ for k, v in obj.items():
304
+ found += find_placeholders(v, f"{path}.{k}" if path else str(k))
305
+ elif isinstance(obj, list):
306
+ for i, v in enumerate(obj):
307
+ found += find_placeholders(v, f"{path}[{i}]")
308
+ elif _is_placeholder(obj):
309
+ found.append(path)
310
+ return found
311
+
312
+
313
+ # --------------------------------------------------------------------------
314
+ # derived parts
315
+
316
+ def headline_results(pkg: dict | None, repo: pathlib.Path, warnings: list[str], override: str | None = None,
317
+ info: dict | None = None) -> list[dict] | None:
318
+ """The main_results entries of the headline configuration (headline.py), when one is declared and
319
+ judged against the gate-bound comparator receipt; None (the default applies) when none is declared
320
+ or it cannot be judged (a warning says why). A judged headline that is not a subset refuses."""
321
+ from . import headline as hl
322
+ rel, source = hl.declared(pkg or {}, repo, override)
323
+ if info is not None:
324
+ info.clear()
325
+ info.update({"config": rel, "source": source, "applied": False, "reason": None, "receipt": None,
326
+ "theorems": 0})
327
+ if rel is None:
328
+ return None
329
+ cfg = hl.load(repo, rel)
330
+ try:
331
+ sidecar = gate_mod.sidecar_at(repo)
332
+ except ValueError as e:
333
+ raise core.Fail(str(e)) from e
334
+ if rel in holes_smoke(sidecar): # before judging: the plain reason, not "not a subset"
335
+ raise core.Fail(f"headline configuration {rel} ({source}) is marked as a smoke check in "
336
+ f"lean-pkg-signoff.json: a smoke check states no result, so it cannot be the headline; "
337
+ f"declare the configuration of the main results, or drop the smoke mark")
338
+ res = hl.judge(pkg or {}, repo, rel, cfg)
339
+ if info is not None:
340
+ info.update(receipt=res["receipt"], theorems=len(cfg["theorem_names"]))
341
+ if not res["judged"]:
342
+ warnings.append(f"headline configuration {rel} ({source}) not applied: {res['reason']}; "
343
+ f"status.main_results lists every tracked comparator configuration until a comparator "
344
+ f"receipt the gate records validates at HEAD")
345
+ if info is not None:
346
+ info["reason"] = res["reason"]
347
+ return None
348
+ why = hl.refusal(rel, res)
349
+ if why:
350
+ raise core.Fail(why)
351
+ solution, challenge = module_path(cfg["solution_module"]), module_path(cfg["challenge_module"])
352
+ if core.git_show_bytes(repo, solution) is None:
353
+ warnings.append(f"{rel}: solution module file {solution} is not tracked at HEAD "
354
+ f"(main_results.file uses the conventional module path)")
355
+ from .comparator_config import scaffold_todo_names
356
+ todo = scaffold_todo_names(cfg, rel, sidecar) if hl.is_config_path(rel) else set()
357
+ names = cfg["theorem_names"]
358
+ if todo & set(names):
359
+ warnings.append(f"{rel}: {len(todo & set(names))} theorem name(s) still marked TODO in the "
360
+ f"scaffold; left out of status.main_results")
361
+ holes = list(cfg.get("definition_names") or [])
362
+ out = []
363
+ for name in names:
364
+ if name in todo:
365
+ continue
366
+ entry = {"comparator_config": rel, "declaration": name, "file": solution, "challenge_file": challenge}
367
+ if holes:
368
+ entry["definition_holes"] = holes
369
+ entry["judged_as"] = res["judged_as"]
370
+ out.append(entry)
371
+ if info is not None:
372
+ info["applied"] = True
373
+ return out
374
+
375
+
376
+ def main_results(repo: pathlib.Path, warnings: list[str], pkg: dict | None = None,
377
+ headline: str | None = None, info: dict | None = None) -> list[dict]:
378
+ """The headline configuration's theorems when one is declared and judged (headline_results); else
379
+ one entry per theorem of every comparator configuration tracked at HEAD."""
380
+ picked = headline_results(pkg, repo, warnings, headline, info)
381
+ if picked is not None:
382
+ return picked
383
+ out: list[dict] = []
384
+ try: # lean-pkg-signoff.json at HEAD (holes.py)
385
+ smoke = holes_smoke(gate_mod.sidecar_at(repo))
386
+ except ValueError as e:
387
+ raise core.Fail(str(e)) from e
388
+ for rel in gate_mod.head_comparator_configs(repo):
389
+ if rel in smoke:
390
+ warnings.append(f"{rel}: marked as a smoke check in lean-pkg-signoff.json; its theorems state no "
391
+ f"result and are left out of status.main_results")
392
+ continue
393
+ raw = core.git_show_bytes(repo, rel)
394
+ try:
395
+ cfg = json.loads(raw or b"")
396
+ except ValueError as e:
397
+ raise core.Fail(f"{rel} at HEAD is not valid JSON: {e}") from e
398
+ if not isinstance(cfg, dict):
399
+ raise core.Fail(f"{rel} at HEAD is not a JSON object")
400
+ solution = module_path(cfg.get("solution_module"))
401
+ challenge = module_path(cfg.get("challenge_module"))
402
+ if solution is None:
403
+ raise core.Fail(f"{rel}: solution_module is missing or empty")
404
+ if core.git_show_bytes(repo, solution) is None:
405
+ warnings.append(f"{rel}: solution module file {solution} is not tracked at HEAD "
406
+ f"(main_results.file uses the conventional module path)")
407
+ names = cfg.get("theorem_names") or []
408
+ if not isinstance(names, list) or not all(isinstance(n, str) for n in names):
409
+ raise core.Fail(f"{rel}: theorem_names must be a list of strings")
410
+ if not names:
411
+ warnings.append(f"{rel}: theorem_names is empty; no main_results entry")
412
+ holes = cfg.get("definition_names") or []
413
+ judged = None
414
+ try: # lean-pkg-signoff.json at HEAD (holes.py)
415
+ sidecar = gate_mod.sidecar_at(repo)
416
+ except ValueError as e:
417
+ raise core.Fail(str(e)) from e
418
+ if holes:
419
+ try:
420
+ so = check_definition_holes(cfg, rel, cfg_rel=rel, cfg_bytes=raw, sidecar=sidecar,
421
+ warn=warnings.append)
422
+ judged = cfg["judged_as"] if so["source"] == "inline" else signoff_summary(so)
423
+ except ValueError as e:
424
+ warnings.append(f"{e}; judged_as is null in main_results")
425
+ from .comparator_config import scaffold_todo_names
426
+ todo = scaffold_todo_names(cfg, rel, sidecar) # #23.6: scaffolded, not yet written: not a main result
427
+ if todo & set(names):
428
+ warnings.append(f"{rel}: {len(todo & set(names))} theorem name(s) still marked TODO in the "
429
+ f"scaffold; left out of status.main_results")
430
+ for name in names:
431
+ if name in todo:
432
+ continue
433
+ entry = {"comparator_config": rel, "declaration": name, "file": solution}
434
+ if challenge:
435
+ entry["challenge_file"] = challenge
436
+ if holes:
437
+ entry["definition_holes"] = list(holes)
438
+ entry["judged_as"] = judged
439
+ out.append(entry)
440
+ if not out:
441
+ warnings.append("no comparator configuration with theorem_names is tracked at HEAD: "
442
+ "status.main_results is empty")
443
+ return out
444
+
445
+
446
+ def receipt_facts(pkg: dict, repo: pathlib.Path, bind: dict | None = None) -> dict | None:
447
+ """sorry_count, axioms and evidence pointers from the lower-tier gate receipt, if readable.
448
+
449
+ bind (render --repo): a dict that receives {receipt, included, reason}; the facts are then used only
450
+ when the receipt validates against HEAD of `repo` (gate_mod.validate_receipt: bound to HEAD or an
451
+ evidence-only descendant), so a registry receipt for another commit is never presented as this
452
+ checkout's evidence."""
453
+ gate = pkg.get("gate") or {}
454
+ rel = gate.get("receipt")
455
+ rec = gate_mod.recorded_json(repo, rel) if rel else None
456
+ if bind is not None:
457
+ bind.update(receipt=rel, included=False, reason=None)
458
+ if not rel:
459
+ bind["reason"] = "no gate receipt is recorded in the registry"
460
+ return None
461
+ if not isinstance(rec, dict):
462
+ bind["reason"] = f"the recorded gate receipt {rel} is not committed at HEAD (or not JSON)"
463
+ return None
464
+ try:
465
+ gate_mod.validate_receipt(pkg, repo, rec)
466
+ except core.Fail as e:
467
+ bind["reason"] = f"the recorded gate receipt {rel} does not validate at HEAD ({e})"
468
+ return None
469
+ bind["included"] = True
470
+ if not isinstance(rec, dict):
471
+ return None
472
+ facts: dict = {}
473
+ if isinstance(rec.get("sorry_count"), int):
474
+ facts["sorry_count"] = rec["sorry_count"]
475
+ if isinstance(rec.get("axioms"), list):
476
+ facts["axioms"] = [str(a) for a in rec["axioms"]]
477
+ facts["evidence"] = {"commit": rec.get("commit"), "gate_receipt": rel,
478
+ "comparator_receipt": gate.get("comparator")}
479
+ return facts
480
+
481
+
482
+ def alignment_from_claims(pkg: dict, repo: pathlib.Path) -> dict | None:
483
+ """`alignment` rows from claims.yaml tracked at HEAD; None when there is no such file."""
484
+ rel = pkg.get("claims_file") or claims_mod.DEFAULT_CLAIMS_FILE
485
+ raw = core.git_show_bytes(repo, rel)
486
+ if raw is None:
487
+ return None
488
+ doc = claims_mod.load_claims_text(raw.decode("utf-8", errors="replace"), rel)
489
+ errors = claims_mod.validate_claims(doc, pkg.get("name"))
490
+ if errors:
491
+ raise core.Fail(f"{rel} at HEAD is not a valid claims/1 file (fix it, then "
492
+ f"`lean-pkg claims sync`):\n " + "\n ".join(errors))
493
+ rows = []
494
+ for c in doc.get("claims") or []:
495
+ c = claims_mod.normalize_claim(c)
496
+ rows.append({"source": c.get("citation"), "lean": c["decl"], "module": c["file"],
497
+ "kind": c["kind"], "claim": c["id"], "status": c["status"],
498
+ "note": c["summary"]})
499
+ return {"generated_from": rel, "statements": rows}
500
+
501
+
502
+ # --------------------------------------------------------------------------
503
+ # render
504
+
505
+ def render_doc(pkg: dict, repo: pathlib.Path, existing: dict | None,
506
+ authors: list[str] | None = None, headline: str | None = None,
507
+ info: dict | None = None, bind: dict | None = None) -> tuple[dict, list[str]]:
508
+ """The document and its warnings (placeholders are reported by the caller). `headline`: the
509
+ --headline-config override; `info` (when given) receives the headline view (headline_results);
510
+ `bind` (render --repo): receipt facts only when bound to HEAD (receipt_facts)."""
511
+ warnings: list[str] = []
512
+ name = pkg["name"]
513
+ doc: dict = dict(existing or {})
514
+ doc["version"] = SCHEMA_VERSION
515
+
516
+ project = _section(existing, "project")
517
+ project["name"] = name
518
+ if "description" not in project:
519
+ project["description"] = (f"{PLACEHOLDER} project.description: a concise account of the "
520
+ f"mathematical content and principal results")
521
+ kept_authors = [a for a in (project.get("authors") or []) if isinstance(a, str)
522
+ and a.strip() and not _is_placeholder(a)]
523
+ if authors:
524
+ project["authors"] = list(authors)
525
+ elif kept_authors:
526
+ project["authors"] = kept_authors
527
+ elif consent_authors(pkg):
528
+ project["authors"] = consent_authors(pkg)
529
+ else:
530
+ project["authors"] = [f"{PLACEHOLDER} project.authors: no consent[] entry with role "
531
+ f"owner/author in the registry; pass --author NAME or record "
532
+ f"consent (lean-pkg record {name} consent-recorded ...)"]
533
+ project["license"] = pkg.get("license_spdx") or (
534
+ f"{PLACEHOLDER} project.license: license_spdx is unset in the registry "
535
+ f"(lean-pkg update {name} --license-spdx SPDX)")
536
+ doc["project"] = _ordered(project, PROJECT_ORDER)
537
+
538
+ if not isinstance(doc.get("sources"), list) or not doc["sources"]:
539
+ src = {"title": f"{PLACEHOLDER} sources[0].title: the registry carries no paper "
540
+ f"metadata; name the formalized source by hand (title, authors, "
541
+ f"id = DOI/arXiv/URL, type, location)",
542
+ "relationship": "formalizes"}
543
+ if pkg.get("owner_project"):
544
+ src["note"] = f"registry owner_project: {pkg['owner_project']}"
545
+ doc["sources"] = [src]
546
+
547
+ if "related_formalizations" not in doc:
548
+ doc["related_formalizations"] = ([{"id": MATHLIB_URL, "relationship": "builds-on",
549
+ "note": "pinned in lake-manifest.json"}]
550
+ if pkg.get("mathlib_pin") else [])
551
+
552
+ status = _section(existing, "status")
553
+ if "scope" not in status:
554
+ status["scope"] = (f"{PLACEHOLDER} status.scope: what is formalized and what is "
555
+ f"excluded, in the project's own words")
556
+ for k in ("sorry_count", "axioms", "evidence"):
557
+ status.pop(k, None)
558
+ facts = receipt_facts(pkg, repo, bind)
559
+ if facts:
560
+ status.update(facts)
561
+ status["main_results"] = main_results(repo, warnings, pkg, headline, info)
562
+ doc["status"] = _ordered(status, STATUS_ORDER)
563
+
564
+ automation = _section(existing, "automation")
565
+ if not isinstance(automation.get("methods"), list) or not automation["methods"]:
566
+ automation["methods"] = [{"method": "other"}]
567
+ note = str(pkg.get("automation") or "").strip()
568
+ automation["notes"] = note or (
569
+ f"{PLACEHOLDER} automation.notes: the registry's automation disclosure is empty "
570
+ f"(lean-pkg update {name} --automation TEXT)")
571
+ doc["automation"] = _ordered(automation, AUTOMATION_ORDER)
572
+
573
+ if not isinstance(doc.get("review"), dict):
574
+ doc["review"] = {"status": "unchecked",
575
+ "notes": "seeded by lean-pkg formalization: no human review status is "
576
+ "recorded in the registry; mechanical evidence (gate and "
577
+ "comparator receipts) is listed under status.evidence"}
578
+
579
+ alignment = alignment_from_claims(pkg, repo)
580
+ if alignment is not None:
581
+ doc["alignment"] = alignment
582
+
583
+ ack = render_acknowledgements(doc.get("acknowledgements"), pkg)
584
+ if ack is not None:
585
+ if ack:
586
+ doc["acknowledgements"] = ack
587
+ else:
588
+ doc.pop("acknowledgements", None)
589
+
590
+ return _ordered(doc, TOP_ORDER), warnings
591
+
592
+
593
+ def dump_doc(doc: dict) -> str:
594
+ return HEADER + yaml.safe_dump(doc, sort_keys=False, allow_unicode=True, width=100,
595
+ default_flow_style=False)
596
+
597
+
598
+ def load_existing(path: pathlib.Path) -> tuple[str | None, dict | None]:
599
+ """(text, mapping) of an existing formalization.yaml; (None, None) when absent."""
600
+ if path.is_symlink():
601
+ raise core.Fail(f"{path} is a symlink; refusing to read or write through it")
602
+ if not path.is_file():
603
+ return None, None
604
+ text = path.read_text()
605
+ try:
606
+ data = yaml.safe_load(text)
607
+ except yaml.YAMLError as e:
608
+ raise core.Fail(f"{path}: not valid YAML: {e}") from e
609
+ if data is None:
610
+ data = {}
611
+ if not isinstance(data, dict):
612
+ raise core.Fail(f"{path}: top level is not a mapping")
613
+ return text, data
614
+
615
+
616
+ # --------------------------------------------------------------------------
617
+ # validation
618
+
619
+ def load_schema() -> dict:
620
+ text = importlib.resources.files("lean_pkg").joinpath("schemas", SCHEMA_FILE).read_text()
621
+ return json.loads(text)
622
+
623
+
624
+ def _import_jsonschema():
625
+ try:
626
+ import jsonschema # optional dependency
627
+ except ImportError:
628
+ return None
629
+ return jsonschema
630
+
631
+
632
+ def structural_errors(doc) -> list[str]:
633
+ """A hand-written subset of the v0.4 schema for hosts without jsonschema."""
634
+ errors: list[str] = []
635
+ if not isinstance(doc, dict):
636
+ return ["<root>: not a mapping"]
637
+
638
+ def nonempty_str(v) -> bool:
639
+ return isinstance(v, str) and len(v) > 0
640
+
641
+ for k in ("project", "sources", "automation", "review"):
642
+ if k not in doc:
643
+ errors.append(f"<root>: '{k}' is a required property")
644
+ p = doc.get("project")
645
+ if p is not None:
646
+ if not isinstance(p, dict):
647
+ errors.append("project: not a mapping")
648
+ else:
649
+ for k in ("name", "authors", "license"):
650
+ if k not in p:
651
+ errors.append(f"project: '{k}' is a required property")
652
+ if "name" in p and not nonempty_str(p["name"]):
653
+ errors.append("project/name: must be a non-empty string")
654
+ if "license" in p and not nonempty_str(p["license"]):
655
+ errors.append("project/license: must be a non-empty string")
656
+ a = p.get("authors")
657
+ if "authors" in p and (not isinstance(a, list) or not a
658
+ or not all(nonempty_str(x) for x in a)):
659
+ errors.append("project/authors: must be a non-empty list of non-empty strings")
660
+ s = doc.get("sources")
661
+ if s is not None:
662
+ if not isinstance(s, list) or not s:
663
+ errors.append("sources: must be a non-empty list")
664
+ else:
665
+ for i, e in enumerate(s):
666
+ if not isinstance(e, dict) or not nonempty_str(e.get("title")):
667
+ errors.append(f"sources/{i}: 'title' is required and must be non-empty")
668
+ continue
669
+ if e.get("relationship", "") not in SOURCE_RELATIONSHIPS:
670
+ errors.append(f"sources/{i}/relationship: not one of {list(SOURCE_RELATIONSHIPS)}")
671
+ if e.get("author_endorsement", "") not in ENDORSEMENTS:
672
+ errors.append(f"sources/{i}/author_endorsement: not one of {list(ENDORSEMENTS)}")
673
+ r = doc.get("related_formalizations")
674
+ if r is not None:
675
+ if not isinstance(r, list):
676
+ errors.append("related_formalizations: must be a list")
677
+ else:
678
+ for i, e in enumerate(r):
679
+ if not isinstance(e, dict) or not nonempty_str(e.get("id")):
680
+ errors.append(f"related_formalizations/{i}: 'id' is required and must be non-empty")
681
+ elif e.get("relationship", "") not in RELATED_RELATIONSHIPS:
682
+ errors.append(f"related_formalizations/{i}/relationship: not one of "
683
+ f"{list(RELATED_RELATIONSHIPS)}")
684
+ a = doc.get("automation")
685
+ if a is not None:
686
+ m = a.get("methods") if isinstance(a, dict) else None
687
+ if not isinstance(a, dict) or "methods" not in a:
688
+ errors.append("automation: 'methods' is a required property")
689
+ elif not isinstance(m, list) or not m:
690
+ errors.append("automation/methods: must be a non-empty list")
691
+ else:
692
+ for i, e in enumerate(m):
693
+ if not isinstance(e, dict) or e.get("method") not in METHOD_ENUM:
694
+ errors.append(f"automation/methods/{i}/method: not one of {list(METHOD_ENUM)}")
695
+ rv = doc.get("review")
696
+ if rv is not None and (not isinstance(rv, dict) or not nonempty_str(rv.get("status"))):
697
+ errors.append("review/status: required, non-empty string")
698
+ st = doc.get("status")
699
+ if st is not None:
700
+ if not isinstance(st, dict):
701
+ errors.append("status: not a mapping")
702
+ else:
703
+ for k in ("sorry_count", "sorry_in_definitions"):
704
+ v = st.get(k)
705
+ if k in st and (not isinstance(v, int) or isinstance(v, bool) or v < 0):
706
+ errors.append(f"status/{k}: must be a non-negative integer")
707
+ mr = st.get("main_results")
708
+ if "main_results" in st and (not isinstance(mr, list)
709
+ or not all(isinstance(e, dict) for e in mr)):
710
+ errors.append("status/main_results: must be a list of mappings")
711
+ return errors
712
+
713
+
714
+ def validate_doc(doc) -> tuple[str, list[str]]:
715
+ """('jsonschema' | 'structural', errors)."""
716
+ js = _import_jsonschema()
717
+ if js is None:
718
+ return "structural", structural_errors(doc)
719
+ validator = js.Draft7Validator(load_schema())
720
+ errs = sorted(validator.iter_errors(doc), key=lambda e: [str(x) for x in e.path])
721
+ return "jsonschema", [f"{'/'.join(str(x) for x in e.path) or '<root>'}: {e.message}"
722
+ for e in errs]
723
+
724
+
725
+ # --------------------------------------------------------------------------
726
+ # the subcommand and the audit hook
727
+
728
+ def _atomic_write(path: pathlib.Path, text: str) -> None:
729
+ path.parent.mkdir(parents=True, exist_ok=True)
730
+ tmp = path.with_name(path.name + ".tmp")
731
+ tmp.write_text(text)
732
+ os.replace(tmp, path)
733
+
734
+
735
+ def target_rel(pkg: dict) -> str:
736
+ return pkg.get("formalization_yaml") or DEFAULT_PATH
737
+
738
+
739
+ def render_for(pkg: dict, repo: pathlib.Path, authors: list[str] | None = None, headline: str | None = None,
740
+ info: dict | None = None, bind: dict | None = None) -> tuple[str, dict, list[str], str | None]:
741
+ """(rendered text, doc, warnings, existing text) for the package's target path."""
742
+ existing_text, existing = load_existing(repo / target_rel(pkg))
743
+ doc, warnings = render_doc(pkg, repo, existing, authors, headline, info, bind)
744
+ return dump_doc(doc), doc, warnings, existing_text
745
+
746
+
747
+ def _render_payload(name: str, pkg: dict, repo: pathlib.Path, authors, headline,
748
+ bind: dict | None = None) -> tuple[str, dict, list[str], str | None, str]:
749
+ """(text, payload, warnings, existing text, summary) of one validated render."""
750
+ rel = target_rel(pkg)
751
+ hinfo: dict = {}
752
+ text, doc, warnings, existing_text = render_for(pkg, repo, authors, headline, hinfo, bind)
753
+ mode, errors = validate_doc(doc)
754
+ if errors:
755
+ raise core.Fail(f"{name}: the rendered formalization.yaml fails the {SCHEMA_VERSION} "
756
+ f"schema ({mode}); fix the kept keys in {rel}:\n " + "\n ".join(errors))
757
+ placeholders = find_placeholders(doc)
758
+ warnings = warnings + [f"placeholder at {p} (the registry holds no value for it)"
759
+ for p in placeholders]
760
+ n_results = len(doc["status"]["main_results"])
761
+ payload = {"ok": True, "name": name, "path": rel, "validation": mode,
762
+ "main_results": n_results, "headline": hinfo if hinfo.get("config") else None,
763
+ "placeholders": placeholders, "warnings": warnings, "written": False, "unchanged": False,
764
+ "registry_updated": False, "repo_override": None, "yaml": text}
765
+ summary = (f"{n_results} main result(s)"
766
+ + (f" from the headline configuration {hinfo['config']}" if hinfo.get("applied") else "")
767
+ + f"; validation: {mode} OK; {len(placeholders)} placeholder(s)")
768
+ return text, payload, warnings, existing_text, summary
769
+
770
+
771
+ def _write_out(name: str, out: str, text: str, summary: str, payload: dict,
772
+ warnings: list[str]) -> tuple[list[str], dict, list[str]]:
773
+ outp = pathlib.Path(out)
774
+ if outp.is_symlink():
775
+ raise core.Fail(f"{outp} is a symlink; refusing to write through it")
776
+ _atomic_write(outp, text)
777
+ payload.update(path=str(outp), written=True)
778
+ return [f"{name}: wrote {outp} ({summary}); registry untouched"], payload, warnings
779
+
780
+
781
+ @contextlib.contextmanager
782
+ def head_snapshot(d: pathlib.Path):
783
+ """(checkout path, HEAD sha) of a private clone of DIR's repository checked out at DIR's committed
784
+ HEAD, for one render: objects shared (git clone --shared), nothing written to DIR, removed on exit.
785
+ Every read of the render (tracked bytes and the files it reads directly, formalization.yaml and the
786
+ receipts) then sees DIR's HEAD, never its working tree. A package in a subdirectory keeps its prefix."""
787
+ head = core.git_head(d)
788
+ if head is None:
789
+ raise core.Fail(f"--repo {d}: no commit at HEAD")
790
+ top = core.git(d, "rev-parse", "--show-toplevel").stdout.strip()
791
+ prefix = core.git(d, "rev-parse", "--show-prefix").stdout.strip().strip("/")
792
+ with tempfile.TemporaryDirectory(prefix="lean-pkg-render-repo-") as tmp:
793
+ snap = pathlib.Path(tmp) / "head"
794
+ p = core.git(pathlib.Path(tmp), "-c", "core.hooksPath=/dev/null", "clone", "-q", "--shared",
795
+ "--no-checkout", top, str(snap))
796
+ if p.returncode == 0:
797
+ p = core.git(snap, "-c", "core.hooksPath=/dev/null", "-c", "advice.detachedHead=false",
798
+ "checkout", "-q", "--detach", head)
799
+ if p.returncode != 0:
800
+ raise core.Fail(f"--repo {d}: cannot read its HEAD {head[:12]} ({(p.stderr or '').strip()})")
801
+ yield (snap / prefix if prefix else snap), head
802
+
803
+
804
+ def _render_from_repo(reg: dict, name: str, repo_dir: str, *, out: str | None, authors, headline
805
+ ) -> tuple[list[str], dict, list[str]]:
806
+ """`formalization render NAME --repo DIR`: read-only (never --write, never the registry). The checkout
807
+ rules, the stderr note and JSON repo_override {path, registered_path, remote_match} are page --repo's
808
+ (gate_mod.repo_override); repo_override also carries head (DIR's HEAD), source "committed-head" and
809
+ receipt_facts {receipt, included, reason}."""
810
+ _reg, override = gate_mod.repo_override(reg, name, repo_dir)
811
+ if note := gate_mod.repo_override_note(override):
812
+ print(note, file=core.sys.stderr)
813
+ d = pathlib.Path(override["path"])
814
+ pkg = core.get_pkg(_reg, name)
815
+ extra: list[str] = []
816
+ dirty = core.git(d, "status", "--porcelain", "--untracked-files=no").stdout.strip()
817
+ if dirty:
818
+ extra.append(f"--repo {d}: uncommitted changes to tracked files are not read (the render uses the "
819
+ f"committed HEAD only)")
820
+ bind: dict = {}
821
+ with head_snapshot(d) as (snap, head):
822
+ text, payload, warnings, _existing, summary = _render_payload(
823
+ name, {**pkg, "local_path": str(snap)}, snap, authors, headline, bind)
824
+ if not bind.get("included"):
825
+ extra.append(f"status.sorry_count, status.axioms and status.evidence omitted: {bind.get('reason')} "
826
+ f"(--repo {d} at {head[:12]})")
827
+ warnings = extra + warnings
828
+ override = {**override, "head": head, "source": "committed-head", "receipt_facts": bind}
829
+ payload.update(warnings=warnings, repo_override=override)
830
+ origin = f"from --repo {d} at {head[:12]} (committed HEAD)"
831
+ if out:
832
+ lines, payload, warnings = _write_out(name, out, text, summary, payload, warnings)
833
+ return [lines[0].replace("; registry untouched", f"; {origin}; registry untouched")], payload, warnings
834
+ return [text.rstrip("\n")], payload, warnings
835
+
836
+
837
+ def do_formalization(reg_path, reg, events_p, name: str, *, write: bool, out: str | None,
838
+ force: bool, authors: list[str] | None, agent: str | None,
839
+ reason: str = "", no_registry: bool = False,
840
+ headline: str | None = None, repo_dir: str | None = None) -> tuple[list[str], dict, list[str]]:
841
+ """(stdout lines, payload, stderr warnings). The YAML text is in payload['yaml'].
842
+
843
+ --write checks before it writes: the lease (a live lease held by another agent refuses unless
844
+ --force --reason) and a dry run of the registry update, so a refusal leaves formalization.yaml
845
+ untouched. A file whose kept view equals the render's is rewritten (derived keys refreshed, #341);
846
+ --force alone overwrites a file whose kept keys differ; with --reason it also overrides the lease.
847
+ no_registry (--write --no-registry, #22.8): write the file only; the registry is read, never written
848
+ (no pointer update, no event), so the invocation is not a registry write. headline (--headline-config PATH):
849
+ the headline configuration for this render (headline.py); --write also records it in the registry
850
+ field headline_config. repo_dir (--repo DIR, read-only, refused with --write): render from DIR's
851
+ committed HEAD instead of the registered local_path (_render_from_repo)."""
852
+ if repo_dir is not None and write:
853
+ raise core.UsageError("--repo reads another checkout; --write edits the registered checkout's "
854
+ "formalization.yaml (drop one)")
855
+ if write and out:
856
+ raise core.UsageError("--write and --out are mutually exclusive")
857
+ if no_registry and not write:
858
+ raise core.UsageError("--no-registry needs --write (a render without --write never touches the registry)")
859
+ if repo_dir is not None:
860
+ return _render_from_repo(reg, name, repo_dir, out=out, authors=authors, headline=headline)
861
+ pkg = core.get_pkg(reg, name)
862
+ repo = core.repo_path(pkg)
863
+ if not repo.is_dir():
864
+ raise core.Fail(f"{name}: local_path does not exist: {repo}")
865
+ if core.git_head(repo) is None:
866
+ raise core.Fail(f"{name}: {repo} is not a git checkout with a commit")
867
+
868
+ rel = target_rel(pkg)
869
+ text, payload, warnings, existing_text, summary = _render_payload(name, pkg, repo, authors, headline)
870
+
871
+ if out:
872
+ return _write_out(name, out, text, summary, payload, warnings)
873
+
874
+ if not write:
875
+ return [text.rstrip("\n")], payload, warnings
876
+
877
+ target = repo / rel
878
+ lease_force = bool(force and reason)
879
+ sets = {"formalization_yaml": rel}
880
+ if headline and pkg.get("headline_config") != headline:
881
+ sets["headline_config"] = headline # --headline-config: recorded, so re-renders (audit) agree
882
+ needs_update = any(pkg.get(k) != v for k, v in sets.items())
883
+ if needs_update or existing_text != text: # something will be written: the lease decides first
884
+ core.refuse_invalid_lease(name, pkg.get("lease"))
885
+ lease = pkg.get("lease")
886
+ if core.lease_live(lease, core.dt.datetime.now(core.dt.timezone.utc)) \
887
+ and agent != lease.get("agent") and not lease_force:
888
+ holder = lease.get("agent")
889
+ raise core.Fail(f"{name}: lease held by {holder} — pass --agent {holder}, or --force --reason "
890
+ f"TEXT to override it; nothing written")
891
+ update_kw = dict(sets=sets, status=None,
892
+ reason=reason or "lean-pkg formalization --write", redetect=False,
893
+ agent=agent, force=lease_force)
894
+ if no_registry:
895
+ payload["registry_skipped"] = True
896
+ if needs_update and not no_registry: # every registry check first, on a copy: a refusal writes nothing
897
+ cli.do_update(reg_path, reg, events_p, name, dry_run=True, **update_kw)
898
+ payload.update(refreshed_derived=[], kept_overwritten=[])
899
+ if existing_text is not None and existing_text == text:
900
+ payload["unchanged"] = True
901
+ lines = [f"{name}: {rel} is already what the generator emits; nothing written ({summary})"]
902
+ else:
903
+ # #341: a file that differs from the render only in derived keys (a re-gate moved the receipts) is
904
+ # refreshed without --force; --force is needed only to replace hand-written content.
905
+ cmp = compare_with_file(existing_text, text) if existing_text is not None else None
906
+ hand = hand_written_changes(cmp) if cmp else ""
907
+ if hand and not force:
908
+ raise core.Fail(f"{name}: {rel} differs from the render in {hand}; inspect "
909
+ f"`lean-pkg formalization render {name}` and pass --force to write the render "
910
+ f"(--force replaces the whole file, these included); nothing written")
911
+ _atomic_write(target, text)
912
+ payload["written"] = True
913
+ lines = [f"{name}: wrote {target} ({summary}) — not committed; commit it yourself"]
914
+ if cmp:
915
+ payload.update(refreshed_derived=cmp["derived"], kept_overwritten=cmp["kept"])
916
+ derived = ", ".join(cmp["derived"]) or "none (only the generator's layout changed)"
917
+ lines.append(f"{name}: refreshed derived keys: {derived}; "
918
+ + (f"--force replaced {hand}" if hand else "every kept key unchanged"))
919
+ if needs_update and no_registry:
920
+ unset = {k: v for k, v in sets.items() if pkg.get(k) != v}
921
+ lines.append(f"{name}: registry untouched (--no-registry); "
922
+ + " and ".join(f"{k} is not set" for k in unset) + ": run `lean-pkg update " + name
923
+ + "".join(f" --{k.replace('_', '-')} {v}" for k, v in unset.items())
924
+ + "` when the registry is open")
925
+ elif needs_update:
926
+ up_lines, _ = cli.do_update(reg_path, reg, events_p, name, **update_kw)
927
+ lines += up_lines
928
+ payload["registry_updated"] = True
929
+ return lines, payload, warnings
930
+
931
+
932
+ def audit_findings(pkg: dict, repo: pathlib.Path) -> list[tuple[str, str]]:
933
+ """(check, detail) pairs for `audit`: formalization-missing | formalization-drift | warn."""
934
+ rel = pkg.get("formalization_yaml")
935
+ if not rel:
936
+ return []
937
+ target = repo / rel
938
+ if not target.is_file():
939
+ return [("formalization-missing", rel)]
940
+ try:
941
+ text, _doc, _warnings, existing_text = render_for(pkg, repo)
942
+ except (core.Fail, core.UsageError) as e:
943
+ return [("warn", f"formalization.yaml cannot be re-rendered: {e}")]
944
+ if existing_text != text:
945
+ return [("formalization-drift", f"{rel} differs from `lean-pkg formalization render "
946
+ f"{pkg['name']}`: {stale_hint(pkg['name'], existing_text, text)}")]
947
+ return []
948
+
949
+
950
+ ANCHOR_CMD = "anchor"
951
+ ANCHOR_ONLY = (("arxiv", "--arxiv"), ("from_file", "--from-file"), ("fetch", "--fetch"),
952
+ ("compare_tex", "--compare-tex"), ("accept_diff", "--accept-diff"), ("main_tex", "--main-tex"))
953
+ RENDER_ONLY = (("out", "--out"), ("force", "--force"), ("reason", "--reason"), ("author", "--author"),
954
+ ("no_registry", "--no-registry"), ("headline_config", "--headline-config"), ("repo", "--repo"))
955
+
956
+
957
+ def is_anchor(args) -> bool:
958
+ """`lean-pkg formalization anchor NAME ...`: the keyword form (never a registry write)."""
959
+ return getattr(args, "name", None) == ANCHOR_CMD
960
+
961
+
962
+ def cmd_formalization(args) -> int:
963
+ if is_anchor(args):
964
+ given = [flag for dest, flag in RENDER_ONLY if getattr(args, dest, None)]
965
+ if given:
966
+ raise core.UsageError(f"formalization anchor: {', '.join(given)} belong(s) to the render form "
967
+ f"(`lean-pkg formalization NAME`)")
968
+ if not getattr(args, "package", None):
969
+ raise core.UsageError("formalization anchor: name the package: "
970
+ "`lean-pkg formalization anchor NAME --arxiv <id>v<N> --from-file E-PRINT`")
971
+ if not getattr(args, "arxiv", None):
972
+ raise core.UsageError("formalization anchor: --arxiv <id>v<N> is required")
973
+ from .anchor import cmd_anchor
974
+ return cmd_anchor(args)
975
+ given = [flag for dest, flag in ANCHOR_ONLY if getattr(args, dest, None)]
976
+ if getattr(args, "package", None) or given:
977
+ raise core.UsageError(f"formalization {args.name}: "
978
+ + (f"{', '.join(given)} go(es) with" if given else "a second name needs")
979
+ + " the anchor form: `lean-pkg formalization anchor NAME --arxiv <id>v<N> ...`")
980
+ headline = getattr(args, "headline_config", None)
981
+ if headline is not None and not headline.strip():
982
+ raise core.UsageError("--headline-config needs a path (clear the registry field with "
983
+ "`lean-pkg update NAME --headline-config ''`)")
984
+ reg_path, events_p = core.registry_path(args), core.events_path(args)
985
+ lines, payload, warnings = do_formalization(
986
+ reg_path, core.load_registry(reg_path), events_p, args.name, write=args.write,
987
+ out=args.out, force=args.force, authors=args.author, agent=args.agent,
988
+ reason=getattr(args, "reason", "") or "", no_registry=getattr(args, "no_registry", False),
989
+ headline=headline, repo_dir=getattr(args, "repo", None))
990
+ for w in warnings:
991
+ print(f"lean-pkg: warning: {w}", file=core.sys.stderr)
992
+ if getattr(args, "json_out", False):
993
+ core.print_json(payload)
994
+ else:
995
+ print("\n".join(lines))
996
+ return 0
997
+
998
+
999
+ def add_parsers(sub, add_json) -> None:
1000
+ # `formalization render|anchor`: real subparsers (anchor was a value of the name positional before 1.0).
1001
+ # Each sets the namespace the old single parser produced (anchor: name == "anchor", the package in
1002
+ # `package`); `formalization NAME ...` is `formalization render NAME ...` (command_tree.IMPLIED_VERBS).
1003
+ n = sub.add_parser("formalization",
1004
+ help=f"formalization.yaml ({SCHEMA_VERSION}, what Palomar reads): render it from the registry "
1005
+ f"and the repo at HEAD; anchor the companion to one arXiv version")
1006
+ fsub = n.add_subparsers(dest="formalization_cmd", required=True, metavar="{render,anchor,kept}")
1007
+ s = fsub.add_parser("render",
1008
+ help=f"render formalization.yaml ({SCHEMA_VERSION}, what Palomar reads) "
1009
+ f"from the registry and the repo at HEAD; stdout unless --write/--out "
1010
+ f"(`formalization NAME` is the same)")
1011
+ s.add_argument("name", help="the package")
1012
+ s.add_argument("--write", action="store_true",
1013
+ help="write <repo>/<formalization_yaml or formalization.yaml> and set the "
1014
+ "registry pointer (event updated); a file differing only in derived keys is "
1015
+ "refreshed, one whose kept keys differ is refused without --force")
1016
+ s.add_argument("--no-registry", action="store_true",
1017
+ help="with --write: write the file only; the registry is not updated (no pointer, no "
1018
+ "event), so this is not a registry write (no lock, no --commit)")
1019
+ s.add_argument("--out", default=None, metavar="PATH",
1020
+ help="write the render here instead; the registry is untouched")
1021
+ s.add_argument("--force", action="store_true",
1022
+ help="with --write: overwrite a file whose kept keys differ from the render; with --reason "
1023
+ "also override a live lease held by another agent")
1024
+ s.add_argument("--reason", default="",
1025
+ help="with --write --force: why another agent's lease is overridden (recorded in "
1026
+ "the updated event)")
1027
+ s.add_argument("--author", action="append", default=None, metavar="NAME",
1028
+ help="project.authors entry (repeatable); otherwise kept from the file, else "
1029
+ "consent[] owners/authors, else a placeholder")
1030
+ s.add_argument("--headline-config", dest="headline_config", default=None, metavar="PATH",
1031
+ help="the headline comparator configuration (the paper's main results) for this render; "
1032
+ "--write also records it (registry headline_config). Default: the registry field, else "
1033
+ "comparator.headline.json when tracked. status.main_results then lists its theorems "
1034
+ "only, each covered by the gate-bound comparator receipt (else refused)")
1035
+ s.add_argument("--repo", default=None, metavar="DIR",
1036
+ help="read the checkout DIR instead of the registered local_path, for this call only (never "
1037
+ "saved): claims, comparator configurations, the kept keys and the receipts at DIR's "
1038
+ "committed HEAD; the gate receipt's facts only when bound to that HEAD. DIR must be a "
1039
+ "git work tree, and when it has remotes one must be the package's repo; not with --write")
1040
+ s.add_argument("--agent", default=None, help="lease holder, if one is live (for the registry update)")
1041
+ add_json(s)
1042
+ render = s
1043
+ a = fsub.add_parser(
1044
+ "anchor", help="bind the companion to one posted arXiv version (writes package files, never the registry)",
1045
+ description="`lean-pkg formalization anchor NAME --arxiv <id>v<N> (--from-file E-PRINT | --fetch) "
1046
+ "[--compare-tex LOCAL.tex [--accept-diff REASON]] [--main-tex PATH] [--write]`: bind the companion to one "
1047
+ "posted arXiv version. Reads the e-print (gzip'd tar, gzip'd .tex or tar; PDF-only is refused) in memory, "
1048
+ "hashes it and its .tex/.bib/.bbl/.sty files, finds the main .tex (\\documentclass), compares it with "
1049
+ "LOCAL.tex and records it all in data/source-baselines/arXiv-<id>v<N>.json. Without --write: a dry run. "
1050
+ "--write refuses unless the e-print is tied to the manuscript coverage.yaml is bound to (same version, a "
1051
+ "matching bound sha256, or --compare-tex identical / --accept-diff); a move to another version prints the "
1052
+ "`claims rebase` command. Never writes the registry; never commits")
1053
+ a.add_argument("package", nargs="?", default=None, help="the package to anchor")
1054
+ a.add_argument("--arxiv", default=None, metavar="ID",
1055
+ help="the arXiv id WITH its version (<id>v<N> or arXiv:<id>v<N>); unversioned ids are refused")
1056
+ a.add_argument("--from-file", dest="from_file", default=None, metavar="E-PRINT",
1057
+ help="the e-print as downloaded from arxiv.org/e-print/<id>v<N> (offline; no network)")
1058
+ a.add_argument("--fetch", action="store_true",
1059
+ help="download the e-print over HTTPS (60 s timeout, 64 MiB cap) and the arXiv API entry of "
1060
+ "that version; the only network access this command makes")
1061
+ a.add_argument("--compare-tex", dest="compare_tex", default=None, metavar="LOCAL.tex",
1062
+ help="compare this local .tex with the e-print's main .tex (line endings and trailing "
1063
+ "whitespace normalised); the differing lines are shown")
1064
+ a.add_argument("--accept-diff", dest="accept_diff", default=None, metavar="REASON",
1065
+ help="with --compare-tex: anchor although the files differ; the reason is recorded")
1066
+ a.add_argument("--main-tex", dest="main_tex", default=None, metavar="PATH",
1067
+ help="the e-print's main .tex when more than one file carries \\documentclass")
1068
+ a.add_argument("--write", action="store_true",
1069
+ help="write the source-baseline record, coverage.yaml manuscript.version and the "
1070
+ "formalization.yaml source id (never the registry; not committed); without it a dry run")
1071
+ a.add_argument("--agent", default=None, help="lease holder, if one is live")
1072
+ add_json(a)
1073
+ cli_parser._hidden_copies(a, render) # a render flag on anchor (and back) is refused as before, by name
1074
+ cli_parser._hidden_copies(render, a)
1075
+ a.set_defaults(fn=cmd_formalization, name=ANCHOR_CMD)
1076
+ render.set_defaults(fn=cmd_formalization)
1077
+ from .formalization_kept import add_parser as add_kept # the kept view and its hash (read-only)
1078
+ add_kept(fsub, add_json)