File size: 47,065 Bytes
091d8c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0988eb8
 
 
091d8c3
 
 
 
 
0988eb8
 
 
 
091d8c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c9ce02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
091d8c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8605993
 
 
 
 
 
 
 
 
091d8c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c9ce02
091d8c3
 
 
 
 
 
 
4c9ce02
091d8c3
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
#!/usr/bin/env python3
"""lbc: Lean build cache tool (pack, unpack, fetch, build keys) for the MoteMath Lean build cache.

Design: ../ARCHITECTURE.md. Standard library plus the `zstd` command-line tool; `fetch` also needs huggingface_hub.

  lbc.py key      <project_dir> [--package NAME]
  lbc.py pack     <package_dir> <out_dir> --package NAME --commit SHA --source-repo URL --license SPDX
                  --project-dir DIR [--toolchain TC] [--shard-bytes N] [--level N] [--exclude-setup-json]
  lbc.py unpack   <staging_dir> <package_dir> [--shards part-00001.tar.zst,...]
  lbc.py check    <staging_dir>
  lbc.py fetch    <project_dir> [--module M ...] [--package P ...] [--namespace MoteMath] [--dry-run] [--check]

`package_dir` is the directory that contains the package's `.lake/build` (the project root for the root package,
`.lake/packages/<name>` for a dependency).

`fetch` downloads only what is needed. With `--module`, it takes the import closure of those modules across every
package, using each build's `shards/modules.jsonl` import index, and downloads only the shards holding those modules
(plus the shard with package-level files). Without `--module` it fetches every shard of every package found. Mathlib
and its standard dependencies come from Mathlib's own cache (`lake exe cache get`).
"""
import argparse, hashlib, io, json, os, platform as _pf, re, subprocess, sys, tarfile, time

SCHEMA = "lean-build-manifest/1"
KEY_TAG = "lean-build-key-v1"
STD = {"mathlib", "batteries", "Qq", "aesop", "proofwidgets", "plausible", "LeanSearchClient", "importGraph", "Cli"}


def sha256_file(p, bufsize=1 << 20):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for b in iter(lambda: f.read(bufsize), b""):
            h.update(b)
    return h.hexdigest()


def compress_frame(raw, level):
    """One zstd frame (content size recorded). Uses the zstandard module when present, else Python 3.14's own
    compression.zstd, else the zstd CLI."""
    try:
        import zstandard
        return zstandard.ZstdCompressor(level=level, write_content_size=True).compress(raw)
    except ImportError:
        pass
    try:
        from compression import zstd as _z  # Python 3.14+; one-shot compress records the content size
        return _z.compress(raw, level=level)
    except ImportError:
        # --stream-size records the content size in the frame header, as the library paths do (2026-11-13)
        return subprocess.run(["zstd", f"-{level}", "-q", "-c", f"--stream-size={len(raw)}"], input=raw,
                              capture_output=True, check=True).stdout


def decompress_frame(comp):
    try:
        import zstandard
        # decompressobj, not decompress(): frames written by the zstd CLI from a pipe (every build packed before
        # 2026-11-13) do not record their content size, and ZstdDecompressor.decompress() refuses those
        # ("could not determine content size in frame header"), found by the independent restore test on 2026-11-13
        return zstandard.ZstdDecompressor().decompressobj().decompress(comp)
    except ImportError:
        pass
    try:
        from compression import zstd as _z  # Python 3.14+ (no zstd install needed, e.g. on Windows)
        return _z.decompress(comp)
    except ImportError:
        return subprocess.run(["zstd", "-d", "-q", "-c"], input=comp, capture_output=True, check=True).stdout


def platform_triple():
    """Lean's own target triple for this machine (what `lean --version` prints), e.g. x86_64-unknown-linux-gnu,
    aarch64-apple-darwin, x86_64-w64-windows-gnu. Windows was 'pc-windows-msvc' before 2026-11-10; no Windows build
    was ever keyed with it."""
    m = _pf.machine().lower()
    arch = {"amd64": "x86_64", "x86_64": "x86_64", "aarch64": "aarch64", "arm64": "aarch64"}.get(m, m)
    osn = {"linux": "unknown-linux-gnu", "darwin": "apple-darwin", "win32": "w64-windows-gnu"}.get(sys.platform, sys.platform)
    return f"{arch}-{osn}"


# ---------------------------------------------------------------- licence detection (gate G5)

LICENSE_NAME = re.compile(r"(?i)^(licen[cs]e|copying)([.\-_].*)?$")


def classify_license(text):
    """SPDX id for the two licences the cache redistributes, else UNKNOWN (a licence file that is neither)."""
    t = " ".join(text.split()).lower()
    if "apache license" in t and "version 2.0" in t:
        return "Apache-2.0"
    if "mit license" in t or "permission is hereby granted, free of charge" in t:
        return "MIT"
    return "UNKNOWN"


def detect_license(pkg_dir):
    """Licence of the package in `pkg_dir`: {"spdx", "file", "from"}.

    Looks for LICENSE / LICENCE / COPYING (any case, any extension) in the package directory, then in each parent up to
    the top of the git repository that contains it. A Lake project kept in a subdirectory (openai/math `lean/`,
    RogersRamanujan-artifacts/<artifact>) is covered by its repository's licence file; before 2026-11-09 only the package
    directory was searched and such packages were skipped as NONE. The search never leaves the repository: a dependency
    checkout under .lake/packages is its own repository, so it never inherits the consumer's licence.
    """
    d = os.path.abspath(pkg_dir)
    r = subprocess.run(["git", "-C", d, "rev-parse", "--show-toplevel"], capture_output=True, text=True)
    top = os.path.abspath(r.stdout.strip()) if r.returncode == 0 and r.stdout.strip() else d
    try:
        inside = os.path.commonpath([os.path.normcase(top), os.path.normcase(d)]) == os.path.normcase(top)
    except ValueError:
        inside = False
    if not inside:
        top = d
    cur = d
    while True:
        try:
            names = sorted(n for n in os.listdir(cur) if LICENSE_NAME.match(n) and os.path.isfile(os.path.join(cur, n)))
        except OSError:
            names = []
        if names:
            f = os.path.join(cur, names[0])
            with open(f, encoding="utf-8", errors="replace") as fh:
                spdx = classify_license(fh.read())
            return {"spdx": spdx, "file": f, "from": "package" if cur == d else "repository"}
        if os.path.normcase(cur) == os.path.normcase(top) or os.path.dirname(cur) == cur:
            return {"spdx": "NONE", "file": None, "from": None}
        cur = os.path.dirname(cur)


