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
// Author:  Daniel Iwugo
// Comment: Christ is King
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2026 Daniel Iwugo
//! `stegobench report`: the last mile, where a number meets a page.
//!
//! WHAT THIS EXISTS TO STOP
//!
//! Without it, somebody building an evaluation document opens a `result-v1`
//! file, copies the AUC into a table, and leaves behind the four fields that
//! decide what the AUC is worth: which corpus, which configuration, whether
//! the pairing held, and which side of the train and test split the pairs
//! landed on. The number survives the journey to the page and the conditions
//! do not. That is the exact failure this repository was built to correct,
//! happening one step after the part that was built to correct it.
//!
//! So every row this module emits carries its conditions in the row. Not in a
//! legend, not in a heading, not in a footnote: in the cells, so a reader who
//! lifts one line out of the table takes the caveats with it whether they
//! meant to or not.
//!
//! WHAT IT REFUSES
//!
//! Three refusals, each of them a rule from `docs/leaderboard.md` rather than
//! a preference:
//!
//! 1. Results over different corpora are never put in one table. An AUC on
//!    one corpus and an AUC on another are measurements of two populations,
//!    not two scores on one scale. Two documents naming the same corpus with
//!    different digests are two corpora here, because the digest is what
//!    names the bytes and the name is only a label somebody chose.
//! 2. `custom` runs sit in their own sections, never interleaved with `named`
//!    ones, each section carrying a plain sentence saying what it is
//!    comparable with.
//! 3. Nothing is ordered by score. Rows are ordered by arm and then detector,
//!    so the table cannot be read as a ranking it was never entitled to be.
//!
//! WHERE THE MEMORY GOES
//!
//! Rows are gathered into one bounded `Vec` and sorted, rather than streamed
//! in two passes. Grouping and ordering both need every row before either can
//! be decided, and a two-pass version would re-read and re-parse every file
//! to save memory it never needed to spend: a row is a few hundred bytes and
//! the cap is [`MAX_RESULTS`], so the worst case is a few megabytes. The cap
//! is a hard refusal rather than a truncation, because a table that quietly
//! stopped at ten thousand rows is precisely the "looks complete and is not"
//! failure the rest of this module is about.

use std::collections::{BTreeMap, HashMap};
use std::fmt::Write as _;
use std::io::{Read as _, Write as _};
use std::path::{Path, PathBuf};

use stegobench_core::exit;
use stegobench_core::result::{
    ArmMetrics, Configuration, ContaminationCheck, CorpusSource, Determinism, Domain, Isolation,
    Pairing, PinnedBy, PluginRef, RateUnit, Result1, SplitDiscipline,
};

use crate::cli::ReportFormat;

/// The largest a single `result-v1` document may be before this refuses to
/// read it.
///
/// The documents this repository publishes are under two kilobytes each. The
/// only field that can grow without bound is `metrics.tpr_at_fpr`, and a map
/// with a thousand false-alarm rates in it would still be a few tens of
/// kilobytes. One mebibyte is therefore roughly a five-hundredfold headroom
/// over anything a real run writes, and it stops a report over a directory
/// from loading whatever else somebody happened to leave in there.
pub const MAX_RESULT_BYTES: u64 = 1024 * 1024;

/// The largest number of result documents one report may cover.
///
/// See the module docstring for why this is a refusal rather than a
/// truncation. Ten thousand rows is already far more than anybody reads; a
/// report that needs more is a query, and the answer is to narrow the paths
/// or work from `--format csv`.
pub const MAX_RESULTS: usize = 10_000;

/// How deep a directory walk descends before refusing.
///
/// Results live one or two directories under whatever a user points at.
/// Eight levels is generous, bounded, and stops a cycle made of directory
/// links from turning a report into an infinite walk. Symbolic links to
/// directories are not followed at all, so the depth cap is a second line
/// rather than the only one.
pub const MAX_DEPTH: usize = 8;

/// How many per-arm lines one table prints before it names the rest instead.
///
/// A Core tier run breaks down into 39 arms and a report may hold thousands of
/// documents, so an uncapped breakdown is a wall of text nobody reads with the
/// main table buried somewhere above it. Two hundred lines is five such runs,
/// which is more than anybody compares by eye and far short of the wall.
///
/// This one truncates where [`MAX_RESULTS`] refuses, and the difference is
/// that nothing is lost here: the documents are all still in the table above,
/// the count of what is not shown is printed, and `--format csv` and `--json`
/// carry every arm of every document with no cap at all.
pub const MAX_ARM_LINES_SHOWN: usize = 200;

/// Why a whole report could not be produced.
///
/// A single unreadable file is NOT one of these: that is a recorded skip
/// which appears in the output (see [`Skipped`]), because dropping one
/// document silently is how a table comes to look complete while it is not.
/// These are the cases where there is no honest table to print at all.
#[derive(Debug, thiserror::Error)]
pub enum ReportError {
    #[error("cannot read {path}: {}", crate::plain_io(.source))]
    Read {
        path: String,
        #[source]
        source: std::io::Error,
    },
    /// A path named on the command line that is not there, or cannot be
    /// opened at all.
    ///
    /// Kept apart from [`ReportError::Read`] because it is the same fault
    /// `score --corpus /nope` answers, and the two disagreed: `score` crafted
    /// an explanation and returned a refusal, while `report` handed back
    /// `No such file or directory (os error 2)` under exit 1. One kind of
    /// mistake, two exit codes and two registers.
    #[error(
        "{path} cannot be read: {why}.\n\
         `report` takes result documents, or the directories `score --out` \
         wrote them to. Check the path, and `stegobench score --help` says \
         where the documents land"
    )]
    PathUnusable { path: String, why: String },
    #[error(
        "nothing under {paths} is a result document, so there is no table to \
         print. An empty table under an exit code of zero reads as \"checked, \
         nothing to worry about\", which is a different claim from \"nothing \
         was found\". Point this at result-v1 files, or at a directory holding \
         them"
    )]
    NothingFound { paths: String },
    #[error(
        "{found} result documents were found under {paths} and this refuses \
         past {cap}. A table nobody reads is not the problem; a table that \
         quietly stopped short would be. Narrow the paths, or ask for \
         --format csv over smaller batches"
    )]
    TooMany {
        found: usize,
        cap: usize,
        paths: String,
    },
    #[error(
        "the directory tree under {path} goes deeper than {cap} levels. \
         Refusing rather than walking further: results sit one or two levels \
         down, and anything deeper is more likely a link cycle than a corpus \
         of measurements"
    )]
    TooDeep { path: String, cap: usize },
    #[error("could not write the report to {path}: {source}")]
    Write {
        path: String,
        #[source]
        source: std::io::Error,
    },
}

impl ReportError {
    /// Which documented exit code this is.
    ///
    /// The split follows the same rule the rest of this binary uses: a
    /// refusal is something that will refuse again if retried unchanged, and
    /// a failure is something that might not.
    pub fn exit_code(&self) -> i32 {
        match self {
            // The command points somewhere with nothing in it. The fix is in
            // the command, so this is a usage error rather than a breakage.
            ReportError::NothingFound { .. } => exit::USAGE,
            // Capable of it, declining. Retrying unchanged refuses again.
            // The same code `score` returns for a `--corpus` that is not
            // there. Retrying unchanged refuses again.
            ReportError::TooMany { .. }
            | ReportError::TooDeep { .. }
            | ReportError::PathUnusable { .. } => exit::PREFLIGHT_REFUSED,
            ReportError::Read { .. } | ReportError::Write { .. } => exit::FAILURE,
        }
    }
}

/// A file that was found, could not be turned into a row, and is named in the
/// output for it.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Skipped {
    pub path: String,
    pub reason: String,
    /// True where the file was found but is not a valid `result-v1`, as
    /// opposed to not being readable at all. The two exit differently.
    pub invalid_document: bool,
}

/// One measurement, flattened into the cells a table needs.
#[derive(Debug, Clone)]
pub struct Row {
    pub source: String,
    pub detector: String,
    pub subject_version: String,
    /// What names the bytes that ran: `image-digest`, `executable-hash`,
    /// `unpinned`, `mixed` where the plugins of one run disagree, or
    /// `unrecorded` where the document named none.
    pub pinned_by: &'static str,
    /// What those bytes could reach, in the same five shapes.
    pub isolation: &'static str,
    pub corpus_name: String,
    pub corpus_digest: String,
    pub corpus_source: CorpusSource,
    pub corpus_tier: Option<String>,
    pub corpus_pairs: u64,
    pub configuration: Configuration,
    pub embedder: String,
    pub rate: Option<(f64, RateUnit)>,
    pub domain: Domain,
    pub format: String,
    pub auc: f64,
    /// The 95 per cent interval, in the same cell as the figure it qualifies.
    ///
    /// In the cell rather than in a column of its own, for the reason every
    /// other condition is in a cell: a row somebody copies out of the middle
    /// of a table takes its caveats with it whether they meant to or not,
    /// and an AUC of 0.60 whose interval runs from 0.29 to 0.91 is a
    /// different claim from one that runs from 0.59 to 0.61.
    pub auc_ci95: Option<[f64; 2]>,
    pub tpr_at_fpr: BTreeMap<String, f64>,
    /// The false-alarm rate each of those figures actually came from, keyed
    /// identically. Empty for a document written before the field existed.
    pub fpr_achieved: BTreeMap<String, f64>,
    /// The same measurement taken again within each arm, ordered by arm name.
    ///
    /// Empty for a document whose corpus holds fewer than two named arms, and
    /// a row whose breakdown is empty renders exactly as it did before there
    /// was one: an empty column of "not applicable" on the common case is
    /// noise, and noise is what a reader learns to skip past.
    pub per_arm: Vec<ArmMetrics>,
    pub pairing: Pairing,
    pub split: SplitDiscipline,
    pub n_clean: u64,
    pub n_stego: u64,
    pub n_error: u64,
    pub trained_on: Option<String>,
    pub self_reported: bool,
    pub network_reachable: bool,
    pub harness_version: String,
    pub started_utc: String,
    /// The conditions that a reader must not be able to miss, spelled out as
    /// words rather than symbols, because a legend is something a lifted row
    /// leaves behind.
    pub flags: Vec<String>,
}

impl Row {
    /// The arm, as a person describes it out loud.
    pub fn arm(&self) -> String {
        match self.rate {
            None => self.embedder.clone(),
            Some((v, RateUnit::Bpp)) => format!("{} at {v} bpp", self.embedder),
            // Rendered as a percentage because that is how the JPEG tools are
            // driven and how every paper states it. The unit travels with the
            // number: 5% of capacity and 0.05 bits per pixel are different
            // quantities and a bare 0.05 in a table invites the comparison.
            Some((v, RateUnit::CapacityFraction)) => {
                format!("{} at {:.3}% of capacity", self.embedder, v * 100.0)
            }
        }
    }

    /// The sort key. Deliberately not the score: see the module docstring.
    fn order(&self) -> (String, String, String, String, String) {
        let rate = match self.rate {
            // Zero-padded so it sorts numerically as text, and the unit leads
            // so two units never interleave into a false ordering.
            Some((v, unit)) => format!("{}-{:016.6}", unit_str(unit), v),
            None => "0-none".to_string(),
        };
        (
            self.embedder.clone(),
            rate,
            self.detector.clone(),
            self.subject_version.clone(),
            self.source.clone(),
        )
    }
}

/// Rows that may honestly sit in one table: one corpus, by digest, and one
/// configuration.
#[derive(Debug, Clone)]
pub struct Group {
    pub corpus_name: String,
    pub corpus_digest: String,
    pub configuration: Configuration,
    pub rows: Vec<Row>,
}

impl Group {
    /// The sentence that goes under the heading, saying what these numbers
    /// may be put beside.
    pub fn comparability(&self) -> String {
        match self.configuration {
            Configuration::Named => format!(
                "NAMED: quotable beside another `named` run over this same \
                 digest of {}, and beside nothing else.",
                self.corpus_name
            ),
            Configuration::Custom => format!(
                "CUSTOM: {} declared no digest in advance. Quote these \
                 figures beside nothing else.",
                self.corpus_name
            ),
        }
    }
}

/// Everything a report renders from, already grouped, sorted and bounded.
#[derive(Debug, Clone)]
pub struct Report {
    pub groups: Vec<Group>,
    pub skipped: Vec<Skipped>,
    /// How many result documents made it into a group.
    pub read: usize,
    /// The paths the user asked for, as typed, for the preamble.
    pub asked_for: Vec<String>,
}

impl Report {
    /// Whether any figure in this report may be put beside any other.
    ///
    /// False whenever there is more than one group, which is the common case
    /// and the one a reader is most likely to get wrong.
    pub fn any_cross_group_comparison_is_valid(&self) -> bool {
        self.groups.len() <= 1
    }

    /// The exit code the command should leave with.
    ///
    /// A report that dropped a document is not a success. It still prints,
    /// because a named skip in the output is far more use than a bare error,
    /// but the code says the table is incomplete so a script cannot treat it
    /// as whole. An invalid document is a schema failure; an unreadable file
    /// is an ordinary one.
    pub fn exit_code(&self) -> i32 {
        if self.skipped.iter().any(|s| s.invalid_document) {
            exit::SCHEMA_INVALID
        } else if !self.skipped.is_empty() {
            exit::FAILURE
        } else {
            exit::OK
        }
    }
}

// ── gathering ───────────────────────────────────────────────────────────────

/// Collects every `*.json` under `paths`, in a deterministic order.
///
/// A path named on the command line is taken as given, whatever its
/// extension, because the user asked for that file by name. A directory is
/// walked for `*.json` only, so a README beside the results is not reported
/// as a broken document.
fn discover(paths: &[PathBuf]) -> Result<(Vec<PathBuf>, Vec<Skipped>), ReportError> {
    let mut found = Vec::new();
    let mut skipped = Vec::new();
    for path in paths {
        let meta = std::fs::metadata(path).map_err(|e| match e.kind() {
            std::io::ErrorKind::NotFound | std::io::ErrorKind::PermissionDenied => {
                ReportError::PathUnusable {
                    path: path.display().to_string(),
                    why: crate::plain_io(&e),
                }
            }
            _ => ReportError::Read {
                path: path.display().to_string(),
                source: e,
            },
        })?;
        if meta.is_dir() {
            walk(path, 0, &mut found, &mut skipped)?;
        } else {
            found.push(path.clone());
        }
        if found.len() > MAX_RESULTS {
            return Err(ReportError::TooMany {
                found: found.len(),
                cap: MAX_RESULTS,
                paths: display_paths(paths),
            });
        }
    }
    // Sorted here, at the boundary between the filesystem and everything
    // downstream, because `read_dir` order is whatever the filesystem feels
    // like and two runs over the same directory must produce identical bytes.
    found.sort();
    found.dedup();
    Ok((found, skipped))
}

fn walk(
    dir: &Path,
    depth: usize,
    found: &mut Vec<PathBuf>,
    skipped: &mut Vec<Skipped>,
) -> Result<(), ReportError> {
    if depth >= MAX_DEPTH {
        return Err(ReportError::TooDeep {
            path: dir.display().to_string(),
            cap: MAX_DEPTH,
        });
    }
    let entries = std::fs::read_dir(dir).map_err(|e| ReportError::Read {
        path: dir.display().to_string(),
        source: e,
    })?;
    for entry in entries {
        let entry = entry.map_err(|e| ReportError::Read {
            path: dir.display().to_string(),
            source: e,
        })?;
        let path = entry.path();
        // `file_type` does not follow the link, which is the point: a link
        // pointing back up the tree would otherwise be a cycle.
        let kind = entry.file_type().map_err(|e| ReportError::Read {
            path: path.display().to_string(),
            source: e,
        })?;
        if kind.is_symlink() {
            // Recorded rather than passed over. A walk that quietly dropped a
            // linked result would produce a table short by one row with
            // nothing in the output saying so, which is the failure this
            // whole module is built around. Only links that look like they
            // were meant to be results are worth naming; a link to a README
            // is not a gap in anything.
            if path.extension().is_some_and(|e| e == "json") {
                skipped.push(Skipped {
                    path: path.display().to_string(),
                    reason: "is a symbolic link, and a directory walk does \
                             not follow links. Name it on the command line to \
                             include it"
                        .to_string(),
                    invalid_document: false,
                });
            }
            continue;
        }
        if kind.is_dir() {
            walk(&path, depth + 1, found, skipped)?;
        } else if path.extension().is_some_and(|e| e == "json") {
            found.push(path);
        }
        if found.len() > MAX_RESULTS {
            return Err(ReportError::TooMany {
                found: found.len(),
                cap: MAX_RESULTS,
                paths: dir.display().to_string(),
            });
        }
    }
    Ok(())
}

