greengate-runtime 4.11.0

The amont hook logic: registry, dispatchers, checks and the trust model
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
//! The two dispatchers.
//!
//! They are NOT the same shape, and both shapes are load-bearing:
//!
//! - `pre-commit` runs its checks CONCURRENTLY and reports EVERY failure.
//!   Serial would be a visible slowdown on each commit; stopping at the first
//!   failure would hide the rest, so you'd fix one lint error, commit, and
//!   immediately meet the next.
//! - `pre-push` runs them SERIALLY and stops at the FIRST failure, naming just
//!   that check. The steps are ordered and expensive (protected branch, then
//!   branch name, then rebase, then the whole test suite) and there is no point
//!   running tests after a rebase conflict.
//!
//! Resist the tempting shared `run_all` helper — collapsing these is the
//! obvious way to silently lose the distinction. `tests/it/dispatchers.rs` pins
//! both.
//!
//! Checks are FUNCTIONS in this binary, called directly. They used to be files:
//! `.git/hooks/pre-commit-*`, each an identical `sh` shim whose only job was to
//! re-exec this same binary and tell it its own name. One commit therefore cost
//! 27 processes — a shim, the binary, then 13 more shims and 13 more binaries —
//! to do work the binary already had in a table.
//!
//! Deleting that removed the filename glob (order was lexicographic, so a
//! rename could silently reorder a gate), the shebang emulation Windows needed
//! because it cannot execute a `#!` script, and the spawn plumbing under both.
//! Order is now a declared list in `registry`.

use std::sync::Mutex;

use crate::check::{Check, Outcome, Severity, Stage, Verdict};
use crate::configured_skips;
use crate::names::BIN;
use crate::registry::{all_stage_checks, Ctx, Overrides};
use crate::ui::{highlight, valid_sign, warning_sign};

/// The checks for a stage, minus anything `hook.skip` filters out. Resolution
/// goes through `names_check`, the one rule this and the severity lookup share:
/// `git config hook.skip ruff` skips `pre-commit-ruff` by short name.
fn selected<'a>(
    settings: &crate::config::Settings,
    stage: Stage,
    manifest: &'a crate::manifest::Manifest,
) -> Vec<&'a dyn Check> {
    selected_during(settings, stage, &[], manifest)
}

/// Do this repository's hooks apply the CONVENTIONS, or only the safety net?
///
/// `git config greengate.conventions declared` (usually `--global`, set by
/// `amont enroll`) scopes the house rules to repositories that commit an
/// `amont.conf` — the standing grant of `init.templateDir` then becomes safe
/// to hand a whole team: a clone of somebody else's project gets conflict,
/// secret, size and debug-leftover protection, and none of this team's
/// opinions about commit subjects or branch names. The default,
/// `everywhere`, keeps today's behaviour exactly.
///
/// Presence of the manifest is the declaration; its CONTENT stays
/// trust-gated. Reading presence executes nothing, so no consent is needed.
pub fn conventions_apply(
    settings: &crate::config::Settings,
    manifest: &crate::manifest::Manifest,
) -> bool {
    manifest.declared || !declared_mode(settings)
}

/// One config read per process — this sits on the hook path of every commit.
fn declared_mode(settings: &crate::config::Settings) -> bool {
    *settings.declared_mode.get_or_init(|| {
        crate::config::enumerated_or(
            settings,
            "greengate.conventions",
            &["everywhere", "declared"],
            "everywhere",
        ) == "declared"
    })
}

/// The checks for a stage, minus `hook.skip` and minus anything that declares
/// it does not run during an operation currently in progress.
fn selected_during<'a>(
    settings: &crate::config::Settings,
    stage: Stage,
    in_progress: &[crate::check::GitState],
    manifest: &'a crate::manifest::Manifest,
) -> Vec<&'a dyn Check> {
    let skips = configured_skips(settings);
    // Externals are included here, so `hook.skip` and the severity override
    // govern a declared command exactly as they govern a built-in. A repository
    // that can add a check it cannot disable would be a worse deal than not
    // being able to add one.
    let (kept, dropped): (Vec<_>, Vec<_>) = all_stage_checks(stage, manifest)
        .into_iter()
        .partition(|c| !skips.iter().any(|s| crate::skip_suppresses(c.name(), s)));
    let names: Vec<&str> = dropped.iter().map(|c| c.name()).collect();
    announce_skips(settings, manifest.file_name(), &names);

    // Announced separately from `hook.skip`, and with the operation named: "not
    // during a rebase" is a property of the moment and will be true again in a
    // minute, which is a different thing to tell a reader than "you disabled
    // this".
    let (kept, paused): (Vec<_>, Vec<_>) = kept.into_iter().partition(|check| {
        !check
            .scope()
            .not_during
            .iter()
            .any(|state| in_progress.contains(state))
    });
    if !paused.is_empty() {
        let what = in_progress
            .iter()
            .map(|s| s.as_str())
            .collect::<Vec<_>>()
            .join(" and ");
        println!(
            "{} {} check(s) paused during {what}: {}",
            warning_sign(),
            paused.len(),
            paused
                .iter()
                .map(|c| c.name())
                .collect::<Vec<_>>()
                .join(", ")
        );
    }

    // The conventions split, last: a held-back check was neither skipped (a
    // choice about THIS repository) nor paused (a property of the moment) —
    // this repository simply never subscribed. One line, count not names:
    // in the clone-of-somebody-else's-project case this prints on every
    // commit, and fifteen names every time is how a safety message becomes
    // scroll-past noise.
    if conventions_apply(settings, manifest) {
        return kept;
    }
    let (kept, held): (Vec<_>, Vec<_>) = kept
        .into_iter()
        .partition(|check| check.reach() == crate::check::Reach::Safety);
    if !held.is_empty() {
        println!(
            "{} {} convention check(s) held back — no {} here and \
             greengate.conventions is `declared`; the safety net still runs",
            warning_sign(),
            held.len(),
            manifest.file_name(),
        );
    }
    kept
}

/// The key that turns evidence ordering on. `declared` — the registry's
/// order, the one this file's header argues for — is the default and nothing
/// about it changes.
const ORDER: &str = "greengate.order";

/// How far back [`crate::gate_evidence::order_by_evidence`] looks. Not a
/// config key: it is an input to an ordering that changes nothing about what
/// runs, and a knob nobody can predict the effect of is a knob that invites
/// cargo-culting. Ninety days is the same window the report defaults to, so
/// the ordering a push takes is the ordering `amont-fleet gates` explains.
const ORDER_WINDOW_DAYS: u64 = 90;

/// Does this repository want its push gates ordered by what the record says?
fn evidence_ordering(settings: &crate::config::Settings) -> bool {
    crate::config::enumerated_or(settings, ORDER, &["declared", "evidence"], "declared")
        == "evidence"
}

/// Reorder the SCOPED push gates — the suites and audits — by the local
/// record, leaving everything else exactly where the registry put it.
///
/// Two halves, and the split is the safety property. The unscoped pre-push
/// checks ask about the PUSH — is this branch protected, is the name legal,
/// is the branch behind, is there a secret in it — and the registry orders
/// them "cheapest and most decisive first" for a reason: discovering a
/// protected branch after twenty minutes of tests is precisely the waste this
/// feature exists to remove, and promoting a suite above them would
/// reintroduce it. So they keep their positions absolutely.
///
/// The scoped gates are permuted among the positions they already occupy.
/// Nothing is added, removed or skipped — [`crate::gate_evidence`] argues
/// that at length — and with no history the permutation is the identity.
fn ordered_by_evidence<'a>(
    settings: &crate::config::Settings,
    checks: Vec<&'a dyn Check>,
) -> Vec<&'a dyn Check> {
    if !evidence_ordering(settings) || checks.len() < 2 {
        return checks;
    }
    let slots: Vec<usize> = checks
        .iter()
        .enumerate()
        .filter(|(_, c)| !c.scope().is_unscoped())
        .map(|(i, _)| i)
        .collect();
    if slots.len() < 2 {
        return checks;
    }
    let names: Vec<String> = slots
        .iter()
        .map(|&i| checks[i].name().to_string())
        .collect();
    let history = crate::gate_evidence::history_in(std::path::Path::new("."));
    if history.is_empty() {
        return checks;
    }
    let order = crate::gate_evidence::order_by_evidence(
        &names,
        &history,
        crate::gate_evidence::now(),
        ORDER_WINDOW_DAYS,
    );
    let mut out = checks.clone();
    for (slot, &pick) in slots.iter().zip(&order) {
        out[*slot] = checks[slots[pick]];
    }
    if out
        .iter()
        .map(|c| c.name())
        .ne(checks.iter().map(|c| c.name()))
    {
        crate::say!(
            "{} gate order from this repository's own record: {}",
            valid_sign(),
            slots
                .iter()
                .map(|&i| out[i].name())
                .collect::<Vec<_>>()
                .join(", ")
        );
    }
    out
}

/// Say out loud which checks did not run.
///
/// A skip is otherwise invisible at exactly the moment it matters. With
/// `hook.skip = merge-conflict` set, a commit printed six green ticks and no
/// hint that a seventh check had been disabled — the developer sees a clean run
/// and concludes they are covered.
///
/// It is worse than it sounds, because one value can silence a whole stage:
/// `hook.skip = pre-commit` suppresses all fifteen. That is now something
/// somebody meant rather than the accident it once was — `e` used to cost
/// twenty by substring reach — but a commit under it still looks exactly like a
/// commit that had nothing to report.
///
/// One line, only when something was actually skipped, so a normal commit is
/// unchanged. This reaches every skip however it was created — hand-edited
/// config included — which no dashboard can claim.
fn announce_skips(settings: &crate::config::Settings, manifest_file: &str, dropped: &[&str]) {
    if dropped.is_empty() {
        return;
    }
    // Two lines, not one: "you decided this" (hook.skip on this machine)
    // and "your team decided this" (a skip line in the committed
    // greengate.conf) are different things to be told — the same reason paused
    // and held-back get their own sentences. A name both sources suppress
    // is announced as the machine's: the local decision is the nearer one.
    let (machine, _policy) = crate::skips_by_source(settings);
    let (yours, theirs): (Vec<&&str>, Vec<&&str>) = dropped
        .iter()
        .partition(|name| machine.iter().any(|s| crate::skip_suppresses(name, s)));
    let say = |names: &[&&str], via: &str| {
        if names.is_empty() {
            return;
        }
        let plural = if names.len() == 1 { "check" } else { "checks" };
        println!(
            "{} {} {plural} skipped by {}: {}",
            warning_sign(),
            names.len(),
            highlight(via),
            names.iter().map(|n| **n).collect::<Vec<_>>().join(", ")
        );
    };
    say(&yours, "hook.skip");
    say(&theirs, manifest_file);
}

/// Say, once per stage, what the manifest's policy could not do — withheld
/// behind trust, or aiming at names that exist nowhere. Policy that silently
/// does not apply is a silent behaviour change, which is the one kind this
/// codebase does not allow itself.
fn announce_policy_state(settings: &crate::config::Settings, manifest: &crate::manifest::Manifest) {
    if let Some(why) = manifest.policy_withheld {
        println!(
            "{} {} policy not applied: {why}",
            warning_sign(),
            highlight(manifest.file_name()),
        );
    }
    for note in &manifest.policy_notes {
        println!("{} {}", warning_sign(), note);
    }
    // The version floor rides the same two call sites: once per stage,
    // beside the other "this repository expects something you lack" lines.
    crate::skew::announce_minimum(settings);
}

/// Run every item concurrently and collect `(name, code)` in the INPUT order.
///
/// Extracted so the concurrency itself can be tested with a rendezvous instead
/// of a stopwatch — an earlier wall-clock test was flaky the moment the machine
/// was busy, and a threshold that trips under load teaches you to ignore it.
fn run_concurrently<T, R, F>(items: &[T], run: F, if_thread_died: R) -> Vec<R>
where
    T: Sync,
    R: Send + Sync + Clone,
    F: Fn(&T) -> R + Sync,
{
    let slots: Vec<Mutex<Option<R>>> = items.iter().map(|_| Mutex::new(None)).collect();
    std::thread::scope(|scope| {
        for (item, slot) in items.iter().zip(&slots) {
            let run = &run;
            let died = &if_thread_died;
            scope.spawn(move || {
                // CAUGHT, not propagated. `thread::scope` re-raises a child
                // panic in the parent, which would abort the whole hook with a
                // backtrace and throw away the other nineteen checks' results —
                // and would make `if_thread_died` unreachable, which is what it
                // was until this test existed to notice.
                let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(item)))
                    .unwrap_or_else(|_| died.clone());
                *slot.lock().expect("poisoned") = Some(outcome);
            });
        }
    });
    slots
        .into_iter()
        .map(|s| {
            s.into_inner()
                .expect("poisoned")
                .unwrap_or_else(|| if_thread_died.clone())
        })
        .collect()
}

/// Take the index-fidelity hold, or say why the caller must stop.
///
/// Extracted from `pre_commit` so that `amont run` — which its own doc
/// comment calls "a rehearsal of the hook" — can take exactly the same hold
/// rather than judging the working tree while a real commit judges the index.
///
/// Around the WHOLE fan-out, not per check: twenty checks run concurrently and
/// would fight over one working tree.
fn hold_unstaged() -> Result<crate::staged_only::StagedOnly, Verdict> {
    // BEFORE `enter()`, not after: `enter()` is what checks out the tree and
    // parks the unstaged half, and a signal landing in the gap between that
    // and the handler being armed would hit the default disposition — dead
    // process, tree left checked out, nothing restored. The handler no-ops
    // harmlessly on a signal that arrives before there is anything held.
    crate::staged_only::install_signal_handler();
    match crate::staged_only::StagedOnly::enter() {
        Ok(guard) => Ok(guard),
        Err(e) => {
            // Refusing to check the wrong content is the safe direction; a
            // check that read the tree would be answering about a commit
            // nobody is making.
            eprintln!("{e}");
            Err(Verdict::Block)
        }
    }
}

