stegobench-cli 1.0.0

The stegobench command
Documentation
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
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
// Author:  Daniel Iwugo
// Comment: Christ is King
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2026 Daniel Iwugo

//! `stegobench score`: the headline verb, joined up.
//!
//! Three pieces that already existed do the work. The corpus reader streams
//! samples off disk, the runner asks the detector about each one and records
//! the answer as it goes, and the metrics crate turns scores and labels into
//! numbers. This module is the seam between them, and the place the result
//! document is assembled.
//!
//! WHERE THE MEMORY GOES, STATED RATHER THAN IMPLIED
//!
//! The scoring pass holds one item at a time, so a corpus of any size costs
//! the same. The metrics pass does not and cannot: a ROC AUC is defined over
//! the whole set and needs every score before it can rank them. That is one
//! f64 and one bool per item, so a Core tier is a few megabytes, and it is
//! bounded by the corpus rather than by anything this code chooses.
//!
//! It is worth naming because it is the one place a bigger corpus eventually
//! bites, and a reader of this file should meet that fact here rather than
//! discover it at ten times the scale.
//!
//! WHY THE WORK IS IN TWO HALVES
//!
//! [`prepare`] establishes what the corpus IS: its digest, whether it is the
//! corpus a registry entry named, whether every image is the file its record
//! describes, whether a cover and its stego twin land on the same side of the
//! split, and what each item's label is. None of those answers depends on
//! which detector is asked, and on a Core tier they cost tens of minutes and a
//! full read of every byte.
//!
//! [`score_one`] then asks one detector, and can be called again for the next
//! one against the same [`Prepared`]. Scoring seven detectors therefore pays
//! for the corpus once rather than seven times, which is the difference
//! between an afternoon and a day and a half, and the reason a baseline over
//! the whole registry is a command somebody will actually run.

use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, HashMap};
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use stegobench_core::corpus::CorpusEntry;
use stegobench_core::header::{self, Shape};
use stegobench_core::registry::{Entry, Kind};
use stegobench_core::result::{
    AdapterRef, Arm, ArmMetrics, Configuration, CorpusRef, CorpusSource, Declarations, Determinism,
    Domain, Host, Isolation, Metrics, Pairing, PinnedBy, PluginRef, Provenance, Rate, RateUnit,
    Result1, SelfTest, SplitDiscipline, Subject, SubjectKind, RESULT_SCHEMA_ID,
};
use stegobench_core::samples::{Role, Sample, Samples};
use stegobench_plugin::runner::{self, JsonLines, Tally};
use stegobench_plugin::{Record, WorkItem};

/// What the caller asked for, gathered so the signature stays readable.
pub struct Request<'a> {
    pub corpus: &'a Path,
    pub records: PathBuf,
    pub timeout: Duration,
    /// How many images to score at once. 1 is one at a time.
    pub jobs: usize,
    /// Keep what the detector printed for every image, not only the ones it
    /// could not be read on.
    pub keep_raw: bool,
    /// The seed the caller declared their plugin was run with.
    pub seed: Option<u64>,
    /// Where the self-test fixtures live.
    pub fixtures: Option<&'a Path>,
    pub limit: Option<u64>,
    /// The registry's entry for this corpus, where the caller named one.
    ///
    /// Carries the name, the tier and, if anybody has computed it, the digest
    /// this run is checked against. See [`Configuration`] for why the check
    /// rather than the name is what earns `named`.
    pub registered: Option<&'a CorpusEntry>,
    /// The corpus the detector was trained on, as the caller declared it.
    ///
    /// Nothing here can establish this from the outside, which is exactly why
    /// it is a declaration: a trained detector scored on what it trained on
    /// produces a number that measures memory rather than detection, and a
    /// reader has no way to tell from the document unless the document says.
    pub trained_on: Option<&'a str>,
    /// Which half of the split to score, where the caller asked for one.
    pub split: Option<&'a str>,
    /// The trees a relative `invoke.adapter` is resolved against.
    ///
    /// Empty for a caller with no registry directory to name, which then falls
    /// back to the directory the command was typed in. See
    /// [`stegobench_plugin::adapter`].
    pub adapter_roots: &'a [PathBuf],
}

/// Why a run could not produce a result.
#[derive(Debug, thiserror::Error)]
pub enum ScoreError {
    #[error("{0}")]
    Corpus(#[from] stegobench_core::samples::SampleError),
    #[error("{0}")]
    Run(#[from] runner::RunError),
    #[error("could not open the records file at {path}: {source}")]
    Records {
        path: String,
        #[source]
        source: std::io::Error,
    },
    #[error(
        "{name} is registered as an embedder, and an embedder cannot be asked \
         to tell two images apart. Pick a detector: `stegobench list detectors`"
    )]
    NotADetector { name: String },
    #[error(
        "the corpus at {path} puts {count} stego image(s) on a different side \
         of the train and test split from the cover they were made from, for \
         example: {examples}. A cover and its stego twin on opposite sides \
         inflates every number computed from this corpus, and the inflation is \
         invisible in the output, so this refuses rather than reporting a \
         confident wrong answer"
    )]
    SplitLeaks {
        path: String,
        count: usize,
        examples: String,
    },
    #[error(
        "the directory at {path} is not {id}. That corpus is registered with \
         the digest {want}, and these records come to {got}. Whatever the \
         directory is called, it is not the corpus you named, and a number \
         measured here would be filed under a name it does not belong to"
    )]
    NotThatCorpus {
        path: String,
        id: String,
        want: String,
        got: String,
    },
    #[error(
        "{asked:?} is not a side of a split. The two halves are `train` and \
         `test`"
    )]
    UnknownSplit { asked: String },
    #[error(
        "the corpus at {path} carries no train and test split, so there is \
         no half to score. Its records state no `split`, and inventing one \
         here would put a cover and its stego twin on opposite sides, which \
         is the exact fault the split exists to prevent"
    )]
    NoSplitLabels { path: String },
    #[error(
        "the corpus at {path} holds {clean} clean and {stego} stego image(s), \
         and a measurement needs both. A detector scored on one side of the \
         question has not been measured, it has been asked a leading one"
    )]
    OneSided {
        path: String,
        clean: u64,
        stego: u64,
    },
    /// The corpus had both sides and the detector answered about neither.
    ///
    /// Kept apart from `OneSided` because that message blames the corpus, and
    /// an adversarial researcher whose batched plugin printed nothing at all was
    /// told his ten-clean, ten-stego corpus held "0 clean and 0 stego". He was
    /// right that the refusal was correct to fire and said he would have spent
    /// twenty minutes auditing the corpus before suspecting his own adapter. The
    /// refusal is as loud as before; it now points at the tool.
    #[error(
        "{name} produced no usable answer for any of the {asked} image(s) in the \
         corpus at {path}, which holds {clean} clean and {stego} stego, so there \
         is nothing to compute a metric over. The corpus is not the problem here: \
         every item was offered to the tool and every answer came back unusable. \
         {why}\n\nCheck what the tool actually printed: `--keep-raw` writes its \
         own output beside the records, and `stegobench doctor` runs the entry's \
         self-test against the fixtures."
    )]
    NothingAnswered {
        name: String,
        path: String,
        asked: u64,
        clean: u64,
        stego: u64,
        why: String,
    },
    #[error(
        "{name} answered about {answered} image(s), and no ROC AUC can be \
         computed from those answers, so this run has no headline number. \
         {why}\n\nA result-v1 document has to carry an AUC, and the value \
         that would have been written is 0.5, which is exactly the figure \
         that means a detector carries no information at all. Publishing it \
         would be indistinguishable from publishing a measurement that came \
         out at chance, so the run is refused instead and nothing is written."
    )]
    NoAuc {
        name: String,
        answered: usize,
        why: String,
    },
    #[error(
        "{id} is not the image its own record describes. The record states \
         {want} and the file on disk is {got}. A run cannot be named over a \
         corpus whose images and records disagree: the digest that names the \
         corpus is taken over what the records SAY, so swapping the images \
         underneath them leaves it unchanged"
    )]
    ImageChanged {
        id: String,
        want: String,
        got: String,
    },
}

impl ScoreError {
    /// Which documented exit code this is.
    ///
    /// Every one of these used to leave the process with 4, plugin failure,
    /// including four cases where no plugin was involved and one where nothing
    /// had run yet. The codes are a contract a script and an agent act on, and
    /// the distinction that matters to both is whether retrying unchanged
    /// could work: a refusal will refuse again, a breakage might not.
    pub fn exit_code(&self) -> i32 {
        use stegobench_core::exit;
        match self {
            // The caller asked for something incoherent. Fix the command.
            ScoreError::NotADetector { .. } => exit::USAGE,
            // The command named a half that does not exist. Fix the command.
            ScoreError::UnknownSplit { .. } => exit::USAGE,
            // The corpus cannot answer the question asked of it. Not the
            // command's fault and not a breakage: a pre-flight refusal.
            ScoreError::NoSplitLabels { .. } => exit::PREFLIGHT_REFUSED,
            // A claim about the bytes was checked and did not hold.
            ScoreError::NotThatCorpus { .. } | ScoreError::ImageChanged { .. } => {
                exit::VERIFY_MISMATCH
            }
            // The corpus is unfit for a measurement, and will be as unfit the
            // second time. Refusals, not breakages.
            ScoreError::SplitLeaks { .. } | ScoreError::OneSided { .. } => exit::PREFLIGHT_REFUSED,
            // The corpus was fit to measure and the tool was not fit to
            // answer, which is the same shape as NoAuc and gets its code.
            ScoreError::NothingAnswered { .. } => exit::PLUGIN_FAILED,
            // Something broke: a tool, a disk, a file that is not what it
            // claimed to be. A run whose answers cannot be turned into a
            // metric belongs here rather than with the refusals: the corpus
            // was fit to measure and what came back was not fit to rank, so
            // retrying against a fixed tool genuinely could work.
            ScoreError::Run(_) | ScoreError::NoAuc { .. } => exit::PLUGIN_FAILED,
            ScoreError::Corpus(_) | ScoreError::Records { .. } => exit::FAILURE,
        }
    }

    /// A stable word for why this failed, for a caller branching in a script.
    ///
    /// The exit code says how bad it was and the message says what happened
    /// in English, and neither is something to branch on: there are more
    /// failures than codes, and the prose is written to be read by a person
    /// and will be reworded when a person is confused by it. `metrics`
    /// already publishes one of these and `score` did not, so automating
    /// against `score` meant matching English that nothing promised to keep.
    pub fn reason(&self) -> &'static str {
        match self {
            ScoreError::Corpus(_) => "corpus-unreadable",
            ScoreError::Run(_) => "plugin-failed",
            ScoreError::Records { .. } => "records-unreadable",
            ScoreError::NotADetector { .. } => "not-a-detector",
            ScoreError::UnknownSplit { .. } => "unknown-split",
            ScoreError::NoSplitLabels { .. } => "no-split-labels",
            ScoreError::NotThatCorpus { .. } => "not-that-corpus",
            ScoreError::ImageChanged { .. } => "image-changed",
            ScoreError::SplitLeaks { .. } => "split-leaks",
            ScoreError::OneSided { .. } => "one-sided",
            ScoreError::NothingAnswered { .. } => "nothing-answered",
            ScoreError::NoAuc { .. } => "no-auc",
        }
    }
}

/// Everything about the corpus that does not depend on which detector is asked.
///
/// Built once by [`prepare`] and handed to [`score_one`] for each detector in
/// turn. A field here is a property of the bytes on disk; anything that varies
/// with the subject stays out.
pub struct Prepared {
    corpus: PathBuf,
    limit: Option<u64>,
    /// The registry entry's own name and tier for the corpus, copied out so a
    /// `Prepared` does not borrow the registry for its whole life.
    /// The registry entry this corpus resolved to: its id, its display
    /// name and its tier.
    ///
    /// The id is carried as well as the name because the two differ and
    /// the contamination check compares against them. `stegobench-starter`
    /// is what `list corpora` prints and what a careful person passes to
    /// `--trained-on`; `Stegobench starter corpus` is what a reader sees.
    /// Comparing only the second exonerates exactly the person who used
    /// the right name.
    registered: Option<(String, String, Option<String>)>,
    checks: Checks,
    /// Whether the directory was proved to be the corpus a registry entry
    /// named, images included.
    claim_holds: bool,
    /// One label per scorable item, in corpus order, truncated by `limit`.
    ///
    /// Held once for the whole command rather than re-walked per detector. It
    /// is one bool per item, so a Core tier is 344 KB, which is an order of
    /// magnitude below the score vector the metrics pass already needs.
    labels: Vec<bool>,
    /// The corpus the detector was trained on, as the caller declared it.
    ///
    /// Copied onto the `Prepared` because every result written from it carries
    /// the same declaration: it is a property of the detector and the command,
    /// not of one pass over the corpus.
    trained_on: Option<String>,
    /// Whether the detector declared it was trained on this very corpus.
    contaminated: bool,
    /// Whether the contamination declaration could be checked at all, so the
    /// document can say "could not tell" instead of "clean".
    contamination_check: stegobench_core::result::ContaminationCheck,
    /// How many items the corpus held, where `--limit` stopped the run short.
    ///
    /// `None` means the run covered all of it.
    of_items: Option<u64>,
    /// Which samples this run covers, in corpus order.
    ///
    /// All true unless `--split` narrowed it. One bool per sample, the same
    /// shape as `labels`, and `Feed` walks the same order so the two index
    /// the same items.
    keep: Vec<bool>,
    /// The half being scored, where one was asked for.
    pub side: Option<Side>,
    /// The distinct arm names this run covers, sorted, and an index into them
    /// per scored sample.
    ///
    /// Interned for the same reason [`Side`] is an enum rather than a string:
    /// a Core tier is 344,357 samples over 39 arms, and holding the name on
    /// every sample is tens of megabytes to answer a question with 39
    /// answers. `None` is a sample whose record names no arm, which every
    /// clean image is.
    arm_names: Vec<String>,
    arms: Vec<Option<u16>>,
    /// When the shared preparation began, and how long it took.
    ///
    /// Every result written from this `Prepared` reports `started_utc` as the
    /// moment preparation began and folds `preflight` into its own elapsed
    /// time. Both are true of each result: establishing what the corpus was is
    /// work that result rests on. What no result claims is the time spent on
    /// the OTHER detectors, because waiting for a different measurement is not
    /// part of making this one.
    started_utc: String,
    preflight: Duration,
}

impl Prepared {
    /// How many items each detector will be asked about.
    pub fn items(&self) -> u64 {
        self.labels.len() as u64
    }

    /// Seconds spent establishing what the corpus is, before any detector ran.
    pub fn preflight_seconds(&self) -> f64 {
        self.preflight.as_secs_f64()
    }
}

/// Run the detector over the corpus and build the result document.
///
/// The single-detector path, kept as one call. It is [`prepare`] followed by
/// [`score_one`], and a caller scoring several detectors uses those two
/// directly so the corpus is established once.
pub fn score<P>(
    entry: &Entry,
    request: &Request,
    mut progress: P,
) -> Result<(Result1, Tally), ScoreError>
where
    P: FnMut(&str),
{
    // Asked before the corpus is touched. An embedder cannot be scored however
    // good the corpus is, and finding that out after a Core-tier walk would be
    // finding it out far too late.
    refuse_embedder(entry)?;
    let prepared = prepare(
        request.corpus,
        request.registered,
        request.limit,
        request.trained_on,
        request.split,
        &mut progress,
    )?;
    score_one(
        entry,
        &prepared,
        &request.records,
        How {
            timeout: request.timeout,
            jobs: request.jobs,
            keep_raw: request.keep_raw,
            seed: request.seed,
            fixtures: request.fixtures,
            adapter_roots: request.adapter_roots,
        },
        &mut progress,
    )
}

fn refuse_embedder(entry: &Entry) -> Result<(), ScoreError> {
    if entry.kind == Kind::Embedder {
        return Err(ScoreError::NotADetector {
            name: entry.name.clone(),
        });
    }
    Ok(())
}

/// Establish what the corpus is, once, before any detector is asked anything.
///
/// Every refusal this can raise is a fact about the corpus rather than about a
/// tool, so raising them here means a seven-detector command refuses before it
/// spends an hour on the first one rather than after.
pub fn prepare<P>(
    corpus: &Path,
    registered: Option<&CorpusEntry>,
    limit: Option<u64>,
    trained_on: Option<&str>,
    split: Option<&str>,
    mut progress: P,
) -> Result<Prepared, ScoreError>
where
    P: FnMut(&str),
{
    // WHY NAMING A CORPUS IS NOT ENOUGH TO EARN `named`
    //
    // Started HERE, before the corpus is identified rather than after. The
    // pre-flight passes below read every record and, for a named run, hash
    // every image, which on a Core tier is tens of minutes. A reader takes
    // elapsed_seconds as how long the run took, and time spent establishing
    // what was being measured is part of how long it took.
    let started = Instant::now();
    let started_utc = now_utc();

    // `Configuration` is documented as set by the harness from what it
    // actually ran, never by the person running it, and that is the whole
    // value of the field: one somebody can set in their own favour is not
    // worth having. A `--corpus-id` flag that took the user's word would hand
    // them exactly that.
    //
    // So the flag states a claim and this checks it, against a digest an
    // INDEPENDENT registry entry declared in advance. Checked HERE, before a
    // single image is scored, because the answer does not depend on the run
    // and a Core tier is hours: discovering at the end that the directory was
    // never the corpus named is discovering it far too late.
    // Recorded on the document as well as warned about, because the warning
    // goes to whoever ran this and the document goes to whoever has to trust
    // the number.
    let mut contaminated = false;
    let mut contamination_check = stegobench_core::result::ContaminationCheck::NotDeclared;
    let claim_holds = match registered {
        None => false,
        Some(entry) => match entry
            .integrity
            .as_ref()
            .and_then(|i| i.records_sha256.as_deref())
        {
            None => {
                progress(&format!(
                    "{} is registered but its entry declares no records \
                     digest, so there is nothing to check this directory \
                     against and the run is marked custom",
                    entry.id
                ));
                false
            }
            Some(want) => {
                let got = corpus_digest(corpus)?;
                if got.as_deref() == Some(want) {
                    // The manifest is the one the registry named. Now check
                    // that the images are the ones the manifest describes,
                    // because the digest above would not notice if they were
                    // not. See `verify_bytes`.
                    progress(
                        "the corpus matches the digest its registry entry \
                         declares; checking the images against their own \
                         records before naming the run",
                    );
                    let checked = verify_bytes(corpus, &mut progress)?;
                    progress(&format!(
                        "{checked} image(s) are the files their records \
                         describe"
                    ));
                    true
                } else {
                    // Refused rather than downgraded. The user asserted
                    // something about these bytes that is not true of them,
                    // and filing the run quietly as custom would answer a
                    // different question from the one they asked.
                    return Err(ScoreError::NotThatCorpus {
                        path: corpus.display().to_string(),
                        id: entry.id.clone(),
                        want: want.to_string(),
                        got: got.unwrap_or_else(|| {
                            "nothing, because at least one record states no \
                             digest for its own image"
                                .into()
                        }),
                    });
                }
            }
        },
    };

    // Checked before a single image is scored, because a corpus that leaks a
    // cover across the boundary produces a confident wrong answer, and
    // producing it first and mentioning the problem afterwards is how a bad
    // number gets quoted. It used to run after the scoring pass, which was
    // defensible for one detector and indefensible for seven: a corpus this
    // refuses would have cost every one of them a full run first.
    let checks = check(corpus)?;
    if !checks.split_leaks.is_empty() {
        return Err(ScoreError::SplitLeaks {
            path: corpus.display().to_string(),
            count: checks.split_leaks.count,
            examples: checks.split_leaks.examples(),
        });
    }

    // A WHOLE CLASS BEING ONE FORMAT AND THE OTHER CLASS ANOTHER.
    //
    // No pair comparison reaches this. A steganalysis researcher looked at a
    // corpus directory for thirty seconds, before running anything, and said
    // that the clean class was PNG and the stego class JPEG, so any detector
    // that can tell the two apart scores 1.0 without doing steganalysis at all.
    // He was right and the tool said nothing, because the per-pair check can
    // only speak about pairs it can resolve and this corpus's clean halves were
    // not present. Said here, and recorded as `arm.clean_format` beside the
    // existing `arm.format`, which described the stego half only.
    if let (Some(clean), Some(stego)) = (
        checks.arm.clean_format.as_deref(),
        Some(checks.arm.format.as_str()),
    ) {
        if clean != stego && !stego.is_empty() {
            progress(&format!(
                "WARNING: every clean image here is {clean} and every stego image \
                 is {stego}. A detector that merely tells the two formats apart \
                 scores perfectly on this corpus without detecting anything, so a \
                 high number here is not evidence of steganalysis. The result \
                 records both formats"
            ));
        }
    }

    // A confounded corpus is reported rather than refused, which is the
    // opposite of what a split leak gets, and the difference is deliberate.
    // A leak makes a number wrong while looking right. A second variable
    // between the clean and stego halves is a real property of some arms, kept
    // on purpose to demonstrate what it does, so the run happens and the
    // document says what it measured.
    match checks.pairing {
        Pairing::Confounded => progress(&format!(
            "WARNING: {} stego image(s) differ from their cover in more than \
             the payload, for example: {}. This run measures that difference \
             as well as the payload, and the result says so",
            checks.pairing_breaks.count,
            checks.pairing_breaks.examples()
        )),
        // Two different situations reached this verdict and they need different
        // next steps. A corpus whose records name nothing cannot be checked at
        // all; a corpus whose records name a clean half that was not extracted
        // beside them is one directory away from being checkable, and saying
        // only "could not be checked" leaves the user to work that out from a
        // sidecar by hand, which is what one did.
        Pairing::Unverified if checks.unreadable > 0 => progress(&format!(
            "the pairing rule could not be checked: {} stego image(s) name a \
             clean half that is not in this corpus. Extract the clean arm they \
             refer to alongside them and the rule becomes checkable; a record's \
             own `clean` field names the one it wants. The result says \
             unverified rather than claiming the rule held",
            checks.unreadable
        )),
        Pairing::Unverified => progress(
            "the pairing rule could not be checked: no stego image here names \
             a cover or a clean half this could read alongside it. The result \
             says unverified rather than claiming the rule held",
        ),
        Pairing::SingleVariable => {
            if checks.unreadable > 0 {
                progress(&format!(
                    "{} of {} stego image(s) could not be compared with their \
                     cover, so the pairing check covered the rest",
                    checks.unreadable,
                    checks.unreadable + checks.compared
                ));
            }
        }
    }

    // A detector scored on what it trained on measures memory rather than
    // detection, and the number comes out high. Said out loud at the moment
    // the run happens, because the person typing the command is the only one
    // who can still decide not to quote it; a reader meeting the document
    // later can only find the declaration if they go looking.
    if let Some(trained) = trained_on {
        // Every name this corpus answers to, because a person declaring
        // contamination honestly may write any of them: the registry id from
        // `list corpora`, the display name from `describe`, or the directory
        // they pointed at. Matching only one of the three let the most
        // precise declaration through unflagged, which is the wrong way round
        // for a check whose whole purpose is catching a flattering number.
        let t = trained.trim();
        let mut aliases: Vec<String> = vec![corpus_name(corpus)];
        if let Some(e) = registered {
            aliases.push(e.id.clone());
            aliases.push(e.name.clone());
        }
        if let Some(base) = corpus.file_name().and_then(|s| s.to_str()) {
            aliases.push(base.to_string());
        }
        let same = aliases
            .iter()
            .any(|a| a.trim().eq_ignore_ascii_case(t) && !a.trim().is_empty());
        contaminated = same;
        // Declared, so the only question left is whether this corpus could be
        // identified well enough for the comparison to mean anything.
        contamination_check = if registered.is_some() {
            stegobench_core::result::ContaminationCheck::Checked
        } else {
            stegobench_core::result::ContaminationCheck::DeclaredButUncheckable
        };
        if same {
            progress(&format!(
                "WARNING: this detector is declared as trained on {trained}, \
                 which is the corpus it is being scored against. The number \
                 below measures what it memorised as well as what it detects, \
                 and it is not a figure to quote for {trained}"
            ));
        } else if registered.is_none() {
            // The names did not match, and without a registry entry that is
            // weaker than it sounds: the only names this directory has are
            // the ones on disk, so a detector trained on the very corpus this
            // directory holds a copy of goes unflagged whenever the copy was
            // given another name. Said out loud, because the alternative is a
            // line that reads like a clean bill of health for a check that
            // could not run.
            progress(&format!(
                "declared as trained on {trained}. This corpus is not \
                 identified, so that could not be checked against it: pass \
                 --corpus-id to say which registered corpus this directory \
                 holds and the check becomes real"
            ));
        } else {
            progress(&format!(
                "declared as trained on {trained}, which is not the corpus \
                 being scored, and the result records it so a reader can \
                 judge that for themselves"
            ));
        }
    }

    // A prefix of a tier is not the tier, whatever the whole of it hashes to,
    // and the digest above is taken over the whole corpus rather than over
    // what was scored.
    if claim_holds && limit.is_some() {
        progress(
            "this run scored part of the corpus, so it is marked custom \
             rather than named: a prefix of a tier is not the tier",
        );
    }

    // Read once here rather than once per detector. Walking the corpus for
    // labels is cheap next to hashing it, but it is still a walk of every
    // record on disk, and seven of them over a Core tier is seven times
    // 344,357 file reads for an answer that cannot have changed.
    //
    // Built alongside the keep mask, because `--split test` changes which
    // samples are scored and the two have to describe the same set. Both
    // follow corpus order, which is the order `Feed` walks, so the mask and
    // the labels index the same items.
    let wanted = match split {
        None => None,
        Some(s) => match Side::parse(s) {
            Some(side) => Some(side),
            None => {
                return Err(ScoreError::UnknownSplit {
                    asked: s.to_string(),
                })
            }
        },
    };
    if wanted.is_some() && checks.sides.iter().all(Option::is_none) {
        return Err(ScoreError::NoSplitLabels {
            path: corpus.display().to_string(),
        });
    }

    let mut labels = Vec::new();
    let mut keep = Vec::new();
    // Set only when `--limit` actually cut the walk short, so the ordinary
    // whole-corpus run says nothing rather than saying "all of it".
    let mut of_items: Option<u64> = None;
    let mut arm_names: Vec<String> = Vec::new();
    let mut arms: Vec<Option<u16>> = Vec::new();
    let mut rows = Samples::open(corpus)?.enumerate();
    while let Some((i, sample)) = rows.next() {
        let sample = sample?;
        let take = match wanted {
            None => true,
            // A sample the corpus says nothing about is not in the half you
            // asked for. Dropping it silently would be the wrong default, so
            // the count of what was left out is reported below.
            Some(side) => checks.sides.get(i).copied().flatten() == Some(side),
        };
        keep.push(take);
        if take {
            labels.push(sample.role == Role::Stego);
            arms.push(intern(&mut arm_names, arm_name_of(&sample)));
            if limit.is_some_and(|n| labels.len() as u64 >= n) {
                // Keep walking, without scoring, purely to learn how big the
                // corpus was. The digest covers the directory rather than the
                // subset, so this count is the only thing that can tell a
                // reader, or `verify`, that the run stopped early.
                let mut total = i as u64 + 1;
                for (_, rest) in rows.by_ref() {
                    rest?;
                    total += 1;
                }
                of_items = Some(total);
                break;
            }
        }
    }
    if let Some(side) = wanted {
        let left_out = keep.iter().filter(|k| !**k).count();
        progress(&format!(
            "scoring the {} split only: {} image(s), {left_out} left out",
            side.as_str(),
            labels.len()
        ));
    }

    // The corpus itself is one-sided, which no detector can fix. Refused here
    // so a seven-detector command says so once, before anything runs, rather
    // than seven times after seven full runs. `score_one` asks the same
    // question again of what the detector actually ANSWERED, which is a
    // different fact and can only be known afterwards.
    let stego = labels.iter().filter(|l| **l).count() as u64;
    let clean = labels.len() as u64 - stego;
    if clean == 0 || stego == 0 {
        return Err(ScoreError::OneSided {
            path: match wanted {
                Some(side) => format!("{} ({} split)", corpus.display(), side.as_str()),
                None => corpus.display().to_string(),
            },
            clean,
            stego,
        });
    }

    Ok(Prepared {
        corpus: corpus.to_path_buf(),
        limit,
        of_items,
        registered: registered.map(|e| (e.id.clone(), e.name.clone(), e.tier.clone())),
        trained_on: trained_on.map(str::to_string),
        contaminated,
        contamination_check,
        checks,
        claim_holds,
        labels,
        keep,
        side: wanted,
        arm_names,
        arms,
        started_utc,
        preflight: started.elapsed(),
    })
}

