paperboy 0.7.0

A Rust TUI API tester
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
//! Headless CLI report runner:
//! `paperboy -c collection -e env -r report [--dry-run] [-o out.csv|-]`.
//!
//! The report engine ([`crate::report`]) is front-end agnostic, so this module
//! is a thin CLI shell around it: it loads the report / collection / environment
//! files, assembles a [`RunContext`], runs the flow (live, or a no-HTTP dry
//! expansion under `--dry-run`), streams a `done/total` progress line to stderr,
//! and writes the tabular result (CSV in v1) to a file or stdout.
//!
//! Decorative/progress output goes to **stderr** so that `-o -` can emit clean
//! CSV to stdout for piping; a file/derived output prints its human summary to
//! stdout instead.

use std::collections::HashMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Mutex;

use crate::environment::{looks_like_env, parse_vars};
use crate::postman::{looks_like_postman, parse_collection};
use crate::report::flow::Header;
use crate::report::metrics::{Metrics, Movement, PERCENT_DECIMALS, percent_text};
use crate::report::model::{OutputColumn, Partial, ReportRow};
use crate::report::params::{ParamValues, undeclared};
use crate::report::producers::resolve_path;
use crate::report::report::{expand_output_tokens, name_has_output_token};
use crate::report::run::{
    Cancel, DryRunner, LiveRunner, RowEvent, RowSink, RunContext, finalize, run_flow_raw,
};
use crate::report::validate::{Context, Severity, validate};
use crate::report::writer::{OUTPUT_EXTENSIONS, writer_for_extension};
use crate::report::{CsvWriter, Report, ReportResult, ReportWriter};
use crate::shared_utils::sanitize_file_stem;

/// A seed for a bare `--shuffle`, from the clock.
///
/// Not cryptographic and not meant to be: it only has to differ between runs so
/// that repeated runs explore different legal orders, and it is printed, which
/// is what makes a failure reproducible.
fn random_seed() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos() as u64)
        .unwrap_or(1)
}

/// Run a report headlessly. Returns an OS exit code: 0 when the report was
/// produced and every row ran cleanly, 1 on a fatal setup/validation error
/// *or* when the run collected per-row errors. The output is still written in
/// that second case — the non-zero code is there so a CI pipeline can't pass
/// green on a report in which every request failed.
///
/// `collection` names the collection to run against (re-pointable without
/// editing the report); when `None`, the report's own `# collection:` header is
/// used, resolved relative to the report's folder. `env_paths` are zero or more
/// environments used as the base variable layer and (when repeated) the
/// environments an `ENVS` loop can select by name; when empty, the report's
/// `# environment:` header (if any) is used, likewise resolved relative to the
/// report. `--dry-run` expands the flow without sending any request, and `-o`
/// chooses the output (`-` = stdout; a path whose extension selects the format;
/// omitted = the `# output:` format written to a `# name:`-derived file next to
/// the report, honouring the `{time}` token). `outputs` is repeatable: one run
/// renders the same result once per requested format. `params` are the `--param
/// NAME=VALUE` values for the report's `PARAM` declarations; anything not
/// supplied falls back to the default written in the report. `progress_json`
/// replaces the human `done/total` counter with a newline-delimited JSON event
/// stream on stderr (see [`Progress`]).
///
/// A run can be **stopped**: on a signal, or — with `stop_on_stdin` — on a
/// `stop` line (or EOF) on stdin, which is the channel a parent process can
/// use on any platform. A stopped run starts no further rows, lets the ones in
/// flight finish, runs `CLEANUP`, writes the outputs it was asked for marked
/// as partial, and exits [`EXIT_INTERRUPTED`]; `grace_secs` bounds how long it
/// will wait for that (see [`Control`]).
pub fn run(
    collection_path: Option<String>,
    env_paths: Vec<String>,
    report_path: String,
    outputs: Vec<String>,
    dry_run: bool,
    targets: Vec<String>,
    shuffle: Option<Option<u64>>,
    params: ParamValues,
    gates: Gates,
    progress_json: bool,
    grace_secs: Option<u64>,
    stop_on_stdin: bool,
) -> i32 {
    let control = Control::new(grace_secs);
    control.listen(stop_on_stdin);
    run_with_progress(
        collection_path,
        env_paths,
        report_path,
        outputs,
        dry_run,
        targets,
        shuffle,
        params,
        gates,
        Progress::new(progress_json),
        control,
    )
}