/// Reads one file into a `Result1`, or into the reason it is not one.
fn load(path: &Path) -> Result<Result1, Skipped> {
    let shown = path.display().to_string();
    let unreadable = |e: std::io::Error| Skipped {
        path: shown.clone(),
        reason: format!("cannot be read: {e}"),
        invalid_document: false,
    };
    // Bounded at the read itself rather than by asking for the size first and
    // then reading without a limit. The two-step version has a window where
    // the file grows between the question and the answer, and the whole point
    // of the cap is that no answer this gives depends on a file being the
    // size it was a moment ago.
    let file = std::fs::File::open(path).map_err(unreadable)?;
    let mut text = String::new();
    std::io::Read::read_to_string(&mut file.take(MAX_RESULT_BYTES + 1), &mut text)
        .map_err(unreadable)?;
    if text.len() as u64 > MAX_RESULT_BYTES {
        return Err(Skipped {
            path: shown,
            reason: format!(
                "is larger than the {MAX_RESULT_BYTES} byte cap this reads a \
                 result document up to. A real result-v1 document is a couple \
                 of kilobytes"
            ),
            invalid_document: false,
        });
    }
    let parsed: Result1 = serde_json::from_str(&text).map_err(|e| Skipped {
        path: shown.clone(),
        reason: format!("is not a result-v1 document: {e}"),
        invalid_document: true,
    })?;
    parsed.validate().map_err(|problems| Skipped {
        path: shown,
        reason: format!("does not validate: {}", problems.join("; ")),
        invalid_document: true,
    })?;
    Ok(parsed)
}

/// One word for a whole run, where a run can name several plugins.
///
/// Neither "mixed" nor "unrecorded" is a value the schema carries: they are
/// what a row says when the plugins disagree, or when the document named no
/// plugin at all. Both are said rather than collapsed into the commonest
/// value, because every answer here is a claim about what produced the number.
fn agreed(plugins: &[PluginRef], of: impl Fn(&PluginRef) -> &'static str) -> &'static str {
    let mut seen = plugins.iter().map(of);
    match seen.next() {
        None => "unrecorded",
        Some(first) if seen.all(|other| other == first) => first,
        Some(_) => "mixed",
    }
}

/// Turns a document into a row, working out the conditions that go beside the
/// number.
/// The plugins in one result whose determinism is the given value.
///
/// Names them rather than counting, because the reader's next question after
/// "this run is not reproducible" is always "which part of it".
fn named(r: &Result1, want: Determinism) -> String {
    let mut names: Vec<&str> = r
        .provenance
        .plugins
        .iter()
        .filter(|p| p.determinism == want)
        .map(|p| p.name.as_str())
        .collect();
    names.sort_unstable();
    names.join(", ")
}

fn to_row(source: &Path, r: Result1) -> Row {
    let pinned_by = agreed(&r.provenance.plugins, |p| match p.pinned_by {
        PinnedBy::ImageDigest => "image-digest",
        PinnedBy::ExecutableHash => "executable-hash",
        PinnedBy::Unpinned => "unpinned",
    });
    let isolation = agreed(&r.provenance.plugins, |p| match p.isolation {
        Isolation::SandboxNoNetwork => "sandbox-no-network",
        Isolation::Host => "host",
        Isolation::RemoteService => "remote-service",
        Isolation::Unstated => "unstated",
    });

    let mut flags = Vec::new();
    match r.declarations.pairing {
        Pairing::SingleVariable => {}
        // These repeat on every flagged row, so each is a label and a clause,
        // not a sentence. `stegobench help pairing` and `help splits` carry
        // the reasoning.
        Pairing::Confounded => {
            flags.push("CONFOUNDED: the pair differs in more than the payload".to_string())
        }
        // THE TWO UNVERIFIED CASES ARE NOT THE SAME CLAIM.
        //
        // One is a corpus whose records never said what the clean half was, and
        // "nothing could be compared" is the whole truth about it. The other is
        // a corpus whose records named a clean half it did not ship, which a
        // researcher demonstrated is reachable from a confounded corpus by
        // pointing one field at a file that is not there: the check cannot run,
        // the row says `unverified`, and `help results` tells a reader to treat
        // that as "nothing is claimed" rather than as a warning. Separated here
        // because this table is what a reviewer reads.
        Pairing::Unverified if r.declarations.pairing_evidence.named_a_half_not_here > 0 => flags
            .push(format!(
                "PAIRING UNVERIFIED: {} pair(s) name a clean half this corpus \
                 does not contain, so the rule could not be checked on a corpus \
                 that asked for it to be",
                r.declarations.pairing_evidence.named_a_half_not_here
            )),
        Pairing::Unverified => {
            flags.push("PAIRING UNVERIFIED: nothing could be compared".to_string())
        }
    }
    // A RUN THAT ASKED THE DETECTOR NOTHING IS NOT A MEASUREMENT OF IT.
    //
    // Resuming is legitimate and a Core tier run depends on it, so this is not
    // a refusal. But a document whose every answer came off disk summarises a
    // file this run did not produce, and a researcher demonstrated the obvious
    // consequence: hand-write the file, score it, and the harness seals a
    // perfect result without anything being edited afterwards. The terminal
    // said so; this table did not, and this table is what a reviewer reads.
    if r.provenance.answers.resumed > 0 && r.provenance.answers.measured == 0 {
        flags.push(format!(
            "NOTHING MEASURED HERE: all {} answer(s) were already in the \
             records file, so this run summarised them rather than producing \
             them",
            r.provenance.answers.resumed
        ));
    }
    if r.declarations.split_discipline == SplitDiscipline::ByFile {
        flags.push("SPLIT BY FILE: inflates every number here".to_string());
    }
    if r.metrics.n_error > 0 {
        flags.push(format!(
            "{} image(s) unscored and not counted",
            r.metrics.n_error
        ));
    }
    // Against the id as well as the display name, and case folded. The two
    // differ, and comparing only the name cleared the one person who had
    // declared the contamination precisely: `--trained-on stegobench-starter`
    // is the id `list corpora` prints, while the corpus renders as
    // `Stegobench starter corpus`, so the careful declaration read as a
    // different corpus and the flag stayed off.
    if r.declarations.trained_on.as_deref().is_some_and(|t| {
        let t = t.trim();
        t.eq_ignore_ascii_case(r.corpus.name.trim())
            || r.corpus
                .id
                .as_deref()
                .is_some_and(|id| t.eq_ignore_ascii_case(id.trim()))
    }) {
        flags.push("TRAINED ON THIS CORPUS: not being measured".to_string());
    } else if let Some(trained) = r.declarations.trained_on.as_deref() {
        // THE DECLARATION SURVIVES EVEN WHEN THE MATCH FAILS.
        //
        // This table used to drop `trained_on` entirely whenever the names did
        // not match, so the one honest thing a submitter did, saying what their
        // detector learned from, disappeared from the artefact while staying in
        // the JSON. A researcher got from flagged to unflagged with `cp -r`: the
        // copy has a different name, the names stop matching, and the row went
        // quiet about a declaration that had not changed.
        //
        // Said in two different strengths, because a corpus nothing could
        // identify is a weaker statement than one that was identified and
        // genuinely differs.
        if r.declarations.contamination_check == ContaminationCheck::DeclaredButUncheckable {
            flags.push(format!(
                "TRAINED ON {trained}, AND THIS CORPUS COULD NOT BE IDENTIFIED: \
                 the two were compared by name, so whether they are the same \
                 corpus is unknown rather than no"
            ));
        } else {
            flags.push(format!("trained on {trained}, which is not this corpus"));
        }
    }
    if let Some(side) = r.declarations.split_scored.as_deref() {
        flags.push(format!("scored the {side} split only"));
    } else if r.declarations.split_discipline != SplitDiscipline::NotApplicable {
        // A whole-corpus run over a corpus that HAS a split is the case the
        // researcher used: for a detector that learned nothing it is harmless,
        // and for one that learned anything it makes the figure unquotable,
        // while the row's only split column reads `by-cover` either way.
        flags.push(
            "SCORED TRAIN AND TEST TOGETHER: quotable only for a detector that \
             learned nothing from this corpus"
                .to_string(),
        );
    }
    if r.declarations.self_reported {
        flags.push("self-reported, not re-run by anybody else".to_string());
    }
    if r.corpus.digest.is_empty() {
        flags.push("NO CORPUS DIGEST: nobody can check which bytes this measured".to_string());
    }
    // Named rather than blanket, and the two cases are kept apart. This
    // warning used to fire on every row in every report, because the value
    // was hardcoded rather than read from anywhere, and a warning that is
    // always on is one a reader learns to skip past. "Somebody measured this
    // tool and it varies" and "nobody has checked" are different facts and
    // only the first is a reason to distrust the number.
    let varies = named(&r, Determinism::Nondeterministic);
    if !varies.is_empty() {
        flags.push(format!(
            "NONDETERMINISTIC: two runs need not agree ({varies})"
        ));
    }
    let unchecked = named(&r, Determinism::Unstated);
    if !unchecked.is_empty() {
        flags.push(format!(
            "determinism unstated, so reproducibility is unverified ({unchecked})"
        ));
    }
    if r.provenance.network_reachable {
        flags.push("the plugins could reach the network during this run".to_string());
    }

    // By arm name and deliberately not by score, for the reason the rows
    // themselves are not ordered by score: an ordering is read as a ranking
    // whatever the prose beside it says.
    let mut per_arm = r.metrics.per_arm;
    per_arm.sort_by(|a, b| a.arm.cmp(&b.arm));

    Row {
        source: source.display().to_string(),
        detector: r.subject.name,
        subject_version: r.subject.version,
        pinned_by,
        isolation,
        corpus_name: r.corpus.name,
        corpus_digest: r.corpus.digest,
        corpus_source: r.corpus.source,
        corpus_tier: r.corpus.tier,
        corpus_pairs: r.corpus.pairs,
        configuration: r.declarations.configuration,
        embedder: r.arm.embedder,
        rate: r.arm.rate.map(|x| (x.value, x.unit)),
        domain: r.arm.domain,
        format: r.arm.format,
        auc: r.metrics.auc,
        auc_ci95: r.metrics.auc_ci95,
        tpr_at_fpr: r.metrics.tpr_at_fpr,
        fpr_achieved: r.metrics.fpr_achieved,
        per_arm,
        pairing: r.declarations.pairing,
        split: r.declarations.split_discipline,
        n_clean: r.metrics.n_clean,
        n_stego: r.metrics.n_stego,
        n_error: r.metrics.n_error,
        trained_on: r.declarations.trained_on,
        self_reported: r.declarations.self_reported,
        network_reachable: r.provenance.network_reachable,
        harness_version: r.provenance.harness_version,
        started_utc: r.provenance.started_utc,
        flags,
    }
}

/// Reads every result under `paths` and groups what it finds.
pub fn build(paths: &[PathBuf]) -> Result<Report, ReportError> {
    let (files, mut skipped) = discover(paths)?;
    let mut rows: Vec<Row> = Vec::new();

    for file in &files {
        match load(file) {
            Ok(doc) => rows.push(to_row(file, doc)),
            Err(s) => skipped.push(s),
        }
    }

    if rows.is_empty() && skipped.is_empty() {
        return Err(ReportError::NothingFound {
            paths: display_paths(paths),
        });
    }

    // Two documents naming the same corpus with two different digests are two
    // corpora here. The digest names the bytes; the name is a label somebody
    // chose, and putting the two in one table on the strength of the label is
    // exactly the comparison this refuses to make.
    let mut buckets: BTreeMap<(u8, String, String), Vec<Row>> = BTreeMap::new();
    for row in rows {
        // `named` sections lead, because they are the ones somebody else's
        // number can join. The rank is part of the key so the order is a
        // property of the sort rather than of a later shuffle.
        let rank = match row.configuration {
            Configuration::Named => 0,
            Configuration::Custom => 1,
        };
        buckets
            .entry((rank, row.corpus_name.clone(), row.corpus_digest.clone()))
            .or_default()
            .push(row);
    }

    let mut read = 0;
    let mut groups = Vec::new();
    for ((rank, corpus_name, corpus_digest), mut rows) in buckets {
        rows.sort_by_key(|r| r.order());
        mark_repeats(&mut rows);
        read += rows.len();
        groups.push(Group {
            corpus_name,
            corpus_digest,
            configuration: if rank == 0 {
                Configuration::Named
            } else {
                Configuration::Custom
            },
            rows,
        });
    }

    skipped.sort();
    Ok(Report {
        groups,
        skipped,
        read,
        asked_for: paths.iter().map(|p| p.display().to_string()).collect(),
    })
}

/// Marks the case where one group holds more than one measurement of the same
/// detector on the same arm.
///
/// Two rows that look like one thing measured twice are a reader's invitation
/// to pick the flattering one, or to assume one of them is a typo. Saying so
/// in the row costs nothing and removes the guess.
fn mark_repeats(rows: &mut [Row]) {
    let mut counts: HashMap<(String, String, String), usize> = HashMap::new();
    for row in rows.iter() {
        *counts
            .entry((row.detector.clone(), row.embedder.clone(), row.arm()))
            .or_default() += 1;
    }
    for row in rows.iter_mut() {
        let key = (row.detector.clone(), row.embedder.clone(), row.arm());
        if let Some(&n) = counts.get(&key) {
            if n > 1 {
                row.flags.push(format!(
                    "one of {n} runs of this detector on this arm in this \
                     report; they are separate measurements, not a best-of"
                ));
            }
        }
    }
}

fn display_paths(paths: &[PathBuf]) -> String {
    paths
        .iter()
        .map(|p| p.display().to_string())
        .collect::<Vec<_>>()
        .join(", ")
}

// ── rendering ───────────────────────────────────────────────────────────────

/// Eight hex characters of a digest, with the full value left to the heading
/// and to `--format csv`.
///
/// Abbreviated rather than dropped: a reader comparing two rows needs to see
/// at a glance that two corpora with one name are not one corpus, and eight
/// characters does that without a sixty-four character column nobody reads.
pub fn abbreviate(digest: &str) -> String {
    if digest.is_empty() {
        return "none".to_string();
    }
    // Sliced by characters rather than by bytes. A digest is hex in every
    // document this repository has ever written, and this string arrived from
    // a JSON file somebody else may have produced, so a byte slice through
    // the middle of a multi-byte character would panic on their input rather
    // than ours.
    let first_eight = |s: &str| s.chars().take(8).collect::<String>();
    match digest.split_once(':') {
        Some((algo, hex)) => {
            if hex.chars().count() > 8 {
                format!("{algo}:{}", first_eight(hex))
            } else {
                digest.to_string()
            }
        }
        None => {
            if digest.chars().count() > 8 {
                first_eight(digest)
            } else {
                digest.to_string()
            }
        }
    }
}

fn unit_str(unit: RateUnit) -> &'static str {
    match unit {
        RateUnit::Bpp => "bpp",
        RateUnit::CapacityFraction => "capacity_fraction",
    }
}

fn domain_str(d: Domain) -> &'static str {
    match d {
        Domain::Spatial => "spatial",
        Domain::Jpeg => "jpeg",
        Domain::Structural => "structural",
        Domain::Mixed => "mixed",
        Domain::Unstated => "unstated",
    }
}

fn pairing_str(p: Pairing) -> &'static str {
    match p {
        Pairing::SingleVariable => "single-variable",
        Pairing::Confounded => "confounded",
        Pairing::Unverified => "unverified",
    }
}