/// Ask one detector about a corpus [`prepare`] has already established.
///
/// Callable repeatedly against the same [`Prepared`]. Nothing it does touches
/// the corpus beyond reading the images the detector is handed, so the second
/// detector costs a scoring pass and nothing else.
/// How to run one detector, as against which detector and over what.
///
/// Grouped because every one of these is decided once, before any detector
/// is probed for, and they travel together to every scoring call.
#[derive(Clone, Copy)]
pub struct How<'a> {
    /// What one image is given before the detector is killed.
    pub timeout: Duration,
    /// How many images to score at once. 1 is one at a time.
    pub jobs: usize,
    /// Keep what the detector printed for every image, not only the ones it
    /// could not be read on.
    pub keep_raw: bool,
    /// The seed the caller declared their plugin was run with.
    pub seed: Option<u64>,
    /// Where the self-test fixtures live, so the run can record whether the
    /// plugin settled them. `None` records nothing rather than guessing.
    pub fixtures: Option<&'a Path>,
    /// The trees a relative `invoke.adapter` is resolved against.
    pub adapter_roots: &'a [PathBuf],
}

pub fn score_one<P>(
    entry: &Entry,
    prepared: &Prepared,
    records: &Path,
    how: How<'_>,
    mut progress: P,
) -> Result<(Result1, Tally), ScoreError>
where
    P: FnMut(&str),
{
    let How {
        timeout,
        jobs,
        keep_raw,
        seed,
        fixtures,
        adapter_roots,
    } = how;

    // Two images against a corpus of thousands, run beside the measurement so
    // the document can say whether the thing it measured was working. Doing
    // it here rather than trusting a `doctor` from an hour ago is the point:
    // the claim is about this run.
    let selftest =
        fixtures.map(
            |dir| match stegobench_plugin::selftest::run(entry, dir, adapter_roots) {
                stegobench_plugin::selftest::Verified::Passed => SelfTest::Passed,
                stegobench_plugin::selftest::Verified::Failed(_) => SelfTest::Failed,
                stegobench_plugin::selftest::Verified::Skipped(_) => SelfTest::Skipped,
                stegobench_plugin::selftest::Verified::Answered(_) => SelfTest::Answered,
            },
        );
    refuse_embedder(entry)?;

    // The scoring pass. Streams, and every answer is on disk before the next
    // item begins, so an interrupted run resumes rather than restarts.
    let file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(records)
        .map_err(|e| ScoreError::Records {
            path: records.display().to_string(),
            source: e,
        })?;
    let mut sink = JsonLines::new(file);

    // Streamed, not collected. Building a Vec of 344,357 items here would put
    // the corpus back in memory one layer above the runner that was written
    // specifically not to hold it.
    let mut feed = Feed::filtered(
        &prepared.corpus,
        prepared.limit,
        prepared.side.map(|_| prepared.keep.clone()),
    )?;
    // Beside the records and named after them, so the two halves of one
    // run's evidence sit together and a second detector cannot write into
    // the first one's.
    let raw_path = {
        let name = records.file_name().unwrap_or_default().to_string_lossy();
        let stem = name.strip_suffix(".records.jsonl").unwrap_or(&name);
        records.with_file_name(format!("{stem}.raw.jsonl"))
    };
    // Said BEFORE the first image, because a batched detector answers in groups
    // and the gap before the first answer is the whole batch. A developer
    // walking this watched five minutes of nothing, found the host side process
    // at 0% CPU because the work was inside the container, and came within a
    // minute of killing the run as hung. The run was fine. One line at the start
    // is what turns that silence into something expected.
    if let Some(batch) = entry
        .invoke
        .as_ref()
        .and_then(|i| i.batch)
        .filter(|b| *b > 1)
    {
        progress(&format!(
            "{} asks about {batch} image(s) per container, so the first answers \
             arrive together rather than one at a time. Progress is reported \
             every {}s while that happens, including when the count has not \
             moved yet",
            entry.name,
            runner::HEARTBEAT.as_secs()
        ));
    }
    let own_started = Instant::now();
    // A run that knows its own rate should not leave a reader doing the
    // arithmetic. The reasoning is on `revised_estimate`.
    let total = prepared.items();
    let declared_total = entry
        .cost
        .seconds_per_image
        .map(|s| s * total.max(1) as f64);
    let mut said_already = false;
    let tally = runner::score(
        runner::Run {
            entry,
            already: records,
            timeout,
            jobs,
            adapter_roots,
            raw: runner::RawPolicy {
                path: Some(&raw_path),
                every: keep_raw,
            },
        },
        &mut feed,
        &mut sink,
        |t| {
            progress(&format!("{} scored, {} errored", t.scored, t.errored));
            // Once per run, not once per heartbeat: an estimate that revises
            // itself every thirty seconds is noise. The latch is set by any
            // verdict, including "close enough to say nothing", so a run whose
            // rate settles early stops recomputing this.
            if !said_already && t.scored >= REVISE_AFTER {
                said_already = true;
                if let Some(line) = revised_estimate(
                    t.scored,
                    total.saturating_sub(t.seen()),
                    total,
                    own_started.elapsed(),
                    declared_total,
                ) {
                    progress(&line);
                }
            }
        },
    )?;
    // Said once, after the run, because it is a fact about the evidence
    // rather than about the measurement: the number is still good and the
    // reader has to know the tool's own words were not all kept.
    if let Some(problem) = &tally.raw_problem {
        progress(problem);
    }

    // A corpus defect part way through is a failure, not a short run. Checked
    // after the loop because the iterator cannot return one.
    if let Some(e) = feed.fault {
        return Err(ScoreError::Corpus(e));
    }

    // The metrics pass. Labels came from the corpus in `prepare` and scores
    // come from the records, joined by position, because both are produced in
    // the same deterministic order and the runner refuses to continue when
    // they disagree.
    let Joined {
        scores,
        labels,
        arms,
        errored,
        answers_a_verdict,
    } = join(records, &prepared.labels, &prepared.arms)?;
    let n_stego = labels.iter().filter(|l| **l).count() as u64;
    let n_clean = labels.len() as u64 - n_stego;
    if n_clean == 0 || n_stego == 0 {
        // WHICH OF THE TWO IS AT FAULT IS NOT A DETAIL.
        //
        // These counts are taken over the images the detector ANSWERED about,
        // so a tool that answered about nothing produces 0 and 0 whatever the
        // corpus holds, and the refusal then blamed the corpus. A researcher
        // whose plugin printed nothing at all was told his ten-clean,
        // ten-stego corpus held none of either.
        let corpus_sides = prepared.labels.iter().filter(|l| **l).count() as u64;
        let corpus_clean = prepared.labels.len() as u64 - corpus_sides;
        if scores.is_empty() && corpus_clean > 0 && corpus_sides > 0 {
            return Err(ScoreError::NothingAnswered {
                name: entry.name.clone(),
                path: prepared.corpus.display().to_string(),
                asked: prepared.labels.len() as u64,
                clean: corpus_clean,
                stego: corpus_sides,
                why: match errored {
                    0 => "No record carried a score or a verdict at all.".to_string(),
                    n => format!("All {n} of them came back as failures."),
                },
            });
        }
        return Err(ScoreError::OneSided {
            path: prepared.corpus.display().to_string(),
            clean: n_clean,
            stego: n_stego,
        });
    }

    let checks = &prepared.checks;

    // THE PAIRING AND SPLIT NOTES ARE NOT REPEATED HERE.
    //
    // They are facts about the corpus, so `prepare` says them once for the
    // whole command. This block said them again, once per detector, and a
    // single detector run therefore printed the same paragraph twice: a
    // journey transcript caught it with the unverified-pairing message
    // appearing back to back. A warning a reader sees twice in one run is one
    // they start skimming, which costs exactly the warnings this project
    // depends on being read.

    let named = if prepared.claim_holds && prepared.limit.is_none() {
        Configuration::Named
    } else {
        Configuration::Custom
    };

    // NOTHING HERE INVENTS A NUMBER WHEN THE METRIC CANNOT BE COMPUTED.
    //
    // This line used to read `.unwrap_or(0.5)`, and 0.5 is the one value that
    // must never be a fallback: it is exactly what an AUC says when a detector
    // carries no information. A run that could not be measured was therefore
    // published as a run that came out at chance, and no field in the document
    // told the two apart. That is the class of fault this project exists to
    // correct, so it is refused rather than defaulted.
    //
    // `result-v1` requires the field, so the choice is refuse or lie, and it
    // is not this code's to make the field optional.
    let auc = match stegobench_metrics::roc_auc(&scores, &labels) {
        Some(auc) => auc,
        None => {
            return Err(ScoreError::NoAuc {
                name: entry.name.clone(),
                answered: scores.len(),
                why: why_no_auc(&scores, &labels, ""),
            })
        }
    };

    // The uncertainty beside the number, where there is enough of each class
    // to estimate one. `None` is honest for a run with a single clean or a
    // single stego image: a variance over one observation is not an
    // estimate, and a fabricated interval there would be worse than none.
    let auc_ci95 = stegobench_metrics::roc_auc_interval(&scores, &labels, stegobench_metrics::Z_95)
        .map(|ci| [ci.low, ci.high]);

    // A detector that gave ONE answer to everything scores exactly 0.5, and so
    // does a coin flip. The number is correctly computed in both cases and it
    // means completely different things: one detector could not tell these
    // images apart, the other ranked them no better than chance.
    //
    // Measured 2026-09-29 on the first end to end run this project ever did:
    // zsteg answered `false` for all 18 images of the starter corpus, 12 of
    // them stego, and the run reported `AUC 0.5000 ... 0 unanswered` with
    // nothing saying the answers were identical. `n_error` was correctly zero,
    // because the tool did answer; it just said the same thing every time.
    //
    // Said out loud here rather than recorded in the document, because
    // `result-v1` has no field for it and inventing one quietly is how a
    // schema stops meaning what it says. See DEFERRED.md.
    // Both judgements live in `stegobench-metrics` so that `metrics`, the
    // documented path for anybody bringing their own detector, cannot drift
    // from what `score` says about the same numbers. The crate returns the
    // finding; the wording stays here, because a dependency-free arithmetic
    // crate has no business owning a sentence.
    //
    // Said out loud rather than recorded in the document, because `result-v1`
    // has no field for either and inventing one quietly is how a schema stops
    // meaning what it says. See DEFERRED.md.
    // Said before the findings, because it changes how the next sentence reads:
    // an identical-answers warning about a verdict-only tool is a much weaker
    // claim than the same warning about one that had a scale to spread over.
    if answers_a_verdict {
        progress(&format!(
            "{} answers yes or no rather than giving a score, so every record \
             here has `score: null` and a `verdict` instead. That is the answer, \
             not a gap, which is why none of these count as unscored. It also \
             means there is no threshold to choose for this detector: a run with \
             it is already at its only operating point",
            entry.name
        ));
    }
    for finding in stegobench_metrics::findings(&scores, &labels) {
        progress(&match finding {
            stegobench_metrics::Finding::EveryScoreIdentical { count } => format!(
                "every one of the {count} answers from {} was identical, so this AUC is 0.5 \
                 by construction and not by measurement: it did not separate these images. \
                 A detector that found nothing and an adapter misreading its output look \
                 exactly like this, and only the tool's own output tells them apart",
                entry.name
            ),
            stegobench_metrics::Finding::ScoresRunBackwards { auc, inverted } => format!(
                "{} scored {auc:.4}, which is below the 0.5 a coin flip gets. That \
                 usually means its scores run the wrong way round rather than that \
                 it cannot see anything: at {inverted:.4} it separates these images about as \
                 well inverted as it would upright. Check the adapter's sign before \
                 reading this as a measurement",
                entry.name
            ),
        });
    }

    let mut tpr_at_fpr = BTreeMap::new();
    let mut fpr_achieved = BTreeMap::new();
    let mut threshold_at_fpr = BTreeMap::new();
    // A budget finer than one clean image cannot be spent, and the figure
    // then belongs to a rate nobody asked for. Collected so it is said once
    // with all three rates rather than three times.
    let mut unspendable: Vec<String> = Vec::new();
    for fpr in [0.01, 0.05, 0.10] {
        match stegobench_metrics::tpr_at_fpr(&scores, &labels, fpr) {
            Some(tpr) => {
                let key = format!("{fpr:.2}");
                tpr_at_fpr.insert(key.clone(), tpr);
                if let Some(point) = stegobench_metrics::operating_point(&scores, &labels, fpr) {
                    fpr_achieved.insert(key.clone(), point.achieved_fpr);
                    // The cutoff that bought this rate. Published because every
                    // other figure here says how good the detector is and only
                    // this one says what to compare against, and a developer
                    // whose whole task was choosing it searched the document,
                    // found nothing, and reimplemented the sweep himself.
                    //
                    // Absent rather than zero where the point is the origin: a
                    // threshold of 0.0 would be a number somebody could type,
                    // and nothing is flagged there.
                    if let Some(threshold) = point.threshold {
                        threshold_at_fpr.insert(key, threshold);
                    }
                    if !point.budget_was_expressible(n_clean as usize) {
                        unspendable.push(format!("{:.0}%", fpr * 100.0));
                    }
                }
            }
            // Unreachable given the AUC above succeeded: these three budgets
            // are constants inside [0, 1], and the only other way this answers
            // None is a curve that could not be drawn, which is the same
            // condition the AUC just cleared. It is checked rather than
            // assumed, because a silently missing key in the published map
            // would read as "this detector was measured and reached nothing at
            // that budget", which is a different and much worse claim.
            None => {
                return Err(ScoreError::NoAuc {
                    name: entry.name.clone(),
                    answered: scores.len(),
                    why: why_no_auc(
                        &scores,
                        &labels,
                        &format!(" at a false-alarm budget of {fpr:.2}"),
                    ),
                })
            }
        }
    }
    if !unspendable.is_empty() {
        // The figure is right and the heading is not, which is the shape of
        // fault a reader cannot catch: they copy the cell out, and "TPR at a
        // 1% false-alarm rate" travels with it as a claim nobody made.
        progress(&format!(
            "{} clean image(s) cannot express a false-alarm budget finer than \
             {:.1}%, so the figure(s) reported at {} are the figure at the \
             nearest rate this corpus can actually show. The number is real; \
             the heading over it is finer than the measurement. More clean \
             images is the only fix",
            n_clean,
            stegobench_metrics::fpr_resolution(n_clean as usize) * 100.0,
            unspendable.join(", ")
        ));
    }

    // Said where a reader is looking, because the two timing fields in the
    // document are about to be true and misleading at the same time. A
    // reviewer read `elapsed_seconds: 0.004` over eighteen images and asked,
    // correctly, when the detection had actually run.
    if tally.resumed > 0 && tally.scored == 0 {
        progress(&format!(
            "every one of the {} answer(s) came from the existing records, so \
             nothing was scored. The run time and start time below are this \
             command's, not the measurement's",
            tally.resumed
        ));
    } else if tally.resumed > 0 {
        progress(&format!(
            "{} answer(s) came from the existing records and {} were scored \
             now, so the run time below covers this command rather than the \
             whole measurement",
            tally.resumed, tally.scored
        ));
    }

    let (version, pinned_by) = pinning(entry);
    let adapter = adapter_ref(entry, adapter_roots);

    let mut result = Result1 {
        schema: RESULT_SCHEMA_ID.to_string(),
        subject: Subject {
            name: entry.name.clone(),
            version: version.clone(),
            kind: SubjectKind::Detector,
        },
        corpus: CorpusRef {
            name: match &prepared.registered {
                Some((_, name, _)) => name.clone(),
                None => corpus_name(&prepared.corpus),
            },
            id: prepared.registered.as_ref().map(|(id, _, _)| id.clone()),
            tier: prepared
                .registered
                .as_ref()
                .and_then(|(_, _, tier)| tier.clone()),
            // The user pointed at a directory. Nothing here downloaded it, and
            // saying otherwise would be the harness vouching for bytes it
            // never saw arrive. Naming the corpus does not change that: a
            // registry entry describes a dataset, it does not deliver one.
            source: CorpusSource::Supplied,
            digest: checks.digest.clone().unwrap_or_default(),
            // PAIRS, not items. This wrote `labels.len()`, which is clean plus
            // stego, while `generators/emit_results.py` wrote the stego rows,
            // which is pairs. One published field meant two things depending on
            // which half of this project produced the document, and the field
            // carried no doc comment to arbitrate: a shipped result says
            // `pairs: 200` beside `n_stego: 200`, and a run of the starter
            // corpus said `pairs: 18` for 6 covers and 12 stego images.
            //
            // A pair is a cover and its stego twin, so the count is the stego
            // side. See the field's own documentation in `result.rs`.
            pairs: labels.iter().filter(|&&stego| stego).count() as u64,
            of_items: prepared.of_items,
            // Which half was scored, so a reader is never left inferring it
            // from `split_discipline`. That field says the corpus keeps a
            // pair together; this one says which side of it the number came
            // from, and for a trained detector they are different questions.
            split: prepared.side.map(|s| s.as_str().to_string()),
        },
        arm: checks.arm.clone(),
        metrics: Metrics {
            auc,
            auc_ci95,
            tpr_at_fpr,
            fpr_achieved,
            threshold_at_fpr,
            verdict_rate: None,
            n_clean,
            n_stego,
            n_error: errored,
            per_arm: per_arm(&scores, &labels, &arms, &prepared.arm_names),
        },
        provenance: Provenance {
            seed,
            plugins: vec![PluginRef {
                name: entry.name.clone(),
                image: version,
                determinism: entry.determinism.unwrap_or(Determinism::Unstated),
                selftest,
                adapter,
                // Declared, not expanded: the expanded form carries this
                // machine's absolute paths and this document is written to be
                // given away.
                argv: entry.invoke.as_ref().map(|i| i.argv.clone()),
                // Two fields because an entry can declare an image AND
                // `invoke.host`: the image digest names the subject while what
                // executes is an adapter here that posts to a running
                // instance. The pin and the sandbox disagree for that shape,
                // and a single value could only ever be right about one of
                // them.
                pinned_by,
                isolation: isolation(entry),
            }],
            harness_version: env!("CARGO_PKG_VERSION").to_string(),
            started_utc: prepared.started_utc.clone(),
            // The shared pre-flight plus this detector's own pass. Both are
            // work this number rests on. What it does NOT include is time
            // spent on the other detectors of the same command: waiting for a
            // different measurement is not part of making this one.
            // THIS INVOCATION, which on a resumed run is not the
            // measurement. A resume re-reads the existing records and scores
            // nothing, so a document written by one says eighteen images were
            // scored in four milliseconds and dates itself to the moment of
            // the resume rather than of the detection. Both fields are then
            // true about a run that measured nothing and read as though they
            // describe the one that did.
            //
            // The honest figure needs the first run's start carried forward,
            // and there is nowhere trustworthy to carry it yet, so what this
            // does instead is say so out loud where a reader will see it.
            elapsed_seconds: prepared.preflight.as_secs_f64() + own_started.elapsed().as_secs_f64(),
            // Three routes, three answers, and the one-line version used to
            // get two of them wrong.
            //
            // A container is launched with `--network=none` (see
            // `stegobench_plugin::selftest`), so nothing inside it can reach
            // anything. A locally installed binary runs here with this
            // machine's network and nothing constrains it. A host adapter runs
            // here too, and for a service entry the network is not merely
            // reachable, it is the only way the tool is asked anything at all,
            // so reporting it as unreachable was the most misleading of the
            // three.
            network_reachable: !runs_in_container(entry),
            host: Some(host()),
            // Filled in after the run, below: the file is still being
            // appended to at this point.
            records: None,
            // From the run's own tally rather than from the records file,
            // because the file cannot say which of its lines this command
            // wrote. Sealed, so a hand-written records file cannot claim to
            // have been measured.
            answers: stegobench_core::result::AnswerSource {
                measured: tally.scored,
                resumed: tally.resumed,
            },
        },
        declarations: Declarations {
            split_discipline: checks.split,
            pairing: checks.pairing,
            configuration: named,
            trained_on: prepared.trained_on.clone(),
            contaminated: prepared.contaminated,
            contamination_check: prepared.contamination_check,
            // The side actually scored, so `--split test` and a whole-corpus
            // run stop producing identical documents.
            split_scored: prepared.side.map(|s| s.as_str().to_string()),
            // True because somebody ran this, and the harness cannot know
            // whether that somebody owns the detector. The submission path
            // is what clears it.
            self_reported: true,
            // The counts behind `pairing`, so a reviewer reading only this
            // document can tell a corpus that claimed nothing from one whose
            // claims named files it did not ship.
            pairing_evidence: stegobench_core::result::PairingEvidence {
                compared: checks.compared,
                named_a_half_not_here: checks.unreadable,
                differed: checks.pairing_breaks.count as u64,
            },
        },
        content_digest: None,
    };
    // AFTER THE RUN, because the file is appended to as each item is scored
    // and a digest taken before the last write names a file nobody has.
    //
    // Failing to read it back is not a reason to lose the measurement, which
    // is finished and correct. The field is left absent and the document then
    // says nothing about its records rather than saying something wrong: an
    // absent digest and a digest that does not match are different, and only
    // one of them is an accusation.
    result.provenance.records = stegobench_core::result::records_digest(records).ok();
    // Last, because it covers every other field. Sealing earlier would digest
    // a document that did not exist yet.
    result.seal();
    Ok((result, tally))
}

