greenbelay 6.3.1

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
//! The guard itself: payload in, decision out.
//!
//! ## The contract
//!
//! **Every failure path exits 0 having written nothing.** Unreadable payload,
//! unknown event, a tool that is not Bash, a command this crate's lexer cannot
//! parse, a working directory that no longer exists, a rule that panics, a
//! journal that cannot be written — all of them are silence.
//!
//! That is not defensiveness, it is the only posture that keeps the guard
//! installed. A hook that fails toward refusing gets in the way of work the
//! author knew was correct, and the fix a person reaches for at that moment is
//! to delete the whole thing from `settings.json`, which switches off every
//! rule at once. A hook that fails toward silence loses one firing.
//!
//! ## The order is a cost decision
//!
//! `examine` runs first and touches nothing. Only if something fires do we pay
//! for `git config` (one process per key) or `confirm` (one process, or a
//! directory read). This runs before every shell command the model issues, so
//! the no-fire path is the path that has to be free.

use std::io::{IsTerminal, Read};
use std::process::ExitCode;

use crate::assertions::{self, Assertion, Claim, Verdict};
use crate::decision::{self, Decision};
use crate::journal;
use crate::payload::{self, Bash, Event, Session};
use crate::rules::{self, Confirmed, Context, Finding, Rule, Stance};
use crate::shell::{self, Parsed, Simple};

pub fn run() -> ExitCode {
    // A person typing `amont-agent hook` with no payload would otherwise block
    // on stdin forever with no indication why.
    if std::io::stdin().is_terminal() {
        eprintln!(concat!(
            greenbelay_guard::bin!(),
            ": `hook` reads a Claude Code payload on stdin.\n\
             Try `",
            greenbelay_guard::bin!(),
            " check '<command>'` to test a command by hand."
        ));
        return ExitCode::from(2);
    }

    let mut raw = String::new();
    if std::io::stdin().read_to_string(&mut raw).is_err() {
        return Decision::Silent.emit();
    }

    // A panic anywhere below is a bug in this crate, and a bug in this crate
    // must not become a refused command or a broken session.
    let decided = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| decide(&raw)));
    match decided {
        Ok(d) => d.emit(),
        Err(_) => {
            eprintln!(concat!(
                greenbelay_guard::bin!(),
                ": internal error; allowing the command through"
            ));
            Decision::Silent.emit()
        }
    }
}

/// `ask-unopened-page`: a question that names a local page nobody opened for
/// the person. The stance is looked up only once a page is named.
fn ask_unopened_page(ask: &payload::Ask) -> Decision {
    use greenbelay_guard::page_open::{self, Verdict};
    let rule = &rules::ask_unopened_page::RULE;
    let (pages, why) = match page_open::judge(ask) {
        Verdict::Shown => return Decision::Silent,
        Verdict::Unopened(pages) => (pages, None),
        Verdict::Unknown { pages, why } => (pages, Some(why)),
    };
    let stance = crate::stance::resolve(rule);
    if stance == Stance::Observe {
        return Decision::Silent;
    }
    let commands = page_open::commands(&pages);
    match why {
        Some(why) => Decision::Advise(decision::phrase(
            rule.id,
            &format!(
                "this question names a page the hook cannot tell was opened for the person ({why}). \
                 A URL or a path in a question does not show it (`work.page-shown-before-asked`). \
                 If it was not opened, open it before asking:\n{commands}"
            ),
            "",
        )),
        None => {
            let text = decision::phrase(
                rule.id,
                &format!(
                    "this question names a page that was never opened for the person. A URL or a path in a question does not show it (`work.page-shown-before-asked`). \
                     Open each page, one command per page, then ask the question again:\n{commands}"
                ),
                "",
            );
            if stance == Stance::Deny {
                Decision::Deny(text)
            } else {
                Decision::Advise(text)
            }
        }
    }
}

/// A turn ending. `clear-at-boundary` asks for the plan's state only past
/// 200k, within one deadline shared with its repository checks. `Working` is
/// in flight, so only `plan-phases-open` judges it; at `PlanOnly` past 200k
/// `clear-at-boundary` judges first, and when its Continue spoke,
/// `plan-phases-open` stays silent for the rest of the turn.
fn on_stop(stop: &payload::Stop) -> Decision {
    use crate::clear_boundary;
    use crate::plan_phases::PhaseFact;
    let deadline = std::time::Instant::now() + clear_boundary::DEADLINE;
    let clear = clear_boundary::on_stop(
        stop,
        || crate::plan_phases::open_phase(stop, deadline),
        deadline,
        || crate::stance::resolve(&rules::clear_at_boundary::RULE),
    );
    if !matches!(clear, Decision::Silent) {
        return clear;
    }
    // The state file is read first: only a turn the rule spoke in pays for
    // the git calls of `open_phase`.
    if clear_boundary::spoke_this_turn(stop)
        && crate::plan_phases::open_phase(stop, deadline) == PhaseFact::PlanOnly
    {
        return Decision::Silent;
    }
    crate::plan_phases::on_stop(stop, || {
        crate::stance::resolve(&rules::plan_phases_open::RULE)
    })
}

fn decide(raw: &str) -> Decision {
    // Name the session before any stance is looked up (ADR-0042 shadow arm).
    if let Some(session) = serde_json::from_str::<serde_json::Value>(raw)
        .ok()
        .and_then(|v| v.get("session_id")?.as_str().map(str::to_string))
    {
        greenbelay_guard::shadow::enter_session(&session);
    }
    match payload::parse(raw) {
        Event::SessionStart(session) => {
            // The fact that we ran is what `doctor` uses to tell "no rule
            // fired" apart from "the guard is dead". Written first, so a slow
            // fetch below can never cost the heartbeat.
            heartbeat();
            crate::session_state::sweep();
            if session.source == "compact" {
                crate::session_state::compact(&session.session);
            }
            crate::preview::sweep();
            crate::plan_phases::sweep();
            crate::clear_boundary::sweep();
            if session.source == "clear" {
                crate::clear_boundary::on_session_start_clear(&session.session, &session.cwd);
            }
            crate::attestations::sweep();
            on_session_start(&session)
        }
        Event::NotOurs => Decision::Silent,
        Event::Prompt(prompt) => {
            crate::preview::on_prompt(&prompt);
            crate::plan_phases::on_prompt(&prompt);
            Decision::Silent
        }
        Event::PreAsk(ask) => {
            crate::implementation_review::on_pre_ask(&ask);
            let stance = crate::stance::resolve(&crate::push_preview::RULE);
            match crate::preview::on_pre_ask(&ask, stance) {
                Some(why) => {
                    Decision::Deny(decision::phrase(crate::push_preview::RULE.id, &why, ""))
                }
                None => ask_unopened_page(&ask),
            }
        }
        Event::PrePlanExit(plan) => {
            let stance = crate::stance::resolve(&rules::plan_review_panel::RULE);
            let paths = crate::stance::resolve(&rules::plan_names_no_paths::RULE);
            crate::plan_review::on_plan_exit(&plan, stance, paths)
        }
        Event::PostPlanExit(plan) => {
            crate::preview::on_plan_answered(&plan);
            crate::review_outcomes::on_plan_answered(&plan);
            Decision::Silent
        }
        Event::PostAsk(ask) => {
            let mut said: Vec<String> = Vec::new();
            crate::preview::on_post_ask(&ask);
            if let Some(text) = crate::implementation_review::on_post_ask(&ask) {
                if crate::stance::resolve(&crate::implementation_review_rule::RULE)
                    != Stance::Observe
                {
                    said.push(decision::phrase(
                        crate::implementation_review_rule::RULE.id,
                        &text,
                        "",
                    ));
                }
            }
            if said.is_empty() {
                Decision::Silent
            } else {
                Decision::Assert(said.join("\n\n"))
            }
        }
        Event::Stop(stop) => on_stop(&stop),
        Event::PreFile(op) => on_pre_file(&op),
        Event::PreGrep(op) => on_grep(&op),
        Event::PreScreenshot(op) => on_screenshot(&op),
        Event::PreRelaisRun(op) => on_relais_run(&op),
        Event::PostLsp(call) => on_post_lsp(&call),
        Event::PostFile(op) => on_post_file(&op),
        Event::PostWrite(op) => on_post_write(&op),
        Event::PreBash(bash) => {
            let decision = on_bash(&bash);
            record_bash_activity(&bash);
            decision
        }
        Event::PostBash(bash) => on_post_bash(&bash),
        Event::PostBashFailure(bash) => on_post_bash_failure(&bash),
    }
}

/// The environment variable that replaces the clock the activity record and
/// `work-overlap` read, as epoch seconds. For tests: the hook is a process per
/// call, so a test cannot pass a clock any other way.
const ENV_NOW: &str = greenbelay_guard::env_var!("TEST_NOW");

fn clock() -> std::time::SystemTime {
    std::env::var(ENV_NOW)
        .ok()
        .and_then(|seconds| seconds.trim().parse::<u64>().ok())
        .map_or_else(std::time::SystemTime::now, |seconds| {
            std::time::UNIX_EPOCH + std::time::Duration::from_secs(seconds)
        })
}

/// A Read, Edit, Write, MultiEdit or NotebookEdit about to run. A write also
/// asks `work-overlap` and then records where the session works; the record
/// comes after the decision and never changes it.
fn on_pre_file(op: &crate::payload::FileOp) -> Decision {
    let decision = on_file(op);
    if !op.writes || crate::stance::switched_off() {
        return decision;
    }
    let Some(place) = op.path.parent().and_then(crate::activity::resolve) else {
        return decision;
    };
    let now = clock();
    let overlap = work_overlap(op, &place, now);
    record_activity(&op.session, &place, now, &op.permission_mode, &op.cwd);
    combine([decision, overlap])
}

/// A git command that changes where the session works records its place.
fn record_bash_activity(bash: &Bash) {
    if crate::stance::switched_off() {
        return;
    }
    let now = clock();
    for target in crate::activity::bash_targets(&bash.command, &bash.cwd) {
        if let Some(place) = crate::activity::resolve(&target) {
            record_activity(&bash.session, &place, now, &bash.permission_mode, &bash.cwd);
        }
    }
}

/// Keep the session's activity; a failure is journalled once per session and
/// then ignored.
fn record_activity(
    session: &str,
    place: &crate::activity::Place,
    now: std::time::SystemTime,
    mode: &str,
    cwd: &std::path::Path,
) {
    let (key, outcome, excerpt) = match crate::activity::record(session, place, now) {
        Ok(crate::activity::Recorded::Whole) => return,
        Ok(crate::activity::Recorded::TrimFailed) => (
            "activity-untrimmed",
            "untrimmed",
            crate::activity::Recorded::TRIM_FAILED_REASON,
        ),
        Err(failure) => ("activity-unrecorded", "unrecorded", failure.as_str()),
    };
    if matches!(crate::lsp::told(session, key), crate::lsp::Told::First) {
        journal::record(&journal::Entry {
            rule: rules::work_overlap::RULE.id,
            stance: "-",
            outcome,
            session,
            repo: &repo_name(cwd),
            mode,
            excerpt,
        });
    }
}

/// The session's first write in a repository, while another session was last
/// seen working there within the window: told once per session and repository,
/// counted from the first write that finds a live peer.
fn work_overlap(
    op: &crate::payload::FileOp,
    place: &crate::activity::Place,
    now: std::time::SystemTime,
) -> Decision {
    let rule = &rules::work_overlap::RULE;
    let key = format!("work-overlap {}", place.repo_identity.display());
    if crate::lsp::was_told(&op.session, &key) {
        return Decision::Silent;
    }
    // The horizon, not the configured window, bounds this first pass: the
    // window is a `git config` read, paid only once a peer is in the repository.
    let horizon = now
        .checked_sub(crate::activity::HORIZON)
        .unwrap_or(std::time::UNIX_EPOCH);
    let candidates = crate::activity::peers_in(&op.session, &place.repo_identity, horizon);
    if candidates.is_empty() {
        return Decision::Silent;
    }
    let window = greenbelay_guard::gitconfig::duration_or(
        greenbelay_guard::config_key!("work-overlap.window"),
        crate::activity::DEFAULT_WINDOW,
    );
    let live: Vec<crate::activity::Peer> = candidates
        .into_iter()
        .filter(|peer| peer.is_live(now, window))
        .collect();
    let Some(freshest) = live.first() else {
        return Decision::Silent;
    };
    // Consumed only here, once a live peer is found: a session that met no
    // peer is told when one appears.
    if matches!(
        crate::lsp::told(&op.session, &key),
        crate::lsp::Told::Before
    ) {
        return Decision::Silent;
    }
    let stance = crate::stance::resolve(rule);
    note_file(
        rule,
        stance,
        op,
        &format!("{} in {}", freshest.session, freshest.worktree.display()),
    );
    match stance {
        Stance::Observe => Decision::Silent,
        // The ceiling is advise (`max_stance`); a deny stance still advises.
        Stance::Advise | Stance::Deny => {
            Decision::Advise(rules::work_overlap::phrase(&place.repo_name(), &live, now))
        }
    }
}