fn split_str(s: SplitDiscipline) -> &'static str {
    match s {
        SplitDiscipline::ByCover => "by-cover",
        SplitDiscipline::ByFile => "by-file",
        SplitDiscipline::NotApplicable => "not-applicable",
    }
}

fn configuration_str(c: Configuration) -> &'static str {
    match c {
        Configuration::Named => "named",
        Configuration::Custom => "custom",
    }
}

fn source_str(s: CorpusSource) -> &'static str {
    match s {
        CorpusSource::Fetched => "fetched",
        CorpusSource::Supplied => "supplied",
    }
}

/// The detection rate at a given false-alarm rate, matched numerically.
///
/// The keys are decimal fractions written as text, so "0.1" and "0.10" are
/// the same rate written two ways and a string lookup would find one of them.
fn tpr_at(map: &BTreeMap<String, f64>, target: f64) -> Option<f64> {
    map.iter()
        .find(|(k, _)| k.parse::<f64>().is_ok_and(|v| (v - target).abs() < 1e-9))
        .map(|(_, v)| *v)
}

/// Whether a figure filed under `target` was measured at a lower false-alarm
/// rate than `target`, because the corpus is too coarse to express it.
///
/// With six clean images the only rates that exist are multiples of one sixth,
/// so a one per cent budget buys exactly what a zero per cent budget buys. The
/// arithmetic is right and conservative; the heading is what it cannot
/// support, and this is the column somebody acts on.
fn budget_unexpressible(row: &Row, target: f64) -> Option<f64> {
    tpr_at(&row.fpr_achieved, target).filter(|a| *a < target - 1e-9)
}

fn tpr_cell(row: &Row, target: f64) -> String {
    match tpr_at(&row.tpr_at_fpr, target) {
        // The achieved rate goes in the cell rather than in a footnote,
        // because the cell is what gets copied out on its own.
        Some(v) => match budget_unexpressible(row, target) {
            Some(achieved) => format!("{v:.4} at {} FA", percent(achieved)),
            None => format!("{v:.4}"),
        },
        // Not a dash and not a zero. Both read as an answer, and the truth is
        // that this run did not report that point on the curve.
        None => "not reported".to_string(),
    }
}

/// A false-alarm rate as the headings write one, so the cell and the column it
/// sits under are in the same units.
fn percent(rate: f64) -> String {
    let shown = format!("{:.2}", rate * 100.0);
    format!("{}%", shown.trim_end_matches('0').trim_end_matches('.'))
}

/// The sentence under a table holding at least one such cell.
const FA_NOTE: &str = "Where a cell names a false-alarm rate after the figure, \
                       the run was measured at that rate rather than at the one \
                       its column asks for: this corpus has too few clean \
                       images to express that budget, so the figure is real and \
                       the heading is not.";

fn any_budget_unexpressible(group: &Group) -> bool {
    group.rows.iter().any(|r| {
        FIXED_FPR_COLUMNS
            .iter()
            .any(|t| budget_unexpressible(r, *t).is_some())
    })
}

/// The two points on the curve every table carries a column for.
const FIXED_FPR_COLUMNS: [f64; 2] = [0.01, 0.10];

/// The flags, joined for a single cell.
fn flags_cell(flags: &[String]) -> String {
    if flags.is_empty() {
        // Deliberately not "ok" or "clean". Neither is a claim this can make:
        // nothing was flagged, which is a weaker statement and the true one.
        return "nothing flagged".to_string();
    }
    flags.join(" · ")
}

/// A figure with its interval where there is one, and bare where there is not.
///
/// Never an invented interval and never a placeholder in place of one: an AUC
/// of 0.60 whose interval runs from 0.29 to 0.91 is a different claim from one
/// that runs from 0.59 to 0.61, and a run that reported no interval has made
/// neither claim.
fn auc_cell(auc: f64, ci95: Option<[f64; 2]>) -> String {
    match ci95 {
        Some([lo, hi]) => format!("{auc:.4} [{lo:.3}, {hi:.3}]"),
        None => format!("{auc:.4}"),
    }
}

/// The columns every format agrees on, in order.
const HEADINGS: [&str; 12] = [
    "detector",
    "isolation",
    "corpus",
    "config",
    "arm",
    "domain",
    "AUC",
    "TPR@1%FA",
    "TPR@10%FA",
    "pairing",
    "split",
    "clean/stego/unscored",
];

fn cells(row: &Row) -> [String; 12] {
    [
        row.detector.clone(),
        row.isolation.to_string(),
        format!("{} @ {}", row.corpus_name, abbreviate(&row.corpus_digest)),
        configuration_str(row.configuration).to_string(),
        row.arm(),
        domain_str(row.domain).to_string(),
        auc_cell(row.auc, row.auc_ci95),
        tpr_cell(row, FIXED_FPR_COLUMNS[0]),
        tpr_cell(row, FIXED_FPR_COLUMNS[1]),
        pairing_str(row.pairing).to_string(),
        split_str(row.split).to_string(),
        format!("{}/{}/{}", row.n_clean, row.n_stego, row.n_error),
    ]
}

/// The columns of the per-arm breakdown.
///
/// Each line names its detector and its corpus rather than inheriting them
/// from a heading, for the reason every other row in this module does: a line
/// lifted out of the middle takes its conditions with it.
const ARM_HEADINGS: [&str; 5] = ["detector", "corpus", "arm", "AUC", "clean/stego"];

fn arm_cells(row: &Row, arm: &ArmMetrics) -> [String; 5] {
    [
        row.detector.clone(),
        format!("{} @ {}", row.corpus_name, abbreviate(&row.corpus_digest)),
        arm.arm.clone(),
        auc_cell(arm.auc, arm.auc_ci95),
        format!("{}/{}", arm.n_clean, arm.n_stego),
    ]
}

/// The sentence above a per-arm breakdown.
///
/// The reasoning is one line here and at length in `stegobench help reports`,
/// because it is the same reasoning every time and a paragraph repeated under
/// every table is a paragraph nobody reads twice.
const ARM_INTRO: &str = "The AUC above pools the arms this run covered, and a \
                         pooled figure describes none of them: chance on one \
                         arm beside detection on another averages to \
                         something in between that nothing measured.";

/// The per-arm lines for one table, and how many documents' breakdowns the cap
/// left out.
///
/// None where no document in the table carries a breakdown, which is the
/// common case and the one that must render as it did before.
///
/// Whole documents are kept or left out together, and once one is left out
/// every later one is too, so the cap cannot produce a breakdown that looks
/// complete for a document it cut in half or an order that depends on which
/// documents happened to be small.
fn arm_table(group: &Group) -> Option<(Vec<[String; 5]>, usize)> {
    let mut lines: Vec<[String; 5]> = Vec::new();
    let mut withheld = 0usize;
    let mut full = false;
    for row in group.rows.iter().filter(|r| !r.per_arm.is_empty()) {
        // The first document is printed whatever its size, so a corpus with
        // more arms than the cap shows its breakdown rather than nothing.
        let fits = lines.is_empty() || lines.len() + row.per_arm.len() <= MAX_ARM_LINES_SHOWN;
        if full || !fits {
            full = true;
            withheld += 1;
            continue;
        }
        for arm in &row.per_arm {
            lines.push(arm_cells(row, arm));
        }
    }
    if lines.is_empty() {
        return None;
    }
    Some((lines, withheld))
}

fn arm_withheld_note(withheld: usize) -> String {
    format!(
        "{withheld} further document(s) in this table carry a per-arm \
         breakdown that is not printed here, because this stops at \
         {MAX_ARM_LINES_SHOWN} lines. --format csv and --json carry every arm \
         of every document."
    )
}

/// The block naming what did not make it into the table.
///
/// Written at the TOP of the report rather than at the bottom. A reader who
/// stops after the first table would otherwise never learn that the table is
/// short, and the whole point of naming a skipped file is that it reaches the
/// person reading the number.
fn incompleteness(report: &Report) -> Option<String> {
    if report.skipped.is_empty() {
        return None;
    }
    let mut s = format!(
        "THIS REPORT IS INCOMPLETE. {} file(s) could not be turned into a \
         row:\n",
        report.skipped.len()
    );
    for skip in &report.skipped {
        // A two-space bullet, not a deeper indent: four spaces inside a
        // Markdown blockquote turn the line into a code block, which would
        // hide the reason behind a horizontal scrollbar in exactly the
        // artefact this block exists to be read in.
        let _ = writeln!(s, "  - {}: {}", skip.path, skip.reason);
    }
    Some(s)
}

fn preamble(report: &Report) -> String {
    let mut s = format!(
        "{} result document(s) from {}, in {} table(s).\n",
        report.read,
        display_list(&report.asked_for),
        report.groups.len()
    );
    // Both lines are load-bearing and both are one line. Why a corpus
    // boundary is not comparable, and why an ordering is not a ranking, live
    // in `stegobench help reports`.
    if !report.any_cross_group_comparison_is_valid() {
        s.push_str("Nothing may be read across a table boundary.\n");
    }
    s.push_str(
        "Ordered by arm then detector, never by score. Not a ranking. \
         (`stegobench help reports`)\n",
    );
    s
}

fn render_text(report: &Report) -> String {
    let mut out = String::new();
    if let Some(block) = incompleteness(report) {
        // Wrapped line by line rather than as one blob, so the indented list
        // of skipped paths keeps its shape.
        for line in block.lines() {
            let _ = writeln!(out, "{}", wrap(line, 78));
        }
        out.push('\n');
    }
    for line in preamble(report).lines() {
        let _ = writeln!(out, "{}", wrap(line, 78));
    }

    for group in &report.groups {
        let _ = write!(
            out,
            "\n{} ({})\ncorpus digest: {}\n\n{}\n\n",
            group.corpus_name,
            configuration_str(group.configuration),
            if group.corpus_digest.is_empty() {
                "none, so nobody can check which bytes these numbers came from"
            } else {
                &group.corpus_digest
            },
            wrap(&group.comparability(), 78)
        );

        let mut table: Vec<Vec<String>> = vec![HEADINGS.iter().map(|h| h.to_string()).collect()];
        for row in &group.rows {
            table.push(cells(row).to_vec());
        }
        // Two spaces rather than one, because twelve columns of mostly numbers
        // run together at a single space and the eye loses which figure sits
        // under which heading.
        for line in stegobench_core::table::align_with(&table, "  ") {
            let _ = writeln!(out, "{line}");
        }
        if any_budget_unexpressible(group) {
            let _ = writeln!(out, "\n{}", wrap(FA_NOTE, 78));
        }

        if let Some((lines, withheld)) = arm_table(group) {
            let _ = write!(out, "\n{}\n\n", wrap(&format!("Per arm. {ARM_INTRO}"), 78));
            let mut arms: Vec<Vec<String>> =
                vec![ARM_HEADINGS.iter().map(|h| h.to_string()).collect()];
            arms.extend(lines.into_iter().map(|l| l.to_vec()));
            for line in stegobench_core::table::align_with(&arms, "  ") {
                let _ = writeln!(out, "{line}");
            }
            if withheld > 0 {
                let _ = writeln!(out, "{}", wrap(&arm_withheld_note(withheld), 78));
            }
        }

        // The flags get their own lines under the table rather than a
        // thirteenth column, because they are sentences and a column would
        // force them into abbreviations a reader has to decode. Each line
        // names its own row, so it travels with it.
        // The conditions, spelled out under the table rather than squeezed
        // into a thirteenth column. Each one is a sentence, and a column
        // would force it into an abbreviation the reader has to decode from
        // a legend, which is the thing this whole command exists to avoid.
        //
        // Only the rows that have something to say appear here: a page of
        // "nothing flagged" would bury the handful of lines that matter, and
        // the count below says how many rows had nothing rather than leaving
        // the reader to subtract.
        let flagged: Vec<&Row> = group.rows.iter().filter(|r| !r.flags.is_empty()).collect();
        out.push('\n');
        if flagged.is_empty() {
            let _ = writeln!(
                out,
                "{}",
                wrap(
                    &format!(
                        "Nothing was flagged on any of the {} row(s).",
                        group.rows.len()
                    ),
                    78
                )
            );
        } else {
            let _ = writeln!(out, "Conditions, read before quoting a figure:");
            for row in &flagged {
                let _ = writeln!(
                    out,
                    "{}",
                    wrap(
                        &format!(
                            "  {} / {}: {}",
                            row.detector,
                            row.arm(),
                            flags_cell(&row.flags)
                        ),
                        78
                    )
                );
            }
            let quiet = group.rows.len() - flagged.len();
            if quiet > 0 {
                let _ = writeln!(
                    out,
                    "{}",
                    wrap(
                        &format!(
                            "  the other {quiet} row(s) in this table had \
                             nothing flagged"
                        ),
                        78
                    )
                );
            }
        }
        let _ = writeln!(
            out,
            "{}",
            wrap(
                "  --format csv carries the full digests and each row's \
                 source file.",
                78
            )
        );
    }
    out
}

fn render_markdown(report: &Report) -> String {
    let mut out = String::from("# Steganalysis results\n\n");
    if let Some(block) = incompleteness(report) {
        // A blockquote rather than a paragraph, so it survives being pasted
        // into a document with its own styling and still reads as a warning.
        for line in block.lines() {
            let _ = writeln!(out, "> {line}");
        }
        out.push('\n');
    }
    out.push_str(&preamble(report));
    out.push('\n');

    for group in &report.groups {
        let _ = write!(
            out,
            "## {} ({})\n\nCorpus digest: `{}`\n\n{}\n\n",
            group.corpus_name,
            configuration_str(group.configuration),
            if group.corpus_digest.is_empty() {
                "none"
            } else {
                &group.corpus_digest
            },
            group.comparability()
        );
        if group.corpus_digest.is_empty() {
            out.push_str(
                "This corpus carries no digest, so nobody can check which \
                 bytes these numbers came from.\n\n",
            );
        }
        let mut headings: Vec<String> = HEADINGS.iter().map(|h| h.to_string()).collect();
        headings.push("conditions".to_string());
        let _ = writeln!(out, "| {} |", headings.join(" | "));
        let _ = writeln!(
            out,
            "|{}|",
            headings.iter().map(|_| "---").collect::<Vec<_>>().join("|")
        );
        for row in &group.rows {
            let mut line: Vec<String> = cells(row).iter().map(|c| escape_md(c)).collect();
            line.push(escape_md(&flags_cell(&row.flags)));
            let _ = writeln!(out, "| {} |", line.join(" | "));
        }
        out.push('\n');
        if any_budget_unexpressible(group) {
            let _ = writeln!(out, "{FA_NOTE}\n");
        }

        if let Some((lines, withheld)) = arm_table(group) {
            let _ = write!(out, "### Per arm\n\n{ARM_INTRO}\n\n");
            let _ = writeln!(out, "| {} |", ARM_HEADINGS.join(" | "));
            let _ = writeln!(
                out,
                "|{}|",
                ARM_HEADINGS
                    .iter()
                    .map(|_| "---")
                    .collect::<Vec<_>>()
                    .join("|")
            );
            for line in lines {
                let cells: Vec<String> = line.iter().map(|c| escape_md(c)).collect();
                let _ = writeln!(out, "| {} |", cells.join(" | "));
            }
            let _ = writeln!(out);
            if withheld > 0 {
                let _ = writeln!(out, "{}\n", arm_withheld_note(withheld));
            }
        }
    }
    out
}

/// A pipe in a cell would end the cell early and silently shift every figure
/// on that row one column left.
fn escape_md(cell: &str) -> String {
    cell.replace('|', "\\|").replace('\n', " ")
}