pub fn pre_commit(ctx: &Ctx) -> Verdict {
    let settings = ctx.settings;
    // A detached rehearsal's passes become cluster tokens before any gate
    // asks for one (ADR-0017). Costs one `stat` when nothing is pending, and
    // nothing in a repository that declares no `platform=any` gate.
    crate::cluster::collect_if_declared(ctx.manifest);
    // Before anything runs: a pinned tool at the wrong version makes every
    // verdict below it suspect, and the warning costs one --version per pin.
    crate::manifest::verify_tool_pins(&ctx.manifest.pins, ctx.manifest.file_name());
    announce_policy_state(ctx.settings, ctx.manifest);
    let in_progress = crate::git_states_in_progress();
    let checks = selected_during(ctx.settings, Stage::PreCommit, &in_progress, ctx.manifest);

    // Tree gates (ADR-0024): judged BEFORE the hold, which is the only moment
    // unstaged edits are visible; started AFTER it, so they lint the commit's
    // tree. They never decide the commit.
    let tree_gates = if ctx.manifest.tree.is_empty() || !crate::tree_lint::enabled(settings) {
        None
    } else {
        match crate::tree_lint::guard(settings) {
            Some(why) => {
                crate::hooks::common::say("  tree lint not proven — CI will lint:");
                crate::hooks::common::say(&crate::tree_lint::fit_line("    ", &why, ""));
                crate::tree_lint::note_withheld(&ctx.manifest.tree);
                None
            }
            None => Some(&ctx.manifest.tree),
        }
    };

    let held = match hold_unstaged() {
        Ok(guard) => guard,
        Err(verdict) => return verdict,
    };

    let root = crate::hooks::common::repo_root();
    // How long this commit's own declared checks are expected to run — the
    // cover a tree gate can hide behind — from their last measured runs.
    let decls =
        crate::hooks::run_tests::blocking_commit_decls(ctx.settings, &ctx.manifest.externals);
    // Only declarations whose scope this commit touches RUN; the others
    // return at once, and their duration says nothing about cover.
    let staged = if ctx.manifest.tree.is_empty() {
        Vec::new()
    } else {
        crate::hooks::common::staged_files(&[])
    };
    // A declaration in scope that was never measured is UNKNOWN cover, and
    // unknown means run: the run teaches both numbers, exactly as an unknown
    // gate time does. Guessing 0 would skip the one commit that could learn.
    let cover_ms = if tree_gates.is_some() {
        decls
            .iter()
            .filter(|d| d.scope.touches(&staged))
            .map(|d| crate::tree_cache::duration_of(&d.id).unwrap_or(u64::MAX))
            .max()
            .unwrap_or(0)
    } else {
        0
    };
    let side_car = tree_gates.and_then(|g| {
        crate::tree_lint::start(
            settings,
            std::path::Path::new(&root),
            g,
            &ctx.manifest.pins,
            cover_ms,
        )
    });

    let severities = Overrides::read(settings);
    // Resolved once and handed down (ADR-0020): the stage and the wave
    // ledger below ask the same question, and each read of a git setting is
    // a spawn the commit's budget counts (`spawn_budget.rs`).
    let waves = Waves::resolve(settings);
    let (verdict, outcomes, durations) =
        run_stage_traced(settings, &checks, ctx, &severities, waves);
    // Remember how long the declared checks that judged something took, for
    // the next commit's cover estimate.
    if !ctx.manifest.tree.is_empty() {
        let measured: Vec<(String, u64)> = checks
            .iter()
            .zip(outcomes.iter().zip(&durations))
            .filter(|(c, (o, _))| {
                matches!(o, Outcome::Passed | Outcome::Failed)
                    && decls
                        .iter()
                        .any(|d| d.id == c.name() && d.scope.touches(&staged))
            })
            .map(|(c, (_, ms))| (c.name().to_string(), *ms))
            .collect();
        crate::tree_cache::record_durations(&measured);
    }

    // The wave ledger (ADR-0020): how long the Light wave held the Heavy one
    // back, and what a blocking Light failure skipped. Hook only, never
    // `amont run`, like the downgrade ledger below.
    if waves == Waves::LightThenHeavy {
        let light_ms = checks
            .iter()
            .zip(&durations)
            .filter(|(c, _)| !is_heavy(**c))
            .map(|(_, ms)| *ms)
            .max()
            .unwrap_or(0);
        let skipped: Vec<&str> = checks
            .iter()
            .zip(&outcomes)
            .filter(|(_, o)| **o == Outcome::Skipped)
            .map(|(c, _)| c.name())
            .collect();
        // Heavy checks this change reached that judged something, or would
        // have: clippy on a `.txt`-only commit returns `Passed` having judged
        // nothing, and one that came back `Inert`, `Unavailable` or `Deferred`
        // waited for nothing either. A commit with none writes no line, and
        // spends no git spawn on the ledger's path (`spawn_budget.rs`). The
        // staged list is the stage's own, cached; the tracked list is read
        // only for a Heavy check this change touched (`would_judge` asks it
        // only then), so an ordinary commit pays nothing here.
        let staged = crate::hooks::common::staged_files(&[]);
        let heavy_checks = checks
            .iter()
            .zip(&outcomes)
            .filter(|(c, o)| is_heavy(**c) && o.judged_or_skipped())
            .filter(|(c, _)| c.scope().touches(&staged))
            .filter(|(c, _)| {
                c.would_judge(&staged, crate::hooks::common::tracked_files().as_deref())
            })
            .count();
        crate::waves::note(light_ms, heavy_checks, &skipped);
    }

    // The shadow-mode ledger. Silent, best-effort, and never consulted by any
    // verdict — see `crate::downgrade`.
    crate::downgrade::note(
        settings,
        &downgraded_events(&checks, &outcomes, &severities),
    );

    // What post-commit will bind to the commit: the gate-declared checks
    // that RAN clean, recorded while the index still is the commit's tree.
    // Called on every verdict — an empty record clears any leftover marker,
    // so a blocked attempt (or a repo with nothing declared) cannot leave an
    // earlier attempt's marker to vouch for the next commit. `Unavailable`
    // deliberately does not qualify: a check whose tool is missing judged
    // nothing, and stamping it would be the paper promise this exists to
    // replace.
    // EVERY blocking declaration, not only the npm GATE names: a custom
    // `pre-commit check … block …` earns its stamp the same way, and a
    // same-named pre-push declaration defers to it (see `pair_verdict`).
    let ran: Vec<String> = if matches!(verdict, Verdict::Block) {
        Vec::new()
    } else {
        crate::hooks::run_tests::blocking_commit_decls(ctx.settings, &ctx.manifest.externals)
            .into_iter()
            .filter(|d| {
                checks
                    .iter()
                    .zip(&outcomes)
                    .any(|(c, o)| c.name() == d.id && matches!(o, Outcome::Passed | Outcome::Fixed))
            })
            // A pass the cluster proved is recorded in its own ref and never
            // becomes a local token (ADR-0016).
            .filter(|d| !crate::cluster::proved_on_index(&d.id))
            // The token, not the bare script: a skip is honoured only for the
            // same command run by the same program (`gate_identity`). A
            // declaration whose program cannot be identified earns no stamp.
            .filter_map(|d| {
                ctx.manifest
                    .externals
                    .iter()
                    .find(|e| e.id == d.id)
                    .and_then(|e| crate::gate_identity::external_token(e, &d.script))
            })
            .collect()
    };
    // A rewrite means the tree the gates linted is not the one committed.
    let stampable =
        !matches!(verdict, Verdict::Block) && !outcomes.iter().any(|o| matches!(o, Outcome::Fixed));
    let mut ran = ran;
    if let Some(car) = side_car {
        ran.extend(crate::tree_lint::finish(settings, car, stampable));
    }
    let ran: Vec<&str> = ran.iter().map(String::as_str).collect();
    crate::gate_stamp::record(&ran);
    // The blocking declarations the busy policy deferred, by script name, on
    // the staged tree (the commit's, under the hold): pre-push reads them to
    // defer the push twin too (ADR-0013). Never a token: nothing is stamped.
    let deferred: Vec<String> =
        crate::hooks::run_tests::blocking_commit_decls(ctx.settings, &ctx.manifest.externals)
            .into_iter()
            .filter(|d| {
                checks
                    .iter()
                    .zip(&outcomes)
                    .any(|(c, o)| c.name() == d.id && matches!(o, Outcome::Deferred))
            })
            .map(|d| d.script)
            .collect();
    if !deferred.is_empty() {
        if let Some(tree) = crate::git::stdout(&["write-tree"]) {
            crate::gate_stamp::record_deferred(&tree, &deferred);
        }
    }
    // Under the hold, the index IS the commit's tree: its evidence goes there.
    if !ctx.manifest.tree.is_empty() {
        if let Some(tree) = crate::git::stdout(&["write-tree"]) {
            crate::tree_lint::flush_evidence(&tree);
        }
    }

    drop(held);
    verdict
}

/// The checks that FAILED without blocking, each with why — the shadow-mode
/// signal [`crate::downgrade`] keeps.
///
/// Derived at the hook entry points and deliberately NOT inside
/// [`run_stage_traced`], which is where `classify` already computes the same
/// set. `run_all` reaches that function too, so recording there would let
/// every `amont run` rehearsal inflate a ledger a lead is going to read as a
/// count of real commits — and `run --all-files` over a dirty tree would add
/// dozens of events for content nobody is committing.
///
/// A check that DECLARES `warn` is counted but is not evidence about a
/// rollout: it was never going to block, so calling it "would have blocked"
/// would inflate the one number the whole feature exists to produce. Only an
/// override of a blocking check earns that.
fn downgraded_events(
    checks: &[&dyn Check],
    outcomes: &[Outcome],
    severities: &Overrides,
) -> Vec<(String, crate::downgrade::Origin)> {
    checks
        .iter()
        .zip(outcomes)
        .filter(|(_, o)| matches!(o, Outcome::Failed))
        .filter(|(c, _)| matches!(severities.of(**c), Severity::Warn))
        .map(|(c, _)| (c.name().to_string(), downgrade_origin(*c, severities)))
        .collect()
}

/// Why this check did not block. Shared, because `pre_push` fail-fasts and
/// never builds an outcomes vector to hand to [`downgraded_events`].
fn downgrade_origin(check: &dyn Check, severities: &Overrides) -> crate::downgrade::Origin {
    use crate::downgrade::Origin;
    use crate::registry::Source;
    if matches!(check.severity(), Severity::Warn) {
        return Origin::Declared;
    }
    match severities.applied_with_source(check.name()) {
        Some((_, _, Source::Config)) => Origin::Config,
        Some((_, _, Source::Policy)) => Origin::Policy,
        // Declared `block`, resolved `warn`, and nothing claims to have
        // overridden it: a contradiction. Count it, but not as evidence — the
        // conservative direction for a number whose only failure mode is
        // being too alarming.
        None => Origin::Declared,
    }
}

/// The pre-commit body, over the checks it is GIVEN.
///
/// A seam, so a test can hand it a check that panics. Without it the value
/// standing in for a dead check was a literal at one call site that no test
/// could reach — the rule was asserted on the runner and merely hoped for here.
fn run_stage(checks: &[&dyn Check], ctx: &Ctx, severities: &Overrides) -> Verdict {
    let settings = ctx.settings;
    run_stage_traced(settings, checks, ctx, severities, Waves::resolve(settings)).0
}

/// [`run_stage`], keeping the per-check outcomes — index-aligned with
/// `checks` — alive past the verdict. `pre_commit` needs them to know which
/// gate-declared checks actually ran (`gate_stamp`); `Report` cannot answer
/// that, because `classify` deliberately drops the names of `Passed`.
fn run_stage_traced(
    settings: &crate::config::Settings,
    checks: &[&dyn Check],
    ctx: &Ctx,
    severities: &Overrides,
    waves: Waves,
) -> (Verdict, Vec<Outcome>, Vec<u64>) {
    if checks.is_empty() {
        return (Verdict::Proceed, Vec::new(), Vec::new());
    }
    // One slot per check: everything a check says lands in its own buffer
    // and reaches stdout as ONE block when it finishes — see `live`. Off
    // (`greengate.progress false`), no sink is ever installed and every print
    // streams exactly as it always did.
    let stage = crate::live::enabled(settings).then(|| {
        let names: Vec<&str> = checks.iter().map(|c| c.name()).collect();
        crate::live::Stage::begin(settings, &names)
    });
    let items: Vec<(usize, &&dyn Check)> = checks.iter().enumerate().collect();
    let run_one = |(idx, check): &(usize, &&dyn Check)| -> (Outcome, u64) {
        let started = std::time::Instant::now();
        let _sink = stage.as_ref().map(|s| s.enter(*idx));
        // The block is emitted however the check leaves — a panicking
        // check's partial output still reaches the reader, above the
        // dead-check verdict `run_concurrently` fills in.
        let flush = stage
            .as_ref()
            .map(|s| crate::live::FinishOnDrop::new(ctx.settings, s, *idx));
        let sub = Ctx {
            name: check.name(),
            args: ctx.args,
            hooks_dir: ctx.hooks_dir,
            push: ctx.push,
            manifest: ctx.manifest,
            settings: ctx.settings,
            handed_to_cluster: ctx.handed_to_cluster,
            land: ctx.land,
            audits: ctx.audits,
            source_worktree: ctx.source_worktree,
        };
        let slot = enter(**check, || severities.of(**check));
        let outcome = deferred_or(&slot, check.run(&sub));
        if let Some(f) = &flush {
            f.outcome(outcome);
        }
        // The record measures the check, not its wait for a host slot.
        let ran = started.elapsed().saturating_sub(slot.queued());
        let ms = u64::try_from(ran.as_millis()).unwrap_or(u64::MAX);
        (outcome, ms)
    };
    // A check whose thread died has not passed. Stated here, where the slot
    // is filled, rather than hidden in a `Default` impl that every future
    // `#[derive(Default)]` would silently inherit.
    let died = (Outcome::Failed, 0);
    let timed = match waves {
        Waves::LightThenHeavy => in_waves(&items, &run_one, died, severities),
        Waves::One => run_concurrently(&items, run_one, died),
    };
    let (outcomes, durations): (Vec<Outcome>, Vec<u64>) = timed.into_iter().unzip();

    let report = classify(checks, &outcomes, severities);
    announce(settings, &report);
    (report.verdict(), outcomes, durations)
}

/// How a pre-commit stage runs its checks (ADR-0020).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Waves {
    /// Every check at once, as before 2.1 (`greengate.failFast false`).
    One,
    /// The Light checks, then the Heavy ones only if none blocked.
    LightThenHeavy,
}

impl Waves {
    /// `GREENGATE_FAIL_FAST` for one run, then `greengate.failFast` (git config, then
    /// a trusted `set failFast` in `amont.conf`), then on. Read once by the
    /// caller and handed down, never cached behind the settings it takes.
    fn resolve(settings: &crate::config::Settings) -> Waves {
        if resolve_fail_fast(std::env::var(FAIL_FAST_ENV).ok().as_deref(), settings) {
            Waves::LightThenHeavy
        } else {
            Waves::One
        }
    }
}

/// Heavy checks take a host slot and run in the second wave (ADR-0009,
/// ADR-0020); everything else is Light.
fn is_heavy(check: &dyn Check) -> bool {
    check.weight() == crate::host_slots::Weight::Heavy
}

const FAIL_FAST_ENV: &str = "GREENGATE_FAIL_FAST";