/// Where the checkout stands against the remote, stated once per session.
///
/// Governed by the `stale-base` rule's stance, so one key silences both the
/// notice and the branch-creation rule: `observe` measures and journals but
/// says nothing; anything above it speaks. There is nothing to refuse at a
/// session opening, so `deny` speaks exactly like `advise` here.
fn on_session_start(session: &Session) -> Decision {
    if !session.cwd.is_dir() {
        return Decision::Silent;
    }
    let mut lines: Vec<String> = Vec::new();
    if let Some(line) = stale_checkout_notice(session) {
        lines.push(line);
    }
    if let Some(line) = crate::guidance::notice(&session.cwd) {
        lines.push(line);
    }
    if let Some(line) = crate::shim::notice() {
        lines.push(line);
    }
    if let Some(line) = crate::plans::notice(&session.cwd) {
        lines.push(line);
    }
    if let Some(line) = inbox_notice(session) {
        lines.push(line);
    }
    if lines.is_empty() {
        Decision::Silent
    } else {
        Decision::Context(lines.join("\n\n"))
    }
}

/// The unfiled inbox lines, at a `startup` or `clear` only, governed by the
/// `clear-at-boundary` stance: `observe` journals the counts and says nothing.
fn inbox_notice(session: &Session) -> Option<String> {
    if !matches!(session.source.as_str(), "startup" | "clear") {
        return None;
    }
    if !session.cwd.is_dir() {
        return None;
    }
    let common = greenbelay_guard::git::stdout_in(
        &session.cwd,
        &["rev-parse", "--path-format=absolute", "--git-common-dir"],
    )
    .filter(|dir| !dir.is_empty())?;
    let inbox_dir = std::path::PathBuf::from(common).join("greenharness");
    // No inbox directory: nothing was ever appended, so no clock is read.
    if !inbox_dir.is_dir() {
        return None;
    }
    let rule = &rules::clear_at_boundary::RULE;
    let stance = crate::stance::resolve(rule);
    let today = greenbelay_guard::civil::day_of(&local_date(&session.cwd)?)?;
    let found = greenbelay_process::inbox::notice(
        &inbox_dir.join("inbox.md"),
        stance,
        today,
        std::time::SystemTime::now(),
    )?;
    let outcome = match stance {
        Stance::Observe => "watched",
        Stance::Advise | Stance::Deny => "advised",
    };
    journal::record(&journal::Entry {
        rule: rule.id,
        stance: stance.as_str(),
        outcome,
        session: &session.session,
        repo: &repo_name(&session.cwd),
        mode: "-",
        excerpt: &format!(
            "session start {}: orphans {}, fresh {}, being filed {}",
            session.source, found.orphans, found.fresh, found.being_filed
        ),
    });
    found.text
}

/// How long `date +%F` may take before the inbox block is given up.
const LOCAL_DATE_DEADLINE: std::time::Duration = std::time::Duration::from_millis(500);

/// The local calendar day, `YYYY-MM-DD`, from `date +%F`: the clock the inbox
/// writers date their lines by. A `date` that fails or hangs past
/// [`LOCAL_DATE_DEADLINE`] is `None`, and the block is left out.
fn local_date(dir: &std::path::Path) -> Option<String> {
    match run_with_deadline(
        std::ffi::OsStr::new("date"),
        &["+%F"],
        dir,
        LOCAL_DATE_DEADLINE,
    ) {
        Ran::Exited {
            code: Some(0),
            stdout,
        } => Some(stdout.trim().to_string()),
        Ran::Exited { .. } | Ran::TimedOut | Ran::Failed(_) => None,
    }
}

/// The stale-checkout half of the session notice. `None` is silence —
/// up to date, not a repository, or the rule is only observing.
fn stale_checkout_notice(session: &Session) -> Option<String> {
    let rule = &rules::stale_base::RULE;
    let stance = crate::stance::resolve(rule);
    let drift = crate::stale::measure(&session.cwd, "HEAD")?;
    if drift.behind == 0 {
        return None;
    }
    let outcome = match stance {
        Stance::Observe => "watched",
        Stance::Advise | Stance::Deny => "advised",
    };
    journal::record(&journal::Entry {
        rule: rule.id,
        stance: stance.as_str(),
        outcome,
        session: &session.session,
        repo: &drift.repo,
        mode: "-",
        excerpt: &format!("session start: {} behind {}", drift.behind, drift.base),
    });
    match stance {
        Stance::Observe => None,
        Stance::Advise | Stance::Deny => Some(format!(
            concat!(greenbelay_guard::bin!(), "/{}: {}"),
            rule.id,
            crate::stale::notice(&drift)
        )),
    }
}

