rust-fs-core 0.3.2

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

use saphyr::{LoadableYamlNode, Yaml};
use std::path::{Path, PathBuf};

fn manifest_dir() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}

fn ci_yml() -> PathBuf {
    manifest_dir()
        .join(".github")
        .join("workflows")
        .join("ci.yml")
}

/// Read a file the guards depend on, or fail.
///
/// It panics rather than returning `None` on purpose. An
/// `if !path.exists() { return }` anywhere in this module would
/// reproduce the exact class of blindness the module exists to prevent:
/// an assertion that is present, runs, and cannot report the thing it
/// was written for. A missing workflow is a finding, not a skip.
fn read_or_panic(path: &Path) -> String {
    std::fs::read_to_string(path).unwrap_or_else(|e| {
        panic!(
            "cannot read {}: {e}. This guard must fail rather than skip: a \
             version of it that returned early here would be the same \
             blindness it exists to prevent.",
            path.display()
        )
    })
}

/// The command lines of a shell script, with comments removed.
///
/// ONE PLACE, because two callers used to disagree about what a
/// comment is. `runs_with_overflow_checks` stripped them and
/// `step_declares_the_handshake` read `step.run` raw, so a step could
/// be armed by a line that never executes:
///
///     run: |
///       # EXPECT_OVERFLOW_CHECKS=1 -- see ci_profile.rs
///       cargo test --locked --all-targets
///
/// The handshake half said yes on the comment, the command half found
/// the real run, both workflow assertions passed, and the process got
/// no `EXPECT_OVERFLOW_CHECKS` -- so the runtime probe returned without
/// asserting anything. Two readers of one text must not have two
/// grammars.
///
/// It is shell, not YAML: [`parse_workflow`] has already removed the
/// workflow's own comments, and what reaches here is the inside of a
/// `run:` block, where `#` is the shell's comment character.
///
/// # A LOGICAL LINE, NOT A PHYSICAL ONE
///
/// A line ending in an unescaped `\` continues onto the next: the shell
/// removes the backslash-newline pair and reads one command. Splitting
/// on physical lines made
///
///     cargo test --locked --all-targets && \
///     echo done
///
/// an `&&` list followed by ANOTHER command on the next line, which is
/// the swallowed shape, and the guard refused a correct gate. Measured:
/// `bash -e -c $'false && \\\necho done'` exits 1. The same split let
/// `cargo test --locked \` + `--release` count as a debug run.
///
/// A trailing `&&`, `||` or `|` continues the line as well; see the
/// comment at that branch.
///
/// Only an ODD run of trailing backslashes continues (`a\\` ends in an
/// escaped backslash), and a line whose text was cut at a comment never
/// does: the backslash is inside the comment. Both measured with
/// `bash -e -c`.
fn command_lines(script: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut pending = String::new();
    let mut continuing = false;
    for raw in script.lines() {
        // A continuation keeps its leading whitespace, which is what
        // separates its first word from the previous line's last one.
        let line = if continuing { raw } else { raw.trim_start() };
        let (text, continues) = match comment_start(line) {
            Some(at) => (&line[..at], false),
            None => match line.strip_suffix('\\') {
                Some(body) if body.chars().rev().take_while(|c| *c == '\\').count() % 2 == 0 => {
                    (body, true)
                }
                _ => (line, false),
            },
        };
        pending.push_str(text);
        // A LIST OPERATOR AT THE END OF A LINE CONTINUES IT TOO, with no
        // backslash: `a &&` / `a ||` / `a |` newline `b` is one list.
        // Reading the next line as a fresh command made
        //
        //     test -n "$CI" &&
        //     export EXPECT_OVERFLOW_CHECKS=1
        //
        // an unconditional export. The tokeniser decides, so a quoted
        // or escaped `&&` does not continue anything. The two are joined
        // with a space, which is all the newline was.
        let ends_in_a_list_operator = !continues
            && shell_commands(&pending)
                .last()
                .is_some_and(|(_, sep)| matches!(sep, Sep::And | Sep::Or | Sep::Pipe));
        if ends_in_a_list_operator {
            pending.push(' ');
        }
        continuing = continues || ends_in_a_list_operator;
        if continuing {
            continue;
        }
        let logical = pending.trim();
        if !logical.is_empty() {
            out.push(logical.to_string());
        }
        pending.clear();
    }
    let logical = pending.trim();
    if !logical.is_empty() {
        out.push(logical.to_string());
    }
    out
}

/// Where a shell comment begins on a line, if it does.
///
/// A `#` is the comment character only where a WORD begins: at the
/// start of the line, or after a character that ends a word. The rule
/// used to be `line.split(" #")`, which is that rule written for
/// exactly one such character, so a comment glued to a terminator
/// survived into the line and was read as part of it:
///
///     cargo test --locked --lib;# EXPECT_OVERFLOW_CHECKS=1 is set in CI
///
/// The handshake half found the variable in the comment, the command
/// half found a real debug run before it, and the step counted as
/// arming a probe the process would never receive.
///
/// THE ALPHABET IS [`shell_commands`]' OWN SEPARATOR SET, not a second
/// one invented here. That is the whole point: two readers of one text
/// must not have two grammars, which is why `command_lines` exists at
/// all. `|` and a tab are in the set and were not holes -- other
/// mechanisms already caught them -- and they are handled here because
/// the rule is "a word begins", not because either was measured
/// escaping.
///
/// A `#` inside quotes is data, and so is one inside a word:
/// `--features a#b` is one argument, and cutting at it would truncate
/// a real command and make the guard refuse a correct workflow.
fn comment_start(line: &str) -> Option<usize> {
    let mut quote: Option<char> = None;
    let mut at_word_start = true;
    for (index, c) in line.char_indices() {
        if let Some(q) = quote {
            if c == q {
                quote = None;
            }
            at_word_start = false;
            continue;
        }
        match c {
            '#' if at_word_start => return Some(index),
            '\'' | '"' => {
                quote = Some(c);
                at_word_start = false;
            }
            ';' | '&' | '|' | '(' | ')' => at_word_start = true,
            c if c.is_whitespace() => at_word_start = true,
            _ => at_word_start = false,
        }
    }
    None
}

/// Whether one tokenised command is a `set` that turns `errexit` off.
///
/// Actions runs a `run:` block as `bash -e`, so a failing command ends
/// the step. `set +e` withdraws that for everything after it, which
/// makes every later command in the block advisory -- including the one this
/// file exists to require. Recognised in all its spellings (`set +e`,
/// `set +ex`, `set +o errexit`) rather than as a fixed string.
///
/// IT TOKENISES WITH [`shell_commands`] RATHER THAN `split_whitespace`.
/// Whitespace is not what ends a word in a shell, so the option name
/// with the next command's punctuation glued to it -- `set +o
/// errexit;`, `set +o errexit&&` -- read as `errexit;`, which is not
/// `errexit`, and the withdrawal was invisible. Only the detached
/// `set +o errexit ;` was caught, which is the spelling nobody writes.
///
/// Sharing the tokeniser also settles the quoted case for free:
/// `echo "set +o errexit"` yields the words `["echo", ""]`, so a
/// printed withdrawal withdraws nothing.
///
/// # FROM WHERE IT RUNS, NOT FOR THE WHOLE SCRIPT
///
/// A `set +e` anywhere used to refuse every run in the block, including
/// one that had already run under `errexit` -- and a failure there has
/// already ended the step before the `set +e` is reached. Measured:
/// `bash -e -c $'false\nset +e'` exits 1. So [`debug_runs`] walks the
/// commands in order and withdraws only what follows.
fn set_disables_errexit(words: &[String]) -> bool {
    let mut words = words.iter().map(String::as_str);
    if words.next() != Some("set") {
        return false;
    }
    let mut expecting_option_name = false;
    for word in words {
        if expecting_option_name {
            if word == "errexit" {
                return true;
            }
            expecting_option_name = false;
            continue;
        }
        if word == "+o" {
            expecting_option_name = true;
            continue;
        }
        if let Some(flags) = word.strip_prefix('+') {
            if flags.contains('e') {
                return true;
            }
        }
    }
    false
}

/// What follows a command on its line, and therefore whether the shell
/// reads the command's exit status.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Sep {
    /// Nothing -- the command ends the line.
    End,
    /// `&&`: the chain fails if this command fails.
    And,
    /// `||`: the failure is caught and discarded.
    Or,
    /// `;`: under `bash -e` a failure still ends the step, because
    /// `-e` aborts before the next command runs. MEASURED, not
    /// reasoned: `bash -e -c 'false; echo REACHED'` prints nothing and
    /// exits 1.
    Semi,
    /// `|`: the line's status becomes the LAST command's. Actions'
    /// default `bash -e` does not set `pipefail`.
    Pipe,
    /// `&`: backgrounded, so nothing waits for it.
    Amp,
}

/// Index of the `)` that closes the `$( )` / `<( )` / `>( )` span whose
/// `(` is at `open`, or `None` if the span is never closed.
///
/// # WHY THIS IS NOT A PAREN COUNT
///
/// It was one, and it was wrong in BOTH directions, because deciding
/// where a span ends is itself shell parsing. Verdicts below taken from
/// `bash -e -c`, not from reading this file:
///
/// | line | bash | a bare paren count |
/// |---|---|---|
/// | `cat <(echo a\) ; false)` | exit 0 — swallowed | closes at `\)`, so the `false` reads as top-level: **a swallowed suite counted as a gate** |
/// | `cat <(echo "a)") ; false` | exit 1 — the `false` IS read | closes at the quoted `)`, then the stray `"` opens a quote that eats the rest: **a real gate refused** |
///
/// The first is the defect this file exists to prevent. The second is
/// the one this file's own history warns about — a guard that starts
/// refusing correct workflows — and it is why a `\)` special case would
/// not have been a fix.
///
/// The rules are the shell's, and the same ones the tokeniser below
/// already applies fifteen lines on: outside quotes a backslash escapes
/// the next character; inside `"` it still does; inside `'` there are no
/// escapes at all and a backslash is data. Parentheses inside any quote
/// are data.
fn end_of_substitution(chars: &[char], open: usize) -> Option<usize> {
    debug_assert_eq!(chars.get(open), Some(&'('), "open must index the `(`");
    let mut depth = 0usize;
    let mut quote: Option<char> = None;
    let mut j = open;
    while j < chars.len() {
        let c = chars[j];
        match quote {
            // No escapes inside `'`; only another `'` ends it.
            Some('\'') => {
                if c == '\'' {
                    quote = None;
                }
            }
            Some(q) => {
                if c == '\\' && j + 1 < chars.len() {
                    j += 2;
                    continue;
                }
                if c == q {
                    quote = None;
                }
            }
            None => {
                if c == '\\' && j + 1 < chars.len() {
                    j += 2;
                    continue;
                }
                // A NESTED SPAN'S PARENTHESES ARE ITS OWN. Quotes and
                // escapes were tracked and these two were not, so a `)`
                // inside a nested backtick span or a `${...}` closed the
                // OUTER substitution early. Both directions were
                // measured against `bash -e -c`:
                //
                //   echo $(echo `echo x)`) ; cargo test --lib
                //       bash reads the trailing status; the span closed
                //       at the `)` inside the backticks, the unmatched
                //       backtick then ate the rest of the line, and a
                //       real gate was DROPPED.
                //
                //   $(echo ${x:+)} ; cargo test --lib)
                //       bash swallows it; the span closed at the `)`
                //       inside `${...}`, so the `cargo test` read as
                //       top-level and a swallowed suite was COUNTED.
                //
                // Skipping the nested span is the same answer as for a
                // quote: what is inside it is not this scanner's
                // punctuation.
                if c == '`' {
                    match end_of_backticks(chars, j) {
                        Some(close) => {
                            j = close + 1;
                            continue;
                        }
                        None => return None,
                    }
                }
                if c == '$' && j + 1 < chars.len() && chars[j + 1] == '{' {
                    match end_of_braces(chars, j + 1) {
                        Some(close) => {
                            j = close + 1;
                            continue;
                        }
                        None => return None,
                    }
                }
                match c {
                    '\'' | '"' => quote = Some(c),
                    '(' => depth += 1,
                    ')' => {
                        // `depth` is at least 1 here because `open`
                        // indexes a `(`; subtracting without checking
                        // would panic in the debug profile the PR gate
                        // runs precisely so an overflow is visible.
                        depth = depth.saturating_sub(1);
                        if depth == 0 {
                            return Some(j);
                        }
                    }
                    _ => {}
                }
            }
        }
        j += 1;
    }
    None
}

/// Index of the `}` closing the `${...}` opened at `open`, which
/// indexes the `{`, or `None` if it is never closed.
///
/// Brace expansions nest — `${x:-${y}}` is legal — so this counts
/// braces the way [`end_of_substitution`] counts parentheses, and for
/// the same reason: a `}` belonging to an inner expansion is not the
/// outer one's close.
///
/// Quoting inside `${...}` is NOT tracked, and the limit is stated
/// rather than implied. The expansion's own grammar allows a quoted
/// word in the default value, so `${x:-"}"}` would close early here.
/// No workflow in this constellation writes one, and the effect is to
/// end the outer span early, which drops a gate rather than inventing
/// one — the direction this file declares as safe.
fn end_of_braces(chars: &[char], open: usize) -> Option<usize> {
    debug_assert_eq!(chars.get(open), Some(&'{'), "open must index the brace");
    let mut depth = 0usize;
    let mut j = open;
    while j < chars.len() {
        // A NESTED SPAN'S CONTENTS ARE DATA, WHICH IS THE SAME RULE ONE
        // LAYER DOWN. This counted every `{` and `}`, so a literal
        // brace inside a command substitution -- where it is an
        // ordinary argument character -- read as another expansion
        // level, the closing `}` never brought the depth back to zero,
        // this answered `None`, `shell_commands` treated the span as
        // unterminated and dropped the rest of the line, and an `&&`
        // chain that did NOT end the step looked as though it did:
        //
        //   cargo test --locked --lib && echo ${x:-$(echo {)} ; true
        //
        // bash exits 0 whether the suite passes or fails -- the
        // `; true` swallows it -- and the guard counted it as the gate.
        // Measured both ways with `bash -e -c`; and
        // `echo "${x:-$(echo {)}"` prints `{`, so the brace really is
        // data.
        //
        // `braces_no_nesting` passing was never evidence this was
        // right: it shows the depth counter does something, not that it
        // is correct on a brace that is not an expansion.
        if chars[j] == '$' && j + 1 < chars.len() && chars[j + 1] == '(' {
            match end_of_substitution(chars, j + 1) {
                Some(close) => {
                    j = close + 1;
                    continue;
                }
                None => return None,
            }
        }
        if chars[j] == '`' {
            match end_of_backticks(chars, j) {
                Some(close) => {
                    j = close + 1;
                    continue;
                }
                None => return None,
            }
        }
        // ONLY `${` OPENS A LEVEL, apart from the opening brace this
        // was called on. A bare `{` elsewhere is data.
        if chars[j] == '$' && j + 1 < chars.len() && chars[j + 1] == '{' {
            depth += 1;
            j += 2;
            continue;
        }
        match chars[j] {
            '\\' if j + 1 < chars.len() => {
                j += 1;
            }
            '{' if j == open => depth += 1,
            '}' => {
                depth = depth.saturating_sub(1);
                if depth == 0 {
                    return Some(j);
                }
            }
            _ => {}
        }
        j += 1;
    }
    None
}

/// Index of the backtick closing the span opened at `open`, or `None`.
///
/// Same blindness, same direction: inside backticks a `\` escapes the
/// next character, so `` `echo a\` ; false` `` is ONE substitution and
/// its status is swallowed — measured, `exit 0`. Stopping at the escaped
/// backtick resumed tokenising inside the span and read the `false` as a
/// top-level command, counting a suite whose failure nothing sees.
///
/// Quoting is deliberately NOT tracked here. Backtick spans nest quotes
/// and escapes in a way that needs its own grammar, no workflow in this
/// constellation writes one, and an untested branch in a guard is worth
/// less than a stated limit. The escape is handled because it is the
/// spelling that produces a FALSE PASS.
fn end_of_backticks(chars: &[char], open: usize) -> Option<usize> {
    debug_assert_eq!(chars.get(open), Some(&'`'), "open must index the backtick");
    let mut j = open + 1;
    while j < chars.len() {
        if chars[j] == '\\' && j + 1 < chars.len() {
            j += 2;
            continue;
        }
        if chars[j] == '`' {
            return Some(j);
        }
        j += 1;
    }
    None
}

/// One shell line split into the commands it invokes, each with the
/// separator that follows it, and with the contents of quoted spans
/// dropped.
///
/// It is not a shell. It knows four things: the separators above; that
/// whitespace divides words; that what sits inside `'` or `"` is DATA
/// rather than a word; and that an `&` right after `>` or `<` is part
/// of a redirection (`2>&1`) rather than a separator.
///
/// The quoting rule is the whole difference between running a command
/// and printing it:
///
///     cargo test --locked --lib      -> [["cargo", "test", ...]]
///     echo "cargo test --locked"     -> [["echo", ""]]
///
/// The characters are the same and the substring match that used to
/// stand here could not tell them apart.
///
/// OVER-STRICT IS THE SAFE DIRECTION, as everywhere else in this file:
/// a shape it fails to recognise makes the guard refuse a correct
/// workflow, loudly, with the command quoted. The other way round is a
/// gate that went blind and said nothing.
fn shell_commands(line: &str) -> Vec<(Vec<String>, Sep)> {
    scan_shell(line).commands
}

/// What [`scan_shell`] reads from one line.
struct ShellScan {
    /// The commands, as [`shell_commands`] returns them.
    commands: Vec<(Vec<String>, Sep)>,
    /// For each command, in order, the command substitutions in its
    /// words: `Some(inner text)` for a `$( )` or backtick span whose
    /// status can be the command's, `None` for any expansion that runs
    /// something whose status this file does not follow -- a process
    /// substitution, a `${...}` carrying a substitution, a substitution
    /// inside double quotes, or a span that never closes. An arithmetic
    /// `$(( ))` is not recorded: it is not a command substitution and
    /// does not change which one decides. See [`substitution_gates`].
    substitutions: Vec<Vec<Option<String>>>,
    /// Whether the line is PLAIN; see [`scan_shell`].
    plain: bool,
}

/// [`shell_commands`], and whether the line is PLAIN: no bare `(`/`)`,
/// no quote left open at its end, no span that never closes.
///
/// The commands alone cannot say whether one of them runs in a subshell
/// -- `(export X=1); cargo test` tokenises exactly like `export X=1;
/// cargo test` -- and that is the one fact an `export` needs before it
/// can be believed. See [`exports_the_handshake`]. The answer comes from
/// this tokeniser rather than from a second scan of the text, because
/// two readers of one line must not have two grammars.
fn scan_shell(line: &str) -> ShellScan {
    let chars: Vec<char> = line.chars().collect();
    let mut out: Vec<(Vec<String>, Sep)> = Vec::new();
    let mut substitutions: Vec<Vec<Option<String>>> = Vec::new();
    let mut spans: Vec<Option<String>> = Vec::new();
    let mut words: Vec<String> = Vec::new();
    let mut word = String::new();
    let mut started = false;
    let mut quote: Option<char> = None;
    let mut i = 0;
    let mut plain = true;

    macro_rules! end_word {
        () => {
            if started {
                words.push(std::mem::take(&mut word));
                started = false;
            }
        };
    }

    while i < chars.len() {
        let c = chars[i];
        if let Some(q) = quote {
            // Inside a quoted span every character is data, including a
            // separator: `echo "a && cargo test"` is one command.
            //
            // A BACKSLASH INSIDE `"` ESCAPES THE NEXT CHARACTER, and
            // without this the span ended at the first `\"`:
            // `echo "a \" && cargo test"` split where the shell does
            // not, and the second half read as a command being run. In
            // `'` there are no escapes at all -- a backslash is data --
            // which is why this is conditional on the quote character.
            if q == '"' && c == '\\' && i + 1 < chars.len() {
                i += 2;
                continue;
            }
            // A substitution inside `"` still runs, and its status can
            // be the command's (`x="$(false)"` exits 1). It is recorded
            // as one this file does not follow, which is enough to stop
            // an EARLIER substitution being taken for the last one.
            //
            // `$((` IS ARITHMETIC, NOT A SUBSTITUTION, quoted as it is
            // bare: `x=$(false) y="$((1+1))"` exits 1 (Greptile on
            // rust-partitions#112). A substitution inside the arithmetic
            // is still one, and is met on its own `$(` a few characters on.
            if q == '"'
                && (c == '`'
                    || (c == '$'
                        && chars.get(i + 1) == Some(&'(')
                        && chars.get(i + 2) != Some(&'(')))
            {
                spans.push(None);
            }
            if c == q {
                quote = None;
            }
            i += 1;
            continue;
        }
        // A COMMAND SUBSTITUTION SWALLOWS ITS COMMAND'S STATUS, so what
        // is inside one is data exactly as a quoted span is.
        // `$(` and `)` used to fall into the separator arm below and
        // become `Sep::Semi`, so `echo $(cargo test --locked --lib)`
        // parsed as three commands with the inner one looking
        // status-read. Measured: `bash -e -c 'echo $(false); echo R'`
        // exits 0 and prints R -- only `echo`'s status is read.
        //
        // A BARE `( … )` SUBSHELL IS NOT THIS. Its status IS read, so it
        // keeps falling through to the separator arm.
        // `<( … )` AND `>( … )` ARE THE SAME SWALLOWING. A process
        // substitution hands the command a file name to read, and the
        // command's own status is all the line reports. Measured:
        //
        //   bash -e -c 'cat <(false)'          exit 0
        //   bash -e -c 'cat <(false); echo R'  exit 0, R printed
        //
        // Only `$(` was recognised, so `cat <(cargo test --locked
        // --all-targets)` split at the `(` into a `cat <` command and a
        // `cargo test` one that looked status-read -- and the guard
        // counted a suite whose failure nothing could see.
        //
        // FINDING THE END OF THE SPAN IS ITSELF SHELL PARSING, and the
        // first version of this counted bare parentheses. See
        // [`end_of_substitution`]: a `\)` or a `")"` inside the span is
        // data, and taking either for the close resumed tokenising in
        // the middle of a span the shell had not left.
        if matches!(c, '$' | '<' | '>') && i + 1 < chars.len() && chars[i + 1] == '(' {
            started = true;
            i = match end_of_substitution(&chars, i + 1) {
                Some(close) => {
                    let inner: String = chars[i + 2..close].iter().collect();
                    // Only `$( )` hands its status on. `<( )`/`>( )` run
                    // something whose status nothing reads (`x=<(false)`
                    // exits 0), and `$(( ))` is arithmetic, which is not
                    // a command substitution at all and leaves the last
                    // real one deciding (`x=$(false) y=$((1+1))` exits 1).
                    if c != '$' {
                        spans.push(None);
                    } else if !inner.starts_with('(') {
                        spans.push(Some(inner));
                    } else if runs_a_substitution(&inner) {
                        // Arithmetic that runs a substitution: that one's
                        // status is the command's
                        // (`x=$(false) y=$(( $(true; echo 1) + 1 ))` exits
                        // 0), and it is not followed (Greptile on
                        // rust-img-vmdk#102).
                        spans.push(None);
                    }
                    close + 1
                }
                // Unterminated: the shell would not accept this line at
                // all, and there is no command after it to read.
                None => {
                    spans.push(None);
                    plain = false;
                    chars.len()
                }
            };
            continue;
        }
        if c == '`' {
            started = true;
            i = match end_of_backticks(&chars, i) {
                Some(close) => {
                    spans.push(Some(chars[i + 1..close].iter().collect()));
                    close + 1
                }
                None => {
                    spans.push(None);
                    plain = false;
                    chars.len()
                }
            };
            continue;
        }
        // A `${...}` EXPANSION IS DATA HERE TOO, and this site was
        // missed when the same rule went into `end_of_substitution`: a
        // fix applied one function away and not applied here. `$` and
        // `{` were ordinary word characters, so the `)` in
        //
        //   cargo test --locked --lib && echo ${x:+)}
        //
        // fell into the separator arm below and split the line. The
        // `&&` chain then no longer ENDED the step, which is this
        // file's rule for whether an `&&` list's failure is read, so
        // the suite's failure read as swallowed and a real gate was
        // dropped. Measured: `bash -e -c 'x=1; false && echo ${x:+)}'`
        // exits 1 and the `true` spelling exits 0, so the status is
        // read.
        if c == '$' && i + 1 < chars.len() && chars[i + 1] == '{' {
            started = true;
            i = match end_of_braces(&chars, i + 1) {
                Some(close) => {
                    // A plain `${z}` runs nothing and leaves the status
                    // alone (`x=$(false) y=${z}` exits 1); one carrying a
                    // substitution runs it, and this file does not follow
                    // it (`x=$(false) y=${z:-$(true)}` exits 0).
                    let text: String = chars[i..=close].iter().collect();
                    if runs_a_substitution(&text[2..]) {
                        spans.push(None);
                    }
                    close + 1
                }
                None => {
                    spans.push(None);
                    plain = false;
                    chars.len()
                }
            };
            continue;
        }
        match c {
            '\\' if i + 1 < chars.len() => {
                // Outside quotes a backslash escapes the next character,
                // so `echo a\&\& b` is one command, not two.
                word.push(chars[i + 1]);
                started = true;
                i += 2;
            }
            '\'' | '"' => {
                quote = Some(c);
                started = true;
                i += 1;
            }
            '&' | '|' | ';' | '(' | ')' => {
                if matches!(c, '(' | ')') {
                    plain = false;
                }
                // `2>&1` and `>&2`: an `&` bound to a redirection is
                // part of the word, and the command's status is still
                // read.
                if c == '&' && started && (word.ends_with('>') || word.ends_with('<')) {
                    word.push(c);
                    i += 1;
                    continue;
                }
                let doubled = i + 1 < chars.len() && chars[i + 1] == c;
                let sep = match (c, doubled) {
                    ('&', true) => Sep::And,
                    ('&', false) => Sep::Amp,
                    ('|', true) => Sep::Or,
                    ('|', false) => Sep::Pipe,
                    _ => Sep::Semi,
                };
                end_word!();
                if !words.is_empty() {
                    out.push((std::mem::take(&mut words), sep));
                    substitutions.push(std::mem::take(&mut spans));
                }
                i += if doubled && c != ';' { 2 } else { 1 };
            }
            c if c.is_whitespace() => {
                end_word!();
                i += 1;
            }
            _ => {
                word.push(c);
                started = true;
                i += 1;
            }
        }
    }
    if started {
        words.push(word);
    }
    if !words.is_empty() {
        out.push((words, Sep::End));
        substitutions.push(spans);
    }
    if quote.is_some() {
        plain = false;
    }
    ShellScan {
        commands: out,
        substitutions,
        plain,
    }
}