/// [`Waves::resolve`] with the environment value handed in: the testable seam,
/// because setting a variable in a threaded test binary races its siblings.
fn resolve_fail_fast(from_env: Option<&str>, settings: &crate::config::Settings) -> bool {
    match from_env
        .filter(|v| !v.is_empty())
        .map(str::to_ascii_lowercase)
        .as_deref()
    {
        Some("true" | "1" | "yes" | "on") => true,
        Some("false" | "0" | "no" | "off") => false,
        Some(other) => {
            crate::config::complain(
                FAIL_FAST_ENV,
                &format!("{other:?} is not true or false"),
                "greengate.failFast",
            );
            crate::config::boolean_or(settings, "greengate.failFast", true)
        }
        None => crate::config::boolean_or(settings, "greengate.failFast", true),
    }
}

/// The stage in two waves (ADR-0020): every Light check at once, then — only
/// if none of them FAILED at a blocking severity — every Heavy check at once.
/// A Heavy check the first wave condemned never starts: it takes no host
/// slot, earns no stamp, and comes back `Skipped`. Results stay index-aligned
/// with `items`, as `run_concurrently`'s do.
///
/// Waves, not cancellation: the check runner kills only a tool's direct child
/// (`wait_within`), so stopping a running `cargo test` would orphan its test
/// binaries. A wave that never starts needs no kill.
fn in_waves<'a, F>(
    items: &[(usize, &&'a dyn Check)],
    run: &F,
    died: (Outcome, u64),
    severities: &Overrides,
) -> Vec<(Outcome, u64)>
where
    F: Fn(&(usize, &&'a dyn Check)) -> (Outcome, u64) + Sync,
{
    let (light, heavies): (Vec<_>, Vec<_>) =
        items.iter().copied().partition(|(_, c)| !is_heavy(**c));
    let mut out = vec![died; items.len()];
    let light_out = if light.is_empty() {
        Vec::new()
    } else {
        run_concurrently(&light, run, died)
    };
    // A dead Light thread reads `Failed` and so condemns the Heavy wave: a
    // check that died has not passed.
    let blocked = light
        .iter()
        .zip(&light_out)
        .any(|((_, c), (o, _))| *o == Outcome::Failed && severities.of(**c) == Severity::Block);
    for ((idx, _), r) in light.iter().zip(light_out) {
        out[*idx] = r;
    }
    if heavies.is_empty() {
        return out;
    }
    if blocked {
        // Only a check that would have judged something is SKIPPED; the rest
        // would have come back `Inert` (clippy in a repository with no Rust),
        // and naming them would list checks that never apply here. The check
        // answers for itself (`Check::would_judge`).
        let staged = crate::hooks::common::staged_files(&[]);
        let tracked = crate::hooks::common::tracked_files();
        for (idx, c) in &heavies {
            out[*idx] = if c.would_judge(&staged, tracked.as_deref()) {
                (Outcome::Skipped, 0)
            } else {
                (Outcome::Inert, 0)
            };
        }
        return out;
    }
    for ((idx, _), r) in heavies.iter().zip(run_concurrently(&heavies, run, died)) {
        out[*idx] = r;
    }
    out
}

/// What a stage concluded, before anything is printed or exited.
///
/// A VALUE, so the classification can be asserted directly. While this was one
/// function that classified, printed and returned an exit code, its tests could
/// only check the code — whether the right thing was SAID went untested.
#[derive(Debug, Default, PartialEq, Eq)]
struct Report<'a> {
    /// Repaired. The commit proceeds, but the author's files changed under
    /// them and that must be said out loud.
    fixed: Vec<&'a str>,
    /// Failed, and the severity that applies blocks.
    blocked: Vec<&'a str>,
    /// Failed, but configured to warn. The check printed an error and meant it,
    /// so somebody has to say it did not block.
    downgraded: Vec<&'a str>,
    /// Could not run. Distinct from "passed", which is the whole point.
    unavailable: Vec<&'a str>,
    /// Deferred to CI by the busy policy (ADR-0013). Not passed, not a gap
    /// on this machine's part either: said so, with what to do about it.
    deferred: Vec<(&'a str, Severity)>,
    /// Heavy checks that never started because a Light one blocked first
    /// (ADR-0020). Said in quiet mode too: a refused commit whose suite did
    /// not run must never read as one whose suite passed.
    skipped: Vec<&'a str>,
    /// How many passed outright. Only read when `greengate.quiet` swallowed their
    /// individual lines — a run that says nothing at all is indistinguishable
    /// from a gate that never ran, and that is the one thing this crate will
    /// not let a reader believe.
    passed: usize,
}

impl Report<'_> {
    fn verdict(&self) -> Verdict {
        Verdict::blocking(!self.blocked.is_empty())
    }
}

/// Pure: outcomes and severities in, a verdict out. No IO.
fn classify<'a>(
    checks: &[&'a dyn Check],
    outcomes: &[Outcome],
    severities: &Overrides,
) -> Report<'a> {
    let mut report = Report::default();
    for (check, outcome) in checks.iter().zip(outcomes) {
        match outcome {
            Outcome::Passed => report.passed += 1,
            // `Warned` needs nothing: a check that chose to warn has already
            // said what it wanted to, and a roll-up would only repeat it.
            Outcome::Warned => {}
            Outcome::Fixed => report.fixed.push(check.name()),
            Outcome::Unavailable => report.unavailable.push(check.name()),
            // Judged nothing, said nothing: not a pass to count, not a gap
            // to announce.
            Outcome::Inert => {}
            Outcome::Deferred => report.deferred.push((check.name(), severities.of(*check))),
            Outcome::Skipped => report.skipped.push(check.name()),
            Outcome::Failed => match severities.of(*check) {
                Severity::Block => report.blocked.push(check.name()),
                Severity::Warn => report.downgraded.push(check.name()),
            },
        }
    }
    report
}

/// Says what happened. Prints; decides nothing.
fn announce(settings: &crate::config::Settings, report: &Report) {
    if crate::live::quiet(settings) && report.passed > 0 {
        println!("{} {} check(s) passed", valid_sign(), report.passed);
    }
    if !report.fixed.is_empty() {
        // Louder than a pass, because files on disk are not what the author
        // left them: they asked for the repair, but they did not watch it.
        println!(
            "{} {} check(s) fixed and re-staged: {}",
            valid_sign(),
            report.fixed.len(),
            report.fixed.join(", ")
        );
    }
    if !report.unavailable.is_empty() {
        // Distinct from "passed". Silence here is how a repo looks verified
        // when nothing actually ran — the trailing count is the one line
        // guaranteed to be read, whatever the twenty blocks above said.
        println!(
            "{} {} check(s) could not run: {}",
            warning_sign(),
            report.unavailable.len(),
            report.unavailable.join(", ")
        );
    }
    if !report.deferred.is_empty() {
        announce_deferred(&report.deferred);
    }
    if !report.downgraded.is_empty() {
        println!(
            "{} {} check(s) reported a problem but are set to warn: {}",
            warning_sign(),
            report.downgraded.len(),
            report.downgraded.join(", ")
        );
    }
    if !report.skipped.is_empty() {
        announce_skipped(&report.skipped, &report.blocked);
    }
    if report.blocked.is_empty() {
        return;
    }
    println!("\n🚨  Error raised by:");
    for name in &report.blocked {
        println!("    - {}", highlight(name));
    }
}

/// Point every check at `git ls-files` instead of the index.
///
/// THE definition, called from both entry points. There used to be two: this
/// one, and a copy in `main.rs` built from a RAW `ls-files` — no `-z` — whose
/// output git QUOTES for any unusual byte, so `é.json` arrived as the nine-byte
/// literal `"\303\251.json"` and was handed to prettier and eslint as a path
/// that does not exist. And because `override_file_set` writes a `OnceLock`,
/// main's quoted list WON: whichever ran first was the one that counted, and
/// main's ran first. `git.rs` documents this exact failure.
pub fn enter_all_files_mode() {
    crate::hooks::common::override_file_set(
        crate::git::stdout_paths(&["ls-files"]).unwrap_or_default(),
    );
}

/// `amont run` — every applicable check, on demand.
///
/// Two questions, and the mode says which it answers:
///
/// - **staged** (default) is "would my commit pass" — the same set a commit
///   would check, so it is a rehearsal of the hook, and it takes the same
///   index-fidelity hold the hook takes.
/// - **`--all-files`** is "does my working tree pass". Deliberately NOT the same
///   question: on a dirty tree it reports on content that is not committed and
///   may never be. That is right for adopting a check into an existing
///   repository, where `git add .` is not an acceptable way to measure the mess,
///   and it is why `--all-files` takes no stash — there is no staged/unstaged
///   distinction to protect when the answer is "all of it".
pub fn run_all(ctx: &Ctx, all_files: bool) -> Verdict {
    let settings = ctx.settings;
    // ORDER: the override goes in FIRST. It is what tells `fixing_enabled` and
    // `restage` that the file set is not the index, and both are consulted
    // from inside the checks below.
    if all_files {
        enter_all_files_mode();
        if crate::hooks::common::fixing_requested(settings) {
            println!(
                "{} {} is set, but fixing is off for {}: the input set is the \
                 working tree, not the index",
                warning_sign(),
                highlight("greengate.fix"),
                highlight("--all-files")
            );
        }
        // Stash-free, per decision 1 of docs/index-fidelity-and-run-modes.md:
        // there is no staged/unstaged distinction to protect when the input
        // set is `git ls-files`, so a hold would be surprising extra mutation
        // with no correctness upside.
        return run_stage(
            &selected(ctx.settings, Stage::PreCommit, ctx.manifest),
            ctx,
            &Overrides::read(settings),
        );
    }

    // Staged mode IS a rehearsal of the commit, so it takes the same hold the
    // commit does. Without it, `amont run` failed on garbage in the tree
    // that `git commit` — which holds the unstaged half aside — passed, and
    // vice versa: the two modes disagreed about the same repository, which is
    // exactly what this mode exists not to do.
    let held = match hold_unstaged() {
        Ok(guard) => guard,
        Err(verdict) => return verdict,
    };
    let verdict = run_stage(
        &selected(ctx.settings, Stage::PreCommit, ctx.manifest),
        ctx,
        &Overrides::read(settings),
    );
    // AFTER the report has been printed: dropping earlier would put the
    // unstaged content back under a check that is still reading files.
    drop(held);
    verdict
}

/// `amont run <check>` — one check by name. `None` when there is no such
/// check, which the caller turns into a usage error.
///
/// Lives here rather than in `main.rs` so `registry::lookup` stays inside the
/// runtime, and so the hold decision is made once: a named check takes the
/// index-fidelity hold only when it is a `Stage::PreCommit` check running in
/// staged mode. A pre-push or commit-msg check invoked by name must never
/// touch the working tree — nothing about a push is a staging operation.
/// Resolve what `amont run <name>` means, exactly as `hook.skip` resolves a
/// name — the rest of the tool taught `ban-terms`; making `run` demand the
/// full id was a pointless second vocabulary. Ambiguity is an answer, not a
/// guess: the two `branch-pattern` checks are different code at different
/// stages.
///
/// Public because the CALLER needs the answer before anything else happens:
/// main decides whether to synthesize push refs from the resolved name, and
/// an ambiguous name must say so rather than fail on a missing upstream it
/// was never going to use.
pub fn resolve_check_name(name: &str, manifest: &crate::manifest::Manifest) -> Named2 {
    if crate::registry::lookup(name, manifest).is_some() {
        return Named2::Resolved(name.to_string());
    }
    let mut matches: Vec<String> = crate::registry::CHECKS
        .iter()
        .map(|c| c.name.to_string())
        .chain(manifest.externals.iter().map(|e| e.id.clone()))
        .filter(|id| crate::skip_suppresses(id, name))
        .collect();
    matches.dedup();
    match matches.len() {
        0 => Named2::Unknown,
        1 => Named2::Resolved(matches.remove(0)),
        _ => Named2::Ambiguous(matches),
    }
}

/// How a run name resolved.
pub enum Named2 {
    Resolved(String),
    Unknown,
    Ambiguous(Vec<String>),
}

pub fn run_named(ctx: &Ctx, name: &str, all_files: bool) -> Named {
    let full: String = match resolve_check_name(name, ctx.manifest) {
        Named2::Resolved(id) => id,
        Named2::Unknown => return Named::Unknown,
        Named2::Ambiguous(ids) => return Named::Ambiguous(ids),
    };
    let name = full.as_str();
    let Some(run_check) = crate::registry::lookup(name, ctx.manifest) else {
        return Named::Unknown;
    };
    // The Ctx must carry the RESOLVED id: lookup's closure re-resolves
    // through `ctx.name`, and handing it the short name back would panic on
    // the very ambiguity this function just settled.
    let ctx = &Ctx {
        name,
        args: ctx.args,
        hooks_dir: ctx.hooks_dir,
        push: ctx.push,
        manifest: ctx.manifest,
        settings: ctx.settings,
        handed_to_cluster: ctx.handed_to_cluster,
        land: ctx.land,
        audits: ctx.audits,
        source_worktree: ctx.source_worktree,
    };
    // Under quiet, a check run by name is captured like one inside its stage
    // — one slot, its tool's output to a log, one line on a pass — whatever
    // `greengate.progress` says: the person who asked for quiet asked for this.
    let check = crate::registry::one_named(name, ctx.manifest);
    let run = |ctx: &Ctx| match check.filter(|_| crate::live::quiet(ctx.settings)) {
        Some(check) => run_quiet(ctx, check),
        None => run_check(ctx),
    };
    if all_files {
        enter_all_files_mode();
        return Named::Ran(run(ctx));
    }
    let is_pre_commit_check = check.is_some_and(|c| c.stage() == Stage::PreCommit);
    if !is_pre_commit_check {
        return Named::Ran(run(ctx));
    }
    let held = match hold_unstaged() {
        Ok(guard) => guard,
        Err(verdict) => return Named::Ran(verdict),
    };
    let verdict = run(ctx);
    drop(held);
    Named::Ran(verdict)
}

/// One check by name, in a one-slot stage. The verdict is the one
/// `registry::lookup` gives a check: blocking only a failed `block` check.
/// Enter `check` for the host-slot bookkeeping: a heavy check whose severity
/// is `warn` never waits for a slot (`host_slots::never_waits`), except inside
/// a rehearsal snapshot, where no push connection is open, no commit waits,
/// and land's pre-stage needs the check's evidence: there it follows the
/// busy policy the rehearsal sets, except in land's pre-stage, where a `warn`
/// check waits at most `greengate.warnSlotWait` and then runs unqueued
/// (`host_slots::wait_bounded_for_warn`). Only a heavy check can wait, so only it
/// asks `severity`, which the caller answers from its stage's severity fold
/// when it has one: a git-config read per check broke the commit's git-spawn
/// budget.
fn enter(check: &dyn Check, severity: impl FnOnce() -> Severity) -> crate::host_slots::CheckGuard {
    let guard = crate::host_slots::enter_check(check.name(), check.weight());
    if check.weight() == crate::host_slots::Weight::Heavy {
        if !crate::rehearsal::in_snapshot() {
            if matches!(severity(), Severity::Warn) {
                crate::host_slots::never_waits();
            }
        } else if crate::rehearsal::in_prestage() && matches!(severity(), Severity::Warn) {
            crate::host_slots::wait_bounded_for_warn();
        }
    }
    guard
}

fn run_quiet(ctx: &Ctx, check: &dyn Check) -> Verdict {
    let stage = crate::live::Stage::begin(ctx.settings, &[check.name()]);
    stage.named();
    let _sink = stage.enter(0);
    let flush = crate::live::FinishOnDrop::new(ctx.settings, &stage, 0);
    let outcome = {
        let slot = enter(check, || crate::registry::severity_of(ctx.settings, check));
        deferred_or(&slot, check.run(ctx))
    };
    flush.outcome(outcome);
    // The block prints here, before anything the caller says after it.
    drop(flush);
    // The same rule `registry::lookup` applies, with every variant named.
    let blocks = match outcome {
        Outcome::Failed => match crate::registry::severity_of(ctx.settings, check) {
            Severity::Block => true,
            Severity::Warn => false,
        },
        Outcome::Passed
        | Outcome::Warned
        | Outcome::Fixed
        | Outcome::Unavailable
        | Outcome::Inert
        | Outcome::Deferred
        | Outcome::Skipped => false,
    };
    Verdict::blocking(blocks)
}

/// What `run_named` resolved a name to.
pub enum Named {
    Ran(Verdict),
    /// Nothing matches — full id, short name, or entrypoint.
    Unknown,
    /// A short name that reaches more than one check; the caller lists them
    /// so the user can pick a full id.
    Ambiguous(Vec<String>),
}

/// Why a pre-push gate need not run in this push (ADR-0018: the refusal and
/// the loop ask the same question, through `pre_push`'s `decide`).
enum Skip {
    /// The rehearsal that made this snapshot gave it to the cluster.
    HandedToCluster,
    /// Its stamp, or its cluster token, is on every pushed tip.
    Stamped,
    /// It completed without passing on every pushed tip's tree, in a
    /// rehearsal or land's pre-stage (ADR-0018). Never a pass: it is not
    /// attested, and only a push that would otherwise refuse honours it.
    CompletedEarlier,
    /// Its commit-time twin was proved on the cluster for every tip.
    TwinOnCluster(String),
    /// Its commit-time pair covered the push; `coverage` says whether by every
    /// pushed commit's stamp or by the tips' own stamp keys (ADR-0019).
    GatedAtCommit {
        name: String,
        coverage: crate::hooks::run_tests::Coverage,
    },
    /// Its commit-time pair was deferred to CI on this many pushed commits.
    DeferredAtCommit(String, usize),
}

/// What `decide` says about one gate: skip it, for a reason, or run it —
/// noting the commit-time pair that left this many pushed commits unstamped.
enum Decision {
    Skip(Skip),
    Run {
        unstamped_pair: Option<(String, usize)>,
        /// A same-named commit-time declaration that did not vouch, and why:
        /// the push says so before it runs the gate.
        unpaired: Option<(String, crate::hooks::run_tests::WhyNot)>,
    },
}

/// `greengate.pushStamps`, as the refusal needs it: whether anything run before
/// the push can let it skip its gates.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum StampReuse {
    On,
    Off,
}