def cmd_license(a):
    print(json.dumps(detect_license(a.package_dir)))


# ---------------------------------------------------------------- build keys

def read_manifest(d):
    p = os.path.join(d, "lake-manifest.json")
    if not os.path.exists(p):
        return None
    with open(p, encoding="utf-8") as f:
        return json.load(f)


def packages_dir(project_dir):
    root = read_manifest(project_dir) or {}
    return os.path.join(project_dir, root.get("packagesDir", ".lake/packages"))


def package_dir(project_dir, name):
    """Directory of a package: the project itself, a local path dependency (manifest "dir"), or .lake/packages/<name>."""
    root = read_manifest(project_dir) or {}
    if name == root.get("name"):
        return project_dir
    for p in root.get("packages", []):
        if p.get("name") == name and p.get("type") == "path" and p.get("dir"):
            return os.path.normpath(os.path.join(project_dir, p["dir"]))
    d = os.path.join(packages_dir(project_dir), name)
    # Lake drops the «» quotes of a package name in its directory name (.lake/packages/doc-gen4 for «doc-gen4»)
    plain = os.path.join(packages_dir(project_dir), name.strip("«»"))
    return d if os.path.isdir(d) or not os.path.isdir(plain) else plain


def closure(project_dir, package=None):
    """(name, rev) closure of `package` (default: root) using the root manifest's revisions."""
    root = read_manifest(project_dir)
    if root is None:
        raise SystemExit(f"no lake-manifest.json in {project_dir}")
    revs = {p["name"]: p.get("rev", "") for p in root.get("packages", [])}
    root_name = root.get("name")
    root_rev = subprocess.run(["git", "-C", project_dir, "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip()
    if package in (None, root_name):
        names = set(revs)
        own = (root_name, root_rev)
    else:
        if package not in revs:
            raise SystemExit(f"{package} not in the root manifest")
        pm = read_manifest(package_dir(project_dir, package))
        names = {p["name"] for p in (pm or {}).get("packages", [])}
        missing = sorted(n for n in names if n not in revs)
        if missing:
            raise SystemExit(f"{package} requires packages absent from the root manifest: {missing}")
        own = (package, revs[package])
    return sorted({(n, revs[n]) for n in names} | {own})


def build_key(toolchain, plat, cl, changes=None):
    s = f"{KEY_TAG}\n{toolchain}\n{plat}\n" + json.dumps(cl, separators=(",", ":"))
    if changes:  # sources that differ from their pinned commit (e.g. a project's dependency patches): a different build
        s += "\nsource-changes:" + json.dumps(sorted(changes.items()), separators=(",", ":"))
    return hashlib.sha256(s.encode()).hexdigest()[:16]


def source_changes(project_dir, cl):
    """{package: sha256[:16]} for every non-root package in the closure whose checkout differs from its pinned commit
    (git diff against HEAD plus untracked files, outside .lake). Empty for unmodified checkouts, so their keys are
    unchanged. A dependency patched by the project (openai/math lean/patches) gets a key of its own, and so does
    every package built on top of it."""
    root = (read_manifest(project_dir) or {}).get("name")
    out = {}
    for name, _rev in cl:
        if name == root:
            continue
        d = package_dir(project_dir, name)
        if not os.path.exists(os.path.join(d, ".git")):
            continue
        spec = ["--", ".", ":(exclude).lake"]
        diff = subprocess.run(["git", "-C", d, "diff", "--binary", "HEAD"] + spec, capture_output=True).stdout
        unt = subprocess.run(["git", "-C", d, "ls-files", "--others", "--exclude-standard", "-z"] + spec,
                             capture_output=True).stdout.split(b"\0")
        unt = sorted(u for u in unt if u)
        if not diff and not unt:
            continue
        h = hashlib.sha256(diff)
        for u in unt:
            h.update(b"\0" + u + b"\0")
            with open(os.path.join(d, u.decode()), "rb") as f:
                h.update(f.read())
        out[name] = h.hexdigest()[:16]
    return out


def key_for(project_dir, package=None):
    """(build key, closure, source changes) of a package in a project checkout."""
    tc, plat = toolchain_of(project_dir), platform_triple()
    cl = closure(project_dir, package)
    ch = source_changes(project_dir, cl)
    return build_key(tc, plat, cl, ch), cl, ch


def toolchain_of(project_dir):
    with open(os.path.join(project_dir, "lean-toolchain"), encoding="utf-8") as f:
        return f.read().strip()


# ---------------------------------------------------------------- imports

MODIFIERS = {"public", "private", "meta"}


def parse_imports(path):
    """Module names imported by a Lean source file's header, or None if the file is missing.

    The header is read as a token stream, as Lean's grammar does: `module`? `prelude`? then any number of
    `[public|private|meta]* import [all|runtime]? <ident>`, where the identifier may sit on a later line.
    The header ends at the first token that does not fit.
    """
    try:
        text = open(path, encoding="utf-8", errors="replace").read()
    except FileNotFoundError:
        return None
    text = re.sub(r"/-.*?-/", " ", text, flags=re.S)
    text = "\n".join(line.split("--", 1)[0] for line in text.splitlines())
    toks = text.split()
    out, i = [], 0
    while i < len(toks) and toks[i] in ("module", "prelude"):
        i += 1
    while i < len(toks):
        j = i
        while j < len(toks) and toks[j] in MODIFIERS:
            j += 1
        if j >= len(toks) or toks[j] != "import":
            break
        j += 1
        while j < len(toks) and toks[j] in ("all", "runtime"):
            j += 1
        if j >= len(toks):
            break
        out.append(toks[j])
        i = j + 1
    return out


def cmd_reindex(a):
    """Rewrite shards/modules.jsonl of a staged build from its index and the package sources, then SHA256SUMS."""
    out, pkg_dir = os.path.abspath(a.staging_dir), os.path.abspath(a.package_dir)
    man, idx = load(out)
    mod_shard = {}
    for e in idx.values():
        if e["module"]:
            mod_shard.setdefault(e["module"], set()).add(e["shard"])
    mods = sorted({e["module"] for e in idx.values() if e["module"] and e["path"].endswith(".olean")})
    unparsed = 0
    with open(os.path.join(out, "shards", "modules.jsonl"), "w", encoding="utf-8", newline="\n") as f:
        for m in mods:
            imps = parse_imports(os.path.join(pkg_dir, *m.split(".")) + ".lean")
            unparsed += imps is None
            f.write(json.dumps({"module": m, "shards": sorted(mod_shard.get(m, [])), "imports": imps}, separators=(",", ":")) + "\n")
    if "modules_index" not in man.get("features", []) or man.get("modules_without_source") != unparsed:
        man.setdefault("features", []).append("modules_index") if "modules_index" not in man.get("features", []) else None
        man["modules_without_source"] = unparsed
        with open(os.path.join(out, "manifest.json"), "w", encoding="utf-8", newline="\n") as f:
            json.dump(man, f, indent=1)
    write_sums(out)
    print(json.dumps({"package": man["package"], "modules": len(mods), "modules_without_source": unparsed}))


# ---------------------------------------------------------------- pack

def module_of(rel):
    """Module name for a build file, or None for package-level files."""
    for pre in (".lake/build/lib/lean/", ".lake/build/ir/"):
        if rel.startswith(pre):
            parts = rel[len(pre):].split("/")
            return ".".join(parts[:-1] + [parts[-1].split(".")[0]])
    return None


def list_build_files(package_dir, exclude_setup_json):
    root = os.path.join(package_dir, ".lake", "build")
    if not os.path.isdir(root):
        raise SystemExit(f"no .lake/build under {package_dir}")
    out, skipped = [], []
    for dp, dns, fns in os.walk(root, followlinks=False):
        dns.sort()
        for fn in fns:
            full = os.path.join(dp, fn)
            rel = os.path.relpath(full, package_dir).replace(os.sep, "/")
            if os.path.islink(full) or not os.path.isfile(full):
                skipped.append((rel, "not a regular file")); continue
            if exclude_setup_json and rel.endswith(".setup.json"):
                skipped.append((rel, "setup.json excluded")); continue
            out.append(rel)
    return out, skipped


def deterministic_info(rel, size, executable):
    ti = tarfile.TarInfo(rel)
    ti.size, ti.mtime, ti.uid, ti.gid, ti.uname, ti.gname = size, 0, 0, 0, "", ""
    ti.mode = 0o755 if executable else 0o644
    ti.type = tarfile.REGTYPE
    return ti


def cmd_pack(a):
    pkg_dir = os.path.abspath(a.package_dir)
    out = os.path.abspath(a.out_dir)
    files, skipped = list_build_files(pkg_dir, a.exclude_setup_json)
    if not files:
        # e.g. a project with no default targets: `lake build` exits 0 and builds nothing. Fail before creating the
        # output folder, so the caller sees a non-zero exit and no half-made build folder (2026-11-10).
        raise SystemExit(f"no build outputs under {pkg_dir}/.lake/build: nothing to pack")
    os.makedirs(os.path.join(out, "shards"), exist_ok=False)
    keyed = sorted(files, key=lambda r: ((module_of(r) or ""), r.encode()))
    toolchain = a.toolchain or toolchain_of(a.project_dir)
    plat = platform_triple()
    rootname = read_manifest(a.project_dir).get("name")
    cl = closure(a.project_dir, None if a.package == rootname else a.package)
    changes = source_changes(a.project_dir, cl)
    key = build_key(toolchain, plat, cl, changes)
    shards, index, mod_shard, frames = [], [], {}, []
    # one frame per module (package-level files first, as module None): a deterministic tar, compressed as its own
    # zstd frame. Frames are appended to the current shard; a shard is a valid multi-frame zstd file.
    groups = []
    for rel in keyed:
        mod = module_of(rel)
        if not groups or groups[-1][0] != mod:
            groups.append((mod, []))
        groups[-1][1].append(rel)

    def build_tar(group):
        mod, rels = group
        buf = io.BytesIO(); ents = []
        with tarfile.open(fileobj=buf, mode="w", format=tarfile.GNU_FORMAT) as tf:
            for rel in rels:
                full = os.path.join(pkg_dir, rel)
                with open(full, "rb") as f:
                    data = f.read()
                tf.addfile(deterministic_info(rel, len(data), os.access(full, os.X_OK)), io.BytesIO(data))
                ents.append((rel, hashlib.sha256(data).hexdigest(), len(data)))
        raw = buf.getvalue()
        return mod, ents, len(raw), compress_frame(raw, a.level)

    from concurrent.futures import ThreadPoolExecutor
    workers = max(1, os.cpu_count() or 1)
    st = {"f": None, "name": None, "off": 0, "raw": 0, "files": 0, "first": None, "last": None, "h": None}

    def close_shard():
        st["f"].close()
        p = os.path.join(out, st["name"])
        shards.append({"name": st["name"], "sha256": st["h"].hexdigest(), "bytes": os.path.getsize(p),
                       "bytes_uncompressed": st["raw"], "files": st["files"],
                       "first_module": st["first"], "last_module": st["last"]})

    total = 0
    with ThreadPoolExecutor(workers) as ex:
        for i in range(0, len(groups), 4 * workers):
            for mod, ents, rawlen, comp in ex.map(build_tar, groups[i:i + 4 * workers]):
                if st["f"] is None or st["raw"] >= a.shard_bytes:
                    if st["f"] is not None:
                        close_shard()
                    st["name"] = f"shards/part-{len(shards):05d}.tar.zst"
                    st["f"] = open(os.path.join(out, st["name"]), "wb")
                    st.update(off=0, raw=0, files=0, first=mod, h=hashlib.sha256())
                st["f"].write(comp); st["h"].update(comp)
                frames.append({"shard": st["name"], "offset": st["off"], "length": len(comp), "raw_length": rawlen,
                               "module": mod, "files": len(ents), "sha256": hashlib.sha256(comp).hexdigest()})
                for rel, h, size in ents:
                    index.append({"path": rel, "sha256": h, "bytes": size, "shard": st["name"], "module": mod})
                    total += size
                if mod:
                    mod_shard.setdefault(mod, set()).add(st["name"])
                st["off"] += len(comp); st["raw"] += rawlen; st["files"] += len(ents); st["last"] = mod
    if st["f"] is not None:
        close_shard()
    with open(os.path.join(out, "shards", "frames.jsonl"), "w", encoding="utf-8", newline="\n") as f:
        for e in frames:
            f.write(json.dumps(e, separators=(",", ":")) + "\n")
    with open(os.path.join(out, "shards", "index.jsonl"), "w", encoding="utf-8", newline="\n") as f:
        for e in index:
            f.write(json.dumps(e, separators=(",", ":")) + "\n")
    mods = sorted({e["module"] for e in index if e["module"] and e["path"].endswith(".olean")})
    unparsed = 0
    with open(os.path.join(out, "shards", "modules.jsonl"), "w", encoding="utf-8", newline="\n") as f:
        for m in mods:
            imps = parse_imports(os.path.join(pkg_dir, *m.split(".")) + ".lean")
            unparsed += imps is None
            f.write(json.dumps({"module": m, "shards": sorted(mod_shard.get(m, [])), "imports": imps}, separators=(",", ":")) + "\n")
    man = {
        "schema": SCHEMA, "features": ["modules_index", "module_frames"], "frames": len(frames), "package": a.package, "source_repo": a.source_repo,
        "commit": a.commit, "license": a.license, "toolchain": toolchain, "platform": plat, "build_key": key,
        "closure": [list(x) for x in cl], "modules_built": len(mods), "modules_without_source": unparsed,
        "files": len(index), "bytes_uncompressed": total, "bytes_compressed": sum(s["bytes"] for s in shards),
        "shard_target_bytes_uncompressed": a.shard_bytes, "shards": shards, "zstd_level": a.level,
        "excluded": {"setup_json": bool(a.exclude_setup_json), "skipped": skipped[:50], "skipped_count": len(skipped)},
        "packed_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "unofficial": True,
    }
    if changes:
        man["source_changes"] = changes  # packages built from sources that differ from their pinned commit
    with open(os.path.join(a.project_dir, "lake-manifest.json"), "rb") as s, open(os.path.join(out, "lake-manifest.json"), "wb") as d:
        d.write(s.read())
    # manifest.json is the LAST file written, and it appears in one step: a build folder with a manifest is complete,
    # one without is an interrupted pack (build-group.sh repacks it). SHA256SUMS.txt already lists the manifest's hash.
    man_bytes = json.dumps(man, indent=1).encode("utf-8")
    write_sums(out, extra={"manifest.json": hashlib.sha256(man_bytes).hexdigest()})
    tmp = os.path.join(out, "manifest.json.lbc-tmp")
    with open(tmp, "wb") as f:
        f.write(man_bytes)
    os.replace(tmp, os.path.join(out, "manifest.json"))
    print(json.dumps({k: man[k] for k in ("package", "build_key", "modules_built", "modules_without_source", "files",
                                         "bytes_uncompressed", "bytes_compressed")} | {"shards": len(shards)}))


def write_sums(out, extra=None):
    """SHA256SUMS.txt over every file in the build folder; `extra` adds rows for files written afterwards."""
    rows = dict(extra or {})
    for dp, _, fns in os.walk(out):
        for fn in sorted(fns):
            if fn != "SHA256SUMS.txt" and not fn.endswith(".lbc-tmp"):
                p = os.path.join(dp, fn)
                rows.setdefault(os.path.relpath(p, out).replace(os.sep, "/"), sha256_file(p))
    with open(os.path.join(out, "SHA256SUMS.txt"), "w", encoding="utf-8", newline="\n") as f:
        for r, h in sorted(rows.items()):
            f.write(f"{h}  {r}\n")


# ---------------------------------------------------------------- check, unpack

def load(staging):
    with open(os.path.join(staging, "manifest.json"), encoding="utf-8") as f:
        man = json.load(f)
    idx = {}
    with open(os.path.join(staging, "shards", "index.jsonl"), encoding="utf-8") as f:
        for line in f:
            if line.strip():
                e = json.loads(line); idx[e["path"]] = e
    return man, idx


def cmd_check(a):
    man, idx = load(a.staging_dir)
    bad = [s["name"] for s in man["shards"] if sha256_file(os.path.join(a.staging_dir, s["name"])) != s["sha256"]]
    for b in bad:
        print(f"MISMATCH {b}")
    print(f"shards={len(man['shards'])} bad={len(bad)} files_in_index={len(idx)}")
    sys.exit(1 if bad else 0)


def safe_rel(name):
    parts = name.split("/")
    return (name.startswith(".lake/build/") and not name.startswith("/") and "\\" not in name
            and all(p not in ("", ".", "..") for p in parts))


def write_member(dest, name, data, mode, now):
    out = os.path.join(dest, *name.split("/"))
    os.makedirs(os.path.dirname(out), exist_ok=True)
    tmp = out + ".lbc-tmp"
    with open(tmp, "wb") as f:
        f.write(data)
    os.chmod(tmp, mode & 0o777)
    os.replace(tmp, out)
    os.utime(out, (now, now))


def check_member(m, idx, shard_name, data):
    if not m.isreg() or not safe_rel(m.name):
        raise SystemExit(f"refusing unsafe member {m.name!r} in {shard_name}")
    e = idx.get(m.name)
    if e is None or e["shard"] != shard_name:
        raise SystemExit(f"member not in index for this shard: {m.name}")
    if hashlib.sha256(data).hexdigest() != e["sha256"] or len(data) != e["bytes"]:
        raise SystemExit(f"file hash mismatch: {m.name}")


def extract_shard(shard_path, shard_name, idx, dest, now):
    """Legacy builds (one zstd stream per shard): stream the whole shard."""
    n = 0
    # resolve symlinks first: the Hugging Face cache hands back a symlink, and zstd silently skips symlinks
    z = subprocess.Popen(["zstd", "-d", "-q", "-c", os.path.realpath(shard_path)], stdout=subprocess.PIPE)
    with tarfile.open(fileobj=z.stdout, mode="r|") as tf:
        for m in tf:
            data = tf.extractfile(m).read() if m.isreg() else b""
            check_member(m, idx, shard_name, data)
            write_member(dest, m.name, data, m.mode, now)
            n += 1
    if z.wait() != 0:
        raise SystemExit(f"zstd failed on {shard_name}")
    return n


def extract_frame(comp, fr, idx, dest, now):
    """Verify one module frame (compressed hash, raw length), then extract its tar with per-file hash checks."""
    if len(comp) != fr["length"] or hashlib.sha256(comp).hexdigest() != fr["sha256"]:
        raise SystemExit(f"frame hash mismatch: {fr['shard']} offset {fr['offset']} ({fr['module']})")
    raw = decompress_frame(comp)
    if len(raw) != fr["raw_length"]:
        raise SystemExit(f"frame length mismatch: {fr['module']}")
    n = 0
    with tarfile.open(fileobj=io.BytesIO(raw), mode="r:") as tf:
        for m in tf.getmembers():
            data = tf.extractfile(m).read() if m.isreg() else b""
            check_member(m, idx, fr["shard"], data)
            if idx[m.name]["module"] != fr["module"]:
                raise SystemExit(f"member {m.name} is not in module {fr['module']}")
            write_member(dest, m.name, data, m.mode, now)
            n += 1
    if n != fr["files"]:
        raise SystemExit(f"frame {fr['module']}: extracted {n} files, index says {fr['files']}")
    return n


def load_frames(path):
    out = []
    for line in open(path, encoding="utf-8"):
        if line.strip():
            out.append(json.loads(line))
    return out


def extract_frames_from_file(path, frames, idx, dest, now):
    n = 0
    with open(os.path.realpath(path), "rb") as f:
        for fr in frames:
            f.seek(fr["offset"])
            n += extract_frame(f.read(fr["length"]), fr, idx, dest, now)
    return n


def cmd_unpack(a):
    man, idx = load(a.staging_dir)
    framed = "module_frames" in man.get("features", [])
    frames = load_frames(os.path.join(a.staging_dir, "shards", "frames.jsonl")) if framed else []
    want = set(a.shards.split(",")) if a.shards else None
    dest, now, seen, used = os.path.abspath(a.package_dir), time.time(), 0, 0
    for s in man["shards"]:
        if want is not None and s["name"] not in want and os.path.basename(s["name"]) not in want:
            continue
        sp = os.path.join(a.staging_dir, s["name"])
        if sha256_file(sp) != s["sha256"]:
            raise SystemExit(f"shard hash mismatch: {s['name']}")
        if framed:
            got = extract_frames_from_file(sp, [fr for fr in frames if fr["shard"] == s["name"]], idx, dest, now)
        else:
            got = extract_shard(sp, s["name"], idx, dest, now)
        if got != s["files"]:
            raise SystemExit(f"{s['name']}: extracted {got} files, manifest says {s['files']}")
        seen += got
        used += 1
    if want is None and seen != len(idx):
        raise SystemExit(f"extracted {seen} files, index has {len(idx)}")
    print(f"unpacked {seen} files from {used} of {len(man['shards'])} shards into {dest} (all sha256 verified)")


# ---------------------------------------------------------------- strip (2026-11-12)

STRIP_DEFAULT = r"^\.lake/build/bin/"


def cmd_strip(a):
    """Remove files matching --pattern (default: everything under .lake/build/bin/, i.e. the executables and their
    response, trace and hash files) from a staged build folder, in place, without rebuilding.
    Only the frames that hold such files are rewritten; every other frame keeps its bytes, so the other shards keep
    their hashes. frames.jsonl offsets, index.jsonl, the manifest (shard hashes, sizes, file counts) and SHA256SUMS.txt
    are updated, and the manifest records what was removed under "stripped". The build key does not change: it is
    computed from the toolchain, platform and dependency closure, not from the contents.
    User decision 2026-11-12: strip native executables from the public builds; libraries (.so, .a, .o) stay because
    Lake needs them for the packages' own library targets."""
    d = os.path.abspath(a.staging_dir)
    pat = re.compile(a.pattern or STRIP_DEFAULT)
    man, idx = load(d)
    gone = sorted(p for p in idx if pat.search(p))
    if not gone:
        print(json.dumps({"stripped": 0})); return
    gone_set = set(gone)
    if "module_frames" not in man.get("features", []):
        # legacy build (one zstd stream per shard, packed before 2026-11-09): rewrite each affected shard whole
        removed_bytes = 0
        for s in man["shards"]:
            if not any(idx[p]["shard"] == s["name"] for p in gone):
                continue
            sp = os.path.join(d, s["name"])
            if sha256_file(sp) != s["sha256"]:
                raise SystemExit(f"shard hash mismatch before strip: {s['name']}")
            raw = subprocess.run(["zstd", "-d", "-q", "-c", sp], capture_output=True, check=True).stdout
            buf, n = io.BytesIO(), 0
            with tarfile.open(fileobj=io.BytesIO(raw), mode="r:") as tf, \
                    tarfile.open(fileobj=buf, mode="w", format=tarfile.GNU_FORMAT) as tw:
                for m in tf.getmembers():
                    if m.name in gone_set:
                        removed_bytes += m.size; continue
                    data = tf.extractfile(m).read() if m.isreg() else b""
                    tw.addfile(deterministic_info(m.name, len(data), bool(m.mode & 0o111)), io.BytesIO(data))
                    n += 1
            comp = compress_frame(buf.getvalue(), man.get("zstd_level", 19))
            with open(sp + ".lbc-tmp", "wb") as f:
                f.write(comp)
            os.replace(sp + ".lbc-tmp", sp)
            s.update(sha256=hashlib.sha256(comp).hexdigest(), bytes=len(comp), files=n)
            if "bytes_uncompressed" in s:
                s["bytes_uncompressed"] = len(buf.getvalue())
        new_frames = None
    else:
        new_frames, removed_bytes = _strip_frames(d, man, idx, gone, gone_set)
    _strip_finish(d, man, idx, gone, gone_set, new_frames, removed_bytes, pat)


def _strip_frames(d, man, idx, gone, gone_set):
    frames = load_frames(os.path.join(d, "shards", "frames.jsonl"))
    by_shard = {}
    for fr in frames:
        by_shard.setdefault(fr["shard"], []).append(fr)
    new_frames, removed_bytes = [], 0
    for s in man["shards"]:
        frs = sorted(by_shard.get(s["name"], []), key=lambda f: f["offset"])
        if not any(idx[p]["shard"] == s["name"] for p in gone):
            new_frames += frs; continue
        sp = os.path.join(d, s["name"])
        if sha256_file(sp) != s["sha256"]:
            raise SystemExit(f"shard hash mismatch before strip: {s['name']}")
        blob = open(sp, "rb").read()
        out, off, h, raw_total, nfiles = io.BytesIO(), 0, hashlib.sha256(), 0, 0
        for fr in frs:
            comp = blob[fr["offset"]:fr["offset"] + fr["length"]]
            if hashlib.sha256(comp).hexdigest() != fr["sha256"]:
                raise SystemExit(f"frame hash mismatch: {fr['shard']} {fr['offset']}")
            raw = decompress_frame(comp)
            keep_n = fr["files"]
            with tarfile.open(fileobj=io.BytesIO(raw), mode="r:") as tf:
                members = tf.getmembers()
                if any(m.name in gone_set for m in members):
                    buf = io.BytesIO()
                    with tarfile.open(fileobj=buf, mode="w", format=tarfile.GNU_FORMAT) as tw:
                        keep_n = 0
                        for m in members:
                            if m.name in gone_set:
                                removed_bytes += m.size; continue
                            data = tf.extractfile(m).read() if m.isreg() else b""
                            tw.addfile(deterministic_info(m.name, len(data), bool(m.mode & 0o111)), io.BytesIO(data))
                            keep_n += 1
                    raw = buf.getvalue()
                    comp = compress_frame(raw, man.get("zstd_level", 19)) if keep_n else b""
            if not comp:
                continue  # a frame that held only stripped files disappears
            out.write(comp); h.update(comp)
            new_frames.append(dict(fr, offset=off, length=len(comp), raw_length=len(raw), files=keep_n,
                                   sha256=hashlib.sha256(comp).hexdigest()))
            off += len(comp); raw_total += len(raw); nfiles += keep_n
        tmp = sp + ".lbc-tmp"
        with open(tmp, "wb") as f:
            f.write(out.getvalue())
        os.replace(tmp, sp)
        s.update(sha256=h.hexdigest(), bytes=off, bytes_uncompressed=raw_total, files=nfiles)
    return new_frames, removed_bytes


def _strip_finish(d, man, idx, gone, gone_set, new_frames, removed_bytes, pat):
    index = [e for p, e in idx.items() if p not in gone_set]
    if new_frames is not None:
        with open(os.path.join(d, "shards", "frames.jsonl"), "w", encoding="utf-8", newline="\n") as f:
            for e in new_frames:
                f.write(json.dumps(e, separators=(",", ":")) + "\n")
        man["frames"] = len(new_frames)
    with open(os.path.join(d, "shards", "index.jsonl"), "w", encoding="utf-8", newline="\n") as f:
        for e in index:
            f.write(json.dumps(e, separators=(",", ":")) + "\n")
    man["files"] = len(index)
    man["bytes_uncompressed"] = sum(e["bytes"] for e in index)
    man["bytes_compressed"] = sum(s["bytes"] for s in man["shards"])
    man.setdefault("stripped", []).append({"at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
                                           "pattern": pat.pattern, "files": gone, "bytes": removed_bytes,
                                           "reason": "native executables are not redistributed (decision 2026-11-12)"})
    man_bytes = json.dumps(man, indent=1).encode("utf-8")
    write_sums(d, extra={"manifest.json": hashlib.sha256(man_bytes).hexdigest()})
    tmp = os.path.join(d, "manifest.json.lbc-tmp")
    with open(tmp, "wb") as f:
        f.write(man_bytes)
    os.replace(tmp, os.path.join(d, "manifest.json"))
    print(json.dumps({"stripped": len(gone), "bytes": removed_bytes, "files_left": len(index),
                      "bytes_compressed": man["bytes_compressed"]}))


# ---------------------------------------------------------------- fetch from Hugging Face

def _resolve(url, token):
    """Follow the Hub's redirect once by hand, so the CDN gets no Authorization header; return (url, needs_auth)."""
    import urllib.request
    import urllib.error

    class NoRedirect(urllib.request.HTTPRedirectHandler):
        def redirect_request(self, *args, **kw):
            return None

    req = urllib.request.Request(url, method="HEAD", headers={"Authorization": f"Bearer {token}"} if token else {})
    try:
        urllib.request.build_opener(NoRedirect).open(req, timeout=60)
        return url, True
    except urllib.error.HTTPError as e:
        if e.code in (301, 302, 303, 307, 308) and e.headers.get("Location"):
            from urllib.parse import urljoin
            return urljoin(url, e.headers["Location"]), False
        raise


def _range_get(url, start, end, token, with_auth):
    import urllib.request
    h = {"Range": f"bytes={start}-{end}"}
    if with_auth and token:
        h["Authorization"] = f"Bearer {token}"
    for attempt in range(4):
        try:
            with urllib.request.urlopen(urllib.request.Request(url, headers=h), timeout=300) as r:
                body = r.read()
                if r.status == 200:  # the server ignored the range: slice the whole body
                    body = body[start:end + 1]
                if len(body) != end - start + 1:
                    raise IOError(f"short range read {len(body)} of {end - start + 1}")
                return body
        except Exception:
            if attempt == 3:
                raise
            time.sleep(2 * (attempt + 1))


def cmd_fetch(a):
    from huggingface_hub import hf_hub_download, hf_hub_url, get_token
    from concurrent.futures import ThreadPoolExecutor
    proj = os.path.abspath(a.project_dir)
    root = read_manifest(proj)
    if root is None:
        raise SystemExit("no lake-manifest.json: run `lake exe cache get` (or `lake update`) in the project first")
    tc, plat = toolchain_of(proj), platform_triple()
    pkgs = [root["name"]] + [p["name"] for p in root.get("packages", []) if p["name"] not in STD]
    # Mathlib and the other standard packages normally come from Mathlib's own cache. When that cache has nothing for
    # this project (its Lean version differs from Mathlib's, as for fermats-last-theorem), they are fetched from here
    # too: any standard package that is checked out and has a published build for its exact key, unless it already has
    # at least as many compiled modules as that build (then Mathlib's cache provided it). `lake exe cache get` compiles
    # a few Mathlib and Batteries modules for its own tool, so "has some .olean files" is not the test.
    def n_oleans(d):
        lib = os.path.join(d, ".lake", "build", "lib")
        return sum(f.endswith(".olean") for _, _, fs in os.walk(lib) for f in fs) if os.path.isdir(lib) else 0
    std_missing = [p["name"] for p in root.get("packages", []) if p["name"] in STD
                   and os.path.isdir(package_dir(proj, p["name"]))]
    if a.package:
        pkgs = [p for p in pkgs if p in set(a.package)]
        std_missing = [p for p in std_missing if p in set(a.package)]
    # Lake checks out only the dependencies the project's targets need (teorth/analysis lists doc-gen4 and its
    # dependencies, which `lake exe cache get` leaves out). Such a package is skipped with a note, not an error
    # (found by the independent restore test on 2026-11-13; before, fetch stopped here).
    missing_deps = [p for p in pkgs if p != root["name"] and not os.path.isdir(package_dir(proj, p))]
    for p in missing_deps:
        print(f"{p}: not checked out by Lake (not needed by this project's targets); skipped")
    pkgs = [p for p in pkgs if p not in missing_deps]
    if not os.path.isdir(packages_dir(proj)) and len(root.get("packages", [])) > 0 and missing_deps:
        print("note: no dependency is checked out; run `lake exe cache get` (or `lake env true`) first if the build fails")
    cache = os.path.join(proj, ".lake", "lbc-cache")
    token = get_token()
    cat_path = hf_hub_download(f"{a.namespace}/lean-builds-index", "catalog/builds.jsonl", repo_type="dataset",
                               cache_dir=cache)
    catalog = {}
    for line in open(cat_path, encoding="utf-8"):
        if line.strip():
            r = json.loads(line)
            catalog[r["build_key"]] = r
    builds = {}
    for p in pkgs + std_missing:
        pdir = package_dir(proj, p)
        key = key_for(proj, None if p == root["name"] else p)[0]
        row = catalog.get(key)
        if p in std_missing:
            if row is None:
                continue  # the usual case: Mathlib's own cache serves it
            if n_oleans(pdir) >= int(row.get("modules") or 0):
                print(f"{p}: already compiled ({n_oleans(pdir)} modules); not fetched")
                continue
        if row is None:
            print(f"{p}: no published build for key {key} (toolchain {tc}, platform {plat}); build it locally")
            continue
        get = lambda f, r=row: hf_hub_download(r["hf_repo"], f"{r['hf_path']}/{f}", repo_type="dataset", cache_dir=cache)
        mp = get("manifest.json")
        if sha256_file(mp) != row["manifest_sha256"]:
            raise SystemExit(f"{p}: manifest hash differs from the catalog")
        man = json.load(open(mp, encoding="utf-8"))
        idx = {}
        for line in open(get("shards/index.jsonl"), encoding="utf-8"):
            if line.strip():
                e = json.loads(line)
                idx[e["path"]] = e
        feats = man.get("features", [])
        mods = {}
        if "modules_index" in feats:
            for line in open(get("shards/modules.jsonl"), encoding="utf-8"):
                if line.strip():
                    e = json.loads(line)
                    mods[e["module"]] = e
        frames = load_frames(get("shards/frames.jsonl")) if "module_frames" in feats else None
        builds[p] = {"row": row, "man": man, "idx": idx, "mods": mods, "frames": frames, "dir": pdir, "get": get}
    owner = {m: p for p, b in builds.items() for m in b["mods"]}
    whole, need = set(), set()
    if a.module:
        todo = list(a.module)
        while todo:
            m = todo.pop()
            if m in need or m not in owner:
                continue
            need.add(m)
            imps = builds[owner[m]]["mods"][m]["imports"]
            if imps is None:
                whole.add(owner[m])
            else:
                todo += imps
        for m in a.module:
            if m not in owner:
                print(f"note: {m} is not in any fetched build index (Mathlib, core, or not published)")
    now = time.time()
    tot_b = tot_all = 0
    for p, b in builds.items():
        man, frames = b["man"], b["frames"]
        allb = sum(s["bytes"] for s in man["shards"])
        tot_all += allb
        partial = bool(a.module) and p not in whole and bool(b["mods"])
        pneed = {m for m in need if owner.get(m) == p} if partial else None
        if partial and not pneed:
            print(f"{p}: nothing needed")
            continue
        if frames is not None:
            sel = [fr for fr in frames if not partial or fr["module"] is None or fr["module"] in pneed]
            size = sum(fr["length"] for fr in sel)
            nsh = len({fr["shard"] for fr in sel})
        else:
            if partial:
                shards = {s for m in pneed for s in b["mods"][m]["shards"]}
                shards |= {e["shard"] for e in b["idx"].values() if e["module"] is None}
            else:
                shards = {s["name"] for s in man["shards"]}
            sel = [s for s in man["shards"] if s["name"] in shards]
            size = sum(s["bytes"] for s in sel)
            nsh = len(sel)
        tot_b += size
        print(f"{p}: {size/1e6:.1f} of {allb/1e6:.1f} MB from {nsh} of {len(man['shards'])} shards"
              + (f", {len(pneed)} of {len(b['mods'])} modules" if partial else ""))
        if a.dry_run:
            continue
        if frames is None:
            for s in sel:
                sp = b["get"](s["name"])
                if sha256_file(sp) != s["sha256"]:
                    raise SystemExit(f"{p}: shard hash mismatch {s['name']}")
                if extract_shard(sp, s["name"], b["idx"], b["dir"], now) != s["files"]:
                    raise SystemExit(f"{p}: {s['name']} file count mismatch")
            continue
        by_shard = {}
        for fr in sel:
            by_shard.setdefault(fr["shard"], []).append(fr)
        shard_bytes = {s["name"]: s["bytes"] for s in man["shards"]}
        for sh, frs in sorted(by_shard.items()):
            frs.sort(key=lambda fr: fr["offset"])
            need_b = sum(fr["length"] for fr in frs)
            if not partial or need_b > 0.6 * shard_bytes[sh]:
                sp = b["get"](sh)  # most of the shard is needed: one whole download, cached by the Hub client
                extract_frames_from_file(sp, frs, b["idx"], b["dir"], now)
                continue
            url, direct = _resolve(hf_hub_url(b["row"]["hf_repo"], f"{b['row']['hf_path']}/{sh}", repo_type="dataset"), token)
            runs, cur = [], None
            for fr in frs:  # frames closer than 256 KiB share one range request
                if cur and fr["offset"] - cur[1] <= 262144:
                    cur[1] = fr["offset"] + fr["length"]
                    cur[2].append(fr)
                else:
                    cur = [fr["offset"], fr["offset"] + fr["length"], [fr]]
                    runs.append(cur)

            def do_run(run, url=url, direct=direct, b=b):
                body = _range_get(url, run[0], run[1] - 1, token, direct)
                return sum(extract_frame(body[fr["offset"] - run[0]: fr["offset"] - run[0] + fr["length"]], fr,
                                         b["idx"], b["dir"], now) for fr in run[2])

            with ThreadPoolExecutor(8) as ex:
                list(ex.map(do_run, runs))
    print(f"TOTAL {tot_b/1e6:.1f} of {tot_all/1e6:.1f} MB" + (" (dry run, nothing written)" if a.dry_run else " fetched and verified"))
    if a.check and not a.dry_run:
        targets = ["+" + m for m in a.module] if a.module else []
        r = subprocess.run(["lake", "build", "--no-build"] + targets, cwd=proj)
        sys.exit(r.returncode)


def cmd_key(a):
    tc, plat = toolchain_of(a.project_dir), platform_triple()
    key, cl, ch = key_for(a.project_dir, a.package)
    print(json.dumps({"toolchain": tc, "platform": plat, "build_key": key, "closure": cl, "source_changes": ch}, indent=1))


def main():
    ap = argparse.ArgumentParser(prog="lbc")
    sp = ap.add_subparsers(dest="cmd", required=True)
    k = sp.add_parser("key"); k.add_argument("project_dir"); k.add_argument("--package")
    p = sp.add_parser("pack"); p.add_argument("package_dir"); p.add_argument("out_dir")
    for opt in ("--package", "--commit", "--source-repo", "--license", "--project-dir"):
        p.add_argument(opt, required=True)
    p.add_argument("--toolchain"); p.add_argument("--shard-bytes", type=int, default=1_000_000_000)
    p.add_argument("--level", type=int, default=19); p.add_argument("--exclude-setup-json", action="store_true")
    u = sp.add_parser("unpack"); u.add_argument("staging_dir"); u.add_argument("package_dir"); u.add_argument("--shards")
    c = sp.add_parser("check"); c.add_argument("staging_dir")
    st = sp.add_parser("strip"); st.add_argument("staging_dir"); st.add_argument("--pattern")
    r = sp.add_parser("reindex"); r.add_argument("staging_dir"); r.add_argument("package_dir")
    d = sp.add_parser("pkgdir"); d.add_argument("project_dir"); d.add_argument("name")
    li = sp.add_parser("license"); li.add_argument("package_dir")
    f = sp.add_parser("fetch"); f.add_argument("project_dir"); f.add_argument("--module", action="append")
    f.add_argument("--package", action="append"); f.add_argument("--namespace", default="MoteMath")
    f.add_argument("--dry-run", action="store_true"); f.add_argument("--check", action="store_true")
    a = ap.parse_args()
    {"key": cmd_key, "pack": cmd_pack, "unpack": cmd_unpack, "check": cmd_check, "strip": cmd_strip, "fetch": cmd_fetch, "reindex": cmd_reindex, "license": cmd_license, "pkgdir": lambda a: print(package_dir(os.path.abspath(a.project_dir), a.name))}[a.cmd](a)


if __name__ == "__main__":
    main()