/// The arguments of a `cargo test` invocation on this line, or `None`
/// if the line does not invoke one.
///
/// The scan used to ask `command.contains("cargo test")`, and a line
/// that only PRINTS the command satisfied it:
///
///     echo "EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib"
///
/// That one line met both of this file's workflow assertions -- the
/// debug run and the handshake -- with no debug run behind either. A
/// check whose result does not depend on the thing it exists to detect
/// is this constellation's named defect, found inside a guard written
/// to prevent it.
///
/// Leading `NAME=value` assignments and an `env` prefix are stepped
/// over, because `EXPECT_OVERFLOW_CHECKS=1 cargo test …` is exactly the
/// spelling this guard is looking for; so is a `+toolchain` selector
/// between `cargo` and its subcommand. The one wrapper recognised is this
/// repository's `scripts/tier.sh ... -- cargo test ...`: it preserves the
/// command's status and is behavior-tested by `tests/output_budget.rs`.
/// Arbitrary wrappers such as `sudo` and `xargs` remain unrecognised, which
/// is the strict direction.
fn cargo_test_arguments(words: &[String]) -> Option<Vec<&str>> {
    let words = budgeted_tier_payload(words).unwrap_or(words);
    let mut words = words
        .iter()
        .map(String::as_str)
        .skip_while(|w| *w == "env" || (!w.starts_with('-') && w.contains('=')));
    let program = words.next()?;
    if program != "cargo" && !program.ends_with("/cargo") {
        return None;
    }
    let mut rest = words.skip_while(|w| w.starts_with('+'));
    if rest.next()? != "test" {
        return None;
    }
    // A REDIRECTION IS NOT AN ARGUMENT. `2>&1` would otherwise read as
    // a bare test-name filter and disqualify a run that is fine, and a
    // separate `>` takes the following word with it.
    let mut arguments = Vec::new();
    let mut argument_is_a_redirection_target = false;
    for word in rest {
        if argument_is_a_redirection_target {
            argument_is_a_redirection_target = false;
            continue;
        }
        if word.contains('>') || word.contains('<') {
            argument_is_a_redirection_target = word.ends_with('>') || word.ends_with('<');
            continue;
        }
        arguments.push(word);
    }
    Some(arguments)
}

/// Return the command after this repository's checked output-budget adapter.
///
/// The adapter's interface has a literal `--`, so this does not search an
/// arbitrary command for the words `cargo test`. It accepts only `tier.sh`
/// under a `scripts/` path, optionally launched through Bash, after ordinary
/// environment assignments. That keeps the workflow guard coupled to the
/// behavior-tested wrapper rather than teaching it to trust every script.
fn budgeted_tier_payload(words: &[String]) -> Option<&[String]> {
    let mut at = 0;
    while words
        .get(at)
        .is_some_and(|word| word == "env" || (!word.starts_with('-') && word.contains('=')))
    {
        at += 1;
    }
    if words
        .get(at)
        .is_some_and(|word| word == "bash" || word.rsplit('/').next() == Some("bash"))
    {
        at += 1;
    }
    let adapter = words.get(at)?;
    if adapter.rsplit('/').next() != Some("tier.sh")
        || !adapter.split('/').any(|part| part == "scripts")
    {
        return None;
    }
    let delimiter = words[at + 1..].iter().position(|word| word == "--")? + at + 1;
    Some(&words[delimiter + 1..])
}

#[test]
fn the_checked_tier_wrapper_still_exposes_the_gating_cargo_test() {
    let wrapped = shell_commands(
        "bash scripts/tier.sh 'test (debug)' debug 750 50000 -- cargo test --locked --all-targets",
    );
    assert_eq!(wrapped.len(), 1);
    assert_eq!(
        cargo_test_arguments(&wrapped[0].0),
        Some(vec!["--locked", "--all-targets"])
    );

    let arbitrary = shell_commands(
        "bash scripts/not-the-checked-wrapper.sh -- cargo test --locked --all-targets",
    );
    assert_eq!(cargo_test_arguments(&arbitrary[0].0), None);
}

/// Cargo options that take their value as the NEXT argument.
///
/// Needed only to tell an option's value from a bare test-name filter:
/// `--features qemu-validation` is not a filter and
/// `cargo test --locked qemu` is.
const OPTIONS_TAKING_A_VALUE: [&str; 18] = [
    "-p",
    "--package",
    "--exclude",
    "-F",
    "--features",
    "--target",
    "--target-dir",
    "--manifest-path",
    "--profile",
    "--test",
    "--bin",
    "--example",
    "--bench",
    "-j",
    "--jobs",
    "--message-format",
    "--color",
    "--config",
];

/// Whether `cargo test`'s own `arguments` select the release profile by
/// its short flag (#120).
///
/// `cargo test -r` is `cargo test --release`, and a line scan for the
/// string `--release` does not see it. Nor is it one spelling: clap merges
/// short flags, so `-qr` and `-rq` carry it as well, anywhere before `--`.
/// A cluster ends at a short option that takes a value -- `-p`, `-j`, `-F`
/// or `-Z` -- whose value is the rest of the word or, when the word ends
/// there, the next one: `-j4 -r` is release, `-pr` names a package `r`.
/// Everything after `--` belongs to the test harness, where `-r` is not
/// cargo's.
fn selects_release_by_short_flag(arguments: &[&str]) -> bool {
    let mut next_is_a_value = false;
    for argument in arguments {
        if std::mem::take(&mut next_is_a_value) {
            continue;
        }
        if *argument == "--" {
            return false;
        }
        if argument.starts_with("--") {
            next_is_a_value = !argument.contains('=') && OPTIONS_TAKING_A_VALUE.contains(argument);
            continue;
        }
        let Some(cluster) = argument.strip_prefix('-') else {
            continue;
        };
        for (at, flag) in cluster.char_indices() {
            match flag {
                'r' => return true,
                'p' | 'j' | 'F' | 'Z' => {
                    next_is_a_value = at + 1 == cluster.len();
                    break;
                }
                _ => {}
            }
        }
    }
    false
}

/// Test-harness options that take their value as the NEXT argument,
/// so that `-- --test-threads 1` is not read as a filter named `1`.
const HARNESS_OPTIONS_TAKING_A_VALUE: [&str; 6] = [
    "--test-threads",
    "--color",
    "--format",
    "--logfile",
    "--shuffle-seed",
    "-Z",
];

/// Whether these arguments select something OTHER than the crate's
/// library unit tests, where the overflow probe lives.
///
/// `--test <name>` builds one integration target and no library unit
/// tests. Several repositories here run a cross-validation suite that
/// way, in its own job, beside the real one.
///
/// This used to be `command.contains("--test ")`, which is one of that
/// option's two spellings, and which said nothing at all about `--doc`,
/// `--no-run`, `--bins`, or a bare filter. So four different one-line
/// edits each left the guard green with the probe unbuilt or unrun --
/// `--no-run` most starkly, since it compiles and executes nothing.
///
/// THE ANSWER IS TO COMPARE THE ARGUMENTS, NOT TO WIDEN THE SUBSTRING.
/// The trailing space in the old match was doing real work: `--tests`
/// DOES build the library unit tests and contains `--test`, so dropping
/// the space would have excluded a run that genuinely satisfies this
/// guard. Whole arguments answer both spellings and the `--tests` near
/// miss at once, with no space left load-bearing.
///
/// # AND AFTER `--`, THE HARNESS'S OWN SELECTION
///
/// Everything after a bare `--` belongs to the test harness, not to
/// cargo -- `-- --test-threads=1` selects no target. The walk used to
/// STOP there, and its comment admitted a filter passed that way would
/// still narrow the run. It does, to nothing:
/// `cargo test --locked --lib -- nonexistent_filter` builds the library,
/// runs zero tests, exits 0, and counted as the required debug run.
///
/// So the harness arguments are walked too, by the same rule as cargo's:
/// a bare word is a filter unless it is the value of an option that
/// takes one ([`HARNESS_OPTIONS_TAKING_A_VALUE`]). `--ignored` (only
/// `#[ignore]` tests), `--list` (none) and `--skip` (whatever matches
/// its word, the probe included) narrow it without a filter, and a
/// second `--` makes every word after it a filter. Unrecognised options
/// such as `--nocapture` are accepted: none of them selects tests.
fn omits_the_library_unit_tests(arguments: &[&str]) -> bool {
    let mut harness = arguments.iter().skip_while(|a| **a != "--").skip(1);
    let mut expecting_a_value = false;
    while let Some(argument) = harness.next() {
        if expecting_a_value {
            expecting_a_value = false;
            continue;
        }
        if *argument == "--" {
            if harness.next().is_some() {
                return true;
            }
            break;
        }
        if ["--ignored", "--list", "--skip"].contains(argument) || argument.starts_with("--skip=") {
            return true;
        }
        if HARNESS_OPTIONS_TAKING_A_VALUE.contains(argument) {
            expecting_a_value = true;
            continue;
        }
        if !argument.starts_with('-') {
            return true;
        }
    }

    let cargo_arguments = arguments.iter().take_while(|a| **a != "--");
    let mut expecting_a_value = false;
    for argument in cargo_arguments {
        if expecting_a_value {
            expecting_a_value = false;
            continue;
        }
        if OPTIONS_TAKING_A_VALUE.contains(argument) {
            // `--test` and friends disqualify whether or not the name
            // is attached, so answer before consuming the value.
            expecting_a_value = true;
        }
        let selects_elsewhere = [
            "--test",
            "--doc",
            "--no-run",
            "--bin",
            "--example",
            "--bench",
        ]
        .iter()
        .any(|o| *argument == *o || argument.starts_with(&format!("{o}=")))
            || ["--bins", "--examples", "--benches"].contains(argument);
        if selects_elsewhere {
            return true;
        }
        // A bare word is a test-name filter, which runs only the tests
        // matching it -- the probe among the ones it may exclude.
        if !argument.starts_with('-') {
            return true;
        }
    }
    false
}

/// Whether the shell reads this command's exit status.
///
/// Nothing here used to look at status handling at all, so
/// `cargo test --locked --all-targets || true` was matched, counted as
/// gating, and gated nothing: the job goes green with the probe
/// failing. A pipe and a trailing `&` are the same edit in other
/// spellings.
///
/// This file already enumerates two levels of the same defect -- a
/// step's `if:` and `continue-on-error:`, and a job's. Suppression
/// inside the command is the third, and it was not on the list.
///
/// WHICH SEPARATORS DISCARD A STATUS IS MEASURED, NOT REASONED.
/// Actions runs a `run:` block as `bash -e` with no `pipefail`, and
/// under that shell:
///
/// ```text
/// bash -e -c 'false; echo REACHED'  prints nothing, exit 1  READ
/// bash -e -c 'false && echo x'                     exit 1   READ
/// bash -e -c 'false || true'                       exit 0   discarded
/// bash -e -c 'false | cat'                         exit 0   discarded
/// bash -e -c 'false &'                             exit 0   discarded
/// bash -e -c 'set +e; false; echo REACHED'  prints, exit 0  discarded
/// ```
///
/// So `;` belongs with `&&`. The first version of this rule refused
/// it, reasoning that the line's status becomes the next command's --
/// true without `-e`, false with it, and the sort of claim that has to
/// be run rather than thought about.
///
/// `set +e` is the caller's to handle, because it withdraws `errexit`
/// from every later command in the block rather than from one line.
///
/// It stays STRICTER than bash in two places, and both are stated
/// rather than accidental:
///
/// - `cargo test … & wait $!` does propagate the failure (measured:
///   exit 1) and is refused anyway, because recognising it means
///   tracking which job `$!` names;
/// - `cargo test --locked --all-targets && echo ok | tee log` is
///   refused because the tail contains a `Pipe`, and bash reads that
///   status: `|` binds tighter than `&&`, so the pipeline is the last
///   member of the list rather than something after it. MEASURED:
///   `bash -e -c 'false && echo ok | tee /dev/null'` exits 1.
///   `grep -cE 'cargo test.*&&.*\|'` is 0 in all six copies' `ci.yml`,
///   so nothing hits it today; fixing it means telling a pipeline
///   INSIDE a list from one that follows it, which is a change to the
///   tokenizer rather than to this rule.
///
/// Refusing a correct workflow loudly is this file's declared
/// direction; passing a broken one silently is the defect it exists
/// for.
fn status_is_read(
    commands: &[(Vec<String>, Sep)],
    index: usize,
    is_last_command_line: bool,
) -> bool {
    let tail = &commands[index..];
    if !tail
        .iter()
        .all(|(_, sep)| matches!(sep, Sep::End | Sep::And | Sep::Semi))
    {
        return false;
    }
    // AN `&&` LIST ONLY CARRIES ITS FAILURE IF IT ENDS THE LINE, and
    // this cost a measurement to get right. `set -e` exempts a command
    // that is part of an `&&` list from aborting the shell -- and the
    // list's own non-zero status does not abort it either, so whatever
    // follows the list runs and its status becomes the line's:
    //
    //   bash -e -c 'false && echo x'                exit 1   READ
    //   bash -e -c 'false && echo x; echo REACHED'  exit 0   DISCARDED
    //   bash -e -c 'false && echo x && echo y'      exit 1   READ
    //
    // So `cargo test --locked --lib && echo ok; echo done` is a gate
    // that cannot fail, and the rule above -- which asked only that no
    // `||`, `|` or `&` follow -- counted it as read.
    //
    // A NEWLINE ENDS A COMMAND THE SAME WAY `;` DOES, and this rule
    // could not see one. `runs_with_overflow_checks` calls this per
    // line, so "ends the line" was the whole test -- and a `run: |`
    // block is the spelling a workflow is actually written in:
    //
    //   run: |
    //     cargo test --locked --all-targets && echo done
    //     echo "second line"
    //
    // The `&&` list ends its own line, the tail is `[And, End]`, and
    // the step exits 0 with the suite red. Measured:
    // `bash -e -c $'false && echo x\necho R'` exits 0 and prints R,
    // exactly as the `;` spelling does.
    //
    // `an_and_list_that_does_not_end_the_line_has_its_failure_swallowed`
    // is named for this defect and reaches only the `;` half: both of
    // its inputs put the following command on the SAME line. So the
    // rule needs to know whether anything runs after this LINE too,
    // which is a fact about the script rather than about the line.
    if tail[0].1 == Sep::And {
        return is_last_command_line
            && tail
                .iter()
                .all(|(_, sep)| matches!(sep, Sep::And | Sep::End));
    }
    true
}

/// Whether the `&&`/`||` list a command sits in can skip it while
/// leaving the step green.
///
/// [`status_is_read`] looks only at what FOLLOWS a command, and a run
/// the shell never starts was counted. `set -e` does not act on a
/// failing command that is not the last of an `&&`/`||` list, so
/// measured with `bash -e -c` and a `cargo` that records whether it ran:
///
/// ```text
/// true || cargo test                          exit 0, never ran
/// true || echo x | cargo test                 exit 0, never ran
/// test -n "$CI" && cargo test ; echo done     exit 0, never ran (CI unset)
/// test -n "$CI" && cargo test                 exit 1, never ran -- loud
/// ```
///
/// The separator that decides is the one before the command's PIPELINE,
/// because `|` binds tighter than `&&` and `||`:
///
/// - after `||` the run happens only if the left side failed, and when
///   it succeeds the list is green. Refused always -- including
///   `false || cargo test`, which bash does run, because whether the
///   left side fails is not in the text;
/// - after `&&` a skipped run leaves the list's status non-zero, which
///   fails the step only if that status IS the step's: nothing but more
///   `&&` after it, on the last line. `cd . && cargo test` followed by
///   another line is refused for the same reason as `false ||`.
fn list_can_skip(
    commands: &[(Vec<String>, Sep)],
    index: usize,
    is_last_command_line: bool,
) -> bool {
    let before = commands[..index]
        .iter()
        .rev()
        .map(|(_, sep)| *sep)
        .find(|sep| *sep != Sep::Pipe);
    match before {
        Some(Sep::Or) => true,
        Some(Sep::And) => {
            !(is_last_command_line
                && commands[index..]
                    .iter()
                    .all(|(_, sep)| matches!(sep, Sep::And | Sep::End)))
        }
        _ => false,
    }
}

/// If this command is made only of assignments, the text of the command
/// substitution whose status it hands on.
///
/// # A SUBSTITUTION THAT IS THE WHOLE COMMAND IS NOT SWALLOWED
///
/// Every substitution was treated as swallowing its status, and bash
/// says otherwise: for a command with no program, the status is that of
/// the LAST command substitution performed. Measured with `bash -e -c`,
/// suite passing / failing:
///
/// ```text
/// x=$(cargo test)                 0 / 1   gates
/// x=$(true) y=$(cargo test)       0 / 1   gates
/// x=$(cargo test) y=$(true)       0 / 0   the last one decides
/// echo $(cargo test)              0 / 0   echo decides
/// export x=$(cargo test)          0 / 0   export decides
/// env x=$(cargo test)             127     env runs cargo's output
/// $(cargo test)                   127     so does a bare substitution
/// ```
///
/// The last two are why a substitution standing as the PROGRAM is not
/// accepted: `cargo test` writes to stdout, the shell runs that text as
/// a command, and the step fails whatever the suite did. Only a pure
/// assignment qualifies, and only when its last substitution is one
/// [`scan_shell`] could follow (`Some`); `x=$(cargo test) y="$(true)"`
/// ends in a quoted one and is refused.
fn whole_command_substitution<'a>(
    words: &[String],
    substitutions: &'a [Option<String>],
) -> Option<&'a str> {
    if words.is_empty() || !words.iter().all(|word| is_assignment(word)) {
        return None;
    }
    substitutions.last()?.as_deref()
}