/// The tag a push carries, if it pushes one: its refusal names
/// `amont land --tag`, since `amont land` alone pushes the branch.
fn pushed_tag(refs: &[crate::pushrefs::PushRef]) -> Option<&str> {
    refs.iter()
        .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
        .find_map(|r| r.remote_ref.strip_prefix("refs/tags/"))
}

/// The bare push's refusal (ADR-0018), one command per line, each line at most
/// 80 columns, so each copies cleanly. With stamp reuse off, nothing amont can
/// run beforehand lets this push skip its gates, so `rehearse` is not
/// offered. A tag push is offered `amont land --tag`, never the branch
/// remedies, whose records do not answer for a release.
pub(crate) fn push_refusal(
    short: &str,
    missing: &[&str],
    reuse: StampReuse,
    tag: Option<&str>,
) -> Vec<String> {
    let mut out = vec![format!(
        "{BIN}: push refused: {} push gate{} {} not run on {short}:",
        missing.len(),
        if missing.len() == 1 { "" } else { "s" },
        if missing.len() == 1 { "has" } else { "have" },
    )];
    out.extend(wrap_names(missing));
    let land = match tag {
        Some(tag) => format!("{BIN} land --tag {tag}"),
        None => format!("{BIN} land"),
    };
    if reuse == StampReuse::Off {
        out.push("    stamp reuse is off (greengate.pushStamps false); turn it on:".to_string());
        out.push("        git config greengate.pushStamps true".to_string());
        out.push("    then run the gates before git connects, and push:".to_string());
        out.push(format!("        {land}"));
    } else {
        out.push("    run them before git connects, then push:".to_string());
        out.push(format!("        {land}"));
        if tag.is_none() {
            out.push("    or stamp this tree first:".to_string());
            out.push(format!("        {BIN} rehearse --wait"));
        }
    }
    out.push("    or run them in this push:".to_string());
    out.push("        git config greengate.pushGates inline".to_string());
    out
}

/// The refusal inside `amont land`'s own push, led by the sentinel `land`
/// matches. `land` is what land's pre-stage saw: a pushed range whose remote
/// side differs is the remote moving under land; anything else is evidence
/// the pre-stage should have left and did not.
pub(crate) fn land_refusal(
    land: &crate::rehearsal::LandLine,
    refs: &[crate::pushrefs::PushRef],
    missing: &[&str],
) -> Vec<String> {
    let moved = refs
        .iter()
        .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
        .any(|r| r.remote_oid != land.remote_tip);
    let mut out = Vec::new();
    if moved {
        out.push(crate::land::LAND_REMOTE_MOVED.to_string());
        out.push(format!(
            "{BIN}: the remote moved during land; run {BIN} land again"
        ));
    } else {
        out.push(crate::land::LAND_EVIDENCE_MISSING.to_string());
        out.push(format!("{BIN}: land's pre-stage left no evidence for:"));
    }
    out.extend(wrap_names(missing));
    out
}

/// Gate names as indented lines of at most 80 columns.
pub(crate) fn wrap_names(names: &[&str]) -> Vec<String> {
    let mut lines = Vec::new();
    let mut line = String::from("       ");
    for name in names {
        if line.len() + 1 + name.len() > 80 && !line.trim().is_empty() {
            lines.push(std::mem::replace(&mut line, String::from("       ")));
        }
        line.push(' ');
        line.push_str(name);
    }
    if !line.trim().is_empty() {
        lines.push(line);
    }
    lines
}

