File size: 71,562 Bytes
868a5eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
#!/usr/bin/env python
"""Selection quality gate + replacement tooling for the 1000-episode DROID alignment selection.

Only exterior cameras are gated (wrist excluded).  Everything is written under data/selection_qa/ and
out/selection_qa/ (plus data/task_selection_final.{tsv,md} by `finalize`); data/task_selection.tsv and
data/manifest_v2.txt are never modified.

Subcommands
  score     [--uuids FILE | UUID ... | --all-selected] [--chunk i --nchunks n] [--workers W] [--force]
            For every episode that HAS data/<uuid>/calib_refined_v2.json: render both exterior cameras with the
            current v2 calibration at every out/gt/<uuid>/<serial>/<step:04d>.png step whose GT status is usable
            (ok/single/low_conf; robot_not_visible = empty GT and failed/marginal/render_* are skipped) and write
            data/selection_qa/scores/<uuid>.json (per camera n_usable, iou_median, iou_p10, r2g_median, r2g_p90,
            refine status, ext_base_source; time sweep_class).  Episodes without a v2 file are reported as pending
            (no score file).  A score is re-used unless the v2 file changed (md5) or --force.
  decide    [--iou-min 0.80] [--r2g-max 6.0] [--min-frames 6] [--fail-errors] [--r2g-metric r2g|r2g_near] [--gt-set strict|ext]
            PASS iff BOTH exterior cameras have n_usable >= min-frames, iou_median >= iou-min, r2g_median <= r2g-max,
            refine status != failed and the time sweep_class is not 'edge'.  Insufficient GT frames => unverifiable
            => FAIL.  No MP4 on GCS => FAIL (can never be verified).  No v2 file / no fresh score => pending.
            Writes data/selection_qa/decisions.csv, decision_table.md, out/selection_qa/decide_summary.json and
            updates the qa_status/qa_reasons columns of data/selection_qa/selection_working.tsv.
  replace   [--seed N] [--round K] [--dry-run] [--no-extra]
            One replacement per FAILED active slot, same task string + outcome, drawn from calib/superset_meta.jsonl
            (never a uuid already in the working selection / used_uuids.txt / the known no-MP4 episodes), preferring
            both exterior cameras GT-source with superset IoU >= 0.85 and len in [max(20, 0.5x), 2x] of the dropped
            episode (tiers 0..4, random within the best non-empty tier).  Round 1 also adds the +1 success for
            'Move object into or out of container ...' (the 1000th episode).  Writes
            data/selection_qa/replacements_round<K>.tsv (uuid<TAB>rel), appends to used_uuids.txt and updates
            selection_working.tsv (dropped rows -> qa_status 'replaced', new rows -> 'pending').
  pending   [--out FILE]   active episodes with a v2 file but no fresh score (input for the scoring array)
  pool      candidate counts per (task, outcome) -> data/selection_qa/pool_counts.csv
  finalize  [--force]      when all active episodes PASS and the quotas are met: data/task_selection_final.tsv/.md
  reselect  [--iou-min 0.75 --r2g-max 8.0 --min-frames 6 --r2g-metric r2g_near --gt-set ext] [--seed] [--max-new-rounds 2]
            [--margin 1.5] [--dry-run] [--write-final]
            Re-decide EVERY row of selection_working.tsv (originals and replacements, whatever their status) and fill each
            (task, outcome) quota with passing originals first, then passing replacements (tier 0 first, then higher
            min-camera IoU).  Short slots: (a) pool not dry -> exactly the shortfall is sampled (never-run pending rows
            first) and queued -> data/selection_qa/reselect_round<k>.tsv, exit 10 (run
            `MANIFEST_ONLY=<tsv> ROUND_TAG=reselect<k> sbatch scripts/replace_loop.sh`, then re-run reselect);
            (b) pool dry -> backfill with the same task's other outcome (passing unused originals, then replacements, then
            pool candidates x margin via the pipeline).  When nothing is queued: data/task_selection_final.{tsv,md},
            data/manifest_final.txt, out/index_final.jsonl, out/selection_qa/reselect_report.json.

Working-selection columns (data/selection_qa/selection_working.tsv): kind task outcome uuid rel steps rendered
round_added replaces replaced_by qa_status qa_reasons; active rows = qa_status != 'replaced'.
"""
import argparse
import collections
import csv
import hashlib
import json
import os
import random
import sys
import time
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))

QA = ROOT / "data/selection_qa"
SCORES = QA / "scores"
OUT_QA = ROOT / "out/selection_qa"
WORKING = QA / "selection_working.tsv"
DECISIONS = QA / "decisions.csv"
USED = QA / "used_uuids.txt"
TASK_TSV = ROOT / "data/task_selection.tsv"
TASK_MD = ROOT / "data/task_selection.md"
FINAL_TSV = ROOT / "data/task_selection_final.tsv"
FINAL_MD = ROOT / "data/task_selection_final.md"
SUPERSET_META = ROOT / "calib/superset_meta.jsonl"
SUPERSET_EXT = ROOT / "calib/cam2base_extrinsic_superset.json"

SEL_COLS = ["kind", "task", "outcome", "uuid", "rel", "steps", "rendered"]
WORK_COLS = SEL_COLS + ["round_added", "replaces", "replaced_by", "qa_status", "qa_reasons"]
TARGET_TOTAL = 1000
EXTRA_TASK_PREFIX = "Move object into or out of container"
EXTRA_TAG = "extra_1000th"

USABLE = ("ok", "single", "low_conf")     # GT statuses gated (== benchmark_align / compare_dn 'usable')
USABLE_EXT = USABLE + ("render_far_off", "render_missing_robot")   # extended set (pipeline's own 'usable'), decide --gt-set ext
MIN_GT_PX = 3000                           # == benchmark_align.MIN_GT_PX
NEAR_PX = 60.0                             # r2g_near: render-edge px within 60 px of any GT px (== benchmark_align r2g_near)
# the 8 selected episodes without MP4 recordings on GCS (pipeline_v2.json status no_mp4 / .gt_done note no_mp4)
NO_MP4_KNOWN = {
    "PennPAL+c5f808b7+2023-10-19-00h-17m-09s", "PennPAL+c5f808b7+2023-10-19-00h-03m-31s",
    "PennPAL+c5f808b7+2023-10-19-00h-13m-07s", "REAL+4f8ca688+2023-05-21-09h-20m-27s",
    "REAL+de601749+2023-12-19-18h-24m-04s", "REAL+de601749+2023-12-19-18h-35m-31s",
    "REAL+de601749+2023-12-19-20h-08m-06s", "REAL+4f8ca688+2023-05-21-09h-26m-37s",
}
DEFAULTS = dict(iou_min=0.80, r2g_max=6.0, min_frames=6, r2g_metric="r2g", gt_set="strict")
LEN_FLOOR = 20


def log(msg):
    print(f"[select_qa {time.strftime('%H:%M:%S')}] {msg}", flush=True)


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


def atomic_json(path, obj):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_suffix(path.suffix + ".tmp")
    json.dump(obj, open(tmp, "w"), indent=1)
    os.replace(tmp, path)