/// The `cargo test` commands inside a command substitution whose status
/// becomes the substitution's.
///
/// ERREXIT IS OFF IN HERE. Bash does not pass `-e` into a substitution
/// (`inherit_errexit` is off), so `;` DISCARDS a status here where it
/// does not outside: `x=$(cargo test; true)` exits 0 with the suite
/// failing. So the rule is simpler and stricter than the outer one: the
/// run must be in the LAST list, with nothing after it but `&&`, not
/// piped onward, not backgrounded, and not after `||`. Measured:
/// `x=$(cargo test && echo ok)` and `x=$(echo x | cargo test)` gate;
/// `x=$(cargo test | cat)` and `x=$(true || cargo test)` do not.
///
/// A substitution nested the same way (`x=$(y=$(cargo test))`) hands its
/// status on too, and is followed.
///
/// Each run comes with what the substitution itself did to the handshake
/// before it: `Some(false)` when a command withdrew it
/// ([`withdraws_the_handshake`]), `Some(true)` when a later unconditional
/// export put it back ([`exports_the_handshake`], by the same rule as
/// outside), and `None` when nothing touched it, so the run has what the
/// shell exported. The substitution inherits the shell's exports and can
/// change them for the commands after, in either direction. Measured with
/// `env | grep -c`: `export X=1; x=$(unset X; env)` gives 0 (Greptile on
/// rust-img-qcow2#94); `export X=1; x=$(unset X; export X=1; env)` gives 1
/// and so does `x=$(export X=1; env)` with nothing exported outside
/// (Greptile on rust-img-vmdk#102); `x=$(false && export X=1; env)`,
/// `x=$(export X=1 | cat; env)` and `x=$(unset X; y=$(export X=1); env)`
/// give 0.
fn substitution_gates(script: &str) -> Vec<(Vec<String>, Option<bool>)> {
    let scan = scan_shell(script);
    let commands = &scan.commands;
    let Some(last) = commands.len().checked_sub(1) else {
        return Vec::new();
    };
    // A trailing `;` ends the list as a newline would (`x=$(false;)`
    // exits 1); a trailing `&` backgrounds it (`x=$(false &)` exits 0).
    if !scan.plain || !matches!(commands[last].1, Sep::End | Sep::Semi) {
        return Vec::new();
    }
    let mut out = Vec::new();
    let mut handshake = None;
    let mut exports_reach = true;
    for (index, (words, sep)) in commands.iter().enumerate() {
        let handshake_before = handshake;
        if opens_a_compound_command(words) {
            exports_reach = false;
        }
        let unconditional = (index == 0 || commands[index - 1].1 == Sep::Semi)
            && !matches!(sep, Sep::Pipe | Sep::Amp);
        if exports_the_handshake(words) {
            if exports_reach && unconditional {
                handshake = Some(true);
            }
        } else if withdraws_the_handshake(words) {
            handshake = Some(false);
        }
        let decides = commands[index..last]
            .iter()
            .all(|(_, sep)| *sep == Sep::And)
            && commands[..index]
                .iter()
                .rev()
                .map(|(_, sep)| *sep)
                .find(|sep| *sep != Sep::Pipe)
                != Some(Sep::Or);
        if !decides {
            continue;
        }
        if cargo_test_arguments(words).is_some() {
            out.push((words.clone(), handshake_before));
        } else if let Some(inner) = whole_command_substitution(words, &scan.substitutions[index]) {
            out.extend(
                substitution_gates(inner)
                    .into_iter()
                    .map(|(run, inner)| (run, inner.or(handshake_before))),
            );
        }
    }
    out
}

/// Every `cargo test` invocation in a shell script that would be
/// compiled with overflow checks on AND whose failure would be read.
///
/// The argument is the SHELL text of one step's `run:`, not YAML.
/// [`parse_workflow`] has already turned the workflow into a structure,
/// so a YAML comment can no longer reach this function at all -- that
/// half of the old scan is now the parser's job, by construction. Shell
/// comments still reach here, and [`command_lines`] is the one place
/// they are removed.
///
/// Seven things disqualify a command, and each one is a way the guard
/// could otherwise be satisfied by something that does not actually
/// build the library in debug and fail loudly:
///
/// - an earlier command disables `set -e`, which makes every command
///   after it advisory ([`set_disables_errexit`]);
/// - it is a shell comment, or an inline trailing comment on an
///   otherwise-`--release` line ([`command_lines`]);
/// - it does not invoke `cargo test` at all, only mentions it
///   ([`cargo_test_arguments`]);
/// - it passes `--release`, or names a profile explicitly;
/// - it sets a `CARGO_PROFILE_*` variable, which can turn overflow
///   checks off for the dev or test profile from outside the manifest;
/// - it selects something other than the library unit tests, before or
///   after `--` ([`omits_the_library_unit_tests`]);
/// - its exit status is discarded ([`status_is_read`]).
///
/// A `cargo build` is not a `cargo test` and is not considered, nor is
/// any step that invokes no cargo at all.
fn runs_with_overflow_checks(script: &str) -> Vec<String> {
    debug_runs(script, false)
        .into_iter()
        .map(|run| run.line)
        .collect()
}

/// A logical line carrying a qualifying run, and whether a qualifying
/// `cargo test` on it RECEIVES the handshake.
#[derive(Debug)]
struct DebugRun {
    line: String,
    receives_the_handshake: bool,
}

/// The one walk behind every scan of a `run:` block, in execution order.
///
/// # WHY ONE WALK, IN ORDER
///
/// Two facts here depend on WHERE a command sits, and both were decided
/// for the whole block or the whole line instead:
///
/// - `set +e` refused every run in the block, including one that had
///   already run under `errexit` (a false refusal);
/// - the handshake armed every run in a STEP if any line in it assigned
///   the variable, and every run on a LINE if any command on it did --
///   so `cargo test --locked --lib; export EXPECT_OVERFLOW_CHECKS=1` and
///   `EXPECT_OVERFLOW_CHECKS=1 echo x; cargo test --locked --lib` both
///   counted as proving the build traps while the test process received
///   no variable (a false pass, and the one that matters).
///
/// Walking the commands in order answers both the way the shell does.
/// `exported` starts as whatever the step's `env:` mapping put in the
/// environment, and a run receives the handshake from its own
/// assignment prefix if it has one, otherwise from `exported` as it
/// stands when the run starts.
fn debug_runs(script: &str, handshake_in_env: bool) -> Vec<DebugRun> {
    let lines = command_lines(script);
    let last_line = lines.len().saturating_sub(1);
    let mut errexit_withdrawn = false;
    let mut exported = handshake_in_env;
    // Whether an `export` can still be believed to run in THIS shell.
    // See [`exports_the_handshake`] for why this only ever goes false.
    let mut exports_reach_the_shell = true;
    let mut out = Vec::new();
    for (line_index, line) in lines.iter().enumerate() {
        let ShellScan {
            commands,
            substitutions,
            plain,
        } = scan_shell(line);
        if !plain {
            exports_reach_the_shell = false;
        }
        let profile_is_named = line.contains("--release")
            || line.contains("--profile")
            || line.contains("CARGO_PROFILE_");
        let mut qualifies = false;
        let mut receives_the_handshake = false;
        for (index, (words, sep)) in commands.iter().enumerate() {
            if opens_a_compound_command(words) {
                exports_reach_the_shell = false;
            }
            // Whether an `&&` chain's failure reaches the step depends on
            // nothing running after it -- on a later line included -- and
            // whether the run happens at all on what comes before it.
            let is_last_command_line = line_index == last_line;
            let decides_the_step = status_is_read(&commands, index, is_last_command_line)
                && !list_can_skip(&commands, index, is_last_command_line);
            if !errexit_withdrawn && !profile_is_named && decides_the_step {
                // The run itself, or the runs inside a substitution whose
                // status this command hands on.
                let runs = if cargo_test_arguments(words).is_some() {
                    vec![(words.clone(), None)]
                } else {
                    whole_command_substitution(words, &substitutions[index])
                        .map(substitution_gates)
                        .unwrap_or_default()
                };
                for (run, set_inside) in runs {
                    let Some(arguments) = cargo_test_arguments(&run) else {
                        continue;
                    };
                    if omits_the_library_unit_tests(&arguments)
                        || selects_release_by_short_flag(&arguments)
                    {
                        continue;
                    }
                    qualifies = true;
                    // A run inside a substitution inherits what the shell
                    // has EXPORTED; the outer command's own assignments
                    // are shell variables and do not reach it. Measured:
                    // `EXPECT_OVERFLOW_CHECKS=1 x=$(cargo test ...)`
                    // leaves `cargo` without the variable. Unless the
                    // substitution withdrew or re-exported it before the run.
                    receives_the_handshake |= handshake_prefix(&run)
                        .0
                        .unwrap_or(set_inside.unwrap_or(exported));
                }
            }
            // A WITHDRAWAL APPLIES WHEREVER IT SITS, conditional or in a
            // subshell, and that asymmetry with `export` is deliberate.
            // Whether `a && set +e` runs is not knowable from the text,
            // and the spelling that matters is the one that DOES run on
            // CI: `CI=true bash -e -c '[ -n "$CI" ] && set +e; false;
            // echo R'` prints R and exits 0, and the same shape with
            // `unset` leaves the suite without the variable. Believing
            // only unconditional withdrawals would count both. So a
            // skipped or subshelled `set +e`/`unset` refuses a gate that
            // works -- loud, and the direction this file declares -- and
            // `a_withdrawal_under_control_flow_is_still_applied` pins it.
            if set_disables_errexit(words) {
                errexit_withdrawn = true;
            }
            // What this command does to the shell's environment applies
            // to the commands AFTER it, so it is recorded last.
            let unconditional = (index == 0 || commands[index - 1].1 == Sep::Semi)
                && !matches!(sep, Sep::Pipe | Sep::Amp);
            if exports_the_handshake(words) {
                if exports_reach_the_shell && unconditional {
                    exported = true;
                }
            } else if withdraws_the_handshake(words) {
                exported = false;
            }
        }
        if qualifies {
            out.push(DebugRun {
                line: line.clone(),
                receives_the_handshake,
            });
        }
    }
    out
}

/// WHAT ELSE DECIDES WHETHER A STEP GATES.
///
/// The first version of this guard matched the text of a `- run:` line
/// and never looked at anything else in the step. That is enough to
/// find the command and useless for deciding whether the command's
/// result is read. Measured against this repository's own workflow:
/// adding `if: false` to the step, or `continue-on-error: true`, left
/// every one of the guard's 31 tests green while the gate went blind.
/// A step that runs and whose result nothing reads is this
/// constellation's own named defect, reproduced inside the guard
/// written to prevent it.
///
/// So the list is enumerated first, rather than discovered one defeat
/// at a time. A `run:` step gates a pull request only if ALL of these
/// hold:
///
/// 1. the step carries no `if:` -- a false condition skips it;
/// 2. the step carries no `continue-on-error:` -- its failure is
///    discarded;
/// 3. its JOB carries no `if:` -- same reasoning, one level up;
/// 4. its JOB carries no `continue-on-error:`;
/// 5. the workflow's `on:` still includes `pull_request` -- a scan
///    scoped to `ci.yml` assumes `ci.yml` is what runs on a pull
///    request, and that is a fact about the file, not a given.
///
/// OVER-STRICT IS THE SAFE DIRECTION HERE, so 1 and 2 reject on the
/// key's PRESENCE rather than trying to evaluate it. `if: false`,
/// `if: ${{ false }}`, and an `if:` on an expression that happens to
/// evaluate false are distinct spellings, and this crate has already
/// been caught by four spellings of one manifest key -- enumerating
/// them is the losing game. A step that genuinely needs a condition
/// can be split out; a guard that tries to interpret conditions is a
/// guard with a new defeat every time GitHub adds syntax.
///
/// # Why this is parsed and no longer scanned
///
/// The version this replaces hand-rolled the YAML: `.lines()`, an
/// indent count, `split_once(':')` for the key, and `after != "|"` for
/// a block scalar. It was defeated three more times after the five
/// spellings above, and each defeat was the same shape -- ordinary
/// YAML the scanner had not been taught:
///
/// ```text
///   "if": false               quoted key -- matched no NON_GATING_KEYS
///                             entry, so the step counted as gating
///                             while Actions skipped it. SILENT.
///   "continue-on-error": true same.
///   # pull_request:           a substring match over the `on:` block's
///                             raw text, comments included, so
///                             commenting the trigger out left the
///                             guard green. SILENT.
///   run: |-  / run: >         only a bare `|` opened a block, so every
///                             other legal style was read as the
///                             command itself and the block's contents
///                             never parsed. LOUD -- it failed a
///                             correct workflow.
/// ```
///
/// Quoted keys, block scalar styles, comments and nested mappings are
/// not edge cases; they are the grammar. A parser handles all of them
/// by construction, and does not need to be taught the next one. The
/// sibling `rust-fs-xfs` copy patched each hole individually and its
/// own comments record the cost: the identical quote-normalisation was
/// added to its TOML key scan, and then had to be added again, a few
/// dozen lines away, to its YAML key scan. The same lesson twice in one
/// file is the argument against learning it a third time.
///
/// `saphyr` is a dev-dependency, so nothing here reaches a consumer of
/// the crate.
#[derive(Debug)]
struct Step {
    keys: Vec<String>,
    run: String,
    /// The step's `env:` mapping, as `KEY=VALUE`.
    ///
    /// The handshake is an environment variable, and an inline
    /// `VAR=1 cargo test` prefix is bash syntax. A matrix that includes
    /// `windows-latest` runs the same step under PowerShell, where that
    /// prefix is a syntax error -- so on a cross-platform crate the
    /// handshake HAS to be declared here rather than in the command,
    /// and a guard that only reads the command would refuse the only
    /// spelling that works.
    env: Vec<String>,
}

#[derive(Debug)]
struct Job {
    keys: Vec<String>,
    steps: Vec<Step>,
}

#[derive(Debug)]
struct Workflow {
    triggers: Vec<String>,
    jobs: Vec<Job>,
}

/// The value of `name` in a YAML mapping, or `None`.
///
/// By name rather than by constructing a key, because `saphyr`'s `Yaml`
/// borrows the source text and building one to hand to `get` is more
/// ceremony than the lookup is worth here.
fn field<'a, 'b>(node: &'a Yaml<'b>, name: &str) -> Option<&'a Yaml<'b>> {
    node.as_mapping()?
        .iter()
        .find(|(key, _)| key.as_str() == Some(name))
        .map(|(_, value)| value)
}

/// An env value as text, whether it was written `1`, `"1"` or `true`.
///
/// `EXPECT_OVERFLOW_CHECKS: 1` and `EXPECT_OVERFLOW_CHECKS: "1"` are
/// the same variable to Actions, and a guard that accepted only the
/// quoted spelling would be back to matching spellings.
fn scalar_text(node: &Yaml) -> Option<String> {
    if let Some(text) = node.as_str() {
        return Some(text.to_string());
    }
    if let Some(i) = node.as_integer() {
        return Some(i.to_string());
    }
    node.as_bool().map(|b| b.to_string())
}