pub fn pre_push(ctx: &Ctx) -> Verdict {
    let settings = ctx.settings;
    // `greengate.treeLintWait` counts from HERE, so no earlier wait (a test
    // rehearsal's `greengate.rehearsalWait`) can extend it.
    let push_started = std::time::Instant::now();
    // The notes push `attest` makes re-enters this hook; its ref list is only
    // ever the attest ref, so there is nothing to prove — and proving it
    // would recurse.
    if crate::attest::push_guard_active() {
        return Verdict::Proceed;
    }
    // Before the stamps are read: what a detached rehearsal finished while the
    // laptop was away counts at this push (ADR-0017). Not inside a rehearsal's
    // own snapshot, which stands in for a push that is not happening.
    if !crate::rehearsal::in_snapshot() {
        crate::cluster::collect_if_declared(ctx.manifest);
    }
    crate::manifest::verify_tool_pins(&ctx.manifest.pins, ctx.manifest.file_name());
    announce_policy_state(ctx.settings, ctx.manifest);
    // NB: no CHERRY_PICK_HEAD check here — the zsh pre-push had none either.
    let severities = Overrides::read(settings);
    // pre-push had NO state guard at all, with a comment admitting it existed
    // only because the zsh version had none. Now it asks the same question
    // pre-commit does and each check answers for itself.
    let in_progress = crate::git_states_in_progress();
    // Declared order unless this repository asked for the other one. The
    // permutation is decided BEFORE the live stage is begun, because the
    // stage draws the list in the order it is given.
    let pre_push_checks = ordered_by_evidence(
        settings,
        selected_during(ctx.settings, Stage::PrePush, &in_progress, ctx.manifest),
    );
    let stage = crate::live::enabled(settings).then(|| {
        let names: Vec<&str> = pre_push_checks.iter().map(|c| c.name()).collect();
        crate::live::Stage::begin(settings, &names)
    });
    // What actually PASSED, for the attestation at the bottom. `Warned` and
    // `Unavailable` stay out — "could not run" is not "passed" — and a
    // commit-time-gated pair counts, because its stamps say the check ran on
    // every pushed tree.
    let mut passed: Vec<String> = Vec::new();
    // Accumulated rather than written per check: one append at the end costs a
    // single file open, and the loop below can leave early.
    let mut downgraded: Vec<(String, crate::downgrade::Origin)> = Vec::new();
    // PUSH STAMPS. The tips being pushed, and what earlier runs of THIS gate
    // recorded against their trees — an `amont run pre-push` rehearsal, or a
    // push whose gate passed and whose transport then died. A scoped gate
    // (a test suite: its verdict is a function of the tree alone) whose
    // stamp sits on every tip is not run again; the unscoped ones
    // (branch-protect, secrets — questions about the push, not the content)
    // always run. `greengate.pushStamps false` turns the reuse off.
    //
    // Reading `ctx.push` here may consume stdin, exactly as `attest` does
    // below; every pre-push check reads it anyway.
    let tips: Vec<String> = {
        let mut t: Vec<String> = ctx
            .push
            .get()
            .iter()
            .filter(|r| !r.local_oid.chars().all(|c| c == '0'))
            // An annotated tag pushes its tag object; what was tested, stamped
            // and recorded is the commit it points at (ADR-0018).
            .map(|r| {
                crate::git::stdout(&[
                    "rev-parse",
                    "--verify",
                    "-q",
                    &format!("{}^{{commit}}", r.local_oid),
                ])
                .unwrap_or_else(|| r.local_oid.clone())
            })
            .collect();
        t.sort_unstable();
        t.dedup();
        t
    };
    let reuse_stamps = crate::gate_stamp::push_stamps_enabled(settings);
    // The working tree AS THE SUITE WILL BE HANDED IT, captured before any
    // gate has run.
    //
    // Timing is the point. Asking afterwards means a gate that modifies a
    // tracked file — a formatter, a suite that updates a snapshot fixture —
    // disqualifies its OWN stamp. What a stamp needs to know is what the
    // suite could READ, which is the state it was handed; a change the suite
    // itself made was never an input to it.
    //
    // Tracked modifications only. `stamp_tips` argues that gap, which is a
    // deliberate one.
    //
    // Read whatever `reuse_stamps` says: the attestation asks it too (#289),
    // and an empty string here would read as a clean tree.
    let tree_at_start =
        crate::git::stdout(&["status", "--porcelain", "--untracked-files=no"]).unwrap_or_default();
    // Inside a rehearsal snapshot only the content gates make sense: the
    // unscoped checks ask about a PUSH — its branch name, its target, its
    // secrets — and no push is happening. Said once, not per check.
    let rehearsing = crate::rehearsal::in_snapshot();
    let handed_to_cluster = ctx.handed_to_cluster;
    // The push `amont land` makes after its pre-stage ran the gates
    // (ADR-0018), as `<sha> <remote tip>`.
    let land = match ctx.land {
        crate::rehearsal::LandEnv::Absent => None,
        crate::rehearsal::LandEnv::Valid(line) => Some(line),
        crate::rehearsal::LandEnv::Malformed(raw) => {
            eprintln!(
                "{BIN}: push refused: {} is not `<sha> <remote tip>` ({raw:?})",
                crate::rehearsal::LAND_ENV
            );
            eprintln!(
                "    unset it, then push again:  unset {}",
                crate::rehearsal::LAND_ENV
            );
            return Verdict::Block;
        }
    };
    // ADR-0018: a heavy gate never runs while git holds the remote's
    // connection open, unless this machine asked for that
    // (`greengate.pushGates inline`). Land's own push expects its pre-stage's
    // evidence; a bare push under `refuse` (the default) refuses at once.
    // Neither waits for a background rehearsal: that wait would itself hold
    // the connection.
    let gate_before_push =
        !rehearsing && (land.is_some() || crate::rehearsal::refuse_push_gates(settings));
    // A background rehearsal of one of these tips may be mid-suite right
    // now. Waiting for it is strictly less work than starting over, and
    // its stamp — read AFTER the wait, below — is the hand-off.
    // Only when this push has test gates for the rehearsal to vouch for: a
    // rehearsal that is only proving tree lint is waited for by the tree
    // verdict alone, under its own `greengate.treeLintWait` (ADR-0024), never
    // under `greengate.rehearsalWait`.
    if reuse_stamps && !tips.is_empty() && !gate_before_push {
        let changed = crate::pushrefs::changed_files(ctx.push.get());
        if !scoped_push_gates(settings, ctx.manifest, &changed).is_empty() {
            crate::rehearsal::await_for(settings, &tips);
        }
    }
    let push_stamps = if reuse_stamps && !tips.is_empty() {
        crate::gate_stamp::stamps_for(&tips)
    } else {
        Default::default()
    };
    if rehearsing {
        crate::say!(
            "rehearsal: running the test gates only — the push-shaped checks run at push time"
        );
    }
    let stamped_on_every_tip = |name: &str| -> bool {
        // The complete token, or nothing: a gate whose identity cannot be
        // worked out is never skipped on a stamp.
        let Some(token) = crate::gate_identity::token(&ctx.manifest.externals, name) else {
            return false;
        };
        !tips.is_empty()
            && tips
                .iter()
                .all(|t| push_stamps.get(t).is_some_and(|s| s.contains(&token)))
    };
    // A trusted `platform=any` gate is also vouched for by its cluster token
    // on every tip's tree (ADR-0016). Asked only for such a gate, so a
    // repository with none pays no spawn.
    let cluster_stamped = |name: &str| -> bool {
        reuse_stamps
            && ctx
                .manifest
                .externals
                .iter()
                .find(|e| e.id == name)
                .is_some_and(|e| crate::cluster::vouched_on_every(settings, e, &tips))
    };
    // Why a gate need not run in this push, or that it must. ONE function,
    // asked by the loop below and by the refusal before it, so a gate the
    // loop would skip is never refused, and one it would run never passes
    // the refusal (ADR-0018).
    let decide = |check: &dyn Check| -> Decision {
        // Handed to the cluster by the rehearsal that made this snapshot: not
        // repeated here, its pass comes back as a cluster token.
        if rehearsing && handed_to_cluster.iter().any(|gate| gate == check.name()) {
            return Decision::Skip(Skip::HandedToCluster);
        }
        // A dependency audit is never skipped: its verdict depends on the
        // day's advisories and the push's stakes, so it replays a fresh
        // record instead, inside the check (ADR-0018).
        if crate::hooks::audit::is_audit(check.name()) {
            return Decision::Run {
                unstamped_pair: None,
                unpaired: None,
            };
        }
        if stamped_push_gate(check)
            && (stamped_on_every_tip(check.name()) || cluster_stamped(check.name()))
        {
            return Decision::Skip(Skip::Stamped);
        }
        if gate_before_push && reuse_stamps && stamped_push_gate(check) {
            let done = crate::gate_identity::token(&ctx.manifest.externals, check.name())
                .is_some_and(|token| {
                    crate::gate_stamp::done_on_every(&tips, &token, severities.of(check))
                });
            if done {
                return Decision::Skip(Skip::CompletedEarlier);
            }
        }
        let declared = ctx
            .manifest
            .externals
            .iter()
            .find(|e| e.stage == Stage::PrePush && e.id == check.name());
        // A `platform=any` push gate whose commit twin declares the same suite
        // and was proved on the cluster on every tip's tree is gated at commit
        // too, and counts as a cluster pass under its own id (ADR-0016).
        if let Some(push_gate) = declared.filter(|_| reuse_stamps) {
            let claimed_from_twin = ctx
                .manifest
                .externals
                .iter()
                .filter(|e| e.stage == Stage::PreCommit && e.short_name == push_gate.short_name)
                .any(|twin| {
                    crate::cluster::claim_twin_cluster_pass(settings, push_gate, twin, &tips)
                });
            if claimed_from_twin {
                return Decision::Skip(Skip::TwinOnCluster(push_gate.short_name.clone()));
            }
        }
        // The push side of a pair is `(name, scope)`, from whichever of the
        // two kinds of check this is. A declared pre-push external supplies
        // its own; anything else is a BUILT-IN, and `pairing_name` plus the
        // registry's scope say the same two things about it.
        let builtin_scope = check.scope();
        let pairing: Option<(&str, &crate::check::Scope)> = match declared {
            Some(ext) => match &ext.kind {
                crate::manifest::Kind::Runnable { scope, .. } => {
                    Some((ext.short_name.as_str(), scope))
                }
                // A declared pre-push entry that runs nothing has no scope to
                // judge with, and is not a built-in either. Nothing to pair.
                _ => None,
            },
            None => Some((check.pairing_name(), &builtin_scope)),
        };
        let Some((name, push_scope)) = pairing else {
            return Decision::Run {
                unstamped_pair: None,
                unpaired: None,
            };
        };
        match crate::hooks::run_tests::pair_verdict(
            ctx.settings,
            name,
            push_scope,
            ctx.manifest,
            ctx.push,
        ) {
            crate::hooks::run_tests::PairVerdict::Gated(coverage) => {
                Decision::Skip(Skip::GatedAtCommit {
                    name: name.to_string(),
                    coverage,
                })
            }
            crate::hooks::run_tests::PairVerdict::Deferred(n) => {
                Decision::Skip(Skip::DeferredAtCommit(name.to_string(), n))
            }
            crate::hooks::run_tests::PairVerdict::Unstamped(n) => Decision::Run {
                unstamped_pair: Some((name.to_string(), n)),
                unpaired: None,
            },
            crate::hooks::run_tests::PairVerdict::NotPaired(why) => Decision::Run {
                unstamped_pair: None,
                unpaired: why.map(|why| (name.to_string(), why)),
            },
        }
    };
    // The question `amont list` answers with "inert here — needs go.sum",
    // asked of the index once (see the loop below).
    let tracked = crate::tracked_paths();
    // ADR-0018: refuse before any heavy gate starts. The gates this push
    // owes are the scoped ones its range touches (`scoped_push_gates`, the
    // same set a rehearsal stamps); each is asked `decide`, and any it would
    // have to RUN means the push refuses.
    if gate_before_push && !tips.is_empty() {
        let changed = crate::pushrefs::changed_files(ctx.push.get());
        let owed = scoped_push_gates(settings, ctx.manifest, &changed);
        // Why each owed gate would run, kept from the one `decide` that found
        // it missing: the reasons are printed ahead of the refusal without
        // asking the gate a second time.
        let reasons: std::cell::RefCell<Vec<(String, crate::hooks::run_tests::WhyNot)>> =
            std::cell::RefCell::new(Vec::new());
        let missing: Vec<&str> = pre_push_checks
            .iter()
            .filter(|c| {
                if crate::hooks::audit::is_audit(c.name()) {
                    // Owed on every push it is opted into, whatever the
                    // range touches, unless a fresh record answers for it.
                    c.scope().opted_in(&tracked)
                        && crate::hooks::audit::owed(settings, ctx.audits, c.name(), ctx.push.get())
                } else {
                    // A declared command whose program is not installed can
                    // never be stamped or recorded, so no pre-stage could
                    // answer for it: owing it would refuse every push for
                    // good. It runs below instead, fails to start, and warns,
                    // as before 2.0. Only that: a gate whose token failed for
                    // another reason stays owed.
                    owed.iter().any(|o| o == c.name())
                        && !crate::gate_identity::program_missing(&ctx.manifest.externals, c.name())
                        && match decide(**c) {
                            Decision::Run { unpaired, .. } => {
                                reasons.borrow_mut().extend(unpaired);
                                true
                            }
                            Decision::Skip(_) => false,
                        }
                }
            })
            .map(|c| c.name())
            .collect();
        if !missing.is_empty() {
            let short: String = tips
                .first()
                .map(|t| t.chars().take(8).collect())
                .unwrap_or_default();
            // Why a pair did not vouch comes BEFORE the refusal: refusing is the
            // default for a bare push, so a refused push is where a silent
            // "it would have run the suite again" went unexplained.
            for (name, why) in reasons.borrow().iter() {
                crate::hooks::run_tests::say_why_not(name, why);
            }
            let lines = match land {
                Some(line) => land_refusal(line, ctx.push.get(), &missing),
                None => push_refusal(
                    &short,
                    &missing,
                    if reuse_stamps {
                        StampReuse::On
                    } else {
                        StampReuse::Off
                    },
                    pushed_tag(ctx.push.get()),
                ),
            };
            for line in lines {
                eprintln!("{line}");
            }
            return Verdict::Block;
        }
    }
    // What actually RAN and passed here (as opposed to being vouched for by
    // a stamp) — the set this run may stamp in turn.
    let mut ran_and_passed: Vec<String> = Vec::new();
    // Scoped gates that RAN here and completed without passing — a warning,
    // or a tool that was missing (ADR-0018): recorded beside the stamps, never
    // as one, so a refusing push does not ask for them again.
    let mut completed_otherwise: Vec<(String, crate::gate_stamp::Completion)> = Vec::new();
    // What each gate COST and how it ENDED, for the record `gate_evidence`
    // reads. Every outcome, failures included: the stamp deliberately has no
    // opinion about a gate that failed, and a dataset that kept only the
    // passes could never say a gate is flaky.
    let mut evidence: Vec<crate::gate_stamp::Run> = Vec::new();
    // The question `amont list` answers with "inert here — needs go.sum":
    // does this repository carry the marker that turns the check on? Asked
    // of the index, once, and answered the same way here — a check the
    // registry calls inert used to run anyway, find its tool or lockfile
    // missing, and warn that it "could not run" on every push of a
    // repository it was never meant to touch.
    // Inside a rehearsal a heavy gate hands its slot to the next one; the
    // scope releases what is parked on every way out of this function.
    let park = crate::host_slots::ParkScope::begin();
    for (idx, check) in pre_push_checks.iter().enumerate() {
        if !check.scope().opted_in(&tracked) {
            continue;
        }
        let _sink = stage.as_ref().map(|s| s.enter(idx));
        let flush = stage
            .as_ref()
            .map(|s| crate::live::FinishOnDrop::new(ctx.settings, s, idx));
        // A declared pre-push external whose NAME is also declared at
        // pre-commit (blocking) is a gate pair: the commit-time side earned
        // per-commit stamps, and this side runs only for pushes carrying
        // commits with no record of it — the same contract the npm gate has
        // always had, for vocabularies npm never heard of (`cargo test`,
        // `pytest`, anything). Messages mirror the npm gate's exactly;
        // docs/checks.md quotes them. `decide` holds the reasoning, shared
        // with the refusal above.
        // The dependency audits are unscoped too (opted in by a lockfile,
        // with no file scope), but a rehearsal is exactly where their record
        // is earned (ADR-0018), so they run here.
        if rehearsing && !stamped_push_gate(*check) && !crate::hooks::audit::is_audit(check.name())
        {
            continue;
        }
        // A push of deletions only (or of no ref at all: git ran the hook
        // with nothing to push) has no commit for an audit to answer for, and
        // running one would hold the connection open for nothing (ADR-0018).
        if gate_before_push && tips.is_empty() && crate::hooks::audit::is_audit(check.name()) {
            continue;
        }
        match decide(*check) {
            Decision::Skip(Skip::HandedToCluster) => {
                crate::say!(
                    "{} {} runs on the cluster — the next commit or push collects it",
                    valid_sign(),
                    highlight(check.name()),
                );
                continue;
            }
            Decision::Skip(Skip::Stamped) => {
                crate::say!(
                    "{} {} passed on this exact tree earlier — not repeating it here",
                    valid_sign(),
                    highlight(check.name()),
                );
                passed.push(check.name().to_string());
                continue;
            }
            Decision::Skip(Skip::CompletedEarlier) => {
                crate::say!(
                    "{} {} ran on this tree earlier and did not pass cleanly (it warned or \
                     could not run) — not repeating it here",
                    warning_sign(),
                    highlight(check.name()),
                );
                continue;
            }
            Decision::Skip(Skip::TwinOnCluster(short)) => {
                crate::say!(
                    "{} {} gated at commit on the cluster instead — not repeating it here",
                    valid_sign(),
                    highlight(&short),
                );
                passed.push(check.name().to_string());
                continue;
            }
            Decision::Skip(Skip::GatedAtCommit { name, coverage }) => {
                crate::say!(
                    "{} {} gated at commit instead — not repeating it here",
                    valid_sign(),
                    highlight(&name),
                );
                // A second line only when a TIP vouched alone: the plain line
                // has always meant "every pushed commit carries its stamp",
                // and a reader who pushed an unstamped commit deserves to see
                // what the skip rests on. Its own line, so the first stays
                // within 80 columns; "the code at", because a plans-only tip
                // never ran the gate itself — its canonical tree did.
                if let crate::hooks::run_tests::Coverage::Tips(tips) = coverage {
                    crate::say!("    the code at tip {} passed at commit", tips.join(", "));
                }
                passed.push(check.name().to_string());
                continue;
            }
            Decision::Skip(Skip::DeferredAtCommit(name, n)) => {
                crate::say!(
                    "{} {} was deferred to CI at commit on {n} pushed commit{} \
                     — deferring it here too",
                    warning_sign(),
                    highlight(&name),
                    if n == 1 { "" } else { "s" },
                );
                evidence.push(crate::gate_stamp::Run {
                    at: crate::gate_evidence::now(),
                    gate: check.name().to_string(),
                    outcome: crate::gate_stamp::RunOutcome::Deferred,
                    ms: 0,
                });
                continue;
            }
            Decision::Run {
                unstamped_pair: Some((name, n)),
                ..
            } => {
                // `greengate.unstampedPush refuse`: never run a suite with
                // the remote's connection held open — say how to earn
                // the stamp instead. Not inside a rehearsal snapshot:
                // running there is how the stamp is earned.
                if !rehearsing && crate::rehearsal::refuse_unstamped(ctx.settings) {
                    crate::say!(
                        "{} {} is declared at commit time, but {n} pushed \
                         commit{} carr{} no record of it (rewritten by a \
                         rebase or amend, or made without the hooks) — \
                         refusing the push",
                        warning_sign(),
                        name,
                        if n == 1 { "" } else { "s" },
                        if n == 1 { "ies" } else { "y" },
                    );
                    crate::say!(
                        "    Test this tree first, with no push waiting on it: {} — then push again",
                        highlight(&format!("{BIN} rehearse --wait")),
                    );
                    crate::downgrade::note(settings, &downgraded);
                    record_evidence(&tips, &evidence);
                    println!("\n🚨  Error raised by hook {}", highlight(check.name()));
                    return Verdict::Block;
                }
                crate::say!(
                    "{} {} is declared at commit time, but {n} pushed \
                     commit{} carr{} no record of it — running it here",
                    warning_sign(),
                    name,
                    if n == 1 { "" } else { "s" },
                    if n == 1 { "ies" } else { "y" },
                );
            }
            Decision::Run {
                unstamped_pair: None,
                unpaired,
            } => {
                if let Some((name, why)) = unpaired {
                    crate::hooks::run_tests::say_why_not(&name, &why);
                }
            }
        }
        let sub = Ctx {
            name: check.name(),
            args: ctx.args,
            hooks_dir: ctx.hooks_dir,
            push: ctx.push,
            manifest: ctx.manifest,
            settings: ctx.settings,
            handed_to_cluster: ctx.handed_to_cluster,
            land: ctx.land,
            audits: ctx.audits,
            source_worktree: ctx.source_worktree,
        };
        // Wall clock around the check itself, not around the hook: the number
        // that catches a suite which stopped finding tests is how long THAT
        // gate took, and everything outside this call is bookkeeping.
        let started = std::time::Instant::now();
        let mut severity_read: Option<Severity> = None;
        let slot = enter(*check, || {
            let severity = crate::registry::severity_of(ctx.settings, *check);
            severity_read = Some(severity);
            severity
        });
        let outcome = deferred_or(&slot, check.run(&sub));
        if let Some(f) = &flush {
            f.outcome(outcome);
        }
        let ran = started.elapsed().saturating_sub(slot.queued());
        drop(slot);
        evidence.push(crate::gate_stamp::Run {
            at: crate::gate_evidence::now(),
            gate: check.name().to_string(),
            outcome: run_outcome(outcome),
            ms: ran.as_millis().min(u128::from(u64::MAX)) as u64,
        });
        match outcome {
            Outcome::Passed => {
                passed.push(check.name().to_string());
                // An audit's pass is a record of its report, never a stamp.
                if stamped_push_gate(*check) {
                    ran_and_passed.push(check.name().to_string());
                }
            }
            // Announced, never fatal: a check that could not run has not
            // invalidated anything, and neither has a warning.
            Outcome::Unavailable => {
                if stamped_push_gate(*check) {
                    completed_otherwise.push((
                        check.name().to_string(),
                        crate::gate_stamp::Completion::Unavailable,
                    ));
                }
                println!(
                    "{} {} could not run",
                    warning_sign(),
                    highlight(check.name())
                )
            }
            Outcome::Warned => {
                if stamped_push_gate(*check) {
                    completed_otherwise.push((
                        check.name().to_string(),
                        crate::gate_stamp::Completion::Warned,
                    ));
                }
            }
            // Not run, never fatal, never passed: CI runs it (ADR-0013).
            Outcome::Deferred => announce_deferred(&[(
                check.name(),
                severity_read.unwrap_or_else(|| crate::registry::severity_of(ctx.settings, *check)),
            )]),
            // Nothing to judge: not passed (nothing to stamp or attest), not
            // a gap (nothing is missing). The dispatcher asked the registry's
            // opt-in question above; this is a check answering it for itself.
            Outcome::Inert => {}
            // Cannot occur: `Fix::Rewrite` is refused on a pre-push
            // declaration, so nothing here can repair anything.
            Outcome::Fixed => {}
            // Cannot occur: pre-push is serial and stops at the first failure
            // on its own; only pre-commit's waves skip (ADR-0020).
            Outcome::Skipped => {}
            Outcome::Failed => match severities.of(*check) {
                Severity::Warn => {
                    if stamped_push_gate(*check) {
                        completed_otherwise.push((
                            check.name().to_string(),
                            crate::gate_stamp::Completion::FailedUnderWarn,
                        ));
                    }
                    downgraded.push((
                        check.name().to_string(),
                        downgrade_origin(*check, &severities),
                    ));
                    println!(
                        "{} {} reported a problem (severity warn)",
                        warning_sign(),
                        highlight(check.name())
                    );
                }
                // Fail-fast applies ONLY to Block: the later steps are
                // expensive and their preconditions are gone.
                Severity::Block => {
                    // Record what already warned before leaving. Those checks
                    // ran and reported; a later check blocking does not unmake
                    // them, and dropping them here would make the ledger quietly
                    // under-count every push that ended badly.
                    crate::downgrade::note(settings, &downgraded);
                    // The same argument for the evidence, and it matters more
                    // here: this is the path a FAILURE leaves by, and a record
                    // written only on the way out of a successful push would
                    // be a dataset of passes calling itself a dataset of runs.
                    record_evidence(&tips, &evidence);
                    println!("\n🚨  Error raised by hook {}", highlight(check.name()));
                    return Verdict::Block;
                }
            },
        }
    }
    drop(park);
    // Every block gate passed — stamp the tips with the scoped gates that
    // RAN here, so the next push of this content (a retry after a dropped
    // connection, or the real push after an `amont run pre-push` rehearsal)
    // skips them. Only when what ran is what is being pushed: with
    // `greengate.testPushedTree` the suite ran on the tip itself — unless the
    // snapshot could not be made, which `stamp_tips` asks about rather than
    // assuming; otherwise it ran on the working tree, which vouches for the
    // tip only when the two are the same content — HEAD, with nothing
    // modified and nothing untracked.
    // The same proxy `attestable` uses, for the same reason: a scoped gate
    // whose files the push never touched returns `Passed` having run
    // nothing, and a stamp for THAT would let a later push that does touch
    // them skip a suite nobody ran.
    if reuse_stamps && !ran_and_passed.is_empty() {
        let changed = crate::pushrefs::changed_files(ctx.push.get());
        let really_ran: Vec<String> = pre_push_checks
            .iter()
            .filter(|c| ran_and_passed.iter().any(|p| p == c.name()))
            .filter(|c| c.scope().touches(&changed))
            .map(|c| c.name().to_string())
            .collect();
        stamp_tips(&ctx.manifest.externals, &tips, &really_ran, &tree_at_start);
    }
    record_audits(ctx.audits, &tree_at_start);
    if reuse_stamps && !completed_otherwise.is_empty() {
        let changed = crate::pushrefs::changed_files(ctx.push.get());
        let really_ran: Vec<(String, crate::gate_stamp::Completion)> = completed_otherwise
            .into_iter()
            .filter(|(name, _)| {
                pre_push_checks
                    .iter()
                    .any(|c| c.name() == name && c.scope().touches(&changed))
            })
            .collect();
        record_completions(&ctx.manifest.externals, &tips, &really_ran, &tree_at_start);
    }
    // …and say so to CI, if this repository opted in.
    // Gated behind `enabled()` HERE, not just inside `attest_push`: reading
    // `ctx.push` may consume stdin, and a disabled repo should leave stdin
    // exactly as it found it.
    // Tree gates (ADR-0024) are not push checks: nothing runs here. Each is
    // attested only when the TREE of every pushed tip carries its commit-time
    // proof; a whole-tree proof needs no changed-files scope. Fail-closed:
    // anything else is simply not attested, and CI lints.
    let (tree_proven, tree_unproven) =
        if !ctx.manifest.tree.is_empty() && crate::attest::enabled(settings) {
            crate::tree_lint::await_verdict(settings, &ctx.manifest.tree, &tips, push_started)
        } else {
            (Vec::new(), Vec::new())
        };
    if !tree_unproven.is_empty() {
        crate::hooks::common::say(&crate::tree_lint::fit_line(
            "  lint not attested (cold or changed tree): ",
            &tree_unproven.join(" "),
            " — CI will lint",
        ));
    }
    if (!passed.is_empty() || !tree_proven.is_empty()) && crate::attest::enabled(settings) {
        let remote = ctx
            .args
            .first()
            .map(|a| a.to_string_lossy().into_owned())
            .unwrap_or_default();
        let changed = crate::pushrefs::changed_files(ctx.push.get());
        // Only local passes enter the laptop's attestation (ADR-0016); the
        // cluster's go to the linux block, which `attest_push` narrows per tip
        // to the trees the cluster actually judged.
        let (cluster_passed, local): (Vec<String>, Vec<String>) = passed
            .iter()
            .cloned()
            .partition(|p| crate::cluster::proved_anywhere(p));
        let vouched = attestable(&pre_push_checks, &local, &changed);
        let cluster_vouched = attestable(&pre_push_checks, &cluster_passed, &changed);
        // Per tip, the gates whose run saw that tip's content: the working
        // tree was the tip when they started, or they ran in a checkout of it
        // (#289; the rule `stamp_tips` applies). A tree gate's proof is the
        // tree's own commit-time record, so it needs no witness.
        let witness = TipWitness::new(&tree_at_start);
        let gates_for = |tip: &str| -> Vec<String> {
            vouched
                .iter()
                .filter(|g| witness.vouches(g, tip))
                .chain(tree_proven.iter())
                .cloned()
                .collect()
        };
        crate::attest::attest_push_per_tip(
            ctx.settings,
            &remote,
            ctx.push.get(),
            &gates_for,
            &cluster_vouched,
        );
    }
    // Outside the `passed` branch above on purpose: a push that changes only
    // documentation or its plan still carries a plan and a review to record.
    // holds-until: a dispatch-level test drives a push where no gate passed;
    // until one exists, moving this call inside that branch fails no test.
    if crate::attest::enabled(settings) {
        let remote = ctx
            .args
            .first()
            .map(|a| a.to_string_lossy().into_owned())
            .unwrap_or_default();
        crate::attest::provenance_push(ctx.settings, &remote, ctx.push.get());
    }
    crate::downgrade::note(settings, &downgraded);
    record_evidence(&tips, &evidence);
    Verdict::Proceed
}