/// Which of the conditions stopped a metric being computed, in words.
///
/// The sentences are [`crate::metrics::MetricsError`]'s and are not repeated
/// here: this path and `stegobench metrics` refuse for the same reasons, and
/// two sets of words for one condition is the copy that drifts. What this adds
/// is the part that is only true here, where the answers came from a detector
/// this harness ran rather than from a file somebody wrote, so the next step
/// differs even though the condition does not.
///
/// `at` names the operating point, and is empty for the AUC itself.
fn why_no_auc(scores: &[f64], labels: &[bool], at: &str) -> String {
    let refusal = crate::metrics::why_unrankable(scores, labels, at);
    let here = match refusal.reason() {
        // Nothing the user did: `score` builds both lists from the same
        // records in the same order, so they cannot legitimately disagree.
        "length-mismatch" => {
            " Both are built from the same records in the same order here, so \
             this is a bug in stegobench rather than anything you did. Please \
             report it with this message."
        }
        // Every image errored. The sentence underneath is `metrics`' one, and
        // there a user really did hand over an empty file; here nobody gave
        // anything, the detector produced nothing, and a reader who is told
        // "no scores were given" has no reason to look at the tool.
        "empty" => {
            " Every image was put to this tool and none of them came back with \
             a number, which is the tool or its parser rather than the corpus: \
             `stegobench doctor` runs its self-test and says which."
        }
        // The numbers came from the detector, so the next step is the detector.
        "not-a-number" => {
            " This is the detector's output, so the fix is with the tool or \
             its parser: `stegobench doctor` runs its self-test."
        }
        // The corpus may well hold both sides. What is one-sided is the set of
        // answers this tool managed to produce, and saying so points at the
        // tool rather than sending somebody to re-examine their corpus.
        "one-sided" => {
            " Whatever the corpus holds, this tool produced a usable answer \
             for only one of them."
        }
        _ => "",
    };
    format!("{refusal}{here}")
}

/// The items to score, one at a time, stopping at `limit` where one is set.
///
/// An iterator cannot return an error, and a corpus defect must not read as
/// the end of the corpus: that is the difference between "scored everything"
/// and "scored as far as the broken file", and they have the same shape from
/// the outside. So a fault stops the feed and is picked up by the caller.
struct Feed {
    samples: Samples,
    limit: Option<u64>,
    taken: u64,
    /// How many samples have been looked at, kept or not.
    ///
    /// Separate from `taken`, which counts only what was yielded: the mask is
    /// indexed by position in the corpus and the limit is a count of work, so
    /// one cannot stand in for the other once a split is being filtered.
    seen: usize,
    /// Which positions to yield, or `None` for all of them.
    keep: Option<Vec<bool>>,
    fault: Option<stegobench_core::samples::SampleError>,
}

impl Feed {
    fn filtered(
        corpus: &Path,
        limit: Option<u64>,
        keep: Option<Vec<bool>>,
    ) -> Result<Self, ScoreError> {
        Ok(Self {
            samples: Samples::open(corpus)?,
            limit,
            taken: 0,
            seen: 0,
            keep,
            fault: None,
        })
    }
}

/// Whether a run of this entry happens inside a container, which is the only
/// route that is sandboxed away from the network.
///
/// An entry naming an image is not enough. `invoke.host` says the thing that
/// runs is a program on this machine, and the image reference is then the
/// subject's identity rather than a description of what executes.
fn runs_in_container(entry: &Entry) -> bool {
    entry.image.is_some() && !entry.invoke.as_ref().is_some_and(|i| i.host)
}

impl Iterator for Feed {
    type Item = WorkItem;

    fn next(&mut self) -> Option<WorkItem> {
        loop {
            if self.limit.is_some_and(|n| self.taken >= n) {
                return None;
            }
            match self.samples.next()? {
                Ok(sample) => {
                    let at = self.seen;
                    self.seen += 1;
                    if let Some(keep) = &self.keep {
                        // Past the end of the mask means the mask was built
                        // under a limit that stopped early, so there is
                        // nothing further this run covers.
                        match keep.get(at) {
                            Some(true) => {}
                            Some(false) => continue,
                            None => return None,
                        }
                    }
                    self.taken += 1;
                    return Some(WorkItem {
                        id: sample.id,
                        path: sample.image,
                    });
                }
                Err(e) => {
                    self.fault = Some(e);
                    return None;
                }
            }
        }
    }
}

/// How many example violations are kept to show the user.
///
/// The count is exact and the examples are capped, which is the only shape
/// that works: a corpus built by a broken script fails on every one of its
/// 344,357 rows, and a list of them would put the whole corpus in memory to
/// print three lines of it.
/// How many images a run has to have scored before its own rate is worth
/// quoting back.
///
/// Sixteen rather than a handful: the first invocation of a batched detector
/// carries the whole container start, so a rate taken over two images is a
/// measurement of the startup and not of the work.
const REVISE_AFTER: u64 = 16;

const MAX_EXAMPLES: usize = 3;

/// A tally of one kind of corpus defect, with a few examples kept to show.
#[derive(Default)]
struct Violations {
    count: usize,
    examples: Vec<String>,
}

impl Violations {
    fn note(&mut self, what: String) {
        self.count += 1;
        if self.examples.len() < MAX_EXAMPLES {
            self.examples.push(what);
        }
    }

    fn is_empty(&self) -> bool {
        self.count == 0
    }

    fn examples(&self) -> String {
        self.examples.join("; ")
    }
}

/// What the corpus turned out to be, as opposed to what it claims.
/// Which half of a train and test split a sample falls in.
///
/// A byte per sample rather than the split string per sample: a Core tier is
/// 344,357 records, and holding "test" as a `String` for each is thirty
/// megabytes to answer a question with two answers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Side {
    Train,
    Test,
}

impl Side {
    fn parse(s: &str) -> Option<Side> {
        match s.trim().to_ascii_lowercase().as_str() {
            "train" => Some(Side::Train),
            "test" => Some(Side::Test),
            _ => None,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Side::Train => "train",
            Side::Test => "test",
        }
    }
}

struct Checks {
    split: SplitDiscipline,
    /// The side each sample falls on, in corpus order.
    ///
    /// A stego row inherits its cover's side, which is the whole discipline:
    /// the split is a property of the cover and a pair that straddles it
    /// inflates every number computed from the corpus. `None` where the
    /// corpus says nothing, or where a stego row's cover cannot be found.
    sides: Vec<Option<Side>>,
    split_leaks: Violations,
    pairing: Pairing,
    pairing_breaks: Violations,
    /// Stego images whose cover could be found and compared.
    compared: u64,
    /// Stego images naming a cover that could not be compared, because one of
    /// the two images could not be read or is in a format this does not
    /// measure.
    unreadable: u64,
    /// A name for this corpus's content, or `None` where it cannot have one.
    ///
    /// Computed over every record's own stated digest, in corpus order, so two
    /// people holding the same corpus compute the same value and a result can
    /// say which bytes it was measured on. It identifies the MANIFEST rather
    /// than the bytes: nothing here reopens an image to check the claim, which
    /// is why `corpus.source` sits beside it and says whether the harness
    /// fetched the corpus or was handed it.
    digest: Option<String>,
    /// What was embedded, as the corpus itself states it.
    arm: Arm,
}

/// Names a corpus by what its records declare about their own images.
///
/// Fed in corpus order, which is sorted by id and therefore identical on every
/// machine, so two people holding the same corpus compute the same value and a
/// result can say which bytes it was measured on. Constant memory: it is a
/// hash state and two counters.
///
/// It identifies the MANIFEST rather than the bytes. Nothing here reopens an
/// image to check the claim a record makes about it, which is a real limit and
/// is why the result document carries `corpus.source` beside the digest to say
/// whether the harness fetched the corpus or was handed it.
#[derive(Default)]
pub struct CorpusDigest {
    hash: Sha256,
    seen: u64,
    every_record_declares_one: bool,
}

impl CorpusDigest {
    fn new() -> Self {
        Self {
            hash: Sha256::new(),
            seen: 0,
            every_record_declares_one: true,
        }
    }

    fn note(&mut self, sample: &Sample) {
        self.seen += 1;
        self.hash.update(sample.id.as_bytes());
        self.hash.update(b"\0");
        match &sample.digest {
            Some(d) => self.hash.update(d.as_bytes()),
            None => self.every_record_declares_one = false,
        }
        self.hash.update(b"\n");
    }

    /// The digest, or `None` where the corpus cannot honestly have one.
    ///
    /// A digest over a corpus where some records state none of their own would
    /// name the file list, and the field it goes in is read as naming the
    /// content. Carrying nothing is the smaller claim, which is to say it is
    /// not a false one.
    fn finish(self) -> Option<String> {
        (self.every_record_declares_one && self.seen > 0)
            .then(|| format!("sha256:{:x}", self.hash.finalize()))
    }
}

/// Checks that every image is the file its own record says it is.
///
/// THE HOLE THIS CLOSES
///
/// The corpus digest is taken over what the records STATE about their images,
/// not over the images. That is what lets it survive a corpus being extracted
/// from a shard and moved, and it is the right property for identifying a
/// corpus. It is the wrong property to rest a `named` result on by itself:
/// somebody could take the real manifest records, pair them with easier
/// images, and match the registry's digest exactly while measuring something
/// else entirely.
///
/// So a run that claims a registered corpus pays for one pass over the bytes.
/// It costs a read of the corpus, which the detector was going to do anyway,
/// and it turns `named` from "the manifest matches" into "the images are the
/// ones the manifest describes", which is what a reader assumes the word means.
///
/// Not done for a `custom` run. There is no external claim to check one
/// against, the records are the only description of the corpus that exists,
/// and comparing them with themselves would be theatre.
fn verify_bytes<P>(root: &Path, progress: &mut P) -> Result<u64, ScoreError>
where
    P: FnMut(&str),
{
    let mut checked = 0u64;
    let mut skipped = 0u64;
    let mut last_beat = Instant::now();
    for sample in Samples::open(root)? {
        let sample = sample?;
        let Some(want) = sample.digest.as_deref() else {
            // A corpus reaching here has a digest, which means every record
            // stated one, so this cannot fire. Counted rather than asserted.
            skipped += 1;
            continue;
        };
        let got = hash_file(&sample.image).map_err(|e| ScoreError::Records {
            path: sample.image.display().to_string(),
            source: e,
        })?;
        if got != want {
            return Err(ScoreError::ImageChanged {
                id: sample.id,
                want: want.to_string(),
                got,
            });
        }
        checked += 1;
        // Baseline Section 2.1: a long loop emits a heartbeat. Hashing a Core
        // tier is tens of gigabytes and a silent minute reads as a hang.
        if last_beat.elapsed() >= HEARTBEAT {
            progress(&format!("{checked} image(s) checked against their records"));
            last_beat = Instant::now();
        }
    }
    debug_assert_eq!(skipped, 0, "a digested corpus had a record with no digest");
    Ok(checked)
}

/// How often a long pass says it is still alive.
const HEARTBEAT: Duration = Duration::from_secs(30);

/// The sha256 of a file as lower case hex, streamed rather than read whole.
///
/// A corpus image is a few hundred kilobytes and reading one whole would be
/// fine; reading one that turns out to be a gigabyte would not, and this is
/// pointed at files somebody else produced.
fn hash_file(path: &Path) -> std::io::Result<String> {
    use std::io::Read;
    let mut file = std::fs::File::open(path)?;
    let mut hasher = Sha256::new();
    let mut buf = vec![0u8; 64 * 1024];
    loop {
        let n = file.read(&mut buf)?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
    }
    Ok(format!("{:x}", hasher.finalize()))
}

/// One image whose bytes are not the bytes its record claims.
#[derive(Debug, Clone, PartialEq)]
pub struct Mismatch {
    /// The sample id, so the answer names the record rather than a path.
    pub id: String,
    /// What the record says the image hashes to.
    pub claimed: String,
    /// What it actually hashes to, or why that could not be established.
    pub found: Result<String, String>,
}

/// How many mismatches are named before the rest are only counted.
///
/// A corpus that has been swapped wholesale produces one mismatch per image,
/// and printing 344,357 lines helps nobody. The first few identify the fault;
/// the count establishes its size.
const NAMED_MISMATCHES: usize = 10;

/// Re-read every image and check it against the digest its record states.
///
/// The corpus digest is computed from what the records SAY, so two corpora
/// whose records match have the same digest whatever the images actually
/// contain. That is the right identity for naming a corpus somebody extracted
/// and moved, and it is not proof that the bytes are the ones measured: a
/// stego image can be replaced with an easier one, the record left alone, and
/// every digest still agrees. This is the check that closes that, and it is
/// the reason `verify` can say "these bytes" rather than "this list of names".
///
/// Returns the mismatches found and the number of images actually read, so a
/// caller can tell "checked and clean" from "there was nothing to check".
pub fn rehash_corpus(
    root: &Path,
    mut progress: impl FnMut(&str),
) -> Result<(Vec<Mismatch>, u64), ScoreError> {
    let mut bad = Vec::new();
    let mut read = 0u64;
    let mut extra = 0u64;
    let mut last = Instant::now();
    for sample in Samples::open(root)? {
        let sample = sample?;
        let Some(claimed) = sample.digest.as_deref() else {
            continue;
        };
        read += 1;
        if last.elapsed() >= HEARTBEAT {
            progress(&format!("rehashed {read} image(s) so far"));
            last = Instant::now();
        }
        let found = hash_file(&sample.image).map_err(|e| e.to_string());
        if found.as_deref() == Ok(claimed) {
            continue;
        }
        if bad.len() < NAMED_MISMATCHES {
            bad.push(Mismatch {
                id: sample.id.clone(),
                claimed: claimed.to_string(),
                found,
            });
        } else {
            extra += 1;
        }
    }
    if extra > 0 {
        progress(&format!(
            "{} further image(s) also differ and are not listed",
            extra
        ));
    }
    Ok((bad, read))
}

/// The digest of a corpus on disk, for a caller that wants only that.
///
/// `score` folds this into a walk it was doing anyway. `verify` has no such
/// walk, so it pays for its own.
pub fn corpus_digest(root: &Path) -> Result<Option<String>, ScoreError> {
    let mut digest = CorpusDigest::new();
    for sample in Samples::open(root)? {
        digest.note(&sample?);
    }
    Ok(digest.finish())
}

/// One value seen across a corpus, or the fact that there was not one.
///
/// Three answers, because three things are true of a real corpus: it states one
/// arm, or it states several, or it states none. Collapsing the last two into
/// "unknown" is how `spatial` came to be written on JPEG runs.
///
/// Constant memory whatever the corpus holds: once a second distinct value
/// arrives, nothing more needs keeping.
#[derive(Debug, Clone, PartialEq, Default)]
enum Uniform<T> {
    #[default]
    Nothing,
    One(T),
    Many,
}

impl<T: PartialEq> Uniform<T> {
    fn note(&mut self, value: Option<T>) {
        let Some(value) = value else { return };
        match self {
            Uniform::Nothing => *self = Uniform::One(value),
            Uniform::One(seen) if *seen == value => {}
            Uniform::One(_) => *self = Uniform::Many,
            Uniform::Many => {}
        }
    }

    fn one(&self) -> Option<&T> {
        match self {
            Uniform::One(v) => Some(v),
            _ => None,
        }
    }
}

impl Uniform<String> {
    /// The single value, or a word saying which of the other two cases it is.
    /// Both go in a string field a person reads, so both have to be words.
    fn or_say_why(&self) -> String {
        match self {
            Uniform::One(v) => v.clone(),
            Uniform::Many => "mixed".into(),
            Uniform::Nothing => "unstated".into(),
        }
    }
}

/// What the corpus says about the arm it holds, gathered while walking it.
#[derive(Default)]
struct ArmFacts {
    tool: Uniform<String>,
    rate: Uniform<(String, f64)>,
    domain: Uniform<String>,
    format: Uniform<String>,
    /// The same question asked of the CLEAN side, so a corpus whose two classes
    /// are different formats says so. See `Arm::clean_format`.
    clean_format: Uniform<String>,
}

/// What a cover contributes to both checks, gathered in one pass.
#[derive(Clone)]
struct Cover {
    split: Option<String>,
    shape: Option<Shape>,
}