fn render_csv(report: &Report) -> String {
    // A CSV cannot carry a paragraph, so the incompleteness travels as rows
    // of their own with a `record_type` that a consumer has to look at. A
    // comment line would be dropped by a strict parser, and the one thing
    // that must not be droppable is the fact that the table is short.
    let rates = fpr_columns(report);
    let mut columns: Vec<String> = [
        "record_type",
        "corpus_name",
        "corpus_digest",
        "corpus_source",
        "corpus_tier",
        "corpus_pairs",
        "configuration",
        "detector",
        "subject_version",
        "pinned_by",
        "isolation",
        "embedder",
        "arm_name",
        "rate_value",
        "rate_unit",
        "domain",
        "image_format",
        "auc",
        "auc_ci95_low",
        "auc_ci95_high",
    ]
    .iter()
    .map(|c| (*c).to_string())
    .collect();
    for (name, _) in &rates {
        columns.push(name.clone());
        columns.push(format!("{name}_achieved_fpr"));
    }
    columns.extend(
        [
            "pairing",
            "split_discipline",
            "n_clean",
            "n_stego",
            "n_error",
            "trained_on",
            "self_reported",
            "network_reachable",
            "harness_version",
            "started_utc",
            "conditions",
            "source_path",
        ]
        .iter()
        .map(|c| (*c).to_string()),
    );
    let mut out = String::new();
    let _ = writeln!(out, "{}", columns.join(","));

    for skip in &report.skipped {
        let mut line = vec![String::new(); columns.len()];
        line[0] = "skipped_file".into();
        line[columns.len() - 2] = skip.reason.clone();
        line[columns.len() - 1] = skip.path.clone();
        let _ = writeln!(
            out,
            "{}",
            line.iter()
                .map(|c| csv_field(c))
                .collect::<Vec<_>>()
                .join(",")
        );
    }

    for group in &report.groups {
        for row in &group.rows {
            let mut emit = |line: Vec<String>| {
                debug_assert_eq!(line.len(), columns.len());
                let _ = writeln!(
                    out,
                    "{}",
                    line.iter()
                        .map(|c| csv_field(c))
                        .collect::<Vec<_>>()
                        .join(",")
                );
            };
            emit(csv_line(row, None, &rates));
            // Straight after the document they break down, and uncapped:
            // this is the format a script reads, and a script that asked for
            // every field is not helped by a figure being left out of it.
            for arm in &row.per_arm {
                emit(csv_line(row, Some(arm), &rates));
            }
        }
    }
    out
}

/// One CSV line: the document as a whole, or one arm within it.
///
/// An arm line repeats every condition of the document it came from rather
/// than pointing back at a line above it. A spreadsheet gets sorted, and a row
/// whose conditions live in a neighbouring row loses them the first time
/// somebody clicks a column heading.
fn csv_line(row: &Row, arm: Option<&ArmMetrics>, rates: &[(String, f64)]) -> Vec<String> {
    let (rate_value, rate_unit) = match row.rate {
        Some((v, u)) => (v.to_string(), unit_str(u).to_string()),
        None => (String::new(), String::new()),
    };
    let (auc, ci95) = match arm {
        Some(a) => (a.auc, a.auc_ci95),
        None => (row.auc, row.auc_ci95),
    };
    let (ci_low, ci_high) = match ci95 {
        Some([lo, hi]) => (format!("{lo:.4}"), format!("{hi:.4}")),
        // Empty rather than a placeholder: this run reported no interval, and
        // any number here would be one nobody measured.
        None => (String::new(), String::new()),
    };
    // The curve was reported for the run rather than per arm, so an arm line
    // leaves these empty instead of repeating a figure that is about a
    // different population. An empty cell is also what a run that never
    // reported a given rate gets: the same "nobody measured this" the interval
    // columns already use, and a rate a document does not carry must not read
    // as a zero.
    let mut curve: Vec<String> = Vec::with_capacity(rates.len() * 2);
    for (_, rate) in rates {
        let (tpr, achieved) = match arm {
            Some(_) => (None, None),
            None => (
                tpr_at(&row.tpr_at_fpr, *rate),
                tpr_at(&row.fpr_achieved, *rate),
            ),
        };
        curve.push(tpr.map(|v| format!("{v:.4}")).unwrap_or_default());
        curve.push(achieved.map(|v| format!("{v:.4}")).unwrap_or_default());
    }

    let mut line = vec![
        match arm {
            Some(_) => "arm".to_string(),
            None => "result".to_string(),
        },
        row.corpus_name.clone(),
        row.corpus_digest.clone(),
        source_str(row.corpus_source).to_string(),
        row.corpus_tier.clone().unwrap_or_default(),
        row.corpus_pairs.to_string(),
        configuration_str(row.configuration).to_string(),
        row.detector.clone(),
        row.subject_version.clone(),
        row.pinned_by.to_string(),
        row.isolation.to_string(),
        row.embedder.clone(),
        arm.map(|a| a.arm.clone()).unwrap_or_default(),
        rate_value,
        rate_unit,
        domain_str(row.domain).to_string(),
        row.format.clone(),
        format!("{auc:.4}"),
        ci_low,
        ci_high,
    ];
    line.extend(curve);
    line.extend([
        pairing_str(row.pairing).to_string(),
        split_str(row.split).to_string(),
        match arm {
            Some(a) => a.n_clean.to_string(),
            None => row.n_clean.to_string(),
        },
        match arm {
            Some(a) => a.n_stego.to_string(),
            None => row.n_stego.to_string(),
        },
        // Unscored images are counted for the run and not attributed to an
        // arm, so an arm line leaves the cell empty rather than claiming zero.
        match arm {
            Some(_) => String::new(),
            None => row.n_error.to_string(),
        },
        row.trained_on.clone().unwrap_or_default(),
        row.self_reported.to_string(),
        row.network_reachable.to_string(),
        row.harness_version.clone(),
        row.started_utc.clone(),
        flags_cell(&row.flags),
        row.source.clone(),
    ]);
    line
}

/// One column per false-alarm rate any document in this report was scored at,
/// in numerical order.
///
/// The union across every row rather than the set the first row happened to
/// carry. Two documents scored at different budgets are ordinary, and a column
/// set taken from one of them would drop the other's figures with nothing in
/// the file saying so, which is the failure the whole module is built around.
///
/// The rate is rendered from the parsed number rather than copied from the
/// key, so "0.1" and "0.10" are one column rather than two names for one rate.
fn fpr_columns(report: &Report) -> Vec<(String, f64)> {
    let mut rates: Vec<f64> = Vec::new();
    for group in &report.groups {
        for row in &group.rows {
            // A key that is not a decimal fraction is refused by
            // `Result1::validate`, so nothing reaching here loses a column.
            for rate in row.tpr_at_fpr.keys().filter_map(|k| k.parse::<f64>().ok()) {
                if !rates.iter().any(|r| (r - rate).abs() < 1e-9) {
                    rates.push(rate);
                }
            }
        }
    }
    rates.sort_by(|a, b| a.total_cmp(b));
    rates
        .into_iter()
        .map(|rate| (format!("tpr_at_fpr_{rate}"), rate))
        .collect()
}

/// RFC 4180 quoting, written here rather than pulled in as a dependency: a
/// dozen lines of our own beats a crate in the graph for one call site.
fn csv_field(value: &str) -> String {
    if value.contains([',', '"', '\n', '\r']) {
        format!("\"{}\"", value.replace('"', "\"\""))
    } else {
        value.to_string()
    }
}

/// Wraps a sentence to a column, for the plain-text format.
///
/// Leading whitespace on the input is kept and repeated on every wrapped
/// line, so an indented list stays an indented list rather than collapsing
/// into the margin on its second line.
fn wrap(text: &str, width: usize) -> String {
    let indent: String = text.chars().take_while(|c| *c == ' ').collect();
    // A word longer than the column is never cut: breaking a digest or a path
    // in half would produce something that looks like a shorter digest.
    let room = width.saturating_sub(indent.chars().count()).max(1);
    let mut out = String::new();
    let mut line = String::new();
    for word in text.split_whitespace() {
        if !line.is_empty() && line.chars().count() + 1 + word.chars().count() > room {
            out.push_str(&indent);
            out.push_str(&line);
            out.push('\n');
            line.clear();
        }
        if !line.is_empty() {
            line.push(' ');
        }
        line.push_str(word);
    }
    if !line.is_empty() {
        out.push_str(&indent);
        out.push_str(&line);
    }
    out
}

fn display_list(items: &[String]) -> String {
    if items.is_empty() {
        return "nowhere".to_string();
    }
    items.join(", ")
}

/// Renders the report in the requested format.
pub fn render(report: &Report, format: ReportFormat) -> String {
    match format {
        ReportFormat::Text => render_text(report),
        ReportFormat::Markdown => render_markdown(report),
        ReportFormat::Csv => render_csv(report),
    }
}

/// The report as a machine reads it.
pub fn to_json(report: &Report) -> serde_json::Value {
    serde_json::json!({
        "ok": report.skipped.is_empty(),
        "results_read": report.read,
        "files_skipped": report.skipped.len(),
        "complete": report.skipped.is_empty(),
        "cross_table_comparison_valid": report.any_cross_group_comparison_is_valid(),
        "skipped": report.skipped.iter().map(|s| serde_json::json!({
            "path": s.path,
            "reason": s.reason,
            "invalid_document": s.invalid_document,
        })).collect::<Vec<_>>(),
        "groups": report.groups.iter().map(|g| serde_json::json!({
            "corpus": { "name": g.corpus_name, "digest": g.corpus_digest },
            "configuration": configuration_str(g.configuration),
            "comparability": g.comparability(),
            "rows": g.rows.iter().map(|r| serde_json::json!({
                "source": r.source,
                "detector": r.detector,
                "subject_version": r.subject_version,
                "pinned_by": r.pinned_by,
                "isolation": r.isolation,
                "corpus": {
                    "name": r.corpus_name,
                    "digest": r.corpus_digest,
                    "digest_short": abbreviate(&r.corpus_digest),
                    "source": source_str(r.corpus_source),
                    "tier": r.corpus_tier,
                    "pairs": r.corpus_pairs,
                },
                "configuration": configuration_str(r.configuration),
                "arm": r.arm(),
                "embedder": r.embedder,
                "domain": domain_str(r.domain),
                "format": r.format,
                "auc": r.auc,
                "auc_ci95": r.auc_ci95,
                "tpr_at_fpr": r.tpr_at_fpr,
                // Always present, empty object and all, for the reason
                // `per_arm` is: a key that appears for some documents and not
                // others makes every consumer handle two shapes of one answer.
                "fpr_achieved": r.fpr_achieved,
                // Always present, empty array and all, because the key being
                // absent for most documents would make every consumer handle
                // two shapes of the same answer. The values are the schema's
                // own, so an arm that reported no interval carries no
                // `auc_ci95` key rather than a null somebody reads as zero.
                "per_arm": r.per_arm,
                "pairing": pairing_str(r.pairing),
                "split_discipline": split_str(r.split),
                "n_clean": r.n_clean,
                "n_stego": r.n_stego,
                "n_error": r.n_error,
                "trained_on": r.trained_on,
                "self_reported": r.self_reported,
                "network_reachable": r.network_reachable,
                "harness_version": r.harness_version,
                "started_utc": r.started_utc,
                "conditions": r.flags,
            })).collect::<Vec<_>>(),
        })).collect::<Vec<_>>(),
    })
}

/// Writes the rendered report, complete or not at all.
///
/// Rename-on-close, per the robustness mandate: a reader who opens the path
/// sees either the previous file or the whole new one, never half a table. A
/// half-written table is the worst artefact this command could produce,
/// because it looks exactly like a complete one.
pub fn write_atomically(path: &Path, body: &str) -> Result<(), ReportError> {
    let temp = temp_path_for(path);

    let write = |temp: &Path| -> std::io::Result<()> {
        let mut file = std::fs::File::create(temp)?;
        file.write_all(body.as_bytes())?;
        // Flushed to the disk before the rename, so a crash between the two
        // cannot leave a correctly named file with nothing in it.
        file.sync_all()?;
        Ok(())
    };

    if let Err(source) = write(&temp) {
        // Never leave a .part behind, per the robustness mandate.
        let _ = std::fs::remove_file(&temp);
        return Err(ReportError::Write {
            path: path.display().to_string(),
            source,
        });
    }
    if let Err(source) = std::fs::rename(&temp, path) {
        let _ = std::fs::remove_file(&temp);
        return Err(ReportError::Write {
            path: path.display().to_string(),
            source,
        });
    }
    Ok(())
}

