greenbelay 6.15.0

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

use greenbelay_guard::activity;
use greenbelay_guard::analysis;
use greenbelay_guard::assertions;
use greenbelay_guard::backtest;
use greenbelay_guard::civil;
use greenbelay_guard::compliance;
use greenbelay_guard::corpus;
use greenbelay_guard::decision;
use greenbelay_guard::doctor;
use greenbelay_guard::git;
use greenbelay_guard::graduate;
use greenbelay_guard::guidance;
use greenbelay_guard::harness_review;
use greenbelay_guard::migrate_plugin;
use greenbelay_guard::names::BIN;
use greenbelay_process::attestations;
use greenbelay_process::block_fingerprint;
use greenbelay_process::block_registry;
use greenbelay_process::content_id;
mod hook;
mod open;
mod plugin_install;
use greenbelay_guard::journal;
use greenbelay_guard::json;
use greenbelay_guard::lsp;
use greenbelay_guard::mine;
use greenbelay_guard::payload;
use greenbelay_guard::push_target;
#[cfg(unix)]
use greenbelay_guard::quiet;
use greenbelay_process::clear_boundary;
use greenbelay_process::code_review;
use greenbelay_process::impl_review_outcomes;
use greenbelay_process::implementation_review;
use greenbelay_process::implementation_review_rule;
use greenbelay_process::plan_apply;
use greenbelay_process::plan_phases;
use greenbelay_process::plan_review;
use greenbelay_process::plan_text;
use greenbelay_process::plans;
use greenbelay_process::preview;
use greenbelay_process::push_preview;
use greenbelay_process::review_brief;
use greenbelay_process::review_outcomes;
mod rule_table;
mod suppressions;
use greenbelay_guard::rules;
use greenbelay_guard::session_state;
use greenbelay_guard::settings;
use greenbelay_guard::shape;
use greenbelay_guard::shell;
use greenbelay_guard::shim;
use greenbelay_guard::stale;
use greenbelay_guard::stance;
use greenbelay_guard::transcript;
use greenbelay_guard::ui;
use greenbelay_process::board;
use greenbelay_process::shipped;

use std::ffi::OsString;
use std::path::PathBuf;
use std::process::ExitCode;

const USAGE: &str = concat!(
    "\
usage: ",
    greenbelay_guard::bin!(),
    " <command>

  hook                  read a Claude Code payload on stdin, decide
  install [--write]     add the hook to settings.json (prints it by default), and
                        place and enable the clear-relay plugin
  uninstall [--write]   remove exactly what install added, the plugin included
  migrate [--reverse] [--dry-run]
                        move this machine's state, git config keys and plugin
                        registration to the current names (or back); --dry-run
                        says what would change and writes nothing
  status                every rule, its stance, and what it has seen
  doctor [--json]       is the guard installed, runnable, and actually firing?
                        --json prints the findings and, apart from health, the
                        hook integration: present, absent, partial or unknown
  corpus check          replay every reviewed judgement through the rules
  graduate <rule> --to advise|deny
  demote <rule>         back to observing, no questions asked
  mine [flags]          shapes the model got wrong that no rule names yet
  output-audit --since <UTC> --until <UTC> [--json]
                        where tool output went in a window, by kind of call
  size-evidence [--days <n>] [--relay-dir <dir>]
                        clear-at-boundary size decisions of the last n days
                        (default 7) and the clear-relay submissions after each
                        handoff request; unreadable relay logs counted apart
  size-replay [--transcripts <dir>] [--since <YYYY-MM-DD>]
                        replay the size kind over recorded transcripts, Stop
                        by Stop: coverage, fires per week, the release bar
  backtest [flags]      replay your transcripts through the rules
  rollup [--weeks <n>] [--json] [--transcripts <dir>] [-q]
                        firings per week and rule, past the journal's rotation,
                        with each rule's tool calls and the rate per 1,000
  harness-review [--json] [--check] [--model <id>] [--out <dir>]
                        one row per rule and assertion: firings, compliance
                        per model, shadow-arm share, replay count; writes
                        <out dir>/<date>.json, --out defaulting to
                        <journal dir>/harness-review. --model is the model
                        the review is for (default: the model with the most
                        Bash calls in your transcripts, named in the output).
                        --check prints one line and exits 1 when that default
                        model is not the one the last review was made for
  explain <rule>        every match for one rule, for review
  check '<command>'     run the rules over one command, no stdin
                        [--dialect bash|zsh|unknown, default unknown]
                        [--cwd <dir>, default this directory] [--explain]
                        decide as the hook would in <dir>; --explain also
                        lists rules that matched but were not confirmed
  analyze '<command>'   the shell analysis of one command, as JSON — the
                        interface tools/shell-oracle compares against real
                        shells [--dialect, as for check]
  rules [--json]        every rule, its stance and its evidence; --json is
                        one array, the interface the homebrew tap reads
  preview register --url <url> --guide <file.md> [--repo <dir>] [--open]
                        validate a localhost preview of HEAD for approval
                        and render its guide to a page
  suppressions --staged judge the staged change: a lint suppression it adds
                        without a reason blocks (exit 1); the pre-commit gate
  open <url|path>       open a page for the person, through the opener in
                        `git config --global greenbelay.opener`
  plan-sha [--short] [--block [--lang <l>]] [--legacy] [--] <file|->
                        the sha256 of a plan's canonical body, as reviewed
  plan-panel <plan.md>  the review agents a plan still needs, as the
                        plan-review-panel hook will judge it
  plan-review record <plan.md> [--transcript <path>]
                        keep what each reviewer of a plan did, as outcome rows
  plan-review stats [--json] [--model <id>]
                        per (role, model): reviews, findings, accepted ones;
                        marks a seat that is a retire-candidate
  plan-review stats --time [--since <YYYY-MM-DD>] [--json]
                        per landed plan: time to done, blocked and person
                        hours, stops, word growth since round 1
  implementation-review record <plan.md> --verdict <v>
                        keep the implementation review's findings (JSON on
                        stdin) as one outcome row
  plan-apply [--dry-run|--check|--record-fallback] <plan.md>
                        apply the reviewers' Patches to a plan with no model
                        (accepted findings on stdin; exit 3 = some unmatched)
  attestations [--apply]
                        what ~/.claude/greenbelay/attestations keeps and
                        why; --apply moves the rest to a 7-day trash
  tree-sha [--block] [-C <dir>] [--] [<rev>]
                        the content id an implementation review and a
                        preview approval bind to: HEAD's tree without
                        docs/plans/ (not attest's canonical tree)
  block sha [-C <dir>] [--base <ref>]
                        the fingerprint of the branch's change, as a copy of
                        a reviewed block is recognised by
  rules-sha [-C <dir>]  the sha256 of the code rules `aval` reports, as an
                        implementation-review brief binds them
  review-brief [-C <dir>] [--plan <path>] [--base <ref>]
                        the implementation-review brief: tree and rules
                        lines, plan, diff, full code rules, decisions
  shipped <plan.md> [--json]
                        what shipped under a plan, derived from git: per
                        repository its merge commits, PRs, releases, and
                        signed provenance
  board [--repo <name>...] [--since <dur>] [--fetch] [--json]
                        the work in flight per repository (worktrees, live
                        unmerged branches, their active plan, the sessions
                        working there) and what landed recently, from git
                        and the session activity files
  owner claim|release|show
                        which session owns a worktree or a programme ticket;
                        `owner --help` documents the exit codes (0 done, 1 none
                        recorded or failed, 2 usage, 3 held by a live session)
  who-pushed <branch|sha> [--repo <r>] [--json]
                        which session published a branch or commit, newest
                        first (exit 1 when none is recorded)
  quiet [--max-bytes N[k]] -- <cmd…>
                        run a command with its output in a log file: one line
                        on a pass, the failure on a fail, the real exit code.
                        N is 1 to 48k bytes of excerpt (default 16k); exits
                        1 wrapper failure, 2 usage, 126 cannot execute,
                        127 not found, the command's own code, or
                        128+signal

install/uninstall flags:
  --write               actually edit the file
  --reformat            accept a normalised file when we cannot match its style
  --project             .claude/settings.json instead of ~/.claude
  --local               .claude/settings.local.json

backtest/explain/mine flags:
  --transcripts <dir>   where the .jsonl transcripts live
  --since <YYYY-MM-DD>  ignore entries before this day
  --rule <id>           restrict to one rule (repeatable)
  --sample <n>          sample matches to print per rule
  --format cases        emit matches as reviewable case lines (explain, mine)
  --json                machine-readable output

mine flags:
  --window <n>          tool calls a correction may arrive within (default 3)
  --min-support <n>     calls a shape needs before it is proposed (default 5)
  --min-rate <0..1>     share of them that must have gone wrong (default 0.3)

explain flags:
  --rank novelty        label the matches least like the ones already reviewed
  --out <dir>           explain clear-at-boundary --format cases: write the Stop
                        fixtures there (default: the checkout's
                        tests/corpus/stop/clear-at-boundary/); --sample <n>
                        keeps the n most recent Stops
  --cases <file>        explain clear-at-boundary --format cases: the .cases
                        file whose Stop lines are not printed again (default:
                        the checkout's tests/corpus/clear-at-boundary.cases)

backtest flags:
  --compliance          per model, per week: what the model did NEXT after a
                        rule fired — did the advice change anything?
"
);

enum Sub {
    Hook,
    Install,
    Uninstall,
    Status,
    Doctor,
    Corpus,
    Graduate,
    Demote,
    Backtest,
    Rollup,
    HarnessReview,
    Explain,
    Mine,
    OutputAudit,
    SizeEvidence,
    SizeReplay,
    Check,
    Analyze,
    Rules,
    Preview,
    PlanSha,
    PlanPanel,
    PlanReview,
    ImplementationReview,
    PlanApply,
    TreeSha,
    Block,
    RulesSha,
    ReviewBrief,
    Attestations,
    Quiet,
    Shipped,
    Board,
    Owner,
    WhoPushed,
    Open,
    Suppressions,
    Migrate,
}

const SUBCOMMANDS: [(&str, Sub); 38] = [
    ("hook", Sub::Hook),
    ("install", Sub::Install),
    ("uninstall", Sub::Uninstall),
    ("status", Sub::Status),
    ("doctor", Sub::Doctor),
    ("corpus", Sub::Corpus),
    ("graduate", Sub::Graduate),
    ("demote", Sub::Demote),
    ("backtest", Sub::Backtest),
    ("rollup", Sub::Rollup),
    ("harness-review", Sub::HarnessReview),
    ("explain", Sub::Explain),
    ("mine", Sub::Mine),
    ("output-audit", Sub::OutputAudit),
    ("size-evidence", Sub::SizeEvidence),
    ("size-replay", Sub::SizeReplay),
    ("check", Sub::Check),
    ("analyze", Sub::Analyze),
    ("rules", Sub::Rules),
    ("preview", Sub::Preview),
    ("plan-sha", Sub::PlanSha),
    ("plan-panel", Sub::PlanPanel),
    ("plan-review", Sub::PlanReview),
    ("implementation-review", Sub::ImplementationReview),
    ("plan-apply", Sub::PlanApply),
    ("tree-sha", Sub::TreeSha),
    ("block", Sub::Block),
    ("rules-sha", Sub::RulesSha),
    ("review-brief", Sub::ReviewBrief),
    ("attestations", Sub::Attestations),
    ("quiet", Sub::Quiet),
    ("shipped", Sub::Shipped),
    ("board", Sub::Board),
    ("owner", Sub::Owner),
    ("who-pushed", Sub::WhoPushed),
    ("open", Sub::Open),
    ("suppressions", Sub::Suppressions),
    ("migrate", Sub::Migrate),
];

enum Invocation {
    Sub { name: Sub, args: Vec<OsString> },
    Help,
    Version,
    Usage(String),
}

fn parse(argv: Vec<OsString>) -> Invocation {
    let Some(first) = argv.first() else {
        return Invocation::Usage("no command given".into());
    };
    let head = first.to_string_lossy().into_owned();
    if head == "--help" || head == "-h" || head == "help" {
        return Invocation::Help;
    }
    if head == "--version" || head == "-V" {
        return Invocation::Version;
    }
    for (name, sub) in SUBCOMMANDS {
        if head == name {
            return Invocation::Sub {
                name: sub,
                args: argv[1..].to_vec(),
            };
        }
    }
    // Help wins over a word we do not know (cli.help.help-and-version):
    // `amont-agent --bogus --help` is someone asking how to use us.
    if argv.iter().any(|a| a == "--help" || a == "-h") {
        return Invocation::Help;
    }
    Invocation::Usage(format!("unknown command `{head}`"))
}

/// Die quietly when the reader hangs up, like every other Unix filter.
///
/// Rust ignores SIGPIPE at startup, so `amont-agent rules | head` panicked
/// with a backtrace the moment `head` closed the pipe — `println!` hit EPIPE
/// and EPIPE is a panic. Restoring SIGPIPE's default disposition makes the
/// exit what a shell user expects (killed by the signal, status 141).
///
/// It matters more here than in an ordinary filter. This binary's entire
/// claim is that it is composed and predictable in front of somebody's
/// shell; a stack trace out of `rules | head` reads as a crash in exactly
/// the tool you were deciding whether to trust with your commands. It is
/// also the one thing this crate did NOT inherit when it left the amont
/// workspace: amont's `main` has carried this since `list | head` panicked,
/// and the split copied the modules the crate imported rather than the ones
/// it should have.
///
/// `extern "C"` rather than a crate: std already links libc, and a signal
/// disposition is not worth a dependency. Windows has no SIGPIPE; there the
/// pipe-closed write fails an `Err` path instead of raising a signal, and
/// this is a no-op.
#[cfg(unix)]
fn die_on_sigpipe() {
    extern "C" {
        fn signal(signum: i32, handler: usize) -> usize;
    }
    const SIGPIPE: i32 = 13;
    const SIG_DFL: usize = 0;
    unsafe {
        signal(SIGPIPE, SIG_DFL);
    }
}

#[cfg(not(unix))]
fn die_on_sigpipe() {}

/// What a command does about the one-time migration before it runs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum MigrationMode {
    /// Reads or reports only: no migration.
    Skip,
    /// Try once without waiting; never fail or block the command.
    Zero,
    /// Wait up to the cap for the lock; refuse to run when the migration
    /// cannot finish.
    Capped(std::time::Duration),
}

const MIGRATE_WAIT_CAP: std::time::Duration = std::time::Duration::from_secs(30);

/// A test seam: how long `install` waits for the migration lock, in
/// milliseconds.
const ENV_MIGRATE_WAIT_MS: &str = greenbelay_guard::env_var!("TEST_MIGRATE_WAIT_MS");

/// The migration mode of a subcommand. `migrate` and `doctor` report on the
/// migration themselves; a command asked for help or the version, or asked
/// only to preview or check (`--dry-run`, `--check`), changes nothing; a hook
/// never waits, since its stdout is a decision; `install` waits and refuses.
fn migration_mode(name: &Sub, args: &[OsString]) -> MigrationMode {
    let reads_only = args.iter().any(|arg| {
        arg == "--help"
            || arg == "-h"
            || arg == "--version"
            || arg == "--dry-run"
            || arg == "--check"
    });
    if matches!(name, Sub::Migrate | Sub::Doctor) || reads_only {
        return MigrationMode::Skip;
    }
    match name {
        Sub::Install => MigrationMode::Capped(
            std::env::var(ENV_MIGRATE_WAIT_MS)
                .ok()
                .and_then(|text| text.parse().ok())
                .map_or(MIGRATE_WAIT_CAP, std::time::Duration::from_millis),
        ),
        _ => MigrationMode::Zero,
    }
}

/// Run the one-time migration before a command. Only a `Capped` command can
/// be refused; for every other mode the command goes on whatever happens,
/// and a command that may talk says once that the migration failed.
fn preflight_migration(name: &Sub, args: &[OsString]) -> Result<(), String> {
    match migration_mode(name, args) {
        MigrationMode::Skip => Ok(()),
        MigrationMode::Zero => {
            let failed = greenbelay_guard::migrate::preflight();
            if failed && !matches!(name, Sub::Hook) {
                eprintln!("{BIN}: migration failed (see {BIN} doctor); run {BIN} migrate");
            }
            Ok(())
        }
        MigrationMode::Capped(wait) => greenbelay_guard::migrate::settle(wait).map_err(|error| {
            format!(
                "{error}\nnothing was installed; fix what it names, then run `{BIN} install` again"
            )
        }),
    }
}

/// What `greenbelay migrate` was asked to do.
struct MigrateRequest {
    direction: greenbelay_guard::migrate::Direction,
    dry_run: bool,
}

/// The request in `args`, or the exit code of `--help` or a usage error.
fn parse_migrate(args: &[OsString]) -> Result<MigrateRequest, ExitCode> {
    use greenbelay_guard::migrate::Direction;
    let mut request = MigrateRequest {
        direction: Direction::Forward,
        dry_run: false,
    };
    for arg in args {
        match arg.to_string_lossy().as_ref() {
            "--reverse" => request.direction = Direction::Reverse,
            "--dry-run" => request.dry_run = true,
            "--help" | "-h" => {
                println!(concat!(
                    "usage: ",
                    greenbelay_guard::bin!(),
                    " migrate [--reverse] [--dry-run]"
                ));
                println!();
                println!("Move this machine's state directories, git config keys and plugin");
                println!("registration to the current names; --reverse moves them back.");
                println!("  --dry-run  print what would change; write nothing, take no lock");
                return Err(ExitCode::SUCCESS);
            }
            other => {
                eprintln!("{BIN}: migrate takes --reverse and --dry-run, not {other}");
                return Err(ExitCode::from(2));
            }
        }
    }
    Ok(request)
}

fn run_migrate(args: &[OsString]) -> ExitCode {
    use greenbelay_guard::migrate::{self, MigrateError};
    let request = match parse_migrate(args) {
        Ok(request) => request,
        Err(code) => return code,
    };
    let direction = request.direction;
    let Some(env) = migrate::Env::from_process() else {
        eprintln!("{BIN}: {}", MigrateError::NoHome);
        return ExitCode::FAILURE;
    };
    if request.dry_run {
        return match migrate::machine_plan(&env, direction) {
            Ok(lines) => {
                let registry = migrate_plugin::registry_state_after(&env, direction);
                if lines.is_empty() {
                    // "nothing to do" only when Claude Code's registry needs
                    // nothing either: a script reading it must not be told so
                    // while the plugin stays off.
                    match registry.report() {
                        None => println!("nothing to do: {}", already(direction)),
                        Some(_) => println!("nothing to move: {}", already(direction)),
                    }
                }
                let mut refused = false;
                for line in lines {
                    match line {
                        migrate::PlanLine::Action(text) => println!("would: {text}"),
                        migrate::PlanLine::Refusal { step, reason } => {
                            refused = true;
                            println!("would refuse: {step}: {reason}");
                        }
                    }
                }
                print_registry(&registry, RegistryVoice::WouldThenNeed);
                if refused {
                    eprintln!("migrate would stop: fix what is named above first");
                    return ExitCode::FAILURE;
                }
                ExitCode::SUCCESS
            }
            Err(error) => {
                eprintln!("{BIN}: {error}");
                ExitCode::FAILURE
            }
        };
    }
    // Say once that another process holds the lock before waiting for it; a
    // lock the probe gets is released at once.
    let probe = greenbelay_guard::lock::lock_within(
        &env.config_dir
            .join(greenbelay_guard::names::MIGRATE_LOCK_FILE),
        std::time::Duration::ZERO,
    );
    if matches!(probe, Ok(None)) {
        eprintln!("{BIN}: waiting for another migration to finish");
    }
    drop(probe);
    let outcome = migrate::machine_in(&env, direction, migrate::Wait::Capped(MIGRATE_WAIT_CAP));
    let verdict = match settled_verdict(&env, direction, outcome) {
        Ok(verdict) => verdict,
        Err(code) => return code,
    };
    if let Err(error) = migrate_local_repository(&env, direction) {
        eprintln!("{BIN}: {error}");
        return ExitCode::FAILURE;
    }
    eprintln!("{verdict}");
    print_registry(&migrate_plugin::registry_state(&env), RegistryVoice::Run);
    ExitCode::SUCCESS
}