def write_tsv(path, rows, cols):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_suffix(path.suffix + ".tmp")
    with open(tmp, "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=cols, delimiter="\t", extrasaction="ignore", lineterminator="\n")
        w.writeheader()
        for r in rows:
            w.writerow({c: ("" if r.get(c) is None else r.get(c)) for c in cols})
    os.replace(tmp, path)


def outcome_of_rel(rel):
    return "success" if "/success/" in rel else ("failure" if "/failure/" in rel else "unknown")


def pct(vals, q):
    import numpy as np
    a = np.asarray([v for v in vals if v is not None and v == v], dtype=float)
    return float(np.percentile(a, q)) if a.size else None


def r4(v, nd=4):
    return None if v is None or v != v else round(float(v), nd)


# ----------------------------------------------------------------------------- selection state

def load_task_selection():
    return list(csv.DictReader(open(TASK_TSV), delimiter="\t"))


def load_working(create=True):
    """Working selection; created from data/task_selection.tsv (round 0, all pending) on first use."""
    if WORKING.exists():
        rows = list(csv.DictReader(open(WORKING), delimiter="\t"))
        for r in rows:
            for c in WORK_COLS:
                r.setdefault(c, "")
        return rows
    rows = []
    for r in load_task_selection():
        rr = {c: r.get(c, "") for c in SEL_COLS}
        rr.update(round_added="0", replaces="", replaced_by="", qa_status="pending", qa_reasons="")
        rows.append(rr)
    if create:
        write_tsv(WORKING, rows, WORK_COLS)
        log(f"created {WORKING} from {TASK_TSV} ({len(rows)} rows)")
    return rows


def save_working(rows):
    write_tsv(WORKING, rows, WORK_COLS)


def active_rows(rows):
    return [r for r in rows if r.get("qa_status") != "replaced"]


def quotas():
    """Design quotas per (task, outcome) from data/task_selection.tsv (+1 success for the extra slot)."""
    q = collections.OrderedDict()
    kind = {}
    for r in load_task_selection():
        key = (r["task"], r["outcome"])
        q[key] = q.get(key, 0) + 1
        kind[r["task"]] = r["kind"]
    for (t, o) in list(q):
        if o == "success" and t.startswith(EXTRA_TASK_PREFIX):
            q[(t, o)] += 1
    return q, kind


def task_order():
    seen = []
    for r in load_task_selection():
        if r["task"] not in seen:
            seen.append(r["task"])
    return seen


def pipeline_status(uuid):
    p = ROOT / "out" / uuid / "pipeline_v2.json"
    if p.exists():
        try:
            d = json.load(open(p))
            return str(d.get("status", "")), str(d.get("reason", "") or "")
        except (OSError, ValueError):
            return "corrupt", ""
    return "none", ""


def is_no_mp4(uuid):
    if uuid in NO_MP4_KNOWN:
        return True
    st, _ = pipeline_status(uuid)
    if st == "no_mp4":
        return True
    g = ROOT / "out/gt" / uuid / ".gt_done"
    if g.exists():
        try:
            if json.load(open(g)).get("note") == "no_mp4":
                return True
        except (OSError, ValueError):
            pass
    return False


def v2_path(uuid):
    return ROOT / "data" / uuid / "calib_refined_v2.json"


def load_score(uuid):
    p = SCORES / f"{uuid}.json"
    if not p.exists():
        return None
    try:
        return json.load(open(p))
    except (OSError, ValueError):
        return None


def score_fresh(uuid, sc=None):
    """True when a score exists and was computed from the current calib_refined_v2.json."""
    sc = load_score(uuid) if sc is None else sc
    if not sc:
        return False
    vp = v2_path(uuid)
    if not vp.exists():
        return False
    return sc.get("calib_md5") == md5_file(vp)


# ----------------------------------------------------------------------------- score

_RR = None


def _worker_init():
    os.environ.setdefault("OMP_NUM_THREADS", "1")
    os.environ.setdefault("MKL_NUM_THREADS", "1")
    import cv2
    cv2.setNumThreads(1)


def _ext_serials_from_gt(uuid):
    """Exterior serials of the GT folder (select_meta.json cam == ext; fallback: .gt_done serials)."""
    g = ROOT / "out/gt" / uuid
    ext = []
    sm = g / "select_meta.json"
    if sm.exists():
        try:
            for s, m in (json.load(open(sm)).get("serials") or {}).items():
                if m.get("cam") == "ext":
                    ext.append(str(s))
        except (OSError, ValueError):
            pass
    if not ext and (g / ".gt_done").exists():
        try:
            for s, c in (json.load(open(g / ".gt_done")).get("serials") or {}).items():
                if c == "ext":
                    ext.append(str(s))
        except (OSError, ValueError):
            pass
    return ext


def score_one(uuid):
    """Render both exterior cameras at every usable GT step with the current v2 calibration -> score record."""
    global _RR
    import cv2
    import numpy as np
    import render_episode as RE
    from benchmark_align import edge, dt_to, iou_of
    RE.VERBOSE = False
    t0 = time.time()
    ep_dir = ROOT / "data" / uuid
    gdir = ROOT / "out/gt" / uuid
    vp = v2_path(uuid)
    rec = dict(uuid=uuid, status="scored", scored_at=time.strftime("%Y-%m-%d %H:%M:%S"), calib_md5=None, cams={})
    if not vp.exists():
        rec.update(status="pending", error="no calib_refined_v2.json")
        return rec
    rec["calib_md5"] = md5_file(vp)
    if not (gdir / ".gt_done").exists():
        rec.update(status="no_gt", error="out/gt/<uuid>/.gt_done missing")
    try:
        if _RR is None:
            _RR = RE.RobotRenderer()
        sess = RE.EpisodeSession(str(ep_dir), wrist=False, renderer=_RR)
    except Exception as e:  # noqa: BLE001
        rec.update(status="error", error=f"EpisodeSession: {e!r}", elapsed_s=round(time.time() - t0, 1))
        return rec
    tq = sess.time_quality or {}
    rec.update(calib_version=sess.calib_version, time_offset_ms=float(sess.dt_ms),
               time_quality=dict(sweep_class=tq.get("sweep_class"), n_steps=tq.get("n_steps"), prior_used=tq.get("prior_used")),
               gt_masks_used=bool(sess.gt_masks_used), calib_mount_md5_ok=sess.calib_mount_md5_ok,
               calib_problems=list(sess.calib_problems or []), arm=sess.arm_type, wrist_serial=sess.wrist_serial,
               n_steps=int(sess.n), ext_serials_session=[str(s) for s in sess.serials if str(s) != sess.wrist_serial])
    status_all = {}
    if (gdir / "status.json").exists():
        try:
            status_all = json.load(open(gdir / "status.json"))
        except (OSError, ValueError):
            status_all = {}
    gt_ext = _ext_serials_from_gt(uuid)
    serials = [s for s in rec["ext_serials_session"]]
    for s in gt_ext:
        if s not in serials:
            serials.append(s)
    for serial in serials:
        q = (sess.quality or {}).get(serial) or {}
        cam = dict(role="ext", in_session=serial in rec["ext_serials_session"], in_gt=serial in gt_ext,
                   refine_status=q.get("status"), metric_after=q.get("metric_after"), metric_before=q.get("metric_before"),
                   metric_name=q.get("metric_name"), refine_n_steps=q.get("n_steps"), refine_notes=q.get("notes"),
                   ext_base_source=sess.ext_base_source.get(serial), K_source=sess.K_source.get(serial),
                   K_quality=sess.K_quality.get(serial), n_gt=0, n_usable=0, n_skipped_status=0, n_small_gt=0,
                   n_empty_render=0, status_counts={}, frames=[])  # n_skipped_status = GT steps without a png / beyond the h5
        st = status_all.get(serial) or {}
        cam["n_gt"] = len(st)
        cnt = collections.Counter(st.values())
        cam["status_counts"] = dict(cnt)
        if serial not in rec["ext_serials_session"] or serial not in sess.cap_ts or serial not in sess.K_mp4:
            cam["error"] = "camera not renderable with this session (no extrinsics / cap_ts / K)"
            rec["cams"][serial] = cam
            continue
        wh = tuple(sess.mp4_wh.get(serial, tuple(sess.wh[serial])))
        K = sess.K_mp4[serial]
        for step_s, status in sorted(st.items(), key=lambda kv: int(kv[0])):
            step = int(step_s)
            gp = gdir / serial / f"{step:04d}.png"
            if not gp.exists() or step >= sess.n - 1 or step >= len(sess.cap_ts[serial]):
                cam["n_skipped_status"] += 1
                continue
            gt = cv2.imread(str(gp), cv2.IMREAD_GRAYSCALE)
            if gt is None:
                cam["n_skipped_status"] += 1
                continue
            gt = gt > 127
            if (gt.shape[1], gt.shape[0]) != wh:
                gt = cv2.resize(gt.astype(np.uint8) * 255, wh, interpolation=cv2.INTER_NEAREST) > 127
            gt_px = int(gt.sum())
            if gt_px < MIN_GT_PX:
                cam["n_small_gt"] += 1
                continue
            T = sess.set_step(serial, step, interp=True)
            _, mask = sess.rr.render(T, K, wh)
            rend_px = int(mask.sum())
            iou = iou_of(mask, gt)
            r2g = r2g_p90 = r2g_near = None
            if rend_px > 0:
                e_g = edge(gt)
                dt_g = dt_to(e_g)
                e_r = edge(mask)
                d = dt_g[e_r]
                if d.size:
                    r2g, r2g_p90 = float(d.mean()), float(np.percentile(d, 90))
                    near = dt_to(gt)[e_r] <= NEAR_PX       # render-edge px within NEAR_PX of ANY GT px (occlusion-robust)
                    r2g_near = float(d[near].mean()) if near.any() else None
            else:
                cam["n_empty_render"] += 1
            cam["frames"].append(dict(step=step, status=status, used=status in USABLE, gt_px=gt_px, rend_px=rend_px, iou=r4(iou),
                                      r2g=r4(r2g, 2), r2g_p90=r4(r2g_p90, 2), r2g_near=r4(r2g_near, 2), g=r4(float(sess.gs[step]), 3)))
        # aggregates: strict GT set (ok/single/low_conf, the gate) and the extended set (+render_far_off/render_missing_robot)
        for suffix, allowed in (("", USABLE), ("_ext", USABLE_EXT)):
            fr = [f for f in cam["frames"] if f["status"] in allowed]
            ious = [f["iou"] for f in fr if f["iou"] is not None]
            r2gs = [f["r2g"] for f in fr if f["r2g"] is not None]
            nears = [f["r2g_near"] for f in fr if f["r2g_near"] is not None]
            cam["n_usable" + suffix] = len(fr)
            cam["iou_median" + suffix] = r4(pct(ious, 50))
            cam["iou_p10" + suffix] = r4(pct(ious, 10))
            cam["iou_mean" + suffix] = r4(sum(ious) / len(ious)) if ious else None
            cam["r2g_median" + suffix] = r4(pct(r2gs, 50), 2)
            cam["r2g_p90" + suffix] = r4(pct(r2gs, 90), 2)
            cam["r2g_mean" + suffix] = r4(sum(r2gs) / len(r2gs), 2) if r2gs else None
            cam["r2g_near_median" + suffix] = r4(pct(nears, 50), 2)
        cam["res"] = f"{wh[0]}x{wh[1]}"
        rec["cams"][serial] = cam
    rec["elapsed_s"] = round(time.time() - t0, 1)
    return rec


def _score_task(uuid):
    try:
        return score_one(uuid)
    except Exception as e:  # noqa: BLE001
        import traceback
        return dict(uuid=uuid, status="error", error=repr(e), traceback=traceback.format_exc(),
                    scored_at=time.strftime("%Y-%m-%d %H:%M:%S"), calib_md5=md5_file(v2_path(uuid)) if v2_path(uuid).exists() else None)


def resolve_uuids(a):
    if a.uuids_file:
        us = [l.split("\t")[0].strip() for l in open(a.uuids_file) if l.strip() and not l.startswith("#")]
    elif a.uuid:
        us = list(a.uuid)
    else:
        us = [r["uuid"] for r in active_rows(load_working())]
    if a.nchunks and a.nchunks > 1:
        us = [u for i, u in enumerate(us) if i % a.nchunks == a.chunk]
    return us


def cmd_score(a):
    us = resolve_uuids(a)
    todo, skipped, pending = [], 0, 0
    for u in us:
        if not v2_path(u).exists():
            pending += 1
            continue
        if not a.force and score_fresh(u):
            skipped += 1
            continue
        todo.append(u)
    log(f"score: {len(us)} requested, {pending} pending (no v2), {skipped} fresh, {len(todo)} to score, workers {a.workers}")
    SCORES.mkdir(parents=True, exist_ok=True)
    OUT_QA.mkdir(parents=True, exist_ok=True)
    if not todo:
        return
    t0 = time.time()
    results = []
    if a.workers <= 1:
        _worker_init()
        for u in todo:
            results.append(_score_task(u))
            _report_score(results[-1])
    else:
        import multiprocessing as mp
        from concurrent.futures import ProcessPoolExecutor
        ctx = mp.get_context("spawn")
        with ProcessPoolExecutor(max_workers=a.workers, mp_context=ctx, initializer=_worker_init) as ex:
            for rec in ex.map(_score_task, todo):
                results.append(rec)
                _report_score(rec)
    for rec in results:
        atomic_json(SCORES / f"{rec['uuid']}.json", rec)
    n_err = sum(r["status"] == "error" for r in results)
    log(f"score: wrote {len(results)} score files ({n_err} errors) in {time.time() - t0:.0f} s -> {SCORES}")


def _report_score(rec):
    if rec["status"] != "scored":
        log(f"  {rec['uuid']}: {rec['status']} {rec.get('error', '')}")
        return
    parts = []
    for s, c in rec["cams"].items():
        parts.append(f"{s}: n={c['n_usable']} iou_med={c.get('iou_median')} r2g_med={c.get('r2g_median')} {c.get('refine_status')}")
    log(f"  {rec['uuid']}: sweep={rec.get('time_quality', {}).get('sweep_class')} " + " | ".join(parts) + f" ({rec.get('elapsed_s')} s)")


# ----------------------------------------------------------------------------- decide

def evaluate(uuid, thr, fail_errors=False):
    """-> (decision 'pass'|'fail'|'pending', reasons list, detail dict).  thr: iou_min, r2g_max, min_frames,
    r2g_metric ('r2g' | 'r2g_near'), gt_set ('strict' | 'ext')."""
    sfx = "_ext" if thr.get("gt_set") == "ext" else ""
    r2g_key = ("r2g_near_median" if thr.get("r2g_metric") == "r2g_near" else "r2g_median") + sfx
    det = dict(uuid=uuid, pipeline_status="", n_ext_cams=0, sweep_class=None, dt_ms=None, cams=[])
    st, reason = pipeline_status(uuid)
    det["pipeline_status"] = st if st != "none" else ("done_v2" if (ROOT / "out" / uuid / ".done_v2").exists() else "none")
    if is_no_mp4(uuid):
        return "fail", ["no_mp4"], det
    if not v2_path(uuid).exists():
        r = ["no_calib_v2"] + ([f"pipeline:{st}:{reason}"] if st in ("failed", "waiting_gt") else [])
        return "pending", r, det
    sc = load_score(uuid)
    if sc is None:
        return "pending", ["unscored"], det
    if not score_fresh(uuid, sc):
        return "pending", ["stale_score"], det
    if sc.get("status") == "error":
        return ("fail" if fail_errors else "pending"), [f"score_error:{str(sc.get('error', ''))[:80]}"], det
    if sc.get("status") == "no_gt":
        return "fail", ["no_gt_masks(unverifiable)"], det
    tq = sc.get("time_quality") or {}
    det["sweep_class"] = tq.get("sweep_class")
    det["dt_ms"] = sc.get("time_offset_ms")
    reasons = []
    cams = sc.get("cams") or {}
    ext = [(s, c) for s, c in cams.items() if c.get("role") == "ext"]
    det["n_ext_cams"] = len(ext)
    if len(ext) < 2:
        reasons.append(f"missing_camera(n_ext={len(ext)})")
    for s, c in ext:
        det["cams"].append(dict(serial=s, n_usable=c.get("n_usable" + sfx), iou_median=c.get("iou_median" + sfx), iou_p10=c.get("iou_p10" + sfx),
                                r2g_median=c.get("r2g_median" + sfx), r2g_p90=c.get("r2g_p90" + sfx), r2g_near_median=c.get("r2g_near_median" + sfx),
                                refine_status=c.get("refine_status"), ext_base_source=c.get("ext_base_source")))
        if c.get("error"):
            reasons.append(f"{s}:not_renderable")
            continue
        n = c.get("n_usable" + sfx) or 0
        if n < thr["min_frames"]:
            reasons.append(f"{s}:unverifiable(n_usable {n}<{thr['min_frames']})")
            continue
        iou = c.get("iou_median" + sfx)
        if iou is None or iou < thr["iou_min"]:
            reasons.append(f"{s}:iou_median {iou}<{thr['iou_min']}")
        r2g = c.get(r2g_key)
        if r2g is None or r2g > thr["r2g_max"]:
            reasons.append(f"{s}:{r2g_key} {r2g}>{thr['r2g_max']}")
        if c.get("refine_status") == "failed":
            reasons.append(f"{s}:refine_failed")
    if det["sweep_class"] == "edge":
        reasons.append("time_sweep_edge")
    return ("fail" if reasons else "pass"), reasons, det


def reason_key(x):
    """'22008760:iou_median 0.71<0.8' -> 'iou_median'; 'missing_camera(n_ext=1)' -> 'missing_camera'."""
    if ":" in x and x.split(":")[0].isdigit():
        x = x.split(":", 1)[1]
    return x.split("(")[0].split(" ")[0]


CAM_KEYS = ("serial", "n_usable", "iou_median", "iou_p10", "r2g_median", "r2g_p90", "r2g_near_median", "refine_status", "ext_base_source")


def decision_table(rows, decisions):
    """rows = active working rows; decisions = {uuid: decision}; -> list of dict per (task, outcome) + totals."""
    q, kind = quotas()
    tab = []
    tot = collections.Counter()
    for (t, o), quota in q.items():
        rr = [r for r in rows if r["task"] == t and r["outcome"] == o]
        c = collections.Counter(decisions.get(r["uuid"], "pending") for r in rr)
        line = dict(kind=kind[t], task=t, outcome=o, quota=quota, active=len(rr), passed=c["pass"], failed=c["fail"],
                    pending=c["pending"], short=quota - len(rr))
        tab.append(line)
        for k in ("quota", "active", "passed", "failed", "pending", "short"):
            tot[k] += line[k]
    return tab, dict(tot)


def fmt_table(tab, tot):
    hdr = ["kind", "task", "outcome", "quota", "active", "pass", "fail", "pending", "short"]
    lines = ["| " + " | ".join(hdr) + " |", "|" + "---|" * len(hdr)]
    for l in tab:
        lines.append(f"| {l['kind']} | {l['task'][:70]} | {l['outcome']} | {l['quota']} | {l['active']} | {l['passed']} | {l['failed']} | {l['pending']} | {l['short']} |")
    lines.append(f"| **total** |  |  | {tot['quota']} | {tot['active']} | {tot['passed']} | {tot['failed']} | {tot['pending']} | {tot['short']} |")
    return "\n".join(lines)


def cmd_decide(a):
    thr = dict(iou_min=a.iou_min, r2g_max=a.r2g_max, min_frames=a.min_frames, r2g_metric=a.r2g_metric, gt_set=a.gt_set)
    rows = load_working()
    act = active_rows(rows)
    decisions, out_rows, reason_counter = {}, [], collections.Counter()
    for r in act:
        d, reasons, det = evaluate(r["uuid"], thr, a.fail_errors)
        decisions[r["uuid"]] = d
        r["qa_status"] = d
        r["qa_reasons"] = "; ".join(reasons)
        for x in reasons:
            reason_counter[reason_key(x)] += 1
        o = dict(uuid=r["uuid"], kind=r["kind"], task=r["task"], outcome=r["outcome"], decision=d, reasons="; ".join(reasons),
                 round_added=r["round_added"], replaces=r["replaces"], pipeline_status=det["pipeline_status"],
                 n_ext_cams=det["n_ext_cams"], sweep_class=det["sweep_class"], dt_ms=det["dt_ms"])
        for i, c in enumerate(sorted(det["cams"], key=lambda c: c["serial"])[:2], 1):
            for k in CAM_KEYS:
                o[f"cam{i}_{k}"] = c.get(k)
        out_rows.append(o)
    cols = ["uuid", "kind", "task", "outcome", "decision", "reasons", "round_added", "replaces", "pipeline_status", "n_ext_cams",
            "sweep_class", "dt_ms"] + [f"cam{i}_{k}" for i in (1, 2) for k in CAM_KEYS]
    QA.mkdir(parents=True, exist_ok=True)
    OUT_QA.mkdir(parents=True, exist_ok=True)
    with open(DECISIONS, "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=cols, lineterminator="\n")
        w.writeheader()
        for o in out_rows:
            w.writerow({c: ("" if o.get(c) is None else o.get(c)) for c in cols})
    save_working(rows)
    tab, tot = decision_table(act, decisions)
    md = fmt_table(tab, tot)
    cnt = collections.Counter(decisions.values())
    summary = dict(written=time.strftime("%Y-%m-%d %H:%M:%S"), thresholds=thr, n_active=len(act), n_pass=cnt["pass"], n_fail=cnt["fail"],
                   n_pending=cnt["pending"], target_total=TARGET_TOTAL, quota_total=tot["quota"], short=tot["short"],
                   complete=(cnt["pass"] == tot["quota"] == TARGET_TOTAL and cnt["fail"] == 0 and cnt["pending"] == 0),
                   reason_counts=dict(reason_counter), table=tab,
                   failed=[o["uuid"] for o in out_rows if o["decision"] == "fail"],
                   pending=[o["uuid"] for o in out_rows if o["decision"] == "pending"])
    atomic_json(OUT_QA / "decide_summary.json", summary)
    with open(QA / "decision_table.md", "w") as f:
        f.write(f"# Selection QA decisions ({summary['written']})\n\nthresholds: iou_median >= {thr['iou_min']}, {thr['r2g_metric']} median <= {thr['r2g_max']} px, "
                f"n_usable >= {thr['min_frames']} per exterior camera (GT set {thr['gt_set']}), refine status != failed, time sweep_class != edge\n\n"
                f"active {len(act)}: pass {cnt['pass']} / fail {cnt['fail']} / pending {cnt['pending']} (target {TARGET_TOTAL})\n\n{md}\n\n"
                f"reason counts (fail + pending): {json.dumps(dict(reason_counter))}\n")
    print(md)
    print(f"active {len(act)}: pass {cnt['pass']} fail {cnt['fail']} pending {cnt['pending']} | quota total {tot['quota']} | "
          f"reason counts {dict(reason_counter)}")
    print(f"-> {DECISIONS}, {QA / 'decision_table.md'}, {OUT_QA / 'decide_summary.json'}")


# ----------------------------------------------------------------------------- replace

def load_pool():
    meta = [json.loads(l) for l in open(SUPERSET_META) if l.strip()]
    ext = json.load(open(SUPERSET_EXT))
    pool = collections.defaultdict(list)
    for m in meta:
        e = ext.get(m["uuid"], {})
        sers = sorted(k for k in e if k.isdigit())
        srcs = [e.get(f"{s}_source") for s in sers]
        ious = [e.get(f"{s}_quality_metric") for s in sers if e.get(f"{s}_metric_type") == "IoU"]
        cand = dict(uuid=m["uuid"], rel=m["rel"], len=int(m.get("len") or 0), task=m["task"], outcome=outcome_of_rel(m["rel"]),
                    n_cams=len(sers), both_gt=(len(sers) >= 2 and all(x == "GT" for x in srcs)),
                    min_iou=(min(ious) if len(ious) == len(sers) and sers else None), sources=srcs)
        pool[(m["task"], cand["outcome"])].append(cand)
    return pool


def tier_of(c, lo, hi):
    in_len = lo <= c["len"] <= hi
    good = c["both_gt"] and c["min_iou"] is not None and c["min_iou"] >= 0.85
    if good and in_len:
        return 0
    if c["both_gt"] and in_len:
        return 1
    if c["both_gt"]:
        return 2
    if in_len:
        return 3
    return 4


def pick(pool_list, excl, lo, hi, rng):
    cands = [c for c in pool_list if c["uuid"] not in excl and c["len"] >= LEN_FLOOR]
    if not cands:
        return None, None
    best = min(tier_of(c, lo, hi) for c in cands)
    tier = [c for c in cands if tier_of(c, lo, hi) == best]
    return rng.choice(tier), best


def next_round():
    ks = [int(p.stem.split("round")[-1]) for p in QA.glob("replacements_round*.tsv") if p.stem.split("round")[-1].isdigit()]
    return (max(ks) + 1) if ks else 1


def cmd_replace(a):
    rng = random.Random(a.seed)
    rows = load_working()
    act = active_rows(rows)
    k = a.round or next_round()
    used = set(l.strip() for l in open(USED) if l.strip()) if USED.exists() else set()
    excl = {r["uuid"] for r in rows} | used | NO_MP4_KNOWN
    pool = load_pool()
    failed = [r for r in act if r["qa_status"] == "fail" and not r.get("replaced_by")]
    extra_done = any(r.get("replaces") == EXTRA_TAG for r in rows)
    new_rows, picks, dry = [], [], []
    q, kind = quotas()
    for r in failed:
        key = (r["task"], r["outcome"])
        L = int(r["steps"] or 0)
        lo, hi = max(LEN_FLOOR, 0.5 * L), 2.0 * L if L else 10 ** 9
        c, tier = pick(pool.get(key, []), excl, lo, hi, rng)
        if c is None:
            dry.append(dict(task=r["task"], outcome=r["outcome"], dropped=r["uuid"], reason=r["qa_reasons"]))
            continue
        excl.add(c["uuid"])
        nr = dict(kind=r["kind"], task=r["task"], outcome=r["outcome"], uuid=c["uuid"], rel=c["rel"], steps=str(c["len"]), rendered="0",
                  round_added=str(k), replaces=r["uuid"], replaced_by="", qa_status="pending", qa_reasons="")
        new_rows.append(nr)
        picks.append(dict(dropped=r["uuid"], dropped_steps=L, dropped_reasons=r["qa_reasons"], task=r["task"], outcome=r["outcome"],
                          new=c["uuid"], new_rel=c["rel"], new_len=c["len"], tier=tier, both_gt=c["both_gt"], min_iou=r4(c["min_iou"], 3),
                          sources=c["sources"], len_bucket=[int(lo), int(hi)]))
        r["replaced_by"] = c["uuid"]
    if not a.no_extra and not extra_done:
        t = [t for t in task_order() if t.startswith(EXTRA_TASK_PREFIX)]
        if t:
            t = t[0]
            lens = sorted(int(r["steps"]) for r in act if r["task"] == t and r["outcome"] == "success" and r["steps"])
            L = lens[len(lens) // 2] if lens else 200
            lo, hi = max(LEN_FLOOR, 0.5 * L), 2.0 * L
            c, tier = pick(pool.get((t, "success"), []), excl, lo, hi, rng)
            if c is not None:
                excl.add(c["uuid"])
                nr = dict(kind=kind[t], task=t, outcome="success", uuid=c["uuid"], rel=c["rel"], steps=str(c["len"]), rendered="0",
                          round_added=str(k), replaces=EXTRA_TAG, replaced_by="", qa_status="pending", qa_reasons="")
                new_rows.append(nr)
                picks.append(dict(dropped=EXTRA_TAG, dropped_steps=L, dropped_reasons="+1 success (1000th episode)", task=t, outcome="success",
                                  new=c["uuid"], new_rel=c["rel"], new_len=c["len"], tier=tier, both_gt=c["both_gt"], min_iou=r4(c["min_iou"], 3),
                                  sources=c["sources"], len_bucket=[int(lo), int(hi)]))
    print(f"round {k}: {len(failed)} failed slots, {len(new_rows)} replacements picked, {len(dry)} slots with an empty pool"
          + (" (DRY RUN: nothing written)" if a.dry_run else ""))
    for p in picks:
        print(f"  {p['task'][:45]:45s} {p['outcome']:7s} {p['dropped']:42s} ({p['dropped_steps']} steps) -> {p['new']} "
              f"len {p['new_len']} tier {p['tier']} both_gt {p['both_gt']} min_iou {p['min_iou']} | {p['dropped_reasons'][:80]}")
    for d in dry:
        print(f"  DRY POOL: {d['task'][:45]} {d['outcome']} dropped {d['dropped']} ({d['reason'][:60]})")
    report = dict(round=k, seed=a.seed, written=time.strftime("%Y-%m-%d %H:%M:%S"), dry_run=a.dry_run, n_failed=len(failed),
                  n_replacements=len(new_rows), picks=picks, dry_slots=dry)
    OUT_QA.mkdir(parents=True, exist_ok=True)
    atomic_json(OUT_QA / (f"replace_round{k}{'_dryrun' if a.dry_run else ''}.json"), report)
    if a.dry_run:
        print(f"-> {OUT_QA / f'replace_round{k}_dryrun.json'}")
        return
    QA.mkdir(parents=True, exist_ok=True)
    for r in rows:
        if r.get("replaced_by"):
            r["qa_status"] = "replaced"
    rows.extend(new_rows)
    save_working(rows)
    with open(USED, "a") as f:
        for nr in new_rows:
            f.write(nr["uuid"] + "\n")
    rp = QA / f"replacements_round{k}.tsv"
    with open(rp, "w") as f:
        for nr in new_rows:
            f.write(f"{nr['uuid']}\t{nr['rel']}\n")
    print(f"-> {rp} ({len(new_rows)} lines), {WORKING} ({len(rows)} rows, {len(active_rows(rows))} active), {USED}")


# ----------------------------------------------------------------------------- pending / pool

def cmd_pending(a):
    rows = active_rows(load_working())
    out = []
    for r in rows:
        u = r["uuid"]
        if not v2_path(u).exists():
            continue
        sc = load_score(u)
        if sc is None or not score_fresh(u, sc) or (a.include_errors and sc.get("status") == "error"):
            out.append((u, r["rel"]))
    if a.out:
        Path(a.out).parent.mkdir(parents=True, exist_ok=True)
        with open(a.out, "w") as f:
            for u, rel in out:
                f.write(f"{u}\t{rel}\n")
    else:
        for u, rel in out:
            print(f"{u}\t{rel}")
    n_v2 = sum(v2_path(r["uuid"]).exists() for r in rows)
    print(f"# active {len(rows)}, with v2 {n_v2}, needing a score {len(out)}" + (f" -> {a.out}" if a.out else ""), file=sys.stderr)


def cmd_pool(a):
    rows = load_working(create=False)
    used = set(l.strip() for l in open(USED) if l.strip()) if USED.exists() else set()
    excl = {r["uuid"] for r in rows} | used | NO_MP4_KNOWN
    pool = load_pool()
    q, kind = quotas()
    lines = []
    for (t, o), quota in q.items():
        cs = [c for c in pool.get((t, o), []) if c["uuid"] not in excl and c["len"] >= LEN_FLOOR]
        both = [c for c in cs if c["both_gt"]]
        good = [c for c in both if c["min_iou"] is not None and c["min_iou"] >= 0.85]
        lines.append(dict(kind=kind[t], task=t, outcome=o, quota=quota, pool_total=len(pool.get((t, o), [])), available=len(cs),
                          both_gt=len(both), both_gt_iou85=len(good)))
    cols = ["kind", "task", "outcome", "quota", "pool_total", "available", "both_gt", "both_gt_iou85"]
    QA.mkdir(parents=True, exist_ok=True)
    with open(QA / "pool_counts.csv", "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=cols, lineterminator="\n")
        w.writeheader()
        w.writerows(lines)
    print("| " + " | ".join(cols) + " |\n|" + "---|" * len(cols))
    for l in lines:
        print(f"| {l['kind']} | {l['task'][:70]} | {l['outcome']} | {l['quota']} | {l['pool_total']} | {l['available']} | {l['both_gt']} | {l['both_gt_iou85']} |")
    print(f"-> {QA / 'pool_counts.csv'}  (available = not in the working selection / used_uuids / no-MP4 list and len >= {LEN_FLOOR})")


# ----------------------------------------------------------------------------- finalize

def cmd_finalize(a):
    rows = load_working(create=False)
    act = active_rows(rows)
    summ_p = OUT_QA / "decide_summary.json"
    summ = json.load(open(summ_p)) if summ_p.exists() else {}
    thr = summ.get("thresholds", DEFAULTS)
    q, kind = quotas()
    cnt = collections.Counter(r["qa_status"] for r in act)
    per = collections.Counter((r["task"], r["outcome"]) for r in act)
    problems = []
    if len(act) != TARGET_TOTAL:
        problems.append(f"active {len(act)} != {TARGET_TOTAL}")
    if cnt["pass"] != len(act):
        problems.append(f"not all pass: {dict(cnt)}")
    for key, quota in q.items():
        if per.get(key, 0) != quota:
            problems.append(f"{key[0][:40]}/{key[1]}: {per.get(key, 0)} != quota {quota}")
    if problems and not a.force:
        print("NOT FINAL: " + "; ".join(problems))
        sys.exit(1)
    order = task_order()
    act_sorted = sorted(act, key=lambda r: (order.index(r["task"]) if r["task"] in order else 99, 0 if r["outcome"] == "success" else 1,
                                             int(r["round_added"] or 0), r["uuid"]))
    for r in act_sorted:
        r["rendered"] = "1" if (ROOT / "out" / r["uuid"] / ".done_v2").exists() else "0"
    write_tsv(FINAL_TSV, act_sorted, SEL_COLS)
    # markdown
    dl = ""
    if TASK_MD.exists():
        txt = TASK_MD.read_text()
        i, j = txt.find("## How to download"), txt.find("## Episodes by task")
        if 0 <= i < j:
            dl = txt[i:j]
    n_off = sum(1 for r in act_sorted if r["kind"] == "official")
    n_cus = len(act_sorted) - n_off
    n_rep = sum(1 for r in act_sorted if r["replaces"] and r["replaces"] != EXTRA_TAG)
    md = [f"# DROID Episode Selection (final, QA-gated)", "",
          f"Total: **{len(act_sorted)} episodes** — {n_off} official-task episodes and {n_cus} lab-defined-task episodes; "
          f"{n_rep} of the original 999 were replaced after the exterior-camera alignment gate, plus 1 extra success for "
          f"'{EXTRA_TASK_PREFIX} ...' (the 1000th). All episodes are from the subset with improved dual-camera extrinsics "
          f"(`cam2base_extrinsic_superset.json` on HF `KarlP/droid`). Generated {time.strftime('%Y-%m-%d %H:%M:%S')} by "
          f"`scripts/select_qa.py finalize`" + (" **(--force: QA incomplete: " + "; ".join(problems) + ")**" if problems else "") + ".", ""]
    if dl:
        md.append(dl.rstrip() + "\n")
    md += ["## QA gate", "",
           f"Per episode, both exterior cameras were rendered with the per-episode v2 calibration (`data/<uuid>/calib_refined_v2.json`) at every "
           f"SAM3 GT-mask step (`out/gt/<uuid>/`, GT status ok/single/low_conf) and compared with the GT silhouette. PASS iff for BOTH exterior "
           f"cameras: n_usable >= {thr['min_frames']} (GT set {thr.get('gt_set', 'strict')}), IoU median >= {thr['iou_min']}, "
           f"{thr.get('r2g_metric', 'r2g')} median <= {thr['r2g_max']} px (render-edge -> nearest GT-edge mean distance at native resolution"
           f"{'; only render-edge px within 60 px of any GT px' if thr.get('r2g_metric') == 'r2g_near' else ''}), refine status != failed, "
           f"and the time-offset sweep class is not 'edge'. "
           f"Wrist cameras are not gated.", ""]
    tab, tot = decision_table(act_sorted, {r["uuid"]: r["qa_status"] for r in act_sorted})
    md.append(fmt_table(tab, tot))
    md += ["", "Per-episode metrics: `data/selection_qa/decisions.csv`; per-frame scores: `data/selection_qa/scores/<uuid>.json`.", ""]
    # QA metric summary
    ious, r2gs = [], []
    for r in act_sorted:
        sc = load_score(r["uuid"]) or {}
        for s, c in (sc.get("cams") or {}).items():
            if c.get("iou_median") is not None:
                ious.append(c["iou_median"])
            if c.get("r2g_median") is not None:
                r2gs.append(c["r2g_median"])
    if ious:
        md += [f"Exterior-camera distribution over the {len(ious)} gated cameras: IoU median p10/p50/p90 = "
               f"{pct(ious, 10):.3f}/{pct(ious, 50):.3f}/{pct(ious, 90):.3f}; r2g median p10/p50/p90 = "
               f"{pct(r2gs, 10):.2f}/{pct(r2gs, 50):.2f}/{pct(r2gs, 90):.2f} px.", ""]
    md += ["## Episodes by task", ""]
    for t in order:
        rr = [r for r in act_sorted if r["task"] == t]
        if not rr:
            continue
        ns = sum(r["outcome"] == "success" for r in rr)
        nf = len(rr) - ns
        md += [f"### {t}", "", f"*{kind[t]}* — {ns} success, {nf} failure", ""]
        for o in ("success", "failure"):
            sub = sorted([r for r in rr if r["outcome"] == o], key=lambda r: r["uuid"])
            if not sub:
                continue
            md += [f"**{o}**", ""]
            for r in sub:
                tag = ""
                if r["replaces"] == EXTRA_TAG:
                    tag = " *(extra 1000th)*"
                elif r["replaces"]:
                    tag = f" *(replaces `{r['replaces']}`, round {r['round_added']})*"
                md.append(f"- `{r['uuid']}` — `{r['rel']}` ({r['steps']} steps){tag}")
            md.append("")
    dropped = [r for r in rows if r["qa_status"] == "replaced"]
    if dropped:
        md += ["## Replaced episodes (failed the gate)", "", "| dropped uuid | task | outcome | reasons | replaced by |", "|---|---|---|---|---|"]
        for r in sorted(dropped, key=lambda r: r["uuid"]):
            md.append(f"| `{r['uuid']}` | {r['task'][:50]} | {r['outcome']} | {r['qa_reasons'][:120]} | `{r['replaced_by']}` |")
        md.append("")
    md += ["## Flat list (uuid, relative_path)", "", "```"]
    md += [f"{r['uuid']}\t{r['rel']}" for r in sorted(act_sorted, key=lambda r: r["uuid"])]
    md += ["```", ""]
    FINAL_MD.write_text("\n".join(md))
    print(f"FINAL: {len(act_sorted)} episodes -> {FINAL_TSV}, {FINAL_MD}" + (f"  (forced; problems: {'; '.join(problems)})" if problems else ""))


# ----------------------------------------------------------------------------- reselect

MANIFEST_FINAL = ROOT / "data/manifest_final.txt"
INDEX_FINAL = ROOT / "out/index_final.jsonl"
FINAL_COLS = SEL_COLS + ["qa_iou_min_cam", "qa_r2g_near_max_cam", "replaced_from", "backfill_note"]


def pick_info():
    """uuid -> dict(tier, min_iou, both_gt, for_slot) from every real replace / reselect round report."""
    out = {}
    for p in sorted(OUT_QA.glob("replace_round*.json")) + sorted(OUT_QA.glob("reselect_plan_round*.json")):
        if p.stem.endswith("_dryrun"):
            continue
        try:
            d = json.load(open(p))
        except (OSError, ValueError):
            continue
        for pk in (d.get("picks") or []) + (d.get("new_candidates") or []):
            out[pk["new"]] = dict(tier=pk.get("tier"), min_iou=pk.get("min_iou"), both_gt=pk.get("both_gt"),
                                  for_slot=tuple(pk["for_slot"]) if pk.get("for_slot") else None)
    return out


def qa_metrics(uuid, gt_set):
    """Per-episode exterior QA metrics from the score file (min-camera IoU median, max-camera r2g_near median)."""
    sfx = "_ext" if gt_set == "ext" else ""
    sc = load_score(uuid) or {}
    cams = [(s, c) for s, c in (sc.get("cams") or {}).items() if c.get("role") == "ext"]
    ious = [c.get("iou_median" + sfx) for _, c in cams]
    nears = [c.get("r2g_near_median" + sfx) for _, c in cams]
    ok_i = cams and all(v is not None for v in ious)
    ok_n = cams and all(v is not None for v in nears)
    return dict(iou_min_cam=min(ious) if ok_i else None, r2g_near_max_cam=max(nears) if ok_n else None, n_cams=len(cams),
                sweep_class=(sc.get("time_quality") or {}).get("sweep_class"), dt_ms=sc.get("time_offset_ms"),
                cams={s: dict(n_usable=c.get("n_usable" + sfx), iou_median=c.get("iou_median" + sfx), r2g_median=c.get("r2g_median" + sfx),
                              r2g_near_median=c.get("r2g_near_median" + sfx), refine_status=c.get("refine_status"),
                              ext_base_source=c.get("ext_base_source")) for s, c in cams})



def merge_concurrent(rows):
    """Append rows another process added to the working file since we loaded it (lost-update guard for concurrent runs)."""
    if not WORKING.exists():
        return rows
    have = {r["uuid"] for r in rows}
    extra = [r for r in load_working(create=False) if r["uuid"] not in have]
    if extra:
        print(f"  note: {len(extra)} row(s) added to {WORKING.name} by a concurrent run were kept: " + ", ".join(r["uuid"] for r in extra[:5]) + ("..." if len(extra) > 5 else ""))
    return rows + extra

def other_outcome(o):
    return "failure" if o == "success" else "success"


def next_reselect_round():
    ks = [int(p.stem.split("round")[-1]) for p in QA.glob("reselect_round*.tsv") if p.stem.split("round")[-1].isdigit()]
    return (max(ks) + 1) if ks else 1


def cmd_reselect(a):
    import math
    thr = dict(iou_min=a.iou_min, r2g_max=a.r2g_max, min_frames=a.min_frames, r2g_metric=a.r2g_metric, gt_set=a.gt_set)
    rng = random.Random(a.seed)
    if not WORKING.exists():
        print(f"{WORKING} missing (run decide/replace first)")
        sys.exit(1)
    rows = load_working(create=False)
    for i, r in enumerate(rows):
        r["_i"] = i
    OUT_QA.mkdir(parents=True, exist_ok=True)
    # 0. every episode with a v2 file needs a fresh score
    need = [(r["uuid"], r["rel"]) for r in rows if v2_path(r["uuid"]).exists() and not score_fresh(r["uuid"])]
    if need:
        p = OUT_QA / "reselect_to_score.txt"
        with open(p, "w") as f:
            for u, rel in need:
                f.write(f"{u}\t{rel}\n")
        print(f"NEEDS SCORING: {len(need)} episodes with a v2 file but no fresh score -> {p}\n"
              f"  sbatch -p c6-128-main -c 8 --mem=16G --wrap \"{sys.executable} {ROOT}/scripts/select_qa.py score --uuids {p} --workers 8\"")
        sys.exit(10)
    # 1. decisions for EVERY row (originals and replacements, whatever their current status)
    dec, reasons, qm = {}, {}, {}
    for r in rows:
        d, rs, _ = evaluate(r["uuid"], thr)
        dec[r["uuid"]], reasons[r["uuid"]] = d, rs
        qm[r["uuid"]] = qa_metrics(r["uuid"], thr["gt_set"])
        r["qa_status"] = d
        r["qa_reasons"] = "; ".join(rs)
    info = pick_info()
    q, kind = quotas()
    order = task_order()
    by_slot = collections.defaultdict(list)
    for r in rows:
        by_slot[(r["task"], r["outcome"])].append(r)

    def rank_key(r):
        u = r["uuid"]
        tier = (info.get(u) or {}).get("tier")
        return (0 if r["round_added"] == "0" else 1, tier if tier is not None else 9, -(qm[u]["iou_min_cam"] or 0.0), r["_i"])

    # 2. fill each slot: passing originals (tsv order) -> passing replacements (tier, then min-camera IoU)
    final, used, short = [], set(), collections.OrderedDict()
    for slot, quota in q.items():
        cands = sorted([r for r in by_slot[slot] if dec[r["uuid"]] == "pass"], key=rank_key)
        take = cands[:quota]
        for r in take:
            final.append(dict(row=r, slot=slot, role="original" if r["round_added"] == "0" else "replacement", from_slot=slot))
            used.add(r["uuid"])
        if len(take) < quota:
            short[slot] = quota - len(take)
    # 3. shortfall: (a) refill from the slot's own pool, (b) backfill from the same task's other outcome
    pool = load_pool()
    used_file = set(l.strip() for l in open(USED) if l.strip()) if USED.exists() else set()
    excl = {r["uuid"] for r in rows} | used_file | NO_MP4_KNOWN
    rounds_done = next_reselect_round() - 1
    k = rounds_done + 1
    can_run = rounds_done < a.max_new_rounds
    to_run, unfillable, backfill_log = [], collections.OrderedDict(), []

    def pending_rows(slot):
        return [r for r in by_slot[slot] if dec[r["uuid"]] == "pending" and not v2_path(r["uuid"]).exists() and not is_no_mp4(r["uuid"])]

    def len_bucket(slot):
        lens = sorted(int(r["steps"]) for r in by_slot[slot] if r["round_added"] == "0" and r["steps"])
        L = lens[len(lens) // 2] if lens else 150
        return max(LEN_FLOOR, 0.5 * L), 2.0 * L

    def sample_new(slot, n, for_slot, why):
        """n candidates of `slot` (pending-but-never-run rows first, then the superset pool), queued for the pipeline."""
        got = []
        for r in pending_rows(slot):
            if len(got) >= n:
                break
            if r["uuid"] in {g["new"] for g in to_run}:
                continue
            got.append(dict(new=r["uuid"], new_rel=r["rel"], new_len=int(r["steps"] or 0), own_slot=list(slot), for_slot=list(for_slot), kind=why,
                            source="pending_row", tier=(info.get(r["uuid"]) or {}).get("tier"), min_iou=(info.get(r["uuid"]) or {}).get("min_iou"),
                            both_gt=(info.get(r["uuid"]) or {}).get("both_gt"), existing_row=True))
        lo, hi = len_bucket(for_slot)
        while len(got) < n:
            c, tier = pick(pool.get(slot, []), excl, lo, hi, rng)
            if c is None:
                break
            excl.add(c["uuid"])
            got.append(dict(new=c["uuid"], new_rel=c["rel"], new_len=c["len"], own_slot=list(slot), for_slot=list(for_slot), kind=why, source="pool",
                            tier=tier, min_iou=r4(c["min_iou"], 3), both_gt=c["both_gt"], sources=c["sources"], existing_row=False))
        return got

    for slot, s in short.items():
        t, o = slot
        avail = [c for c in pool.get(slot, []) if c["uuid"] not in excl and c["len"] >= LEN_FLOOR] + pending_rows(slot)
        if avail and can_run:                                   # (a) exactly the shortfall from the slot's own pool
            got = sample_new(slot, s, slot, "refill")
            to_run += got
            if len(got) < s:
                unfillable[slot] = s - len(got)
            continue
        # (b) pool dry (or rounds exhausted): same task, other outcome, passing & unused: originals first, then replacements
        oth = (t, other_outcome(o))
        spare = sorted([r for r in by_slot[oth] if dec[r["uuid"]] == "pass" and r["uuid"] not in used], key=rank_key)
        for r in spare[:s]:
            final.append(dict(row=r, slot=slot, role="backfill", from_slot=oth))
            used.add(r["uuid"])
            backfill_log.append(dict(slot=list(slot), uuid=r["uuid"], from_slot=list(oth), source="original" if r["round_added"] == "0" else "replacement"))
        s -= min(s, len(spare))
        if s > 0 and can_run:
            n_new = int(math.ceil(s * a.margin))
            got = sample_new(oth, n_new, slot, "backfill")
            to_run += got
            if not got:
                unfillable[slot] = s
        elif s > 0:
            unfillable[slot] = s

    # ---- summary of the plan
    n_final = len(final)
    roles = collections.Counter(e["role"] for e in final)
    print(f"reselect (iou_min {thr['iou_min']} r2g_max {thr['r2g_max']} {thr['r2g_metric']} gt_set {thr['gt_set']} min_frames {thr['min_frames']}): "
          f"{len(rows)} rows -> decisions {dict(collections.Counter(dec.values()))}; originals {dict(collections.Counter(dec[r['uuid']] for r in rows if r['round_added'] == '0'))}")
    print(f"filled {n_final}/{TARGET_TOTAL}: {dict(roles)}; short slots {len(short)}: "
          + "; ".join(f"{t[:40]}/{o} -{s}" for (t, o), s in short.items()))
    for b in backfill_log:
        print(f"  backfill {b['slot'][0][:40]}/{b['slot'][1]} <- {b['uuid']} ({b['from_slot'][1]}, {b['source']})")
    for g in to_run:
        print(f"  to_run [{g['kind']} for {g['for_slot'][0][:40]}/{g['for_slot'][1]}] {g['new']} ({g['own_slot'][1]}, len {g['new_len']}, tier {g['tier']}, "
              f"min_iou {g['min_iou']}, {g['source']})")
    for (t, o), s in unfillable.items():
        print(f"  UNFILLABLE {t[:40]}/{o}: short {s} (pool dry, no spare other-outcome episodes" + ("" if can_run else ", rounds exhausted") + ")")
    plan = dict(written=time.strftime("%Y-%m-%d %H:%M:%S"), thresholds=thr, seed=a.seed, round=k, dry_run=a.dry_run, n_rows=len(rows),
                decisions=dict(collections.Counter(dec.values())), n_final=n_final, roles=dict(roles),
                short={f"{t} / {o}": s for (t, o), s in short.items()}, backfills=backfill_log, new_candidates=to_run,
                unfillable={f"{t} / {o}": s for (t, o), s in unfillable.items()})
    if a.dry_run:
        atomic_json(OUT_QA / f"reselect_plan_round{k}_dryrun.json", plan)
        print(f"DRY RUN -> {OUT_QA / f'reselect_plan_round{k}_dryrun.json'} (nothing else written)")
        return
    # ---- persist decisions in the working file
    if to_run:
        new_rows = []
        for g in to_run:
            if g["existing_row"]:
                continue
            t_own, o_own = g["own_slot"]
            new_rows.append(dict(kind=kind[t_own], task=t_own, outcome=o_own, uuid=g["new"], rel=g["new_rel"], steps=str(g["new_len"]), rendered="0",
                                 round_added=str(100 + k), replaces=f"reselect{k}:{g['kind']}:{g['for_slot'][0][:40]}/{g['for_slot'][1]}",
                                 replaced_by="", qa_status="pending", qa_reasons=""))
        rows.extend(new_rows)
        save_working(merge_concurrent(rows))
        QA.mkdir(parents=True, exist_ok=True)
        with open(USED, "a") as f:
            for nr in new_rows:
                f.write(nr["uuid"] + "\n")
        rp = QA / f"reselect_round{k}.tsv"
        with open(rp, "w") as f:
            for g in to_run:
                f.write(f"{g['new']}\t{g['new_rel']}\n")
        atomic_json(OUT_QA / f"reselect_plan_round{k}.json", plan)
        print(f"ROUND {k}: {len(to_run)} episodes need GT masks + pipeline + score -> {rp}\n"
              f"  MANIFEST_ONLY={rp} ROUND_TAG=reselect{k} sbatch scripts/replace_loop.sh   # then re-run reselect")
        sys.exit(10)
    save_working(merge_concurrent(rows))
    atomic_json(OUT_QA / f"reselect_plan_round{k}.json", plan)
    if n_final != TARGET_TOTAL and not a.write_final:
        print(f"NOT FINAL: {n_final} != {TARGET_TOTAL} (unfillable {plan['unfillable']}); --write-final to write anyway")
        sys.exit(2)
    write_finals(final, rows, dec, reasons, qm, thr, q, kind, order, backfill_log, unfillable, info)


def write_finals(final, rows, dec, reasons, qm, thr, q, kind, order, backfill_log, unfillable, info):
    o_rank = {"success": 0, "failure": 1}
    r_rank = {"original": 0, "replacement": 1, "backfill": 2}
    final.sort(key=lambda e: (order.index(e["slot"][0]) if e["slot"][0] in order else 99, o_rank.get(e["slot"][1], 2), r_rank[e["role"]],
                              -(qm[e["row"]["uuid"]]["iou_min_cam"] or 0)))
    in_final = {e["row"]["uuid"] for e in final}
    # dropped originals per slot -> replaced_from mapping (prefer the `replaces` link, then greedy in tsv order)
    dropped = collections.defaultdict(list)
    for r in rows:
        if r["round_added"] == "0" and r["uuid"] not in in_final:
            dropped[(r["task"], r["outcome"])].append(r)
    assigned = {}
    for e in final:
        if e["role"] == "original":
            continue
        rep = e["row"]["replaces"]
        cand = [d for d in dropped[e["slot"]] if d["uuid"] == rep and d["uuid"] not in assigned.values()]
        if cand:
            assigned[e["row"]["uuid"]] = cand[0]["uuid"]
    for e in final:
        if e["role"] == "original" or e["row"]["uuid"] in assigned:
            continue
        free = [d for d in dropped[e["slot"]] if d["uuid"] not in assigned.values()]
        if free:
            assigned[e["row"]["uuid"]] = free[0]["uuid"]
    replaced_by = collections.defaultdict(list)
    for new, old in assigned.items():
        replaced_by[old].append(new)
    # ---- tsv
    out_rows = []
    for e in final:
        r, u = e["row"], e["row"]["uuid"]
        m = qm[u]
        note = ""
        if e["role"] == "backfill":
            note = f"backfill: counted toward {e['slot'][1]} quota of this task (own outcome {r['outcome']}; {e['slot'][1]} pool dry)"
        elif r["replaces"] == EXTRA_TAG:
            note = "extra 1000th episode"
        out_rows.append(dict(kind=r["kind"], task=r["task"], outcome=r["outcome"], uuid=u, rel=r["rel"], steps=r["steps"],
                             rendered="1" if (ROOT / "out" / u / ".done_v2").exists() else "0",
                             qa_iou_min_cam=r4(m["iou_min_cam"]), qa_r2g_near_max_cam=r4(m["r2g_near_max_cam"], 2),
                             replaced_from=assigned.get(u, ""), backfill_note=note, _slot=e["slot"], _role=e["role"]))
    write_tsv(FINAL_TSV, out_rows, FINAL_COLS)
    with open(MANIFEST_FINAL, "w") as f:
        for o in out_rows:
            f.write(f"{o['uuid']}\t{o['rel']}\n")
    # ---- index_final.jsonl (read-only re-derivation from out/<uuid>/quality.json + metadata + scores)
    smeta = {}
    for l in open(SUPERSET_META):
        if l.strip():
            m = json.loads(l)
            smeta[m["uuid"]] = m
    with open(str(INDEX_FINAL) + ".tmp", "w") as f:
        for o in out_rows:
            u = o["uuid"]
            qj = {}
            p = ROOT / "out" / u / "quality.json"
            if p.exists():
                try:
                    qj = json.load(open(p))
                except (OSError, ValueError):
                    qj = {}
            out_dir = ROOT / "out" / u
            cams = list((qj.get("videos") or {}).keys()) or sorted(d.name for d in out_dir.iterdir() if d.is_dir() and d.name.isdigit()) if out_dir.exists() else []
            m = qm[u]
            rec = dict(uuid=u, rel=o["rel"], task=o["task"], outcome=o["outcome"], success=o["outcome"] == "success", slot_outcome=o["_slot"][1],
                       role=o["_role"], replaced_from=o["replaced_from"] or None, backfill_note=o["backfill_note"] or None,
                       kind=o["kind"], lab=u.split("+")[0], steps=int(o["steps"]) if o["steps"] else (smeta.get(u) or {}).get("len"),
                       arm=qj.get("arm"), gripper_type=qj.get("gripper_type"), cameras=cams, ext_serials=qj.get("ext_serials"),
                       wrist_serial=qj.get("wrist_serial"), out_dir=str(out_dir), done_v2=(out_dir / ".done_v2").exists(),
                       calib_v2=str(v2_path(u)) if v2_path(u).exists() else None, time_offset_ms=qj.get("time_offset_ms"),
                       time_sweep_class=(qj.get("time_quality") or {}).get("sweep_class"), ext_base_source=qj.get("ext_base_source"),
                       refine_quality={s: dict(status=(v or {}).get("status"), metric_after=(v or {}).get("metric_after"), metric_name=(v or {}).get("metric_name"))
                                       for s, v in (qj.get("quality") or {}).items()},
                       overall_status=qj.get("overall_status"), flags=qj.get("flags"), mount_params_md5=qj.get("mount_params_md5"),
                       qa=dict(decision=dec[u], thresholds=thr, iou_min_cam=m["iou_min_cam"], r2g_near_max_cam=m["r2g_near_max_cam"], cams=m["cams"],
                               score_file=str(SCORES / f"{u}.json")))
            f.write(json.dumps(rec, default=str) + "\n")
    os.replace(str(INDEX_FINAL) + ".tmp", INDEX_FINAL)
    # ---- markdown
    n_succ = sum(o["outcome"] == "success" for o in out_rows)
    roles = collections.Counter(o["_role"] for o in out_rows)
    dl = ""
    if TASK_MD.exists():
        txt = TASK_MD.read_text()
        i, j = txt.find("## How to download"), txt.find("## Episodes by task")
        if 0 <= i < j:
            dl = txt[i:j]
    ious = [o["qa_iou_min_cam"] for o in out_rows if o["qa_iou_min_cam"] is not None]
    nears = [o["qa_r2g_near_max_cam"] for o in out_rows if o["qa_r2g_near_max_cam"] is not None]
    md = ["# DROID Episode Selection (final, QA-gated)", "",
          f"Total: **{len(out_rows)} episodes** ({n_succ} success, {len(out_rows) - n_succ} failure by the episode's own outcome) — "
          f"{roles.get('original', 0)} originals of `data/task_selection.tsv` kept, {roles.get('replacement', 0)} replaced by same-task/same-outcome episodes "
          f"from the superset pool, {roles.get('backfill', 0)} backfilled from the same task's other outcome (pool dry). "
          f"All episodes are from the subset with improved dual-camera extrinsics (`cam2base_extrinsic_superset.json` on HF `KarlP/droid`). "
          f"Generated {time.strftime('%Y-%m-%d %H:%M:%S')} by `scripts/select_qa.py reselect`.", ""]
    if dl:
        md.append(dl.rstrip() + "\n")
    md += ["## QA gate", "",
           f"Both exterior cameras of every episode were rendered with the per-episode v2 calibration (`data/<uuid>/calib_refined_v2.json`) at every "
           f"SAM3 GT-mask step of `out/gt/<uuid>/` (GT statuses {'ok/single/low_conf/render_far_off/render_missing_robot' if thr['gt_set'] == 'ext' else 'ok/single/low_conf'}) "
           f"and compared with the GT silhouette at native resolution. PASS iff for BOTH exterior cameras: n_usable >= {thr['min_frames']}, "
           f"IoU median >= {thr['iou_min']}, {thr['r2g_metric']} median <= {thr['r2g_max']} px "
           f"({'render-edge -> nearest GT-edge mean distance over render-edge pixels within 60 px of any GT pixel (robust to robot parts the GT omits)' if thr['r2g_metric'] == 'r2g_near' else 'render-edge -> nearest GT-edge mean distance'}), "
           f"refine status != failed, time-offset sweep class != edge. Wrist cameras are not gated. Episodes without MP4 recordings on GCS fail.", ""]
    if ious:
        md += [f"Final selection, per-episode min-camera IoU median: p10/p50/p90 = {pct(ious, 10):.3f}/{pct(ious, 50):.3f}/{pct(ious, 90):.3f} (min {min(ious):.3f}); "
               f"max-camera r2g_near median: p10/p50/p90 = {pct(nears, 10):.2f}/{pct(nears, 50):.2f}/{pct(nears, 90):.2f} px (max {max(nears):.2f}).", ""]
    hdr = ["kind", "task", "slot", "quota", "final", "originals kept", "originals dropped", "replacements", "backfilled in", "lent to other outcome"]
    md += ["| " + " | ".join(hdr) + " |", "|" + "---|" * len(hdr)]
    tot = collections.Counter()
    for (t, o), quota in q.items():
        es = [x for x in out_rows if x["_slot"] == (t, o)]
        kept = sum(x["_role"] == "original" for x in es)
        reps = sum(x["_role"] == "replacement" for x in es)
        bf_in = sum(x["_role"] == "backfill" for x in es)
        lent = sum(1 for x in out_rows if x["_role"] == "backfill" and x["task"] == t and x["outcome"] == o)
        n_orig = sum(1 for r in rows if r["round_added"] == "0" and r["task"] == t and r["outcome"] == o)
        md.append(f"| {kind[t]} | {t[:70]} | {o} | {quota} | {len(es)} | {kept} | {n_orig - kept} | {reps} | {bf_in} | {lent} |")
        for key, v in (("quota", quota), ("final", len(es)), ("kept", kept), ("dropped", n_orig - kept), ("reps", reps), ("bf", bf_in), ("lent", lent)):
            tot[key] += v
    md.append(f"| **total** |  |  | {tot['quota']} | {tot['final']} | {tot['kept']} | {tot['dropped']} | {tot['reps']} | {tot['bf']} | {tot['lent']} |")
    if unfillable:
        md += ["", "**Unfilled slots:** " + "; ".join(f"{t} / {o}: short {s}" for (t, o), s in unfillable.items())]
    md += ["", "Per-episode metrics: `data/task_selection_final.tsv` (qa_iou_min_cam, qa_r2g_near_max_cam), `out/index_final.jsonl`, "
           "`data/selection_qa/scores/<uuid>.json` (per frame).", "", "## Episodes by task", ""]
    for t in order:
        es = [x for x in out_rows if x["_slot"][0] == t]
        if not es:
            continue
        ns = sum(x["_slot"][1] == "success" for x in es)
        md += [f"### {t}", "", f"*{kind[t]}* — {ns} success, {len(es) - ns} failure (quota slots; an episode's own outcome is shown when it differs)", ""]
        for o in ("success", "failure"):
            sub = sorted([x for x in es if x["_slot"][1] == o], key=lambda x: x["uuid"])
            if not sub:
                continue
            md += [f"**{o}**", ""]
            for x in sub:
                tag = ""
                if x["_role"] == "replacement":
                    tag = f" *(replacement" + (f" for `{x['replaced_from']}`" if x["replaced_from"] else ", extra 1000th") + ")*"
                elif x["_role"] == "backfill":
                    tag = f" *(backfill from {x['outcome']}" + (f", for `{x['replaced_from']}`" if x["replaced_from"] else "") + ")*"
                md.append(f"- `{x['uuid']}` — `{x['rel']}` ({x['steps']} steps; IoU {x['qa_iou_min_cam']}, r2g_near {x['qa_r2g_near_max_cam']} px){tag}")
            md.append("")
    drop_rows = [r for r in rows if r["round_added"] == "0" and r["uuid"] not in in_final]
    if drop_rows:
        md += ["## Replaced original episodes (failed the gate)", "", "| dropped uuid | task | outcome | reasons | replaced by |", "|---|---|---|---|---|"]
        for r in sorted(drop_rows, key=lambda r: (order.index(r["task"]) if r["task"] in order else 99, r["outcome"], r["uuid"])):
            md.append(f"| `{r['uuid']}` | {r['task'][:50]} | {r['outcome']} | {'; '.join(reasons[r['uuid']])[:140]} | "
                      + ", ".join(f"`{x}`" for x in replaced_by.get(r["uuid"], [])) + " |")
        md.append("")
    md += ["## Flat list (uuid, relative_path)", "", "```"]
    md += [f"{x['uuid']}\t{x['rel']}" for x in sorted(out_rows, key=lambda x: x["uuid"])]
    md += ["```", ""]
    FINAL_MD.write_text("\n".join(md))
    # ---- report
    per_task = []
    for (t, o), quota in q.items():
        es = [x for x in out_rows if x["_slot"] == (t, o)]
        per_task.append(dict(task=t, slot=o, quota=quota, final=len(es), originals_kept=sum(x["_role"] == "original" for x in es),
                             replacements=sum(x["_role"] == "replacement" for x in es), backfilled_in=sum(x["_role"] == "backfill" for x in es),
                             own_outcome_counts=dict(collections.Counter(x["outcome"] for x in es))))
    report = dict(written=time.strftime("%Y-%m-%d %H:%M:%S"), thresholds=thr, n_final=len(out_rows), n_success=n_succ, n_failure=len(out_rows) - n_succ,
                  roles=dict(roles), originals_dropped=len(drop_rows), unfillable={f"{t} / {o}": s for (t, o), s in unfillable.items()},
                  backfills=backfill_log, iou_min_cam_p10_p50_p90=[r4(pct(ious, 10)), r4(pct(ious, 50)), r4(pct(ious, 90))], iou_min_cam_min=r4(min(ious)) if ious else None,
                  r2g_near_max_cam_p10_p50_p90=[r4(pct(nears, 10), 2), r4(pct(nears, 50), 2), r4(pct(nears, 90), 2)], r2g_near_max_cam_max=r4(max(nears), 2) if nears else None,
                  per_task=per_task, files=dict(tsv=str(FINAL_TSV), md=str(FINAL_MD), manifest=str(MANIFEST_FINAL), index=str(INDEX_FINAL)))
    atomic_json(OUT_QA / "reselect_report.json", report)
    print(f"FINAL {len(out_rows)} episodes ({n_succ} success / {len(out_rows) - n_succ} failure): {dict(roles)}; originals dropped {len(drop_rows)}; "
          f"IoU_min_cam p10/p50/p90 {report['iou_min_cam_p10_p50_p90']} min {report['iou_min_cam_min']}; r2g_near_max p10/p50/p90 "
          f"{report['r2g_near_max_cam_p10_p50_p90']} max {report['r2g_near_max_cam_max']}")
    print(f"-> {FINAL_TSV}\n-> {FINAL_MD}\n-> {MANIFEST_FINAL}\n-> {INDEX_FINAL}\n-> {OUT_QA / 'reselect_report.json'}")


# ----------------------------------------------------------------------------- main

def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = ap.add_subparsers(dest="cmd", required=True)
    s = sub.add_parser("score")
    s.add_argument("uuid", nargs="*")
    s.add_argument("--uuids", dest="uuids_file", default=None, help="file with uuid (first tab column) per line")
    s.add_argument("--all-selected", action="store_true", help="(default) all active rows of the working selection")
    s.add_argument("--chunk", type=int, default=int(os.environ.get("SLURM_ARRAY_TASK_ID", 0)))
    s.add_argument("--nchunks", type=int, default=1)
    s.add_argument("--workers", type=int, default=int(os.environ.get("SLURM_CPUS_PER_TASK", 1)))
    s.add_argument("--force", action="store_true")
    s.set_defaults(fn=cmd_score)
    d = sub.add_parser("decide")
    d.add_argument("--iou-min", type=float, default=DEFAULTS["iou_min"])
    d.add_argument("--r2g-max", type=float, default=DEFAULTS["r2g_max"])
    d.add_argument("--min-frames", type=int, default=DEFAULTS["min_frames"])
    d.add_argument("--fail-errors", action="store_true", help="treat scoring errors as FAIL instead of pending")
    d.add_argument("--r2g-metric", choices=("r2g", "r2g_near"), default="r2g",
                   help="r2g = mean render-edge -> GT-edge distance (default); r2g_near = only render-edge px within 60 px of any GT px "
                        "(robust to robot parts the GT omits, e.g. the base behind a table)")
    d.add_argument("--gt-set", choices=("strict", "ext"), default="strict",
                   help="strict = GT statuses ok/single/low_conf (default); ext = + render_far_off/render_missing_robot")
    d.set_defaults(fn=cmd_decide)
    r = sub.add_parser("replace")
    r.add_argument("--seed", type=int, default=0)
    r.add_argument("--round", type=int, default=None)
    r.add_argument("--dry-run", action="store_true")
    r.add_argument("--no-extra", action="store_true", help="do not add the +1 success for the 1000th episode")
    r.set_defaults(fn=cmd_replace)
    p = sub.add_parser("pending")
    p.add_argument("--out", default=None)
    p.add_argument("--include-errors", action="store_true")
    p.set_defaults(fn=cmd_pending)
    sub.add_parser("pool").set_defaults(fn=cmd_pool)
    rs = sub.add_parser("reselect", help="re-decide every scored episode, fill the quotas (originals -> replacements -> refill/backfill), write finals")
    rs.add_argument("--iou-min", type=float, default=0.75)
    rs.add_argument("--r2g-max", type=float, default=8.0)
    rs.add_argument("--min-frames", type=int, default=6)
    rs.add_argument("--r2g-metric", choices=("r2g", "r2g_near"), default="r2g_near")
    rs.add_argument("--gt-set", choices=("strict", "ext"), default="ext")
    rs.add_argument("--seed", type=int, default=0)
    rs.add_argument("--max-new-rounds", type=int, default=2, help="pipeline rounds for refills/backfills (reselect_round<k>.tsv)")
    rs.add_argument("--margin", type=float, default=1.5, help="oversampling factor for other-outcome backfill candidates that still need the pipeline")
    rs.add_argument("--dry-run", action="store_true")
    rs.add_argument("--write-final", action="store_true", help="write the final files even when fewer than 1000 slots could be filled")
    rs.set_defaults(fn=cmd_reselect)
    f = sub.add_parser("finalize")
    f.add_argument("--force", action="store_true")
    f.set_defaults(fn=cmd_finalize)
    a = ap.parse_args()
    a.fn(a)


if __name__ == "__main__":
    main()