/// What one check's outcome is called in the record.
fn run_outcome(outcome: Outcome) -> crate::gate_stamp::RunOutcome {
    use crate::gate_stamp::RunOutcome as R;
    match outcome {
        Outcome::Passed => R::Passed,
        Outcome::Failed => R::Failed,
        Outcome::Warned => R::Warned,
        Outcome::Fixed => R::Fixed,
        Outcome::Unavailable => R::Unavailable,
        Outcome::Inert => R::Inert,
        Outcome::Deferred => R::Deferred,
        // Never produced at pre-push (ADR-0020); were it, it judged nothing.
        Outcome::Skipped => R::Inert,
    }
}

/// The check's outcome, unless the busy policy deferred it: then Deferred,
/// whatever the check made of its refused spawn (ADR-0013).
fn deferred_or(slot: &crate::host_slots::CheckGuard, outcome: Outcome) -> Outcome {
    if slot.deferred().is_some() {
        Outcome::Deferred
    } else {
        outcome
    }
}

/// The Heavy checks a blocking Light failure kept from starting (ADR-0020),
/// what blocked, and how to run each one now: `amont run` takes one name, so
/// one line per check, each short enough for an 80-column terminal.
fn announce_skipped(names: &[&str], blocked_by: &[&str]) {
    let names_list = names
        .iter()
        .map(|n| highlight(n))
        .collect::<Vec<_>>()
        .join(", ");
    match blocked_by {
        [one] => println!(
            "{} {} check(s) skipped because {} failed: {names_list}",
            crate::ui::skipped_sign(),
            names.len(),
            highlight(one),
        ),
        _ => println!(
            "{} {} check(s) skipped, a blocking check failed: {names_list}",
            crate::ui::skipped_sign(),
            names.len(),
        ),
    }
    println!("  fix the failures above and commit again; to run one now:");
    for n in names {
        println!("    {}", highlight(&format!("{BIN} run {n}")));
    }
}

/// The deferral roll-up: which checks, then how to run each now and how to
/// stop deferring. Printed in quiet mode too, like `could not run`: a gate
/// skipped without a word looks exactly like a pass. Each deferred check is
/// advised the command that waits for its slot; the `onBusy wait` hint is
/// offered only for `block` checks, since a `warn` check never waits on a
/// commit or a push and the hint cannot stop it deferring there.
fn announce_deferred(deferred: &[(&str, Severity)]) {
    for line in deferral_advice(deferred) {
        println!("{line}");
    }
}

/// The lines [`announce_deferred`] prints: the roll-up, then one `run now:`
/// command per deferred check (`amont run` takes one check by name, and a
/// `--raw` run waits for its slot under `GREENGATE_ON_BUSY=wait`, warn or block),
/// then the `onBusy wait` hint only when a `block` check is in the list,
/// since only a `block` check stops deferring under it.
fn deferral_advice(deferred: &[(&str, Severity)]) -> Vec<String> {
    let names: Vec<&str> = deferred.iter().map(|(name, _)| *name).collect();
    let mut lines = vec![format!(
        "{} {} check(s) deferred to CI, no host slot freed: {}",
        warning_sign(),
        names.len(),
        names.join(", ")
    )];
    let mut any_block = false;
    for (name, severity) in deferred {
        match severity {
            Severity::Block => any_block = true,
            Severity::Warn => {}
        }
        lines.push(format!(
            "  run now: {}",
            highlight(&format!("GREENGATE_ON_BUSY=wait {BIN} run --raw {name}"))
        ));
    }
    if any_block {
        lines.push(format!(
            "  stop deferring the block checks: {}",
            highlight("set onBusy wait")
        ));
    }
    lines
}

/// File this push's runs under the content they judged.
///
/// ONE key, not one per tip: a push of two branches ran each gate once, and
/// writing the same run onto both trees would make a report count it twice.
/// The first tip's tree is that key, falling back to `HEAD` — and to nothing
/// at all when git will not name either, which costs a row in a report and
/// never a verdict.
fn record_evidence(tips: &[String], runs: &[crate::gate_stamp::Run]) {
    if runs.is_empty() {
        return;
    }
    let tree = tips
        .first()
        .and_then(|tip| crate::git::stdout(&["rev-parse", &format!("{tip}^{{tree}}")]))
        .or_else(|| crate::git::stdout(&["rev-parse", "HEAD^{tree}"]));
    if let Some(tree) = tree {
        crate::gate_stamp::record_runs(&tree, runs);
    }
}

/// Is `check` a push gate that runs before git connects, and is stamped for
/// it (ADR-0018)? A scoped one, or a declared `heavy` one whatever its scope:
/// a `*` declaration can be any command, and one that runs for a minute on
/// the open connection is the failure ADR-0018 exists to stop (#414). The
/// built-in unscoped checks (branch-protect, secrets) are light and need the
/// push's own refs, so they stay in the hook; the dependency audits answer
/// through their own record.
pub fn stamped_push_gate(check: &dyn Check) -> bool {
    !crate::hooks::audit::is_audit(check.name())
        && (!check.scope().is_unscoped() || check.weight() == crate::host_slots::Weight::Heavy)
}

/// The stamped pre-push gates ([`stamped_push_gate`]) — test suites, and
/// declared heavy gates — that have work to do for a push that changed
/// `changed`: what a rehearsal would run, and therefore what its stamp would
/// have to name before a push may skip anything.
///
/// The same two filters `pre_push` applies before stamping (selected here,
/// and `scope().touches` the change), so the rehearsal's idea of "nothing to
/// do" is the push's idea of "nothing to stamp".
pub fn scoped_push_gates(
    settings: &crate::config::Settings,
    manifest: &crate::manifest::Manifest,
    changed: &[String],
) -> Vec<String> {
    let in_progress = crate::git_states_in_progress();
    let tracked = crate::tracked_paths();
    selected_during(settings, Stage::PrePush, &in_progress, manifest)
        .into_iter()
        .filter(|c| stamped_push_gate(*c) && c.scope().touches(changed))
        // The same opt-in gate `pre_push` applies: a suite the repository
        // never turned on is not work a rehearsal owes a stamp for.
        .filter(|c| c.scope().opted_in(&tracked))
        .map(|c| c.name().to_string())
        .collect()
}

/// The dependency audits a push of `refs` owes (ADR-0018): opted in, and
/// with no fresh record for the pushed commits in the push's mode. Owed
/// whatever the range touches, unlike `scoped_push_gates`.
pub fn owed_audits(
    settings: &crate::config::Settings,
    manifest: &crate::manifest::Manifest,
    ledger: &crate::hooks::audit::Ledger,
    refs: &[crate::pushrefs::PushRef],
) -> Vec<String> {
    let in_progress = crate::git_states_in_progress();
    let tracked = crate::tracked_paths();
    selected_during(settings, Stage::PrePush, &in_progress, manifest)
        .into_iter()
        .filter(|c| crate::hooks::audit::is_audit(c.name()))
        .filter(|c| c.scope().opted_in(&tracked))
        .filter(|c| crate::hooks::audit::owed(settings, ledger, c.name(), refs))
        .map(|c| c.name().to_string())
        .collect()
}