/// How the registry diagnostics are phrased. Both go to stderr: they are
/// commands for the person to run, never something greenbelay does.
#[derive(Clone, Copy)]
enum RegistryVoice {
    /// An explicit run that settled: say what to run.
    Run,
    /// A dry run or an install preview: `would then need:` lines.
    WouldThenNeed,
}

/// Say what Claude Code's plugin registry needs, never doing it.
fn print_registry(state: &migrate_plugin::RegistryState, voice: RegistryVoice) {
    use greenbelay_guard::ui::sanitize;
    let Some(report) = state.report() else {
        return;
    };
    let what = sanitize(&report.what);
    if report.commands.is_empty() {
        eprintln!("{what}");
        if let Some(hint) = report.hint {
            eprintln!("  {hint}");
        }
        return;
    }
    match voice {
        RegistryVoice::Run => {
            eprintln!("{what}; run:");
            for command in &report.commands {
                eprintln!("  {}", sanitize(command));
            }
        }
        RegistryVoice::WouldThenNeed => {
            eprintln!("{what}; you would then need to run:");
            for command in &report.commands {
                eprintln!("would then need: {}", sanitize(command));
            }
        }
    }
}

/// What a finished state is called in a "nothing to do" line.
fn already(direction: greenbelay_guard::migrate::Direction) -> &'static str {
    match direction {
        greenbelay_guard::migrate::Direction::Forward => "already migrated",
        greenbelay_guard::migrate::Direction::Reverse => "already reversed",
    }
}

/// The closing line of a run, after its step lines are printed; or the exit
/// code of a run that did not finish, after its error is printed.
fn settled_verdict(
    env: &greenbelay_guard::migrate::Env,
    direction: greenbelay_guard::migrate::Direction,
    outcome: Result<greenbelay_guard::migrate::Outcome, greenbelay_guard::migrate::MigrateError>,
) -> Result<String, ExitCode> {
    use greenbelay_guard::migrate::{self, Direction, MigrateError, Outcome};
    match outcome {
        Ok(Outcome::Migrated { steps, elapsed }) => {
            for step in &steps {
                eprintln!("{step}");
            }
            Ok(if steps.is_empty() {
                "nothing to move".to_string()
            } else {
                format!(
                    "migrated {} steps in {:.1}s",
                    steps.len(),
                    elapsed.as_secs_f64()
                )
            })
        }
        Ok(Outcome::AlreadyDone) => Ok(format!("nothing to do: {}", already(Direction::Forward))),
        Ok(Outcome::ReversedAlready) => {
            Ok(format!("nothing to do: {}", already(Direction::Reverse)))
        }
        Ok(Outcome::Reversed) => Ok("reversed".to_string()),
        Ok(Outcome::Busy) => {
            eprintln!(
                "{BIN}: another process holds the migration lock {}; retry when it finishes",
                env.config_dir
                    .join(greenbelay_guard::names::MIGRATE_LOCK_FILE)
                    .display()
            );
            Err(ExitCode::FAILURE)
        }
        Ok(Outcome::FailedBefore) => {
            let note = migrate::failure_note(env).unwrap_or_default();
            eprintln!(
                "{BIN}: an earlier migration failed: {}; run {BIN} migrate to try again",
                note.trim().replace('\n', ": ")
            );
            Err(ExitCode::FAILURE)
        }
        Err(error) => {
            eprintln!("{BIN}: {error}");
            match (&error, direction) {
                (MigrateError::Locked { .. } | MigrateError::Step { .. }, _) => {}
                (_, Direction::Forward) => eprintln!(
                    "fix what it names, then run {BIN} migrate again (or \
                     run {BIN} migrate --reverse to put everything back)"
                ),
                (_, Direction::Reverse) => {
                    eprintln!("fix what it names, then run {BIN} migrate --reverse again");
                }
            }
            Err(ExitCode::FAILURE)
        }
    }
}

/// An explicit run inside a git repository also renames that repository's own
/// config keys; never a hook's job.
fn migrate_local_repository(
    env: &greenbelay_guard::migrate::Env,
    direction: greenbelay_guard::migrate::Direction,
) -> Result<(), String> {
    let Ok(here) = std::env::current_dir() else {
        return Ok(());
    };
    let inside = std::process::Command::new("git")
        .current_dir(&here)
        .args(["rev-parse", "--is-inside-work-tree"])
        .output()
        .is_ok_and(|output| output.status.success());
    if !inside {
        return Ok(());
    }
    greenbelay_guard::migrate_config::migrate_local(env, &here, direction)
        .map(drop)
        .map_err(|error| error.to_string())
}

fn main() -> ExitCode {
    // `suppressions --staged` must see the index git handed the hook (a
    // temporary one on `commit -a` and `commit <path>`), so it is read here,
    // before the scrub below removes it.
    let hook_index = std::env::var_os("GIT_INDEX_FILE");
    // amont hands a declared pre-commit check the absolute commit index and
    // its owner's per-worktree git-dir; only `suppressions` reads the pair,
    // and the index wins over `GIT_INDEX_FILE` only for a matching owner.
    let index_handoff = suppressions::IndexHandoff::from_env();
    // Claude Code does not spawn us from git, but a session started inside a
    // git hook still carries GIT_DIR / GIT_WORK_TREE, and those beat
    // `current_dir` for every git command we run. `crate::git` builds
    // its own Commands and has no seam to pass an environment through, so the
    // scrub has to happen here. This is the same failure the test harness's
    // `strip_git_env` exists to prevent; it committed to the wrong repository
    // once.
    //
    // NAMED, not a `GIT_` prefix sweep. The sweep took `GIT_CONFIG_GLOBAL`
    // and `GIT_CONFIG_SYSTEM` with it, and those two say where config LIVES
    // rather than which repository this is — so a person who keeps their git
    // config somewhere other than `~/.gitconfig` had every stance they set
    // silently ignored, and this crate's own tests could not point the
    // reader at a fixture. amont's `rehearsal::strip_repo_env` draws the
    // line in the same place and for the same reason.
    for key in [
        "GIT_DIR",
        "GIT_WORK_TREE",
        "GIT_INDEX_FILE",
        "GIT_COMMON_DIR",
        "GIT_PREFIX",
        "GIT_OBJECT_DIRECTORY",
        "GIT_ALTERNATE_OBJECT_DIRECTORIES",
        "GIT_NAMESPACE",
        "GIT_REFLOG_ACTION",
        "GIT_EXEC_PATH",
    ] {
        std::env::remove_var(key);
    }

    let invocation = parse(std::env::args_os().skip(1).collect());
    // `hook` and `board` feed git children on stdin (`git patch-id`). A
    // child that exits before reading all of it, or is killed at its
    // deadline, would raise SIGPIPE in the feeder and kill the whole
    // process: the hook then exits 141 and its decision is lost. Both keep
    // SIGPIPE ignored, so the write fails as an error the caller handles;
    // `board` already treats EPIPE on its own output as a quiet exit.
    // `suppressions` feeds `git cat-file` the same way. `plan-review` keeps
    // it ignored so that `plan-review stats … | head` ends on EPIPE with the
    // command's own exit code, not by the signal (141). `rollup` keeps it
    // ignored so that `rollup | head` ends on EPIPE after its state writes.
    if !matches!(
        invocation,
        Invocation::Sub {
            name: Sub::Hook | Sub::Board | Sub::Suppressions | Sub::PlanReview | Sub::Rollup,
            ..
        }
    ) {
        die_on_sigpipe();
    }
    if let Invocation::Sub { name, args } = &invocation {
        if let Err(why) = preflight_migration(name, args) {
            eprintln!("{BIN}: {why}");
            return ExitCode::FAILURE;
        }
    }
    match invocation {
        Invocation::Help => {
            print!("{USAGE}");
            ExitCode::SUCCESS
        }
        Invocation::Version => {
            println!(
                concat!(greenbelay_guard::bin!(), " {}"),
                env!("CARGO_PKG_VERSION")
            );
            ExitCode::SUCCESS
        }
        Invocation::Usage(why) => {
            eprintln!("{BIN}: {why}\n");
            eprint!("{USAGE}");
            ExitCode::from(2)
        }
        Invocation::Sub { name, args } => match name {
            // `hook` takes no flags: everything it needs arrives on stdin.
            // Claude Code may pass `--event <name>` for readability, and it is
            // accepted and ignored — the payload names its own event, and
            // trusting argv over the payload would let the two disagree.
            Sub::Hook => {
                let _ = args;
                hook::run()
            }
            Sub::Install => run_install(&args, true),
            Sub::Uninstall => run_install(&args, false),
            Sub::Status => run_status(),
            Sub::Doctor => {
                // Non-zero when the guard is not doing anything, so this is
                // usable from a cron job or a SessionStart check without
                // anybody having to read the text.
                if args.iter().any(|a| a == "--help" || a == "-h") {
                    println!(concat!(
                        "usage: ",
                        greenbelay_guard::bin!(),
                        " doctor [--json]"
                    ));
                    println!();
                    println!("Check that the guard is installed and alive; exit 0 when it is.");
                    println!("  --json  print one JSON document: healthy, findings, integration");
                    return ExitCode::SUCCESS;
                }
                if let Some(bad) = args.iter().find(|a| *a != "--json") {
                    eprintln!(
                        concat!(
                            greenbelay_guard::bin!(),
                            ": doctor takes only --json, not {}"
                        ),
                        bad.to_string_lossy()
                    );
                    return ExitCode::from(2);
                }
                let scanned = doctor::scan();
                let mut findings =
                    doctor::run(rule_table::RULES, attestations::doctor_finding(), &scanned);
                findings.push(plan_root_finding());
                findings.push(open::opener_finding());
                if let Ok(project) = std::env::current_dir() {
                    findings.extend(greenbelay_process::agents::review_gaps(&project));
                }
                let healthy = if args.iter().any(|a| a == "--json") {
                    println!(
                        "{}",
                        doctor::json(&findings, &doctor::integration(&scanned))
                    );
                    doctor::healthy(&findings)
                } else {
                    doctor::report(&findings)
                };
                if healthy {
                    ExitCode::SUCCESS
                } else {
                    ExitCode::FAILURE
                }
            }
            Sub::Migrate => run_migrate(&args),
            Sub::Corpus => run_corpus(&args),
            Sub::Graduate => run_graduate(&args, true),
            Sub::Demote => run_graduate(&args, false),
            Sub::Backtest => run_backtest(&args, false),
            Sub::Rollup => run_rollup(&args),
            Sub::HarnessReview => run_harness_review(&args),
            Sub::Explain => run_backtest(&args, true),
            Sub::Mine => run_mine(&args),
            Sub::OutputAudit => run_output_audit(&args),
            Sub::SizeEvidence => run_size_evidence(&args),
            Sub::SizeReplay => run_size_replay(&args),
            Sub::Check => run_check(&args),
            Sub::Analyze => run_analyze(&args),
            Sub::Rules => run_rules(&args),
            Sub::Preview => run_preview(&args),
            Sub::PlanSha => run_plan_sha(&args),
            Sub::Shipped => shipped::run(&args),
            Sub::Board => board::run(&args),
            Sub::Owner => {
                let words: Vec<String> = args
                    .iter()
                    .map(|arg| arg.to_string_lossy().into_owned())
                    .collect();
                ExitCode::from(greenbelay_guard::owner::command::run(&words))
            }
            Sub::WhoPushed => {
                let words: Vec<String> = args
                    .iter()
                    .map(|arg| arg.to_string_lossy().into_owned())
                    .collect();
                ExitCode::from(greenbelay_guard::owner::command::who_pushed(&words))
            }
            Sub::Open => open::run(&args),
            Sub::Suppressions => suppressions::run(&args, index_handoff, hook_index),
            Sub::PlanPanel => run_plan_panel(&args),
            Sub::PlanReview => {
                let (said, code) = review_outcomes::run(&args);
                // `print!` panics on a closed pipe (exit 101); a reader that
                // stops early (`| head`) is not a failure of its own, so the
                // command keeps its own exit code, success or failure.
                use std::io::Write as _;
                let mut out = std::io::stdout().lock();
                match out.write_all(said.as_bytes()).and_then(|()| out.flush()) {
                    Ok(()) => code,
                    Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => code,
                    Err(e) => {
                        eprintln!(
                            "{}: plan-review: cannot write output: {e}",
                            greenbelay_guard::names::BIN
                        );
                        ExitCode::from(1)
                    }
                }
            }
            Sub::ImplementationReview => {
                let (said, code) = impl_review_outcomes::run(&args);
                print!("{said}");
                code
            }
            Sub::PlanApply => {
                let (said, code) = plan_apply::run(&args);
                print!("{said}");
                code
            }
            Sub::TreeSha => run_tree_sha(&args),
            Sub::Block => run_block(&args),
            Sub::RulesSha => run_rules_sha(&args),
            Sub::ReviewBrief => run_review_brief(&args),
            Sub::Attestations => attestations::run_cli(&args),
            #[cfg(unix)]
            Sub::Quiet => quiet::run(&args),
            #[cfg(not(unix))]
            Sub::Quiet => {
                eprintln!(concat!(
                    greenbelay_guard::bin!(),
                    ": quiet is not supported on this platform"
                ));
                ExitCode::from(2)
            }
        },
    }
}

#[derive(Default)]
struct Flags {
    write: bool,
    reformat: bool,
    project: bool,
    local: bool,
    transcripts: Vec<PathBuf>,
    since: Option<civil::Day>,
    only: Vec<String>,
    sample: Option<usize>,
    json: bool,
    format: Option<String>,
    to: Option<String>,
    force: bool,
    window: Option<usize>,
    min_support: Option<u32>,
    min_rate: Option<f64>,
    rank: Option<String>,
    compliance: bool,
    check: bool,
    out: Option<PathBuf>,
    cases: Option<PathBuf>,
    model: Option<String>,
    dialect: Option<rules::Dialect>,
    cwd: Option<PathBuf>,
    explain: bool,
    rest: Vec<String>,
}

fn flags(args: &[OsString]) -> Result<Flags, String> {
    let mut f = Flags::default();
    let mut i = 0;
    while i < args.len() {
        let a = args[i].to_string_lossy().into_owned();
        let value = |i: &mut usize, what: &str| -> Result<String, String> {
            *i += 1;
            args.get(*i)
                .map(|v| v.to_string_lossy().into_owned())
                .ok_or_else(|| format!("{what} needs a value"))
        };
        match a.as_str() {
            "--out" => f.out = Some(PathBuf::from(value(&mut i, &a)?)),
            "--cases" => f.cases = Some(PathBuf::from(value(&mut i, &a)?)),
            "--model" => f.model = Some(value(&mut i, &a)?),
            "--transcripts" => f.transcripts.push(PathBuf::from(value(&mut i, &a)?)),
            "--since" => {
                let v = value(&mut i, &a)?;
                f.since =
                    Some(civil::day_of(&v).ok_or_else(|| format!("--since: `{v}` is not a date"))?);
            }
            "--rule" => f.only.push(value(&mut i, &a)?),
            "--sample" => {
                let v = value(&mut i, &a)?;
                let count: usize = v
                    .parse()
                    .map_err(|_| format!("--sample: `{v}` is not a number"))?;
                if count == 0 {
                    return Err("--sample: takes 1 or more".to_string());
                }
                f.sample = Some(count);
            }
            "--window" => {
                let v = value(&mut i, &a)?;
                f.window = Some(
                    v.parse()
                        .map_err(|_| format!("--window: `{v}` is not a number"))?,
                );
            }
            "--min-support" => {
                let v = value(&mut i, &a)?;
                f.min_support = Some(
                    v.parse()
                        .map_err(|_| format!("--min-support: `{v}` is not a number"))?,
                );
            }
            "--min-rate" => {
                let v = value(&mut i, &a)?;
                let rate: f64 = v
                    .parse()
                    .map_err(|_| format!("--min-rate: `{v}` is not a number"))?;
                if !(0.0..=1.0).contains(&rate) {
                    return Err(format!("--min-rate: `{v}` is not a share between 0 and 1"));
                }
                f.min_rate = Some(rate);
            }
            "--rank" => f.rank = Some(value(&mut i, &a)?),
            "--dialect" => {
                let v = value(&mut i, &a)?;
                f.dialect = Some(
                    rules::Dialect::parse(&v)
                        .ok_or_else(|| format!("--dialect: `{v}` is not bash, zsh or unknown"))?,
                );
            }
            "--cwd" => f.cwd = Some(PathBuf::from(value(&mut i, &a)?)),
            "--explain" => f.explain = true,
            "--compliance" => f.compliance = true,
            "--check" => f.check = true,
            "--json" => f.json = true,
            "--format" => f.format = Some(value(&mut i, &a)?),
            "--to" => f.to = Some(value(&mut i, &a)?),
            "--force" => f.force = true,
            "--write" => f.write = true,
            "--reformat" => f.reformat = true,
            "--project" => f.project = true,
            "--local" => f.local = true,
            other if other.starts_with('-') => return Err(format!("unknown flag `{other}`")),
            other => f.rest.push(other.to_string()),
        }
        i += 1;
    }
    Ok(f)
}

/// Which rules and assertions a backtest replays.
///
/// Both kinds answer to an id, and somebody asking "how often would this have
/// fired" does not care which list it came from.
fn selected(only: &[String]) -> Result<Vec<backtest::Subject>, String> {
    let everything = || {
        rule_table::RULES
            .iter()
            .map(backtest::Subject::Rule)
            .chain(
                assertions::ASSERTIONS
                    .iter()
                    .map(backtest::Subject::Assertion),
            )
            .collect::<Vec<_>>()
    };
    if only.is_empty() {
        return Ok(everything());
    }
    only.iter()
        .map(|id| {
            rules::by_id(rule_table::RULES, id)
                .map(backtest::Subject::Rule)
                .or_else(|| assertions::by_id(id).map(backtest::Subject::Assertion))
                .ok_or_else(|| {
                    let known: Vec<&str> = everything().iter().map(|s| s.id()).collect();
                    format!("no rule `{id}` — known rules: {}", known.join(", "))
                })
        })
        .collect()
}