fn on_bash(bash: &Bash) -> Decision {
    let parsed = shell::lex(&bash.command);
    // A pass file of the implementation review is written by the hook
    // alone. A command that would write there is refused before any stance
    // is consulted: there is no legitimate writer to advise, and `observe`
    // turns a rule off, not a boundary. A read of the record passes.
    if let Some(span) = crate::implementation_review::store_clause(&parsed) {
        let rule = &crate::implementation_review_rule::RULE;
        journal::record(&journal::Entry {
            rule: rule.id,
            stance: "deny",
            outcome: "denied",
            session: &bash.session,
            repo: &repo_name(&bash.cwd),
            mode: &bash.permission_mode,
            excerpt: &crate::backtest::excerpt(&bash.command, span.start, span.end),
        });
        return Decision::Deny(decision::phrase(
            rule.id,
            crate::implementation_review::GUARD_REASON,
            crate::implementation_review::GUARD_REMEDY,
        ));
    }
    // When a `preview register` call started, for `preview::bind` to tell
    // its own output from a line an earlier clause printed.
    crate::preview::stamp_register(bash, &parsed);
    // No early return on `Parsed::Opaque`: `rules::evaluate` owns that
    // policy, so the hook, `check` and the backtester cannot drift apart on
    // it. Legacy rules are skipped on an unreadable command exactly as they
    // were; a rule built on the shell analysis judges it with its own account
    // of what it could not read.
    let input = rules::Input::new(&bash.command, rules::tool_shell::dialect(), &parsed);
    let fired = rules::evaluate(crate::rule_table::RULES, &input);
    let dumped = rules::dump::dumps(&parsed);
    if fired.is_empty() && dumped.is_empty() {
        // The whole no-fire path: one lex, no processes, no files.
        return Decision::Silent;
    }

    // A pipeline we could not read is recorded even when nothing fires: a
    // guard that says nothing must stay distinguishable from a guard that
    // could not look, and this is the only place that difference is written
    // down.
    for cmd in parsed.hidden() {
        if let Some(why) = &cmd.opaque {
            journal::record(&journal::Entry {
                rule: "-",
                stance: "-",
                outcome: "partial",
                session: &bash.session,
                repo: &repo_name(&bash.cwd),
                mode: &bash.permission_mode,
                excerpt: &why.why(),
            });
            break;
        }
    }

    let mut deny: Vec<String> = Vec::new();
    let mut advise: Vec<String> = Vec::new();

    // A `cat`-shaped dump is a read the session should remember, and may be
    // one it already made.
    if !bash.background {
        for d in &dumped {
            let ctx = Context {
                platform: Some(crate::rules::Platform::host()),
                cwd: &bash.cwd,
                parsed: &parsed,
                background: bash.background,
                timeout_ms: bash.timeout_ms,
                tool_use_id: &bash.tool_use_id,
                transcript: bash.transcript.as_deref(),
                agent_transcript: bash.agent_transcript.as_deref(),
                command: &bash.command,
                output: None,
                session: &bash.session,
                failed: false,
            };
            if writes_or_waits(&ctx, d) {
                continue;
            }
            let path = resolve_path(&ctx.cwd_at(d.at), &d.path);
            let verdict = reread_verdict(
                &bash.session,
                bash.agent_id.as_deref(),
                &path,
                &d.window,
                &bash.permission_mode,
                &bash.cwd,
                &d.path,
            );
            if let Some(text) = verdict.text {
                match verdict.stance {
                    Stance::Deny => deny.push(text),
                    Stance::Advise => advise.push(text),
                    Stance::Observe => {}
                }
            }
            // The read itself is remembered by `on_post_bash`, once the
            // command has actually run: a `cat` that is refused below, or that
            // fails on a path that is not there, put nothing in context.
        }
    }

    // Refuse-once refusals, phrased after the loop (see `alone` below), and
    // the files this command already dumped, so `cat a; cat a` is one decision.
    let mut refused_once: Vec<(&'static str, String, String)> = Vec::new();
    let mut settled: std::collections::HashSet<std::path::PathBuf> =
        std::collections::HashSet::new();
    for (rule, finding) in &fired {
        let is_grep = rule.id == rules::symbol_grep_not_lsp::RULE.id;
        let (stance, source) = if is_grep {
            crate::stance::resolve_for(rule, &bash.agent)
        } else {
            (
                crate::stance::resolve(rule),
                crate::stance::Source::Configured,
            )
        };
        let Confirmation {
            floor,
            ceiling,
            said,
        } = match confirmed(rule, stance, finding, bash, &parsed) {
            Ok(c) => c,
            Err(why) => {
                // The reason is the record. `status` tallies these, and "why did
                // confirm say no" is the number that decides whether an observing
                // rule may ever advise — a rule declined for `already in a linked
                // worktree` a thousand times is a rule being obeyed, not one that
                // is wrong. A live rule's `examine` lets nearly every command
                // through, so its declines are not a signal, only a line per
                // Bash call.
                if !matches!(rule.examine, rules::Examine::Live(_)) {
                    note(rule, "unconfirmed", why, bash, finding);
                }
                continue;
            }
        };
        let grep_pattern = if is_grep {
            match grep_gate(bash, &parsed, finding, stance) {
                Ok(pattern) => pattern,
                Err(why) => {
                    note(rule, "unconfirmed", why, bash, finding);
                    continue;
                }
            }
        } else {
            String::new()
        };
        // A `confirm` that learned the reason by looking speaks and journals
        // it in place of the finding's; every other rule keeps the finding's
        // reason and the command span.
        let (reason, excerpt, remedy): (&str, Option<&str>, &str) = match &said {
            Some((reason, excerpt, remedy)) => (
                reason.as_str(),
                Some(excerpt.as_str()),
                remedy.as_deref().unwrap_or(&finding.remedy),
            ),
            None => (finding.reason.as_str(), None, finding.remedy.as_str()),
        };
        let stance = final_stance(
            stance,
            floor,
            ceiling,
            reading_for(rule, &parsed),
            rule.max_stance,
        );
        // The telling follows `final_stance`: a floor or a ceiling may have
        // moved the stance, and the key recorded is the one that is spoken.
        let stance = if is_grep {
            match grep_telling(
                &bash.session,
                &grep_pattern,
                bash.agent_id.as_deref(),
                stance,
                source,
                &bash.cwd,
                &bash.permission_mode,
            ) {
                Some(spoken) => spoken,
                None => {
                    note(
                        rule,
                        "unconfirmed",
                        "this session was told about this pattern",
                        bash,
                        finding,
                    );
                    continue;
                }
            }
        } else {
            stance
        };
        let remedy = if is_grep && is_denial_by_agent(stance, source) {
            rules::symbol_grep_not_lsp::DENY_REMEDY
        } else {
            remedy
        };
        let text = decision::phrase(rule.id, reason, remedy);
        match stance {
            Stance::Observe => note_with(rule, "observe", "watched", bash, finding, excerpt),
            Stance::Advise => {
                note_with(rule, "advise", "advised", bash, finding, excerpt);
                advise.push(text);
            }
            Stance::Deny => match once_target(rule, finding, bash, &parsed) {
                OnceTarget::Always => {
                    note_with(rule, "deny", "denied", bash, finding, excerpt);
                    deny.push(text);
                }
                // Journalled `unrecorded` where it was found, once.
                OnceTarget::Unresolved => advise.push(text),
                // A file this command already dumped earlier was decided there.
                OnceTarget::File { path, .. } if !settled.insert(crate::lsp::normal(&path)) => {}
                OnceTarget::File { path, cwd } => match refuse_once_at(
                    rule,
                    &bash.session,
                    bash.agent_id.as_deref(),
                    &cwd,
                    &bash.permission_mode,
                    &path,
                ) {
                    Once::Refuse => {
                        note_with(rule, "deny", "denied", bash, finding, excerpt);
                        refused_once.push((rule.id, reason.to_string(), remedy.to_string()));
                    }
                    // Journalled by `refuse_once_at`.
                    Once::Allowed => {}
                    Once::Unrecorded => advise.push(text),
                },
            },
        }
    }
    // The way through a refuse-once refusal is the same command again; it
    // is promised only when no other rule refuses that command too.
    let alone = deny.is_empty();
    for (id, reason, remedy) in refused_once {
        let through = if alone {
            "If you need the whole file in the result, repeat this same command unchanged: it \
             will be allowed."
        } else {
            "Repeated unchanged, this rule lets the command through; the other refusal here \
             still stands."
        };
        deny.push(decision::phrase(
            id,
            &format!("{reason} {}", rules::REFUSED_ONCE),
            &format!("{remedy} {through}"),
        ));
    }

    // Where each branch destination stands before the push, for
    // `push-published` to compare against once it has run. Only a push that
    // is going to run is worth remembering.
    if deny.is_empty() {
        crate::preview::record_before(bash, &parsed);
    }

    // A refusal outranks advice: there is no point advising about a command
    // that is not going to run. The advisory findings are still journalled.
    if !deny.is_empty() {
        Decision::Deny(deny.join("\n\n"))
    } else if !advise.is_empty() {
        Decision::Advise(advise.join("\n\n"))
    } else {
        Decision::Silent
    }
}

/// The call's stdout and stderr joined by a newline, or `None` when it has neither.
fn joined_output(bash: &Bash) -> Option<String> {
    match (bash.stdout.as_deref(), bash.stderr.as_deref()) {
        (None, None) => None,
        (Some(o), None) => Some(o.to_string()),
        (None, Some(e)) => Some(e.to_string()),
        (Some(o), Some(e)) => Some(format!("{o}\n{e}")),
    }
}

/// A call that has already run and reported success.
///
/// The shape mirrors `on_bash` deliberately — lex, pure prefilter, and only
/// then anything that touches the world — because this fires after EVERY
/// successful Bash call, of every session on the machine. A user-scope hook is
/// not per-project: two other sessions' commands arrive here too, which is also
/// why every answer is taken from the payload's `cwd` and never from this
/// process's own.
///
/// There is nothing left to refuse, so `deny` speaks like `advise`, the same
/// way it does at a session opening.
fn on_post_bash(bash: &Bash) -> Decision {
    let claims = on_post_bash_claims(bash);
    match (claims, suppressions_after_bash(bash)) {
        (Decision::Assert(a), Some(b)) => Decision::Assert(format!("{a}\n\n{b}")),
        (Decision::Silent, Some(b)) => Decision::Assert(b),
        (
            claims @ (Decision::Advise(_)
            | Decision::Deny(_)
            | Decision::Ask(_)
            | Decision::Context(_)
            | Decision::AssertAfterFailure(_)
            | Decision::Continue(_)
            | Decision::UserNote(_)),
            Some(_),
        ) => claims,
        (claims, None) => claims,
    }
}

/// The claims a successful call made, checked against the world.
fn on_post_bash_claims(bash: &Bash) -> Decision {
    let parsed = shell::lex(&bash.command);
    if matches!(parsed, Parsed::Opaque(_)) {
        return Decision::Silent;
    }
    // A `preview register` that ran on its own is bound to this session and
    // prompt here, from its printed output. One that did not bind says so —
    // even run in the background, which is one of the reasons it cannot.
    let unbound = crate::preview::bind(bash, &parsed)
        .map(|t| decision::phrase(crate::push_preview::RULE.id, &t, ""));
    if bash.background {
        // Detached: the tool call returned a task id, not a result. Whatever it
        // claimed has not finished happening.
        return unbound.map_or(Decision::Silent, Decision::Assert);
    }

    let output = joined_output(bash);
    let ctx = Context {
        platform: Some(crate::rules::Platform::host()),
        cwd: &bash.cwd,
        parsed: &parsed,
        background: bash.background,
        timeout_ms: bash.timeout_ms,
        tool_use_id: &bash.tool_use_id,
        transcript: bash.transcript.as_deref(),
        agent_transcript: bash.agent_transcript.as_deref(),
        command: &bash.command,
        output: output.as_deref(),
        session: &bash.session,
        failed: false,
    };

    // A `cat`-shaped dump that has now run is a read the session should
    // remember. It needs the whole command: a path recorded from a half-read
    // line would have `file-reread` advise, later, about a file the session
    // may never have read.
    if parsed.fully_read() {
        if let Some(agent) = crate::lsp::agent_key(bash.agent_id.as_deref()) {
            let delivered = bash_delivered_whole(bash);
            for d in rules::dump::dumps(&parsed) {
                let path = resolve_path(&ctx.cwd_at(d.at), &d.path);
                let certain = delivered
                    && d.window != crate::session_state::INEXACT
                    && rules::dump::runs_unconditionally(&bash.command, d.at);
                crate::session_state::record(
                    &bash.session,
                    &agent,
                    "read",
                    &path,
                    &d.window,
                    certain,
                );
            }
        }
    }

    let claimed = assertions::examine_all(&parsed);
    if claimed.is_empty() {
        // The whole no-claim, no-dump path: one lex, no processes, no files.
        return unbound.map_or(Decision::Silent, Decision::Assert);
    }

    let mut spoken: Vec<String> = unbound.into_iter().collect();
    for (assertion, claim) in &claimed {
        let stance = crate::stance::resolve_assertion(assertion);
        match (assertion.verify)(&ctx, claim) {
            Verdict::Unknown(why) => {
                note_claim(assertion, "unverified", why, bash, claim);
            }
            Verdict::Held => note_claim(assertion, stance.as_str(), "held", bash, claim),
            Verdict::Noted(outcome) => note_claim(assertion, stance.as_str(), outcome, bash, claim),
            Verdict::Broken { reason, remedy } => {
                note_claim(assertion, stance.as_str(), "broken", bash, claim);
                if stance != Stance::Observe {
                    spoken.push(decision::phrase(assertion.id, &reason, &remedy));
                }
            }
        }
    }

    if spoken.is_empty() {
        Decision::Silent
    } else {
        Decision::Assert(spoken.join("\n\n"))
    }
}

/// A Bash call that FAILED: only [`assertions::AFTER_FAILURE`] run, with the
/// same verdict handling as [`on_post_bash`]. A detached call has not ended.
fn on_post_bash_failure(bash: &Bash) -> Decision {
    let claims = on_post_bash_failure_claims(bash);
    match (claims, suppressions_after_bash(bash)) {
        (Decision::AssertAfterFailure(a), Some(b)) => {
            Decision::AssertAfterFailure(format!("{a}\n\n{b}"))
        }
        (Decision::Silent, Some(b)) => Decision::AssertAfterFailure(b),
        (
            claims @ (Decision::Advise(_)
            | Decision::Deny(_)
            | Decision::Ask(_)
            | Decision::Context(_)
            | Decision::Assert(_)
            | Decision::Continue(_)
            | Decision::UserNote(_)),
            Some(_),
        ) => claims,
        (claims, None) => claims,
    }
}

fn on_post_bash_failure_claims(bash: &Bash) -> Decision {
    if bash.background {
        return Decision::Silent;
    }
    let parsed = shell::lex(&bash.command);
    if !parsed.fully_read() {
        return Decision::Silent;
    }
    let claimed = assertions::after_failure(&parsed);
    if claimed.is_empty() {
        return Decision::Silent;
    }
    // The failure text is the top-level `error` string, after stdout and stderr.
    let output = [
        joined_output(bash),
        bash.error.clone().filter(|e| !e.is_empty()),
    ]
    .into_iter()
    .flatten()
    .reduce(|acc, e| format!("{acc}\n{e}"));
    let ctx = Context {
        platform: Some(crate::rules::Platform::host()),
        cwd: &bash.cwd,
        parsed: &parsed,
        background: bash.background,
        timeout_ms: bash.timeout_ms,
        tool_use_id: &bash.tool_use_id,
        transcript: bash.transcript.as_deref(),
        agent_transcript: bash.agent_transcript.as_deref(),
        command: &bash.command,
        output: output.as_deref(),
        session: &bash.session,
        failed: true,
    };
    let mut spoken = Vec::new();
    for (assertion, claim) in &claimed {
        let stance = crate::stance::resolve_assertion(assertion);
        match (assertion.verify)(&ctx, claim) {
            Verdict::Unknown(why) => note_claim(assertion, "unverified", why, bash, claim),
            Verdict::Held => note_claim(assertion, stance.as_str(), "held", bash, claim),
            Verdict::Noted(outcome) => note_claim(assertion, stance.as_str(), outcome, bash, claim),
            Verdict::Broken { reason, remedy } => {
                note_claim(assertion, stance.as_str(), "broken", bash, claim);
                if stance != Stance::Observe {
                    spoken.push(decision::phrase(assertion.id, &reason, &remedy));
                }
            }
        }
    }
    if spoken.is_empty() {
        Decision::Silent
    } else {
        Decision::AssertAfterFailure(spoken.join("\n\n"))
    }
}

/// How long the after-Bash suppression check gets, git included.
const SUPPRESSIONS_DEADLINE: std::time::Duration = std::time::Duration::from_secs(1);
/// The most changed files the after-Bash suppression check examines.
const SUPPRESSIONS_MAX_FILES: usize = 50;

/// A Bash call that may have left a lint suppression in the working tree: the
/// tree is compared with HEAD and what it adds is told, once per
/// session. A command naming no suppression keyword costs no process. Every
/// failure is journalled (`bash-slow`, `bash-git`, `bash-cap`) and silent, and
/// so is a HEAD blob that is not UTF-8 (`bash-skip`): the commit gate is the
/// backstop. The answer is the text to tell, if any.
fn suppressions_after_bash(bash: &Bash) -> Option<String> {
    use rules::lint_suppression_added as lsa;
    if bash.background || !lsa::command_names_marker(&bash.command.to_ascii_lowercase()) {
        return None;
    }
    if matches!(shell::lex(&bash.command), Parsed::Opaque(_)) {
        return None;
    }
    let rule = &lsa::RULE;
    let stance = crate::stance::resolve(rule);
    let repo = repo_name(&bash.cwd);
    let journal_outcome = |outcome: &str, excerpt: &str| {
        journal::record(&journal::Entry {
            rule: rule.id,
            stance: stance.as_str(),
            outcome,
            session: &bash.session,
            repo: &repo,
            mode: &bash.permission_mode,
            excerpt,
        });
    };
    let deadline = std::time::Instant::now() + SUPPRESSIONS_DEADLINE;
    let failure = |what: &str| {
        let outcome = if std::time::Instant::now() >= deadline {
            "bash-slow"
        } else {
            "bash-git"
        };
        journal_outcome(outcome, what);
    };
    let Some(top) = greenbelay_guard::git::stdout_bounded(
        &bash.cwd,
        &["rev-parse", "--show-toplevel"],
        deadline,
    ) else {
        failure("rev-parse");
        return None;
    };
    let root = std::path::PathBuf::from(top);
    let Some(status) = greenbelay_guard::git::bytes_bounded(
        &root,
        &["status", "--porcelain=v1", "-z", "--untracked-files=all"],
        None,
        deadline,
    ) else {
        failure("status");
        return None;
    };
    let files = changed_examined_files(&status);
    if files.is_empty() {
        return None;
    }
    if files.len() > SUPPRESSIONS_MAX_FILES {
        journal_outcome("bash-cap", &format!("{} files", files.len()));
        return None;
    }

    // The HEAD side, not the index: a `sed -i … && git add` stages its
    // suppression, and an index comparison would then see nothing. Sizes
    // first, so no blob over the rule's read limit is read. A renamed or
    // deleted file is read at its old path.
    let tracked: Vec<String> = files
        .iter()
        .filter_map(|f| f.before_path().map(|path| format!("HEAD:{path}")))
        .collect();
    let mut oversize: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut unborn: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut before_blobs: std::collections::HashMap<String, Vec<u8>> =
        std::collections::HashMap::new();
    if !tracked.is_empty() {
        let mut input = Vec::new();
        for name in &tracked {
            input.extend_from_slice(name.as_bytes());
            input.push(b'\n');
        }
        let Some(sizes) = greenbelay_guard::git::bytes_bounded(
            &root,
            &["cat-file", "--batch-check=%(objectsize)"],
            Some(&input),
            deadline,
        ) else {
            failure("cat-file");
            return None;
        };
        let sizes = String::from_utf8_lossy(&sizes).into_owned();
        let answers: Vec<&str> = sizes.lines().collect();
        if answers.len() != tracked.len() {
            failure("cat-file");
            return None;
        }
        let mut readable = Vec::new();
        for (name, answer) in tracked.iter().zip(answers) {
            let answer = answer.trim();
            // With a custom format git answers `<name> missing` for a name
            // HEAD does not hold (a file added to the index only): no before side.
            if answer.ends_with(" missing") {
                unborn.insert(name.clone());
                continue;
            }
            match answer.parse::<u64>() {
                Ok(size) if size > lsa::MAX_READ => {
                    oversize.insert(name.clone());
                }
                Ok(_) => readable.push(name.clone()),
                Err(_) => {
                    failure("cat-file");
                    return None;
                }
            }
        }
        let Some(blobs) = greenbelay_guard::git::cat_file_batch_bounded(&root, &readable, deadline)
        else {
            failure("cat-file");
            return None;
        };
        before_blobs = blobs.into_iter().collect();
    }

    let mut texts: Vec<(std::path::PathBuf, String, std::path::PathBuf, String)> = Vec::new();
    for file in &files {
        let before = match file.before_path() {
            Some(path) => {
                let name = format!("HEAD:{path}");
                if oversize.contains(&name) {
                    continue;
                }
                if unborn.contains(&name) {
                    String::new()
                } else {
                    match before_blobs.remove(&name).map(String::from_utf8) {
                        Some(Ok(text)) => text,
                        Some(Err(_)) => {
                            journal_outcome("bash-skip", path);
                            continue;
                        }
                        None => {
                            failure("cat-file");
                            return None;
                        }
                    }
                }
            }
            None => String::new(),
        };
        let after = if file.deleted {
            String::new()
        } else {
            match read_small(&root.join(&file.path)) {
                Some(text) => text,
                None => continue,
            }
        };
        let old_path = file.old_path.as_deref().unwrap_or(&file.path);
        texts.push((
            std::path::PathBuf::from(old_path),
            before,
            std::path::PathBuf::from(&file.path),
            after,
        ));
    }
    let changes: Vec<lsa::FileChange<'_>> = texts
        .iter()
        .map(|(old_path, before, new_path, after)| lsa::FileChange {
            old_path: old_path.as_path(),
            before: before.as_str(),
            new_path: new_path.as_path(),
            after: after.as_str(),
        })
        .collect();
    let hits = lsa::net_added(&changes);
    if hits.is_empty() {
        return None;
    }

    let shown_root = root.to_string_lossy().into_owned();
    let mut ordinals: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
    let mut fresh = Vec::new();
    for added in hits {
        let marker = format!("{}[{}]", added.hit.kind, added.hit.codes);
        let counter = ordinals
            .entry(format!("{}\t{marker}", added.path.display()))
            .or_insert(0);
        *counter += 1;
        let key = format!(
            "suppression\t{shown_root}\t{}\t{marker}\t{counter}",
            added.path.display()
        );
        let first = stance == Stance::Observe
            || first_telling(rule, &bash.session, &key, &bash.cwd, &bash.permission_mode);
        if first {
            fresh.push(added);
        }
    }
    if fresh.is_empty() {
        journal_outcome("told-before", &shown_root);
        return None;
    }
    let first_path = fresh[0].path.to_string_lossy().into_owned();
    let hits_only: Vec<lsa::Hit> = fresh.iter().map(|added| added.hit.clone()).collect();
    journal::record(&journal::Entry {
        rule: rule.id,
        stance: stance.as_str(),
        outcome: outcome_of(stance),
        session: &bash.session,
        repo: &repo,
        mode: &bash.permission_mode,
        excerpt: &lsa::excerpt(&first_path, &hits_only, &lsa::Mode::Bash),
    });
    match stance {
        Stance::Observe => None,
        Stance::Advise | Stance::Deny => {
            let fresh_hits: Vec<(std::path::PathBuf, lsa::Hit)> = fresh
                .into_iter()
                .map(|added| (added.path, added.hit))
                .collect();
            Some(lsa::bash_phrase(&repo, &fresh_hits))
        }
    }
}

/// A file `git status` reports as changed, of a kind the rule examines.
struct ChangedFile {
    path: String,
    /// The path HEAD knew it by, when the change is a rename.
    old_path: Option<String>,
    untracked: bool,
    deleted: bool,
}

impl ChangedFile {
    /// The path to read from HEAD: none for a file HEAD never held.
    fn before_path(&self) -> Option<&str> {
        if self.untracked {
            None
        } else {
            Some(self.old_path.as_deref().unwrap_or(&self.path))
        }
    }
}

/// A path worth reading: an examined kind by name, or extensionless, which only
/// its content (a shell shebang) can tell.
fn candidate_path(path: &str) -> bool {
    let path = std::path::Path::new(path);
    rules::lint_suppression_added::examined(path)
        || (path.file_name().is_some() && path.extension().is_none())
}

/// The candidate files of a `status --porcelain=v1 -z` listing, deletions and
/// the old side of a rename included: they are before-only sides of the net
/// count, so a moved marker cancels.
fn changed_examined_files(status: &[u8]) -> Vec<ChangedFile> {
    let mut out = Vec::new();
    let mut fields = status.split(|b| *b == 0).filter(|f| !f.is_empty());
    while let Some(field) = fields.next() {
        if field.len() < 4 {
            continue;
        }
        let (code, path) = field.split_at(3);
        let renamed = code[0] == b'R' || code[0] == b'C' || code[1] == b'R' || code[1] == b'C';
        let old_path = if renamed { fields.next() } else { None };
        if code[..2] == *b"!!" {
            continue;
        }
        let Ok(path) = std::str::from_utf8(path) else {
            continue;
        };
        let old_path = old_path.and_then(|old| std::str::from_utf8(old).ok());
        if path.contains('\n') || old_path.is_some_and(|old| old.contains('\n')) {
            continue;
        }
        if !candidate_path(path) && !old_path.is_some_and(candidate_path) {
            continue;
        }
        out.push(ChangedFile {
            path: path.to_string(),
            old_path: old_path.map(str::to_string),
            untracked: code[..2] == *b"??",
            deleted: code[0] == b'D' || code[1] == b'D',
        });
    }
    out
}

/// A regular UTF-8 file within the rule's read limit, else `None`.
fn read_small(path: &std::path::Path) -> Option<String> {
    use std::io::Read;
    let meta = std::fs::metadata(path).ok()?;
    if !meta.is_file() || meta.len() > rules::lint_suppression_added::MAX_READ {
        return None;
    }
    let mut bytes = Vec::new();
    std::fs::File::open(path)
        .ok()?
        .take(rules::lint_suppression_added::MAX_READ + 1)
        .read_to_end(&mut bytes)
        .ok()?;
    String::from_utf8(bytes).ok()
}

fn note_claim(assertion: &Assertion, stance: &str, outcome: &str, bash: &Bash, claim: &Claim) {
    let excerpt = crate::backtest::excerpt(&bash.command, claim.span.start, claim.span.end);
    journal::record(&journal::Entry {
        rule: assertion.id,
        stance,
        outcome,
        session: &bash.session,
        repo: &attributed_repo(assertion.id, bash),
        mode: &bash.permission_mode,
        excerpt: &excerpt,
    });
}

/// A rule with no `confirm` is confirmed. A `confirm` that cannot answer is
/// NOT — failing to establish the fact is silence, like everything else here.
/// The `Err` names why, in the words the rule chose, for the journal.
/// A Read, Edit, Write or MultiEdit about to run: remember a write, and
/// before a Read, say whether the session already has that file. The Read
/// itself is remembered by [`on_post_file`], once it has happened.
fn on_file(op: &crate::payload::FileOp) -> Decision {
    if op.writes {
        // A pass file of the implementation review is written by the hook
        // alone; a Write or Edit there is refused whatever the rule's
        // stance, since there is no legitimate writer to advise.
        if crate::implementation_review::guards_path(&op.path) {
            let rule = &crate::implementation_review_rule::RULE;
            journal::record(&journal::Entry {
                rule: rule.id,
                stance: "deny",
                outcome: "denied",
                session: &op.session,
                repo: &repo_name(&op.cwd),
                mode: &op.permission_mode,
                excerpt: &format!("write {}", op.path.display()),
            });
            return Decision::Deny(decision::phrase(
                rule.id,
                crate::implementation_review::GUARD_REASON,
                crate::implementation_review::GUARD_REMEDY,
            ));
        }
        if let Some(agent) = crate::lsp::agent_key(op.agent_id.as_deref()) {
            crate::session_state::record(&op.session, &agent, "write", &op.path, "full", true);
        }
        return write_decision(op);
    }
    let mut advise: Vec<String> = Vec::new();
    let mut deny: Vec<String> = Vec::new();
    let shown = op.path.to_string_lossy().into_owned();

    let persisted = op.window == "full" && rules::persisted_output_dump::is_persisted(&shown);
    if persisted {
        let rule = &rules::persisted_output_dump::RULE;
        let stance = crate::stance::resolve(rule);
        let text = decision::phrase(
            rule.id,
            &rules::persisted_output_dump::reason(),
            &rules::persisted_output_dump::remedy(),
        );
        note_file(rule, stance, op, &shown);
        match stance {
            Stance::Deny => deny.push(text),
            Stance::Advise => advise.push(text),
            Stance::Observe => {}
        }
    }
    let reread = reread_verdict(
        &op.session,
        op.agent_id.as_deref(),
        &op.path,
        &crate::session_state::read_window(&op.path, &op.window),
        &op.permission_mode,
        &op.cwd,
        &shown,
    );
    if let Some(text) = reread.text {
        match reread.stance {
            Stance::Deny => deny.push(text),
            Stance::Advise => advise.push(text),
            Stance::Observe => {}
        }
    }
    // Code that LSP would answer for: the remedy is LSP, and while this rule
    // speaks, `read-unbounded-large` does not. An observing rule leaves it
    // speaking, so turning this rule off never loses the size advice.
    let mut code_spoken = false;
    if !persisted && !reread.seen {
        if let Some(bytes) = rules::code_read_not_lsp::applies(&op.path, &op.window) {
            if crate::lsp::serves(&op.path).is_ok()
                && crate::lsp::agent_has_tool(&op.agent, &op.cwd).is_ok()
            {
                let rule = &rules::code_read_not_lsp::RULE;
                let stance = crate::stance::resolve(rule);
                let lsp_first = crate::lsp::asked(&op.session, op.agent_id.as_deref(), &op.path);
                if lsp_first {
                    // LSP came first: the case the advice was meant to
                    // produce. This rule is silent; `read-unbounded-large`
                    // still speaks, because after LSP named a line the
                    // remedy for a large whole Read is the window around it.
                    journal::record(&journal::Entry {
                        rule: rule.id,
                        stance: stance.as_str(),
                        outcome: "lsp-first",
                        session: &op.session,
                        repo: &repo_name(&op.cwd),
                        mode: &op.permission_mode,
                        excerpt: &shown,
                    });
                }
                // A refusal is not told once: every Read is refused until LSP
                // has been asked, which is the way through the text names.
                let first = !lsp_first
                    && (stance == Stance::Observe
                        || stance == Stance::Deny
                        || first_telling(
                            rule,
                            &op.session,
                            // Per agent: a subagent is told on its own.
                            &match &op.agent_id {
                                None => format!("read {}", op.path.display()),
                                Some(id) => format!("read {} @{id}", op.path.display()),
                            },
                            &op.cwd,
                            &op.permission_mode,
                        ));
                if first {
                    note_file(rule, stance, op, &shown);
                    let (reason, remedy) = if stance == Stance::Deny {
                        rules::code_read_not_lsp::phrase_refusal(&shown, bytes)
                    } else {
                        rules::code_read_not_lsp::phrase(&shown, bytes)
                    };
                    let text = decision::phrase(rule.id, &reason, &remedy);
                    match stance {
                        Stance::Deny => deny.push(text),
                        Stance::Advise => advise.push(text),
                        Stance::Observe => {}
                    }
                    code_spoken = stance != Stance::Observe;
                }
            }
        }
    }
    // Last, and quiet on a file the session has seen whatever `file-reread`'s
    // stance: its remedy already says to use `offset`/`limit`.
    if !persisted && !reread.seen && !code_spoken {
        if let Some(bytes) = rules::read_unbounded_large::applies(&op.path, &op.window, &op.agent) {
            let rule = &rules::read_unbounded_large::RULE;
            let stance = crate::stance::resolve(rule);
            use rules::read_unbounded_large::Finder;
            let finder = if crate::lsp::is_code(&shown) && crate::lsp::serves(&op.path).is_ok() {
                Finder::Lsp
            } else {
                Finder::Grep
            };
            match stance {
                // Refuse once per agent and file; the same Read again is the
                // agent's informed choice and passes (deliberate-output plan,
                // Phase 3). No prompt: feedback to the agent only.
                Stance::Deny => match refuse_once(rule, op) {
                    Once::Refuse => {
                        note_file(rule, stance, op, &shown);
                        let (reason, remedy) =
                            rules::read_unbounded_large::phrase_refusal(&shown, bytes, finder);
                        deny.push(decision::phrase(rule.id, &reason, &remedy));
                    }
                    Once::Allowed => {}
                    // A refusal that cannot be remembered would refuse the
                    // promised retry forever: say it as advice instead.
                    // `refuse_once` journalled it `unrecorded`; noting it as
                    // `denied` too would count a refusal that never happened.
                    Once::Unrecorded => {
                        let (reason, remedy) =
                            rules::read_unbounded_large::phrase(&shown, bytes, finder);
                        advise.push(decision::phrase(rule.id, &reason, &remedy));
                    }
                },
                Stance::Advise => {
                    let (reason, remedy) =
                        rules::read_unbounded_large::phrase(&shown, bytes, finder);
                    note_file(rule, stance, op, &shown);
                    advise.push(decision::phrase(rule.id, &reason, &remedy));
                }
                Stance::Observe => note_file(rule, stance, op, &shown),
            }
        }
    }
    if !deny.is_empty() {
        Decision::Deny(deny.join("\n\n"))
    } else if !advise.is_empty() {
        Decision::Advise(advise.join("\n\n"))
    } else {
        Decision::Silent
    }
}

/// Every write rule's verdict on one Write, Edit or MultiEdit, collected:
/// any Deny makes the result a Deny, and either way every text is carried,
/// joined with blank lines, as the Read branch does.
fn write_decision(op: &crate::payload::FileOp) -> Decision {
    combine([
        lint_suppression(op),
        guidance_written(op),
        guidance_shape(op),
    ])
}

/// The verdicts of several rules as one: any Deny makes a Deny, and either
/// way every text is carried, joined with blank lines.
fn combine(decisions: impl IntoIterator<Item = Decision>) -> Decision {
    let mut denied = false;
    let mut asked = false;
    let mut texts: Vec<String> = Vec::new();
    for decision in decisions {
        match decision {
            Decision::Silent => {}
            Decision::Deny(text) => {
                denied = true;
                texts.push(text);
            }
            Decision::Ask(text) => {
                asked = true;
                texts.push(text);
            }
            Decision::Advise(text) => texts.push(text),
            // A write rule answers Silent, Advise, Ask or Deny; these belong
            // to other events. If one ever reaches here, its text is kept as
            // advice rather than dropped.
            Decision::Context(text)
            | Decision::Assert(text)
            | Decision::AssertAfterFailure(text)
            | Decision::Continue(text)
            | Decision::UserNote(text) => texts.push(text),
        }
    }
    if texts.is_empty() {
        Decision::Silent
    } else if denied {
        Decision::Deny(texts.join("\n\n"))
    } else if asked {
        Decision::Ask(texts.join("\n\n"))
    } else {
        Decision::Advise(texts.join("\n\n"))
    }
}

/// The key a once-per-session telling is kept under: per agent, so a subagent
/// is told on its own.
fn telling_key(what: &str, op: &crate::payload::FileOp) -> String {
    match &op.agent_id {
        None => format!("{what} {}", op.path.display()),
        Some(id) => format!("{what} {} @{id}", op.path.display()),
    }
}

/// A write to a file agents read as guidance: told once per session and file.
fn guidance_written(op: &crate::payload::FileOp) -> Decision {
    use rules::agent_guidance_written as agw;
    if op.change.is_none() || !agw::is_guidance(&op.path) {
        return Decision::Silent;
    }
    let rule = &agw::RULE;
    let stance = crate::stance::resolve(rule);
    let shown = op.path.to_string_lossy().into_owned();
    let first = stance == Stance::Observe
        || first_telling(
            rule,
            &op.session,
            &telling_key("write", op),
            &op.cwd,
            &op.permission_mode,
        );
    if !first {
        journal_repeat(rule, stance, op, &shown);
        return Decision::Silent;
    }
    note_file(rule, stance, op, &shown);
    match stance {
        Stance::Observe => Decision::Silent,
        // The ceiling is advise (`max_stance`); a deny stance still advises.
        Stance::Advise | Stance::Deny => Decision::Advise(agw::phrase(&shown)),
    }
}

/// A write that leaves a skill unfindable or an always-on file over budget.
/// Judged only on a whole-file rebuild; a fragment is journalled and silent.
fn guidance_shape(op: &crate::payload::FileOp) -> Decision {
    use rules::agent_guidance_shape as ags;
    use rules::lint_suppression_added as lsa;
    let (Some(change), Some(kind)) = (&op.change, ags::kind(&op.path)) else {
        return Decision::Silent;
    };
    let rule = &ags::RULE;
    let stance = crate::stance::resolve(rule);
    let shown = op.path.to_string_lossy().into_owned();
    let rebuilt = lsa::reconstruct(&op.path, change);
    if let lsa::Mode::Fragment(why) = rebuilt.mode {
        journal::record(&journal::Entry {
            rule: rule.id,
            stance: stance.as_str(),
            outcome: "fragment",
            session: &op.session,
            repo: &repo_name(&op.cwd),
            mode: &op.permission_mode,
            excerpt: &format!("{shown} {}", why.as_str()),
        });
        return Decision::Silent;
    }
    let Some(text) = ags::check(&op.path, kind, &rebuilt.before, &rebuilt.after) else {
        return Decision::Silent;
    };
    let first = stance == Stance::Observe
        || first_telling(
            rule,
            &op.session,
            &telling_key("shape", op),
            &op.cwd,
            &op.permission_mode,
        );
    if !first {
        journal_repeat(rule, stance, op, &shown);
        return Decision::Silent;
    }
    note_file(rule, stance, op, &ags::excerpt(&shown, kind));
    match stance {
        Stance::Observe => Decision::Silent,
        // The ceiling is advise (`max_stance`); a deny stance still advises.
        Stance::Advise | Stance::Deny => Decision::Advise(text),
    }
}

/// A finding already told this session: journalled, not said again.
fn journal_repeat(rule: &Rule, stance: Stance, op: &crate::payload::FileOp, shown: &str) {
    journal::record(&journal::Entry {
        rule: rule.id,
        stance: stance.as_str(),
        outcome: "told-before",
        session: &op.session,
        repo: &repo_name(&op.cwd),
        mode: &op.permission_mode,
        excerpt: shown,
    });
}

/// An Edit, MultiEdit or Write that adds a lint suppression or loosens a lint
/// configuration. The file is rebuilt before and after only for a file type the
/// rule examines; the effects (the bounded read) stay here at the boundary.
fn lint_suppression(op: &crate::payload::FileOp) -> Decision {
    use rules::lint_suppression_added as lsa;
    let Some(change) = &op.change else {
        return Decision::Silent;
    };
    if !lsa::worth_rebuilding(&op.path, change) {
        return Decision::Silent;
    }
    let rebuilt = lsa::reconstruct(&op.path, change);
    let hits = lsa::examine_change(&op.path, &rebuilt.before, &rebuilt.after);
    if hits.is_empty() {
        return Decision::Silent;
    }
    let rule = &lsa::RULE;
    let stance = crate::stance::resolve(rule);
    let shown = op.path.to_string_lossy().into_owned();
    note_file(
        rule,
        stance,
        op,
        &lsa::excerpt(&shown, &hits, &rebuilt.mode),
    );
    let text = lsa::phrase(&shown, &hits, &rebuilt.mode);
    match stance {
        Stance::Deny => Decision::Deny(text),
        Stance::Advise => Decision::Advise(text),
        Stance::Observe => Decision::Silent,
    }
}

/// An LSP call that has run: the files it was about go on the session's
/// record under the calling agent, and the call is journalled (`lsp`,
/// `lsp-error` for an `Error performing` answer, `lsp-unparsed` when the
/// response had no text `result`). An error counts as asked: a refusal must
/// never block a Read because the server is broken. Never speaks.
fn on_post_lsp(call: &crate::payload::LspCall) -> Decision {
    let outcome = match call.response.as_deref() {
        None => "lsp-unparsed",
        Some(r) if r.starts_with("Error performing") => "lsp-error",
        Some(_) => "lsp",
    };
    let repo = repo_name(&call.cwd);
    let excerpt = format!("{} {}", call.operation, call.file_path.display());
    let entry = |outcome, excerpt: &str| {
        journal::record(&journal::Entry {
            rule: "-",
            stance: "-",
            outcome,
            session: &call.session,
            repo: &repo,
            mode: &call.permission_mode,
            excerpt,
        })
    };
    entry(outcome, &excerpt);
    let files = crate::lsp::asked_files(call);
    if let Err(why) = crate::lsp::record_asked(&call.session, call.agent_id.as_deref(), &files) {
        entry("unrecorded", why);
    }
    Decision::Silent
}

/// A Read that has run and succeeded: the file is in context now, so this is
/// the moment to remember it. Recording before the call did the wrong thing
/// twice over — a Read refused above, or one that failed on a path that is
/// not there, was still on record, and a retry was told its contents were
/// already in context.
fn on_post_file(op: &crate::payload::FileOp) -> Decision {
    if !op.writes {
        if let Some(agent) = crate::lsp::agent_key(op.agent_id.as_deref()) {
            let window = crate::session_state::read_window(&op.path, &op.window);
            crate::session_state::record(
                &op.session,
                &agent,
                "read",
                &op.path,
                &window,
                !op.persisted_result,
            );
        }
    }
    Decision::Silent
}

/// How long `adr-lint check` gets on one file.
const ADR_LINT_DEADLINE: std::time::Duration = std::time::Duration::from_secs(1);
/// How long `amont list --json` gets: it takes about a second, and is asked
/// once per session and repository. Well under the hook's own 10 s timeout,
/// so a hung `amont` ends here and its closed gate is cached, instead of
/// Claude Code killing the hook before anything is recorded.
const AMONT_LIST_DEADLINE: std::time::Duration = std::time::Duration::from_secs(5);

/// A child process that was run with a deadline.
enum Ran {
    Exited { code: Option<i32>, stdout: String },
    TimedOut,
    Failed(String),
}

/// Runs `program` in `dir` with stdin closed and stdout captured, and kills
/// it at `deadline`. The reader is never joined after a kill: a grandchild
/// holding the pipe would hold the hook with it.
fn run_with_deadline(
    program: &std::ffi::OsStr,
    args: &[&str],
    dir: &std::path::Path,
    deadline: std::time::Duration,
) -> Ran {
    use std::process::Stdio;
    let mut child = match std::process::Command::new(program)
        .args(args)
        .current_dir(dir)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
    {
        Ok(child) => child,
        Err(e) => return Ran::Failed(e.to_string()),
    };
    let Some(mut pipe) = child.stdout.take() else {
        return Ran::Failed("no stdout".to_string());
    };
    let (sender, receiver) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let mut printed = Vec::new();
        pipe.read_to_end(&mut printed).ok(); // a short read leaves what was read; the exit status reports the rest
        sender.send(printed).ok(); // the receiver is gone only after a kill, when the output is not wanted
    });
    let end = std::time::Instant::now() + deadline;
    let status = loop {
        match child.try_wait() {
            Ok(Some(status)) => break status,
            Ok(None) if std::time::Instant::now() < end => {
                std::thread::sleep(std::time::Duration::from_millis(5));
            }
            Ok(None) => {
                child.kill().ok(); // a child that already exited needs no kill; the timeout is reported either way
                child.wait().ok(); // reaped if it can be; the timeout is reported either way
                return Ran::TimedOut;
            }
            Err(e) => return Ran::Failed(e.to_string()),
        }
    };
    let printed = receiver
        .recv_timeout(std::time::Duration::from_millis(500))
        .unwrap_or_default();
    Ran::Exited {
        code: status.code(),
        stdout: String::from_utf8_lossy(&printed).into_owned(),
    }
}

