File size: 64,811 Bytes
c13745f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af165f8
 
 
c13745f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
"""Generate the repository's report set and root README from the stored result files.

Every number written here is read from a `result.json` / `eval_*.json` / `summary.json`
produced by a run.  Nothing is typed in by hand and nothing is estimated: experiments
that have not finished are reported as running, with the progress parsed from their log.

Run as often as you like; it is idempotent.  Output goes to hf_work/stage3/.
"""
import json, glob, os, re, subprocess, datetime
from pathlib import Path
from statistics import mean, stdev

ROOT = Path("/home/ubuntu/pro")
HF = ROOT / "hf_work"
OUT = HF / "stage3"
REP = OUT / "REPORTS"
LOGS = OUT / "LOGS"
NOW = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC")

B = ROOT / "baselines"
M = ROOT / "TSRDA_MTLCC"
P = ROOT / "TSRDA_PLANTEUR"
FD = ROOT / "TSRDA_FOUNDATION"


def foundation():
    """The external-pre-training / PASTIS-components track (TSRDA_FOUNDATION/make_report.py); None if unavailable."""
    import importlib, sys as _s
    if str(FD) not in _s.path:
        _s.path.insert(0, str(FD))
    try:
        mod = importlib.import_module("make_report")
        return mod
    except Exception as e:  # never let this track break the main reports
        print("[make_reports] foundation track unavailable:", e)
        return None


# --------------------------------------------------------------------------- utils
def jload(p, default=None):
    try:
        return json.loads(Path(p).read_text())
    except Exception:
        return default


def fmt(x, n=4):
    return "–" if x is None else f"{x:.{n}f}"


def pct(x, n=2):
    return "–" if x is None else f"{100 * x:.{n}f}"


def meansd(v):
    """mean ± sd string; sd needs >= 2 values."""
    if not v:
        return "–"
    if len(v) == 1:
        return f"{v[0]:.4f} (1 run)"
    return f"{mean(v):.4f} ± {stdev(v):.4f}"


def best_val(hist, which="ema"):
    """Best validation mIoU in a T-SRDA history.json (entries hold raw/ema sub-dicts)."""
    v = []
    for h in hist or []:
        x = h.get(which)
        if isinstance(x, dict) and x.get("miou") is not None:
            v.append(x["miou"])
        elif h.get(f"{which}_mIoU") is not None:
            v.append(h[f"{which}_mIoU"])
    return max(v) if v else None


def tail(p, n=3):
    try:
        return Path(p).read_text(errors="replace").splitlines()[-n:]
    except Exception:
        return []