fn run_backtest(args: &[OsString], explain: bool) -> ExitCode {
    let mut f = match flags(args) {
        Ok(f) => f,
        Err(why) => {
            eprintln!("{BIN}: {why}");
            return ExitCode::from(2);
        }
    };
    if explain {
        match f.rest.len() {
            1 => f.only.push(f.rest[0].clone()),
            _ => {
                eprintln!(concat!(
                    greenbelay_guard::bin!(),
                    ": explain needs exactly one rule"
                ));
                return ExitCode::from(2);
            }
        }
    }
    let chosen = match selected(&f.only) {
        Ok(c) => c,
        Err(why) => {
            eprintln!("{BIN}: {why}");
            return ExitCode::from(2);
        }
    };
    let as_cases = explain && f.format.as_deref() == Some("cases");
    if let Some(other) = f.format.as_deref() {
        if other != "cases" {
            eprintln!("{BIN}: --format takes `cases`, not `{other}`");
            return ExitCode::from(2);
        }
    }
    let exporting = as_cases && f.only == [greenbelay_guard::rules::clear_at_boundary::RULE.id];
    let unused: &[(bool, &str)] = if exporting {
        &[
            (f.since.is_some(), "--since"),
            (f.json, "--json"),
            (f.rank.is_some(), "--rank"),
        ]
    } else if explain {
        &[(f.out.is_some(), "--out"), (f.cases.is_some(), "--cases")]
    } else {
        &[(f.cases.is_some(), "--cases")]
    };
    if let Some((_, name)) = unused.iter().find(|(given, _)| *given) {
        let scope = if exporting {
            "the Stop export does not use"
        } else {
            "only `explain clear-at-boundary --format cases` takes"
        };
        eprintln!("{BIN}: {name}: {scope} it");
        return ExitCode::from(2);
    }
    if exporting {
        return run_export_stops(&f);
    }
    let roots = match transcript::roots(&f.transcripts) {
        Ok(r) => r,
        Err(e) => {
            eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
            return ExitCode::from(2);
        }
    };
    let scan = transcript::Scan {
        roots: &roots,
        tool: "Bash",
        since: f.since,
    };
    let novelty = match f.rank.as_deref() {
        None => false,
        Some("novelty") if explain => true,
        Some("novelty") => {
            eprintln!(concat!(
                greenbelay_guard::bin!(),
                ": --rank novelty is for `explain`, which prints the matches"
            ));
            return ExitCode::from(2);
        }
        Some(other) => {
            eprintln!("{BIN}: --rank takes `novelty`, not `{other}`");
            return ExitCode::from(2);
        }
    };
    if f.compliance {
        return run_compliance(&f, &roots, &scan, &chosen);
    }
    // A review dump wants everything, not a sample: the point is to look at
    // each match once and decide. Novelty ranking is the exception — it
    // answers "which twenty are worth an hour", and ordering every match by
    // novelty is quadratic in a number that runs to thousands.
    let samples = if novelty {
        usize::MAX
    } else {
        f.sample.unwrap_or(if as_cases {
            usize::MAX
        } else if explain {
            40
        } else {
            2
        })
    };
    match backtest::run(&scan, &chosen, samples) {
        Ok(mut report) => {
            if novelty {
                rank_by_novelty(&mut report, f.sample.unwrap_or(20));
            }
            if as_cases {
                // Every line starts unreviewed. The file this is appended to is
                // the same format the reviewer edits in place — one format, so
                // the review is a single pass with no export step to forget.
                println!("{}", corpus::HEADER);
                let mut seen = std::collections::BTreeSet::new();
                for group in &report.samples {
                    for sample in group {
                        if seen.insert(sample.command.clone()) {
                            print!(
                                "{}",
                                corpus::line_for(corpus::Verdict::Unreviewed, &sample.command)
                            );
                        }
                    }
                }
            } else if f.json {
                println!("{}", report.to_json(&roots));
            } else {
                print!("{}", report.render(&roots));
            }
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
            ExitCode::from(2)
        }
    }
}

/// `explain clear-at-boundary --format cases`: freeze the Stops the rule's
/// journal lines record as fixtures, and print one `?` case line for each.
/// Stdout carries only case lines; the notes and the summary go to stderr.
fn run_export_stops(flags: &Flags) -> ExitCode {
    let rule = greenbelay_guard::rules::clear_at_boundary::RULE.id;
    let out = match &flags.out {
        Some(dir) => dir.clone(),
        None if corpus::checkout_present() => corpus::stop_dir_for(rule),
        None => {
            eprintln!(
                concat!(
                    "{}: this build has no checkout to write fixtures into; ",
                    "pass --out <dir>, or run `cargo run -- explain {} --format cases` ",
                    "from a checkout of ",
                    greenbelay_guard::bin!()
                ),
                BIN, rule
            );
            return ExitCode::from(2);
        }
    };
    let roots = match transcript::roots(&flags.transcripts) {
        Ok(r) => r,
        Err(e) => {
            eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
            return ExitCode::from(2);
        }
    };
    let Some(journal_dir) = journal::dir() else {
        eprintln!("{BIN}: no journal directory: neither CLAUDE_CONFIG_DIR nor HOME is set");
        return ExitCode::from(2);
    };
    let journal_files = match greenbelay_process::clear_boundary_export::journal_files(&journal_dir)
    {
        Ok(files) => files,
        Err(error) => {
            eprintln!("{BIN}: {}: {error}", journal_dir.display());
            return ExitCode::from(2);
        }
    };
    let cases_path = flags
        .cases
        .clone()
        .unwrap_or_else(|| corpus::path_for(rule));
    let cases_text = match std::fs::read_to_string(&cases_path) {
        Ok(text) => text,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(error) => {
            eprintln!("{BIN}: {}: {error}", cases_path.display());
            return ExitCode::from(2);
        }
    };
    let mut options = greenbelay_process::clear_boundary_export::Options::new(out);
    options.journal = journal_files;
    options.transcripts = transcript::files(&roots);
    options.transcript_roots = roots.dirs.clone();
    options.cases_text = cases_text;
    options.sample = flags.sample;
    options.home = std::env::var("HOME").ok();
    let report = greenbelay_process::clear_boundary_export::export(&options);
    for note in &report.notes {
        eprintln!("{BIN}: {note}");
    }
    if report.found_nothing() {
        eprintln!(
            "{BIN}: no clear-at-boundary lines in {}",
            journal_dir.display()
        );
        return ExitCode::FAILURE;
    }
    eprintln!("{}", report.summary());
    for line in &report.stdout {
        println!("{line}");
    }
    if report.failed() {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}

/// Keep the `n` matches least like the cases already reviewed, and least like
/// each other.
///
/// The default sample is the first `n` matches the walk met, which is the
/// oldest project, the oldest session, and — because a habit repeats — very
/// often twenty spellings of one command. Labelling those costs the same
/// hour and moves the precision estimate by almost nothing. This picks the
/// hour's worth that moves it most.
fn rank_by_novelty(report: &mut backtest::Report, n: usize) {
    for (i, subject) in report.rules.iter().enumerate() {
        // Already-labelled cases are seeds: they are the neighbourhoods the
        // corpus already covers, and a second review pass should not hand
        // back the first pass's cases.
        let seeds: Vec<shape::Shape> = corpus::read(subject.id())
            .iter()
            .map(|c| shape::Shape::of_command(&c.command))
            .collect();
        let candidates: Vec<shape::Shape> = report.samples[i]
            .iter()
            .map(|s| shape::Shape::of_command(&s.command))
            .collect();
        let picked = shape::pick_novel(&candidates, &seeds, n);
        // In the greedy order, which is "most novel first": a reviewer who
        // stops halfway has still labelled the half that was worth most.
        let mut held: Vec<Option<backtest::Sample>> =
            report.samples[i].drain(..).map(Some).collect();
        report.samples[i] = picked.iter().filter_map(|&j| held[j].take()).collect();
    }
}

/// `harness-review`: the ADR-0042 review table, or with `--check` the one line
/// that says a model has not been reviewed yet.
fn run_harness_review(args: &[OsString]) -> ExitCode {
    if args.iter().any(|a| a == "--help" || a == "-h") {
        println!(concat!("usage: ", greenbelay_guard::bin!(), " harness-review [--json] [--check] [--model <id>] [--transcripts <dir>] [--since <date>] [--out <dir>]"));
        return ExitCode::SUCCESS;
    }
    let f = match flags(args) {
        Ok(f) => f,
        Err(why) => {
            eprintln!("{BIN}: {why}");
            return ExitCode::from(2);
        }
    };
    if let Some(operand) = f.rest.first() {
        eprintln!("{BIN}: harness-review takes no operand, got `{operand}`");
        return ExitCode::from(2);
    }
    let Some(journal_dir) = journal::dir() else {
        eprintln!(concat!(
            greenbelay_guard::bin!(),
            ": no home directory, so no journal directory"
        ));
        return ExitCode::from(2);
    };
    let roots = match transcript::roots(&f.transcripts) {
        Ok(r) => r,
        Err(e) => {
            eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
            return ExitCode::from(2);
        }
    };
    let scan = transcript::Scan {
        roots: &roots,
        tool: "Bash",
        since: f.since,
    };
    let out = f
        .out
        .clone()
        .unwrap_or_else(|| harness_review::reviews_dir(&journal_dir));
    if f.check {
        return match harness_review::check(&out, &scan) {
            Ok(None) => ExitCode::SUCCESS,
            Ok(Some(line)) => {
                println!("{line}");
                ExitCode::FAILURE
            }
            Err(e) => {
                eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
                ExitCode::from(2)
            }
        };
    }
    let today = match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
        Ok(d) => day_of_seconds(d.as_secs()),
        Err(e) => {
            eprintln!("{BIN}: cannot read the clock: {e}");
            return ExitCode::from(2);
        }
    };
    let table: Vec<&'static rules::Rule> = rule_table::RULES.iter().collect();
    let review = match harness_review::review(
        &scan,
        &table,
        stance_of_part,
        &journal::paths(),
        today,
        f.model.as_deref(),
    ) {
        Ok(r) => r,
        Err(e) => {
            eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
            return ExitCode::from(2);
        }
    };
    if let Err(e) = harness_review::write(&out, &review) {
        eprintln!("{BIN}: could not write the review file: {e}");
        return ExitCode::from(2);
    }
    if f.json {
        println!("{}", review.to_json());
    } else {
        print!("{}", review.render());
    }
    ExitCode::SUCCESS
}

fn stance_of_part(part: &backtest::Subject) -> rules::Stance {
    match part {
        backtest::Subject::Rule(r) => stance::resolve(r),
        backtest::Subject::Assertion(a) => stance::resolve_assertion(a),
    }
}

fn run_compliance(
    f: &Flags,
    roots: &transcript::Roots,
    scan: &transcript::Scan,
    chosen: &[backtest::Subject],
) -> ExitCode {
    // Assertions check what a command that already ran actually did, so
    // "what did the model do next" is a different question with a different
    // answer. Named rather than silently dropped.
    let rules: Vec<&'static rules::Rule> = chosen
        .iter()
        .filter_map(|s| match s {
            backtest::Subject::Rule(r) => Some(*r),
            backtest::Subject::Assertion(_) => None,
        })
        .collect();
    if rules.is_empty() {
        eprintln!(concat!(
            greenbelay_guard::bin!(),
            ": --compliance is about rules, and none were selected"
        ));
        return ExitCode::from(2);
    }
    let options = compliance::Options {
        window: f.window.unwrap_or(compliance::Options::default().window),
    };
    match compliance::run(scan, &rules, options) {
        Ok(report) => {
            if f.json {
                println!("{}", report.to_json(roots));
            } else {
                print!("{}", report.render(roots));
            }
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
            ExitCode::from(2)
        }
    }
}