/// The `adr-lint` program to run: `GREENBELAY_ADR_LINT`, else PATH's.
fn adr_lint_program() -> std::ffi::OsString {
    std::env::var_os(greenbelay_guard::env_var!("ADR_LINT"))
        .filter(|program| !program.is_empty())
        .unwrap_or_else(|| std::ffi::OsString::from("adr-lint"))
}

/// Journals a note under `adr-lint-written` at most once per session and
/// outcome.
fn adr_lint_note_once(
    op: &crate::payload::FileOp,
    root: &std::path::Path,
    outcome: &str,
    excerpt: &str,
) {
    let key = format!("adr-lint-written {outcome}");
    let first = match crate::lsp::told(&op.session, &key) {
        crate::lsp::Told::Before => false,
        crate::lsp::Told::First | crate::lsp::Told::Unrecorded(_) => true,
    };
    if first {
        adr_lint_note(op, root, "-", outcome, excerpt);
    }
}

/// `stance` is `-` for a note that is not about a finding: the stance is
/// resolved (several `git config` reads) only when there is one to say. The
/// repository is the written file's, not the session's working directory.
fn adr_lint_note(
    op: &crate::payload::FileOp,
    root: &std::path::Path,
    stance: &str,
    outcome: &str,
    excerpt: &str,
) {
    journal::record(&journal::Entry {
        rule: rules::adr_lint_written::RULE.id,
        stance,
        outcome,
        session: &op.session,
        repo: &repo_name(root),
        mode: &op.permission_mode,
        excerpt,
    });
}