/// The body of [`run`], with the event stream's destination passed in.
///
/// Split out so the stream itself can be tested: the events are a published
/// contract that other programs parse, and asserting on it by spawning the
/// binary and scraping its real stderr would test the shell as much as the
/// contract. A test hands in a capturing [`Progress`] and reads the events the
/// run actually produced, output files and all.
#[allow(clippy::too_many_arguments)]
fn run_with_progress(
    collection_path: Option<String>,
    env_paths: Vec<String>,
    report_path: String,
    outputs: Vec<String>,
    dry_run: bool,
    targets: Vec<String>,
    shuffle: Option<Option<u64>>,
    params: ParamValues,
    gates: Gates,
    progress: Progress,
    control: Control,
) -> i32 {
    let progress_json = progress.on();
    // stdout stays clean for a piped CSV (`-o -`); everything human goes to the
    // "decorative" stream, which is stderr in that case and stdout otherwise.
    let to_stdout = outputs.iter().any(|o| o == "-");

    // --- report ----------------------------------------------------------
    let report = match Report::load_local(&report_path) {
        Ok(r) => r,
        Err(e) => {
            return progress.setup_failed(vec![format!("cannot read report file: {e}")]);
        }
    };
    let mut flow = match report.flow() {
        Ok(f) => f,
        Err(e) => {
            return progress.setup_failed(vec![format!(
                "report '{report_path}' has a syntax error: {e}"
            )]);
        }
    };
    // The report's folder anchors every relative reference it makes: the
    // `# collection:`/`# environment:` header fallbacks below, and (later) the
    // `# root:` producer/baseline base directory.
    let report_dir = report.path.as_deref().and_then(Path::parent);

    // --- parameters ------------------------------------------------------
    // Checked here, before anything is loaded or sent: a `--param` naming a
    // parameter this report doesn't declare is almost always a caller whose
    // command line has drifted from the script, and letting it through would
    // run the whole report against the default it thought it had replaced.
    let undeclared_params = undeclared(&flow.params(), &params);
    if !undeclared_params.is_empty() {
        let declared = flow.params();
        let known = if declared.is_empty() {
            "it declares none".to_string()
        } else {
            format!(
                "it declares: {}",
                declared
                    .iter()
                    .map(|p| p.name.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        };
        return progress.setup_failed(vec![format!(
            "report '{report_path}' has no parameter named {} ({known})",
            undeclared_params
                .iter()
                .map(|n| format!("'{n}'"))
                .collect::<Vec<_>>()
                .join(", ")
        )]);
    }

    // --- outputs ---------------------------------------------------------
    // Judged before anything is loaded or sent, for the same reason the
    // parameters above are: a mistyped format is a setup error, and finding it
    // only once the report has been rendered would mean paying for a whole run
    // of live requests to be told where it couldn't be written.
    if let Err(e) = check_outputs(&outputs, &flow.header) {
        return progress.setup_failed(vec![e]);
    }

    // --- collection ------------------------------------------------------
    // `-c` re-points the report at any collection; when omitted, fall back to
    // the report's own `# collection:` header (resolved relative to the report's
    // folder) so a workspace report "just runs" without repeating the path.
    // A flow that embeds its own requests needs no collection at all: the
    // `REQUESTS` section *is* the collection, which is the whole point of a
    // monitor that ships as one file.
    let embedded = flow.embedded_entries();
    let collection_path = match collection_path {
        Some(c) => Some(c),
        None => match report.collection_ref() {
            Some(c) => Some(resolve_path(report_dir, &c).to_string_lossy().into_owned()),
            // The *declaration* is what excuses the missing collection, not
            // how many requests it yielded. A section that parsed to nothing
            // must reach validation, which knows why it did.
            None if flow.requests.is_some() => None,
            None => {
                return progress.setup_failed(vec![format!(
                    "no collection to run against — pass -c/--collection, add a '# collection:' header to '{report_path}', or embed the requests in a REQUESTS section"
                )]);
            }
        },
    };
    let col_content = match &collection_path {
        Some(path) => match fs::read_to_string(path) {
            Ok(c) => c,
            Err(e) => {
                return progress
                    .setup_failed(vec![format!("cannot read collection file '{path}': {e}")]);
            }
        },
        None => String::new(),
    };
    let mut entries = match &collection_path {
        Some(_) => parse_collection(&col_content),
        None => Vec::new(),
    };
    // Appended, so an external collection's requests keep the names they had
    // and a collision is visible to validation rather than resolved silently
    // by whichever list was searched first.
    let embedded_count = embedded.len();
    entries.extend(embedded);
    let collection_path = collection_path.unwrap_or_else(|| {
        let s = if embedded_count == 1 { "" } else { "s" };
        format!("(embedded: {embedded_count} request{s})")
    });
    if entries.is_empty() {
        // As in `cli.rs`: prefer the concrete Hurl parse reason (line + what's
        // wrong) when the source is Hurl — one malformed line rejects the whole
        // file, so "no requests found" alone hides the real cause.
        // A `REQUESTS` section that yielded nothing is the likelier cause when
        // the flow has one, and it knows its own line numbers within the file.
        let embedded_why = flow
            .requests
            .as_deref()
            .and_then(|t| crate::hurl::parse_hurl_error_from(t, flow.requests_line.max(1)));
        let message = match embedded_why.or_else(|| {
            (!looks_like_postman(&col_content))
                .then(|| crate::hurl::parse_hurl_error(&col_content))
                .flatten()
        }) {
            Some(why) => format!("no requests found in '{collection_path}' — {why}"),
            None => format!("no requests found in '{collection_path}'"),
        };
        return progress.setup_failed(vec![message]);
    }

    // --- environment(s) --------------------------------------------------
    // Zero or more `-e` environments. Each is loaded, named by its file stem,
    // and made selectable by that name in an `ENVS` loop — so a
    // `FOR … IN ENVS BASELINE("prod"), COMPARISON("staging")` comparison runs
    // headlessly by passing `-e prod.vars -e staging.vars`. The first `-e`
    // doubles as the base variable layer for requests outside any `ENVS` loop.
    // Distinct stems are required so an `ENVS` clause names an environment
    // unambiguously. Backward compatible with a single `-e`.
    //
    // When no `-e` is given, fall back to the report's `# environment:` header
    // (resolved relative to the report's folder), mirroring the collection
    // fallback above. Explicit `-e` flags always win.
    let env_paths: Vec<String> = if env_paths.is_empty() {
        match report.environment_ref() {
            Some(e) => vec![resolve_path(report_dir, &e).to_string_lossy().into_owned()],
            None => Vec::new(),
        }
    } else {
        env_paths
    };
    let mut base_vars: HashMap<String, String> = HashMap::new();
    let mut named_envs: HashMap<String, HashMap<String, String>> = HashMap::new();
    let mut env_names_loaded: Vec<String> = Vec::new();
    for env_path in &env_paths {
        let env_content = match fs::read_to_string(env_path) {
            Ok(c) => c,
            Err(e) => {
                return progress.setup_failed(vec![format!(
                    "cannot read environment file '{env_path}': {e}"
                )]);
            }
        };
        if !looks_like_env(&env_content) {
            return progress.setup_failed(vec![format!(
                "'{env_path}' is not a valid environment file (expected KEY=value lines)"
            )]);
        }
        let name = crate::shared_utils::stem(env_path, "env");
        if named_envs.contains_key(&name) {
            return progress.setup_failed(vec![format!(
                "duplicate environment name '{name}' (from '{env_path}') — each -e file must have a distinct stem so an ENVS clause can name it unambiguously"
            )]);
        }
        let env = parse_vars(name.clone(), &env_content);
        let flat: HashMap<String, String> = env
            .vars
            .iter()
            .map(|v| (v.key.clone(), v.value.clone()))
            .collect();
        // The first environment is the base variable layer.
        if env_names_loaded.is_empty() {
            base_vars = flat.clone();
        }
        named_envs.insert(name.clone(), flat);
        env_names_loaded.push(name);
    }

    // --- validation ------------------------------------------------------
    // Same checks the TUI runs. A hard error blocks a live run (as it does in
    // the TUI); a dry run proceeds regardless so the projected expansion — and
    // any unresolved names as per-row errors — can still be inspected.
    let titles: Vec<String> = entries.iter().map(|e| e.title.clone()).collect();
    let fields: Vec<(String, Vec<String>)> = entries
        .iter()
        .map(|e| {
            (
                e.title.clone(),
                e.reports.iter().map(|(n, _)| n.clone()).collect(),
            )
        })
        .collect();
    let env_names: Vec<String> = named_envs.keys().cloned().collect();
    // The headless runner has nothing open, so every helper collection is read
    // from disk relative to the report.
    let cli_strings = crate::i18n::Strings::for_language(&crate::i18n::Language::English);
    let (helpers, helper_errors) = crate::report::context::load_helpers(
        &[],
        &flow,
        Some(std::path::Path::new(&report_path)),
        &cli_strings,
    );
    // Relative producer paths (and the `# baseline:` snapshot) resolve against
    // `# root:` if set, else the report file's own directory (`report_dir`,
    // computed above). Computed here so validation's baseline-existence check
    // and the run context agree.
    let root: Option<PathBuf> = match flow.header.root() {
        Some(r) if !r.trim().is_empty() => Some(resolve_path(report_dir, r)),
        _ => report_dir.map(Path::to_path_buf),
    };
    // For the variable-availability check: the base env variables and the union
    // of all loaded env variables.
    let base_var_names_owned: Vec<String> = env_names_loaded
        .first()
        .and_then(|first_name| named_envs.get(first_name))
        .map(|m| {
            let mut keys: Vec<String> = m.keys().cloned().collect();
            keys.sort();
            keys
        })
        .unwrap_or_default();
    let mut all_env_var_names_owned: Vec<String> = named_envs
        .values()
        .flat_map(|m| m.keys().cloned())
        .collect();
    all_env_var_names_owned.sort();
    all_env_var_names_owned.dedup();

    let ctx = Context {
        request_titles: Some(&titles),
        env_names: Some(&env_names),
        request_fields: Some(&fields),
        root: root.as_deref(),
        base_var_names: Some(&base_var_names_owned),
        all_env_var_names: Some(&all_env_var_names_owned),
        request_entries: Some(&entries),
        helpers: &helpers,
        helper_errors: &helper_errors,
        // The headless runner has no language setting of its own — its output
        // is read by scripts and CI logs, which is English territory.
        strings: &cli_strings,
    };
    let diags = validate(&flow, &ctx);
    let has_error = diags.iter().any(|d| d.severity == Severity::Error);
    // Carried rather than printed when the stream is on: a validation warning
    // is a fact about the run a consumer wants, and prose on the stream's own
    // channel is a line it would have to throw away to keep parsing.
    let mut setup_warnings: Vec<String> = Vec::new();
    for d in &diags {
        let tag = match d.severity {
            Severity::Error => "error",
            Severity::Warning => "warning",
        };
        if progress_json {
            if d.severity == Severity::Warning {
                setup_warnings.push(d.message.clone());
            }
        } else {
            eprintln!("{tag}: {}", d.message);
        }
    }
    if has_error && !dry_run {
        // The diagnostics themselves were printed above in the human mode, so
        // only the stream needs them repeated here.
        let mut errors: Vec<String> = diags
            .iter()
            .filter(|d| progress_json && d.severity == Severity::Error)
            .map(|d| d.message.clone())
            .collect();
        errors.push(
            "the report has validation errors — fix them or use --dry-run to preview".to_string(),
        );
        return progress.setup_failed_with(errors, setup_warnings);
    }

    // --- targets ---------------------------------------------------------
    // Pruning happens after validation and before the run, on the flow itself,
    // so a dry run previews exactly the subset a live run would send. It is
    // refused outright on an unknown target: running a different set of steps
    // than the one asked for is a worse answer than running none.
    if !targets.is_empty()
        && let Err(errs) = crate::report::graph::prune_to_targets(
            &mut flow,
            &targets,
            &entries,
            &helpers,
            &cli_strings,
        )
    {
        return progress.setup_failed_with(errs, setup_warnings);
    }

    // --- run context -----------------------------------------------------
    // Live requests are rooted at the collection's directory so relative
    // form-file paths resolve as they would when sent by hand.
    let file_root = Path::new(&collection_path).parent().map(Path::to_path_buf);

    let live = LiveRunner {
        file_root: file_root.clone(),
    };
    let dry = DryRunner;

    // --- header block ----------------------------------------------------
    let mut decor = Decor::new(to_stdout, progress_json);
    decor.line(&format!("PaperBoy — report \"{}\"", report.name));
    decor.line(&format!("  Collection : {collection_path}"));
    if let [one] = env_names_loaded.as_slice() {
        decor.line(&format!("  Environment: {one}"));
    } else if !env_names_loaded.is_empty() {
        decor.line(&format!(
            "  Environments: {} (base: {})",
            env_names_loaded.join(", "),
            env_names_loaded[0]
        ));
    }
    if dry_run {
        decor.line("  Mode       : DRY RUN (no requests sent)");
    }
    if !targets.is_empty() {
        decor.line(&format!("  Targets    : {}", targets.join(", ")));
    }
    // Echoed for the same reason the seed below is: a report is a script's
    // output as much as a person's, and "which folder did last night's run
    // actually look at?" has to be answerable from the run's own log rather
    // than from the calling shell's history. Sorted, since the values arrive
    // as a map.
    if !params.is_empty() {
        let mut supplied: Vec<String> = params
            .iter()
            .map(|(name, value)| format!("{name}={value}"))
            .collect();
        supplied.sort();
        decor.line(&format!("  Parameters : {}", supplied.join(", ")));
    }
    // Printed whether or not a seed was supplied, because a shuffled run that
    // fails is only useful if it can be repeated, and the seed is the whole of
    // what has to be carried from the failing run to the reproduction.
    let shuffle = shuffle.map(|s| s.unwrap_or_else(random_seed));
    if let Some(seed) = shuffle {
        decor.line(&format!(
            "  Shuffle    : seed {seed} (replay with --shuffle={seed})"
        ));
    }
    // The plan, printed as waves rather than a numbered sequence: a numbered
    // list would imply a total order that a graph does not have, and the reason
    // to print it at all is to show what the graph does and does not constrain.
    if dry_run {
        let lines = crate::report::graph::explain(&flow, &entries, &helpers, &cli_strings);
        if !lines.is_empty() {
            decor.line("");
            for l in lines {
                decor.line(&l);
            }
            decor.line("");
        }
    }

    // --- run -------------------------------------------------------------
    // A projection pass first: a no-HTTP expansion of the same flow, which
    // answers how many rows there will be and what the columns are called
    // *before* anything is sent. The human mode needs the count for the
    // `done/total` denominator; `--progress-json` needs the whole shape for its
    // `plan` event, so a front-end can draw the empty grid up front.
    //
    // A dry run is already that expansion, so it only pays for a second one
    // when the stream is on — and then only because `plan` has to precede the
    // rows it describes, which the pass producing them cannot do.
    let projection = (!dry_run || progress_json).then(|| {
        let ctx = RunContext {
            entries: &entries,
            helpers: &helpers,
            base_vars: base_vars.clone(),
            named_envs: named_envs.clone(),
            root: root.clone(),
            runner: &dry,
            strings: &cli_strings,
            params: params.clone(),
            sink: None,
            shuffle,
            // A projection sends nothing and takes no time worth stopping.
            cancel: None,
        };
        run_flow_raw(&flow, &ctx)
    });
    // Projected, not final: a column only a live response can name (and the
    // comparison columns `finalize` adds) isn't in this set, so a row's cells
    // are streamed against the planned grid and anything else is read from the
    // report file at the end. The alternative — growing the column set
    // mid-stream — would defeat the point of announcing it up front.
    let (streamed_columns, withheld_columns) = split_streamed_columns(
        projection
            .as_ref()
            .map(|p| p.resolved_columns(&flow.header))
            .unwrap_or_default(),
    );
    let total = projection.as_ref().map_or(0, |p| p.rows.len());
    let no_match = projection
        .as_ref()
        .map(|p| p.no_match_marker.clone())
        .unwrap_or_default();
    let slots = RowSlots::new(projection.as_ref().map_or(&[], |p| p.rows.as_slice()));
    // Kept rather than dropped, because it is the *shape* of the report —
    // column order, statistics, ground truths, the no-match marker — and a run
    // that is given up on never returns the assembled result those would
    // otherwise come from. An abandoned run's report is this shape with the
    // rows that actually finished poured into it.
    let shape = projection;

    // A gate with nothing to measure is refused before anything is sent: a
    // `--fail-under` on a report that declares no `TRUTH` can only ever be a
    // mistake, and the two ways of finding that out later are both bad — a
    // twenty-minute run thrown away, or a gate that passes every deploy while
    // measuring nothing at all.
    let has_truth = shape
        .as_ref()
        .map(|p| p.resolved_columns(&flow.header))
        .unwrap_or_default()
        .iter()
        .any(|c| c.truth.is_some());
    if gates.fail_under.is_some() && !has_truth {
        return progress.setup_failed(vec![
            "--fail-under has nothing to measure: no column in this report is scored \
             against a TRUTH (a `# columns:` directive can also leave the scored column out)"
                .to_string(),
        ]);
    }
    // The movement gate needs both halves of the comparison it is named after:
    // something to be right or wrong about, and something to have been right or
    // wrong about last time. Refused up front for the same reason as the
    // accuracy gate — the two ways of finding out later are a long run thrown
    // away, or a gate that waves every deploy through while measuring nothing.
    if gates.net_gain.is_some() {
        if !has_truth {
            return progress.setup_failed(vec![
                "--require-net-gain has nothing to measure: no column in this report is \
                 scored against a TRUTH (a `# columns:` directive can also leave the \
                 scored column out)"
                    .to_string(),
            ]);
        }
        if crate::report::compare::comparison_roles(&flow).is_none()
            && flow.header.baseline().is_none()
        {
            return progress.setup_failed(vec![
                "--require-net-gain has nothing to compare against: this report declares \
                 no baseline (an `ENVS BASELINE(…)/COMPARISON(…)` clause, or a \
                 `# baseline:` snapshot)"
                    .to_string(),
            ]);
        }
    }

    let done = std::sync::atomic::AtomicUsize::new(0);
    // What a stopped run has to show for itself. The rows are copied out as
    // they land because a run that is given up on never hands its own result
    // back: the only rows reachable from outside the run thread are the ones
    // the sink has already seen. That costs a second copy of every row on a run
    // nobody interrupts — the price of not having a four-hour run leave nothing
    // behind when it is stopped in its fifth.
    let harvest = Mutex::new(Harvest::default());
    let sink = |ev: RowEvent| {
        if !dry_run && let RowEvent::Completed { row, errors } = &ev {
            let mut held = harvest.lock().unwrap_or_else(|e| e.into_inner());
            held.completed += 1;
            held.rows.push((*row).clone());
            held.errors
                .extend(errors.iter().map(|e| (row.path.clone(), e.clone())));
        }
        // The two progress modes are exclusive: interleaving a redrawn human
        // line with the NDJSON stream would corrupt both (the counter uses a
        // bare `\r` and no newline, so it would land *inside* an event line).
        if progress_json {
            match ev {
                RowEvent::Started(path) => progress.row_started(path, &slots),
                RowEvent::Completed { row, errors } => {
                    progress.row_completed(row, errors, &streamed_columns, &no_match, &slots)
                }
            }
            return;
        }
        // Count only completed rows for the progress readout (a row is also
        // announced when it starts, which we ignore here).
        if !matches!(ev, RowEvent::Completed { .. }) {
            return;
        }
        let n = done.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
        // Progress is inherently ephemeral; keep it on stderr regardless of
        // where the CSV goes, redrawing one line in place.
        eprint!("\r  running {n}/{total}   ");
        let _ = std::io::stderr().flush();
    };
    // A dry run sends nothing, so there is no counter to draw — but it does
    // *produce* rows, and a consumer previewing a big run wants to watch the
    // grid fill exactly as a live one would. A live run always takes the hook:
    // it is also how a stop gets its rows.
    let sink: Option<&RowSink> = match (dry_run, progress_json) {
        (true, false) => None,
        _ => Some(&sink),
    };

    let result = if dry_run {
        progress.plan(
            &report.name,
            total,
            &streamed_columns,
            &withheld_columns,
            true,
        );
        let ctx = RunContext {
            entries: &entries,
            helpers: &helpers,
            base_vars,
            named_envs,
            root,
            runner: &dry,
            strings: &cli_strings,
            params: params.clone(),
            sink,
            shuffle,
            // Likewise a dry run: there is no request in flight to wind down,
            // and a stop that arrives during one is served by the process
            // ending, not by a partial report of requests never sent.
            cancel: None,
        };
        let mut r = run_flow_raw(&flow, &ctx);
        finalize(&mut r, &flow, &ctx);
        decor.line(&format!("  Rows       : {} projected", r.rows.len()));
        r
    } else {
        decor.line(&format!("  Rows       : {total}"));
        progress.plan(
            &report.name,
            total,
            &streamed_columns,
            &withheld_columns,
            false,
        );
        let ctx = RunContext {
            entries: &entries,
            helpers: &helpers,
            base_vars,
            named_envs,
            root,
            runner: &live,
            strings: &cli_strings,
            params,
            sink,
            shuffle,
            cancel: Some(control.cancel.as_ref()),
        };
        // The run gets a thread of its own so this one is free to watch for a
        // stop request while it happens. Nothing else here is concurrent: the
        // run is a single call that returns a whole report, and there is no
        // point in the middle of it at which it could ask "has anyone asked me
        // to stop?" on this thread's behalf.
        // Whether the stream has already been told the run is winding down. A
        // run can be stopped and finish before the watcher's next poll — two
        // fast rows and a stop between them — and a consumer that learns a run
        // was interrupted only from its terminal event has to work that out
        // backwards. Announced once, from whichever side notices first.
        let mut announced_stop = false;
        let ending = std::thread::scope(|s| {
            let (tx, rx) = std::sync::mpsc::channel();
            let (flow_ref, ctx_ref) = (&flow, &ctx);
            s.spawn(move || {
                let mut r = run_flow_raw(flow_ref, ctx_ref);
                finalize(&mut r, flow_ref, ctx_ref);
                let _ = tx.send(r);
            });
            let mut deadline: Option<std::time::Instant> = None;
            loop {
                match rx.recv_timeout(STOP_POLL) {
                    Ok(r) => return Ending::Ran(r),
                    // The run thread panicked, taking its sender with it.
                    // Stop waiting and let the scope's join re-raise that panic
                    // rather than inventing a result out of half a run.
                    Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => return Ending::Lost,
                    Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
                }
                if control.cancel.stopped() && deadline.is_none() {
                    deadline = Some(std::time::Instant::now() + control.grace);
                    announced_stop = true;
                    progress.run_stopping(control.source(), control.grace);
                    if !progress_json {
                        eprintln!(
                            "\r  stopping   : no new rows; up to {}s for the rows in flight and CLEANUP",
                            grace_label(control.grace)
                        );
                    }
                }
                if deadline.is_some_and(|d| std::time::Instant::now() >= d) {
                    // The grace period is up and rows are still in flight. What
                    // finished is all there will ever be, so write that and go:
                    // waiting any longer is the thing the caller just refused.
                    let mut r = abandoned_result(shape.as_ref(), &harvest, total, control.grace);
                    finalize(&mut r, &flow, &ctx);
                    let code = deliver(
                        &r,
                        &flow.header,
                        &report,
                        &outputs,
                        &mut decor,
                        &progress,
                        &setup_warnings,
                        gates,
                    );
                    (control.abandon)(code);
                    return Ending::Delivered(code);
                }
            }
        });
        match ending {
            Ending::Ran(mut r) => {
                if control.cancel.stopped() {
                    if !announced_stop {
                        progress.run_stopping(control.source(), control.grace);
                    }
                    // Stopped, but it wound down on its own terms: the rows in
                    // flight finished and `CLEANUP` ran. The report is short,
                    // and says so.
                    r.partial = Some(Partial {
                        rows_completed: harvest.lock().unwrap_or_else(|e| e.into_inner()).completed,
                        rows_planned: total,
                    });
                }
                if !progress_json {
                    match &r.partial {
                        Some(p) => eprintln!(
                            "\r  stopped    : {} of {} rows ran   ",
                            p.rows_completed, p.rows_planned
                        ),
                        None => eprintln!("\r  running {total}/{total}   done"),
                    }
                }
                r
            }
            // Already written and announced inside the scope above; in a real
            // run `Control::abandon` ended the process before this was reached.
            Ending::Delivered(code) => return code,
            Ending::Lost => unreachable!("the scope re-raises the run thread's panic"),
        }
    };

    deliver(
        &result,
        &flow.header,
        &report,
        &outputs,
        &mut decor,
        &progress,
        &setup_warnings,
        gates,
    )
}

/// Say what happened and hand the report over: the human summary, one rendering
/// per requested `-o`, the exit code, and the stream's terminal event.
///
/// A function rather than the tail of [`run_with_progress`] because a run that
/// is given up on has to do all of this from *inside* the scope holding its
/// straggling threads (see [`Control::abandon`]) — and a partial report that
/// went out by a different path than a whole one would be exactly the kind of
/// second implementation that drifts.
#[allow(clippy::too_many_arguments)]
fn deliver(
    result: &ReportResult,
    header: &Header,
    report: &Report,
    outputs: &[String],
    decor: &mut Decor,
    progress: &Progress,
    setup_warnings: &[String],
    gates: Gates,
) -> i32 {
    let progress_json = progress.on();
    // --- warnings, skips, errors -----------------------------------------
    if !result.warnings.is_empty() {
        decor.line(&format!("  Warnings   : {}", result.warnings.len()));
        for w in &result.warnings {
            decor.line(&format!("    ~ {w}"));
        }
    }
    if !result.skipped.is_empty() {
        decor.line(&format!(
            "  Skipped    : {} ({})",
            result.skipped.len(),
            result.skipped.join(", ")
        ));
    }
    if !result.errors.is_empty() {
        decor.line(&format!("  Errors     : {}", result.errors.len()));
        for e in &result.errors {
            decor.line(&format!("    ! {e}"));
        }
    }
    // Said in the summary as well as in the file, because the person who
    // pressed the button is looking at this and not at the report yet.
    if result.dry_run {
        decor.line("  Dry run    : no requests were sent — rows are projected, nothing was scored");
    }
    if let Some(partial) = &result.partial {
        decor.line(&format!(
            "  Stopped    : PARTIAL — {} of {} rows ran",
            partial.rows_completed, partial.rows_planned
        ));
    }

    // --- gate -------------------------------------------------------------
    // Evaluated before the files are written so the verdict is on the terminal
    // next to the numbers it was drawn from, and written into no output: the
    // threshold is this caller's policy, not a fact about the run, and a report
    // that recorded it would read as though the run had been scored against it
    // for everyone who opens the file later.
    let gate = gates.fail_under.map(|required| match result.partial {
        Some(_) => Gate::not_measured(required),
        None => Gate::measure(result, required),
    });
    if let Some(g) = &gate {
        decor.line(&format!("  Gate       : {}", g.note));
    }
    let net_gain = gates.net_gain.map(|required| match result.partial {
        Some(_) => NetGain::not_measured(required),
        None => NetGain::measure(result, required),
    });
    if let Some(n) = &net_gain {
        decor.line(&format!("  Movement   : {}", n.note));
    }

    // --- output ----------------------------------------------------------
    // One run, one result, rendered once per requested format — never re-run.
    // Each file is announced as it lands, and a failure part-way through leaves
    // the ones already written where they are: they are faithful renderings of
    // a run that really happened, and removing them would destroy the only
    // record of it to tidy up after a disk that was full.
    let requested: Vec<Option<&str>> = if outputs.is_empty() {
        vec![None]
    } else {
        outputs.iter().map(|o| Some(o.as_str())).collect()
    };
    let mut write_failed = false;
    for target in requested {
        match write_output(&result, header, target, &report) {
            Ok(OutputTarget::Stdout(format)) => {
                // The report already went to stdout; nothing more to print there.
                progress.output_written("-", format, None);
            }
            Ok(OutputTarget::File(path)) => {
                decor.line(&format!("  Output     : {}", path.display()));
                let fmt = output_extension_of(&path.to_string_lossy());
                progress.output_written(&path.to_string_lossy(), &fmt, None);
            }
            Err(e) => {
                // Reported as a failed `output_written` rather than as prose,
                // so a `--progress-json` consumer hears about the file it asked
                // for on the same channel as the ones that landed.
                if progress_json {
                    let path = target.unwrap_or("");
                    progress.output_written(path, &output_extension_of(path), Some(&e));
                } else {
                    eprintln!("error: cannot write output: {e}");
                }
                write_failed = true;
            }
        }
    }

    // The report was produced either way, but a caller scripting this needs to
    // hear what happened in the exit code rather than by scraping the output.
    //
    // 3 beats 1 because it is the more informative of the two, and a skip only
    // ever arises *from* a failure — so exit 3 already implies exit 1's
    // condition while adding the fact that part of the run never happened at
    // all. (2 is left alone: clap uses it for argument errors, and a caller
    // must be able to tell "you invoked me wrongly" from "your API is broken".)
    //
    // 4 beats both, because it explains them: a stopped run's skips and errors
    // are as likely to be *of* the stop as of the API, and a caller that reads
    // 1 or 3 here would go looking for a fault that isn't there. A failed write
    // still wins, since then there is no report to have stopped short.
    let exit = if write_failed {
        1
    } else if result.partial.is_some() {
        EXIT_INTERRUPTED
    } else {
        match (result.skipped.is_empty(), result.errors.is_empty()) {
            (false, _) => EXIT_SKIPPED,
            (true, false) => 1,
            // The gate is the last word, and only ever on a run that would
            // otherwise have exited 0: a run that already failed has a better
            // answer to give than "and the accuracy was low too", and the
            // accuracy of a run that broke half way through is not the figure
            // the caller meant to gate on anyway.
            // A gate that could not be measured at all is a broken run, not a
            // quality miss: `--fail-under` was asked for and the report came
            // back with nothing scored, which no retry of a *better* API would
            // fix and which exit 5 ("the answers were wrong") would misdescribe.
            // Both gates answer the same question — "is this run good enough
            // to ship" — so they share an exit code, and either one of them
            // failing is enough. Unmeasurable beats failed for the same reason
            // in both: a gate that was asked for and could not be evaluated is
            // a broken run, which no retry of a *better* API would fix.
            (true, true) => match (&gate, &net_gain) {
                (Some(g), _) if g.actual.is_none() => 1,
                (_, Some(n)) if n.net.is_none() => 1,
                (Some(g), _) if !g.passed => EXIT_GATE_FAILED,
                (_, Some(n)) if !n.passed => EXIT_GATE_FAILED,
                _ => 0,
            },
        }
    };
    progress.run_finished(
        result,
        exit,
        setup_warnings,
        gate.as_ref(),
        net_gain.as_ref(),
    );
    exit
}

/// What the caller asked this run to be held to.
///
/// One value rather than a parameter each, because they travel together
/// through three layers to reach [`deliver`] and a second `Option` beside the
/// first in a positional call is a mistake waiting to be made -- the two are
/// both "a threshold, or none".
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Gates {
    /// `--fail-under`: the accuracy, as a percentage, the run must reach.
    pub fail_under: Option<f64>,
    /// `--require-net-gain`: how many more rows the run must fix than it
    /// breaks, against its baseline. Zero is "no net regression"; a negative
    /// value is a tolerance, allowing that many net regressions through.
    pub net_gain: Option<i64>,
}

/// A `--fail-under` quality gate: the accuracy the caller demanded, the
/// accuracy the run achieved, and the verdict.
///
/// Measured on the whole run's `Correct` roll-up — the per-row verdict, over
/// the rows that had a ground truth to compare against. Rows with no truth are
/// not counted as failures: a report that scores half its rows is answering a
/// different question from one that scores all of them, and treating "not
/// asked" as "got it wrong" would make the threshold mean something different
/// for every report.
#[derive(Debug, Clone, PartialEq)]
struct Gate {
    /// The threshold, as a percentage.
    required: f64,
    /// What the run scored, as a percentage, or `None` when nothing was scored.
    actual: Option<f64>,
    /// How many rows the figure is drawn from.
    compared: usize,
    passed: bool,
    /// The one-line explanation, shared by the summary and the event stream so
    /// the two can never disagree about why a deploy was blocked.
    note: String,
}

impl Gate {
    fn measure(result: &ReportResult, required: f64) -> Gate {
        match Metrics::gate_rollup(result) {
            Some(m) if m.compared > 0 => {
                // Compared *unrounded*. Rounding first meant `--fail-under 100`
                // passed a run that got a row wrong — 1999 of 2000 is 99.95%,
                // which displays as "100.0%" — and a gate that can be told
                // "nothing may fail" and then wave a failure through is worse
                // than no gate at all.
                //
                // The number shown is still the rounded one, except where that
                // would contradict the verdict: see [`Gate::phrase`].
                let actual = m.accuracy().unwrap_or(0.0) * 100.0;
                let passed = meets(m.correct, m.compared, required);
                let (shown, demanded) = Gate::phrase(actual, required, passed);
                Gate {
                    required,
                    actual: Some(actual),
                    compared: m.compared,
                    passed,
                    note: format!(
                        "accuracy {shown}% over {} scored row{} — {} the required {demanded}%",
                        m.compared,
                        if m.compared == 1 { "" } else { "s" },
                        if passed { "at or above" } else { "UNDER" }
                    ),
                }
            }
            // The report declares a `TRUTH` (checked before the run) but no row
            // arrived at one: every truth was blank, or unresolved, or the rows
            // that would have carried them never ran. There is no accuracy to
            // compare, and passing a gate on no evidence is the outcome the
            // gate exists to prevent — so this is reported as a broken run
            // (exit 1) rather than as a quality miss; see [`deliver`].
            _ => Gate {
                required,
                actual: None,
                compared: 0,
                passed: false,
                note: format!(
                    "no row was scored, so there is no accuracy to hold to the required {}%",
                    percent_text_bare(required)
                ),
            },
        }
    }

    /// The gate on a run that was stopped: measured on nothing, because the
    /// figure would be drawn from whichever rows happened to finish.
    ///
    /// A stopped run exits [`EXIT_INTERRUPTED`] whatever the gate says, so this
    /// changes no exit code; it exists so the summary and the `run_finished`
    /// event cannot report a *verdict* on a half-run — "passed: true" over the
    /// third of the suite that ran is exactly the false green a gate is bought
    /// to prevent. (The two stop paths disagree about the evidence, too: an
    /// abandoned run clears its verdicts, a graceful one keeps them.)
    fn not_measured(required: f64) -> Gate {
        Gate {
            required,
            actual: None,
            compared: 0,
            passed: false,
            note: format!(
                "the run was stopped before it finished, so its accuracy was not held to the required {}%",
                percent_text_bare(required)
            ),
        }
    }

    /// How to print the two figures so the sentence cannot contradict itself.
    ///
    /// At one decimal place a 94.96% prints as "95.0%", and "accuracy 95.0% —
    /// UNDER the required 95.0%" is an unanswerable bug report. So the shown
    /// precision is the *smallest* one at which the two numbers, as printed,
    /// still order the way the verdict says they do.
    fn phrase(actual: f64, required: f64, passed: bool) -> (String, String) {
        for places in PERCENT_DECIMALS..=6 {
            let (a, r) = (format!("{actual:.places$}"), format!("{required:.places$}"));
            let agrees = match (a.parse::<f64>(), r.parse::<f64>()) {
                (Ok(a), Ok(r)) => (a >= r) == passed,
                _ => false,
            };
            if agrees {
                return (a, r);
            }
        }
        // Unreachable for any real report (it would take ~10^7 scored rows for
        // a single wrong answer to vanish at six places), but a gate that
        // panicked on the arithmetic would be worse than one that over-prints.
        (format!("{actual:.6}"), format!("{required:.6}"))
    }
}

/// Did `correct` out of `compared` meet the threshold?
///
/// Decided in integers, because neither side of the question is a float. The
/// run's score is a ratio of two counts, and the threshold is a decimal
/// somebody typed — but `(23 / 40) * 100.0` is `57.49999999999999`, so a run
/// that got exactly the 57.5% it was asked for failed the gate, and
/// [`Gate::phrase`] then printed the only sentence it could: "57.500000% —
/// UNDER the required 57.500000%". Blocking a release over the last bit of a
/// `f64` is the one failure mode a gate cannot have.
///
/// So the threshold is put back into the decimal it was written as — `57.5`
/// becomes 575 hundredths of a percent — and the comparison is a
/// cross-multiplication of exact integers:
///
/// ```text
/// correct / compared >= significand / (100 * 10^scale)
/// ```
///
/// This also subsumes the whole-row special case that used to guard
/// `--fail-under 100`: with a significand of 100 and no decimals it reduces to
/// `correct >= compared`, which is "every scored row was right" said exactly.
///
/// The `f64` is kept for *display* only, where being out by 10^-14 cannot
/// mislead anyone.
fn meets(correct: usize, compared: usize, required: f64) -> bool {
    let exact = decimal(required)
        .and_then(|(sig, scale)| Some((sig, 10u128.checked_pow(scale)?)))
        .and_then(|(sig, pow)| {
            let lhs = (correct as u128).checked_mul(100)?.checked_mul(pow)?;
            let rhs = sig.checked_mul(compared as u128)?;
            Some(lhs >= rhs)
        });
    // A threshold no decimal can describe (an infinity, a NaN) never reaches
    // here — `percentage` rejects those on the command line — and the integers
    // cannot overflow `u128` for any run that fits in memory. The float
    // comparison is kept as the answer of last resort rather than a panic:
    // whatever else is wrong, the gate still returns a verdict.
    exact.unwrap_or_else(|| {
        let actual = if compared == 0 {
            0.0
        } else {
            correct as f64 / compared as f64 * 100.0
        };
        actual >= required
    })
}

/// A threshold as the decimal it was written as: an integer significand and
/// the number of decimal places, so `57.5` is `(575, 1)`.
///
/// Recovered from the `f64` rather than carried alongside it from the command
/// line. Rust prints a float as the *shortest* decimal that round-trips to the
/// same value, which — for anything a person types as a percentage — is the
/// decimal they typed: `57.5` prints as `57.5`, never as
/// `57.499999999999996`. Display never uses exponent notation, and a threshold
/// is range-checked to 0–100 at the point of parsing, so the text here is
/// always plain digits with at most one point.
fn decimal(percent: f64) -> Option<(u128, u32)> {
    let text = format!("{percent}");
    let (whole, frac) = text.split_once('.').unwrap_or((text.as_str(), ""));
    Some((format!("{whole}{frac}").parse().ok()?, frac.len() as u32))
}

/// A `--require-net-gain` gate: whether the run improved on its baseline by as
/// much as the caller demanded.
///
/// The question `--fail-under` cannot answer. An accuracy threshold is an
/// absolute floor, and a suite that has climbed well above it can break rows
/// for months without ever reaching it -- a run at 98% that breaks three of a
/// hundred rows still clears `--fail-under 95` comfortably, and the only
/// evidence that anything went wrong is a number nobody is comparing against
/// last week's. This gate is on the *change*: rows fixed minus rows regressed,
/// counted exactly as the `Trend` column counts them, over the rows that were
/// scored on both sides.
///
/// It also needs no maintenance, which is the other half of why it catches
/// things a floor does not. An accuracy threshold has to be raised by hand as a
/// suite improves or it quietly stops meaning anything, and raising it is
/// nobody's job; "do not go backwards" keeps its meaning at every level of
/// quality.
#[derive(Debug, Clone, PartialEq)]
struct NetGain {
    /// The minimum net improvement demanded. Zero is "no net regression"; a
    /// negative value lets that many net regressions through.
    required: i64,
    /// `fixed - regressed`, or `None` when no row was scored on both sides.
    net: Option<i64>,
    /// The counts behind the figure, for the event stream.
    movement: Option<Movement>,
    passed: bool,
    /// The one-line explanation, shared by the summary and the event stream so
    /// the two can never disagree about why a deploy was blocked.
    note: String,
}

impl NetGain {
    fn measure(result: &ReportResult, required: i64) -> NetGain {
        match Metrics::gate_movement(result) {
            Some(m) => {
                // Whole rows on both sides, so there is no arithmetic here to
                // be imprecise about -- unlike the accuracy gate, which had to
                // be taught not to fail a run for landing exactly on its
                // threshold.
                let net = m.fixed as i64 - m.regressed as i64;
                let passed = net >= required;
                NetGain {
                    required,
                    net: Some(net),
                    movement: Some(m),
                    passed,
                    note: format!(
                        "{} fixed, {} regressed — {}, {} the required {}",
                        m.fixed,
                        m.regressed,
                        net_text(net),
                        if passed { "at or above" } else { "BELOW" },
                        required_text(required)
                    ),
                }
            }
            // The report declares a baseline (checked before the run) and not
            // one row reached it with a truth on both sides: the comparison
            // never happened. As with `--fail-under`, that is a broken run
            // rather than a quality miss -- see [`deliver`].
            None => NetGain {
                required,
                net: None,
                movement: None,
                passed: false,
                note: format!(
                    "no row was scored against a baseline, so there is no movement to hold to the required {}",
                    required_text(required)
                ),
            },
        }
    }

    /// The gate on a run that was stopped, for the same reason
    /// [`Gate::not_measured`] exists: the rows that happened to finish are not
    /// the run the caller meant to gate on, and "passed" over a third of a
    /// suite is exactly the false green a gate is bought to prevent.
    fn not_measured(required: i64) -> NetGain {
        NetGain {
            required,
            net: None,
            movement: None,
            passed: false,
            note: format!(
                "the run was stopped before it finished, so its movement was not held to the required {}",
                required_text(required)
            ),
        }
    }
}

/// A net movement in prose: the sentence reads about a run, not about a signed
/// integer, and `-3` in the middle of one is a number a reader has to stop and
/// decode.
fn net_text(net: i64) -> String {
    match net {
        0 => "level".to_string(),
        n if n > 0 => format!("a net gain of {n}"),
        n => format!("a net loss of {}", -n),
    }
}

/// A `--require-net-gain` threshold in prose.
fn required_text(required: i64) -> String {
    match required {
        0 => "break-even".to_string(),
        n if n > 0 => format!("net gain of {n}"),
        n => format!("floor of {n}"),
    }
}

/// A threshold as it is written in the summary: the shared percentage
/// rendering, without the `%` (the sentences around it supply their own).
fn percent_text_bare(percent: f64) -> String {
    percent_text(percent).trim_end_matches('%').to_string()
}

/// A `--fail-under` gate was not met: the run itself was fine, and the answers
/// were not good enough.
///
/// Its own code because the two call for different responses. 1 says the run
/// broke and is worth retrying; this says the run worked perfectly and the API
/// is wrong, which no retry will fix. Only ever returned in place of 0 — see
/// the precedence in [`deliver`].
pub const EXIT_GATE_FAILED: i32 = 5;

/// The run finished, but some steps never ran because something they depended
/// on failed. Documented in the README; changing it is a breaking change for
/// anyone scripting a release check.
pub const EXIT_SKIPPED: i32 = 3;

/// The run was stopped on request and wrote the rows it had.
///
/// Distinct from 1 and 3 because it answers a different question. 1 says the
/// API under test misbehaved; 3 says the report's own dependencies pruned part
/// of it; 4 says nothing was wrong at all — someone pressed stop. A caller that
/// retries on 1 must not retry on 4, and a dashboard that paints 1 red should
/// not paint this red.
pub const EXIT_INTERRUPTED: i32 = 4;

/// A second stop request, which gives up on the wind-down itself.
///
/// 128 + SIGINT, the shell's convention for "killed by an interrupt", and
/// deliberately *not* [`EXIT_INTERRUPTED`]: this path may have skipped
/// `CLEANUP` and may have written nothing, so a caller that treats 4 as "I have
/// a partial report" would be wrong to treat this the same way.
pub const EXIT_FORCED: i32 = 130;

/// How long a stopped run waits for the rows already in flight, unless
/// `--grace` says otherwise.
///
/// Thirty seconds because the wait is for work already paid for — an upload
/// half-sent, a slow report endpoint — and, after it, for `CLEANUP` to release
/// what the run took. Too short and a stop routinely abandons both; too long
/// and the stop button feels broken. A second stop is the escape hatch either
/// way, so this only has to be a sensible default rather than a bound anyone
/// has to live with.
pub const DEFAULT_GRACE_SECS: u64 = 30;

/// How often the waiting loop looks up from the run to see whether a stop has
/// been asked for. Short enough to feel immediate, long enough not to spin.
const STOP_POLL: std::time::Duration = std::time::Duration::from_millis(50);

/// The stop channel of a headless run: the switch the flow reads, how long a
/// stop will wait for the work already under way, and how the process ends if
/// that wait runs out.
///
/// Two things can flip the switch, and both are opt-in from the caller's side
/// rather than PaperBoy's business:
///
/// * a **signal** — `SIGINT` (Ctrl-C) or, on Unix, `SIGTERM`/`SIGHUP`, which is
///   what a CI job cancel sends;
/// * a **`stop` line on stdin**, with `--stop-on-stdin`. Signals are awkward to
///   send from a parent process on Windows (there is no `SIGTERM`; a parent can
///   only `TerminateProcess`, which is ungraceful, or arrange a console group
///   to send `CTRL_BREAK_EVENT`), so a program driving PaperBoy gets a channel
///   that works identically everywhere and needs no signal handling at all.
///   With `--progress-json` it completes the pair: events out on stderr,
///   control in on stdin. EOF counts as a stop, so a run also winds down when
///   the parent that started it goes away.
pub struct Control {
    cancel: std::sync::Arc<Cancel>,
    grace: std::time::Duration,
    /// What asked for the stop, for the `run_stopping` event: `"signal"`,
    /// `"stdin"` or `"eof"`. A consumer that started the run itself already
    /// knows it sent a signal; one watching a run it did not start does not,
    /// and "the parent went away" reads very differently from "an operator
    /// pressed Ctrl-C". Written once by whichever watcher fires first.
    source: std::sync::Arc<std::sync::Mutex<&'static str>>,
    /// Called when the grace period expires with rows still in flight, *after*
    /// the partial report has been written.
    ///
    /// In a real run this ends the process. The stragglers are inside a
    /// `std::thread::scope`, which joins on the way out, so there is no way to
    /// stop waiting for them and still return normally — "give up on the
    /// stragglers" and "exit" are the same act. A test passes a hook that
    /// returns instead, and simply waits them out.
    abandon: fn(i32),
}

impl Control {
    /// A control plane for a real run: `grace` seconds (or the default), ending
    /// the process if the wind-down overruns.
    pub fn new(grace_secs: Option<u64>) -> Self {
        Control {
            cancel: std::sync::Arc::new(Cancel::new()),
            grace: std::time::Duration::from_secs(grace_secs.unwrap_or(DEFAULT_GRACE_SECS)),
            source: std::sync::Arc::new(std::sync::Mutex::new("stop")),
            abandon: |code| std::process::exit(code),
        }
    }

    /// A control plane for a test: no signal handler and no stdin watcher
    /// (a test process must not have its Ctrl-C redefined, and its stdin is not
    /// a control channel), and a grace expiry that *returns* instead of ending
    /// the process — so a test of the abandoned path asserts on the report that
    /// was written and then simply waits the stragglers out.
    ///
    /// The switch itself is reachable through [`Control::switch`], which is how
    /// a test stops a run: from inside a fake runner, at a row of its choosing,
    /// with no timing to get wrong.
    #[cfg(test)]
    fn for_test() -> Self {
        Control {
            cancel: std::sync::Arc::new(Cancel::new()),
            grace: std::time::Duration::from_secs(DEFAULT_GRACE_SECS),
            source: std::sync::Arc::new(std::sync::Mutex::new("stop")),
            abandon: |_| {},
        }
    }

    /// The stop switch, for a caller that needs to flip it itself.
    #[cfg(test)]
    fn switch(&self) -> std::sync::Arc<Cancel> {
        self.cancel.clone()
    }

    /// How long this run will wait, once stopped, before giving up on the rows
    /// still in flight.
    #[cfg(test)]
    fn with_grace(mut self, grace: std::time::Duration) -> Self {
        self.grace = grace;
        self
    }

    /// What asked for the stop, as of now.
    fn source(&self) -> &'static str {
        *self.source.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Start listening for stop requests: always for signals, and for `stop`
    /// lines on stdin when the caller asked for that channel.
    ///
    /// The second request from either source is the hard kill: it exits at
    /// once, on the assumption that a caller repeating itself has decided the
    /// wind-down is not going to happen (a `CLEANUP` hanging on the very
    /// service that has stopped responding is the case this exists for).
    fn listen(&self, stop_on_stdin: bool) {
        let cancel = self.cancel.clone();
        let source = self.source.clone();
        let hits = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let signal_hits = hits.clone();
        // Best effort: a handler can only be installed once per process, and a
        // failure here costs the graceful path, not the run. (It also keeps the
        // tests, which call the runner many times over, from tripping on the
        // second install.)
        let _ = ctrlc::set_handler(move || {
            if signal_hits.fetch_add(1, std::sync::atomic::Ordering::Relaxed) > 0 {
                std::process::exit(EXIT_FORCED);
            }
            *source.lock().unwrap_or_else(|e| e.into_inner()) = "signal";
            cancel.stop();
        });
        if !stop_on_stdin {
            return;
        }
        let cancel = self.cancel.clone();
        let source = self.source.clone();
        // Detached on purpose: a blocking read on stdin cannot be cancelled,
        // and there is nothing to join it for — the thread's only job is to
        // outlive its own `read_line` or the process, whichever comes first.
        std::thread::spawn(move || {
            let mut line = String::new();
            loop {
                line.clear();
                match std::io::stdin().read_line(&mut line) {
                    // EOF: the parent closed the pipe or died, and a run nobody
                    // is listening to any more should wind down rather than
                    // carry on sending requests for an hour. A `stop` line is
                    // usually followed by exactly this, though, and the reason
                    // the caller gave is worth more than the one it implies —
                    // so an already-stopped run keeps the source it has.
                    Ok(0) => {
                        if !cancel.stopped() {
                            *source.lock().unwrap_or_else(|e| e.into_inner()) = "eof";
                        }
                        cancel.stop();
                        return;
                    }
                    Ok(_) => {
                        if !line.trim().eq_ignore_ascii_case("stop") {
                            continue;
                        }
                        if hits.fetch_add(1, std::sync::atomic::Ordering::Relaxed) > 0 {
                            std::process::exit(EXIT_FORCED);
                        }
                        *source.lock().unwrap_or_else(|e| e.into_inner()) = "stdin";
                        cancel.stop();
                    }
                    Err(_) => return,
                }
            }
        });
    }
}

/// The one format stdout takes: a pipe is for text, and a binary `.xlsx` down
/// it would be useless. Named so the value written and the value *announced*
/// come from the same place.
const CSV_EXTENSION: &str = "csv";

/// Where the rendered report ended up (for the closing summary line).
enum OutputTarget {
    /// Written to stdout, in the format named — carried rather than assumed by
    /// the caller, so the announcement can't drift from what was written if
    /// stdout ever takes a second format.
    Stdout(&'static str),
    File(PathBuf),
}

/// Serialize `result` and write it to the chosen destination:
/// - `Some("-")`  → stdout (clean CSV, for piping);
/// - `Some(path)` → that file (its extension selects the format: csv/json/xlsx);
/// - `None`       → a file derived from the header (`# output:` format,
///   `# name:`-derived stem honouring `{time}`, next to the report file).
///
/// An unrecognised extension/format is an error naming the supported set.
fn write_output(
    result: &ReportResult,
    header: &Header,
    output: Option<&str>,
    report: &Report,
) -> Result<OutputTarget, String> {
    match output {
        Some("-") => {
            // stdout is for piping text, so it always emits CSV (a binary xlsx
            // to a terminal would be useless); write to a named file for other
            // formats.
            let bytes = CsvWriter.write(result, header)?;
            std::io::stdout()
                .write_all(&bytes)
                .map_err(|e| e.to_string())?;
            Ok(OutputTarget::Stdout(CSV_EXTENSION))
        }
        Some(path) => {
            let ext = output_extension_of(path);
            let writer = writer_for_extension(&ext).ok_or_else(|| unsupported_ext(&ext))?;
            let bytes = writer.write(result, header)?;
            fs::write(path, bytes).map_err(|e| format!("{path}: {e}"))?;
            Ok(OutputTarget::File(PathBuf::from(path)))
        }
        None => {
            // The format comes from a `# output:` directive (default csv).
            let ext = output_extension_from_header(header)?;
            let writer = writer_for_extension(&ext).ok_or_else(|| unsupported_ext(&ext))?;
            let path = derived_output_path(report, &ext);
            let bytes = writer.write(result, header)?;
            fs::write(&path, bytes).map_err(|e| format!("{}: {e}", path.display()))?;
            Ok(OutputTarget::File(path))
        }
    }
}

/// Everything about `-o` that can be judged before the run, judged before it.
///
/// With nothing chosen the header decides, so the format it names has to exist;
/// with `-o` given, every path must carry a format PaperTrail can write.
fn check_outputs(outputs: &[String], header: &Header) -> Result<(), String> {
    if outputs.is_empty() {
        output_extension_from_header(header)?;
        return Ok(());
    }
    // Two formats written to one pipe would interleave into something that is
    // neither of them, and there is no second stdout to send the other to.
    if outputs.iter().filter(|o| o.as_str() == "-").count() > 1 {
        return Err("-o - was given more than once, but there is only one stdout".to_string());
    }
    let mut seen: Vec<&str> = Vec::new();
    for out in outputs {
        if out == "-" {
            continue;
        }
        // Writing the same path twice means the second write destroys the
        // first, so the run would quietly produce one file where two were
        // asked for. Far more likely a typo in one of them than an intent.
        if seen.contains(&out.as_str()) {
            return Err(format!("-o {out} was given more than once"));
        }
        seen.push(out);
        let ext = output_extension_of(out);
        if writer_for_extension(&ext).is_none() {
            return Err(unsupported_ext(&ext));
        }
    }
    Ok(())
}

/// The format an output path selects: its extension, lowercased, defaulting to
/// CSV for a path that has none.
fn output_extension_of(path: &str) -> String {
    Path::new(path)
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("csv")
        .to_ascii_lowercase()
}

/// The output extension implied by a `# output:` directive: its value lowercased
/// and trimmed (empty ⇒ `csv`). Errors when the named format isn't supported.
fn output_extension_from_header(header: &Header) -> Result<String, String> {
    let ext = header
        .output()
        .map(|f| f.trim().to_ascii_lowercase())
        .filter(|f| !f.is_empty())
        .unwrap_or_else(|| "csv".to_string());
    if writer_for_extension(&ext).is_none() {
        return Err(format!(
            "unsupported '# output:' format '{ext}' (supported: {})",
            OUTPUT_EXTENSIONS.join(", ")
        ));
    }
    Ok(ext)
}

/// The error for an output extension PaperTrail can't write.
fn unsupported_ext(ext: &str) -> String {
    format!(
        "unsupported output extension '.{ext}' (supported: {})",
        OUTPUT_EXTENSIONS.join(", ")
    )
}

/// The default output path when `-o` is omitted: alongside the report file with
/// the `ext` extension, unless the report *name* carries the `{time}` token, in
/// which case the token-expanded, sanitised name wins (a distinct file per run)
/// — placed in the report's own folder. Mirrors the TUI's `csv_export_path`.
fn derived_output_path(report: &Report, ext: &str) -> PathBuf {
    if name_has_output_token(&report.name) {
        let stem = sanitize_file_stem(&expand_output_tokens(&report.name));
        let file = format!("{stem}.{ext}");
        return match report.path.as_deref().and_then(Path::parent) {
            Some(dir) => dir.join(file),
            None => PathBuf::from(file),
        };
    }
    if let Some(path) = &report.path {
        return path.with_extension(ext);
    }
    PathBuf::from(format!("{}.{ext}", sanitize_file_stem(&report.name)))
}

/// Routes human-readable lines to the right stream: stderr when the CSV is going
/// to stdout (`-o -`, so stdout stays clean for piping), stdout otherwise.
///
/// Silenced entirely when those lines would land on a stderr that
/// `--progress-json` has claimed for the machine-readable stream: a consumer
/// reading NDJSON line by line must not have to sort prose out of it, and every
/// fact the header block carries is in the events anyway. Decoration bound for
/// *stdout* is left alone — nothing is competing for it there.
struct Decor {
    to_stderr: bool,
    silent: bool,
}

impl Decor {
    fn new(csv_to_stdout: bool, progress_json: bool) -> Self {
        Decor {
            to_stderr: csv_to_stdout,
            silent: csv_to_stdout && progress_json,
        }
    }
    fn line(&mut self, s: &str) {
        if self.silent {
        } else if self.to_stderr {
            eprintln!("{s}");
        } else {
            println!("{s}");
        }
    }
}

/// The version of the `--progress-json` event stream, carried on **every**
/// event as `"schema"`.
///
/// On every event rather than only on the first because a consumer may attach
/// to a stream already in progress (a tail, a restarted reader), and a version
/// it can only have learned from a line it missed is no version at all. It is
/// also the one thing that cannot be retrofitted: a reader written against
/// schema 1 has to be able to *refuse* a schema 2 stream rather than silently
/// mis-read it, which means the number has to be there from the first release.
const PROGRESS_SCHEMA: u32 = 1;

/// How long a cell value may be before `row_completed` stops carrying it.
///
/// Progress is meant to be cheap. A column holding a whole engine response
/// would be streamed through stderr on every row while the same bytes are
/// already going to the output file, so anything this long is announced as
/// withheld and the consumer reads the full value from the report at the end
/// (by `row_index`, which is where that row landed in it).
const PROGRESS_MAX_CELL: usize = 4096;

/// The `--progress-json` emitter: newline-delimited JSON on stderr, one object
/// per line, flushed as each event is produced.
///
/// **stderr**, because `-o -` has already promised stdout to the report itself
/// and the existing contract puts progress on stderr. **Line-delimited**,
/// because the point is to be read incrementally — `for line in proc.stderr` in
/// Python, with an ordinary `json.loads` per line, and no streaming parser.
///
/// Every row event carries `path`: the row's structural [`ReportRow::path`]
/// (`(loop index, iteration)` pairs flattened into a dotted string, `"0.3"`,
/// `"0.1.2.0"`, `""` for the single row of a loop-free report). It is the join
/// key, and it is what makes the stream usable under `PARALLEL`: it is assigned
/// before the run, stable, unique, and identifies a row no matter what order
/// the workers finish in. Beside it rides [`RowSlots`]'s `row_index`, which is
/// where that row lands in the written report — so a consumer can hold a cheap
/// live grid and fill in the full values from the file once the run is done.
struct Progress {
    /// Where a formatted event line goes, or `None` when `--progress-json` was
    /// not asked for.
    ///
    /// A sink rather than a bare `bool` so the stream can be asserted on in a
    /// test: the events are a published contract (a consumer parses them by
    /// key), and a contract that can only be observed by running the binary and
    /// scraping the real stderr is one that gets broken quietly.
    out: Option<Box<dyn Fn(&str) + Sync + Send>>,
    /// Set once `run_finished` has gone out; every later event is dropped.
    ///
    /// The stream's headline promise is a single terminal event — an event
    /// *after* it breaks the contract from the other end, and a consumer that
    /// finalises its state there will either throw or silently mis-record. The
    /// window is real: a run given up on writes its report and exits while
    /// straggler rows are still in flight, and one landing in the sink between
    /// the terminal event and `process::exit` would be announced into a stream
    /// that had already ended. A latch here rather than disarming the sink,
    /// because it closes that shape wherever it appears rather than in the one
    /// place we found it.
    finished: std::sync::atomic::AtomicBool,
}

impl Progress {
    fn new(on: bool) -> Self {
        Progress {
            finished: std::sync::atomic::AtomicBool::new(false),
            out: on.then(|| {
                Box::new(|line: &str| {
                    let mut err = std::io::stderr().lock();
                    let _ = err.write_all(line.as_bytes());
                    let _ = err.flush();
                }) as Box<dyn Fn(&str) + Sync + Send>
            }),
        }
    }

    /// Whether `--progress-json` was asked for.
    fn on(&self) -> bool {
        self.out.is_some()
    }

    /// A fatal setup failure — an unreadable collection, a `--param` the report
    /// doesn't declare, a validation error. Returns the exit code, so a call
    /// site reads `return progress.setup_failed(…)`.
    ///
    /// This still ends the stream with `run_finished`. The run never started,
    /// so there is no row to report on — but that is a distinction the *runner*
    /// cares about, not the program driving it, which asked one question: did
    /// it work, and if not, why? Leaving these outside the stream would have
    /// made `run_finished`'s promise ("one terminal event, carrying the code
    /// you will get") false for exactly the failures a caller hits most — a
    /// mistyped parameter, a folder that isn't there — and left a consumer
    /// that skips non-JSON lines with an empty stream, a bare exit 1, and
    /// nothing to show anyone.
    ///
    /// The prose is *replaced* rather than accompanied, because with `-o -` it
    /// would land on the stream's own channel: the message is in the event.
    fn setup_failed(&self, errors: Vec<String>) -> i32 {
        self.setup_failed_with(errors, Vec::new())
    }

    /// [`setup_failed`](Self::setup_failed), also carrying the validation
    /// warnings collected before the failure (which the human mode has already
    /// printed).
    fn setup_failed_with(&self, errors: Vec<String>, warnings: Vec<String>) -> i32 {
        if self.out.is_none() {
            for message in &errors {
                eprintln!("error: {message}");
            }
            return 1;
        }
        self.emit(
            "run_finished",
            serde_json::json!({
                "ok": false,
                "exit_code": 1,
                // No row ever ran, which is itself the fact a consumer needs to
                // tell a setup failure from a run in which everything failed.
                "rows": 0,
                // Carried even here, so every `run_finished` has one shape and
                // a consumer can read the same keys whatever ended the run.
                "interrupted": false,
                "dry_run": false,
                "partial": false,
                "rows_completed": serde_json::Value::Null,
                "rows_planned": serde_json::Value::Null,
                "rows_ok": 0,
                "rows_failed": 0,
                "warnings": warnings,
                "skipped": [],
                "errors": errors,
                // Null for the same reason as the gate below: nothing ran, so
                // there is nothing to have scored and nothing to have moved.
                "scored": serde_json::Value::Null,
                "movement": serde_json::Value::Null,
                // Null rather than absent: nothing ran, so no gate was ever
                // evaluated, and a consumer reading the same key on every
                // `run_finished` must not have to treat a missing key as a
                // pass. (`--fail-under` may well have been asked for.)
                "gate": serde_json::Value::Null,
            }),
        );
        1
    }

    /// Write one event as a single line.
    ///
    /// Formatted into a `String` and written in one call rather than
    /// `eprintln!`'d piecewise, because `PARALLEL` rows are announced from
    /// several threads at once and a line assembled in pieces could interleave
    /// with another's — which would corrupt exactly the property (one object per
    /// line) the whole transport rests on.
    fn emit(&self, event: &str, fields: serde_json::Value) {
        let Some(out) = &self.out else {
            return;
        };
        if self.finished.load(std::sync::atomic::Ordering::Acquire) {
            return;
        }
        let mut obj = serde_json::Map::new();
        obj.insert("event".into(), serde_json::Value::String(event.into()));
        obj.insert("schema".into(), serde_json::json!(PROGRESS_SCHEMA));
        if let serde_json::Value::Object(map) = fields {
            for (k, v) in map {
                obj.insert(k, v);
            }
        }
        out(&format!("{}\n", serde_json::Value::Object(obj)));
    }

    /// Once, after the projection pass and before anything is sent: how many
    /// rows there will be and what the columns are called, so a front-end can
    /// draw the empty grid up front instead of growing it a row at a time.
    fn plan(
        &self,
        report_name: &str,
        total: usize,
        streamed: &[OutputColumn],
        withheld: &[OutputColumn],
        dry_run: bool,
    ) {
        self.emit(
            "plan",
            serde_json::json!({
                "report": report_name,
                "dry_run": dry_run,
                "total": total,
                "columns": streamed.iter().map(|c| c.header.clone()).collect::<Vec<_>>(),
                // Named, not silently dropped: a consumer that sees a column
                // missing from `row_completed` has to be able to tell "too big
                // to stream, read it from the report" from "this report has no
                // such column".
                "withheld_columns": withheld.iter().map(|c| c.header.clone()).collect::<Vec<_>>(),
            }),
        );
    }

    fn row_started(&self, path: &[(usize, usize)], slots: &RowSlots) {
        self.emit(
            "row_started",
            serde_json::json!({ "path": path_key(path), "row_index": slots.index_of(path) }),
        );
    }

    /// One finished row: its slot, its scalar cells, and whether it went wrong.
    fn row_completed(
        &self,
        row: &ReportRow,
        errors: &[String],
        columns: &[OutputColumn],
        no_match: &str,
        slots: &RowSlots,
    ) {
        if self.out.is_none() {
            return;
        }
        let mut cells = serde_json::Map::new();
        // Withheld, not shortened: a consumer told a value was "truncated"
        // could reasonably render the stub it was given, and there is no stub —
        // the cell is absent, to be read from the report. Same word as `plan`'s
        // `withheld_columns`, because it is the same mechanism.
        let mut withheld: Vec<String> = Vec::new();
        for col in columns {
            let value = col.value(row, no_match);
            if value.len() > PROGRESS_MAX_CELL {
                withheld.push(col.header.clone());
                continue;
            }
            cells.insert(col.header.clone(), serde_json::Value::String(value));
        }
        self.emit(
            "row_completed",
            serde_json::json!({
                "path": path_key(&row.path),
                "row_index": slots.index_of(&row.path),
                "ok": errors.is_empty(),
                "target": row.target,
                "cells": serde_json::Value::Object(cells),
                "errors": errors,
                "withheld": withheld,
            }),
        );
    }

    /// One output file as it lands — announced individually, and including the
    /// ones that failed, because a part-written set is left in place on purpose:
    /// the files already written are faithful renderings of a run that really
    /// happened, and a consumer needs to know which of them exist.
    fn output_written(&self, path: &str, format: &str, error: Option<&str>) {
        self.emit(
            "output_written",
            serde_json::json!({
                "path": path,
                "format": format,
                "ok": error.is_none(),
                "error": error,
            }),
        );
    }

    /// The last line of the stream: the run's verdict and the process's exit
    /// code.
    ///
    /// Last, *after* the `output_written` events, because a file that fails to
    /// write changes the exit code — emitting this at the end of the run proper
    /// would mean publishing a number the process then contradicts. A consumer
    /// therefore has one terminal event to wait for, and the code on it is the
    /// code it will get.
    fn run_finished(
        &self,
        result: &ReportResult,
        exit_code: i32,
        setup_warnings: &[String],
        gate: Option<&Gate>,
        net_gain: Option<&NetGain>,
    ) {
        // The validation warnings are folded in with the run's own: a consumer
        // asked what it should be told about this run, and "which phase raised
        // it" is not a distinction it can act on. In the human mode they were
        // printed as they were found, which is why they are carried rather than
        // re-derived here.
        let warnings: Vec<&String> = setup_warnings
            .iter()
            .chain(result.warnings.iter())
            .collect();
        // Counted over the rows that actually ran: a projected row of a dry
        // run, or one a stopped run never reached, has neither succeeded nor
        // failed, and folding those into `rows_ok` would report a run that was
        // abandoned after two rows as thirty-eight clean ones.
        let ran = result.rows.len() - result.pending.len();
        let rows_failed = result
            .rows
            .iter()
            .enumerate()
            .filter(|(r, row)| !result.pending.contains(r) && !row.errors.is_empty())
            .count();
        let rows_ok = ran - rows_failed;
        // Projection-independent, exactly as the gate is: these answer how the
        // run went, not what the table shows, so a `# columns:` directive that
        // hides a column cannot change them. See `Metrics::gate_rollup`.
        let scored = Metrics::gate_rollup(result)
            .filter(|m| m.compared > 0)
            .map(|m| {
                serde_json::json!({
                    "compared": m.compared,
                    "correct": m.correct,
                    "incorrect": m.incorrect,
                    // A percentage, unrounded, to match `gate.actual` — the two
                    // are the same number and a consumer comparing them must not
                    // find them disagreeing by a tenth.
                    "accuracy": m.accuracy().map(|a| a * 100.0),
                })
            });
        // One object holding everything known about the comparison: the counts,
        // and the verdict where `--require-net-gain` asked for one. The verdict
        // is carried *here* rather than beside the accuracy gate because it is
        // read off these very numbers, and a consumer that found them in two
        // places would have to decide which to believe.
        //
        // Null only when there is nothing to say at all: no baseline, and no
        // gate that was asked for and could not be measured. A stopped or
        // baseline-less run under the gate still gets an object, with null
        // counts and the note saying why — the same shape as `gate`, so one
        // key can be read on every `run_finished`.
        let moved = net_gain
            .and_then(|n| n.movement)
            .or_else(|| Metrics::gate_movement(result));
        let movement = (moved.is_some() || net_gain.is_some()).then(|| {
            let mut obj = serde_json::json!({
                "fixed": moved.map(|m| m.fixed),
                "regressed": moved.map(|m| m.regressed),
                "still_wrong": moved.map(|m| m.still_wrong),
                "unchanged": moved.map(|m| m.unchanged),
            });
            if let (Some(n), Some(map)) = (net_gain, obj.as_object_mut()) {
                map.insert("required_net_gain".into(), serde_json::json!(n.required));
                map.insert("net_gain".into(), serde_json::json!(n.net));
                map.insert("passed".into(), serde_json::json!(n.passed));
                map.insert("note".into(), serde_json::json!(n.note));
            }
            obj
        });
        self.emit(
            "run_finished",
            serde_json::json!({
                "ok": exit_code == 0,
                "exit_code": exit_code,
                "rows": result.rows.len(),
                // A stop is not a silent EOF. `interrupted` says the run was
                // told to stop; `partial` says the report it produced is
                // therefore short, with the counts to say by how much.
                "interrupted": exit_code == EXIT_INTERRUPTED,
                // Nothing was sent: the rows below are projected. Stated on
                // the terminal event as well as on `plan` because a consumer
                // that joined late, or that keeps only the last event, must
                // not read a preview as a run.
                "dry_run": result.dry_run,
                "partial": result.partial.is_some(),
                "rows_completed": result.partial.map(|p| p.rows_completed),
                "rows_planned": result.partial.map(|p| p.rows_planned),
                "rows_ok": rows_ok,
                "rows_failed": rows_failed,
                "warnings": warnings,
                "skipped": result.skipped,
                "errors": result.errors,
                // The run's own arithmetic, so a caller gating on quality does
                // not have to parse the report it just wrote — and reads the
                // same figures the gate was decided on. Both are `null` rather
                // than zeroed when there is nothing to report: a run with no
                // ground truth has not scored 0%, and one with no baseline has
                // not "stayed still".
                "scored": scored,
                "movement": movement,
                // Present only when `--fail-under` asked for one, so a consumer
                // can tell "the gate passed" from "there was no gate" — the
                // difference between a checked deploy and an unchecked one.
                "gate": gate.map(|g| serde_json::json!({
                    "metric": "accuracy",
                    "required": g.required,
                    "actual": g.actual,
                    "compared": g.compared,
                    "passed": g.passed,
                    "note": g.note,
                })),
            }),
        );
        // After the emit, not before — this is the one event the latch must
        // not swallow.
        self.finished
            .store(true, std::sync::atomic::Ordering::Release);
    }

    /// The stop was heard and the run is winding down: no new rows will start,
    /// and the rows in flight have `grace` to finish before they are given up
    /// on.
    ///
    /// Emitted because a dashboard that sent `stop` and then saw nothing for
    /// forty seconds has no way to tell "winding down" from "ignored me" —
    /// and the answer decides whether a user presses the button again (which
    /// is the hard kill).
    fn run_stopping(&self, source: &str, grace: std::time::Duration) {
        self.emit(
            "run_stopping",
            serde_json::json!({
                "source": source,
                "grace_seconds": grace.as_secs(),
            }),
        );
    }
}

/// A grace period as it is spoken about in prose: `30`, but `0.25` rather than
/// a truncated `0` for the sub-second periods only a test sets today.
///
/// `--grace` takes whole seconds, so this is belt and braces — but the two
/// sentences it feeds ("did not wind down within {}s") read as a lie at any
/// duration under one, and a number that renders as zero is the worst kind.
fn grace_label(grace: std::time::Duration) -> String {
    match grace.subsec_nanos() {
        0 => grace.as_secs().to_string(),
        _ => format!("{}", grace.as_secs_f64()),
    }
}

/// What a run has produced so far, copied out of the row stream as it goes.
///
/// The insurance policy behind a stopped run: the fully assembled result only
/// exists when the run *returns*, so a run abandoned mid-flight would otherwise
/// have nothing to show. See [`abandoned_result`].
#[derive(Default)]
struct Harvest {
    /// Every completed row, in the order the run finished them (not report
    /// order — the writer sorts nothing, so these are laid back into the
    /// projected shape as they came).
    rows: Vec<ReportRow>,
    /// The per-row errors those rows raised, each kept beside the path of the
    /// row that raised it — the errors arrive in the same completion order as
    /// the rows, and are laid back into report order the same way.
    errors: Vec<(Vec<(usize, usize)>, String)>,
    /// How many rows completed — counted rather than taken from `rows.len()`
    /// so it keeps meaning the same thing if the rows are ever pruned.
    completed: usize,
}

/// How the waiting loop around a live run ended.
enum Ending {
    /// The run returned — on its own, or because a stop request wound it down
    /// inside the grace period.
    Ran(ReportResult),
    /// The grace period expired, and the partial report has already been
    /// written and announced from inside the run's scope (which is the only
    /// place it can be, since the scope joins the stragglers on the way out).
    Delivered(i32),
    /// The run thread died without sending. Only reachable if it panicked, and
    /// the scope re-raises that panic as it joins.
    Lost,
}

/// The report an abandoned run leaves behind: the projection's *shape* —
/// columns, statistics, ground truths, the no-match marker — filled with the
/// rows that actually finished.
///
/// Rebuilt from the outside like this because the run that would have assembled
/// it is still running and will never be heard from again. What is lost with it
/// is everything computed at the end from the whole run: images, ground-truth
/// verdicts, and so the metrics over them. That is the real difference between
/// a wind-down inside the grace period and one that overran it, and it is why
/// the grace period is worth having rather than stopping dead on the first
/// request for it.
fn abandoned_result(
    shape: Option<&ReportResult>,
    harvest: &Mutex<Harvest>,
    planned: usize,
    grace: std::time::Duration,
) -> ReportResult {
    let held = harvest.lock().unwrap_or_else(|e| e.into_inner());
    let mut result = shape.cloned().unwrap_or_default();
    result.partial = Some(Partial {
        rows_completed: held.completed,
        rows_planned: planned,
    });
    // Back into report order. The rows were harvested as they *finished*, so
    // under PARALLEL they arrive scrambled, and nothing downstream sorts them:
    // the writers lay rows down as they are given. Leaving them would break the
    // one property that makes PARALLEL trustworthy — that a report is the same
    // at any degree — at exactly the moment someone is squinting at it, and
    // would make two abandoned runs of the same corpus undiffable.
    //
    // Sorting by path *is* the canonical order: it is the same ordering
    // `RowSlots` assigns slot numbers in, so a `row_index` streamed during the
    // run still points at the row it names here.
    let mut rows = held.rows.clone();
    rows.sort_by(|a, b| a.path.cmp(&b.path));
    result.rows = rows;
    // The errors inherit the same scramble, and the ordinary path merges them
    // in plan order; a stable sort by path keeps one row's errors in the order
    // that row raised them.
    let mut errors = held.errors.clone();
    errors.sort_by(|a, b| a.0.cmp(&b.0));
    result.errors = errors.into_iter().map(|(_, e)| e).collect();
    // A warning rather than an error: nothing about the API under test went
    // wrong. It is here because "CLEANUP may not have run" is the one
    // consequence of this path that outlives the run — a leaked session or an
    // unreleased lock is someone else's problem in ten minutes' time.
    result.warnings = vec![format!(
        "the run was stopped and did not wind down within {}s: rows still in flight were \
         abandoned, and CLEANUP may not have run (check for leftover sessions or locks)",
        grace_label(grace)
    )];
    result.skipped = Vec::new();
    // Ground truths and images are assembled at the end of a run, so this
    // report has none: leaving the *configuration* for them in place would
    // render a scoring column with nothing scored and metric cards reading 0%,
    // which is a lie about the rows that did run.
    result.column_truths.clear();
    result.column_images.clear();
    result.truths.clear();
    result.verdicts.clear();
    result.images.clear();
    result.pending.clear();
    result
}

/// The projected grid: every row's structural path in canonical (sorted) order,
/// so a streamed row can be announced with the slot number it occupies as well
/// as its path.
///
/// The number is what makes the live grid and the finished report *explicitly*
/// linkable: a `-o out.json` report is a list of rows in this same canonical
/// order, and it carries no path of its own (the path is a run-time coordinate,
/// deliberately outside the exported model). Without the index a consumer would
/// have to re-derive the ordering rule to match the two, which is exactly the
/// kind of implicit contract that breaks silently.
///
/// The one report where the two part company is a comparison: `ENVS` baseline
/// and candidate rows are streamed separately and then *collapsed* into one row
/// each by `finalize`, so the report has fewer rows than the grid. The index
/// still identifies the slot — it is the projection's, which is what `plan`'s
/// `total` counts too — and `path` remains the identity either way.
struct RowSlots {
    order: HashMap<Vec<(usize, usize)>, usize>,
}

impl RowSlots {
    fn new(projected: &[ReportRow]) -> Self {
        let mut paths: Vec<Vec<(usize, usize)>> =
            projected.iter().map(|r| r.path.clone()).collect();
        paths.sort();
        RowSlots {
            order: paths.into_iter().enumerate().map(|(i, p)| (p, i)).collect(),
        }
    }

    /// The slot this path occupies, or `None` for a row the projection did not
    /// foresee (a snapshot row injected by a `FILE(…)` role, say) — reported as
    /// `null` rather than guessed at.
    fn index_of(&self, path: &[(usize, usize)]) -> Option<usize> {
        self.order.get(path).copied()
    }
}

/// A row's structural path as a dotted string — `[(0, 3), (1, 2)]` → `"0.3.1.2"`,
/// the empty path (a report with no loop) → `""`.
///
/// A string rather than the nested array it is, because it exists to be used as
/// a dictionary key on the other side: `updates[ev["path"]] = ev` needs no
/// normalisation, whereas a list of pairs has to be tupled first in every
/// language that reads this.
fn path_key(path: &[(usize, usize)]) -> String {
    path.iter()
        .map(|(node, iter)| format!("{node}.{iter}"))
        .collect::<Vec<_>>()
        .join(".")
}

/// Split the planned columns into the ones `row_completed` carries and the ones
/// it withholds.
///
/// `DETAIL` columns and `IMAGE` columns are withheld by declaration: the author
/// has already said this column is a drill-down or a picture, which is exactly
/// the content that is too big to repeat on stderr once per row while the
/// report file is being written with it anyway. Everything else is a scalar the
/// grid can show.
fn split_streamed_columns(columns: Vec<OutputColumn>) -> (Vec<OutputColumn>, Vec<OutputColumn>) {
    columns
        .into_iter()
        .partition(|c| !c.detail && c.image.is_none())
}

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

    /// A unique scratch directory for a test, cleaned up by the caller.
    fn temp_dir(tag: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "paperboy_report_cli_{tag}_{}",
            uuid::Uuid::new_v4()
        ));
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn sanitize_file_stem_replaces_path_and_awkward_chars() {
        assert_eq!(sanitize_file_stem("a/b:c"), "a_b_c");
        assert_eq!(sanitize_file_stem("../escape"), "___escape");
        assert_eq!(sanitize_file_stem("  keep me-1_2  "), "keep me-1_2");
        // Empty / all-punctuation names fall back to a safe default.
        assert_eq!(sanitize_file_stem("   "), "report");
    }

    #[test]
    fn derived_output_path_uses_report_path_for_plain_name() {
        let mut report = Report::from_text("nightly", "# name: nightly\n");
        report.path = Some(PathBuf::from("/reports/nightly.trail"));
        assert_eq!(
            derived_output_path(&report, "csv"),
            PathBuf::from("/reports/nightly.csv")
        );
    }

    #[test]
    fn derived_output_path_expands_time_token_next_to_report() {
        let mut report = Report::from_text("run_{time}", "# name: run_{time}\n");
        report.path = Some(PathBuf::from("/reports/nightly.trail"));
        let out = derived_output_path(&report, "csv");
        let name = out.file_name().unwrap().to_string_lossy();
        // Token expanded (no literal "{time}") and placed in the report's dir.
        assert!(name.starts_with("run_"), "unexpected name: {name}");
        assert!(name.ends_with(".csv"), "unexpected name: {name}");
        assert!(!name.contains("{time}"), "token not expanded: {name}");
        assert_eq!(out.parent(), Some(Path::new("/reports")));
    }

    #[test]
    fn derived_output_path_pathless_report_sanitizes_name() {
        let report = Report::from_text("weird/name", "# name: weird/name\n");
        assert_eq!(
            derived_output_path(&report, "csv"),
            PathBuf::from("weird_name.csv")
        );
    }

    #[test]
    fn dry_run_writes_projected_csv_to_file() {
        let dir = temp_dir("dry");
        let coll = dir.join("api.hurl");
        fs::write(&coll, "# Ping\nGET https://example.test/ping\nHTTP *\n").unwrap();
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\n# columns: Ping.HttpStatus as Status\nREPORT REQUEST Ping\n",
        )
        .unwrap();
        let out = dir.join("out.csv");

        let code = run(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            vec![out.to_string_lossy().into_owned()],
            true, // dry-run: no HTTP
            Vec::new(),
            None,
            ParamValues::new(),
            Gates::default(),
            false,
            None,
            false,
        );
        assert_eq!(code, 0, "dry run should succeed");

        let csv = fs::read_to_string(&out).unwrap();
        let mut lines = csv.lines();
        assert_eq!(lines.next(), Some("Status"), "header row");
        // One projected row exists (the dry cell value is a placeholder).
        assert!(lines.next().is_some(), "one projected row expected");

        fs::remove_dir_all(&dir).ok();
    }

    /// The complaint this exists for: a dry run used to write a file that
    /// looked exactly like a real one — every planned row scored against its
    /// ground truth, `Correct: incorrect` on all of them because the response
    /// cells were blank, and a footer asserting "Accuracy 0.0%" for a run that
    /// sent nothing. The file has to say what it is, and must not pretend to
    /// have measured anything.
    #[test]
    fn a_dry_run_report_is_marked_and_carries_no_verdicts_or_accuracy() {
        let dir = temp_dir("drymark");
        let coll = dir.join("api.hurl");
        fs::write(&coll, "# Ping\nGET https://example.test/ping\nHTTP *\n").unwrap();
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\n\
             REPORT REQUEST Ping WITH\n    status: status TRUTH \"200\"\nEND\n",
        )
        .unwrap();
        let csv_out = dir.join("out.csv");
        let json_out = dir.join("out.json");

        let code = run(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            vec![
                csv_out.to_string_lossy().into_owned(),
                json_out.to_string_lossy().into_owned(),
            ],
            true, // dry-run: no HTTP
            Vec::new(),
            None,
            ParamValues::new(),
            Gates::default(),
            false,
            None,
            false,
        );
        assert_eq!(code, 0, "dry run should succeed");

        let csv = fs::read_to_string(&csv_out).unwrap();
        assert_eq!(
            csv.lines().last(),
            Some("DRY RUN,no requests were sent - these rows are projected rather than measured"),
            "the file says what it is: {csv:?}"
        );
        assert!(
            !csv.contains("incorrect"),
            "nothing was run, so nothing is wrong: {csv:?}"
        );
        assert!(
            !csv.contains(crate::report::metrics::ACCURACY_LABEL),
            "and nothing was measured: {csv:?}"
        );

        let v: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&json_out).unwrap()).unwrap();
        assert_eq!(v["dry_run"], serde_json::json!(true));
        assert!(
            v.get("metrics").is_none(),
            "no metrics object for a run that measured nothing: {v}"
        );

        fs::remove_dir_all(&dir).ok();
    }

    /// The point of `--param` for a caller shelling out to PaperBoy: one
    /// report, pointed at a different folder per run, without editing the
    /// `.trail` or writing a throwaway `.vars` file. The supplied value has to
    /// beat the declared default and reach the producer path, which is what
    /// decides how many rows there are.
    #[test]
    fn a_supplied_param_repoints_a_folders_loop() {
        let dir = temp_dir("param");
        let coll = dir.join("api.hurl");
        fs::write(&coll, "# Ping\nGET https://example.test/ping\nHTTP *\n").unwrap();

        // The batch this run is about, next to a decoy the default points at.
        let batch = dir.join("batch-07");
        fs::create_dir_all(batch.join("case-a")).unwrap();
        fs::create_dir_all(batch.join("case-b")).unwrap();
        fs::create_dir_all(dir.join("empty")).unwrap();

        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\nPARAM FOLDER CASES = \"./empty\"\n\
             FOR CASE IN FOLDERS \"{{CASES}}\"\n    REPORT CASE\n    REPORT REQUEST Ping\nEND\n",
        )
        .unwrap();

        let run_with = |params: ParamValues, out: &Path| {
            run(
                Some(coll.to_string_lossy().into_owned()),
                Vec::new(),
                report.to_string_lossy().into_owned(),
                vec![out.to_string_lossy().into_owned()],
                true, // dry-run: the loop still expands, no HTTP
                Vec::new(),
                None,
                params,
                Gates::default(),
                false,
                None,
                false,
            )
        };

        // The default is honoured when nothing is supplied: an empty folder,
        // so nothing to iterate.
        let default_out = dir.join("default.csv");
        assert_eq!(run_with(ParamValues::new(), &default_out), 0);
        let csv = fs::read_to_string(&default_out).unwrap();
        assert!(
            !csv.contains("case-a"),
            "the declared default should still point at ./empty:\n{csv}"
        );

        // …and is beaten by the value this run was given.
        let chosen_out = dir.join("chosen.csv");
        let mut params = ParamValues::new();
        params.insert("CASES".into(), batch.to_string_lossy().into_owned());
        assert_eq!(run_with(params, &chosen_out), 0);
        let csv = fs::read_to_string(&chosen_out).unwrap();
        assert!(
            csv.contains("case-a") && csv.contains("case-b"),
            "both cases from the supplied folder expected:\n{csv}"
        );

        fs::remove_dir_all(&dir).ok();
    }

    /// A `--param` the report doesn't declare is a caller whose command line
    /// has drifted from the script. Running anyway would produce a full report
    /// built from the default it believed it had replaced, so it stops.
    #[test]
    fn a_param_the_report_does_not_declare_is_refused() {
        let dir = temp_dir("badparam");
        let coll = dir.join("api.hurl");
        fs::write(&coll, "# Ping\nGET https://example.test/ping\nHTTP *\n").unwrap();
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\nPARAM FOLDER CASES = \"./empty\"\n\
             # columns: Ping.HttpStatus as Status\nREPORT REQUEST Ping\n",
        )
        .unwrap();
        let out = dir.join("out.csv");

        let mut params = ParamValues::new();
        params.insert("CASE_DIR".into(), "./whatever".into());
        let code = run(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            vec![out.to_string_lossy().into_owned()],
            true,
            Vec::new(),
            None,
            params,
            Gates::default(),
            false,
            None,
            false,
        );
        assert_eq!(code, 1, "an undeclared parameter is a setup error");
        assert!(!out.exists(), "nothing should be written for a refused run");

        fs::remove_dir_all(&dir).ok();
    }

    /// The point of a repeatable `-o` for an application embedding PaperBoy:
    /// one run of the requests yields a rendering to show a user *and* a
    /// structure to parse, instead of running the whole report twice and
    /// hoping the two runs agree.
    #[test]
    fn one_run_writes_every_requested_format() {
        let dir = temp_dir("multiout");
        let coll = dir.join("api.hurl");
        fs::write(&coll, "# Ping\nGET https://example.test/ping\nHTTP *\n").unwrap();
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\n# columns: Ping.HttpStatus as Status\n\
             REPORT REQUEST Ping\n",
        )
        .unwrap();

        let html = dir.join("out.html");
        let json = dir.join("out.json");
        let csv = dir.join("out.csv");
        let code = run(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            vec![
                html.to_string_lossy().into_owned(),
                json.to_string_lossy().into_owned(),
                csv.to_string_lossy().into_owned(),
            ],
            true, // dry-run: no HTTP
            Vec::new(),
            None,
            ParamValues::new(),
            Gates::default(),
            false,
            None,
            false,
        );
        assert_eq!(code, 0, "a multi-output dry run should succeed");

        // Each file exists and is actually in its own format, so the extension
        // picked the writer rather than one format being written three times.
        let html_text = fs::read_to_string(&html).unwrap();
        assert!(html_text.contains("<table"), "not HTML:\n{html_text}");
        let json_text = fs::read_to_string(&json).unwrap();
        assert!(
            serde_json::from_str::<serde_json::Value>(&json_text).is_ok(),
            "not JSON:\n{json_text}"
        );
        let csv_text = fs::read_to_string(&csv).unwrap();
        assert!(csv_text.starts_with("Status"), "not CSV:\n{csv_text}");

        fs::remove_dir_all(&dir).ok();
    }

    /// The `-o` combinations that cannot mean what they say, refused before a
    /// single request goes out — a typo in a format should not cost a whole
    /// run of live traffic to discover.
    #[test]
    fn impossible_output_combinations_are_refused_before_the_run() {
        let dir = temp_dir("badout");
        let coll = dir.join("api.hurl");
        fs::write(&coll, "# Ping\nGET https://example.test/ping\nHTTP *\n").unwrap();
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\n# columns: Ping.HttpStatus as Status\n\
             REPORT REQUEST Ping\n",
        )
        .unwrap();

        let go = |outs: Vec<String>| {
            run(
                Some(coll.to_string_lossy().into_owned()),
                Vec::new(),
                report.to_string_lossy().into_owned(),
                outs,
                true,
                Vec::new(),
                None,
                ParamValues::new(),
                Gates::default(),
                false,
                None,
                false,
            )
        };

        // There is only one stdout, and two formats down it would interleave
        // into neither of them.
        assert_eq!(go(vec!["-".into(), "-".into()]), 1, "two stdouts");

        // The same path twice means the second write destroys the first.
        let dup = dir.join("out.json").to_string_lossy().into_owned();
        assert_eq!(go(vec![dup.clone(), dup.clone()]), 1, "duplicate path");
        assert!(
            !dir.join("out.json").exists(),
            "a refused run writes nothing"
        );

        // A format PaperTrail can't write, alongside one it can: the good one
        // must not be written either, or a caller gets a partial answer from a
        // command line that was rejected.
        let good = dir.join("fine.csv");
        assert_eq!(
            go(vec![
                good.to_string_lossy().into_owned(),
                dir.join("out.docx").to_string_lossy().into_owned(),
            ]),
            1,
            "unsupported extension"
        );
        assert!(!good.exists(), "nothing is written for a refused run");

        fs::remove_dir_all(&dir).ok();
    }

    /// `-o -` mixed with files is the shape an integrator actually uses: pipe
    /// one format onward while keeping another on disk.
    #[test]
    fn stdout_and_a_file_can_be_asked_for_together() {
        let dir = temp_dir("mixedout");
        let coll = dir.join("api.hurl");
        fs::write(&coll, "# Ping\nGET https://example.test/ping\nHTTP *\n").unwrap();
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\n# columns: Ping.HttpStatus as Status\n\
             REPORT REQUEST Ping\n",
        )
        .unwrap();
        let json = dir.join("out.json");
        let code = run(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            vec!["-".into(), json.to_string_lossy().into_owned()],
            true,
            Vec::new(),
            None,
            ParamValues::new(),
            Gates::default(),
            false,
            None,
            false,
        );
        assert_eq!(code, 0);
        assert!(json.exists(), "the file output still lands");

        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn multi_env_loads_every_env_and_runs_the_envs_loop() {
        // Two `-e` files with distinct stems make a `FOR … IN ENVS` loop
        // resolvable headlessly: both environments load, are selectable by
        // stem, and the flow iterates once per environment.
        let dir = temp_dir("multienv");
        let coll = dir.join("api.hurl");
        fs::write(&coll, "# Ping\nGET https://example.test/ping\nHTTP *\n").unwrap();
        fs::write(dir.join("prod.vars"), "HOST=prod.test\n").unwrap();
        fs::write(dir.join("staging.vars"), "HOST=staging.test\n").unwrap();
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\nFOR TARGET IN ENVS \"prod\", \"staging\"\n    REPORT TARGET\n    REPORT REQUEST Ping\nEND\n",
        )
        .unwrap();
        let out = dir.join("out.csv");

        let code = run(
            Some(coll.to_string_lossy().into_owned()),
            vec![
                dir.join("prod.vars").to_string_lossy().into_owned(),
                dir.join("staging.vars").to_string_lossy().into_owned(),
            ],
            report.to_string_lossy().into_owned(),
            vec![out.to_string_lossy().into_owned()],
            true, // dry-run: no HTTP, but the ENVS loop still expands per env
            Vec::new(),
            None,
            ParamValues::new(),
            Gates::default(),
            false,
            None,
            false,
        );
        assert_eq!(code, 0, "a multi-env dry run should succeed");

        let csv = fs::read_to_string(&out).unwrap();
        // The ENVS loop iterated once per loaded environment (no "not loaded"
        // errors), so both env names appear in the reported TARGET column.
        assert!(csv.contains("prod"), "prod env row missing:\n{csv}");
        assert!(csv.contains("staging"), "staging env row missing:\n{csv}");

        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn duplicate_env_stem_is_rejected() {
        // Two `-e` files that share a stem are ambiguous for an ENVS clause, so
        // the second is a fatal setup error.
        let dir = temp_dir("dupenv");
        let coll = dir.join("api.hurl");
        fs::write(&coll, "# Ping\nGET https://example.test/ping\nHTTP *\n").unwrap();
        let a = dir.join("a");
        let b = dir.join("b");
        fs::create_dir_all(&a).unwrap();
        fs::create_dir_all(&b).unwrap();
        fs::write(a.join("prod.vars"), "HOST=a.test\n").unwrap();
        fs::write(b.join("prod.vars"), "HOST=b.test\n").unwrap();
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\nREPORT REQUEST Ping\n",
        )
        .unwrap();

        let code = run(
            Some(coll.to_string_lossy().into_owned()),
            vec![
                a.join("prod.vars").to_string_lossy().into_owned(),
                b.join("prod.vars").to_string_lossy().into_owned(),
            ],
            report.to_string_lossy().into_owned(),
            vec!["-".to_string()],
            true,
            Vec::new(),
            None,
            ParamValues::new(),
            Gates::default(),
            false,
            None,
            false,
        );
        assert_eq!(code, 1, "a duplicate env stem is a fatal setup error");

        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn missing_collection_is_a_setup_error() {
        let dir = temp_dir("nocoll");
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: missing.hurl\nREPORT REQUEST Ping\n",
        )
        .unwrap();

        let code = run(
            Some(dir.join("missing.hurl").to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            vec!["-".to_string()],
            true,
            Vec::new(),
            None,
            ParamValues::new(),
            Gates::default(),
            false,
            None,
            false,
        );
        assert_eq!(code, 1, "a missing collection is a fatal setup error");

        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn unsupported_output_extension_is_rejected() {
        let dir = temp_dir("badext");
        let coll = dir.join("api.hurl");
        fs::write(&coll, "# Ping\nGET https://example.test/ping\nHTTP *\n").unwrap();
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\nREPORT REQUEST Ping\n",
        )
        .unwrap();

        let code = run(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            vec![dir.join("out.docx").to_string_lossy().into_owned()],
            true,
            Vec::new(),
            None,
            ParamValues::new(),
            Gates::default(),
            false,
            None,
            false,
        );
        assert_eq!(code, 1, "an unsupported extension should fail");

        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn dry_run_writes_each_supported_output_format() {
        let dir = temp_dir("fmts");
        let coll = dir.join("api.hurl");
        fs::write(&coll, "# Ping\nGET https://example.test/ping\nHTTP *\n").unwrap();
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\n# columns: Ping.HttpStatus as Status\nREPORT REQUEST Ping\n",
        )
        .unwrap();

        for (ext, check) in [
            (
                "json",
                &(|b: &[u8]| b.starts_with(b"{")) as &dyn Fn(&[u8]) -> bool,
            ),
            (
                "html",
                &(|b: &[u8]| b.starts_with(b"<!DOCTYPE html>")) as &dyn Fn(&[u8]) -> bool,
            ),
            (
                "xlsx",
                &(|b: &[u8]| b.starts_with(b"PK")) as &dyn Fn(&[u8]) -> bool,
            ),
            (
                "pdf",
                &(|b: &[u8]| b.starts_with(b"%PDF-")) as &dyn Fn(&[u8]) -> bool,
            ),
        ] {
            let out = dir.join(format!("out.{ext}"));
            let code = run(
                Some(coll.to_string_lossy().into_owned()),
                Vec::new(),
                report.to_string_lossy().into_owned(),
                vec![out.to_string_lossy().into_owned()],
                true, // dry-run: no HTTP
                Vec::new(),
                None,
                ParamValues::new(),
                Gates::default(),
                false,
                None,
                false,
            );
            assert_eq!(code, 0, ".{ext} output should succeed");
            let bytes = fs::read(&out).unwrap();
            assert!(!bytes.is_empty(), ".{ext} is non-empty");
            assert!(check(&bytes), ".{ext} has the expected magic/shape");
        }

        fs::remove_dir_all(&dir).ok();
    }

    /// With neither `-c` nor `-e`, the report's own `# collection:` and
    /// `# environment:` headers are honoured, resolved relative to the report's
    /// folder — so a workspace report "just runs" with `paperboy -r report`.
    #[test]
    fn headers_supply_collection_and_environment_when_flags_omitted() {
        let dir = temp_dir("hdrres");
        // Put the report in a sub-folder to prove the header paths resolve
        // relative to the report, not the process CWD.
        let sub = dir.join("reports");
        fs::create_dir_all(&sub).unwrap();
        fs::write(
            dir.join("api.hurl"),
            "# Ping\nGET https://example.test/ping\nHTTP *\n",
        )
        .unwrap();
        fs::write(dir.join("prod.vars"), "HOST=prod.test\n").unwrap();
        let report = sub.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: ../api.hurl\n# environment: ../prod.vars\nREPORT HOST\nREPORT REQUEST Ping\n",
        )
        .unwrap();
        let out = dir.join("out.csv");

        let code = run(
            None,       // no -c → header's `# collection:` is used
            Vec::new(), // no -e → header's `# environment:` is used
            report.to_string_lossy().into_owned(),
            vec![out.to_string_lossy().into_owned()],
            true, // dry-run: no HTTP
            Vec::new(),
            None,
            ParamValues::new(),
            Gates::default(),
            false,
            None,
            false,
        );
        assert_eq!(code, 0, "header-resolved run should succeed");

        let csv = fs::read_to_string(&out).unwrap();
        // The environment loaded (HOST from prod.vars is in the projection).
        assert!(csv.contains("prod.test"), "env not applied:\n{csv}");

        fs::remove_dir_all(&dir).ok();
    }

    /// With no `-c` and no `# collection:` header there is nothing to run
    /// against — a clear, fatal setup error.
    #[test]
    fn missing_collection_and_no_header_is_a_setup_error() {
        let dir = temp_dir("nohdr");
        let report = dir.join("r.trail");
        fs::write(&report, "# name: r\nREPORT REQUEST Ping\n").unwrap();

        let code = run(
            None,
            Vec::new(),
            report.to_string_lossy().into_owned(),
            vec!["-".to_string()],
            true,
            Vec::new(),
            None,
            ParamValues::new(),
            Gates::default(),
            false,
            None,
            false,
        );
        assert_eq!(
            code, 1,
            "no collection flag and no header is a fatal setup error"
        );

        fs::remove_dir_all(&dir).ok();
    }

    // --- --progress-json --------------------------------------------------

    /// Collect the stream into lines, as a consumer reading `proc.stderr`
    /// would.
    fn capturing() -> (Progress, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
        let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let sink = std::sync::Arc::clone(&log);
        (
            Progress {
                finished: std::sync::atomic::AtomicBool::new(false),
                out: Some(Box::new(move |line: &str| {
                    sink.lock().unwrap().push(line.to_string())
                })),
            },
            log,
        )
    }

    fn col(header: &str) -> OutputColumn {
        OutputColumn {
            header: header.to_string(),
            sources: vec![header.to_string()],
            stats: Vec::new(),
            image: None,
            truth: None,
            detail: false,
        }
    }

    fn row(path: Vec<(usize, usize)>, cells: &[(&str, &str)]) -> ReportRow {
        ReportRow {
            cells: cells
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
            path,
            ..ReportRow::default()
        }
    }

    /// The transport's whole contract in one test: every event is a complete
    /// JSON object on a line of its own, ending in a newline, and every one of
    /// them carries the schema version — including the ones a consumer that
    /// attached late is the first to see.
    #[test]
    fn every_progress_event_is_one_versioned_json_object_per_line() {
        let (progress, log) = capturing();
        progress.plan("nightly", 2, &[col("Status")], &[col("Body")], false);
        progress.row_started(&[(0, 1)], &RowSlots::new(&[]));
        progress.row_completed(
            &row(vec![(0, 1)], &[("Status", "200")]),
            &[],
            &[col("Status")],
            "",
            &RowSlots::new(&[]),
        );
        progress.output_written("out.json", "json", None);
        progress.run_finished(&ReportResult::default(), 0, &[], None, None);

        let lines = log.lock().unwrap().clone();
        let events: Vec<String> = lines
            .iter()
            .map(|l| {
                assert!(l.ends_with('\n'), "each event is its own line: {l:?}");
                assert_eq!(l.matches('\n').count(), 1, "one line per event: {l:?}");
                let v: serde_json::Value = serde_json::from_str(l).expect("a line is one object");
                assert_eq!(v["schema"], serde_json::json!(PROGRESS_SCHEMA));
                v["event"].as_str().unwrap().to_string()
            })
            .collect();
        assert_eq!(
            events,
            [
                "plan",
                "row_started",
                "row_completed",
                "output_written",
                "run_finished"
            ]
        );
    }

    /// `path` is the join key, so it has to be the *same* key everywhere: the
    /// dotted flattening of the row's structural path, usable as a dictionary
    /// key without any normalisation on the consumer's side.
    #[test]
    fn a_rows_path_is_a_dotted_string_on_every_event() {
        assert_eq!(path_key(&[]), "");
        assert_eq!(path_key(&[(0, 3)]), "0.3");
        assert_eq!(path_key(&[(0, 3), (1, 2)]), "0.3.1.2");

        let (progress, log) = capturing();
        // Both events name the same row, so both must agree on its identity
        // *and* on the slot it occupies in the projected grid.
        let slots = RowSlots::new(&[
            row(vec![(0, 0)], &[]),
            row(vec![(0, 3), (1, 2)], &[]),
            row(vec![(9, 9)], &[]),
        ]);
        progress.row_started(&[(0, 3), (1, 2)], &slots);
        progress.row_completed(&row(vec![(0, 3), (1, 2)], &[]), &[], &[], "", &slots);
        for line in log.lock().unwrap().iter() {
            let v: serde_json::Value = serde_json::from_str(line).unwrap();
            assert_eq!(v["path"], serde_json::json!("0.3.1.2"), "{line}");
            assert_eq!(v["row_index"], serde_json::json!(1), "{line}");
        }
        // A row the projection never saw is reported as unplaced rather than
        // guessed at.
        assert_eq!(slots.index_of(&[(7, 7)]), None);
    }

    /// A row that failed has to be distinguishable from one that merely
    /// finished — the result-level error list says *that* something went wrong
    /// but not *which slot* to paint red.
    #[test]
    fn row_completed_carries_the_errors_that_row_raised() {
        let (progress, log) = capturing();
        progress.row_completed(
            &row(vec![(0, 0)], &[("Status", "500")]),
            &["Ping: connection refused".to_string()],
            &[col("Status")],
            "",
            &RowSlots::new(&[]),
        );
        let v: serde_json::Value = serde_json::from_str(&log.lock().unwrap()[0]).unwrap();
        assert_eq!(v["ok"], serde_json::json!(false));
        assert_eq!(v["errors"], serde_json::json!(["Ping: connection refused"]));
    }

    /// Progress must stay cheap. A `DETAIL` or `IMAGE` column is the author
    /// saying "this one is big", and the same bytes are already going to the
    /// report file — so they are named in `plan` as withheld and left out of
    /// every row, to be joined from the report by `path` at the end.
    #[test]
    fn detail_and_image_columns_are_withheld_from_the_stream() {
        let mut detail = col("Raw: Response");
        detail.detail = true;
        let mut picture = col("Shot");
        picture.image = Some(crate::report::flow::ImageSpec::default());
        let (streamed, withheld) = split_streamed_columns(vec![col("Status"), detail, picture]);
        assert_eq!(
            streamed
                .iter()
                .map(|c| c.header.as_str())
                .collect::<Vec<_>>(),
            ["Status"]
        );
        assert_eq!(
            withheld
                .iter()
                .map(|c| c.header.as_str())
                .collect::<Vec<_>>(),
            ["Raw: Response", "Shot"]
        );

        let (progress, log) = capturing();
        progress.plan("r", 1, &streamed, &withheld, false);
        let v: serde_json::Value = serde_json::from_str(&log.lock().unwrap()[0]).unwrap();
        assert_eq!(v["columns"], serde_json::json!(["Status"]));
        assert_eq!(
            v["withheld_columns"],
            serde_json::json!(["Raw: Response", "Shot"])
        );
    }

    /// The same protection for a column nobody flagged: a value big enough to
    /// be a response body is named rather than streamed, so a
    /// consumer knows to read that cell from the report instead of trusting a
    /// silently shortened one.
    #[test]
    fn an_oversized_cell_is_named_rather_than_streamed() {
        let big = "x".repeat(PROGRESS_MAX_CELL + 1);
        let (progress, log) = capturing();
        progress.row_completed(
            &row(vec![(0, 0)], &[("Status", "200"), ("Body", &big)]),
            &[],
            &[col("Status"), col("Body")],
            "",
            &RowSlots::new(&[]),
        );
        let v: serde_json::Value = serde_json::from_str(&log.lock().unwrap()[0]).unwrap();
        assert_eq!(v["cells"]["Status"], serde_json::json!("200"));
        assert!(
            v["cells"].get("Body").is_none(),
            "the giant cell is omitted"
        );
        assert_eq!(v["withheld"], serde_json::json!(["Body"]));
    }

    /// Nothing is emitted at all without the flag — the stream is opt-in, and a
    /// run that didn't ask for it must not find JSON on its stderr.
    #[test]
    fn without_the_flag_no_events_are_emitted() {
        let progress = Progress::new(false);
        assert!(progress.out.is_none());
        // Exercising the emitters must be a no-op rather than a panic.
        progress.plan("r", 1, &[col("Status")], &[], false);
        progress.row_started(&[(0, 0)], &RowSlots::new(&[]));
        progress.row_completed(
            &row(vec![(0, 0)], &[]),
            &[],
            &[col("Status")],
            "",
            &RowSlots::new(&[]),
        );
        progress.run_finished(&ReportResult::default(), 0, &[], None, None);
    }

    /// The flag is wired all the way through and changes nothing about the
    /// report itself: the same run, with the same output, and the same exit
    /// code.
    #[test]
    fn progress_json_does_not_disturb_the_report() {
        let dir = temp_dir("progress");
        let coll = dir.join("api.hurl");
        fs::write(&coll, "# Ping\nGET https://example.test/ping\nHTTP *\n").unwrap();
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\n# columns: Ping.HttpStatus as Status\nREPORT REQUEST Ping\n",
        )
        .unwrap();
        let out = dir.join("out.csv");

        let code = run(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            vec![out.to_string_lossy().into_owned()],
            true, // dry-run: no HTTP
            Vec::new(),
            None,
            ParamValues::new(),
            Gates::default(),
            true, // --progress-json
            None,
            false,
        );
        assert_eq!(code, 0);
        let csv = fs::read_to_string(&out).unwrap();
        assert_eq!(csv.lines().next(), Some("Status"), "header row");

        fs::remove_dir_all(&dir).ok();
    }

    /// Parse a captured stream into `(event name, object)` pairs.
    fn events(log: &std::sync::Arc<std::sync::Mutex<Vec<String>>>) -> Vec<serde_json::Value> {
        log.lock()
            .unwrap()
            .iter()
            .map(|l| serde_json::from_str(l).expect("every line is one JSON object"))
            .collect()
    }

    /// The load-bearing claim behind `row_index`: the slot a row is announced
    /// in is the row it occupies in the written report. Asserted against the
    /// real writer rather than against the ordering rule, because the rule is
    /// only worth anything if the two agree — and a `row_index` that quietly
    /// points at the wrong row is worse than none at all, since it looks like
    /// it works.
    #[test]
    fn a_streamed_rows_index_is_its_position_in_the_written_report() {
        let dir = temp_dir("slots");
        let coll = dir.join("api.hurl");
        fs::write(&coll, "# Ping\nGET https://example.test/ping\nHTTP *\n").unwrap();
        let report = dir.join("r.trail");
        // Nested loops, so the paths are two pairs deep and their order is a
        // real question rather than 0, 1, 2.
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\n# columns: X, Y\n\
             FOR X IN [\"a\", \"b\", \"c\"]\n    FOR Y IN [\"1\", \"2\"]\n        REPORT REQUEST Ping\n    END\nEND\n",
        )
        .unwrap();
        let out = dir.join("out.json");

        let (progress, log) = capturing();
        let code = run_with_progress(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            vec![out.to_string_lossy().into_owned()],
            true, // dry-run: the expansion is what the ordering claim is about
            Vec::new(),
            None,
            ParamValues::new(),
            Gates::default(),
            progress,
            Control::for_test(),
        );
        assert_eq!(code, 0);

        let written: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&out).unwrap()).unwrap();
        let rows = written["rows"].as_array().unwrap();
        assert_eq!(rows.len(), 6, "three by two");

        let streamed: Vec<serde_json::Value> = events(&log)
            .into_iter()
            .filter(|e| e["event"] == "row_completed")
            .collect();
        assert_eq!(streamed.len(), rows.len(), "one event per written row");
        // `plan` promised this many, before any of them existed.
        let plan = events(&log)
            .into_iter()
            .find(|e| e["event"] == "plan")
            .unwrap();
        assert_eq!(plan["total"], serde_json::json!(6));

        let mut seen: Vec<usize> = Vec::new();
        for ev in &streamed {
            let index = ev["row_index"].as_u64().expect("a projected row is placed") as usize;
            seen.push(index);
            let written_row = &rows[index];
            for key in ["X", "Y"] {
                assert_eq!(
                    ev["cells"][key], written_row[key],
                    "row {index} disagrees on {key}: streamed {ev}, written {written_row}"
                );
            }
        }
        seen.sort();
        assert_eq!(
            seen,
            (0..rows.len()).collect::<Vec<_>>(),
            "every slot filled once"
        );

        fs::remove_dir_all(&dir).ok();
    }

    /// A setup failure is the most likely thing a caller will hit — a mistyped
    /// `--param`, a folder that isn't there — and it used to leave the stream
    /// empty: exit 1, no events, and nothing to show anyone. `run_finished` is
    /// the terminal event unconditionally, so a consumer has one thing to wait
    /// for and one place to read the reason.
    #[test]
    fn a_setup_failure_still_ends_the_stream_with_run_finished() {
        let dir = temp_dir("setupfail");
        let coll = dir.join("api.hurl");
        fs::write(&coll, "# Ping\nGET https://example.test/ping\nHTTP *\n").unwrap();
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\nPARAM TEXT WHO = \"world\"\nREPORT REQUEST Ping\n",
        )
        .unwrap();
        let mut params = ParamValues::new();
        params.insert("WHOM".into(), "nobody".into());

        let (progress, log) = capturing();
        let code = run_with_progress(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            vec![dir.join("out.csv").to_string_lossy().into_owned()],
            true,
            Vec::new(),
            None,
            params,
            Gates::default(),
            progress,
            Control::for_test(),
        );
        assert_eq!(code, 1, "an undeclared parameter is a setup error");

        let events = events(&log);
        assert_eq!(
            events.len(),
            1,
            "nothing ran, so only the verdict: {events:?}"
        );
        let last = &events[0];
        assert_eq!(last["event"], "run_finished");
        assert_eq!(last["exit_code"], serde_json::json!(1));
        assert_eq!(last["ok"], serde_json::json!(false));
        // Zero rows is itself the fact that tells a setup failure from a run in
        // which every row failed.
        assert_eq!(last["rows"], serde_json::json!(0));
        assert!(
            last["errors"][0]
                .as_str()
                .unwrap()
                .contains("no parameter named 'WHOM'"),
            "the reason has to be *in* the stream: {last}"
        );

        fs::remove_dir_all(&dir).ok();
    }

    /// A validation error is the other common setup failure, and it carries
    /// more than one message: every diagnostic reaches the stream, not just the
    /// summary line the human mode ends on.
    #[test]
    fn a_validation_failure_puts_every_diagnostic_in_the_stream() {
        let dir = temp_dir("validfail");
        let coll = dir.join("api.hurl");
        fs::write(&coll, "# Ping\nGET https://example.test/ping\nHTTP *\n").unwrap();
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\nREPORT REQUEST Ghost\n",
        )
        .unwrap();

        let (progress, log) = capturing();
        let code = run_with_progress(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            vec![dir.join("out.csv").to_string_lossy().into_owned()],
            false, // a live run is what validation blocks
            Vec::new(),
            None,
            ParamValues::new(),
            Gates::default(),
            progress,
            Control::for_test(),
        );
        assert_eq!(code, 1);

        let events = events(&log);
        assert_eq!(events.len(), 1, "blocked before the plan: {events:?}");
        let errors = events[0]["errors"].as_array().unwrap();
        assert!(
            errors.iter().any(|e| e.as_str().unwrap().contains("Ghost")),
            "the diagnostic itself, not just the summary: {errors:?}"
        );
        assert!(
            errors
                .iter()
                .any(|e| e.as_str().unwrap().contains("validation errors")),
            "{errors:?}"
        );

        fs::remove_dir_all(&dir).ok();
    }

    // --- stopping a run ---------------------------------------------------

    /// A local server that flips `cancel` once it is about to answer request
    /// number `stop_after`, and holds every later request for `straggler_ms`.
    ///
    /// The switch is thrown *before* the response goes out, which is what makes
    /// the sequential case exact: the run cannot finish row `stop_after` — let
    /// alone claim the next one — until it has read a response the server only
    /// writes after stopping it.
    /// `row_delays[i]` holds back the response to row `ri` by that many
    /// milliseconds, which is how a test decides the order rows *finish* in
    /// under `PARALLEL` — the property the report is then expected not to
    /// inherit. Empty leaves every row answered as fast as it can be.
    fn stopping_server(
        cancel: std::sync::Arc<Cancel>,
        stop_after: usize,
        straggler_ms: u64,
        row_delays: Vec<u64>,
    ) -> u16 {
        use std::io::{Read, Write};
        use std::net::TcpListener;
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        let seen = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        std::thread::spawn(move || {
            // One thread per connection: under PARALLEL there is more than one
            // in flight at a time, and serialising them here would hide exactly
            // the case these tests are about.
            while let Ok((mut sock, _)) = listener.accept() {
                let (cancel, seen, row_delays) = (cancel.clone(), seen.clone(), row_delays.clone());
                std::thread::spawn(move || {
                    let mut buf = [0u8; 2048];
                    let read = sock.read(&mut buf).unwrap_or(0);
                    let req = String::from_utf8_lossy(&buf[..read]).into_owned();
                    let n = seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
                    if n >= stop_after {
                        cancel.stop();
                    }
                    // Which row asked is in the path (`GET /ping/r3`), so a
                    // delay can be pinned to a row rather than to arrival
                    // order — under PARALLEL the requests arrive together.
                    let row = req
                        .split("/ping/r")
                        .nth(1)
                        .and_then(|rest| rest.split_whitespace().next())
                        .and_then(|i| i.parse::<usize>().ok());
                    match row.and_then(|i| row_delays.get(i).copied()) {
                        Some(ms) => std::thread::sleep(std::time::Duration::from_millis(ms)),
                        None if n > stop_after && straggler_ms > 0 => {
                            std::thread::sleep(std::time::Duration::from_millis(straggler_ms))
                        }
                        None => {}
                    }
                    let body = "{\"ok\":true}";
                    let resp = format!(
                        "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                        body.len()
                    );
                    let _ = sock.write_all(resp.as_bytes());
                    let _ = sock.flush();
                });
            }
        });
        port
    }

    /// Write a collection and a report that loops `rows` times over one request
    /// against `port`, and return the two paths.
    fn stop_fixture(
        dir: &Path,
        port: u16,
        rows: usize,
        parallel: Option<usize>,
    ) -> (PathBuf, PathBuf) {
        let coll = dir.join("api.hurl");
        fs::write(
            &coll,
            format!("# Ping\nGET http://127.0.0.1:{port}/ping/{{{{X}}}}\nHTTP *\n"),
        )
        .unwrap();
        let items: Vec<String> = (0..rows).map(|i| format!("\"r{i}\"")).collect();
        let head = match parallel {
            Some(n) => format!("PARALLEL({n}) FOR"),
            None => "FOR".to_string(),
        };
        let report = dir.join("r.trail");
        fs::write(
            &report,
            format!(
                "# name: r\n# collection: api.hurl\n# columns: X, Ping.HttpStatus as Status\n\
                 {head} X IN [{}]\n    REPORT REQUEST Ping\nEND\n",
                items.join(", ")
            ),
        )
        .unwrap();
        (coll, report)
    }

    /// A report result scored `correct` right out of `correct + incorrect`,
    /// which is all [`Gate::measure`] reads.
    fn scored(correct: usize, incorrect: usize) -> ReportResult {
        let mut res = ReportResult::default();
        let verdicts = [
            (crate::report::model::Verdict::Correct, correct),
            (crate::report::model::Verdict::Incorrect, incorrect),
        ];
        for (verdict, n) in verdicts {
            for _ in 0..n {
                let r = res.rows.len();
                let mut row = crate::report::model::ReportRow::default();
                row.cells.insert(
                    crate::report::compare::CORRECT_COLUMN.to_string(),
                    verdict.as_str().to_string(),
                );
                res.rows.push(row);
                // The roll-up is read off the rows; the map only has to be
                // non-empty for the run to count as scored at all.
                res.verdicts.insert((r, "status".to_string()), verdict);
            }
        }
        res
    }

    /// The bug the gate was bought to prevent, in its purest form: 1999 of 2000
    /// is 99.95%, which *displays* as 100.0%. Rounding before the comparison
    /// let `--fail-under 100` — "nothing may fail" — wave a failure through.
    #[test]
    fn a_hundred_percent_gate_counts_rows_rather_than_rounding() {
        let g = Gate::measure(&scored(1999, 1), 100.0);
        assert!(!g.passed, "one row was wrong: {}", g.note);
        assert!(g.note.contains("99.95"), "and the note says so: {}", g.note);

        let clean = Gate::measure(&scored(2000, 0), 100.0);
        assert!(clean.passed, "{}", clean.note);
        assert!(clean.note.contains("100.0%"), "{}", clean.note);
    }

    /// The other half of the same fix: comparing unrounded means a 94.96% now
    /// fails a 95% gate, so the sentence must not round it to "95.0% — UNDER
    /// the required 95.0%", which is an unanswerable bug report.
    #[test]
    fn a_gate_never_prints_a_figure_that_contradicts_its_verdict() {
        let g = Gate::measure(&scored(2374, 126), 95.0);
        assert!(!g.passed, "94.96% is under 95%: {}", g.note);
        assert!(
            g.note.contains("94.96") && g.note.contains("UNDER"),
            "the printed figure must be visibly under the threshold: {}",
            g.note
        );

        // And a threshold with more precision than the display: 95.04% is over
        // 95.0% as shown, and under the threshold that was actually demanded.
        let fine = Gate::measure(&scored(9504, 496), 95.04);
        assert!(fine.passed, "{}", fine.note);
        let just_under = Gate::measure(&scored(9503, 497), 95.04);
        assert!(!just_under.passed, "{}", just_under.note);
        assert!(
            just_under.note.contains("95.03") && just_under.note.contains("95.04"),
            "both figures are printed at the precision that separates them: {}",
            just_under.note
        );
    }

    /// A run that scored exactly what was asked of it passes. `23 / 40` is
    /// 57.5% in arithmetic and `57.49999999999999` in `f64`, so comparing the
    /// computed percentage blocked a release for getting precisely the number
    /// it was told to get -- and said so in the only words it had: "57.500000%
    /// -- UNDER the required 57.500000%".
    #[test]
    fn a_run_that_exactly_meets_its_threshold_is_not_failed_by_the_last_bit() {
        let g = Gate::measure(&scored(23, 17), 57.5);
        assert!(g.passed, "23 of 40 is exactly 57.5%: {}", g.note);
        assert!(g.note.contains("at or above"), "{}", g.note);
        // The sentence is readable, not the six-decimal shape the contradiction
        // used to force.
        assert!(!g.note.contains("57.500000"), "{}", g.note);

        // The exactness has to cut both ways, or it is just a looser gate.
        let under = Gate::measure(&scored(22, 18), 57.5);
        assert!(!under.passed, "22 of 40 is 55%: {}", under.note);
    }

    /// The same question asked of every threshold shape there is: a tie must
    /// pass, and one row fewer must not. Each of these has a different
    /// floating-point accident behind it -- some decimals round up when they
    /// become a `f64` and some round down, so a cross-multiplication done in
    /// floats fails one direction or the other depending on the number typed.
    #[test]
    fn a_threshold_is_held_to_the_decimal_it_was_written_as() {
        // (threshold, rows scored, rows right for an exact tie)
        let cases = [
            (57.5, 40usize, 23usize),
            (2.6, 500, 13),
            (95.1, 1000, 951),
            (33.0, 300, 99),
            (0.1, 1000, 1),
            (8.2, 500, 41),
            (57.35, 2000, 1147),
            (100.0, 2000, 2000),
            (0.0, 10, 0),
        ];
        for (required, compared, tie) in cases {
            let g = Gate::measure(&scored(tie, compared - tie), required);
            assert!(
                g.passed,
                "{tie} of {compared} meets {required}%: {}",
                g.note
            );
            if tie > 0 {
                let g = Gate::measure(&scored(tie - 1, compared - tie + 1), required);
                assert!(
                    !g.passed,
                    "{} of {compared} does not meet {required}%: {}",
                    tie - 1,
                    g.note
                );
            }
        }
    }

    /// A report result in which `fixed` rows improved on the baseline,
    /// `regressed` rows got worse and `unchanged` landed where they were --
    /// which is all [`NetGain::measure`] reads, by way of `row_trend`.
    fn moved(fixed: usize, regressed: usize, unchanged: usize) -> ReportResult {
        use crate::report::model::Trend;
        let mut res = scored(fixed + unchanged, regressed);
        let runs = [
            (Trend::Fixed, fixed),
            (Trend::Regressed, regressed),
            (Trend::Unchanged, unchanged),
        ];
        let mut r = 0;
        for (trend, n) in runs {
            for _ in 0..n {
                res.trends.insert((r, "status".to_string()), trend);
                r += 1;
            }
        }
        res
    }

    /// The gate `--fail-under` cannot be. A suite sitting at 97% has three
    /// points of room above a 95% floor, and can spend them a row at a time
    /// without the floor ever noticing -- which is precisely how a suite ends
    /// up at 95%.
    #[test]
    fn a_movement_gate_catches_the_slide_an_accuracy_floor_sits_above() {
        let slipped = moved(0, 3, 97);
        assert!(
            Gate::measure(&slipped, 95.0).passed,
            "97% clears a 95% floor, three broken rows and all"
        );
        let n = NetGain::measure(&slipped, 0);
        assert!(!n.passed, "three rows went backwards: {}", n.note);
        assert!(
            n.note.contains("0 fixed") && n.note.contains("3 regressed"),
            "the note says what moved: {}",
            n.note
        );

        // Break-even passes: the threshold is "do not go backwards", not "get
        // better every time", which no suite can promise. Trading a fix for a
        // regression is deliberately allowed through at 0 -- a run that wants
        // to be told about churn asks for a net gain of 1.
        assert!(NetGain::measure(&moved(1, 1, 10), 0).passed);
        assert!(NetGain::measure(&moved(2, 1, 10), 0).passed);
        assert!(!NetGain::measure(&moved(1, 2, 10), 0).passed);
        assert!(!NetGain::measure(&moved(3, 3, 10), 1).passed);
    }

    /// The threshold is a number of rows, so it can also demand progress, or
    /// tolerate a little regression -- and each shape has to read as a sentence
    /// about a run rather than as a signed integer in the middle of one.
    #[test]
    fn a_movement_threshold_says_in_words_what_it_asked_for() {
        let demanding = NetGain::measure(&moved(2, 0, 10), 5);
        assert!(!demanding.passed, "{}", demanding.note);
        assert!(
            demanding.note.contains("net gain of 2") && demanding.note.contains("BELOW"),
            "{}",
            demanding.note
        );

        let tolerant = NetGain::measure(&moved(0, 2, 10), -2);
        assert!(tolerant.passed, "two net regressions were allowed for");
        assert!(
            tolerant.note.contains("a net loss of 2"),
            "{}",
            tolerant.note
        );

        let level = NetGain::measure(&moved(1, 1, 10), 0);
        assert!(level.note.contains("level"), "{}", level.note);
        assert!(level.note.contains("break-even"), "{}", level.note);
    }

    /// A gate measured on nothing is a broken run, not a quality miss -- the
    /// same rule the accuracy gate follows, and for the same reason: a
    /// comparison that never happened is not a comparison that went well.
    #[test]
    fn a_movement_gate_with_nothing_to_compare_is_not_a_pass() {
        let n = NetGain::measure(&scored(10, 0), 0);
        assert!(!n.passed);
        assert!(n.net.is_none(), "there is no figure, not a figure of zero");

        let stopped = NetGain::not_measured(0);
        assert!(!stopped.passed);
        assert!(stopped.net.is_none());
        assert!(stopped.note.contains("stopped"), "{}", stopped.note);
    }

    /// A run that was stopped is not given a verdict at all: the figure would
    /// be drawn from whichever rows happened to finish, and the two stop paths
    /// do not even agree about which those are.
    #[test]
    fn a_stopped_run_gets_no_gate_verdict() {
        let g = Gate::not_measured(95.0);
        assert!(!g.passed && g.actual.is_none());
        assert!(g.note.contains("stopped"), "{}", g.note);
    }

    /// Nothing scored is a broken run, not a quality miss — [`deliver`] turns
    /// this into exit 1 rather than exit 5.
    #[test]
    fn a_gate_with_nothing_scored_is_unmeasured_rather_than_failed() {
        let g = Gate::measure(&ReportResult::default(), 95.0);
        assert_eq!(g.actual, None);
        assert_eq!(g.compared, 0);
        assert!(!g.passed);
    }

    /// `--fail-under`, the reason it exists: the run was faultless — every
    /// request sent, every response read — and the answers were wrong. Nothing
    /// in the exit code said so before, so a post-deploy check could go green
    /// against a service that got every question wrong.
    #[test]
    fn a_run_below_the_required_accuracy_fails_the_gate() {
        let dir = temp_dir("under");
        let port = answering_server(200);
        let coll = dir.join("api.hurl");
        fs::write(
            &coll,
            format!("# Ping\nGET http://127.0.0.1:{port}/ping\nHTTP 200\n"),
        )
        .unwrap();
        let report = dir.join("r.trail");
        // The service answers 200; the report says it should answer 201.
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\n\
             REPORT REQUEST Ping WITH\n    status: status TRUTH \"201\"\nEND\n",
        )
        .unwrap();

        let (progress, log) = capturing();
        let code = run_with_progress(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            Vec::new(),
            false,
            Vec::new(),
            None,
            ParamValues::new(),
            Gates {
                fail_under: Some(95.0),
                ..Gates::default()
            },
            progress,
            Control::for_test(),
        );
        assert_eq!(code, EXIT_GATE_FAILED, "0% accuracy is under 95%");

        let finished: serde_json::Value = log
            .lock()
            .unwrap()
            .iter()
            .map(|l| serde_json::from_str::<serde_json::Value>(l).unwrap())
            .find(|e| e["event"] == "run_finished")
            .expect("the terminal event");
        assert_eq!(finished["exit_code"], serde_json::json!(EXIT_GATE_FAILED));
        let gate = &finished["gate"];
        assert_eq!(gate["required"], serde_json::json!(95.0));
        assert_eq!(gate["actual"], serde_json::json!(0.0));
        assert_eq!(gate["compared"], serde_json::json!(1));
        assert_eq!(gate["passed"], serde_json::json!(false));
        // The run itself was clean: the gate is the only thing that failed, and
        // a caller must be able to tell that from a broken API.
        assert!(
            finished["errors"].as_array().is_some_and(|e| e.is_empty()),
            "nothing went wrong with the run: {finished}"
        );

        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn a_run_that_meets_the_threshold_passes_and_says_so() {
        let dir = temp_dir("over");
        let port = answering_server(200);
        let coll = dir.join("api.hurl");
        fs::write(
            &coll,
            format!("# Ping\nGET http://127.0.0.1:{port}/ping\nHTTP 200\n"),
        )
        .unwrap();
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\n\
             REPORT REQUEST Ping WITH\n    status: status TRUTH \"200\"\nEND\n",
        )
        .unwrap();

        let (progress, log) = capturing();
        let code = run_with_progress(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            Vec::new(),
            false,
            Vec::new(),
            None,
            ParamValues::new(),
            Gates {
                fail_under: Some(95.0),
                ..Gates::default()
            },
            progress,
            Control::for_test(),
        );
        assert_eq!(code, 0, "100% clears 95%");

        let finished: serde_json::Value = log
            .lock()
            .unwrap()
            .iter()
            .map(|l| serde_json::from_str::<serde_json::Value>(l).unwrap())
            .find(|e| e["event"] == "run_finished")
            .expect("the terminal event");
        // Reported even when it passes: "the gate passed" and "there was no
        // gate" are different facts about a deploy.
        assert_eq!(finished["gate"]["passed"], serde_json::json!(true));
        assert_eq!(finished["gate"]["actual"], serde_json::json!(100.0));

        fs::remove_dir_all(&dir).ok();
    }

    /// The terminal event carries the run's own arithmetic, so a caller gating
    /// on quality does not have to parse the report it just wrote -- and reads
    /// the same figures the gate was decided on, rather than a second opinion
    /// that can drift from it.
    #[test]
    fn the_terminal_event_carries_the_runs_own_figures() {
        let dir = temp_dir("figures");
        let port = answering_server(200);
        let coll = dir.join("api.hurl");
        fs::write(
            &coll,
            format!("# Ping\nGET http://127.0.0.1:{port}/ping\nHTTP 200\n"),
        )
        .unwrap();
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\n\
             REPORT REQUEST Ping WITH\n    status: status TRUTH \"200\"\nEND\n",
        )
        .unwrap();

        let (progress, log) = capturing();
        let code = run_with_progress(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            Vec::new(),
            false,
            Vec::new(),
            None,
            ParamValues::new(),
            Gates::default(),
            progress,
            Control::for_test(),
        );
        assert_eq!(code, 0);

        let finished: serde_json::Value = log
            .lock()
            .unwrap()
            .iter()
            .map(|l| serde_json::from_str::<serde_json::Value>(l).unwrap())
            .find(|e| e["event"] == "run_finished")
            .expect("the terminal event");
        assert_eq!(finished["rows"], serde_json::json!(1));
        assert_eq!(finished["rows_ok"], serde_json::json!(1));
        assert_eq!(finished["rows_failed"], serde_json::json!(0));
        let scored = &finished["scored"];
        assert_eq!(scored["compared"], serde_json::json!(1));
        assert_eq!(scored["correct"], serde_json::json!(1));
        assert_eq!(scored["incorrect"], serde_json::json!(0));
        // A percentage, to match `gate.actual`: the same number said the same
        // way, so a consumer comparing the two cannot find them disagreeing.
        assert_eq!(scored["accuracy"], serde_json::json!(100.0));
        // Nothing to compare against, so nothing has moved -- said as null
        // rather than as four zeroes, which would claim the run held steady.
        assert_eq!(finished["movement"], serde_json::Value::Null);

        fs::remove_dir_all(&dir).ok();
    }

    /// The gate end to end: a run that broke a row its baseline had right exits
    /// 5, and the terminal event carries the verdict beside the counts it was
    /// drawn from. The run itself is faultless -- every request sent, every
    /// response read -- which is exactly the shape a caller must be able to
    /// tell from a broken API.
    #[test]
    fn a_run_that_went_backwards_fails_the_movement_gate() {
        let dir = temp_dir("regressed");
        let port = answering_server(200);
        let coll = dir.join("api.hurl");
        fs::write(
            &coll,
            format!("# Ping\nGET http://127.0.0.1:{port}/ping\nHTTP 200\n"),
        )
        .unwrap();
        // The snapshot answered 201, which is what the report asks for; this
        // run answers 200. One row, right last time and wrong now.
        fs::write(
            dir.join("prev.baseline"),
            serde_json::json!({
                "version": 2,
                "rows": [{"key": [], "cells": {"Ping.status": "201"}}],
            })
            .to_string(),
        )
        .unwrap();
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\n# baseline: prev.baseline\n\
             REPORT REQUEST Ping WITH\n    status: status TRUTH \"201\"\nEND\n",
        )
        .unwrap();

        let (progress, log) = capturing();
        let code = run_with_progress(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            Vec::new(),
            false,
            Vec::new(),
            None,
            ParamValues::new(),
            Gates {
                net_gain: Some(0),
                ..Gates::default()
            },
            progress,
            Control::for_test(),
        );
        assert_eq!(code, EXIT_GATE_FAILED, "a row went backwards");

        let finished: serde_json::Value = log
            .lock()
            .unwrap()
            .iter()
            .map(|l| serde_json::from_str::<serde_json::Value>(l).unwrap())
            .find(|e| e["event"] == "run_finished")
            .expect("the terminal event");
        let movement = &finished["movement"];
        assert_eq!(movement["regressed"], serde_json::json!(1));
        assert_eq!(movement["fixed"], serde_json::json!(0));
        assert_eq!(movement["net_gain"], serde_json::json!(-1));
        assert_eq!(movement["required_net_gain"], serde_json::json!(0));
        assert_eq!(movement["passed"], serde_json::json!(false));
        assert!(
            movement["note"]
                .as_str()
                .is_some_and(|n| n.contains("BELOW")),
            "the verdict is explained where it is reported: {finished}"
        );
        assert!(
            finished["errors"].as_array().is_some_and(|e| e.is_empty()),
            "nothing went wrong with the run itself: {finished}"
        );

        fs::remove_dir_all(&dir).ok();
    }

    /// A report that scores nothing is refused before anything is sent, for the
    /// same reason `--fail-under` is: the alternatives are a long run thrown
    /// away, or a gate that waves every deploy through while measuring nothing.
    #[test]
    fn a_movement_gate_is_refused_when_there_is_nothing_to_compare() {
        let dir = temp_dir("nogain");
        let port = answering_server(200);
        let coll = dir.join("api.hurl");
        fs::write(
            &coll,
            format!("# Ping\nGET http://127.0.0.1:{port}/ping\nHTTP 200\n"),
        )
        .unwrap();

        // Scored, but against no baseline: there is a right answer and nothing
        // to have moved from.
        let scored_only = dir.join("scored.trail");
        fs::write(
            &scored_only,
            "# name: r\n# collection: api.hurl\n\
             REPORT REQUEST Ping WITH\n    status: status TRUTH \"200\"\nEND\n",
        )
        .unwrap();
        // And the other half: no truth at all, so no row can be right or wrong
        // on either side.
        let unscored = dir.join("unscored.trail");
        fs::write(
            &unscored,
            "# name: r\n# collection: api.hurl\nREPORT REQUEST Ping\n",
        )
        .unwrap();

        for (path, expected) in [
            (&scored_only, "nothing to compare against"),
            (&unscored, "nothing to measure"),
        ] {
            let (progress, log) = capturing();
            let code = run_with_progress(
                Some(coll.to_string_lossy().into_owned()),
                Vec::new(),
                path.to_string_lossy().into_owned(),
                Vec::new(),
                false,
                Vec::new(),
                None,
                ParamValues::new(),
                Gates {
                    net_gain: Some(0),
                    ..Gates::default()
                },
                progress,
                Control::for_test(),
            );
            assert_eq!(code, 1, "refused rather than run");
            let text = log.lock().unwrap().join("\n");
            assert!(
                text.contains(expected) && text.contains("--require-net-gain"),
                "the refusal says which half is missing: {text}"
            );
        }

        fs::remove_dir_all(&dir).ok();
    }

    /// A gate needs something to measure. Refused up front rather than at the
    /// end, because the two alternatives are both traps: a long run thrown
    /// away, or — worse — a threshold that quietly passes every deploy because
    /// there was never anything to hold it to.
    #[test]
    fn a_gate_on_a_report_that_scores_nothing_is_refused() {
        let dir = temp_dir("nogate");
        let coll = dir.join("api.hurl");
        fs::write(&coll, "# Ping\nGET https://example.test/ping\nHTTP *\n").unwrap();
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\nREPORT REQUEST Ping\n",
        )
        .unwrap();

        let (progress, log) = capturing();
        let code = run_with_progress(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            Vec::new(),
            false,
            Vec::new(),
            None,
            ParamValues::new(),
            Gates {
                fail_under: Some(95.0),
                ..Gates::default()
            },
            progress,
            Control::for_test(),
        );
        assert_eq!(code, 1, "a gate with nothing to measure is an error");
        let text = log.lock().unwrap().join("\n");
        assert!(text.contains("TRUTH"), "and says what is missing: {text}");

        fs::remove_dir_all(&dir).ok();
    }

    /// A server that answers every request with `status` and a tiny body, for
    /// the tests about what a *failing* run does. One thread per connection,
    /// like `stopping_server`, and it lives as long as the process — a test
    /// binary that exits is the only teardown it needs.
    fn answering_server(status: u16) -> u16 {
        use std::io::{Read, Write};
        use std::net::TcpListener;
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        std::thread::spawn(move || {
            while let Ok((mut sock, _)) = listener.accept() {
                std::thread::spawn(move || {
                    let mut buf = [0u8; 2048];
                    let _ = sock.read(&mut buf);
                    let body = "{\"ok\":false}";
                    let resp = format!(
                        "HTTP/1.1 {status} Nope\r\nContent-Type: application/json\r\n\
                         Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
                        body.len()
                    );
                    let _ = sock.write_all(resp.as_bytes());
                    let _ = sock.flush();
                });
            }
        });
        port
    }

    /// A server that fails its first `bad` requests and answers 200 after —
    /// the shape a `[Options] retry` exists for, and the shape a cold start,
    /// a rolling deploy or a just-scaled instance really has.
    fn flaky_server(bad: usize) -> u16 {
        use std::io::{Read, Write};
        use std::net::TcpListener;
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        let seen = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        std::thread::spawn(move || {
            while let Ok((mut sock, _)) = listener.accept() {
                let seen = seen.clone();
                std::thread::spawn(move || {
                    let mut buf = [0u8; 2048];
                    let _ = sock.read(&mut buf);
                    let n = seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    let status = if n < bad { 503 } else { 200 };
                    let body = "{\"ok\":true}";
                    let resp = format!(
                        "HTTP/1.1 {status} S\r\nContent-Type: application/json\r\n\
                         Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
                        body.len()
                    );
                    let _ = sock.write_all(resp.as_bytes());
                    let _ = sock.flush();
                });
            }
        });
        port
    }

    /// The whole point of `[Options] retry`. Hurl hands back *every* attempt
    /// and marks the superseded ones; reading the first one meant a request
    /// that failed twice and then succeeded was reported as a failed run — so
    /// a retry, the one thing written to absorb a cold start, made a green
    /// deploy red.
    #[test]
    fn a_request_that_succeeds_on_retry_is_a_clean_run() {
        let dir = temp_dir("retry");
        let port = flaky_server(2);
        let coll = dir.join("api.hurl");
        fs::write(
            &coll,
            format!(
                "# Ping\nGET http://127.0.0.1:{port}/ping\n\
                 [Options]\nretry: 5\nretry-interval: 10\nHTTP 200\n"
            ),
        )
        .unwrap();
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\nREPORT REQUEST Ping\n",
        )
        .unwrap();

        let (progress, log) = capturing();
        let code = run_with_progress(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            Vec::new(),
            false,
            Vec::new(),
            None,
            ParamValues::new(),
            Gates::default(),
            progress,
            Control::for_test(),
        );
        assert_eq!(code, 0, "the third attempt answered 200");

        let events: Vec<serde_json::Value> = log
            .lock()
            .unwrap()
            .iter()
            .map(|l| serde_json::from_str(l).unwrap())
            .collect();
        let row = events
            .iter()
            .find(|e| e["event"] == "row_completed")
            .expect("a row event");
        assert_eq!(row["ok"], serde_json::json!(true), "{row}");
        assert!(
            row["errors"].as_array().is_some_and(|e| e.is_empty()),
            "no error survived the retry: {row}"
        );
        let finished = events
            .iter()
            .find(|e| e["event"] == "run_finished")
            .expect("the terminal event");
        assert!(
            finished["errors"].as_array().is_some_and(|e| e.is_empty()),
            "{finished}"
        );

        fs::remove_dir_all(&dir).ok();
    }

    /// A step that failed *above* a loop is a failure of every row inside it:
    /// the rows ran against a login that never happened. They used to stream
    /// `ok: true` — each row reported only the errors raised while it was the
    /// current row — so a dashboard watching the rows saw a clean run whose
    /// terminal event then said otherwise.
    #[test]
    fn rows_inherit_the_failure_of_the_step_above_them() {
        let dir = temp_dir("inherit");
        let bad = answering_server(500);
        let coll = dir.join("api.hurl");
        fs::write(
            &coll,
            format!(
                "# Setup\nGET http://127.0.0.1:{bad}/login\nHTTP 200\n\n\
                 # Ping\nGET http://127.0.0.1:{bad}/ping/{{{{X}}}}\nHTTP *\n"
            ),
        )
        .unwrap();
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\n\
             REPORT REQUEST Setup\n\
             FOR X IN [\"a\", \"b\"]\n    REPORT REQUEST Ping\nEND\n",
        )
        .unwrap();

        let (progress, log) = capturing();
        let code = run_with_progress(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            Vec::new(),
            false,
            Vec::new(),
            None,
            ParamValues::new(),
            Gates::default(),
            progress,
            Control::for_test(),
        );
        assert_eq!(code, 1, "the run failed");

        let events: Vec<serde_json::Value> = log
            .lock()
            .unwrap()
            .iter()
            .map(|l| serde_json::from_str(l).unwrap())
            .collect();
        let rows: Vec<&serde_json::Value> = events
            .iter()
            .filter(|e| e["event"] == "row_completed")
            .collect();
        assert!(!rows.is_empty(), "some row ran: {events:?}");
        for row in &rows {
            assert_eq!(
                row["ok"],
                serde_json::json!(false),
                "every row is downstream of the failed setup: {row}"
            );
            assert!(
                row["errors"].as_array().is_some_and(|e| !e.is_empty()),
                "and says which failure it inherited: {row}"
            );
        }
        // The run's own list still holds the failure exactly once: inheritance
        // widens the *attribution*, it does not duplicate the error.
        let finished = events
            .iter()
            .find(|e| e["event"] == "run_finished")
            .expect("the terminal event");
        assert_eq!(
            finished["errors"].as_array().map(Vec::len),
            Some(1),
            "one failure, reported once: {finished}"
        );

        fs::remove_dir_all(&dir).ok();
    }

    /// The gate, end to end: a deploy check whose request comes back 500 must
    /// fail the pipeline step. Before this, the reason lived only in the row's
    /// `.Error` cell — the process exited 0, the stream said `ok: true`, and a
    /// post-deploy smoke test went green against a broken service.
    #[test]
    fn a_report_whose_request_failed_exits_non_zero_and_says_which_row() {
        let dir = temp_dir("gate");
        let port = answering_server(500);
        let coll = dir.join("api.hurl");
        fs::write(
            &coll,
            format!("# Ping\nGET http://127.0.0.1:{port}/ping\nHTTP 200\n"),
        )
        .unwrap();
        let report = dir.join("r.trail");
        fs::write(
            &report,
            "# name: r\n# collection: api.hurl\nREPORT REQUEST Ping\n",
        )
        .unwrap();

        let (progress, log) = capturing();
        let code = run_with_progress(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            Vec::new(),
            false,
            Vec::new(),
            None,
            ParamValues::new(),
            Gates::default(),
            progress,
            Control::for_test(),
        );
        assert_eq!(code, 1, "a broken API fails the run");

        let events: Vec<serde_json::Value> = log
            .lock()
            .unwrap()
            .iter()
            .map(|l| serde_json::from_str(l).unwrap())
            .collect();
        let row = events
            .iter()
            .find(|e| e["event"] == "row_completed")
            .expect("a row event");
        assert_eq!(row["ok"], serde_json::json!(false), "the row is not clean");
        assert!(
            row["errors"].as_array().is_some_and(|e| !e.is_empty()),
            "and carries why: {row}"
        );
        let finished = events
            .iter()
            .find(|e| e["event"] == "run_finished")
            .expect("the terminal event");
        assert_eq!(finished["ok"], serde_json::json!(false));
        assert_eq!(finished["exit_code"], serde_json::json!(1));
        assert!(
            finished["errors"].as_array().is_some_and(|e| !e.is_empty()),
            "the stream says what broke: {finished}"
        );

        fs::remove_dir_all(&dir).ok();
    }

    /// The whole promise of a stop: the rows that finished are written, the
    /// report says it is short and by how much, and the exit code says the run
    /// was told to stop rather than that the API is broken.
    #[test]
    fn a_stopped_run_writes_the_rows_that_finished_and_says_it_is_partial() {
        let dir = temp_dir("stop");
        let control = Control::for_test();
        let port = stopping_server(control.switch(), 2, 0, Vec::new());
        let (coll, report) = stop_fixture(&dir, port, 6, None);
        let out = dir.join("out.json");

        let (progress, log) = capturing();
        let code = run_with_progress(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            vec![out.to_string_lossy().into_owned()],
            false,
            Vec::new(),
            None,
            ParamValues::new(),
            Gates::default(),
            progress,
            control,
        );
        assert_eq!(
            code, EXIT_INTERRUPTED,
            "\"I was told to stop\" has a code of its own"
        );

        let written: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&out).unwrap()).unwrap();
        assert_eq!(written["partial"], serde_json::json!(true));
        assert_eq!(written["rows_completed"], serde_json::json!(2));
        assert_eq!(written["rows_planned"], serde_json::json!(6));
        assert_eq!(
            written["rows"].as_array().unwrap().len(),
            2,
            "only the rows that really ran: {written}"
        );

        let events = events(&log);
        let stopping = events.iter().find(|e| e["event"] == "run_stopping");
        assert!(
            stopping.is_some(),
            "the stream says it is winding down: {events:?}"
        );
        let finished = events
            .iter()
            .find(|e| e["event"] == "run_finished")
            .expect("a terminal event, always");
        assert_eq!(finished["interrupted"], serde_json::json!(true));
        assert_eq!(finished["partial"], serde_json::json!(true));
        assert_eq!(finished["rows_completed"], serde_json::json!(2));
        assert_eq!(finished["rows_planned"], serde_json::json!(6));
        assert_eq!(finished["exit_code"], serde_json::json!(EXIT_INTERRUPTED));
        assert!(
            events.iter().any(|e| e["event"] == "output_written"),
            "and the output it announced was written before it: {events:?}"
        );

        fs::remove_dir_all(&dir).ok();
    }

    /// The grace period expiring is not an excuse to produce nothing: what the
    /// stream saw is written, marked partial, with the caveat that the rows
    /// still in flight — and `CLEANUP` — were left behind.
    #[test]
    fn a_run_given_up_on_still_writes_what_it_had() {
        let dir = temp_dir("abandon");
        // Zero grace: the first straggler is given up on immediately, which is
        // the same code path as a 30-second wait, minus the wait.
        let control = Control::for_test().with_grace(std::time::Duration::ZERO);
        let port = stopping_server(control.switch(), 1, 600, Vec::new());
        let (coll, report) = stop_fixture(&dir, port, 6, Some(2));
        let out = dir.join("out.json");

        let (progress, log) = capturing();
        let code = run_with_progress(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            vec![out.to_string_lossy().into_owned()],
            false,
            Vec::new(),
            None,
            ParamValues::new(),
            Gates::default(),
            progress,
            control,
        );
        assert_eq!(code, EXIT_INTERRUPTED);

        let written: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&out).unwrap()).unwrap();
        assert_eq!(written["partial"], serde_json::json!(true));
        assert_eq!(written["rows_planned"], serde_json::json!(6));
        assert!(
            written["rows"].as_array().unwrap().len() < 6,
            "the run was abandoned: {written}"
        );
        let events = events(&log);
        let finished = events
            .iter()
            .find(|e| e["event"] == "run_finished")
            .expect("still one terminal event");
        assert_eq!(finished["interrupted"], serde_json::json!(true));
        let warnings = finished["warnings"].as_array().unwrap();
        assert!(
            warnings
                .iter()
                .any(|w| w.as_str().unwrap_or_default().contains("CLEANUP")),
            "a report written over a run that never wound down has to say so: {warnings:?}"
        );
        assert_eq!(finished["exit_code"], serde_json::json!(EXIT_INTERRUPTED));

        fs::remove_dir_all(&dir).ok();
    }

    /// The two ways an abandoned run can lie about itself, both of them only
    /// on this path: rows in the order they *finished* rather than the order
    /// the report is defined to be in, and a row announced after the stream
    /// said it had ended.
    #[test]
    fn an_abandoned_parallel_report_is_still_in_report_order_and_ends_when_it_says_it_does() {
        let dir = temp_dir("abandon_order");
        let control = Control::for_test().with_grace(std::time::Duration::from_millis(250));
        // The rows are answered back-to-front, so a report that simply keeps
        // what the sink handed it comes out reversed. r0 is slow enough to
        // still be in flight when the grace period runs out — it is the
        // straggler whose late arrival must not reach the stream.
        let port = stopping_server(control.switch(), 1, 0, vec![700, 60, 40, 20]);
        let (coll, report) = stop_fixture(&dir, port, 4, Some(4));
        let out = dir.join("out.json");

        let (progress, log) = capturing();
        let code = run_with_progress(
            Some(coll.to_string_lossy().into_owned()),
            Vec::new(),
            report.to_string_lossy().into_owned(),
            vec![out.to_string_lossy().into_owned()],
            false,
            Vec::new(),
            None,
            ParamValues::new(),
            Gates::default(),
            progress,
            control,
        );
        assert_eq!(code, EXIT_INTERRUPTED);

        let written: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&out).unwrap()).unwrap();
        let xs: Vec<String> = written["rows"]
            .as_array()
            .unwrap()
            .iter()
            .map(|r| r["X"].as_str().unwrap_or_default().to_string())
            .collect();
        assert!(
            xs.len() > 1,
            "the ordering only means something with several rows: {written}"
        );
        let mut sorted = xs.clone();
        sorted.sort();
        assert_eq!(
            xs, sorted,
            "an abandoned report is still a report: the same rows in the same order a \
             sequential run would have written them"
        );

        let events = events(&log);
        assert_eq!(
            events.last().map(|e| e["event"].clone()),
            Some(serde_json::json!("run_finished")),
            "a straggler landing after the terminal event would break the one promise \
             the stream makes: {events:#?}"
        );
    }
}