const OUTPUT_AUDIT_USAGE: &str = concat!(
    "\
usage: ",
    greenbelay_guard::bin!(),
    " output-audit --since <UTC> --until <UTC>
                                [--transcripts <dir>]... [--json]

Where tool output went: the bytes tool results put into session context in
the window [since, until), by kind of call (ci-log-failed, ci-log,
ci-status, check, check-quiet, check-git-hook, git, shell, read, search,
edit, agent, lsp, web, mcp, other-tool, unmatched), apart from subagents,
beside the token usage the transcripts report, by model. Bash results are
also broken down by command family (the program, plus the subcommand for
git, gh, kubectl, cargo, npm, pnpm, docker, brew, greenbelay, greengate,
relais and amont), for the main conversation and for subagents. Bash file
dumps (`cat`, `sed -n`, `head`, `tail`, read as `whole-file-dump` reads
them) are broken down by class: one or many whole files, one or many
windows, or mixed, marked `(mixed output)` when another clause also prints,
with the results over 8 KiB, those with long lines (average over 400 B),
those the Read tool would have cut (over 2,000 B) and the hook refusals.
(`long`, `cuts` and `refus` head the text table; `persisted`, the results too
large to return, is reported in --json only.)

Each result, each agent launch and each message counts once, however many
times a resumed session copies it. `over 200 B` is the share of passing
results beyond 200 bytes each: what a one-line quiet summary would not
carry, a proxy, not a measure. Usage is what the transcripts report: not
billing and not quota. The output carries counts only, no command or
result text beyond program names.

  --since, --until  UTC instants, YYYY-MM-DDTHH:MM:SS[.fff]Z
  --transcripts     a transcript root (repeatable; default: the Claude
                    config directory's projects/)
  --json            the aggregate as JSON, exact integers

Exit 0, also when some files could not be read (the coverage line and the
JSON `coverage.complete` say so); 1 when the transcripts cannot be found;
2 on a usage error.
"
);

const SIZE_EVIDENCE_USAGE: &str = "usage: greenbelay size-evidence [--days <n>] [--relay-dir <dir>]

The size kind of clear-at-boundary (ADR-0083): its decisions past the size,
read from <data dir>/size-evidence/ (kept 30 days, apart from the journal),
with each handoff request paired to a clear-relay `submit` of the same
session within 2 h.

  --days <n>         the window, in days back from now (default 7)
  --relay-dir <dir>  the clear-relay logs (default: the plugin's default
                     stateDir, <state dir>/greenbelay/clear-relay)

A request is unheeded when no submit followed, also when the relay never
armed and wrote no log; evidence is missing only when the relay directory
or a session's log cannot be read. Exit 0; 1 when there is no data
directory; 2 on a usage error.
";

/// `size-evidence [--days <n>] [--relay-dir <dir>]`: the size kind's
/// decisions, read from its own day files, with each handoff request paired
/// to a clear-relay submit.
fn run_size_evidence(args: &[OsString]) -> ExitCode {
    use greenbelay_process::size_evidence;
    let args: Vec<String> = args
        .iter()
        .map(|a| a.to_string_lossy().into_owned())
        .collect();
    if args.iter().any(|a| a == "--help" || a == "-h") {
        print!("{SIZE_EVIDENCE_USAGE}");
        return ExitCode::SUCCESS;
    }
    let usage = |why: &str| {
        eprintln!("{BIN}: size-evidence: {why}; try `{BIN} size-evidence --help`");
        ExitCode::from(2)
    };
    let mut days = 7;
    let mut relay_dir = size_evidence::relay_dir();
    let mut words = args.iter();
    while let Some(word) = words.next() {
        let (flag, attached) = match word.split_once('=') {
            Some((flag, value)) if flag.starts_with("--") => (flag, Some(value.to_string())),
            Some(_) | None => (word.as_str(), None),
        };
        if !matches!(flag, "--days" | "--relay-dir") {
            return usage(&format!("unexpected argument `{word}`"));
        }
        let Some(setting) = attached.or_else(|| words.next().cloned()) else {
            return usage(&format!("{flag} needs a value"));
        };
        if flag == "--relay-dir" {
            relay_dir = Some(std::path::PathBuf::from(setting));
            continue;
        }
        match setting.parse::<u64>() {
            Ok(n) if n > 0 => days = n,
            _ => return usage("--days needs a whole number of days above 0"),
        }
    }
    let (Some(evidence_dir), Some(relay_dir)) = (size_evidence::dir(), relay_dir) else {
        eprintln!(
            "{BIN}: size-evidence: no data or state directory (set HOME, or pass --relay-dir)"
        );
        return ExitCode::from(1);
    };
    let since = size_evidence::since(size_evidence::now_ms(), days);
    let report = size_evidence::report_in(&evidence_dir, &relay_dir, since);
    print!("{}", report.render(days));
    ExitCode::SUCCESS
}

const SIZE_REPLAY_USAGE: &str =
    "usage: greenbelay size-replay [--transcripts <dir>] [--since <YYYY-MM-DD>]

Replays the size kind of clear-at-boundary (ADR-0083) at deny over the
transcripts under <dir> (default: <Claude config dir>/projects), from the
day given (default: all), and prints whether its bar is met: at least one
fire a day, at most 10% of fires held wrongly (a background task launched
before the fire was still running).

Exit 0 whether or not the bar is met (the first line says); 1 when the
transcripts directory is missing; 2 on a usage error.
";

/// `size-replay [--transcripts <dir>] [--since <YYYY-MM-DD>]`.
fn run_size_replay(args: &[OsString]) -> ExitCode {
    let args: Vec<String> = args
        .iter()
        .map(|a| a.to_string_lossy().into_owned())
        .collect();
    if args.iter().any(|a| a == "--help" || a == "-h") {
        print!("{SIZE_REPLAY_USAGE}");
        return ExitCode::SUCCESS;
    }
    let usage = |why: &str| {
        eprintln!("{BIN}: size-replay: {why}; try `{BIN} size-replay --help`");
        ExitCode::from(2)
    };
    let mut root = greenbelay_guard::settings::config_dir().map(|dir| dir.join("projects"));
    let mut since = String::from("0000-00-00");
    let mut words = args.iter();
    while let Some(word) = words.next() {
        let (flag, attached) = match word.split_once('=') {
            Some((flag, value)) if flag.starts_with("--") => (flag, Some(value.to_string())),
            Some(_) | None => (word.as_str(), None),
        };
        if !matches!(flag, "--transcripts" | "--since") {
            return usage(&format!("unexpected argument `{word}`"));
        }
        let Some(setting) = attached.or_else(|| words.next().cloned()) else {
            return usage(&format!("{flag} needs a value"));
        };
        if flag == "--transcripts" {
            root = Some(std::path::PathBuf::from(setting));
        } else if greenbelay_guard::civil::day_of(&format!("{setting}T00:00:00Z")).is_some() {
            since = setting;
        } else {
            return usage(&format!(
                "--since needs a day as YYYY-MM-DD, not `{setting}`"
            ));
        }
    }
    let Some(root) = root else {
        eprintln!("{BIN}: size-replay: no Claude config directory; pass --transcripts <dir>");
        return ExitCode::from(1);
    };
    if !root.is_dir() {
        eprintln!(
            "{BIN}: size-replay: no transcripts directory at {}; pass --transcripts <dir>",
            root.display()
        );
        return ExitCode::from(1);
    }
    print!(
        "{}",
        greenbelay_process::size_replay::replay(&root, &since).render()
    );
    ExitCode::SUCCESS
}

fn run_output_audit(args: &[OsString]) -> ExitCode {
    use greenbelay_guard::output_audit::{self, Instant, Window};
    let args: Vec<String> = args
        .iter()
        .map(|a| a.to_string_lossy().into_owned())
        .collect();
    if args.iter().any(|a| a == "--help" || a == "-h") {
        print!("{OUTPUT_AUDIT_USAGE}");
        return ExitCode::SUCCESS;
    }
    let usage = |why: &str| {
        eprintln!("{BIN}: output-audit: {why}; try `{BIN} output-audit --help`");
        ExitCode::from(2)
    };
    let (mut since, mut until, mut roots, mut as_json) = (None, None, Vec::new(), false);
    let mut words = args.iter();
    while let Some(word) = words.next() {
        if word == "--" {
            // No operands: anything after `--` is a usage error.
            if let Some(operand) = words.next() {
                return usage(&format!("unexpected operand `{operand}`"));
            }
            break;
        }
        let (flag, attached) = match word.split_once('=') {
            Some((flag, value)) if flag.starts_with("--") => (flag, Some(value.to_string())),
            Some(_) | None => (word.as_str(), None),
        };
        if flag == "--json" {
            if attached.is_some() {
                return usage("--json takes no value");
            }
            as_json = true;
            continue;
        }
        if !matches!(flag, "--since" | "--until" | "--transcripts") {
            return usage(&format!("unknown argument `{word}`"));
        }
        let Some(value) = attached.or_else(|| words.next().cloned()) else {
            return usage(&format!("{flag} needs a value"));
        };
        if flag == "--transcripts" {
            roots.push(std::path::PathBuf::from(value));
            continue;
        }
        let Some(at) = Instant::parse(&value) else {
            return usage(&format!(
                "{flag} takes a UTC instant like 2026-11-06T10:03:38Z, not `{value}`"
            ));
        };
        if flag == "--since" {
            since = Some(at);
        } else {
            until = Some(at);
        }
    }
    let (Some(since), Some(until)) = (since, until) else {
        return usage("--since and --until are both required");
    };
    if since >= until {
        return usage("--since must be before --until");
    }
    let roots = match transcript::roots(&roots) {
        Ok(r) => r,
        Err(e) => {
            eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
            return ExitCode::from(1);
        }
    };
    let window = Window { since, until };
    let audit = output_audit::audit(&roots, &window);
    if as_json {
        println!("{}", audit.to_json(&window));
    } else {
        print!("{}", output_audit_text(&audit, &window));
    }
    ExitCode::SUCCESS
}

/// A count a person reads at a glance: 812, 4.5K, 27.4M, 12.3G.
fn scaled(count: u64) -> String {
    let units = [(1e9, "G"), (1e6, "M"), (1e3, "K")];
    let amount = count as f64;
    // The largest unit whose value rounds to 1.0 or more: 999,950 is 1.0M,
    // never 1000.0K.
    units
        .iter()
        .find(|(size, _)| (amount / size * 10.0).round() >= 10.0)
        .map_or_else(
            || count.to_string(),
            |(size, unit)| format!("{:.1}{unit}", amount / size),
        )
}

/// One context's Bash dumps by class: how many results passed 8 KiB, how
/// many of those had long lines, and how many Read would have cut.
fn dumps_text(
    title: &str,
    map: &std::collections::BTreeMap<
        greenbelay_guard::output_audit::DumpClass,
        greenbelay_guard::output_audit::DumpBucket,
    >,
) -> String {
    let mut out = format!("\n{title}, Bash file dumps by class\n");
    if map.is_empty() {
        out.push_str("  none\n");
        return out;
    }
    out.push_str(&format!(
        "  {:<26} {:>5} {:>6} {:>9} {:>9} {:>9} {:>5}\n",
        "class", "calls", "bytes", ">8KiB", "long", "cuts", "refus"
    ));
    let pair = |calls: u64, bytes: u64| format!("{calls}/{}", scaled(bytes));
    for (class, bucket) in map {
        out.push_str(&format!(
            "  {:<26} {:>5} {:>6} {:>9} {:>9} {:>9} {:>5}\n",
            class.to_string(),
            bucket.calls,
            scaled(bucket.result_bytes),
            pair(bucket.large, bucket.large_bytes),
            pair(bucket.long_lines, bucket.long_lines_bytes),
            pair(bucket.cut_by_read, bucket.cut_by_read_bytes),
            bucket.refused
        ));
    }
    out
}

/// The top families of one context by result bytes, then the rest summed.
fn families_text(
    title: &str,
    map: &std::collections::BTreeMap<String, greenbelay_guard::output_audit::Bucket>,
) -> String {
    const SHOWN: usize = 15;
    let total: u64 = map.values().map(|b| b.result_bytes).sum();
    let mut out = format!("\n{title}, Bash by command family\n");
    if map.is_empty() {
        out.push_str("  none\n");
        return out;
    }
    let share = |bytes: u64| {
        if total == 0 {
            0.0
        } else {
            100.0 * bytes as f64 / total as f64
        }
    };
    out.push_str(&format!(
        "  {:<26} {:>7} {:>8} {:>6}\n",
        "family", "calls", "bytes", "share"
    ));
    let mut rows: Vec<_> = map.iter().collect();
    rows.sort_by(|a, b| b.1.result_bytes.cmp(&a.1.result_bytes).then(a.0.cmp(b.0)));
    for (family, b) in rows.iter().take(SHOWN) {
        out.push_str(&format!(
            "  {:<26} {:>7} {:>8} {:>5.1}%\n",
            family,
            b.calls,
            scaled(b.result_bytes),
            share(b.result_bytes)
        ));
    }
    if rows.len() > SHOWN {
        let (calls, bytes) = rows[SHOWN..]
            .iter()
            .fold((0, 0), |(c, y), (_, b)| (c + b.calls, y + b.result_bytes));
        out.push_str(&format!(
            "  {:<26} {:>7} {:>8} {:>5.1}%\n",
            "other families",
            calls,
            scaled(bytes),
            share(bytes)
        ));
    }
    out
}

/// The aggregate as tables under 80 columns, largest result bytes first;
/// exact integers are in `--json`.
fn output_audit_text(
    audit: &greenbelay_guard::output_audit::Audit,
    window: &greenbelay_guard::output_audit::Window,
) -> String {
    let mut out = format!(
        "window {} .. {} (until excluded)\n{} sessions, {} agent launches\n",
        window.since.as_str(),
        window.until.as_str(),
        audit.sessions,
        audit.agent_launches
    );
    for (title, map) in [
        ("main conversation", &audit.main),
        ("subagents", &audit.sidechain),
    ] {
        let total: u64 = map.values().map(|b| b.result_bytes).sum();
        out.push_str(&format!("\n{title}: {}B of tool output\n", scaled(total)));
        if map.is_empty() {
            out.push_str("  none\n");
            continue;
        }
        out.push_str(&format!(
            "  {:<15} {:>7} {:>7} {:>8} {:>6} {:>10}\n",
            "kind", "calls", "failed", "bytes", "share", "over 200 B"
        ));
        let mut rows: Vec<_> = map.iter().collect();
        rows.sort_by(|a, b| b.1.result_bytes.cmp(&a.1.result_bytes));
        for (kind, b) in rows {
            let share = if total == 0 {
                0.0
            } else {
                100.0 * b.result_bytes as f64 / total as f64
            };
            out.push_str(&format!(
                "  {:<15} {:>7} {:>7} {:>8} {:>5.1}% {:>10}\n",
                kind.as_str(),
                b.calls,
                b.failed,
                scaled(b.result_bytes),
                share,
                scaled(b.over_summary)
            ));
        }
    }
    for (title, map) in [
        ("main conversation", &audit.main_families),
        ("subagents", &audit.sidechain_families),
    ] {
        out.push_str(&families_text(title, map));
    }
    for (title, map) in [
        ("main conversation", &audit.main_dumps),
        ("subagents", &audit.sidechain_dumps),
    ] {
        out.push_str(&dumps_text(title, map));
    }
    out.push_str("\nreported usage by model, tokens (not billing, not quota)\n");
    if audit.usage.is_empty() {
        out.push_str("  none\n");
    } else {
        out.push_str(&format!(
            "  {:<22} {:>8} {:>8} {:>9} {:>9} {:>8}\n",
            "model", "messages", "input", "cache wr", "cache rd", "output"
        ));
        for (model, u) in &audit.usage {
            out.push_str(&format!(
                "  {:<22} {:>8} {:>8} {:>9} {:>9} {:>8}\n",
                model.chars().take(22).collect::<String>(),
                u.messages,
                scaled(u.input),
                scaled(u.cache_creation),
                scaled(u.cache_read),
                scaled(u.output)
            ));
        }
    }
    let coverage = &audit.coverage;
    let mut lost = Vec::new();
    for (count, one, many) in [
        (
            coverage.files_unreadable,
            "unreadable file",
            "unreadable files",
        ),
        (
            coverage.files_truncated,
            "file cut short by a read error",
            "files cut short by a read error",
        ),
        (coverage.bad_lines, "unparsable line", "unparsable lines"),
        (
            coverage.oversized_lines,
            "oversized line",
            "oversized lines",
        ),
    ] {
        if count > 0 {
            lost.push(format!("{count} {}", if count == 1 { one } else { many }));
        }
    }
    out.push_str(&format!(
        "\ncoverage: {} {} read ({} older skipped)",
        coverage.files_scanned,
        if coverage.files_scanned == 1 {
            "file"
        } else {
            "files"
        },
        coverage.files_skipped
    ));
    if lost.is_empty() {
        out.push_str(", every line read\n");
    } else {
        out.push_str("; not counted:\n");
        for problem in lost {
            out.push_str(&format!("  {problem}\n"));
        }
    }
    out
}

fn run_mine(args: &[OsString]) -> ExitCode {
    let f = match flags(args) {
        Ok(f) => f,
        Err(why) => {
            eprintln!("{BIN}: {why}");
            return ExitCode::from(2);
        }
    };
    if !f.only.is_empty() {
        eprintln!(concat!(
            greenbelay_guard::bin!(),
            ": mine looks for what no rule names yet, so --rule means nothing"
        ));
        return ExitCode::from(2);
    }
    let as_cases = f.format.as_deref() == Some("cases");
    if let Some(other) = f.format.as_deref() {
        if other != "cases" {
            eprintln!("{BIN}: --format takes `cases`, not `{other}`");
            return ExitCode::from(2);
        }
    }
    let roots = match transcript::roots(&f.transcripts) {
        Ok(r) => r,
        Err(e) => {
            eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
            return ExitCode::from(2);
        }
    };
    let scan = transcript::Scan {
        roots: &roots,
        tool: "Bash",
        since: f.since,
    };
    let default = mine::Options::default();
    let options = mine::Options {
        window: f.window.unwrap_or(default.window),
        min_support: f.min_support.unwrap_or(default.min_support),
        min_rate: f.min_rate.unwrap_or(default.min_rate),
        samples: f.sample.unwrap_or(default.samples),
    };
    match mine::run(&scan, options, rule_table::RULES) {
        Ok(report) => {
            if as_cases {
                // The same file `explain --format cases` writes, and the same
                // one `corpus check` reads — so a shape mined today is a
                // reviewable case today, before anybody has written the rule
                // it might become.
                println!("{}", corpus::HEADER);
                let mut seen = std::collections::BTreeSet::new();
                for command in report.sample_commands() {
                    if seen.insert(command.to_string()) {
                        print!("{}", corpus::line_for(corpus::Verdict::Unreviewed, command));
                    }
                }
            } else if f.json {
                println!("{}", report.to_json(&roots));
            } else {
                print!("{}", report.render(&roots));
            }
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
            ExitCode::from(2)
        }
    }
}

/// The analysis of one command as JSON: what `tools/shell-oracle` checks
/// against bash and zsh actually running it. Counts are per contribution,
/// never aggregated — aggregation is policy.
fn run_analyze(args: &[OsString]) -> ExitCode {
    let f = match flags(args) {
        Ok(f) => f,
        Err(why) => {
            eprintln!("{BIN}: {why}");
            return ExitCode::from(2);
        }
    };
    if f.rest.len() != 1 {
        eprintln!(concat!(
            greenbelay_guard::bin!(),
            ": analyze needs exactly one command, quoted"
        ));
        return ExitCode::from(2);
    }
    let src = &f.rest[0];
    let dialect = f.dialect.unwrap_or(rules::Dialect::Unknown);
    let a = analysis::analyze(src, dialect);
    let upper = |u: analysis::domain::Upper| match u {
        analysis::domain::Upper::Finite(n) => serde_json::json!(n),
        analysis::domain::Upper::Saturated => serde_json::json!("saturated"),
        analysis::domain::Upper::Uncapped(_) => serde_json::json!("uncapped"),
        analysis::domain::Upper::Unknown => serde_json::json!("unknown"),
    };
    let contributions: Vec<serde_json::Value> = a
        .effects
        .contributions
        .iter()
        .map(|c| {
            serde_json::json!({
                "program": c.program,
                "span": [c.span.start, c.span.end],
                "hosts": c.targets.hosts,
                "unresolved": !c.targets.unresolved.is_empty(),
                "local": c.targets.local,
                "lower": c.transfers.lower,
                "upper": upper(c.transfers.upper),
                "paced": c.paced.map(|p| p.secs),
            })
        })
        .collect();
    let out = serde_json::json!({
        "dialect": dialect.as_str(),
        "parsed": analysis::frontend::parse(src).is_ok(),
        "incomplete": a.incomplete.as_ref().map(|i| i.why),
        "unknown": a.effects.unknown.len(),
        "contributions": contributions,
    });
    println!("{out}");
    ExitCode::SUCCESS
}

const PLAN_SHA_USAGE: &str = concat!(
    "\
usage: ",
    greenbelay_guard::bin!(),
    " plan-sha [--short] [--block [--lang <language>] [--slice <role>]] [--legacy] [--] <file|->

The sha256 of what a plan says, which its review binds to (ADR-0022,
work.plan-review-panel). The plan is read without its YAML front matter,
its `## Review panel` section, its `## Full reviews` section and its
machine comment (`<!-- panel: ... -->` on the last line), so writing review
results into it never changes the sha. The rest is read as CommonMark:

  counts         every word, number and operator; code blocks and code
                 spans exactly as written; link destinations; the kind of
                 each block (list item, quote, heading, table cell, an
                 ordered list's start)
  does not count blank lines, line wrapping, indentation outside code,
                 table padding, list-marker style (`*`/`-`), emphasis
                 style (`*x*`/`_x_`), escapes (`\\_`), CRLF

So a formatter such as prettier keeps the sha, unless it rewrites code.

  --short            the first 12 hex characters, for the machine comment
  --block            the review block a plan-review-* agent's prompt carries:
                     <<<PLAN path=<realpath> sha=<64 hex>>>>
  --lang <language>  with --block, for plan-review-language: adds lang=<l>
  --slice <role>     with --block, for a seat bound to its slice of the plan
                     (ADR-0061 work.review-slices): adds slice=<64 hex> and
                     prints a second line naming the phases of the slice.
                     A seat of a file type (lang:<x>, react, ui-design,
                     platform) on a plan whose every phase names a file has
                     a slice; on any other plan it gets the plain block, and
                     stderr says it binds the whole body. --slice lang:<x>
                     implies --lang <x>
                     (--lang=<l> and --slice=<role> work too)
  --legacy           the byte sha from before 2.25, to check a plan whose
                     machine comment was written then; temporary, removed
                     after the transition (not with --block)
  -                  read the plan from stdin (not with --block, which
                     needs the file's path)

Prints one line on stdout, or two with --slice. Exit 0, 1 when the file
cannot be read or its sha cannot be computed (the reason on stderr), 2 on a
usage error.
"
);

/// The `--slice <role>` checks that need no plan: a known role whose file
/// types the table knows, agreeing with `--lang`. Returns the `--lang` the
/// block carries: `--slice lang:<x>` implies `--lang <x>`.
fn slice_lang(role: &str, lang: Option<&str>) -> Result<Option<String>, String> {
    if plan_review::remit(role).is_empty() {
        return Err(format!(
            "unknown role {role}; roles: {}, lang:<language>",
            plan_review::NAMED_ROLES.join(", ")
        ));
    }
    if greenbelay_process::file_types::profile_reads(role).is_none() {
        return Err(format!("{role} binds the whole body; drop --slice"));
    }
    match (role.strip_prefix("lang:"), lang) {
        (Some(want), Some(have)) if have != want => Err(format!(
            "--slice {role} conflicts with --lang {have}; pass --lang {want} or drop --lang"
        )),
        (Some(want), None) => Ok(Some(want.to_string())),
        (_, have) => Ok(have.map(str::to_string)),
    }
}

fn run_plan_sha(args: &[OsString]) -> ExitCode {
    let args: Vec<String> = args
        .iter()
        .map(|a| a.to_string_lossy().into_owned())
        .collect();
    let (mut short, mut block, mut lang, mut file) = (false, false, None, None);
    let mut legacy = false;
    let mut slice: Option<String> = None;
    // Help wins over every other flag, as in plan-panel.
    if args
        .iter()
        .take_while(|a| a.as_str() != "--")
        .any(|a| a == "--help" || a == "-h")
    {
        print!("{PLAN_SHA_USAGE}");
        return ExitCode::SUCCESS;
    }
    let mut i = 0;
    let mut operands_only = false;
    while i < args.len() {
        let a = args[i].as_str();
        // `--lang=x` and `--slice=x` are the GNU spellings of the two-word ones.
        if let Some((flag, value)) = a
            .split_once('=')
            .filter(|(f, _)| !operands_only && (*f == "--lang" || *f == "--slice"))
        {
            if value.is_empty() {
                eprintln!("{BIN}: {flag} needs a value");
                return ExitCode::from(2);
            }
            if flag == "--lang" {
                lang = Some(value.to_string());
            } else {
                slice = Some(value.to_string());
            }
            i += 1;
            continue;
        }
        match a {
            _ if operands_only || a == "-" || !a.starts_with('-') => {
                if file.is_some() {
                    eprintln!(concat!(
                        greenbelay_guard::bin!(),
                        ": plan-sha takes one file; try `",
                        greenbelay_guard::bin!(),
                        " plan-sha --help`"
                    ));
                    return ExitCode::from(2);
                }
                file = Some(a.to_string());
            }
            "--" => operands_only = true,
            "--help" | "-h" => {
                print!("{PLAN_SHA_USAGE}");
                return ExitCode::SUCCESS;
            }
            "--short" => short = true,
            "--block" => block = true,
            "--legacy" => legacy = true,
            "--lang" => {
                i += 1;
                match args.get(i) {
                    Some(v) => lang = Some(v.clone()),
                    None => {
                        eprintln!(concat!(greenbelay_guard::bin!(), ": --lang needs a value"));
                        return ExitCode::from(2);
                    }
                }
            }
            "--slice" => {
                i += 1;
                match args.get(i) {
                    Some(v) if !v.starts_with('-') => slice = Some(v.clone()),
                    _ => {
                        eprintln!(concat!(greenbelay_guard::bin!(), ": --slice needs a value"));
                        return ExitCode::from(2);
                    }
                }
            }
            other => {
                eprintln!("{BIN}: unknown flag `{other}`; try `{BIN} plan-sha --help`");
                return ExitCode::from(2);
            }
        }
        i += 1;
    }
    let Some(file) = file else {
        eprint!("{BIN}: plan-sha needs a file, or - for stdin\n\n{PLAN_SHA_USAGE}");
        return ExitCode::from(2);
    };
    let conflict = if short && block {
        Some("--short and --block exclude each other")
    } else if lang.is_some() && !block {
        Some("--lang only goes with --block")
    } else if block && file == "-" {
        Some("--block needs the plan's file, not stdin")
    } else if block && legacy {
        Some("--legacy only prints a sha; drop --block")
    } else if slice.is_some() && !block {
        Some(concat!(
            "--slice needs --block: ",
            greenbelay_guard::bin!(),
            " plan-sha --block --slice <role> <plan.md>"
        ))
    } else {
        None
    };
    if let Some(why) = conflict {
        eprintln!("{BIN}: {why}; try `{BIN} plan-sha --help`");
        return ExitCode::from(2);
    }
    if let Some(role) = slice.as_deref() {
        match slice_lang(role, lang.as_deref()) {
            Ok(l) => lang = l,
            Err(why) => {
                eprintln!("{BIN}: {why}; try `{BIN} plan-sha --help`");
                return ExitCode::from(2);
            }
        }
    }
    let text = if file == "-" {
        use std::io::Read;
        let mut t = String::new();
        if let Err(e) = std::io::stdin().read_to_string(&mut t) {
            eprintln!("{BIN}: cannot read stdin: {e}");
            return ExitCode::from(1);
        }
        t
    } else {
        match std::fs::read_to_string(&file) {
            Ok(t) => t,
            Err(e) => {
                eprintln!("{BIN}: cannot read {file}: {e}");
                return ExitCode::from(1);
            }
        }
    };
    let sha = if legacy {
        eprintln!(concat!(
            greenbelay_guard::bin!(),
            ": --legacy is removed after the transition"
        ));
        plan_text::legacy_sha(&text)
    } else {
        match plan_text::shas(&text) {
            Ok(s) => s.sha,
            Err(why) => {
                eprintln!("{BIN}: {why}");
                return ExitCode::from(1);
            }
        }
    };
    greenbelay_process::plan_id::remember_live(&text);
    if block {
        let path = plan_review::real(std::path::Path::new(&file));
        let cut = match slice.as_deref() {
            None => None,
            Some(role) => match plan_review::slice_for(&text, role) {
                Ok(s) => Some((role, s)),
                Err(why) => {
                    eprintln!("{BIN}: {why}");
                    return ExitCode::from(1);
                }
            },
        };
        let slice_sha = match &cut {
            Some((_, plan_review::SliceFor::Slice(s))) => Some(s.sha.as_str()),
            _ => None,
        };
        println!(
            "{}",
            plan_review::block(&path, &sha, lang.as_deref(), slice_sha)
        );
        match &cut {
            Some((_, plan_review::SliceFor::Slice(s))) => println!(
                "Your slice: {} and the shared sections. The other phases belong to other seats: read them only to follow yours, and raise a finding there only if it blocks.",
                s.kept.join(", ")
            ),
            Some((role, plan_review::SliceFor::WholeBody(why))) => {
                eprintln!("{BIN}: {role} binds the whole body ({})", why.as_str());
            }
            None => {}
        }
    } else if short {
        println!("{}", &sha[..12]);
    } else {
        println!("{sha}");
    }
    ExitCode::SUCCESS
}

const BLOCK_USAGE: &str = concat!(
    "\
usage: ",
    greenbelay_guard::bin!(),
    " block sha [-C <dir>] [--base <ref>]
       ",
    greenbelay_guard::bin!(),
    " block list [--json]
       ",
    greenbelay_guard::bin!(),
    " block revoke <fp> --because <text>
       ",
    greenbelay_guard::bin!(),
    " block reinstate <fp>

The fingerprint of a branch's change, which a copy of a reviewed block
shares with its source: the sha256 of the `+` and `-` lines of `git diff`
from the merge base to HEAD (docs/plans/ left out), without paths, line
numbers or context, the common indentation removed, and CR and trailing
blanks stripped. git runs with its own settings, not the person's.

  sha          print `<64 hex>` TAB `fp:<12 hex>` on stdout
  -C <dir>     the repository at <dir> (default: the current one)
  --base <ref> the ref to take the merge base with (default: the default
               branch of origin)

Exit codes of `sha`: 0; 1 when there is no fingerprint (a binary file in
the diff, which is never a copy, or git failing; the reason on stderr); 2 on
a usage error.

  list         one row per registered block, no header, on stdout:
               fp:<12 hex> TAB active|revoked TAB <roles, comma-separated>
               TAB <copy count> TAB <source repo, - when unknown>; --json
               adds the copies and `source_repo` (null when unknown)
  revoke       revoke a block until the person reinstates it: the pilot is
               printed as <source repo> TAB <branch> TAB - and every
               recorded copy as <repo> TAB <branch> TAB <commit> for a
               re-check; revoking again prints them again
  reinstate    lift a revocation, on stderr; the person runs it, not an agent
  <fp>         fp:<12 hex>, a unique prefix of it, or the 64 hex

Exit codes of `list`, `revoke` and `reinstate`: 0; 1 when the fingerprint
names no block or several (`give more hex`), the registry cannot be found or
written; 2 on a usage error.
"
);

/// How long finding the default branch, and then the diff, may each take.
const BLOCK_GIT_BUDGET: std::time::Duration = std::time::Duration::from_secs(20);

fn run_block(args: &[OsString]) -> ExitCode {
    let args: Vec<String> = args
        .iter()
        .map(|a| a.to_string_lossy().into_owned())
        .collect();
    match args.first().map(String::as_str) {
        Some("--help" | "-h") => block_help(),
        Some("sha") => run_block_sha(&args[1..]),
        Some("list") => run_block_list(&args[1..]),
        Some("revoke") => run_block_revoke(&args[1..]),
        Some("reinstate") => run_block_reinstate(&args[1..]),
        Some(_) if args.iter().any(|word| is_help(word)) => block_help(),
        Some(other) => {
            eprintln!("{BIN}: block: unknown verb `{other}`; try `{BIN} block --help`");
            eprint!("{BLOCK_USAGE}");
            ExitCode::from(2)
        }
        None => {
            eprintln!(concat!(
                greenbelay_guard::bin!(),
                ": block: needs a verb; try `",
                greenbelay_guard::bin!(),
                " block --help`"
            ));
            eprint!("{BLOCK_USAGE}");
            ExitCode::from(2)
        }
    }
}

fn is_help(word: &str) -> bool {
    word == "--help" || word == "-h"
}

fn block_help() -> ExitCode {
    print!("{BLOCK_USAGE}");
    ExitCode::SUCCESS
}

/// The registry's base directory: the journal directory.
fn block_base() -> Option<std::path::PathBuf> {
    let base = journal::dir();
    if base.is_none() {
        eprintln!(concat!(
            greenbelay_guard::bin!(),
            ": block: no home or CLAUDE_CONFIG_DIR to find the registry in"
        ));
    }
    base
}

/// The one registered fingerprint `given` names (`fp:<hex>`, a hex prefix or
/// all 64 hex). Anything else is matched against the registry's own listing
/// and never joins a path.
fn resolve_block_fp(base: &std::path::Path, given: &str) -> Result<String, ExitCode> {
    let id = given.strip_prefix("fp:").unwrap_or(given);
    let mut hits: Vec<String> = Vec::new();
    if !id.is_empty() {
        hits = block_registry::fingerprints(base)
            .into_iter()
            .filter(|fingerprint| fingerprint.starts_with(id))
            .collect();
    }
    match hits.pop() {
        Some(only) if hits.is_empty() => Ok(only),
        Some(_) => {
            eprintln!(
                "{BIN}: block: fp:{id} matches {} blocks; give more hex",
                hits.len() + 1
            );
            Err(ExitCode::from(1))
        }
        None => {
            eprintln!("{BIN}: block: no entry fp:{id}; see {BIN} block list");
            Err(ExitCode::from(1))
        }
    }
}

fn block_usage_error(why: &str) -> ExitCode {
    eprintln!("{BIN}: block: {why}; try `{BIN} block --help`");
    ExitCode::from(2)
}

fn run_block_list(args: &[String]) -> ExitCode {
    let mut json = false;
    for word in args {
        match word.as_str() {
            help if is_help(help) => return block_help(),
            "--json" => json = true,
            other => return block_usage_error(&format!("unknown argument `{other}`")),
        }
    }
    let Some(base) = block_base() else {
        return ExitCode::from(1);
    };
    let mut rows = Vec::new();
    for fingerprint in block_registry::fingerprints(&base) {
        let mut roles: Vec<String> = block_registry::entries(&base, &fingerprint)
            .into_iter()
            .flat_map(|entry| entry.registered.roles)
            .collect();
        roles.sort();
        roles.dedup();
        let copies = block_registry::copies(&base, &fingerprint);
        let revoked = block_registry::revoked(&base, &fingerprint);
        let source = block_registry::source_entry(&base, &fingerprint)
            .and_then(|entry| entry.registered.source_repo);
        let short = format!("fp:{}", &fingerprint[..12]);
        if json {
            let listed: Vec<serde_json::Value> = copies
                .iter()
                .map(|copy| {
                    serde_json::json!({
                        "repo": copy.repo,
                        "branch": copy.branch,
                        "commit": copy.commit,
                    })
                })
                .collect();
            rows.push(serde_json::json!({
                "fingerprint": fingerprint,
                "short": short,
                "state": if revoked.is_some() { "revoked" } else { "active" },
                "because": revoked,
                "roles": roles,
                "copies": listed,
                "source_repo": source,
            }));
        } else {
            let state = if revoked.is_some() {
                "revoked"
            } else {
                "active"
            };
            println!(
                "{short}\t{state}\t{}\t{}\t{}",
                roles.join(","),
                copies.len(),
                source.as_deref().unwrap_or("-")
            );
        }
    }
    if json {
        println!("{}", serde_json::Value::Array(rows));
    }
    ExitCode::SUCCESS
}

fn run_block_revoke(args: &[String]) -> ExitCode {
    let (mut fingerprint, mut because) = (None, None);
    let mut i = 0;
    while i < args.len() {
        let word = args[i].as_str();
        i += 1;
        if is_help(word) {
            return block_help();
        } else if let Some(value) = word.strip_prefix("--because=") {
            because = Some(value.to_string());
        } else if word == "--because" {
            let Some(value) = args.get(i) else {
                return block_usage_error("--because needs a value");
            };
            i += 1;
            because = Some(value.clone());
        } else if word.starts_with('-') {
            return block_usage_error(&format!("unknown argument `{word}`"));
        } else if fingerprint.replace(word).is_some() {
            return block_usage_error("revoke takes one fingerprint");
        }
    }
    let Some(fingerprint) = fingerprint else {
        return block_usage_error("revoke needs a fingerprint");
    };
    let because = because.unwrap_or_default();
    if because.trim().is_empty() {
        return block_usage_error("revoke needs --because <text>");
    }
    let Some(base) = block_base() else {
        return ExitCode::from(1);
    };
    let fingerprint = match resolve_block_fp(&base, fingerprint) {
        Ok(fingerprint) => fingerprint,
        Err(code) => return code,
    };
    if let Err(why) = block_registry::revoke(&base, &fingerprint, &because) {
        eprintln!(
            "{BIN}: block: could not revoke fp:{}: {why}",
            &fingerprint[..12]
        );
        return ExitCode::from(1);
    }
    eprintln!(
        concat!(greenbelay_guard::bin!(), ": block: fp:{} is revoked"),
        &fingerprint[..12]
    );
    if let Some(pilot) = block_registry::source_entry(&base, &fingerprint).or_else(|| {
        block_registry::entries(&base, &fingerprint)
            .into_iter()
            .next()
    }) {
        let source = pilot.registered.source_repo.as_deref().unwrap_or("-");
        println!("{source}\t{}\t-", pilot.registered.source_branch);
    }
    for copy in block_registry::copies(&base, &fingerprint) {
        println!("{}\t{}\t{}", copy.repo, copy.branch, copy.commit);
    }
    ExitCode::SUCCESS
}

fn run_block_reinstate(args: &[String]) -> ExitCode {
    if args.iter().any(|word| is_help(word)) {
        return block_help();
    }
    let [given] = args else {
        return block_usage_error("reinstate takes one fingerprint");
    };
    if given.starts_with('-') {
        return block_usage_error(&format!("unknown argument `{given}`"));
    }
    let Some(base) = block_base() else {
        return ExitCode::from(1);
    };
    let fingerprint = match resolve_block_fp(&base, given) {
        Ok(fingerprint) => fingerprint,
        Err(code) => return code,
    };
    let short = &fingerprint[..12];
    if block_registry::revoked(&base, &fingerprint).is_none() {
        eprintln!("{BIN}: block: fp:{short} was not revoked");
        return ExitCode::SUCCESS;
    }
    if let Err(why) = block_registry::reinstate(&base, &fingerprint) {
        eprintln!("{BIN}: block: could not reinstate fp:{short}: {why}");
        return ExitCode::from(1);
    }
    eprintln!("{BIN}: block: fp:{short} reinstated");
    ExitCode::SUCCESS
}

fn run_block_sha(args: &[String]) -> ExitCode {
    let (mut dir, mut base) = (std::path::PathBuf::from("."), None);
    let mut i = 0;
    while i < args.len() {
        let word = args[i].as_str();
        i += 1;
        if is_help(word) {
            return block_help();
        }
        if word == "--" {
            if let Some(extra) = args.get(i) {
                return block_usage_error(&format!("unknown argument `{extra}`"));
            }
            break;
        }
        let (flag, attached) = match word.split_once('=') {
            Some((long, value)) if long.starts_with("--") => (long, Some(value.to_string())),
            _ => match (word.get(..2), word.get(2..)) {
                (Some("-C"), Some(rest)) if !rest.is_empty() => ("-C", Some(rest.to_string())),
                _ => (word, None),
            },
        };
        if flag != "-C" && flag != "--base" {
            eprintln!("{BIN}: block: unknown argument `{word}`; try `{BIN} block --help`");
            return ExitCode::from(2);
        }
        let value = match attached {
            Some(value) => value,
            None => {
                let Some(value) = args.get(i) else {
                    eprintln!("{BIN}: block: {flag} needs a value");
                    return ExitCode::from(2);
                };
                i += 1;
                value.clone()
            }
        };
        if value.is_empty() {
            return block_usage_error(&format!("{flag} needs a non-empty value"));
        }
        if flag == "-C" {
            dir = std::path::PathBuf::from(value);
        } else {
            base = Some(value);
        }
    }
    let Some(repo) = push_target::toplevel(&dir) else {
        eprintln!(
            concat!(
                greenbelay_guard::bin!(),
                ": block: {} is not inside a git repository"
            ),
            dir.display()
        );
        return ExitCode::from(1);
    };
    let Some(base) = base.or_else(|| {
        git::default_ref(&repo, std::time::Instant::now() + BLOCK_GIT_BUDGET)
            .map(|(reference, _)| reference)
    }) else {
        eprintln!(concat!(
            greenbelay_guard::bin!(),
            ": block: no default branch of `origin` is known; pass --base <ref>"
        ));
        return ExitCode::from(1);
    };
    let deadline = std::time::Instant::now() + BLOCK_GIT_BUDGET;
    let Some(merge_base) =
        git::stdout_bounded(&repo, &["merge-base", base.as_str(), "HEAD"], deadline)
    else {
        eprintln!("{BIN}: block: `git merge-base {base} HEAD` failed");
        return ExitCode::from(1);
    };
    let diff = match block_fingerprint::diff_of(&repo, &merge_base, "HEAD", deadline) {
        Ok(diff) => diff,
        Err(why) => {
            eprintln!("{BIN}: block: {why}");
            return ExitCode::from(1);
        }
    };
    match block_fingerprint::fingerprint_of_diff(&diff) {
        Some(fingerprint) => {
            println!("{}\t{}", fingerprint.full(), fingerprint.short());
            ExitCode::SUCCESS
        }
        None => {
            let path = block_fingerprint::binary_path(&diff).unwrap_or_default();
            eprintln!(
                "{BIN}: block: the diff has a binary file ({path}); a binary change is never a copy"
            );
            ExitCode::from(1)
        }
    }
}

const TREE_SHA_USAGE: &str = concat!(
    "\
usage: ",
    greenbelay_guard::bin!(),
    " tree-sha [--block] [-C <dir>] [--] [<rev>]

The content id an implementation review and a preview approval bind to
(not attest's canonical tree): the sha256 of `git ls-tree -r -z` of <rev>
(default HEAD) with every entry under docs/plans/ left out, 64 hex in any
object format (attest SPEC, \"Content id\"). Recording the review in the
plan, or adding a plan, therefore never changes it; a code change does
(ADR-0022, ADR-0034, work.implementation-review).

  --block    the review block the implementation-review agent's prompt
             carries: <<<TREE repo=<name> sha=<64 hex>>>>, where <name>
             is the basename of the directory holding the common .git
  -C <dir>   answer for the repository at <dir> (default: the current one)

Prints one line on stdout. Exit 0; 1 outside a repository or for a rev
that names no tree (the reason on stderr); 2 on a usage error.
"
);

fn run_tree_sha(args: &[OsString]) -> ExitCode {
    let args: Vec<String> = args
        .iter()
        .map(|a| a.to_string_lossy().into_owned())
        .collect();
    let (mut block, mut dir, mut rev) = (false, None, None);
    let mut i = 0;
    let mut operands_only = false;
    while i < args.len() {
        let a = args[i].as_str();
        match a {
            _ if operands_only || !a.starts_with('-') => {
                if rev.is_some() {
                    eprintln!(concat!(
                        greenbelay_guard::bin!(),
                        ": tree-sha takes one rev; try `",
                        greenbelay_guard::bin!(),
                        " tree-sha --help`"
                    ));
                    return ExitCode::from(2);
                }
                rev = Some(a.to_string());
            }
            "--" => operands_only = true,
            "--help" | "-h" => {
                print!("{TREE_SHA_USAGE}");
                return ExitCode::SUCCESS;
            }
            "--block" => block = true,
            "-C" => {
                i += 1;
                match args.get(i) {
                    Some(v) => dir = Some(std::path::PathBuf::from(v)),
                    None => {
                        eprintln!(concat!(greenbelay_guard::bin!(), ": -C needs a directory"));
                        return ExitCode::from(2);
                    }
                }
            }
            other => {
                eprintln!("{BIN}: unknown flag `{other}`; try `{BIN} tree-sha --help`");
                return ExitCode::from(2);
            }
        }
        i += 1;
    }
    let dir = dir.unwrap_or_else(|| {
        std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."))
    });
    let Some(repo) = push_target::toplevel(&dir) else {
        eprintln!(
            concat!(
                greenbelay_guard::bin!(),
                ": {} is not inside a git repository"
            ),
            dir.display()
        );
        return ExitCode::from(1);
    };
    let rev = rev.as_deref().unwrap_or("HEAD");
    let sha = match content_id::content_id(&repo, rev) {
        Ok(s) => s,
        Err(why) => {
            eprintln!("{BIN}: {why}");
            return ExitCode::from(1);
        }
    };
    if block {
        let Some(name) = implementation_review::repo_name(&repo) else {
            eprintln!(
                concat!(
                    greenbelay_guard::bin!(),
                    ": the repository at {} has no name (git rev-parse --git-common-dir failed)"
                ),
                repo.display()
            );
            return ExitCode::from(1);
        };
        println!("{}", implementation_review::block(&name, &sha));
    } else {
        println!("{sha}");
    }
    ExitCode::SUCCESS
}

const RULES_SHA_USAGE: &str = concat!(
    "\
usage: ",
    greenbelay_guard::bin!(),
    " rules-sha [-C <dir>]

The lowercase sha256 hex of the stdout of
`aval --json rules --level constraint --governs code --full`, run in <dir>
(default: the current directory). An implementation-review brief carries it
as <<<RULES sha=<64 hex>>>>; the push check compares it.

Prints one line on stdout. Exit 0; 3 when aval is missing or fails (the
command on stderr, nothing on stdout); 2 on a usage error.
"
);

const REVIEW_BRIEF_USAGE: &str = concat!("\
usage: ", greenbelay_guard::bin!(), " review-brief [-C <dir>] [--plan <path>] [--base <ref>] [--profile <role>]
                                [--interdiff <head>]

The markdown brief an implementation reviewer is launched with: the
<<<TREE ...>>> block, the <<<RULES sha=...>>> line and greenspotter's
<<<CANDIDATES ...>>> block (paste them verbatim into the reviewer prompt),
the plan's Verification section, the diff since the merge-base, the
candidates, the code rules in full (a --profile brief: its own judge rules
and an index of the rest, ADR-0065), the constraint rules, the decisions that
bear on the changed files, and the plan's Non-goals. A repository with no
.adr.yaml gets no rules line and a note that no decided code rules apply.
greenspotter is `greenspotter` from PATH, or $GREENBELAY_GREENSPOTTER; when it cannot
answer, the block is <<<CANDIDATES unavailable>>> and the brief goes on.

  -C <dir>        the repository (default: the current directory)
  --plan <path>   the plan (default: the one file under docs/plans/ changed
                  since the merge-base; the brief says when there is none
                  or several)
  --base <ref>    the base ref (default: the remote's default branch)
  --profile <role>
                  a code-review profile (backend, platform, unix, tui,
                  react, ui-design, architect or lang:<x>): adds a `Profile:
                  <role>` line, the judge rules
                  whose `Reviewed by:` names that role, and the plan's Goal
                  and Behaviour. lang:<x>, react, ui-design and platform get
                  only their file types' part of the diff (renames as a
                  deletion and an addition), the stat whole and the other
                  files under `## Not in this brief`; the count is on
                  stderr. Without it the plan section carries the plan's
                  declared code review.
  --interdiff <head>
                  a delta brief: the same headers, then only what changed
                  since <head> (7-64 hex digits: the head an earlier review
                  read, as the push check's stale line names it): the plain
                  diff when <head> is an ancestor of HEAD, else the diff
                  between the two branch patches. Refused (exit 1, naming
                  the brief to build) when <head> cannot be read, the rule
                  files changed since it, this role's last passed review of
                  the branch read another head, or what changed is 60 KB or more; it
                  is never cut.

Exit 0; 1 when the repository or its base cannot be read; 3 when aval is missing or fails (nothing on
stdout); 2 on a usage error.
");

/// The flags of `rules-sha` and `review-brief`.
struct BriefFlags {
    dir: std::path::PathBuf,
    plan: Option<std::path::PathBuf>,
    base: Option<String>,
    profile: Option<String>,
    interdiff: Option<String>,
}

/// One subcommand's name, usage and accepted flags, kept together.
struct BriefCommand {
    name: &'static str,
    usage: &'static str,
    flags: &'static [&'static str],
}

/// `rules-sha` takes `-C` alone.
const RULES_SHA_COMMAND: BriefCommand = BriefCommand {
    name: "rules-sha",
    usage: RULES_SHA_USAGE,
    flags: &["-C"],
};

const REVIEW_BRIEF_COMMAND: BriefCommand = BriefCommand {
    name: "review-brief",
    usage: REVIEW_BRIEF_USAGE,
    flags: &["-C", "--plan", "--base", "--profile", "--interdiff"],
};

fn brief_flags(command: &BriefCommand, args: &[OsString]) -> Result<BriefFlags, ExitCode> {
    let BriefCommand {
        name,
        usage,
        flags: accepted,
    } = command;
    let args: Vec<String> = args
        .iter()
        .map(|a| a.to_string_lossy().into_owned())
        .collect();
    if args.iter().any(|a| a == "--help" || a == "-h") {
        print!("{usage}");
        return Err(ExitCode::SUCCESS);
    }
    let mut flags = BriefFlags {
        dir: std::path::PathBuf::from("."),
        plan: None,
        base: None,
        profile: None,
        interdiff: None,
    };
    let mut i = 0;
    while i < args.len() {
        let word = args[i].as_str();
        i += 1;
        // Neither command takes an operand, so `--` only ends the flags.
        if word == "--" {
            if let Some(operand) = args.get(i) {
                eprintln!("{BIN}: {name}: unknown argument `{operand}`; try `{BIN} {name} --help`");
                return Err(ExitCode::from(2));
            }
            break;
        }
        // POSIX shapes: `--name=value`, and a short flag's value attached as `-C<dir>`.
        let (flag, attached) = match word.split_once('=') {
            Some((long, value)) if long.starts_with("--") => (long, Some(value.to_string())),
            // `get` keeps a word whose second byte is inside a character a usage error.
            _ => match (word.get(..2), word.get(2..)) {
                (Some(short), Some(rest))
                    if !rest.is_empty() && !word.starts_with("--") && accepted.contains(&short) =>
                {
                    (short, Some(rest.to_string()))
                }
                _ => (word, None),
            },
        };
        if !accepted.contains(&flag) {
            eprintln!("{BIN}: {name}: unknown argument `{word}`; try `{BIN} {name} --help`");
            return Err(ExitCode::from(2));
        }
        let value = match attached {
            Some(value) => value,
            None => {
                let Some(value) = args.get(i) else {
                    eprintln!("{BIN}: {name}: {flag} needs a value");
                    return Err(ExitCode::from(2));
                };
                i += 1;
                value.clone()
            }
        };
        match flag {
            "-C" => flags.dir = std::path::PathBuf::from(value),
            "--plan" => flags.plan = Some(std::path::PathBuf::from(value)),
            "--base" => flags.base = Some(value),
            "--interdiff" => {
                let hex = value.bytes().all(|b| b.is_ascii_hexdigit());
                if !hex || !(7..=64).contains(&value.len()) {
                    eprintln!(
                        "{BIN}: {name}: --interdiff takes a commit id (7 to 64 hex digits), not `{value}`"
                    );
                    return Err(ExitCode::from(2));
                }
                flags.interdiff = Some(value);
            }
            "--profile" => {
                if !code_review::valid_profile(&value) {
                    eprintln!(
                        "{BIN}: {name}: unknown profile `{value}`; try `{BIN} {name} --help`"
                    );
                    return Err(ExitCode::from(2));
                }
                flags.profile = Some(value);
            }
            _ => {
                unreachable!("`accepted` holds only -C, --plan, --base, --profile and --interdiff")
            }
        }
    }
    Ok(flags)
}

fn run_rules_sha(args: &[OsString]) -> ExitCode {
    let flags = match brief_flags(&RULES_SHA_COMMAND, args) {
        Ok(f) => f,
        Err(code) => return code,
    };
    match review_brief::rules_sha(&flags.dir) {
        Ok(sha) => {
            println!("{sha}");
            ExitCode::SUCCESS
        }
        Err(why) => {
            eprintln!("{BIN}: {why}");
            ExitCode::from(3)
        }
    }
}

fn run_review_brief(args: &[OsString]) -> ExitCode {
    let flags = match brief_flags(&REVIEW_BRIEF_COMMAND, args) {
        Ok(f) => f,
        Err(code) => return code,
    };
    let request = review_brief::BriefRequest {
        dir: flags.dir,
        plan: flags.plan,
        base: flags.base,
        profile: flags.profile,
        interdiff: flags.interdiff,
    };
    match review_brief::build(&request) {
        Ok(brief) => {
            for notice in &brief.notices {
                eprintln!("{BIN}: review-brief: {notice}");
            }
            print!("{}", brief.text);
            ExitCode::SUCCESS
        }
        Err(review_brief::BriefError::Aval(why)) => {
            eprintln!("{BIN}: {why}");
            ExitCode::from(3)
        }
        Err(review_brief::BriefError::Repository(why)) => {
            eprintln!("{BIN}: {why}");
            ExitCode::from(1)
        }
        Err(review_brief::BriefError::DeltaRefused(why)) => {
            eprintln!("{BIN}: review-brief: {why}");
            ExitCode::from(1)
        }
    }
}

const PLAN_PANEL_USAGE: &str = concat!(
    "\
usage: ",
    greenbelay_guard::bin!(),
    " plan-panel [--code-review [-C <dir>] [--base <ref>]]
                              <plan.md>

The review agents a plan still needs, computed as the plan-review-panel
hook will judge it at ExitPlanMode, and whether this is the whole panel or
a delta since the plan's last accepted body. The seats come from the file
types of the paths in backticks under the plan's `## Phases` (seats=paths),
each attributed to the repository of the machine comment
(`<!-- panel: repos=... adds=... -->`) that holds it; when the Phases name
no path, from every area of those repositories (seats=areas), with advice
on stderr to name the files. adds= declares what no path shows: cli, ui,
screen, ops, contract, lang:<language>.

First line: repos=<names> areas=<classes> body=<12 hex>
            panel=full|delta|current seats=paths|areas
(areas= lists the classes the seats came from, one line in the output).
Then one line per agent to launch: `plan-review-<role>`, and `--lang <l>`
for a language review (the flag its `plan-sha --block` call takes).

--code-review prints, instead, the code-review profiles proposed for each
repository of the machine comment, from the file types of the paths the
Phases name in it (from its areas when the seats come from areas): one
line `<repo>\t<profiles comma-separated>`, or `<repo>\tnone\t<reason>`
with the reason `markdown only`, `no reviewed file type`, `no file named`
or `no language area`; `cut -f2` reads `none`, and the line pastes as
`- <repo>: none — <reason>`. A plan's `## Code review` section
(`- <repo>: <profiles>` or `- <repo>: none — <reason>`, after Non-goals)
declares them; without the flag a plan with no such section is warned
about on stderr and the output above is unchanged.

  -C <dir>      with --code-review: also read the branch of the repository
                at <dir>; a registered, unrevoked, pin-checked copy of a
                reviewed block is proposed as `<repo>\tnone\tcopy of fp:<id>`
                while the implementation-review hook enforces; otherwise
                the profiles are proposed, with the cause on stderr
  --base <ref>  the branch starts at its merge base with <ref> (default:
                origin's default branch); needs --code-review, like -C
                (without it: exit 2)

Exit 0, 1 when the plan cannot be read, its comment is wrong or its Code
review section does not parse (the reason on stderr), 2 on a usage error.
"
);

/// The proposal `lines`, with the branch's own repository proposed as a copy
/// when `-C` or `--base` named a branch that is a verified registered block.
/// Without either flag the lines are unchanged.
fn plan_panel_branch(lines: &str, dir: Option<&str>, base: Option<&str>) -> Result<String, String> {
    if dir.is_none() && base.is_none() {
        return Ok(lines.to_string());
    }
    let hook = greenbelay_guard::stance::resolve(&implementation_review_rule::RULE);
    let branch =
        code_review::branch_proposal(std::path::Path::new(dir.unwrap_or(".")), base, hook)?;
    for notice in &branch.notices {
        eprintln!("{notice}");
    }
    let Some(id) = branch.copy_of else {
        return Ok(lines.to_string());
    };
    let reason = code_review::NoReviewReason::CopyOf(id);
    let mut out = String::new();
    for line in lines.lines() {
        if line.split('\t').next() == Some(branch.repo.as_str()) {
            out.push_str(&format!("{}\tnone\t{reason}\n", branch.repo));
        } else {
            out.push_str(line);
            out.push('\n');
        }
    }
    Ok(out)
}

fn run_plan_panel(args: &[OsString]) -> ExitCode {
    let args: Vec<String> = args
        .iter()
        .map(|a| a.to_string_lossy().into_owned())
        .collect();
    if args.iter().any(|a| a == "--help" || a == "-h") {
        print!("{PLAN_PANEL_USAGE}");
        return ExitCode::SUCCESS;
    }
    let mut proposing = false;
    let (mut branch_dir, mut branch_base): (Option<String>, Option<String>) = (None, None);
    let mut operands: Vec<&String> = Vec::new();
    let mut i = 0;
    while i < args.len() {
        let word = args[i].as_str();
        i += 1;
        if word == "--code-review" {
            proposing = true;
            continue;
        }
        let (flag, attached) = match word.split_once('=') {
            Some((long, value)) if long.starts_with("--") => (long, Some(value.to_string())),
            _ => match (word.get(..2), word.get(2..)) {
                (Some("-C"), Some(rest)) if !rest.is_empty() => ("-C", Some(rest.to_string())),
                _ => (word, None),
            },
        };
        if flag != "-C" && flag != "--base" {
            operands.push(&args[i - 1]);
            continue;
        }
        let value = match attached {
            Some(value) => value,
            None => {
                let Some(value) = args.get(i) else {
                    eprintln!("{BIN}: plan-panel: {flag} needs a value");
                    return ExitCode::from(2);
                };
                i += 1;
                value.clone()
            }
        };
        if flag == "-C" {
            branch_dir = Some(value);
        } else {
            branch_base = Some(value);
        }
    }
    if !proposing && (branch_dir.is_some() || branch_base.is_some()) {
        eprint!("{BIN}: plan-panel: -C and --base need --code-review\n\n{PLAN_PANEL_USAGE}");
        return ExitCode::from(2);
    }
    let [file] = operands.as_slice() else {
        eprint!("{BIN}: plan-panel takes one plan file\n\n{PLAN_PANEL_USAGE}");
        return ExitCode::from(2);
    };
    let text = match code_review::read_plan(std::path::Path::new(file)) {
        Ok(text) => text,
        Err(why) => {
            eprintln!("{BIN}: {why}");
            return ExitCode::from(1);
        }
    };
    match code_review::parse(&text) {
        Err(why) => {
            eprintln!("{BIN}: plan-panel: ## Code review: {why}");
            return ExitCode::from(1);
        }
        Ok(None) if !proposing => eprintln!(
            concat!(greenbelay_guard::bin!(), ": plan-panel: no ## Code review section; run plan-panel --code-review and add it after ## Non-goals")
        ),
        Ok(_) => {}
    }
    if proposing {
        return match code_review::proposal(&text) {
            Ok(lines) => {
                let lines = match plan_panel_branch(
                    &lines,
                    branch_dir.as_deref(),
                    branch_base.as_deref(),
                ) {
                    Ok(lines) => lines,
                    Err(why) => {
                        eprintln!("{BIN}: plan-panel: {why}");
                        return ExitCode::from(1);
                    }
                };
                print!("{lines}");
                ExitCode::SUCCESS
            }
            Err(why) => {
                eprintln!("{BIN}: {why}");
                ExitCode::from(1)
            }
        };
    }
    match plan_review::panel(std::path::Path::new(file)) {
        Ok(p) => {
            if let Some(note) = &p.id_note {
                eprintln!("{BIN}: plan-panel: {note}");
            }
            for line in &p.misplaced_steps {
                eprintln!(
                    "{BIN}: plan-panel: {file}:{line}: steps block outside ## Phases; not counted. Move it under ## Phases."
                );
            }
            let areas = p.classes.iter().cloned().collect::<Vec<_>>().join(",");
            println!(
                "repos={} areas={} body={} panel={} seats={} {}",
                p.repos,
                if areas.is_empty() { "-" } else { &areas },
                &p.sha[..12],
                p.mode,
                p.source.as_str(),
                p.counts
            );
            if let Some(advice) = &p.advice {
                eprintln!("{BIN}: plan-panel: {advice}");
            }
            for role in &p.needed {
                let cut = if p.sliced.contains(role) {
                    format!(" --slice {role}")
                } else {
                    String::new()
                };
                match plan_review::agent_for(role) {
                    (agent, Some(lang)) => println!("{agent} --lang {lang}{cut}"),
                    (agent, None) => println!("{agent}{cut}"),
                }
            }
            ExitCode::SUCCESS
        }
        Err(why) => {
            eprintln!("{BIN}: {why}");
            ExitCode::from(1)
        }
    }
}

const PREVIEW_USAGE: &str = concat!(
    "\
usage: ",
    greenbelay_guard::bin!(),
    " preview register --url <url> --guide <file.md> [--repo <dir>] [--open]

Validate a localhost preview of the repository's HEAD, for the person to
approve before a UI-changing push (ADR-0023), and render its guide to a
page (work.preview-is-guided). Run it in the foreground as the last
command of its line (`cd <wt> && npm run build && ",
    greenbelay_guard::bin!(),
    " preview
register …` is fine; nothing piped, redirected or after it): the Claude
Code hook binds its output to the session.

  --url <url>         where the clean worktree is served (http or https)
  --guide <file.md>   what the person needs to decide with. Must be OUTSIDE
                      the worktree (it and its page would dirty the commit
                      they describe) and carry these H2 sections, emoji
                      and case aside:
                        ## Where we are          project, branch, plan, why
                                                 they are asked
                        ## What you should see   in their words; \"nothing
                                                 new\" when that is the point
                        ## Try it                numbered steps (`1. ...`):
                                                 the URL, each click by its
                                                 label, what should appear
                        ## Reference             ![before](before.png)
                                                 ![after](after.png)
                        ## Already checked       what you verified, and what
                                                 to look at especially
                      A heading may carry a note: `## Try it (2 min)`.
                      Images are relative to the guide's directory; two
                      named *before* and *after* show side by side.

                      Mockup mode: when the branch (from its merge base
                      with the default branch) commits a picked mockup's
                      artboards (`*.dc.html` under docs/mockups/<screen>, or
                      `git config greenbelay.preview.mockups`), the guide
                      must also show, under ## Reference, the screen path,
                      `Viewport: <width>px · <theme>`, and the artboard
                      beside the built screen as files next to it
                      (artboard.png / after.png; also mockup / live, and
                      state pairs such as artboard-empty.png /
                      after-empty.png), plus a section
                        ## Differences from the mockup
                                                 `None`, or bullets
                                                 `- fixed: …` /
                                                 `- deliberate: <reason>`
                      Copy the images beside the guide as their own step,
                      before this command.
  --repo <dir>        the repository (default: the current directory)
  --open              open the rendered page with the platform opener; a
                      failure to open never fails the command
  --attestation <f>   DEPRECATED alias of --guide, for one release: read as
                      the guide, and refused unless it is one

Writes index.html beside the guide and prints one JSON object, on one
line, on stdout: id, repo, commit, url, guide, page, page_url, label,
aliases, question_prefix. Start the marked question with `question_prefix`
(`[preview <id>] <label>`), verbatim: the id is what approves. Exit 0 when
valid, 1 when refused (the reason on stderr), 2 on a usage error.

example:
  ",
    greenbelay_guard::bin!(),
    " preview register --url http://localhost:5173/settings \\
    --guide ~/.claude/greenbelay/attestations/abc1234/guide.md
"
);

fn run_preview(args: &[OsString]) -> ExitCode {
    let args: Vec<String> = args
        .iter()
        .map(|a| a.to_string_lossy().into_owned())
        .collect();
    if args.is_empty() || args.iter().any(|a| a == "--help" || a == "-h") {
        print!("{PREVIEW_USAGE}");
        return if args.is_empty() {
            ExitCode::from(2)
        } else {
            ExitCode::SUCCESS
        };
    }
    if args[0] != "register" {
        eprintln!(
            concat!(
                greenbelay_guard::bin!(),
                ": unknown preview command `{}`; try `",
                greenbelay_guard::bin!(),
                " preview --help`"
            ),
            args[0]
        );
        return ExitCode::from(2);
    }
    let (mut url, mut guide, mut attestation, mut repo) = (None, None, None, None);
    let mut open = false;
    let mut i = 1;
    while i < args.len() {
        if args[i] == "--open" {
            open = true;
            i += 1;
            continue;
        }
        let (flag, inline) = match args[i].split_once('=') {
            Some((f, v)) if f.starts_with("--") => (f.to_string(), Some(v.to_string())),
            _ => (args[i].clone(), None),
        };
        let value = match inline {
            Some(v) => v,
            None => {
                i += 1;
                match args.get(i) {
                    Some(v) => v.clone(),
                    None => {
                        eprintln!("{BIN}: {flag} needs a value");
                        return ExitCode::from(2);
                    }
                }
            }
        };
        match flag.as_str() {
            "--url" => url = Some(value),
            "--guide" => guide = Some(value),
            "--attestation" => attestation = Some(value),
            "--repo" => repo = Some(value),
            other => {
                eprintln!("{BIN}: unknown flag `{other}`; try `{BIN} preview --help`");
                return ExitCode::from(2);
            }
        }
        i += 1;
    }
    let guide = match (guide, attestation) {
        (Some(g), None) => g,
        (Some(g), Some(_)) => {
            eprintln!(concat!(
                greenbelay_guard::bin!(),
                ": --attestation is deprecated and ignored beside --guide"
            ));
            g
        }
        (None, Some(a)) => {
            eprintln!(
                concat!(greenbelay_guard::bin!(), ": --attestation is deprecated; use --guide. It is read as the guide, and refused unless it is one (see `", greenbelay_guard::bin!(), " preview --help`)")
            );
            a
        }
        (None, None) => {
            eprintln!(
                concat!(greenbelay_guard::bin!(), ": preview register needs --guide <file.md>: the person is guided, not quizzed (see `", greenbelay_guard::bin!(), " preview --help`)")
            );
            return ExitCode::from(2);
        }
    };
    let Some(url) = url else {
        eprintln!(concat!(
            greenbelay_guard::bin!(),
            ": preview register needs --url"
        ));
        return ExitCode::from(2);
    };
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let dir = repo.map(PathBuf::from).unwrap_or_else(|| cwd.clone());
    let dir = if dir.is_absolute() {
        dir
    } else {
        cwd.join(dir)
    };
    match preview::register(&dir, &url, std::path::Path::new(&guide)) {
        Ok(mut r) => {
            if r.unchanged {
                eprintln!(concat!(greenbelay_guard::bin!(), ": before and after are byte-identical; the hook approves this preview as unchanged when it binds it, if they still are"));
            }
            if open {
                r.opened = Some(open_page(std::path::Path::new(&r.page)));
            }
            println!("{}", r.to_json());
            ExitCode::SUCCESS
        }
        Err(why) => {
            eprintln!("{BIN}: preview not registered: {why}");
            ExitCode::from(1)
        }
    }
}

/// Open the registered page through the same opener as `amont-agent open`.
/// Whatever happens, the registration stands: the page is a convenience.
fn open_page(page: &std::path::Path) -> bool {
    match open::open_url(&greenbelay_process::guide::file_url(page)) {
        Ok(()) => true,
        Err(why) => {
            eprintln!("{BIN}: {why}");
            false
        }
    }
}

fn run_check(args: &[OsString]) -> ExitCode {
    let f = match flags(args) {
        Ok(f) => f,
        Err(why) => {
            eprintln!("{BIN}: {why}");
            return ExitCode::from(2);
        }
    };
    if f.rest.len() != 1 {
        eprintln!(concat!(
            greenbelay_guard::bin!(),
            ": check needs exactly one command, quoted"
        ));
        return ExitCode::from(2);
    }
    let src = &f.rest[0];
    let parsed = shell::lex(src);
    // The dialect is what the command would run in. `check` has no hook
    // payload and no business guessing from its own `SHELL`, so it is told,
    // or it says `unknown` — the same answer the backtester has to give.
    let input = rules::Input::new(src, f.dialect.unwrap_or(rules::Dialect::Unknown), &parsed);
    let found = rules::evaluate(rule_table::RULES, &input);
    if found.is_empty() {
        match &parsed {
            shell::Parsed::Opaque(why) => println!("no opinion: {}", why.why()),
            _ => println!("no rule fires"),
        }
        return ExitCode::SUCCESS;
    }
    let cwd = match f.cwd.clone().map(Ok).unwrap_or_else(std::env::current_dir) {
        Ok(dir) => dir,
        Err(e) => {
            eprintln!("{BIN}: check: the working directory cannot be read: {e}");
            return ExitCode::from(2);
        }
    };
    let mut printed = 0;
    for (rule, finding) in found {
        // The stance in force on THIS machine, which is what the hook would
        // do — with the shipped one beside it when they differ. Printing
        // only the default read `[advise]` for a rule long graduated to deny,
        // and the reader took it for the verdict.
        let mut now = stance::resolve(rule);
        let mut reason = finding.reason.clone();
        let mut remedy = finding.remedy.clone();
        if rule.confirm.is_some() {
            match hook::confirmed_for_check(rule, &finding, src, &cwd, &parsed) {
                Ok(checked) => {
                    now = checked.stance;
                    if let Some((said, said_remedy)) = checked.said {
                        reason = said;
                        if let Some(said_remedy) = said_remedy {
                            remedy = said_remedy;
                        }
                    }
                }
                Err(why) => {
                    if f.explain {
                        println!("{} not confirmed: {why}", rule.id);
                    }
                    continue;
                }
            }
        }
        printed += 1;
        if now == rule.default_stance {
            println!("{} [{}]", rule.id, now.as_str());
        } else {
            println!(
                "{} [{}, ships as {}]",
                rule.id,
                now.as_str(),
                rule.default_stance.as_str()
            );
        }
        println!("  {reason}");
        println!("  → {remedy}");
        println!(
            "  â–¸ {}",
            backtest::excerpt(src, finding.span.start, finding.span.end)
        );
    }
    if printed == 0 {
        // A live rule's `examine` lets an unreadable command through to its
        // `confirm`; when nothing was confirmed, the verdict is the lexer's.
        match &parsed {
            shell::Parsed::Opaque(why) => println!("no opinion: {}", why.why()),
            _ => println!("no rule fires"),
        }
    }
    name_the_unread(src, &parsed);
    ExitCode::SUCCESS
}

/// Say which pipelines went unread, after the verdict.
///
/// The verdict stays on the first line so that "no rule fires" and "no
/// opinion" keep meaning what they meant. What follows is the difference
/// between having looked and having been able to look.
fn name_the_unread(src: &str, parsed: &shell::Parsed) {
    let clauses = parsed.clauses();
    for (i, cmd) in clauses.iter().enumerate() {
        let Some(why) = &cmd.opaque else { continue };
        // One line per unreadable PIPELINE: a clause whose predecessor pipes
        // into it is a later stage of a run already named.
        if cmd.prev.is_some_and(|c| c.is_pipe()) {
            continue;
        }
        let mut end = i;
        while clauses[end].next.is_some_and(|c| c.is_pipe()) && end + 1 < clauses.len() {
            end += 1;
        }
        println!("  ⋯ not read: {}", why.why());
        println!("    {}", backtest::excerpt(src, cmd.at, clauses[end].end));
    }
}

/// A stance as `rules` shows it: the one in force, and what the rule ships as
/// only when they differ — that difference is a decision somebody made on
/// this machine. Printing the shipped default alone listed a rule promoted to
/// `deny` as `observe`, so the one command you would run to ask whether a
/// rule is armed was the one that got it wrong.
fn stance_shown(now: rules::Stance, ships: rules::Stance) -> String {
    if now == ships {
        now.as_str().to_string()
    } else {
        format!("{} (ships as {})", now.as_str(), ships.as_str())
    }
}

const RULES_USAGE: &str = concat!("usage: ", greenbelay_guard::bin!(), " rules [--json]\n");

/// `rules` takes `--json` and nothing else. It matches its arguments itself:
/// `flags()` accepts every flag any subcommand knows and keeps bare words,
/// so `rules --force` or `rules foo` would pass through it silently, and
/// until 2.27 `rules` ignored its arguments altogether — `rules --json`
/// printed the text table and exited 0.
fn run_rules(args: &[OsString]) -> ExitCode {
    let args: Vec<String> = args
        .iter()
        .map(|a| a.to_string_lossy().into_owned())
        .collect();
    // Help wins wherever it appears, as in the other subcommands.
    if args.iter().any(|a| a == "-h" || a == "--help") {
        print!("{RULES_USAGE}");
        return ExitCode::SUCCESS;
    }
    match args.as_slice() {
        [] => print_rules_text(),
        [a] if a == "--json" => print_rules_json(),
        [a, rest @ ..] if a == "--json" => {
            eprintln!(
                concat!(
                    greenbelay_guard::bin!(),
                    ": unexpected argument `{}`; `rules` takes only --json"
                ),
                rest[0]
            );
            ExitCode::from(2)
        }
        [a, ..] => {
            eprintln!("{BIN}: unknown argument `{a}`; `rules` takes only --json");
            ExitCode::from(2)
        }
    }
}

/// One object per rule, then per assertion, in the order the text prints
/// them. The keys are an interface — `scripts/bump-tap.py` and the tap's
/// formula read them — and `tests/rules_json.rs` pins the exact set.
/// `default_stance` is what ships; `stance` is what is in force here.
fn print_rules_json() -> ExitCode {
    let entry = |id: &str,
                 kind: &str,
                 ships: rules::Stance,
                 now: rules::Stance,
                 max: rules::Stance,
                 e: &rules::Evidence,
                 prevents: &str,
                 irreversible: bool| {
        json::object(&[
            json::string_field("id", id),
            json::string_field("kind", kind),
            json::string_field("default_stance", ships.as_str()),
            json::string_field("stance", now.as_str()),
            json::string_field("max_stance", max.as_str()),
            json::float_field("per_1000", e.per_1000),
            json::string_field("measured", e.measured),
            json::string_field("prevents", prevents),
            json::bool_field("irreversible", irreversible),
        ])
    };
    let mut items: Vec<String> = rule_table::RULES
        .iter()
        .map(|r| {
            entry(
                r.id,
                "rule",
                r.default_stance,
                stance::resolve(r),
                r.max_stance,
                &r.evidence,
                r.prevents,
                r.irreversible,
            )
        })
        .collect();
    // An assertion has no ceiling, so it reports `deny`: nothing caps it.
    items.extend(assertions::ASSERTIONS.iter().map(|a| {
        entry(
            a.id,
            "assertion",
            a.default_stance,
            stance::resolve_assertion(a),
            rules::Stance::Deny,
            &a.evidence,
            a.prevents,
            a.irreversible,
        )
    }));
    println!("{}", json::array(&items));
    ExitCode::SUCCESS
}

fn print_rules_text() -> ExitCode {
    let w = ui::id_column(rule_table::RULES);
    let rule_stances: Vec<String> = rule_table::RULES
        .iter()
        .map(|r| stance_shown(stance::resolve(r), r.default_stance))
        .collect();
    let assertion_stances: Vec<String> = assertions::ASSERTIONS
        .iter()
        .map(|a| stance_shown(stance::resolve_assertion(a), a.default_stance))
        .collect();
    // Wide enough for the longest entry, so a moved stance does not push its
    // row's evidence out of line with the others.
    let s = rule_stances
        .iter()
        .chain(&assertion_stances)
        .map(String::len)
        .max()
        .unwrap_or(0)
        .max(8);
    for (r, shown) in rule_table::RULES.iter().zip(&rule_stances) {
        // Named only when it bites: a rule capped below `deny` can never be
        // configured past it, and that is worth seeing next to its stance.
        let ceiling = if r.max_stance < rules::Stance::Deny {
            format!("  (max {})", r.max_stance.as_str())
        } else {
            String::new()
        };
        println!(
            "{:<w$}{:<s$} {:>6.1}/1000  measured {}{ceiling}",
            r.id, shown, r.evidence.per_1000, r.evidence.measured
        );
    }
    // Listed apart, because they answer a different question: a rule judges a
    // command before it runs, an assertion checks what a command that already
    // reported success actually did.
    for (a, shown) in assertions::ASSERTIONS.iter().zip(&assertion_stances) {
        println!(
            "{:<w$}{:<s$} {:>6.1}/1000  measured {}  (assertion)",
            a.id, shown, a.evidence.per_1000, a.evidence.measured
        );
    }
    ExitCode::SUCCESS
}

fn run_install(args: &[OsString], adding: bool) -> ExitCode {
    let f = match flags(args) {
        Ok(f) => f,
        Err(why) => {
            eprintln!("{BIN}: {why}");
            return ExitCode::from(2);
        }
    };
    let scope = if f.local {
        settings::Scope::ProjectLocal
    } else if f.project {
        settings::Scope::Project
    } else {
        settings::Scope::User
    };
    let project = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let Some(path) = scope.path(&project) else {
        eprintln!(concat!(
            greenbelay_guard::bin!(),
            ": cannot find your Claude Code settings directory"
        ));
        return ExitCode::from(2);
    };
    // The absolute path of THIS binary. A `PATH`-resolved command exits 127
    // into Claude Code's non-blocking bucket the moment PATH differs, which
    // disables the guard with nothing to notice it.
    let bin = match std::env::current_exe() {
        Ok(b) => b,
        Err(e) => {
            eprintln!("{BIN}: cannot resolve my own path: {e}");
            return ExitCode::from(2);
        }
    };

    let plugin = plugin_install::placement();
    if plugin.is_none() {
        eprintln!(
            "{BIN}: no state directory resolves (XDG_STATE_HOME, CLAUDE_CONFIG_DIR, HOME), so the clear-relay plugin is left out"
        );
    }
    let planned = if adding {
        settings::plan_install(&path, &bin, f.reformat, plugin.as_ref())
    } else {
        settings::plan_uninstall(&path, f.reformat, plugin.as_ref())
    };
    let plan = match planned {
        Ok(p) => p,
        Err(e) => {
            eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
            if adding {
                eprintln!("\n{}", settings::snippet(&bin));
            }
            return ExitCode::from(2);
        }
    };

    if !f.write {
        if matches!(plan.change, settings::Change::RemoveFile) {
            println!(
                "{} would be removed: nothing else is left in it.",
                plan.path.display()
            );
            if let Some(dir) = &plan.remove_dir {
                println!("would remove {}", dir.display());
            }
            println!("Nothing written. Re-run with --write to apply.");
            return ExitCode::SUCCESS;
        }
        println!("{}", plan.change.describe(&plan.path));
        for (dest, _) in &plan.files {
            println!("would write {}", dest.display());
        }
        if let Some(dir) = &plan.remove_dir {
            println!("would remove {}", dir.display());
        }
        println!("Nothing written. Re-run with --write to apply:\n");
        print!("{}", plan.after);
        if adding && plugin.is_some() {
            print_install_registry(RegistryVoice::WouldThenNeed);
        }
        return ExitCode::SUCCESS;
    }
    if matches!(plan.change, settings::Change::WouldReformat) {
        eprintln!("{}\n", plan.change.describe(&plan.path));
        eprint!("{}", settings::snippet(&bin));
        return ExitCode::from(2);
    }
    match settings::apply(&plan) {
        Ok(()) => {
            println!("{}", plan.change.describe(&plan.path));
            for (dest, _) in &plan.files {
                eprintln!("wrote {}", dest.display());
            }
            if adding && !plan.files.is_empty() {
                if let Some(placement) = &plugin {
                    eprintln!(
                        "enabled {}@{}: an answer ending \"safe to /clear; next: `<prompt>`\"",
                        placement.plugin, placement.marketplace
                    );
                    eprintln!(
                        "  clears the session after 10 s, then submits <prompt> (type or /stay to keep it); remove: {BIN} uninstall --write"
                    );
                }
            }
            // The same condition as the preview's, so a preview never names
            // commands its --write leaves unsaid (plugin files already placed).
            if adding && plugin.is_some() {
                print_install_registry(RegistryVoice::Run);
            }
            if let Some(dir) = &plan.remove_dir {
                eprintln!("removed {}", dir.display());
            }
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!(
                "{BIN}: could not apply the change to {} and the clear-relay plugin: {e}",
                plan.path.display()
            );
            ExitCode::from(2)
        }
    }
}

/// The registry lines of an install: judged against the side the plugin is
/// installed under, from the Claude config directory whatever the scope.
fn print_install_registry(voice: RegistryVoice) {
    if let Some(env) = greenbelay_guard::migrate::Env::from_process() {
        print_registry(
            &migrate_plugin::registry_state_for(
                &env,
                greenbelay_guard::migrate::Direction::Forward,
            ),
            voice,
        );
    }
}

/// `rollup.log` could not be read: say so on stderr.
fn report_rollup_problem(problem: Option<&greenbelay_guard::rollup::Problem>) {
    use greenbelay_guard::rollup::Problem;
    match problem {
        Some(Problem::UnknownVersion(version)) => {
            eprintln!("{BIN}: rollup.log has format {version}, skipped; upgrade {BIN}");
        }
        Some(Problem::Unreadable(failure)) => {
            eprintln!("{BIN}: rollup.log unreadable: {}", failure.why());
        }
        None => {}
    }
}

/// One line naming the newest `rollup-failed` journal record the roll-up has
/// not got past (newer than its watermark), in the journal.
fn rollup_failed_line(unfolded: &[journal::Row]) -> Option<String> {
    let newest = unfolded
        .iter()
        .filter(|row| row.outcome == "rollup-failed")
        .max_by_key(|row| row.ts)?;
    Some(format!(
        "{BIN}: rollup: a fold failed: `rollup-failed` record at {} in the journal",
        civil::iso(day_of_seconds(newest.ts))
    ))
}

/// The plan root in use and where it came from.
fn plan_root_finding() -> doctor::Finding {
    use plan_review::{RootSource, ROOT_REMEDY};
    match plan_review::resolved_root() {
        Some((path, RootSource::CwdFallback)) => doctor::Finding::warn(
            format!("plan root: {} (cwd fallback)", path.display()),
            format!("plan review falls back to the working directory and the attestations sweep removes nothing; {ROOT_REMEDY}"),
        ),
        Some((path, source)) => doctor::Finding::good(format!(
            "plan root: {} ({})",
            path.display(),
            source.label()
        )),
        None => doctor::Finding::warn(
            "plan root: unset",
            format!("plan review cannot resolve repos= and the attestations sweep removes nothing; {ROOT_REMEDY}"),
        ),
    }
}

const ROLLUP_USAGE: &str =
    "usage: greenbelay rollup [--weeks <n>] [--json] [--transcripts <dir>] [-q]";

/// `greenbelay rollup [--weeks <n>] [--json] [--transcripts <dir>] [-q]`.
///
/// Every state write (the calls freeze) finishes, and its lock is released,
/// before the first byte goes to stdout.
fn run_rollup(args: &[OsString]) -> ExitCode {
    use greenbelay_guard::rollup;
    if args.iter().any(|a| a == "--help" || a == "-h") {
        println!("{ROLLUP_USAGE}");
        return ExitCode::SUCCESS;
    }
    let RollupArgs {
        progress,
        weeks,
        given,
    } = match parse_rollup_args(args) {
        Ok(parsed) => parsed,
        Err(code) => return code,
    };
    let Some(journal_path) = journal::path() else {
        eprintln!("{BIN}: cannot find the state directory (is HOME set?)");
        return ExitCode::FAILURE;
    };
    let rollup_path = rollup::path_beside(&journal_path);
    let known: Vec<rollup::Known> = rule_table::RULES
        .iter()
        .map(backtest::Subject::Rule)
        .chain(
            assertions::ASSERTIONS
                .iter()
                .map(backtest::Subject::Assertion),
        )
        .map(|subject| rollup::Known {
            id: subject.id(),
            replay: subject.replay().as_str(),
        })
        .collect();
    let today = day_of_seconds(unix_now());
    let current = civil::week_start(today);

    let counted = rollup::load(&journal::paths(), &rollup_path);
    report_rollup_problem(counted.problem.as_ref());
    // An unreadable or unknown-format roll-up has no honest counts to print:
    // retro would read the zeros as real.
    if counted.problem.is_some() {
        return ExitCode::FAILURE;
    }
    let closed = weeks.or(if given.json { None } else { Some(1) });
    let shown = rollup::weeks_shown(
        &counted,
        &rollup::merged_calls(&counted.rollup, &Default::default()),
        today,
        closed,
    );
    let freezable = if counted.problem.is_none() {
        rollup::freezable_weeks(
            &counted.rollup,
            &shown,
            today,
            rollup::covered_since(&counted),
        )
    } else {
        Vec::new()
    };

    let live = scan_and_freeze(
        &rollup_path,
        &given.transcripts,
        &freezable,
        current,
        progress,
    );

    let counted = rollup::load(&journal::paths(), &rollup_path);
    let calls = rollup::merged_calls(&counted.rollup, &live);
    let report = rollup::build(&counted, &calls, &known, today, &shown);
    let text = if given.json {
        format!("{}\n", report.to_json())
    } else {
        report.to_text(ui::id_column(rule_table::RULES))
    };
    use std::io::Write as _;
    match std::io::stdout().lock().write_all(text.as_bytes()) {
        Err(err) if err.kind() != std::io::ErrorKind::BrokenPipe => {
            eprintln!("{BIN}: cannot write the report: {err}");
            ExitCode::FAILURE
        }
        _ => ExitCode::SUCCESS,
    }
}

/// Whether `rollup` draws its progress line on a terminal.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Progress {
    Shown,
    Hidden,
}

struct RollupArgs {
    progress: Progress,
    weeks: Option<usize>,
    given: Flags,
}

/// Parse `rollup`'s arguments; an `Err` is the exit code to leave with, after
/// the message is printed.
fn parse_rollup_args(args: &[OsString]) -> Result<RollupArgs, ExitCode> {
    use greenbelay_guard::rollup;
    let mut progress = Progress::Shown;
    let mut weeks: Option<usize> = None;
    let mut rest: Vec<OsString> = Vec::new();
    let mut iter = args.iter();
    while let Some(arg) = iter.next() {
        let text = arg.to_string_lossy().into_owned();
        let (name, inline) = match text.split_once('=') {
            Some((name, inline_value)) if name.starts_with("--") => {
                (name, Some(inline_value.to_string()))
            }
            _ => (text.as_str(), None),
        };
        match name {
            "-q" | "--quiet" => progress = Progress::Hidden,
            "--weeks" => {
                let given = inline.or_else(|| {
                    iter.next()
                        .map(|arg_value| arg_value.to_string_lossy().into_owned())
                });
                match given.as_deref().map(str::parse::<usize>) {
                    Some(Ok(count)) if (1..=rollup::WEEKS_KEPT as usize).contains(&count) => {
                        weeks = Some(count);
                    }
                    Some(_) => {
                        eprintln!(
                            "{BIN}: --weeks takes a number from 1 to {}",
                            rollup::WEEKS_KEPT
                        );
                        return Err(ExitCode::from(2));
                    }
                    None => {
                        eprintln!("{BIN}: --weeks needs a value");
                        return Err(ExitCode::from(2));
                    }
                }
            }
            "--json" => rest.push(arg.clone()),
            "--transcripts" => {
                // The two-word form passes the path through untouched; only the
                // `=` form has been through text.
                let dir: Option<OsString> = match inline {
                    Some(inline_value) => Some(OsString::from(inline_value)),
                    None => iter.next().cloned(),
                };
                match dir {
                    Some(dir) if !dir.is_empty() => {
                        rest.push(OsString::from("--transcripts"));
                        rest.push(dir);
                    }
                    _ => {
                        eprintln!("{BIN}: --transcripts needs a directory");
                        return Err(ExitCode::from(2));
                    }
                }
            }
            other if other.starts_with('-') => {
                eprintln!("{BIN}: rollup has no flag `{other}`; try `{BIN} rollup --help`");
                return Err(ExitCode::from(2));
            }
            _ => rest.push(arg.clone()),
        }
    }
    let given = match flags(&rest) {
        Ok(parsed) => parsed,
        Err(why) => {
            eprintln!("{BIN}: {why}");
            return Err(ExitCode::from(2));
        }
    };
    if let Some(extra) = given.rest.first() {
        eprintln!("{BIN}: rollup takes no argument, not `{extra}`");
        return Err(ExitCode::from(2));
    }
    Ok(RollupArgs {
        progress,
        weeks,
        given,
    })
}

/// Scan the transcripts for tool calls and freeze the closed weeks that can be
/// frozen; the calls to report are returned.
fn scan_and_freeze(
    rollup_path: &std::path::Path,
    transcripts: &[PathBuf],
    freezable: &[civil::Day],
    current: civil::Day,
    progress: Progress,
) -> greenbelay_guard::rollup::Calls {
    use greenbelay_guard::rollup;
    // The scan holds no lock: it is the slow part.
    let mut live = rollup::Calls::new();
    let mut freeze = true;
    match transcript::roots(transcripts) {
        Ok(roots) => {
            use std::io::IsTerminal as _;
            if progress == Progress::Shown && std::io::stderr().is_terminal() {
                eprintln!("{BIN}: counting tool calls in the transcripts...");
            }
            let first = freezable
                .iter()
                .copied()
                .min()
                .map_or(current, |first_week| first_week.min(current));
            match transcript::calls_by_week(&roots, Some(first)) {
                Ok(scanned) => {
                    if scanned.unreadable > 0 {
                        // A file that would not read whole makes every count a
                        // lower bound: show them, store none.
                        eprintln!(
                            "{BIN}: warning: {} transcript file(s) unreadable; calls of closed weeks not stored",
                            scanned.unreadable
                        );
                        freeze = false;
                    }
                    live = scanned
                        .weeks
                        .into_iter()
                        .filter(|(week, _)| *week == current || freezable.contains(week))
                        .collect();
                }
                Err(err) => eprintln!("{BIN}: {}", err.explain()),
            }
        }
        Err(err) => eprintln!(
            "{BIN}: warning: {}; calls come from the frozen weeks only",
            err.explain()
        ),
    }
    if freeze && !freezable.is_empty() {
        if let Err(err) = rollup::freeze_calls(rollup_path, &live, freezable) {
            eprintln!(
                "{BIN}: warning: calls of closed weeks not stored: {}",
                err.why()
            );
        }
    }
    live
}

/// Closed weeks `status` counts, besides the current one.
const SEEN_WEEKS: i64 = 4;

/// Seconds since the Monday `SEEN_WEEKS` weeks before this week's.
fn seen_window(now: u64) -> u64 {
    let today = day_of_seconds(now);
    let start = civil::week_start(today) - 7 * SEEN_WEEKS;
    now.saturating_sub(start as u64 * 86_400)
}

/// The label over `status`'s seen column. The four-week form only when the
/// counts reach back to the start of the oldest of the four closed weeks;
/// otherwise it says where they really start.
fn seen_label(now: u64, covered_since: Option<u64>) -> String {
    let Some(since) = covered_since else {
        return "seen (journal empty)".to_string();
    };
    if since <= now.saturating_sub(seen_window(now)) {
        "seen, last 4 weeks + this week".to_string()
    } else {
        format!("seen since {}", civil::iso(day_of_seconds(since)))
    }
}

/// The civil day a count of Unix seconds falls in.
fn day_of_seconds(seconds: u64) -> civil::Day {
    civil::Day::try_from(seconds / 86_400).unwrap_or(civil::Day::MAX)
}

fn unix_now() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |elapsed| elapsed.as_secs())
}

fn run_status() -> ExitCode {
    let w = ui::id_column(rule_table::RULES);
    let now = unix_now();
    let seen = journal::tally(seen_window(now));
    let counted = journal::path().map(|path| {
        greenbelay_guard::rollup::load(
            &journal::paths(),
            &greenbelay_guard::rollup::path_beside(&path),
        )
    });
    if let Some(counted) = &counted {
        report_rollup_problem(counted.problem.as_ref());
        if let Some(line) = rollup_failed_line(&counted.journal) {
            eprintln!("{line}");
        }
    }
    let since = seen_label(
        now,
        counted
            .as_ref()
            .and_then(greenbelay_guard::rollup::covered_since),
    );
    println!(
        "{:<w$}{:<10}{:<10}  {:<31}  {since}",
        "rule", "ships as", "now", "evidence"
    );
    for r in rule_table::RULES {
        let now = stance::resolve(r);
        println!(
            "{:<w$}{:<10}{:<10}  {:<31}  {}",
            r.id,
            r.default_stance.as_str(),
            now.as_str(),
            format!(
                "{:.1}/1000 measured {}",
                r.evidence.per_1000, r.evidence.measured
            ),
            describe_seen(seen.get(r.id))
        );
    }
    if let Some(p) = journal::path() {
        println!("\njournal: {}", p.display());
    }
    ExitCode::SUCCESS
}

/// One cell of the `seen` column.
///
/// The counts are what happened; the reason is why it did not. A rule whose
/// `confirm` declined a hundred times for `already in a linked worktree` is a
/// rule watching a convention being followed, and that is the sentence that
/// tells a reader whether the rule is precise or merely quiet.
fn describe_seen(seen: Option<&journal::Seen>) -> String {
    let Some(s) = seen.filter(|s| s.total() > 0) else {
        return "-".to_string();
    };
    let mut parts = Vec::new();
    for (n, what) in [
        (s.denied, "denied"),
        (s.advised, "advised"),
        (s.watched, "watched"),
    ] {
        if n > 0 {
            parts.push(format!("{n} {what}"));
        }
    }
    if s.unconfirmed > 0 {
        match s.top_reason() {
            // Records written before the reason was carried say `skipped`,
            // which is not a reason. Show the count and nothing invented.
            Some((why, n)) if why != "skipped" => parts.push(format!(
                "{} unconfirmed ({} \u{d7}{n})",
                s.unconfirmed,
                why.replace('_', " ")
            )),
            _ => parts.push(format!("{} unconfirmed", s.unconfirmed)),
        }
    }
    parts.join(", ")
}

fn run_corpus(args: &[OsString]) -> ExitCode {
    let f = match flags(args) {
        Ok(f) => f,
        Err(why) => {
            eprintln!("{BIN}: {why}");
            return ExitCode::from(2);
        }
    };
    match f.rest.first().map(String::as_str) {
        Some("check") | None => {}
        Some(other) => {
            eprintln!("{BIN}: corpus takes `check`, not `{other}`");
            return ExitCode::from(2);
        }
    }
    let mut healthy = true;
    let w = ui::id_column(rule_table::RULES);
    for rule in rule_table::RULES {
        let score = corpus::score_with(rule, Some(greenbelay_process::clear_boundary::stop_judge));
        if score.reviewed == 0 && score.unreviewed == 0 {
            println!("{:<w$}no cases yet", rule.id);
            continue;
        }
        let precision = match score.precision() {
            Some(p) => format!("{:.0}%", p * 100.0),
            None => "unmeasured".to_string(),
        };
        println!(
            "{:<w$}{} reviewed ({} negative), {} unreviewed, precision {precision}",
            rule.id, score.reviewed, score.negatives, score.unreviewed
        );
        for d in &score.disagreements {
            healthy = false;
            // The checkout's file when there is one; outside a checkout the
            // path the binary was built from means nothing on this disk.
            let path = corpus::path_for(rule.id);
            let shown = if path.exists() {
                path.display().to_string()
            } else {
                format!("{}.cases", rule.id)
            };
            match &d.fixture {
                Some(fixture) => println!(
                    "  {}:{} expected {} — {} ({fixture}): {}",
                    shown,
                    d.line,
                    d.expected.as_str(),
                    corpus::escape(&d.command),
                    d.why
                ),
                None => println!(
                    "  {}:{} expected {} — {}: {}",
                    shown,
                    d.line,
                    d.expected.as_str(),
                    corpus::escape(&d.command),
                    d.why
                ),
            }
        }
    }
    if healthy {
        ExitCode::SUCCESS
    } else {
        ExitCode::FAILURE
    }
}

fn run_graduate(args: &[OsString], promoting: bool) -> ExitCode {
    let f = match flags(args) {
        Ok(f) => f,
        Err(why) => {
            eprintln!("{BIN}: {why}");
            return ExitCode::from(2);
        }
    };
    let Some(id) = f.rest.first() else {
        eprintln!(concat!(greenbelay_guard::bin!(), ": name a rule"));
        return ExitCode::from(2);
    };
    let Some(rule) = rules::by_id(rule_table::RULES, id) else {
        let known: Vec<&str> = rule_table::RULES.iter().map(|r| r.id).collect();
        eprintln!("{BIN}: no rule `{id}` — known: {}", known.join(", "));
        return ExitCode::from(2);
    };
    let to = if promoting {
        let Some(to) = f.to.as_deref().and_then(rules::Stance::parse) else {
            eprintln!(concat!(
                greenbelay_guard::bin!(),
                ": graduate needs --to advise|deny"
            ));
            return ExitCode::from(2);
        };
        to
    } else {
        rules::Stance::Observe
    };

    let verdict = graduate::assess_score(
        rule,
        to,
        &corpus::score_with(rule, Some(greenbelay_process::clear_boundary::stop_judge)),
    );
    for (ok, line) in &verdict.lines {
        println!(
            "  {} {line}",
            if *ok {
                crate::ui::valid_sign()
            } else {
                crate::ui::error_sign()
            }
        );
    }
    if !verdict.allowed && !f.force {
        // The file to append to is the checkout's. An installed copy has no
        // checkout, and naming the path of the machine that built it would
        // send the reader to a directory that exists nowhere near them.
        let where_ = if corpus::checkout_present() {
            corpus::path_for(rule.id).display().to_string()
        } else {
            format!(
                concat!(
                    "crates/greenbelay-guard/tests/corpus/{}.cases   # in a checkout of ",
                    greenbelay_guard::bin!()
                ),
                rule.id
            )
        };
        eprintln!(
            concat!(
                "\nrefusing to move {} to {}: not enough evidence.\n\
             Review its matches first:\n  \
             ",
                greenbelay_guard::bin!(),
                " explain {} --format cases >> {}\n\
             then label each line and re-run. `--force` overrides and is recorded as forced."
            ),
            rule.id,
            to.as_str(),
            rule.id,
            where_
        );
        return ExitCode::from(2);
    }
    match graduate::set(rule, to) {
        Ok(()) => {
            println!(
                "{} is now `{}`{}",
                rule.id,
                to.as_str(),
                if verdict.allowed { "" } else { " (forced)" }
            );
            ExitCode::SUCCESS
        }
        Err(why) => {
            eprintln!("{BIN}: could not record the stance: {why}");
            ExitCode::from(2)
        }
    }
}

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

    fn args(list: &[&str]) -> Vec<OsString> {
        list.iter().map(OsString::from).collect()
    }

    #[test]
    fn each_command_gets_its_migration_mode() {
        assert_eq!(migration_mode(&Sub::Migrate, &[]), MigrationMode::Skip);
        assert_eq!(migration_mode(&Sub::Doctor, &[]), MigrationMode::Skip);
        assert_eq!(migration_mode(&Sub::Hook, &[]), MigrationMode::Zero);
        assert_eq!(migration_mode(&Sub::Status, &[]), MigrationMode::Zero);
        assert_eq!(migration_mode(&Sub::Uninstall, &[]), MigrationMode::Zero);
        for flag in ["--help", "-h", "--version", "--dry-run", "--check"] {
            assert_eq!(
                migration_mode(&Sub::PlanApply, &args(&[flag])),
                MigrationMode::Skip,
                "{flag}"
            );
            assert_eq!(
                migration_mode(&Sub::Install, &args(&["--write", flag])),
                MigrationMode::Skip,
                "{flag}"
            );
        }
    }

    #[test]
    fn install_waits_for_the_lock() {
        assert!(matches!(
            migration_mode(&Sub::Install, &args(&["--write"])),
            MigrationMode::Capped(_)
        ));
    }

    #[test]
    fn the_dumps_table_fits_80_columns() {
        use greenbelay_guard::output_audit::{DumpBucket, DumpClass, DumpOutput, DumpShape};
        let bucket = DumpBucket {
            calls: 12_345,
            result_bytes: 2_000_000_000,
            large: 234,
            large_bytes: 90_000_000,
            long_lines: 23,
            long_lines_bytes: 9_000_000,
            cut_by_read: 12,
            cut_by_read_bytes: 900_000,
            refused: 99,
            ..DumpBucket::default()
        };
        let map: std::collections::BTreeMap<DumpClass, DumpBucket> = [
            DumpShape::WholeOne,
            DumpShape::WholeMany,
            DumpShape::Window,
            DumpShape::WindowMany,
            DumpShape::Mixed,
        ]
        .into_iter()
        .map(|shape| {
            (
                DumpClass {
                    shape,
                    output: DumpOutput::Mixed,
                },
                bucket.clone(),
            )
        })
        .collect();
        let table = dumps_text("main conversation", &map);
        for line in table.lines() {
            assert!(line.chars().count() <= 80, "{} wide: {line}", line.len());
        }
        assert!(table.contains("window-many (mixed output)"), "{table}");
    }
}

#[cfg(test)]
mod rollup_tests {
    use super::*;
    use greenbelay_guard::rollup;

    #[test]
    fn rule_tool_has_an_entry_for_every_rule_and_assertion() {
        let ids = rule_table::RULES
            .iter()
            .map(|r| r.id)
            .chain(assertions::ASSERTIONS.iter().map(|a| a.id));
        for id in ids {
            assert!(
                rollup::rule_tool(id).is_some(),
                "`{id}` has no entry in rollup::RULE_TOOLS"
            );
        }
        let known: Vec<&str> = rule_table::RULES
            .iter()
            .map(|r| r.id)
            .chain(assertions::ASSERTIONS.iter().map(|a| a.id))
            .collect();
        for id in rollup::mapped_ids() {
            assert!(known.contains(&id), "RULE_TOOLS names `{id}`, no such rule");
        }
    }

    #[test]
    fn a_rule_with_a_bash_replay_maps_to_bash() {
        for rule in rule_table::RULES {
            let replay = backtest::Subject::Rule(rule).replay();
            if replay.why() != "not-shell" {
                assert_eq!(
                    rollup::rule_tool(rule.id),
                    Some(rollup::Tool::Bash),
                    "`{}` replays on Bash",
                    rule.id
                );
            }
        }
    }

    #[test]
    fn a_rollup_row_fits_in_eighty_columns_with_the_real_rule_column() {
        let width = ui::id_column(rule_table::RULES);
        let rule = rollup::RuleReport {
            rule: "screenshot-in-main-session".to_string(),
            denied: 1_234_567,
            advised: 0,
            watched: 0,
            unconfirmed: 0,
            tool: rollup::Tool::Bash,
            calls: Some(12_345_678),
            replay: "exact".to_string(),
        };
        let report = rollup::Report {
            covered_since: Some(0),
            weeks: vec![rollup::WeekReport {
                week: 19_674,
                partial: true,
                rules: vec![rule],
            }],
        };
        for line in report.to_text(width).lines() {
            assert!(line.chars().count() <= 80, "`{line}` is wider than 80");
        }
    }

    #[test]
    fn the_status_label_switches_only_when_coverage_allows() {
        // Wednesday 2023-11-15; the oldest closed week of four starts Monday
        // 2023-10-16.
        let now = 1_700_000_000 + 86_400;
        let window_start = 19_646u64 * 86_400;
        assert_eq!(
            seen_label(now, Some(window_start)),
            "seen, last 4 weeks + this week"
        );
        assert_eq!(
            seen_label(now, Some(window_start - 5)),
            "seen, last 4 weeks + this week"
        );
        assert_eq!(
            seen_label(now, Some(window_start + 1)),
            "seen since 2023-10-16"
        );
        assert_eq!(seen_label(now, None), "seen (journal empty)");
    }
}