/// Does the repository at `root` vendor adr-lint's `check` row? Asked of
/// `amont list --json` once per session and repository; the answer is kept on
/// the session's record.
fn adr_lint_gate(op: &crate::payload::FileOp, root: &std::path::Path) -> bool {
    use rules::adr_lint_written::{gate, Gate};
    let open_key = format!("adr-lint-written gate-open {}", root.display());
    let closed_key = format!("adr-lint-written gate-closed {}", root.display());
    if crate::lsp::was_told(&op.session, &open_key) {
        return true;
    }
    if crate::lsp::was_told(&op.session, &closed_key) {
        return false;
    }
    let shown = root.display().to_string();
    let answer = run_with_deadline(
        std::ffi::OsStr::new(greenbelay_guard::gate::gate_binary()),
        &["list", "--json"],
        root,
        AMONT_LIST_DEADLINE,
    );
    let open = match answer {
        Ran::Exited {
            code: Some(0),
            stdout,
        } => match gate(&stdout) {
            Gate::Open => true,
            Gate::Closed => false,
            Gate::Unexpected => {
                adr_lint_note_once(op, root, "amont-list-unexpected", &shown);
                false
            }
        },
        Ran::Exited { .. } | Ran::TimedOut | Ran::Failed(_) => {
            adr_lint_note_once(op, root, "amont-list-failed", &shown);
            false
        }
    };
    let _ = crate::lsp::told(&op.session, if open { &open_key } else { &closed_key }); // unrecorded only means the next write asks again
    open
}

/// An Edit, MultiEdit or Write that has run: the file is checked by
/// `adr-lint check --json` when its repository vendors that row.
fn on_post_write(op: &crate::payload::FileOp) -> Decision {
    use rules::adr_lint_written as al;
    if !al::considered(&op.path) {
        return Decision::Silent;
    }
    let Some(dir) = op.path.parent() else {
        return Decision::Silent;
    };
    let Some(top) = greenbelay_guard::git::stdout_in(dir, &["rev-parse", "--show-toplevel"]) else {
        return Decision::Silent;
    };
    let root = crate::lsp::normal(std::path::Path::new(&top));
    let Ok(relative) = crate::lsp::normal(&op.path)
        .strip_prefix(&root)
        .map(|p| p.to_owned())
    else {
        return Decision::Silent;
    };
    if !adr_lint_gate(op, &root) {
        return Decision::Silent;
    }
    let relative = relative.to_string_lossy().into_owned();
    let ran = run_with_deadline(
        &adr_lint_program(),
        &["check", "--json", "--", &relative],
        &root,
        ADR_LINT_DEADLINE,
    );
    let verdict = match ran {
        Ran::Exited { code, stdout } => al::interpret(code, &stdout),
        Ran::TimedOut => {
            adr_lint_note(op, &root, "-", "adr-lint-slow", &relative);
            return Decision::Silent;
        }
        Ran::Failed(why) => {
            adr_lint_note_once(op, &root, "adr-lint-unavailable", &why);
            return Decision::Silent;
        }
    };
    match verdict {
        al::Verdict::Clean => Decision::Silent,
        al::Verdict::Failed(outcome) => {
            adr_lint_note_once(op, &root, outcome, &relative);
            Decision::Silent
        }
        al::Verdict::Findings(findings) => {
            let stance = crate::stance::resolve(&al::RULE);
            for finding in &findings {
                adr_lint_note(
                    op,
                    &root,
                    stance.as_str(),
                    outcome_of(stance),
                    &al::excerpt(finding),
                );
            }
            match stance {
                Stance::Observe => Decision::Silent,
                // The ceiling is advise (`max_stance`); a deny stance still advises.
                Stance::Advise | Stance::Deny => Decision::Assert(al::phrase(&findings)),
            }
        }
    }
}