/// Checks the two reliability claims the result document carries.
///
/// SPLIT DISCIPLINE, WHICH FILES ON DISK CAN PROVE
///
/// A split label travels with a cover, and a stego image names the cover it was
/// made from, so a stego image carrying a DIFFERENT split from its own cover is
/// a corpus that will leak a photograph across the train and test boundary.
/// Violating it inflates every number computed from the corpus and is invisible
/// in the output, which is exactly why the harness must not take it on trust.
///
/// PAIRING, WHERE ONLY THE NEGATIVE IS PROVABLE
///
/// The rule is that a clean image and its stego twin differ in nothing but the
/// payload. Nothing short of decoding both images could prove that, and even
/// that would miss a cover re-encoded before the payload went in. The reachable
/// half is the refutation: if the two differ in format, width, height, bit depth
/// or channel count, then something other than the payload changed, and the
/// number about to be computed is measuring that too.
///
/// So this returns `SingleVariable` where every comparable pair matched,
/// `Confounded` where any did not, and `Unverified` where nothing could be
/// compared. The third answer is the point. A benchmark that says "single
/// variable" having looked at nothing is making the unchecked claim this
/// project exists to stop repeating.
///
/// WHAT THIS HOLDS IN MEMORY, AND WHY THAT IS BOUNDED
///
/// One entry per COVER, not one per sample, and the stego rows are streamed
/// against it rather than gathered. A Core tier is 10,000 covers against
/// 344,357 samples, so this is an order of magnitude below the corpus and
/// bounded by a number the corpus states rather than by anything this code
/// chooses. It costs a second walk of the directory tree, because a cover can
/// sort after the arm that used it and the map has to be complete before any
/// row is judged against it.
fn check(corpus: &Path) -> Result<Checks, ScoreError> {
    let mut covers: HashMap<String, Cover> = HashMap::new();
    // The clean halves, keyed on the digest each one states for itself, so a
    // stego row can find the exact file it is supposed to differ from in
    // nothing but the payload. See `Sample::clean_digest`: joining a JPEG arm
    // through `source_png` compares the stego JPEG against the original PNG
    // crop, which differs in format, and reported 6,859 of 7,812 images in a
    // correctly paired tier as confounded.
    let mut clean_halves: HashMap<String, Cover> = HashMap::new();
    let mut any_split = false;
    let mut digest = CorpusDigest::new();
    let mut facts = ArmFacts::default();

    for sample in Samples::open(corpus)? {
        let sample = sample?;

        // Folded into a walk that was happening anyway.
        digest.note(&sample);

        if sample.role == Role::Stego {
            // Gathered from the stego side only. The arm is what was embedded,
            // and a clean row states `clean` as its tool, which would turn
            // every corpus into a mixed one.
            let arm = &sample.arm;
            facts
                .tool
                .note(arm.tool.clone().or_else(|| arm.name.clone()));
            facts.domain.note(arm.domain.clone());
            facts.format.note(image_format(&sample.image));
            facts
                .rate
                .note(arm.rate.zip(arm.rate_unit.clone()).map(|(r, u)| (u, r)));
        }

        if sample.role != Role::Clean {
            continue;
        }
        // The clean side's own format, gathered in the walk that was happening
        // anyway, so the document can state both halves rather than only the
        // one that was embedded into.
        facts.clean_format.note(image_format(&sample.image));
        any_split |= sample.split.is_some();

        // Filed under BOTH names a stego row might use to reach it, and the
        // second one is the one that matters. The packer renames every member
        // to its position in the tier, so a cover whose record says
        // `file = "09710.png"` is extracted as `000123.png`, while every stego
        // row made from it still says `09710.png`. Joining on the name on disk
        // alone matches nothing on a packed release, and a check that cannot
        // look reports clean.
        let on_disk = sample
            .image
            .file_name()
            .and_then(|n| n.to_str())
            .map(str::to_string);
        let declared = sample.declared_name.clone();
        // Read once, whichever names it goes in under. An unreadable cover is
        // not a corpus defect this should refuse over: the sample reader has
        // already accepted the file, the detector will be asked about it
        // regardless, and the honest consequence is that this pair cannot be
        // compared rather than that the run cannot happen.
        let shape = header::read(&sample.image).ok();
        let cover = Cover {
            split: sample.split.clone(),
            shape,
        };

        // The record's own name wins, and the name on disk only fills a gap it
        // left. The two are not equally trustworthy: a stego row joins on
        // `source_png`, which names a cover the way its RECORD does, and on a
        // real release the names on disk collide. Every arm restarts its
        // numbering at 000000, so four clean arms extracted beside a cover
        // tier all offer `000000.png`, and letting those overwrite an
        // authoritative entry would silently attach a stego row to the wrong
        // photograph.
        if let Some(name) = declared {
            covers.insert(name, cover.clone());
        }
        if let Some(name) = on_disk {
            covers.entry(name).or_insert(cover.clone());
        }

        // Filed by its own digest as well, which is what a stego row's
        // `clean_sha256` names. Unlike the names above this cannot collide: two
        // clean rows sharing a digest are the same bytes, so whichever wins is
        // the same comparison.
        if let Some(digest) = sample.digest {
            clean_halves.insert(digest, cover);
        }
    }

    let mut checks = Checks {
        split: SplitDiscipline::NotApplicable,
        split_leaks: Violations::default(),
        pairing: Pairing::Unverified,
        pairing_breaks: Violations::default(),
        compared: 0,
        unreadable: 0,
        sides: Vec::new(),
        digest: digest.finish(),
        arm: arm_of(&facts),
    };

    for sample in Samples::open(corpus)? {
        let sample = sample?;

        // Recorded for EVERY sample and in corpus order, so the mask lines up
        // with the labels built from the same walk. A stego row takes its
        // cover's side, because the split is a property of the cover and
        // reading the row's own value would let a corpus put a pair on both
        // sides of it.
        let side = match (&sample.role, &sample.cover) {
            (Role::Clean, _) => sample.split.as_deref().and_then(Side::parse),
            (_, Some(name)) => covers
                .get(name)
                .and_then(|c| c.split.as_deref())
                .and_then(Side::parse)
                .or_else(|| sample.split.as_deref().and_then(Side::parse)),
            (_, None) => sample.split.as_deref().and_then(Side::parse),
        };
        checks.sides.push(side);

        if sample.role != Role::Stego {
            continue;
        }
        // The SPLIT is joined on the cover, and that is right for every arm: a
        // JPEG arm's clean half and its stego half both descend from the one
        // crop, so they inherit that crop's side. A stego row with no split of
        // its own cannot contradict anything; only a row that states one can.
        if let Some(cover_name) = &sample.cover {
            if let Some(cover) = covers.get(cover_name) {
                if let (Some(split), Some(cover_split)) = (&sample.split, &cover.split) {
                    any_split = true;
                    if split != cover_split {
                        checks.split_leaks.note(format!(
                            "{} is in the {split} split while its cover {cover_name} is \
                             in the {cover_split} split",
                            sample.id
                        ));
                    }
                }
            }
        }

        // The PAIRING comparand, which is a different question and often a
        // different file. The rule being checked is that a stego image differs
        // from its clean twin in nothing but the payload, so the comparand is
        // the twin, and only the corpus can say which file that is.
        let against = match &sample.clean_digest {
            Some(digest) => match clean_halves.get(digest) {
                Some(half) => Some((half, "its clean half".to_string())),
                // The corpus names a clean half that is not in this directory,
                // so this pair cannot be compared. It deliberately does NOT
                // fall back to the cover: for a JPEG arm the cover is the crop
                // the clean half was encoded from, which differs in format by
                // construction, and comparing against it reports a correctly
                // paired arm as confounded.
                None => {
                    checks.unreadable += 1;
                    continue;
                }
            },
            // No clean half stated, so the cover is the best available
            // comparand. True of the spatial arms, where the clean half IS the
            // crop, and of any corpus whose records do not carry the field.
            None => sample.cover.as_ref().and_then(|name| {
                covers
                    .get(name)
                    .map(|cover| (cover, format!("its cover {name}")))
            }),
        };
        let Some((against, label)) = against else {
            continue;
        };

        match (against.shape, header::read(&sample.image).ok()) {
            (Some(clean_shape), Some(stego_shape)) => match difference(clean_shape, stego_shape) {
                None => checks.compared += 1,
                Some(what) => {
                    checks.compared += 1;
                    checks
                        .pairing_breaks
                        .note(format!("{} and {label} {what}", sample.id));
                }
            },
            _ => checks.unreadable += 1,
        }
    }

    if any_split {
        checks.split = SplitDiscipline::ByCover;
    }
    checks.pairing = if !checks.pairing_breaks.is_empty() {
        Pairing::Confounded
    } else if checks.compared > 0 {
        Pairing::SingleVariable
    } else {
        Pairing::Unverified
    };
    Ok(checks)
}

/// The arm block, built from what the corpus states rather than from a guess.
///
/// Every field here used to be a constant, and two of the three constants were
/// wrong for most of the corpus: `spatial` on a JPEG arm and `png` on a corpus
/// of JPEGs are not placeholders a reader can see through, they are facts the
/// document appears to assert.
fn arm_of(facts: &ArmFacts) -> Arm {
    let rate = facts.rate.one().and_then(|(unit, value)| {
        let unit = match unit.as_str() {
            "bits per pixel" => RateUnit::Bpp,
            // Both JPEG tools are driven as a share of whatever capacity they
            // report for that cover, which is the distinction the unit exists
            // to carry.
            "bits per non-zero AC coefficient" => return None,
            u if u.contains("capacity") => RateUnit::CapacityFraction,
            _ => return None,
        };
        Some(Rate {
            value: *value,
            unit,
        })
    });

    let domain = match &facts.domain {
        Uniform::One(d) => match d.as_str() {
            "spatial" => Domain::Spatial,
            "jpeg-dct" | "jpeg" => Domain::Jpeg,
            "container" | "structural" => Domain::Structural,
            _ => Domain::Unstated,
        },
        Uniform::Many => Domain::Mixed,
        // The corpus said nothing, so the format is the only evidence left.
        // A corpus of JPEGs is not proof that the payload went into the
        // coefficients, which is why this is the fallback and not the rule.
        Uniform::Nothing => match facts.format.one().map(String::as_str) {
            Some("jpeg") => Domain::Jpeg,
            Some(_) => Domain::Spatial,
            None => Domain::Unstated,
        },
    };

    Arm {
        embedder: facts.tool.or_say_why(),
        rate,
        domain,
        format: facts.format.or_say_why(),
        clean_format: facts.clean_format.one().cloned(),
    }
}

/// What a file calls itself, normalised, for the arm's `format` field.
///
/// The extension rather than the header, deliberately. This field records what
/// the corpus claims to be, and the pairing check reads the headers separately,
/// so a corpus whose names and bytes disagree shows up as a disagreement rather
/// than being quietly resolved in one direction.
fn image_format(path: &Path) -> Option<String> {
    let ext = path.extension()?.to_str()?.to_ascii_lowercase();
    Some(match ext.as_str() {
        "jpg" | "jpeg" => "jpeg".into(),
        "tif" | "tiff" => "tiff".into(),
        _ => ext,
    })
}

/// The first way two images differ other than in their payload, in words.
///
/// Ordered so the reader is told the most fundamental difference rather than
/// the first one an arbitrary field order happens to reach: a PNG against a
/// JPEG is a different fact from a PNG one pixel wider than another.
fn difference(cover: Shape, stego: Shape) -> Option<String> {
    if cover.format != stego.format {
        return Some(format!(
            "are different formats: {} against {}",
            cover.format.name(),
            stego.format.name()
        ));
    }
    let (Some(c), Some(s)) = (cover.geometry, stego.geometry) else {
        return None;
    };
    if (c.width, c.height) != (s.width, s.height) {
        return Some(format!(
            "are different sizes: {} by {} against {} by {}",
            c.width, c.height, s.width, s.height
        ));
    }
    if c.depth != s.depth {
        return Some(format!(
            "have different bit depths: {} against {}",
            c.depth, s.depth
        ));
    }
    if c.channels != s.channels {
        return Some(format!(
            "have different channel counts: {} against {}",
            c.channels, s.channels
        ));
    }
    None
}

/// The arm a sample belongs to, or `None` where its record names none.
///
/// A clean image has no arm by construction: it is the thing every arm is
/// measured against. `None` here means "not part of any arm", not "unknown".
fn arm_name_of(sample: &stegobench_core::samples::Sample) -> Option<&str> {
    if sample.role != Role::Stego {
        return None;
    }
    sample.arm.name.as_deref()
}

/// The index of `name` in `table`, adding it if it is new.
///
/// Linear because a corpus has tens of arms, not thousands, and a map would
/// cost more in allocation than the scan saves. Refuses to grow past
/// `u16::MAX` distinct arms rather than wrapping the index: a corpus with
/// 65,536 arms is a corrupt corpus, and a wrapped index would silently file
/// one arm's scores under another's name.
fn intern(table: &mut Vec<String>, name: Option<&str>) -> Option<u16> {
    let name = name?;
    if let Some(i) = table.iter().position(|n| n == name) {
        return u16::try_from(i).ok();
    }
    if table.len() >= u16::MAX as usize {
        return None;
    }
    table.push(name.to_string());
    u16::try_from(table.len() - 1).ok()
}

/// The time still to come, measured rather than declared.
///
/// `plan` promised twenty four minutes for a run whose first detector alone was
/// on course for two and three quarter hours, and the person waiting worked that
/// out himself from the line count of the records file, nine minutes in. By then
/// the tool had scored thirty two images and knew its own throughput better than
/// any declared figure could, and said nothing. A declared rate is a guess made
/// before the run; this is a measurement of this machine, this corpus and this
/// day.
///
/// `None` where the two agree closely enough that saying so would be noise. The
/// band is wide on purpose: a tenth of a second either way on a tool that takes
/// a second is not news, and a reader who is told their estimate has moved by
/// 10% learns to skip the line that would have told them it moved by 1,200%.
fn revised_estimate(
    scored: u64,
    left: u64,
    total: u64,
    elapsed: Duration,
    declared_total: Option<f64>,
) -> Option<String> {
    if scored == 0 {
        return None;
    }
    let per_image = elapsed.as_secs_f64() / scored as f64;
    let projected = per_image * left as f64;
    // Against the time still to come rather than against the whole run, because
    // what a reader is deciding is whether to keep waiting.
    let declared_left = declared_total.map(|d| d * (left as f64 / total.max(1) as f64));
    let out_by = declared_left.map(|d| projected / d.max(1e-9));
    if out_by.is_some_and(|r| (0.7..1.4).contains(&r)) {
        return None;
    }
    let how_long = crate::human_duration(projected);
    let measured = format!(
        "measured on this machine: {per_image:.1}s an image over the first \
         {scored} scored, so the {left} still to go will take about {how_long}"
    );
    Some(match out_by {
        Some(ratio) if ratio > 1.0 => format!(
            "{measured}, which is {ratio:.0}x what this detector's declared rate \
             predicted. The declared figure is a guess made before the run; this \
             one is what is happening"
        ),
        Some(ratio) => format!(
            "{measured}, which is {:.0}x faster than this detector's declared \
             rate predicted",
            1.0 / ratio.max(1e-9)
        ),
        None => format!(
            "{measured}. This detector declares no rate, so there was nothing to \
             estimate from beforehand"
        ),
    })
}

/// What `join` read out of a records file.
///
/// A struct rather than the tuple it used to be: four of the five fields are
/// positionally parallel sequences and a count, and a tuple lets two of them
/// swap and still compile.
struct Joined {
    scores: Vec<f64>,
    labels: Vec<bool>,
    arms: Vec<Option<u16>>,
    errored: u64,
    /// True when every answer came from a `verdict` and none from a `score`.
    ///
    /// A verdict-only detector reads as a broken one. Its records all carry
    /// `score: null`, the report says `0 unscored`, and the two look like a
    /// contradiction until somebody compares a record of this detector's with a
    /// record of a scoring one's. They are not in conflict: a verdict IS the
    /// answer, mapped to 1.0 or 0.0 here so the same arithmetic runs over both.
    answers_a_verdict: bool,
}

/// Scores and labels, joined by position.
///
/// The labels are handed in rather than re-read, because they are a property
/// of the corpus and every detector of one command shares them.
fn join(records: &Path, labels: &[bool], arms: &[Option<u16>]) -> Result<Joined, ScoreError> {
    let file = std::fs::File::open(records).map_err(|e| ScoreError::Records {
        path: records.display().to_string(),
        source: e,
    })?;
    let mut scores = Vec::new();
    let mut errored = 0;
    let mut kept = Vec::new();
    // Carried alongside rather than re-derived, because an unanswered item
    // drops out here and a per-arm count taken from the corpus afterwards
    // would claim images the detector never scored.
    let mut kept_arms = Vec::new();
    let mut any_score = false;
    for ((line, label), arm) in BufReader::new(file)
        .lines()
        .zip(labels.iter())
        .zip(arms.iter().chain(std::iter::repeat(&None)))
    {
        let Ok(line) = line else { break };
        if line.trim().is_empty() {
            continue;
        }
        let Ok(record) = serde_json::from_str::<Record>(&line) else {
            break;
        };
        if record.score.is_some() {
            any_score = true;
        }
        match record
            .score
            .or(record.verdict.map(|v| if v { 1.0 } else { 0.0 }))
        {
            Some(s) => {
                scores.push(s);
                kept.push(*label);
                kept_arms.push(*arm);
            }
            // An item the tool could not answer about is counted, never
            // guessed at. A metric computed over the survivors of a partly
            // failed run is how an evaluation misleads without anyone
            // intending it, which is why n_error is required.
            None => errored += 1,
        }
    }
    Ok(Joined {
        answers_a_verdict: !any_score && !scores.is_empty(),
        scores,
        labels: kept,
        arms: kept_arms,
        errored,
    })
}

/// One AUC per arm, each against the whole clean set.
///
/// Returns empty for a corpus with fewer than two named arms, because a
/// breakdown with one row is the headline figure printed twice and a reader
/// would reasonably read two numbers as two measurements.
fn per_arm(
    scores: &[f64],
    labels: &[bool],
    arms: &[Option<u16>],
    names: &[String],
) -> Vec<ArmMetrics> {
    let present: std::collections::BTreeSet<u16> = arms
        .iter()
        .zip(labels.iter())
        .filter(|(_, stego)| **stego)
        .filter_map(|(a, _)| *a)
        .collect();
    if present.len() < 2 {
        return Vec::new();
    }

    let clean: Vec<f64> = scores
        .iter()
        .zip(labels.iter())
        .filter(|(_, stego)| !**stego)
        .map(|(s, _)| *s)
        .collect();

    let mut out = Vec::new();
    for arm in present {
        let mut s = clean.clone();
        let mut l = vec![false; clean.len()];
        for ((score, stego), a) in scores.iter().zip(labels.iter()).zip(arms.iter()) {
            if *stego && *a == Some(arm) {
                s.push(*score);
                l.push(true);
            }
        }
        // Skipped rather than reported as zero. An arm the detector answered
        // nothing about has not been measured, and a row saying `auc: 0` for
        // it would read as a detector that got everything wrong.
        let Some(auc) = stegobench_metrics::roc_auc(&s, &l) else {
            continue;
        };
        let n_stego = l.iter().filter(|x| **x).count() as u64;
        out.push(ArmMetrics {
            arm: names
                .get(arm as usize)
                .cloned()
                .unwrap_or_else(|| arm.to_string()),
            auc,
            auc_ci95: stegobench_metrics::roc_auc_interval(&s, &l, stegobench_metrics::Z_95)
                .map(|ci| [ci.low, ci.high]),
            n_clean: clean.len() as u64,
            n_stego,
        });
    }
    out
}

/// What machine this ran on, as far as it can be established portably.
///
/// The operating system and the architecture always, because both are compile
/// time constants and both change what a number means: a detector's timing
/// certainly, and occasionally its answers, where a library dispatches on the
/// instruction set. The core count where the standard library will say. Memory
/// has no portable answer at all, and a zero there would read as a measurement
/// rather than as a gap, so it is left out.
fn host() -> Host {
    Host {
        cores: std::thread::available_parallelism()
            .ok()
            .map(|n| n.get() as u32),
        memory_gb: None,
        os: std::env::consts::OS.to_string(),
        arch: std::env::consts::ARCH.to_string(),
    }
}

/// How the subject identifies itself: an image digest, or the binary's hash.
/// The adapter that read the tool's output, hashed.
///
/// A pinned container plus an unpinned adapter is not a pinned measurement: the
/// adapter is what decides which number in the tool's output is the score, and
/// the sandbox is handed it from the host at run time. Nothing recorded it, so
/// a reader with the exact image still could not reproduce a figure.
///
/// Returns `None` where the entry needs no adapter, and also where the file
/// cannot be read or hashed. That second case is deliberate: an entry saying
/// "there was an adapter and here is its hash" and one saying nothing are
/// different statements, and a hash-shaped "unknown" would be neither.
fn adapter_ref(entry: &Entry, roots: &[PathBuf]) -> Option<AdapterRef> {
    let declared = entry.invoke.as_ref()?.adapter.as_ref()?;
    let path = stegobench_plugin::adapter::resolve(declared, roots).ok()?;
    let sha256 = stegobench_plugin::hash_file(&path).ok()?;
    Some(AdapterRef {
        declared: declared.clone(),
        sha256,
    })
}

fn pinning(entry: &Entry) -> (String, PinnedBy) {
    if let Some(image) = &entry.image {
        // AN IMAGE IS ONLY A PIN WHERE THIS HARNESS ACTUALLY RAN IT. A
        // container is started by digest, so the runtime enforces it. An entry
        // that names an image and sets `invoke.host` ran an adapter here
        // instead, against an instance somebody else started, and nothing in
        // this run checked that the instance was built from those bytes.
        // Calling that `image-digest` would tell a reader they are holding a
        // comparable-by-construction number when they are holding a claim.
        let pinned = if runs_in_container(entry) {
            PinnedBy::ImageDigest
        } else {
            PinnedBy::Unpinned
        };
        return (image.reference.clone(), pinned);
    }
    match entry
        .binary
        .as_ref()
        .and_then(|b| b.command.first())
        .and_then(|program| stegobench_plugin::which(program))
        .and_then(|path| stegobench_plugin::hash_file(&path).ok())
    {
        Some(hash) => (hash, PinnedBy::ExecutableHash),
        // The program ran and its bytes could not be hashed afterwards. Said
        // as "unpinned" rather than written as a hash-shaped "unknown" that a
        // reader could mistake for one.
        None => ("unknown".into(), PinnedBy::Unpinned),
    }
}

/// What the tool could reach, which is a different question from what pins it.
///
/// A container is started with `--network=none` and sees nothing. A service
/// entry is reached over HTTP, so the network is not merely available, it is
/// the only channel the tool is asked anything through. Anything else is a
/// program on this machine holding this machine's network.
fn isolation(entry: &Entry) -> Isolation {
    if runs_in_container(entry) {
        return Isolation::SandboxNoNetwork;
    }
    if entry
        .invoke
        .as_ref()
        .is_some_and(|i| i.host && i.endpoint_env.is_some())
    {
        return Isolation::RemoteService;
    }
    Isolation::Host
}

/// The corpus directory's own name, which is the only name it has.
fn corpus_name(path: &Path) -> String {
    path.file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("corpus")
        .to_string()
}

/// A UTC timestamp in ISO 8601, captured once per run and reused.
///
/// Written out by hand rather than by pulling in a date library. A result
/// document is read by people and by other tools, so a bare count of seconds
/// would be a number nobody can check against a log, and a dependency whose
/// only job is printing one string is a dependency to audit for ever.
///
/// The civil-date arithmetic is Howard Hinnant's days-from-civil, inverted.
/// It is exact for every date this will ever see and does not need a table.
fn now_utc() -> String {
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    iso8601(secs)
}