def hhmm(sec):
    if not sec:
        return "–"
    h, m = divmod(int(sec) // 60, 60)
    return f"{h} h {m:02d} m"


# --------------------------------------------------------------------- collect data
def mtlcc_main():
    """TSRDA on MTLCC, the headline run (seed 3407, mask 0.15)."""
    return jload(M / "runs/outputs/option1_results.json", {})


def mtlcc_seeds():
    """Seed-variance fine-tunes: test metrics per seed and per weight set."""
    rows = {}
    main = mtlcc_main()
    if main:
        rows[3407] = {"raw": main.get("test_raw", {}).get("stcln"),
                      "ema": main.get("test_ema", {}).get("stcln")}
    for d in sorted(glob.glob(str(M / "runs/finetune_seed*"))):
        s = int(re.search(r"seed(\d+)", d).group(1))
        rows[s] = {w: (jload(f"{d}/eval_test_{w}.json") or {}).get("stcln") for w in ("raw", "ema")}
    return rows


def mtlcc_ablations():
    """Ablation fine-tunes written by the queue (runs_ablate/<name>/)."""
    out = []
    for d in sorted(glob.glob(str(M / "runs_ablate/*"))):
        name = os.path.basename(d)
        meta = jload(f"{d}/meta.json", {}) or {}
        rows = {w: (jload(f"{d}/eval_test_{w}.json") or {}).get("stcln") for w in ("raw", "ema")}
        hist = jload(f"{d}/history.json") or []
        best = best_val(hist)
        out.append(dict(name=name, meta=meta, test=rows, epochs=len(hist), best_val_ema=best))
    return out


def mask04_progress():
    log = M / "runs_mask04/run.log"
    eps = re.findall(r"^\[ep\s+(\d+) DONE\].*elapsed=([\d.]+)min", log.read_text(errors="replace"), re.M) if log.exists() else []
    ft = jload(M / "runs_mask04/finetune_mask04/history.json")
    ev = {w: (jload(M / f"runs_mask04/finetune_mask04/eval_test_{w}.json") or {}).get("stcln") for w in ("raw", "ema")}
    return dict(done=len(eps), total=100,
                min_per_ep=(mean([float(e[1]) for e in eps[-10:]]) if eps else None),
                ft_epochs=(len(ft) if ft else 0), test=ev)


def planteur_runs():
    rows = []
    for p in sorted(glob.glob(str(P / "runs/finetune/*/result.json"))):
        r = jload(p, {})
        rows.append(dict(dir=os.path.basename(os.path.dirname(p)), **r))
    return rows


def planteur_pending():
    plan = [(f, s) for f in (0.02, 0.05, 0.10, 0.25) for s in (3407, 42, 1234)] + [(0.50, 3407), (1.00, 3407)]
    done = {os.path.basename(os.path.dirname(p)) for p in glob.glob(str(P / "runs/finetune/*/result.json"))}
    pend = [(f, s) for f, s in plan if f"frac{int(f*100):03d}_seed{s}" not in done]
    return plan, pend


def planteur_full():
    """T-SRDA test mIoU-8 at 100 % labels (same budget as the baselines), or None while it is not measured."""
    f = P / "runs/finetune/frac100_seed3407/result.json"
    if not f.exists():
        return None
    return json.load(open(f))["test"]["miou"]


def planteur_active():
    """The fine-tune the orchestrator is on right now, from its retry log."""
    log = P / "runs/finetune_retry.log"
    if not log.exists():
        return None
    txt = log.read_text(errors="replace")
    hdr = re.findall(r"===== fine-tune (\d+)/(\d+): fraction (\S+) seed (\d+) =====", txt)
    eps = re.findall(r"^\[ep\s+(\d+)\].*?(\d+)s/ep", txt, re.M)
    if not hdr:
        return None
    k, n, frac, seed = hdr[-1]
    return dict(k=int(k), n=int(n), frac=frac, seed=int(seed),
                epoch=(int(eps[-1][0]) if eps else 0), sec_per_ep=(int(eps[-1][1]) if eps else None))


def curve():
    """Label-efficiency curve: mean ± sd over seeds, per fraction."""
    by = {}
    for r in planteur_runs():
        f = r.get("fraction")
        by.setdefault(f, []).append(r)
    rows = []
    for f in sorted(by):
        rs = by[f]
        sel = [x["best"][x.get("selected_weights", "raw")] for x in rs]
        tst = [x.get("test") or {} for x in rs]
        rows.append(dict(frac=f, n_patches=rs[0].get("n_labelled_patches"), n=len(rs),
                         seeds=sorted(x.get("run_seed") for x in rs),
                         val=meansd([s["miou"] for s in sel]),
                         test=meansd([t["miou"] for t in tst if t.get("miou") is not None]),
                         test_vals=[t["miou"] for t in tst if t.get("miou") is not None],
                         oa=meansd([t["oa"] for t in tst if t.get("oa") is not None]),
                         mf1=meansd([t["mf1"] for t in tst if t.get("mf1") is not None]),
                         hours=sum(x.get("train_seconds", 0) for x in rs) / 3600))
    return rows


def git_env():
    def q(c):
        try:
            return subprocess.run(c, capture_output=True, text=True, shell=True, timeout=30).stdout.strip()
        except Exception:
            return "?"
    return dict(
        torch=q("python3 -c 'import torch;print(torch.__version__)'"),
        cuda=q("python3 -c 'import torch;print(torch.version.cuda)'"),
        gpu=q("nvidia-smi --query-gpu=name,memory.total --format=csv,noheader | head -1"),
        python=q("python3 -V"),
    )


def gpu_now():
    try:
        o = subprocess.run("nvidia-smi --query-gpu=memory.used,memory.total,utilization.gpu --format=csv,noheader",
                           shell=True, capture_output=True, text=True, timeout=30).stdout.strip()
        return o
    except Exception:
        return "?"


def running():
    try:
        o = subprocess.run("ps -eo etime,args", shell=True, capture_output=True, text=True, timeout=30).stdout
    except Exception:
        return []
    keep, seen = [], set()
    for ln in o.splitlines():
        if not re.search(r"(pretrain|train_initial|finetune|finetune_ext|eval_mtlcc|run_experiments|train_cnn|structured_pretrain|planteur_ladder|planteur_ladder_eval)\.py|retry_ft\.sh|chain[ABC]\.sh"
                         r"|runs_mask04/run\.sh|ablate\.sh|queue\.sh", ln) or "grep" in ln:
            continue
        ln = ln.strip()
        if "shell-snapshots" in ln or re.match(r"\S+\s+/bin/(ba)?sh -c ", ln):      # the assistant's own shell wrapper: its text is the command line, never a job
            continue
        ln = re.sub(r"hf_[A-Za-z0-9]{20,}", "hf_***", ln)                         # never let a credential reach a published page
        # one line per distinct command: data-loader workers repeat their parent's argv
        cmd = ln.split(None, 1)[1] if " " in ln else ln
        if cmd in seen:
            continue
        seen.add(cmd)
        keep.append(ln)
    return keep


# ------------------------------------------------------------------------ reports
HEAD = "*Generated automatically by [`make_reports.py`](https://huggingface.co/Dhruv1000/TSRDA/blob/main/TOOLS/make_reports.py) on {now} from the run files in this repository. No value on this page was typed by hand.*"


def r_status():
    pl = planteur_active()
    plan, pend = planteur_pending()
    m4 = mask04_progress()
    abl = mtlcc_ablations()
    lines = [f"# Live status\n", HEAD.format(now=NOW), ""]
    lines += ["## Running now\n",
              f"GPU: `{gpu_now()}` (shared machine — other tenants hold most of it).\n",
              "| Job | Where | Progress |", "|---|---|---|"]
    if pl and pend:
        eta = (100 - pl["epoch"]) * (pl["sec_per_ep"] or 0) / 3600
        lines.append(f"| T-SRDA PLANTEUR label-efficiency curve | `TSRDA_PLANTEUR/runs/` | run {pl['k']} of {pl['n']} "
                     f"(fraction {pl['frac']}, seed {pl['seed']}) — epoch {pl['epoch']}/100 at "
                     f"{pl['sec_per_ep']} s/epoch, ≈{eta:.1f} h left on this run |")
    if m4["done"] < m4["total"]:
        left = (m4["total"] - m4["done"]) * (m4["min_per_ep"] or 0) / 60
        lines.append(f"| MTLCC re-pre-training at mask ratio 0.4 | `TSRDA_MTLCC/runs_mask04/` | epoch "
                     f"{m4['done']}/{m4['total']} at {fmt(m4['min_per_ep'],1)} min/epoch, ≈{left:.1f} h left |")
    for a in abl:
        if not (a["test"].get("ema") or a["test"].get("raw")):
            lines.append(f"| MTLCC ablation `{a['name']}` | `TSRDA_MTLCC/runs_ablate/{a['name']}/` | "
                         f"epoch {a['epochs']}/100 |")
    _fd = foundation()
    if _fd:
        for b in _fd.branch_state():
            if b["done"]:
                continue
            prog = (f"epoch {b['epoch']}/{b['of']}" if b["epoch"] else ("running, first validation pending" if b.get("started") else "queued in its chain"))
            best = f", best val {b['best_raw']:.4f}" if b.get("best_raw") else ""
            lines.append(f"| Enhancement track: PLANTEUR `{b['name']}` branch | `TSRDA_FOUNDATION/runs_planteur/` | {prog}{best} |")
        if not (FD / "results/planteur_ladder/ladder.json").exists():
            lines.append("| Enhancement track: PLANTEUR ladder (readouts, caches, nested ensembles) | `TSRDA_FOUNDATION/` | "
                         "queued — starts when the branches above finish; see [`08_FOUNDATION_TRACK.md`](08_FOUNDATION_TRACK.md) |")
    _tbl_empty = lines[-1] == "|---|---|---|"
    if _tbl_empty:
        lines.append("| *(nothing)* | — | **All queued experiments have finished.** |")
    lines += ["", "Process list:\n", "```"] + (running() or ["(none)"]) + ["```", ""]
    lines += ["## Queued / not started\n", "| Work | Why it matters | State |", "|---|---|---|"]
    if pend:
        lines.append(f"| PLANTEUR fine-tunes: " + ", ".join(f"{int(f*100)} %/seed {s}" for f, s in pend) +
                     " | completes the label-efficiency curve | queued behind the running fine-tune |")
    ABL_Q = {"scratch_R4": "isolates what the masked pre-training contributes",
             "scratch_R1": "paired with `scratch_R4`: bounds what the temporal reduction costs at an equal budget",
             "no_boundary": "isolates the boundary decoder's loss"}
    have = {a["name"]: a for a in abl}
    for n, why in ABL_Q.items():
        a_ = have.get(n)
        if a_ and (a_["test"].get("ema") or a_["test"].get("raw")):
            state = "**done** — see [`01_MTLCC.md`](01_MTLCC.md)"
        elif a_:
            state = f"running (epoch {a_['epochs']}/100)"
        else:
            state = "queued, one at a time"
        lines.append(f"| Ablation `{n}` | {why} | {state} |")
    lines += [
        ("| MTLCC fine-tune on the mask-0.4 encoder | tests whether the paper's 40 % masking beats the 15 % in the released script | "
         + ("**done** — see [`01_MTLCC.md`](01_MTLCC.md)" if m4["test"].get("ema") else
            ("fine-tuning / test evaluation" if m4["done"] >= m4["total"] else "queued behind its pre-training")) + " |"),
        "| Ablation: temporal encoder swapped for window / full self-attention, **with the pre-trained encoder in place** | this is the paper's central claim and is **not yet measured** | not started (needs two new training runs) |",
        "| Ablation: reduction factor R ∈ {2, 8} | would complete the R sweep; R ∈ {1, 4} is covered from scratch | not started (needs two new pre-training runs) |",
        "| U-BARN, SITS-Former, SITS-MoCo baselines | the three self-supervised competitors in the STCLN table | not started (adapters not written) |",
        "| STCLN_wp on PLANTEUR | needs its own PLANTEUR pre-training run | not started |",
        "| Seq2seq form of BUnetConvLSTM | would explain the one large unexplained gap vs the published table | not started |",
        "", "Nothing in the two tables above is reported as a result anywhere in this repository until its "
        "run writes a result file.", ""]
    return "\n".join(lines)


def r_mtlcc():
    main = mtlcc_main()
    seeds = mtlcc_seeds()
    m4 = mask04_progress()
    abl = mtlcc_ablations()
    bl = jload(B / "results/mtlcc/summary.json", []) or []
    L = [f"# MTLCC — T-SRDA, seed variance, ablations and the nine-method benchmark\n", HEAD.format(now=NOW), ""]
    L += ["## Protocol (taken verbatim from the STCLN MTLCC scripts)\n",
          "* 13 Sentinel-2 bands scaled by 1e-4, no per-band normalisation; 30 of ≈36 acquisition dates; 48×48 tiles.",
          "* Unlabelled pre-training pool: `train_fold0` (4,873 tiles). Labelled budget: the 78 hand-picked tiles of `finetuning_STCLN.py`.",
          "* Model selection on the 78 validation tiles. Test set: `eval.tileids` — 1,495 tiles, 1,787,407 scored pixels.",
          "* Metrics follow the STCLN definition (pixels with label > 0 and prediction > 0). One metric implementation is shared by every method.", ""]

    if main:
        L += ["## T-SRDA headline run (seed 3407, pre-trained at mask ratio 0.15)\n",
              "| Split | Weights | OA | mIoU | mF1 | κ |", "|---|---|---|---|---|---|"]
        for split in ("val", "test"):
            for w in ("raw", "ema"):
                r = main.get(f"{split}_{w}", {}).get("stcln")
                if r:
                    L.append(f"| {split} | {w} | {fmt(r['OA'])} | **{fmt(r['mIoU'])}** | {fmt(r['mF1'])} | {fmt(r['kappa'])} |")
        L.append("")

    if len(seeds) > 1:
        L += ["## Seed variance (the same pre-trained encoder, three fine-tuning seeds)\n",
              "This is the error bar the comparison needs. The encoder is identical in all three rows; only the "
              "fine-tuning seed differs.\n",
              "| Seed | test mIoU (raw) | test mIoU (EMA) | test OA (EMA) |", "|---|---|---|---|"]
        for s in sorted(seeds):
            r, e = seeds[s].get("raw"), seeds[s].get("ema")
            L.append(f"| {s} | {fmt(r['mIoU']) if r else '–'} | {fmt(e['mIoU']) if e else '–'} | {fmt(e['OA']) if e else '–'} |")
        vr = [seeds[s]["raw"]["mIoU"] for s in seeds if seeds[s].get("raw")]
        ve = [seeds[s]["ema"]["mIoU"] for s in seeds if seeds[s].get("ema")]
        if len(vr) > 1 or len(ve) > 1:
            L.append(f"| **mean ± sd** | **{meansd(vr)}** | **{meansd(ve)}** | – |")
        L += ["",
              "**What this means for the paper.** The spread between seeds is of the same order as the margin "
              "T-SRDA holds over STCLN_wp on this dataset, so a single-seed win here is not evidence of an "
              "architectural advantage. Any claim of superiority on MTLCC has to be stated with these error bars "
              "or withdrawn.", ""]

    if abl:
        L += ["## Ablations\n", "| Ablation | What changes | Epochs | best val mIoU (EMA) | test mIoU (raw) | test mIoU (EMA) |",
              "|---|---|---|---|---|---|"]
        # The reference row is the headline run itself, so the delta each ablation costs can be
        # read off the table without scrolling back to the headline section.
        L.append("| **T-SRDA, full recipe** | reference: pre-trained encoder, R=4, boundary weight 0.5 | 100 | "
                 f"{fmt(main.get('val_ema', {}).get('stcln', {}).get('mIoU'))} | "
                 f"{fmt(main.get('test_raw', {}).get('stcln', {}).get('mIoU'))} | "
                 f"**{fmt(main.get('test_ema', {}).get('stcln', {}).get('mIoU'))}** |")
        for a in abl:
            r, e = a["test"].get("raw"), a["test"].get("ema")
            done = bool(e)
            # While a run is unfinished its best-so-far validation score says nothing useful, so it is
            # labelled rather than printed as if it were a result.
            L.append(f"| `{a['name']}` | {a['meta'].get('what','–')} | "
                     f"{a['epochs'] if done else str(a['epochs']) + ' *(running)*'} | "
                     f"{fmt(a['best_val_ema']) if done else '*running*'} | "
                     f"{fmt(r['mIoU']) if r else '*running*'} | {fmt(e['mIoU']) if e else '*running*'} |")
        L += ["", "Every row keeps the seed, the data, the labelled budget, the selection rule and the metric code "
                  "fixed. `scratch_R4` and `no_boundary` change one thing each against the reference. `scratch_R1` "
                  "changes two — no pre-training *and* R=1 — because an R=1 network cannot load an encoder "
                  "pre-trained at R=4 (R sets the shape of each block's point-wise projection), so it is read "
                  "against `scratch_R4` rather than against the reference.", ""]
        # Deltas are computed here rather than written out, so they cannot drift from the table above.
        ref_e = main.get("test_ema", {}).get("stcln", {}).get("mIoU")
        done = {a["name"]: a["test"]["ema"]["mIoU"] for a in abl if a["test"].get("ema")}
        if ref_e and "scratch_R4" in done:
            L += [f"* **Masked pre-training is worth {fmt(ref_e - done['scratch_R4'])} mIoU** "
                  f"({fmt(done['scratch_R4'])} → {fmt(ref_e)}, EMA). That is the largest effect measured in this "
                  "project and roughly forty times the seed spread above. It says the self-supervised stage carries "
                  "most of the accuracy; it says nothing about whether the T-SRDA encoder is responsible, because "
                  "pre-training and architecture still vary together everywhere else.", ""]
        if "scratch_R1" in done and "scratch_R4" in done:
            d = done["scratch_R1"] - done["scratch_R4"]
            L += [f"* **The temporal reduction costs {fmt(d)} mIoU at an equal budget** — full-resolution keys and "
                  f"values (R=1) reach {fmt(done['scratch_R1'])} against {fmt(done['scratch_R4'])} for R=4, both "
                  "from scratch. This runs against the efficiency argument for the reduction and we report it as "
                  "measured. Bounds on it: R=1 is also the larger network (6.16 M vs 6.02 M parameters), so "
                  "capacity and reduction are not separated; both rows are un-pre-trained, so it is unknown whether "
                  "the gap survives pre-training; and it is one seed per row, while the 0.0030 spread above was "
                  "measured for the pre-trained configuration and from-scratch training is ordinarily noisier.", ""]
        if "plain_ce" in done and ref_e:
            d = done["plain_ce"] - ref_e
            L += [f"* **Our loss family is worth {fmt(-d)} mIoU on top of plain cross-entropy** "
                  f"({fmt(done['plain_ce'])} → {fmt(ref_e)}, EMA), about six seed standard deviations. The run "
                  "keeps our optimiser, schedule, EMA and augmentation and changes only the objective, so it "
                  "measures the largest single piece of the recipe gap, not all of it. It stopped at epoch 81 on "
                  "the patience rule (best EMA at epoch 72). Consequence for the comparison table: with STCLN's "
                  f"plain-CE objective T-SRDA scores {fmt(done['plain_ce'])}, which is *below* the released "
                  "STCLN_wp weights (0.6814). The margin T-SRDA holds over STCLN_wp in the headline table is "
                  "therefore smaller than the loss family it was trained with, and cannot be credited to the "
                  "architecture. Caveat: STCLN_wp was fine-tuned by its own authors' recipe, which differs from "
                  "ours in more than the loss, and this is one seed.", ""]
        nb = next((a for a in abl if a["name"] == "no_boundary" and a["test"].get("ema")), None)
        if nb and ref_e:
            ref_r = main.get("test_raw", {}).get("stcln", {}).get("mIoU")
            ref_v = main.get("val_ema", {}).get("stcln", {}).get("mIoU")
            L += [f"* **The boundary loss has no effect this experiment can resolve.** Setting its weight to 0 gives "
                  f"test mIoU {fmt(nb['test']['ema']['mIoU'])} EMA against {fmt(ref_e)} "
                  f"({fmt(nb['test']['ema']['mIoU'] - ref_e)}), well inside the 0.0030 seed spread. The three "
                  f"available comparisons also disagree in sign — raw test {fmt(nb['test']['raw']['mIoU'])} vs "
                  f"{fmt(ref_r)} favours removing it, best validation {fmt(nb['best_val_ema'])} vs {fmt(ref_v)} "
                  "favours keeping it — and its raw score exceeding its own EMA score is atypical. Taken together "
                  "that is the signature of an effect below the noise floor, not of a component that earns its "
                  "place. We do not claim the boundary decoder helps on MTLCC.", ""]

    L += ["## Mask-ratio check (an inconsistency found in the released code)\n",
          "The released `pretraining_STCLN.py` loops `for maskR in [0.15]`, but the STCLN paper states that 40 % of "
          "pixels are masked, its Fig. 12 recommends 0.4, and the checkpoint path hard-coded in the released "
          "`finetuning_STCLN.py` is `.../batchtimespace0.4/checkpoint_99.utae.tar` — so the authors' own released "
          "weights were pre-trained at 0.4, not 0.15. Our MTLCC pre-training followed the script (0.15); our PASTIS "
          "pre-training used 0.4.\n",
          f"A second pre-training at 0.4 is therefore running, otherwise identical: epoch **{m4['done']}/100**"
          + (f" at {fmt(m4['min_per_ep'],1)} min/epoch" if m4["min_per_ep"] else "") + ".\n"]
    if m4["test"].get("ema"):
        L += ["| Pre-training mask ratio | test mIoU (EMA) |", "|---|---|",
              f"| 0.15 (released script) | {fmt(main.get('test_ema',{}).get('stcln',{}).get('mIoU'))} |",
              f"| 0.40 (paper text, Fig. 12, released checkpoint) | {fmt(m4['test']['ema']['mIoU'])} |", ""]
    else:
        L += ["The comparison will be made on **validation** first, so the test set is not consulted to choose a "
              "mask ratio. No number is claimed for 0.4 until the run finishes.\n"]
    L += ["`MASK_RATIO` is now an environment override in `MTLCC/code/config.py`; the default is left at the script's "
          "0.15 so every number already published keeps its meaning.", ""]

    if bl:
        L += ["## The nine-method benchmark on MTLCC\n",
              "| Rank | Method | lr (chosen on validation) | Params | val mIoU | test OA | test mIoU | test mF1 |",
              "|---|---|---|---|---|---|---|---|"]
        for i, r in enumerate(sorted(bl, key=lambda x: -(x.get("mIoU") or 0)), 1):
            L.append(f"| {i} | {r['model']} | {r['lr']} | {fmt(r.get('params_M'),2)} M | {fmt(r.get('val_mIoU'))} | "
                     f"{fmt(r.get('OA'))} | **{fmt(r.get('mIoU'))}** | {fmt(r.get('mF1'))} |")
        L += ["", "Methods absent from this table were not run; no value was copied from a paper into our columns. "
                  "See [`03_BASELINE_REPRODUCTION.md`](03_BASELINE_REPRODUCTION.md) for how these compare with the "
                  "published table and why they differ.", ""]
    return "\n".join(L)


def r_planteur():
    rows = curve()
    plan, pend = planteur_pending()
    act = planteur_active()
    pl = jload(B / "results/planteur/summary.json", {}) or {}
    L = [f"# PLANTEUR — label efficiency of T-SRDA, and the baseline table\n", HEAD.format(now=NOW), ""]
    L += ["## Protocol\n",
          "* Official folds: 1 / 4 / 5 = **1,896 train / 411 validation / 443 test** patches; 12 monthly Sentinel-2 "
          "mosaics, 10 bands, 128×128 px.",
          "* Official metric: mIoU over 8 classes, Background **scored**, void ignored, a class absent from the "
          "prediction scores IoU 0.",
          "* T-SRDA is pre-trained once, without labels, on all 1,896 training patches, then fine-tuned on a random "
          "subset of the given size. The subset seed and the run seed are the same number so each row is one "
          "self-contained experiment.",
          "* Baselines are trained on **100 % of the labels** — they have no pre-training stage, so this is the "
          "fairest comparison available to them, and it is deliberately the hardest setting for the label-efficiency "
          "claim.", ""]
    if rows:
        L += ["## Label-efficiency curve (T-SRDA)\n",
              "| Labelled fraction | Patches | Seeds | val mIoU-8 | **test mIoU-8** | test OA | test mF1 | GPU time |",
              "|---|---|---|---|---|---|---|---|"]
        for r in rows:
            L.append(f"| {r['frac']:.0%} | {r['n_patches']} | {r['n']} ({', '.join(str(s) for s in r['seeds'])}) | "
                     f"{r['val']} | **{r['test']}** | {r['oa']} | {r['mf1']} | {r['hours']:.1f} h |")
        L.append("")
        if pend:
            L.append("*Not yet in the table (running or queued):* " +
                     ", ".join(f"{int(f*100)} %/seed {s}" for f, s in pend) + ".")
            if act:
                L.append(f"\nThe orchestrator is on run {act['k']} of {act['n']} — {act['frac']} / seed {act['seed']}, "
                         f"epoch {act['epoch']} of 100.")
            L.append("")
    if pl.get("baselines"):
        L += ["## Baselines at 100 % labels (official 443-patch test set)\n",
              "| Rank | Method | lr | Params | OA | mIoU-8 | mF1 | val mIoU-8 | Train |",
              "|---|---|---|---|---|---|---|---|---|"]
        for i, r in enumerate(sorted(pl["baselines"], key=lambda x: -(x.get("mIoU") or 0)), 1):
            L.append(f"| {i} | {r.get('model')} | {r.get('lr')} | {fmt(r.get('params_M'),2)} M | {fmt(r.get('OA'))} | "
                     f"**{fmt(r.get('mIoU'))}** | {fmt(r.get('mF1'))} | {fmt(r.get('val', r.get('val_mIoU')))} | "
                     f"{fmt(r.get('train_h'),1)} h |")
        L.append("")
    else:
        smd = B / "results/planteur/summary.md"
        if smd.exists():
            t = smd.read_text()
            i = t.find("| Rank")
            j = t.find("### Per-class")
            if i >= 0:
                L += ["## Baselines at 100 % labels (official 443-patch test set)\n", t[i:j if j > 0 else len(t)].strip(), ""]
    L += ["## Reading this honestly\n",
          "T-SRDA's curve is measured at small label budgets and the baselines are measured at 100 %. Those are "
          "different experiments and the numbers must not be ranked against each other as if they were one table. "
          "What the curve does support is the shape of the trend — how much of the achievable score survives when "
          "labels are cut — and that is the claim the PLANTEUR section of the paper makes. A T-SRDA run at 100 % "
          + ("labels is the last row of the curve and is queued; until it lands, no same-budget comparison is claimed." if planteur_full() is None else
             f"labels has now been measured: {planteur_full():.4f} test mIoU-8 from a single seed, at the same budget as "
             "the baselines above. That one row is a same-budget comparison; the lower-budget rows still are not."), ""]
    return "\n".join(L)


def r_reproduction():
    src = B / "results/mtlcc/paper_comparison.md"
    L = [f"# Why our baseline numbers differ from the published STCLN table\n", HEAD.format(now=NOW), ""]
    L += ["## The short answer\n",
          "**The STCLN repository ships only STCLN.** It contains `STCLN.py`, `pretraining_STCLN.py`, "
          "`finetuning_STCLN.py` and `test_STCLN.py` for MTLCC and PASTIS — and nothing else. There is no code in it "
          "for UTAE, 3D U-Net, BCLSTM, BUnetConvLSTM, BAtrousConvLSTM, U-BARN, SITS-Former or SITS-MoCo. For seven of "
          "the nine methods in the published table, the authors' exact training script, hyper-parameters, crop "
          "policy, augmentation and selection rule are simply not available, so an exact reproduction of those rows "
          "is impossible — by anyone, not just by us.\n",
          "What we could do instead, and did: clone each method's own original repository, verify that it implements "
          "the architecture the paper names, port it into one shared harness that holds the data, splits, labelled "
          "budget, selection rule and metric code identical for every method, and record every deviation. The "
          "deviations are listed in [`../BASELINES/ADAPTATIONS.md`](../BASELINES/ADAPTATIONS.md).\n",
          "The two rows where exact reproduction *was* possible are the two the repository actually ships, and they "
          "come out right:\n",
          "| Method | Ours (at the paper's own lr 1e-4) | Published | Difference |", "|---|---|---|---|",
          "| STCLN_wp | 0.6953 | 0.6953 | **0.0000** |",
          "| STCLN | 0.6391 | 0.6448 | −0.0057 |", "",
          "That is the harness validating itself: when the authors' code and settings are available, our pipeline "
          "reproduces their published number exactly. So the differences in the other rows are differences in the "
          "*baselines'* training setups, not errors in our data loading, our metric or our evaluation.", ""]
    if src.exists():
        t = src.read_text()
        i = t.find("|")
        L += ["## Row by row\n", t[i:].strip() if i >= 0 else t.strip(), ""]
    L += ["## The one gap we cannot yet explain\n",
          "**BUnetConvLSTM** comes out 0.15 mIoU *below* the published value — the only large negative gap. The "
          "suspected cause is the form of the network: the `osss-mcr` repository implements the N-to-1 variant "
          "(one label map per sequence), while the published row behaves like a sequence-to-sequence form. Testing "
          "the seq2seq form is queued and until it is run this row stays flagged in the paper rather than being "
          "explained away.\n",
          "The positive gaps (BAtrousConvLSTM +0.12, BCLSTM +0.12, 3D U-Net +0.05, UTAE +0.01) are consistent with a "
          "single cause: our harness gives every baseline the same careful treatment — a learning rate chosen on "
          "validation from three candidates, the same augmentation, the same long schedule with early stopping — "
          "whereas a paper comparing nine methods typically trains each once. Being *better* than a published "
          "baseline is not a result in our favour; it means our baselines are stronger, which makes the comparison "
          "harder for T-SRDA, not easier. We report it that way round.", ""]
    return "\n".join(L)


def r_pastis():
    return "\n".join([
        "# PASTIS — what the stored 58.63 % / 60.44 % numbers actually are\n", HEAD.format(now=NOW), "",
        "The PASTIS work in [`../PASTIS/`](../PASTIS) predates the MTLCC and PLANTEUR studies and is kept here "
        "unchanged, including its own full README and reports. It should **not** be read as a clean architecture "
        "comparison, for three reasons that are documented in its own files and repeated here so nobody has to dig "
        "for them:\n",
        "1. **The headline figure is an ensemble**, not a single network — the best directly evaluated method blends "
        "a 5×5 local-moments Gaussian readout with a preceding ensemble.",
        "2. **It contains an externally pre-trained component** (a frozen TESSERA checkpoint) whose geographic "
        "overlap with the PASTIS test region is uncertified.",
        "3. **The same test fold was inspected repeatedly** while those variants were explored, which makes the "
        "results exploratory. Best observed test performance from that process must not be presented as a "
        "validation-selected benchmark.\n",
        "The detailed table, the per-class scores and the reviewer-readiness audit are in "
        "[`../PASTIS/RESULTS.md`](../PASTIS/RESULTS.md) and "
        "[`../PASTIS/reports/reviewer_readiness/REVIEWER_READINESS.md`](../PASTIS/reports/reviewer_readiness/REVIEWER_READINESS.md).\n",
        "**Consequence for the paper.** The PASTIS row cannot carry an architecture claim as it stands. The only "
        "clean option is a re-run of the single-network configuration under the frozen recipe, with no external "
        "weights and one pass over the test set. That run is listed as not started in "
        "[`07_STATUS.md`](07_STATUS.md), and the manuscript marks the PASTIS section accordingly instead of quoting "
        "the 58.63 % figure as a comparable result.", ""])


def r_inventory():
    L = [f"# Run inventory — every training run behind this repository\n", HEAD.format(now=NOW), ""]
    L += ["## T-SRDA, MTLCC\n", "| Run | Encoder | Seed | Epochs | best val mIoU | test mIoU (raw / EMA) | Files |",
          "|---|---|---|---|---|---|---|"]
    main = mtlcc_main()
    if main:
        L.append(f"| headline fine-tune | mask 0.15, 100 ep | 3407 | 100 | "
                 f"{fmt(main.get('val_ema',{}).get('stcln',{}).get('mIoU'))} | "
                 f"{fmt(main.get('test_raw',{}).get('stcln',{}).get('mIoU'))} / "
                 f"{fmt(main.get('test_ema',{}).get('stcln',{}).get('mIoU'))} | `MTLCC/` |")
    for s, v in sorted(mtlcc_seeds().items()):
        if s == 3407:
            continue
        h = jload(M / f"runs/finetune_seed{s}/history.json") or []
        bv = best_val(h)
        L.append(f"| seed-variance fine-tune | mask 0.15, 100 ep | {s} | {len(h)} | {fmt(bv)} | "
                 f"{fmt(v['raw']['mIoU']) if v.get('raw') else '–'} / {fmt(v['ema']['mIoU']) if v.get('ema') else '–'} | "
                 f"`LOGS/mtlcc/seeds_finetune.log` |")
    m4 = mask04_progress()
    _st = "done" if m4["done"] >= m4["total"] else "**running**"
    L.append(f"| mask-0.4 re-pre-training | {_st}, epoch {m4['done']}/100 | 3407 | – | – | – | "
             f"`LOGS/mtlcc/mask04_pretrain.log` |")
    if m4["ft_epochs"]:
        _t = m4["test"]
        L.append(f"| mask-0.4 fine-tune | {'done' if _t.get('ema') else '**running**'}, {m4['ft_epochs']} ep | 3407 | {m4['ft_epochs']} | – | "
                 f"{fmt(_t['raw']['mIoU']) if _t.get('raw') else '–'} / {fmt(_t['ema']['mIoU']) if _t.get('ema') else '–'} | "
                 f"`LOGS/mtlcc/mask04_finetune.log` |")
    for a in mtlcc_ablations():
        r, e = a["test"].get("raw"), a["test"].get("ema")
        L.append(f"| ablation `{a['name']}` | {a['meta'].get('what','–')} | {a['meta'].get('seed','3407')} | "
                 f"{a['epochs']} | {fmt(a['best_val_ema'])} | {fmt(r['mIoU']) if r else '*running*'} / "
                 f"{fmt(e['mIoU']) if e else '*running*'} | `LOGS/mtlcc/ablate_{a['name']}.log` |")
    L.append("")

    L += ["## T-SRDA, PLANTEUR\n", "| Run | Labelled | Seed | Epochs | Early stop | best val mIoU-8 | test mIoU-8 | GPU time |",
          "|---|---|---|---|---|---|---|---|"]
    for r in planteur_runs():
        sel = r.get("selected_weights", "raw")
        L.append(f"| `{r['dir']}` | {r.get('fraction',0):.0%} ({r.get('n_labelled_patches')} patches) | "
                 f"{r.get('run_seed')} | {r.get('epochs_run')} | {'yes' if r.get('early_stopped') else 'no'} | "
                 f"{fmt(r['best'][sel]['miou'])} | {fmt((r.get('test') or {}).get('miou'))} | "
                 f"{hhmm(r.get('train_seconds'))} |")
    act = planteur_active()
    if act:
        L.append(f"| `frac{int(float(act['frac'].rstrip('%'))):03d}_seed{act['seed']}` (running) | {act['frac']} | "
                 f"{act['seed']} | {act['epoch']}/100 | – | – | – | in progress |")
    L.append("")

    for ds, title in (("mtlcc", "MTLCC"), ("planteur", "PLANTEUR")):
        runs = sorted(glob.glob(str(B / f"results/{ds}/*/*")))
        if not runs:
            continue
        L += [f"## Baselines, {title} (every learning-rate trial, not only the winners)\n",
              "| Run | Model | lr | best val | test mIoU | Train | Status |", "|---|---|---|---|---|---|---|"]
        for d in runs:
            rj = jload(f"{d}/result.json")
            nm = os.path.basename(d)
            if rj:
                tj = (rj.get("test") or {})
                tv = (tj.get("stcln") or tj).get("mIoU")
                L.append(f"| `{nm}` | {rj.get('model')} | {rj.get('lr')} | {fmt(rj.get('best_val_mIoU'))} | "
                         f"{fmt(tv)} | {hhmm(rj.get('train_seconds'))} | done |")
            else:
                L.append(f"| `{nm}` | – | – | – | – | – | no result file (unfinished or abandoned trial) |")
        L.append("")
    return "\n".join(L)


def r_repro():
    e = git_env()
    return "\n".join([
        f"# Reproducing this work\n", HEAD.format(now=NOW), "",
        "## Environment\n",
        f"| | |", "|---|---|",
        f"| Python | `{e['python']}` |", f"| PyTorch | `{e['torch']}` |", f"| CUDA (torch) | `{e['cuda']}` |",
        f"| GPU | `{e['gpu']}` |",
        "| Machine | shared: other tenants hold most of the GPU's memory for the whole period these runs cover |", "",
        "The shared GPU matters for reading the timings in [`05_RUN_INVENTORY.md`](05_RUN_INVENTORY.md): wall-clock "
        "per epoch varies by more than 2× between quiet and busy periods, so wall time is reported for the record, "
        "never used as a measurement.\n",
        "## Commands\n",
        "```bash",
        "# ---- T-SRDA on MTLCC -------------------------------------------------",
        "cd MTLCC/code",
        "python3 prep_data.py                      # one-off: decode the TFRecords",
        "python3 pretrain.py --seed 3407 --epochs 100          # NDVI-gated masked reconstruction",
        "MASK_RATIO=0.4 EXP_ROOT=../runs_mask04 python3 pretrain.py --seed 3407 --epochs 100   # paper's ratio",
        "python3 train_initial.py --pretrain_pth ../runs/checkpoints/pretrain/checkpoint_99.utae.tar --seed 3407",
        "python3 train_initial.py --pretrain_pth none --seed 3407   # ablation: no pre-training",
        "python3 eval_mtlcc.py --ckpt ../runs/finetune_seed42/model_best_ema.tar --split test",
        "",
        "# ---- T-SRDA on PLANTEUR ----------------------------------------------",
        "cd PLANTEUR/code",
        "python3 run_experiments.py pretrain      # once, unlabelled, on all 1,896 train patches",
        "python3 run_experiments.py finetune      # the whole (fraction, seed) plan + test evaluation",
        "python3 run_experiments.py summary",
        "",
        "# ---- the nine baselines ----------------------------------------------",
        "cd BASELINES",
        "python3 scripts/run_mtlcc.py    --model utae --lr 1e-4 --seed 3407",
        "python3 scripts/run_planteur.py --model stcln --lr 1e-4 --seed 3407",
        "python3 scripts/summarize_mtlcc.py && python3 scripts/summarize_planteur.py",
        "",
        "# ---- reports and manuscript ------------------------------------------",
        "python3 TOOLS/make_reports.py            # regenerates every page in REPORTS/",
        "cd PAPER && ./build.sh                   # regenerates every table, then main.pdf",
        "```",
        "",
        "## Memory knobs\n",
        "The GPU is shared, so two environment variables exist purely to make evaluation fit alongside other "
        "tenants. **Neither changes a result** — they only change how the same computation is chunked:\n",
        "| Variable | Effect |", "|---|---|",
        "| `SPATIAL_CHUNK` | frames per chunk through the spatial encoder during evaluation (default 32; the "
        "PLANTEUR runs needed 6) |",
        "| `EVAL_BATCH` | patches per evaluation batch |", "",
        "`PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True` is set for every run. Every long job is wrapped in a "
        "retry loop, because a CUDA out-of-memory caused by another tenant is a transient condition, not a failed "
        "experiment; the retry wrappers are committed next to the runs (`runs/retry_ft.sh`, `runs/seeds.sh`, "
        "`runs/eval_seeds.sh`, `runs_mask04/run.sh`).\n",
        "## Rules this repository follows\n",
        "1. A number appears only if a result file in this repository contains it. Unfinished work is labelled "
        "unfinished.",
        "2. Published numbers from other papers are never mixed into our columns; they sit in rows marked "
        "*published*.",
        "3. Every deviation from an original implementation is written down in "
        "[`../BASELINES/ADAPTATIONS.md`](../BASELINES/ADAPTATIONS.md) before the run is reported.",
        "4. The test set is consulted once per configuration, after selection on validation. Where that discipline "
        "was broken (PASTIS), it is stated plainly in [`04_PASTIS.md`](04_PASTIS.md).",
        "5. Reports are generated from the run files by `TOOLS/make_reports.py`, so the repository cannot drift out "
        "of step with its own results.", ""])


def r_index():
    return "\n".join([
        "# Reports\n", HEAD.format(now=NOW), "",
        "| Page | What is in it |", "|---|---|",
        "| [`00_OVERVIEW.md`](00_OVERVIEW.md) | the whole project on one page: what was built, what is measured, what is not |",
        "| [`01_MTLCC.md`](01_MTLCC.md) | T-SRDA on MTLCC, seed error bars, ablations, mask-ratio check, nine-method table |",
        "| [`02_PLANTEUR.md`](02_PLANTEUR.md) | the label-efficiency curve and the PLANTEUR baseline table |",
        "| [`03_BASELINE_REPRODUCTION.md`](03_BASELINE_REPRODUCTION.md) | why our baseline numbers differ from the published STCLN table, row by row |",
        "| [`04_PASTIS.md`](04_PASTIS.md) | what the stored PASTIS figures are, and why they cannot carry a claim |",
        "| [`05_RUN_INVENTORY.md`](05_RUN_INVENTORY.md) | every training run, its configuration, its metric and its wall time |",
        "| [`06_REPRODUCIBILITY.md`](06_REPRODUCIBILITY.md) | environment, exact commands, memory knobs, the rules this repo follows |",
        "| [`07_STATUS.md`](07_STATUS.md) | what is running right now, what is queued, what has not been started |",
        "| [`08_FOUNDATION_TRACK.md`](08_FOUNDATION_TRACK.md) | the PASTIS enhancements (frozen TESSERA Gaussian, branches, nested ensembles) ported to MTLCC and PLANTEUR — a separate, externally pre-trained track |", ""])


def r_overview():
    main = mtlcc_main()
    seeds = mtlcc_seeds()
    rows = curve()
    bl = jload(B / "results/mtlcc/summary.json", []) or []
    plan, pend = planteur_pending()
    L = [f"# Overview\n", HEAD.format(now=NOW), ""]
    L += ["## What this project is\n",
          "**T-SRDA** is a crop-mapping network for satellite image time series. It pairs an atrous (ASPP) spatial "
          "encoder with a *temporal spatial-reduction dual-attention* block: queries stay at full temporal "
          "resolution while keys and values are grouped by a reduction factor R, which buys a global temporal "
          "receptive field at O(T²D/R) instead of O(T²D). It is pre-trained without labels by NDVI-gated masked "
          "reconstruction, then fine-tuned for segmentation.\n",
          "It is evaluated against the nine methods of the STCLN paper (Qin et al., 2025) on three datasets, with "
          "the baselines re-run by us in one shared harness rather than quoted.\n"]
    L += ["## Where the numbers stand\n", "| Dataset | T-SRDA | Best baseline we re-ran | Status |", "|---|---|---|---|"]
    if main:
        best = max(((r.get("mIoU") or 0, r["model"]) for r in bl if r.get("key") != "tsrda"), default=(None, "–"))
        sv = [seeds[s]["ema"]["mIoU"] for s in seeds if seeds[s].get("ema")]
        L.append(f"| MTLCC (78 labelled tiles) | test mIoU **{fmt(main.get('test_ema',{}).get('stcln',{}).get('mIoU'))}** "
                 f"(EMA, seed 3407); over {len(sv)} seeds {meansd(sv)} | {best[1]} {fmt(best[0])} | "
                 f"benchmark complete for 7 of 9 methods; mask-ratio check and ablations running |")
    if rows:
        L.append(f"| PLANTEUR (2–100 % labels) | curve measured at " +
                 ", ".join(f"{r['frac']:.0%}" for r in rows) + f"; best so far {rows[-1]['test']} at {rows[-1]['frac']:.0%} "
                 f"| STCLN 0.3602 at 100 % labels | {len(plan)-len(pend)} of {len(plan)} fine-tunes done |")
    L.append("| PASTIS | see [`04_PASTIS.md`](04_PASTIS.md) | – | stored figures are an ensemble with external "
             "pre-training; not a clean comparison |")
    L.append("")
    L += ["## What is honestly not established yet\n",
          "This section exists so that no reader has to find it out for themselves.\n",
          "1. **The central architectural claim is only partly isolated.** A from-scratch pair (R=4 against R=1, "
          "the latter keeping keys and values at full temporal resolution) bounds what the reduction costs, but no "
          "ablation has yet swapped the temporal spatial-reduction block for window attention or full "
          "self-attention with the pre-trained encoder in place, so the result is not cleanly separated from the "
          "rest of the recipe (loss, schedule, EMA, decoder).",
          "2. **MTLCC's margin is inside seed noise.** See the error bars in [`01_MTLCC.md`](01_MTLCC.md).",
          "3. **T-SRDA and the baselines are measured at different label budgets on PLANTEUR** — the curve at 2–25 % "
          + ("versus baselines at 100 %. The 100 % T-SRDA run is queued; until then there is no same-budget row." if planteur_full() is None else
             f"versus baselines at 100 %. The one same-budget row (T-SRDA at 100 %: {planteur_full():.4f}) is a single seed, "
             "while the 2–25 % points have three."),
          "4. **Seven of the nine baselines cannot be reproduced exactly**, because the STCLN repository ships only "
          "STCLN. What that means in practice is set out in [`03_BASELINE_REPRODUCTION.md`](03_BASELINE_REPRODUCTION.md).",
          "5. **One baseline gap is unexplained** (BUnetConvLSTM, −0.15 against the published value).",
          "6. **PASTIS cannot carry a claim** in its current form.\n",
          "Items 1–3 and 6 are what stands between the draft manuscript in [`../PAPER/`](../PAPER) and a "
          "submittable paper. The manuscript marks each of them in red rather than papering over them.\n"]
    L += ["## Layout\n", "| Folder | What is in it |", "|---|---|",
          "| [`REPORTS/`](.) | these pages — generated from the result files |",
          "| [`MTLCC/`](../MTLCC) | T-SRDA on MTLCC: code, checkpoints, results |",
          "| [`PLANTEUR/`](../PLANTEUR) | T-SRDA on PLANTEUR: code, checkpoints, the label-efficiency runs |",
          "| [`BASELINES/`](../BASELINES) | the nine-method harness: cloned repos' adapters, every run, every log |",
          "| [`PASTIS/`](../PASTIS) | the earlier PASTIS work, unchanged, with its own README |",
          "| [`PAPER/`](../PAPER) | the journal-style manuscript (working draft), LaTeX + PDF |",
          "| [`LOGS/`](../LOGS) | raw training logs, as written by the jobs |",
          "| [`TOOLS/`](../TOOLS) | the generators that build these reports |", ""]
    return "\n".join(L)


# -------------------------------------------------------------------------- README
def root_readme_legacy():
    main = mtlcc_main()
    seeds = mtlcc_seeds()
    rows = curve()
    plan, pend = planteur_pending()
    m4 = mask04_progress()
    sv = [seeds[s]["ema"]["mIoU"] for s in seeds if seeds[s].get("ema")]
    tail_md = (HF / "readme_tail.md").read_text()
    L = ["""---
tags:
- pytorch
- remote-sensing
- satellite-time-series
- crop-mapping
- semantic-segmentation
- sentinel-2
- self-supervised-learning
- pastis
- mtlcc
- planteur
metrics:
- mIoU
- f1
- accuracy
- kappa
---
""",
         "# T-SRDA — crop mapping on satellite image time series",
         "",
         "Temporal **S**patial-**R**eduction **D**ual **A**ttention for Sentinel-2 time series, pre-trained without "
         "labels and evaluated against the nine methods of the STCLN paper on **MTLCC**, **PLANTEUR** and **PASTIS**.",
         "",
         f"*Snapshot {NOW}. Experiments are still running; every number below is read from a result file in this "
         "repository by [`TOOLS/make_reports.py`](TOOLS/make_reports.py), and work that has not finished is labelled "
         "as such rather than estimated.*",
         "",
         "## Start here",
         "",
         "| | |", "|---|---|",
         "| **Read the project on one page** | [`REPORTS/00_OVERVIEW.md`](REPORTS/00_OVERVIEW.md) |",
         "| **What is running right now** | [`REPORTS/07_STATUS.md`](REPORTS/07_STATUS.md) |",
         "| **All reports** | [`REPORTS/`](REPORTS) |",
         "| **The manuscript** | [`PAPER/main.pdf`](PAPER/main.pdf) — working draft |",
         "| **Lost the VM? Rebuild it** | [`RESTORE/RESTORE.md`](RESTORE/RESTORE.md) — one script restores code, checkpoints and context |",
         "| **Project brief for Claude Code** | [`CLAUDE.md`](CLAUDE.md) — rules, layout, open work, the user's request log |",
         "| **Full chat history** | [`HISTORY/`](HISTORY) — readable log, compaction summaries, redacted raw sessions |",
         "", "## Results at a glance", "",
         "| Dataset | Setting | Metric | T-SRDA | Reference |", "|---|---|---|---|---|"]
    if main:
        L.append(f"| MTLCC | 78 labelled tiles, test = 1,495 tiles | mIoU | "
                 f"**{fmt(main.get('test_ema',{}).get('stcln',{}).get('mIoU'))}** (EMA, seed 3407)"
                 + (f", {meansd(sv)} over {len(sv)} seeds" if len(sv) > 1 else "") +
                 " | STCLN_wp 0.6814 (our re-run), 0.6953 at the paper's lr |")
    for r in rows:
        if r["frac"] in (0.02, 0.10, 0.25, 1.0):
            L.append(f"| PLANTEUR | {r['frac']:.0%} of labels ({r['n_patches']} patches) | mIoU-8 | "
                     f"**{r['test']}** | best baseline at 100 % labels: STCLN 0.3602 |")
    L.append("| PASTIS | see the note | mIoU | not a clean comparison — "
             "[`REPORTS/04_PASTIS.md`](REPORTS/04_PASTIS.md) | – |")
    L += ["",
          "The MTLCC seed spread and the different label budgets on PLANTEUR are the two things that stop these rows "
          "being read as a ranking; both are explained in the reports rather than buried.", ""]

    # --- ablations: every figure below is read from the run files, none typed ---
    abl = {a["name"]: a for a in mtlcc_ablations() if a["test"].get("ema")}
    ref = main.get("test_ema", {}).get("stcln", {}).get("mIoU") if main else None
    if abl and ref:
        g = lambda n: abl[n]["test"]["ema"]["mIoU"]
        L += ["## What the MTLCC ablations show", "",
              "One seed per row, same 78 labelled tiles, same test set; the seed spread of the full recipe is "
              f"{meansd(sv)}. Full table and caveats: [`REPORTS/01_MTLCC.md`](REPORTS/01_MTLCC.md).", "",
              "| Question | Run | test mIoU (EMA) | Δ | Reading |", "|---|---|---|---|---|"]
        if "scratch_R4" in abl:
            L.append(f"| What does masked pre-training buy? | `scratch_R4` | {fmt(g('scratch_R4'))} | "
                     f"{g('scratch_R4') - ref:+.4f} vs full | **The largest effect measured.** The self-supervised "
                     "stage carries most of the accuracy. |")
        if "scratch_R1" in abl and "scratch_R4" in abl:
            L.append(f"| What does the temporal reduction cost? | `scratch_R1` | {fmt(g('scratch_R1'))} | "
                     f"{g('scratch_R1') - g('scratch_R4'):+.4f} vs `scratch_R4` | R=1 is *better* from scratch: the "
                     "reduction is a cost–accuracy trade, not a free saving. R=1 is also the larger net. |")
        if "plain_ce" in abl:
            L.append(f"| How much is our loss worth? | `plain_ce` | {fmt(g('plain_ce'))} | "
                     f"{g('plain_ce') - ref:+.4f} vs full | With STCLN's plain cross-entropy T-SRDA falls **below** "
                     "STCLN_wp (0.6814): the headline margin is not the architecture's. |")
        if "no_boundary" in abl:
            L.append(f"| Does the boundary loss help? | `no_boundary` | {fmt(g('no_boundary'))} | "
                     f"{g('no_boundary') - ref:+.4f} vs full | Null result — inside the seed spread, signs disagree "
                     "across raw / EMA / validation. |")
        L += ["",
              "None of these runs attributes any accuracy to the T-SRDA *temporal encoder* itself, because "
              "pre-training and architecture are still varied together. The encoder swap that would separate them "
              "is not yet run.", ""]
    L += ["## Repository layout", "",
          "| Folder | Dataset | Contents |", "|---|---|---|",
          "| [`REPORTS/`](REPORTS) | all | **Generated reports** — overview, per-dataset results, run inventory, "
          "reproduction analysis, live status. |",
          "| [`MTLCC/`](MTLCC) | MTLCC (13 bands, 48×48 tiles) | T-SRDA port: code, tools, results, checkpoints. "
          "Full write-up: [`MTLCC/REPORT.md`](MTLCC/REPORT.md). |",
          "| [`PLANTEUR/`](PLANTEUR) | PLANTEUR 2026 (10 bands, 128×128, tropical crops) | Label-efficiency study, "
          f"{len(plan)-len(pend)} of {len(plan)} fine-tunes complete. |",
          "| [`BASELINES/`](BASELINES) | MTLCC + PLANTEUR | The nine-method harness: adapters, every learning-rate "
          "trial, logs, checkpoints, and [`ADAPTATIONS.md`](BASELINES/ADAPTATIONS.md). |",
          "| [`PASTIS/`](PASTIS) | PASTIS (10 bands, 128×128) | The earlier PASTIS work, unchanged, with its own "
          "README reproduced below. |",
          "| [`PAPER/`](PAPER) | all | Journal-style manuscript (**working draft**). Tables are generated from the "
          "result files; unfinished experiments are marked in red in the PDF. |",
          "| [`LOGS/`](LOGS) | all | Raw training logs as the jobs wrote them. |",
          "| [`RESTORE/`](RESTORE) | all | **Disaster-recovery kit**: code snapshot with hashes, environment, third-party commits, "
          "`restore.sh`. Pre-training checkpoints are under `MTLCC/checkpoints/` and `PLANTEUR/checkpoints/`. |",
          "| [`HISTORY/`](HISTORY), [`MEMORY/`](MEMORY), [`CLAUDE.md`](CLAUDE.md) | – | The conversation (secrets removed), "
          "the assistant's notes, and the brief a new session reads first. |",
          "| [`TOOLS/`](TOOLS) | – | The generators that build the reports and this README. |",
          "", "## Method in one paragraph", "",
          "An atrous/ASPP spatial encoder embeds every acquisition. The temporal encoder then projects point-wise, "
          "groups R consecutive acquisitions into reduced keys and values, runs self-attention on the reduced "
          "sequence and cross-attention from the full-resolution queries, giving a global temporal receptive field at "
          "O(T²D/R) cost; a small convolutional MLP with a parallel depthwise Conv1d follows, and the date positional "
          "encoding is added *before* the key/value reduction so no temporal information is lost to it. Pre-training "
          "reconstructs masked acquisitions under an NDVI gate applied **per frame**, which is what the released "
          "STCLN code does (a per-pixel gate would hide 18 % of the values instead of 4 %). Fine-tuning adds an "
          "attention pool over time, parallel semantic and boundary decoders and a gated refinement step, trained "
          "with cross-entropy + 0.75 Lovász + 0.5 boundary BCE under AdamW, a halved encoder learning rate, warm-up "
          "and cosine decay, and an EMA of the weights.",
          "", "## Honest limits", "",
          "1. The **central architectural claim is only partly isolated.** A from-scratch pair (R=4 vs R=1) bounds "
          "what the temporal reduction costs, but the swap of the whole temporal block for window or full "
          "self-attention *with the pre-trained encoder in place* has not been run.",
          "2. On **MTLCC the margin over STCLN_wp is inside seed noise, and the loss-family ablation removes it** — "
          "with plain cross-entropy T-SRDA scores below STCLN_wp "
          "([`REPORTS/01_MTLCC.md`](REPORTS/01_MTLCC.md)). We do not claim T-SRDA beats STCLN_wp on MTLCC.",
          "3. On **PLANTEUR, T-SRDA and the baselines are measured at different label budgets**; the same-budget row "
          "is queued.",
          "4. **Seven of the nine baselines cannot be reproduced exactly** — the STCLN repository ships only STCLN "
          "([`REPORTS/03_BASELINE_REPRODUCTION.md`](REPORTS/03_BASELINE_REPRODUCTION.md)).",
          "5. The **PASTIS figures are an ensemble** with an externally pre-trained component and a history of test "
          "inspection ([`REPORTS/04_PASTIS.md`](REPORTS/04_PASTIS.md)).",
          "6. The released STCLN pre-training script masks 15 % of pixels while the paper says 40 %; our MTLCC "
          "encoder followed the script, and a 0.4 re-run is "
          + (f"in progress (epoch {m4['done']}/100)." if m4["done"] < 100 else "complete — see the report."),
          "", "## Licence and attribution", "",
          "Third-party baseline code is cloned unmodified from each method's own repository; the clone sources, "
          "commits and licence files are listed in [`BASELINES/README.md`](BASELINES/README.md). The MTLCC and "
          "PLANTEUR datasets stay with their original licences and are not redistributed here.",
          "", "---", ""]
    return "\n".join(L) + "\n" + tail_md


def root_readme():
    """Front page: built by readme_builder.py from the result files and the figures module."""
    import importlib, sys as _s
    _s.path.insert(0, str(HF))
    import readme_builder, make_figures
    importlib.reload(readme_builder)
    return readme_builder.build(_s.modules[__name__], make_figures, (HF / "readme_tail.md").read_text())


# ----------------------------------------------------------------------------- logs
LOG_MAP = [
    (M / "runs/seeds.log", "mtlcc/seeds_finetune.log"),
    (M / "runs/eval_seeds.log", "mtlcc/seeds_test_eval.log"),
    (M / "runs_mask04/run.log", "mtlcc/mask04_pretrain.log"),
    (P / "runs/finetune_retry.log", "planteur/finetune_curve.log"),
    (P / "runs/all.log", "planteur/pretrain_and_early_runs.log"),
    (HF / "queue.log", "queue/queue.log"),
]


def copy_logs():
    import shutil
    for src, dst in LOG_MAP:
        if Path(src).exists():
            d = LOGS / dst
            d.parent.mkdir(parents=True, exist_ok=True)
            shutil.copy(src, d)
    for p in glob.glob(str(M / "runs_ablate/*/train.log")):
        d = LOGS / f"mtlcc/ablate_{Path(p).parent.name}.log"
        d.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy(p, d)
    for p in glob.glob(str(M / "runs_mask04/finetune_mask04/train.log")):
        d = LOGS / "mtlcc/mask04_finetune.log"
        d.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy(p, d)
    (LOGS / "README.md").write_text(
        "# Raw logs\n\n" + HEAD.format(now=NOW) + "\n\nThese are the jobs' own stdout, copied unedited — including "
        "the CUDA out-of-memory retries caused by other tenants on the shared GPU, which is why several of them "
        "contain `[retry]` lines.\n\n| File | Job |\n|---|---|\n" +
        "\n".join(f"| [`{d}`]({d}) | {s}|" for s, d in LOG_MAP if Path(s).exists()) + "\n")


# ----------------------------------------------------------------------------- foundation track
def stage_foundation():
    """Writes REPORTS/08_FOUNDATION_TRACK.md and stages stage3/FOUNDATION (code, results, logs, scripts, report)."""
    import shutil
    fd = foundation()
    if not fd:
        return
    try:
        fd.main()                                            # TSRDA_FOUNDATION/REPORT.md
    except Exception as e:
        print("[make_reports] foundation report failed:", e); return
    rep = (FD / "REPORT.md").read_text()
    # links in REPORT.md are relative to FOUNDATION/; re-root them for REPORTS/
    rep = re.sub(r"\]\((?!https?:|#|\.\./)([^)]+)\)", r"](../FOUNDATION/\1)", rep)
    (REP / "08_FOUNDATION_TRACK.md").write_text(rep)
    dst = OUT / "FOUNDATION"
    if dst.exists():
        shutil.rmtree(dst)
    dst.mkdir(parents=True)
    for f in list(FD.glob("*.py")) + list(FD.glob("*.md")) + list(FD.glob("*.sh")):
        shutil.copy(f, dst / f.name)
    shutil.copytree(FD / "planteur_branches", dst / "planteur_branches", ignore=shutil.ignore_patterns("__pycache__"))
    shutil.copytree(FD / "results", dst / "results")
    shutil.copytree(FD / "logs", dst / "logs")
    (dst / "runs_planteur").mkdir()
    for f in (FD / "runs_planteur").glob("*.sh"):
        shutil.copy(f, dst / "runs_planteur" / f.name)
    for f in (FD / "runs_planteur").glob("*/completed.json"):
        (dst / "runs_planteur" / f.parent.name).mkdir(exist_ok=True)
        shutil.copy(f, dst / "runs_planteur" / f.parent.name / f.name)


# ----------------------------------------------------------------------------- main
def main():
    REP.mkdir(parents=True, exist_ok=True)
    LOGS.mkdir(parents=True, exist_ok=True)
    (OUT / "TOOLS").mkdir(parents=True, exist_ok=True)
    pages = {
        "README.md": r_index(), "00_OVERVIEW.md": r_overview(), "01_MTLCC.md": r_mtlcc(),
        "02_PLANTEUR.md": r_planteur(), "03_BASELINE_REPRODUCTION.md": r_reproduction(),
        "04_PASTIS.md": r_pastis(), "05_RUN_INVENTORY.md": r_inventory(),
        "06_REPRODUCIBILITY.md": r_repro(), "07_STATUS.md": r_status(),
    }
    for n, t in pages.items():
        (REP / n).write_text(t)
    stage_foundation()
    import subprocess as _sp, sys as _s
    _sp.run([_s.executable, str(HF / "make_figures.py")], check=False)      # figures + GIFs -> stage3/assets
    (OUT / "README.md").write_text(root_readme())
    copy_logs()
    import shutil
    for f in ("make_reports.py", "build_stage2.py", "sync_hf.py", "queue.sh", "make_figures.py", "readme_builder.py",
              "make_history.py", "make_restore.py"):
        if (HF / f).exists():
            shutil.copy(HF / f, OUT / "TOOLS" / f)
    (OUT / "TOOLS/README.md").write_text(
        "# Tools\n\n" + HEAD.format(now=NOW) + "\n\n| File | What it does |\n|---|---|\n"
        "| `make_reports.py` | reads every run's result file and regenerates `REPORTS/` and the root `README.md` |\n"
        "| `build_stage2.py` | stages the `BASELINES/`, `PLANTEUR/` and `PAPER/` folders for upload |\n"
        "| `sync_hf.py` | uploads the staged tree to this repository |\n"
        "| `make_figures.py` | draws every figure and GIF on the front page from the result files |\n"
        "| `readme_builder.py` | assembles the front page (`README.md`) |\n"
        "| `make_history.py`, `make_restore.py` | build the disaster-recovery kit and the redacted chat history |\n"
        "| `queue.sh` | the job queue: waits for a free slot, starts the next experiment, regenerates the reports "
        "and re-syncs |\n\nThese run on the machine that holds the datasets; they are published so the reports can "
        "be audited against the runs.\n")
    print(f"[make_reports] wrote {len(pages)} report pages + README + logs -> {OUT}")


if __name__ == "__main__":
    main()