/// What `symbol-grep-not-lsp` needs beyond its `confirm`: the facts are in
/// the payload, not the command. The agent must have the LSP tool. Returns
/// the searched pattern; the telling follows `final_stance` ([`grep_telling`]).
fn grep_gate(
    bash: &Bash,
    parsed: &Parsed,
    finding: &Finding,
    stance: Stance,
) -> Result<String, &'static str> {
    crate::lsp::agent_has_tool(&bash.agent, &bash.cwd)?;
    if stance == Stance::Observe {
        return Ok(String::new());
    }
    rules::symbol_grep_not_lsp::search_at(parsed, finding.span.start)
        .map(|search| search.pattern.to_string())
        .ok_or("the command no longer matches")
}

/// Whether this spoken stance is a refusal that `denyAgents` raised, as
/// opposed to a `deny` the person configured for everyone.
fn is_denial_by_agent(stance: Stance, source: crate::stance::Source) -> bool {
    stance == Stance::Deny && source == crate::stance::Source::DenyAgents
}

/// The stance `symbol-grep-not-lsp` speaks with for this pattern, or `None`
/// when the telling was already made. An observing rule records nothing, so
/// it never uses up the one telling. A refusal `denyAgents` raised is told
/// once per pattern and agent (`grep <pattern> @<agent id>`), so a parent
/// session advised on the pattern does not stop the worker's refusal; every
/// other stance keeps the session's `grep <pattern>` key. A refusal that
/// cannot be recorded would refuse the retry it promises forever, so it
/// falls back to Advise, journalled `unrecorded`.
fn grep_telling(
    session: &str,
    pattern: &str,
    agent_id: Option<&str>,
    stance: Stance,
    source: crate::stance::Source,
    cwd: &std::path::Path,
    mode: &str,
) -> Option<Stance> {
    let rule = &rules::symbol_grep_not_lsp::RULE;
    let plain = format!("grep {pattern}");
    if stance == Stance::Observe {
        return Some(stance);
    }
    if !is_denial_by_agent(stance, source) {
        return first_telling(rule, session, &plain, cwd, mode).then_some(stance);
    }
    let unrecorded = |why: &str| {
        journal::record(&journal::Entry {
            rule: rule.id,
            stance: Stance::Deny.as_str(),
            outcome: "unrecorded",
            session,
            repo: &repo_name(cwd),
            mode,
            excerpt: why,
        });
        first_telling(rule, session, &plain, cwd, mode).then_some(Stance::Advise)
    };
    let Some(key_agent) = crate::lsp::agent_key(agent_id) else {
        return unrecorded("no usable agent id");
    };
    match crate::lsp::told(session, &format!("{plain} @{key_agent}")) {
        crate::lsp::Told::First => Some(Stance::Deny),
        crate::lsp::Told::Before => None,
        crate::lsp::Told::Unrecorded(why) => unrecorded(why),
    }
}

/// A Grep tool call about to run: the tool's half of `symbol-grep-not-lsp`.
/// The pure tests come first; the world is asked only about a symbol search
/// over code.
fn on_grep(op: &crate::payload::GrepOp) -> Decision {
    use rules::symbol_grep_not_lsp as sg;
    if op.output_mode.as_deref() == Some("count") || !sg::symbol(&op.pattern) {
        return Decision::Silent;
    }
    let scope = match &op.path {
        None => sg::GrepScope::Dir,
        Some(p) if p.is_dir() => sg::GrepScope::Dir,
        Some(p) if p.is_file() => sg::GrepScope::File(
            p.file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_default(),
        ),
        Some(_) => sg::GrepScope::Missing,
    };
    if !sg::grep_tool_targets_code(&scope, op.glob.as_deref(), op.kind.as_deref()) {
        return Decision::Silent;
    }
    let target = op.path.clone().unwrap_or_else(|| op.cwd.clone());
    if crate::lsp::serves(&target).is_err()
        || crate::lsp::agent_has_tool(&op.agent, &op.cwd).is_err()
    {
        return Decision::Silent;
    }
    let rule = &sg::RULE;
    let (resolved, source) = crate::stance::resolve_for(rule, &op.agent);
    let Some(stance) = grep_telling(
        &op.session,
        &op.pattern,
        op.agent_id.as_deref(),
        resolved,
        source,
        &op.cwd,
        &op.permission_mode,
    ) else {
        return Decision::Silent;
    };
    journal::record(&journal::Entry {
        rule: rule.id,
        stance: stance.as_str(),
        outcome: outcome_of(stance),
        session: &op.session,
        repo: &repo_name(&op.cwd),
        mode: &op.permission_mode,
        excerpt: &format!("Grep {}", op.pattern),
    });
    let (reason, remedy) = sg::phrase(&op.pattern);
    let remedy: &str = if is_denial_by_agent(stance, source) {
        sg::DENY_REMEDY
    } else {
        &remedy
    };
    let text = decision::phrase(rule.id, &reason, remedy);
    match stance {
        Stance::Observe => Decision::Silent,
        Stance::Advise => Decision::Advise(text),
        Stance::Deny => Decision::Deny(text),
    }
}

/// A `take_screenshot` from the main conversation without a `filePath`:
/// advised once per session. A subagent and a saved image are not ours.
fn on_screenshot(op: &crate::payload::ScreenshotOp) -> Decision {
    use rules::screenshot_in_main_session as sms;
    if op.agent_id.is_some() || op.file_path.is_some() {
        return Decision::Silent;
    }
    let rule = &sms::RULE;
    let stance = crate::stance::resolve(rule);
    let journal_as = |outcome: &str| {
        journal::record(&journal::Entry {
            rule: rule.id,
            stance: stance.as_str(),
            outcome,
            session: &op.session,
            repo: &repo_name(&op.cwd),
            mode: &op.permission_mode,
            excerpt: "take_screenshot @main",
        });
    };
    let first = stance == Stance::Observe
        || first_telling(rule, &op.session, rule.id, &op.cwd, &op.permission_mode);
    if !first {
        journal_as("told-before");
        return Decision::Silent;
    }
    // The ceiling is advise (`max_stance`): a deny stance still advises, and is
    // journalled as advised, not through `outcome_of`, which would say denied.
    match stance {
        Stance::Observe => {
            journal_as(outcome_of(stance));
            Decision::Silent
        }
        Stance::Advise | Stance::Deny => {
            journal_as("advised");
            Decision::Advise(sms::phrase())
        }
    }
}

/// The most a contract file is read for its `kind`.
const CONTRACT_READ_LIMIT: u64 = 64 * 1024;

/// How long the checkout probe may take.
const CHECKOUT_PROBE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(3);

/// The kind of a relais task; `None` when it cannot be told (unreadable,
/// not a regular file, too large, unparsable, or an unknown shape).
fn relais_task_kind(
    task: &crate::payload::RelaisTask,
    cwd: &std::path::Path,
) -> Option<rules::relais_run_forks::Kind> {
    use crate::payload::RelaisTask;
    use rules::relais_run_forks::Kind;
    use std::io::Read;
    let from_kind = |kind: Option<&str>| match kind {
        None | Some("change") => Kind::Change,
        Some(_) => Kind::Other,
    };
    match task {
        RelaisTask::Inline { kind } => Some(from_kind(kind.as_deref())),
        RelaisTask::Unknown => None,
        RelaisTask::Path(path) => {
            let path = cwd.join(path);
            // The path is judged before the open, because opening a FIFO
            // blocks until a writer comes; the handle is judged again after,
            // so a swap between the two is still refused.
            if !std::fs::metadata(&path).ok()?.is_file() {
                return None;
            }
            let file = std::fs::File::open(&path).ok()?;
            if !file.metadata().ok()?.is_file() {
                return None;
            }
            let mut text = Vec::new();
            file.take(CONTRACT_READ_LIMIT + 1)
                .read_to_end(&mut text)
                .ok()?;
            if text.len() as u64 > CONTRACT_READ_LIMIT {
                return None;
            }
            let contract: serde_json::Value = serde_json::from_slice(&text).ok()?;
            let object = contract.as_object()?;
            Some(from_kind(object.get("kind").and_then(|x| x.as_str())))
        }
    }
}

/// A relais `run` that would fork a worktree of its own: advised every time.
fn on_relais_run(op: &crate::payload::RelaisRunOp) -> Decision {
    use crate::git::CheckoutProbe;
    use rules::relais_run_forks as rrf;
    let rule = &rrf::RULE;
    let stance = crate::stance::resolve(rule);
    let Some(run_cwd) = op.run_cwd.as_deref() else {
        return Decision::Silent;
    };
    let run_dir = op.cwd.join(run_cwd);
    // The run's repository, not the session's: the week's audit matches a
    // fire to its relais run by repository.
    let journal_as = |outcome: &str, excerpt: &str| {
        journal::record(&journal::Entry {
            rule: rule.id,
            stance: stance.as_str(),
            outcome,
            session: &op.session,
            repo: &repo_name(&run_dir),
            mode: &op.permission_mode,
            excerpt,
        });
    };
    let workspace = op.workspace.as_deref();
    let checkout = match crate::git::checkout_probe(
        &run_dir,
        std::time::Instant::now() + CHECKOUT_PROBE_DEADLINE,
    ) {
        CheckoutProbe::Bare => {
            journal_as("silent", "relais run bare");
            return Decision::Silent;
        }
        CheckoutProbe::NotARepo => {
            journal_as("silent", "relais run not_a_repo");
            return Decision::Silent;
        }
        CheckoutProbe::Failed => {
            journal_as("silent", "relais run probe_failed");
            return Decision::Silent;
        }
        CheckoutProbe::Primary => rrf::Checkout::Primary,
        CheckoutProbe::Linked => rrf::Checkout::Linked,
    };
    if rrf::fork_of(checkout, workspace).is_none() {
        return Decision::Silent;
    }
    let Some(kind) = relais_task_kind(&op.task, &run_dir) else {
        journal_as("silent", "relais run kind_unknown");
        return Decision::Silent;
    };
    let Some(fire) = rrf::judge(kind, workspace, checkout) else {
        return Decision::Silent;
    };
    journal_as(
        outcome_of(stance),
        &format!(
            "relais run {} {}",
            fire.label(),
            workspace.unwrap_or("auto")
        ),
    );
    // The resolved directory, so `.` or a symlink names the real place.
    // Windows's verbatim `\\?\` prefix is dropped from what the reader sees.
    let shown = std::fs::canonicalize(&run_dir).unwrap_or_else(|_| run_dir.clone());
    let shown = shown.display().to_string();
    let text = rrf::phrase(
        fire,
        workspace,
        shown.strip_prefix(r"\\?\").unwrap_or(&shown),
    );
    match stance {
        Stance::Observe => Decision::Silent,
        Stance::Advise => Decision::Advise(text),
        Stance::Deny => Decision::Deny(text),
    }
}

/// Where a refuse-once rule stands on this call.
enum Once {
    /// The first time this agent asks for this file: refuse, with feedback.
    Refuse,
    /// Asked again after the feedback: allowed, journalled.
    Allowed,
    /// The refusal could not be remembered: refusing would refuse the retry
    /// it promises forever, so the call passes, journalled.
    Unrecorded,
}

/// Refuse once per session, agent and file, then allow the same call
/// (deliberate-output plan, Phase 3). The key is the rule id, the agent's
/// checked key and the normalised path; the file's size is left out so a
/// growing log keeps the promise the feedback makes.
fn refuse_once(rule: &Rule, op: &crate::payload::FileOp) -> Once {
    refuse_once_at(
        rule,
        &op.session,
        op.agent_id.as_deref(),
        &op.cwd,
        &op.permission_mode,
        &op.path,
    )
}

/// [`refuse_once`] for any tool call that names one file: a Read's
/// payload, or the file a `cat` dumps (`whole-file-dump`).
fn refuse_once_at(
    rule: &Rule,
    session: &str,
    agent_id: Option<&str>,
    cwd: &std::path::Path,
    mode: &str,
    path: &std::path::Path,
) -> Once {
    let repo = repo_name(cwd);
    let excerpt = |agent: &str| format!("{} @{agent}", path.display());
    let Some(agent) = crate::lsp::agent_key(agent_id) else {
        journal::record(&journal::Entry {
            rule: rule.id,
            stance: Stance::Deny.as_str(),
            outcome: "unrecorded",
            session,
            repo: &repo,
            mode,
            excerpt: &excerpt("?"),
        });
        return Once::Unrecorded;
    };
    let key = format!(
        "{} {} @{agent}",
        rule.id,
        crate::lsp::normal(path).display()
    );
    let (once, outcome) = match crate::lsp::told(session, &key) {
        crate::lsp::Told::First => return Once::Refuse,
        crate::lsp::Told::Before => (Once::Allowed, "allowed-after-feedback"),
        crate::lsp::Told::Unrecorded(_) => (Once::Unrecorded, "unrecorded"),
    };
    journal::record(&journal::Entry {
        rule: rule.id,
        stance: Stance::Deny.as_str(),
        outcome,
        session,
        repo: &repo,
        mode,
        excerpt: &excerpt(&agent),
    });
    once
}

/// Whether a rule about to speak has not yet told this session about `key`.
/// A record that could not be kept is journalled, and the rule speaks: being
/// told twice costs less than never being told.
fn first_telling(rule: &Rule, session: &str, key: &str, cwd: &std::path::Path, mode: &str) -> bool {
    match crate::lsp::told(session, key) {
        crate::lsp::Told::First => true,
        crate::lsp::Told::Before => false,
        crate::lsp::Told::Unrecorded(why) => {
            journal::record(&journal::Entry {
                rule: rule.id,
                stance: "-",
                outcome: "unrecorded",
                session,
                repo: &repo_name(cwd),
                mode,
                excerpt: why,
            });
            true
        }
    }
}

fn outcome_of(stance: Stance) -> &'static str {
    match stance {
        Stance::Observe => "watched",
        Stance::Advise => "advised",
        Stance::Deny => "denied",
    }
}