fn iso8601(secs: u64) -> String {
    let days = (secs / 86_400) as i64;
    let rem = secs % 86_400;
    let (h, m, s) = (rem / 3600, (rem % 3600) / 60, rem % 60);

    // Shift the epoch to 0000-03-01 so a leap day lands at the end of the
    // cycle and the month arithmetic has no special cases.
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = if month <= 2 { y + 1 } else { y };
    format!("{year:04}-{month:02}-{d:02}T{h:02}:{m:02}:{s:02}Z")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_timestamp_is_iso_8601_and_correct() {
        // A result document is read by people and by tools. This is written
        // by hand rather than by a dependency, so it is checked against dates
        // somebody can verify independently.
        assert_eq!(iso8601(0), "1970-01-01T00:00:00Z");
        assert_eq!(iso8601(1_000_000_000), "2001-09-09T01:46:40Z");
        // A leap day, which is where hand-rolled date arithmetic goes wrong.
        assert_eq!(iso8601(1_709_164_800), "2024-02-29T00:00:00Z");
        // The turn of a century that is not a leap year.
        assert_eq!(iso8601(4_102_444_800), "2100-01-01T00:00:00Z");
    }

    /// A PNG that is a real header and nothing after it.
    ///
    /// The pairing check reads headers, so a fixture of eight magic bytes would
    /// exercise only the branch where nothing can be compared. `padding` puts
    /// bytes after the header without changing what the header says, which is
    /// what a payload does to a file's size.
    fn png(width: u32, height: u32, depth: u8, colour: u8, padding: usize) -> Vec<u8> {
        let mut v = b"\x89PNG\r\n\x1a\n".to_vec();
        v.extend_from_slice(&13u32.to_be_bytes());
        v.extend_from_slice(b"IHDR");
        v.extend_from_slice(&width.to_be_bytes());
        v.extend_from_slice(&height.to_be_bytes());
        v.extend_from_slice(&[depth, colour, 0, 0, 0]);
        v.extend_from_slice(&[0, 0, 0, 0]);
        v.extend_from_slice(&vec![0u8; padding]);
        v
    }

    fn corpus(root: &Path, clean: usize, stego: usize) {
        std::fs::create_dir_all(root).expect("corpus");
        for i in 0..clean {
            std::fs::write(root.join(format!("c{i:03}.png")), png(32, 32, 8, 2, 0)).unwrap();
            std::fs::write(
                root.join(format!("c{i:03}.json")),
                r#"{"role":"clean","sha256":"0"}"#,
            )
            .unwrap();
        }
        for i in 0..stego {
            // Same header, more bytes. A payload changes the file, not its
            // shape, which is the whole premise of the pairing check.
            std::fs::write(root.join(format!("s{i:03}.png")), png(32, 32, 8, 2, 64)).unwrap();
            std::fs::write(
                root.join(format!("s{i:03}.json")),
                r#"{"role":"stego","source_png":"c000.png","sha256":"0"}"#,
            )
            .unwrap();
        }
    }

    fn request(dir: &Path, limit: Option<u64>) -> Request<'_> {
        Request {
            corpus: dir,
            registered: None,
            trained_on: None,
            adapter_roots: &[],
            records: dir.with_extension("records.jsonl"),
            timeout: Duration::from_secs(5),
            jobs: 1,
            keep_raw: false,
            seed: None,
            fixtures: None,
            limit,
            split: None,
        }
    }

    /// Rung 5: `contaminated: false` is a positive claim, and `cp -r` produces
    /// it on a byte-identical corpus with an identical digest because the names
    /// stop matching. The run says so in the terminal; the document said only
    /// `false`.
    #[cfg(unix)]
    #[test]
    fn a_declaration_that_could_not_be_checked_says_so_rather_than_reading_as_clean() {
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 3, 3);
        let entry = sizing_detector(tmp.path());

        let mut req = request(&root, None);
        req.trained_on = Some("some-other-corpus");
        let result = score(&entry, &req, |_| {}).expect("scores").0;

        assert!(
            !result.declarations.contaminated,
            "the names do not match, so this is not a proven contamination"
        );
        assert_eq!(
            result.declarations.contamination_check,
            stegobench_core::result::ContaminationCheck::DeclaredButUncheckable,
            "`false` was published as though the check had run"
        );
        assert_eq!(
            result.declarations.trained_on.as_deref(),
            Some("some-other-corpus"),
            "the declaration itself was dropped"
        );
    }

    /// Nobody declared anything, so there is nothing to be unsure about, and
    /// the uncheckable value must not become the default.
    #[cfg(unix)]
    #[test]
    fn a_run_with_no_declaration_is_not_marked_uncheckable() {
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 3, 3);
        let entry = sizing_detector(tmp.path());
        let result = score(&entry, &request(&root, None), |_| {})
            .expect("scores")
            .0;
        assert_eq!(
            result.declarations.contamination_check,
            stegobench_core::result::ContaminationCheck::NotDeclared
        );
    }

    /// Rung 5: `--split test` and a whole-corpus run produced identical
    /// documents, and the only split related field in either read `by-cover`.
    #[cfg(unix)]
    #[test]
    fn the_document_says_which_side_of_the_split_was_scored() {
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        split_corpus(&root, false);
        let entry = sizing_detector(tmp.path());

        let mut req = request(&root, None);
        req.split = Some("test");
        req.records = root.with_extension("test.records.jsonl");
        let held_out = score(&entry, &req, |_| {}).expect("scores").0;
        assert_eq!(held_out.declarations.split_scored.as_deref(), Some("test"));

        let whole = score(&entry, &request(&root, None), |_| {})
            .expect("scores")
            .0;
        assert_eq!(
            whole.declarations.split_scored, None,
            "a whole corpus run claimed a side"
        );
        assert_ne!(
            held_out.declarations, whole.declarations,
            "the two runs are still indistinguishable in the document"
        );
    }

    /// Rung 5, spotted by the researcher in thirty seconds of looking at a
    /// directory and never by the tool: the clean class is one format and the
    /// stego class another, so telling the formats apart scores 1.0 without
    /// detecting anything. No pair comparison reaches this.
    #[cfg(unix)]
    #[test]
    fn a_corpus_whose_two_classes_are_different_formats_says_so() {
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        // Clean side PNG, stego side JPEG, and no clean half stated, which is
        // exactly the shape he was handed.
        std::fs::create_dir_all(&root).unwrap();
        for i in 0..3 {
            std::fs::write(root.join(format!("c{i}.png")), png(64, 64, 8, 2, i)).unwrap();
            std::fs::write(
                root.join(format!("c{i}.json")),
                format!(r#"{{"role":"clean","sha256":"{i}"}}"#),
            )
            .unwrap();
            std::fs::write(root.join(format!("s{i}.jpg")), jpeg(64, 64)).unwrap();
            std::fs::write(
                root.join(format!("s{i}.json")),
                format!(
                    r#"{{"role":"stego","sha256":"s{i}","arm":{{"tool":"steghide"}},"clean":"nowhere/{i}.jpg","clean_sha256":"absent{i}"}}"#
                ),
            )
            .unwrap();
        }
        let entry = sizing_detector(tmp.path());

        let mut said = Vec::new();
        let result = score(&entry, &request(&root, None), |m: &str| {
            said.push(m.to_string())
        })
        .expect("scores")
        .0;

        assert_eq!(result.arm.clean_format.as_deref(), Some("png"));
        assert_eq!(result.arm.format, "jpeg");
        assert!(
            said.iter()
                .any(|m| m.contains("every clean image here is png and every stego image is jpeg")),
            "nothing said the two classes are different formats: {said:?}"
        );
        assert!(
            said.iter().any(|m| m.contains("not evidence of")),
            "the warning did not say what it means: {said:?}"
        );
    }

    /// And a corpus whose two classes are the same format is not warned about,
    /// because a warning that fires on every ordinary corpus is noise.
    #[cfg(unix)]
    #[test]
    fn a_corpus_of_one_format_throughout_is_not_warned_about() {
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 3, 3);
        let entry = sizing_detector(tmp.path());
        let mut said = Vec::new();
        score(&entry, &request(&root, None), |m: &str| {
            said.push(m.to_string())
        })
        .expect("scores");
        assert!(
            !said.iter().any(|m| m.contains("every clean image here is")),
            "{said:?}"
        );
    }

    #[test]
    fn the_feed_hands_out_one_item_at_a_time_in_corpus_order() {
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 2, 2);
        let feed = Feed::filtered(&root, None, None).expect("opens");
        let ids: Vec<String> = feed.map(|w| w.id).collect();
        assert_eq!(ids, ["c000", "c001", "s000", "s001"]);
    }

    #[test]
    fn a_limit_stops_the_feed_early() {
        // The smoke-test path. It is also why such a run is marked custom: a
        // prefix of a corpus is not the corpus.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 4, 4);
        let feed = Feed::filtered(&root, Some(3), None).expect("opens");
        assert_eq!(feed.count(), 3);
    }

    #[test]
    fn a_corpus_defect_stops_the_feed_and_is_kept_rather_than_read_as_the_end() {
        // The difference between "scored everything" and "scored as far as
        // the broken file" is invisible from outside an iterator, and they
        // are very different claims about a number.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 2, 2);
        // An image with no record beside it.
        std::fs::write(root.join("orphan.png"), b"\x89PNG\r\n\x1a\n").unwrap();
        let mut feed = Feed::filtered(&root, None, None).expect("opens");
        let seen = feed.by_ref().count();
        assert!(
            feed.fault.is_some(),
            "a defect was read as the end, after {seen}"
        );
    }

    #[cfg(unix)]
    /// A detector that scores by file size, so a test can measure without
    /// installing anything.
    fn sizing_detector(dir: &Path) -> Entry {
        use std::os::unix::fs::PermissionsExt;
        let script = dir.join("size.sh");
        std::fs::write(
            &script,
            "#!/bin/sh\n[ \"$1\" = \"--version\" ] && { echo v1; exit 0; }\n\
             wc -c < \"$1\" | tr -d ' ' | awk '{print $1/1000}'\n",
        )
        .unwrap();
        let mut perms = std::fs::metadata(&script).unwrap().permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&script, perms).unwrap();
        toml::from_str(&format!(
            "name = \"sizer\"\nkind = \"detector\"\nlicence = \"MIT\"\n\
             [binary]\ncommand = [{:?}]\nversion_args = [\"--version\"]\n\
             [emits]\noutput = \"score\"\nhigher_means_stego = true\n\
             [invoke]\nargv = [\"{{file}}\"]\nparser = \"number\"\n\
             [selftest]\nmust_detect = \"fixtures/a.png\"\nmust_clear = \"fixtures/b.png\"\n",
            script.display().to_string()
        ))
        .expect("parses")
    }

    #[cfg(unix)]
    #[test]
    fn two_runs_over_the_same_corpus_agree_on_every_number() {
        // Baseline Section 2.1 asks for byte-identical output from two runs,
        // and a result document cannot give that: it records when the run
        // started and how long it took, and those genuinely differ. So what
        // is asserted is the part a reader acts on. If the metrics moved
        // between two runs over unchanged bytes, the measurement would not be
        // a measurement.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 3, 3);
        let entry = sizing_detector(tmp.path());

        let first = score(&entry, &request(&root, None), |_| {})
            .expect("first run")
            .0;
        // A second records file, so the second run genuinely re-scores rather
        // than resuming and agreeing with itself by construction.
        let mut second_request = request(&root, None);
        second_request.records = root.with_extension("second.jsonl");
        let second = score(&entry, &second_request, |_| {})
            .expect("second run")
            .0;

        assert_eq!(first.metrics, second.metrics);
        assert_eq!(first.corpus, second.corpus);
        assert_eq!(first.declarations, second.declarations);
        assert_eq!(first.subject, second.subject);
    }

    /// A detector that prints nothing at all, successfully.
    #[cfg(unix)]
    fn silent_detector(dir: &Path) -> Entry {
        use std::os::unix::fs::PermissionsExt;
        let script = dir.join("silent.sh");
        std::fs::write(
            &script,
            "#!/bin/sh\n[ \"$1\" = \"--version\" ] && { echo v1; exit 0; }\nexit 0\n",
        )
        .unwrap();
        let mut perms = std::fs::metadata(&script).unwrap().permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&script, perms).unwrap();
        toml::from_str(&format!(
            "name = \"mute\"\nkind = \"detector\"\nlicence = \"MIT\"\n\
             [binary]\ncommand = [{:?}]\nversion_args = [\"--version\"]\n\
             [emits]\noutput = \"score\"\nhigher_means_stego = true\n\
             [invoke]\nargv = [\"{{file}}\"]\nparser = \"number\"\n\
             [selftest]\nmust_detect = \"fixtures/a.png\"\nmust_clear = \"fixtures/b.png\"\n",
            script.display().to_string()
        ))
        .expect("parses")
    }

    /// Rung 5 of the journey round: a plugin that printed nothing was refused,
    /// correctly, with a message saying the researcher's ten-clean, ten-stego
    /// corpus held "0 clean and 0 stego image(s)". He said he would have spent
    /// twenty minutes auditing the corpus before suspecting his own adapter.
    #[cfg(unix)]
    #[test]
    fn a_detector_that_answered_nothing_is_blamed_rather_than_the_corpus() {
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 3, 3);
        let entry = silent_detector(tmp.path());

        let err = score(&entry, &request(&root, None), |_| {}).expect_err("refused");
        let said = err.to_string();
        assert_eq!(err.reason(), "nothing-answered", "{said}");
        assert!(
            said.contains("3 clean and 3 stego"),
            "the corpus was reported as empty: {said}"
        );
        assert!(
            said.contains("The corpus is not the problem here"),
            "nothing pointed at the tool: {said}"
        );
        assert!(said.contains("mute"), "the tool is not named: {said}");
        assert!(
            said.contains("--keep-raw"),
            "no way to see what the tool printed: {said}"
        );
    }

    /// And a corpus that genuinely has one side keeps the refusal that blames
    /// the corpus, so the two cannot collapse into one.
    #[cfg(unix)]
    #[test]
    fn a_corpus_with_only_one_side_is_still_the_thing_blamed() {
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 3, 0);
        let entry = sizing_detector(tmp.path());

        let err = score(&entry, &request(&root, None), |_| {}).expect_err("refused");
        assert_eq!(err.reason(), "one-sided", "{err}");
    }

    /// A detector that gives the same answer to every image.
    #[cfg(unix)]
    fn constant_detector(dir: &Path) -> Entry {
        use std::os::unix::fs::PermissionsExt;
        let script = dir.join("constant.sh");
        std::fs::write(
            &script,
            "#!/bin/sh\n[ \"$1\" = \"--version\" ] && { echo v1; exit 0; }\necho 0.5\n",
        )
        .unwrap();
        let mut perms = std::fs::metadata(&script).unwrap().permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&script, perms).unwrap();
        toml::from_str(&format!(
            "name = \"constant\"\nkind = \"detector\"\nlicence = \"MIT\"\n\
             [binary]\ncommand = [{:?}]\nversion_args = [\"--version\"]\n\
             [emits]\noutput = \"score\"\nhigher_means_stego = true\n\
             [invoke]\nargv = [\"{{file}}\"]\nparser = \"number\"\n\
             [selftest]\nmust_detect = \"fixtures/a.png\"\nmust_clear = \"fixtures/b.png\"\n",
            script.display().to_string()
        ))
        .expect("parses")
    }

    #[test]
    fn an_estimate_twelve_times_out_is_corrected_in_the_direction_it_is_wrong() {
        // The measurement that produced this: 32 images in 9.5 minutes against a
        // declared floor of 13 minutes for 553. The reader worked out the 12x
        // himself and the tool, which had the same two numbers, said nothing.
        let said = revised_estimate(
            32,
            521,
            553,
            Duration::from_secs_f64(570.0),
            Some(1.4 * 553.0),
        )
        .expect("a 12x miss is worth saying");
        assert!(said.contains("measured on this machine"), "{said}");
        assert!(
            said.contains("13x what this detector's declared rate predicted"),
            "{said}"
        );
        assert!(
            said.contains("2.6 hours"),
            "the projection is missing: {said}"
        );
    }

    #[test]
    fn an_estimate_that_was_about_right_says_nothing_at_all() {
        assert_eq!(
            revised_estimate(
                20,
                80,
                100,
                Duration::from_secs_f64(20.0),
                Some(1.0 * 100.0)
            ),
            None,
            "a run going to plan interrupted the reader to say so"
        );
    }

    #[test]
    fn a_run_faster_than_promised_is_also_worth_saying() {
        let said = revised_estimate(
            50,
            50,
            100,
            Duration::from_secs_f64(5.0),
            Some(10.0 * 100.0),
        )
        .expect("a 100x overestimate is worth saying");
        assert!(said.contains("faster"), "{said}");
    }

    #[test]
    fn a_detector_declaring_no_rate_gets_a_measurement_rather_than_a_comparison() {
        let said = revised_estimate(16, 984, 1000, Duration::from_secs_f64(160.0), None)
            .expect("a measurement stands on its own");
        assert!(said.contains("declares no rate"), "{said}");
        assert!(said.contains("2.7 hours"), "{said}");
    }

    #[test]
    fn nothing_is_claimed_before_anything_has_been_scored() {
        assert_eq!(
            revised_estimate(0, 100, 100, Duration::from_secs_f64(30.0), Some(100.0)),
            None,
            "a rate was divided by zero images"
        );
    }

    /// A detector that answers yes or no, and whose answer varies.
    ///
    /// Varies deliberately, so the identical-answers warning stays silent and
    /// the verdict notice is the only thing the test can be reading.
    #[cfg(unix)]
    fn verdict_detector(dir: &Path) -> Entry {
        use std::os::unix::fs::PermissionsExt;
        let script = dir.join("verdict.sh");
        std::fs::write(
            &script,
            "#!/bin/sh\n[ \"$1\" = \"--version\" ] && { echo v1; exit 0; }\n\
             case \"$1\" in *s*) echo \"[?] b1,lsb,bY .. text: hello\" ;; esac\n",
        )
        .unwrap();
        let mut perms = std::fs::metadata(&script).unwrap().permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&script, perms).unwrap();
        toml::from_str(&format!(
            "name = \"verdicter\"\nkind = \"detector\"\nlicence = \"MIT\"\n\
             [binary]\ncommand = [{:?}]\nversion_args = [\"--version\"]\n\
             [emits]\noutput = \"verdict\"\n\
             [invoke]\nargv = [\"{{file}}\"]\nparser = \"zsteg\"\n\
             [selftest]\nmust_detect = \"fixtures/a.png\"\nmust_clear = \"fixtures/b.png\"\n",
            script.display().to_string()
        ))
        .expect("parses")
    }

    #[cfg(unix)]
    #[test]
    fn a_verdict_only_detector_says_so_rather_than_reading_as_a_gap() {
        // Rung 3 of the journey round: every zsteg record said `score: null`
        // while the report said `0 unscored`, and the persona spent a while
        // deciding which of the two was the bug before working out that neither
        // was. He only got there by diffing a record of zsteg's against one of
        // stegexpose's by hand.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 3, 3);
        let entry = verdict_detector(tmp.path());

        let mut said = Vec::new();
        let result = score(&entry, &request(&root, None), |m: &str| {
            said.push(m.to_string())
        })
        .expect("a verdict detector still produces a result")
        .0;

        assert_eq!(result.metrics.n_error, 0, "a verdict is an answer");
        assert!(
            said.iter().any(|m| m.contains("not a gap")),
            "nothing explained the null scores: {said:?}"
        );
        assert!(
            said.iter().any(|m| m.contains("no threshold to choose")),
            "nothing said a verdict detector has no cutoff: {said:?}"
        );
        assert!(
            result.metrics.threshold_at_fpr.is_empty()
                || result
                    .metrics
                    .threshold_at_fpr
                    .values()
                    .all(|t| *t == 0.0 || *t == 1.0),
            "a verdict detector's only cutoffs are its two answers: {:?}",
            result.metrics.threshold_at_fpr
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_scoring_detector_is_not_told_it_answers_a_verdict() {
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 3, 3);
        let entry = sizing_detector(tmp.path());

        let mut said = Vec::new();
        score(&entry, &request(&root, None), |m: &str| {
            said.push(m.to_string())
        })
        .expect("scores");

        assert!(
            !said.iter().any(|m| m.contains("not a gap")),
            "a scoring detector was told it answers a verdict: {said:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn one_answer_to_everything_is_named_rather_than_published_as_chance() {
        // The case this exists for, measured on the first end to end run this
        // project did: zsteg answered `false` for all 18 images of the starter
        // corpus, 12 of them stego, and the run said `AUC 0.5000 ... 0
        // unanswered`. Every number was right. Nothing said the detector had
        // not separated anything, and AUC 0.5 from one repeated answer reads
        // identically to AUC 0.5 from a detector ranking at chance.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 3, 3);
        let entry = constant_detector(tmp.path());

        let mut said = Vec::new();
        let result = score(&entry, &request(&root, None), |m: &str| {
            said.push(m.to_string())
        })
        .expect("a constant detector still produces a result")
        .0;

        // The figure itself is honest and stays: 0.5 is what a set of ties is.
        assert!(
            (result.metrics.auc - 0.5).abs() < 1e-12,
            "{:?}",
            result.metrics
        );
        assert_eq!(result.metrics.n_error, 0, "it answered every image");

        let warned = said.iter().any(|m| m.contains("identical"));
        assert!(
            warned,
            "nothing said the answers were all the same: {said:?}"
        );
        assert!(
            said.iter().any(|m| m.contains("by construction")),
            "the warning does not say why the 0.5 is not a measurement: {said:?}"
        );
    }

    /// The leaderboard rejects a detector that trained on the corpus it was
    /// scored against, and the harness had no way to say so: `trained_on` was
    /// written as `None` whatever the run was. An honest submitter had to
    /// hand-edit a machine-produced document to declare it, which is the one
    /// thing the submission rules treat as suspect. The flag exists so the
    /// honest answer is the easy one.
    #[cfg(unix)]
    #[test]
    fn a_declared_training_corpus_is_recorded_and_the_self_scored_case_is_warned_about() {
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 3, 3);
        let entry = sizing_detector(tmp.path());
        let registered = registered_corpus(None);

        // Declared as trained on something else: recorded, and not a warning.
        let mut elsewhere = request(&root, None);
        elsewhere.registered = Some(&registered);
        elsewhere.trained_on = Some("some-other-corpus");
        let mut said = Vec::new();
        let result = score(&entry, &elsewhere, |m: &str| said.push(m.to_string()))
            .expect("a result")
            .0;
        assert_eq!(
            result.declarations.trained_on.as_deref(),
            Some("some-other-corpus"),
            "the declaration did not reach the document"
        );
        assert!(
            !said.iter().any(|m| m.contains("WARNING")),
            "training on a different corpus is not a warning: {said:?}"
        );

        // Declared as trained on the corpus being scored: still recorded, and
        // said out loud, because the person running it is the last one who can
        // decide not to quote the number.
        let root2 = tmp.path().join("corpus2");
        corpus(&root2, 3, 3);
        let mut itself = request(&root2, None);
        itself.registered = Some(&registered);
        itself.trained_on = Some("example");
        let mut said = Vec::new();
        let result = score(&entry, &itself, |m: &str| said.push(m.to_string()))
            .expect("a result")
            .0;
        assert_eq!(result.declarations.trained_on.as_deref(), Some("example"));
        assert!(
            said.iter()
                .any(|m| m.contains("WARNING") && m.contains("scored against")),
            "scoring a detector on what it trained on has to say so: {said:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_detector_that_separates_the_images_is_not_warned_about() {
        // The other half, so the warning cannot be made to pass by always
        // firing. The sizing detector gives stego and clean different scores.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 3, 3);
        let entry = sizing_detector(tmp.path());

        let mut said = Vec::new();
        score(&entry, &request(&root, None), |m: &str| {
            said.push(m.to_string())
        })
        .expect("run");
        assert!(
            !said.iter().any(|m| m.contains("identical")),
            "warned about a detector that did separate the images: {said:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_resumed_run_reports_the_same_numbers_as_an_uninterrupted_one() {
        // The failure this prevents is the worst kind: a resumed run that
        // quietly measures less than it claims, because the resumed items
        // were counted as done but never joined to their labels.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 3, 3);
        let entry = sizing_detector(tmp.path());

        let whole = score(&entry, &request(&root, None), |_| {})
            .expect("whole")
            .0;

        // Score part, then finish, against one records file. The limit has to
        // reach past the clean images: enumeration is sorted, so a limit of
        // three here would score `c000` to `c002` and nothing else, and a
        // one-sided run is correctly refused before it can be resumed.
        let mut partial = request(&root, Some(4));
        partial.records = root.with_extension("resumed.jsonl");
        score(&entry, &partial, |_| {}).expect("partial");
        let mut rest = request(&root, None);
        rest.records = partial.records.clone();
        let (resumed, tally) = score(&entry, &rest, |_| {}).expect("resumed");

        assert_eq!(tally.resumed, 4, "the scored part should have been reused");
        assert_eq!(whole.metrics, resumed.metrics);
    }

    /// A corpus carrying split labels, with one knob: whether the stego rows
    /// agree with their covers.
    fn split_corpus(root: &Path, leak: bool) {
        std::fs::create_dir_all(root).expect("corpus");
        for i in 0..3 {
            let split = if i == 0 { "test" } else { "train" };
            std::fs::write(root.join(format!("c{i}.png")), png(32, 32, 8, 2, 0)).unwrap();
            std::fs::write(
                root.join(format!("c{i}.json")),
                format!(r#"{{"role":"clean","split":"{split}","sha256":"0"}}"#),
            )
            .unwrap();

            // The leak puts the stego twin of cover 0 on the other side.
            let stego_split = if leak && i == 0 { "train" } else { split };
            std::fs::write(root.join(format!("s{i}.png")), png(32, 32, 8, 2, 64)).unwrap();
            std::fs::write(
                root.join(format!("s{i}.json")),
                format!(
                    r#"{{"role":"stego","source_png":"c{i}.png","split":"{stego_split}","sha256":"0"}}"#
                ),
            )
            .unwrap();
        }
    }

    #[test]
    fn a_corpus_that_keeps_twins_together_is_reported_as_by_cover() {
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        split_corpus(&root, false);
        let checks = check(&root).expect("checked");
        assert!(
            checks.split_leaks.is_empty(),
            "{}",
            checks.split_leaks.examples()
        );
        assert_eq!(checks.split, SplitDiscipline::ByCover);
    }

    #[cfg(unix)]
    #[test]
    fn a_cover_split_from_its_twin_stops_the_run() {
        // The whole reason the check exists. A photograph on both sides of the
        // boundary inflates every number computed from the corpus, and the
        // inflation is invisible in the output, so a confident wrong answer is
        // the alternative to refusing.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        split_corpus(&root, true);

        let checks = check(&root).expect("checked");
        assert_eq!(checks.split_leaks.count, 1);
        assert!(
            checks.split_leaks.examples().contains("c0.png"),
            "{}",
            checks.split_leaks.examples()
        );

        let entry = sizing_detector(tmp.path());
        let err = score(&entry, &request(&root, None), |_| {}).expect_err("refused");
        assert!(err.to_string().contains("different side"), "{err}");
    }

    #[cfg(unix)]
    #[test]
    fn scoring_the_test_half_leaves_the_train_half_out_and_says_which_it_used() {
        // The point of the flag. A detector trained on this corpus can only
        // be measured on the half it never saw, and the number is worthless
        // unless the document says which half that was: a reader comparing
        // two results cannot tell a held-out score from a whole-corpus one
        // by looking at the figure.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        split_corpus(&root, false);

        let prepared = prepare(&root, None, None, None, Some("test"), |_| {}).expect("prepared");
        assert_eq!(prepared.side, Some(Side::Test));
        // Cover 0 and its twin are the test half; the other two pairs are not.
        assert_eq!(prepared.items(), 2);
        assert_eq!(prepared.keep, [true, false, false, true, false, false]);

        let entry = sizing_detector(tmp.path());
        let (doc, _) = score_one(
            &entry,
            &prepared,
            &root.with_extension("t.jsonl"),
            How {
                timeout: Duration::from_secs(5),
                jobs: 1,
                keep_raw: false,
                seed: None,
                fixtures: None,
                adapter_roots: &[],
            },
            |_| {},
        )
        .expect("scored");
        assert_eq!(doc.corpus.split.as_deref(), Some("test"));
        assert_eq!(doc.corpus.pairs, 1, "one stego image in the test half");
    }

    #[cfg(unix)]
    #[test]
    fn scoring_the_train_half_covers_the_samples_the_test_half_did_not() {
        // The two halves partition the corpus. If they overlapped, a detector
        // could be trained and measured on the same photograph without either
        // command saying anything was wrong.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        split_corpus(&root, false);

        let test = prepare(&root, None, None, None, Some("test"), |_| {}).expect("test half");
        let train = prepare(&root, None, None, None, Some("train"), |_| {}).expect("train half");
        assert_eq!(train.side, Some(Side::Train));
        assert_eq!(train.items(), 4);
        for (a, b) in test.keep.iter().zip(train.keep.iter()) {
            assert!(
                !(*a && *b),
                "a sample landed in both halves: {:?}",
                test.keep
            );
        }
        let both: Vec<bool> = test
            .keep
            .iter()
            .zip(train.keep.iter())
            .map(|(a, b)| *a || *b)
            .collect();
        assert!(both.iter().all(|x| *x), "a sample landed in neither half");
    }

    #[test]
    fn two_arms_are_measured_separately_against_the_shared_clean_set() {
        // Detection at one payload rate and at another are different
        // questions. Pooling them answers neither: the headline lands
        // between the two and describes no arm that exists.
        let names = vec!["weak-0100".to_string(), "loud-0400".to_string()];
        // Two clean, then two of each arm. The loud arm is separable and the
        // weak one is not, which is the shape a real corpus has.
        let scores = vec![0.1, 0.2, 0.15, 0.25, 0.9, 0.95];
        let labels = vec![false, false, true, true, true, true];
        let arms = vec![None, None, Some(0), Some(0), Some(1), Some(1)];

        let rows = per_arm(&scores, &labels, &arms, &names);
        assert_eq!(rows.len(), 2, "{rows:?}");
        let weak = rows.iter().find(|r| r.arm == "weak-0100").expect("weak");
        let loud = rows.iter().find(|r| r.arm == "loud-0400").expect("loud");

        assert_eq!(weak.n_clean, 2);
        assert_eq!(weak.n_stego, 2);
        assert_eq!(loud.n_clean, 2, "the clean set is shared, not divided");
        assert_eq!(loud.n_stego, 2);
        assert!(
            loud.auc > weak.auc,
            "the separable arm should score higher: {rows:?}"
        );
        assert_eq!(loud.auc, 1.0);
    }

    #[test]
    fn one_arm_gets_no_breakdown_because_it_would_be_the_headline_twice() {
        let names = vec!["only-0100".to_string()];
        let scores = vec![0.1, 0.9];
        let labels = vec![false, true];
        let arms = vec![None, Some(0)];
        assert!(per_arm(&scores, &labels, &arms, &names).is_empty());
    }

    #[test]
    fn a_corpus_whose_records_name_no_arm_gets_no_breakdown() {
        let scores = vec![0.1, 0.2, 0.9, 0.95];
        let labels = vec![false, false, true, true];
        let arms = vec![None, None, None, None];
        assert!(per_arm(&scores, &labels, &arms, &[]).is_empty());
    }

    #[test]
    fn an_arm_the_detector_answered_nothing_about_is_left_out_not_scored_zero() {
        // A row saying `auc: 0` would read as a detector that got everything
        // wrong, which is a claim about the detector. Nothing was measured.
        let names = vec!["a".to_string(), "b".to_string(), "c".to_string()];
        let scores = vec![0.1, 0.9, 0.8];
        let labels = vec![false, true, true];
        let arms = vec![None, Some(0), Some(1)];
        let rows = per_arm(&scores, &labels, &arms, &names);
        assert_eq!(rows.len(), 2);
        assert!(!rows.iter().any(|r| r.arm == "c"), "{rows:?}");
    }

    #[test]
    fn the_arm_table_holds_one_entry_per_distinct_name_however_often_it_repeats() {
        // The scale rule: a Core tier is 344,357 samples over 39 arms, and
        // holding the name on every sample is tens of megabytes to answer a
        // question with 39 answers.
        let mut table = Vec::new();
        for _ in 0..1000 {
            assert_eq!(intern(&mut table, Some("wow-0200")), Some(0));
            assert_eq!(intern(&mut table, Some("hill-0400")), Some(1));
        }
        assert_eq!(table.len(), 2);
        assert_eq!(intern(&mut table, None), None);
        assert_eq!(table.len(), 2, "None must not become an arm");
    }

    /// Collects what `score_one` said, so a test can assert on the words a
    /// user actually reads rather than on a field they never see.
    #[cfg(unix)]
    fn said(entry: &Entry, prepared: &Prepared, records: &Path) -> String {
        let mut lines = Vec::new();
        let _ = score_one(
            entry,
            prepared,
            records,
            How {
                timeout: Duration::from_secs(5),
                jobs: 1,
                keep_raw: false,
                seed: None,
                fixtures: None,
                adapter_roots: &[],
            },
            |m| lines.push(m.to_string()),
        );
        lines.join("\n")
    }

    #[cfg(unix)]
    #[test]
    fn a_budget_the_corpus_cannot_express_is_said_out_loud() {
        // The finding: `TPR@1%FA` over six clean images is `TPR@0%FA` wearing
        // a better name, and an engineer picking a review threshold reads
        // that column and nothing else. The figure stays; the claim over it
        // gets qualified where the reader meets it.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 3, 3);
        let prepared = prepare(&root, None, None, None, None, |_| {}).expect("prepared");
        let entry = sizing_detector(tmp.path());
        let text = said(&entry, &prepared, &root.with_extension("u.jsonl"));
        assert!(
            text.contains("cannot express a false-alarm budget finer than"),
            "{text}"
        );
        assert!(text.contains("1%"), "the budgets should be named: {text}");
        assert!(
            text.contains("The number is real"),
            "it must not read as the figure being wrong: {text}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_corpus_large_enough_for_the_budget_is_not_warned_about() {
        // A warning that fires every time is one a reader stops seeing, which
        // is the fault this whole journey kept turning up.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 120, 120);
        let prepared = prepare(&root, None, None, None, None, |_| {}).expect("prepared");
        let entry = sizing_detector(tmp.path());
        let text = said(&entry, &prepared, &root.with_extension("v.jsonl"));
        assert!(
            !text.contains("cannot express a false-alarm budget"),
            "120 clean images can express 1%: {text}"
        );
    }

    #[test]
    fn a_budget_is_expressible_exactly_when_one_clean_image_fits_inside_it() {
        // The rule itself, without a corpus in the way. One image in a
        // hundred is 1%, so a hundred clean images can just express it and
        // ninety-nine cannot.
        assert!(stegobench_metrics::fpr_resolution(100) <= 0.01);
        assert!(stegobench_metrics::fpr_resolution(99) > 0.01);
    }

    #[test]
    fn a_whole_corpus_run_records_no_split_rather_than_guessing_one() {
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        split_corpus(&root, false);
        let prepared = prepare(&root, None, None, None, None, |_| {}).expect("prepared");
        assert_eq!(prepared.side, None);
        assert_eq!(prepared.items(), 6);
    }

    #[test]
    fn asking_for_a_half_of_a_corpus_that_has_none_is_refused() {
        // Inventing a split here would put a cover and its twin on opposite
        // sides, which is the exact fault the whole split discipline exists
        // to prevent. Silently scoring everything instead would be worse: the
        // caller asked for a held-out number and would get a whole-corpus one.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 2, 2);
        let err = prepare(&root, None, None, None, Some("test"), |_| {})
            .err()
            .expect("refused");
        assert!(err.to_string().contains("no train and test split"), "{err}");
        assert_eq!(err.exit_code(), 3);
    }

    #[test]
    fn a_side_that_is_not_a_side_is_a_usage_error_naming_both_halves() {
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        split_corpus(&root, false);
        let err = prepare(&root, None, None, None, Some("holdout"), |_| {})
            .err()
            .expect("refused");
        let text = err.to_string();
        assert!(text.contains("holdout"), "{text}");
        assert!(text.contains("train") && text.contains("test"), "{text}");
        assert_eq!(err.exit_code(), 2);
    }

    #[test]
    fn a_half_holding_one_class_is_refused_and_the_message_names_the_half() {
        // A filter can make a two-class corpus one-sided, and the refusal
        // then has to say the half rather than the corpus: the directory is
        // fine and re-running without --split would work.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        std::fs::create_dir_all(&root).unwrap();
        // The test half is a lone clean image; both stego images are train.
        for (name, body) in [
            ("c0.json", r#"{"role":"clean","split":"test","sha256":"0"}"#),
            (
                "c1.json",
                r#"{"role":"clean","split":"train","sha256":"0"}"#,
            ),
        ] {
            std::fs::write(root.join(name), body).unwrap();
        }
        std::fs::write(root.join("c0.png"), png(32, 32, 8, 2, 0)).unwrap();
        std::fs::write(root.join("c1.png"), png(32, 32, 8, 2, 0)).unwrap();
        std::fs::write(root.join("s1.png"), png(32, 32, 8, 2, 64)).unwrap();
        std::fs::write(
            root.join("s1.json"),
            r#"{"role":"stego","source_png":"c1.png","split":"train","sha256":"0"}"#,
        )
        .unwrap();

        let err = prepare(&root, None, None, None, Some("test"), |_| {})
            .err()
            .expect("refused");
        let text = err.to_string();
        assert!(text.contains("test split"), "{text}");
        assert!(text.contains("has not been measured"), "{text}");
    }

    #[test]
    fn a_corpus_with_no_split_labels_says_not_applicable_rather_than_by_cover() {
        // "No split applies" and "the split was checked and held" are
        // different facts, and a directory of loose samples is an ordinary
        // thing to score.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 2, 2);
        let checks = check(&root).expect("checked");
        assert!(checks.split_leaks.is_empty());
        assert_eq!(checks.split, SplitDiscipline::NotApplicable);
    }

    #[test]
    fn a_stego_row_inheriting_its_cover_split_is_not_a_violation() {
        // Arm rows in the real corpus carry no split of their own, precisely
        // because the split is a property of the cover. Reading that absence
        // as a disagreement would refuse every correctly built corpus.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("c0.png"), png(32, 32, 8, 2, 0)).unwrap();
        std::fs::write(
            root.join("c0.json"),
            r#"{"role":"clean","split":"test","sha256":"0"}"#,
        )
        .unwrap();
        std::fs::write(root.join("s0.png"), png(32, 32, 8, 2, 64)).unwrap();
        std::fs::write(
            root.join("s0.json"),
            r#"{"role":"stego","source_png":"c0.png","sha256":"0"}"#,
        )
        .unwrap();
        let checks = check(&root).expect("checked");
        assert!(
            checks.split_leaks.is_empty(),
            "{}",
            checks.split_leaks.examples()
        );
        assert_eq!(checks.split, SplitDiscipline::ByCover);
    }

    /// A corpus of one pair, where the test chooses what the stego image is.
    fn pair(root: &Path, stego_image: &[u8]) {
        std::fs::create_dir_all(root).expect("corpus");
        std::fs::write(root.join("c0.png"), png(64, 64, 8, 2, 0)).unwrap();
        std::fs::write(root.join("c0.json"), r#"{"role":"clean","sha256":"0"}"#).unwrap();
        std::fs::write(root.join("s0.png"), stego_image).unwrap();
        std::fs::write(
            root.join("s0.json"),
            r#"{"role":"stego","source_png":"c0.png","sha256":"0"}"#,
        )
        .unwrap();
    }

    #[test]
    fn a_stego_image_shaped_like_its_cover_is_reported_as_single_variable() {
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        pair(&root, &png(64, 64, 8, 2, 128));
        let checks = check(&root).expect("checked");
        assert!(checks.pairing_breaks.is_empty());
        assert_eq!(checks.compared, 1);
        assert_eq!(checks.pairing, Pairing::SingleVariable);
    }

    #[test]
    fn a_stego_image_a_different_size_from_its_cover_is_confounded() {
        // The failure the check exists for. A resized stego half means the
        // detector is being asked to tell two SIZES apart, and it will do it
        // well, and the number will look like detection.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        pair(&root, &png(63, 64, 8, 2, 0));
        let checks = check(&root).expect("checked");
        assert_eq!(checks.pairing, Pairing::Confounded);
        assert_eq!(checks.pairing_breaks.count, 1);
        assert!(
            checks.pairing_breaks.examples().contains("different sizes"),
            "{}",
            checks.pairing_breaks.examples()
        );
    }

    #[test]
    fn a_stego_image_in_another_format_is_confounded_and_says_which_two() {
        // The real case that voided a measurement round: one half written as
        // JPEG against a clean half that was not.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        let mut jpeg = vec![0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x11, 0x08];
        jpeg.extend_from_slice(&64u16.to_be_bytes());
        jpeg.extend_from_slice(&64u16.to_be_bytes());
        jpeg.push(3);
        jpeg.extend_from_slice(&[1, 0x11, 0, 2, 0x11, 0, 3, 0x11, 0]);
        pair(&root, &jpeg);
        let checks = check(&root).expect("checked");
        assert_eq!(checks.pairing, Pairing::Confounded);
        let seen = checks.pairing_breaks.examples();
        assert!(seen.contains("PNG") && seen.contains("JPEG"), "{seen}");
    }

    #[test]
    fn a_stego_image_of_another_bit_depth_or_channel_count_is_confounded() {
        for stego in [png(64, 64, 16, 2, 0), png(64, 64, 8, 6, 0)] {
            let tmp = tempfile::tempdir().expect("tmp");
            let root = tmp.path().join("corpus");
            pair(&root, &stego);
            let checks = check(&root).expect("checked");
            assert_eq!(checks.pairing, Pairing::Confounded);
        }
    }

    /// A minimal JPEG header of the given size, enough for `header::read`.
    fn jpeg(width: u16, height: u16) -> Vec<u8> {
        let mut bytes = vec![0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x11, 0x08];
        bytes.extend_from_slice(&height.to_be_bytes());
        bytes.extend_from_slice(&width.to_be_bytes());
        bytes.push(3);
        bytes.extend_from_slice(&[1, 0x11, 0, 2, 0x11, 0, 3, 0x11, 0]);
        bytes
    }

    /// A corpus shaped like a Pentimento JPEG arm, which is three rows and not
    /// two: a PNG cover crop, the clean JPEG encoded from it, and the stego
    /// JPEG. The stego row names the crop under `source_png` and the clean JPEG
    /// under `clean_sha256`, which is what the real records do.
    ///
    /// `clean_digest` is what the stego row claims its clean half is, so a test
    /// can point it at the clean row, at nothing, or leave it out.
    fn jpeg_arm(root: &Path, stego_image: &[u8], clean_digest: Option<&str>) {
        std::fs::create_dir_all(root).expect("corpus");
        // The cover tier: a PNG crop, which is the grandparent of the pair.
        std::fs::write(root.join("c0.png"), png(64, 64, 8, 2, 0)).unwrap();
        std::fs::write(
            root.join("c0.json"),
            r#"{"role":"clean","file":"c0.png","sha256":"covercrop"}"#,
        )
        .unwrap();
        // The clean half: the same picture as a JPEG, which is what the stego
        // image actually differs from in nothing but the payload.
        std::fs::write(root.join("k0.jpg"), jpeg(64, 64)).unwrap();
        std::fs::write(
            root.join("k0.json"),
            r#"{"role":"clean","file":"clean_jpeg/00000.jpg","sha256":"cleanhalf"}"#,
        )
        .unwrap();
        std::fs::write(root.join("s0.jpg"), stego_image).unwrap();
        let clean = match clean_digest {
            Some(digest) => format!(r#","clean_sha256":"{digest}""#),
            None => String::new(),
        };
        std::fs::write(
            root.join("s0.json"),
            format!(r#"{{"role":"stego","source_png":"c0.png","sha256":"0"{clean}}}"#),
        )
        .unwrap();
    }

    #[test]
    fn a_jpeg_arm_is_compared_against_its_clean_jpeg_half_and_not_against_the_cover_crop() {
        // The regression. Every JPEG arm of a correctly built corpus used to
        // fail this check, because the comparand was the PNG crop the clean
        // half had been encoded from rather than the clean half itself. On the
        // Nano tier that reported 6,859 of 7,812 images as confounded and put
        // the claim into the result document, which is the exact class of
        // confidently wrong statement about evidence this project exists to
        // prevent.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        jpeg_arm(&root, &jpeg(64, 64), Some("cleanhalf"));
        let checks = check(&root).expect("checked");
        assert!(
            checks.pairing_breaks.is_empty(),
            "{}",
            checks.pairing_breaks.examples()
        );
        assert_eq!(checks.compared, 1);
        assert_eq!(checks.unreadable, 0);
        assert_eq!(checks.pairing, Pairing::SingleVariable);
    }

    #[test]
    fn the_same_corpus_stating_no_clean_half_falls_back_to_the_cover_and_is_confounded() {
        // The other side of the same fact, so the test suite records WHY the
        // field is load-bearing rather than only that the good case passes. A
        // corpus whose records do not name a clean half has nothing better to
        // offer than the cover, and against the cover this pair really does
        // differ in more than the payload.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        jpeg_arm(&root, &jpeg(64, 64), None);
        let checks = check(&root).expect("checked");
        assert_eq!(checks.pairing, Pairing::Confounded);
        let seen = checks.pairing_breaks.examples();
        assert!(seen.contains("its cover c0.png"), "{seen}");
    }

    #[test]
    fn a_clean_half_the_corpus_names_but_does_not_ship_is_uncomparable_rather_than_confounded() {
        // It must NOT fall back to the cover here. Falling back would compare
        // against the one file already known to differ in more than the
        // payload, and report a corpus that is merely incomplete as one that is
        // confounded. Those are different problems with different fixes.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        jpeg_arm(&root, &jpeg(64, 64), Some("a-digest-no-row-here-states"));
        let checks = check(&root).expect("checked");
        assert_eq!(checks.compared, 0);
        assert_eq!(checks.unreadable, 1);
        assert!(checks.pairing_breaks.is_empty());
        assert_eq!(checks.pairing, Pairing::Unverified);
    }

    /// Rung 5 of the journey round, and the gap the two tests above sit either
    /// side of without closing. Both verdicts are correct; the problem is that
    /// one corpus can reach either of them by editing a single field, in the
    /// flattering direction, and the verdict alone does not say which happened.
    /// A submitter who wants the mild `unverified` badge instead of the damning
    /// `confounded` one points `clean` at a file they do not ship.
    #[test]
    fn the_two_unverified_corpora_are_told_apart_by_the_counts_rather_than_the_verdict() {
        let tmp = tempfile::tempdir().expect("tmp");

        // Names a clean half it does not contain: uncomparable, and the corpus
        // is the thing at fault.
        let dangling = tmp.path().join("dangling");
        jpeg_arm(
            &dangling,
            &jpeg(64, 64),
            Some("a-digest-no-row-here-states"),
        );
        let dangling = check(&dangling).expect("checked");

        // Claims nothing about a clean half AND has no cover to fall back to,
        // so there was never anything to compare.
        let silent = tmp.path().join("silent");
        std::fs::create_dir_all(&silent).unwrap();
        std::fs::write(silent.join("c0.png"), png(64, 64, 8, 2, 0)).unwrap();
        std::fs::write(silent.join("c0.json"), r#"{"role":"clean","sha256":"a"}"#).unwrap();
        std::fs::write(silent.join("s0.png"), png(64, 64, 8, 2, 9)).unwrap();
        std::fs::write(silent.join("s0.json"), r#"{"role":"stego","sha256":"b"}"#).unwrap();
        let silent = check(&silent).expect("checked");

        // The verdict is the same for both, which is the finding.
        assert_eq!(dangling.pairing, Pairing::Unverified);
        assert_eq!(silent.pairing, Pairing::Unverified);
        // The counts are not, which is the fix.
        assert_eq!(
            dangling.unreadable, 1,
            "the dangling pointer was not counted"
        );
        assert_eq!(
            silent.unreadable, 0,
            "a corpus that claimed nothing was blamed"
        );
    }

    #[test]
    fn a_stego_image_differing_from_its_clean_half_is_still_confounded_and_says_so() {
        // The check has to keep working after the comparand moved. A stego
        // image a different size from its clean half is the original failure
        // this whole check exists for, and the message names the clean half
        // rather than a cover the reader would then go and inspect in vain.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        jpeg_arm(&root, &jpeg(63, 64), Some("cleanhalf"));
        let checks = check(&root).expect("checked");
        assert_eq!(checks.pairing, Pairing::Confounded);
        let seen = checks.pairing_breaks.examples();
        assert!(seen.contains("its clean half"), "{seen}");
        assert!(seen.contains("different sizes"), "{seen}");
    }

    #[test]
    fn the_split_still_joins_on_the_cover_when_the_pairing_joins_on_the_digest() {
        // Two joins, two keys, on purpose. The split is a property of the
        // COVER and every arm descending from one crop inherits its side; the
        // pairing comparand is the clean TWIN. Moving the second must not move
        // the first, or a corpus would stop being checked for the leak that
        // inflates every number taken from it.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        jpeg_arm(&root, &jpeg(64, 64), Some("cleanhalf"));
        // The cover says test; the stego row contradicts it.
        std::fs::write(
            root.join("c0.json"),
            r#"{"role":"clean","file":"c0.png","sha256":"covercrop","split":"test"}"#,
        )
        .unwrap();
        std::fs::write(
            root.join("s0.json"),
            r#"{"role":"stego","source_png":"c0.png","sha256":"0","split":"train","clean_sha256":"cleanhalf"}"#,
        )
        .unwrap();
        let checks = check(&root).expect("checked");
        assert_eq!(checks.split_leaks.count, 1);
        assert_eq!(checks.split, SplitDiscipline::ByCover);
        // And the pairing is still clean, measured against the twin.
        assert_eq!(checks.pairing, Pairing::SingleVariable);
    }

    #[cfg(unix)]
    #[test]
    fn a_confounded_corpus_is_scored_and_the_document_says_so() {
        // Deliberately the opposite of what a split leak gets. A second
        // variable is a real property of some arms, kept on purpose to show
        // what it does, so the run happens and the result carries the fact.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        std::fs::create_dir_all(&root).unwrap();
        for i in 0..2 {
            std::fs::write(root.join(format!("c{i}.png")), png(64, 64, 8, 2, i)).unwrap();
            std::fs::write(
                root.join(format!("c{i}.json")),
                r#"{"role":"clean","sha256":"0"}"#,
            )
            .unwrap();
            std::fs::write(root.join(format!("s{i}.png")), png(48, 48, 8, 2, 64 + i)).unwrap();
            std::fs::write(
                root.join(format!("s{i}.json")),
                format!(r#"{{"role":"stego","source_png":"c{i}.png","sha256":"0"}}"#),
            )
            .unwrap();
        }

        let entry = sizing_detector(tmp.path());
        let mut warnings = Vec::new();
        let (result, _) = score(&entry, &request(&root, None), |line| {
            warnings.push(line.to_string())
        })
        .expect("scored");
        assert_eq!(result.declarations.pairing, Pairing::Confounded);
        assert!(
            warnings.iter().any(|w| w.starts_with("WARNING")),
            "the run said nothing about it: {warnings:?}"
        );
    }

    #[test]
    fn a_corpus_nothing_can_be_compared_in_says_unverified() {
        // Three ways to end up here, and none of them may read as the rule
        // holding: unreadable images, stego rows that name no cover, and a
        // cover this cannot measure.
        let tmp = tempfile::tempdir().expect("tmp");

        let unreadable = tmp.path().join("unreadable");
        std::fs::create_dir_all(&unreadable).unwrap();
        std::fs::write(unreadable.join("c0.png"), b"\x89PNG\r\n\x1a\n").unwrap();
        std::fs::write(
            unreadable.join("c0.json"),
            r#"{"role":"clean","sha256":"0"}"#,
        )
        .unwrap();
        std::fs::write(unreadable.join("s0.png"), b"\x89PNG\r\n\x1a\n").unwrap();
        std::fs::write(
            unreadable.join("s0.json"),
            r#"{"role":"stego","source_png":"c0.png","sha256":"0"}"#,
        )
        .unwrap();
        let checks = check(&unreadable).expect("checked");
        assert_eq!(checks.pairing, Pairing::Unverified);
        assert_eq!(checks.unreadable, 1);
        assert_eq!(checks.compared, 0);

        let unlinked = tmp.path().join("unlinked");
        std::fs::create_dir_all(&unlinked).unwrap();
        std::fs::write(unlinked.join("c0.png"), png(64, 64, 8, 2, 0)).unwrap();
        std::fs::write(unlinked.join("c0.json"), r#"{"role":"clean","sha256":"0"}"#).unwrap();
        std::fs::write(unlinked.join("s0.png"), png(64, 64, 8, 2, 1)).unwrap();
        std::fs::write(unlinked.join("s0.json"), r#"{"role":"stego","sha256":"0"}"#).unwrap();
        let checks = check(&unlinked).expect("checked");
        assert_eq!(checks.pairing, Pairing::Unverified);
        assert_eq!(checks.compared, 0);
    }

    #[test]
    fn a_format_this_cannot_measure_is_compared_as_far_as_its_format_and_no_further() {
        // Two BMPs of unknown size are not evidence that they match, but they
        // are evidence that neither is a JPEG. Claiming more than that would
        // be the unchecked claim in a smaller costume.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("c0.bmp"), b"BM\x40\x00\x40\x00").unwrap();
        std::fs::write(root.join("c0.json"), r#"{"role":"clean","sha256":"0"}"#).unwrap();
        std::fs::write(root.join("s0.bmp"), b"BM\x20\x00\x20\x00").unwrap();
        std::fs::write(
            root.join("s0.json"),
            r#"{"role":"stego","source_png":"c0.bmp","sha256":"0"}"#,
        )
        .unwrap();
        let checks = check(&root).expect("checked");
        assert_eq!(checks.compared, 1);
        assert_eq!(checks.pairing, Pairing::SingleVariable);
    }

    #[test]
    fn the_count_of_violations_is_exact_while_the_examples_are_capped() {
        // A corpus built by a broken script fails on every row. The count has
        // to be the real one and the list must not grow with the corpus.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("c0.png"), png(64, 64, 8, 2, 0)).unwrap();
        std::fs::write(root.join("c0.json"), r#"{"role":"clean","sha256":"0"}"#).unwrap();
        for i in 0..12 {
            std::fs::write(root.join(format!("s{i:02}.png")), png(48, 48, 8, 2, i)).unwrap();
            std::fs::write(
                root.join(format!("s{i:02}.json")),
                r#"{"role":"stego","source_png":"c0.png","sha256":"0"}"#,
            )
            .unwrap();
        }
        let checks = check(&root).expect("checked");
        assert_eq!(checks.pairing_breaks.count, 12);
        assert_eq!(checks.pairing_breaks.examples.len(), MAX_EXAMPLES);
    }

    /// A corpus whose records state the digests the test chooses.
    /// A corpus whose records state the TRUE digest of each image, except
    /// where the label is empty, which leaves the field off entirely.
    ///
    /// True rather than arbitrary, because a named run checks the images
    /// against their records and a fixture of made up hashes would exercise
    /// only the failure branch. The `label` still varies the content, so two
    /// corpora built from different labels get different digests.
    fn digested(root: &Path, labels: &[&str]) {
        std::fs::create_dir_all(root).expect("corpus");
        for (i, label) in labels.iter().enumerate() {
            let role = if i == 0 { "clean" } else { "stego" };
            let mut bytes = png(64, 64, 8, 2, i);
            bytes.extend_from_slice(label.as_bytes());
            let image = root.join(format!("i{i}.png"));
            std::fs::write(&image, &bytes).unwrap();
            let sha = if label.is_empty() {
                String::new()
            } else {
                format!(r#","sha256":"{}""#, hash_file(&image).expect("hashed"))
            };
            std::fs::write(
                root.join(format!("i{i}.json")),
                format!(r#"{{"role":"{role}"{sha}}}"#),
            )
            .unwrap();
        }
    }

    #[test]
    fn the_same_corpus_in_two_places_gets_the_same_digest() {
        // The point of the field. A corpus extracted from a shard and moved is
        // still the same corpus, and a digest that changed with the path would
        // name the directory rather than the data.
        let tmp = tempfile::tempdir().expect("tmp");
        let here = tmp.path().join("here");
        let there = tmp.path().join("somewhere/else/entirely");
        digested(&here, &["aa", "bb", "cc"]);
        digested(&there, &["aa", "bb", "cc"]);
        let a = check(&here).expect("checked").digest;
        let b = check(&there).expect("checked").digest;
        assert!(a.is_some(), "no digest was computed");
        assert_eq!(a, b);
    }

    #[test]
    fn one_changed_record_changes_the_corpus_digest() {
        let tmp = tempfile::tempdir().expect("tmp");
        let a = tmp.path().join("a");
        let b = tmp.path().join("b");
        digested(&a, &["aa", "bb", "cc"]);
        digested(&b, &["aa", "bb", "cd"]);
        assert_ne!(
            check(&a).expect("checked").digest,
            check(&b).expect("checked").digest
        );
    }

    #[test]
    fn a_corpus_missing_one_digest_carries_none_at_all() {
        // A digest over a partly digested corpus names the file list, and the
        // field is read as naming the content. Carrying nothing is the smaller
        // lie, which is to say it is not one.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        digested(&root, &["aa", "", "cc"]);
        assert_eq!(check(&root).expect("checked").digest, None);
    }

    #[cfg(unix)]
    #[test]
    fn the_digest_reaches_the_result_document() {
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        digested(&root, &["aa", "bb", "cc"]);
        let entry = sizing_detector(tmp.path());
        let (result, _) = score(&entry, &request(&root, None), |_| {}).expect("scored");
        assert!(
            result.corpus.digest.starts_with("sha256:"),
            "{:?}",
            result.corpus.digest
        );
        result.validate().expect("valid");
    }

    /// A corpus of one arm, described the way the shipped packer describes it.
    fn armed(root: &Path, extra: &str, extension: &str) {
        std::fs::create_dir_all(root).expect("corpus");
        std::fs::write(root.join("c0.png"), png(64, 64, 8, 2, 0)).unwrap();
        std::fs::write(
            root.join("c0.json"),
            r#"{"role":"clean","tool":"clean","sha256":"aa"}"#,
        )
        .unwrap();
        std::fs::write(root.join(format!("s0.{extension}")), png(64, 64, 8, 2, 8)).unwrap();
        std::fs::write(
            root.join("s0.json"),
            format!(r#"{{"role":"stego","sha256":"bb"{extra}}}"#),
        )
        .unwrap();
    }

    #[test]
    fn the_arm_is_read_off_the_corpus_rather_than_assumed() {
        // Every field here used to be a constant, and two of the three were
        // wrong for most of the shipped corpus.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        armed(
            &root,
            r#","tool":"wow","arm":"wow-0200","rate":0.2,"rate_unit":"bits per pixel","domain":"spatial""#,
            "png",
        );
        let arm = check(&root).expect("checked").arm;
        assert_eq!(arm.embedder, "wow");
        assert_eq!(arm.domain, Domain::Spatial);
        assert_eq!(arm.format, "png");
        let rate = arm.rate.expect("a rate");
        assert_eq!(rate.unit, RateUnit::Bpp);
        assert!((rate.value - 0.2).abs() < f64::EPSILON);
    }

    #[test]
    fn a_clean_row_does_not_make_every_corpus_a_mixed_one() {
        // Clean rows state `clean` as their tool. Counting them would make one
        // arm look like two on every corpus that ships its own clean half.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        armed(&root, r#","tool":"hugo","domain":"spatial""#, "png");
        assert_eq!(check(&root).expect("checked").arm.embedder, "hugo");
    }

    #[test]
    fn a_jpeg_arm_is_not_labelled_spatial_and_a_capacity_share_is_not_bpp() {
        // The two wrong constants, in one corpus. A reader comparing 0.05 of a
        // reported capacity against 0.4 bits per pixel is comparing nothing,
        // which is why the unit refuses to be guessed.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        armed(
            &root,
            r#","tool":"outguess","rate":0.05,"rate_unit":"fraction of the capacity outguess reports","domain":"jpeg-dct""#,
            "jpg",
        );
        let arm = check(&root).expect("checked").arm;
        assert_eq!(arm.embedder, "outguess");
        assert_eq!(arm.domain, Domain::Jpeg);
        assert_eq!(arm.format, "jpeg", "jpg and jpeg are one format");
        assert_eq!(arm.rate.expect("a rate").unit, RateUnit::CapacityFraction);
    }

    #[test]
    fn a_rate_in_a_unit_this_cannot_carry_is_dropped_rather_than_relabelled() {
        // The JPEG adaptive schemes are driven in bits per non-zero AC
        // coefficient, which `result-v1` has no unit for. Writing the number
        // under one of the two units it does have would publish a false one.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        armed(
            &root,
            r#","tool":"juniward","rate":0.4,"rate_unit":"bits per non-zero AC coefficient","domain":"jpeg-dct""#,
            "jpg",
        );
        let arm = check(&root).expect("checked").arm;
        assert_eq!(arm.rate, None);
        assert_eq!(arm.embedder, "juniward");
    }

    #[test]
    fn a_corpus_of_several_arms_says_mixed_rather_than_picking_one() {
        // A whole tier is a legitimate thing to score and its aggregate is a
        // real number. Labelling it with whichever arm sorted first would
        // attribute that number to one scheme out of thirty-nine.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("c0.png"), png(64, 64, 8, 2, 0)).unwrap();
        std::fs::write(root.join("c0.json"), r#"{"role":"clean","sha256":"a"}"#).unwrap();
        for (i, (tool, domain)) in [("wow", "spatial"), ("outguess", "jpeg-dct")]
            .into_iter()
            .enumerate()
        {
            std::fs::write(root.join(format!("s{i}.png")), png(64, 64, 8, 2, i + 1)).unwrap();
            std::fs::write(
                root.join(format!("s{i}.json")),
                format!(r#"{{"role":"stego","sha256":"b","tool":"{tool}","domain":"{domain}"}}"#),
            )
            .unwrap();
        }
        let arm = check(&root).expect("checked").arm;
        assert_eq!(arm.embedder, "mixed");
        assert_eq!(arm.domain, Domain::Mixed);
    }

    #[test]
    fn a_corpus_that_says_nothing_about_its_arm_says_unstated() {
        // The honest answer to a directory of loose samples, and a different
        // statement from naming a scheme nobody recorded.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        armed(&root, "", "png");
        let arm = check(&root).expect("checked").arm;
        assert_eq!(arm.embedder, "unstated");
        assert_eq!(arm.rate, None);
        // The format is the only evidence left, and a PNG corpus is a spatial
        // one until something says otherwise.
        assert_eq!(arm.domain, Domain::Spatial);
    }

    #[test]
    fn a_cover_renamed_by_the_packer_is_still_found_by_the_name_its_record_gives() {
        // The shape of a real release, and the one that made both checks inert
        // before this: every member is renamed to its position in the tier, so
        // the cover on disk is `000000.png` while every stego row made from it
        // still names `09710.png`. Joining on the name on disk matches nothing,
        // and a check that cannot look reports clean.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("000000.png"), png(64, 64, 8, 2, 0)).unwrap();
        std::fs::write(
            root.join("000000.json"),
            r#"{"role":"clean","file":"09710.png","split":"test","sha256":"a"}"#,
        )
        .unwrap();
        // A stego twin that is a different size, and in the other split.
        std::fs::write(root.join("000001.png"), png(48, 48, 8, 2, 0)).unwrap();
        std::fs::write(
            root.join("000001.json"),
            r#"{"role":"stego","file":"000001.png","source_png":"09710.png","split":"train","sha256":"b"}"#,
        )
        .unwrap();

        let checks = check(&root).expect("checked");
        assert_eq!(
            checks.pairing,
            Pairing::Confounded,
            "the cover was never found, so nothing was compared"
        );
        assert_eq!(checks.split_leaks.count, 1, "the split join did not fire");
    }

    #[test]
    fn an_arm_reusing_a_basename_cannot_displace_the_cover_it_collides_with() {
        // The shape of a real multi arm extraction. Every arm restarts its
        // numbering at 000000, so several clean arms offer the same name on
        // disk as a cover tier file, and an overwrite there attaches a stego
        // row to the wrong photograph without saying anything.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        std::fs::create_dir_all(root.join("cover")).unwrap();
        std::fs::create_dir_all(root.join("clean-grey")).unwrap();

        // The cover, 64 by 64, extracted as 000000.png but recorded as its
        // own name in the tier.
        std::fs::write(root.join("cover/000000.png"), png(64, 64, 8, 2, 0)).unwrap();
        std::fs::write(
            root.join("cover/000000.json"),
            r#"{"role":"clean","file":"09710.png","sha256":"a"}"#,
        )
        .unwrap();
        // A clean arm image of a DIFFERENT size, whose own name on disk and
        // in its record is also 000000.png.
        std::fs::write(root.join("clean-grey/000000.png"), png(32, 32, 8, 2, 0)).unwrap();
        std::fs::write(
            root.join("clean-grey/000000.json"),
            r#"{"role":"clean","file":"000000.png","sha256":"b"}"#,
        )
        .unwrap();
        // A stego row made from the cover, matching the cover's shape.
        std::fs::write(root.join("s0.png"), png(64, 64, 8, 2, 7)).unwrap();
        std::fs::write(
            root.join("s0.json"),
            r#"{"role":"stego","source_png":"09710.png","sha256":"c"}"#,
        )
        .unwrap();

        let checks = check(&root).expect("checked");
        assert_eq!(checks.compared, 1);
        assert_eq!(
            checks.pairing,
            Pairing::SingleVariable,
            "the stego row was compared against the wrong image: {}",
            checks.pairing_breaks.examples()
        );
    }

    #[test]
    fn a_manifest_carrying_a_path_in_its_file_field_still_joins() {
        // Some manifests write `covers/09710.png` rather than a bare name. The
        // join only ever needs the last component, and a path in that field
        // must not reach out of the corpus either.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("000000.png"), png(64, 64, 8, 2, 0)).unwrap();
        std::fs::write(
            root.join("000000.json"),
            r#"{"role":"clean","file":"covers/09710.png","sha256":"a"}"#,
        )
        .unwrap();
        std::fs::write(root.join("000001.png"), png(64, 64, 8, 2, 9)).unwrap();
        std::fs::write(
            root.join("000001.json"),
            r#"{"role":"stego","source_png":"09710.png","sha256":"b"}"#,
        )
        .unwrap();
        let checks = check(&root).expect("checked");
        assert_eq!(checks.compared, 1);
        assert_eq!(checks.pairing, Pairing::SingleVariable);
    }

    /// A registry entry for a corpus, with the digest the test chooses.
    #[cfg(unix)]
    fn registered_corpus(declared: Option<&str>) -> CorpusEntry {
        let integrity = match declared {
            Some(d) => format!("[integrity]\nrecords_sha256 = \"{d}\"\n"),
            None => String::new(),
        };
        toml::from_str(&format!(
            "id = \"example\"\nname = \"Example Tier\"\ntier = \"nano\"\n\
             description = \"For a test.\"\n{integrity}\
             [licence]\nstatus = \"unverified\"\nredistribution = \"unknown\"\n\
             redistribution_reason = \"A fixture.\"\n\
             [obtain]\ninstructions = \"A fixture.\"\n\
             [properties]\nbase_images = 1\nsize_note = \"A fixture.\"\n"
        ))
        .expect("parses")
    }

    #[cfg(unix)]
    #[test]
    fn a_corpus_matching_the_digest_its_registry_entry_declares_is_named() {
        // The only way to `named`. The harness is comparing the bytes in front
        // of it with a claim somebody else wrote down first, which is what
        // makes the field worth having.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        digested(&root, &["aa", "bb", "cc"]);
        let digest = corpus_digest(&root).expect("readable").expect("named");
        let entry = registered_corpus(Some(&digest));

        let mut request = request(&root, None);
        request.registered = Some(&entry);
        let (result, _) = score(&sizing_detector(tmp.path()), &request, |_| {}).expect("scored");

        assert_eq!(result.declarations.configuration, Configuration::Named);
        assert_eq!(result.corpus.name, "Example Tier");
        assert_eq!(result.corpus.tier.as_deref(), Some("nano"));
        result.validate().expect("valid");
    }

    /// THE CLAIM THE TWO-HALVES REFACTOR RESTS ON, MEASURED RATHER THAN
    /// DESCRIBED.
    ///
    /// Scoring seven detectors over a Core tier must not hash 344,357 images
    /// seven times. The byte verification is the most expensive thing this
    /// module does and it emits one distinctive progress line, so counting
    /// that line across a two-detector run is a direct measurement of how many
    /// times the corpus was established.
    #[cfg(unix)]
    #[test]
    fn the_expensive_corpus_work_happens_once_however_many_detectors_are_asked() {
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        digested(&root, &["aa", "bb", "cc"]);
        let digest = corpus_digest(&root).expect("readable").expect("named");
        let entry = registered_corpus(Some(&digest));

        let mut lines: Vec<String> = Vec::new();
        let prepared = prepare(&root, Some(&entry), None, None, None, |l: &str| {
            lines.push(l.to_string())
        })
        .expect("prepared");

        let verified = |lines: &[String]| {
            lines
                .iter()
                .filter(|l| l.contains("are the files their records describe"))
                .count()
        };
        assert_eq!(
            verified(&lines),
            1,
            "the byte check should have run exactly once: {lines:?}"
        );

        // Two detectors against the one `Prepared`. Different records files,
        // so neither resumes from the other.
        let detector = sizing_detector(tmp.path());
        let after = lines.len();
        for name in ["first", "second"] {
            let records = tmp.path().join(format!("{name}.jsonl"));
            score_one(
                &detector,
                &prepared,
                &records,
                How {
                    timeout: Duration::from_secs(5),
                    jobs: 1,
                    keep_raw: false,
                    seed: None,
                    fixtures: None,
                    adapter_roots: &[],
                },
                |l: &str| lines.push(l.to_string()),
            )
            .unwrap_or_else(|e| panic!("{name} failed: {e}"));
        }
        assert_eq!(
            verified(&lines),
            1,
            "a detector re-ran the byte check: {:?}",
            &lines[after..]
        );

        // And the shared preparation is genuinely attributed to each result
        // rather than dropped: both name the same start.
        let one = score_one(
            &detector,
            &prepared,
            &tmp.path().join("third.jsonl"),
            How {
                timeout: Duration::from_secs(5),
                jobs: 1,
                keep_raw: false,
                seed: None,
                fixtures: None,
                adapter_roots: &[],
            },
            |_| {},
        )
        .expect("third")
        .0;
        assert_eq!(one.provenance.started_utc, prepared.started_utc);
        assert!(one.provenance.elapsed_seconds >= prepared.preflight_seconds());
        assert_eq!(one.declarations.configuration, Configuration::Named);
    }

    /// A container is sandboxed with no network; a local program and a host
    /// adapter are not. The one-line version got two of the three wrong, and
    /// the service case got it backwards: the network is not merely reachable
    /// for one of those, it is the only way the tool is asked anything.
    #[test]
    fn what_a_result_says_about_the_network_is_true_for_all_three_routes() {
        let digest = "5".repeat(64);
        let container: Entry = toml::from_str(&format!(
            "name = \"c\"\nkind = \"detector\"\nlicence = \"MIT\"\n\
             [image]\nreference = \"ghcr.io/x/y@sha256:{digest}\"\n\
             [selftest]\nmust_detect = \"a.png\"\nmust_clear = \"b.png\"\n"
        ))
        .expect("parses");
        let local: Entry = toml::from_str(
            "name = \"l\"\nkind = \"detector\"\nlicence = \"MIT\"\n\
             [binary]\ncommand = [\"sh\"]\n\
             [selftest]\nmust_detect = \"a.png\"\nmust_clear = \"b.png\"\n",
        )
        .expect("parses");
        let service: Entry = toml::from_str(&format!(
            "name = \"s\"\nkind = \"detector\"\nlicence = \"MIT\"\n\
             [image]\nreference = \"ghcr.io/x/s@sha256:{digest}\"\n\
             [invoke]\nhost = true\nadapter = \"a.py\"\nentrypoint = \"python3\"\n\
             argv = [\"{{adapter}}\", \"{{file}}\"]\nparser = \"number\"\n\
             [selftest]\nmust_detect = \"a.png\"\nmust_clear = \"b.png\"\n"
        ))
        .expect("parses");

        assert!(runs_in_container(&container));
        assert!(!runs_in_container(&local));
        assert!(
            !runs_in_container(&service),
            "an entry naming an image AND invoke.host does not run in that \
             image, so a result claiming a sandbox and no network is false \
             about both halves"
        );
    }

    /// The two fields that replaced `route`, over the three shapes the
    /// registry actually holds plus the one that used to break the single
    /// field. Each is asserted on its own, because each is read on its own.
    #[test]
    fn the_pin_and_the_sandbox_are_answered_separately_for_every_entry_shape() {
        let digest = "5".repeat(64);
        let image_block = format!("[image]\nreference = \"ghcr.io/x/y@sha256:{digest}\"\n");
        let tail = "[selftest]\nmust_detect = \"a.png\"\nmust_clear = \"b.png\"\n";
        let adapter = "[invoke]\nhost = true\nadapter = \"a.py\"\n\
             entrypoint = \"python3\"\nargv = [\"{adapter}\", \"{file}\"]\n\
             parser = \"number\"\n";

        let parse = |body: String| -> Entry { toml::from_str(&body).expect("parses") };
        let head = |n: &str| format!("name = \"{n}\"\nkind = \"detector\"\nlicence = \"MIT\"\n");

        let container = parse(format!("{}{image_block}{tail}", head("c")));
        assert_eq!(pinning(&container).1, PinnedBy::ImageDigest);
        assert_eq!(isolation(&container), Isolation::SandboxNoNetwork);

        // A program that is not installed cannot be hashed, and the fallback
        // must be the admission rather than a hash-shaped "unknown".
        let local = parse(format!(
            "{}[binary]\ncommand = [\"definitely-not-installed-xyzzy\"]\n{tail}",
            head("l")
        ));
        assert_eq!(pinning(&local).1, PinnedBy::Unpinned);
        assert_eq!(isolation(&local), Isolation::Host);

        // The shape that broke the single field: the image names the subject,
        // an adapter here did the running, and the tool was reached over HTTP.
        let service = parse(format!(
            "{}{image_block}{adapter}endpoint_env = \"X_ENDPOINT\"\n{tail}",
            head("s")
        ));
        assert_eq!(
            pinning(&service).1,
            PinnedBy::Unpinned,
            "nothing in the run checked that the instance came from that image"
        );
        assert_eq!(pinning(&service).0, format!("ghcr.io/x/y@sha256:{digest}"));
        assert_eq!(isolation(&service), Isolation::RemoteService);

        // An adapter with no endpoint reaches no service, so it is an ordinary
        // host run, and the image it names still did not execute.
        let adapter_only = parse(format!("{}{image_block}{adapter}{tail}", head("a")));
        assert_eq!(pinning(&adapter_only).1, PinnedBy::Unpinned);
        assert_eq!(isolation(&adapter_only), Isolation::Host);
    }

    /// A document must never state a sandbox beside a reachable network, which
    /// is the contradiction the old single field forced onto every service
    /// result. Asserted against `validate` so it cannot come back quietly.
    #[test]
    fn the_two_fields_and_the_network_flag_never_contradict_each_other() {
        for entry in [
            "name = \"c\"\nkind = \"detector\"\nlicence = \"MIT\"\n\
             [image]\nreference = \"ghcr.io/x/y@sha256:abc\"\n",
            "name = \"s\"\nkind = \"detector\"\nlicence = \"MIT\"\n\
             [image]\nreference = \"ghcr.io/x/y@sha256:abc\"\n\
             [invoke]\nhost = true\nadapter = \"a.py\"\nentrypoint = \"python3\"\n\
             argv = [\"{adapter}\", \"{file}\"]\nparser = \"number\"\n\
             endpoint_env = \"X_ENDPOINT\"\n",
            "name = \"l\"\nkind = \"detector\"\nlicence = \"MIT\"\n\
             [binary]\ncommand = [\"sh\"]\n",
        ] {
            let e: Entry = toml::from_str(&format!(
                "{entry}[selftest]\nmust_detect = \"a.png\"\nmust_clear = \"b.png\"\n"
            ))
            .expect("parses");
            let sandboxed = isolation(&e) == Isolation::SandboxNoNetwork;
            // `network_reachable` is written as this expression, so the two
            // fields are asserted to be opposites rather than merely to look
            // plausible side by side.
            let network_reachable = !runs_in_container(&e);
            assert_ne!(
                sandboxed, network_reachable,
                "{}: a sandbox with no network beside a reachable network is \
                 the contradiction this change exists to remove",
                e.name
            );
        }
    }

    /// Proved end to end rather than through the helper alone, because the
    /// field a reader acts on is the one in the document.
    #[cfg(unix)]
    #[test]
    fn a_local_run_reports_the_network_as_reachable_in_the_document() {
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 2, 2);
        let (result, _) =
            score(&sizing_detector(tmp.path()), &request(&root, None), |_| {}).expect("scored");
        assert!(
            result.provenance.network_reachable,
            "a program on this machine runs with this machine's network"
        );
    }

    #[test]
    fn every_way_a_run_can_fail_has_its_own_exit_code() {
        // They all used to be 4, plugin failure, including four where no
        // plugin was involved. A script and an agent act on these.
        use stegobench_core::exit;
        let cases = [
            (ScoreError::NotADetector { name: "x".into() }, exit::USAGE),
            (
                ScoreError::NotThatCorpus {
                    path: "p".into(),
                    id: "i".into(),
                    want: "a".into(),
                    got: "b".into(),
                },
                exit::VERIFY_MISMATCH,
            ),
            (
                ScoreError::SplitLeaks {
                    path: "p".into(),
                    count: 1,
                    examples: "e".into(),
                },
                exit::PREFLIGHT_REFUSED,
            ),
            (
                ScoreError::OneSided {
                    path: "p".into(),
                    clean: 1,
                    stego: 0,
                },
                exit::PREFLIGHT_REFUSED,
            ),
            (
                ScoreError::Records {
                    path: "p".into(),
                    source: std::io::Error::other("x"),
                },
                exit::FAILURE,
            ),
            (
                ScoreError::NoAuc {
                    name: "x".into(),
                    answered: 4,
                    why: "w".into(),
                },
                exit::PLUGIN_FAILED,
            ),
        ];
        for (err, want) in cases {
            assert_eq!(err.exit_code(), want, "{err}");
        }
    }

    /// The fallback that used to sit on the AUC, and why it could not stay.
    ///
    /// `.unwrap_or(0.5)` wrote the one value an AUC must never default to: 0.5
    /// is exactly what the metric says when a detector carries no information,
    /// so a run that could not be measured was published as a run that came
    /// out at chance, and no field in the document told the two apart.
    #[test]
    fn a_run_with_no_computable_auc_refuses_rather_than_publishing_a_half() {
        let err = ScoreError::NoAuc {
            name: "zsteg".into(),
            answered: 12,
            why: why_no_auc(&[1.0, f64::NAN], &[false, true], ""),
        };
        let text = err.to_string();
        assert_eq!(err.exit_code(), stegobench_core::exit::PLUGIN_FAILED);
        // The reader is told which condition fired, not merely that one did.
        assert!(text.contains("not numbers"), "{text}");
        // And is told why 0.5 in particular could not be the fallback, since
        // that is the whole argument.
        assert!(text.contains("0.5"), "{text}");
        assert!(text.contains("nothing is written"), "{text}");
    }

    /// Three conditions, three actions, so three messages rather than one.
    #[test]
    fn every_reason_an_auc_cannot_be_computed_is_named_separately() {
        let mismatch = why_no_auc(&[1.0, 2.0], &[true], "");
        assert!(mismatch.contains("2 score(s)") && mismatch.contains("1 label(s)"));
        assert!(
            mismatch.contains("bug in stegobench"),
            "a length mismatch is not the user's doing: {mismatch}"
        );

        let nan = why_no_auc(&[f64::NAN, 1.0], &[true, false], "");
        assert!(
            nan.contains("1 of the 2 answer(s) are not numbers"),
            "{nan}"
        );
        assert!(
            nan.contains("stegobench doctor"),
            "a NaN from a detector needs a next step: {nan}"
        );

        // The case a detector that fails on everything lands in. The shared
        // sentence is `metrics`' one, where a user really did hand over an
        // empty file, so on this path it needs the reason nothing arrived.
        let empty = why_no_auc(&[], &[], "");
        assert!(
            empty.contains("none of them came back with a number"),
            "an empty answer set has to say the tool produced nothing: {empty}"
        );
        assert!(
            empty.contains("stegobench doctor"),
            "and where to look next: {empty}"
        );

        let one_sided = why_no_auc(&[1.0, 2.0], &[true, true], "");
        assert!(one_sided.contains("0 clean and 2 stego"), "{one_sided}");
        assert!(
            one_sided.contains("this tool produced a usable answer"),
            "the tool, not the corpus, is what is one-sided here: {one_sided}"
        );

        // And the residual case is not silently dressed up as one of the
        // three. It cannot be reached from `roc_auc`'s own contract, so it
        // says it is a bug rather than inventing a cause.
        let residual = why_no_auc(&[1.0, 2.0], &[true, false], "");
        assert!(residual.contains("bug in stegobench"), "{residual}");

        // The operating point is carried into the residual message, so a
        // detection rate that could not be formed says which budget it was.
        let at_budget = why_no_auc(&[1.0, 2.0], &[true, false], " at a budget of 0.01");
        assert!(at_budget.contains("at a budget of 0.01"), "{at_budget}");
    }

    /// The sentences come from `MetricsError` and are not a second copy.
    ///
    /// This is the drift guard: the refusal a user reads on the score path
    /// has to be the refusal `stegobench metrics` gives for the same
    /// condition, with only the score path's own next step added.
    #[test]
    fn the_refusals_are_the_metrics_commands_own_words() {
        for (scores, labels) in [
            (vec![1.0, 2.0], vec![true]),
            (vec![f64::NAN, 1.0], vec![true, false]),
            (vec![1.0, 2.0], vec![true, true]),
            (vec![], vec![]),
        ] {
            let shared = crate::metrics::why_unrankable(&scores, &labels, "").to_string();
            let here = why_no_auc(&scores, &labels, "");
            assert!(
                here.starts_with(&shared),
                "{here}\ndoes not open with\n{shared}"
            );
        }
    }

    /// The four conditions above are what `roc_auc` itself answers `None` to,
    /// asserted against the crate rather than against this file's memory of
    /// it. If the metrics crate grows a fifth, this fails and the diagnosis
    /// above gets updated rather than quietly falling through to "a bug".
    #[test]
    fn the_conditions_this_diagnoses_are_the_ones_the_metric_actually_refuses() {
        assert_eq!(stegobench_metrics::roc_auc(&[1.0, 2.0], &[true]), None);
        assert_eq!(
            stegobench_metrics::roc_auc(&[f64::NAN, 1.0], &[true, false]),
            None
        );
        assert_eq!(
            stegobench_metrics::roc_auc(&[1.0, 2.0], &[true, true]),
            None
        );
        // And a well-formed input still produces one, so the test above is
        // not passing because nothing works.
        assert!(stegobench_metrics::roc_auc(&[1.0, 2.0], &[false, true]).is_some());
    }

    #[cfg(unix)]
    #[test]
    fn swapping_the_images_under_a_matching_manifest_is_caught() {
        // The attack the byte check exists for, and the reason a corpus digest
        // alone cannot carry a named result. Take the real records, keep them
        // byte for byte so the corpus digest is unchanged, and put easier
        // images underneath. Everything the registry can compare still agrees.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        digested(&root, &["aa", "bb", "cc"]);
        let digest = corpus_digest(&root).expect("readable").expect("named");
        let entry = registered_corpus(Some(&digest));

        // The records are untouched; only the pixels change.
        std::fs::write(root.join("i1.png"), png(64, 64, 8, 2, 99)).unwrap();
        assert_eq!(
            corpus_digest(&root).expect("readable").as_deref(),
            Some(digest.as_str()),
            "the corpus digest noticed, which would make this test prove nothing"
        );

        let mut request = request(&root, None);
        request.registered = Some(&entry);
        let err = score(&sizing_detector(tmp.path()), &request, |_| {}).expect_err("refused");
        assert!(
            err.to_string().contains("is not the image its own record"),
            "{err}"
        );
        assert_eq!(err.exit_code(), stegobench_core::exit::VERIFY_MISMATCH);
    }

    #[cfg(unix)]
    #[test]
    fn a_custom_run_does_not_pay_for_the_byte_check() {
        // There is no external claim to check a custom run against, the
        // records are the only description of that corpus that exists, and
        // comparing them with themselves would be theatre that costs a whole
        // extra read of the corpus.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        digested(&root, &["aa", "bb", "cc"]);
        std::fs::write(root.join("i1.png"), png(64, 64, 8, 2, 99)).unwrap();

        let mut said = Vec::new();
        let (result, _) = score(&sizing_detector(tmp.path()), &request(&root, None), |l| {
            said.push(l.to_string())
        })
        .expect("scored");
        assert_eq!(result.declarations.configuration, Configuration::Custom);
        assert!(
            !said.iter().any(|l| l.contains("their records describe")),
            "a custom run paid for the check: {said:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_directory_that_is_not_the_corpus_it_claims_is_refused() {
        // Refused rather than downgraded to custom. The user asserted
        // something about these bytes that is not true of them, and filing the
        // run quietly as custom would answer a different question from the one
        // they asked.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        digested(&root, &["aa", "bb", "cc"]);
        let entry = registered_corpus(Some(&format!("sha256:{}", "0".repeat(64))));

        let mut request = request(&root, None);
        request.registered = Some(&entry);
        let err = score(&sizing_detector(tmp.path()), &request, |_| {}).expect_err("refused");
        assert!(err.to_string().contains("is not example"), "{err}");
    }

    #[cfg(unix)]
    #[test]
    fn naming_a_corpus_whose_entry_declares_no_digest_stays_custom() {
        // Nobody has computed the digest for most corpora, and that is the
        // ordinary state rather than a fault. What must not happen is the name
        // alone earning `named`, because then the person running the benchmark
        // sets the field.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        digested(&root, &["aa", "bb", "cc"]);
        let entry = registered_corpus(None);

        let mut request = request(&root, None);
        request.registered = Some(&entry);
        let mut said = Vec::new();
        let (result, _) = score(&sizing_detector(tmp.path()), &request, |l| {
            said.push(l.to_string())
        })
        .expect("scored");

        assert_eq!(result.declarations.configuration, Configuration::Custom);
        assert!(
            said.iter()
                .any(|l| l.contains("declares no records digest")),
            "it downgraded silently: {said:?}"
        );
        // The name and tier are still carried: they are what the user said,
        // and the digest beside them is what the harness measured.
        assert_eq!(result.corpus.name, "Example Tier");
    }

    #[cfg(unix)]
    #[test]
    fn a_partial_run_over_a_matching_corpus_is_still_custom() {
        // A prefix of a tier is not the tier, whatever the whole of it hashes
        // to, and the digest is taken over the whole corpus rather than over
        // what was scored.
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        digested(&root, &["aa", "bb", "cc", "dd"]);
        let digest = corpus_digest(&root).expect("readable").expect("named");
        let entry = registered_corpus(Some(&digest));

        let mut request = request(&root, Some(3));
        request.registered = Some(&entry);
        let mut said = Vec::new();
        let (result, _) = score(&sizing_detector(tmp.path()), &request, |l| {
            said.push(l.to_string())
        })
        .expect("scored");

        assert_eq!(result.declarations.configuration, Configuration::Custom);
        assert!(
            said.iter().any(|l| l.contains("prefix of a tier")),
            "{said:?}"
        );
    }
    #[test]
    fn an_embedder_is_refused_rather_than_scored() {
        // Asking an embedder to tell two images apart produces a number that
        // means nothing, and it would look exactly like a weak detector.
        let entry: Entry = toml::from_str(
            "name = \"x\"\nkind = \"embedder\"\nlicence = \"MIT\"\n\
             [image]\nreference = \"a@sha256:b\"\nsize_mb = 1\nbundled = true\n\
             [selftest]\nmust_detect = \"fixtures/a.png\"\nmust_clear = \"fixtures/b.png\"\n",
        )
        .expect("parses");
        let tmp = tempfile::tempdir().expect("tmp");
        let root = tmp.path().join("corpus");
        corpus(&root, 1, 1);
        let err = score(&entry, &request(&root, None), |_| {}).expect_err("refused");
        assert!(err.to_string().contains("cannot be asked"), "{err}");
    }

    /// Every variant answers, and no two answer the same, so a variant added
    /// later cannot quietly inherit somebody else's word.
    ///
    /// The list is built by hand rather than derived, and that is the point:
    /// `reason()` matches without a wildcard, so a new variant breaks the
    /// build there and whoever fixes it comes here next. Every variant is
    /// present, including the two that wrap another crate's error, because
    /// leaving those out is exactly how a twelfth variant would be given a
    /// word one of them already owns.
    #[test]
    fn every_score_error_has_its_own_stable_word() {
        let every: Vec<ScoreError> = vec![
            ScoreError::Corpus(stegobench_core::samples::SampleError::TooManySamples),
            ScoreError::Run(runner::RunError::BadRecord {
                path: "p".into(),
                reason: "r".into(),
            }),
            ScoreError::Records {
                path: "p".into(),
                source: std::io::Error::other("x"),
            },
            ScoreError::NotADetector { name: "n".into() },
            ScoreError::SplitLeaks {
                path: "p".into(),
                count: 1,
                examples: "e".into(),
            },
            ScoreError::NotThatCorpus {
                path: "p".into(),
                id: "i".into(),
                want: "w".into(),
                got: "g".into(),
            },
            ScoreError::UnknownSplit {
                asked: "sideways".into(),
            },
            ScoreError::NoSplitLabels { path: "p".into() },
            ScoreError::OneSided {
                path: "p".into(),
                clean: 1,
                stego: 0,
            },
            ScoreError::NoAuc {
                name: "n".into(),
                answered: 1,
                why: "w".into(),
            },
            ScoreError::ImageChanged {
                id: "i".into(),
                want: "w".into(),
                got: "g".into(),
            },
        ];
        let mut seen = std::collections::BTreeSet::new();
        for e in &every {
            let word = e.reason();
            assert!(!word.is_empty(), "a variant answered with nothing");
            assert!(
                word.chars().all(|c| c.is_ascii_lowercase() || c == '-'),
                "{word:?} is not the kebab-case vocabulary the others use"
            );
            assert!(seen.insert(word), "{word:?} is claimed by two variants");
        }
        assert_eq!(seen.len(), every.len());
    }
}