/// Push-stamp every tip whose content is what the gates actually tested.
///
/// See the comment at the call site for the two cases. Silent when nothing
/// qualifies — a dirty working tree is the ordinary state of a machine
/// mid-work, and a note on every push would teach people to ignore it.
fn stamp_tips(
    externals: &[crate::manifest::External],
    tips: &[String],
    gates: &[String],
    tree_at_start: &str,
) {
    let witness = TipWitness::new(tree_at_start);
    // TRACKED modifications only — a KNOWN gap, kept deliberately, and
    // spelled out because the comment that used to sit here argued it
    // backwards ("untracked files are not in any tree the suite could have
    // been asked about"). That is not the reason. The danger is not that the
    // tree lacks them, it is that the RUN had them: a new test file, a
    // fixture, a local `.env`, present while the suite ran and absent from
    // the tree the stamp vouches for.
    //
    // Counting them was tried, and is worse than the gap. Gates leave
    // artefacts — a log, a coverage directory, whatever a declared
    // `amont.conf` command writes — and nothing cleans them up, so a
    // repository using declared gates would stop earning stamps permanently
    // after its first commit. That does not merely lose an optimisation: it
    // puts the suite back INSIDE the push, which is the failure the whole
    // stamping mechanism exists to prevent. amont's own push flow
    // (`flows/push.rs`, steps `first push` and `retry`) is exactly that
    // shape, and CI is where it surfaced — a `*.log` line in one developer's
    // global gitignore had hidden it on the machine that wrote the change.
    //
    // `greengate.testPushedTree true` closes the gap properly for anyone who
    // wants it closed: it runs the suite in a checkout of the commit, where
    // no untracked file exists to be read.
    //
    // `tree_at_start` — not a fresh `git status`. The gates have run by now
    // and may have written into the tree; what a stamp needs to know is what
    // the suite could READ, which is the state it was handed. See the
    // capture in `pre_push`.
    let mut stamped: Vec<String> = Vec::new();
    for tip in tips {
        // PER GATE, from what each one actually did — not from the config.
        // `greengate.testPushedTree` is a request; `pushed_tree::ran_on_tip` is
        // the record of which gates were handed a checkout of this tip. A
        // gate that ran somewhere else (a snapshot that could not be made,
        // or a check that ran in the working tree) may vouch for the tip
        // only when the working tree WAS the tip. Deciding from the flag
        // stamped every passing gate onto a tip that one of them had never
        // seen.
        let vouched: Vec<String> = gates
            .iter()
            .filter(|g| witness.vouches(g, tip))
            .cloned()
            .collect();
        if vouched.is_empty() {
            continue;
        }
        let spec = format!("{tip}^{{tree}}");
        let Some(tree) = crate::git::stdout(&["rev-parse", &spec]) else {
            continue;
        };
        // A gate the cluster proved on this tree is already recorded in its
        // own ref: a local push stamp would let the laptop vouch for it.
        let vouched: Vec<String> = vouched
            .into_iter()
            .filter(|g| !crate::cluster::proved(g, &tree))
            .collect();
        // Tokens, not names; a gate with no identity is not stamped.
        let tokens: Vec<String> = vouched
            .iter()
            .filter_map(|g| crate::gate_identity::token(externals, g))
            .collect();
        if crate::gate_stamp::stamp_push(tip, &tree, &tokens) {
            for g in vouched {
                if !stamped.contains(&g) {
                    stamped.push(g);
                }
            }
        }
    }
    if !stamped.is_empty() {
        crate::say!(
            "{} stamped {} for this tree — the next push of it skips them ({})",
            valid_sign(),
            highlight(&stamped.join(" ")),
            crate::gate_stamp::NOTES_REF,
        );
    }
}

/// Write the audit records this push produced (ADR-0018), only for a commit
/// the working tree IS: HEAD, inside a rehearsal snapshot or with a clean
/// worktree — the tools read the working tree, not the commit.
fn record_audits(ledger: &crate::hooks::audit::Ledger, tree_at_start: &str) {
    let pending = ledger.take_pending();
    if pending.is_empty() {
        return;
    }
    let witness = TipWitness::new(tree_at_start);
    for record in pending {
        if !witness.tree_is_tip(&record.tip) {
            continue;
        }
        if let Err(why) = crate::hooks::audit::write_pending(&record) {
            crate::hooks::common::warn(&format!(
                "{why} — the next push of this tree owes the audit again"
            ));
        }
    }
}

/// Record the gates that completed without passing (ADR-0018), on exactly the
/// tips `stamp_tips` would stamp: a tip whose content is what the gates ran
/// on — HEAD, inside a rehearsal snapshot or with a clean worktree. One note
/// write per tree and kind of completion.
fn record_completions(
    externals: &[crate::manifest::External],
    tips: &[String],
    gates: &[(String, crate::gate_stamp::Completion)],
    tree_at_start: &str,
) {
    if gates.is_empty() {
        return;
    }
    let witness = TipWitness::new(tree_at_start);
    let mut by_kind: Vec<(crate::gate_stamp::Completion, Vec<String>)> = Vec::new();
    for (gate, how) in gates {
        let Some(token) = crate::gate_identity::token(externals, gate) else {
            continue;
        };
        match by_kind.iter_mut().find(|(kind, _)| kind == how) {
            Some((_, tokens)) => tokens.push(token),
            None => by_kind.push((*how, vec![token])),
        }
    }
    for tip in tips {
        if !witness.tree_is_tip(tip) {
            continue;
        }
        let Some(tree) = crate::git::stdout(&["rev-parse", &format!("{tip}^{{tree}}")]) else {
            continue;
        };
        for (how, tokens) in &by_kind {
            if let Err(why) = crate::gate_stamp::record_done(&tree, tokens, *how) {
                crate::hooks::common::warn(&format!(
                    "{why} — the next push of this tree owes those gates again"
                ));
            }
        }
    }
}

/// Of the checks that passed, the ones an attestation may actually VOUCH for.
///
/// A language gate whose scope the push never touched returns `Passed` having
/// run nothing — `cargo_test` walks its refs, finds no crate root, and falls
/// out of the loop green. That is right for a push gate (there was nothing to
/// object to) and wrong for an attestation: a JS-only push was minting
/// `gates … pre-push-cargo-test pre-push-go-test pre-push-pytest`, and in a
/// MIXED repository CI would then skip a suite that nobody ran on that tree.
///
/// The declared `scope` is the honest filter, and the same data `amont list`
/// already reports. Unscoped checks (`Scope::ALWAYS` — branch-protect,
/// secrets) match everything and are vouched for, which is accurate: they
/// really did run. An empty `changed` vouches for nothing scoped, which is
/// the safe direction — CI runs the suite.
///
/// [`Scope::touches`], NOT `Scope::matches`. `matches` also asks whether the
/// repository has opted in — whether a `Cargo.toml` exists — and asking that
/// of a push DIFF can only answer no unless the push happened to touch the
/// marker. So `pre-push-cargo-test` was vouched for by a push that edited
/// `Cargo.toml` and never by one that edited only `.rs` files, which is the
/// ordinary case and the one worth skipping CI for. The feature attested
/// almost nothing, silently, and looked like it worked.
///
/// WHAT THIS IS STILL A PROXY FOR, stated plainly because the trust path
/// deserves it: the honest question is "did this gate actually run", and no
/// gate reports that. `rust_tools::test` returns `Passed` whether it ran a
/// suite or found no crate root and fell out of its loop — the very thing
/// the first paragraph describes. Scope is the closest available stand-in.
/// It is now a good one: a gate is vouched for only if the push changed a
/// file its extensions cover.
///
/// The gap that remains is narrow and one-directional: a `.rs` file outside
/// every crate would be covered here while `cargo test` had nothing to say
/// about it. Closing it properly means an outcome that distinguishes "ran
/// and passed" from "found nothing to do", which is a change to every gate
/// and to `Outcome` itself — worth doing, not worth smuggling into this.
/// Which pushed tips a gate's run in this process saw (#289): the working
/// tree was the tip when the gates started, or the gate ran in a checkout of
/// it (`pushed_tree::ran_on_tip`). Shared by the push stamps and the
/// attestation, so the two never disagree about what was tested.
struct TipWitness {
    head: Option<String>,
    /// The working tree held HEAD's content when the gates started: clean
    /// of tracked changes, or a rehearsal snapshot. A snapshot is a checkout
    /// git made of the commit, and whatever `greengate.snapshotPrepare` added to
    /// make it runnable (a `node_modules`, a virtualenv) is not a reason to
    /// distrust it.
    tree_is_head: bool,
}

impl TipWitness {
    fn new(tree_at_start: &str) -> Self {
        Self::from_parts(
            crate::git::stdout(&["rev-parse", "HEAD"]),
            crate::rehearsal::in_snapshot(),
            tree_at_start,
        )
    }

    fn from_parts(head: Option<String>, in_snapshot: bool, tree_at_start: &str) -> Self {
        TipWitness {
            head,
            tree_is_head: in_snapshot || tree_at_start.trim().is_empty(),
        }
    }

    /// The working tree was `tip` when the gates started.
    fn tree_is_tip(&self, tip: &str) -> bool {
        self.tree_is_head && self.head.as_deref() == Some(tip)
    }

    fn vouches(&self, gate: &str, tip: &str) -> bool {
        self.tree_is_tip(tip) || crate::pushed_tree::ran_on_tip(gate, tip)
    }
}