/// Whether a Bash result reached the model whole: not an error, shorter than
/// the harness cap (`BASH_MAX_OUTPUT_LENGTH`, else 30,000, counted in
/// characters), and without a persisted-output marker. A payload with no
/// `tool_response` at all is not a harness result and is taken as whole; one
/// whose `tool_response` carries no `stdout` is an unrecognised shape.
fn bash_delivered_whole(bash: &Bash) -> bool {
    if bash.errored {
        return false;
    }
    let Some(out) = &bash.stdout else {
        return !bash.has_response;
    };
    let cap = std::env::var("BASH_MAX_OUTPUT_LENGTH")
        .ok()
        .and_then(|v| v.trim().parse::<usize>().ok())
        .unwrap_or(30_000);
    out.chars().count() < cap && !crate::payload::has_persisted_marker(out)
}

/// Lexical clean-up of an absolute path: `.` components dropped, `..` folded.
/// No file is touched, so a path that is not there compares like any other.
fn normalized(path: std::path::PathBuf) -> std::path::PathBuf {
    use std::path::Component;
    let mut out = std::path::PathBuf::new();
    for part in path.components() {
        match part {
            Component::CurDir => {}
            Component::ParentDir => {
                out.pop();
            }
            other => out.push(other.as_os_str()),
        }
    }
    out
}

/// The path a word names when the clause at `at` runs, so that a write and a
/// dump are compared where each one acts, not as spelled.
fn named_path(ctx: &Context, at: usize, text: &str) -> std::path::PathBuf {
    normalized(resolve_path(&ctx.cwd_at(at), text))
}

/// Whether the command also changes the dumped file under the dump, or waits
/// for it to change. Each exception is bound to the dumped path:
/// - an earlier clause redirects (`>`/`>>`) onto the same file;
/// - an earlier interpreter heredoc names the file as a quoted literal and
///   writes (`open(p, 'w')`, `write_text`, ...);
/// - a `while`/`until` loop that runs `sleep` and names the file starts at or
///   before the dump (the dump may sit in the loop or follow it).
///
/// Such a dump shows a file that changes under it, so it is neither a certain
/// read to remember nor a repeat to refuse.
fn writes_or_waits(ctx: &Context, d: &rules::dump::Dump) -> bool {
    let target = named_path(ctx, d.at, &d.path);
    let clauses = || ctx.parsed.judgeable();
    let redirected = clauses().any(|c| {
        c.at < d.at
            && c.redirects
                .iter()
                .any(|(op, w)| op.contains('>') && named_path(ctx, c.at, &w.text) == target)
    });
    if redirected {
        return true;
    }
    // holds-until: the heredoc exception holds for a python, perl, node or
    // ruby heredoc whose body names the dumped path as a quoted literal (or
    // as a variable or first parameter bound to it in the body) and opens
    // that name in a write mode or calls write_text/write_bytes/writeFileSync
    // on it; it ends when the interpreter's write is read from the shell
    // analysis's effects instead of matched in the body text.
    let scripted = rules::dump::heredoc_bodies(ctx.command).iter().any(|h| {
        h.start < d.at
            && h.program
                .as_deref()
                .is_some_and(|p| p.starts_with("python") || matches!(p, "perl" | "node" | "ruby"))
            && body_writes_path(&h.body, &d.path)
    });
    if scripted {
        return true;
    }
    rules::dump::wait_loops(ctx.command)
        .into_iter()
        .filter(|l| l.start <= d.at)
        .any(|l| {
            let inside = || clauses().filter(|c| l.start <= c.at && c.at < l.end);
            inside().any(runs_sleep)
                && inside().any(|c| {
                    c.words
                        .iter()
                        .map(|w| w.text.as_str())
                        .chain(c.redirects.iter().map(|(_, w)| w.text.as_str()))
                        .any(|t| path_like_word(t) && named_path(ctx, c.at, t) == target)
                })
        })
}

/// Whether an interpreter body writes `path`: the quoted literal, or a name
/// the body binds to it, opened in a write mode or given to a path writer.
fn body_writes_path(body: &str, path: &str) -> bool {
    let lits = [format!("'{path}'"), format!("\"{path}\"")];
    let is_ident = |t: &str| {
        !t.is_empty()
            && t.chars().all(|c| c.is_alphanumeric() || c == '_')
            && !t.starts_with(|c: char| c.is_ascii_digit())
    };
    let mut names: Vec<String> = Vec::new();
    for lit in &lits {
        for (i, _) in body.match_indices(lit.as_str()) {
            let before = body[..i].trim_end();
            if let Some(lhs) = before
                .strip_suffix('=')
                .filter(|l| !l.ends_with(['=', '!', '<', '>']))
            {
                let lhs = lhs.trim_end();
                let start = lhs
                    .rfind(|c: char| !(c.is_alphanumeric() || c == '_'))
                    .map_or(0, |k| k + 1);
                if is_ident(&lhs[start..]) {
                    names.push(lhs[start..].to_string());
                }
            } else if let Some(call) = before.strip_suffix('(') {
                // The literal is the first argument of `name(`: the name's
                // `def name(first, ...)` binds it.
                let start = call
                    .rfind(|c: char| !(c.is_alphanumeric() || c == '_'))
                    .map_or(0, |k| k + 1);
                let name = &call[start..];
                if is_ident(name) {
                    let def = format!("def {name}(");
                    if let Some(k) = body.find(&def) {
                        let rest = &body[k + def.len()..];
                        let first = rest.split([',', ')']).next().unwrap_or("").trim();
                        if is_ident(first) {
                            names.push(first.to_string());
                        }
                    }
                }
            }
        }
    }
    let names_path = |arg: &str| {
        let arg = arg.trim();
        lits.iter().any(|l| l == arg) || names.iter().any(|n| n == arg)
    };
    let write_mode = |m: &str| m.contains(['w', 'a', 'x', '+']);
    let opens = body.match_indices("open(").any(|(i, _)| {
        let rest = &body[i + "open(".len()..];
        let end = rest.find(')').unwrap_or(rest.len());
        let mut args = rest[..end].split(',');
        let target = args.next().unwrap_or("");
        names_path(target)
            && args.any(|a| {
                let a = a.trim();
                let a = a
                    .strip_prefix("mode")
                    .map_or(a, |m| m.trim_start().trim_start_matches('=').trim());
                ["'", "\""].iter().any(|q| {
                    a.strip_prefix(q)
                        .and_then(|m| m.strip_suffix(q))
                        .is_some_and(write_mode)
                })
            })
    });
    if opens {
        return true;
    }
    let writers = [".write_text(", ".write_bytes("].iter().any(|w| {
        body.match_indices(w).any(|(i, _)| {
            let recv = &body[..i];
            match recv.strip_suffix(')') {
                Some(inner) => inner
                    .rfind('(')
                    .is_some_and(|k| names_path(&inner[k + 1..])),
                None => {
                    let start = recv
                        .rfind(|c: char| !(c.is_alphanumeric() || c == '_'))
                        .map_or(0, |k| k + 1);
                    names_path(&recv[start..])
                }
            }
        })
    });
    writers
        || body.match_indices("writeFileSync(").any(|(i, _)| {
            let rest = &body[i + "writeFileSync(".len()..];
            names_path(rest.split([',', ')']).next().unwrap_or(""))
        })
}

/// Whether the clause runs `sleep`, past the loop keywords the lexer leaves at
/// the front of a clause (`do sleep 1`).
fn runs_sleep(c: &Simple) -> bool {
    c.words
        .iter()
        .find(|w| w.quoted || !matches!(w.text.as_str(), "until" | "while" | "do" | "then" | "!"))
        .is_some_and(|w| !w.quoted && w.text == "sleep")
}

fn path_like_word(text: &str) -> bool {
    !text.is_empty() && !text.starts_with('-')
}

/// The answer to the `file-reread` question.
struct Reread {
    /// The session already has this file: a repeat of a whole read, or of the
    /// same window. True whatever `file-reread`'s stance, so a rule that
    /// yields to it does not start speaking when it observes.
    seen: bool,
    /// What to say, when the rule may speak.
    text: Option<String>,
    /// The stance the verdict was reached under (capped to advise for a read
    /// that is not an exact window).
    stance: Stance,
}

/// The `file-reread` question, asked and journalled the same way for a Read
/// and for a `cat`. `text` is `Some` when the session already has this file
/// and the rule may speak; the journal records the watched case too.
fn reread_verdict(
    session: &str,
    agent_id: Option<&str>,
    path: &std::path::Path,
    window: &str,
    mode: &str,
    cwd: &std::path::Path,
    shown: &str,
) -> Reread {
    let unseen = Reread {
        seen: false,
        text: None,
        stance: Stance::Observe,
    };
    // An agent id that cannot be a key: no record, no deny, no advice.
    let Some(agent) = crate::lsp::agent_key(agent_id) else {
        return unseen;
    };
    let Some(prior) = crate::session_state::prior(session, &agent, path, window) else {
        return unseen;
    };
    // A different window of a file read before is a different read; only a
    // certain record covering this exact window is a re-read, and a read that
    // is not an exact window can only be advised about.
    let (seen, exact) = match prior {
        crate::session_state::Prior::Covered(s) => (s, true),
        crate::session_state::Prior::Partial(s) => (s, false),
    };
    let rule = &rules::file_reread::RULE;
    let stance = crate::stance::resolve(rule);
    let stance = if exact {
        stance
    } else {
        stance.min(Stance::Advise)
    };
    let (reason, remedy) = rules::file_reread::phrase(shown, &seen);
    let outcome = match stance {
        Stance::Observe => "watched",
        Stance::Advise => "advised",
        Stance::Deny => "denied",
    };
    journal::record(&journal::Entry {
        rule: rule.id,
        stance: stance.as_str(),
        outcome,
        session,
        repo: &repo_name(cwd),
        mode,
        excerpt: shown,
    });
    Reread {
        seen: true,
        text: match stance {
            Stance::Observe => None,
            Stance::Advise => Some(decision::phrase(rule.id, &reason, &remedy)),
            Stance::Deny => Some(decision::phrase(rule.id, &reason, &remedy)),
        },
        stance,
    }
}

fn note_file(rule: &Rule, stance: Stance, op: &crate::payload::FileOp, shown: &str) {
    journal::record(&journal::Entry {
        rule: rule.id,
        stance: stance.as_str(),
        outcome: match stance {
            Stance::Observe => "watched",
            Stance::Advise => "advised",
            Stance::Deny => "denied",
        },
        session: &op.session,
        repo: &repo_name(&op.cwd),
        mode: &op.permission_mode,
        excerpt: shown,
    });
}

fn resolve_path(cwd: &std::path::Path, text: &str) -> std::path::PathBuf {
    if text.starts_with('/') {
        std::path::PathBuf::from(text)
    } else if let Some(rest) = text.strip_prefix("~/") {
        std::env::var_os("HOME")
            .map(|h| std::path::PathBuf::from(h).join(rest))
            .unwrap_or_else(|| cwd.join(text))
    } else {
        cwd.join(text)
    }
}

/// What a confirmed finding carries into the decision: a stance floor, and
/// for a rule that learned its reason by looking, the reason and the journal
/// excerpt to use instead of the finding's.
struct Confirmation {
    floor: Option<Stance>,
    ceiling: Option<Stance>,
    said: Option<(String, String, Option<String>)>,
}

/// Rules whose `confirm` reads nothing from the working directory, so a
/// session left in a removed worktree is judged like any other. Next to the
/// publication gates in [`unknown_directory`], which need one.
const NEEDS_NO_DIRECTORY: [&str; 1] = [rules::publish_without_skill::RULE.id];

