File size: 37,794 Bytes
3a77415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Write BENCH_FILES.tsv and SHA256SUMS: the concrete file list of the Thor-T-bench dataset, in ONE layout shared with
the replay recipe of the forge (fucina_en/examples/thor/recipe_c.yaml, inputs with repo Anjielon/Thor-T-bench).

Layout of the dataset (top level):
  scripts/   genera_numeri.py, its manifest, the register extract, the run scripts, this script, verifica_ricetta.py
  logs/      every per-question log and bench output that genera_numeri.py reads, under logs/bench, logs/gguf,
             logs/forge (the three data roots of the script); logs/chain/mmlu_C_stored_order.log (replay check)
  hf/        the cais/mmlu parquet in the Hugging Face cache layout
  bench/     the benchmark input files (.bin, .txt, .csv, mixed-order bench and its index, stratified sample)
  teacher/   the Q8_0 teacher
  corpora/   the replay corpora (teacher-distillation corpus and its held-out part, attention text, CoT corpus)
  stats/     the earlier quantized student whose flow defines the per-expert statistics
  hessians/  the 80 dense Hessians (in place of the unreleased large calibration text)
  SHA256SUMS, BENCH_FILES.tsv, REPLAY_STATUS (written only by the replay's verification step)

How the list is built: genera_numeri.py is run in --bundle mode under an audit hook and every data file it opens is
recorded; the parquet (opened by PyArrow outside Python's open) and the files that ship without being read by the
script are added explicitly. Logs of jobs still running are listed as "pending, hash at release".

--test builds a full copy (files copied, not linked) of the dataset in a scratch directory and runs the documented --bundle command on it.

Usage: OMP_NUM_THREADS=1 nice -n 19 python3 elenca_bundle.py [--test]
(also run automatically at the end of every full run of genera_numeri.py)
"""
from __future__ import annotations

import argparse
import hashlib
import json
import os
import time
import re
import runpy
import shutil
import subprocess
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
OUT = HERE / "BENCH_FILES.tsv"
SUMS = HERE / "SHA256SUMS"
SCRATCH = Path(os.environ.get("THOR_SCRATCH", "/tmp/claude-1000/elenca_bundle"))

BENCH = os.environ.get("THOR_BENCH_ROOT", "/mnt/models/banco_completo")
GGUF = os.environ.get("THOR_GGUF_ROOT", "/mnt/models/gguf")
FORGE = os.environ.get("THOR_FORGE_ROOT", "/home/angelo/tony-forgia")
HFC = os.environ.get("HF_HOME_CACHE", "/home/angelo/.cache/huggingface")
KAGGLE = os.environ.get("THOR_KAGGLE_ROOT", str(Path(GGUF).parent / "kaggle_banchi_1103"))
ROOTS = {BENCH: "logs/bench", GGUF: "logs/gguf", FORGE: "logs/forge", HFC: "hf", KAGGLE: "logs/kaggle"}
ENV_OF = {"logs/bench": "THOR_BENCH_ROOT", "logs/gguf": "THOR_GGUF_ROOT", "logs/forge": "THOR_FORGE_ROOT",
          "hf": "HF_HOME_CACHE", "logs/kaggle": "THOR_KAGGLE_ROOT"}

OURS = "CC BY 4.0 (ours)"
TEACHER = "MIT (Ornith-1.5-35B-A3B; generated by or converted from the MIT-licensed teacher)"
BENCH_LIC = {"mmlu": "MIT (cais/mmlu)", "arc": "CC BY-SA 4.0 (allenai/ai2_arc)", "boolq": "CC BY-SA 3.0 (google/boolq)",
             "openbookqa": "not declared (allenai/openbookqa)", "piqa": "not declared (PIQA)",
             "truthfulqa": "Apache 2.0 (truthfulqa/truthful_qa)", "hellaswag": "MIT (rowanz/hellaswag)",
             "winogrande": "not declared (WinoGrande)", "mmlu_pro": "MIT (TIGER-Lab/MMLU-Pro)"}
SAMPLE_LIC = {"gsm8k": "MIT (openai/gsm8k)", "ifeval": "Apache 2.0 (google/IFEval)",
              "math500": "MIT (MATH; MATH-500 subset declares none)"}

# explicit rows: (path in bundle, source, licence)
FIXED = [
    ("scripts/genera_numeri.py", str(HERE / "genera_numeri.py"), OURS),
    ("scripts/manifest_file.json", str(HERE / "manifest_file.json"), OURS),
    ("scripts/cicli_extract.tsv", str(HERE / "cicli_extract.tsv"), OURS),
    ("scripts/elenca_bundle.py", str(HERE / "elenca_bundle.py"), OURS),
    ("scripts/verifica_ricetta.py", str(HERE / "verifica_ricetta.py"), OURS),
    ("scripts/letture.json", str(HERE / "letture.json"), OURS),
    ("scripts/date_letture.json", str(HERE / "date_letture.json"), OURS),
    ("scripts/date_letture_fonte.json", str(HERE / "date_letture_fonte.json"), OURS),
    ("scripts/esiti_1108_PRODUCERS.tsv", str(HERE / "esiti_1108_PRODUCERS.tsv"), OURS),
    ("scripts/storia_arresto_M.tsv", str(HERE / "storia_arresto_M.tsv"), OURS),
    ("scripts/ricetta_SM.tsv", str(HERE / "ricetta_SM.tsv"), OURS),
    ("scripts/radice_costo.tsv", str(HERE / "radice_costo.tsv"), OURS),
    ("scripts/costo_SM.tsv", str(HERE / "costo_SM.tsv"), OURS),
    ("scripts/sizing_points.tsv", str(HERE / "sizing_points.tsv"), OURS),
    ("scripts/check_layout.py", str(HERE / "check_layout.py"), OURS),
    ("scripts/righe_citate.tsv", str(HERE / "righe_citate.tsv"), OURS),
    ("scripts/SM_CONSTRUCTION_FILES.tsv", str(HERE / "SM_CONSTRUCTION_FILES.tsv"), OURS),
    ("REDACTION.md", str(HERE / "REDACTION.md"), OURS),
    ("README.md", str(HERE.parent / "schede_hf_1109" / "README_bench.md"), OURS),   # the dataset card itself (19d)
    ("scripts/split_fucina.sh", str(HERE / "split_fucina.sh"), OURS),
    ("scripts/KQAT_FILE_DATES.tsv", str(HERE / "KQAT_FILE_DATES.tsv"), OURS),
    ("bench/c4/c4_validation_00000_testa.json", "/mnt/models/gguf/tony-tern/pannello/c4/c4_validation_00000_testa.json", OURS),
    ("construction_SM/code/applica_kqat.py", "/home/angelo/tony-forgia/sorgenti_forgia/kernel_qat/applica_kqat.py", OURS),
    ("construction_SM/code/confronta_cardan.py", "/home/angelo/tony-forgia/sorgenti_forgia/kernel_qat/confronta_cardan.py", OURS),
    ("scripts/fucina_depriv.sed", str(HERE / "fucina_depriv.sed"), OURS),
    ("scripts/ptq1/verifica_completa.out", str(HERE / "bundle_ptq1/verifica_completa.out"), OURS),
    ("scripts/ptq1/verifica_completa_q2_0.out", str(HERE / "bundle_ptq1/verifica_completa_q2_0.out"), OURS),
    ("scripts/microbatch_shares.json", str(HERE / "microbatch_shares.json"), OURS),
    ("scripts/microbatch_shares.py", str(HERE / "strumenti" / "microbatch_shares.py"), OURS),
    ("scripts/run/BENCH_SCRIPT_VERSIONS.txt", str(HERE / "BENCH_SCRIPT_VERSIONS.txt"), OURS),
    ("scripts/contaminazione_mmlupro.json", str(HERE / "contaminazione_mmlupro.json"), OURS),
    ("scripts/contaminazione_mmlupro.py", str(HERE / "contaminazione_mmlupro.py"), OURS),
    ("scripts/estrai_letture.py", str(HERE / "estrai_letture.py"), OURS),
    ("hf/hub/datasets--cais--mmlu/snapshots/c30699e8356da336a370243923dbaf21066bb9fe/all/test-00000-of-00001.parquet",
     HFC + "/hub/datasets--cais--mmlu/snapshots/c30699e8356da336a370243923dbaf21066bb9fe/all/test-00000-of-00001.parquet",
     "MIT (cais/mmlu)"),
    ("teacher/Ornith-1.5-35B-A3B-Q8_0.gguf", GGUF + "/tony-tern/teacher-q8/Ornith-1.5-35B-A3B-Q8_0.gguf", TEACHER),
    ("corpora/e2e_corpus_4096_maestro.pt", "/mnt/deposito/e2e_corpus_maestro/e2e_corpus_4096_maestro.pt", TEACHER),
    ("corpora/e2e_heldout_4096_maestro.pt", "/mnt/deposito/e2e_corpus_maestro/e2e_heldout_4096_maestro.pt", TEACHER),
    ("corpora/calib_auto2_pulito.txt", FORGE + "/calib_auto2_pulito.txt", TEACHER),
    ("corpora/corpus_cot.txt", FORGE + "/thor/cot_calib/corpus_cot.txt", "CC BY 4.0 (see THIRD_PARTY.md)"),
    ("stats/Thor-v20-downaggr3.gguf", GGUF + "/tony-tern/Thor-v20-downaggr3.gguf", OURS),
    ("logs/chain/mmlu_C_stored_order.log", BENCH + "/esiti_finale_1107/C_ordine_memorizzato/mmlu_C.log", OURS),
    ("THIRD_PARTY.md", str(HERE / "THIRD_PARTY.md"), OURS),
    ("LICENSE.base-model", str(HERE / "LICENSE.base-model"), "MIT (text of the base model's licence)"),
    ("scripts/converti_multiple_choice.py", FORGE + "/converti_multiple_choice.py", OURS),
    ("scripts/costruisci_banchi.py", FORGE + "/banco_completo/costruisci_banchi.py", OURS),
    ("hf/tokenizer/tokenizer.json", GGUF + "/thor-src-hf/tokenizer.json",
     "MIT (tokenizer of Ornith-1.5-35B-A3B at revision 10fbf86f): decodes the calibration selection"),
    ("hf/hub/datasets--TIGER-Lab--MMLU-Pro/test-00000-of-00001.parquet",
     sorted(Path(HFC + "/hub/datasets--TIGER-Lab--MMLU-Pro/snapshots").glob("*/data/test-00000-of-00001.parquet"))[0].as_posix()
     if Path(HFC + "/hub/datasets--TIGER-Lab--MMLU-Pro/snapshots").exists() else "", "MIT (TIGER-Lab/MMLU-Pro)"),
    ("scripts/winogrande_ramo.py", str(HERE / "winogrande_ramo.py"), OURS),
    ("scripts/ricostruisci_banchi.py", str(HERE / "ricostruisci_banchi.py"), OURS),
    ("scripts/winogrande_ramo.json", str(HERE / "winogrande_ramo.json"), OURS),
    ("scripts/ptq1/converti_tq1r_ptq1.py", str(HERE / "bundle_ptq1/converti_tq1r_ptq1.py"), OURS),
    ("scripts/ptq1/ptq1_lib.py", str(HERE / "bundle_ptq1/ptq1_lib.py"), OURS),
    ("scripts/ptq1/verifica_lossless.py", str(HERE / "bundle_ptq1/verifica_lossless.py"), OURS),
    ("scripts/ptq1/verifica_c_upstream.py", str(HERE / "bundle_ptq1/verifica_c_upstream.py"), OURS),
    ("scripts/fucina_split.tsv", str(HERE / "fucina_split.tsv"), OURS),
    ("scripts/ptq1/verifica_lossless.out", str(HERE / "ptq1/verifica_lossless.out"), OURS),
    ("scripts/ptq1/verifica_c_upstream.out", str(HERE / "ptq1/verifica_c_upstream.out"), OURS),
    ("scripts/ptq1/verifica_completa.out", str(HERE / "ptq1/verifica_completa.out"), OURS),
    ("bench/calib_mmlu.jsonl", GGUF + "/tony-tern/SELRISP/calib/calib_mmlu.jsonl",
     "MIT (cais/mmlu validation/dev, as token ids): the calibration selection"),
]
# bench inputs whose source declares no licence: listed with their sha256 so a copy can be checked, not shipped
NOT_SHIPPED = ("winogrande-debiased-eval.csv", "piqa_full.bin", "openbookqa_test.bin")
PAPER = Path(os.environ.get("THOR_PAPER_DIR", str(HERE.parent / "latex")))
BENCH_FILES = (  # benchmark inputs of the run scripts (stato/banco_completo_v3.sh, mmlu_blocchi_*.sh)
    [FORGE + f"/mc_v2/mmlu_{b}.bin" for b in ("00000", "02000", "04000", "06000", "08000", "10000", "12000", "14000")]
    + [FORGE + "/mc_v2/" + n for n in ("mmlu_test.bin", "arc_challenge_test.bin", "arc_easy_test.bin", "boolq_test.bin",
                                        "openbookqa_test.bin", "truthfulqa_mc1_test.bin", "mmlu2000_mescolato.bin",
                                        "mmlu2000_mescolato.indice.tsv", "mmlu2000_strat.bin",
                                        "mmlu2000_strat.indice.tsv")]
    + [FORGE + "/banco_completo/bin/mmlu_pro_mc.bin", FORGE + "/banco_completo/bin/piqa_full.bin",
       "/home/angelo/odino-lab/collaudo/bench/hellaswag_val_full.txt",
       "/home/angelo/odino-lab/collaudo/bench/winogrande-debiased-eval.csv"])
JOB_SCRIPTS_EXTRA = {"banco_gsm_solo_1109.sh", "vel_paper_finale_1107.sh", "aragorn_mmlu_1109.sh", "aragorn_mmlu_1109.bat",
                     "aragorn_mmlu_xs_1109.sh", "aragorn_mmlu_xs_1109.bat", "aragorn_q4_1109.sh", "aragorn_q4_1109.bat",
                     "aragorn_rivali_1109.sh", "aragorn_rivali_1109.bat", "cudavec_b_1109.sh", "cudavec_b_1109.bat"}
JOB_SCRIPTS = {"banco_finale_1107.sh", "banco_finale_v2_1107.sh", "banco_senza_bbh_1108.sh", "controllo_np_1109.sh",
               "rivali_suite_1109.sh", "maestro_lancio_1109.sh", "coda_paper_notte_1109_v2.sh",
               "mcnemar_completo_1101.py"}
SCRIPT_GLOBS = ["stato/banco_completo*.sh", "stato/mmlu_blocchi*.sh", "stato/ptq1_xs_1109.sh",
                "stato/mcnemar_completo_1101.py"]
# jobs still running are found from the state, not from a list: a file is pending when its job's Done switch is 0
# or when any file in its directory changed in the last RECENT seconds (a log or server log still growing)
RECENT = int(os.environ.get("THOR_PENDING_RECENT_S", "1800"))
PENDING = [("qtwoDone", "/esiti_finale_1107/Q2_K/"), ("rootDone", "/esiti_finale_1107/RADICE/"),
           ("ptqDone", "/esiti_finale_1107/PTQ1_0/"), ("vnewDone", "/esiti_finale_1107/velocita_rivali/"),
           ("ctrlPostDone", "/CONTROLLO_SOLO_POST_C0B_1109/completo/"), ("npCtlDone", "/controllo_np/XS_arc_np5"), ("npCtlDone", "/controllo_np/M_arc_np5")]


_CACHE_F = HERE / ".elenca_sha_cache.json"
try:
    import json as _json
    _CACHE = _json.loads(_CACHE_F.read_text()) if _CACHE_F.exists() else {}
except ValueError:
    _CACHE = {}


def sha256(p: str) -> str:
    st = os.stat(p)
    key = f"{p}|{st.st_size}|{int(st.st_mtime)}"
    if key in _CACHE:
        return _CACHE[key]
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for blk in iter(lambda: f.read(1 << 22), b""):
            h.update(blk)
    _CACHE[key] = h.hexdigest()
    _CACHE_F.write_text(_json.dumps(_CACHE, indent=0))
    return _CACHE[key]


# Redaction of private paths in the SHIPPED copies of text files (decision of the coordinator, round 18): the originals
# are never touched; SHA256SUMS and BENCH_FILES.tsv hash the redacted copies; the map ships as REDACTION.md.
REDACT_MAP = [
    ("/home/angelo/claude-pod-lavoro", "$THOR_POD"),
    ("/home/claudepod", "$THOR_POD_HOME"),
    ("/home/angelo/tony-forgia", "$THOR_LAB"),
    ("/mnt/models/gguf", "$THOR_GGUF"),
    ("/mnt/models/build", "$THOR_BUILD"),
    ("/mnt/models/banco_completo", "$THOR_BENCH"),
    ("/mnt/deposito", "$THOR_DEPOT"),
    ("/mnt/lavoro", "$THOR_WORK"),
    ("/mnt/usb-ssd", "$THOR_USB"),
    ("/mnt/nas", "$THOR_NAS"),
]
REDACT_RE = [(re.compile(r"/mnt/models/hf(?=/|\b)(?!-)"), "$THOR_HF"),
             (re.compile(r"\b192\.168\.\d{1,3}\.\d{1,3}\b"), "$LAN_IP"), (re.compile(r"\bS-1-5-21-[0-9-]+\b"), "$SID"),
             (re.compile(r"(?<=/home/)angelo\b"), "$USER"), (re.compile(r"(?i)(?<=\\Users\\)angel\b"), "$USER"),
             (re.compile(r"(?<=C:/Users/)angel\b"), "$USER"), (re.compile(r"\bclaudepod\b"), "$USER")]
REDACT_EXT = {".log", ".txt", ".tsv", ".json", ".md", ".out", ".yaml", ".yml", ".csv", ".cfg", ".toml", ".jsonl",
              ".mesc", ""}
CODE_EXT = {".py", ".sh", ".bat", ".ps1", ".diff", ".patch"}   # code ships byte-identical (round 18f), never redacted
REDACT_DIRS = ("logs/", "construction_SM/", "scripts/", "stats/")


def redacts(bp: str) -> bool:
    """text files under the shipped log, script and construction folders (dataset files, the paper, hf/ are not)"""
    ext = os.path.splitext(bp)[1].lower()
    if ext in CODE_EXT or ".sh." in os.path.basename(bp):   # code, incl. saved versions such as x.sh.until_1110
        return False
    return bp.startswith(REDACT_DIRS) and (ext in REDACT_EXT or ext.startswith(".log")) and not bp.endswith(".gz")


def redact_bytes(b: bytes) -> bytes:
    t = b.decode("utf-8", "surrogateescape")
    for a, z in REDACT_MAP:
        t = t.replace(a, z)
    for rx, z in REDACT_RE:
        t = rx.sub(z, t)
    return t.encode("utf-8", "surrogateescape")


def shipped_bytes(src: str, bp: str) -> bytes | None:
    """the bytes that ship for bp, or None when the file ships unchanged"""
    if not redacts(bp):
        return None
    return redact_bytes(Path(src).read_bytes())


SECRET_RE = re.compile(rb"hf_[A-Za-z0-9]{30,}|-----BEGIN [A-Z ]*PRIVATE KEY-----|ssh-(?:rsa|ed25519) AAAA[0-9A-Za-z+/]{40,}"
                       rb"|(?i:(?:HF_TOKEN|api[_-]?key|password|passwd|secret|token)\s*[=:]\s*[\"']?[A-Za-z0-9_\-]{16,})")
SECRET_HITS: list = []


def scan_secrets(src: str, bp: str) -> None:
    """code ships unredacted: scan it for secrets before it is listed (round 18f); any hit stops the listing"""
    if (os.path.splitext(bp)[1].lower() not in CODE_EXT and ".sh." not in os.path.basename(bp)) or not os.path.isfile(src):
        return
    for m in SECRET_RE.finditer(Path(src).read_bytes()):
        SECRET_HITS.append((bp, m.group(0)[:12].decode("utf-8", "replace") + "..."))


def sha256_shipped(src: str, bp: str) -> str:
    b = shipped_bytes(src, bp)
    return sha256(src) if b is None else hashlib.sha256(b).hexdigest()


def size_shipped(src: str, bp: str) -> int:
    b = shipped_bytes(src, bp)
    return os.path.getsize(src) if b is None else len(b)


EXPECT = {"arc_challenge": 1172, "arc_easy": 2376, "boolq": 3270, "piqa_full": 1838, "openbookqa": 500,
          "truthfulqa_mc1": 817, "mmlu_pro_mc": 12032, "hellaswag": 10042, "winogrande": 1267, "mmlu_full": 14042}


def _last_index(src: str) -> int | None:
    with open(src, "rb") as fh:
        fh.seek(max(0, os.path.getsize(src) - 65536))
        lines = fh.read().decode(errors="replace").splitlines()
    for ln in reversed(lines):
        m = re.match(r"^(\d+)\t", ln)
        if m:
            return int(m.group(1))
    return None


_OPEN: set | None = None


def held_open(src: str) -> bool:
    """true if a live process holds the file open (a server or scorer still writing it): /proc/*/fd"""
    global _OPEN
    if _OPEN is None:
        _OPEN = set()
        for pid in os.listdir("/proc"):
            if not pid.isdigit():
                continue
            try:
                for fd in os.listdir(f"/proc/{pid}/fd"):
                    try:
                        _OPEN.add(os.readlink(f"/proc/{pid}/fd/{fd}"))
                    except OSError:
                        pass
            except OSError:
                pass
    return os.path.realpath(src) in _OPEN


def is_final(src: str) -> bool:
    """final when the job that writes the file has finished: a scoring log whose last item index equals the size of
    its task, an lm-eval log whose task has a results JSON, a server log whose lm-eval log is final (no time window)"""
    name, d = os.path.basename(src), os.path.dirname(src)
    if held_open(src):
        return False
    try:
        stem = name[:-4] if name.endswith(".log") else name
        if name.endswith("_arc_np1.log"):
            # the first -np control stopped for good at the first five-option question: a finished, partial log
            with open(src, "rb") as fh:
                fh.seek(max(0, os.path.getsize(src) - 4096))
                return b"requires a higher -np" in fh.read()
        if name.endswith(".lmeval.log"):
            task = name[:-len(".lmeval.log")]
            return any(f.startswith("results") and f.endswith(".json")
                       for _, _, fs in os.walk(os.path.join(d, task)) for f in fs)
        if name.startswith("server_") and name.endswith(".log"):
            lm = os.path.join(d, name[len("server_"):-4] + ".lmeval.log")
            return not os.path.exists(lm) or is_final(lm)
        if name.startswith("samples_") or (name.startswith("results") and name.endswith(".json")):
            return True
        if name.endswith(".log"):
            with open(src, "rb") as fh:
                fh.seek(max(0, os.path.getsize(src) - 8192))
                if re.search(rb"Final (result|estimate|Winogrande score)", fh.read()):
                    return True                          # the scorer's own completion marker
        if stem in EXPECT:
            if _last_index(src) == EXPECT[stem]:
                return True
            with open(src, "rb") as fh:                 # concatenated block logs hold only MCLP rows
                return sum(1 for ln in fh if ln.startswith(b"MCLP\t")) == EXPECT[stem]
        m = re.match(r"^mmlu_(\d{5})$", stem)
        if m:
            return _last_index(src) == (42 if m.group(1) == "14000" else 2000)
        return True
    except OSError:
        return False


def bundle_path(src: str) -> str | None:
    for root, pre in ROOTS.items():
        r = root.rstrip("/") + "/"
        if src.startswith(r):
            return pre + "/" + src[len(r):]
    return None


def bench_licence(name: str) -> str:
    n = name.lower()
    for k in ("mmlu_pro", "hellaswag", "winogrande", "truthfulqa", "openbookqa", "boolq", "piqa", "arc", "mmlu"):
        if k in n:
            return BENCH_LIC[k]
    return OURS


def emitted_macros(tex: Path) -> dict[str, str]:
    out = {}
    for ln in tex.read_text(errors="replace").splitlines():
        if ln.startswith("\\newcommand{\\"):
            name = ln[len("\\newcommand{\\"):].split("}", 1)[0]
            out[name] = ln.split("}{", 1)[1].rsplit("}", 1)[0] if "}{" in ln else ""
    return out


DEPRIV = [("/mnt/models/build/thor-pub-q8/gguf-py", "' + os.environ['THOR_ENGINE_SRC'] + '/gguf-py"),
          ("/mnt/models/build/thor-pub-q8/build-cpu/bin/libggml-base.so",
           "' + os.environ['THOR_ENGINE_BIN'] + '/libggml-base.so"),
          ("/mnt/models/build/upstream-ptq1-1109/build-cpu/bin/libggml-base.so",
           "' + os.environ['THOR_UPSTREAM_BIN'] + '/libggml-base.so"),
          ("/mnt/usb-ssd/lancio_1103/Thor-T-35B-A3B-XS.gguf", "' + os.environ['THOR_XS_GGUF'] + '"),
          ("/home/angelo/tony-forgia/pubblicazioni/C_ternario_casa/revisione_1109/ptq1", "' + os.path.dirname(os.path.abspath(__file__)) + '"),
          ("/mnt/models/build/thor-pub-q8", "' + os.environ['THOR_ENGINE_SRC'] + '")]


def deprivatize_ptq1() -> None:
    """bundle copies of the PTQ1_0 scripts with every private path replaced by an environment variable"""
    out = HERE / "bundle_ptq1"
    out.mkdir(exist_ok=True)
    for f in ("converti_tq1r_ptq1.py", "ptq1_lib.py", "verifica_lossless.py", "verifica_c_upstream.py"):
        t = (HERE / "ptq1" / f).read_text()
        for a, b in DEPRIV:
            t = t.replace("'" + a + "'", "'" + b + "'").replace('"' + a + '"', "'" + b + "'")
        if not re.search(r"^import os\b|^import .*\bos\b", t, re.M):
            # insert after the module docstring and any __future__ import, so the file still compiles
            lines = t.split("\n")
            k = 0
            if lines and lines[0].startswith("#!"):
                k = 1
            src_ = "\n".join(lines[k:])
            mdoc = re.match(r'\s*("""|\'\'\')(.*?)\1', src_, re.S)
            pos = len("\n".join(lines[:k])) + (1 if k else 0) + (mdoc.end() if mdoc else 0)
            fut = list(re.finditer(r"^from __future__ import .*$", t, re.M))
            if fut:
                pos = max(pos, fut[-1].end())
            t = t[:pos] + "\nimport os\n" + t[pos:]
        if re.search(r"/mnt/|/home/angelo", t):
            raise SystemExit(f"private path left in the bundle copy of {f}")
        (out / f).write_text(t)
        import py_compile  # noqa: PLC0415
        py_compile.compile(str(out / f), doraise=True)


def collect() -> list[tuple[str, str, str]]:
    seen: set[str] = set()

    def hook(event, args):
        if event == "open" and args and isinstance(args[0], (str, bytes, os.PathLike)):
            mode = args[1] if len(args) > 1 else "r"
            if isinstance(mode, str) and any(c in mode for c in "wax"):
                return
            if isinstance(mode, int) and mode & (os.O_WRONLY | os.O_RDWR):
                return
            p = os.path.abspath(os.fsdecode(args[0]))  # as opened: a symlinked directory keeps its place in the layout
            if os.path.isfile(p):
                seen.add(p)

    gen = runpy.run_path(str(HERE / "genera_numeri.py"), run_name="genera_bundle_lib")
    n = gen["write_register_extract"](HERE / "cicli_extract.tsv")
    print(f"register extract: {n} rows")
    (SCRATCH / "out" / "sections").mkdir(parents=True, exist_ok=True)
    env_keep = dict(os.environ)
    os.environ["THOR_LATEX_DIR"] = str(SCRATCH / "out")
    os.environ["THOR_NO_BUNDLE_LIST"] = "1"
    sys.addaudithook(hook)
    argv_keep = sys.argv
    sys.argv = ["genera_numeri.py", "--bundle", "--no-hash"]
    try:
        runpy.run_path(str(HERE / "genera_numeri.py"), run_name="__main__")
    finally:
        sys.argv = argv_keep
        os.environ.clear()
        os.environ.update(env_keep)
    rows = []
    paper = str(PAPER.resolve()) + "/"
    for p in sorted(seen):
        bp = bundle_path(p)
        if (bp is None or p.endswith((".gguf", ".pyc")) or "/site-packages/" in p or p.endswith("/cicli.tsv")
                or os.path.basename(p).startswith(".") or os.path.realpath(p).startswith(paper)
                or os.path.realpath(p).startswith(str(HERE) + "/")):
            continue
        lic = OURS
        if os.path.basename(p).startswith("samples_"):      # lm-eval samples contain dataset text
            lic = next((v for k, v in SAMPLE_LIC.items() if k in p.lower()), "licence of its dataset (THIRD_PARTY.md)")
        rows.append((bp, p, lic))
    rows += FIXED
    for p in BENCH_FILES:
        rows.append(("bench/" + os.path.basename(p), p, bench_licence(os.path.basename(p))))
    # a frozen copy of the paper sources, so that the unused-macro check of --bundle runs on the dataset; hashed at release
    for f in sorted([*PAPER.glob("*.tex"), *PAPER.glob("sections/*.tex"), *PAPER.glob("*.bib")]):
        if ".bak" in f.name or "PROPOSTA" in f.name or f.name == "Z_open_items.tex":
            continue
        rows.append(("paper/" + str(f.relative_to(PAPER)), str(f), OURS))
    # run scripts: those that wrote the final bench (they name its directory), plus the ones the coordinator's job map
    # lists; the earlier-engine bench scripts ship apart, marked as such
    stato = Path(FORGE) / "stato"
    final = set()
    for p in sorted([*stato.glob("*.sh"), *stato.glob("*.py")]):
        if ".bak" in p.name:
            continue
        try:
            txt = p.read_text(errors="replace")
        except OSError:
            continue
        if "esiti_finale" in txt or p.name in JOB_SCRIPTS:
            final.add(p.name)
            rows.append(("scripts/run/" + p.name, str(p), OURS))
    # scripts named by the job that wrote each log (job -> script), and the per-run model registries
    for nm in sorted(JOB_SCRIPTS_EXTRA):
        p = stato / nm
        if p.exists() and nm not in final:
            final.add(nm)
            rows.append(("scripts/run/" + nm, str(p), OURS))
    # the bench script as it ran the teacher's launch-engine re-run and the runs before it (saved 10 Nov 00:06), next to
    # the current one (port-guard early returns release the GPU lock, 10 Nov 04:43); BENCH_SCRIPT_VERSIONS.txt says which
    bak = stato / "banco_senza_bbh_1108.sh.bak_1110"
    if bak.exists():
        rows.append(("scripts/run/banco_senza_bbh_1108.sh.until_1110", str(bak), OURS))
    # producer scripts and raw outputs of the same-session CUDA speeds and of the PTQ1_0 fork runs (CUDA and Vulkan),
    # with the fork's local patch (prints MCLP lines, output only)
    for sub in ("aragorn_stessa_sessione_1110", "ptq1_fork_cuda_1110", "ptq1_fork_vulkan_1110", "top1_c4_1031",
                "q2_0_upstream_1110", "cudavec_b", "c4_rilasciati_1110"):
        for p in sorted((stato / sub).rglob("*")):
            if p.is_file() and p.name not in ("schtasks_prima.csv", "tasklist_prima.txt"):   # Windows SID, task list
                rel = str(p.relative_to(stato))
                if "/aragorn_prism_cuda/" in "/" + rel:   # first fork CUDA run, contaminated by a parallel task
                    rel = rel.replace("aragorn_prism_cuda/", "DISCARDED_aragorn_prism_cuda_contaminated_first_run/")
                rows.append(("logs/forge/stato/" + rel, str(p), OURS))
    for nm in ("banco_senza_bbh_1108.sh.bak_1110b",):
        if (stato / nm).exists():
            rows.append(("scripts/run/banco_senza_bbh_1108.sh.from_1110_0443", str(stato / nm), OURS))
    for p in sorted((Path(FORGE) / "banco_completo").glob("modelli_*.tsv")):
        rows.append(("scripts/run/registries/" + p.name, str(p), OURS))
    for p in sorted(stato.glob("banco_completo*.sh")):
        if p.name not in final and ".bak" not in p.name:
            rows.append(("scripts/run/earlier_engine/" + p.name, str(p), OURS + "; earlier engine only, not the final bench"))
    # rows prepared with the forge (FUCINA_REPLAY.md, layout of the bench dataset): they define source and licence
    rr = HERE / "BENCH_FILES_replay_rows.tsv"
    if rr.exists():
        rep_rows = {ln.split("\t")[0]: ln.split("\t") for ln in rr.read_text().splitlines()[1:] if ln.strip()}
        # the forge's rows give the source path; the licence stays the one of this list (one value per file)
        rows = [(bp, rep_rows[bp][1], lic) if bp in rep_rows else (bp, src, lic) for bp, src, lic in rows]
        have = {bp for bp, _, _ in rows}
        rows += [(bp, r[1], r[4]) for bp, r in rep_rows.items() if bp not in have]
    # per-question logs of every reading of Table 20 and every candidate log of the C-candidates table (G17_R4 S1/S2)
    lj = HERE / "letture.json"
    if lj.exists():
        dd = json.loads(lj.read_text())
        sub = lambda x: x.replace("{gguf}", GGUF).replace("{bench}", BENCH)
        for o_ in dd.get("outside", []):
            if o_.get("register") or not o_.get("dir", "").startswith(("{", "/")):
                continue
            d_ = Path(sub(o_["dir"]))
            pre = o_.get("prefix", "")
            for f_ in sorted(d_.glob(f"{pre}*.log")) if d_.exists() else []:
                bp = bundle_path(str(f_))
                if bp:
                    rows.append((bp, str(f_), OURS))
            for f_ in (d_ / "gguf.txt",):
                if f_.exists() and bundle_path(str(f_)):
                    rows.append((bundle_path(str(f_)), str(f_), OURS))
        for c_ in dd.get("candidates", []) + dd.get("unfolded", []) + dd.get("pool", []):
            for q_ in c_.get("paths", []):
                q_ = sub(q_)
                if os.path.isfile(q_) and bundle_path(q_):
                    rows.append((bundle_path(q_), q_, OURS))
    # scripts, argument files and logs of the construction of S and M (G17_R5 S1), listed in SM_CONSTRUCTION_FILES.tsv
    smf = HERE / "SM_CONSTRUCTION_FILES.tsv"
    if smf.exists():
        for ln in smf.read_text(errors="replace").splitlines()[1:]:
            f_ = ln.split("\t")
            if len(f_) >= 2 and f_[0] not in ("-", "") and f_[1] not in ("-", "") and os.path.isfile(f_[1]):
                rows.append((f_[0], f_[1], OURS))
    for p in sorted(Path(GGUF + "/tony-tern/hessiane-densi-grande").glob("*.npy")):
        rows.append(("hessians/hessiane-densi-grande/" + p.name, str(p),
                     "CC BY 4.0 (ours; statistics of a non-released corpus)"))
    # the full stderr of each scoring run (.mesc, next to the answer log) ships with every shipped log (G20_R4 m5,
    # G21_R4): added last, so that logs listed by any rule above are covered
    have = {r[1] for r in rows}
    for bp_, p_, lic_ in list(rows):
        if os.path.isfile(p_ + ".mesc") and (p_ + ".mesc") not in have:
            rows.append((bp_ + ".mesc", p_ + ".mesc", lic_))
            have.add(p_ + ".mesc")
    return rows


def write(rows: list[tuple[str, str, str]]) -> None:
    mac = emitted_macros(Path(os.environ.get("THOR_LATEX_DIR", str(HERE.parent / "latex"))) / "numbers_final.tex")
    pending_dirs = [d for m, d in PENDING if mac.get(m, "0") != "1"]
    import time  # noqa: PLC0415
    now = time.time()
    recent_dirs = set()

    def growing(src: str) -> bool:
        """a file is pending only if the job that writes it has not finished: a log without its completion marker, a
        sample file without the results JSON of its run, a server log of a task without results (no time window)"""
        # a log modified in the last RECENT seconds is pending too: genera_numeri.py (rivals_suite) applies the same
        # window, so a job that lands during a run cannot make the full run and the bundle run read different files
        try:
            cut = os.environ.get("THOR_LOG_CUTOFF")   # one cutoff T0 for the chain (same rule as genera_numeri.py)
            young = (os.path.getmtime(src) > float(cut)) if cut else (time.time() - os.path.getmtime(src) < RECENT)
        except OSError:
            young = False
        return young or not is_final(src)
    out = ["path_in_bundle\tsource_path\tsha256\tbytes\tlicence"]
    sums, models, done, miss, pend = [], [], set(), 0, 0
    for bp, src, lic in rows:
        if bp in done:
            continue
        done.add(bp)
        if os.path.basename(src) in NOT_SHIPPED and os.path.exists(src):
            out.append(f"{bp}\t{src}\tnot shipped ({sha256(src)})\t{os.path.getsize(src)}\t"
                       f"source declares no licence; see THIRD_PARTY.md")
        elif any(d in src for d in pending_dirs) or (bp.startswith("logs/") and growing(src)):
            out.append(f"{bp}\t{src}\tpending, hash at release\t\t{lic}")
            pend += 1
        elif os.path.exists(src):
            scan_secrets(src, bp)
            h = sha256_shipped(src, bp) if not bp.endswith(".gguf") else sha256(src)
            (models if bp.endswith(".gguf") else sums).append(f"{h}  {bp}")   # model files: SHA256SUMS.models
            orig = sha256(src) if redacts(bp) else ""
            out.append(f"{bp}\t{src}\t{h}\t{size_shipped(src, bp)}\t{lic}" + (f"\tredacted; original sha256 {orig}" if orig else ""))
        else:
            out.append(f"{bp}\t{src}\tMISSING\t\t{lic}")
            miss += 1
    out.append("REPLAY_STATUS\t(dataset root; written by the replay's verification step)\tpending\t\t" + OURS)
    if SECRET_HITS:
        for bp_, hit in SECRET_HITS:
            print(f"SECRET? {bp_}: {hit}")
        raise SystemExit(f"possible secrets in {len(SECRET_HITS)} shipped code files: listing stopped, nothing written")
    out.append("SHA256SUMS\t(generated)\t-\t-\t" + OURS)
    out.append("SHA256SUMS.models\t(generated; the two model files, optional for --bundle)\t-\t-\t" + OURS)
    out.append("BENCH_FILES.tsv\t(this file)\t-\t-\t" + OURS)
    OUT.write_text("\n".join(out) + "\n")
    SUMS.write_text("\n".join(sums) + "\n")
    (HERE / "SHA256SUMS.models").write_text("\n".join(models) + "\n")
    print(f"{len(out) - 1} rows -> {OUT} ({miss} missing, {pend} pending)")
    if miss:
        raise SystemExit("BENCH_FILES: missing source files")


def test_bundle() -> None:
    """copy the dataset (files, not links) into a scratch directory and run the README command on it. The two model
    files (teacher, earlier student; tens of GB, never read by --bundle) are not copied: their hashes are in
    SHA256SUMS.models, which --bundle does not check, so the copy is a complete --bundle input without them."""
    d = SCRATCH / "thor-t-bench"
    shutil.rmtree(d, ignore_errors=True)
    skipped = []
    for ln in OUT.read_text().splitlines()[1:]:
        bp, src, h = ln.split("\t")[:3]
        if (not os.path.exists(src) or h in ("-", "MISSING") or h.startswith("not shipped")
                or h.startswith("pending")):
            continue   # no pending row is copied: the test must see exactly what a user downloads (G20_R4 S1)
        if bp.endswith(".gguf"):
            skipped.append(bp)
            continue
        t = d / bp
        t.parent.mkdir(parents=True, exist_ok=True)
        b_ = shipped_bytes(src, bp)
        if b_ is None:
            shutil.copy(src, t)    # no dates preserved: the bundle run must not depend on file times
        else:
            t.write_bytes(b_)      # the redacted copy that ships (REDACTION.md)
    shutil.copy(SUMS, d / "SHA256SUMS")
    import py_compile  # noqa: PLC0415
    for py in d.rglob("*.py"):
        py_compile.compile(str(py), doraise=True)   # every shipped Python file must compile
    env = dict(os.environ, THOR_BENCH_ROOT=str(d / "logs/bench"), THOR_GGUF_ROOT=str(d / "logs/gguf"),
               THOR_FORGE_ROOT=str(d / "logs/forge"), THOR_RELEASE_ROOT=str(d / "release"),
               HF_HOME_CACHE=str(d / "hf"), THOR_FILE_MANIFEST=str(d / "scripts/manifest_file.json"),
               THOR_CICLI_EXTRACT=str(d / "scripts/cicli_extract.tsv"), THOR_LATEX_DIR=str(d / "out"),
               THOR_BUNDLE_DIR=str(d), THOR_PAPER_DIR=str(d / "paper"), THOR_NO_BUNDLE_LIST="1",
               OMP_NUM_THREADS="1",
               THOR_FORBID_PRIVATE=":".join(x for x in ("/mnt/models", "/mnt/usb-ssd", FORGE, BENCH, GGUF,
                                                        os.path.expanduser("~/tony-forgia")) if x))
    r = subprocess.run([sys.executable, str(d / "scripts/genera_numeri.py"), "--bundle", "--no-hash"], env=env,
                       capture_output=True, text=True, cwd=d)
    tail = [ln for ln in (r.stdout + r.stderr).splitlines() if not ln.startswith("WARNING")]
    print("\n".join(tail[-4:]))
    a = emitted_macros(HERE.parent / "latex" / "numbers_final.tex")
    b = emitted_macros(d / "out" / "numbers_final.tex") if (d / "out" / "numbers_final.tex").exists() else {}
    if r.returncode:
        diff = sorted(k for k in a.keys() | b.keys() if a.get(k) != b.get(k))
        raise SystemExit(f"bundle test FAILED (exit {r.returncode}); macros differing: {len(diff)}")
    diff = sorted(k for k in a.keys() | b.keys() if a.get(k) != b.get(k))
    print(f"bundle test: exit 0 on a copy (not links); {len(b)} macros; {len(diff)} differ from the full run"
          + (f": {diff[:12]}" if diff else "") + f"; not copied (model files): {skipped}")
    if diff:
        raise SystemExit("bundle test: macros differ from the full run")
    # guard self-test (G17_R4 m1): drop one macro that a live branch of the paper uses; --bundle must then fail
    for drop in ("mStopN", "ptqForkClean", "fucinaReplayVerified", "rrootDone"):   # value, \ifnum, \ifcsname      # a value macro and a switch used only in \ifnum
        r2 = subprocess.run([sys.executable, str(d / "scripts/genera_numeri.py"), "--bundle", "--no-hash"],
                            env=dict(env, THOR_GUARD_DROP=drop), capture_output=True, text=True, cwd=d)
        if r2.returncode == 0 or drop not in (r2.stdout + r2.stderr):
            raise SystemExit(f"guard self-test FAILED: --bundle accepted a paper without the macro {drop}")
        print(f"guard self-test: dropping {drop} makes --bundle fail as it should (exit {r2.returncode})")


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--test", action="store_true", help="also materialize the bundle and run the README command on it")
    a = ap.parse_args()
    deprivatize_ptq1()
    write(collect())
    if a.test:
        test_bundle()


if __name__ == "__main__":
    main()