fn attestable(checks: &[&dyn Check], passed: &[String], changed: &[String]) -> Vec<String> {
    checks
        .iter()
        .filter(|c| passed.iter().any(|p| p == c.name()))
        .filter(|c| c.scope().touches(changed))
        .map(|c| c.name().to_string())
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::check::{Builtin, Scope};
    use std::sync::atomic::{AtomicUsize, Ordering};

    /// #289: a dirty working tree witnesses no tip, even HEAD; a clean one,
    /// or a snapshot, witnesses HEAD only.
    #[test]
    fn only_a_clean_head_or_a_snapshot_witnesses_a_tip() {
        let head = Some("a".repeat(40));
        let tip = "a".repeat(40);
        let other = "b".repeat(40);
        let dirty = TipWitness::from_parts(head.clone(), false, " M src/lib.rs\n");
        assert!(!dirty.tree_is_tip(&tip));
        let clean = TipWitness::from_parts(head.clone(), false, "");
        assert!(clean.tree_is_tip(&tip));
        assert!(!clean.tree_is_tip(&other));
        let snapshot = TipWitness::from_parts(head, true, " M node_modules/x\n");
        assert!(snapshot.tree_is_tip(&tip));
    }

    /// ADR-0018: the refusals fit 80 columns, put each command on its own
    /// line, and name only amont's own commands (every Green Harness part is
    /// optional: amont runs without relais, the skills or amont-agent).
    #[test]
    fn the_push_refusals_fit_and_name_only_amont() {
        let many: Vec<String> = (0..12)
            .map(|i| format!("pre-push-gate-number-{i}"))
            .collect();
        let names: Vec<&str> = many.iter().map(String::as_str).collect();
        let refs = vec![crate::pushrefs::PushRef {
            local_ref: "refs/heads/x".into(),
            local_oid: "a".repeat(40),
            remote_ref: "refs/heads/x".into(),
            remote_oid: "b".repeat(40),
        }];
        let sets = [
            push_refusal("abcdef12", &names, StampReuse::On, None),
            push_refusal("abcdef12", &names, StampReuse::Off, None),
            land_refusal(
                &crate::rehearsal::LandLine {
                    sha: "a".repeat(40),
                    remote_tip: "b".repeat(40),
                },
                &refs,
                &names,
            ),
            land_refusal(
                &crate::rehearsal::LandLine {
                    sha: "a".repeat(40),
                    remote_tip: "c".repeat(40),
                },
                &refs,
                &names,
            ),
            push_refusal(
                "abcdef12",
                &names,
                StampReuse::On,
                Some("v12.345.6789-rc.1+build.2026-11-05"),
            ),
        ];
        for lines in &sets {
            for line in lines {
                assert!(line.chars().count() <= 80, "{line:?}");
                for foreign in ["relais", "skill", "amont-agent"] {
                    assert!(!line.contains(foreign), "{line:?}");
                }
            }
            let joined = lines.join("\n");
            for name in &names {
                assert!(joined.contains(name), "every gate is named: {joined}");
            }
        }
        assert!(sets[0].iter().any(|l| l.ends_with(&format!("{BIN} land"))));
        assert!(sets[0]
            .iter()
            .any(|l| l.ends_with(&format!("{BIN} rehearse --wait"))));
        assert!(
            !sets[1].iter().any(|l| l.contains("rehearse")),
            "{:?}",
            sets[1]
        );
        assert!(sets[1]
            .iter()
            .any(|l| l.contains("greengate.pushStamps true")));
        assert!(sets[1].iter().any(|l| l.ends_with(&format!("{BIN} land"))));
        assert_eq!(sets[2][0], crate::land::LAND_EVIDENCE_MISSING);
        assert_eq!(sets[3][0], crate::land::LAND_REMOTE_MOVED);
        assert!(sets[0][0].starts_with(&format!("{BIN}: push refused:")));
        // A tag push is offered the tag's own land, never the branch remedies.
        assert!(
            sets[4].iter().any(|l| l.ends_with(&format!(
                "{BIN} land --tag v12.345.6789-rc.1+build.2026-11-05"
            ))),
            "{:?}",
            sets[4]
        );
        assert!(
            !sets[4].iter().any(|l| l.contains("rehearse")),
            "{:?}",
            sets[4]
        );
    }

    /// A check whose only job is to carry a name and a severity into `report`.
    /// Its `run` is never called — `report` is fed outcomes directly, which is
    /// what makes `Unavailable` testable at all: the real thing needs a missing
    /// binary, and a test that uninstalls the developer's toolchain is worse
    /// than no test.
    const fn stub(name: &'static str, severity: Severity) -> Builtin {
        Builtin {
            name,
            stage: Stage::PreCommit,
            scope: Scope::ALWAYS,
            severity,
            run: |_| Outcome::Passed,
            fix: crate::check::Fix::None,
            reach: crate::check::Reach::Convention,
        }
    }

    /// A pre-push gate with an OPT-IN file, as the real Rust and Python
    /// gates have: `.rs` files, but only where a `Cargo.toml` exists.
    const fn opt_in(
        name: &'static str,
        exts: &'static [&'static str],
        names: &'static [&'static str],
    ) -> Builtin {
        Builtin {
            name,
            stage: Stage::PrePush,
            scope: Scope::new(exts, names),
            severity: Severity::Block,
            run: |_| Outcome::Passed,
            fix: crate::check::Fix::None,
            reach: crate::check::Reach::Convention,
        }
    }

    /// A pre-push gate scoped to one language's files.
    const fn scoped(name: &'static str, exts: &'static [&'static str]) -> Builtin {
        Builtin {
            name,
            stage: Stage::PrePush,
            scope: Scope::new(exts, &[]),
            severity: Severity::Block,
            run: |_| Outcome::Passed,
            fix: crate::check::Fix::None,
            reach: crate::check::Reach::Convention,
        }
    }

    /// The over-claim this filter exists to stop, caught in the wild: a
    /// JS-only push minted `gates … pre-push-cargo-test pre-push-go-test
    /// pre-push-pytest`, because each of those gates finds nothing of its
    /// language to do and returns `Passed` having run NOTHING. Harmless in a
    /// single-language repo, unsound in a mixed one — CI would skip a suite
    /// nobody ran on that tree.
    #[test]
    fn a_gate_whose_language_the_push_never_touched_is_not_vouched_for() {
        let js = scoped("pre-push-run-tests-js", &[".ts", ".js"]);
        let rust = scoped("pre-push-cargo-test", &[".rs"]);
        let py = scoped("pre-push-pytest", &[".py"]);
        let always = stub("pre-push-secrets", Severity::Block);
        let checks: Vec<&dyn Check> = vec![&js, &rust, &py, &always];
        let passed: Vec<String> = checks.iter().map(|c| c.name().to_string()).collect();

        let changed = vec!["app/routes/home.ts".to_string()];
        let vouched = attestable(&checks, &passed, &changed);
        assert_eq!(
            vouched,
            vec![
                "pre-push-run-tests-js".to_string(),
                "pre-push-secrets".to_string()
            ],
            "only the gate that had work, plus the unscoped one that always runs"
        );

        // Nothing computed about the push vouches for nothing scoped — the
        // safe direction, since CI then runs the suite.
        assert_eq!(
            attestable(&checks, &passed, &[]),
            vec!["pre-push-secrets".to_string()]
        );

        // A check that did NOT pass is never vouched for, whatever its scope.
        let only_rust_passed = vec!["pre-push-cargo-test".to_string()];
        assert!(attestable(&checks, &only_rust_passed, &changed).is_empty());
    }

    /// No overrides configured. `report` takes them as a VALUE now, so its
    /// tests need no repository and no git at all.
    fn none() -> Overrides {
        Overrides::default()
    }

    static BLOCKER: Builtin = stub("stub-blocker", Severity::Block);
    static WARNER: Builtin = stub("stub-warner", Severity::Warn);

    /// The unit tests hold `&dyn Check` for the same reason the dispatcher
    /// does: `report` must not be able to tell a built-in from an external.
    const fn as_checks(cs: [&'static Builtin; 3]) -> [&'static dyn Check; 3] {
        [cs[0], cs[1], cs[2]]
    }

    /// The classification itself, which used to be unreachable: while one
    /// function classified AND printed AND returned a code, a test could assert
    /// the code and nothing else.
    #[test]
    fn every_outcome_lands_in_the_right_bucket() {
        let checks: [&dyn Check; 5] = [&BLOCKER, &BLOCKER, &WARNER, &BLOCKER, &BLOCKER];
        let got = classify(
            &checks,
            &[
                Outcome::Passed,
                Outcome::Unavailable,
                Outcome::Failed,
                Outcome::Failed,
                Outcome::Inert,
            ],
            &none(),
        );
        assert_eq!(got.blocked, ["stub-blocker"], "{got:?}");
        assert_eq!(got.downgraded, ["stub-warner"], "{got:?}");
        assert_eq!(got.unavailable, ["stub-blocker"], "{got:?}");
        assert_eq!(got.passed, 1, "inert is not a pass: {got:?}");
    }

    /// A clean stage concludes nothing at all — not an empty message, no
    /// message. Twenty checks that passed should print no roll-ups.
    ///
    /// `passed` is a tally, not a roll-up. It exists so that `greengate.quiet` can
    /// say how many lines it swallowed, and it must never be the reason this
    /// report looks like it has something to announce.
    #[test]
    fn a_clean_stage_has_nothing_to_report() {
        let checks: [&dyn Check; 2] = [&BLOCKER, &WARNER];
        let got = classify(&checks, &[Outcome::Passed, Outcome::Warned], &none());
        assert!(
            got.fixed.is_empty()
                && got.blocked.is_empty()
                && got.downgraded.is_empty()
                && got.unavailable.is_empty(),
            "a clean stage found something to announce: {got:?}"
        );
        assert_eq!(got.passed, 1, "the pass was not tallied: {got:?}");
        assert_eq!(got.verdict(), Verdict::Proceed);
    }

    #[test]
    fn a_blocking_failure_is_the_only_thing_that_fails_the_commit() {
        let b: &dyn Check = &BLOCKER;
        let w: &dyn Check = &WARNER;
        assert_eq!(
            classify(&[b], &[Outcome::Failed], &none()).verdict(),
            Verdict::Block
        );
        assert_eq!(
            classify(&[b], &[Outcome::Passed], &none()).verdict(),
            Verdict::Proceed
        );
        // Every non-blocking shape, one at a time, so a regression cannot hide
        // behind a passing sibling.
        assert_eq!(
            classify(&[b], &[Outcome::Warned], &none()).verdict(),
            Verdict::Proceed
        );
        assert_eq!(
            classify(&[b], &[Outcome::Unavailable], &none()).verdict(),
            Verdict::Proceed
        );
        assert_eq!(
            classify(&[w], &[Outcome::Failed], &none()).verdict(),
            Verdict::Proceed
        );
        // A skipped Heavy check never blocks by itself: the Light failure
        // that skipped it does (ADR-0020). It is listed, never counted passed.
        let skipped = classify(&[b], &[Outcome::Skipped], &none());
        assert_eq!(skipped.verdict(), Verdict::Proceed);
        assert_eq!(skipped.skipped, vec![b.name()]);
        assert_eq!(skipped.passed, 0);
    }

    #[test]
    fn the_environment_word_on_fail_fast_wins_and_a_bad_one_falls_back() {
        let settings = crate::config::Settings::default();
        assert!(!resolve_fail_fast(Some("false"), &settings));
        assert!(!resolve_fail_fast(Some("0"), &settings));
        assert!(resolve_fail_fast(Some("TRUE"), &settings));
        // Unset or unreadable: the configured value, here the default.
        assert!(resolve_fail_fast(None, &settings));
        assert!(resolve_fail_fast(Some(""), &settings));
        assert!(resolve_fail_fast(Some("sometimes"), &settings));
    }

    #[test]
    fn one_blocking_failure_among_many_still_fails() {
        let checks = as_checks([&BLOCKER, &WARNER, &BLOCKER]);
        assert_eq!(
            classify(
                &checks,
                &[Outcome::Unavailable, Outcome::Failed, Outcome::Failed],
                &none()
            )
            .verdict(),
            Verdict::Block
        );
        // Same shape, with the only *blocking* failure removed.
        assert_eq!(
            classify(
                &checks,
                &[Outcome::Unavailable, Outcome::Failed, Outcome::Passed],
                &none()
            )
            .verdict(),
            Verdict::Proceed
        );
    }

    /// The slot of a check whose thread died. Reading that as a pass is how a
    /// crash becomes a green commit.
    ///
    /// Asserted through the RUNNER, not through a `Default` impl: the rule
    /// belongs to this call site, and a test on `Outcome::default()` proved
    /// only that a trait impl existed, not that the runner used it.
    /// A check that PANICS must fail the commit, not pass it — and must not
    /// take the other checks down with it.
    ///
    /// Driven through the stage body rather than the runner, because the value
    /// that stands in for a dead check is chosen at the call site and the
    /// runner's own test cannot see that choice.
    #[test]
    fn a_panicking_check_blocks_the_commit() {
        static DIES: Builtin = Builtin {
            name: "stub-dies",
            stage: Stage::PreCommit,
            scope: Scope::ALWAYS,
            severity: Severity::Block,
            run: |_| panic!("this check died"),
            fix: crate::check::Fix::None,
            reach: crate::check::Reach::Convention,
        };
        let hook = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));
        let push = crate::pushrefs::PushRefs::default();
        let manifest = crate::manifest::Manifest::default();
        let settings = crate::config::Settings::default();
        let ctx = Ctx {
            name: "pre-commit",
            args: &[],
            hooks_dir: std::path::Path::new("."),
            push: &push,
            manifest: &manifest,
            settings: &settings,
            handed_to_cluster: &[],
            land: &crate::rehearsal::LandEnv::Absent,
            audits: &Default::default(),
            source_worktree: None,
        };
        let verdict = run_stage(&[&DIES], &ctx, &none());
        std::panic::set_hook(hook);
        assert_eq!(
            verdict,
            Verdict::Block,
            "a check that died must not let the commit through"
        );
    }

    #[test]
    fn a_thread_that_dies_leaves_a_failure_behind() {
        // The default hook would print a backtrace for the deliberate panic and
        // make a passing run look broken.
        let hook = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));
        let items = ["a", "b", "c"];
        let out = run_concurrently(
            &items,
            |n: &&str| {
                if *n == "b" {
                    panic!("this check died");
                }
                Outcome::Passed
            },
            Outcome::Failed,
        );
        std::panic::set_hook(hook);
        assert_eq!(
            out,
            vec![Outcome::Passed, Outcome::Failed, Outcome::Passed],
            "a dead check must not read as one that passed, \
             and must not take the other checks down with it"
        );
    }
    use std::time::{Duration, Instant};

    /// Concurrency proved by RENDEZVOUS, not by a stopwatch: every task must
    /// observe all the others arrive. Were the runner serial, the first task
    /// would wait alone, time out, and return non-zero — a failure, not a hang.
    #[test]
    fn run_concurrently_actually_overlaps() {
        static ARRIVED: AtomicUsize = AtomicUsize::new(0);
        ARRIVED.store(0, Ordering::SeqCst);
        let names: Vec<&'static str> = vec!["a", "b", "c", "d"];
        let n = names.len();

        let out = run_concurrently(
            &names,
            move |_: &&str| {
                ARRIVED.fetch_add(1, Ordering::SeqCst);
                let deadline = Instant::now() + Duration::from_secs(10);
                while ARRIVED.load(Ordering::SeqCst) < n {
                    if Instant::now() > deadline {
                        return 1; // never met the others — execution was serial
                    }
                    std::thread::yield_now();
                }
                0
            },
            1,
        );
        assert!(
            out.iter().all(|c| *c == 0),
            "tasks did not overlap: {out:?}"
        );
    }

    #[test]
    fn results_come_back_in_input_order() {
        let names: Vec<&'static str> = vec!["first", "second", "third"];
        let out = run_concurrently(&names, |n| if *n == "second" { 7 } else { 0 }, -1);
        assert_eq!(out, vec![0, 7, 0], "results keep the input order");
    }

    /// The filter calls the shared resolver rather than restating it. This test
    /// used to inline `n.contains(s)` — its own copy of the rule — and so went
    /// on passing after the rule changed underneath it.
    #[test]
    fn skips_are_filtered_by_the_shared_resolver() {
        let all = ["pre-commit-ruff", "pre-commit-prettier"];
        let skips = ["ruff".to_string()];
        let kept: Vec<_> = all
            .iter()
            .copied()
            .filter(|n| !skips.iter().any(|s| crate::skip_suppresses(n, s)))
            .collect();
        assert_eq!(kept, vec!["pre-commit-prettier"]);
    }

    /// The ordinary Rust push: source changed, `Cargo.toml` untouched.
    ///
    /// This test used to assert the OPPOSITE, and said so — it pinned
    /// `attestable` filtering on `Scope::matches`, which also asks whether
    /// the repository has opted in. Asking that of a push diff meant a
    /// `.rs`-only push, in a repository with a `Cargo.toml` sitting right
    /// there, attested nothing. Since that is what nearly every Rust push
    /// looks like, the feature was attesting almost nothing at all — quietly,
    /// while appearing to work.
    #[test]
    fn an_ordinary_source_push_is_vouched_for() {
        let rust = opt_in("pre-push-cargo-test", &[".rs"], &["Cargo.toml"]);
        let checks: Vec<&dyn Check> = vec![&rust];
        let passed = vec!["pre-push-cargo-test".to_string()];

        let changed = vec!["crates/greengate/src/main.rs".to_string()];
        assert_eq!(
            attestable(&checks, &passed, &changed),
            vec!["pre-push-cargo-test".to_string()],
            "a push that changed Rust must vouch for the Rust gate"
        );

        // And still when the marker IS in the diff — the opt-in file is not
        // required, but it is not disqualifying either.
        let changed = vec![
            "crates/greengate/src/main.rs".to_string(),
            "Cargo.toml".to_string(),
        ];
        assert_eq!(
            attestable(&checks, &passed, &changed),
            vec!["pre-push-cargo-test".to_string()]
        );
    }

    /// The over-claim the filter exists to stop, with an opt-in gate: a
    /// JS-only push must not vouch for the Rust suite, whatever files the
    /// repository contains.
    ///
    /// This is the half of the contract the fix above must not have broken,
    /// and it is the reason `touches` asks about EXTENSIONS rather than
    /// dropping the scope test altogether.
    #[test]
    fn an_opt_in_gate_is_not_vouched_for_by_a_push_in_another_language() {
        let rust = opt_in("pre-push-cargo-test", &[".rs"], &["Cargo.toml"]);
        let checks: Vec<&dyn Check> = vec![&rust];
        let passed = vec!["pre-push-cargo-test".to_string()];

        for changed in [
            vec!["app/routes/home.ts".to_string()],
            // Even the marker alone: editing Cargo.toml changes no Rust
            // source, so the suite has nothing new to have verified.
            vec!["Cargo.toml".to_string()],
            vec![],
        ] {
            assert!(
                attestable(&checks, &passed, &changed).is_empty(),
                "must not vouch for the Rust gate on {changed:?}"
            );
        }
    }

    /// amont #431: `onBusy wait` cannot stop a `warn` gate deferring, so a
    /// list of warn gates is advised only the command that waits, once per
    /// gate, and the hint is never offered.
    #[test]
    fn deferred_warn_gates_are_each_advised_the_command_that_waits() {
        let lines = deferral_advice(&[
            ("pre-push-probe", Severity::Warn),
            ("pre-push-lint", Severity::Warn),
        ]);
        let said = lines.join("\n");
        assert!(said.contains("2 check(s) deferred to CI"), "{said}");
        for gate in ["pre-push-probe", "pre-push-lint"] {
            assert!(
                said.contains(&format!("GREENGATE_ON_BUSY=wait {BIN} run --raw {gate}")),
                "{said}"
            );
        }
        assert!(!said.contains("set onBusy wait"), "{said}");
    }

    /// A list mixing a `block` and a `warn` gate: both get their command,
    /// and the `onBusy wait` hint says it stops only the block checks.
    #[test]
    fn a_mixed_deferral_names_every_gate_and_scopes_the_hint() {
        let lines = deferral_advice(&[
            ("pre-push-probe", Severity::Warn),
            ("pre-push-cargo-test", Severity::Block),
        ]);
        let said = lines.join("\n");
        for gate in ["pre-push-probe", "pre-push-cargo-test"] {
            assert!(
                said.contains(&format!("GREENGATE_ON_BUSY=wait {BIN} run --raw {gate}")),
                "{said}"
            );
        }
        let hint = lines
            .iter()
            .find(|l| l.contains("set onBusy wait"))
            .expect("the hint, for the block gate");
        assert!(hint.contains("block checks"), "{hint}");
        assert_eq!(lines.len(), 4, "roll-up, two commands, one hint: {said}");
    }
}