/// What a rule's `confirm` sees of a Bash call that has not run yet.
fn context<'a>(bash: &'a Bash, parsed: &'a Parsed) -> Context<'a> {
    Context {
        platform: Some(crate::rules::Platform::host()),
        cwd: &bash.cwd,
        parsed,
        background: bash.background,
        timeout_ms: bash.timeout_ms,
        tool_use_id: &bash.tool_use_id,
        transcript: bash.transcript.as_deref(),
        agent_transcript: bash.agent_transcript.as_deref(),
        command: &bash.command,
        output: None,
        session: &bash.session,
        failed: false,
    }
}

/// What a refusal of a Bash call is bound to.
enum OnceTarget {
    /// Nothing: the rule refuses every time, as rules always have.
    Always,
    /// The file a refuse-once rule's dump names (`whole-file-dump`,
    /// deliberate-output plan Phase 3), with the directory its clause runs
    /// in: the first whole dump of it by this agent is refused, the same
    /// command repeated passes.
    File {
        path: std::path::PathBuf,
        cwd: std::path::PathBuf,
    },
    /// A refuse-once dump whose file could not be resolved again, journalled
    /// `unrecorded`: never refuse what cannot be promised to pass again.
    Unresolved,
}

fn once_target(rule: &Rule, finding: &Finding, bash: &Bash, parsed: &Parsed) -> OnceTarget {
    if rule.id != rules::whole_file_dump::RULE.id {
        return OnceTarget::Always;
    }
    let context = context(bash, parsed);
    match rules::whole_file_dump::target(&context, finding) {
        Ok(target) => OnceTarget::File {
            path: target.path,
            cwd: context.cwd_at(finding.span.start),
        },
        // `confirm` resolved this same dump a moment ago, so only `HOME`
        // changing in between gets here.
        Err(why) => {
            note_with(rule, "deny", "unrecorded", bash, finding, Some(why));
            OnceTarget::Unresolved
        }
    }
}

fn confirmed(
    rule: &Rule,
    stance: Stance,
    finding: &Finding,
    bash: &Bash,
    parsed: &Parsed,
) -> Result<Confirmation, &'static str> {
    let Some(confirm) = rule.confirm else {
        return Ok(Confirmation {
            floor: None,
            ceiling: None,
            said: None,
        });
    };
    let ctx = context(bash, parsed);
    // The directory that matters is the one the matched clause runs in,
    // `cd`s followed — not the session's. A session left in a removed
    // worktree still runs `cd /abs/repo && git push …` in a real repository,
    // and that push must be judged (#67).
    if !ctx.cwd_at(finding.span.start).is_dir() && !NEEDS_NO_DIRECTORY.contains(&rule.id) {
        return unknown_directory(rule, stance, finding, bash);
    }
    match confirm(&ctx, finding) {
        Confirmed::Yes => Ok(Confirmation {
            floor: None,
            ceiling: None,
            said: None,
        }),
        Confirmed::YesAt(floor) => Ok(Confirmation {
            floor: Some(floor),
            ceiling: None,
            said: None,
        }),
        Confirmed::YesSaying {
            floor,
            ceiling,
            reason,
            excerpt,
            remedy,
        } => Ok(Confirmation {
            floor,
            ceiling,
            said: Some((reason, excerpt, remedy)),
        }),
        Confirmed::No(why) => Err(why),
    }
}

/// What `check` reports for a fired rule: the stance the hook would hold it
/// at after `confirm`, and the reason and remedy when `confirm` learned them
/// by looking.
pub struct Checked {
    pub stance: Stance,
    pub said: Option<(String, Option<String>)>,
}

/// How much of a command was read.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Reading {
    Whole,
    Partial,
}

/// How much of the command a rule's finding stands on. The override rule
/// reads the raw text of a clause the lexer left opaque (`bash -c '…'`), so
/// its finding is not a partial reading and may refuse.
fn reading_for(rule: &Rule, parsed: &Parsed) -> Reading {
    if rule.id == rules::suppressions_override::RULE.id {
        return Reading::Whole;
    }
    reading_of(parsed)
}

fn reading_of(parsed: &Parsed) -> Reading {
    if parsed.fully_read() {
        Reading::Whole
    } else {
        Reading::Partial
    }
}

/// The stance a finding is acted on at: the resolved one, raised to the
/// confirm's floor (only when it already advises, capped by the rule's
/// maximum), held at advise on a half-read command so a partial reading never
/// refuses, then held under the confirm's own ceiling. The hook and `check`
/// both come here.
pub fn final_stance(
    resolved: Stance,
    floor: Option<Stance>,
    ceiling: Option<Stance>,
    reading: Reading,
    max_stance: Stance,
) -> Stance {
    let mut stance = resolved;
    if let Some(floor) = floor {
        if stance >= Stance::Advise {
            stance = stance.max(floor).min(max_stance);
        }
    }
    if reading == Reading::Partial {
        stance = stance.min(Stance::Advise);
    }
    ceiling.map_or(stance, |c| stance.min(c))
}

/// `confirm` as the hook runs it, for a command typed to `check`: a [`Bash`]
/// with no transcript and no session, in `cwd`, through [`confirmed`] itself so
/// that there is one construction of the context.
pub fn confirmed_for_check(
    rule: &Rule,
    finding: &Finding,
    command: &str,
    cwd: &std::path::Path,
    parsed: &Parsed,
) -> Result<Checked, &'static str> {
    let bash = Bash {
        command: command.to_string(),
        cwd: cwd.to_path_buf(),
        session: String::new(),
        permission_mode: String::new(),
        background: false,
        timeout_ms: None,
        tool_use_id: String::new(),
        prompt_id: String::new(),
        stdout: None,
        stderr: None,
        error: None,
        has_response: false,
        errored: false,
        agent_id: None,
        transcript: None,
        agent_transcript: None,
        agent: crate::lsp::Agent::Main,
    };
    let resolved = crate::stance::resolve(rule);
    let Confirmation {
        floor,
        ceiling,
        said,
    } = confirmed(rule, resolved, finding, &bash, parsed)?;
    let stance = final_stance(
        resolved,
        floor,
        ceiling,
        reading_for(rule, parsed),
        rule.max_stance,
    );
    Ok(Checked {
        stance,
        said: said.map(|(reason, _, remedy)| (reason, remedy)),
    })
}

/// The matched clause runs in a directory that does not exist. Most rules
/// have nothing to look at and decline. The publication gates cannot: when
/// the session's directory is gone the shell does not run there either —
/// Claude Code resets it to the project root — so a push with no `cd` of
/// its own publishes from a repository this hook cannot name. Under deny
/// that is held, like any other push shape the gate cannot read.
fn unknown_directory(
    rule: &Rule,
    stance: Stance,
    finding: &Finding,
    bash: &Bash,
) -> Result<Confirmation, &'static str> {
    const WHY: &str = "the working directory does not exist";
    let gates = [
        crate::push_preview::RULE.id,
        crate::implementation_review_rule::RULE.id,
    ];
    if stance != Stance::Deny || !gates.contains(&rule.id) {
        return Err(WHY);
    }
    let excerpt = crate::backtest::excerpt(&bash.command, finding.span.start, finding.span.end);
    Ok(Confirmation {
        floor: None,
        ceiling: None,
        said: Some((
            "This push runs in a directory that does not exist, so the repository it \
             publishes from cannot be named."
                .to_string(),
            excerpt,
            Some(
                "Start the command with `cd <repository> &&`, or push with \
                 `git -C <repository> push …`."
                    .to_string(),
            ),
        )),
    })
}

fn note(rule: &Rule, stance: &str, outcome: &str, bash: &Bash, finding: &Finding) {
    note_with(rule, stance, outcome, bash, finding, None);
}

/// [`note`], with the journal excerpt a `confirm` chose in place of the
/// command span.
fn note_with(
    rule: &Rule,
    stance: &str,
    outcome: &str,
    bash: &Bash,
    finding: &Finding,
    excerpt: Option<&str>,
) {
    let span = crate::backtest::excerpt(&bash.command, finding.span.start, finding.span.end);
    let excerpt = excerpt.unwrap_or(&span);
    // A rule built on the shell analysis judged the command under a dialect
    // the replay cannot recover from a transcript, so the record carries it:
    // `bypassPermissions+zsh`. Folded into the mode token, which nothing
    // parses, so the journal format is unchanged.
    let mode = match rule.examine {
        rules::Examine::Analysis(_) | rules::Examine::Live(_) => format!(
            "{}+{}",
            bash.permission_mode,
            rules::tool_shell::dialect().as_str()
        ),
        rules::Examine::Legacy(_) => bash.permission_mode.clone(),
    };
    journal::record(&journal::Entry {
        rule: rule.id,
        stance,
        outcome,
        session: &bash.session,
        repo: &attributed_repo(rule.id, bash),
        mode: &mode,
        excerpt,
    });
}

/// The repository a journal line names. For the preview gate's push records
/// that is the repository the push runs in — `cd`s and `-C` followed — not
/// the session's: a session in one worktree pushing another must not log
/// the push under the first one's name.
fn attributed_repo(id: &str, bash: &Bash) -> String {
    let pushes = [
        crate::push_preview::RULE.id,
        crate::implementation_review_rule::RULE.id,
        crate::assertions::push_published::ASSERTION.id,
        crate::assertions::land_retry::ASSERTION.id,
    ];
    if !pushes.contains(&id) {
        return repo_name(&bash.cwd);
    }
    let parsed = shell::lex(&bash.command);
    let resolved = crate::push_target::find(&parsed).and_then(|cmd| {
        let ctx = Context {
            platform: Some(crate::rules::Platform::host()),
            cwd: &bash.cwd,
            parsed: &parsed,
            background: bash.background,
            timeout_ms: bash.timeout_ms,
            tool_use_id: &bash.tool_use_id,
            transcript: bash.transcript.as_deref(),
            agent_transcript: bash.agent_transcript.as_deref(),
            command: &bash.command,
            output: None,
            session: &bash.session,
            failed: false,
        };
        crate::push_target::repository(&ctx.cwd_at(cmd.at), cmd)
    });
    match resolved.as_deref().and_then(std::path::Path::file_name) {
        Some(n) => n.to_string_lossy().into_owned(),
        None => repo_name(&bash.cwd),
    }
}

/// The basename of the repository, not its path. Enough to group firings by
/// project without writing `/Users/<name>/…` into a log file.
fn repo_name(cwd: &std::path::Path) -> String {
    let mut dir = cwd;
    loop {
        if dir.join(".git").exists() {
            break;
        }
        match dir.parent() {
            Some(p) => dir = p,
            None => break,
        }
    }
    dir.file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| "-".to_string())
}

/// One line, rewritten by rename so it is always current and always whole.
/// `doctor` compares it against the newest transcript timestamp: transcripts
/// prove sessions happened, this proves the guard ran in one.
fn heartbeat() {
    let Some(dir) = journal::dir() else { return };
    if std::fs::create_dir_all(&dir).is_err() {
        return;
    }
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    journal::private(&dir, 0o700);
    let tmp = dir.join("heartbeat.new");
    if std::fs::write(&tmp, format!("{now} {}\n", env!("CARGO_PKG_VERSION"))).is_ok() {
        // Narrowed BEFORE the rename, so no window exists in which the
        // finished file is readable by anyone but its owner. It carries only
        // a timestamp and a version, but it sits in the same directory as the
        // journal and there is no reason for the two to disagree about who
        // may read them.
        journal::private(&tmp, 0o600);
        let _ = std::fs::rename(&tmp, dir.join("heartbeat"));
    }
}

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

    fn text(d: Decision) -> (&'static str, String) {
        match d {
            Decision::Silent => ("silent", String::new()),
            Decision::Advise(t) => ("advise", t),
            Decision::Deny(t) => ("deny", t),
            Decision::Ask(t) => ("ask", t),
            Decision::Context(t)
            | Decision::Assert(t)
            | Decision::AssertAfterFailure(t)
            | Decision::Continue(t)
            | Decision::UserNote(t) => ("other", t),
        }
    }

    #[test]
    fn silence_stays_silent() {
        assert_eq!(
            text(combine([Decision::Silent, Decision::Silent])).0,
            "silent"
        );
    }

    #[test]
    fn advice_is_joined_with_a_blank_line() {
        let (kind, t) = text(combine([
            Decision::Advise("one".into()),
            Decision::Silent,
            Decision::Advise("two".into()),
        ]));
        assert_eq!((kind, t.as_str()), ("advise", "one\n\ntwo"));
    }

    #[test]
    fn any_deny_denies_and_carries_every_text() {
        let (kind, t) = text(combine([
            Decision::Advise("one".into()),
            Decision::Deny("two".into()),
            Decision::Advise("three".into()),
        ]));
        assert_eq!((kind, t.as_str()), ("deny", "one\n\ntwo\n\nthree"));
    }

    #[test]
    fn an_ask_beats_advice_and_carries_every_text() {
        let (kind, t) = text(combine([
            Decision::Advise("one".into()),
            Decision::Ask("two".into()),
        ]));
        assert_eq!((kind, t.as_str()), ("ask", "one\n\ntwo"));
    }

    #[test]
    fn a_deny_beats_an_ask() {
        let (kind, t) = text(combine([
            Decision::Ask("one".into()),
            Decision::Deny("two".into()),
        ]));
        assert_eq!((kind, t.as_str()), ("deny", "one\n\ntwo"));
    }

    #[test]
    fn text_from_another_event_is_kept_as_advice() {
        let (kind, t) = text(combine([Decision::Context("one".into())]));
        assert_eq!((kind, t.as_str()), ("advise", "one"));
    }
}