/// The keys of a YAML mapping, as plain strings.
///
/// The parser has already resolved the quoting, so `"if"`, `'if'` and
/// `if` all arrive here as `if`. That is the whole of the quoted-key
/// fix: there is no un-quoting step to forget.
fn keys_of(node: &Yaml) -> Vec<String> {
    node.as_mapping()
        .map(|mapping| {
            mapping
                .iter()
                .filter_map(|(key, _)| key.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default()
}

/// Structure a workflow far enough to answer the five questions above.
///
/// Panics on a workflow it cannot parse, deliberately. A guard that
/// returned an empty `Workflow` for a file it did not understand would
/// report "no debug run gates this" -- which is a failure, so that
/// direction is safe -- but a guard that returned early with a PASS
/// would be the blindness this module exists to prevent. Failing on the
/// parse error names the real problem instead of a consequence of it.
fn parse_workflow(text: &str) -> Workflow {
    let documents = Yaml::load_from_str(text).unwrap_or_else(|e| {
        panic!(
            "workflow is not valid YAML: {e}. This guard reads the workflow \
             rather than scanning its text, so a file it cannot parse is a \
             failure and never a pass."
        )
    });
    let Some(document) = documents.first() else {
        return Workflow {
            triggers: Vec::new(),
            jobs: Vec::new(),
        };
    };

    // `on:` takes three legal shapes: a mapping of trigger names, a
    // sequence of them, or a single scalar. All three are names.
    //
    // Note that `on` survives as the string key `on` and is not folded
    // into the boolean `true` -- saphyr implements the YAML 1.2 core
    // schema, where only `true`/`false` are booleans. The YAML 1.1
    // reading that would break every GitHub workflow ever written does
    // not apply.
    let triggers = match field(document, "on") {
        Some(on) if on.as_mapping().is_some() => keys_of(on),
        Some(on) if on.as_sequence().is_some() => on
            .as_sequence()
            .into_iter()
            .flatten()
            .filter_map(|item| item.as_str().map(str::to_string))
            .collect(),
        Some(on) => on.as_str().map(str::to_string).into_iter().collect(),
        None => Vec::new(),
    };

    let mut jobs = Vec::new();
    if let Some(mapping) = field(document, "jobs").and_then(Yaml::as_mapping) {
        for (_, body) in mapping.iter() {
            let steps = field(body, "steps")
                .and_then(Yaml::as_sequence)
                .into_iter()
                .flatten()
                .map(|step| Step {
                    keys: keys_of(step),
                    env: field(step, "env")
                        .and_then(Yaml::as_mapping)
                        .map(|m| {
                            m.iter()
                                .filter_map(|(k, v)| {
                                    Some(format!("{}={}", k.as_str()?, scalar_text(v)?))
                                })
                                .collect()
                        })
                        .unwrap_or_default(),
                    // A `run:` block of any style -- `|`, `|-`, `|+`,
                    // `>`, `>-`, `|2` -- arrives as one string with the
                    // block folded per its own rules, so a command
                    // inside a shell loop is seen whole rather than as
                    // fragments, and no style is mistaken for the
                    // command itself.
                    run: field(step, "run")
                        .and_then(Yaml::as_str)
                        .unwrap_or_default()
                        .to_string(),
                })
                .collect();
            jobs.push(Job {
                keys: keys_of(body),
                steps,
            });
        }
    }

    Workflow { triggers, jobs }
}

/// Does this workflow still run on a pull request at all?
///
/// A whole-name comparison against the parsed trigger keys. The version
/// this replaces asked `wf.triggers.contains("pull_request")` of the
/// `on:` block's raw text -- comments and blank lines included -- so
/// the word appearing anywhere in it satisfied the guard. Commenting
/// the real key out, or deleting it and leaving a comment naming it,
/// left `ci.yml` no longer running on pull requests at all with the
/// guard still green.
///
/// `pull_request_target` DELIBERATELY DOES NOT COUNT, and the omission
/// is the point rather than an oversight. It runs against the base
/// repository with a write token and the repository's secrets, and it
/// checks out the base ref by default -- so a workflow triggered only
/// that way may never build the contributor's code at all, and
/// accepting it as proof the merge is gated is permissive in the worst
/// direction. `rust-fs-xfs#146` and `rust-fs-ext4#149` record it as a
/// live gap in the hand-rolled guard this file replaces, where the
/// clause was written by hand and then copied between repositories.
///
/// A parser has no opinion about `pull_request_target` unless someone
/// writes one. So it is not written. If this repository ever needs it
/// accepted, that is a decision with its own justification, and it
/// comes with a check that the checkout selects the pull request head.
fn runs_on_pull_request(wf: &Workflow) -> bool {
    wf.triggers.iter().any(|t| t == "pull_request")
}

/// Keys whose presence on a step or job means its result does not gate.
const NON_GATING_KEYS: [&str; 2] = ["if", "continue-on-error"];

/// Walk a workflow's steps and collect what `select` finds in each
/// `run:`.
///
/// `gating` restricts the walk to steps whose result the pull-request
/// gate actually reads: the workflow must still trigger on a pull
/// request, and neither the job nor the step may carry a key from
/// [`NON_GATING_KEYS`].
///
/// One walk rather than two. The headline assertion used the line-based
/// scan while only the handshake assertion was step-aware, so under
/// `if: false` the headline PASSED and its failure message would have
/// claimed the pull-request gate could see an overflow when the step it
/// names does not run. Every defeat spelling still turned the suite red
/// through the other assertion, so this was a precision defect rather
/// than a hole -- but it left the "runs without --release" property
/// verified line-based, and defeatable if the handshake assertion were
/// ever weakened. Both halves share this walk now and cannot drift
/// apart again. Found on the sibling `rust-fs-btrfs` copy of this guard
/// and corrected here rather than left to diverge.
fn collect_steps(workflow: &str, gating: bool) -> Vec<Step> {
    let wf = parse_workflow(workflow);
    if gating && !runs_on_pull_request(&wf) {
        return Vec::new();
    }
    let carries_a_non_gating_key =
        |keys: &[String]| keys.iter().any(|k| NON_GATING_KEYS.contains(&k.as_str()));

    let mut out = Vec::new();
    for job in wf.jobs {
        if gating && carries_a_non_gating_key(&job.keys) {
            continue;
        }
        for step in job.steps {
            if gating && carries_a_non_gating_key(&step.keys) {
                continue;
            }
            out.push(step);
        }
    }
    out
}

fn scan_steps(workflow: &str, gating: bool, select: fn(&str) -> Vec<String>) -> Vec<String> {
    collect_steps(workflow, gating)
        .iter()
        .flat_map(|step| select(&step.run))
        .collect()
}

/// The runs in this step that ask the build to prove it traps an
/// overflow.
///
/// Either spelling counts, and both are the same instruction to
/// Actions: the variable inline in the command, or declared in the
/// step's `env:` mapping. The mapping is not a concession -- it is the
/// ONLY spelling that works on a matrix including `windows-latest`,
/// where an inline `VAR=1 cargo test` prefix is a PowerShell syntax
/// error. A guard that read only the command would refuse the correct
/// workflow on every cross-platform crate in this constellation.
///
/// THE INLINE HALF READS COMMANDS, NOT THE RAW BLOCK. It used to be
/// `step.run.contains(...)`, and `step.run` is the block verbatim --
/// comments included -- while the other half of the scan strips them.
/// Two readers of one text with two grammars, so a step could be armed
/// by a line the shell never executes:
///
///     run: |
///       # EXPECT_OVERFLOW_CHECKS=1 -- see ci_profile.rs
///       cargo test --locked --all-targets
///
/// Both workflow assertions passed on that and the process got no
/// variable at all, leaving the runtime probe to return without
/// asserting anything. [`command_lines`] is now the single grammar.
///
/// # AND IT IS A PROPERTY OF THE RUN, NOT OF THE STEP
///
/// This was `step_declares_the_handshake`, a yes/no for the whole step,
/// and every run in an armed step then counted. So an assignment that
/// prefixed a different command, or an export that ran after the suite,
/// armed a `cargo test` whose process never received the variable. The
/// env mapping is now the INITIAL environment of [`debug_runs`], which
/// decides per run.
fn step_runs_that_prove_the_build_traps(step: &Step) -> Vec<String> {
    let handshake_in_env = step.env.iter().any(|entry| entry == HANDSHAKE);
    debug_runs(&step.run, handshake_in_env)
        .into_iter()
        .filter(|run| run.receives_the_handshake)
        .map(|run| run.line)
        .collect()
}

/// Whether any command on a shell line ASSIGNS the handshake, rather
/// than mentioning it.
///
/// A `contains` over the line stood here, and `command_lines` had
/// already removed comments -- but a printed mention is not a comment:
///
///     echo "EXPECT_OVERFLOW_CHECKS=1"
///     cargo test --locked --all-targets
///
/// That armed the whole step, `gating_runs_that_prove_the_build_traps`
/// then counted the `cargo test` beneath it as proving the build traps,
/// and the process received no variable at all -- so the runtime probe
/// returned without asserting anything. The same defect as the comment
/// grammar it replaced, one grammar later.
///
/// THIS ANSWERS WHAT A COMMAND DOES, NOT WHICH RUN IT REACHES. It is the
/// per-command half, asked of a whole line so the tests can state its
/// spellings; [`debug_runs`] asks the same two pieces --
/// [`handshake_prefix`] and [`exports_the_handshake`] -- of each command
/// in order, which is what decides whether a particular `cargo test`
/// receives the variable.
fn line_assigns_the_handshake(line: &str) -> bool {
    shell_commands(line)
        .iter()
        .any(|(words, _)| command_assigns_the_handshake(words))
}

const HANDSHAKE_NAME: &str = "EXPECT_OVERFLOW_CHECKS";
const HANDSHAKE: &str = "EXPECT_OVERFLOW_CHECKS=1";

/// Whether one tokenised command puts the handshake into an
/// ENVIRONMENT a process receives.
///
/// # AN ASSIGNMENT ON ITS OWN EXPORTS NOTHING
///
/// This returned true on seeing the handshake anywhere in a command's
/// assignment prefix, and a standalone
///
/// ```text
/// EXPECT_OVERFLOW_CHECKS=1
/// cargo test --locked --lib
/// ```
///
/// is a prefix with no command after it: bash sets a SHELL variable
/// that the `cargo test` on the next line never sees. So the guard
/// reported a probe that could not have run — the recurring defect,
/// inside the guard written to close it.
///
/// Three conditions, and the defect was the absence of the second:
///
/// 1. **Name shape.** [`is_assignment`] requires a name that is a legal
///    shell identifier, so `1abc=x` is not an assignment and neither is
///    a bare `=x`.
/// 2. **Leading position, WITH A COMMAND AFTER IT.** A prefix
///    assignment is exported to the command it prefixes and to nothing
///    else, so with no command there is nothing to export to.
/// 3. **Or an exporting builtin**, which puts it in the shell's own
///    environment and so reaches later commands
///    ([`exports_the_handshake`]).
///
/// # THE TEMPTING FIX IS TO REQUIRE `export`, AND IT WOULD BE WRONG
///
/// `EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib` is the spelling
/// the guard exists to accept.
/// `a_real_assignment_beside_a_run_on_one_line_still_counts` and
/// `every_spelling_that_really_assigns_it_still_arms_the_step` are the
/// acceptance arms.
///
/// # WHAT IS DELIBERATELY STILL REFUSED
///
/// `declare -x` and `typeset -x` do export — measured in
/// `rust-img-vhdx`'s `assigns_the_handshake`, which is the one copy in
/// the constellation that built that table:
///
/// ```text
/// export X=1      child sees it: 1     declare -x X=1  child sees it: 1
/// declare X=1     child sees it: 0     typeset -x X=1  child sees it: 1
/// typeset X=1     child sees it: 0
/// readonly X=1    child sees it: 0
/// ```
///
/// This file recognises only `export`, so the `-x` spellings are
/// REFUSED. That is the over-strict direction and it is left alone
/// deliberately: recognising them widens what counts as armed, which is
/// the unsafe direction, and no workflow here writes one. The four
/// non-exporting spellings are already refused, because none of them is
/// `export`, `env` or an assignment.
fn command_assigns_the_handshake(words: &[String]) -> bool {
    if exports_the_handshake(words) {
        return true;
    }
    // AND A COMMAND FOLLOWS. A command made only of assignments is the
    // defect this function was changed for.
    let (value, a_command_follows) = handshake_prefix(words);
    value == Some(true) && a_command_follows
}

/// The handshake's value in this command's assignment PREFIX, if the
/// prefix sets it, and whether a command follows the prefix.
///
/// Every word before the program must be another `NAME=value` or `env`,
/// which is exactly the shape [`cargo_test_arguments`] steps over, so
/// `echo EXPECT_OVERFLOW_CHECKS=1` sets nothing: `echo` is the program.
/// The LAST assignment to the name wins, as it does in the shell, and
/// `EXPECT_OVERFLOW_CHECKS=0 cargo test` overrides an earlier export --
/// which is why this answers a value rather than a yes.
fn handshake_prefix(words: &[String]) -> (Option<bool>, bool) {
    let mut value = None;
    let mut at = 0;
    while at < words.len() {
        let word = words[at].as_str();
        if word == "env" {
            at += 1;
            continue;
        }
        if is_assignment(word) {
            if word.split_once('=').map(|(name, _)| name) == Some(HANDSHAKE_NAME) {
                value = Some(word == HANDSHAKE);
            }
            at += 1;
            continue;
        }
        // The program name. Anything matching after it is an argument
        // rather than an assignment.
        break;
    }
    (value, at < words.len())
}

/// Whether this command is an `export` of the handshake.
///
/// # `export` IS THE COMMAND EVEN BEHIND AN ASSIGNMENT PREFIX
///
/// Only a first word of `export` was recognised, so
/// `FOO=1 export EXPECT_OVERFLOW_CHECKS=1` -- which bash runs as
/// `export` with `FOO` set for its duration, and which does export the
/// handshake (measured: a following `cargo` sees it) -- was refused.
/// Assignments are stepped over. `env` is NOT: `env FOO=1 export ...`
/// runs an external program called `export`, which does not exist, and
/// could not touch this shell if it did.
///
/// Any option refuses it: `export -n EXPECT_OVERFLOW_CHECKS=1` sets the
/// value and REMOVES the export, and a list of the harmless options is
/// a list to keep up to date for no workflow that needs one.
///
/// # WHAT THIS DOES NOT DECIDE: WHETHER THE EXPORT REACHES THE RUN
///
/// That is [`debug_runs`]' job, because it depends on where the command
/// sits. An export counts only if all of these hold, and each refusal is
/// a spelling measured to leave the variable out of `cargo`'s
/// environment:
///
/// - it runs BEFORE the `cargo test` (`cargo test ...; export ...`);
/// - it is not conditional: first on its line or after a `;`, not after
///   `&&`/`||` (`test -n "$CI" && export ...`);
/// - it is not a pipeline member or backgrounded (`export ... | cat`,
///   `export ... &`), both of which run in a subshell;
/// - nothing from the top of the script up to it is a subshell, an
///   unclosed quote or span, a heredoc, or a compound command
///   ([`scan_shell`]'s PLAIN flag and [`opens_a_compound_command`]),
///   because any of those can put it in a subshell or make it data --
///   `(export ...)` and a heredoc body among them. This is coarser than
///   the shell, in the refusing direction: an `if` anywhere above an
///   export stops it counting, even where it would have run.
/// - nothing between it and the run withdraws it
///   ([`withdraws_the_handshake`]).
fn exports_the_handshake(words: &[String]) -> bool {
    let mut rest = words
        .iter()
        .map(String::as_str)
        .skip_while(|word| is_assignment(word));
    if rest.next() != Some("export") {
        return false;
    }
    let mut value = None;
    for word in rest {
        if word.starts_with('-') && word != "--" {
            return false;
        }
        if let Some((name, _)) = word.split_once('=') {
            if name == HANDSHAKE_NAME {
                value = Some(word == HANDSHAKE);
            }
        }
    }
    value == Some(true)
}

/// Whether a command that is not an exporting `export` touches the
/// handshake's name at all -- `unset EXPECT_OVERFLOW_CHECKS`,
/// `export -n EXPECT_OVERFLOW_CHECKS`, `EXPECT_OVERFLOW_CHECKS=0`, or a
/// declaration builtin naming it.
///
/// Any such mention withdraws an earlier export for the runs after it.
/// That over-reads some harmless commands (`echo EXPECT_OVERFLOW_CHECKS`
/// withdraws it too), which is the refusing direction; the reverse would
/// let `unset` leave a run counted as armed.
fn withdraws_the_handshake(words: &[String]) -> bool {
    let program = words
        .iter()
        .map(String::as_str)
        .find(|word| !is_assignment(word));
    let declares = matches!(
        program,
        Some("export" | "declare" | "typeset" | "local" | "readonly")
    );
    words.iter().any(|word| {
        word == HANDSHAKE_NAME
            || (word.starts_with("EXPECT_OVERFLOW_CHECKS=") && (word != HANDSHAKE || declares))
    })
}

/// Whether `text` runs a command substitution: a backtick, or `$(` that is
/// not the `$((` of arithmetic. A substitution inside arithmetic is still
/// found, on its own `$(` further on.
///
/// Arithmetic is not a substitution and leaves the last real one deciding
/// (`x=$(false) y=${z:-$((1+1))}` exits 1), so a plain `contains("$(")`
/// took `$((` for one and refused a gate (Greptile on
/// rust-partitions#112).
fn runs_a_substitution(text: &str) -> bool {
    let b = text.as_bytes();
    b.contains(&b'`')
        || b.windows(3)
            .any(|w| w[0] == b'$' && w[1] == b'(' && w[2] != b'(')
        || b.ends_with(b"$(")
}

/// Words that begin, continue or end a compound command, where the
/// shell's reading of an `export` inside depends on control flow and
/// redirection this file does not track.
const COMPOUND_WORDS: [&str; 17] = [
    "{", "}", "if", "then", "elif", "else", "fi", "for", "while", "until", "do", "done", "case",
    "esac", "select", "function", "coproc",
];

/// Whether this command is part of a compound command, or opens a
/// heredoc whose body the line splitter would read as commands. See
/// [`exports_the_handshake`] for why an export after one is refused.
fn opens_a_compound_command(words: &[String]) -> bool {
    let program = words
        .iter()
        .map(String::as_str)
        .find(|word| !is_assignment(word));
    program.is_some_and(|program| COMPOUND_WORDS.contains(&program))
        || words.iter().any(|word| word.contains("<<"))
}

/// `NAME=value`, the shape a shell reads as an assignment rather than a
/// program name.
fn is_assignment(word: &str) -> bool {
    match word.split_once('=') {
        Some((name, _)) => {
            !name.is_empty()
                && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
                && !name.starts_with(|c: char| c.is_ascii_digit())
        }
        None => false,
    }
}

/// The run commands of steps that run in debug AND actually gate a
/// pull request -- without requiring the handshake.
fn gating_runs_with_overflow_checks(workflow: &str) -> Vec<String> {
    scan_steps(workflow, true, runs_with_overflow_checks)
}

/// The runs that both run in debug with the handshake AND actually gate
/// a pull request.
///
/// Step-aware rather than text-aware, because the handshake may be
/// declared in the step's `env:` mapping rather than inline in the
/// command -- see [`step_runs_that_prove_the_build_traps`].
fn gating_runs_that_prove_the_build_traps(workflow: &str) -> Vec<String> {
    collect_steps(workflow, true)
        .iter()
        .flat_map(step_runs_that_prove_the_build_traps)
        .collect()
}

/// The debug runs that ask the build to prove it traps an overflow.
///
/// A subset of [`runs_with_overflow_checks`]: those whose `cargo test`
/// process receives the `EXPECT_OVERFLOW_CHECKS` handshake, so that
/// `overflow_checks::the_build_the_gate_asked_to_check_does_check`
/// performs an overflow and fails if the build let it through.
///
/// A run carrying the handshake but also `--release` is not counted,
/// because [`runs_with_overflow_checks`] has already excluded it. Such
/// a step is a misconfiguration and it fails loudly rather than
/// quietly: the checks are legitimately off in release, so the
/// assertion the handshake arms would fire there every time.
///
/// THE SECOND CALL SITE OF THE SAME QUESTION, and it needs its own
/// witness. This used to filter whole lines with a `contains`, and then
/// with [`line_assigns_the_handshake`], so a mention or an assignment
/// ANYWHERE on the line armed a run elsewhere on it:
///
///     echo "EXPECT_OVERFLOW_CHECKS=1" && cargo test --locked --lib
///     EXPECT_OVERFLOW_CHECKS=1 echo x; cargo test --locked --lib
///
/// Both now go through [`debug_runs`], which decides per `cargo test`.
fn debug_runs_that_prove_the_build_traps(script: &str) -> Vec<String> {
    debug_runs(script, false)
        .into_iter()
        .filter(|run| run.receives_the_handshake)
        .map(|run| run.line)
        .collect()
}

/// The guard. Reads the workflow this repository's pull requests are
/// gated by and refuses if nothing in it compiles the overflow checks.
///
/// `ci.yml` specifically, not every workflow -- see
/// [`a_checking_debug_run_that_is_not_in_ci_yml_does_not_satisfy_this_guard`],
/// which is the one repository-specific decision in this file.
#[test]
fn the_pr_gate_still_tests_in_a_profile_that_can_see_an_overflow() {
    let path = ci_yml();
    let workflow = read_or_panic(&path);

    let debug_runs = gating_runs_with_overflow_checks(&workflow);
    assert!(
        !debug_runs.is_empty(),
        "no `cargo test` in {} runs without `--release`, so a defect whose \
         only symptom is an arithmetic overflow panic can merge without the \
         PR gate ever seeing it. release.yml already runs a debug suite, and \
         that does not help: it triggers on a version tag, after the change \
         has merged. If the debug step in ci.yml looked redundant beside the \
         release ones, it is not -- see the comment above it.",
        path.display()
    );
}

/// The other half of the workflow scan: the step exists, but does it
/// ask the build anything?
///
/// # Why a handshake rather than more spellings
///
/// The manifest scan below reads `Cargo.toml` and asks whether a known
/// spelling of "overflow checks are off" is present. Several spellings
/// of the key were needed before it was right, and then routes turned
/// up that are not in that file at all: a
/// `CARGO_PROFILE_TEST_OVERFLOW_CHECKS` variable set at step or job
/// level in the workflow, and a `.cargo/config.toml`, which nothing
/// here reads. All of them leave the debug step present, running, green
/// and blind.
///
/// They are all the same shape: a scanner enumerating the ways a thing
/// can be disabled, in the places it happens to look. Another pass buys
/// the next one. So the question is put to the build instead -- perform
/// an overflow, see whether you are stopped -- and this test's job
/// shrinks to making sure the gate still asks it.
#[test]
fn the_debug_run_asks_the_build_to_prove_it_traps_overflows() {
    let path = ci_yml();
    let workflow = read_or_panic(&path);

    let proving = gating_runs_that_prove_the_build_traps(&workflow);
    assert!(
        !proving.is_empty(),
        "no `cargo test` in {} runs without `--release` while setting \
         EXPECT_OVERFLOW_CHECKS=1, so nothing checks whether the profile the \
         gate builds actually traps an arithmetic overflow. Reading \
         Cargo.toml is not enough: the checks can also be turned off by a \
         CARGO_PROFILE_TEST_OVERFLOW_CHECKS variable at step or job level, \
         or by a .cargo/config.toml, neither of which is in any file this \
         test reads. The handshake is what arms the one check that cannot be \
         fooled by where the setting lives.",
        path.display()
    );
}

/// THE DISTINCTION THIS REPOSITORY NEEDS THAT A PORTED COPY WOULD MISS.
///
/// A workflow carrying a checking debug run under a name other than
/// `ci.yml` -- `release.yml`, in this repository's own case -- must not
/// satisfy the guards above. Simulated here with `release.yml`'s actual
/// step shape: a plain `cargo test --locked --all-targets` with no
/// `EXPECT_OVERFLOW_CHECKS`, because that workflow was never asked to
/// carry the handshake and is not asked to.
///
/// The scenario worth pinning is the near miss: even a hypothetical
/// debug run in `release.yml` that DID set the handshake would not make
/// `ci.yml`'s own absence of one acceptable, because `release.yml`
/// triggers too late to gate a merge. Both shapes are asserted below.
///
/// This is why the scan is scoped to one file rather than globbed over
/// `.github/workflows/`. A workflow that triggers on a version tag runs
/// after the change has already merged, so a debug run there does not
/// gate anything; a scan across every workflow would count it and
/// report the gate as sound when no pull request is covered. The
/// guard's correctness therefore comes from WHICH FILE it opens, not
/// from the parser refusing these shapes, and that is a fact worth
/// pinning rather than leaving as a comment someone could stop
/// believing.
#[test]
fn a_checking_debug_run_that_is_not_in_ci_yml_does_not_satisfy_this_guard() {
    let release_yml_as_it_is = "\
jobs:
  test:
    steps:
      - run: cargo test --locked --all-targets
      - run: cargo test --locked --all-targets -- --ignored
";
    // The `-- --ignored` step runs ONLY `#[ignore]` tests, so the probe
    // is not among them and it is not a debug run in this file's sense.
    // See `omits_the_library_unit_tests`.
    assert_eq!(
        scan_steps(release_yml_as_it_is, false, runs_with_overflow_checks),
        vec!["cargo test --locked --all-targets".to_string()],
        "release.yml's plain step IS a debug run -- the parser counts it, \
         and the only reason it does not satisfy the guard is that the guard \
         never opens that file"
    );
    assert!(
        scan_steps(
            release_yml_as_it_is,
            false,
            debug_runs_that_prove_the_build_traps
        )
        .is_empty(),
        "release.yml carries no handshake, and is not asked to"
    );

    let release_yml_with_a_handshake = "\
jobs:
  test:
    steps:
      - run: EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --all-targets
";
    assert_eq!(
        scan_steps(
            release_yml_with_a_handshake,
            false,
            debug_runs_that_prove_the_build_traps
        ),
        vec!["EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --all-targets".to_string()],
        "the parser itself would count this step too -- so widening the scan \
         to every workflow would silently stop catching this repository's \
         actual defect"
    );

    // And the real guards must be reading ci.yml, not one of these.
    let scanned = read_or_panic(&ci_yml());
    assert!(
        !gating_runs_that_prove_the_build_traps(&scanned).is_empty(),
        "the guards above must be satisfied by ci.yml's own content, not by \
         any of the strings in this test"
    );
}

/// The full dotted paths that switch overflow checks off for the
/// profile `cargo test` builds.
///
/// # This compares a whole path, because a key is not a word
///
/// The first version of this scan tracked the `[section]` and compared
/// the key to the literal `"overflow-checks"`. That reads correctly and
/// is defeated by ordinary TOML, because the same setting has several
/// spellings and cargo honours all of them without a warning. Measured
/// on a sibling repository with a runtime `u64::MAX + 1` unit test as
/// the probe -- `cargo test --locked --lib` EXIT=101 means the checks
/// are on, EXIT=0 means they are off, and `cargo metadata --no-deps`
/// was EXIT=0 for every one:
///
/// ```text
///   (nothing)                                          EXIT=101  on
///   [profile.test]  overflow-checks = false            EXIT=0    off
///   [profile.test]  "overflow-checks" = false          EXIT=0    off
///   [profile.test]  'overflow-checks' = false          EXIT=0    off
///   [profile]       test.overflow-checks = false       EXIT=0    off
/// ```
///
/// A bare key, a basic string, a literal string, and a dotted key that
/// puts the profile name on the key side where a section-matching scan
/// never looks. Four of those five defeated the first version, and each
/// leaves the debug step in `ci.yml` present, running, green and blind
/// -- the exact state the guard exists to refuse.
///
/// So the section and the key are joined into one path and normalised
/// per segment, and the comparison is against the whole thing. That
/// covers the spellings above, a quoted *section* (`["profile"."test"]`),
/// and a fully top-level dotted key with no section at all.
///
/// Only `profile.dev` and `profile.test` count. `cargo test` builds the
/// `test` profile, which inherits from `dev`, so either can disable the
/// checks in one line. `profile.release` is deliberately absent: the
/// checks are off there by default, that is what ships, and the release
/// steps exist to test what ships.
fn profiles_disabling_overflow_checks(manifest: &str) -> Vec<String> {
    /// Split a dotted TOML path and strip each segment's quoting, so
    /// that `"profile" . 'test'` and `profile.test` are one path.
    fn normalise(path: &str) -> String {
        path.split('.')
            .map(|segment| {
                segment
                    .trim()
                    .trim_matches(|c| c == '"' || c == '\'')
                    .trim()
            })
            .collect::<Vec<_>>()
            .join(".")
    }

    const DISABLED: [&str; 2] = [
        "profile.dev.overflow-checks",
        "profile.test.overflow-checks",
    ];

    let mut section = String::new();
    let mut found = Vec::new();
    for raw in manifest.lines() {
        let line = raw.split('#').next().unwrap_or(raw).trim();
        if line.starts_with('[') {
            section = normalise(line.trim_matches(|c| c == '[' || c == ']'));
            continue;
        }
        let Some((key, value)) = line.split_once('=') else {
            continue;
        };
        if value.trim() != "false" {
            continue;
        }
        let key = normalise(key);
        let path = if section.is_empty() {
            key
        } else {
            format!("{section}.{key}")
        };
        if DISABLED.contains(&path.as_str()) {
            found.push(path);
        }
    }
    found
}

/// The half of the property the workflow scans cannot see.
///
/// A debug step in `ci.yml` only buys anything while the profile it
/// builds actually checks. One line -- `overflow-checks = false` under
/// `[profile.test]`, or under this repository's existing
/// `[profile.dev]`, a plausible way to make a slow suite faster --
/// would leave that step present, running, green, and no longer able to
/// observe an overflow, with every workflow assertion above still
/// passing. A guard for half a condition is the defect it was written
/// to prevent.
///
/// The runtime probe in `src/lib.rs` would also catch this. This scan
/// is kept as defence in depth: it fails earlier in the gate and names
/// the offending manifest key, which is a better diagnostic than "the
/// build did not trap".
#[test]
fn the_profile_that_cargo_test_builds_still_checks_for_overflow() {
    let path = manifest_dir().join("Cargo.toml");
    let manifest = read_or_panic(&path);

    let disabled = profiles_disabling_overflow_checks(&manifest);
    assert!(
        disabled.is_empty(),
        "{} sets `overflow-checks = false` under {disabled:?}. `cargo test` \
         builds the `test` profile, which inherits from `dev`, so this \
         switches off the check that the debug step in ci.yml exists to run \
         -- leaving that step present, green, and blind. Put it back, or the \
         debug step is costing a compile and buying nothing.",
        path.display()
    );
}

/// The shell scanner is the part of this that can rot, so it is checked
/// against each shape it has to tell apart.
///
/// Its argument is the shell text of one step's `run:`, not YAML. What
/// used to be tested here as YAML -- a debug command quoted in a `#`
/// line of the workflow -- moved to `gating`, because the parser now
/// answers it by construction and this function never sees it.
mod shell_scan {
    use super::runs_with_overflow_checks;

    /// Whether a line's `cargo test` selects something other than the
    /// library unit tests. A line-level wrapper so these tests read as
    /// shell, the way the workflow does.
    fn selects_away_from_the_library(line: &str) -> bool {
        super::shell_commands(line)
            .iter()
            .filter_map(|(words, _)| super::cargo_test_arguments(words))
            .any(|arguments| super::omits_the_library_unit_tests(&arguments))
    }

    /// A LINE THAT PRINTS THE COMMAND IS NOT A RUN.
    ///
    /// The scan asked whether the line CONTAINED "cargo test", so this
    /// one satisfied both of the file's workflow assertions with
    /// nothing behind them: the debug run and, because the same
    /// characters carry `EXPECT_OVERFLOW_CHECKS=1`, the handshake too.
    #[test]
    fn an_echoed_command_is_not_a_run() {
        for line in [
            "echo \"EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\"",
            "echo 'cargo test --locked --all-targets'",
            "echo cargo test --locked --lib",
            "printf '%s\\n' \"cargo test --locked --lib\"",
            "echo \"running: cargo test\" && cargo build --locked",
        ] {
            assert_eq!(
                runs_with_overflow_checks(line),
                Vec::<String>::new(),
                "{line} prints the command; it does not run it"
            );
        }
    }

    /// THE ACCEPTANCE HALF OF THE SAME CHANGE.
    ///
    /// Recognising the invocation rather than the substring must not
    /// cost the spellings a real workflow uses. Each of these DOES
    /// run the suite in debug and each must still be counted --
    /// including the two where `cargo` is not the first word on the
    /// line.
    #[test]
    fn the_spellings_that_do_invoke_cargo_test_still_count() {
        for line in [
            "cargo test --locked --all-targets",
            "EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib",
            "cd .. && cargo test --locked --lib",
            "cargo test --locked --lib 2>&1",
            "cargo test --locked --lib > test.log",
            "cargo +stable test --locked --lib",
            "env EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib",
        ] {
            assert_eq!(
                runs_with_overflow_checks(line).len(),
                1,
                "{line} runs the suite in debug and must be counted"
            );
        }
    }

    /// The trap this repository actually contains, in the form that
    /// still reaches this function. `ci.yml` documents the debug step
    /// by quoting the command, and a `run: |` block can carry the same
    /// habit in shell comments, where the text survives the command's
    /// deletion.
    #[test]
    fn a_debug_run_quoted_in_a_shell_comment_does_not_count() {
        let block = "\
set -euo pipefail
# Measured on this branch:
#     cargo test --locked --release --lib   ->  EXIT=0
#     EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib   ->  EXIT=101
cargo test --locked --release
";
        assert_eq!(
            runs_with_overflow_checks(block),
            Vec::<String>::new(),
            "a debug command quoted inside a comment is documentation, not a run"
        );
    }

    #[test]
    fn a_real_debug_run_counts() {
        let block = "\
cargo test --locked --release
EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib
";
        assert_eq!(
            runs_with_overflow_checks(block),
            vec!["EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib".to_string()],
        );
    }

    /// A command that is `--release` but which carries a trailing
    /// comment mentioning the debug run.
    #[test]
    fn a_trailing_comment_does_not_promote_a_release_run() {
        let inline = "cargo test --locked --release  # not cargo test --lib\n";
        assert_eq!(
            runs_with_overflow_checks(inline),
            Vec::<String>::new(),
            "the command is --release; the comment after it is not a second run"
        );
    }

    /// A `#` THAT DOES NOT BEGIN A WORD IS NOT A COMMENT.
    ///
    /// The acceptance half of widening the comment rule from `" #"` to
    /// the separator alphabet: a `#` inside a word, or inside quotes,
    /// is data. Cutting there would truncate a real command and the
    /// guard would refuse a correct workflow.
    #[test]
    fn a_hash_that_does_not_begin_a_word_is_not_a_comment() {
        for line in [
            "cargo test --locked --features a#b --all-targets",
            "cargo test --locked --all-targets && echo \"done #1\"",
        ] {
            assert_eq!(
                runs_with_overflow_checks(line).len(),
                1,
                "{line:?} has no comment on it: the `#` is inside a word or a quoted span"
            );
        }
    }

    /// THE QUOTE TRACKING IN `comment_start`, WHICH NOTHING ELSE PINS.
    ///
    /// `a_hash_that_does_not_begin_a_word_is_not_a_comment` looks like
    /// it covers this and does not: its quoted `#` sits AFTER the
    /// `cargo test`, so cutting the line there still leaves the
    /// invocation behind and the guard still counts it. The mechanism
    /// survived deletion with every other test green.
    ///
    /// The witnessing input has to put the quoted `#` FIRST, so that
    /// treating it as a comment removes the run:
    ///
    ///     echo "step # 1"; cargo test --locked --all-targets
    ///
    /// Without quote tracking the line is cut to `echo "step`, no
    /// `cargo test` remains, and the guard REFUSES A CORRECT WORKFLOW.
    /// That is the direction this one guards -- a false rejection, not
    /// a false pass.
    ///
    /// It is asserted here rather than as a workflow because YAML ends
    /// a plain scalar at ` #` itself, so the same line written as
    /// `run: echo "step # 1"; ...` is refused before this function ever
    /// sees it -- a different defect, and an easy way to measure the
    /// wrong thing. Only a block scalar reaches here intact, and at
    /// that point the shell text is what is under test.
    #[test]
    fn a_quoted_hash_before_the_run_does_not_cut_the_line_short() {
        for line in [
            "echo \"step # 1\"; cargo test --locked --all-targets",
            "echo 'step # 1' && cargo test --locked --all-targets",
            "printf '%s\\n' \"# not a comment\"; cargo test --locked --lib",
        ] {
            assert_eq!(
                runs_with_overflow_checks(line).len(),
                1,
                "{line:?} runs the suite: the `#` is inside quotes and ends nothing"
            );
        }
    }

    /// The inline-comment strip, which nothing else here pins. A real
    /// debug run whose trailing comment happens to contain `--release`
    /// must still be counted. Without the strip that word disqualifies
    /// the command, and the guard then fails insisting there is no
    /// debug run while one is sitting in front of it.
    #[test]
    fn a_trailing_comment_naming_release_does_not_disqualify_a_debug_run() {
        let line = "cargo test --locked --lib  # deliberately not --release\n";
        assert_eq!(
            runs_with_overflow_checks(line),
            vec!["cargo test --locked --lib".to_string()],
            "the command is a debug run; --release appears only in its comment"
        );
    }

    /// `-r` IS `--release`, IN EVERY SPELLING CLAP ACCEPTS (#120). Each of
    /// these compiles with overflow checks off and counted as the debug
    /// run; the controls beside them are not release and still count.
    #[test]
    fn the_short_release_flag_does_not_count_in_any_spelling() {
        for line in [
            "cargo test --locked -r --all-targets",
            "cargo test --locked -qr --all-targets",
            "cargo test --locked -rq --all-targets",
            "cargo test --locked -j4 -r",
            "cargo test --locked -j 4 -r --lib",
            "cargo test --locked --features x -r",
        ] {
            assert_eq!(
                runs_with_overflow_checks(line),
                Vec::<String>::new(),
                "{line} builds the release profile"
            );
        }
        for line in [
            "cargo test --locked --all-targets -- -r",
            "cargo test --locked --features r",
            "cargo test --locked -F r",
            "cargo test --locked -pr --lib",
            "cargo test --locked -j r --lib",
        ] {
            assert_eq!(
                runs_with_overflow_checks(line).len(),
                1,
                "{line}: the r is a value or the harness's, and the run is debug"
            );
        }
    }

    /// The ways a run can carry no `--release` and still be built
    /// without the checks.
    #[test]
    fn a_profile_named_another_way_does_not_count() {
        let lines = [
            "cargo test --locked --profile release-with-debug --lib",
            "CARGO_PROFILE_TEST_OVERFLOW_CHECKS=false cargo test --locked --lib",
            "CARGO_PROFILE_DEV_OVERFLOW_CHECKS=false cargo test --locked --lib",
        ];
        for line in lines {
            assert_eq!(
                runs_with_overflow_checks(line),
                Vec::<String>::new(),
                "{line} does not compile the overflow checks"
            );
        }
        assert_eq!(
            lines.len(),
            3,
            "the loop above must have examined every shape"
        );
    }

    /// `cargo build` is not `cargo test`. A workflow that builds a
    /// binary and then exercises it with external tooling runs no test
    /// suite, and a scanner that counted `cargo build --release` would
    /// be looking at the wrong steps entirely.
    #[test]
    fn a_cargo_build_step_is_not_a_test_run() {
        let validate_job = "\
cargo build --locked --release
./target/release/some-tool --check /tmp/image
";
        assert_eq!(
            runs_with_overflow_checks(validate_job),
            Vec::<String>::new(),
            "building a binary is not running a test suite"
        );
    }

    /// A COMMAND WHOSE FAILURE IS DISCARDED IS NOT A GATE.
    ///
    /// Nothing here looked at status handling, so a debug run with its
    /// exit status thrown away was matched, counted as gating, and
    /// gated nothing -- the job goes green with the probe failing.
    /// This file already enumerates the same defect at two levels, a
    /// step's `if:`/`continue-on-error:` and a job's; suppression
    /// inside the command is the third.
    ///
    /// The pipe is the one worth reading twice. Actions runs a `run:`
    /// block as `bash -e` with no `pipefail`, so the line's status is
    /// the LAST stage's -- `tee` always succeeds.
    #[test]
    fn a_run_whose_status_is_discarded_does_not_count() {
        for line in [
            "cargo test --locked --all-targets || true",
            "cargo test --locked --all-targets || echo 'ignored'",
            "cargo test --locked --all-targets | tee test.log",
            "cargo test --locked --all-targets &",
            "set +e\ncargo test --locked --all-targets\n",
            "set +o errexit\ncargo test --locked --all-targets\n",
            "set +ex\ncargo test --locked --all-targets\n",
            // The option name with the next command's punctuation
            // glued to it. `split_whitespace` produced `errexit;`,
            // which is not `errexit`, so the withdrawal was invisible
            // and everything after it was counted as gating.
            "set +o errexit; cargo test --locked --all-targets\n",
            "set +o errexit&& cargo test --locked --all-targets\n",
            "set +o errexit\ncargo test --locked --all-targets | tee log\n",
        ] {
            assert_eq!(
                runs_with_overflow_checks(line),
                Vec::<String>::new(),
                "{line:?} runs the suite and throws the answer away"
            );
        }
    }

    /// THE ACCEPTANCE HALF OF THE STATUS RULE.
    ///
    /// `&&` propagates a failure, `set -e` is the default rather than
    /// something to opt into, and a redirection is not a separator --
    /// the `&` in `2>&1` binds to the `>` before it. A status rule that
    /// refused these would refuse most real workflows.
    #[test]
    fn a_run_whose_failure_still_ends_the_step_counts() {
        for line in [
            "cargo test --locked --all-targets",
            "cargo test --locked --all-targets && echo ok",
            "cd .. && cargo test --locked --all-targets && echo ok",
            "cargo test --locked --all-targets 2>&1",
            // `;` is NOT a discard under `bash -e`: the shell aborts
            // before the next command runs. Measured, and the reason
            // the first version of this rule was wrong.
            "cargo test --locked --all-targets; echo done",
            "cargo test --locked --all-targets ; true",
            "set -euo pipefail\ncargo test --locked --all-targets\n",
            // THE ACCEPTANCE HALF OF THE GLUED-PUNCTUATION RULE.
            // `-o errexit` turns the option ON, and a `set +o errexit`
            // that is only PRINTED withdraws nothing -- the tokenizer
            // drops what is inside quotes, so the word is `echo`.
            "set -o errexit; cargo test --locked --all-targets\n",
            "echo \"set +o errexit\"\ncargo test --locked --all-targets\n",
        ] {
            assert_eq!(
                runs_with_overflow_checks(line).len(),
                1,
                "{line:?} fails the step when the suite fails"
            );
        }
    }

    /// SELECTIONS THAT BUILD OR RUN SOMETHING OTHER THAN THE LIBRARY.
    ///
    /// `--doc`, `--no-run` and a bare filter each leave the overflow
    /// probe unbuilt or unrun while the old scan counted the line as
    /// the required debug suite. `--no-run` is the starkest: it
    /// compiles and executes nothing.
    #[test]
    fn a_selection_that_leaves_the_library_unit_tests_out_does_not_count() {
        for line in [
            "cargo test --locked --doc",
            "cargo test --locked --no-run",
            "cargo test --locked --bins",
            "cargo test --locked --examples",
            "cargo test --locked --bin some_tool",
            "cargo test --locked --example inspect",
            "cargo test --locked some_filter",
            "EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --features qemu-validation qemu",
        ] {
            assert!(
                selects_away_from_the_library(line),
                "{line} selects something other than the library unit tests"
            );
            assert_eq!(
                runs_with_overflow_checks(line),
                Vec::<String>::new(),
                "{line} does not build and run the library unit tests"
            );
        }
    }

    /// BOTH SPELLINGS OF `--test` ARE THE SAME OPTION.
    ///
    /// The scan matched the substring `"--test "`, so the `=` form was
    /// invisible: a cross-validation job building one integration
    /// target counted as a full debug run, and the real one could then
    /// be deleted with this guard still green. Nothing noticed because
    /// every such job here is written the long way today; the guard is
    /// what stops the short way from being silently equivalent.
    #[test]
    fn an_equals_spelled_single_target_does_not_count_either() {
        for line in [
            "cargo test --locked --features qemu-validation --test=qemu_validation",
            "EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --test=some_oracle",
            "cargo test --locked --test=\"qemu_validation\"",
        ] {
            assert_eq!(
                runs_with_overflow_checks(line),
                Vec::<String>::new(),
                "{line} builds one integration target and no library unit tests"
            );
            assert!(
                selects_away_from_the_library(line),
                "{line} names a single integration target"
            );
        }
    }

    /// The acceptance half: options that merely START with `--test`
    /// are not the option, and every one of these builds the library
    /// unit tests.
    #[test]
    fn options_that_only_look_like_test_do_not_disqualify_a_run() {
        for line in [
            "cargo test --locked --tests",
            "cargo test --locked --all-targets",
            "cargo test --locked --lib -- --test-threads=1",
        ] {
            assert!(
                !selects_away_from_the_library(line),
                "{line} does not restrict the run to one integration target"
            );
            assert_eq!(
                runs_with_overflow_checks(line).len(),
                1,
                "{line} builds the library unit tests and must be counted"
            );
        }
    }

    /// A FILTER AFTER `--` NARROWS THE RUN AS MUCH AS ONE BEFORE IT.
    ///
    /// The selection walk stopped at `--`, on the reasoning that what
    /// follows belongs to the test harness and selects no target. True,
    /// and beside the point: the harness still takes a bare word as a
    /// test-name filter, so `-- nonexistent_filter` builds the library,
    /// runs ZERO tests, exits 0, and counted as the required debug run.
    /// `--ignored` and `--list` are the same bypass without a filter:
    /// the first runs only `#[ignore]` tests, the second runs nothing.
    /// Measured against this very test binary: each shape below exits 0
    /// having run no test at all (`--list` only prints the names), bar
    /// `--skip`, which drops every test whose name contains its word and
    /// so can drop the probe.
    #[test]
    fn a_harness_filter_after_the_separator_does_not_count() {
        let lines = [
            "cargo test --locked --lib -- nonexistent_filter",
            "cargo test --locked --all-targets -- some::module",
            "cargo test --locked --lib -- --exact some::test",
            "cargo test --locked --lib -- --test-threads 1 some_filter",
            "cargo test --locked --lib -- --skip overflow_checks",
            "cargo test --locked --lib -- --ignored",
            "cargo test --locked --lib -- --list",
            "cargo test --locked --lib -- -- --nocapture",
        ];
        for line in lines {
            assert_eq!(
                runs_with_overflow_checks(line),
                Vec::<String>::new(),
                "harness_filter_after_separator: {line} narrows the harness run, so the \
                 overflow probe may never execute"
            );
            assert!(
                selects_away_from_the_library(line),
                "harness_filter_after_separator: {line} narrows what the harness runs"
            );
        }
        assert_eq!(lines.len(), 8, "every shape above must have been examined");
    }

    /// THE ACCEPTANCE HALF: harness options that run every test, and
    /// the values of the ones that take a separate value, are not
    /// filters.
    #[test]
    fn harness_options_that_run_every_test_still_count() {
        for line in [
            "cargo test --locked --lib -- --test-threads=1",
            "cargo test --locked --lib -- --test-threads 1",
            "cargo test --locked --all-targets -- --nocapture",
            "cargo test --locked --all-targets -- --include-ignored",
            "cargo test --locked --lib -- --show-output --color always",
            "cargo test --locked --lib -- --format terse --logfile test.log",
            "cargo test --locked --lib --",
        ] {
            assert!(
                !selects_away_from_the_library(line),
                "{line} runs every library unit test"
            );
            assert_eq!(
                runs_with_overflow_checks(line).len(),
                1,
                "{line} runs every library unit test and must be counted"
            );
        }
    }

    /// A LINE ENDING IN A BACKSLASH CONTINUES ONTO THE NEXT.
    ///
    /// `command_lines` split on physical lines, so an `&&` list wrapped
    /// with `\` read as a list followed by ANOTHER command on the next
    /// line -- which is the swallowed shape -- and a correct gate was
    /// refused. Measured: `bash -e -c $'false && \\\necho done'` exits 1.
    #[test]
    fn a_continued_line_is_one_command() {
        for script in [
            "cargo test --locked --all-targets && \\\necho done\n",
            "cargo test --locked \\\n  --all-targets\n",
            "cd .. && \\\n  cargo test --locked --lib && \\\n  echo ok\n",
            // A trailing `&&` continues the list with no backslash.
            // Measured: `bash -e -c $'false &&\\necho done'` exits 1.
            "cargo test --locked --all-targets &&\necho done\n",
        ] {
            assert_eq!(
                runs_with_overflow_checks(script).len(),
                1,
                "{script:?} is one logical command whose failure ends the step"
            );
        }
        // CONTROLS. An escaped backslash does not continue the line,
        // and neither does one inside a comment, so each of these still
        // puts a separate command after the `&&` list.
        for script in [
            "cargo test --locked --lib && echo a\\\\\necho b\n",
            "cargo test --locked --lib && echo a # \\\necho b\n",
            "cargo test --locked --all-targets && \\\necho done\necho after\n",
            "cargo test --locked --all-targets &&\necho done\necho after\n",
        ] {
            assert_eq!(
                runs_with_overflow_checks(script),
                Vec::<String>::new(),
                "{script:?}: the && list is followed by another command, so its status is replaced"
            );
        }
    }

    /// `set +e` WITHDRAWS `errexit` FROM WHAT FOLLOWS IT, NOT FROM WHAT
    /// ALREADY RAN. A failing run before it has already ended the step:
    /// `bash -e -c $'false\nset +e'` exits 1.
    #[test]
    fn set_plus_e_after_the_run_does_not_disqualify_it() {
        for script in [
            "cargo test --locked --all-targets\nset +e\necho cleanup\n",
            "cargo test --locked --lib; set +e\n",
            "cargo test --locked --lib\nset +o errexit\n",
        ] {
            assert_eq!(
                runs_with_overflow_checks(script).len(),
                1,
                "{script:?}: the suite ran under errexit"
            );
        }
        // And before it, still refused.
        assert_eq!(
            runs_with_overflow_checks("echo x\nset +e\ncargo test --locked --lib\n"),
            Vec::<String>::new(),
        );
    }

    /// A single integration target is not the crate's arithmetic.
    /// Several repositories here run a cross-validation suite as
    /// `--test <name>` in its own job, and counting it would let the
    /// real debug run be deleted with the guard still green.
    #[test]
    fn a_single_integration_target_does_not_count() {
        for line in [
            "cargo test --locked --features qemu-validation --test qemu_validation",
            "EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --test some_oracle",
        ] {
            assert_eq!(
                runs_with_overflow_checks(line),
                Vec::<String>::new(),
                "{line} builds one integration target and no library unit tests"
            );
        }
    }

    /// A COMMAND SUBSTITUTION SWALLOWS ITS COMMAND'S STATUS.
    ///
    /// `(` and `)` fell into the separator arm and became `Sep::Semi`,
    /// so `echo $(cargo test --locked --lib)` parsed as three commands
    /// with the inner one looking status-read. Measured:
    /// `bash -e -c 'echo $(false); echo R'` exits 0 and prints R.
    /// WHERE A SUBSTITUTION ENDS IS SHELL PARSING, NOT A PAREN COUNT.
    ///
    /// The scanner counted bare parentheses, so a `)` that the shell
    /// treats as DATA ended the span early and tokenising resumed
    /// inside a span the shell had not left. Every verdict below is
    /// `bash -e -c` on that exact line, taken from bash rather than
    /// from this file; `exit 0` means the status was swallowed, so the
    /// suite is not a gate and must not be counted.
    ///
    /// | line | bash | must |
    /// |---|---|---|
    /// | `cat <(echo a\) ; false)` | 0 | not count |
    /// | `cat <(echo "a)" ; false)` | 0 | not count |
    /// | `cat <(echo 'a\)' ; false)` | 0 | not count |
    /// | `` echo `echo a\` ; false` `` | 0 | not count |
    /// | `cat <(echo "a)") ; false` | 1 | **count** |
    /// | `cat <(echo 'a)') ; false` | 1 | **count** |
    /// | `cat <(echo a\\) ; false` | 1 | **count** |
    /// A NESTED SPAN'S PARENTHESES ARE ITS OWN — BACKTICKS.
    ///
    /// `end_of_substitution` tracked quotes and escapes and not nested
    /// spans, so a `)` inside a nested backtick span closed the outer
    /// `$( )` early; the unmatched backtick then ate the rest of the
    /// line and a real gate was DROPPED. `bash -e -c` on the exact
    /// line, `false` versus `true` for the suite: exits 1 and 0, so the
    /// trailing status is read and this must COUNT.
    #[test]
    fn a_nested_backtick_does_not_close_the_outer_substitution() {
        let line = "echo $(echo `echo x)`) ; cargo test --locked --lib";
        assert_eq!(
            runs_with_overflow_checks(line),
            vec![line.to_string()],
            "{line}: the `)` is inside a nested backtick span, so the substitution runs on \
             and the cargo test after it is top-level"
        );
    }

    /// THE SAME, FOR `${{...}}`, AND IT FAILS THE OTHER WAY.
    ///
    /// A `)` inside a brace expansion closed the outer substitution
    /// early, so a suite that bash keeps INSIDE the substitution read
    /// as top-level and a swallowed run was COUNTED. Measured:
    /// `bash -e -c 'x=1; $(echo ${{x:+)}} ; false)'` and the same with
    /// `true` both exit 0 — the inner status never reaches the line.
    #[test]
    fn a_brace_expansion_does_not_close_the_outer_substitution() {
        assert_eq!(
            runs_with_overflow_checks("$(echo ${x:+)} ; cargo test --locked --lib)"),
            Vec::<String>::new(),
            "the whole thing is inside `$( )`; the `)` belongs to the brace expansion"
        );
        // ACCEPTANCE: the same brace expansion with the suite OUTSIDE
        // the substitution is a real gate and must still count.
        let line = "echo $(echo ${x:+)}) ; cargo test --locked --lib";
        assert_eq!(
            runs_with_overflow_checks(line),
            vec![line.to_string()],
            "{line}: the substitution closes and the cargo test after it is top-level"
        );
        // AND THE MAIN TOKENISER SKIPS IT TOO, which is a second site
        // for the same rule. `$` and `{` were ordinary word characters
        // there, so this `)` became a separator, the `&&` chain stopped
        // ending the step, and the suite's failure read as swallowed.
        let line = "cargo test --locked --lib && echo ${x:+)}";
        assert_eq!(
            runs_with_overflow_checks(line),
            vec![line.to_string()],
            "{line}: the `)` belongs to the expansion, so the && list still ends the step"
        );

        // A LITERAL BRACE IS NOT AN EXPANSION LEVEL. `${x:-$(echo {)}`
        // expands to `{` -- the brace is an ordinary argument
        // character inside a command substitution. Counting it as a
        // level left the span unterminated, `shell_commands` dropped
        // the rest of the line, and the `&&` chain looked as though it
        // ended the step. `bash -e -c 'x=1; false && echo
        // ${x:-$(echo {)} ; true'` exits 0, and so does the `true`
        // spelling: the `; true` swallows the suite's failure, so this
        // must NOT count.
        assert_eq!(
            runs_with_overflow_checks("cargo test --locked --lib && echo ${x:-$(echo {)} ; true"),
            Vec::<String>::new(),
            "the `; true` swallows the failure; the brace inside the substitution is data"
        );
        // ACCEPTANCE: the same expansion with the chain really ending
        // the step is a gate. `false && echo ${x:-$(echo {)}` exits 1
        // and the `true` spelling 0.
        let line = "cargo test --locked --lib && echo ${x:-$(echo {)}";
        assert_eq!(
            runs_with_overflow_checks(line),
            vec![line.to_string()],
            "{line}: the && chain ends the step, so the suite's failure is read"
        );
        // EVERY NESTED SHAPE THAT CARRIES A BRACE, each measured with
        // `bash -e -c` in both spellings and each SWALLOWED by the
        // `; true`, so none may count. Three arms of the fix are held
        // by exactly one of these:
        //
        //   ${x:-{}              a literal `{` directly in the
        //                        expansion; expands to `{`
        //   ${x:-$(echo })}      a `}` inside a nested substitution;
        //                        expands to `}`
        //   ${x:-`echo }`}       a `}` inside nested backticks;
        //                        expands to `}`
        //   ${x:-$(echo ${y})}   an expansion inside a substitution
        //                        inside an expansion; expands to `q`
        for expansion in [
            "${x:-{}",
            "${x:-$(echo })}",
            "${x:-`echo }`}",
            "${x:-$(echo ${y})}",
        ] {
            let line = format!("cargo test --locked --lib && echo {expansion} ; true");
            assert_eq!(
                runs_with_overflow_checks(&line),
                Vec::<String>::new(),
                "{line}: the `; true` swallows the failure, so this is not the gate"
            );
        }

        // AND THE ACCEPTANCE SIDE OF THE SAME NESTING, which is what
        // holds the substitution skip specifically. Ending the span
        // early at the `}` inside `$( )` leaves a stray `)` that reads
        // as a separator, so the `&&` chain stops ending the step and a
        // real gate is dropped. `bash -e -c 'x=; false && echo
        // "${x:-$(echo })}"'` exits 1 and the `true` spelling 0.
        for expansion in ["${x:-$(echo })}", "${x:-$(echo ${y})}"] {
            let line = format!("cargo test --locked --lib && echo {expansion}");
            assert_eq!(
                runs_with_overflow_checks(&line),
                vec![line.clone()],
                "{line}: the && chain ends the step, so the suite's failure is read"
            );
        }

        // And a literal brace in a bare substitution, no expansion at
        // all, which is the same character in the simpler position.
        assert_eq!(
            runs_with_overflow_checks("cargo test --locked --lib && echo $(echo {) ; true"),
            Vec::<String>::new(),
            "a literal brace in a substitution does not change where the line ends"
        );

        // AND THEY NEST. `${x:-${y}z)}` expands to `qz)` in bash, so
        // the `)` is the expansion's, and a scanner that stopped at the
        // INNER `}` would resume at `z)}` and take that `)` for a
        // separator -- which ends the `&&` chain early and drops a real
        // gate. Measured: `bash -e -c 'y=q; false && echo ${x:-${y}z)}'`
        // exits 1 and the `true` spelling exits 0.
        let line = "cargo test --locked --lib && echo ${x:-${y}z)}";
        assert_eq!(
            runs_with_overflow_checks(line),
            vec![line.to_string()],
            "{line}: the nested expansion owns both braces and the `)`, so the && list              still ends the step"
        );
        assert_eq!(
            runs_with_overflow_checks("$(echo ${x:-${y:+)}} ; cargo test --locked --lib)"),
            Vec::<String>::new(),
            "a nested brace expansion's braces are its own inside a substitution too"
        );
    }

    #[test]
    fn a_paren_the_shell_reads_as_data_does_not_end_a_substitution() {
        for line in [
            // THE FILED DEFECT, and it is the false-pass direction: the
            // escaped `)` looked like the close, so the `cargo test`
            // after it parsed as a top-level command whose status is
            // read -- while bash keeps it inside the substitution and
            // throws its status away.
            "cat <(echo a\\) ; cargo test --locked --lib)",
            // The same cause quoted. Correct today only by accident:
            // the stray `\"` happened to swallow the rest of the line.
            "cat <(echo \"a)\" ; cargo test --locked --lib)",
            // Inside `'` a backslash is DATA, so `\\)` does not even
            // escape -- the `)` is quoted and the span runs on.
            "cat <(echo 'a\\)' ; cargo test --locked --lib)",
            // `$( )` is the same span with a different opener.
            "echo $(echo a\\) ; cargo test --locked --lib)",
            "echo $(echo \"a)\" ; cargo test --locked --lib)",
            // And the same `'a\'` shape with the suite INSIDE: bash
            // closes the quote, so the cargo test is still in the
            // substitution. `exit 0`, measured.
            "cat <(echo 'a\\' ; cargo test --locked --lib)",
        ] {
            assert_eq!(
                runs_with_overflow_checks(line),
                Vec::<String>::new(),
                "{line}: bash keeps the cargo test inside the substitution and discards \
                 its status, so counting it would count a probe that does not gate the step"
            );
        }
    }

    /// A BACKSLASH EXTENDS A BACKTICK SPAN TOO, and this one was not in
    /// the report -- the backtick skip had the identical blindness and
    /// the identical false-pass direction. Measured:
    /// `bash -e -c 'echo `echo a\` ; false`'` exits 0.
    #[test]
    fn an_escaped_backtick_does_not_end_a_backtick_substitution() {
        let line = "echo `echo a\\` ; cargo test --locked --lib`";
        assert_eq!(
            runs_with_overflow_checks(line),
            Vec::<String>::new(),
            "{line}: the escaped backtick keeps the cargo test inside the substitution"
        );
    }

    /// THE ACCEPTANCE HALF, AND IT IS THE HALF A `\)` SPECIAL CASE
    /// WOULD HAVE LEFT BROKEN.
    ///
    /// These three end their substitution properly and leave a real
    /// top-level `cargo test` whose failure DOES end the step. A
    /// scanner that mis-closes early makes the guard refuse a correct
    /// workflow, which is the direction this file's own history warns
    /// about and the direction the quoted spelling actually failed in.
    #[test]
    fn a_substitution_that_really_closes_still_leaves_a_gate() {
        for line in [
            // Was refused before this change: the scanner closed at the
            // quoted `)` and the leftover `"` ate the rest of the line.
            "cat <(echo \"a)\") ; cargo test --locked --lib",
            "cat <(echo 'a)') ; cargo test --locked --lib",
            // `\\` is an escaped BACKSLASH, so the `)` after it really
            // is the close. A scanner that skipped one character per
            // backslash instead of two would get this backwards.
            "cat <(echo a\\\\) ; cargo test --locked --lib",
            // INSIDE `'` A BACKSLASH IS DATA, so `'a\'` is the
            // literal `a\` and the quote CLOSES at the second `'`.
            // Treating `'` the way `"` is treated makes the `\'` an
            // escape, the quote never closes, no `)` is ever found, and
            // this real gate is silently dropped. `bash -e -c
            // "cat <(echo 'a\\') ; false"` exits 1 -- it is read.
            "cat <(echo 'a\\') ; cargo test --locked --lib",
            // The plain control, unchanged by any of this.
            "cat <(echo a) ; cargo test --locked --lib",
        ] {
            assert_eq!(
                runs_with_overflow_checks(line),
                vec![line.to_string()],
                "{line}: the substitution closes and the cargo test after it is top-level, \
                 so its failure ends the step and it must still count"
            );
        }
    }

    #[test]
    fn a_cargo_test_inside_a_command_substitution_is_not_a_gate() {
        for line in [
            "echo $(cargo test --locked --lib)",
            // `OUT=$(cargo test ...)` used to be listed here. It is the
            // one shape that DOES read the status -- see
            // `a_substitution_that_is_the_whole_command_is_a_gate`.
            "echo `cargo test --locked --lib`",
            "echo \"result: $(cargo test --locked --all-targets)\"",
            // PROCESS SUBSTITUTION IS THE SAME SWALLOWING. `<( … )`
            // hands the command a file to read; only the command's own
            // status reaches the line. Measured, both directions:
            // `bash -e -c 'cat <(false)'` and
            // `bash -e -c 'echo x > >(false)'` each exit 0.
            "cat <(cargo test --locked --all-targets)",
            "diff <(cargo test --locked --lib) expected.txt",
            "echo x > >(cargo test --locked --all-targets)",
        ] {
            assert_eq!(
                runs_with_overflow_checks(line),
                Vec::<String>::new(),
                "{line}: the substitution swallows the status, only the outer command's is read"
            );
        }
    }

    /// A RUN THAT ITS OWN LIST CAN SKIP IS NOT A GATE.
    ///
    /// The status rule looked only at what FOLLOWS a `cargo test`, never
    /// at what precedes it, so a run the shell never starts was counted.
    /// Every verdict below is `bash -e -c` with `cargo` replaced by a
    /// function that records that it ran and returns 0 or 1:
    ///
    /// | line | exit (pass / fail) | ran |
    /// |---|---|---|
    /// | `true \|\| cargo test` | 0 / 0 | no |
    /// | `true \|\| echo x \| cargo test` | 0 / 0 | no |
    /// | `test -n "$CI" && cargo test` + `echo done` (CI unset) | 0 / 0 | no |
    /// | `test -n "$CI" && cargo test; echo done` (CI unset) | 0 / 0 | no |
    /// | `false \|\| false && cargo test` + `echo done` | 0 / 0 | no |
    ///
    /// `set -e` does not act on a failing command that is not the last
    /// in an `&&`/`||` list, so a skipped run leaves the step green
    /// unless the list's own status is the step's.
    #[test]
    fn a_run_that_its_list_can_skip_does_not_count() {
        let lines = [
            "true || cargo test --locked --lib",
            "true || echo x | cargo test --locked --lib",
            "test -n \"$CI\" && cargo test --locked --lib\necho done\n",
            "test -n \"$CI\" && cargo test --locked --lib; echo done",
            "false || false && cargo test --locked --lib\necho done\n",
            // Inside a substitution the same shapes, with no errexit
            // at all: `x=$(true || cargo test)` exits 0 and never runs.
            "x=$(true || cargo test --locked --lib)",
        ];
        for line in lines {
            assert_eq!(
                runs_with_overflow_checks(line),
                Vec::<String>::new(),
                "skippable_run: {line:?} -- the list can skip the cargo test and still \
                 leave the step green"
            );
        }
        assert_eq!(lines.len(), 6, "every shape above must have been examined");

        // DELIBERATELY REFUSED, and bash would gate each: a `||` whose
        // left side fails, and an `&&` condition that holds. Whether it
        // does is not in the text, and the spelling that holds on one
        // runner is the skipping one on another.
        for line in [
            "false || cargo test --locked --lib",
            "cd . && cargo test --locked --lib\necho done\n",
        ] {
            assert_eq!(
                runs_with_overflow_checks(line),
                Vec::<String>::new(),
                "over-strict on purpose: {line:?}"
            );
        }
    }

    /// THE ACCEPTANCE HALF: a condition whose failure IS the step's
    /// status, and separators that do not make the run conditional.
    /// `test -n "$CI" && cargo test` as the last line exits 1 when the
    /// run is skipped -- loud, not silent.
    #[test]
    fn a_run_its_list_cannot_skip_silently_still_counts() {
        for line in [
            "test -n \"$CI\" && cargo test --locked --lib",
            "cd .. && cargo test --locked --lib && echo ok",
            "false || true && cargo test --locked --lib",
            "echo x | cargo test --locked --lib",
            "sleep 0 & cargo test --locked --lib",
            "echo start; cargo test --locked --lib",
        ] {
            assert_eq!(
                runs_with_overflow_checks(line).len(),
                1,
                "{line:?}: a skipped run fails the step, or nothing can skip it"
            );
        }
    }

    /// A SUBSTITUTION THAT IS THE WHOLE COMMAND PASSES ITS STATUS ON.
    ///
    /// Bash: "if the command substitution is the only word, the exit
    /// status is that of the substitution" -- and for a command made
    /// only of assignments, the status is that of the LAST substitution
    /// performed. The scanner treated every substitution as swallowing,
    /// so each of these real gates was refused. Measured as above:
    /// each exits 0 when the run passes and 1 when it fails.
    ///
    /// Inside the substitution errexit is OFF (bash does not inherit
    /// it), so the run must be what decides the substitution's status:
    /// last in its list, not piped onward, not after `;`.
    #[test]
    fn a_substitution_that_is_the_whole_command_is_a_gate() {
        let lines = [
            "x=$(cargo test --locked --lib)",
            "OUT=$(cargo test --locked --lib)",
            "x=$(echo x | cargo test --locked --lib)",
            "x=`cargo test --locked --lib`",
            "x=$(cargo test --locked --lib && echo ok)",
            "x=$(true) y=$(cargo test --locked --lib)",
            "x=a$(cargo test --locked --lib)b",
            "x=$(y=$(cargo test --locked --lib))",
            "x=$(cargo test --locked --lib); echo after",
            "x=$((1+1)) y=$(cargo test --locked --lib)",
            "x=$(cargo test --locked --lib) y=$((1+1))",
            "x=$(cargo test --locked --lib) y=\"$((1+1))\"",
            "x=$(cargo test --locked --lib) y=\"a$((2*3))b\"",
            "x=$(cargo test --locked --lib) y=${z}",
            "x=$(cargo test --locked --lib) y=${z:-$((1+1))}",
            "x=$(cargo test --locked --lib;)",
        ];
        for line in lines {
            assert_eq!(
                runs_with_overflow_checks(line),
                vec![line.to_string()],
                "whole_command_substitution: {line:?} -- the substitution's status is the \
                 command's, so the cargo test inside it gates the step"
            );
        }
        assert_eq!(lines.len(), 16, "every shape above must have been examined");
    }

    /// AND THE SUBSTITUTIONS THAT DO SWALLOW IT, measured the same way:
    /// each exits 0 whether the run passes or fails (or, for `$(cargo
    /// test)` alone and `env x=$(...)`, exits 127 either way -- the
    /// run's own OUTPUT is executed as a command, so no status of the
    /// suite's reaches the step).
    #[test]
    fn a_substitution_that_is_not_the_whole_status_is_not_a_gate() {
        let lines = [
            "echo $(cargo test --locked --lib)",
            "$(cargo test --locked --lib)",
            "x=$(cargo test --locked --lib; true)",
            "x=$(cargo test --locked --lib | cat)",
            "x=$(cargo test --locked --lib) y=$(true)",
            "export x=$(cargo test --locked --lib)",
            "env x=$(cargo test --locked --lib)",
            "x=$(cargo test --locked --lib) true",
            "x=$(cargo test --locked --lib) y=${z:-$(true)}",
            // Arithmetic that runs a substitution: that one decides.
            "x=$(cargo test --locked --lib) y=\"$((1+$(true; echo 1)))\"",
            "x=$(cargo test --locked --lib) N=$(( $(true; printf 1) + 1))",
            "x=$(cargo test --locked --lib) y=$((1+`true; echo 1`))",
            "x=$(cargo test --locked --lib) y=\"$(true)\"",
            "x=$(cargo test --locked --lib) || true",
            "x=$(cargo test --locked --lib) && echo ok\necho after\n",
            "x=$(cargo test --locked --lib &)",
            "x=<(cargo test --locked --lib)",
        ];
        for line in lines {
            assert_eq!(
                runs_with_overflow_checks(line),
                Vec::<String>::new(),
                "{line:?}: the step's status does not depend on the suite's"
            );
        }
        assert_eq!(lines.len(), 17, "every shape above must have been examined");

        // DELIBERATELY REFUSED, each a gate in bash: a quoted
        // substitution, a bare one whose output is redirected away, and
        // a process substitution beside the gating one. Recognising them
        // means tracking quotes and output inside the span.
        for line in [
            "x=\"$(cargo test --locked --lib)\"",
            "$(cargo test --locked --lib > /dev/null)",
            "x=$(cargo test --locked --lib) y=<(true)",
        ] {
            assert_eq!(
                runs_with_overflow_checks(line),
                Vec::<String>::new(),
                "over-strict on purpose: {line:?}"
            );
        }
    }

    /// THE ACCEPTANCE HALF. A substitution in an ARGUMENT of a real run
    /// must not stop it counting -- that is the ordinary spelling for a
    /// thread count, and refusing it refuses a correct workflow.
    #[test]
    fn a_substitution_in_an_argument_leaves_the_run_counted() {
        assert_eq!(
            runs_with_overflow_checks("cargo test --locked --lib -- --test-threads=$(nproc)").len(),
            1,
            "the run is `cargo test`; the substitution is one of its arguments"
        );
        // A BARE SUBSHELL IS NOT A SUBSTITUTION. Its status is read, so
        // it keeps falling through to the separator arm.
        assert_eq!(
            runs_with_overflow_checks("cargo test --locked --lib").len(),
            1,
        );
    }

    /// A BACKSLASH-ESCAPED QUOTE DOES NOT CLOSE THE SPAN.
    ///
    /// The quoted-span rule was `if c == q { quote = None }` with no
    /// escape handling, so this split where the shell does not and the
    /// tail read as a command being run.
    #[test]
    fn an_escaped_quote_does_not_end_the_quoted_span() {
        for line in [
            "echo \"a \\\" && cargo test --locked --lib\"",
            "echo \"quoted \\\" cargo test --locked --all-targets\"",
        ] {
            assert_eq!(
                runs_with_overflow_checks(line),
                Vec::<String>::new(),
                "{line} is one `echo`; the escaped quote is data, not the end of the span"
            );
        }
        // In `'` there are no escapes, so a backslash is data and the
        // span still ends at the next `'`. Asserted so the conditional
        // is a decision rather than an oversight.
        assert_eq!(
            runs_with_overflow_checks("echo 'a \\' && cargo test --locked --lib").len(),
            1,
            "single quotes have no escapes: the span ends and a real run follows"
        );
    }

    /// AN `&&` LIST ONLY CARRIES ITS FAILURE IF IT ENDS THE LINE.
    ///
    /// Measured, because it is the opposite of what the shape suggests:
    ///
    ///     bash -e -c 'false && echo x'                exit 1
    ///     bash -e -c 'false && echo x; echo REACHED'  exit 0, prints
    ///
    /// `set -e` exempts a command inside an `&&` list, and the list's
    /// own failure does not abort either -- so whatever follows runs
    /// and its status becomes the line's. A gate written that way
    /// cannot fail.
    #[test]
    fn an_and_list_that_does_not_end_the_line_has_its_failure_swallowed() {
        for line in [
            "cargo test --locked --lib && echo ok; echo done",
            "cargo test --locked --all-targets && echo ok; ls",
            // A NEWLINE IS THE SPELLING A WORKFLOW ACTUALLY USES, and
            // the two above cannot reach it: both put the following
            // command on the same line, so "ends the line" was true
            // and the rule said read. Measured:
            // `bash -e -c $'false && echo x\necho R'` exits 0.
            "cargo test --locked --all-targets && echo done\necho \"second line\"\n",
            "cargo test --locked --lib && echo ok\ncargo build --locked\n",
        ] {
            assert_eq!(
                runs_with_overflow_checks(line),
                Vec::<String>::new(),
                "{line}: the && list is followed by another command, so its status is replaced"
            );
        }
    }

    /// THE ACCEPTANCE HALF, and it is the common spelling: an `&&` list
    /// that ends the line does carry the failure.
    #[test]
    fn an_and_list_that_ends_the_line_still_counts() {
        for line in [
            "cargo test --locked --lib && echo ok",
            "cargo test --locked --lib && echo ok && echo done",
            "cd .. && cargo test --locked --lib",
            // THE ACCEPTANCE HALF OF THE MULTI-LINE RULE. When the
            // chain IS the last line, its status is the step's, and a
            // fix that keyed on "is a multi-line block" rather than on
            // "is the last line" would refuse this.
            "set -euo pipefail\ncargo test --locked --all-targets && echo ok\n",
            "cd ..\ncargo test --locked --lib && echo ok\n",
        ] {
            assert_eq!(
                runs_with_overflow_checks(line).len(),
                1,
                "{line}: exit 1 propagates, measured with bash -e"
            );
        }
    }

    /// `set +o errexit` ON THE SAME LINE disqualifies the script, the
    /// long spelling as much as the short one. Pinned because it was
    /// raised as a possible hole and is not one.
    #[test]
    fn a_same_line_set_plus_e_still_disqualifies_the_script() {
        for line in [
            "set +o errexit; cargo test --locked --lib",
            "set +e; cargo test --locked --lib",
            "set +ex; cargo test --locked --lib",
        ] {
            assert_eq!(
                runs_with_overflow_checks(line),
                Vec::<String>::new(),
                "{line}: measured -- bash -e -c 'set +o errexit; false; echo R' exits 0"
            );
        }
    }

    /// AND THE DELIBERATE OVER-STRICTNESS BESIDE IT, stated as a test
    /// rather than as a comment.
    ///
    /// A script that turns `errexit` off and back on again is refused
    /// whole. Restoring it does make the later run gate again, so this
    /// refuses a workflow that would work — the file's declared
    /// direction, because tracking where the setting is live means
    /// tracking control flow. It fails loudly with the script quoted,
    /// which is the outcome this file prefers to a silent pass.
    #[test]
    fn errexit_restored_later_is_still_refused_and_that_is_deliberate() {
        let script = "set +e\nsomething || true\nset -e\ncargo test --locked --lib\n";
        assert_eq!(
            runs_with_overflow_checks(script),
            Vec::<String>::new(),
            "over-strict on purpose: the guard does not track where `set -e` is live"
        );
    }

    /// AND THE WITHDRAWALS ARE BELIEVED EVEN UNDER CONTROL FLOW, which
    /// refuses the skipped ones on purpose. See the comment in
    /// `debug_runs`: the conditional that runs on CI is the one that
    /// swallows the suite, and it cannot be told from the one that does
    /// not.
    #[test]
    fn a_withdrawal_under_control_flow_is_still_applied() {
        for script in [
            "[ -n \"$CI\" ] && set +e\ncargo test --locked --lib\n",
            "false && set +e\ncargo test --locked --lib\n",
            "(set +e)\ncargo test --locked --lib\n",
        ] {
            assert_eq!(
                runs_with_overflow_checks(script),
                Vec::<String>::new(),
                "over-strict on purpose: {script:?}"
            );
        }
        for script in [
            "export EXPECT_OVERFLOW_CHECKS=1\n[ -n \"$CI\" ] && unset EXPECT_OVERFLOW_CHECKS\ncargo test --locked --lib\n",
            "export EXPECT_OVERFLOW_CHECKS=1\nunset EXPECT_OVERFLOW_CHECKS | cat\ncargo test --locked --lib\n",
        ] {
            assert_eq!(
                super::debug_runs_that_prove_the_build_traps(script),
                Vec::<String>::new(),
                "over-strict on purpose: {script:?}"
            );
        }
    }

    /// The near miss that the trailing space protects: `--tests` DOES
    /// build the library unit tests and must still count. Without the
    /// space this is excluded and the guard refuses a correct workflow.
    #[test]
    fn a_tests_flag_run_counts_which_is_what_the_trailing_space_protects() {
        assert_eq!(
            runs_with_overflow_checks("cargo test --locked --tests"),
            vec!["cargo test --locked --tests".to_string()],
        );
        assert_eq!(
            runs_with_overflow_checks("cargo test --locked --all-targets").len(),
            1,
            "`--all-targets` builds the library too"
        );
    }
}

/// The handshake half of the shell scanner.
mod handshake {
    use super::debug_runs_that_prove_the_build_traps;

    #[test]
    fn a_debug_run_carrying_the_handshake_counts() {
        let script = "EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n";
        assert_eq!(
            debug_runs_that_prove_the_build_traps(script),
            vec!["EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib".to_string()],
        );
    }

    /// A debug run that exists and asks the build nothing. Buys a
    /// compile and no information.
    #[test]
    fn a_debug_run_without_the_handshake_does_not_count() {
        let script = "cargo test --locked --lib\n";
        assert_eq!(
            debug_runs_that_prove_the_build_traps(script),
            Vec::<String>::new(),
            "the step is there but nothing checks the build it produced"
        );
    }

    /// A handshake on a release run proves nothing and must not satisfy
    /// this: the checks are off in release on purpose.
    #[test]
    fn the_handshake_on_a_release_run_does_not_count() {
        let script = "EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --release\n";
        assert_eq!(
            debug_runs_that_prove_the_build_traps(script),
            Vec::<String>::new(),
        );
    }

    /// And quoted inside a shell comment, which is where a `run: |`
    /// block would explain it.
    #[test]
    fn the_handshake_quoted_in_a_comment_does_not_count() {
        let script = "#     EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n";
        assert_eq!(
            debug_runs_that_prove_the_build_traps(script),
            Vec::<String>::new(),
        );
    }

    /// A PRINTED MENTION IS NOT AN ASSIGNMENT, and it is not a comment
    /// either — which is why stripping comments did not close this.
    ///
    /// `echo "EXPECT_OVERFLOW_CHECKS=1"` on its own line armed the
    /// whole step, so every `cargo test` in it counted as proving the
    /// build traps, while the process received no variable and the
    /// runtime probe returned without asserting anything.
    /// AN ASSIGNMENT WITH NO COMMAND AFTER IT ARMS NOTHING.
    ///
    /// A prefix assignment is exported to the command it prefixes and
    /// to nothing else, so a standalone `EXPECT_OVERFLOW_CHECKS=1` line
    /// sets a SHELL variable that the next line's `cargo test` never
    /// sees. The guard reported a probe that could not have run.
    #[test]
    fn an_assignment_with_no_command_after_it_arms_nothing() {
        for line in [
            "EXPECT_OVERFLOW_CHECKS=1",
            "  EXPECT_OVERFLOW_CHECKS=1  ",
            "env EXPECT_OVERFLOW_CHECKS=1",
            "EXPECT_OVERFLOW_CHECKS=1 OTHER=2",
            // `export` with nothing to export is the same shape.
            "export",
        ] {
            assert!(
                !super::line_assigns_the_handshake(line),
                "{line}: nothing is exported, so no later cargo test can see the handshake"
            );
        }

        // AND THE WHOLE STEP IS NOT ARMED BY ONE. This is the shape a
        // workflow would actually be written in, and it is what
        // `gating_runs_that_prove_the_build_traps` reads.
        let block = "EXPECT_OVERFLOW_CHECKS=1\ncargo test --locked --lib\n";
        assert_eq!(
            super::debug_runs_that_prove_the_build_traps(block),
            Vec::<String>::new(),
            "the assignment is on its own line, so the cargo test runs without it"
        );
    }

    /// ACCEPTANCE FOR THAT, AND IT IS THE HALF A `require export` FIX
    /// WOULD HAVE BROKEN.
    ///
    /// `EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib` is the
    /// spelling this repository's own workflow uses. Requiring `export`
    /// would refuse it — the guard refusing a correct workflow, which
    /// is the failure this file's history is made of.
    #[test]
    fn the_spellings_that_really_export_it_still_arm_the_step() {
        for line in [
            "EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib",
            "env EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib",
            "EXPECT_OVERFLOW_CHECKS=1 RUST_BACKTRACE=1 cargo test --locked --lib",
            "RUST_BACKTRACE=1 EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib",
            "export EXPECT_OVERFLOW_CHECKS=1",
            "export RUST_BACKTRACE=1 EXPECT_OVERFLOW_CHECKS=1",
        ] {
            assert!(
                super::line_assigns_the_handshake(line),
                "{line} really does put the handshake in an environment a child receives"
            );
        }

        // And the printer is still refused, unchanged by any of this.
        assert!(
            !super::line_assigns_the_handshake("echo EXPECT_OVERFLOW_CHECKS=1"),
            "a printed handshake still arms nothing"
        );
    }

    #[test]
    fn a_printed_handshake_does_not_arm_the_step() {
        for line in [
            "echo \"EXPECT_OVERFLOW_CHECKS=1\"",
            "echo EXPECT_OVERFLOW_CHECKS=1",
            "printf '%s\\n' EXPECT_OVERFLOW_CHECKS=1",
            "echo \"setting EXPECT_OVERFLOW_CHECKS=1 for this step\"",
            "grep -q EXPECT_OVERFLOW_CHECKS=1 ci.yml",
        ] {
            assert!(
                !super::line_assigns_the_handshake(line),
                "{line} mentions the handshake; it does not set it"
            );
        }
    }

    /// THE ACCEPTANCE HALF, and it is the larger risk: refusing a real
    /// assignment makes the guard reject a workflow that is doing
    /// exactly what it asks for.
    #[test]
    fn every_spelling_that_really_assigns_it_still_arms_the_step() {
        for line in [
            "EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib",
            "env EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib",
            "RUST_BACKTRACE=1 EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib",
            "export EXPECT_OVERFLOW_CHECKS=1",
            "EXPECT_OVERFLOW_CHECKS=1 cargo +stable test --locked --lib",
        ] {
            assert!(
                super::line_assigns_the_handshake(line),
                "{line} assigns the handshake and must arm the step"
            );
        }
    }

    /// THE SECOND CALL SITE. `debug_runs_that_prove_the_build_traps`
    /// asked the same question with the same `contains`, and fixing
    /// only `step_declares_the_handshake` left the suite green — no
    /// test drove this path with a printed mention on the same line as
    /// a real run.
    #[test]
    fn a_printed_handshake_beside_a_real_run_does_not_prove_anything() {
        for script in [
            "echo \"EXPECT_OVERFLOW_CHECKS=1\" && cargo test --locked --lib\n",
            "cargo test --locked --lib -- --skip EXPECT_OVERFLOW_CHECKS=1\n",
        ] {
            assert_eq!(
                debug_runs_that_prove_the_build_traps(script),
                Vec::<String>::new(),
                "{script:?}: the handshake is mentioned, not assigned, so the process \
                 gets no variable and the runtime probe asserts nothing"
            );
        }
    }

    /// THE HANDSHAKE HAS TO REACH THE `cargo test` PROCESS, NOT JUST
    /// APPEAR SOMEWHERE ON ITS LINE OR IN ITS STEP.
    ///
    /// Arming was decided per physical line (and per step), so an
    /// assignment that prefixed a DIFFERENT command, or an export that
    /// ran AFTER the suite, armed a run whose process never received
    /// the variable -- and the runtime probe returned without asserting
    /// anything. Every script here was run under `bash -e -c` with
    /// `cargo` replaced by a function that reports `printenv
    /// EXPECT_OVERFLOW_CHECKS`: it reports the variable absent in each,
    /// except `env FOO=1 export ...`, where the step dies at exit 127
    /// before the suite runs at all. The acceptance scripts below were
    /// measured the same way and each reports it present.
    #[test]
    fn a_handshake_that_does_not_reach_the_run_does_not_prove_anything() {
        let scripts = [
            // The two shapes filed.
            "cargo test --locked --lib; export EXPECT_OVERFLOW_CHECKS=1\n",
            "EXPECT_OVERFLOW_CHECKS=1 echo x; cargo test --locked --lib\n",
            // The same two across a newline.
            "cargo test --locked --lib\nexport EXPECT_OVERFLOW_CHECKS=1\n",
            "EXPECT_OVERFLOW_CHECKS=1 echo x\ncargo test --locked --lib\n",
            // A prefix on a non-qualifying run beside a qualifying one.
            "EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --no-run; cargo test --locked --lib\n",
            // Exports that never reach the shell running the suite: a
            // subshell, a pipeline member, a background job.
            "(export EXPECT_OVERFLOW_CHECKS=1); cargo test --locked --lib\n",
            "(\nexport EXPECT_OVERFLOW_CHECKS=1\n)\ncargo test --locked --lib\n",
            "export EXPECT_OVERFLOW_CHECKS=1 | cat\ncargo test --locked --lib\n",
            "export EXPECT_OVERFLOW_CHECKS=1 &\ncargo test --locked --lib\n",
            // An export that may not run at all.
            "test -n \"$CI\" && export EXPECT_OVERFLOW_CHECKS=1\ncargo test --locked --lib\n",
            // The same, with the list continued onto the next line:
            // a line ending in `&&` or `||` is not the end of the list.
            "test -n \"$CI\" &&\nexport EXPECT_OVERFLOW_CHECKS=1\ncargo test --locked --lib\n",
            "true ||\nexport EXPECT_OVERFLOW_CHECKS=1\ncargo test --locked --lib\n",
            // An export undone before the suite runs.
            "export EXPECT_OVERFLOW_CHECKS=1\nunset EXPECT_OVERFLOW_CHECKS\ncargo test --locked --lib\n",
            "export EXPECT_OVERFLOW_CHECKS=1\nexport -n EXPECT_OVERFLOW_CHECKS\ncargo test --locked --lib\n",
            // `export -n` sets the value and REMOVES the export.
            "export -n EXPECT_OVERFLOW_CHECKS=1\ncargo test --locked --lib\n",
            // The run's own prefix overrides the export, and the last
            // assignment in a prefix wins.
            "export EXPECT_OVERFLOW_CHECKS=1\nEXPECT_OVERFLOW_CHECKS=0 cargo test --locked --lib\n",
            "EXPECT_OVERFLOW_CHECKS=1 EXPECT_OVERFLOW_CHECKS=0 cargo test --locked --lib\n",
            // A compound command piped into something runs in a
            // subshell, and its body's lines look like any others.
            "if true; then\nexport EXPECT_OVERFLOW_CHECKS=1\nfi | cat\ncargo test --locked --lib\n",
            "{\nexport EXPECT_OVERFLOW_CHECKS=1\n} | cat\ncargo test --locked --lib\n",
            // `env` runs an external program; it cannot export into the shell.
            "env FOO=1 export EXPECT_OVERFLOW_CHECKS=1\ncargo test --locked --lib\n",
            // The body of a heredoc is data.
            "cat <<EOF\nexport EXPECT_OVERFLOW_CHECKS=1\nEOF\ncargo test --locked --lib\n",
        ];
        for script in scripts {
            assert_eq!(
                debug_runs_that_prove_the_build_traps(script),
                Vec::<String>::new(),
                "handshake_must_reach_the_run: {script:?} -- the cargo test process never \
                 receives EXPECT_OVERFLOW_CHECKS=1, so the runtime probe asserts nothing"
            );
        }
        assert_eq!(
            scripts.len(),
            21,
            "every shape above must have been examined"
        );
    }

    /// THE ACCEPTANCE HALF: each of these really does hand the variable
    /// to the `cargo test` process, including the `FOO=1 export` shape a
    /// first-word-only `export` check refused.
    #[test]
    fn a_handshake_that_reaches_the_run_still_proves_it() {
        for script in [
            "EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib; echo done\n",
            "echo start; EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n",
            "export EXPECT_OVERFLOW_CHECKS=1\ncargo test --locked --lib\n",
            "export EXPECT_OVERFLOW_CHECKS=1; cargo test --locked --lib\n",
            "set -euo pipefail\nexport RUST_BACKTRACE=1 EXPECT_OVERFLOW_CHECKS=1\ncd ..\ncargo test --locked --lib\n",
            "FOO=1 export EXPECT_OVERFLOW_CHECKS=1\ncargo test --locked --lib\n",
            "EXPECT_OVERFLOW_CHECKS=1 \\\n  cargo test --locked --lib\n",
        ] {
            assert_eq!(
                debug_runs_that_prove_the_build_traps(script).len(),
                1,
                "{script:?}: the cargo test process receives EXPECT_OVERFLOW_CHECKS=1"
            );
        }
        assert!(
            super::line_assigns_the_handshake("FOO=1 export EXPECT_OVERFLOW_CHECKS=1"),
            "an assignment prefix does not stop `export` being the command"
        );
    }

    /// A RUN INSIDE A GATING SUBSTITUTION RECEIVES WHAT THE SHELL HAS
    /// EXPORTED, OR ITS OWN PREFIX -- NOT THE OUTER ASSIGNMENTS, which
    /// are shell variables. Measured with `cargo` reporting `printenv`.
    #[test]
    fn a_run_inside_a_substitution_receives_only_the_exported_handshake() {
        for script in [
            "export EXPECT_OVERFLOW_CHECKS=1\nx=$(cargo test --locked --lib)\n",
            "x=$(EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib)\n",
            // A withdrawal is answered by the run's own prefix.
            "export EXPECT_OVERFLOW_CHECKS=1\nx=$(unset EXPECT_OVERFLOW_CHECKS; EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib)\n",
            // ...or by exporting it again, which reaches the run (Greptile
            // on rust-img-vmdk#102).
            "export EXPECT_OVERFLOW_CHECKS=1\nx=$(unset EXPECT_OVERFLOW_CHECKS; export EXPECT_OVERFLOW_CHECKS=1; cargo test --locked --lib)\n",
            // An export inside the substitution reaches a run after it
            // there, with nothing exported outside.
            "x=$(export EXPECT_OVERFLOW_CHECKS=1; cargo test --locked --lib)\n",
            "x=$(y=$(export EXPECT_OVERFLOW_CHECKS=1; cargo test --locked --lib))\n",
            // The innermost change wins: withdrawn outside the nested
            // substitution, exported again inside it.
            "export EXPECT_OVERFLOW_CHECKS=1\nx=$(unset EXPECT_OVERFLOW_CHECKS; y=$(export EXPECT_OVERFLOW_CHECKS=1; cargo test --locked --lib))\n",
        ] {
            assert_eq!(
                debug_runs_that_prove_the_build_traps(script).len(),
                1,
                "{script:?}: the cargo test process receives the variable"
            );
        }
        for script in [
            "EXPECT_OVERFLOW_CHECKS=1 x=$(cargo test --locked --lib)\n",
            "x=$(export EXPECT_OVERFLOW_CHECKS=1)\ncargo test --locked --lib\n",
            // Withdrawn inside the substitution, before the run: an `unset`
            // there leaves the suite without the exported variable.
            "export EXPECT_OVERFLOW_CHECKS=1\nx=$(unset EXPECT_OVERFLOW_CHECKS && cargo test --locked --lib)\n",
            "export EXPECT_OVERFLOW_CHECKS=1\nx=$(y=$(unset EXPECT_OVERFLOW_CHECKS; cargo test --locked --lib))\n",
            // A re-export that may not run, or runs in a pipeline's subshell
            // or a nested substitution, does not restore it.
            "export EXPECT_OVERFLOW_CHECKS=1\nx=$(unset EXPECT_OVERFLOW_CHECKS; false && export EXPECT_OVERFLOW_CHECKS=1; cargo test --locked --lib)\n",
            "x=$(export EXPECT_OVERFLOW_CHECKS=1 | cat; cargo test --locked --lib)\n",
            "export EXPECT_OVERFLOW_CHECKS=1\nx=$(unset EXPECT_OVERFLOW_CHECKS; y=$(export EXPECT_OVERFLOW_CHECKS=1); cargo test --locked --lib)\n",
        ] {
            assert_eq!(
                debug_runs_that_prove_the_build_traps(script),
                Vec::<String>::new(),
                "{script:?}: the cargo test process does not receive the variable"
            );
        }
    }

    /// The acceptance half of that call site: the same line shape with a
    /// real assignment still counts.
    #[test]
    fn a_real_assignment_beside_a_run_on_one_line_still_counts() {
        let script = "export EXPECT_OVERFLOW_CHECKS=1 && cargo test --locked --lib\n";
        assert_eq!(debug_runs_that_prove_the_build_traps(script).len(), 1);
    }

    /// The `env:` mapping is untouched by any of this, and it is the
    /// only spelling that works on a matrix including `windows-latest`.
    #[test]
    fn the_env_mapping_still_arms_the_step() {
        let step = super::Step {
            keys: vec!["run".to_string(), "env".to_string()],
            run: "cargo test --locked --lib\n".to_string(),
            env: vec!["EXPECT_OVERFLOW_CHECKS=1".to_string()],
        };
        assert_eq!(
            super::step_runs_that_prove_the_build_traps(&step),
            vec!["cargo test --locked --lib".to_string()]
        );

        // The mapping is the INITIAL environment, so the script can
        // still take it away before the run.
        let unset = super::Step {
            keys: vec!["run".to_string(), "env".to_string()],
            run: "unset EXPECT_OVERFLOW_CHECKS\ncargo test --locked --lib\n".to_string(),
            env: vec!["EXPECT_OVERFLOW_CHECKS=1".to_string()],
        };
        assert!(
            super::step_runs_that_prove_the_build_traps(&unset).is_empty(),
            "the run starts after the variable was unset"
        );

        let printed = super::Step {
            keys: vec!["run".to_string()],
            run: "echo \"EXPECT_OVERFLOW_CHECKS=1\"\ncargo test --locked --lib\n".to_string(),
            env: Vec::new(),
        };
        assert!(
            super::step_runs_that_prove_the_build_traps(&printed).is_empty(),
            "a step whose only mention is printed is not armed"
        );
    }
}

/// The manifest scanner, held to the shapes it has to tell apart. These
/// do not depend on this repository's own `Cargo.toml`, so they keep
/// meaning something after it changes.
mod manifest_parser {
    use super::profiles_disabling_overflow_checks;

    #[test]
    fn the_test_profile_disabling_the_checks_is_caught() {
        let manifest = "\
[profile.release]
lto = true

[profile.test]
overflow-checks = false
";
        assert_eq!(
            profiles_disabling_overflow_checks(manifest),
            vec!["profile.test.overflow-checks".to_string()],
        );
    }

    /// This repository has an explicit `[profile.dev]`, so this is the
    /// likeliest place the setting would actually arrive.
    #[test]
    fn the_dev_profile_disabling_the_checks_is_caught() {
        let manifest = "[profile.dev]\nopt-level = 1\noverflow-checks   =   false\n";
        assert_eq!(
            profiles_disabling_overflow_checks(manifest),
            vec!["profile.dev.overflow-checks".to_string()],
        );
    }

    /// Release is expected to have them off. Flagging it would make the
    /// guard fail on every correct manifest, which is the fastest way
    /// to get a guard deleted.
    #[test]
    fn the_release_profile_disabling_the_checks_is_not_flagged() {
        let manifest = "[profile.release]\noverflow-checks = false\n";
        assert_eq!(
            profiles_disabling_overflow_checks(manifest),
            Vec::<String>::new(),
        );
    }

    /// A commented-out line is not a setting -- the same trap as the
    /// workflow parser's, in the other file this module reads.
    #[test]
    fn a_commented_out_setting_is_not_a_setting() {
        let manifest = "[profile.test]\n# overflow-checks = false\nopt-level = 1\n";
        assert_eq!(
            profiles_disabling_overflow_checks(manifest),
            Vec::<String>::new(),
        );
    }

    /// The comment strip, which nothing else here pins. The realistic
    /// way this setting arrives is with its excuse on the same line,
    /// and it must still be caught: unstripped, the value reads
    /// `false  # speeds the suite up`, which is not `false`, and the
    /// guard waves through the exact edit it exists to catch.
    #[test]
    fn a_disabling_line_with_a_trailing_comment_is_still_caught() {
        let manifest = "[profile.test]\noverflow-checks = false  # speeds the suite up\n";
        assert_eq!(
            profiles_disabling_overflow_checks(manifest),
            vec!["profile.test.overflow-checks".to_string()],
        );
    }

    /// A different setting being `false` is not this setting being
    /// `false`. Without this the scanner could be keying on the value
    /// alone -- flagging any `= false` under those two sections -- and
    /// every other test here would still pass.
    #[test]
    fn another_setting_being_false_is_not_this_one() {
        let manifest = "[profile.test]\ndebug-assertions = false\nopt-level = 1\n";
        assert_eq!(
            profiles_disabling_overflow_checks(manifest),
            Vec::<String>::new(),
        );
    }

    /// THE SPELLINGS THAT DEFEATED THE FIRST VERSION. Each of these was
    /// measured to genuinely switch the checks off, with no warning
    /// from cargo -- see the table on
    /// `profiles_disabling_overflow_checks`. A guard that reads one
    /// spelling of a setting is a guard against typing it one way.
    #[test]
    fn a_double_quoted_key_is_the_same_key() {
        let manifest = "[profile.test]\n\"overflow-checks\" = false\n";
        assert_eq!(
            profiles_disabling_overflow_checks(manifest),
            vec!["profile.test.overflow-checks".to_string()],
        );
    }

    #[test]
    fn a_literal_quoted_key_is_the_same_key() {
        let manifest = "[profile.dev]\n'overflow-checks' = false\n";
        assert_eq!(
            profiles_disabling_overflow_checks(manifest),
            vec!["profile.dev.overflow-checks".to_string()],
        );
    }

    /// The one a section-matching scan cannot see at all: the profile
    /// name is on the key side, so the section is only `profile`.
    #[test]
    fn a_dotted_key_putting_the_profile_on_the_key_side_is_caught() {
        let manifest = "[profile]\ntest.overflow-checks = false\n";
        assert_eq!(
            profiles_disabling_overflow_checks(manifest),
            vec!["profile.test.overflow-checks".to_string()],
        );
    }

    /// And with no section header at all, which is still valid TOML.
    #[test]
    fn a_top_level_dotted_key_is_caught() {
        let manifest = "profile.test.overflow-checks = false\n";
        assert_eq!(
            profiles_disabling_overflow_checks(manifest),
            vec!["profile.test.overflow-checks".to_string()],
        );
    }

    #[test]
    fn a_quoted_section_is_the_same_section() {
        let manifest = "[\"profile\".'test']\noverflow-checks = false\n";
        assert_eq!(
            profiles_disabling_overflow_checks(manifest),
            vec!["profile.test.overflow-checks".to_string()],
        );
    }

    /// Release stays exempt in the dotted spelling too, or normalising
    /// the path would have quietly widened what the guard refuses.
    #[test]
    fn the_release_profile_is_exempt_in_the_dotted_spelling_too() {
        let manifest = "[profile]\nrelease.overflow-checks = false\n";
        assert_eq!(
            profiles_disabling_overflow_checks(manifest),
            Vec::<String>::new(),
        );
    }

    /// `true` is the state we want and must not be reported as the
    /// state we do not. Without this the scanner could be keying on the
    /// word `overflow-checks` alone and nothing here would notice.
    #[test]
    fn enabling_the_checks_explicitly_is_not_flagged() {
        let manifest = "[profile.test]\noverflow-checks = true\n";
        assert_eq!(
            profiles_disabling_overflow_checks(manifest),
            Vec::<String>::new(),
        );
    }
}

/// WHAT ELSE DECIDES WHETHER THE STEP GATES -- one test per item on the
/// enumerated list, because each is a separate way for the gate to go
/// blind with the command still present and still matching.
///
/// The version of this guard these replace matched the `- run:` line in
/// isolation. Measured against this repository's own workflow, `if:
/// false` and `continue-on-error: true` each left all 31 of its tests
/// green while the gate stopped gating.
mod gating {
    use super::gating_runs_that_prove_the_build_traps;

    /// A HANDSHAKE IN A SHELL COMMENT DOES NOT ARM THE STEP.
    ///
    /// `step_declares_the_handshake` read `step.run` verbatim while the
    /// command scan stripped comments, so this workflow satisfied both
    /// assertions and handed the process no `EXPECT_OVERFLOW_CHECKS` at
    /// all -- leaving the runtime probe to return without asserting
    /// anything.
    ///
    /// The existing `handshake::the_handshake_quoted_in_a_comment_does_not_count`
    /// looks like this test and is not: it exercises the script-level
    /// path, which was already comment-stripped, and its fixture has no
    /// real command after the comment, so it could not diverge on the
    /// defect even pointed at the right function.
    #[test]
    fn a_handshake_in_a_shell_comment_does_not_arm_a_step() {
        for block in [
            "      - run: |\n          # EXPECT_OVERFLOW_CHECKS=1 -- see ci_profile.rs\n          cargo test --locked --lib\n",
            "      - run: |\n          cargo test --locked --lib  # EXPECT_OVERFLOW_CHECKS=1 is set in CI\n",
        ] {
            let yaml = GATING.replace(
                "      - run: EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n",
                block,
            );
            assert!(
                gating_runs_that_prove_the_build_traps(&yaml).is_empty(),
                "the variable is named in a comment, so the process never receives \
                 it and the runtime probe asserts nothing: {block:?}"
            );
        }
    }

    /// A HANDSHAKE GLUED TO A TERMINATOR DOES NOT ARM THE STEP EITHER.
    ///
    /// `command_lines` cut the comment at `" #"`, which is the rule
    /// "a `#` that begins a word" written for exactly one of the
    /// characters that end a word. The three it missed are the ones
    /// `shell_commands` already splits on, so the two readers of one
    /// text had two grammars again -- the defect this file records
    /// having fixed once already, at a different character.
    ///
    /// `&&#` is not valid bash, and is here anyway: the guard must not
    /// depend on the evasion being a shape bash would accept, and
    /// over-strict is the safe direction everywhere in this file.
    #[test]
    fn a_handshake_glued_to_a_terminator_does_not_arm_a_step() {
        for block in [
            "      - run: |\n          cargo test --locked --lib;# EXPECT_OVERFLOW_CHECKS=1 is set in CI\n",
            "      - run: |\n          (cargo test --locked --lib)# EXPECT_OVERFLOW_CHECKS=1 is set in CI\n",
            "      - run: |\n          cargo test --locked --lib && echo ok&&# EXPECT_OVERFLOW_CHECKS=1 is set in CI\n",
        ] {
            let yaml = GATING.replace(
                "      - run: EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n",
                block,
            );
            assert!(
                gating_runs_that_prove_the_build_traps(&yaml).is_empty(),
                "the variable is named in a comment, so the process never receives \
                 it and the runtime probe asserts nothing: {block:?}"
            );
        }
    }

    /// THE WORKFLOW PATH OF THE SAME DEFECT. Arming was a property of the
    /// STEP, so any line assigning the handshake armed every run in it.
    #[test]
    fn a_handshake_elsewhere_in_the_step_does_not_arm_the_run() {
        for block in [
            "      - run: |\n          cargo test --locked --lib; export EXPECT_OVERFLOW_CHECKS=1\n",
            "      - run: |\n          EXPECT_OVERFLOW_CHECKS=1 echo x; cargo test --locked --lib\n",
            "      - run: |\n          cargo test --locked --lib\n          export EXPECT_OVERFLOW_CHECKS=1\n",
            "      - run: |\n          EXPECT_OVERFLOW_CHECKS=1 echo x\n          cargo test --locked --lib\n",
        ] {
            let yaml = GATING.replace(
                "      - run: EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n",
                block,
            );
            assert!(
                gating_runs_that_prove_the_build_traps(&yaml).is_empty(),
                "handshake_must_reach_the_run: the cargo test process never receives the \
                 variable, so the runtime probe asserts nothing: {block:?}"
            );
        }
        // Acceptance: an export BEFORE the run, in the same step, arms it.
        let yaml = GATING.replace(
            "      - run: EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n",
            "      - run: |\n          export EXPECT_OVERFLOW_CHECKS=1\n          cargo test --locked --lib\n",
        );
        assert_eq!(gating_runs_that_prove_the_build_traps(&yaml).len(), 1);
    }

    /// THE ACCEPTANCE HALF: both real spellings still arm the step.
    ///
    /// The `env:` mapping is not a concession -- it is the only
    /// spelling that works on a matrix including `windows-latest`.
    #[test]
    fn both_real_spellings_of_the_handshake_still_arm_a_step() {
        for block in [
            "      - run: EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n",
            "      - run: cargo test --locked --lib\n        env:\n          EXPECT_OVERFLOW_CHECKS: \"1\"\n",
            "      - run: |\n          # the guard is armed below, not here\n          EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n",
        ] {
            let yaml = GATING.replace(
                "      - run: EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n",
                block,
            );
            assert_eq!(
                gating_runs_that_prove_the_build_traps(&yaml).len(),
                1,
                "this step really does ask the build to prove it traps: {block:?}"
            );
        }
    }

    /// The shape that does gate, as a control. Every test below is this
    /// with one thing added, so a failure here would mean the fixture
    /// is wrong rather than the property.
    const GATING: &str = "\
on:
  pull_request:
    branches: [main]
jobs:
  test:
    steps:
      - run: EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib
";

    #[test]
    fn the_control_shape_gates() {
        assert_eq!(
            gating_runs_that_prove_the_build_traps(GATING).len(),
            1,
            "the control must be counted, or every test below passes for the wrong reason"
        );
    }

    #[test]
    fn a_step_carrying_if_does_not_gate() {
        for condition in [
            "if: false",
            "if: ${{ false }}",
            "if: github.event_name == 'push'",
            "if: ${{ env.SOMETHING == 'yes' }}",
        ] {
            let yaml = GATING.replace(
                "      - run: EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n",
                &format!(
                    "      - run: EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n        {condition}\n"
                ),
            );
            assert!(
                gating_runs_that_prove_the_build_traps(&yaml).is_empty(),
                "a step carrying `{condition}` may or may not run, so it cannot be what \
                 makes the gate able to see an overflow. Rejected on the key's presence \
                 rather than by evaluating it -- the spellings are open-ended."
            );
        }
    }

    #[test]
    fn a_step_carrying_continue_on_error_does_not_gate() {
        let yaml = GATING.replace(
            "      - run: EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n",
            "      - run: EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n        continue-on-error: true\n",
        );
        assert!(
            gating_runs_that_prove_the_build_traps(&yaml).is_empty(),
            "the step runs and its failure is discarded, which is the project's own named \
             defect: a step that runs and whose result nothing reads"
        );
    }

    #[test]
    fn a_job_carrying_if_does_not_gate() {
        let yaml = GATING.replace("  test:\n", "  test:\n    if: false\n");
        assert!(
            gating_runs_that_prove_the_build_traps(&yaml).is_empty(),
            "the same reasoning one level up: a job that may not run cannot gate"
        );
    }

    #[test]
    fn a_job_carrying_continue_on_error_does_not_gate() {
        let yaml = GATING.replace("  test:\n", "  test:\n    continue-on-error: true\n");
        assert!(
            gating_runs_that_prove_the_build_traps(&yaml).is_empty(),
            "a job whose failure is discarded cannot gate, however sound its steps"
        );
    }

    /// The assumption the `ci.yml`-only scan rests on, which is a fact
    /// about the file rather than a given.
    #[test]
    fn a_workflow_that_no_longer_runs_on_pull_request_does_not_gate() {
        let yaml = GATING.replace(
            "  pull_request:\n    branches: [main]\n",
            "  push:\n    branches: [main]\n",
        );
        assert!(
            gating_runs_that_prove_the_build_traps(&yaml).is_empty(),
            "scoping the scan to ci.yml assumes ci.yml is what runs on a pull request; if its \
             triggers stop including pull_request, the step gates nothing no matter how it looks"
        );
    }

    /// A `run: |` block is read whole, so a command inside a loop is
    /// visible. This repository has TWO such loops in kernel-gate, and
    /// a line-range extraction drops the second.
    #[test]
    fn a_run_block_is_read_whole() {
        let yaml = "\
on:
  pull_request:
    branches: [main]
jobs:
  test:
    steps:
      - name: a block
        run: |
          set -euo pipefail
          EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib
";
        assert_eq!(
            gating_runs_that_prove_the_build_traps(yaml).len(),
            1,
            "a command inside a `run: |` block must be seen; the kernel-gate loops live in \
             blocks like this one"
        );
    }

    /// THE QUOTED SPELLINGS, WHICH WERE SILENT DEFEATS. Measured on
    /// `main` at `57cf1b6`: `if: false` correctly turned the suite red,
    /// and `"if": false` -- the same key, quoted -- left all 34 tests
    /// green while Actions skipped the step. The old parser took its
    /// key as `cur.split(':').next()` with no un-quoting, so the key
    /// read `"if"` and matched no entry in `NON_GATING_KEYS`.
    ///
    /// Nothing un-quotes anything now: the key arrives from the parser
    /// already resolved, so every spelling of it is the same key by
    /// construction.
    #[test]
    fn a_quoted_key_is_the_same_key() {
        for spelling in [
            "\"if\": false",
            "'if': false",
            "\"continue-on-error\": true",
            "'continue-on-error': true",
        ] {
            let yaml = GATING.replace(
                "      - run: EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n",
                &format!(
                    "      - run: EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n        {spelling}\n"
                ),
            );
            assert!(
                gating_runs_that_prove_the_build_traps(&yaml).is_empty(),
                "`{spelling}` is the same key as its bare spelling; quoting it must not \
                 make a skipped step count as the thing gating the merge"
            );
        }
    }

    /// And one level up, on the job.
    #[test]
    fn a_quoted_key_on_the_job_is_the_same_key() {
        for spelling in ["\"if\": false", "\"continue-on-error\": true"] {
            let yaml = GATING.replace("  test:\n", &format!("  test:\n    {spelling}\n"));
            assert!(
                gating_runs_that_prove_the_build_traps(&yaml).is_empty(),
                "`{spelling}` on the job is the same key as its bare spelling"
            );
        }
    }

    /// THE COMMENTED-OUT TRIGGER, ALSO A SILENT DEFEAT. The old check
    /// asked whether the `on:` block's raw text -- comments included --
    /// contained the characters `pull_request`, so commenting the
    /// trigger out left the guard green on a workflow that no longer
    /// ran on pull requests at all. Measured on `main`: 34 passed,
    /// both arms.
    #[test]
    fn a_commented_out_pull_request_trigger_does_not_gate() {
        let commented_with_another_trigger_left = GATING.replace(
            "  pull_request:\n    branches: [main]\n",
            "  # pull_request:\n  #   branches: [main]\n  push:\n    branches: [main]\n",
        );
        let only_a_comment_naming_it = GATING.replace(
            "  pull_request:\n    branches: [main]\n",
            "  # pull_request disabled while we investigate flaky runners\n  push:\n    branches: [main]\n",
        );
        for yaml in [
            &commented_with_another_trigger_left,
            &only_a_comment_naming_it,
        ] {
            assert!(
                gating_runs_that_prove_the_build_traps(yaml).is_empty(),
                "a trigger named only in a comment is not a trigger; the parser drops \
                 comments before anything compares a name, so there is no `#` to strip \
                 and none to forget:\n{yaml}"
            );
        }
    }

    /// A whole-name comparison, so a trigger that merely begins with
    /// those characters is a different trigger. `pull_request_review`
    /// fires on a review, not on the pull request, and cannot be what
    /// gates the merge.
    #[test]
    fn a_trigger_that_merely_begins_with_pull_request_does_not_gate() {
        let yaml = GATING.replace(
            "  pull_request:\n    branches: [main]\n",
            "  pull_request_review:\n    types: [submitted]\n",
        );
        assert!(
            gating_runs_that_prove_the_build_traps(&yaml).is_empty(),
            "pull_request_review is not pull_request; a substring match cannot tell \
             them apart and this comparison must"
        );
    }

    /// `pull_request_target` is not `pull_request`, and is refused on
    /// purpose. It runs against the base repository with a write token
    /// and the repository's secrets, and checks out the base ref by
    /// default, so a workflow triggered only that way may never build
    /// the contributor's code. `rust-fs-xfs#146` and
    /// `rust-fs-ext4#149` record it as a live gap in the hand-rolled
    /// guard this file replaces.
    ///
    /// Pinned as a test rather than left to the comparison, because the
    /// clause is one line and was previously written by hand and copied
    /// between repositories. This is what stops it coming back.
    #[test]
    fn pull_request_target_does_not_gate() {
        let yaml = GATING.replace(
            "  pull_request:\n    branches: [main]\n",
            "  pull_request_target:\n    branches: [main]\n",
        );
        assert!(
            gating_runs_that_prove_the_build_traps(&yaml).is_empty(),
            "pull_request_target runs with the base repository's token and secrets \
             and checks out the base ref; it is not proof that the merge is gated"
        );
    }

    /// `on:` may be a sequence of names rather than a mapping, in
    /// either the flow or the block spelling, and all three are
    /// ordinary workflows.
    #[test]
    fn a_sequence_of_triggers_is_read() {
        for spelling in [
            "on: [push, pull_request]\n",
            "on:\n  - push\n  - pull_request\n",
        ] {
            let yaml = GATING.replace("on:\n  pull_request:\n    branches: [main]\n", spelling);
            assert_eq!(
                gating_runs_that_prove_the_build_traps(&yaml).len(),
                1,
                "this workflow triggers on a pull request as surely as the mapping \
                 spelling does:\n{yaml}"
            );
        }
    }

    /// THE ARM THAT WAS A FALSE ALARM RATHER THAN A DEFEAT, AND SO
    /// CANNOT BE WITNESSED BY THE SUITE GOING RED -- it already did.
    /// The witness is that legal YAML now passes.
    ///
    /// The old parser treated only a bare `|` as a block opener
    /// (`after != "|"`), so `|-`, `|+`, `>`, `>-` and `|2` were read as
    /// the command itself and the block's contents never parsed at all.
    /// Measured on `main`: `run: |` 34 passed, `run: |-` and `run: >`
    /// each EXIT=101 with 2 failed -- the guard refusing a completely
    /// correct workflow, which is the fastest way to get a guard
    /// deleted.
    ///
    /// A parser knows all five styles because they are the grammar.
    #[test]
    fn every_block_scalar_style_is_read_whole() {
        for style in ["|", "|-", "|+", ">", ">-", "|2"] {
            let yaml = GATING.replace(
                "      - run: EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n",
                &format!(
                    "      - name: a block\n        run: {style}\n          EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n"
                ),
            );
            assert_eq!(
                gating_runs_that_prove_the_build_traps(&yaml).len(),
                1,
                "`run: {style}` is a legal block scalar carrying the gating command; \
                 failing here is the guard refusing a correct workflow:\n{yaml}"
            );
        }
    }

    /// A command quoted in a YAML comment is not a run. This used to be
    /// the shell scanner's job and is the parser's now: comments do not
    /// survive parsing, so there is no `#` handling here to get wrong.
    /// It is asserted at this level because that is where the property
    /// now lives -- `ci.yml` really does quote the gating command
    /// verbatim in the comment block above it, so a scan that missed
    /// this would stay green after the step itself was deleted.
    #[test]
    fn a_debug_run_quoted_in_a_yaml_comment_does_not_gate() {
        let yaml = "\
on:
  pull_request:
    branches: [main]
jobs:
  test:
    steps:
      # Do not remove this as a duplicate of the runs above it:
      #     - run: EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib
      - run: cargo test --locked --release
";
        assert!(
            gating_runs_that_prove_the_build_traps(yaml).is_empty(),
            "the gating command appears only inside a comment, and the step that \
             remains is a release run"
        );
    }

    /// A workflow the parser cannot read is a failure, never a pass.
    /// The direction matters: a guard that swallowed the error and
    /// returned an empty structure would report "no debug run gates
    /// this", which is also a failure and therefore safe -- but one
    /// that returned early with a pass would be the blindness this
    /// whole module exists to refuse.
    #[test]
    #[should_panic(expected = "not valid YAML")]
    fn a_workflow_that_does_not_parse_is_a_failure() {
        super::parse_workflow("jobs:\n  test:\n   - broken: [unclosed\n");
    }

    /// THE CONTROL THAT STOPS THE REFUSAL OVER-CORRECTING.
    ///
    /// `pull_request_target` is refused as insufficient ON ITS OWN.
    /// That is not the same as refusing any workflow that mentions it,
    /// and until this test existed nothing in the file could tell the
    /// two apart: every fixture carried at most one trigger, so this
    /// mutation survived the whole suite --
    ///
    /// ```text
    ///   any(t == "pull_request")
    ///       && !any(t == "pull_request_target")
    /// ```
    ///
    /// -- while refusing a perfectly gated workflow. Carrying both
    /// triggers is the ordinary way to reach repository secrets from a
    /// job without giving up the pull-request gate, and such a workflow
    /// IS gated, by its `pull_request:` key.
    ///
    /// An assertion whose result does not depend on the thing it claims
    /// to check is this project's own recurring defect; this one was in
    /// the test pinning the refusal rather than in the refusal itself.
    #[test]
    fn a_workflow_carrying_both_triggers_still_gates() {
        let yaml = GATING.replace(
            "  pull_request:\n    branches: [main]\n",
            "  pull_request:\n    branches: [main]\n  pull_request_target:\n    branches: [main]\n",
        );
        assert_ne!(yaml, GATING, "the mutation must actually apply");
        assert_eq!(
            gating_runs_that_prove_the_build_traps(&yaml).len(),
            1,
            "the workflow still triggers on pull_request, so it still gates; refusing it \
             because pull_request_target is also present would be the over-correction"
        );
    }

    /// THE HANDSHAKE MAY BE DECLARED IN THE STEP'S `env:` MAPPING.
    ///
    /// Not a concession: on a matrix including `windows-latest` it is
    /// the only spelling that works, because an inline
    /// `VAR=1 cargo test` prefix is bash syntax and a PowerShell syntax
    /// error. A guard that read only the command would refuse the
    /// correct workflow on every cross-platform crate here -- the loud
    /// direction, but wrong, and the fastest way to get a guard
    /// deleted.
    #[test]
    fn the_handshake_declared_in_an_env_mapping_counts() {
        for value in ["\"1\"", "1", "'1'"] {
            let yaml = GATING.replace(
                "      - run: EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n",
                &format!(
                    "      - run: cargo test --locked --lib\n        env:\n          EXPECT_OVERFLOW_CHECKS: {value}\n"
                ),
            );
            assert_eq!(
                gating_runs_that_prove_the_build_traps(&yaml).len(),
                1,
                "`EXPECT_OVERFLOW_CHECKS: {value}` in an env mapping is the same \
                 instruction to Actions as the inline prefix, and on a Windows \
                 matrix it is the only one that works:\n{yaml}"
            );
        }
    }

    /// And it must not rescue a `--release` run. The checks are off in
    /// release deliberately, so a handshake there arms an assertion
    /// that would fire on every green run.
    #[test]
    fn the_handshake_in_an_env_mapping_does_not_count_on_a_release_run() {
        let yaml = GATING.replace(
            "      - run: EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n",
            "      - run: cargo test --locked --release --lib\n        env:\n          EXPECT_OVERFLOW_CHECKS: \"1\"\n",
        );
        assert!(
            gating_runs_that_prove_the_build_traps(&yaml).is_empty(),
            "a release run cannot prove the build traps, however it is labelled"
        );
    }

    /// A step carrying an `env:` mapping is still a gating step. Over-
    /// strictness here would cost something real: the handshake itself
    /// lives in such a mapping.
    #[test]
    fn a_step_carrying_an_env_mapping_still_gates() {
        let yaml = GATING.replace(
            "      - run: EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n",
            "      - run: EXPECT_OVERFLOW_CHECKS=1 cargo test --locked --lib\n        env:\n          SOMETHING_ELSE: \"1\"\n",
        );
        assert_eq!(
            gating_runs_that_prove_the_build_traps(&yaml).len(),
            1,
            "`env:` says nothing about whether the step's result is read"
        );
    }
}