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/deps_fill.py ADDED
@@ -0,0 +1,445 @@
1
+ #!/usr/bin/env python3
2
+ """`receipt slurm --preflight-deps --fill-plan DONOR`: steps 1-4 of docs/receipts.md, "Filling missing
3
+ dependency artifacts from a pinned donor", read-only. It writes nothing except the files passed explicitly
4
+ with --plan-out; it never touches the base cache, the donor or the package's .lake/build.
5
+
6
+ 1. The plan: the same dependency preflight as `--preflight-deps` on the base cache (--deps-tar or
7
+ --deps-dir), keeping EVERY missing module (the 500 cap of missing[] is a display cap only). Problems other
8
+ than missing files (a package at another rev, a stripped checkout, a module no package provides, a module
9
+ whose source is not staged) are listed as not fillable from a donor, and refuse.
10
+ 2. The donor checks: DONOR/lean-toolchain is byte for byte `git show SHA:lean-toolchain`; every manifest git
11
+ package is in DONOR/.lake/packages at the manifest's rev (the preflight's own pin check, run on the donor);
12
+ each such checkout has no source edits (`git status --porcelain --untracked-files=no` prints nothing, run
13
+ with GIT_OPTIONAL_LOCKS=0 so git does not refresh the donor's index and with the checkout's core.fsmonitor
14
+ off; no index entry is marked assume-unchanged or skip-worktree, which hide an edit from git status; and
15
+ no untracked or ignored *.lean, lakefile, lean-toolchain or lake-manifest.json sits outside .lake/; a
16
+ package with no `.git` directory, or one git cannot read, refuses: an edit cannot be ruled out); and the first 80 bytes of each candidate .olean
17
+ (marker, format version, Lean version, Lean commit) equal those of the base cache's .olean files, which
18
+ must agree with each other.
19
+ 3. The artifact families: for each missing module, every regular file the donor holds under the module's
20
+ path in its package's build directory (.lake/build/ or build/, in lib/lean/, lib/ or ir/): `<path>.<any
21
+ extension>`, so .olean, .olean.private, .olean.server, .ilean, .ir, each .hash, .trace, ir/*.c, .c.hash
22
+ and anything else present. A module whose .olean or .ilean the donor lacks is not fillable.
23
+ 4. Additions only: no addition may be a member of the base (the base directory's entries, the tarball's
24
+ members, and any --base-list FILE names), or sit under a base member that is not a directory; none may
25
+ be under the package's own .lake/build or hold one of the package's root namespaces.
26
+
27
+ The archive is still written by the user (steps 5-7 of the recipe), and the official preflight rerun on it
28
+ is what confirms the fill. The provenance stub written with --plan-out is collector provenance, never a job
29
+ seal."""
30
+
31
+ from __future__ import annotations
32
+
33
+ import datetime
34
+ import hashlib
35
+ import json
36
+ import os
37
+ import pathlib
38
+ import subprocess
39
+ import tarfile
40
+
41
+ from . import core
42
+ from . import deps_closure as dc
43
+
44
+ BUILD_ROOTS = (".lake/build/", "build/")
45
+ FAMILY_DIRS = ("lib/lean/", "lib/", "ir/")
46
+ PROVENANCE_SCHEMA = "lean-pkg-fill-provenance/1"
47
+ PROVENANCE_KIND = "collector provenance: which bytes were added and where they came from; never a job seal"
48
+ SHOW_MODULES = 20
49
+ CHUNK = 1 << 20
50
+
51
+ # Refusal codes, one per check (JSON refusals[].code; the exit code is 1 for every refusal).
52
+ BASE_PROBLEM = "base-problem" # a preflight problem a donor cannot fill
53
+ DONOR_CACHE = "donor-cache" # DONOR holds no .lake/packages
54
+ DONOR_TOOLCHAIN = "donor-toolchain"
55
+ DONOR_MANIFEST = "donor-manifest"
56
+ DONOR_SOURCE = "donor-source-edits"
57
+ OLEAN_HEADER = "olean-header"
58
+ DONOR_LACKS = "donor-lacks-module"
59
+ BASE_OVERLAP = "base-overlap"
60
+ PACKAGE_BUILD = "package-build" # under the package's own .lake/build or a root namespace
61
+ PLAN_OUT = "plan-out"
62
+
63
+
64
+ def sha256_file(path: pathlib.Path) -> tuple[int, str]:
65
+ h = hashlib.sha256()
66
+ size = 0
67
+ with open(path, "rb") as f:
68
+ while chunk := f.read(CHUNK):
69
+ size += len(chunk)
70
+ h.update(chunk)
71
+ return size, h.hexdigest()
72
+
73
+
74
+ def family_index(cache: dc.Cache) -> dict[str, list[str]]:
75
+ """`.lake/packages/<pkg>/<build root><family dir><module path>` -> the regular files `<that>.<ext>`."""
76
+ out: dict[str, list[str]] = {}
77
+ for rel in cache.files:
78
+ pkg, _, inner = rel[len(dc.PACKAGES):].partition("/")
79
+ if not any(inner.startswith(b) for b in BUILD_ROOTS):
80
+ continue
81
+ head, _, name = rel.rpartition("/")
82
+ stem, dot, _ext = name.partition(".")
83
+ if dot and stem:
84
+ out.setdefault(f"{head}/{stem}", []).append(rel)
85
+ return out
86
+
87
+
88
+ def module_families(index: dict[str, list[str]], pkg: str, mpath: str) -> list[str]:
89
+ files: set[str] = set()
90
+ for b in BUILD_ROOTS:
91
+ for d in FAMILY_DIRS:
92
+ files.update(index.get(f"{dc.PACKAGES}{pkg}/{b}{d}{mpath}", []))
93
+ return sorted(files)
94
+
95
+
96
+ def has_family(files: list[str], mpath: str, ext: str) -> bool:
97
+ """`files` (one module's families) hold `<module path><ext>` in a lib/ directory."""
98
+ return any(f.endswith(f"/lib/lean/{mpath}{ext}") or f.endswith(f"/lib/{mpath}{ext}") for f in files)
99
+
100
+
101
+ def module_part(rel: str) -> str:
102
+ """The path below `<build root><family dir>` of a dependency build file (else the path in the package)."""
103
+ inner = rel[len(dc.PACKAGES):].partition("/")[2]
104
+ for b in BUILD_ROOTS:
105
+ for d in FAMILY_DIRS:
106
+ if inner.startswith(b + d):
107
+ return inner[len(b + d):]
108
+ return inner
109
+
110
+
111
+ # Untracked or ignored files git status never shows but Lake would read: Lean sources and the package's own
112
+ # configuration. `.lake/` is the one generated area (build outputs, nested packages) and is not looked at.
113
+ SOURCE_PATHSPECS = ("*.lean", "lakefile.lean", "lakefile.toml", "lean-toolchain", "lake-manifest.json",
114
+ ":(exclude).lake")
115
+
116
+
117
+ def git_status(checkout: pathlib.Path) -> tuple[bool, str]:
118
+ """(clean, detail) for one donor dependency checkout; never writes (no optional locks, no index refresh),
119
+ never discovers a repository above the checkout. Clean means: no tracked change (git status), no index
120
+ entry hidden from git status (assume-unchanged, skip-worktree), and no untracked or ignored Lean source
121
+ or Lake configuration outside .lake/. The checkout's own core.fsmonitor and untracked cache are off."""
122
+ gitdir = checkout / ".git"
123
+ if not gitdir.is_dir() or gitdir.is_symlink():
124
+ return False, "no .git directory: not a git checkout, so a source edit cannot be ruled out"
125
+ env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
126
+ env.update(GIT_DIR=str(gitdir), GIT_WORK_TREE=str(checkout), GIT_OPTIONAL_LOCKS="0",
127
+ GIT_CONFIG_NOSYSTEM="1", LC_ALL="C")
128
+
129
+ def git(*args: str) -> subprocess.CompletedProcess:
130
+ return subprocess.run(["git", "-c", f"safe.directory={checkout}", "-c", "core.fsmonitor=false",
131
+ "-c", "core.untrackedCache=false", "--no-optional-locks", *args],
132
+ cwd=checkout, env=env, capture_output=True, text=True, timeout=600)
133
+
134
+ def shown(names: list[str]) -> str:
135
+ return ", ".join(names[:5]) + (f" (and {len(names) - 5} more)" if len(names) > 5 else "")
136
+
137
+ try:
138
+ p = git("status", "--porcelain", "--untracked-files=no", "--ignore-submodules=none")
139
+ flags = git("ls-files", "-v", "-z") if p.returncode == 0 else p
140
+ others = (git("ls-files", "--others", "-z", "--", *SOURCE_PATHSPECS)
141
+ if flags.returncode == 0 else flags)
142
+ except (OSError, subprocess.TimeoutExpired) as e:
143
+ return False, f"git status could not run ({type(e).__name__}): a source edit cannot be ruled out"
144
+ if others.returncode != 0:
145
+ why = (others.stderr.strip().splitlines() or ["no message"])[0]
146
+ return False, f"git status failed ({why}): a source edit cannot be ruled out"
147
+ lines = [ln for ln in p.stdout.splitlines() if ln.strip()]
148
+ if lines:
149
+ return False, f"{len(lines)} tracked file(s) differ from the checkout's commit: {shown([ln[3:] for ln in lines])}"
150
+ # ls-files -v tags an assume-unchanged entry in lower case and a skip-worktree one with S (s if both).
151
+ hidden = [e[2:] for e in flags.stdout.split("\0") if e and (e[0].islower() or e[0] == "S")]
152
+ if hidden:
153
+ return False, (f"{len(hidden)} tracked file(s) hidden from git status (assume-unchanged or "
154
+ f"skip-worktree), so an edit cannot be ruled out: {shown(hidden)}")
155
+ extra = [e for e in others.stdout.split("\0") if e]
156
+ if extra:
157
+ return False, (f"{len(extra)} untracked or ignored Lean source or Lake configuration file(s) outside "
158
+ f".lake/: {shown(extra)}")
159
+ return True, "no tracked change, no hidden index entry, no untracked Lean source"
160
+
161
+
162
+ def header_key(h: bytes | None) -> bytes | None:
163
+ """The toolchain-identifying part of an .olean header: the first 80 bytes (format version 2: marker,
164
+ version, flags, Lean version string, Lean commit; the per-module base address follows), or the first 46
165
+ for format version 1 (marker, version, Lean commit; the base address follows at once)."""
166
+ if h is None:
167
+ return None
168
+ return h[:46] if len(h) > 5 and h[5] == 1 else h[:dc.OLEAN_HEADER]
169
+
170
+
171
+ def _inside(path: pathlib.Path, root: pathlib.Path) -> bool:
172
+ try:
173
+ path.resolve().relative_to(root.resolve())
174
+ return True
175
+ except ValueError:
176
+ return False
177
+
178
+
179
+ def cmd(args) -> int:
180
+ repo = pathlib.Path(args.repo).resolve() if args.repo else pathlib.Path.cwd()
181
+ rev = args.commit_sha or "HEAD"
182
+ p = core.git(repo, "rev-parse", "--verify", "--quiet", f"{rev}^{{commit}}")
183
+ commit = p.stdout.strip() if p.returncode == 0 else ""
184
+ if not commit:
185
+ raise core.UsageError(f"--commit {rev}: not a commit in the --repo checkout (default the current directory)")
186
+ donor = pathlib.Path(args.fill_plan)
187
+ if not donor.is_dir():
188
+ raise core.UsageError(f"--fill-plan {args.fill_plan}: not a directory (the donor: a directory holding "
189
+ f".lake/packages)")
190
+ if args.deps_tar:
191
+ base_path = pathlib.Path(args.deps_tar)
192
+ if not base_path.is_file():
193
+ raise core.UsageError(f"--deps-tar {args.deps_tar}: not a file")
194
+ else:
195
+ base_path = pathlib.Path(args.deps_dir)
196
+ if not base_path.is_dir():
197
+ raise core.UsageError(f"--deps-dir {args.deps_dir}: not a directory")
198
+ base_list: list[str] = []
199
+ if args.base_list:
200
+ try:
201
+ raw = pathlib.Path(args.base_list).read_text(encoding="utf-8")
202
+ except (OSError, UnicodeDecodeError) as e:
203
+ raise core.UsageError(f"--base-list {args.base_list}: cannot read it ({type(e).__name__})") from e
204
+ base_list = [n for n in (dc._norm(ln.rstrip("\n")) for ln in raw.splitlines() if ln.strip()) if n]
205
+
206
+ refusals: list[dict] = []
207
+ checks: list[str] = []
208
+
209
+ def refuse(code: str, reason: str) -> None:
210
+ refusals.append({"code": code, "reason": reason})
211
+
212
+ plan_out = pathlib.Path(args.plan_out) if args.plan_out else None
213
+ prov_out = plan_out.with_name(plan_out.name + ".provenance.json") if plan_out else None
214
+ if plan_out:
215
+ for out in (plan_out, prov_out):
216
+ if os.path.lexists(out):
217
+ refuse(PLAN_OUT, f"--plan-out: {out} already exists (never overwritten)")
218
+ for root, what in ((donor, "the donor"), (base_path if base_path.is_dir() else None, "the base cache"),
219
+ (repo / ".lake", "the package's .lake")):
220
+ if root is not None and _inside(out.parent, root):
221
+ refuse(PLAN_OUT, f"--plan-out: {out} is inside {what}, which the plan never writes")
222
+
223
+ # 1. the plan: the official preflight on the base, every missing module kept
224
+ base = None
225
+ try:
226
+ base = dc.read_tar(base_path, headers=True) if args.deps_tar else dc.read_dir(base_path, headers=True)
227
+ except (tarfile.TarError, OSError, EOFError) as e:
228
+ refuse(BASE_PROBLEM, f"--deps-tar: cannot read the tarball ({type(e).__name__}: {e})")
229
+ entries = list(args.entries) or list(dc.DEFAULT_ENTRIES)
230
+ result = {"entries": [], "required_external_modules": 0, "missing_count": 0, "missing": [],
231
+ "missing_all": [], "other_problems": [], "local_modules": [], "checks": []}
232
+ if base is not None:
233
+ if not any(f.startswith(dc.PACKAGES) for f in base.files):
234
+ refuse(BASE_PROBLEM, f"{base.label}: no regular file under .lake/packages/ (the job restores only "
235
+ f"that directory)")
236
+ else:
237
+ result = dc.check(repo, commit, base, entries)
238
+ for pr in result["other_problems"]:
239
+ refuse(BASE_PROBLEM, f"not fillable from a donor: {pr}")
240
+ checks.extend(f"base: {c}" for c in result["checks"])
241
+ missing_all = result["missing_all"]
242
+
243
+ # 2. the donor checks
244
+ donor_checks: list[dict] = []
245
+
246
+ def donor_check(name: str, ok: bool, detail: str, code: str) -> None:
247
+ donor_checks.append({"check": name, "ok": ok, "detail": detail})
248
+ if ok:
249
+ checks.append(f"✓ donor {name}: {detail}")
250
+ else:
251
+ refuse(code, f"donor {name}: {detail}")
252
+
253
+ want_tc = core.git_show_bytes(repo, "./lean-toolchain", commit)
254
+ tc_path = donor / "lean-toolchain"
255
+ have_tc = tc_path.read_bytes() if tc_path.is_file() else None
256
+ if want_tc is None:
257
+ donor_check("lean-toolchain", False, f"no lean-toolchain committed at {commit[:12]}: nothing to compare "
258
+ f"the donor's with", DONOR_TOOLCHAIN)
259
+ elif have_tc is None:
260
+ donor_check("lean-toolchain", False, "the donor has no lean-toolchain file", DONOR_TOOLCHAIN)
261
+ elif have_tc != want_tc:
262
+ donor_check("lean-toolchain", False, f"{have_tc.decode('utf-8', 'replace').strip()!r} is not the "
263
+ f"commit's {want_tc.decode('utf-8', 'replace').strip()!r} (byte "
264
+ f"for byte)", DONOR_TOOLCHAIN)
265
+ else:
266
+ donor_check("lean-toolchain", True, f"= {commit[:12]}:lean-toolchain byte for byte "
267
+ f"({want_tc.decode('utf-8', 'replace').strip()})", DONOR_TOOLCHAIN)
268
+
269
+ names, pins = dc.manifest_pins(repo, commit, [])
270
+ donor_cache = dc.read_dir(donor, headers=True)
271
+ heads: dict[str, str] = {}
272
+ if not any(f.startswith(dc.PACKAGES) for f in donor_cache.files):
273
+ donor_check("cache", False, "no regular file under DONOR/.lake/packages/", DONOR_CACHE)
274
+ else:
275
+ pin_problems: list[str] = []
276
+ heads = dc.pin_check(donor_cache, names, pins, pin_problems, [])
277
+ for pr in pin_problems:
278
+ donor_check("manifest rev", False, pr, DONOR_MANIFEST)
279
+ if names and not pin_problems:
280
+ donor_check("manifest revs", True, f"all {len(names)} manifest git package(s) at the manifest's rev "
281
+ f"(the preflight's pin check)", DONOR_MANIFEST)
282
+ clean = 0
283
+ for name in sorted(heads):
284
+ ok, detail = git_status(donor / ".lake" / "packages" / name)
285
+ if ok:
286
+ clean += 1
287
+ else:
288
+ donor_check("source edits", False, f"{name}: {detail}", DONOR_SOURCE)
289
+ if heads and clean == len(heads):
290
+ donor_check("source edits", True, f"none in {clean} checkout(s) (git status, no "
291
+ f"assume-unchanged/skip-worktree entry, no untracked or "
292
+ f"ignored Lean source outside .lake/)", DONOR_SOURCE)
293
+
294
+ # 3. the artifact families of every missing module
295
+ index = family_index(donor_cache)
296
+ plan: list[dict] = []
297
+ for m in missing_all:
298
+ mpath = dc.module_path(m["module"])
299
+ files = module_families(index, m["package"], mpath)
300
+ entry = {"module": m["module"], "package": m["package"], "lacking": list(m["files"]),
301
+ "required_by": m["required_by"], "fillable": True, "files": [], "bytes": 0}
302
+ lacks = [ext for ext in (".olean", ".ilean") if not has_family(files, mpath, ext)]
303
+ if lacks:
304
+ entry["fillable"] = False
305
+ refuse(DONOR_LACKS, f"module {m['module']} ({m['package']}): the donor has no {'/'.join(lacks)} "
306
+ f"either; build it instead")
307
+ for rel in files:
308
+ size, digest = sha256_file(donor / rel)
309
+ entry["files"].append({"path": rel, "size": size, "sha256": digest})
310
+ entry["bytes"] += size
311
+ plan.append(entry)
312
+
313
+ # the .olean headers: the base's agree, and every candidate equals them
314
+ ref_header = None
315
+ base_headers = {header_key(h) for h in base.headers.values()} if base is not None else set()
316
+ if len(base_headers) > 1:
317
+ refuse(OLEAN_HEADER, f"the base cache's .olean files do not share one {dc.OLEAN_HEADER}-byte header "
318
+ f"({len(base_headers)} different): no single toolchain build to compare with")
319
+ elif not base_headers:
320
+ if missing_all:
321
+ refuse(OLEAN_HEADER, "the base cache holds no built .olean to compare the donor's headers with")
322
+ else:
323
+ ref_header = next(iter(base_headers))
324
+ if not ref_header.startswith(b"olean"):
325
+ refuse(OLEAN_HEADER, "the base cache's .olean files do not start with the olean marker")
326
+ ref_header = None
327
+ if ref_header is not None:
328
+ bad = sorted(f["path"] for e in plan for f in e["files"]
329
+ if f["path"].endswith(".olean") and header_key(donor_cache.headers.get(f["path"])) != ref_header)
330
+ n = sum(1 for e in plan for f in e["files"] if f["path"].endswith(".olean"))
331
+ if bad:
332
+ refuse(OLEAN_HEADER, f"{len(bad)} candidate .olean file(s) differ from the base's first "
333
+ f"{dc.OLEAN_HEADER} bytes (another Lean build): {', '.join(bad[:5])}")
334
+ elif n:
335
+ checks.append(f"✓ olean headers: {n} candidate .olean file(s) = the base's first {dc.OLEAN_HEADER} "
336
+ f"bytes")
337
+
338
+ # 4. additions only
339
+ additions = sorted(f["path"] for e in plan for f in e["files"])
340
+ roots = {lm.split("/", 1)[0] for lm in result["local_modules"]}
341
+ overlap, under_file, own = [], [], []
342
+ base_names = dict(base.members) if base is not None else {}
343
+ for n in base_list:
344
+ base_names.setdefault(n, "f")
345
+ for rel in additions:
346
+ if not rel.startswith(dc.PACKAGES) or rel.startswith(".lake/build/") or \
347
+ module_part(rel).split("/", 1)[0].split(".", 1)[0] in roots:
348
+ own.append(rel)
349
+ if args.deps_dir:
350
+ target = base_path / rel
351
+ if os.path.lexists(target):
352
+ overlap.append(rel)
353
+ parts = rel.split("/")
354
+ for i in range(1, len(parts)):
355
+ q = base_path.joinpath(*parts[:i])
356
+ if os.path.lexists(q) and (q.is_symlink() or not q.is_dir()):
357
+ under_file.append(rel)
358
+ break
359
+ if rel in base_names:
360
+ if rel not in overlap:
361
+ overlap.append(rel)
362
+ else:
363
+ parts = rel.split("/")
364
+ if any(base_names.get("/".join(parts[:i]), "d") != "d" for i in range(1, len(parts))):
365
+ if rel not in under_file:
366
+ under_file.append(rel)
367
+ if overlap:
368
+ refuse(BASE_OVERLAP, f"{len(overlap)} addition(s) already in the base (an addition never replaces a base "
369
+ f"member): {', '.join(overlap[:5])}")
370
+ if under_file:
371
+ refuse(BASE_OVERLAP, f"{len(under_file)} addition(s) under a base member that is not a directory: "
372
+ f"{', '.join(under_file[:5])}")
373
+ if own:
374
+ refuse(PACKAGE_BUILD, f"{len(own)} addition(s) under the package's own .lake/build or holding one of its "
375
+ f"root namespaces ({', '.join(sorted(roots)[:5])}): {', '.join(own[:5])}")
376
+ if additions and not (overlap or under_file or own):
377
+ checks.append(f"✓ additions only: none of the {len(additions)} file(s) is a base member or under one; none "
378
+ f"under the package's own .lake/build or root namespaces")
379
+
380
+ totals = {"missing_modules": len(missing_all), "fillable_modules": sum(1 for e in plan if e["fillable"]),
381
+ "files": len(additions), "bytes": sum(e["bytes"] for e in plan)}
382
+ ok = not refusals
383
+ written = None
384
+ if ok and plan_out:
385
+ base_sha = sha256_file(base_path)[1] if args.deps_tar else None
386
+ prov = {
387
+ "schema": PROVENANCE_SCHEMA,
388
+ "kind": PROVENANCE_KIND,
389
+ "created_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
390
+ "commit": commit,
391
+ "lean_toolchain": (want_tc or b"").decode("utf-8", "replace").strip(),
392
+ "manifest_revs": {n: pins[n] for n in names},
393
+ "base": {"kind": "tar" if args.deps_tar else "dir", "name": base_path.name, "sha256": base_sha},
394
+ "donor": {"name": donor.resolve().name, "package_heads": heads,
395
+ "lean_toolchain_sha256": hashlib.sha256(have_tc or b"").hexdigest(),
396
+ "olean_header_sha256": hashlib.sha256(ref_header).hexdigest() if ref_header else None},
397
+ "donor_checks": donor_checks,
398
+ "plan": [{"module": e["module"], "package": e["package"], "lacking": e["lacking"]} for e in plan],
399
+ "additions": [f for e in plan for f in e["files"]],
400
+ "filled_archive": None,
401
+ "next": ["write the new archive from the base's members plus these additions, never replacing a "
402
+ "base member (docs/receipts.md, step 5)",
403
+ "record the filled archive's sha256 here (step 6)",
404
+ "rerun `lean-pkg receipt slurm --preflight-deps` on the filled archive; submit only on "
405
+ "exit 0 (step 7)"],
406
+ }
407
+ try:
408
+ with open(plan_out, "x", encoding="utf-8") as f:
409
+ f.write("".join(a + "\n" for a in additions))
410
+ with open(prov_out, "x", encoding="utf-8") as f:
411
+ f.write(json.dumps(prov, indent=2, sort_keys=False) + "\n")
412
+ written = {"additions": str(plan_out), "provenance": str(prov_out)}
413
+ except OSError as e:
414
+ refuse(PLAN_OUT, f"--plan-out: cannot write ({type(e).__name__}: {e})")
415
+ ok = False
416
+
417
+ if getattr(args, "json_out", False):
418
+ core.print_json({
419
+ "ok": ok, "preflight_deps": True, "fill_plan": True, "commit": commit,
420
+ "entries": result["entries"], "required_external_modules": result["required_external_modules"],
421
+ "missing_count": result["missing_count"], "missing": result["missing"],
422
+ "base": {"kind": "tar" if args.deps_tar else "dir", "name": base_path.name,
423
+ "files": len(base.files) if base is not None else 0},
424
+ "donor": {"name": donor.resolve().name, "package_heads": heads},
425
+ "donor_checks": donor_checks, "plan": plan,
426
+ "not_fillable": result["other_problems"], "refusals": refusals, "totals": totals,
427
+ "plan_out": written, "checks": checks, "problems": [r["reason"] for r in refusals]})
428
+ return 0 if ok else 1
429
+ verdict = "ok" if ok else f"refused, {len(refusals)} reason(s)"
430
+ print(f"receipt slurm --preflight-deps --fill-plan: {verdict}; {totals['missing_modules']} missing module(s), "
431
+ f"{totals['files']} file(s), {totals['bytes']} byte(s) to add; "
432
+ + (f"wrote {plan_out} and {prov_out}" if written else "nothing written"))
433
+ for c in checks:
434
+ print(f" {c}")
435
+ for e in plan[:SHOW_MODULES]:
436
+ mark = "+" if e["fillable"] else "✗"
437
+ print(f" {mark} {e['package']} {e['module']}: {len(e['files'])} file(s), {e['bytes']} byte(s)")
438
+ if len(plan) > SHOW_MODULES:
439
+ print(f" (and {len(plan) - SHOW_MODULES} more module(s); --json lists every one)")
440
+ for r in refusals:
441
+ print(f" ✗ [{r['code']}] {r['reason']}")
442
+ if ok:
443
+ print("next: write the new archive yourself (base members unchanged, these additions appended; "
444
+ "docs/receipts.md, steps 5-7), then rerun --preflight-deps on it and submit only on exit 0")
445
+ return 0 if ok else 1