/// Where the half-written file lives until the rename makes it real.
///
/// Beside the destination rather than in a system temporary directory,
/// because a rename across filesystems is a copy and a copy is not atomic.
/// The process id keeps two concurrent runs writing to one destination off
/// each other's temporary file, and it never reaches the finished artefact,
/// so it costs nothing in reproducibility.
fn temp_path_for(path: &Path) -> PathBuf {
    let name = path
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| "report".to_string());
    let temp_name = format!(".{name}.part-{}", std::process::id());
    match path.parent().filter(|p| !p.as_os_str().is_empty()) {
        Some(dir) => dir.join(temp_name),
        // A bare file name: `Path::parent` is an empty path rather than None,
        // and joining onto it would produce a path starting with a separator.
        None => PathBuf::from(temp_name),
    }
}

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

    /// The plain-text format wraps its prose to a column, so an assertion on
    /// a sentence has to be made against the words rather than against the
    /// line breaks a particular column happened to produce.
    fn flat(text: &str) -> String {
        text.split_whitespace().collect::<Vec<_>>().join(" ")
    }

    fn group_named<'a>(report: &'a Report, corpus: &str) -> &'a Group {
        report
            .groups
            .iter()
            .find(|g| g.corpus_name == corpus)
            .unwrap_or_else(|| panic!("no group for {corpus}"))
    }

    fn repo_root() -> PathBuf {
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..")
    }

    fn shipped_results() -> PathBuf {
        repo_root().join("results/v1")
    }

    /// A result-v1 document, as JSON, with the knobs a test needs.
    struct Doc {
        detector: String,
        corpus: String,
        digest: String,
        configuration: String,
        pairing: String,
        split: String,
        embedder: String,
        auc: f64,
        n_error: u64,
        trained_on: Option<String>,
        /// Stego images naming a clean half the corpus does not contain.
        named_a_half_not_here: u64,
        /// Whether the contamination declaration could be checked at all.
        contamination_check: String,
        /// Which side was scored, where the run scored one.
        split_scored: Option<String>,
        /// Answers already on disk when the run started, and answers it took.
        resumed: u64,
        measured: u64,
    }

    impl Default for Doc {
        fn default() -> Self {
            Doc {
                detector: "detector-a".into(),
                corpus: "corpus-a".into(),
                digest: format!("sha256:{}", "a".repeat(64)),
                configuration: "custom".into(),
                pairing: "single-variable".into(),
                split: "not-applicable".into(),
                embedder: "suniward".into(),
                auc: 0.9,
                n_error: 0,
                trained_on: None,
                named_a_half_not_here: 0,
                contamination_check: "not-declared".into(),
                split_scored: None,
                resumed: 0,
                measured: 10,
            }
        }
    }

    impl Doc {
        fn value(&self) -> serde_json::Value {
            let mut declarations = serde_json::json!({
                "split_discipline": self.split,
                "pairing": self.pairing,
                "configuration": self.configuration,
                "self_reported": false,
                "pairing_evidence": {
                    "compared": 10 - self.named_a_half_not_here,
                    "named_a_half_not_here": self.named_a_half_not_here,
                    "differed": 0,
                },
            });
            if let Some(t) = &self.trained_on {
                declarations["trained_on"] = serde_json::json!(t);
            }
            declarations["contamination_check"] = serde_json::json!(self.contamination_check);
            if let Some(s) = &self.split_scored {
                declarations["split_scored"] = serde_json::json!(s);
            }
            serde_json::json!({
                "schema": stegobench_core::result::RESULT_SCHEMA_ID,
                "subject": {
                    "name": self.detector,
                    "version": format!("sha256:{}", "b".repeat(64)),
                    "kind": "detector",
                },
                "corpus": {
                    "name": self.corpus,
                    "source": "supplied",
                    "digest": self.digest,
                    "pairs": 10,
                },
                "arm": {
                    "embedder": self.embedder,
                    "rate": {"value": 0.4, "unit": "bpp"},
                    "domain": "spatial",
                    "format": "png",
                },
                "metrics": {
                    "auc": self.auc,
                    "tpr_at_fpr": {"0.01": 0.11, "0.1": 0.55},
                    "n_clean": 5,
                    "n_stego": 5,
                    "n_error": self.n_error,
                },
                "provenance": {
                    "plugins": [{
                        "name": self.detector,
                        "image": format!("sha256:{}", "c".repeat(64)),
                        "determinism": "exact",
                        "pinned_by": "executable-hash",
                        "isolation": "host",
                    }],
                    "harness_version": "0.1.0",
                    "started_utc": "2026-09-27T00:00:00Z",
                    "elapsed_seconds": 1.0,
                    "network_reachable": false,
                    "answers": {
                        "measured": self.measured,
                        "resumed": self.resumed,
                    },
                },
                "declarations": declarations,
            })
        }

        fn write(&self, dir: &Path, name: &str) -> PathBuf {
            let path = dir.join(name);
            std::fs::write(&path, serde_json::to_string_pretty(&self.value()).unwrap()).unwrap();
            path
        }
    }

    /// A default document with one edit applied before it is written.
    fn write_with(dir: &Path, name: &str, edit: impl FnOnce(&mut serde_json::Value)) -> PathBuf {
        let mut v = Doc::default().value();
        edit(&mut v);
        let path = dir.join(name);
        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
        path
    }

    /// The same, sealed the way `score` seals what it writes.
    fn write_sealed(dir: &Path, name: &str, edit: impl FnOnce(&mut serde_json::Value)) -> PathBuf {
        let mut v = Doc::default().value();
        edit(&mut v);
        let mut doc: Result1 = serde_json::from_value(v).expect("the fixture is a result-v1");
        doc.seal();
        let path = dir.join(name);
        std::fs::write(&path, serde_json::to_string_pretty(&doc).unwrap()).unwrap();
        path
    }

    /// How many documents `results/v1` actually holds.
    ///
    /// Counted rather than written down. This used to be the literal 24, and
    /// when three results were withdrawn the test failed with an arithmetic
    /// complaint rather than saying anything about rendering, which is what it
    /// is for. The shipped set is a fixture that changes as measurements are
    /// added and retired, and a test over it should only assert the things
    /// that are true whatever it holds.
    fn shipped_count() -> usize {
        std::fs::read_dir(shipped_results())
            .expect("results/v1 is in the repository")
            .filter_map(|e| e.ok())
            .filter(|e| e.path().extension().is_some_and(|x| x == "json"))
            .count()
    }

    #[test]
    fn the_shipped_results_produce_a_report_in_every_format() {
        let paths = vec![shipped_results()];
        let report = build(&paths).expect("the shipped results build a report");
        assert_eq!(report.read, shipped_count());
        assert!(report.read > 0, "results/v1 is empty");
        assert!(report.skipped.is_empty(), "{:?}", report.skipped);
        assert_eq!(report.exit_code(), exit::OK);
        // Every shipped document names the same corpus today, so this says
        // nothing about how several tables render. That property is covered
        // against built fixtures instead, where the shape can be chosen:
        // see the tests around one name with two digests below.
        for group in &report.groups {
            assert!(!group.rows.is_empty());
        }
        for format in [
            ReportFormat::Text,
            ReportFormat::Markdown,
            ReportFormat::Csv,
        ] {
            let text = render(&report, format);
            assert!(text.contains("round3-q95"), "{format:?}");
            assert!(!text.is_empty());
        }
    }

    /// The whole point, asserted on the real documents: a row lifted out of
    /// the table still says which corpus, which configuration, which pairing
    /// and which split.
    #[test]
    fn every_markdown_row_carries_its_conditions() {
        let report = build(&[shipped_results()]).unwrap();
        let md = render(&report, ReportFormat::Markdown);
        let rows: Vec<&str> = md
            .lines()
            .filter(|l| l.starts_with("| ") && !l.contains("detector") && !l.starts_with("|---"))
            .collect();
        assert_eq!(rows.len(), report.read, "expected one row per result");
        for row in rows {
            assert!(row.contains(" @ sha256:"), "no corpus digest in: {row}");
            assert!(row.contains("custom"), "no configuration in: {row}");
            assert!(
                row.contains("single-variable") || row.contains("confounded"),
                "no pairing in: {row}"
            );
            assert!(row.contains("not-applicable"), "no split in: {row}");
        }
    }

    /// A confounded run has to be readable as confounded from the row itself,
    /// not from a legend the row leaves behind when it is copied.
    #[test]
    fn a_confounded_run_is_marked_in_its_own_row() {
        let report = build(&[shipped_results()]).unwrap();
        let md = render(&report, ReportFormat::Markdown);
        let confounded: Vec<&str> = md
            .lines()
            .filter(|l| l.starts_with("| ") && l.contains("outguess"))
            .collect();
        assert!(!confounded.is_empty(), "no outguess rows found");
        for row in confounded {
            assert!(
                row.contains("CONFOUNDED"),
                "an outguess row does not say so: {row}"
            );
        }
    }

    /// Rung 5: a corpus that named a clean half it does not ship reads, in this
    /// table, exactly like one that claimed nothing, and `help results` tells a
    /// reader to treat that as "nothing is claimed" rather than as a warning. A
    /// submitter reaches the mild badge from the damning one by pointing a
    /// single field at a file they do not provide.
    #[test]
    fn a_corpus_that_named_a_clean_half_it_does_not_ship_says_which_in_the_row() {
        let dir = tempfile::tempdir().unwrap();
        Doc {
            pairing: "unverified".into(),
            named_a_half_not_here: 7,
            ..Doc::default()
        }
        .write(dir.path(), "a.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        for format in [
            ReportFormat::Text,
            ReportFormat::Markdown,
            ReportFormat::Csv,
        ] {
            let text = flat(&render(&report, format));
            assert!(
                text.contains("7 pair(s) name a clean half this corpus does not contain"),
                "{format:?} did not say the corpus named a half it does not ship: {text}"
            );
        }
    }

    /// And a corpus that genuinely claimed nothing keeps the shorter sentence,
    /// so the two cases cannot collapse back into one.
    #[test]
    fn a_corpus_that_claimed_nothing_is_not_accused_of_withholding_a_clean_half() {
        let dir = tempfile::tempdir().unwrap();
        Doc {
            pairing: "unverified".into(),
            ..Doc::default()
        }
        .write(dir.path(), "a.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let text = flat(&render(&report, ReportFormat::Text));
        assert!(text.contains("nothing could be compared"), "{text}");
        assert!(!text.contains("does not contain"), "{text}");
    }

    /// Rung 5: a hand-written records file, scored, yields a sealed document
    /// claiming a perfect result with nothing edited afterwards. The terminal
    /// said "nothing was scored"; this table said nothing, and this table is
    /// what a reviewer reads.
    #[test]
    fn a_run_that_measured_nothing_says_so_in_its_own_row() {
        let dir = tempfile::tempdir().unwrap();
        Doc {
            auc: 1.0,
            measured: 0,
            resumed: 10,
            ..Doc::default()
        }
        .write(dir.path(), "a.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        for format in [
            ReportFormat::Text,
            ReportFormat::Markdown,
            ReportFormat::Csv,
        ] {
            let text = flat(&render(&report, format));
            assert!(
                text.contains("NOTHING MEASURED HERE"),
                "{format:?} published a resumed-only run as a measurement: {text}"
            );
            assert!(text.contains("all 10 answer(s)"), "{text}");
        }
    }

    /// A run that resumed PART of its work is a normal interrupted run and must
    /// not be flagged, or the flag becomes one a reader skips past.
    #[test]
    fn a_partly_resumed_run_is_not_accused_of_measuring_nothing() {
        let dir = tempfile::tempdir().unwrap();
        Doc {
            measured: 6,
            resumed: 4,
            ..Doc::default()
        }
        .write(dir.path(), "a.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let text = flat(&render(&report, ReportFormat::Text));
        assert!(!text.contains("NOTHING MEASURED HERE"), "{text}");
    }

    /// Rung 5: this table dropped `trained_on` entirely whenever the declared
    /// name did not match the corpus name, so the one honest thing a submitter
    /// did disappeared from the artefact while staying in the JSON. `cp -r` was
    /// enough to get there, because the copy has a different name.
    #[test]
    fn a_declaration_that_could_not_be_checked_survives_into_the_row() {
        let dir = tempfile::tempdir().unwrap();
        Doc {
            trained_on: Some("some-other-corpus".into()),
            contamination_check: "declared-but-uncheckable".into(),
            ..Doc::default()
        }
        .write(dir.path(), "a.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        for format in [
            ReportFormat::Text,
            ReportFormat::Markdown,
            ReportFormat::Csv,
        ] {
            let text = flat(&render(&report, format));
            assert!(
                text.contains("TRAINED ON some-other-corpus"),
                "{format:?} dropped the declaration: {text}"
            );
            assert!(
                text.contains("unknown rather than no"),
                "{format:?} read an unchecked declaration as a clean one: {text}"
            );
        }
    }

    /// A declaration that WAS checked and genuinely differs keeps the quieter
    /// wording, so the loud one stays worth reading.
    #[test]
    fn a_checked_declaration_against_a_different_corpus_is_stated_quietly() {
        let dir = tempfile::tempdir().unwrap();
        Doc {
            trained_on: Some("bossbase".into()),
            contamination_check: "checked".into(),
            ..Doc::default()
        }
        .write(dir.path(), "a.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let text = flat(&render(&report, ReportFormat::Text));
        assert!(
            text.contains("trained on bossbase, which is not this corpus"),
            "{text}"
        );
        assert!(!text.contains("unknown rather than no"), "{text}");
    }

    /// Rung 5: `--split test` and a whole-corpus run produced identical
    /// documents, and the warning that says why lives in `--split --help`,
    /// which a reviewer reading a submitted artefact never sees.
    #[test]
    fn the_row_says_which_side_of_the_split_was_scored() {
        let dir = tempfile::tempdir().unwrap();
        Doc {
            split: "by-cover".into(),
            split_scored: Some("test".into()),
            ..Doc::default()
        }
        .write(dir.path(), "a.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let text = flat(&render(&report, ReportFormat::Text));
        assert!(text.contains("scored the test split only"), "{text}");
        assert!(!text.contains("SCORED TRAIN AND TEST TOGETHER"), "{text}");
    }

    /// And the whole-corpus run over a corpus that HAS a split says so, which
    /// is the case that makes a trained detector's figure unquotable.
    #[test]
    fn a_run_over_both_halves_of_a_split_corpus_says_so() {
        let dir = tempfile::tempdir().unwrap();
        Doc {
            split: "by-cover".into(),
            ..Doc::default()
        }
        .write(dir.path(), "a.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let text = flat(&render(&report, ReportFormat::Text));
        assert!(text.contains("SCORED TRAIN AND TEST TOGETHER"), "{text}");
    }

    #[test]
    fn an_unverified_pairing_is_marked_in_the_row() {
        let dir = tempfile::tempdir().unwrap();
        Doc {
            pairing: "unverified".into(),
            ..Doc::default()
        }
        .write(dir.path(), "a.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        for format in [
            ReportFormat::Text,
            ReportFormat::Markdown,
            ReportFormat::Csv,
        ] {
            assert!(
                flat(&render(&report, format)).contains("PAIRING UNVERIFIED"),
                "{format:?} hid an unverified pairing"
            );
        }
    }

    #[test]
    fn a_by_file_split_is_marked_because_it_inflates_the_number() {
        let dir = tempfile::tempdir().unwrap();
        Doc {
            split: "by-file".into(),
            ..Doc::default()
        }
        .write(dir.path(), "a.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert!(flat(&render(&report, ReportFormat::Text)).contains("SPLIT BY FILE"));
    }

    #[test]
    fn unscored_images_and_contamination_reach_the_row() {
        let dir = tempfile::tempdir().unwrap();
        Doc {
            n_error: 7,
            trained_on: Some("corpus-a".into()),
            ..Doc::default()
        }
        .write(dir.path(), "a.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let text = flat(&render(&report, ReportFormat::Text));
        assert!(text.contains("7 image(s) unscored"), "{text}");
        assert!(text.contains("TRAINED ON THIS CORPUS"), "{text}");
    }

    #[test]
    fn a_detector_trained_on_a_different_corpus_is_not_flagged_as_contaminated() {
        let dir = tempfile::tempdir().unwrap();
        Doc {
            trained_on: Some("somewhere-else".into()),
            ..Doc::default()
        }
        .write(dir.path(), "a.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert!(!flat(&render(&report, ReportFormat::Text)).contains("TRAINED ON THIS CORPUS"));
    }

    #[test]
    fn two_corpora_never_share_a_table() {
        let dir = tempfile::tempdir().unwrap();
        Doc {
            corpus: "one".into(),
            ..Doc::default()
        }
        .write(dir.path(), "a.json");
        Doc {
            corpus: "two".into(),
            digest: format!("sha256:{}", "d".repeat(64)),
            ..Doc::default()
        }
        .write(dir.path(), "b.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert_eq!(report.groups.len(), 2);
        assert!(!report.any_cross_group_comparison_is_valid());
        assert!(flat(&render(&report, ReportFormat::Text))
            .contains("Nothing may be read across a table boundary"));
    }

    /// The label is not the bytes. Two documents naming one corpus with two
    /// digests describe two sets of images, and putting them in one table on
    /// the strength of the name is the comparison this refuses to make.
    #[test]
    fn one_corpus_name_with_two_digests_is_two_tables() {
        let dir = tempfile::tempdir().unwrap();
        Doc::default().write(dir.path(), "a.json");
        Doc {
            digest: format!("sha256:{}", "e".repeat(64)),
            ..Doc::default()
        }
        .write(dir.path(), "b.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert_eq!(report.groups.len(), 2, "one name, two digests, one table");
    }

    #[test]
    fn named_and_custom_never_interleave_and_named_leads() {
        let dir = tempfile::tempdir().unwrap();
        Doc {
            configuration: "named".into(),
            ..Doc::default()
        }
        .write(dir.path(), "a.json");
        Doc {
            configuration: "custom".into(),
            detector: "detector-b".into(),
            ..Doc::default()
        }
        .write(dir.path(), "b.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert_eq!(report.groups.len(), 2);
        assert_eq!(report.groups[0].configuration, Configuration::Named);
        assert_eq!(report.groups[1].configuration, Configuration::Custom);
        for group in &report.groups {
            assert_eq!(group.rows.len(), 1, "a group mixed the two");
        }
        let text = flat(&render(&report, ReportFormat::Text));
        assert!(text.contains("Quote these figures beside nothing else"));
    }

    #[test]
    fn a_malformed_json_file_is_named_rather_than_vanishing() {
        let dir = tempfile::tempdir().unwrap();
        Doc::default().write(dir.path(), "good.json");
        std::fs::write(dir.path().join("bad.json"), "{not json").unwrap();
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert_eq!(report.read, 1);
        assert_eq!(report.skipped.len(), 1);
        assert!(report.skipped[0].invalid_document);
        assert_eq!(report.exit_code(), exit::SCHEMA_INVALID);
        for format in [
            ReportFormat::Text,
            ReportFormat::Markdown,
            ReportFormat::Csv,
        ] {
            let text = render(&report, format);
            assert!(text.contains("bad.json"), "{format:?} lost the bad file");
        }
        assert!(flat(&render(&report, ReportFormat::Text)).contains("THIS REPORT IS INCOMPLETE"));
        assert!(render(&report, ReportFormat::Csv).contains("skipped_file"));
    }

    #[test]
    fn valid_json_that_is_not_a_result_is_named_with_its_reason() {
        let dir = tempfile::tempdir().unwrap();
        Doc::default().write(dir.path(), "good.json");
        std::fs::write(dir.path().join("other.json"), r#"{"hello":"world"}"#).unwrap();
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert_eq!(report.skipped.len(), 1);
        assert!(report.skipped[0]
            .reason
            .contains("not a result-v1 document"));
        assert_eq!(report.exit_code(), exit::SCHEMA_INVALID);
    }

    /// Parses as a `result-v1` and fails the rules the type system cannot
    /// hold. It must not reach a table: an AUC of 1.4 in a row a reader
    /// quotes is worse than a named skip.
    #[test]
    fn a_result_that_parses_but_does_not_validate_is_refused_from_the_table() {
        let dir = tempfile::tempdir().unwrap();
        let mut v = Doc::default().value();
        v["metrics"]["auc"] = serde_json::json!(1.4);
        std::fs::write(
            dir.path().join("impossible.json"),
            serde_json::to_string(&v).unwrap(),
        )
        .unwrap();
        Doc::default().write(dir.path(), "good.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert_eq!(report.read, 1);
        assert_eq!(report.skipped.len(), 1);
        assert!(report.skipped[0].reason.contains("does not validate"));
        assert!(!render(&report, ReportFormat::Markdown).contains("1.4000"));
    }

    #[test]
    fn a_file_over_the_size_cap_is_skipped_with_the_cap_named() {
        let dir = tempfile::tempdir().unwrap();
        let big = "x".repeat((MAX_RESULT_BYTES + 1) as usize);
        std::fs::write(dir.path().join("huge.json"), big).unwrap();
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert!(report.groups.is_empty());
        assert_eq!(report.skipped.len(), 1);
        assert!(report.skipped[0].reason.contains("byte cap"));
        // Not a schema failure: nothing was parsed, so nothing was judged.
        assert_eq!(report.exit_code(), exit::FAILURE);
    }

    #[test]
    fn an_empty_directory_refuses_rather_than_printing_an_empty_table() {
        let dir = tempfile::tempdir().unwrap();
        let err = build(&[dir.path().to_path_buf()]).unwrap_err();
        assert!(matches!(err, ReportError::NothingFound { .. }));
        assert_eq!(err.exit_code(), exit::USAGE);
        assert!(err.to_string().contains("no table to print"));
    }

    #[test]
    fn an_empty_input_set_refuses() {
        let err = build(&[]).unwrap_err();
        assert!(matches!(err, ReportError::NothingFound { .. }));
        assert!(err.to_string().contains("nowhere") || err.to_string().contains("nothing under"));
    }

    #[test]
    fn a_directory_of_non_json_files_refuses() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("README.md"), "not a result").unwrap();
        let err = build(&[dir.path().to_path_buf()]).unwrap_err();
        assert!(matches!(err, ReportError::NothingFound { .. }));
    }

    /// `score --corpus /nope` refuses with exit 3 and an explanation, and
    /// this answered the identical mistake with the operating system's own
    /// error number under exit 1. Same fault, same code, and no `os error 2`
    /// in front of a reader.
    #[test]
    fn a_missing_path_refuses_the_way_score_refuses_one() {
        let err = build(&[PathBuf::from("/definitely/not/here")]).unwrap_err();
        assert!(matches!(err, ReportError::PathUnusable { .. }));
        assert_eq!(err.exit_code(), exit::PREFLIGHT_REFUSED);
        let said = err.to_string();
        assert!(said.contains("/definitely/not/here"), "{said}");
        assert!(said.contains("nothing is there"), "{said}");
        assert!(!said.contains("os error"), "{said}");
    }

    /// A file named on the command line is read whatever it is called. Only a
    /// directory walk filters on the extension.
    #[test]
    fn a_named_file_without_a_json_extension_is_still_read() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("result.txt");
        std::fs::write(
            &path,
            serde_json::to_string(&Doc::default().value()).unwrap(),
        )
        .unwrap();
        let report = build(&[path]).unwrap();
        assert_eq!(report.read, 1);
    }

    #[test]
    fn a_tree_deeper_than_the_cap_refuses() {
        let dir = tempfile::tempdir().unwrap();
        let mut deep = dir.path().to_path_buf();
        for i in 0..(MAX_DEPTH + 1) {
            deep = deep.join(format!("d{i}"));
        }
        std::fs::create_dir_all(&deep).unwrap();
        let err = build(&[dir.path().to_path_buf()]).unwrap_err();
        assert!(matches!(err, ReportError::TooDeep { .. }));
        assert_eq!(err.exit_code(), exit::PREFLIGHT_REFUSED);
    }

    #[test]
    fn a_nested_directory_within_the_cap_is_walked() {
        let dir = tempfile::tempdir().unwrap();
        let nested = dir.path().join("a").join("b");
        std::fs::create_dir_all(&nested).unwrap();
        Doc::default().write(&nested, "r.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert_eq!(report.read, 1);
    }

    /// Two runs over the same input produce identical bytes, whatever order
    /// the filesystem hands the directory back in.
    #[test]
    fn two_runs_over_the_same_input_are_byte_identical() {
        let dir = tempfile::tempdir().unwrap();
        for (i, name) in ["z", "m", "a", "q"].iter().enumerate() {
            Doc {
                detector: format!("detector-{name}"),
                auc: 0.5 + i as f64 / 100.0,
                ..Doc::default()
            }
            .write(dir.path(), &format!("{name}.json"));
        }
        for format in [
            ReportFormat::Text,
            ReportFormat::Markdown,
            ReportFormat::Csv,
        ] {
            let first = render(&build(&[dir.path().to_path_buf()]).unwrap(), format);
            let second = render(&build(&[dir.path().to_path_buf()]).unwrap(), format);
            assert_eq!(first, second, "{format:?} is not reproducible");
        }
        // And the shipped corpus of results, which is the realistic case.
        let a = render(&build(&[shipped_results()]).unwrap(), ReportFormat::Csv);
        let b = render(&build(&[shipped_results()]).unwrap(), ReportFormat::Csv);
        assert_eq!(a, b);
    }

    /// The same directory given twice must not double every row.
    #[test]
    fn a_path_named_twice_is_read_once() {
        let dir = tempfile::tempdir().unwrap();
        Doc::default().write(dir.path(), "a.json");
        let report = build(&[dir.path().to_path_buf(), dir.path().to_path_buf()]).unwrap();
        assert_eq!(report.read, 1);
    }

    #[test]
    fn rows_are_ordered_by_arm_and_detector_rather_than_by_score() {
        let dir = tempfile::tempdir().unwrap();
        Doc {
            detector: "zeta".into(),
            auc: 0.99,
            ..Doc::default()
        }
        .write(dir.path(), "a.json");
        Doc {
            detector: "alpha".into(),
            auc: 0.51,
            ..Doc::default()
        }
        .write(dir.path(), "b.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let names: Vec<&str> = report.groups[0]
            .rows
            .iter()
            .map(|r| r.detector.as_str())
            .collect();
        assert_eq!(names, ["alpha", "zeta"], "the table was ranked by score");
        assert!(flat(&render(&report, ReportFormat::Text)).contains("never by score"));
    }

    #[test]
    fn two_runs_of_one_detector_on_one_arm_are_marked_as_separate_measurements() {
        let dir = tempfile::tempdir().unwrap();
        Doc::default().write(dir.path(), "a.json");
        Doc {
            auc: 0.7,
            ..Doc::default()
        }
        .write(dir.path(), "b.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert_eq!(report.groups[0].rows.len(), 2);
        let text = flat(&render(&report, ReportFormat::Text));
        assert!(text.contains("one of 2 runs"), "{text}");
    }

    #[test]
    fn a_corpus_with_no_digest_says_so_in_the_row_and_in_the_heading() {
        let dir = tempfile::tempdir().unwrap();
        Doc {
            digest: String::new(),
            ..Doc::default()
        }
        .write(dir.path(), "a.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let text = flat(&render(&report, ReportFormat::Text));
        assert!(text.contains("NO CORPUS DIGEST"), "{text}");
        assert!(text.contains("nobody can check which bytes"), "{text}");
        assert!(render(&report, ReportFormat::Markdown).contains("carries no digest"));
    }

    #[test]
    fn a_missing_point_on_the_curve_is_not_reported_rather_than_zero() {
        let dir = tempfile::tempdir().unwrap();
        let mut v = Doc::default().value();
        v["metrics"]["tpr_at_fpr"] = serde_json::json!({"0.05": 0.3});
        std::fs::write(
            dir.path().join("a.json"),
            serde_json::to_string(&v).unwrap(),
        )
        .unwrap();
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let text = flat(&render(&report, ReportFormat::Text));
        assert!(text.contains("not reported"), "{text}");
        assert!(
            !text.contains("0.0000"),
            "a missing point read as zero: {text}"
        );
    }

    #[test]
    fn a_rate_carries_its_unit_into_the_arm_cell() {
        let dir = tempfile::tempdir().unwrap();
        let mut v = Doc::default().value();
        v["arm"]["rate"] = serde_json::json!({"value": 0.05, "unit": "capacity_fraction"});
        std::fs::write(
            dir.path().join("a.json"),
            serde_json::to_string(&v).unwrap(),
        )
        .unwrap();
        let mut w = Doc::default().value();
        w["arm"].as_object_mut().unwrap().remove("rate");
        w["arm"]["embedder"] = serde_json::json!("structural");
        std::fs::write(
            dir.path().join("b.json"),
            serde_json::to_string(&w).unwrap(),
        )
        .unwrap();

        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let text = flat(&render(&report, ReportFormat::Text));
        assert!(text.contains("5.000% of capacity"), "{text}");
        assert!(text.contains("structural"), "{text}");
        assert!(
            !text.contains("structural at"),
            "a rateless arm invented one"
        );
    }

    #[test]
    fn the_nondeterminism_warning_names_the_plugin_it_is_about() {
        // It used to fire on every row of every report, because the value was
        // hardcoded rather than read from anywhere. A warning that is always
        // on is one a reader stops seeing, and this one was also false: it
        // said "two runs need not agree" about tools nobody had measured.
        let dir = tempfile::tempdir().unwrap();
        let mut v = Doc::default().value();
        v["provenance"]["plugins"] = serde_json::json!([
            {"name": "steady", "image": format!("sha256:{}", "c".repeat(64)), "determinism": "exact", "pinned_by": "executable-hash", "isolation": "host"},
            {"name": "wobbly", "image": format!("sha256:{}", "d".repeat(64)), "determinism": "nondeterministic", "pinned_by": "executable-hash", "isolation": "host"},
        ]);
        std::fs::write(
            dir.path().join("a.json"),
            serde_json::to_string(&v).unwrap(),
        )
        .unwrap();
        let text = flat(&render(
            &build(&[dir.path().to_path_buf()]).unwrap(),
            ReportFormat::Text,
        ));
        assert!(text.contains("NONDETERMINISTIC"), "{text}");
        assert!(
            text.contains("wobbly"),
            "the warning should name it: {text}"
        );
        assert!(
            !text.contains("NONDETERMINISTIC: two runs need not agree (steady"),
            "the deterministic plugin was accused: {text}"
        );
    }

    #[test]
    fn a_report_of_deterministic_plugins_carries_no_determinism_warning() {
        // The case that proves the flag can now clear. Before, it could not.
        let dir = tempfile::tempdir().unwrap();
        let mut v = Doc::default().value();
        v["provenance"]["plugins"] = serde_json::json!([
            {"name": "steady", "image": format!("sha256:{}", "c".repeat(64)), "determinism": "exact", "pinned_by": "executable-hash", "isolation": "host"},
        ]);
        std::fs::write(
            dir.path().join("a.json"),
            serde_json::to_string(&v).unwrap(),
        )
        .unwrap();
        let text = flat(&render(
            &build(&[dir.path().to_path_buf()]).unwrap(),
            ReportFormat::Text,
        ));
        assert!(!text.contains("NONDETERMINISTIC"), "{text}");
        assert!(!text.contains("determinism unstated"), "{text}");
    }

    #[test]
    fn nobody_having_checked_is_said_differently_from_having_checked_and_found_drift() {
        // Two different facts. Only one of them is a reason to distrust the
        // number, and collapsing them is how the original warning came to
        // mean nothing.
        let dir = tempfile::tempdir().unwrap();
        let mut v = Doc::default().value();
        v["provenance"]["plugins"] = serde_json::json!([
            {"name": "unchecked", "image": format!("sha256:{}", "c".repeat(64)), "determinism": "unstated", "pinned_by": "executable-hash", "isolation": "host"},
        ]);
        std::fs::write(
            dir.path().join("a.json"),
            serde_json::to_string(&v).unwrap(),
        )
        .unwrap();
        let text = flat(&render(
            &build(&[dir.path().to_path_buf()]).unwrap(),
            ReportFormat::Text,
        ));
        assert!(text.contains("determinism unstated"), "{text}");
        assert!(text.contains("unchecked"), "{text}");
        assert!(
            !text.contains("NONDETERMINISTIC"),
            "an unmeasured tool was called nondeterministic: {text}"
        );
    }

    #[test]
    fn plugins_that_disagree_are_said_to_be_mixed_rather_than_picked_between() {
        let dir = tempfile::tempdir().unwrap();
        let mut v = Doc::default().value();
        v["provenance"]["plugins"] = serde_json::json!([
            {"name": "a", "image": format!("sha256:{}", "c".repeat(64)), "determinism": "exact", "pinned_by": "executable-hash", "isolation": "host"},
            {"name": "b", "image": format!("ghcr.io/x/y@sha256:{}", "c".repeat(64)), "determinism": "nondeterministic", "pinned_by": "image-digest", "isolation": "sandbox-no-network"},
        ]);
        v["provenance"]["network_reachable"] = serde_json::json!(true);
        std::fs::write(
            dir.path().join("a.json"),
            serde_json::to_string(&v).unwrap(),
        )
        .unwrap();
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert_eq!(report.groups[0].rows[0].pinned_by, "mixed");
        assert_eq!(report.groups[0].rows[0].isolation, "mixed");
        assert!(flat(&render(&report, ReportFormat::Text)).contains("NONDETERMINISTIC"));
    }

    #[test]
    fn a_network_reachable_run_says_so() {
        let dir = tempfile::tempdir().unwrap();
        let mut v = Doc::default().value();
        v["provenance"]["network_reachable"] = serde_json::json!(true);
        std::fs::write(
            dir.path().join("a.json"),
            serde_json::to_string(&v).unwrap(),
        )
        .unwrap();
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert!(flat(&render(&report, ReportFormat::Text)).contains("reach the network"));
    }

    #[test]
    fn a_self_reported_run_says_so() {
        let dir = tempfile::tempdir().unwrap();
        let mut v = Doc::default().value();
        v["declarations"]["self_reported"] = serde_json::json!(true);
        std::fs::write(
            dir.path().join("a.json"),
            serde_json::to_string(&v).unwrap(),
        )
        .unwrap();
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert!(render(&report, ReportFormat::Csv).contains("self-reported"));
    }

    #[test]
    fn a_row_with_nothing_flagged_does_not_claim_to_be_clean() {
        let dir = tempfile::tempdir().unwrap();
        Doc::default().write(dir.path(), "a.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        // Never "ok" and never "clean": nothing was flagged, which is the
        // weaker statement and the only true one.
        let text = flat(&render(&report, ReportFormat::Text));
        assert!(text.contains("Nothing was flagged"), "{text}");
        assert!(
            !text.contains(" ok ") && !text.contains("clean run"),
            "{text}"
        );
        assert!(render(&report, ReportFormat::Markdown).contains("| nothing flagged |"));
    }

    /// A page of "nothing flagged" would bury the handful of lines that
    /// matter, so the quiet rows are counted rather than listed. The count has
    /// to be there: a reader must not have to subtract to learn that every
    /// other row was looked at.
    #[test]
    fn the_text_conditions_list_only_the_rows_with_something_to_say() {
        let report = build(&[shipped_results()]).unwrap();
        let text = flat(&render(&report, ReportFormat::Text));
        assert!(text.contains("Conditions, read before quoting"), "{text}");
        // Derived from the report rather than typed, so adding a result to
        // the repository does not make this test wrong about arithmetic it
        // is not testing.
        let jpeg = group_named(&report, "round3-q95");
        let quiet = jpeg.rows.iter().filter(|r| r.flags.is_empty()).count();
        assert!(quiet > 0 && quiet < jpeg.rows.len(), "fixture has no mix");
        assert!(
            text.contains(&format!("the other {quiet} row(s) in this table")),
            "{text}"
        );
    }

    /// The other half of the same rule: a table where nothing was flagged says
    /// so, rather than printing an empty conditions block a reader has to
    /// interpret.
    ///
    /// Built here rather than taken from `results/v1`, which used to hold a
    /// second corpus with nothing flagged on any row. That corpus was
    /// withdrawn, and a test that depends on the shipped set happening to
    /// contain a clean table is a test that breaks for a reason unrelated to
    /// what it checks.
    #[test]
    fn a_table_with_nothing_flagged_says_so_rather_than_printing_nothing() {
        let dir = tempfile::tempdir().unwrap();
        for (i, detector) in ["detector-a", "detector-b"].iter().enumerate() {
            Doc {
                detector: (*detector).into(),
                ..Doc::default()
            }
            .write(dir.path(), &format!("{i}.json"));
        }
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let group = group_named(&report, "corpus-a");
        assert!(group.rows.iter().all(|r| r.flags.is_empty()));
        let text = flat(&render(&report, ReportFormat::Text));
        assert!(
            text.contains(&format!(
                "Nothing was flagged on any of the {} row(s)",
                group.rows.len()
            )),
            "{text}"
        );
    }

    #[test]
    fn the_csv_quotes_a_field_that_would_otherwise_break_the_row() {
        assert_eq!(csv_field("plain"), "plain");
        assert_eq!(csv_field("a,b"), "\"a,b\"");
        assert_eq!(csv_field("say \"hi\""), "\"say \"\"hi\"\"\"");
        assert_eq!(csv_field("two\nlines"), "\"two\nlines\"");
    }

    #[test]
    fn the_csv_has_one_field_per_column_on_every_row() {
        let report = build(&[shipped_results()]).unwrap();
        let csv = render(&report, ReportFormat::Csv);
        let mut lines = csv.lines();
        let columns = lines.next().unwrap().split(',').count();
        for line in lines {
            // No shipped field contains a comma or a quote, so a naive split
            // is exact here and a change that introduces one fails loudly.
            assert_eq!(
                line.split(',').count(),
                columns,
                "row has the wrong number of fields: {line}"
            );
        }
    }

    #[test]
    fn a_forged_document_is_named_as_skipped_rather_than_tabled() {
        // The finding: one field edited after the run, and the document came
        // out as an ordinary row under an exit code of zero.
        let dir = tempfile::tempdir().unwrap();
        let path = write_sealed(dir.path(), "a.json", |_| {});
        let mut v: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        v["metrics"]["auc"] = serde_json::json!(0.99);
        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();

        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert!(report.groups.is_empty(), "the forgery made a table");
        assert_eq!(report.skipped.len(), 1, "{:?}", report.skipped);
        assert!(report.skipped[0].invalid_document);
        assert!(
            report.skipped[0]
                .reason
                .contains("does not match its own content digest"),
            "{:?}",
            report.skipped[0]
        );
        assert_eq!(report.exit_code(), exit::SCHEMA_INVALID);
        for format in [
            ReportFormat::Text,
            ReportFormat::Markdown,
            ReportFormat::Csv,
        ] {
            let out = render(&report, format);
            assert!(!out.contains("0.9900"), "{format:?} tabled the forgery");
            assert!(
                flat(&out).contains("content digest"),
                "{format:?} did not name it"
            );
        }
    }

    #[test]
    fn a_sealed_document_nobody_touched_makes_an_ordinary_row() {
        let dir = tempfile::tempdir().unwrap();
        write_sealed(dir.path(), "a.json", |_| {});
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert!(report.skipped.is_empty(), "{:?}", report.skipped);
        assert_eq!(report.exit_code(), exit::OK);
    }

    #[test]
    fn an_auc_outside_its_own_interval_never_reaches_a_table() {
        // Visible with no digest at all, and it used to render as a row.
        let dir = tempfile::tempdir().unwrap();
        write_with(dir.path(), "a.json", |v| {
            v["metrics"]["auc"] = serde_json::json!(0.99);
            v["metrics"]["auc_ci95"] = serde_json::json!([0.5, 0.5]);
        });
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert!(report.groups.is_empty());
        assert_eq!(report.exit_code(), exit::SCHEMA_INVALID);
        assert!(
            report.skipped[0]
                .reason
                .contains("outside its own interval"),
            "{:?}",
            report.skipped[0]
        );
    }

    #[test]
    fn a_budget_the_corpus_could_not_express_is_said_in_the_cell() {
        // "TPR@1%FA" over six clean images is TPR@0%FA, and this is the
        // column an engineer acts on.
        let dir = tempfile::tempdir().unwrap();
        write_with(dir.path(), "a.json", |v| {
            v["metrics"]["fpr_achieved"] = serde_json::json!({"0.01": 0.0, "0.1": 0.1});
        });
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        for format in [ReportFormat::Text, ReportFormat::Markdown] {
            let out = flat(&render(&report, format));
            assert!(out.contains("0.1100 at 0% FA"), "{format:?}: {out}");
            // The rate that was met is left alone, or the mark means nothing.
            assert!(out.contains("0.5500 "), "{format:?}: {out}");
            assert!(!out.contains("0.5500 at"), "{format:?}: {out}");
            assert!(out.contains("too few clean images"), "{format:?}: {out}");
        }
    }

    #[test]
    fn a_document_that_recorded_no_achieved_rates_renders_as_it_always_did() {
        let dir = tempfile::tempdir().unwrap();
        Doc::default().write(dir.path(), "a.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        for format in [ReportFormat::Text, ReportFormat::Markdown] {
            let out = flat(&render(&report, format));
            assert!(!out.contains(" FA"), "{format:?} invented a mark: {out}");
            assert!(!out.contains("too few clean images"), "{format:?}: {out}");
        }
    }

    #[test]
    fn the_csv_gives_every_false_alarm_rate_its_own_column() {
        let dir = tempfile::tempdir().unwrap();
        write_with(dir.path(), "a.json", |v| {
            v["metrics"]["tpr_at_fpr"] = serde_json::json!({"0.01": 0.11, "0.1": 0.55});
            v["metrics"]["fpr_achieved"] = serde_json::json!({"0.01": 0.0, "0.1": 0.1});
        });
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let csv = render(&report, ReportFormat::Csv);
        let header: Vec<&str> = csv.lines().next().unwrap().split(',').collect();
        for column in [
            "tpr_at_fpr_0.01",
            "tpr_at_fpr_0.01_achieved_fpr",
            "tpr_at_fpr_0.1",
            "tpr_at_fpr_0.1_achieved_fpr",
        ] {
            assert!(header.contains(&column), "no {column} in {header:?}");
        }
        assert!(!header.contains(&"tpr_at_fpr"), "the packed cell survived");
        let row: Vec<&str> = csv.lines().nth(1).unwrap().split(',').collect();
        let at = |name: &str| row[header.iter().position(|h| *h == name).unwrap()];
        assert_eq!(at("tpr_at_fpr_0.01"), "0.1100");
        assert_eq!(at("tpr_at_fpr_0.01_achieved_fpr"), "0.0000");
        assert_eq!(at("tpr_at_fpr_0.1"), "0.5500");
        assert_eq!(at("tpr_at_fpr_0.1_achieved_fpr"), "0.1000");
    }

    #[test]
    fn the_csv_columns_cover_the_rates_of_every_document_not_just_the_first() {
        // A column set taken from the first row would drop the second
        // document's figures with nothing in the file saying so.
        let dir = tempfile::tempdir().unwrap();
        write_with(dir.path(), "a.json", |v| {
            v["metrics"]["tpr_at_fpr"] = serde_json::json!({"0.01": 0.11});
        });
        write_with(dir.path(), "b.json", |v| {
            v["subject"]["name"] = serde_json::json!("detector-b");
            v["metrics"]["tpr_at_fpr"] = serde_json::json!({"0.05": 0.33});
        });
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let csv = render(&report, ReportFormat::Csv);
        let header: Vec<&str> = csv.lines().next().unwrap().split(',').collect();
        assert!(header.contains(&"tpr_at_fpr_0.01"), "{header:?}");
        assert!(header.contains(&"tpr_at_fpr_0.05"), "{header:?}");
        assert!(
            csv.contains("0.3300"),
            "the second document's figure: {csv}"
        );
        // A rate a document never reported is empty rather than zero.
        let a_line = csv
            .lines()
            .find(|l| l.contains("detector-a"))
            .expect("a row for detector-a");
        let cells: Vec<&str> = a_line.split(',').collect();
        let at = |name: &str| cells[header.iter().position(|h| *h == name).unwrap()];
        assert_eq!(at("tpr_at_fpr_0.05"), "");
    }

    #[test]
    fn a_csv_arm_line_leaves_the_curve_columns_empty() {
        // The curve was measured for the run, not for the arm, and an arm
        // line repeating it would describe a different population.
        let dir = tempfile::tempdir().unwrap();
        with_arms(dir.path(), two_arms());
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let csv = render(&report, ReportFormat::Csv);
        let header: Vec<&str> = csv.lines().next().unwrap().split(',').collect();
        let index = header
            .iter()
            .position(|h| *h == "tpr_at_fpr_0.01")
            .expect("a column for the rate the fixture reports");
        for line in csv.lines().filter(|l| l.starts_with("arm,")) {
            assert_eq!(line.split(',').nth(index).unwrap(), "", "{line}");
        }
    }

    #[test]
    fn a_pipe_in_a_cell_cannot_shift_a_markdown_row() {
        assert_eq!(escape_md("a|b"), "a\\|b");
        assert_eq!(escape_md("a\nb"), "a b");
    }

    #[test]
    fn abbreviating_a_digest_keeps_the_algorithm_and_refuses_to_invent_one() {
        assert_eq!(abbreviate(""), "none");
        assert_eq!(abbreviate("sha256:0123456789abcdef"), "sha256:01234567");
        assert_eq!(abbreviate("short"), "short");
        assert_eq!(abbreviate("0123456789"), "01234567");
        assert_eq!(abbreviate("sha256:abc"), "sha256:abc");
    }

    #[test]
    fn the_atomic_write_leaves_the_whole_file_and_no_part_file() {
        let dir = tempfile::tempdir().unwrap();
        let out = dir.path().join("report.md");
        write_atomically(&out, "first").unwrap();
        assert_eq!(std::fs::read_to_string(&out).unwrap(), "first");
        write_atomically(&out, "second").unwrap();
        assert_eq!(std::fs::read_to_string(&out).unwrap(), "second");
        let leftovers: Vec<_> = std::fs::read_dir(dir.path())
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
            .filter(|n| n.contains(".part-"))
            .collect();
        assert!(leftovers.is_empty(), "left behind: {leftovers:?}");
    }

    #[test]
    fn an_unwritable_destination_fails_with_the_path_and_leaves_nothing() {
        let dir = tempfile::tempdir().unwrap();
        // A directory that does not exist: the create fails, so the error
        // path that removes the temporary file is the one that runs.
        let out = dir.path().join("no-such-dir").join("report.md");
        let err = write_atomically(&out, "body").unwrap_err();
        assert!(matches!(err, ReportError::Write { .. }));
        assert_eq!(err.exit_code(), exit::FAILURE);
        assert!(err.to_string().contains("report.md"));
        assert!(!dir.path().join("no-such-dir").exists());
    }

    /// A bare file name has an empty parent rather than no parent, and
    /// joining onto it would produce a path starting with a separator. Tested
    /// on the path calculation rather than by changing the process's working
    /// directory, which would race every other test in this binary.
    #[test]
    fn a_destination_with_no_parent_gets_a_temporary_file_beside_it() {
        let bare = temp_path_for(Path::new("bare.md"));
        assert_eq!(bare.parent(), Some(Path::new("")));
        assert!(bare
            .file_name()
            .is_some_and(|n| n.to_string_lossy().starts_with(".bare.md.part-")));

        let nested = temp_path_for(Path::new("/tmp/some/report.md"));
        assert_eq!(nested.parent(), Some(Path::new("/tmp/some")));
        assert!(nested
            .file_name()
            .is_some_and(|n| n.to_string_lossy().starts_with(".report.md.part-")));
    }

    #[test]
    fn the_json_output_says_whether_the_table_is_complete() {
        let dir = tempfile::tempdir().unwrap();
        Doc::default().write(dir.path(), "a.json");
        std::fs::write(dir.path().join("bad.json"), "{").unwrap();
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let json = to_json(&report);
        assert_eq!(json["complete"], serde_json::json!(false));
        assert_eq!(json["files_skipped"], serde_json::json!(1));
        assert_eq!(json["results_read"], serde_json::json!(1));
        assert_eq!(
            json["groups"][0]["rows"][0]["conditions"]
                .as_array()
                .map(|a| a.len()),
            Some(0)
        );
        assert!(json["groups"][0]["comparability"]
            .as_str()
            .is_some_and(|s| s.starts_with("NAMED:") || s.starts_with("CUSTOM:")));
        assert!(json["groups"][0]["rows"][0]["corpus"]["digest"]
            .as_str()
            .is_some_and(|d| d.len() > 8));
    }

    #[test]
    fn the_json_marks_a_single_table_as_internally_comparable() {
        let dir = tempfile::tempdir().unwrap();
        Doc::default().write(dir.path(), "a.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert_eq!(
            to_json(&report)["cross_table_comparison_valid"],
            serde_json::json!(true)
        );
    }

    #[test]
    fn wrapping_keeps_every_word_and_respects_the_column() {
        let text = "one two three four five six seven eight nine ten";
        let wrapped = wrap(text, 12);
        for line in wrapped.lines() {
            assert!(line.chars().count() <= 12, "too long: {line:?}");
        }
        assert_eq!(
            wrapped.split_whitespace().collect::<Vec<_>>(),
            text.split_whitespace().collect::<Vec<_>>()
        );
        assert_eq!(wrap("", 10), "");
        // A word longer than the column is kept whole rather than cut.
        assert_eq!(
            wrap("antidisestablishmentarianism", 5),
            "antidisestablishmentarianism"
        );
    }

    #[test]
    fn display_helpers_say_nowhere_rather_than_nothing() {
        assert_eq!(display_list(&[]), "nowhere");
        assert_eq!(display_paths(&[]), "");
        assert_eq!(display_list(&["a".to_string(), "b".to_string()]), "a, b");
    }

    #[test]
    fn tpr_lookup_matches_a_rate_however_it_was_written() {
        let map = BTreeMap::from([("0.10".to_string(), 0.9), ("0.010".to_string(), 0.4)]);
        assert_eq!(tpr_at(&map, 0.10), Some(0.9));
        assert_eq!(tpr_at(&map, 0.01), Some(0.4));
        assert_eq!(tpr_at(&map, 0.05), None);
    }

    #[test]
    fn a_rate_written_two_ways_is_one_csv_column() {
        // "0.1" and "0.10" are one rate, and two columns for it would put
        // half the figures under each.
        let dir = tempfile::tempdir().unwrap();
        write_with(dir.path(), "a.json", |v| {
            v["metrics"]["tpr_at_fpr"] = serde_json::json!({"0.1": 0.5});
        });
        write_with(dir.path(), "b.json", |v| {
            v["metrics"]["tpr_at_fpr"] = serde_json::json!({"0.10": 0.6});
        });
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let header = render(&report, ReportFormat::Csv)
            .lines()
            .next()
            .unwrap()
            .to_string();
        assert_eq!(header.matches("tpr_at_fpr_0.1,").count(), 1, "{header}");
    }

    #[test]
    fn every_enum_value_renders_to_a_word_rather_than_a_debug_string() {
        for d in [
            Domain::Spatial,
            Domain::Jpeg,
            Domain::Structural,
            Domain::Mixed,
            Domain::Unstated,
        ] {
            assert!(!domain_str(d).is_empty());
        }
        for p in [
            Pairing::SingleVariable,
            Pairing::Confounded,
            Pairing::Unverified,
        ] {
            assert!(!pairing_str(p).is_empty());
        }
        for s in [
            SplitDiscipline::ByCover,
            SplitDiscipline::ByFile,
            SplitDiscipline::NotApplicable,
        ] {
            assert!(!split_str(s).is_empty());
        }
        assert_eq!(source_str(CorpusSource::Fetched), "fetched");
        assert_eq!(source_str(CorpusSource::Supplied), "supplied");
        assert_eq!(unit_str(RateUnit::Bpp), "bpp");
        assert_eq!(configuration_str(Configuration::Named), "named");
    }

    /// A run with no plugins recorded must not be filed under any of the
    /// values the schema carries, on either field.
    #[test]
    fn an_unrecorded_plugin_list_is_named_as_unrecorded() {
        let mut v = Doc::default().value();
        v["provenance"]["plugins"] = serde_json::json!([]);
        let parsed: Result1 = serde_json::from_value(v).unwrap();
        let row = to_row(Path::new("x.json"), parsed);
        assert_eq!(row.pinned_by, "unrecorded");
        assert_eq!(row.isolation, "unrecorded");
    }

    /// A linked result is a row the walk cannot deliver. Dropping it quietly
    /// would produce a table short by one with nothing saying so, which is
    /// the exact failure this module is built around.
    #[test]
    #[cfg(unix)]
    fn a_symlinked_result_file_is_named_rather_than_skipped_silently() {
        let dir = tempfile::tempdir().unwrap();
        let elsewhere = dir.path().join("elsewhere");
        std::fs::create_dir_all(&elsewhere).unwrap();
        let real = Doc::default().write(&elsewhere, "real.json");
        let here = dir.path().join("here");
        std::fs::create_dir_all(&here).unwrap();
        std::os::unix::fs::symlink(&real, here.join("linked.json")).unwrap();
        Doc::default().write(&here, "ordinary.json");

        let report = build(std::slice::from_ref(&here)).unwrap();
        assert_eq!(report.read, 1);
        assert_eq!(report.skipped.len(), 1);
        assert!(report.skipped[0].reason.contains("symbolic link"));
        assert_eq!(report.exit_code(), exit::FAILURE);
        assert!(flat(&render(&report, ReportFormat::Text)).contains("linked.json"));

        // And naming it on the command line does include it, as the message
        // says it will.
        let named = build(&[here.join("linked.json")]).unwrap();
        assert_eq!(named.read, 1);
        assert!(named.skipped.is_empty());
    }

    /// A link that is not trying to be a result is not a gap in anything.
    #[test]
    #[cfg(unix)]
    fn a_symlink_that_is_not_a_json_file_is_not_reported_as_a_gap() {
        let dir = tempfile::tempdir().unwrap();
        Doc::default().write(dir.path(), "a.json");
        std::fs::write(dir.path().join("notes.md"), "notes").unwrap();
        std::os::unix::fs::symlink(dir.path().join("notes.md"), dir.path().join("link.md"))
            .unwrap();
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert!(report.skipped.is_empty(), "{:?}", report.skipped);
    }

    /// The cap is applied to what is read, not to what `metadata` said a
    /// moment earlier, so a file that grows between the two cannot slip past.
    #[test]
    fn the_size_cap_is_applied_to_the_bytes_actually_read() {
        let dir = tempfile::tempdir().unwrap();
        // One byte over, which is the boundary the cap has to get right.
        std::fs::write(
            dir.path().join("edge.json"),
            "x".repeat(MAX_RESULT_BYTES as usize + 1),
        )
        .unwrap();
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert!(report.skipped[0].reason.contains("byte cap"));

        // And exactly at the cap it is read, and refused for being the wrong
        // shape rather than for being too big.
        let at_cap = dir.path().join("at-cap.json");
        std::fs::write(&at_cap, "x".repeat(MAX_RESULT_BYTES as usize)).unwrap();
        let report = build(&[at_cap]).unwrap();
        assert!(
            report.skipped[0].reason.contains("not a result-v1"),
            "{:?}",
            report.skipped
        );
    }

    /// A document whose corpus held more than one named arm, written to
    /// `dir/a.json`.
    fn with_arms(dir: &Path, arms: serde_json::Value) -> PathBuf {
        let mut v = Doc::default().value();
        v["metrics"]["per_arm"] = arms;
        let path = dir.join("a.json");
        std::fs::write(&path, serde_json::to_string(&v).unwrap()).unwrap();
        path
    }

    /// Two arms, of which one is chance and the other is not. It is the case
    /// the breakdown exists for: the pooled figure describes neither.
    fn two_arms() -> serde_json::Value {
        serde_json::json!([
            {"arm": "lsb-0400", "auc": 0.6944, "n_clean": 5, "n_stego": 5},
            {"arm": "lsb-0100", "auc": 0.5, "auc_ci95": [0.4, 0.6], "n_clean": 5, "n_stego": 5},
        ])
    }

    #[test]
    fn a_two_arm_document_breaks_down_into_both_arms_in_every_format() {
        let dir = tempfile::tempdir().unwrap();
        with_arms(dir.path(), two_arms());
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        for format in [
            ReportFormat::Text,
            ReportFormat::Markdown,
            ReportFormat::Csv,
        ] {
            let text = flat(&render(&report, format));
            assert!(text.contains("lsb-0100"), "{format:?} lost an arm: {text}");
            assert!(text.contains("lsb-0400"), "{format:?} lost an arm: {text}");
            assert!(text.contains("0.6944"), "{format:?} lost a figure: {text}");
            assert!(text.contains("0.5000"), "{format:?} lost a figure: {text}");
        }
        // And the headline figure is still there beside them, because the
        // breakdown is additional rather than a replacement.
        assert!(flat(&render(&report, ReportFormat::Text)).contains("0.9000"));
    }

    /// The common case. A document with no breakdown must render exactly as it
    /// did before there was such a thing: no empty column, no "not
    /// applicable" on every row.
    #[test]
    fn a_document_with_no_arms_gains_nothing_in_any_format() {
        let dir = tempfile::tempdir().unwrap();
        Doc::default().write(dir.path(), "a.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert!(arm_table(&report.groups[0]).is_none());
        for format in [ReportFormat::Text, ReportFormat::Markdown] {
            let text = flat(&render(&report, format));
            assert!(!text.contains("Per arm"), "{format:?}: {text}");
            assert!(!text.contains("clean/stego "), "{format:?}: {text}");
        }
        let csv = render(&report, ReportFormat::Csv);
        assert!(
            !csv.lines().any(|l| l.starts_with("arm,")),
            "an arm line with no arms: {csv}"
        );
    }

    #[test]
    fn an_arm_interval_is_shown_where_there_is_one_and_not_invented_where_there_is_not() {
        let dir = tempfile::tempdir().unwrap();
        with_arms(dir.path(), two_arms());
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let text = flat(&render(&report, ReportFormat::Text));
        assert!(text.contains("0.5000 [0.400, 0.600]"), "{text}");
        // The arm that reported none is bare, not bracketed with anything.
        assert!(
            !text.contains("0.6944 ["),
            "an interval was invented: {text}"
        );

        let csv = render(&report, ReportFormat::Csv);
        let arm_lines: Vec<&str> = csv.lines().filter(|l| l.starts_with("arm,")).collect();
        assert_eq!(arm_lines.len(), 2);
        assert!(
            arm_lines.iter().any(|l| l.contains("0.4000,0.6000")),
            "{csv}"
        );
        assert!(
            arm_lines.iter().any(|l| l.contains("0.6944,,")),
            "the missing interval was filled in: {csv}"
        );

        let arms = &to_json(&report)["groups"][0]["rows"][0]["per_arm"];
        assert!(arms[0]["auc_ci95"].is_array());
        assert!(
            arms[1].get("auc_ci95").is_none(),
            "an absent interval became a value: {arms}"
        );
    }

    /// By name, and deliberately not by score. An ordering is read as a
    /// ranking whatever the prose beside it says, which is why the rows above
    /// are not ordered by score either.
    #[test]
    fn the_breakdown_is_ordered_by_arm_name_and_is_reproducible() {
        let dir = tempfile::tempdir().unwrap();
        with_arms(
            dir.path(),
            serde_json::json!([
                {"arm": "wow-0200", "auc": 0.99, "n_clean": 5, "n_stego": 5},
                {"arm": "lsb-0400", "auc": 0.6, "n_clean": 5, "n_stego": 5},
                {"arm": "hugo-0100", "auc": 0.7, "n_clean": 5, "n_stego": 5},
            ]),
        );
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let names: Vec<&str> = report.groups[0].rows[0]
            .per_arm
            .iter()
            .map(|a| a.arm.as_str())
            .collect();
        assert_eq!(names, ["hugo-0100", "lsb-0400", "wow-0200"]);
        for format in [
            ReportFormat::Text,
            ReportFormat::Markdown,
            ReportFormat::Csv,
        ] {
            let first = render(&build(&[dir.path().to_path_buf()]).unwrap(), format);
            let second = render(&build(&[dir.path().to_path_buf()]).unwrap(), format);
            assert_eq!(first, second, "{format:?} is not reproducible");
        }
    }

    #[test]
    fn the_json_carries_the_arm_figures_as_numbers_rather_than_as_a_rendered_string() {
        let dir = tempfile::tempdir().unwrap();
        with_arms(dir.path(), two_arms());
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let row = &to_json(&report)["groups"][0]["rows"][0];
        assert_eq!(row["per_arm"][0]["arm"], serde_json::json!("lsb-0100"));
        assert_eq!(row["per_arm"][0]["auc"], serde_json::json!(0.5));
        assert_eq!(row["per_arm"][0]["n_clean"], serde_json::json!(5));
        assert_eq!(row["per_arm"][1]["auc"], serde_json::json!(0.6944));
        assert_eq!(row["per_arm"].as_array().map(|a| a.len()), Some(2));
    }

    /// The key is there on every row, empty array and all. An absent key would
    /// make a consumer handle two shapes of one answer.
    #[test]
    fn the_json_carries_an_empty_breakdown_as_an_empty_list() {
        let dir = tempfile::tempdir().unwrap();
        Doc::default().write(dir.path(), "a.json");
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert_eq!(
            to_json(&report)["groups"][0]["rows"][0]["per_arm"],
            serde_json::json!([])
        );
    }

    /// The breakdown of one arm is the headline figure written twice, and the
    /// core type says so by leaving it empty. Nothing here second-guesses it.
    #[test]
    fn a_single_arm_breakdown_is_rendered_if_a_document_carries_one() {
        let dir = tempfile::tempdir().unwrap();
        with_arms(
            dir.path(),
            serde_json::json!([{"arm": "only", "auc": 0.9, "n_clean": 5, "n_stego": 5}]),
        );
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert!(flat(&render(&report, ReportFormat::Text)).contains("only"));
    }

    fn many_arms(count: usize, prefix: &str) -> serde_json::Value {
        serde_json::Value::Array(
            (0..count)
                .map(|i| {
                    serde_json::json!({
                        "arm": format!("{prefix}-{i:04}"),
                        "auc": 0.6,
                        "n_clean": 5,
                        "n_stego": 5,
                    })
                })
                .collect(),
        )
    }

    /// A Core tier run breaks down into 39 arms and a report may hold
    /// thousands of documents. The cap stops the wall of text, and it says how
    /// many documents it left out rather than trailing off.
    #[test]
    fn the_breakdown_stops_at_the_cap_and_names_what_it_left_out() {
        let dir = tempfile::tempdir().unwrap();
        for i in 0..4 {
            let mut v = Doc::default().value();
            v["subject"]["name"] = serde_json::json!(format!("detector-{i}"));
            v["provenance"]["plugins"][0]["name"] = serde_json::json!(format!("detector-{i}"));
            v["metrics"]["per_arm"] = many_arms(80, "lsb");
            std::fs::write(
                dir.path().join(format!("{i}.json")),
                serde_json::to_string(&v).unwrap(),
            )
            .unwrap();
        }
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let (lines, withheld) = arm_table(&report.groups[0]).unwrap();
        assert_eq!(lines.len(), 160, "the cap cut a document in half");
        assert_eq!(withheld, 2);
        for format in [ReportFormat::Text, ReportFormat::Markdown] {
            let text = flat(&render(&report, format));
            assert!(
                text.contains("2 further document(s) in this table"),
                "{format:?}: {text}"
            );
        }
        // The machine formats are uncapped: four documents of eighty arms is
        // 320 arm lines and every one of them is there.
        let csv = render(&report, ReportFormat::Csv);
        assert_eq!(csv.lines().filter(|l| l.starts_with("arm,")).count(), 320);
        let json = to_json(&report);
        for row in json["groups"][0]["rows"].as_array().unwrap() {
            assert_eq!(row["per_arm"].as_array().map(|a| a.len()), Some(80));
        }
    }

    /// A corpus with more arms than the cap shows its breakdown rather than
    /// nothing at all.
    #[test]
    fn one_document_larger_than_the_cap_is_still_printed_whole() {
        let dir = tempfile::tempdir().unwrap();
        with_arms(dir.path(), many_arms(MAX_ARM_LINES_SHOWN + 5, "lsb"));
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let (lines, withheld) = arm_table(&report.groups[0]).unwrap();
        assert_eq!(lines.len(), MAX_ARM_LINES_SHOWN + 5);
        assert_eq!(withheld, 0);
    }

    /// An arm line is a line somebody sorts a spreadsheet by, so it repeats
    /// every condition rather than pointing back at the line above it.
    #[test]
    fn a_csv_arm_line_carries_the_conditions_of_the_document_it_came_from() {
        let dir = tempfile::tempdir().unwrap();
        let mut v = Doc::default().value();
        v["declarations"]["pairing"] = serde_json::json!("confounded");
        v["metrics"]["per_arm"] = two_arms();
        std::fs::write(
            dir.path().join("a.json"),
            serde_json::to_string(&v).unwrap(),
        )
        .unwrap();
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        let csv = render(&report, ReportFormat::Csv);
        let columns = csv.lines().next().unwrap().split(',').count();
        for line in csv.lines().filter(|l| l.starts_with("arm,")) {
            assert_eq!(line.split(',').count(), columns, "{line}");
            assert!(line.contains("confounded"), "{line}");
            assert!(line.contains("corpus-a"), "{line}");
            assert!(line.contains("detector-a"), "{line}");
            assert!(line.contains("CONFOUNDED"), "{line}");
        }
    }

    /// Two corpora never share a table, and a per-arm figure is no more
    /// comparable across that boundary than a pooled one. Each breakdown sits
    /// under its own corpus, and every line names it.
    #[test]
    fn a_breakdown_never_crosses_a_corpus_boundary() {
        let dir = tempfile::tempdir().unwrap();
        for (name, digest, arm) in [("one", "d", "lsb-0100"), ("two", "e", "wow-0200")] {
            let mut v = Doc::default().value();
            v["corpus"]["name"] = serde_json::json!(name);
            v["corpus"]["digest"] = serde_json::json!(format!("sha256:{}", digest.repeat(64)));
            v["metrics"]["per_arm"] = serde_json::json!([
                {"arm": arm, "auc": 0.6, "n_clean": 5, "n_stego": 5},
                {"arm": "shared", "auc": 0.7, "n_clean": 5, "n_stego": 5},
            ]);
            std::fs::write(
                dir.path().join(format!("{name}.json")),
                serde_json::to_string(&v).unwrap(),
            )
            .unwrap();
        }
        let report = build(&[dir.path().to_path_buf()]).unwrap();
        assert_eq!(report.groups.len(), 2);
        for group in &report.groups {
            let (lines, _) = arm_table(group).unwrap();
            assert_eq!(lines.len(), 2, "a breakdown gathered two corpora");
            for line in &lines {
                assert!(
                    line[1].starts_with(&group.corpus_name),
                    "an arm line does not name its corpus: {line:?}"
                );
            }
        }
    }

    #[test]
    fn an_auc_cell_brackets_an_interval_only_where_there_is_one() {
        assert_eq!(auc_cell(0.5, None), "0.5000");
        assert_eq!(auc_cell(0.5, Some([0.4, 0.6])), "0.5000 [0.400, 0.600]");
    }

    #[test]
    #[cfg(unix)]
    fn a_symlinked_directory_is_not_followed() {
        {
            let dir = tempfile::tempdir().unwrap();
            let real = dir.path().join("real");
            std::fs::create_dir_all(&real).unwrap();
            Doc::default().write(&real, "a.json");
            // A link pointing at its own ancestor is the cycle the walk must
            // not enter.
            std::os::unix::fs::symlink(dir.path(), real.join("loop")).unwrap();
            let report = build(&[dir.path().to_path_buf()]).unwrap();
            assert_eq!(report.read, 1);
        }
    }
}