fno-agents 0.3.1

PTY supervisor substrate for persistent, attachable multi-CLI coding agents (codex, gemini, claude)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
//! `fno-agents loop-check` verb (Task 1.1, ab-d0337fbc).
//!
//! Single entry-point decision-maker for the target stop hook. Reads external
//! state (manifest, transcript, git, gh, events, ledger) and returns a JSON
//! decision object. The manifest is NEVER mutated; the only write surface is
//! append-only event logs.
//!
//! Module name starts with "loop" to match the LOC-ratchet glob `crates/fno-agents/src/loop*`.

use crate::{completion_output::allow_output, delivery_completion::pr_passes};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

// ── public types ──────────────────────────────────────────────────────────────

/// Why the loop terminated. Serialized as the exact string enum the spec names.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TerminationReason {
    DonePRGreen,
    DoneAdvisory,
    DoneDelivery,
    /// A batch-lane member (batch-lane Wave 2/3): its commits live on a shared
    /// batch branch and ship via the batch PR, not its own, so there is no
    /// per-node PR to go green. Terminal, but NOT a ship reason - the batch's
    /// own `/pr create` graduates the plan; a member must not.
    DoneBatched,
    /// Work complete (PR open, mergeable, reviewed, HEAD shipped) but `done()`
    /// fails SOLELY on CI-green because main itself is red on the same checks,
    /// and a bg agent cannot merge. Proven pre-existing main-red (strict
    /// check-name subset against current main HEAD) terminates the loop with a
    /// one-shot merge-recommendation notify instead of burning to NoProgress.
    /// Terminal, but NOT a ship reason (like DoneBatched): never merges, never
    /// marks the node done - a human merge then the out-of-band-merge reconcile
    /// path closes it, and DonePRGreen always wins when observable.
    DoneAwaitingMerge,
    /// A plan-only thread reached the plan boundary cleanly (manifest `planned`
    /// flag + a promise). It produced planning output, not a delivery, so it is
    /// terminal but deliberately NOT a ship reason (out of finalize.SHIP_REASONS
    /// -> no plan stamp/graduate) and NOT a postmortem reason (a plan is not
    /// stuck). Benign like NoWork; distinct from DoneAdvisory, which DOES
    /// graduate. The scoreboard's `planned` bucket is keyed on the phase set,
    /// never on this terminal.
    DonePlanned,
    NoWork,
    Budget,
    NoProgress,
    Interrupted,
    Aborted,
}

// ── manifest parsing ──────────────────────────────────────────────────────────

/// Fields parsed from target-state.md YAML frontmatter.
#[derive(Debug)]
struct Manifest {
    session_id: Option<String>,
    created_at: Option<String>,
    attended: bool, // default true when absent
    advisory: bool,
    no_ship: bool,
    no_external: bool,
    /// batch-lane member: commits ship via the batch PR, not a per-node PR.
    batched: bool,
    /// plan-only thread: reaches the plan boundary and terminates DonePlanned
    /// (not DoneAdvisory, which would graduate the plan).
    planned: bool,
    /// Plan doc backing this session; source of the `done_probes` declaration.
    plan_path: Option<String>,
    legacy_status: Option<String>, // COMPLETE | BLOCKED | ABORTED
    /// None = absent (unlimited). Some(Ok(v)) = valid cap. Some(Err(s)) = malformed raw value.
    budget_wall_clock_cap_minutes: Option<Result<u64, String>>,
    /// None = absent (unlimited). Some(Ok(v)) = valid cap. Some(Err(s)) = malformed raw value.
    budget_cost_cap_usd: Option<Result<f64, String>>,
}

impl Default for Manifest {
    fn default() -> Self {
        Self {
            session_id: None,
            created_at: None,
            attended: true, // spec: attended defaults to true
            advisory: false,
            no_ship: false,
            no_external: false,
            batched: false,
            planned: false,
            plan_path: None,
            legacy_status: None,
            budget_wall_clock_cap_minutes: None, // None = absent = unlimited
            budget_cost_cap_usd: None,           // None = absent = unlimited
        }
    }
}

/// Read a single `^<field>: value` line from ANYWHERE in the manifest, not just
/// the frontmatter block. `fno target init` writes the immutable frontmatter
/// first, then APPENDS the node-claim fields (`target_claim_key/holder/ttl`)
/// after the closing `---`, so `parse_manifest` (frontmatter-bounded) never sees
/// them. Renewal reads them here instead (x-ba4b). Surrounding quotes stripped.
fn scan_manifest_field(content: &str, field: &str) -> Option<String> {
    let prefix = format!("{field}:");
    content.lines().find_map(|line| {
        let line = line.trim();
        line.strip_prefix(&prefix)
            .map(|v| v.trim().trim_matches(|c| c == '"' || c == '\'').to_string())
            .filter(|v| !v.is_empty())
    })
}

/// Parse frontmatter from a `---\n...\n---\n` block at the top of a file.
/// Returns None if the file does not start with `---`.
/// Unknown fields are silently ignored.
fn parse_manifest(content: &str) -> Option<Manifest> {
    let content = content.trim_start();
    if !content.starts_with("---") {
        return None;
    }
    let after_first = &content[3..];
    // Find closing ---
    let end = after_first.find("\n---")?;
    let body = &after_first[..end];

    let mut m = Manifest {
        attended: true, // default
        ..Default::default()
    };

    for line in body.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if let Some((k, v)) = line.split_once(':') {
            let k = k.trim();
            // YAML string values may be quoted; strip surrounding quotes so a
            // quoted session_id/created_at parses identically (gemini MEDIUM).
            let v = v.trim().trim_matches(|c| c == '"' || c == '\'');
            match k {
                // fno_id is canonical and wins; session_id is the one-release
                // legacy fallback (never overwrites a resolved fno_id).
                "fno_id" => m.session_id = Some(v.to_string()),
                "session_id" => {
                    if m.session_id.is_none() {
                        m.session_id = Some(v.to_string());
                    }
                }
                "created_at" => m.created_at = Some(v.to_string()),
                "attended" => m.attended = v == "true",
                "advisory" => m.advisory = v == "true",
                "no_ship" => m.no_ship = v == "true",
                "no_external" => m.no_external = v == "true",
                "batched" => m.batched = v == "true",
                "planned" => m.planned = v == "true",
                "plan_path" => {
                    if !v.is_empty() {
                        m.plan_path = Some(v.to_string());
                    }
                }
                "status" => {
                    let upper = v.to_uppercase();
                    if matches!(upper.as_str(), "COMPLETE" | "BLOCKED" | "ABORTED") {
                        m.legacy_status = Some(upper);
                    }
                }
                "budget_wall_clock_cap_minutes" => {
                    // Manifests are machine-written numeric fields; tolerate a '#'-tail
                    // (e.g. `90# Auto-merge inputs`) by truncating at the first '#'.
                    let stripped = v
                        .split_once('#')
                        .map(|(before, _)| before.trim())
                        .unwrap_or(v);
                    m.budget_wall_clock_cap_minutes = Some(stripped.parse::<u64>().map_err(|_| {
                        eprintln!(
                            "loop-check: malformed budget cap 'budget_wall_clock_cap_minutes: {v}' - failing closed; fix the config"
                        );
                        v.to_string()
                    }));
                }
                "budget_cost_cap_usd" => {
                    let stripped = v
                        .split_once('#')
                        .map(|(before, _)| before.trim())
                        .unwrap_or(v);
                    m.budget_cost_cap_usd = Some(stripped.parse::<f64>().map_err(|_| {
                        eprintln!(
                            "loop-check: malformed budget cap 'budget_cost_cap_usd: {v}' - failing closed; fix the config"
                        );
                        v.to_string()
                    }));
                }
                _ => {}
            }
        }
    }
    Some(m)
}

// ── settings parsing ──────────────────────────────────────────────────────────

#[derive(Debug, Default)]
struct Settings {
    /// config.budget.attended.wall_clock_cap_minutes
    /// None = absent. Some(Ok(v)) = valid. Some(Err(s)) = malformed raw value.
    attended_wall_cap_minutes: Option<Result<u64, String>>,
    /// config.budget.attended.cost_cap_usd
    attended_cost_cap_usd: Option<Result<f64, String>>,
    /// config.budget.unattended.wall_clock_cap_minutes
    unattended_wall_cap_minutes: Option<Result<u64, String>>,
    /// config.budget.unattended.cost_cap_usd
    unattended_cost_cap_usd: Option<Result<f64, String>>,
    /// flat budget_cap: (folds in ab-41b13d9d) - applies as cost cap for both modes
    flat_budget_cap: Option<Result<f64, String>>,
    /// config.ci.declared_none: true
    ci_declared_none: bool,
    /// config.external_reviewers list
    external_reviewers: Vec<String>,
    /// config.review.github_apps (x-4baa; the GitHub App bot logins gate).
    /// None = key absent -> code default (empty, no gate).
    /// Some([]) = explicitly `[]` -> declared no-review-gate path.
    /// Some(list) = every listed login must have a completed review pass.
    github_apps: Option<Vec<String>>,
    /// config.review.required_bots: legacy alias for `github_apps` (a straight
    /// rename). `github_apps` wins when both are set. Same fail-closed rules.
    required_bots: Option<Vec<String>>,
    /// config.review.peers: local review harnesses. Identity-free entries form
    /// one composite, head-pinned local-attestation gate; entries with a shared
    /// or per-entry identity retain the legacy GitHub-login gate.
    peers: Vec<PeerEntry>,
    /// config.review.peer_identity: the shared login peers post under.
    peer_identity: Option<String>,
    /// config.review.optional_apps: reviewer logins honored-if-present but NOT
    /// required. The gate never WAITS for them (their absence never blocks -
    /// this kills the App-bot usage-limit wedge), but a blocking finding from
    /// one still holds the gate until addressed ("honor if present"). None =
    /// no optional reviewers.
    optional_apps: Option<Vec<String>>,
    /// config.review.reviewers (x-e703, Phase 2): local reviewer names (sigma |
    /// code-review | declare) satisfied by a head-pinned `review_attestation`
    /// event in events.jsonl, NOT a GitHub login. Empty = no reviewers gate
    /// (additive to the login gate; no "declared empty" distinction needed). A
    /// leading '/' is stripped on store so `/code-review` == `code-review`.
    /// Resolvability is validated Python-side; Rust fails closed by matching
    /// evidence, so an unresolvable name is simply never satisfied.
    reviewers: Vec<String>,
    /// config.review.nudge (x-b167): per-login overrides for the bot-review
    /// nudge, resolved against BOT_PROFILES by `resolved_nudge_configs`. Empty =
    /// no overrides (the built-in profiles alone decide nudgeability). A
    /// malformed entry degrades that login to non-nudgeable, never panics (AC8).
    nudge_overrides: Vec<NudgeOverride>,
    /// Top-level `done_probes` (x-a534): the repo-wide probe list, evaluated
    /// alongside the plan's own. The file is FLAT, so this reads off the TOML
    /// root, not out of a `config` table.
    ///
    /// None = key absent (no project gate). Some(Ok(list)) = the declaration.
    /// Some(Err(why)) = present but not an array of strings, which maps to the
    /// plan side's `Unparseable` and BLOCKS - a config key that degrades to
    /// no-gate is a guardrail that disappears when you typo it.
    done_probes: Option<Result<Vec<String>, String>>,
}

/// Normalize a config.review.reviewers entry / an event's reviewer name: strip a
/// leading '/' so `/code-review` and `code-review` name the same reviewer
/// (parity with the Python validator). Quote/comment stripping is the caller's.
fn normalize_reviewer(raw: &str) -> String {
    raw.trim().trim_start_matches('/').to_string()
}

/// Fail-closed sentinel for a structurally-malformed `reviewers:` value (e.g. a
/// `{...}` mapping). Python raises loudly on such a value; the Rust parser must
/// NOT silently drop it to an empty list (= no gate, fail OPEN). Instead it
/// stores this sentinel so the gate stays active but UNSATISFIABLE - the NUL
/// byte can never appear in an emitted `review_attestation.reviewer`, so no
/// evidence ever clears it (codex peer review P1).
const MALFORMED_REVIEWERS_SENTINEL: &str = "\u{0}malformed-reviewers";

/// A `config.review.peers` entry. `provider` is kept for messaging and the
/// same-model guard; `model` carries an optional `"route_provider,route_model"`
/// route (the claude CLI as transport for a genuinely different model); the gate
/// identity selects the legacy posting carrier; otherwise the entry contributes
/// to the composite local-attestation gate.
#[derive(Debug, Default, Clone)]
struct PeerEntry {
    provider: String,
    model: Option<String>,
    identity: Option<String>,
}

/// Strip a trailing YAML inline comment (` # ...`) from a raw scalar value
/// (codex P2 on #448). YAML requires whitespace before the `#`; a value that
/// IS a comment strips to empty. Quoted values containing '#' are out of
/// scope for this minimal parser (no known bot login contains '#').
fn strip_inline_comment(raw: &str) -> &str {
    if raw.starts_with('#') {
        return "";
    }
    match raw.find(" #").or_else(|| raw.find("\t#")) {
        Some(i) => raw[..i].trim_end(),
        None => raw,
    }
}

/// Fail-closed sentinel for an unparseable config.toml (x-81d9 (c)). A
/// scanner error (e.g. tab-indentation, which YAML forbids) previously caused
/// the hand-parser to silently drop the whole config.review subtree, yielding
/// zero required_bots and shipping the PR unreviewed. Now such a file fails
/// CLOSED: this sentinel is placed in the login gate so it can never be
/// satisfied (no real bot login contains a NUL), the gate blocks visibly, and a
/// `loop_check_settings_unparseable` event records it. Distinct from
/// MALFORMED_REVIEWERS_SENTINEL so an audit sees which gate the config tripped.
const UNPARSEABLE_SETTINGS_SENTINEL: &str = "\u{0}unparseable-settings\u{0}";

/// A bare scalar RHS (`key: value`) as a single-item login list. Used when a
/// list key was written scalar-form: it must GATE on that one login, never
/// silently fail open to "no gate" (codex P1 on #205). A structurally-malformed
/// value (a `{...}` flow mapping) is NOT a login - degrade to None so both
/// parsers agree (Python's typed reader drops a mapping to None too; codex P1 on
/// the two-parser-agreement invariant). Empty -> None.
fn scalar_as_singleton(rest: &str) -> Option<Vec<String>> {
    let v = strip_inline_comment(rest.trim())
        .trim_matches(|c| c == '"' || c == '\'')
        .to_string();
    if v.is_empty() || v.contains('{') || v.contains('}') {
        None
    } else {
        Some(vec![v])
    }
}

/// A TOML scalar (string / integer / float / bool) as a String; None for
/// structured values (array / table). Numbers and bools stringify so a
/// `required_bots = 123` or a stray bool still coerces to a login string,
/// matching the old scalar-tolerant behavior.
fn scalar_string(v: &toml::Value) -> Option<String> {
    match v {
        toml::Value::String(s) => Some(s.clone()),
        toml::Value::Boolean(b) => Some(b.to_string()),
        toml::Value::Integer(n) => Some(n.to_string()),
        toml::Value::Float(f) => Some(f.to_string()),
        _ => None,
    }
}

/// Classify a config.review LOGIN list value (`required_bots` / `github_apps` /
/// `optional_apps`) off a typed TOML Value, matching the Python loader:
///   absent        -> None            (key absent; code default = no gate)
///   array         -> Some(items)     (empty stays Some(empty) = declared no-gate)
///   scalar        -> singleton gate  (a bare `key = "codex"` still GATES on codex)
///   table/other   -> None            (an inline table is not a login; Python drops it)
fn value_as_login_list(v: &toml::Value) -> Option<Vec<String>> {
    match v {
        toml::Value::Array(items) => Some(items.iter().filter_map(scalar_string).collect()),
        // A bare scalar routes through scalar_as_singleton so its brace/empty
        // semantics (and the direct unit test) stay live and Python-aligned.
        toml::Value::String(_)
        | toml::Value::Boolean(_)
        | toml::Value::Integer(_)
        | toml::Value::Float(_) => scalar_string(v).and_then(|s| scalar_as_singleton(&s)),
        // Table / other: not a login gate -> None (Python parity).
        _ => None,
    }
}

/// One `[review.nudge]` per-login override (x-b167). Every field is optional in
/// TOML; a value of the wrong type sets `malformed` so that login degrades to
/// non-nudgeable rather than panicking - the stop gate must never panic (AC8).
#[derive(Debug, Clone, Default)]
struct NudgeOverride {
    login: String,
    review_handle: Option<String>,
    wait_minutes: Option<i64>,
    ceiling: Option<usize>,
    /// Defaults to true; `enabled = false` opts a repo out (back to plain
    /// block-and-wait, NOT a faster give-up).
    enabled: bool,
    /// Any field of the wrong type: the whole login drops to non-nudgeable.
    malformed: bool,
}

/// Parse the `[review.nudge]` table (`login -> { review_handle, wait_minutes,
/// ceiling, enabled }`). Lenient by construction, matching `value_as_login_list`:
/// a non-table value, or any field of the wrong type / a non-positive integer,
/// marks that login `malformed`. Never panics (AC8).
fn value_as_nudge_overrides(v: &toml::Value) -> Vec<NudgeOverride> {
    let Some(table) = v.as_table() else {
        // The whole `nudge` value is not a table (scalar/list): no overrides.
        return Vec::new();
    };
    let mut out = Vec::new();
    for (login, entry) in table {
        let mut ov = NudgeOverride {
            login: login.clone(),
            enabled: true,
            ..Default::default()
        };
        let Some(map) = entry.as_table() else {
            // A scalar or list where an inline table was expected (AC8).
            ov.malformed = true;
            out.push(ov);
            continue;
        };
        if let Some(rh) = map.get("review_handle") {
            match rh.as_str() {
                Some(s) => ov.review_handle = Some(s.to_string()),
                None => ov.malformed = true,
            }
        }
        if let Some(wm) = map.get("wait_minutes") {
            match wm.as_integer() {
                // Upper-bounded so `chrono::Duration::minutes` (which panics
                // above i64::MAX/60) can never take the stop gate down on an
                // absurd config value; anything out of range is malformed.
                Some(n) if (1..=MAX_NUDGE_WAIT_MINUTES).contains(&n) => ov.wait_minutes = Some(n),
                _ => ov.malformed = true, // non-int, non-positive, or absurd (AC8)
            }
        }
        if let Some(c) = map.get("ceiling") {
            match c.as_integer() {
                Some(n) if (1..=MAX_NUDGE_CEILING).contains(&n) => ov.ceiling = Some(n as usize),
                _ => ov.malformed = true,
            }
        }
        if let Some(en) = map.get("enabled") {
            match en.as_bool() {
                Some(b) => ov.enabled = b,
                None => ov.malformed = true,
            }
        }
        out.push(ov);
    }
    out
}

/// Classify a config.review.reviewers value (x-e703 local-attestation gate).
/// Unlike the login lists, a structurally-wrong mapping fails CLOSED (Python
/// raises) via the unsatisfiable sentinel, never a silent empty gate. A leading
/// '/' is normalized off each entry.
fn value_as_reviewers(v: &toml::Value) -> Vec<String> {
    match v {
        toml::Value::Array(items) => {
            let mut out = Vec::new();
            for it in items {
                match scalar_string(it) {
                    Some(s) => {
                        let n = normalize_reviewer(&s);
                        if !n.is_empty() {
                            out.push(n);
                        }
                    }
                    // A non-scalar item (nested table/array) is structurally
                    // wrong; Python raises on it, so fail CLOSED with the
                    // sentinel rather than silently dropping it (gemini medium) -
                    // matches the top-level-table arm below.
                    None => return vec![MALFORMED_REVIEWERS_SENTINEL.to_string()],
                }
            }
            out
        }
        toml::Value::String(s) => {
            let n = normalize_reviewer(s);
            if n.is_empty() {
                Vec::new()
            } else {
                vec![n]
            }
        }
        // A table (or other structural shape) fails closed, not empty.
        _ => vec![MALFORMED_REVIEWERS_SENTINEL.to_string()],
    }
}

/// Classify a config.review.peers value into PeerEntry list. A sequence item is
/// either a scalar (provider only) or a mapping whose `provider`/`identity` keys
/// are read order-independently (a real map, so no hand key-order handling). A
/// bare scalar `peers: codex` is one provider (Python's coerce_peers).
fn value_as_peers(v: &toml::Value) -> Vec<PeerEntry> {
    let scalar_entry = |s: String| PeerEntry {
        provider: s,
        model: None,
        identity: None,
    };
    // One table entry -> a PeerEntry (provider/model/identity read order-independently).
    let map_entry = |it: &toml::Value| -> Option<PeerEntry> {
        let provider = it
            .get("provider")
            .and_then(scalar_string)
            .unwrap_or_default();
        let model = it
            .get("model")
            .and_then(scalar_string)
            .filter(|s| !s.is_empty());
        let identity = it
            .get("identity")
            .and_then(scalar_string)
            .filter(|s| !s.is_empty());
        if provider.is_empty() && identity.is_none() {
            None
        } else {
            Some(PeerEntry {
                provider,
                model,
                identity,
            })
        }
    };
    match v {
        toml::Value::Array(items) => items
            .iter()
            .filter_map(|it| match it {
                toml::Value::Table(_) => map_entry(it),
                _ => scalar_string(it)
                    .filter(|s| !s.is_empty())
                    .map(scalar_entry),
            })
            .collect(),
        toml::Value::String(s) if !s.is_empty() => vec![scalar_entry(s.clone())],
        // A single top-level table is ONE peer - parity with Python's
        // coerce_peers, which wraps a dict as [dict]. Dropping it to empty (as
        // this arm did before the codex peer review) silently discards a
        // configured peer gate -> fail-open, the class this PR removes.
        toml::Value::Table(_) => map_entry(v).into_iter().collect(),
        _ => Vec::new(),
    }
}

/// Read an f64 budget cap off a typed Value: a number is Ok, a non-numeric
/// scalar fails CLOSED as Some(Err(raw)) (so check_budget trips), an
/// absent/null key is None (unlimited). Mirrors the manifest cap semantics.
fn read_f64_cap(v: &toml::Value, ctx: &str) -> Option<Result<f64, String>> {
    match v {
        toml::Value::Integer(n) => Some(Ok(*n as f64)),
        toml::Value::Float(f) => Some(Ok(*f)),
        other => {
            let raw = scalar_string(other).unwrap_or_default();
            Some(raw.parse::<f64>().map_err(|_| {
                eprintln!(
                    "loop-check: malformed budget cap '{ctx}: {raw}' - failing closed; fix the config"
                );
                raw
            }))
        }
    }
}

/// Read a u64 budget cap off a typed Value (same fail-closed rule as f64).
fn read_u64_cap(v: &toml::Value, ctx: &str) -> Option<Result<u64, String>> {
    match v {
        toml::Value::Integer(n) => Some(u64::try_from(*n).map_err(|_| {
            eprintln!(
                "loop-check: malformed budget cap '{ctx}: {n}' - failing closed; fix the config"
            );
            n.to_string()
        })),
        other => {
            let raw = scalar_string(other).unwrap_or_default();
            Some(raw.parse::<u64>().map_err(|_| {
                eprintln!(
                    "loop-check: malformed budget cap '{ctx}: {raw}' - failing closed; fix the config"
                );
                raw
            }))
        }
    }
}

/// Classify a top-level `done_probes` value as a probe list or a reason it is
/// unreadable. An empty array is a legitimate "no project probes"; a mapping,
/// a scalar, or an array holding a non-string is NOT - it is a mis-declared
/// gate, and the Err travels to the gate so it blocks with a reason instead of
/// silently reading as no declaration at all.
fn value_as_probe_list(v: &toml::Value) -> Result<Vec<String>, String> {
    let items = v
        .as_array()
        .ok_or_else(|| format!("it is a {}, not an array of strings", v.type_str()))?;
    items
        .iter()
        .map(|i| {
            i.as_str().map(str::to_string).ok_or_else(|| {
                format!(
                    "it holds a {} where a command string was expected",
                    i.type_str()
                )
            })
        })
        .collect()
}

/// Settings with the login gate pinned unsatisfiable - the fail-closed result
/// when config.toml cannot be parsed as TOML at all (x-81d9 (c)). The
/// sentinel goes into BOTH github_apps and required_bots: resolved_required_bots
/// prefers github_apps.or(required_bots), so pinning required_bots alone would
/// be silently outranked by a parseable global file's github_apps during the
/// global+local merge (an unparseable LOCAL file would then resolve to the
/// global gate, re-opening the fail-open this fix removes).
fn fail_closed_settings() -> Settings {
    let sentinel = Some(vec![UNPARSEABLE_SETTINGS_SENTINEL.to_string()]);
    Settings {
        github_apps: sentinel.clone(),
        required_bots: sentinel,
        ..Default::default()
    }
}

/// Parse config.toml with the `toml` crate (stage 3), replacing the
/// former hand-rolled indent state machine that derived one global indent unit
/// and silently dropped the config.review subtree on tabs or mixed widths
/// (x-81d9 (c)). A genuine YAML scanner error (e.g. tab indentation) returns
/// Err so the caller can fail closed + emit an event, rather than silently
/// zeroing the gate. The typed-Value classification preserves every semantic
/// the old ListForm branches encoded (see the value_as_* helpers).
fn parse_settings_result(content: &str) -> Result<Settings, String> {
    let root: toml::Value = content.parse::<toml::Value>().map_err(|e| e.to_string())?;
    let mut s = Settings::default();

    // Top-level flat budget cap.
    if let Some(v) = root.get("budget_cap") {
        s.flat_budget_cap = read_f64_cap(v, "budget_cap");
    }

    // Top-level flat `done_probes` (x-a534). Presence is recorded even when the
    // value is junk: the Err arm blocks downstream rather than degrading to
    // "no probes declared".
    if let Some(v) = root.get("done_probes") {
        s.done_probes = Some(value_as_probe_list(v));
    }

    // Flat config.toml: budget / ci / external_reviewers / review are top-level
    // blocks (no `config:` wrapper). Read them straight off root.
    if let Some(budget) = root.get("budget") {
        if let Some(att) = budget.get("attended") {
            if let Some(v) = att.get("wall_clock_cap_minutes") {
                s.attended_wall_cap_minutes = read_u64_cap(v, "attended.wall_clock_cap_minutes");
            }
            if let Some(v) = att.get("cost_cap_usd") {
                s.attended_cost_cap_usd = read_f64_cap(v, "attended.cost_cap_usd");
            }
        }
        if let Some(un) = budget.get("unattended") {
            if let Some(v) = un.get("wall_clock_cap_minutes") {
                s.unattended_wall_cap_minutes =
                    read_u64_cap(v, "unattended.wall_clock_cap_minutes");
            }
            if let Some(v) = un.get("cost_cap_usd") {
                s.unattended_cost_cap_usd = read_f64_cap(v, "unattended.cost_cap_usd");
            }
        }
    }

    if let Some(ci) = root.get("ci") {
        s.ci_declared_none = ci
            .get("declared_none")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
    }

    if let Some(er) = root.get("external_reviewers") {
        if let Some(items) = er.as_array() {
            s.external_reviewers = items.iter().filter_map(scalar_string).collect();
        }
    }

    if let Some(review) = root.get("review") {
        if let Some(v) = review.get("required_bots") {
            s.required_bots = value_as_login_list(v);
        }
        if let Some(v) = review.get("github_apps") {
            s.github_apps = value_as_login_list(v);
        }
        if let Some(v) = review.get("optional_apps") {
            s.optional_apps = value_as_login_list(v);
        }
        if let Some(v) = review.get("reviewers") {
            s.reviewers = value_as_reviewers(v);
        }
        if let Some(v) = review.get("nudge") {
            s.nudge_overrides = value_as_nudge_overrides(v);
        }
        if let Some(v) = review.get("peers") {
            s.peers = value_as_peers(v);
        }
        if let Some(v) = review.get("peer_identity") {
            s.peer_identity = scalar_string(v).filter(|s| !s.is_empty());
        }
    }

    Ok(s)
}

/// Infallible wrapper: an unparseable file fails CLOSED (unsatisfiable login
/// gate) rather than silently defaulting to no gate. Test-only - production
/// calls parse_settings_result directly so it can also emit the
/// `loop_check_settings_unparseable` event on the Err path.
#[cfg(test)]
fn parse_settings(content: &str) -> Settings {
    parse_settings_result(content).unwrap_or_else(|_| fail_closed_settings())
}

// ── ledger parsing ────────────────────────────────────────────────────────────

/// Sum cost_usd for entries matching session_id. Tolerate missing/malformed as 0.
fn session_cost_from_ledger(ledger_path: &Path, session_id: &str) -> f64 {
    let Ok(content) = std::fs::read_to_string(ledger_path) else {
        return 0.0;
    };
    let Ok(arr) = serde_json::from_str::<Value>(&content) else {
        return 0.0;
    };
    let Some(entries) = arr.as_array() else {
        return 0.0;
    };
    let mut total = 0.0_f64;
    for entry in entries {
        // Either key: new rows carry fno_id, pre-rename rows only session_id.
        let matches = entry.get("fno_id").and_then(|v| v.as_str()) == Some(session_id)
            || entry.get("session_id").and_then(|v| v.as_str()) == Some(session_id);
        if matches {
            if let Some(c) = entry.get("cost_usd").and_then(|v| v.as_f64()) {
                total += c;
            }
        }
    }
    total
}

// ── transcript parsing ────────────────────────────────────────────────────────

#[derive(Debug, PartialEq)]
enum Intent {
    Promise,
    Aborted {
        reason: String,
    },
    /// Agent-declared async watch (x-e2c8): it has armed a harness-tracked
    /// watcher and wants the session to idle until that watcher fires rather
    /// than re-blocking every stop tick. All attributes are advisory (used for
    /// the event and the lease math), never load-bearing: external truth
    /// decides whether idling is actually allowed.
    Watching {
        reason: String,
        pr: Option<String>,
        timeout: Option<String>,
    },
    None,
}

fn extract_assistant_text(val: &Value) -> String {
    // Try /message/content as string
    if let Some(s) = val.pointer("/message/content").and_then(|v| v.as_str()) {
        return s.to_string();
    }
    // Try /message/content as array of blocks
    if let Some(arr) = val.pointer("/message/content").and_then(|v| v.as_array()) {
        let mut parts = Vec::new();
        for block in arr {
            // Only include text blocks (not tool_use, tool_result)
            if block.get("type").and_then(|t| t.as_str()) == Some("text") {
                if let Some(t) = block.get("text").and_then(|v| v.as_str()) {
                    parts.push(t.to_string());
                }
            }
        }
        return parts.join(" ");
    }
    // Fallback: top-level content
    if let Some(s) = val.get("content").and_then(|v| v.as_str()) {
        return s.to_string();
    }
    String::new()
}

/// Detect intent with proper attribute extraction. Precedence within one
/// message: aborted > watching > promise (x-e2c8). aborted is the hardest stop;
/// watching outranks promise so a session that both promises and asks to idle
/// idles (its promise is re-evaluated on the next wake).
fn detect_intent_from_text(text: &str) -> Intent {
    // Look for <aborted ...> tag
    if let Some(aborted_start) = text.find("<aborted") {
        // Find the closing >
        if let Some(gt) = text[aborted_start..].find('>') {
            let tag_text = &text[aborted_start..aborted_start + gt + 1];
            let reason = parse_xml_attr(tag_text, "reason").unwrap_or_default();
            return Intent::Aborted { reason };
        }
    }
    if let Some(w_start) = text.find("<watching") {
        if let Some(gt) = text[w_start..].find('>') {
            let tag_text = &text[w_start..w_start + gt + 1];
            return Intent::Watching {
                reason: parse_xml_attr(tag_text, "reason").unwrap_or_default(),
                pr: parse_xml_attr(tag_text, "pr"),
                timeout: parse_xml_attr(tag_text, "timeout"),
            };
        }
    }
    if text.contains("<promise>") {
        return Intent::Promise;
    }
    Intent::None
}

fn parse_xml_attr(tag_text: &str, attr: &str) -> Option<String> {
    let pattern = format!(r#"{attr}=""#);
    let start = tag_text.find(&pattern)? + pattern.len();
    let end = tag_text[start..].find('"')?;
    Some(tag_text[start..start + end].to_string())
}

/// Extract `last_assistant_message` from the Stop-hook stdin JSON
/// (ab-223d2dae). The harness emits it as a plain string (the stopping
/// turn's final assistant text, blocks joined by newline and trimmed),
/// omitted when empty. Any parse failure -> None so the caller falls back
/// to the transcript scan.
fn extract_last_assistant_message(hook_input: &str) -> Option<String> {
    let val: Value = serde_json::from_str(hook_input).ok()?;
    let s = val.get("last_assistant_message")?.as_str()?;
    let trimmed = s.trim();
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

/// A-primary, B-fallback intent read (ab-223d2dae). A present payload is the
/// stopping turn's final text - recomputed per fire, race-free, overwrite-
/// proof - and is authoritative, INCLUDING its "no tag" answer. Falling
/// through to the transcript behind a tag-less payload would resurrect the
/// stale-promise edge the bounded scan exists to contain. Returns the intent
/// plus its source for the loop_check event (`payload` | `transcript`).
fn detect_intent(
    last_assistant_message: Option<&str>,
    transcript_path: &Path,
) -> (Intent, &'static str) {
    match last_assistant_message {
        Some(text) => (detect_intent_from_text(text), "payload"),
        None => (detect_intent_full(transcript_path), "transcript"),
    }
}

/// Fallback transcript scan (ab-223d2dae, B): bounded lookback over the
/// newest INTENT_LOOKBACK_ENTRIES assistant text entries instead of
/// last-line-only. Newest tag wins; a tag-less entry no longer ends the
/// scan, which covers the promise-overwritten-by-block-feedback shape when
/// no payload exists. The bound is load-bearing: a stale promise from
/// pivoted work must fall out of the window (done()'s head_shipped read is
/// the real gate against the remainder).
const INTENT_LOOKBACK_ENTRIES: usize = 5;

fn detect_intent_full(transcript_path: &Path) -> Intent {
    let Ok(content) = std::fs::read_to_string(transcript_path) else {
        return Intent::None;
    };

    let lines: Vec<&str> = content.lines().collect();
    let mut scanned: usize = 0;
    // `watching` is honored ONLY from the single newest assistant entry
    // (x-e2c8): a stale watch-request from earlier work must not idle a session
    // that has since moved on. `promise`/`aborted` keep their bounded lookback.
    let mut newest_entry = true;
    for line in lines.iter().rev() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let Ok(val) = serde_json::from_str::<Value>(line) else {
            continue;
        };
        let role = val
            .pointer("/message/role")
            .or_else(|| val.get("role"))
            .and_then(|v| v.as_str())
            .unwrap_or("");
        if role != "assistant" {
            continue;
        }
        let text = extract_assistant_text(&val);
        if text.is_empty() {
            continue;
        }
        match detect_intent_from_text(&text) {
            Intent::None => {
                scanned += 1;
                if scanned >= INTENT_LOOKBACK_ENTRIES {
                    return Intent::None;
                }
            }
            // A watching tag below the newest entry is stale: skip it (counts
            // as a scanned entry) and keep scanning for a promise/aborted.
            Intent::Watching { .. } if !newest_entry => {
                scanned += 1;
                if scanned >= INTENT_LOOKBACK_ENTRIES {
                    return Intent::None;
                }
            }
            tagged => return tagged,
        }
        newest_entry = false;
    }
    Intent::None
}

// ── git / gh helpers ──────────────────────────────────────────────────────────

/// PR state vocabulary (fu-4faa3d). Parsed once at the read_pr_info boundary.
/// `as_str()` reproduces the exact legacy strings so the fingerprint (which
/// persists across fires in events.jsonl) stays byte-identical.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PrState {
    Open,
    Merged,
    Closed,
    /// No PR, or an unrecognized gh state string (fail-closed, AC5-EDGE).
    None,
}

impl PrState {
    fn from_gh_str(s: &str) -> Self {
        match s {
            "OPEN" => PrState::Open,
            "MERGED" => PrState::Merged,
            "CLOSED" => PrState::Closed,
            _ => PrState::None,
        }
    }

    fn as_str(&self) -> &'static str {
        match self {
            PrState::Open => "OPEN",
            PrState::Merged => "MERGED",
            PrState::Closed => "CLOSED",
            PrState::None => "none",
        }
    }

    fn is_open_or_merged(&self) -> bool {
        matches!(self, PrState::Open | PrState::Merged)
    }
}

/// CI conclusion vocabulary (fu-4faa3d). `render()` reproduces the exact
/// legacy strings ("FAILURE:{name}" carries the failing check name).
#[derive(Debug, Clone, PartialEq, Eq)]
enum CiConclusion {
    Success,
    /// Failing check name when one was identified.
    Failure(Option<String>),
    Pending,
    /// CI read skipped via ci.declared_none.
    Skipped,
    /// No checks found (fail-closed unless declared_none).
    None,
}

impl CiConclusion {
    fn render(&self) -> String {
        match self {
            CiConclusion::Success => "SUCCESS".to_string(),
            CiConclusion::Failure(Some(name)) => format!("FAILURE:{name}"),
            CiConclusion::Failure(None) => "FAILURE".to_string(),
            CiConclusion::Pending => "PENDING".to_string(),
            CiConclusion::Skipped => "skipped".to_string(),
            CiConclusion::None => "none".to_string(),
        }
    }

    fn is_ok(&self) -> bool {
        matches!(self, CiConclusion::Success | CiConclusion::Skipped)
    }
}

#[derive(Debug)]
struct PrInfo {
    state: PrState,
    number: i64,
    /// PR head commit OID; must match local HEAD for DonePRGreen (codex P1
    /// on #447: a green PR must not complete a session with unpushed work).
    head_oid: String,
    ci_conclusion: CiConclusion,
    /// Every failing check/job name on the PR head (bucket fail|cancel), at the
    /// same granularity as `gh pr checks .name`. Feeds the DoneAwaitingMerge
    /// subset rule against main's failing set. Empty when CI is green/pending.
    failing_checks: Vec<String>,
    /// True iff any check on the PR head is still pending (a non-terminal
    /// bucket). `ci_conclusion` reports `Failure` as soon as ONE check fails even
    /// while others run, so the DoneAwaitingMerge terminal must consult this to
    /// avoid firing while the session's own in-flight job could still turn red.
    ci_has_pending: bool,
    /// GitHub mergeable state ("MERGEABLE" | "CONFLICTING" | "UNKNOWN"). The
    /// DoneAwaitingMerge terminal must not fire on a "CONFLICTING" PR: the human
    /// cannot merge past main-red until the branch is rebased, and the terminal
    /// would drop the node from retry circulation while it is un-mergeable.
    mergeable: String,
    /// Newest review/comment/inline-comment activity (ISO8601 or "none");
    /// folded into the fingerprint's 4th component on done() fires.
    latest_review_ts: String,
    reviewed: bool, // every required bot passed AND no unaddressed blocking finding
    /// Required bots with no completed review pass (names the gap in the
    /// block message, AC1-UI).
    missing_bots: Vec<String>,
    /// Per-missing-bot nudge classification for this fire (x-b167), same order
    /// as `missing_bots`. Empty when the review reads were skipped or there is no
    /// PR. `missing_bots` stays the gate; this only changes idling and messaging.
    /// An EMPTY list with a non-empty `missing_bots` means "not classified" and
    /// is treated exactly like today (every missing bot idlable, today's string).
    bot_nudges: Vec<BotNudge>,
    /// Required bots dropped from the gate because they are rate-limited (a
    /// usage-limit comment, no review). Named in the terminal-allow message so
    /// an operator sees why the gate proceeded without them (AC1-UI).
    usage_limited: Vec<String>,
    /// Blocking inline findings (codex P1 / gemini critical|high) whose
    /// thread has no qualifying ack (AC2).
    unaddressed_findings: Vec<Finding>,
    /// Reads 3+4 were skipped (per-session no_external OR the repo declared
    /// `required_bots: []`). Recorded in loop_check events so the skip is
    /// observable, not silently absent (AC3-UI).
    review_skipped: bool,
    /// Configured `config.review.reviewers` with no head-pinned attestation.
    /// The sole failing term whenever the login gate is vacuous, and the reason
    /// the block message can name real local work instead of an absent bot.
    unattested_reviewers: Vec<UnattestedReviewer>,
    /// Unparseable events.jsonl lines that carry the literal
    /// `review_attestation`. Named in the reason so a corrupt attestation is
    /// not silently dropped. Not exhaustive by construction: a write torn
    /// before that token cannot be recognized at all.
    malformed_attestations: usize,
}

/// The non-interactive invocation that satisfies each local reviewer, mirroring
/// the `invocation` field of `_RESOLVABLE_REVIEWERS` in
/// `cli/src/fno/config/__init__.py`. A block message that names a reviewer
/// without naming how to run it is only half a remedy.
///
/// Two languages, one table: kept honest by
/// `scripts/ci/check-reviewer-descriptor-parity.sh`, not by a comment asking a
/// human to remember.
const REVIEWER_INVOCATIONS: &[(&str, &str, bool)] = &[
    ("sigma", "/fno:review sigma", false),
    (
        "code-review",
        "/code-review, then bash skills/review/scripts/emit-attestation.sh code-review",
        false,
    ),
    ("declare", "/fno:review declare", true),
];

/// `(invocation, is_self_cert)`. The flag mirrors the Python descriptor's
/// `asserts` field: a surface that names `declare` without saying it asserts
/// nothing invites an operator to clear the gate with no review behind it.
fn reviewer_invocation(name: &str) -> Option<(&'static str, bool)> {
    REVIEWER_INVOCATIONS
        .iter()
        .find(|(n, _, _)| *n == name)
        .map(|(_, inv, self_cert)| (*inv, *self_cert))
}

fn git_head_sha(git_bin: &str, cwd: &Path) -> String {
    let out = Command::new(git_bin)
        .args(["rev-parse", "HEAD"])
        .current_dir(cwd)
        .output();
    match out {
        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
        _ => "unknown".to_string(),
    }
}

/// `gh pr view` exits 1 both when no PR exists and when gh itself fails.
/// "No PR" is real world-state - the fingerprint should record it and the
/// NoProgress backstop should keep ticking - while an outage must freeze the
/// streak (US4). Distinguish via gh's deterministic no-PR stderr message. If
/// gh ever changes the message, no-PR fires degrade to outage semantics
/// (freeze -> budget ceiling): safe, never a premature termination.
fn is_no_pr_stderr(stderr: &[u8]) -> bool {
    String::from_utf8_lossy(stderr)
        .to_lowercase()
        .contains("no pull requests found")
}

/// Capture the last ~200 bytes of stderr as a lossy UTF-8 string.
fn stderr_tail(bytes: &[u8]) -> String {
    let s = String::from_utf8_lossy(bytes);
    let s = s.trim();
    if s.len() <= 200 {
        s.to_string()
    } else {
        // Byte index must land on a char boundary or the slice panics
        // (gemini HIGH on PR #447): walk forward to the next boundary.
        let mut start = s.len() - 200;
        while start < s.len() && !s.is_char_boundary(start) {
            start += 1;
        }
        s[start..].to_string()
    }
}

/// A configured local reviewer with no head-pinned `pass` attestation.
#[derive(Debug, Clone, PartialEq)]
struct UnattestedReviewer {
    name: String,
    /// A head this reviewer DID attest at, which is no longer HEAD. Always a
    /// PASS and never empty - normalized at construction so `Some` means
    /// "there is a real prior pass to name", not "check is_empty() first".
    /// Without it the block message reads as "you never ran sigma" to a session
    /// that ran sigma and then pushed a commit, losing turns twice.
    superseded_head: Option<String>,
    /// This reviewer DID attest at the current head, and the verdict was not
    /// `pass`. "No attestation exists" would be a lie to a session that ran the
    /// reviewer and was told no.
    failed_at_head: bool,
}

/// The `config.review.reviewers` entries NOT satisfied by a head-pinned
/// `review_attestation` event (x-e703 Phase 2; list form added by x-cdc7). A
/// reviewer is satisfied when events.jsonl carries a line with
/// `type == "review_attestation"`, `data.reviewer` matching (leading '/'
/// stripped on both sides), `data.head_sha == head_sha`, and
/// `data.verdict == "pass"`.
///
/// The gate reads `.is_empty()` and the block message reads the names, so the
/// decision and the explanation come from ONE scan. When they came from two,
/// the message told sessions to wait on a bot that was never required.
///
/// Fail closed everywhere: an empty/unreadable events file, a stale head_sha
/// (attestation for a prior commit), or a `fail` verdict leaves the reviewer
/// UNSATISFIED, mirroring how a missing bot review holds the login gate. An
/// empty reviewer list is vacuously satisfied (no reviewers gate).
/// `unattested_reviewers` plus the count of unparseable lines that LOOK like
/// attestations. A torn write leaves a corrupt `review_attestation` in the file
/// and the gate then reports "no head-pinned review_attestation", which is the
/// same class of lie this node exists to delete - so the count is surfaced in
/// the reason. Mirrors `open_review_findings`, which already does this for
/// `review_finding`.
fn unattested_reviewers_scan(
    events_path: &Path,
    reviewers: &[String],
    head_sha: &str,
) -> (Vec<UnattestedReviewer>, usize) {
    let unsatisfied_all = || -> Vec<UnattestedReviewer> {
        reviewers
            .iter()
            .map(|r| UnattestedReviewer {
                name: r.trim_start_matches('/').to_string(),
                superseded_head: None,
                failed_at_head: false,
            })
            .collect()
    };
    if reviewers.is_empty() {
        return (Vec::new(), 0);
    }
    let Ok(content) = std::fs::read_to_string(events_path) else {
        // no evidence file -> gate unmet (fail closed)
        return (unsatisfied_all(), 0);
    };
    let mut malformed = 0usize;
    // Single pass (gemini review): record the LATEST verdict per reviewer at the
    // current head. events.jsonl is append-ordered, so a later attestation
    // supersedes an earlier one for the same reviewer - a `fail` posted after a
    // `pass` must revoke it, and a re-run `pass` after a `fail` must restore it
    // (codex peer review P1: a later fail was previously ignored). A reviewer is
    // satisfied iff its latest head-pinned verdict is exactly `pass`. O(lines).
    let mut latest_pass: std::collections::HashMap<String, bool> = std::collections::HashMap::new();
    // reviewer -> every OLD head it attested at, in first-seen order, each
    // carrying that head's LATEST verdict. A single-entry "most recent pass"
    // map cannot survive a retraction: `pass A, pass B, fail B` overwrites A
    // with B and then drops B, reporting no prior pass while A is still a real
    // one (codex P2 on this PR). Multi-round review/fix cycles produce exactly
    // that sequence.
    let mut other_heads: std::collections::HashMap<String, Vec<(String, bool)>> =
        std::collections::HashMap::new();
    for line in content.lines() {
        let Ok(val) = serde_json::from_str::<Value>(line) else {
            if line.contains("review_attestation") {
                malformed += 1;
            }
            continue;
        };
        if val.get("type").and_then(|v| v.as_str()) != Some("review_attestation") {
            continue;
        }
        let Some(r) = val.pointer("/data/reviewer").and_then(|v| v.as_str()) else {
            continue;
        };
        let r = r.trim_start_matches('/').to_string();
        // An event with no `head_sha` is not head-pinned evidence and is
        // skipped outright. Defaulting it to "" would make it MATCH a caller
        // whose own head_sha is "", turning unpinned data into a pass (codex
        // P1 on this PR).
        let Some(line_head) = val.pointer("/data/head_sha").and_then(|v| v.as_str()) else {
            continue;
        };
        let is_pass = val.pointer("/data/verdict").and_then(|v| v.as_str()) == Some("pass");
        if line_head != head_sha {
            // Empty is not a head; recording it would put a `Some` in the
            // message with nothing to print.
            if line_head.is_empty() {
                continue;
            }
            let seen = other_heads.entry(r).or_default();
            match seen.iter().position(|(h, _)| h == line_head) {
                Some(i) => seen[i].1 = is_pass, // latest verdict wins for that head
                None => seen.push((line_head.to_string(), is_pass)),
            }
            continue;
        }
        latest_pass.insert(r, is_pass);
    }
    let out = reviewers
        .iter()
        .map(|entry| entry.trim_start_matches('/'))
        .filter(|name| latest_pass.get(*name) != Some(&true))
        .map(|name| UnattestedReviewer {
            name: name.to_string(),
            // An old head whose LATEST verdict is still a pass. Heads keep
            // first-seen order, so a head re-attested later keeps its original
            // slot and this may name a slightly older one - both are real
            // passes, so the line stays true either way. Only a pass is worth
            // naming: an old-head `fail` rendered as "passed at X, superseded"
            // would imply a successful review that never happened.
            superseded_head: other_heads
                .get(name)
                .and_then(|heads| heads.iter().rev().find(|(_, ok)| *ok))
                .map(|(h, _)| h.clone()),
            failed_at_head: latest_pass.get(name) == Some(&false),
        })
        .collect();
    (out, malformed)
}

/// An operator review finding (x-f8d4) still open: a `review_finding` event for
/// the node with no later `review_finding_resolved` for the same id.
#[derive(Debug, Clone)]
struct OpenFinding {
    id: String,
    first_line: String,
}

/// Scan events.jsonl for OPEN operator review findings scoped to `node`.
///
/// Returns `(open findings sorted by id, malformed-line count)`. A finding is
/// open until an explicit `review_finding_resolved` clears it - node-scoped and
/// NOT head-pinned, so a new commit never auto-clears an operator's comment
/// (Locked Decision 2). Malformed finding lines notice-not-block (AC3-FR): a
/// line that is unparseable JSON but carries the literal `review_finding`, or a
/// parsed `review_finding` missing its id, is our own writer's corrupted output;
/// it is counted for the deny/audit notice but NEVER holds the gate. Any read
/// failure yields no findings (the gate is only ADDED by evidence, never
/// invented from an unreadable file).
fn open_review_findings(events_path: &Path, node: &str) -> (Vec<OpenFinding>, usize) {
    let Ok(content) = std::fs::read_to_string(events_path) else {
        return (Vec::new(), 0);
    };
    // Preserve first-seen order via a Vec of (id, first_line); a later duplicate
    // id (shouldn't happen - ids are minted) just refreshes the first_line.
    let mut findings: Vec<(String, String)> = Vec::new();
    let mut resolved: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut malformed = 0usize;
    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let Ok(val) = serde_json::from_str::<Value>(line) else {
            // Only OUR corrupted output counts toward the notice; unrelated
            // corruption from another writer is not a finding concern.
            if line.contains("review_finding") {
                malformed += 1;
            }
            continue;
        };
        match val.get("type").and_then(|v| v.as_str()) {
            Some("review_finding") => {
                if val.pointer("/data/node").and_then(|v| v.as_str()) != Some(node) {
                    continue;
                }
                match val.pointer("/data/finding_id").and_then(|v| v.as_str()) {
                    Some(id) => {
                        let first = val
                            .pointer("/data/text")
                            .and_then(|v| v.as_str())
                            .unwrap_or("")
                            .lines()
                            .next()
                            .unwrap_or("")
                            .to_string();
                        if let Some(slot) = findings.iter_mut().find(|(fid, _)| fid == id) {
                            slot.1 = first;
                        } else {
                            findings.push((id.to_string(), first));
                        }
                    }
                    None => malformed += 1, // review_finding without an id
                }
            }
            Some("review_finding_resolved") => {
                if let Some(id) = val.pointer("/data/finding_id").and_then(|v| v.as_str()) {
                    resolved.insert(id.to_string());
                }
            }
            _ => {}
        }
    }
    let mut open: Vec<OpenFinding> = findings
        .into_iter()
        .filter(|(id, _)| !resolved.contains(id))
        .map(|(id, first_line)| OpenFinding { id, first_line })
        .collect();
    open.sort_by(|a, b| a.id.cmp(&b.id)); // deterministic deny reason
    (open, malformed)
}

/// Deny reason for an open-finding gate: quote the first finding (id + first
/// line) + the resolve remedy, plus a `[+N more]` count and any malformed-line
/// notice so nothing vanishes silently.
fn build_findings_block_reason(open: &[OpenFinding], malformed: usize) -> String {
    let f = &open[0];
    let more = if open.len() > 1 {
        format!(" [+{} more]", open.len() - 1)
    } else {
        String::new()
    };
    let notice = if malformed > 0 {
        format!(" ({malformed} malformed finding line(s) ignored)")
    } else {
        String::new()
    };
    format!(
        "open review finding {}: {} - address it, then `fno annotate resolve {}`{}{}",
        f.id, f.first_line, f.id, more, notice
    )
}

/// Run done() reads. Returns Ok(PrInfo) or Err((read_name, stderr_tail)) on gh failure.
#[allow(clippy::too_many_arguments)]
fn read_pr_info(
    gh_bin: &str,
    cwd: &Path,
    ci_declared_none: bool,
    no_external: bool,
    required_bots: &[String],
    optional_bots: &[String],
    external_reviewers: &[String],
    reviewers: &[String],
    nudge_configs: &[NudgeConfig],
    head_sha: &str,
    events_path: &Path,
) -> Result<PrInfo, (String, String)> {
    // Read 1: PR state + number + head OID + mergeability
    let pr_view_out = Command::new(gh_bin)
        .args([
            "pr",
            "view",
            "--json",
            "state,number,headRefName,headRefOid,mergeable",
        ])
        .current_dir(cwd)
        .output()
        .map_err(|e| ("pr_view".to_string(), e.to_string()))?;

    if !pr_view_out.status.success() {
        if is_no_pr_stderr(&pr_view_out.stderr) {
            // No PR yet: world-state, not an error. done() is simply false
            // ("no PR for HEAD"), and the backstop can resolve a stuck
            // no-PR session as NoProgress rather than freezing forever.
            return Ok(PrInfo {
                state: PrState::None,
                number: 0,
                head_oid: String::new(),
                ci_conclusion: CiConclusion::None,
                failing_checks: Vec::new(),
                ci_has_pending: false,
                mergeable: "UNKNOWN".to_string(),
                latest_review_ts: "none".to_string(),
                reviewed: false,
                missing_bots: Vec::new(),
                bot_nudges: Vec::new(),
                usage_limited: Vec::new(),
                unaddressed_findings: Vec::new(),
                review_skipped: false,
                unattested_reviewers: Vec::new(),
                malformed_attestations: 0,
            });
        }
        return Err(("pr_view".to_string(), stderr_tail(&pr_view_out.stderr)));
    }

    let pr_json: Value = serde_json::from_slice(&pr_view_out.stdout)
        .map_err(|_| ("pr_view_parse".to_string(), String::new()))?;

    let state = PrState::from_gh_str(
        pr_json
            .get("state")
            .and_then(|v| v.as_str())
            .unwrap_or("none"),
    );
    let number = pr_json.get("number").and_then(|v| v.as_i64()).unwrap_or(0);
    let head_oid = pr_json
        .get("headRefOid")
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string();
    // GitHub's mergeable state: "MERGEABLE" | "CONFLICTING" | "UNKNOWN" (still
    // computing). Only "CONFLICTING" is a definitive no; UNKNOWN must not hold
    // the terminal (it clears on its own). Missing field -> "UNKNOWN".
    let mergeable = pr_json
        .get("mergeable")
        .and_then(|v| v.as_str())
        .unwrap_or("UNKNOWN")
        .to_string();

    // x-8b64 (E): a MERGED PR is terminal. A PR merged out-of-band (GitHub
    // web/mobile, or `gh pr merge`) is done regardless of whether the required
    // bot ever reviewed it or whether CI is still green post-merge - the merge
    // IS the authority. Short-circuit the now-irrelevant CI + review polls
    // (which also avoids a transient gh blip on those reads re-blocking a
    // finished session). The single merge signal is `state` from the same
    // `gh pr view` call that `reconcile`/`fno pr verify` read - one signal, not
    // two independently-polled sources. done()'s `head_shipped` guard still
    // applies downstream: an unpushed commit on top of a merged PR stays
    // unshipped work.
    if state == PrState::Merged {
        return Ok(PrInfo {
            state,
            number,
            head_oid,
            ci_conclusion: CiConclusion::Skipped,
            failing_checks: Vec::new(),
            ci_has_pending: false,
            mergeable,
            latest_review_ts: "none".to_string(),
            reviewed: true,
            missing_bots: Vec::new(),
            bot_nudges: Vec::new(),
            usage_limited: Vec::new(),
            unaddressed_findings: Vec::new(),
            review_skipped: true,
            unattested_reviewers: Vec::new(),
            malformed_attestations: 0,
        });
    }

    // Read 2: CI checks. Compute the conclusion, the full failing-check-name set,
    // AND whether any check is still pending from the same payload (the set feeds
    // the DoneAwaitingMerge subset rule; the pending flag gates that terminal so
    // it never fires on partial CI).
    let no_hosted_ci =
        crate::verify_evidence::hosted_ci_not_configured(ci_declared_none, cwd, head_sha);
    let (ci_conclusion, failing_checks, ci_has_pending) = if no_hosted_ci {
        (CiConclusion::Skipped, Vec::new(), false)
    } else {
        let checks_out = Command::new(gh_bin)
            .args(["pr", "checks", "--json", "name,state,bucket"])
            .current_dir(cwd)
            .output()
            .map_err(|e| ("pr_checks".to_string(), e.to_string()))?;

        if !checks_out.status.success() {
            return Err(("pr_checks".to_string(), stderr_tail(&checks_out.stderr)));
        }

        let checks: Value = serde_json::from_slice(&checks_out.stdout)
            .map_err(|_| ("pr_checks_parse".to_string(), String::new()))?;

        let failing = failing_check_names(&checks);
        let has_pending = ci_has_pending_checks(&checks);
        (
            compute_ci_conclusion(&checks).map_err(|e| (e, String::new()))?,
            failing,
            has_pending,
        )
    };

    // Reads 3+4: reviews + inline findings. Skipped when the session declares
    // no_external OR the repo declares `required_bots: []` (the no-review-gate
    // path, US3 - mirrors ci.declared_none; PR + CI carry the gate). The two
    // skips are orthogonal: one is per-session, the other repo config.
    // Skip the review reads only when there is NOTHING to honor: no required
    // login AND no optional login. An optional-only gate still reads (to catch
    // an optional blocking finding), but its presence is never required.
    // x-e703: the gate is a strict conjunction over the union of GitHub-login
    // evidence (github_apps/peers via optional_bots+required_bots) AND the
    // local-attestation `reviewers`. Each satisfied by its own evidence source,
    // so the two skips are INDEPENDENT: `no_external` (and an empty login set)
    // skips only the EXTERNAL GitHub-login reads - it is scoped to external
    // review (control-plane-loop.md step 2), NOT the local attestation gate. A
    // repo that pins `reviewers: [sigma]` still requires that local pass even
    // when a session runs `--no-external` to skip usage-wedged App bots
    // (fixes a fail-open the sigma review caught). `reviewers` is empty for
    // every pre-x-e703 config, so `reviewers_all_attested` is vacuously true
    // there and this changes nothing for them.
    let login_gate_active = !required_bots.is_empty() || !optional_bots.is_empty();
    let login_skipped = no_external || !login_gate_active;
    // One scan feeds both the gate and its explanation, so the two cannot
    // disagree the way the decision and the message did on PR #618.
    let (unattested, malformed_attestations) =
        unattested_reviewers_scan(events_path, reviewers, head_sha);
    let reviewers_ok = unattested.is_empty();
    let (latest_review_ts, reviewed, missing_bots, bot_nudges, usage_limited, unaddressed_findings) =
        if login_skipped {
            // No GitHub logins to poll (nothing configured, or no_external): skip
            // the gh review reads entirely (fewer calls + no spurious gh-error
            // block). The local attestation gate still applies - reviewers_ok is
            // true when unconfigured, so a login-only or no-gate config is
            // unaffected.
            (
                "none".to_string(),
                reviewers_ok,
                Vec::new(),
                Vec::new(),
                Vec::new(),
                Vec::new(),
            )
        } else {
            // Read 3: top-level reviews + issue comments
            let reviews_out = Command::new(gh_bin)
                .args(["pr", "view", "--json", "reviews,comments"])
                .current_dir(cwd)
                .output()
                .map_err(|e| ("pr_reviews".to_string(), e.to_string()))?;

            if !reviews_out.status.success() {
                return Err(("pr_reviews".to_string(), stderr_tail(&reviews_out.stderr)));
            }

            let reviews_json: Value = serde_json::from_slice(&reviews_out.stdout)
                .map_err(|_| ("pr_reviews_parse".to_string(), String::new()))?;

            // PRESENCE is required-only: an optional login's absence must never
            // create a missing_bot (never wait for it). FINDINGS honor the union:
            // an optional login's blocking P1 still holds the gate ("honor if
            // present"). A dedup keeps a login that is in both lists counted once.
            let info = compute_review_info(&reviews_json, required_bots);
            // Per-missing-bot nudge classification (x-b167), computed AFTER the
            // usage-limit retain (which happened inside compute_review_info) so
            // the two give-up paths never compose (AC6): a usage_limited bot is
            // already out of missing_bots and is never classified here. Derived
            // from the same issue-comment list, fresh every fire.
            let now = Utc::now();
            let review_comments = reviews_json
                .get("comments")
                .and_then(|v| v.as_array())
                .map(|v| v.as_slice())
                .unwrap_or(&[]);
            let bot_nudges: Vec<BotNudge> = info
                .missing_bots
                .iter()
                .map(|bot| {
                    classify_bot_nudge(
                        bot,
                        review_comments,
                        nudge_config_for(nudge_configs, bot),
                        now,
                    )
                })
                .collect();
            // The "empty bot_nudges = not classified = status quo" contract that
            // async_wait_class and build_block_reason rely on holds only because
            // this is an all-or-nothing map: bot_nudges is either empty or 1:1
            // with missing_bots. A future partial classification would silently
            // mis-idle, so pin the invariant here rather than let it drift.
            debug_assert_eq!(bot_nudges.len(), info.missing_bots.len());
            let mut findings_bots: Vec<String> = required_bots.to_vec();
            for b in optional_bots {
                if !findings_bots.iter().any(|x| x == b) {
                    findings_bots.push(b.clone());
                }
            }

            // Read 4: inline review comments (NEW in step 2). Codex's P1s land on
            // the /pulls/N/comments REST endpoint, which `gh pr view --json
            // comments` does NOT return (verified on PR #447). --paginate may
            // emit CONCATENATED JSON arrays (one per page), so parse as a stream.
            let comments_out = Command::new(gh_bin)
                .args([
                    "api",
                    &format!("repos/{{owner}}/{{repo}}/pulls/{number}/comments"),
                    "--paginate",
                ])
                .current_dir(cwd)
                .output()
                .map_err(|e| ("pulls_comments".to_string(), e.to_string()))?;

            if !comments_out.status.success() {
                return Err((
                    "pulls_comments".to_string(),
                    stderr_tail(&comments_out.stderr),
                ));
            }

            let mut inline_comments: Vec<Value> = Vec::new();
            for page in
                serde_json::Deserializer::from_slice(&comments_out.stdout).into_iter::<Value>()
            {
                let page = page.map_err(|_| ("pulls_comments_parse".to_string(), String::new()))?;
                match page.as_array() {
                    Some(arr) => inline_comments.extend(arr.iter().cloned()),
                    None => return Err(("pulls_comments_parse".to_string(), String::new())),
                }
            }

            // Commit timestamps feed the commit-after arm of "addressed". Only
            // fetched when a blocking candidate could exist (cheap pre-scan).
            let has_blocking_candidate = inline_comments.iter().any(|c| {
                c.get("in_reply_to_id").and_then(|v| v.as_i64()).is_none()
                    && blocking_severity(c.get("body").and_then(|v| v.as_str()).unwrap_or(""))
                        .is_some()
            });
            let commit_dates: Vec<String> = if has_blocking_candidate {
                let commits_out = Command::new(gh_bin)
                    .args(["pr", "view", "--json", "commits"])
                    .current_dir(cwd)
                    .output()
                    .map_err(|e| ("pr_commits".to_string(), e.to_string()))?;
                if !commits_out.status.success() {
                    return Err(("pr_commits".to_string(), stderr_tail(&commits_out.stderr)));
                }
                let commits_json: Value = serde_json::from_slice(&commits_out.stdout)
                    .map_err(|_| ("pr_commits_parse".to_string(), String::new()))?;
                commits_json
                    .get("commits")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|c| {
                                c.get("committedDate")
                                    .and_then(|v| v.as_str())
                                    .map(|s| s.to_string())
                            })
                            .collect()
                    })
                    .unwrap_or_default()
            } else {
                Vec::new()
            };

            let (inline_ts, unaddressed) = compute_unaddressed_findings(
                &inline_comments,
                &commit_dates,
                &findings_bots,
                external_reviewers,
            );

            // Read 4's newest comment timestamp joins the activity timestamp so
            // inline-only review traffic advances the fingerprint (closes the
            // false-NoProgress hole).
            let activity_ts = max_ts(&info.latest_ts, &inline_ts);
            // x-e703: the login gate AND the local-attestation reviewers gate must
            // both clear. reviewers is usually empty (vacuously true) so this is a
            // no-op for login-only configs.
            let reviewed = info.all_required_passed() && unaddressed.is_empty() && reviewers_ok;
            // (a) Record the rate-limit drop so a post-hoc audit sees why the gate
            // proceeded without a required bot (AC1-UI). append_loop_event, not
            // Branch-B emit: these are target-stream events (see the doc comment on
            // append_loop_event), deliberately unregistered in KNOWN_EVENT_KINDS.
            if !info.usage_limited.is_empty() {
                append_loop_event(
                    events_path,
                    "review_gate_bot_usage_limited",
                    serde_json::json!({"pr": number, "bots": info.usage_limited.clone()}),
                );
            }
            (
                activity_ts,
                reviewed,
                info.missing_bots,
                bot_nudges,
                info.usage_limited,
                unaddressed,
            )
        };

    Ok(PrInfo {
        state,
        number,
        head_oid,
        ci_conclusion,
        failing_checks,
        ci_has_pending,
        mergeable,
        latest_review_ts,
        reviewed,
        missing_bots,
        bot_nudges,
        usage_limited,
        unaddressed_findings,
        // Telemetry only (no decision reads this): "no review gate of any kind
        // applied" = the login reads were skipped AND no local reviewers gate.
        // A reviewers-only config did gate, so it is NOT review_skipped.
        review_skipped: login_skipped && reviewers.is_empty(),
        unattested_reviewers: unattested,
        malformed_attestations,
    })
}

fn compute_ci_conclusion(checks: &Value) -> Result<CiConclusion, String> {
    let arr = match checks.as_array() {
        Some(a) => a,
        None => return Err("pr_checks_parse".to_string()),
    };

    if arr.is_empty() {
        // No checks configured and no declared_none -> fail closed
        return Ok(CiConclusion::None);
    }

    // `gh pr checks --json` classifies each check into a rollup `bucket`:
    // pass | fail | pending | skipping | cancel. (`conclusion` is NOT an
    // available field on this subcommand; requesting it errored the read on
    // every fire - ab-610d2ee3 follow-on, previously masked by the budget
    // bug terminating sessions before this read ran.) Unknown or missing
    // buckets fail closed as Pending - never green.
    let bucket_of = |check: &Value| -> String {
        check
            .get("bucket")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_lowercase()
    };

    if let Some(failing) = arr
        .iter()
        .find(|c| matches!(bucket_of(c).as_str(), "fail" | "cancel"))
    {
        let name = failing
            .get("name")
            .and_then(|v| v.as_str())
            .unwrap_or("unknown");
        return Ok(CiConclusion::Failure(Some(name.to_string())));
    }
    if arr
        .iter()
        .any(|c| !matches!(bucket_of(c).as_str(), "pass" | "skipping"))
    {
        return Ok(CiConclusion::Pending);
    }
    Ok(CiConclusion::Success)
}

// ── DoneAwaitingMerge classifier ───────────────────────────────────────────────
//
// When done() fails SOLELY on CI-green (PR open+mergeable, reviewed, HEAD
// shipped) the loop would burn to NoProgress while a bg agent waits on a merge
// it cannot perform - but only pathologically so when main ITSELF is red on the
// same checks. `pre_existing_main_red` proves that condition mechanically:
// every failing PR check name must also be failing on current main HEAD (strict
// subset, check-name granularity so the mux flakes rotating test names between
// runs stay matched). Any PR-unique red, or any gh uncertainty, holds as today.

/// How many latest completed main runs to scan. `main_head_failing_checks` keeps
/// only the runs whose headSha equals the newest run's (the current main HEAD),
/// so this bound just needs to comfortably cover ONE commit's workflow fan-out
/// (this repo fires ~4-5 workflow runs per push); a value above that is harmless
/// because the headSha scope discards any older commit's runs. Bounded so the
/// per-fire gh cost stays constant.
const MAIN_RUN_LOOKBACK: usize = 10;

/// Failing check/job names on a `gh pr checks --json name,bucket` payload
/// (bucket fail|cancel), the same granularity a main-HEAD job carries. Non-fail
/// buckets (pass|pending|skipping) are ignored. Malformed entries are skipped.
fn failing_check_names(checks: &Value) -> Vec<String> {
    let Some(arr) = checks.as_array() else {
        return Vec::new();
    };
    arr.iter()
        .filter(|c| {
            let bucket = c
                .get("bucket")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_lowercase();
            matches!(bucket.as_str(), "fail" | "cancel")
        })
        .filter_map(|c| c.get("name").and_then(|v| v.as_str()).map(str::to_string))
        .collect()
}

/// True iff any check is still in a non-terminal bucket (`pending`, or an
/// unrecognized bucket that is not one of pass|fail|cancel|skipping). The
/// DoneAwaitingMerge terminal must not fire while any check is unresolved: a
/// still-running check (e.g. the session's own new job) could turn red, so a
/// partial `Failure` is not yet proof that the ONLY problem is pre-existing
/// main-red.
fn ci_has_pending_checks(checks: &Value) -> bool {
    let Some(arr) = checks.as_array() else {
        return false;
    };
    arr.iter().any(|c| {
        let bucket = c
            .get("bucket")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_lowercase();
        !matches!(bucket.as_str(), "pass" | "fail" | "cancel" | "skipping")
    })
}

/// databaseIds of failed workflow runs from a `gh run list --json
/// databaseId,conclusion,headSha` payload, scoped to a single `head_sha`. Only
/// conclusion=="failure" runs whose headSha equals the current main HEAD count
/// (a cancelled or in-progress run is not proof; a run from an OLDER main commit
/// that has since been fixed is not proof of CURRENT main-red).
fn parse_failing_run_ids(run_list: &Value, head_sha: &str) -> Vec<i64> {
    let Some(arr) = run_list.as_array() else {
        return Vec::new();
    };
    arr.iter()
        .filter(|r| r.get("conclusion").and_then(|v| v.as_str()) == Some("failure"))
        .filter(|r| r.get("headSha").and_then(|v| v.as_str()) == Some(head_sha))
        .filter_map(|r| r.get("databaseId").and_then(|v| v.as_i64()))
        .collect()
}

/// Failing job names from a `gh run view <id> --json jobs` payload. The `jobs`
/// `.name` field is the same namespace as `gh pr checks .name` (both are the
/// check-run/job name), so a name from here matches a PR failing-check name.
fn parse_failing_job_names(jobs_json: &Value) -> Vec<String> {
    let Some(jobs) = jobs_json.get("jobs").and_then(|v| v.as_array()) else {
        return Vec::new();
    };
    jobs.iter()
        .filter(|j| j.get("conclusion").and_then(|v| v.as_str()) == Some("failure"))
        .filter_map(|j| j.get("name").and_then(|v| v.as_str()).map(str::to_string))
        .collect()
}

/// The strict subset rule: main's failing set must COVER every failing PR check.
/// Empty PR-failing is never eligible (that is the DonePRGreen path, not here);
/// any PR-unique failing check blocks the terminal (the session's own breakage).
fn is_pre_existing_main_red(pr_failing: &[String], main_failing: &[String]) -> bool {
    if pr_failing.is_empty() {
        return false;
    }
    pr_failing.iter().all(|c| main_failing.contains(c))
}

/// Union of failing job names on the CURRENT main HEAD commit, scanning the
/// latest N completed runs on `--branch main` and keeping only those whose
/// headSha matches the newest run's (i.e. the current main HEAD). N is sized to
/// cover one commit's workflow fan-out with margin; scoping by headSha means a
/// larger N never pulls in a stale older commit's failures. Fail-CLOSED: any gh
/// error, non-zero exit, malformed JSON, ZERO completed runs, or a missing
/// headSha returns `None` (unknown -> the caller holds as today). A clean read
/// with no failures on HEAD returns `Some(empty)` -> the subset rule then fails
/// and the caller holds; only positive proof fires the terminal.
fn main_head_failing_checks(gh_bin: &str, cwd: &Path, n: usize) -> Option<Vec<String>> {
    let list_out = Command::new(gh_bin)
        .args([
            "run",
            "list",
            "--branch",
            "main",
            "--status",
            "completed",
            "--limit",
            &n.to_string(),
            "--json",
            "databaseId,conclusion,headSha",
        ])
        .current_dir(cwd)
        .output()
        .ok()?;
    if !list_out.status.success() {
        return None; // gh error -> unknown -> hold
    }
    let list: Value = serde_json::from_slice(&list_out.stdout).ok()?;
    let arr = list.as_array()?;
    // Zero completed runs (new/quiet repo) is not proof -> unknown.
    // The newest run's headSha IS the current main HEAD; classify against only
    // that commit's runs so a failure fixed on a later commit never counts.
    let head_sha = arr
        .first()
        .and_then(|r| r.get("headSha"))
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())?;
    let failing_run_ids = parse_failing_run_ids(&list, head_sha);

    let mut names: Vec<String> = Vec::new();
    for id in failing_run_ids {
        let view_out = Command::new(gh_bin)
            .args(["run", "view", &id.to_string(), "--json", "jobs"])
            .current_dir(cwd)
            .output()
            .ok()?;
        if !view_out.status.success() {
            return None; // any per-run gh error -> unknown -> hold (fail closed)
        }
        let view: Value = serde_json::from_slice(&view_out.stdout).ok()?;
        for name in parse_failing_job_names(&view) {
            if !names.contains(&name) {
                names.push(name);
            }
        }
    }
    Some(names)
}

/// Idempotency guard (Concurrency AC): true iff a prior `termination` event with
/// reason `DoneAwaitingMerge` for this session already exists, so a re-evaluation
/// (crash restart, or the two consumers racing) does not double-emit or
/// double-notify. Fail-open (false) on an unreadable events file: at worst one
/// extra notify, never a silent skip of the terminal.
fn already_emitted_awaiting_merge(events_path: &Path, session_id: &str) -> bool {
    let Ok(content) = std::fs::read_to_string(events_path) else {
        return false;
    };
    content.lines().any(|line| {
        let Ok(val) = serde_json::from_str::<Value>(line) else {
            return false;
        };
        val.get("type").and_then(|v| v.as_str()) == Some("termination")
            && val.pointer("/data/session_id").and_then(|v| v.as_str()) == Some(session_id)
            && val.pointer("/data/reason").and_then(|v| v.as_str()) == Some("DoneAwaitingMerge")
    })
}

/// Best-effort `fno notify TITLE BODY`. Spawned detached and never waited on;
/// any failure (missing binary, non-zero exit) is non-fatal - the terminal
/// completes on the durable event row alone (AC2-FR). Suppressed under
/// `FNO_LOOPCHECK_NO_NOTIFY=1` so unit tests never spawn a real notifier.
fn best_effort_notify(title: &str, body: &str) {
    if std::env::var("FNO_LOOPCHECK_NO_NOTIFY").as_deref() == Ok("1") {
        return;
    }
    // var_os avoids a lossy UTF-8 conversion on a path/binary env value and
    // hands the raw OsString straight to Command (gemini review).
    let fno_bin = std::env::var_os("FNO_LOOPCHECK_FNO_BIN").unwrap_or_else(|| "fno".into());
    let _ = Command::new(fno_bin).args(["notify", title, body]).spawn();
}

/// Post a bot's review trigger to the PR once, returning true on success (x-b167
/// section 5). `FNO_LOOPCHECK_NO_COMMENT=1` suppresses the post so the test suite
/// never comments on a real PR, mirroring `FNO_LOOPCHECK_NO_NOTIFY`.
///
/// Idempotency is the PR itself, not a counter: this fires only on a NeedsNudge
/// classification, which means zero qualifying mentions exist within the wait
/// window - the same read every participant makes. A sibling worktree, a
/// `/fno:pr check` cron, a human, and a restarted-after-compaction session all
/// see the same PR and reach the same decision, so there is nothing to double.
fn post_nudge_comment(gh_bin: &str, cwd: &Path, pr_number: i64, review_handle: &str) -> bool {
    if std::env::var("FNO_LOOPCHECK_NO_COMMENT").as_deref() == Ok("1") {
        return false;
    }
    Command::new(gh_bin)
        .args([
            "pr",
            "comment",
            &pr_number.to_string(),
            "--body",
            review_handle,
        ])
        .current_dir(cwd)
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// The first missing bot that has been nudged to its ceiling and gone silent, if
/// any. The NoProgress backstop names it instead of a bare fingerprint streak.
fn unresponsive_bot(pr: &PrInfo) -> Option<&BotNudge> {
    pr.bot_nudges
        .iter()
        .find(|n| n.class == NudgeClass::Unresponsive)
}

/// The give-up line for an unresponsive nudged bot (x-b167 AC13): the operator's
/// two questions ("will it finish, must I act") answered in one line.
fn nudge_giveup_message(n: &BotNudge) -> String {
    format!(
        "{} did not review after {} nudges over {}m; giving up (NoProgress). \
         Move it to config.review.optional_apps or review by hand.",
        n.login, n.nudges, n.span_min
    )
}

/// Per-bot knowledge, login-keyed: the ONE table the review-gate code reads for
/// "what is this bot and how do we reach it". Replaces the scattered `KNOWN_BOTS`
/// membership list and the `USAGE_LIMIT_MARKERS` body-string list.
///
/// One bot wears three names and they are NOT interchangeable at the three sites
/// that use them:
///   - `login`         the review author, what `login_matches_bot` compares against
///   - `review_handle` what a PR comment must CONTAIN to trigger a fresh review
///   - `reply_handle`  what an in-thread reply must ADDRESS to reach the bot
/// A `github-app` reviewer that reviews on mention (not on push) is `nudgeable`:
/// footnote may post its `review_handle` to un-stick a required gate that nobody
/// mentioned (x-b167). Nudge timing (`wait_minutes`, `ceiling`, `enabled`) is
/// config, not code - see `[review.nudge]` / `resolved_nudge_configs`.
struct BotProfile {
    login: &'static str,
    review_handle: &'static str,
    reply_handle: &'static str,
    /// ISSUE-comment body markers this bot posts when it is rate-limited and will
    /// never post a review object (PR #214). Empty for a bot never seen to do so.
    usage_markers: &'static [&'static str],
    nudgeable: bool,
}

/// The shipped bot table. `chatgpt-codex-connector` is characterized from PR #618
/// (mention-triggered, ~4-7m latency, 5/5 mentions answered); `gemini-code-assist`
/// stays `nudgeable: false` with an empty `review_handle` until its trigger is
/// characterized (Evidence Gaps), which is strictly more than the old lists knew.
const BOT_PROFILES: &[BotProfile] = &[
    BotProfile {
        login: "chatgpt-codex-connector",
        review_handle: "@codex review",
        reply_handle: "@chatgpt-codex-connector",
        usage_markers: &["usage limits for code reviews", "codex usage limits"],
        nudgeable: true,
    },
    BotProfile {
        login: "gemini-code-assist",
        review_handle: "",
        reply_handle: "@gemini-code-assist",
        usage_markers: &[],
        nudgeable: false,
    },
];

/// The profile for an actual review/comment AUTHOR login (may carry gh's `[bot]`
/// suffix or be the full login): the profile login is a substring of the author,
/// matching `login_matches_bot(author, profile.login)`. Used to reach a finding
/// author's `reply_handle` (x-b167 AC14).
fn profile_by_author(author: &str) -> Option<&'static BotProfile> {
    BOT_PROFILES
        .iter()
        .find(|p| login_matches_bot(author, p.login))
}

/// Two login strings name the same bot when either is a case-insensitive
/// substring of the other (so a config short name "codex", a full login, and a
/// "[bot]"-suffixed author all correspond). Symmetric superset of
/// `login_matches_bot`.
fn logins_correspond(a: &str, b: &str) -> bool {
    login_matches_bot(a, b) || login_matches_bot(b, a)
}

/// Default nudge cadence (x-b167). 15 minutes is the observed 6m55s worst-case
/// latency on PR #618 with headroom, not a guess; 3 nudges bounds the give-up at
/// ~45 minutes of *asked-for* waiting versus the unbounded budget burn today.
const DEFAULT_NUDGE_WAIT_MINUTES: i64 = 15;
const DEFAULT_NUDGE_CEILING: usize = 3;

/// Sanity ceilings for `[review.nudge]` override integers (x-b167). A value
/// beyond these is a typo, not a cadence: `wait_minutes` is bounded well under
/// `i64::MAX/60` so `chrono::Duration::minutes` can never overflow-panic in the
/// stop gate, and a nudge cadence past a week / 1000 asks is meaningless anyway.
const MAX_NUDGE_WAIT_MINUTES: i64 = 7 * 24 * 60; // one week
const MAX_NUDGE_CEILING: i64 = 1000;

/// A nudgeable bot login with its resolved cadence: BOT_PROFILES defaults
/// overlaid with `[review.nudge]` overrides. ONLY nudgeable logins appear here
/// (enabled, non-empty review_handle, not malformed); any other missing bot
/// classifies `NotNudgeable`.
#[derive(Debug, Clone)]
struct NudgeConfig {
    login: String,
    review_handle: String,
    wait_minutes: i64,
    ceiling: usize,
}

/// Resolve the nudgeable-bot set for this repo: the built-in profiles, then the
/// `[review.nudge]` overrides. A malformed or `enabled = false` override REMOVES
/// its login from the set (opting out is never opting into a faster give-up);
/// an override with no resolvable `review_handle` (neither its own nor a base
/// profile's) is likewise dropped, since there is nothing to post.
fn resolved_nudge_configs(settings: &Settings) -> Vec<NudgeConfig> {
    let mut out: Vec<NudgeConfig> = BOT_PROFILES
        .iter()
        .filter(|p| p.nudgeable && !p.review_handle.is_empty())
        .map(|p| NudgeConfig {
            login: p.login.to_string(),
            review_handle: p.review_handle.to_string(),
            wait_minutes: DEFAULT_NUDGE_WAIT_MINUTES,
            ceiling: DEFAULT_NUDGE_CEILING,
        })
        .collect();

    for ov in &settings.nudge_overrides {
        let base = out
            .iter()
            .find(|c| logins_correspond(&c.login, &ov.login))
            .cloned();
        // Drop first so an override always replaces (or removes) its login.
        out.retain(|c| !logins_correspond(&c.login, &ov.login));
        if ov.malformed || !ov.enabled {
            continue; // opt-out / bad entry -> non-nudgeable
        }
        let handle = ov
            .review_handle
            .clone()
            .or_else(|| base.as_ref().map(|b| b.review_handle.clone()))
            .filter(|h| !h.is_empty());
        let Some(review_handle) = handle else {
            continue; // no trigger to post -> not nudgeable
        };
        out.push(NudgeConfig {
            login: ov.login.clone(),
            review_handle,
            wait_minutes: ov
                .wait_minutes
                .or_else(|| base.as_ref().map(|b| b.wait_minutes))
                .unwrap_or(DEFAULT_NUDGE_WAIT_MINUTES),
            ceiling: ov
                .ceiling
                .or_else(|| base.as_ref().map(|b| b.ceiling))
                .unwrap_or(DEFAULT_NUDGE_CEILING),
        });
    }
    out
}

/// The nudge config for a configured missing-bot login, or None (non-nudgeable).
fn nudge_config_for<'a>(configs: &'a [NudgeConfig], bot: &str) -> Option<&'a NudgeConfig> {
    configs.iter().find(|c| logins_correspond(&c.login, bot))
}

/// A missing bot's nudge classification for this fire (x-b167). Derived fresh
/// from PR comments every fire - no durable counter - so a mention posted by a
/// human, `/fno:pr check`, or a sibling worktree counts identically and
/// self-heals across restart / compaction / handoff.
#[derive(Debug, Clone, PartialEq)]
enum NudgeClass {
    /// No mention within the wait window: work to DO (post the trigger). Never
    /// idlable.
    NeedsNudge,
    /// Newest mention still inside the wait window: a genuine async wait. The
    /// only idlable nudge state.
    Awaiting,
    /// Ceiling reached and the newest mention timed out: nobody will end this
    /// wait. Never idlable, so the NoProgress backstop reaps it.
    Unresponsive,
    /// Login footnote cannot nudge (no profile/override, disabled, or a peer
    /// sentinel): today's block-and-wait behavior, unchanged. Idlable (status
    /// quo).
    NotNudgeable,
}

/// One missing bot's classification plus the facts the block message renders.
#[derive(Debug, Clone)]
struct BotNudge {
    login: String,
    class: NudgeClass,
    /// The trigger to post; "" when NotNudgeable.
    review_handle: String,
    ceiling: usize,
    /// Mention count on the PR (every issue comment containing review_handle).
    nudges: usize,
    /// Minutes since the newest mention (0 when there is none).
    newest_age_min: i64,
    /// Minutes from the oldest mention to now (0 when there is none), for the
    /// "did not review after N nudges over Mm" give-up line.
    span_min: i64,
}

impl BotNudge {
    fn not_nudgeable(login: &str) -> Self {
        BotNudge {
            login: login.to_string(),
            class: NudgeClass::NotNudgeable,
            review_handle: String::new(),
            ceiling: 0,
            nudges: 0,
            newest_age_min: 0,
            span_min: 0,
        }
    }
}

/// Whether this state may idle on a `<watching>` tag: only a genuine async wait
/// (Awaiting) or a login we never nudge (NotNudgeable, status quo). NeedsNudge is
/// work to do; Unresponsive is a wait nobody ends.
fn nudge_class_idlable(class: &NudgeClass) -> bool {
    matches!(class, NudgeClass::Awaiting | NudgeClass::NotNudgeable)
}

/// Classify one missing bot against the PR's issue comments. A mention is every
/// issue comment whose body contains the trigger handle, author unrestricted (a
/// mention is a request from anyone; only a usage-limit *claim* is scoped to the
/// bot's own login). Reads NO review timestamp and NO `reviews[].commit`: the
/// bot gate is PR-lifetime, and touching either silently re-pins it to head.
fn classify_bot_nudge(
    login: &str,
    comments: &[Value],
    cfg: Option<&NudgeConfig>,
    now: DateTime<Utc>,
) -> BotNudge {
    let Some(cfg) = cfg else {
        return BotNudge::not_nudgeable(login);
    };
    if cfg.review_handle.is_empty() {
        return BotNudge::not_nudgeable(login);
    }
    let mut total = 0usize;
    let mut times: Vec<DateTime<Utc>> = Vec::new();
    for c in comments {
        let body = c.get("body").and_then(|v| v.as_str()).unwrap_or("");
        if !body.contains(&cfg.review_handle) {
            continue;
        }
        total += 1;
        // A malformed/missing createdAt must NOT push toward Unresponsive:
        // giving up on a parse error is not reversible, asking again is (AC-ERR).
        if let Some(dt) = c
            .get("createdAt")
            .and_then(|v| v.as_str())
            .and_then(|s| s.parse::<DateTime<Utc>>().ok())
        {
            times.push(dt);
        }
    }
    if total == 0 {
        return BotNudge {
            login: login.to_string(),
            class: NudgeClass::NeedsNudge,
            review_handle: cfg.review_handle.clone(),
            ceiling: cfg.ceiling,
            nudges: 0,
            newest_age_min: 0,
            span_min: 0,
        };
    }
    let (Some(newest), Some(oldest)) = (times.iter().max().copied(), times.iter().min().copied())
    else {
        // Mentions exist but none carried a usable timestamp: ask again (cheap).
        return BotNudge {
            login: login.to_string(),
            class: NudgeClass::NeedsNudge,
            review_handle: cfg.review_handle.clone(),
            ceiling: cfg.ceiling,
            nudges: total,
            newest_age_min: 0,
            span_min: 0,
        };
    };
    let newest_age_min = (now - newest).num_minutes().max(0);
    let span_min = (now - oldest).num_minutes().max(0);
    let class = if (now - newest) < chrono::Duration::minutes(cfg.wait_minutes) {
        NudgeClass::Awaiting
    } else if total >= cfg.ceiling {
        NudgeClass::Unresponsive
    } else {
        NudgeClass::NeedsNudge // previous mention timed out; ask again
    };
    BotNudge {
        login: login.to_string(),
        class,
        review_handle: cfg.review_handle.clone(),
        ceiling: cfg.ceiling,
        nudges: total,
        newest_age_min,
        span_min,
    }
}

/// Default must-have-reviewed list when config.review.github_apps is absent.
/// EMPTY for fresh installs: a clone with no review configuration completes on
/// PR + CI green without hanging on a review bot it has never set up (a fresh
/// `/target` otherwise runs to the budget cap waiting for a codex review that
/// never arrives). Maintainers who want an external-review gate pin it
/// explicitly via config.review.github_apps (e.g. ["chatgpt-codex-connector"]).
const DEFAULT_REQUIRED_BOTS: &[&str] = &[];

/// Stable reviewer key emitted by every identity-free peer. Multiple configured
/// peer harnesses are alternatives for one composite gate, not N required votes.
const LOCAL_PEER_REVIEWER: &str = "peer";

/// An unmatchable reviewer key used when every identity-free peer is the
/// author's own model family. It keeps the local gate fail-closed independently
/// of the producer and is rendered as an actionable same-model refusal.
const SAME_MODEL_LOCAL_PEER_SENTINEL: &str = "\u{0}fno-peer-same-model-local\u{0}";

/// A login no real GitHub account can equal, pushed when a required peer login is
/// backed ONLY by peers whose model is the author's own (same-model guard). It
/// REPLACES the clearable login so a same-model review can never satisfy the
/// cross-model gate.
const SAME_MODEL_PEER_SENTINEL: &str = "\u{0}fno-peer-same-model\u{0}";

/// Model family of a harness or provider name - the same-model guard's proxy for
/// "which model". The author's family is its invoking harness's family
/// (claude->anthropic, codex->openai, gemini->google); a peer's family is its
/// route provider (else its bare provider). An unknown name is None and so never
/// equals any author family (fail open per-peer). A routed-transport author
/// (claude CLI over GLM) still reads as anthropic here - a known limitation that
/// errs toward HOLDING the gate, never wrongly clearing it.
fn harness_family(name: &str) -> Option<&'static str> {
    match name.trim().to_ascii_lowercase().as_str() {
        "claude" | "anthropic" => Some("anthropic"),
        "codex" | "openai" => Some("openai"),
        "gemini" | "google" => Some("google"),
        _ => None,
    }
}

/// The route provider of a peers `model` route: `"route_provider,route_model"`
/// -> `route_provider`. None unless there are exactly two non-empty comma parts,
/// matching the loader's parse rule (config/__init__.py coerce_peers), so a
/// malformed route falls back to the bare provider.
fn route_provider(model: &str) -> Option<&str> {
    let mut parts = model.split(',').map(str::trim);
    match (parts.next(), parts.next(), parts.next()) {
        (Some(prov), Some(rest), None) if !prov.is_empty() && !rest.is_empty() => Some(prov),
        _ => None,
    }
}

/// A peer's effective model family: its route provider's family when it names a
/// valid route, else its bare provider's family. A `model` route is only honored
/// for a **claude** peer, because only the claude transport actually executes a
/// route (`claude -p` over the routed model); codex/gemini dispatch ignores the
/// route and runs the bare provider, so trusting a codex/gemini route would
/// classify a same-model review as cross-model and re-open the bypass this guard
/// exists to close. Matches the loader, which validates routes for claude only.
fn peer_family(peer: &PeerEntry) -> Option<&'static str> {
    let effective = peer
        .model
        .as_deref()
        .filter(|_| peer.provider.trim().eq_ignore_ascii_case("claude"))
        .and_then(route_provider)
        .unwrap_or(peer.provider.as_str());
    harness_family(effective)
}

/// Thin wrapper: resolve the must-have-reviewed login set with NO author-harness
/// awareness (the same-model guard is inert). Test-only convenience so existing
/// tests stay byte-identical; production passes the resolved harness via
/// [`resolved_required_bots_for_author`].
#[cfg(test)]
fn resolved_required_bots(settings: &Settings) -> Vec<String> {
    resolved_required_bots_for_author(settings, None)
}

/// The set of expected review logins that must have passed for the gate to
/// clear (x-4baa): `github_apps` (or its legacy `required_bots` alias) UNION
/// the resolved posting identity of each identity-backed `peers` entry.
/// Identity-free peers are resolved separately into local reviewer evidence.
///
/// `author_harness` is the invoking harness (`claude`/`codex`/`gemini`), resolved
/// from the ambient env markers by the caller. When it resolves to a model
/// family, the same-model guard (x-c2e7) replaces any peer login backed ONLY by
/// the author's own model with SAME_MODEL_PEER_SENTINEL, so a codex-authored run
/// with `peers: [codex]` can no longer review its own work and clear the gate.
/// `None` (unknown authorship) leaves the login set byte-identical - fail open.
fn resolved_required_bots_for_author(
    settings: &Settings,
    author_harness: Option<&str>,
) -> Vec<String> {
    // github_apps wins over the legacy required_bots alias when both are set.
    if settings.github_apps.is_some() && settings.required_bots.is_some() {
        eprintln!(
            "loop-check: both config.review.github_apps and required_bots set - using github_apps"
        );
    }
    let mut logins: Vec<String> = match settings
        .github_apps
        .as_ref()
        .or(settings.required_bots.as_ref())
    {
        Some(list) => list.clone(),
        None => DEFAULT_REQUIRED_BOTS
            .iter()
            .map(|s| s.to_string())
            .collect(),
    };

    // Only identity-backed peers contribute to the expected-login set. Shared
    // identity collapses to one login; per-peer identities each add their own.
    // Identity-free peers are not missing logins: they use local attestations.
    for peer in &settings.peers {
        let id = peer
            .identity
            .clone()
            .or_else(|| settings.peer_identity.clone());
        match id {
            Some(id) if !logins.iter().any(|l| l == &id) => logins.push(id),
            Some(_) => {} // already present (shared identity)
            None => {}    // local-attestation carrier
        }
    }

    // Same-model guard (x-c2e7): a peer login backed ONLY by the author's own
    // model cannot honestly satisfy the cross-model gate. Inert unless the
    // author harness resolves to a family (fail open on unknown authorship, so
    // the block above stays byte-identical). The GITHUB_APPS base set is never
    // touched - only logins contributed by `peers` are eligible.
    if let Some(author) = author_harness.filter(|_| !settings.peers.is_empty()) {
        if let Some(author_fam) = harness_family(author) {
            apply_same_model_guard(&mut logins, settings, author, author_fam);
        }
    }
    logins
}

/// Resolve all identity-free peers into one local reviewer requirement.
///
/// Any cross-model option makes the composite gate satisfiable by a `peer`
/// attestation. When the author is known and every option is same-model, return
/// an unmatchable sentinel so even a forged `peer: pass` cannot self-review the
/// change. Unknown peer families remain eligible, matching the existing
/// identity-backed guard's conservative compatibility rule.
fn resolved_local_peer_reviewers_for_author(
    settings: &Settings,
    author_harness: Option<&str>,
) -> Vec<String> {
    if settings.peer_identity.is_some() {
        return Vec::new();
    }
    let local: Vec<&PeerEntry> = settings
        .peers
        .iter()
        .filter(|peer| peer.identity.is_none())
        .collect();
    if local.is_empty() {
        return Vec::new();
    }
    let Some(author_fam) = author_harness.and_then(harness_family) else {
        return vec![LOCAL_PEER_REVIEWER.to_string()];
    };
    if local
        .iter()
        .any(|peer| peer_family(peer) != Some(author_fam))
    {
        vec![LOCAL_PEER_REVIEWER.to_string()]
    } else {
        eprintln!(
            "loop-check: every identity-free peer is the author's own model - configure a cross-model peer or routed model"
        );
        vec![SAME_MODEL_LOCAL_PEER_SENTINEL.to_string()]
    }
}

/// Replace every peer-contributed login backed ONLY by same-model peers with
/// SAME_MODEL_PEER_SENTINEL and print one loud line per such login. A login with
/// >=1 cross-model peer (a different family, or an unknown provider) is left
/// alone. When a same-model peer login COLLIDES with a github_apps/required_bots
/// base login (`peer_identity` == an App login), the base login is kept (its App
/// requirement is not loosened) AND the sentinel is appended, so a same-model
/// review posted under that shared login can never be the thing that clears the
/// gate - the collision is a fail-closed hold, not an exemption (codex peer
/// review on PR #375). Peers are walked in config order so output is deterministic.
fn apply_same_model_guard(
    logins: &mut Vec<String>,
    settings: &Settings,
    author_harness: &str,
    author_fam: &str,
) {
    let base_set = settings
        .github_apps
        .as_ref()
        .or(settings.required_bots.as_ref());

    // Per distinct peer login, in first-seen order: does any backing peer differ
    // in model family, and the first same-model provider (for the message)?
    let mut seen: Vec<(String, bool, String)> = Vec::new();
    for peer in &settings.peers {
        let Some(login) = peer
            .identity
            .as_deref()
            .or(settings.peer_identity.as_deref())
        else {
            continue;
        };
        let cross = peer_family(peer) != Some(author_fam);
        match seen.iter_mut().find(|(l, _, _)| l.as_str() == login) {
            Some(entry) => entry.1 = entry.1 || cross,
            None => seen.push((login.to_string(), cross, peer.provider.clone())),
        }
    }

    for (login, any_cross, provider) in seen {
        if any_cross {
            continue;
        }
        if base_set.is_some_and(|set| set.contains(&login)) {
            // Collision: the peer posts under a required App login. Keep the App
            // requirement, but add the sentinel so this same-model login can't be
            // what clears the gate (never an exemption - fail closed).
            if !logins.iter().any(|l| l == SAME_MODEL_PEER_SENTINEL) {
                logins.push(SAME_MODEL_PEER_SENTINEL.to_string());
            }
        } else if let Some(slot) = logins.iter_mut().find(|l| **l == login) {
            // Peer-only login: replace it with the sentinel.
            *slot = SAME_MODEL_PEER_SENTINEL.to_string();
        }
        eprintln!(
            "loop-check: peer '{provider}' is the author's own model ({author_harness}-authored run) - the cross-model gate cannot be satisfied by it; configure a cross-model peer or a model route"
        );
    }
}

/// The OPTIONAL reviewer logins (config.review.optional_apps): honored-if-
/// present but never required. Their blocking findings hold the gate, but their
/// absence never does (x-4baa "honor if present"). Empty when unset.
fn resolved_optional_bots(settings: &Settings) -> Vec<String> {
    settings.optional_apps.clone().unwrap_or_default()
}

/// Case-insensitive substring match so a configured short name ("codex") or a
/// full login both match the review author, including gh's `[bot]`-suffixed
/// form (reference_gh_bot_login_suffix_polling_trap).
pub(crate) fn login_matches_bot(login: &str, bot: &str) -> bool {
    !bot.is_empty() && login.to_lowercase().contains(&bot.to_lowercase())
}

fn is_bot_reviewer(login: &str, external_reviewers: &[String]) -> bool {
    if !external_reviewers.is_empty() {
        let login_lower = login.to_lowercase();
        // Case-insensitive substring match: "gemini" matches "gemini-code-assist[bot]"
        if external_reviewers
            .iter()
            .any(|r| login_lower.contains(&r.to_lowercase()))
        {
            return true;
        }
        // Configured list present but no entry matched: fall back to bot heuristic
        // so a configured-but-partial list doesn't make reviewed unreachable.
    }
    // Default: endswith [bot] or a known profile login
    login.ends_with("[bot]") || BOT_PROFILES.iter().any(|p| login.contains(p.login))
}

/// Every usage-limit marker across all bot profiles, unioned. A rate-limited
/// review bot posts one of these as an ISSUE comment when it never posts a review
/// object (PR #214). Matched case-insensitively via `contains` against a
/// lowercased body, mirroring the pinned-string approach in `blocking_severity`.
/// Unioned rather than scoped per-login to stay byte-identical to the old flat
/// `USAGE_LIMIT_MARKERS` const it replaced: an under-match degrades to the safe
/// old block behavior; an over-match risks a false drop.
pub(crate) fn body_is_usage_limit(body: &str) -> bool {
    BOT_PROFILES
        .iter()
        .flat_map(|p| p.usage_markers.iter())
        .any(|m| body.contains(m))
}

/// Per-required-bot review verdict (grilled decision 5 / step 2).
#[derive(Debug)]
struct ReviewInfo {
    /// Latest review/comment activity timestamp, or "none".
    latest_ts: String,
    /// Required bots with no completed review pass. A pass is a top-level
    /// review with any non-empty state on ANY commit - in practice COMMENTED
    /// (verified on PR #447; codex reviews once per PR and never re-reviews,
    /// so requiring a pass on HEAD would make the gate unsatisfiable).
    missing_bots: Vec<String>,
    /// Required bots dropped from `missing_bots` because they are env-blocked
    /// (rate-limited): they posted only a usage-limit comment, never a review.
    /// Keeping them in `missing_bots` wedged the gate until budget death
    /// (PR #214); dropping them lets the gate proceed on remaining evidence
    /// while the caller records the drop (AC1-UI). A bot is never in both
    /// lists - it is scanned only while still in `missing_bots`.
    usage_limited: Vec<String>,
}

impl ReviewInfo {
    /// Every required bot has at least one completed pass.
    fn all_required_passed(&self) -> bool {
        self.missing_bots.is_empty()
    }
}

fn compute_review_info(reviews_json: &Value, required_bots: &[String]) -> ReviewInfo {
    let reviews = reviews_json
        .get("reviews")
        .and_then(|v| v.as_array())
        .map(|v| v.as_slice())
        .unwrap_or(&[]);
    let comments = reviews_json
        .get("comments")
        .and_then(|v| v.as_array())
        .map(|v| v.as_slice())
        .unwrap_or(&[]);

    let mut latest_ts = String::new(); // empty; "none" returned if no activity found
    let mut passed: Vec<bool> = vec![false; required_bots.len()];

    for r in reviews {
        let login = r
            .pointer("/author/login")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let submitted_at = r.get("submittedAt").and_then(|v| v.as_str()).unwrap_or("");
        let state = r.get("state").and_then(|v| v.as_str()).unwrap_or("");

        if !submitted_at.is_empty() && submitted_at > latest_ts.as_str() {
            latest_ts = submitted_at.to_string();
        }

        if !state.is_empty() {
            for (i, bot) in required_bots.iter().enumerate() {
                if login_matches_bot(login, bot) {
                    passed[i] = true;
                }
            }
        }
    }

    for c in comments {
        let created_at = c.get("createdAt").and_then(|v| v.as_str()).unwrap_or("");
        if !created_at.is_empty() && created_at > latest_ts.as_str() {
            latest_ts = created_at.to_string();
        }
    }

    let final_ts = if latest_ts.is_empty() {
        "none".to_string()
    } else {
        latest_ts
    };

    let mut missing_bots: Vec<String> = required_bots
        .iter()
        .zip(passed.iter())
        .filter(|(_, ok)| !**ok)
        .map(|(bot, _)| bot.clone())
        .collect();

    // (a) Usage-limit detection. A still-missing required bot that authored a
    // comment carrying a pinned usage-limit marker is env-blocked, not
    // hasn't-reviewed-yet: it will never post a review, so leaving it in
    // missing_bots blocks every fire until the budget cap kills the session
    // (PR #214). Move it OUT of missing_bots into usage_limited so the gate
    // proceeds on remaining evidence (the caller logs the drop + names the bot,
    // and the merge stays human-gated). Scoped to the bot's OWN author.login so
    // a stranger's comment never drops a required bot (AC1-ERR). Only
    // still-missing bots are scanned, so a bot that actually reviewed is never
    // usage-limited-dropped (AC1-EDGE).
    let mut usage_limited: Vec<String> = Vec::new();
    missing_bots.retain(|bot| {
        let rate_limited = comments.iter().any(|c| {
            let login = c
                .pointer("/author/login")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            if !login_matches_bot(login, bot) {
                return false;
            }
            let body = c
                .get("body")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_lowercase();
            body_is_usage_limit(&body)
        });
        if rate_limited {
            usage_limited.push(bot.clone());
            false
        } else {
            true
        }
    });

    ReviewInfo {
        latest_ts: final_ts,
        missing_bots,
        usage_limited,
    }
}

// ── inline findings (Read 4, step 2 / US2) ────────────────────────────────────

/// A blocking inline finding: a root review comment (in_reply_to_id == null)
/// authored by a required bot whose body carries a blocking severity badge.
#[derive(Debug, Clone)]
struct Finding {
    id: i64,
    /// Bot login that posted the finding (REST `user.login`).
    author: String,
    path: String,
    line: i64,
    created_at: String,
    /// Parsed severity label (P1 / critical / high).
    severity: &'static str,
}

/// Parse a blocking severity from the bot's own badge markup. The exact
/// strings are pinned from PR #447 ground truth; both the alt-text and the
/// badge-URL forms are matched so a partial render still classifies:
///   codex:  `![P1 Badge](https://img.shields.io/badge/P1-orange?style=flat)`
///   gemini: `![high](https://www.gstatic.com/codereviewagent/high-priority.svg)`
/// Anything unparseable is advisory, never blocking (locked decision 4:
/// under-blocking is the only safe failure - the agent cannot edit a bot's
/// comment, and PR history is the post-hoc backstop).
fn blocking_severity(body: &str) -> Option<&'static str> {
    if body.contains("![P1 Badge]") || body.contains("badge/P1-") {
        return Some("P1");
    }
    if body.contains("![critical]") || body.contains("critical-priority.svg") {
        return Some("critical");
    }
    if body.contains("![high]") || body.contains("high-priority.svg") {
        return Some("high");
    }
    None
}

/// Max of two timestamp strings, treating "none"/"" as the lowest value.
/// Both sides are compared chronologically when they parse (gemini HIGH on
/// #448: an offset-suffixed timestamp can sort above a Zulu one
/// lexicographically while being earlier in UTC); the returned value is
/// always one of the ORIGINAL strings so the fingerprint stays byte-stable.
/// Unparseable-but-real strings fall back to lexicographic comparison.
fn max_ts(a: &str, b: &str) -> String {
    if let (Ok(da), Ok(db)) = (a.parse::<DateTime<Utc>>(), b.parse::<DateTime<Utc>>()) {
        return if da >= db {
            a.to_string()
        } else {
            b.to_string()
        };
    }
    let a_real = !a.is_empty() && a != "none";
    let b_real = !b.is_empty() && b != "none";
    match (a_real, b_real) {
        (true, true) => {
            if a >= b {
                a.to_string()
            } else {
                b.to_string()
            }
        }
        (true, false) => a.to_string(),
        (false, true) => b.to_string(),
        (false, false) => "none".to_string(),
    }
}

/// The `wontfix:` decline marker (documented in skills/check-pr). Matched
/// case-insensitively in a non-bot reply body.
const WONTFIX_MARKER: &str = "wontfix:";

/// True iff `a` is strictly after `b`. Both sides parse as RFC3339; an
/// unparseable timestamp returns false, so a blocking finding is never
/// cleared on garbage data. Raw string comparison is NOT used here because
/// offset-suffixed and Z-suffixed forms mis-order lexicographically
/// (e.g. "...T23:30:00+13:00" sorts above "...T11:00:00Z" as a string but
/// is 30 minutes EARLIER in UTC).
fn ts_after(a: &str, b: &str) -> bool {
    match (a.parse::<DateTime<Utc>>(), b.parse::<DateTime<Utc>>()) {
        (Ok(da), Ok(db)) => da > db,
        _ => false,
    }
}

/// Walk the `/pulls/N/comments` array (REST shape: `user.login`,
/// `in_reply_to_id`, `created_at`). Returns the newest comment timestamp
/// (fingerprint contribution) and the UNADDRESSED blocking findings.
///
/// A blocking finding is addressed iff its thread has a non-bot reply AND
/// (a commit landed after the finding's created_at OR a non-bot reply body
/// carries `wontfix:`). The reply is mandatory: a commit alone must not
/// silently clear a P1 (anti-gaming, locked decision 3).
fn compute_unaddressed_findings(
    comments: &[Value],
    commit_dates: &[String],
    required_bots: &[String],
    external_reviewers: &[String],
) -> (String, Vec<Finding>) {
    let mut latest_ts = String::new();
    let mut candidates: Vec<Finding> = Vec::new();
    // finding id -> non-bot replies' bodies
    let mut replies: std::collections::HashMap<i64, Vec<String>> = std::collections::HashMap::new();

    for c in comments {
        let created_at = c.get("created_at").and_then(|v| v.as_str()).unwrap_or("");
        if !created_at.is_empty() && created_at > latest_ts.as_str() {
            latest_ts = created_at.to_string();
        }

        let login = c
            .pointer("/user/login")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let body = c.get("body").and_then(|v| v.as_str()).unwrap_or("");
        let in_reply_to = c.get("in_reply_to_id").and_then(|v| v.as_i64());

        match in_reply_to {
            Some(parent_id) => {
                // A reply. Only non-bot replies count as the agent's ack.
                if !is_bot_reviewer(login, external_reviewers) {
                    replies.entry(parent_id).or_default().push(body.to_string());
                }
            }
            None => {
                // A root comment: a finding when a required bot posted it
                // with a blocking badge.
                let by_required_bot = required_bots
                    .iter()
                    .any(|bot| login_matches_bot(login, bot));
                if by_required_bot {
                    if let Some(severity) = blocking_severity(body) {
                        // A REST comment always carries an integer id; a row
                        // without one is schema drift. Skip it rather than
                        // pooling id-less findings on a shared default bucket
                        // where a single stray reply could mark them all
                        // addressed (under-blocking is the safe direction per
                        // locked decision 4; PR history is the backstop).
                        let Some(id) = c.get("id").and_then(|v| v.as_i64()) else {
                            eprintln!(
                                "loop-check: skipping blocking finding with missing id (author={login})"
                            );
                            continue;
                        };
                        candidates.push(Finding {
                            id,
                            author: login.to_string(),
                            path: c
                                .get("path")
                                .and_then(|v| v.as_str())
                                .unwrap_or("unknown")
                                .to_string(),
                            line: c
                                .get("line")
                                .and_then(|v| v.as_i64())
                                .or_else(|| c.get("original_line").and_then(|v| v.as_i64()))
                                .unwrap_or(0),
                            created_at: created_at.to_string(),
                            severity,
                        });
                    }
                }
            }
        }
    }

    let unaddressed: Vec<Finding> = candidates
        .into_iter()
        .filter(|f| {
            let non_bot_replies = replies.get(&f.id);
            let has_reply = non_bot_replies.map(|r| !r.is_empty()).unwrap_or(false);
            if !has_reply {
                return true; // no ack -> unaddressed
            }
            let commit_after = commit_dates.iter().any(|d| ts_after(d, &f.created_at));
            let wontfix = non_bot_replies
                .map(|rs| rs.iter().any(|b| b.to_lowercase().contains(WONTFIX_MARKER)))
                .unwrap_or(false);
            !(commit_after || wontfix)
        })
        .collect();

    let final_ts = if latest_ts.is_empty() {
        "none".to_string()
    } else {
        latest_ts
    };
    (final_ts, unaddressed)
}

// ── fingerprint + fire history ────────────────────────────────────────────────

fn make_fingerprint(
    head_sha: &str,
    pr_state: &str,
    ci_conclusion: &str,
    latest_ts: &str,
) -> String {
    format!("{head_sha}|{pr_state}|{ci_conclusion}|{latest_ts}")
}

/// Default debounce window: an unchanged fingerprint seen again inside this many
/// seconds is the SAME observation, not a new one. The streak counts independent
/// observations of an unchanged world, not stop-hook fires -- a session taking
/// short turns used to burn a 5-fire backstop in 109 seconds while its CI run
/// still had 7 minutes to go, which no external wait can outrun. The effective
/// floor becomes `(backstop_n - 1) * gap`: 10 minutes unattended, 20 attended.
/// Override with `FNO_LOOPCHECK_MIN_FIRE_GAP_SECS` (0 restores fire counting).
const MIN_FIRE_GAP_SECS: i64 = 300;

/// Resolve the debounce window from the env seam, falling back to the default.
/// Mirrors the `FNO_LOOPCHECK_GH_BIN` / `_NO_NOTIFY` / `_NO_COMMENT` seams.
fn min_fire_gap_secs() -> i64 {
    std::env::var("FNO_LOOPCHECK_MIN_FIRE_GAP_SECS")
        .ok()
        .and_then(|s| s.trim().parse::<i64>().ok())
        .unwrap_or(MIN_FIRE_GAP_SECS)
}

/// Count prior loop_check events for this session_id in the project events file.
/// Returns (total_fires, consecutive_unchanged_count, last_fingerprint_in_log,
/// streak_window_secs).
///
/// `current_fp` is the fingerprint computed this fire (used for streak matching).
/// `last_fp` is the most recent fingerprint recorded in the events log for this
/// session -- used for carry-forward when the gh pre-read fails this fire.
/// `streak_window_secs` is the span from the oldest COUNTED fire to `now`; it is
/// what makes a streak count falsifiable from the events log.
///
/// The streak is debounced by `min_gap_secs`: walking backwards from `now`, a
/// matching fire closer than the gap to the last counted one is skipped
/// TRANSPARENTLY and does not advance the cursor, so a burst collapses to a
/// single observation. The asymmetry is deliberate and load-bearing: a CHANGED
/// fingerprint breaks the streak at any spacing, because real progress is real
/// progress at any speed -- only the *absence* of change needs time to be
/// credible.
fn read_prior_fires(
    events_path: &Path,
    session_id: &str,
    current_fp: &str,
    now: DateTime<Utc>,
    min_gap_secs: i64,
) -> (u64, u64, Option<String>, i64) {
    let Ok(content) = std::fs::read_to_string(events_path) else {
        return (0, 0, None, 0);
    };

    let mut total: u64 = 0;

    for line in content.lines() {
        let Ok(val) = serde_json::from_str::<Value>(line) else {
            continue;
        };
        if val.get("type").and_then(|v| v.as_str()) != Some("loop_check") {
            continue;
        }
        if val.pointer("/data/session_id").and_then(|v| v.as_str()) != Some(session_id) {
            continue;
        }
        total += 1;
    }

    // Calculate consecutive streak from the end (how many recent fires share current_fp)
    // and capture the most recent fp recorded. `next_ts` is the cursor: it starts
    // at `now` and only moves to a fire that was COUNTED, which is what collapses
    // a rapid burst into one observation.
    let mut consecutive: u64 = 0;
    let mut last_fp: Option<String> = None;
    let mut next_ts = now;
    let mut oldest_counted_ts: Option<DateTime<Utc>> = None;
    for line in content.lines().rev() {
        let Ok(val) = serde_json::from_str::<Value>(line) else {
            continue;
        };
        if val.get("type").and_then(|v| v.as_str()) != Some("loop_check") {
            continue;
        }
        if val.pointer("/data/session_id").and_then(|v| v.as_str()) != Some(session_id) {
            continue;
        }
        // US4: gh-errored fires are TRANSPARENT to the streak - they neither
        // advance nor reset the consecutive count (their recorded fp is just
        // a carry-forward, not an observation). After an outage clears, the
        // streak resumes from its pre-outage value (AC4-FR).
        if val
            .pointer("/data/fp_read_failed")
            .and_then(|v| v.as_bool())
            == Some(true)
        {
            continue;
        }
        let fp = val
            .pointer("/data/fingerprint")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        // Capture the most recent fp (first match in reverse order)
        if last_fp.is_none() && !fp.is_empty() {
            last_fp = Some(fp.to_string());
        }
        // A CHANGED fingerprint breaks the streak at ANY spacing - progress is
        // never debounced. This check precedes the gap check on purpose.
        if fp != current_fp {
            break;
        }
        // Debounce. A fire we cannot place in time is skipped transparently
        // rather than counted: giving up on a parse error must fail AWAY from
        // an irreversible NoProgress, matching classify_bot_nudge's precedent.
        let Some(ts) = val
            .get("ts")
            .and_then(|v| v.as_str())
            .and_then(|s| s.parse::<DateTime<Utc>>().ok())
        else {
            continue;
        };
        let gap = (next_ts - ts).num_seconds();
        // gap < 0 means clock skew (a fire stamped after `now`); count it rather
        // than invent a debounce from a bad clock - status quo, no crash.
        if gap < 0 || gap >= min_gap_secs {
            consecutive += 1;
            next_ts = ts;
            oldest_counted_ts = Some(ts);
        }
        // else: same observation seen twice; skip WITHOUT advancing next_ts.
    }

    let streak_window_secs = oldest_counted_ts
        .map(|t| (now - t).num_seconds().max(0))
        .unwrap_or(0);

    (total, consecutive, last_fp, streak_window_secs)
}

// ── event emission ────────────────────────────────────────────────────────────

/// Envelope struct for target-stream events. Field order ts,type,source,data is
/// preserved because serde_json serializes struct fields in declaration order.
/// Method is named `append_loop_event` (NOT .emit / .emit_fields) so the
/// production-emit scanner test in lib.rs does not capture it and force
/// registration in KNOWN_EVENT_KINDS (which is the Branch B / fno-agents
/// daemon stream, not the target stream that these events belong to).
#[derive(Debug, Serialize)]
struct LoopEventEnvelope<'a> {
    ts: String,
    #[serde(rename = "type")]
    event_type: &'a str,
    source: &'static str,
    data: serde_json::Value,
}

// pub(crate): the `finalize` verb (step 6, ab-f8e5f214) reuses this so its
// `session_finalized` events carry the identical RFC3339 timestamp shape.
pub(crate) fn now_rfc3339_utc() -> String {
    // Seconds precision, Z suffix, as required by the envelope spec.
    let now = chrono::Utc::now();
    now.format("%Y-%m-%dT%H:%M:%SZ").to_string()
}

/// Append a target-stream event to a file (O_APPEND, create if missing).
/// Failure is loud on stderr but never fatal to the decision.
fn append_loop_event(path: &Path, event_type: &str, data: serde_json::Value) {
    let env = LoopEventEnvelope {
        ts: now_rfc3339_utc(),
        event_type,
        source: "hook",
        data,
    };
    let Ok(mut line) = serde_json::to_string(&env) else {
        eprintln!("loop-check: failed to serialize event {event_type}");
        return;
    };
    line.push('\n');

    // Create parent dirs
    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }

    match std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)
    {
        Ok(mut f) => {
            if let Err(e) = f.write_all(line.as_bytes()) {
                eprintln!(
                    "loop-check: failed to write event {event_type} to {}: {e}",
                    path.display()
                );
            }
        }
        Err(e) => {
            eprintln!(
                "loop-check: failed to open events file {}: {e}",
                path.display()
            );
        }
    }
}

/// Append to both project and global event logs.
///
/// pub(crate): the `finalize` verb (step 6, ab-f8e5f214) emits its
/// `session_finalized` / `session_finalize_failed` events through the same
/// writer so they land in both logs with the identical `{ts,type,source,data}`
/// envelope loop-check uses.
pub(crate) fn emit_to_both(
    project_events: &Path,
    global_events: &Path,
    event_type: &str,
    data: serde_json::Value,
) {
    append_loop_event(project_events, event_type, data.clone());
    if project_events != global_events {
        append_loop_event(global_events, event_type, data);
    }
}

// ── cancel sentinel ───────────────────────────────────────────────────────────

fn check_cancel_sentinel(cwd: &Path, created_at: &Option<String>) -> bool {
    let sentinel = cwd.join(".fno/.target-cancelled");
    let tombstone = cwd.join(".fno/.target-cancelled-final");

    for path in &[&tombstone, &sentinel] {
        if !path.exists() {
            continue;
        }
        // Check mtime >= created_at
        if let Some(ca) = created_at {
            if let Ok(parsed_ca) = ca.parse::<DateTime<Utc>>() {
                if let Ok(meta) = std::fs::metadata(path) {
                    if let Ok(modified) = meta.modified() {
                        let sentinel_time: DateTime<Utc> = modified.into();
                        if sentinel_time >= parsed_ca {
                            return true;
                        }
                        // Stale sentinel (older than created_at) -> ignore
                        continue;
                    }
                }
            }
            // Can't read mtime -> treat as present (fail-closed)
            return true;
        }
        return true;
    }
    false
}

// ── budget check ──────────────────────────────────────────────────────────────

#[derive(Debug, PartialEq)]
enum BudgetTrip {
    WallClock,
    Cost,
}

/// Resolve an `Option<Result<T, String>>` budget cap for use in check_budget.
/// - None => absent (no cap)
/// - Some(Ok(v)) => valid cap value
/// - Some(Err(raw)) => malformed: fail-closed, treat as cap exceeded immediately
enum ResolvedCap<T> {
    Absent,
    Valid(T),
    Malformed(String),
}

fn resolve_cap<T: Copy>(cap: &Option<Result<T, String>>) -> ResolvedCap<T> {
    match cap {
        None => ResolvedCap::Absent,
        Some(Ok(v)) => ResolvedCap::Valid(*v),
        Some(Err(raw)) => ResolvedCap::Malformed(raw.clone()),
    }
}

fn check_budget(
    manifest: &Manifest,
    settings: &Settings,
    now: &DateTime<Utc>,
    ledger_path: &Path,
) -> Option<BudgetTrip> {
    let attended = manifest.attended;

    // Wall-clock cap: prefer manifest value, then settings
    let wall_cap = match resolve_cap(&manifest.budget_wall_clock_cap_minutes) {
        ResolvedCap::Absent => {
            if attended {
                resolve_cap(&settings.attended_wall_cap_minutes)
            } else {
                resolve_cap(&settings.unattended_wall_cap_minutes)
            }
        }
        other => other,
    };

    match wall_cap {
        ResolvedCap::Malformed(raw) => {
            eprintln!("loop-check: malformed budget cap '{raw}' - failing closed; fix the config");
            return Some(BudgetTrip::WallClock);
        }
        ResolvedCap::Valid(cap) => {
            if let Some(ca_str) = &manifest.created_at {
                if let Ok(created) = ca_str.parse::<DateTime<Utc>>() {
                    // Guard against negative elapsed (clock skew / future created_at)
                    let duration = now.signed_duration_since(created);
                    let elapsed_min = if duration.num_minutes() < 0 {
                        0u64
                    } else {
                        duration.num_minutes() as u64
                    };
                    if elapsed_min >= cap {
                        return Some(BudgetTrip::WallClock);
                    }
                }
            }
        }
        ResolvedCap::Absent => {}
    }

    // Cost cap: prefer manifest value, then nested settings, then flat budget_cap
    let cost_cap = match resolve_cap(&manifest.budget_cost_cap_usd) {
        ResolvedCap::Absent => {
            let nested = if attended {
                resolve_cap(&settings.attended_cost_cap_usd)
            } else {
                resolve_cap(&settings.unattended_cost_cap_usd)
            };
            match nested {
                ResolvedCap::Absent => resolve_cap(&settings.flat_budget_cap),
                other => other,
            }
        }
        other => other,
    };

    match cost_cap {
        ResolvedCap::Malformed(raw) => {
            eprintln!("loop-check: malformed budget cap '{raw}' - failing closed; fix the config");
            Some(BudgetTrip::Cost)
        }
        ResolvedCap::Valid(cap) => {
            if let Some(session_id) = &manifest.session_id {
                let cost = session_cost_from_ledger(ledger_path, session_id);
                if cost >= cap {
                    return Some(BudgetTrip::Cost);
                }
            }
            None
        }
        ResolvedCap::Absent => None,
    }
}

// ── main decision function ────────────────────────────────────────────────────

/// CLI flags parsed for `loop-check`. The three required paths are
/// non-optional by construction (fu-4faa3d): `parse_args` validates them and
/// returns `Err` on absence, so downstream code cannot forget to check.
#[derive(Debug)]
struct LoopCheckArgs {
    state_path: PathBuf,
    transcript_path: PathBuf,
    cwd: PathBuf,
    /// Override for the GLOBAL settings file (default $HOME/.fno/
    /// settings.yaml). Tests point it at a nonexistent path for hermeticity.
    global_settings_path: Option<PathBuf>,
    events_path: Option<PathBuf>,
    global_events_path: Option<PathBuf>,
    settings_path: Option<PathBuf>,
    ledger_path: Option<PathBuf>,
    now_override: Option<String>,
    gh_bin: String,
    git_bin: String,
    /// When set, the full Stop-hook JSON payload is read from stdin so
    /// `last_assistant_message` becomes the primary intent channel
    /// (ab-223d2dae). Flag-gated so manual terminal invocations never hang
    /// on a stdin read.
    hook_input_stdin: bool,
}

fn parse_args(args: &[String]) -> Result<LoopCheckArgs, String> {
    let mut state_path: Option<PathBuf> = None;
    let mut transcript_path: Option<PathBuf> = None;
    let mut cwd: Option<PathBuf> = None;
    let mut global_settings_path: Option<PathBuf> = None;
    let mut events_path: Option<PathBuf> = None;
    let mut global_events_path: Option<PathBuf> = None;
    let mut settings_path: Option<PathBuf> = None;
    let mut ledger_path: Option<PathBuf> = None;
    let mut now_override: Option<String> = None;
    let mut gh_bin = std::env::var("FNO_LOOPCHECK_GH_BIN").unwrap_or_else(|_| "gh".to_string());
    let mut git_bin = std::env::var("FNO_LOOPCHECK_GIT_BIN").unwrap_or_else(|_| "git".to_string());
    let mut hook_input_stdin = false;

    // Skip the "loop-check" verb itself if present
    let args = if args.first().map(|s| s.as_str()) == Some("loop-check") {
        &args[1..]
    } else {
        args
    };

    let mut i = 0;
    while i < args.len() {
        let arg = &args[i];
        // Support both --flag value and --flag=value forms. Unknown flags are
        // tolerated (AC5-FR: forward-compat for the shim).
        if let Some(val) = try_flag_value(arg, "--state", args, &mut i) {
            state_path = Some(PathBuf::from(val));
        } else if let Some(val) = try_flag_value(arg, "--transcript", args, &mut i) {
            transcript_path = Some(PathBuf::from(val));
        } else if let Some(val) = try_flag_value(arg, "--cwd", args, &mut i) {
            cwd = Some(PathBuf::from(val));
        } else if let Some(val) = try_flag_value(arg, "--events", args, &mut i) {
            events_path = Some(PathBuf::from(val));
        } else if let Some(val) = try_flag_value(arg, "--global-events", args, &mut i) {
            global_events_path = Some(PathBuf::from(val));
        } else if let Some(val) = try_flag_value(arg, "--settings", args, &mut i) {
            settings_path = Some(PathBuf::from(val));
        } else if let Some(val) = try_flag_value(arg, "--global-settings", args, &mut i) {
            global_settings_path = Some(PathBuf::from(val));
        } else if let Some(val) = try_flag_value(arg, "--ledger", args, &mut i) {
            ledger_path = Some(PathBuf::from(val));
        } else if let Some(val) = try_flag_value(arg, "--now", args, &mut i) {
            now_override = Some(val);
        } else if let Some(val) = try_flag_value(arg, "--gh-bin", args, &mut i) {
            gh_bin = val;
        } else if let Some(val) = try_flag_value(arg, "--git-bin", args, &mut i) {
            git_bin = val;
        } else if arg == "--hook-input-stdin" {
            // Bare boolean flag (no value): try_flag_value would consume the
            // next token as a value, so it is matched directly (ab-223d2dae).
            hook_input_stdin = true;
        }
        i += 1;
    }

    // Required-flag validation lives here (AC5-ERR), not downstream in decide().
    let state_path = state_path.ok_or_else(|| "--state is required".to_string())?;
    let transcript_path = transcript_path.ok_or_else(|| "--transcript is required".to_string())?;
    let cwd = cwd.ok_or_else(|| "--cwd is required".to_string())?;

    Ok(LoopCheckArgs {
        state_path,
        transcript_path,
        cwd,
        global_settings_path,
        events_path,
        global_events_path,
        settings_path,
        ledger_path,
        now_override,
        gh_bin,
        git_bin,
        hook_input_stdin,
    })
}

fn try_flag_value(arg: &str, flag: &str, args: &[String], i: &mut usize) -> Option<String> {
    if arg == flag {
        *i += 1;
        args.get(*i).cloned()
    } else if let Some(val) = arg.strip_prefix(&format!("{flag}=")) {
        Some(val.to_string())
    } else {
        None
    }
}

/// Core decision logic. Returns (exit_code, json_output).
/// Exit 0 always for allow/block; non-zero only for internal/CLI errors.
pub fn decide(args: &[String]) -> (i32, String) {
    // Missing required flags are CLI misuse: exit 2 with the same JSON error
    // shape the pre-refactor inline checks emitted (AC5-ERR).
    let parsed = match parse_args(args) {
        Ok(p) => p,
        Err(e) => {
            let out = serde_json::json!({ "error": e });
            return (2, out.to_string());
        }
    };

    let state_path = parsed.state_path.clone();
    let transcript_path = parsed.transcript_path.clone();
    let cwd = parsed.cwd.clone();

    // ab-223d2dae (A): the shim feeds the full Stop-hook JSON via stdin so
    // the stopping turn's final text (`last_assistant_message`, recomputed
    // per fire) is readable without racing the transcript flush. Read or
    // parse failures degrade to None (transcript fallback), never an error -
    // but a genuine I/O error is named on stderr (-> the shim's
    // loop-check.stderr.log) so a sustained stdin failure is separable from
    // an ordinary transcript-channel fire in the forensic trail.
    let last_assistant_message: Option<String> = if parsed.hook_input_stdin {
        match std::io::read_to_string(std::io::stdin()) {
            Ok(s) => extract_last_assistant_message(&s),
            Err(e) => {
                eprintln!(
                    "loop-check: failed to read hook input from stdin: {e}; falling back to transcript scan"
                );
                None
            }
        }
    } else {
        None
    };

    // Parse manifest
    let manifest_content = match std::fs::read_to_string(&state_path) {
        Ok(c) => c,
        Err(e) => {
            eprintln!(
                "loop-check: cannot read state file {}: {e}",
                state_path.display()
            );
            let out = allow_output(
                "allow",
                None,
                "corrupt/missing manifest; allowing exit",
                0,
                None,
            );
            return (0, out);
        }
    };

    let manifest = match parse_manifest(&manifest_content) {
        Some(m) => m,
        None => {
            eprintln!("loop-check: corrupt manifest (no frontmatter)");
            let out = allow_output(
                "allow",
                None,
                "corrupt manifest (no frontmatter); allowing exit",
                0,
                None,
            );
            return (0, out);
        }
    };

    // Lease renewal (x-ba4b): keep this session's node claim fresh on every
    // stop, so a worker whose supervisor pid died mid-run (and now runs under a
    // new pid) never loses its claim to TTL expiry. Best-effort and non-fatal:
    // renew only bumps expires_at when the on-disk holder still matches, so it
    // can never steal, and any failure is a warning that just shortens the lease
    // (the loop never blocks on it). The claim key/holder/ttl are APPENDED after
    // the frontmatter by `fno target init`, so scan the whole manifest for them
    // (parse_manifest is frontmatter-bounded and would miss them). Root=None
    // routes node:<id> to the global claims root inside renew.
    if let (Some(key), Some(holder)) = (
        scan_manifest_field(&manifest_content, "target_claim_key"),
        scan_manifest_field(&manifest_content, "target_claim_holder"),
    ) {
        // Renew for the SAME window the claim was acquired with (default 2h,
        // matching init's `_CLAIM_TTL`), so the deadline never grows.
        let ttl_ms = scan_manifest_field(&manifest_content, "target_claim_ttl")
            .and_then(|s| crate::claims::parse_ttl_ms(&s))
            .unwrap_or(7_200_000);
        match crate::claims::renew(&key, &holder, ttl_ms, None) {
            Ok(_) => {}
            Err(e) => eprintln!("loop-check: lease renewal for {key} failed (non-fatal): {e}"),
        }
    }

    // Resolve paths
    let project_events = parsed
        .events_path
        .clone()
        .unwrap_or_else(|| cwd.join(".fno/events.jsonl"));

    let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());
    let global_events = parsed
        .global_events_path
        .clone()
        .unwrap_or_else(|| PathBuf::from(&home).join(".fno/events.jsonl"));

    let ledger_path = parsed
        .ledger_path
        .clone()
        .unwrap_or_else(|| cwd.join(".fno/ledger.json"));

    // Parse settings: GLOBAL first, then overlay the project-local file's
    // populated fields (codex P1 on #447: budgets normally live in the
    // global file; a project-local settings.yaml with unrelated content
    // must not silently uncap the session). An explicit --settings path
    // replaces the merge entirely (tests rely on full isolation).
    //
    // x-81d9 (c): a genuinely unparseable settings.yaml fails CLOSED (the login
    // gate is pinned unsatisfiable) and emits loop_check_settings_unparseable,
    // rather than silently zeroing the required bots and shipping unreviewed.
    let parse_or_emit = |content: &str, path: &Path| -> Settings {
        match parse_settings_result(content) {
            Ok(s) => s,
            Err(e) => {
                eprintln!(
                    "loop-check: config.toml unparseable ({}): {e} - failing the login gate closed",
                    path.display()
                );
                emit_to_both(
                    &project_events,
                    &global_events,
                    "loop_check_settings_unparseable",
                    serde_json::json!({"path": path.display().to_string(), "error": e}),
                );
                fail_closed_settings()
            }
        }
    };
    let settings = if let Some(ref explicit) = parsed.settings_path {
        if let Ok(sc) = std::fs::read_to_string(explicit) {
            parse_or_emit(&sc, explicit)
        } else {
            Settings::default()
        }
    } else {
        let global_path = parsed
            .global_settings_path
            .clone()
            .unwrap_or_else(|| PathBuf::from(&home).join(".fno/config.toml"));
        let mut merged = std::fs::read_to_string(&global_path)
            .map(|sc| parse_or_emit(&sc, &global_path))
            .unwrap_or_default();
        let local_path = cwd.join(".fno/config.toml");
        if let Ok(sc) = std::fs::read_to_string(&local_path) {
            let local = parse_or_emit(&sc, &local_path);
            if local.attended_wall_cap_minutes.is_some() {
                merged.attended_wall_cap_minutes = local.attended_wall_cap_minutes;
            }
            if local.attended_cost_cap_usd.is_some() {
                merged.attended_cost_cap_usd = local.attended_cost_cap_usd;
            }
            if local.unattended_wall_cap_minutes.is_some() {
                merged.unattended_wall_cap_minutes = local.unattended_wall_cap_minutes;
            }
            if local.unattended_cost_cap_usd.is_some() {
                merged.unattended_cost_cap_usd = local.unattended_cost_cap_usd;
            }
            if local.flat_budget_cap.is_some() {
                merged.flat_budget_cap = local.flat_budget_cap;
            }
            if local.ci_declared_none {
                merged.ci_declared_none = true;
            }
            if !local.external_reviewers.is_empty() {
                merged.external_reviewers = local.external_reviewers;
            }
            if local.required_bots.is_some() {
                // Some([]) is a meaningful project-local override (declared
                // no-review-gate), so presence - not non-emptiness - wins.
                merged.required_bots = local.required_bots;
            }
            if local.github_apps.is_some() {
                merged.github_apps = local.github_apps;
            }
            if local.optional_apps.is_some() {
                merged.optional_apps = local.optional_apps;
            }
            if !local.reviewers.is_empty() {
                merged.reviewers = local.reviewers;
            }
            if !local.nudge_overrides.is_empty() {
                // Without this line a project-local `[review.nudge]` (including
                // `enabled = false`) is read from the GLOBAL file only and the
                // repo's own overrides vanish - loop-check would post a nudge a
                // repo explicitly opted out of. Same per-field-overlay trap the
                // done_probes line below documents.
                merged.nudge_overrides = local.nudge_overrides;
            }
            if !local.peers.is_empty() {
                merged.peers = local.peers;
            }
            if local.peer_identity.is_some() {
                merged.peer_identity = local.peer_identity;
            }
            if local.done_probes.is_some() {
                // Presence, not non-emptiness: a project-local `done_probes = []`
                // is a deliberate "this repo declares none", same rule as
                // required_bots. Omitting this line entirely is the silent
                // guardrail bypass this list keeps re-inviting - the field would
                // be read from the GLOBAL file only and the project's own gate
                // would never run.
                merged.done_probes = local.done_probes;
            }
        }
        merged
    };

    // Resolve the must-have-reviewed list once (code default when unset). The
    // author harness (from the ambient env markers, shared with claims.rs) drives
    // the same-model peer guard (x-c2e7); None leaves the set unchanged.
    let author_harness = crate::claims::resolve_harness();
    let required_bots = resolved_required_bots_for_author(&settings, author_harness.as_deref());
    let mut required_reviewers = settings.reviewers.clone();
    for reviewer in resolved_local_peer_reviewers_for_author(&settings, author_harness.as_deref()) {
        if !required_reviewers.contains(&reviewer) {
            required_reviewers.push(reviewer);
        }
    }
    let optional_bots = resolved_optional_bots(&settings);
    let nudge_configs = resolved_nudge_configs(&settings);

    // Now timestamp
    let now: DateTime<Utc> = if let Some(ref s) = parsed.now_override {
        s.parse().unwrap_or_else(|_| Utc::now())
    } else {
        Utc::now()
    };

    let session_id = manifest
        .session_id
        .clone()
        .unwrap_or_else(|| "unknown".to_string());
    let emit = |event_type: &str, data: serde_json::Value| {
        emit_to_both(&project_events, &global_events, event_type, data);
    };

    // ── Step 1: cancel sentinel ───────────────────────────────────────────────
    if check_cancel_sentinel(&cwd, &manifest.created_at) {
        emit(
            "termination",
            serde_json::json!({
                "session_id": session_id,
                "reason": "Interrupted",
                "message": "cancel sentinel present"
            }),
        );
        return (
            0,
            allow_output(
                "allow",
                Some(TerminationReason::Interrupted),
                "cancel sentinel present; exiting",
                0,
                None,
            ),
        );
    }

    // ── Step 2: legacy terminal status ───────────────────────────────────────
    if let Some(ref status) = manifest.legacy_status {
        emit(
            "loop_check_legacy_manifest",
            serde_json::json!({
                "session_id": session_id,
                "status": status
            }),
        );
        return (
            0,
            allow_output(
                "allow",
                None,
                &format!("legacy manifest status={status}; allowing exit"),
                0,
                None,
            ),
        );
    }

    // ── Step 3: budget check ──────────────────────────────────────────────────
    if let Some(trip) = check_budget(&manifest, &settings, &now, &ledger_path) {
        let axis = match &trip {
            BudgetTrip::WallClock => "wall_clock",
            BudgetTrip::Cost => "cost",
        };
        emit(
            "termination",
            serde_json::json!({
                "session_id": session_id,
                "reason": "Budget",
                "axis": axis,
                "message": format!("budget exceeded (axis={axis})")
            }),
        );
        return (
            0,
            allow_output(
                "allow",
                Some(TerminationReason::Budget),
                &format!("budget exceeded (axis={axis})"),
                0,
                None,
            ),
        );
    }

    let generic = crate::delivery_completion::evaluate_manifest(
        &cwd,
        manifest.plan_path.as_deref(),
        &project_events,
    );
    // ── Check gh binary availability ──────────────────────────────────────────
    // Probe by attempting to spawn; if the binary doesn't exist at all (NotFound
    // error kind), treat as absent. Exit-code failures from valid gh commands
    // are handled per-read below as transient failures, not absence.
    let gh_bin = &parsed.gh_bin;
    let gh_available = {
        // Use a harmless read-only probe: `gh auth status` exits non-zero when
        // not logged in, but the binary IS present. We only care about
        // NotFound (binary missing from path entirely).
        match Command::new(gh_bin).arg("--version").output() {
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
            Err(_) => false,
            Ok(_) => true, // any exit code: binary exists
        }
    };

    if !gh_available
        && matches!(
            generic,
            crate::delivery_completion::DeliveryCompletion::Inactive
        )
    {
        if !manifest.attended && !manifest.advisory {
            // Unattended + no advisory + no gh -> Interrupted
            emit(
                "termination",
                serde_json::json!({
                    "session_id": session_id,
                    "reason": "Interrupted",
                    "message": "gh binary not found; unattended sessions require gh"
                }),
            );
            return (
                0,
                allow_output(
                    "allow",
                    Some(TerminationReason::Interrupted),
                    "gh binary not found; unattended sessions require gh",
                    0,
                    None,
                ),
            );
        }
        // Attended or declared advisory -> advisory mode (promise + budget only).
        // Budget was already checked above; honor intent here so a promise can
        // terminate an advisory session (AC5-ERR) - gh reads are impossible, so
        // the promise alone is the completion signal.
        emit(
            "loop_advisory_mode",
            serde_json::json!({
                "session_id": session_id,
                "attended": manifest.attended
            }),
        );
        let (advisory_intent, _advisory_intent_source) =
            detect_intent(last_assistant_message.as_deref(), &transcript_path);
        if let Intent::Aborted { ref reason } = advisory_intent {
            emit(
                "termination",
                serde_json::json!({
                    "session_id": session_id,
                    "reason": "Aborted",
                    "message": reason
                }),
            );
            return (
                0,
                allow_output(
                    "allow",
                    Some(TerminationReason::Aborted),
                    "aborted tag detected (advisory mode)",
                    0,
                    None,
                ),
            );
        }
        if advisory_intent == Intent::Promise {
            emit(
                "termination",
                serde_json::json!({
                    "session_id": session_id,
                    "reason": "DoneAdvisory",
                    "message": "promise accepted in advisory mode (gh unavailable)"
                }),
            );
            return (
                0,
                allow_output(
                    "allow",
                    Some(TerminationReason::DoneAdvisory),
                    "promise accepted in advisory mode (gh unavailable)",
                    0,
                    None,
                ),
            );
        }
        return (
            0,
            allow_output(
                "block",
                None,
                "gh binary not found; running in advisory mode (promise + budget only)",
                0,
                None,
            ),
        );
    }

    // ── Step 4: intent + backstop ─────────────────────────────────────────────
    let (intent, intent_source) =
        detect_intent(last_assistant_message.as_deref(), &transcript_path);
    let git_bin = &parsed.git_bin;
    let head_sha = git_head_sha(git_bin, &cwd);

    // Compute fingerprint from a quick PR state read (or "none" if no PR)
    // We do a lightweight fingerprint computation even when intent is None,
    // to check backstop.
    let backstop_n: u64 = if manifest.attended { 5 } else { 3 };

    // Read PR info for fingerprint.
    // On a hard gh failure (spawn error, non-zero exit, unparseable JSON), carry
    // forward the most recent prior fingerprint so the consecutive-unchanged streak
    // continues instead of resetting to "none|none|none" which would mask NoProgress.
    // fp_read_failed is recorded in the event payload for observability.
    let fp_read_result = Command::new(gh_bin)
        .args(["pr", "view", "--json", "state,number,headRefName"])
        .current_dir(&cwd)
        .output();
    let (fp_pr_state, fp_ci, fp_review_ts, fp_read_failed) = match fp_read_result {
        Ok(o) if o.status.success() => {
            let pv: Value = serde_json::from_slice(&o.stdout).unwrap_or(Value::Null);
            let state =
                PrState::from_gh_str(pv.get("state").and_then(|v| v.as_str()).unwrap_or("none"));

            // Get CI
            let ci = match Command::new(gh_bin)
                .args(["pr", "checks", "--json", "name,state,bucket"])
                .current_dir(&cwd)
                .output()
            {
                Ok(co) if co.status.success() => {
                    let cv: Value = serde_json::from_slice(&co.stdout).unwrap_or(Value::Null);
                    compute_ci_conclusion(&cv).unwrap_or(CiConclusion::None)
                }
                _ => CiConclusion::None,
            };

            // Get review ts (skipped for no_external sessions and declared
            // no-review repos, matching the done() Read 3/4 skip)
            let rv_ts = if !manifest.no_external && !required_bots.is_empty() {
                match Command::new(gh_bin)
                    .args(["pr", "view", "--json", "reviews,comments"])
                    .current_dir(&cwd)
                    .output()
                {
                    Ok(ro) if ro.status.success() => {
                        let rv: Value = serde_json::from_slice(&ro.stdout).unwrap_or(Value::Null);
                        compute_review_info(&rv, &required_bots).latest_ts
                    }
                    _ => "none".to_string(),
                }
            } else {
                "none".to_string()
            };

            (state, ci, rv_ts, false)
        }
        // No PR yet: a healthy fire with a "none" fingerprint (world-state,
        // not an outage) - the backstop keeps ticking for a session that
        // never ships a PR.
        Ok(o) if is_no_pr_stderr(&o.stderr) => {
            (PrState::None, CiConclusion::None, "none".to_string(), false)
        }
        // Hard gh failure (spawn error OR non-zero exit): mark as failed; we will
        // carry forward the prior fingerprint after reading the events log.
        _ => (PrState::None, CiConclusion::None, "none".to_string(), true),
    };

    // Build a tentative fingerprint from this fire's gh reads.
    let tentative_fp = generic.delivery_fingerprint(make_fingerprint(
        &head_sha,
        fp_pr_state.as_str(),
        &fp_ci.render(),
        &fp_review_ts,
    ));

    // Read prior fires. We pass the tentative_fp for streak counting; if the gh
    // read failed we'll override the fingerprint with the carried-forward value below.
    let min_fire_gap = min_fire_gap_secs();
    let (prior_fires, consecutive_unchanged, last_recorded_fp, streak_window) = read_prior_fires(
        &project_events,
        &session_id,
        &tentative_fp,
        now,
        min_fire_gap,
    );

    // If the pre-read gh call hard-failed, carry forward the prior fingerprint
    // (so the streak continues) rather than resetting to "none|none|none".
    let fingerprint = if fp_read_failed && !generic.is_active() {
        last_recorded_fp.unwrap_or(tentative_fp)
    } else {
        tentative_fp
    };

    // Recount consecutive streak with the (possibly carried-forward) fingerprint.
    // We already counted against the tentative_fp; if different, recount from the log.
    let (consecutive_unchanged, streak_window) = if fp_read_failed && !generic.is_active() {
        // Re-read the streak against the carried-forward fingerprint.
        let (_, streak, _, window) = read_prior_fires(
            &project_events,
            &session_id,
            &fingerprint,
            now,
            min_fire_gap,
        );
        (streak, window)
    } else {
        (consecutive_unchanged, streak_window)
    };

    let this_fire = prior_fires + 1;
    // consecutive_unchanged counts prior identical fires; adding this fire.
    // US4: a gh-errored fire is itself transparent - the count holds at its
    // prior value instead of advancing (AC4-HP).
    let consecutive_after = if fp_read_failed {
        consecutive_unchanged
    } else {
        consecutive_unchanged + 1
    };

    let backstop_tripped = consecutive_after >= backstop_n;

    // D (ab-223d2dae): probe done() after MUTE_PROBE_N unchanged mute fires
    // instead of waiting out the full backstop streak. A done-but-mute
    // session (all reads pass, no promise as final text) now resolves as a
    // late DonePRGreen in ~2 fires instead of 5/3 - the post-wedge events
    // audit counted 337 backstop fires, i.e. ~1000 no-op confirmation laps.
    // NoProgress still requires the full backstop_n streak (unchanged below),
    // so the grilled-9 backstop semantics are intact; a probed fire whose
    // done() fails simply blocks with the named reason.
    const MUTE_PROBE_N: u64 = 2;

    let node_id = scan_manifest_field(&manifest_content, "graph_node_id").or_else(|| {
        scan_manifest_field(&manifest_content, "target_claim_key")
            .and_then(|k| k.strip_prefix("node:").map(|s| s.to_string()))
    });
    let (open_findings, malformed_findings) = match node_id.as_deref() {
        Some(n) => open_review_findings(&project_events, n),
        None => (Vec::new(), 0),
    };
    if malformed_findings > 0 {
        emit(
            "loop_check_malformed_finding",
            serde_json::json!({
                "session_id": session_id,
                "node": node_id,
                "malformed_lines": malformed_findings
            }),
        );
    }

    // Run done() on active generic delivery, intent, backstop, or mute-probe; malformed findings cannot block.
    if generic.is_active()
        || intent != Intent::None
        || backstop_tripped
        || consecutive_after >= MUTE_PROBE_N
    {
        // Handle aborted first
        if let Intent::Aborted { ref reason } = intent {
            emit(
                "termination",
                serde_json::json!({
                    "session_id": session_id,
                    "reason": "Aborted",
                    "message": reason
                }),
            );
            emit(
                "loop_check",
                serde_json::json!({
                    "session_id": session_id,
                    "fingerprint": fingerprint,
                    "fires": this_fire,
                    "consecutive_unchanged": consecutive_after,
                    "streak_window_secs": streak_window,
                    "decision": "allow",
                    "intent": "aborted",
                    "intent_source": intent_source,
                    "pr_state": fp_pr_state.as_str(),
                    "ci": fp_ci.render(),
                    "reviewed": false,
                    "fp_read_failed": fp_read_failed
                }),
            );
            return (
                0,
                allow_output(
                    "allow",
                    Some(TerminationReason::Aborted),
                    "aborted tag detected",
                    this_fire,
                    Some(fingerprint),
                ),
            );
        }

        // Operator review-finding gate (x-f8d4, Locked Decision 3): an open
        // review_finding for this node HOLDS every success terminal-allow
        // (DonePlanned / DoneAdvisory / DoneDelivery / DoneBatched / DonePRGreen) until an
        // explicit resolve - a promise cannot self-authorize past an operator's
        // open comment. Placed AFTER the Aborted arm and gated on
        // `!backstop_tripped` so the anti-wedge safety valves still win: an
        // Aborted tag exits, and once the NoProgress backstop streak is reached
        // the session gives up rather than looping forever on an unresolved
        // finding. Fires on a promise OR a mute-probe (the paths that would
        // otherwise terminate-allow), never on an ordinary working fire.
        if !open_findings.is_empty()
            && !backstop_tripped
            && (intent == Intent::Promise || consecutive_after >= MUTE_PROBE_N)
        {
            let reason = build_findings_block_reason(&open_findings, malformed_findings);
            emit(
                "loop_check",
                serde_json::json!({
                    "session_id": session_id,
                    "fingerprint": fingerprint,
                    "fires": this_fire,
                    "consecutive_unchanged": consecutive_after,
                    "streak_window_secs": streak_window,
                    "decision": "block",
                    "intent": if intent == Intent::Promise { "promise" } else { "backstop" },
                    "intent_source": intent_source,
                    "pr_state": fp_pr_state.as_str(),
                    "ci": fp_ci.render(),
                    "reviewed": false,
                    "open_findings": open_findings.iter().map(|f| f.id.as_str()).collect::<Vec<_>>(),
                    "malformed_findings": malformed_findings,
                    "fp_read_failed": fp_read_failed
                }),
            );
            return (
                0,
                allow_output("block", None, &reason, this_fire, Some(fingerprint)),
            );
        }

        if let Some(output) = crate::delivery_completion::gate_output(
            &generic,
            intent == Intent::Promise,
            &project_events,
            &global_events,
            &session_id,
            manifest.session_id.as_deref(),
            node_id.as_deref(),
            intent_source,
            &fingerprint,
            this_fire,
            backstop_tripped,
            consecutive_after,
            streak_window,
            fp_pr_state.as_str(),
            &fp_ci.render(),
        ) {
            return (0, output);
        }

        // Plan-only unit: a plan-only thread reached the plan boundary. Checked
        // BEFORE the advisory unit because DoneAdvisory is a ship reason (it
        // graduates the plan) and a plan-only thread must not graduate its own
        // plan. DonePlanned is benign: not a ship reason, not a postmortem.
        if manifest.planned && intent == Intent::Promise {
            emit(
                "termination",
                serde_json::json!({
                    "session_id": session_id,
                    "reason": "DonePlanned",
                    "message": "promise in plan-only unit"
                }),
            );
            emit(
                "loop_check",
                serde_json::json!({
                    "session_id": session_id,
                    "fingerprint": fingerprint,
                    "fires": this_fire,
                    "consecutive_unchanged": consecutive_after,
                    "streak_window_secs": streak_window,
                    "decision": "allow",
                    "intent": "promise",
                    "intent_source": intent_source,
                    "pr_state": fp_pr_state.as_str(),
                    "ci": fp_ci.render(),
                    "reviewed": true,
                    "fp_read_failed": fp_read_failed
                }),
            );
            return (
                0,
                allow_output(
                    "allow",
                    Some(TerminationReason::DonePlanned),
                    "promise + plan-only unit; done",
                    this_fire,
                    Some(fingerprint),
                ),
            );
        }

        // Advisory unit (no_ship or manifest advisory)
        if (manifest.no_ship || manifest.advisory) && intent == Intent::Promise {
            emit(
                "termination",
                serde_json::json!({
                    "session_id": session_id,
                    "reason": "DoneAdvisory",
                    "message": "promise in advisory/no_ship unit"
                }),
            );
            emit(
                "loop_check",
                serde_json::json!({
                    "session_id": session_id,
                    "fingerprint": fingerprint,
                    "fires": this_fire,
                    "consecutive_unchanged": consecutive_after,
                    "streak_window_secs": streak_window,
                    "decision": "allow",
                    "intent": "promise",
                    "intent_source": intent_source,
                    "pr_state": fp_pr_state.as_str(),
                    "ci": fp_ci.render(),
                    "reviewed": true,
                    "fp_read_failed": fp_read_failed
                }),
            );
            return (
                0,
                allow_output(
                    "allow",
                    Some(TerminationReason::DoneAdvisory),
                    "promise + advisory unit; done",
                    this_fire,
                    Some(fingerprint),
                ),
            );
        }

        // Batched unit (batch-lane Wave 2/3): the node's commits live on a
        // shared batch branch and ship via the batch PR, not its own, so
        // run_done() below would block forever waiting for a per-node PR that
        // never comes. The daemon set `batched: true` at dispatch; a promise
        // here means the member finished committing to the shared branch.
        // Terminal as DoneBatched - deliberately NOT a ship reason, so finalize
        // records the ledger entry but does NOT stamp/graduate the plan (the
        // batch's own `/pr create` graduates it once, for all members). Comes
        // AFTER the advisory arm (a batched unit is not advisory: it sets
        // neither no_ship nor advisory) and BEFORE run_done so no PR is polled.
        if manifest.batched && intent == Intent::Promise {
            emit(
                "termination",
                serde_json::json!({
                    "session_id": session_id,
                    "reason": "DoneBatched",
                    "message": "promise in batched unit; commit landed on shared branch"
                }),
            );
            emit(
                "loop_check",
                serde_json::json!({
                    "session_id": session_id,
                    "fingerprint": fingerprint,
                    "fires": this_fire,
                    "consecutive_unchanged": consecutive_after,
                    "streak_window_secs": streak_window,
                    "decision": "allow",
                    "intent": "promise",
                    "intent_source": intent_source,
                    "pr_state": fp_pr_state.as_str(),
                    "ci": fp_ci.render(),
                    "reviewed": true,
                    "fp_read_failed": fp_read_failed
                }),
            );
            return (
                0,
                allow_output(
                    "allow",
                    Some(TerminationReason::DoneBatched),
                    "promise + batched unit; commit on shared branch, batch PR ships it",
                    this_fire,
                    Some(fingerprint),
                ),
            );
        }

        // Run done() for code units
        let done_result = run_done(
            gh_bin,
            &cwd,
            settings.ci_declared_none,
            manifest.no_external,
            &required_bots,
            &optional_bots,
            &settings.external_reviewers,
            &required_reviewers,
            &nudge_configs,
            &head_sha,
            &project_events,
        );

        match done_result {
            Ok(mut pr_info) => {
                // Read 4's newest activity timestamp folds into the
                // fingerprint's 4th component: a late inline finding advances
                // the fingerprint (re-block, not NoProgress - the codex
                // findings-minutes-after-summary shape). State/CI components
                // stay on the pre-read basis so quiet fires stay comparable.
                // Skipped entirely when the pre-read failed: its stale
                // none|none components would leak into done_fp and manufacture
                // a fingerprint change on a fire US4 declares transparent
                // (sigma-review finding on this branch).
                let (fingerprint, consecutive_after, streak_window) = if !fp_read_failed {
                    let done_fp = make_fingerprint(
                        &head_sha,
                        fp_pr_state.as_str(),
                        &fp_ci.render(),
                        &max_ts(&fp_review_ts, &pr_info.latest_review_ts),
                    );
                    if done_fp != fingerprint {
                        let (_, streak, _, window) = read_prior_fires(
                            &project_events,
                            &session_id,
                            &done_fp,
                            now,
                            min_fire_gap,
                        );
                        (done_fp, streak + 1, window)
                    } else {
                        (fingerprint, consecutive_after, streak_window)
                    }
                } else {
                    (fingerprint, consecutive_after, streak_window)
                };
                let backstop_tripped = consecutive_after >= backstop_n;

                // x-b167 section 5: post the trigger for any NeedsNudge bot ONCE,
                // then treat it as Awaiting for this fire's messaging + idle read.
                // A NeedsNudge state means !reviewed, so no terminal below can
                // fire (they require reviewed=true); posting here is safe. A
                // failed post keeps NeedsNudge so the block message tells the
                // agent to post by hand (AC11) and the count is unchanged - a
                // failed post is never counted as a nudge.
                let nudge_pr_number = pr_info.number;
                for n in pr_info.bot_nudges.iter_mut() {
                    if n.class != NudgeClass::NeedsNudge {
                        continue;
                    }
                    if post_nudge_comment(gh_bin, &cwd, nudge_pr_number, &n.review_handle) {
                        emit(
                            "loop_check_nudge_posted",
                            serde_json::json!({
                                "session_id": session_id,
                                "pr": nudge_pr_number,
                                "bot": n.login,
                                "handle": n.review_handle,
                                "nudge": n.nudges + 1,
                                "ceiling": n.ceiling
                            }),
                        );
                        n.nudges += 1;
                        n.newest_age_min = 0;
                        n.class = NudgeClass::Awaiting;
                    } else {
                        emit(
                            "loop_check_nudge_post_failed",
                            serde_json::json!({
                                "session_id": session_id,
                                "pr": nudge_pr_number,
                                "bot": n.login,
                                "handle": n.review_handle
                            }),
                        );
                    }
                }

                let ci_ok = pr_info.ci_conclusion.is_ok();
                let pr_open = pr_info.state.is_open_or_merged();
                // codex P1 on #447: a green PR must also contain the local
                // HEAD - otherwise unpushed work terminates as DonePRGreen
                // without ever shipping. MERGED PRs are exempt only when the
                // local HEAD matches too; an unpushed commit on top of a
                // merged PR is still unshipped work.
                let head_shipped = !pr_info.head_oid.is_empty() && pr_info.head_oid == head_sha;

                // done_probes: the FINAL DonePRGreen conjunct. Gated on
                // every other conjunct already holding, so a plan with no probes
                // spawns no subprocess and a red/unreviewed PR never pays for one.
                let (mut probe_block, mut probe_results) = (None, Value::Null);
                if pr_open && ci_ok && pr_info.reviewed && head_shipped {
                    match evaluate_done_probes(
                        manifest.plan_path.as_deref(),
                        settings.done_probes.as_ref(),
                        &cwd,
                        &project_events,
                        &session_id,
                        PROBE_TIMEOUT,
                    ) {
                        ProbeGate::Absent => {}
                        ProbeGate::Pass(results) => probe_results = results,
                        ProbeGate::Fail { reason, results } => {
                            probe_block = Some(reason);
                            probe_results = results;
                        }
                    }
                }

                let (reviewed, probes_passed) = (pr_info.reviewed, probe_block.is_none());
                if pr_passes(pr_open, ci_ok, reviewed, head_shipped, probes_passed) {
                    // AC1-UI: name any rate-limited bot the gate proceeded
                    // without, so the terminal message and the emitted event
                    // agree on why a required bot is absent from the evidence.
                    let done_msg = if pr_info.usage_limited.is_empty() {
                        format!("PR #{} is green and reviewed", pr_info.number)
                    } else {
                        format!(
                            "PR #{} is green and reviewed (rate-limited, dropped from gate: {})",
                            pr_info.number,
                            pr_info.usage_limited.join(", ")
                        )
                    };
                    emit(
                        "termination",
                        serde_json::json!({
                            "session_id": session_id,
                            "reason": "DonePRGreen",
                            "message": done_msg.clone()
                        }),
                    );
                    emit(
                        "loop_check",
                        serde_json::json!({
                            "session_id": session_id,
                            "fingerprint": fingerprint,
                            "fires": this_fire,
                            "consecutive_unchanged": consecutive_after,
                            "streak_window_secs": streak_window,
                            "decision": "allow",
                            "intent": if intent == Intent::Promise { "promise" } else { "backstop" },
                            "intent_source": intent_source,
                            "pr_state": pr_info.state.as_str(),
                            "ci": pr_info.ci_conclusion.render(),
                            "reviewed": pr_info.reviewed,
                            "review_skipped": pr_info.review_skipped,
                            "unaddressed_blocking": pr_info.unaddressed_findings.len(),
                            "fp_read_failed": fp_read_failed,
                            "done_probes": probe_results
                        }),
                    );
                    return (
                        0,
                        allow_output(
                            "allow",
                            Some(TerminationReason::DonePRGreen),
                            &done_msg,
                            this_fire,
                            Some(fingerprint),
                        ),
                    );
                }

                // DoneAwaitingMerge: done() failed SOLELY on CI-green
                // (PR open, reviewed, HEAD shipped, but CI red). Reached only
                // when !ci_ok because the DonePRGreen arm above returned - so
                // DonePRGreen precedence holds, and a merge that flipped the PR
                // green would have been caught by the fresh run_done this fire
                // (AC1-FR). If current main HEAD is red on the SAME checks
                // (strict subset, check-name granularity), a bg agent cannot
                // merge past it: terminate clean with a one-shot notify instead
                // of burning to NoProgress. Any PR-unique red or any gh
                // uncertainty falls through to the hold below (fail closed).
                //
                // `!pr_info.ci_has_pending` is load-bearing: ci_conclusion
                // reports Failure as soon as ONE check fails while others still
                // run, so without this guard the terminal could fire on a
                // partial-CI fire where the session's OWN new job is still
                // pending and about to turn red. The terminal must see fully
                // settled-red CI, never partial.
                //
                // `mergeable != "CONFLICTING"` guards a reviewed PR whose branch
                // conflicts with main: the human cannot merge past main-red until
                // it is rebased, so terminating here would drop the node from
                // retry circulation while it is un-mergeable. UNKNOWN (still
                // computing) is allowed - it clears on its own.
                if pr_open
                    && pr_info.reviewed
                    && head_shipped
                    && !ci_ok
                    && !pr_info.ci_has_pending
                    && pr_info.mergeable != "CONFLICTING"
                {
                    if let Some(main_failing) =
                        main_head_failing_checks(gh_bin, &cwd, MAIN_RUN_LOOKBACK)
                    {
                        if is_pre_existing_main_red(&pr_info.failing_checks, &main_failing) {
                            let proof = format!(
                                "same checks red on main (last {} completed runs): {}",
                                MAIN_RUN_LOOKBACK,
                                pr_info.failing_checks.join(", ")
                            );
                            let msg = format!(
                                "PR #{} complete and reviewed; awaiting merge past pre-existing main-red ({proof})",
                                pr_info.number
                            );
                            // Idempotency (Concurrency AC): emit + notify at most
                            // once per session; a re-eval or the two consumers
                            // racing still returns the terminal but does not
                            // double-notify.
                            if !already_emitted_awaiting_merge(&project_events, &session_id) {
                                emit(
                                    "termination",
                                    serde_json::json!({
                                        "session_id": session_id,
                                        "reason": "DoneAwaitingMerge",
                                        "message": msg.clone()
                                    }),
                                );
                                emit(
                                    "loop_check",
                                    serde_json::json!({
                                        "session_id": session_id,
                                        "fingerprint": fingerprint,
                                        "fires": this_fire,
                                        "consecutive_unchanged": consecutive_after,
                                        "streak_window_secs": streak_window,
                                        "decision": "allow",
                                        "intent": if intent == Intent::Promise { "promise" } else { "backstop" },
                                        "intent_source": intent_source,
                                        "pr_state": pr_info.state.as_str(),
                                        "ci": pr_info.ci_conclusion.render(),
                                        "reviewed": pr_info.reviewed,
                                        "review_skipped": pr_info.review_skipped,
                                        "unaddressed_blocking": pr_info.unaddressed_findings.len(),
                                        "fp_read_failed": fp_read_failed
                                    }),
                                );
                                best_effort_notify(
                                    &format!(
                                        "PR #{} ready - merge past pre-existing main-red",
                                        pr_info.number
                                    ),
                                    &msg,
                                );
                            }
                            return (
                                0,
                                allow_output(
                                    "allow",
                                    Some(TerminationReason::DoneAwaitingMerge),
                                    &msg,
                                    this_fire,
                                    Some(fingerprint),
                                ),
                            );
                        }
                    }
                }

                // ── Watching idle-allow (x-e2c8) ─────────────────────────────
                // A verified async wait (CI pending or awaiting a bot review,
                // head pushed, zero unaddressed findings) plus an agent-armed
                // <watching> tag idles NON-terminally: the harness re-invokes the
                // model when the agent's watcher task exits, so re-blocking every
                // ~90s tick until then is pure no-op overhead. done() and every
                // terminal above already ran (a terminal always beats an idle),
                // and this sits BEFORE the NoProgress backstop so a long watched
                // wait degrades to budget/claim-expiry, never a spurious kill.
                if let Intent::Watching {
                    ref reason,
                    ref timeout,
                    ..
                } = intent
                {
                    // Harness + substrate gate: only a Claude session self-wakes
                    // on a background-task exit, and a `fno-agents loop run` child
                    // (FNO_DRIVER_LIB, the same discriminator terminal_stop.rs
                    // uses) exits on allow. codex/gemini keep today's block
                    // behavior until their daemon-consumer waker ships (AC1-EDGE).
                    let blocker = if harness_can_idle(
                        author_harness.as_deref(),
                        std::env::var("FNO_DRIVER_LIB").is_ok(),
                    ) {
                        async_wait_class(&pr_info, &head_sha, open_findings.is_empty())
                    } else {
                        None
                    };
                    if let Some(blocker) = blocker {
                        // Extend the node claim to cover the watch window BEFORE
                        // idling, or the idle opens a dispatcher-stampede gap.
                        // Renewal MUST pass an explicit --ttl (a default refresh
                        // shrinks the lease to 1min) and MUST return Ok(true)
                        // (holder match); anything else blocks (AC3-ERR).
                        let window_ms = watch_window_ms(timeout.as_deref());
                        let renewed = match (
                            scan_manifest_field(&manifest_content, "target_claim_key"),
                            scan_manifest_field(&manifest_content, "target_claim_holder"),
                        ) {
                            (Some(key), Some(holder)) => matches!(
                                crate::claims::renew(&key, &holder, window_ms, None),
                                Ok(true)
                            ),
                            _ => false,
                        };
                        if renewed {
                            emit(
                                "loop_check_watch_idle",
                                serde_json::json!({
                                    "session_id": session_id,
                                    "pr": pr_info.number,
                                    "blocker": blocker,
                                    "declared_timeout": timeout.clone().unwrap_or_default(),
                                    "reason": reason,
                                    "lease_ms": window_ms
                                }),
                            );
                            emit(
                                "loop_check",
                                serde_json::json!({
                                    "session_id": session_id,
                                    "fingerprint": fingerprint,
                                    "fires": this_fire,
                                    "consecutive_unchanged": consecutive_after,
                                    "streak_window_secs": streak_window,
                                    "decision": "allow",
                                    "intent": "watching",
                                    "intent_source": intent_source,
                                    "pr_state": pr_info.state.as_str(),
                                    "ci": pr_info.ci_conclusion.render(),
                                    "reviewed": pr_info.reviewed,
                                    "review_skipped": pr_info.review_skipped,
                                    "fp_read_failed": fp_read_failed
                                }),
                            );
                            let msg = format!(
                                "watching: idling until watcher fires (PR #{}, {blocker} pending)",
                                pr_info.number
                            );
                            return (
                                0,
                                allow_output("allow", None, &msg, this_fire, Some(fingerprint)),
                            );
                        }
                        // renewal failed / holder mismatch -> fall through to the
                        // block below (AC3-ERR): never idle without a lease.
                    }
                    // not async-wait class, or a loop-run child -> fall through:
                    // build_block_reason names the real blocker (AC1-ERR CI red,
                    // AC2-ERR head mismatch / finding).
                }

                // x-b167: a freshly-posted nudge sits in Awaiting until
                // wait_minutes elapses. On a harness that cannot idle on a
                // `<watching>` tag (a loop-run child, codex/gemini, or a failed
                // lease renewal) the fingerprint is stable, so without this guard
                // the generic backstop reaps the wait after backstop_n fires -
                // before the nudge cycle reaches its ceiling, terminating with a
                // generic NoProgress instead of the named give-up. Suppress the
                // backstop ONLY when the sole unmet condition is a live Awaiting
                // nudge: it is self-limiting (Awaiting -> Unresponsive after
                // wait_minutes, when this guard clears and the backstop reaps it
                // naming the bot), and the narrow scope keeps CI red, a finding,
                // an unattested reviewer, or a failed probe tripping it as before.
                let sole_blocker_is_awaiting = pr_open
                    && ci_ok
                    && probe_block.is_none()
                    && !pr_info.reviewed
                    && pr_info.unattested_reviewers.is_empty()
                    && pr_info.unaddressed_findings.is_empty()
                    && pr_info
                        .bot_nudges
                        .iter()
                        .any(|n| n.class == NudgeClass::Awaiting);
                // `probe_block.is_some()` keeps a probe that can never pass in
                // this environment on the NoProgress escape rather than looping
                // to the budget ceiling: PR+CI+review all hold, so without it
                // none of the other disjuncts can ever fire.
                if backstop_tripped
                    && (!pr_open || !ci_ok || !pr_info.reviewed || probe_block.is_some())
                    && !sole_blocker_is_awaiting
                {
                    // Backstop tripped + done() false -> NoProgress. x-b167 AC13:
                    // when a nudged bot never answered, the operator's question is
                    // "is this going to finish, and must I do something" - so name
                    // the bot + nudge count + elapsed instead of a bare fingerprint
                    // streak, and reach the operator (who is not watching the pane)
                    // with exactly one notification.
                    let nudge_giveup = unresponsive_bot(&pr_info);
                    let noprogress_msg = match nudge_giveup {
                        Some(n) => nudge_giveup_message(n),
                        None => format!(
                            "fingerprint unchanged for {} consecutive fires over {}m; PR not done",
                            consecutive_after,
                            streak_window / 60
                        ),
                    };
                    if let Some(n) = nudge_giveup {
                        best_effort_notify(
                            "target: bot review gave up",
                            &format!(
                                "PR #{}: {} did not review after {} nudges over {}m",
                                pr_info.number, n.login, n.nudges, n.span_min
                            ),
                        );
                    }
                    // Backstop tripped + done() false -> NoProgress
                    emit(
                        "termination",
                        serde_json::json!({
                            "session_id": session_id,
                            "reason": "NoProgress",
                            "message": noprogress_msg
                        }),
                    );
                    emit(
                        "loop_check",
                        serde_json::json!({
                            "session_id": session_id,
                            "fingerprint": fingerprint,
                            "fires": this_fire,
                            "consecutive_unchanged": consecutive_after,
                            "streak_window_secs": streak_window,
                            "decision": "allow",
                            "intent": "backstop",
                            "intent_source": intent_source,
                            "pr_state": pr_info.state.as_str(),
                            "ci": pr_info.ci_conclusion.render(),
                            "reviewed": pr_info.reviewed,
                            "review_skipped": pr_info.review_skipped,
                            "unaddressed_blocking": pr_info.unaddressed_findings.len(),
                            "fp_read_failed": fp_read_failed,
                            "done_probes": probe_results
                        }),
                    );
                    let return_msg = match nudge_giveup {
                        Some(_) => noprogress_msg.clone(),
                        None => format!(
                            "fingerprint unchanged for {} fires over {}m; HEAD={}, PR={}, CI={}, reviewed={}",
                            consecutive_after,
                            streak_window / 60,
                            short_sha(&head_sha),
                            pr_info.state.as_str(),
                            pr_info.ci_conclusion.render(),
                            pr_info.reviewed
                        ),
                    };
                    return (
                        0,
                        allow_output(
                            "allow",
                            Some(TerminationReason::NoProgress),
                            &return_msg,
                            this_fire,
                            Some(fingerprint),
                        ),
                    );
                }

                // done() false on promise -> block with named reason. P2
                // (ab-098967b4): enrich with a loop-boundary inbox nudge.
                // A failed probe IS the blocker when everything else is green;
                // build_block_reason would otherwise report a healthy PR.
                let reason = crate::nudge::append_inbox_nudge(
                    &probe_block.clone().unwrap_or_else(|| {
                        build_block_reason(&pr_info, &head_sha, open_findings.is_empty())
                    }),
                    &cwd,
                    &session_id,
                );
                emit(
                    "loop_check",
                    serde_json::json!({
                        "session_id": session_id,
                        "fingerprint": fingerprint,
                        "fires": this_fire,
                        "consecutive_unchanged": consecutive_after,
                        "streak_window_secs": streak_window,
                        "decision": "block",
                        "intent": if intent == Intent::Promise { "promise" } else { "none" },
                        "intent_source": intent_source,
                        "pr_state": pr_info.state.as_str(),
                        "ci": pr_info.ci_conclusion.render(),
                        "reviewed": pr_info.reviewed,
                        "review_skipped": pr_info.review_skipped,
                        "unaddressed_blocking": pr_info.unaddressed_findings.len(),
                        "fp_read_failed": fp_read_failed,
                        "done_probes": probe_results
                    }),
                );
                return (
                    0,
                    allow_output("block", None, &reason, this_fire, Some(fingerprint)),
                );
            }
            Err((failed_read, failed_stderr)) => {
                // US4 (locked decision 6, REVERSES the wedge's behavior): a
                // gh-errored done() read NEVER terminates NoProgress, even
                // with the backstop tripped - a healthy session must not be
                // killed because GitHub blipped. The fire blocks-and-retries
                // and is recorded fp_read_failed=true, keeping it transparent
                // to the streak. Budget remains the sole ceiling during a
                // sustained outage (AC4-EDGE; budget is checked before any
                // gh read, so the outage never makes a session immortal).
                emit(
                    "loop_check_gh_error",
                    serde_json::json!({
                        "session_id": session_id,
                        "read": failed_read,
                        "stderr_tail": failed_stderr
                    }),
                );
                emit(
                    "loop_check",
                    serde_json::json!({
                        "session_id": session_id,
                        "fingerprint": fingerprint,
                        "fires": this_fire,
                        "consecutive_unchanged": consecutive_after,
                        "streak_window_secs": streak_window,
                        "decision": "block",
                        "intent": if intent == Intent::Promise { "promise" } else { "none" },
                        "intent_source": intent_source,
                        "pr_state": "unknown",
                        "ci": "unknown",
                        "reviewed": false,
                        "fp_read_failed": true
                    }),
                );
                return (
                    0,
                    allow_output(
                        "block",
                        None,
                        &format!("gh read '{failed_read}' failed; retrying next fire"),
                        this_fire,
                        Some(fingerprint),
                    ),
                );
            }
        }
    }

    // ── Step 5: no intent, no backstop -> block, record fingerprint ───────────
    emit(
        "loop_check",
        serde_json::json!({
            "session_id": session_id,
            "fingerprint": fingerprint,
            "fires": this_fire,
            "consecutive_unchanged": consecutive_after,
            "streak_window_secs": streak_window,
            "decision": "block",
            "intent": "none",
            "intent_source": intent_source,
            "pr_state": fp_pr_state.as_str(),
            "ci": fp_ci.render(),
            "reviewed": false,
            "fp_read_failed": fp_read_failed
        }),
    );

    // P2 (ab-098967b4): the dominant loop-yield boundary. Enrich the continue
    // message with a one-line inbox nudge so an autonomous loop surfaces mail.
    let continue_msg = crate::nudge::append_inbox_nudge(
        "continue working; no completion signal. If you are only waiting on an async check (CI/review) with nothing to do, arm a harness-tracked watcher with a hard timeout (e.g. background Bash `gh pr checks <N> --watch & w=$!; (sleep 1800; kill $w 2>/dev/null) & wait $w`) and end your turn with `<watching reason=\"ci|review\" pr=\"<N>\" timeout=\"30m\">` - the session idles until the watcher exits instead of re-waking every tick.",
        &cwd,
        &session_id,
    );
    (
        0,
        allow_output("block", None, &continue_msg, this_fire, Some(fingerprint)),
    )
}

#[allow(clippy::too_many_arguments)]
fn run_done(
    gh_bin: &str,
    cwd: &Path,
    ci_declared_none: bool,
    no_external: bool,
    required_bots: &[String],
    optional_bots: &[String],
    external_reviewers: &[String],
    reviewers: &[String],
    nudge_configs: &[NudgeConfig],
    head_sha: &str,
    events_path: &Path,
) -> Result<PrInfo, (String, String)> {
    read_pr_info(
        gh_bin,
        cwd,
        ci_declared_none,
        no_external,
        required_bots,
        optional_bots,
        external_reviewers,
        reviewers,
        nudge_configs,
        head_sha,
        events_path,
    )
}

/// Slack added beyond the declared watch window so the claim lease outlives the
/// agent's watcher (x-e2c8): a watcher that fires right at its timeout must not
/// race claim expiry.
const WATCH_SLACK_MS: i64 = 12 * 60_000;

/// Lease window for an idle watch: the declared timeout clamped to [5m, 2h]
/// (never trust the tag for an unbounded hold) plus slack. Defaults to 30m when
/// the tag omits or mangles `timeout`, giving the ~40m default lease.
fn watch_window_ms(timeout: Option<&str>) -> i64 {
    let declared = timeout
        .and_then(crate::claims::parse_ttl_ms)
        .unwrap_or(30 * 60_000);
    declared.clamp(5 * 60_000, 2 * 3_600_000) + WATCH_SLACK_MS
}

/// Whether a session's harness + substrate can park-and-wake on a `<watching>`
/// idle (x-e2c8). Only a Claude session's harness-tracked background/Monitor
/// tasks re-invoke the model when they exit, so only Claude may idle. A
/// `fno-agents loop run` child exits on allow (FNO_DRIVER_LIB set), and
/// codex/gemini have no self-wake on background-task exit - their waker is the
/// fno-agents daemon consuming the watch event, shipped as a separate
/// live-verified follow-up - so all of those keep today's block behavior rather
/// than idling with nothing to wake them (a dead watch). This is the design's
/// "unroutable harness -> status quo, never a dead watch" degradation.
fn harness_can_idle(author_harness: Option<&str>, is_loop_run_child: bool) -> bool {
    author_harness == Some("claude") && !is_loop_run_child
}

/// Whether the PR is in the async-wait class a `<watching>` tag may idle on
/// (x-e2c8): PR open, local HEAD pushed, no unaddressed findings (inline OR
/// operator), and the sole remaining blocker is CI still pending or an
/// outstanding bot review. Returns the blocker label, or None if anything else
/// blocks. External truth only - the tag is a request, this is the authority.
fn async_wait_class(
    pr: &PrInfo,
    local_head: &str,
    open_findings_empty: bool,
) -> Option<&'static str> {
    let head_shipped = !pr.head_oid.is_empty() && pr.head_oid == local_head;
    if pr.state != PrState::Open
        || !head_shipped
        || !pr.unaddressed_findings.is_empty()
        || !open_findings_empty
    {
        return None;
    }
    // CI still pending AND nothing has concluded red yet: idle on CI. If a
    // check has ALREADY failed while others run, do NOT idle - the agent should
    // start debugging the failure now rather than wait out the rest (gemini).
    if pr.ci_has_pending && !matches!(pr.ci_conclusion, CiConclusion::Failure(_)) {
        return Some("ci");
    }
    // Awaiting an EXTERNAL bot review: a real GitHub login WILL post it, so
    // idling until it does is correct. `reviewed == false` with an EMPTY
    // missing_bots is instead a LOCAL-attestation gate (config.review.reviewers,
    // e.g. sigma) or an unaddressed finding - work the agent must DO, and no
    // GitHub reviewer will ever appear to wake it, so idling would park the
    // session forever. Require an outstanding bot (codex P1).
    //
    // An outstanding LOCAL reviewer disqualifies the wait even when a bot is
    // also outstanding (codex review of x-cdc7): the session has work it can do
    // right now, and if the bot never posts, idling means that work never
    // happens and the run dies on budget with the gate still unmet.
    //
    // x-b167: idle ONLY when every missing bot is in an idlable nudge state
    // (Awaiting, a genuine async wait; or NotNudgeable, today's status quo). A
    // NeedsNudge bot is work to DO (post its trigger) and an Unresponsive bot is
    // a wait nobody ends - idling on either parks the session. This is the same
    // rule x-cdc7 gave unattested_reviewers. An empty bot_nudges (not classified)
    // means every-bot-idlable vacuously, preserving pre-x-b167 behavior.
    if pr.ci_conclusion.is_ok()
        && !pr.reviewed
        && !pr.review_skipped
        && !pr.missing_bots.is_empty()
        && pr.unattested_reviewers.is_empty()
        && pr.bot_nudges.iter().all(|n| nudge_class_idlable(&n.class))
    {
        return Some("review");
    }
    None
}

/// First 8 chars of a sha, never bytes. `&s[..8]` panics when byte offset 8
/// lands inside a multibyte character, and one of these strings comes from a
/// user-writable events.jsonl - a panic there takes the whole stop gate down.
fn short_sha(s: &str) -> String {
    s.chars().take(8).collect()
}

/// The arm-and-tag ritual (x-e2c8, US3) that converts an unwatched async wait
/// into a single idle turn. Supersedes the old "wait silently" prose: waiting
/// silently still costs a full model invocation every ~90s tick, whereas arming
/// a harness-tracked watcher and emitting `<watching>` idles the session to ZERO
/// invocations until the watcher fires. The `gh pr checks` shape is a template
/// (gh's `--watch` exit varies by version); the design depends only on the task
/// EXITING, never on its exit code.
///
/// The bound uses shell builtins, never `timeout(1)`: stock macOS has neither
/// it nor `gtimeout`, so naming it makes the watcher no-op and the session idle
/// forever on a wait that never started. The watchdog is reaped once the wait
/// returns - left alive, it wakes 30m later and kills whatever now holds that
/// recycled pid (codex P1).
fn arm_watch_hint(pr_number: i64, blocker: &str) -> String {
    // The watcher must WAIT on the actual blocker. `gh pr checks --watch` exits
    // the instant CI has no pending checks, so on a review wait (CI already
    // green) it returns immediately and the session just re-blocks - the review
    // path needs a watcher that polls REVIEW state, not checks (codex P2).
    let watcher = if blocker == "review" {
        format!(
            "background Bash `n=$(gh pr view {pr_number} --json reviews --jq '.reviews|length'); i=0; while [ $i -lt 30 ]; do sleep 60; [ \"$(gh pr view {pr_number} --json reviews --jq '.reviews|length')\" -gt \"$n\" ] && break; i=$((i+1)); done` (wakes when a new review posts, or after ~30m)"
        )
    } else {
        format!(
            "background Bash `gh pr checks {pr_number} --watch & w=$!; (sleep 1800; kill $w 2>/dev/null) & k=$!; wait $w; kill $k 2>/dev/null`"
        )
    };
    format!(
        " Arm a harness-tracked watcher with a hard timeout (e.g. {watcher}), then end your turn with `<watching reason=\"{blocker}\" pr=\"{pr_number}\" timeout=\"30m\">` and nothing else - the session then idles until the watcher exits."
    )
}

// ── done_probes ──────────────────────────────────────────────────────
//
// A plan may declare `done_probes` in its frontmatter: runnable commands whose
// success is the operational evidence that the shipped thing actually RUNS.
// DonePRGreen measures artifacts (PR + CI + review), which operational silence
// cannot falsify - grooming shipped three times without ever running. Probes are
// the enforcement arm: the gate refuses done until the declared observation
// holds, forcing the session to perform the last mile before claiming done.

/// Wall-clock ceiling per probe. The host has no `timeout` binary (and no
/// gtimeout), so the bound is native: spawn, poll `try_wait`, kill.
const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);

/// A probe list is a gate, not a test suite.
const PROBE_CAP: usize = 3;

/// Probe stderr is quoted back in the block reason so the agent knows which
/// last-mile action to perform; cap it so the reason stays readable.
const PROBE_STDERR_CAP: usize = 500;

enum ProbeOutcome {
    Pass,
    Fail { code: Option<i32>, stderr: String },
    Timeout,
}

impl ProbeOutcome {
    /// Event rendering: `pass` | `fail:<code>` | `timeout`.
    fn render(&self) -> String {
        match self {
            ProbeOutcome::Pass => "pass".to_string(),
            ProbeOutcome::Fail { code: Some(c), .. } => format!("fail:{c}"),
            ProbeOutcome::Fail { code: None, .. } => "fail:signal".to_string(),
            ProbeOutcome::Timeout => "timeout".to_string(),
        }
    }
}

enum ProbeGate {
    /// No declaration: zero subprocesses, gate behavior byte-identical to before.
    Absent,
    Pass(Value),
    Fail {
        reason: String,
        results: Value,
    },
}

/// Unwrap a YAML scalar to the string a YAML parser would produce.
///
/// Decoding escapes is not cosmetic: the recommended block form routinely
/// carries an inner quote (`- "test -n \"$(cmd)\""`). Leaving the backslashes in
/// would hand `sh -c` literal `\"` characters - a DIFFERENT command than the
/// plan declared, whose result the gate would then trust - and would also key
/// the event by a string the PyYAML-side grader never matches.
fn unquote_scalar(s: &str) -> String {
    let s = s.trim();
    if s.len() >= 2 && s.starts_with('"') && s.ends_with('"') {
        let inner = &s[1..s.len() - 1];
        let mut out = String::with_capacity(inner.len());
        let mut chars = inner.chars();
        while let Some(c) = chars.next() {
            if c != '\\' {
                out.push(c);
                continue;
            }
            match chars.next() {
                Some('n') => out.push('\n'),
                Some('t') => out.push('\t'),
                Some('r') => out.push('\r'),
                Some('0') => out.push('\0'),
                // `\"`, `\\`, `\/` and anything else: keep the escaped char.
                Some(other) => out.push(other),
                None => out.push('\\'),
            }
        }
        return out;
    }
    if s.len() >= 2 && s.starts_with('\'') && s.ends_with('\'') {
        // YAML single-quoted scalars escape only the quote, by doubling it.
        return s[1..s.len() - 1].replace("''", "'");
    }
    s.to_string()
}

/// Split a YAML inline list body. Quoted segments win over comma-splitting
/// because probe commands routinely contain commas (`--jq '.a,.b'`); only an
/// unquoted body falls back to a naive split.
fn split_inline_list(body: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut chars = body.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '"' || c == '\'' {
            let mut item = String::new();
            let mut escaped = false;
            for c2 in chars.by_ref() {
                if escaped {
                    item.push(c2);
                    escaped = false;
                } else if c2 == '\\' {
                    escaped = true;
                } else if c2 == c {
                    break;
                } else {
                    item.push(c2);
                }
            }
            out.push(item);
        }
    }
    if out.is_empty() {
        out = body
            .split(',')
            .map(unquote_scalar)
            .filter(|s| !s.is_empty())
            .collect();
    }
    out
}

/// What a plan doc's frontmatter says about `done_probes`.
#[derive(Debug, PartialEq)]
enum ProbeDecl {
    /// No `done_probes` key, or explicitly `[]` - both mean "no gate".
    None,
    Probes(Vec<String>),
    /// The key is present but no probes could be recovered from it. This is
    /// NEVER treated as "no probes": a declaration this parser cannot read is
    /// the vacuous-pass shape the whole feature exists to prevent, so it fails
    /// closed and asks a human to look.
    Unparseable,
}

/// Read `done_probes` from a plan doc's frontmatter. Accepts the block form
/// (`done_probes:\n  - "cmd"`) and the single-line inline form
/// (`done_probes: ["cmd"]`); anything else declared is `Unparseable`.
fn parse_done_probes(content: &str) -> ProbeDecl {
    let content = content.trim_start();
    if !content.starts_with("---") {
        return ProbeDecl::None;
    }
    let after_first = &content[3..];
    let Some(end) = after_first.find("\n---") else {
        return ProbeDecl::None;
    };

    let mut out = Vec::new();
    let mut declared = false;
    let mut in_block = false;
    for line in after_first[..end].lines() {
        let trimmed = line.trim();
        if !in_block {
            let Some(rest) = trimmed.strip_prefix("done_probes:") else {
                continue;
            };
            declared = true;
            let rest = rest.trim();
            if rest == "[]" {
                return ProbeDecl::None;
            }
            if let Some(inner) = rest.strip_prefix('[') {
                // strip_suffix, not trim_end_matches: the latter eats EVERY
                // trailing ']' (mangling a command that ends in one) and would
                // silently accept an unterminated list.
                let Some(inner) = inner.strip_suffix(']') else {
                    return ProbeDecl::Unparseable;
                };
                let items = split_inline_list(inner);
                // An empty result means a multi-line inline list (items live on
                // following lines) - unrecoverable here, so refuse rather than
                // report the declaration as absent.
                return if items.is_empty() {
                    ProbeDecl::Unparseable
                } else {
                    ProbeDecl::Probes(items)
                };
            }
            in_block = true;
            continue;
        }
        // Inside the block: a comment is not the end of it (treating one as a
        // terminator would silently drop every probe below it).
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        let Some(item) = trimmed.strip_prefix("- ") else {
            break; // the next frontmatter key ends the block
        };
        let item = unquote_scalar(item);
        if !item.is_empty() {
            out.push(item);
        }
    }

    match (declared, out.is_empty()) {
        (false, _) => ProbeDecl::None,
        (true, true) => ProbeDecl::Unparseable,
        (true, false) => ProbeDecl::Probes(out),
    }
}

/// Keep at most the LAST `cap` bytes, without splitting a UTF-8 character.
///
/// The tail, not the head: a failing command's real error is almost always its
/// last line, so keeping the prefix would routinely drop the one diagnostic the
/// block reason exists to surface. Char-boundary aware because `String::drain`
/// and `truncate` panic mid-character, and probe stderr regularly carries
/// arrows, box-drawing, and accented words.
fn keep_last_on_char_boundary(s: &mut String, cap: usize) {
    if s.len() <= cap {
        return;
    }
    let start = s.len() - cap;
    let cut = (start..=s.len())
        .find(|i| s.is_char_boundary(*i))
        .unwrap_or(s.len());
    s.drain(..cut);
}

/// SIGKILL a process group, ignoring "already gone".
fn killpg(pgid: i32) {
    if pgid <= 0 {
        return;
    }
    // SAFETY: pgid is our own spawned group leader's pid; ESRCH is expected
    // once every member has exited and is deliberately ignored.
    unsafe {
        libc::killpg(pgid, libc::SIGKILL);
    }
}

/// Run one probe under a native timeout.
///
/// Two things here are load-bearing rather than defensive. stderr is drained by
/// a reader thread because reading a piped stderr only after exit deadlocks any
/// probe that writes past the pipe buffer. And the child leads its own process
/// group, which is killed on EVERY exit path - not just the timeout.
///
/// The group kill has to cover normal exit too, because `sh` is not the only
/// process holding the stderr write end. A pipeline (`... | grep -q x`) forks,
/// and a probe that backgrounds anything (`sleep 3600 &`, or any command that
/// daemonizes) lets `sh` exit IMMEDIATELY while the descendant keeps the pipe
/// open. `try_wait` then reports success and leaves the timeout loop, so the
/// timer is never consulted again and the drain join blocks for the
/// descendant's whole lifetime - wedging the stop hook well past the 60s the
/// gate promises. Killing the group closes the pipe and bounds the join.
fn run_probe(cmd: &str, cwd: &Path, timeout: std::time::Duration) -> ProbeOutcome {
    use std::os::unix::process::CommandExt;

    let spawned = Command::new("sh")
        .arg("-c")
        .arg(cmd)
        .current_dir(cwd)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .process_group(0)
        .spawn();

    let mut child = match spawned {
        Ok(c) => c,
        Err(e) => {
            return ProbeOutcome::Fail {
                code: Some(127),
                stderr: format!("probe spawn failed: {e}"),
            }
        }
    };

    // Capture the pgid before any wait() can reap the leader.
    let pgid = child.id() as i32;

    let mut pipe = child.stderr.take();
    let drain = std::thread::spawn(move || {
        let mut buf = String::new();
        if let Some(ref mut p) = pipe {
            let _ = p.read_to_string(&mut buf);
        }
        buf
    });

    let start = std::time::Instant::now();
    let outcome = loop {
        match child.try_wait() {
            Ok(Some(status)) => {
                break if status.success() {
                    ProbeOutcome::Pass
                } else {
                    ProbeOutcome::Fail {
                        code: status.code(),
                        stderr: String::new(),
                    }
                };
            }
            Ok(None) => {
                if start.elapsed() >= timeout {
                    kill_process_group(&mut child);
                    break ProbeOutcome::Timeout;
                }
                std::thread::sleep(std::time::Duration::from_millis(50));
            }
            Err(e) => {
                kill_process_group(&mut child);
                break ProbeOutcome::Fail {
                    code: None,
                    stderr: format!("probe wait failed: {e}"),
                };
            }
        }
    };

    // Reap any descendant still holding the stderr write end, so the drain sees
    // EOF. Without this a backgrounding probe blocks the join indefinitely even
    // though the shell itself exited cleanly.
    killpg(pgid);

    // On timeout the stderr tail is worthless (the reason names the timeout) and
    // joining risks the very hang we just escaped if anything outlived the group
    // kill. Drop the handle instead: the thread ends when the pipe closes.
    if matches!(outcome, ProbeOutcome::Timeout) {
        return outcome;
    }

    let mut stderr = drain.join().unwrap_or_default();
    keep_last_on_char_boundary(&mut stderr, PROBE_STDERR_CAP);
    match outcome {
        ProbeOutcome::Fail { code, stderr: s } if s.is_empty() => {
            ProbeOutcome::Fail { code, stderr }
        }
        other => other,
    }
}

/// SIGKILL the child's whole process group, then reap it. A probe pipeline's
/// grandchildren hold the stderr pipe open; killing only the direct child would
/// leave the drain thread blocked on a pipe that never reaches EOF.
fn kill_process_group(child: &mut std::process::Child) {
    killpg(child.id() as i32);
    let _ = child.kill();
    let _ = child.wait();
}

/// Event payload for a refusal where probes were DECLARED but none ran (plan
/// unreadable, unparseable, over cap). It must be a non-empty object: recording
/// a bare null would make the refusal invisible to `prior_fires_declared_probes`,
/// so a plan that tripped the cap and then went missing would silently degrade
/// to "no gate" - the exact fail-open this records history to prevent. The key
/// is underscore-prefixed so it cannot collide with a probe command string.
fn undeterminable_marker(cause: &str) -> Value {
    serde_json::json!({ "_undeterminable": cause })
}

/// True when any prior loop_check fire for this session recorded probe results.
/// Used to fail closed on an unreadable plan only when probes are known to have
/// existed - a probe-less session with a stale plan_path keeps today's behavior.
fn prior_fires_declared_probes(events_path: &Path, session_id: &str) -> bool {
    let Ok(content) = std::fs::read_to_string(events_path) else {
        return false;
    };
    content.lines().any(|line| {
        let Ok(val) = serde_json::from_str::<Value>(line) else {
            return false;
        };
        val.get("type").and_then(|v| v.as_str()) == Some("loop_check")
            && val.pointer("/data/session_id").and_then(|v| v.as_str()) == Some(session_id)
            && val
                .pointer("/data/done_probes")
                .and_then(|v| v.as_object())
                .is_some_and(|m| !m.is_empty())
    })
}

/// Resolve the PLAN source to its probe list, or the gate that must block.
///
/// Split out from `evaluate_done_probes` so the project source can be resolved
/// independently: a plan that declares nothing (or whose doc is missing on a
/// probe-less session) must still let the project's own probes run, which a
/// single early-return-Absent path cannot express.
fn plan_declared_probes(
    plan_path: Option<&str>,
    cwd: &Path,
    events_path: &Path,
    session_id: &str,
) -> Result<Vec<String>, ProbeGate> {
    // Resolve a relative plan_path against the session's cwd, not the process
    // cwd: plan_path is repo-relative in practice, and reading nothing here
    // would degrade to Absent - a silent gate bypass.
    let plan = plan_path.and_then(|p| {
        // A plan_path may carry a `#wave-1`-style fragment; the Python plan
        // readers strip it, and reading the literal name would fail, which on
        // the first fire (no probe history) degrades to Absent - a silent
        // bypass of a gate the plan actually declared.
        let p = Path::new(p.split('#').next().unwrap_or(p));
        let abs = if p.is_absolute() {
            p.to_path_buf()
        } else {
            cwd.join(p)
        };
        std::fs::read_to_string(abs).ok()
    });
    let Some(plan) = plan else {
        // Fail closed only when probes were observed before; otherwise a stale
        // plan_path on a probe-less session must not start refusing done.
        if prior_fires_declared_probes(events_path, session_id) {
            return Err(ProbeGate::Fail {
                reason: format!(
                    "done_probes undeterminable: plan {} is unreadable but a prior fire declared probes; restore the plan doc",
                    plan_path.unwrap_or("(unset)")
                ),
                results: undeterminable_marker("plan-unreadable"),
            });
        }
        return Ok(Vec::new());
    };

    let probes = match parse_done_probes(&plan) {
        ProbeDecl::None => return Ok(Vec::new()),
        ProbeDecl::Unparseable => {
            return Err(ProbeGate::Fail {
                reason: format!(
                    "done_probes undeterminable: plan {} declares the field but no probe could be read from it (use a block list, or a single-line inline list)",
                    plan_path.unwrap_or("(unset)")
                ),
                results: undeterminable_marker("unparseable-declaration"),
            })
        }
        ProbeDecl::Probes(p) => p,
    };
    if probes.len() > PROBE_CAP {
        return Err(ProbeGate::Fail {
            reason: format!(
                "plan declares {} done_probes; the cap is {PROBE_CAP} per source (a probe list is a gate, not a test suite)",
                probes.len()
            ),
            results: undeterminable_marker("over-cap"),
        });
    }
    Ok(probes)
}

/// Evaluate the probe conjunct across BOTH sources. Called ONLY once every
/// other DonePRGreen conjunct already holds, so probes run at most once per
/// would-be-done fire.
///
/// `config_probes` is the repo-wide `done_probes` off config.toml. Both lists
/// run and both must pass: a plan can ADD guardrails and can never silence the
/// project's, including via an explicit `done_probes: []`. A repo-wide guard a
/// plan doc can switch off is a guard on one of two paths, which is decorative.
fn evaluate_done_probes(
    plan_path: Option<&str>,
    config_probes: Option<&Result<Vec<String>, String>>,
    cwd: &Path,
    events_path: &Path,
    session_id: &str,
    timeout: std::time::Duration,
) -> ProbeGate {
    // The project source resolves first: a declaration this parser cannot read
    // must block before anything runs, in the same vocabulary the plan side
    // uses. A config key that degrades to no-gate is a guardrail that
    // disappears when you typo it.
    let project = match config_probes {
        None => Vec::new(),
        Some(Err(why)) => {
            return ProbeGate::Fail {
                reason: format!(
                    "done_probes undeterminable: config.toml declares `done_probes` but {why}"
                ),
                results: undeterminable_marker("unparseable-config-declaration"),
            }
        }
        Some(Ok(p)) => p.clone(),
    };
    // PROBE_CAP applies PER SOURCE, not to the union. The cap encodes
    // per-declaration discipline ("a gate, not a test suite"); one shared
    // budget would instead make two independent authors compete for one number
    // and let a project's policy eat a plan's operational probes.
    if project.len() > PROBE_CAP {
        return ProbeGate::Fail {
            reason: format!(
                "config.toml declares {} done_probes; the cap is {PROBE_CAP} per source (a probe list is a gate, not a test suite)",
                project.len()
            ),
            results: undeterminable_marker("over-cap"),
        };
    }

    let plan_probes = match plan_declared_probes(plan_path, cwd, events_path, session_id) {
        Ok(p) => p,
        Err(gate) => return gate,
    };

    if project.is_empty() && plan_probes.is_empty() {
        return ProbeGate::Absent;
    }

    let mut results = serde_json::Map::new();
    let mut failures = Vec::new();
    for (source, cmd) in project
        .iter()
        .map(|c| ("project", c))
        .chain(plan_probes.iter().map(|c| ("plan", c)))
    {
        let outcome = run_probe(cmd, cwd, timeout);
        // Keyed by the BARE command: cli/src/fno/scoreboard/fold.py joins this
        // map back to the plan's frontmatter by exact command string, so the
        // source label belongs in the failure reason - which is what the
        // operator reads to know which file to edit - and never in the key.
        results.insert(cmd.clone(), Value::String(outcome.render()));
        match &outcome {
            ProbeOutcome::Pass => {}
            ProbeOutcome::Timeout => failures.push(format!(
                "{source} probe `{cmd}` timed out after {}s (killed)",
                timeout.as_secs()
            )),
            ProbeOutcome::Fail { code, stderr } => {
                let code = code.map(|c| c.to_string()).unwrap_or("signal".to_string());
                let tail = if stderr.trim().is_empty() {
                    String::new()
                } else {
                    format!(": {}", stderr.trim())
                };
                failures.push(format!("{source} probe `{cmd}` exited {code}{tail}"));
            }
        }
    }

    let results = Value::Object(results);
    if failures.is_empty() {
        ProbeGate::Pass(results)
    } else {
        ProbeGate::Fail {
            reason: format!(
                "done_probes failed - the shipped thing has no evidence of running: {}",
                failures.join("; ")
            ),
            results,
        }
    }
}

fn build_block_reason(pr: &PrInfo, local_head: &str, open_findings_empty: bool) -> String {
    // The ONE predicate. A message that prescribes the arm-and-tag ritual for a
    // blocker `async_wait_class` refuses to idle is the code contradicting
    // itself, and a session complied with exactly that roughly ten times on
    // #618. Deriving the hint from the classifier makes the two agree by
    // construction rather than by two hand-kept branch orders.
    let idlable = async_wait_class(pr, local_head, open_findings_empty);
    let hint = |blocker: &str| -> String {
        if idlable == Some(blocker) {
            arm_watch_hint(pr.number, blocker)
        } else {
            String::new()
        }
    };
    if !pr.state.is_open_or_merged() {
        return format!(
            "no PR for HEAD (pr_state={}); keep working",
            pr.state.as_str()
        );
    }

    if !pr.head_oid.is_empty() && pr.head_oid != local_head {
        return format!(
            "PR #{} head {} != local HEAD {}: push the latest commits before completing",
            pr.number,
            short_sha(&pr.head_oid),
            short_sha(local_head)
        );
    }

    if !pr.ci_conclusion.is_ok() {
        if pr.ci_conclusion == CiConclusion::None {
            return format!(
                "no CI checks found on PR #{}; declare ci.declared_none: true in settings if intentional",
                pr.number
            );
        }
        // Pending is "not green YET", not red. The MUTE_PROBE_N probe
        // (ab-223d2dae) runs done() while CI is commonly still in flight,
        // so a "CI failed" message here would mislead the blocked agent
        // into debugging a nonexistent failure on every quiet fire.
        if pr.ci_conclusion == CiConclusion::Pending {
            return format!("CI still running on PR #{}.{}", pr.number, hint("ci"));
        }
        let check_name = match &pr.ci_conclusion {
            CiConclusion::Failure(Some(name)) => name.as_str(),
            _ => "CI",
        };
        return format!("CI red on PR #{}: {} failed", pr.number, check_name);
    }

    if !pr.reviewed {
        // Order: work you can do now, cheapest-to-invalidate first, then the
        // async wait. An unaddressed finding leads because addressing it MOVES
        // HEAD, which supersedes any attestation produced before it - naming
        // the reviewer first would make a session run sigma twice. The bot
        // wait comes last: naming only the bot hides the half the session can
        // act on now, and if the bot never posts, the local work never happens
        // and the run dies on budget with the gate still unmet.
        if !pr.unaddressed_findings.is_empty() {
            // AC2-UI: name the specific finding (path:line) and the remedy.
            let f = &pr.unaddressed_findings[0];
            let more = if pr.unaddressed_findings.len() > 1 {
                format!(" [+{} more]", pr.unaddressed_findings.len() - 1)
            } else {
                String::new()
            };
            // x-b167 AC14: "reply in-thread" alone is a half-remedy - a reply
            // that does not address the bot by its full login never reaches it.
            // Name the handle when the finding author is a known bot.
            let reply_to = profile_by_author(&f.author)
                .map(|p| format!(" addressed to {}", p.reply_handle))
                .unwrap_or_default();
            return format!(
                "PR #{}: {} {} at {}:{} unaddressed (reply in-thread{} or wontfix:){}",
                pr.number, f.author, f.severity, f.path, f.line, reply_to, more
            );
        }
        if !pr.unattested_reviewers.is_empty() {
            // The branch that was missing (x-cdc7). Without it a local-only
            // reviewers gate fell through to the generic string below and told
            // the session to wait on a bot that was never required.
            //
            // No arm_watch_hint here, deliberately: `async_wait_class` has
            // ALREADY excluded this blocker from idling, because no GitHub
            // reviewer will ever post the attestation and the session would park
            // forever. Emitting the arm-and-tag ritual on a blocker the same
            // file refuses to idle is the code contradicting itself, and a
            // session did comply with it roughly ten times.
            let head = short_sha(local_head);
            let items: Vec<String> = pr
                .unattested_reviewers
                .iter()
                .map(|r| {
                    // "no attestation" is a lie to a session that ran the
                    // reviewer and got told no; name that case separately.
                    let state = if r.failed_at_head {
                        " (attested at this head, verdict NOT pass)".to_string()
                    } else {
                        match &r.superseded_head {
                            Some(h) => {
                                format!(" (passed at {}, superseded by this head)", short_sha(h))
                            }
                            None => String::new(),
                        }
                    };
                    if r.name == SAME_MODEL_LOCAL_PEER_SENTINEL {
                        return format!(
                            "peer{} -> configure a cross-model peer or routed model",
                            state
                        );
                    }
                    if r.name == LOCAL_PEER_REVIEWER {
                        return format!("peer{} -> run `/fno:review peer --attest`", state);
                    }
                    match reviewer_invocation(&r.name) {
                        Some((inv, self_cert)) => {
                            let mark = if self_cert {
                                " [self-cert: asserts no review evidence]"
                            } else {
                                ""
                            };
                            format!("{}{} -> run `{}`{}", r.name, state, inv, mark)
                        }
                        None => format!("{}{}", r.name, state),
                    }
                })
                .collect();
            let corrupt = match pr.malformed_attestations {
                0 => String::new(),
                n => format!(" ({n} unparseable attestation line(s) ignored)"),
            };
            return format!(
                "PR #{}: reviewers gate unmet - no head-pinned review_attestation at {} for {}{}. \
                 This is local work to DO, not a wait: no GitHub reviewer posts these, \
                 so do not arm a watcher.",
                pr.number,
                head,
                items.join("; "),
                corrupt
            );
        }
        if !pr.missing_bots.is_empty() {
            // x-b167: render per nudge state. `hint("review")` is derived from
            // async_wait_class, so it is EMPTY for NeedsNudge/Unresponsive (both
            // non-idlable) and PRESENT for Awaiting/NotNudgeable by construction -
            // the arm-and-tag ritual can never appear on a blocker the same file
            // refuses to idle (the contradiction x-cdc7 removed). NeedsNudge and
            // Unresponsive lead because they are work/decisions, not waits.
            if let Some(n) = pr
                .bot_nudges
                .iter()
                .find(|n| n.class == NudgeClass::NeedsNudge)
            {
                return format!(
                    "PR #{}: {} reviews on mention, not on push, and has not been asked. Run:\n  \
                     gh pr comment {} --body \"{}\"\nthen arm a watcher (nudge {} of {}).{}",
                    pr.number,
                    n.login,
                    pr.number,
                    n.review_handle,
                    n.nudges + 1,
                    n.ceiling,
                    hint("review")
                );
            }
            if let Some(n) = pr
                .bot_nudges
                .iter()
                .find(|n| n.class == NudgeClass::Unresponsive)
            {
                return format!(
                    "PR #{}: {} did not review after {} nudges over {}m. Nothing further \
                     will arrive on its own. Either post the review by hand, or move this \
                     login to config.review.optional_apps (honored-if-present, never waited \
                     on). Not a wait: do not arm a watcher.{}",
                    pr.number,
                    n.login,
                    n.nudges,
                    n.span_min,
                    hint("review")
                );
            }
            if let Some(n) = pr
                .bot_nudges
                .iter()
                .find(|n| n.class == NudgeClass::Awaiting)
            {
                return format!(
                    "PR #{}: {} nudged {}m ago ({} of {}), awaiting review.{}",
                    pr.number,
                    n.login,
                    n.newest_age_min,
                    n.nudges,
                    n.ceiling,
                    hint("review")
                );
            }
            // All NotNudgeable (or not classified): today's exact string + hint
            // (AC5 - a non-nudgeable required bot keeps the pre-x-b167 behavior).
            return format!(
                "PR #{}: {} has not reviewed.{}",
                pr.number,
                pr.missing_bots.join(", "),
                hint("review")
            );
        }
        // Reaching here means missing_bots is empty, which `async_wait_class`
        // treats as non-idlable, so this must not teach the arm-and-tag ritual
        // either (the two must never disagree about whether a wait is valid).
        return format!(
            "PR #{} not yet reviewed and no reviewer is outstanding; \
             re-check config.review (required_bots / reviewers) - nothing here will \
             arrive on its own.",
            pr.number
        );
    }

    format!("PR #{} done() returned false (unknown reason)", pr.number)
}

// ── public entry points ───────────────────────────────────────────────────────

/// Entry point called from `bin/client.rs` direct dispatch.
/// Prints JSON to stdout, returns exit code.
pub fn run_loop_check(args: &[String]) -> i32 {
    let (code, json) = decide(args);
    println!("{json}");
    code
}

/// Test-friendly variant that returns (exit_code, json_string) without printing.
/// Used by integration tests in tests/loop_check.rs.
pub fn run_loop_check_capture(args: &[String]) -> (i32, String) {
    decide(args)
}

// ── unit tests ────────────────────────────────────────────────────────────────

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

    /// The list half of the scan. Production reads the count too, so this
    /// wrapper lives here rather than as an unused function in the binary.
    fn unattested_reviewers(
        events_path: &Path,
        reviewers: &[String],
        head_sha: &str,
    ) -> Vec<UnattestedReviewer> {
        unattested_reviewers_scan(events_path, reviewers, head_sha).0
    }

    /// The gate's boolean view of `unattested_reviewers`, exactly as
    /// `read_pr_info` derives it. The pre-x-cdc7 predicate tests below are
    /// unchanged on purpose: promoting the return value to a list must not
    /// move the gate.
    fn reviewers_all_attested(events_path: &Path, reviewers: &[String], head_sha: &str) -> bool {
        unattested_reviewers(events_path, reviewers, head_sha).is_empty()
    }

    // ── streak debounce (x-6231) ─────────────────────────────────────────────
    //
    // These drive `read_prior_fires` with an explicit `now` and gap, so they need
    // no env var and are parallel-safe -- unlike the integration suite, which
    // pins FNO_LOOPCHECK_MIN_FIRE_GAP_SECS=0 process-wide.

    const FP: &str = "FP";
    const NOW: &str = "2026-06-05T12:00:00Z";

    fn at(ts: &str) -> DateTime<Utc> {
        ts.parse().unwrap()
    }

    /// Write a loop_check events log from (ts, fingerprint) pairs, oldest first.
    fn write_fire_log(path: &Path, fires: &[(String, &str)]) {
        let mut out = String::new();
        for (ts, fp) in fires {
            out.push_str(
                &serde_json::json!({
                    "ts": ts, "type": "loop_check", "source": "hook",
                    "data": { "session_id": "sess", "fingerprint": fp },
                })
                .to_string(),
            );
            out.push('\n');
        }
        std::fs::write(path, out).unwrap();
    }

    /// Count the streak over prior fires given as SECONDS BEFORE `now`, oldest
    /// first, all sharing FP. Returns (streak, streak_window_secs).
    fn streak_ago(secs_before_now: &[i64], gap: i64) -> (u64, i64) {
        let now = at(NOW);
        let fires: Vec<(String, &str)> = secs_before_now
            .iter()
            .map(|s| {
                (
                    (now - chrono::Duration::seconds(*s))
                        .format("%Y-%m-%dT%H:%M:%SZ")
                        .to_string(),
                    FP,
                )
            })
            .collect();
        let dir = tempfile::TempDir::new().unwrap();
        let p = dir.path().join("events.jsonl");
        write_fire_log(&p, &fires);
        let (_, streak, _, window) = read_prior_fires(&p, "sess", FP, now, gap);
        (streak, window)
    }

    /// The streak rules. `consecutive_after` is streak + 1, so a streak of 4 is
    /// what trips the attended backstop of 5.
    #[test]
    fn debounce_streak_counting_rules() {
        // (case, prior fires as seconds before now (oldest first), gap, streak, window)
        #[rustfmt::skip]
        let cases: &[(&str, &[i64], i64, u64, i64)] = &[
            // AC1-HP: the triggering shape - four fires inside 60s are ONE
            // observation (the current fire), nowhere near backstop_n.
            ("rapid burst collapses to one observation", &[49, 33, 16, 0], 300, 0, 0),
            // AC2-HP: a genuinely stalled session is still reaped.
            ("fires 6 minutes apart still trip the backstop", &[1440, 1080, 720, 360], 300, 4, 1440),
            // AC3-FR: a skip must NOT advance the cursor. This fire is 330s
            // before `now` but only 270s before the burst's oldest member, so it
            // counts ONLY because the burst left the cursor parked at `now`.
            ("a skip does not advance the cursor", &[330, 60, 30, 10], 300, 1, 330),
            // AC6-FR: gap 0 is byte-identical to the old fire counting, which is
            // what lets the integration suite pin the seam and keep every
            // backstop assertion it already had.
            ("gap 0 restores fire counting exactly", &[49, 33, 16], 0, 3, 49),
            // Clock skew must not invent a debounce from a bad clock.
            ("a fire stamped after `now` counts, not crashes", &[1200, -600], 300, 2, 1200),
            // AC8-REG: the recorded sequence behind the false terminal - session
            // 20260727T203203Z, five fires in 109 seconds with CI still PENDING.
            ("the false-NoProgress incident now blocks", &[109, 93, 76, 17], 300, 0, 0),
        ];
        for (case, fires, gap, want_streak, want_window) in cases {
            let (streak, window) = streak_ago(fires, *gap);
            assert_eq!(streak, *want_streak, "streak: {case}");
            assert_eq!(window, *want_window, "window: {case}");
        }
    }

    /// AC4-CON: progress is never debounced - a CHANGED fingerprint breaks the
    /// streak however fast it arrived.
    #[test]
    fn debounce_changed_fingerprint_breaks_streak_at_any_speed() {
        let now = at(NOW);
        let dir = tempfile::TempDir::new().unwrap();
        let p = dir.path().join("events.jsonl");
        write_fire_log(
            &p,
            &[
                ("2026-06-05T11:40:00Z".to_string(), FP),
                ("2026-06-05T11:50:00Z".to_string(), FP),
                ("2026-06-05T11:59:58Z".to_string(), "DIFFERENT"),
            ],
        );
        let (_, streak, _, _) = read_prior_fires(&p, "sess", FP, now, 300);
        assert_eq!(streak, 0, "a 2-second-old change still resets the streak");
    }

    /// AC5-ERR: a fire we cannot place in time is transparent - it neither counts
    /// toward nor breaks the streak, and never panics. Failing this way biases
    /// away from an irreversible NoProgress.
    #[test]
    fn debounce_untimestamped_fire_is_transparent() {
        let dir = tempfile::TempDir::new().unwrap();
        let p = dir.path().join("events.jsonl");
        let lines = [
            r#"{"ts":"2026-06-05T11:40:00Z","type":"loop_check","source":"hook","data":{"session_id":"sess","fingerprint":"FP"}}"#,
            r#"{"ts":"not-a-timestamp","type":"loop_check","source":"hook","data":{"session_id":"sess","fingerprint":"FP"}}"#,
            r#"{"type":"loop_check","source":"hook","data":{"session_id":"sess","fingerprint":"FP"}}"#,
        ];
        std::fs::write(&p, lines.join("\n") + "\n").unwrap();

        let (_, streak, last_fp, _) = read_prior_fires(&p, "sess", FP, at(NOW), 300);
        assert_eq!(
            streak, 1,
            "unplaceable fires skip; the good one still counts"
        );
        assert_eq!(
            last_fp.as_deref(),
            Some(FP),
            "carry-forward still reads the newest recorded fp"
        );
    }

    #[test]
    fn parse_manifest_minimal() {
        let content =
            "---\nsession_id: abc\ncreated_at: 2026-06-05T00:00:00Z\nattended: true\n---\n";
        let m = parse_manifest(content).unwrap();
        assert_eq!(m.session_id.as_deref(), Some("abc"));
        assert_eq!(m.created_at.as_deref(), Some("2026-06-05T00:00:00Z"));
        assert!(m.attended);
        assert!(m.legacy_status.is_none());
    }

    #[test]
    fn scan_manifest_field_reads_claim_fields_after_frontmatter() {
        // x-ba4b regression: `fno target init` APPENDS the node-claim fields
        // AFTER the closing `---`, so the frontmatter-bounded parse_manifest must
        // NOT be relied on for them - the whole-file scanner is what drives
        // renewal. Mirrors init's real manifest shape.
        let content = "---\nsession_id: s1\nattended: false\n---\n\
                       Immutable session manifest.\n\
                       target_claim_key: \"node:x-ba4b\"\n\
                       target_claim_holder: \"target-session:s1\"\n\
                       target_claim_ttl: \"2h\"\n";
        // parse_manifest (frontmatter-bounded) never sees the appended fields.
        let m = parse_manifest(content).unwrap();
        assert_eq!(m.session_id.as_deref(), Some("s1"));
        // The whole-file scanner does.
        assert_eq!(
            scan_manifest_field(content, "target_claim_key").as_deref(),
            Some("node:x-ba4b")
        );
        assert_eq!(
            scan_manifest_field(content, "target_claim_holder").as_deref(),
            Some("target-session:s1")
        );
        assert_eq!(
            scan_manifest_field(content, "target_claim_ttl")
                .as_deref()
                .and_then(crate::claims::parse_ttl_ms),
            Some(7_200_000)
        );
        assert_eq!(scan_manifest_field(content, "nonexistent_field"), None);
    }

    #[test]
    fn parse_manifest_legacy_complete() {
        let content =
            "---\nsession_id: s\ncreated_at: 2026-06-05T00:00:00Z\nstatus: COMPLETE\n---\n";
        let m = parse_manifest(content).unwrap();
        assert_eq!(m.legacy_status.as_deref(), Some("COMPLETE"));
    }

    #[test]
    fn parse_manifest_legacy_blocked() {
        let content =
            "---\nsession_id: s\ncreated_at: 2026-06-05T00:00:00Z\nstatus: BLOCKED\n---\n";
        let m = parse_manifest(content).unwrap();
        assert_eq!(m.legacy_status.as_deref(), Some("BLOCKED"));
    }

    #[test]
    fn parse_manifest_no_ship() {
        let content = "---\nsession_id: s\ncreated_at: 2026-06-05T00:00:00Z\nno_ship: true\n---\n";
        let m = parse_manifest(content).unwrap();
        assert!(m.no_ship);
        assert!(!m.no_external);
    }

    #[test]
    fn parse_manifest_planned() {
        let content = "---\nsession_id: s\ncreated_at: 2026-06-05T00:00:00Z\nplanned: true\n---\n";
        let m = parse_manifest(content).unwrap();
        assert!(m.planned);
        assert!(!m.advisory); // planned is distinct from advisory (which graduates)
    }

    #[test]
    fn parse_manifest_strips_quotes() {
        // gemini MEDIUM on #447: quoted YAML values must parse identically.
        let content = "---\nsession_id: \"s-quoted\"\ncreated_at: '2026-06-05T00:00:00Z'\n---\n";
        let m = parse_manifest(content).unwrap();
        assert_eq!(m.session_id.as_deref(), Some("s-quoted"));
        assert_eq!(m.created_at.as_deref(), Some("2026-06-05T00:00:00Z"));
    }

    #[test]
    fn parse_settings_nested_budget_and_ci() {
        // Flat config.toml: budget / ci are top-level tables (no config: wrapper).
        let cfg = "[budget.unattended]\ncost_cap_usd = 7.5\n\n[ci]\ndeclared_none = true\n";
        let s = parse_settings(cfg);
        assert_eq!(s.unattended_cost_cap_usd, Some(Ok(7.5)));
        assert!(s.ci_declared_none);
    }

    #[test]
    fn stderr_tail_multibyte_boundary_no_panic() {
        // gemini HIGH on #447: tail slice must land on a char boundary.
        let mut payload = String::new();
        while payload.len() < 300 {
            payload.push('\u{00e9}'); // 2-byte char so len-200 can split one
        }
        let tail = stderr_tail(payload.as_bytes());
        assert!(tail.len() <= 200);
        assert!(!tail.is_empty());
    }

    #[test]
    fn parse_manifest_attended_default_true() {
        let content = "---\nsession_id: s\ncreated_at: 2026-06-05T00:00:00Z\n---\n";
        let m = parse_manifest(content).unwrap();
        assert!(m.attended, "attended should default to true when absent");
    }

    #[test]
    fn parse_manifest_budget_caps() {
        let content =
            "---\nsession_id: s\ncreated_at: 2026-06-05T00:00:00Z\nbudget_wall_clock_cap_minutes: 120\nbudget_cost_cap_usd: 5.0\n---\n";
        let m = parse_manifest(content).unwrap();
        assert_eq!(m.budget_wall_clock_cap_minutes, Some(Ok(120)));
        assert_eq!(m.budget_cost_cap_usd, Some(Ok(5.0)));
    }

    #[test]
    fn parse_manifest_no_frontmatter_returns_none() {
        let content = "no frontmatter here";
        assert!(parse_manifest(content).is_none());
    }

    #[test]
    fn parse_settings_flat_budget_cap() {
        let cfg = "budget_cap = 2.5\n";
        let s = parse_settings(cfg);
        assert_eq!(s.flat_budget_cap, Some(Ok(2.5)));
    }

    #[test]
    fn parse_settings_nested_budget() {
        let cfg = "[budget.attended]\nwall_clock_cap_minutes = 90\ncost_cap_usd = 10.0\n\n[budget.unattended]\nwall_clock_cap_minutes = 60\ncost_cap_usd = 5.0\n";
        let s = parse_settings(cfg);
        assert_eq!(s.attended_wall_cap_minutes, Some(Ok(90)));
        assert_eq!(s.attended_cost_cap_usd, Some(Ok(10.0)));
        assert_eq!(s.unattended_wall_cap_minutes, Some(Ok(60)));
        assert_eq!(s.unattended_cost_cap_usd, Some(Ok(5.0)));
    }

    #[test]
    fn parse_settings_ci_declared_none() {
        let cfg = "[ci]\ndeclared_none = true\n";
        let s = parse_settings(cfg);
        assert!(s.ci_declared_none);
    }

    #[test]
    fn parse_settings_comments_ignored() {
        let cfg =
            "# top comment\nbudget_cap = 1.0\n# another\n[ci]\n# inner\ndeclared_none = true\n";
        let s = parse_settings(cfg);
        assert_eq!(s.flat_budget_cap, Some(Ok(1.0)));
        assert!(s.ci_declared_none);
    }

    #[test]
    fn detect_intent_promise() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("t.jsonl");
        let line = serde_json::json!({
            "message": {"role": "assistant", "content": "done <promise>COMPLETE</promise>"}
        });
        std::fs::write(&path, serde_json::to_string(&line).unwrap() + "\n").unwrap();
        assert_eq!(detect_intent_full(&path), Intent::Promise);
    }

    #[test]
    fn detect_intent_aborted_beats_promise() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("t.jsonl");
        // Last line has aborted (even if earlier had promise, aborted in same msg wins)
        let line = serde_json::json!({
            "message": {"role": "assistant", "content": "<aborted reason=\"user\">done</aborted>"}
        });
        std::fs::write(&path, serde_json::to_string(&line).unwrap() + "\n").unwrap();
        assert!(matches!(detect_intent_full(&path), Intent::Aborted { .. }));
    }

    #[test]
    fn detect_intent_tool_result_ignored() {
        // Tool result content with promise-like text should not trigger
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("t.jsonl");
        let user_line = serde_json::json!({
            "message": {"role": "user", "content": "<promise>fake</promise>"}
        });
        std::fs::write(&path, serde_json::to_string(&user_line).unwrap() + "\n").unwrap();
        assert_eq!(detect_intent_full(&path), Intent::None);
    }

    #[test]
    fn detect_intent_none_when_no_assistant() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("t.jsonl");
        let line = serde_json::json!({"message": {"role": "user", "content": "go"}});
        std::fs::write(&path, serde_json::to_string(&line).unwrap() + "\n").unwrap();
        assert_eq!(detect_intent_full(&path), Intent::None);
    }

    #[test]
    fn detect_intent_array_content_blocks() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("t.jsonl");
        let line = serde_json::json!({
            "message": {
                "role": "assistant",
                "content": [
                    {"type": "text", "text": "<promise>done</promise>"},
                    {"type": "tool_use", "name": "Bash"}
                ]
            }
        });
        std::fs::write(&path, serde_json::to_string(&line).unwrap() + "\n").unwrap();
        assert_eq!(detect_intent_full(&path), Intent::Promise);
    }

    #[test]
    fn extract_last_assistant_message_plain_string() {
        let payload = r#"{"transcript_path":"/t.jsonl","last_assistant_message":"  done <promise>MISSION COMPLETE: x</promise>  "}"#;
        assert_eq!(
            extract_last_assistant_message(payload).as_deref(),
            Some("done <promise>MISSION COMPLETE: x</promise>")
        );
    }

    #[test]
    fn extract_last_assistant_message_degrades_to_none() {
        // Missing field, malformed JSON, non-string value, and empty/blank
        // strings all degrade to None (transcript fallback), never an error.
        assert_eq!(
            extract_last_assistant_message(r#"{"transcript_path":"/t.jsonl"}"#),
            None
        );
        assert_eq!(extract_last_assistant_message("not json {"), None);
        assert_eq!(
            extract_last_assistant_message(r#"{"last_assistant_message":{"text":"obj"}}"#),
            None
        );
        assert_eq!(
            extract_last_assistant_message(r#"{"last_assistant_message":"   "}"#),
            None
        );
    }

    #[test]
    fn detect_intent_payload_promise_wins_over_stale_transcript() {
        // AC2-HP: at the promise turn's own fire the transcript does NOT yet
        // contain the final message; the payload alone must carry the intent.
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("t.jsonl");
        let line = serde_json::json!({
            "message": {"role": "assistant", "content": "still working on it"}
        });
        std::fs::write(&path, serde_json::to_string(&line).unwrap() + "\n").unwrap();
        let (intent, source) =
            detect_intent(Some("<promise>MISSION COMPLETE: done</promise>"), &path);
        assert_eq!(intent, Intent::Promise);
        assert_eq!(source, "payload");
    }

    #[test]
    fn detect_intent_payload_no_tag_is_authoritative() {
        // A tag-less payload is the stopping turn's final text; it must NOT
        // fall through to the transcript (stale-promise containment).
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("t.jsonl");
        let line = serde_json::json!({
            "message": {"role": "assistant", "content": "<promise>old stale promise</promise>"}
        });
        std::fs::write(&path, serde_json::to_string(&line).unwrap() + "\n").unwrap();
        let (intent, source) = detect_intent(Some("moving on to other work"), &path);
        assert_eq!(intent, Intent::None);
        assert_eq!(source, "payload");
    }

    #[test]
    fn detect_intent_payload_aborted_beats_promise() {
        let (intent, source) = detect_intent(
            Some("<promise>done</promise> <aborted reason=\"kill\">stop</aborted>"),
            Path::new("/nonexistent"),
        );
        assert!(matches!(intent, Intent::Aborted { ref reason } if reason == "kill"));
        assert_eq!(source, "payload");
    }

    #[test]
    fn watching_intent_parses_all_attrs() {
        let (intent, source) = detect_intent(
            Some("waiting <watching reason=\"ci\" pr=\"404\" timeout=\"30m\">"),
            Path::new("/nonexistent"),
        );
        assert_eq!(source, "payload");
        assert_eq!(
            intent,
            Intent::Watching {
                reason: "ci".into(),
                pr: Some("404".into()),
                timeout: Some("30m".into()),
            }
        );
    }

    #[test]
    fn watching_intent_malformed_attrs_default_to_absent() {
        // A bare tag: attributes absent, not an error; lease math applies its
        // own default window downstream.
        let (intent, _) = detect_intent(Some("<watching>"), Path::new("/nonexistent"));
        assert_eq!(
            intent,
            Intent::Watching {
                reason: String::new(),
                pr: None,
                timeout: None,
            }
        );
    }

    #[test]
    fn watching_intent_aborted_beats_watching() {
        let (intent, _) = detect_intent(
            Some("<watching reason=\"ci\" pr=\"1\"> <aborted reason=\"kill\">"),
            Path::new("/nonexistent"),
        );
        assert!(matches!(intent, Intent::Aborted { ref reason } if reason == "kill"));
    }

    #[test]
    fn watching_intent_beats_promise() {
        let (intent, _) = detect_intent(
            Some("<promise>done</promise> <watching reason=\"review\" pr=\"9\">"),
            Path::new("/nonexistent"),
        );
        assert!(matches!(intent, Intent::Watching { .. }));
    }

    #[test]
    fn watching_intent_newest_transcript_entry_honored() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("t.jsonl");
        let line = serde_json::json!({
            "message": {"role": "assistant", "content": "<watching reason=\"ci\" pr=\"7\">"}
        });
        std::fs::write(&path, serde_json::to_string(&line).unwrap() + "\n").unwrap();
        assert!(matches!(detect_intent_full(&path), Intent::Watching { .. }));
    }

    #[test]
    fn watching_intent_stale_transcript_not_honored() {
        // AC3-EDGE: a watching tag 2 entries back with a tag-less newest entry
        // must NOT resurrect as Watching (payload-or-newest-entry rule).
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("t.jsonl");
        let mut content = String::new();
        for text in [
            "<watching reason=\"ci\" pr=\"3\">", // oldest
            "still going",
            "moving on to unrelated work", // newest
        ] {
            let line = serde_json::json!({"message": {"role": "assistant", "content": text}});
            content.push_str(&serde_json::to_string(&line).unwrap());
            content.push('\n');
        }
        std::fs::write(&path, content).unwrap();
        assert_eq!(detect_intent_full(&path), Intent::None);
    }

    #[test]
    fn watching_intent_stale_watch_does_not_shadow_deeper_promise() {
        // A stale watching in the newest-but-one entry is skipped, and a real
        // promise deeper in the lookback window still wins.
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("t.jsonl");
        let mut content = String::new();
        for text in [
            "<promise>MISSION COMPLETE: shipped</promise>", // oldest, real
            "<watching reason=\"ci\" pr=\"3\">",            // stale (not newest)
            "tag-less newest",                              // newest
        ] {
            let line = serde_json::json!({"message": {"role": "assistant", "content": text}});
            content.push_str(&serde_json::to_string(&line).unwrap());
            content.push('\n');
        }
        std::fs::write(&path, content).unwrap();
        assert_eq!(detect_intent_full(&path), Intent::Promise);
    }

    #[test]
    fn detect_intent_absent_payload_falls_back_to_transcript() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("t.jsonl");
        let line = serde_json::json!({
            "message": {"role": "assistant", "content": "<promise>COMPLETE</promise>"}
        });
        std::fs::write(&path, serde_json::to_string(&line).unwrap() + "\n").unwrap();
        let (intent, source) = detect_intent(None, &path);
        assert_eq!(intent, Intent::Promise);
        assert_eq!(source, "transcript");
    }

    #[test]
    fn detect_intent_lookback_finds_promise_behind_block_feedback() {
        // AC2-EDGE ("the block destroys the evidence"): promise 3 assistant
        // text entries back - block feedback reply + a follow-up on top -
        // must still be detected by the bounded fallback scan.
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("t.jsonl");
        let mut content = String::new();
        for text in [
            "<promise>MISSION COMPLETE: shipped</promise>",
            "acknowledged the block; checking CI",
            "CI is still pending, waiting",
        ] {
            let line = serde_json::json!({
                "message": {"role": "assistant", "content": text}
            });
            content.push_str(&serde_json::to_string(&line).unwrap());
            content.push('\n');
        }
        std::fs::write(&path, content).unwrap();
        assert_eq!(detect_intent_full(&path), Intent::Promise);
    }

    #[test]
    fn detect_intent_lookback_bound_holds() {
        // AC2-EDGE ("grill the stale-promise edge"): a promise older than
        // INTENT_LOOKBACK_ENTRIES assistant text entries must NOT ride the
        // window.
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("t.jsonl");
        let mut content = String::new();
        let line = serde_json::json!({
            "message": {"role": "assistant", "content": "<promise>stale</promise>"}
        });
        content.push_str(&serde_json::to_string(&line).unwrap());
        content.push('\n');
        for i in 0..INTENT_LOOKBACK_ENTRIES {
            let line = serde_json::json!({
                "message": {"role": "assistant", "content": format!("pivoted work step {i}")}
            });
            content.push_str(&serde_json::to_string(&line).unwrap());
            content.push('\n');
        }
        std::fs::write(&path, content).unwrap();
        assert_eq!(detect_intent_full(&path), Intent::None);
    }

    #[test]
    fn parse_args_hook_input_stdin_flag() {
        let args: Vec<String> = [
            "loop-check",
            "--state",
            "/s.md",
            "--transcript",
            "/t.jsonl",
            "--cwd",
            "/w",
            "--hook-input-stdin",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        let parsed = parse_args(&args).unwrap();
        assert!(parsed.hook_input_stdin);
        // Bare flag must not swallow a following flag as its value.
        assert_eq!(parsed.cwd, PathBuf::from("/w"));
    }

    #[test]
    fn block_reason_pending_ci_is_not_red() {
        // The MUTE_PROBE_N probe runs done() while CI is often still in
        // flight; a Pending conclusion must read as "still running", never
        // as the misleading "CI red ... failed" (observed live on PR #455).
        let pr = PrInfo {
            state: PrState::Open,
            number: 455,
            head_oid: "abc".to_string(),
            ci_conclusion: CiConclusion::Pending,
            failing_checks: vec![],
            ci_has_pending: false,
            mergeable: "UNKNOWN".to_string(),
            latest_review_ts: "none".to_string(),
            reviewed: false,
            missing_bots: vec![],
            bot_nudges: vec![],
            usage_limited: vec![],
            unaddressed_findings: vec![],
            review_skipped: false,
            unattested_reviewers: vec![],
            malformed_attestations: 0,
        };
        let reason = build_block_reason(&pr, "abc", true);
        assert!(
            reason.contains("still running"),
            "pending CI must not read as red; got: {reason}"
        );
        assert!(!reason.contains("failed"), "got: {reason}");
    }

    #[test]
    fn unwatched_async_nudge_ci_pending_teaches_arm_and_tag() {
        // AC3-HP: the CI-pending block message must instruct arming a
        // harness-tracked watcher with a timeout and emitting <watching>,
        // replacing the old "wait silently" prose.
        let pr = PrInfo {
            ci_conclusion: CiConclusion::Pending,
            ci_has_pending: true,
            ..watch_pr()
        };
        let reason = build_block_reason(&pr, "abc", true);
        assert!(reason.contains("<watching"), "got: {reason}");
        assert!(reason.contains("timeout"), "got: {reason}");
        assert!(reason.contains("gh pr checks"), "got: {reason}");
        assert!(!reason.contains("wait silently"), "got: {reason}");
    }

    #[test]
    fn no_hint_prescribes_the_timeout_binary() {
        // File-wide, so a future hint cannot reintroduce `timeout(1)` at a site
        // this test does not name. The needle is built at runtime so the test
        // does not match its own source.
        let needle = ["timeout", " "].concat();
        for tail in include_str!("loopcheck.rs").split(&needle).skip(1) {
            assert!(
                !tail.trim_start().starts_with(|c: char| c.is_ascii_digit()),
                "bare timeout invocation: ...{}",
                tail.chars().take(60).collect::<String>()
            );
        }
    }

    #[test]
    fn unwatched_async_nudge_missing_review_teaches_arm_and_tag() {
        let pr = PrInfo {
            ci_conclusion: CiConclusion::Success,
            ci_has_pending: false,
            reviewed: false,
            missing_bots: vec!["chatgpt-codex-connector".into()],
            bot_nudges: vec![],
            ..watch_pr()
        };
        let reason = build_block_reason(&pr, "abc", true);
        assert!(reason.contains("chatgpt-codex-connector"), "got: {reason}");
        assert!(reason.contains("<watching"), "got: {reason}");
    }

    // ── Watching idle-allow classification (x-e2c8) ───────────────────────
    /// An open PR whose head matches local HEAD, CI still pending, no findings.
    fn watch_pr() -> PrInfo {
        PrInfo {
            state: PrState::Open,
            number: 404,
            head_oid: "abc".to_string(),
            ci_conclusion: CiConclusion::Pending,
            failing_checks: vec![],
            ci_has_pending: true,
            mergeable: "UNKNOWN".to_string(),
            latest_review_ts: "none".to_string(),
            reviewed: false,
            missing_bots: vec![],
            bot_nudges: vec![],
            usage_limited: vec![],
            unaddressed_findings: vec![],
            review_skipped: false,
            unattested_reviewers: vec![],
            malformed_attestations: 0,
        }
    }

    #[test]
    fn watch_idle_classifies_pending_ci() {
        assert_eq!(async_wait_class(&watch_pr(), "abc", true), Some("ci"));
    }

    #[test]
    fn codex_watch_harness_gate_is_claude_only() {
        // Only Claude self-wakes on a background-task exit, so only Claude idles.
        assert!(harness_can_idle(Some("claude"), false));
        // A loop-run child (FNO_DRIVER_LIB) exits on allow -> never idles.
        assert!(!harness_can_idle(Some("claude"), true));
        // codex/gemini have no self-wake; their daemon-consumer waker ships
        // separately, so until then they keep today's block behavior.
        assert!(!harness_can_idle(Some("codex"), false));
        assert!(!harness_can_idle(Some("gemini"), false));
        // Unknown harness (bare shell / daemon): conservative block.
        assert!(!harness_can_idle(None, false));
    }

    #[test]
    fn watch_idle_classifies_awaiting_review() {
        // CI green, no pending checks, and a required GitHub bot has not reviewed.
        let pr = PrInfo {
            ci_conclusion: CiConclusion::Success,
            ci_has_pending: false,
            reviewed: false,
            review_skipped: false,
            missing_bots: vec!["chatgpt-codex-connector".into()],
            bot_nudges: vec![],
            ..watch_pr()
        };
        assert_eq!(async_wait_class(&pr, "abc", true), Some("review"));
    }

    #[test]
    fn watch_idle_rejects_ci_pending_with_a_failure() {
        // gemini finding: a check has ALREADY concluded red while others run.
        // The agent should debug now, not idle out the remaining pending checks.
        let pr = PrInfo {
            ci_conclusion: CiConclusion::Failure(Some("unit".into())),
            ci_has_pending: true,
            ..watch_pr()
        };
        assert_eq!(async_wait_class(&pr, "abc", true), None);
    }

    #[test]
    fn watch_idle_rejects_local_attestation_review_gate() {
        // codex P1: reviewed=false with an EMPTY missing_bots is a local
        // attestation (sigma) or unaddressed-finding gate - no GitHub reviewer
        // will ever post to wake the session, so idling would park it forever.
        let pr = PrInfo {
            ci_conclusion: CiConclusion::Success,
            ci_has_pending: false,
            reviewed: false,
            review_skipped: false,
            missing_bots: vec![],
            bot_nudges: vec![],
            ..watch_pr()
        };
        assert_eq!(async_wait_class(&pr, "abc", true), None);
    }

    // ── x-b167 idle rule + message rendering ──────────────────────────────────

    fn bn(login: &str, class: NudgeClass, nudges: usize, newest: i64, span: i64) -> BotNudge {
        BotNudge {
            login: login.into(),
            class,
            review_handle: "@codex review".into(),
            ceiling: 3,
            nudges,
            newest_age_min: newest,
            span_min: span,
        }
    }
    fn bot_review_pr(login: &str, nudges: Vec<BotNudge>) -> PrInfo {
        PrInfo {
            number: 618,
            ci_conclusion: CiConclusion::Success,
            ci_has_pending: false,
            reviewed: false,
            review_skipped: false,
            missing_bots: vec![login.into()],
            bot_nudges: nudges,
            ..watch_pr()
        }
    }

    #[test]
    fn nudge_needs_nudge_blocks_and_names_the_command() {
        // AC1: not idlable; reason gives the exact gh command; no arm-and-tag hint.
        let pr = bot_review_pr(
            "chatgpt-codex-connector",
            vec![bn(
                "chatgpt-codex-connector",
                NudgeClass::NeedsNudge,
                0,
                0,
                0,
            )],
        );
        assert_eq!(async_wait_class(&pr, "abc", true), None);
        let reason = build_block_reason(&pr, "abc", true);
        assert!(
            reason.contains("gh pr comment 618 --body \"@codex review\""),
            "{reason}"
        );
        assert!(
            !reason.contains("harness-tracked watcher"),
            "no arm hint: {reason}"
        );
    }

    #[test]
    fn nudge_awaiting_idles_with_the_arm_hint() {
        // AC2: a genuine async wait - idlable, message says nudged + awaiting,
        // and the arm-and-tag ritual is present.
        let pr = bot_review_pr(
            "chatgpt-codex-connector",
            vec![bn("chatgpt-codex-connector", NudgeClass::Awaiting, 1, 3, 3)],
        );
        assert_eq!(async_wait_class(&pr, "abc", true), Some("review"));
        let reason = build_block_reason(&pr, "abc", true);
        assert!(reason.contains("nudged"), "{reason}");
        assert!(reason.contains("awaiting"), "{reason}");
        assert!(
            reason.contains("harness-tracked watcher"),
            "arm hint present: {reason}"
        );
    }

    #[test]
    fn nudge_unresponsive_blocks_and_names_optional_apps() {
        // AC3: not idlable; names the give-up + optional_apps; no arm-and-tag hint.
        let pr = bot_review_pr(
            "chatgpt-codex-connector",
            vec![bn(
                "chatgpt-codex-connector",
                NudgeClass::Unresponsive,
                3,
                20,
                47,
            )],
        );
        assert_eq!(async_wait_class(&pr, "abc", true), None);
        let reason = build_block_reason(&pr, "abc", true);
        assert!(
            reason.contains("did not review after 3 nudges over 47m"),
            "{reason}"
        );
        assert!(reason.contains("config.review.optional_apps"), "{reason}");
        assert!(reason.contains("do not arm a watcher"), "{reason}");
        assert!(
            !reason.contains("harness-tracked watcher"),
            "no arm hint: {reason}"
        );
    }

    #[test]
    fn nudge_not_nudgeable_keeps_todays_behavior() {
        // AC5: a non-nudgeable required bot keeps today's string + arm hint and
        // stays idlable, regardless of comment history.
        let pr = bot_review_pr(
            "gemini-code-assist",
            vec![bn("gemini-code-assist", NudgeClass::NotNudgeable, 0, 0, 0)],
        );
        assert_eq!(async_wait_class(&pr, "abc", true), Some("review"));
        let reason = build_block_reason(&pr, "abc", true);
        assert!(
            reason.contains("gemini-code-assist has not reviewed"),
            "{reason}"
        );
        assert!(
            reason.contains("harness-tracked watcher"),
            "arm hint present: {reason}"
        );
    }

    #[test]
    fn nudge_empty_classification_is_status_quo() {
        // A non-empty missing_bots with an EMPTY bot_nudges (not classified)
        // behaves exactly as pre-x-b167: idlable, today's string.
        let pr = bot_review_pr("chatgpt-codex-connector", vec![]);
        assert_eq!(async_wait_class(&pr, "abc", true), Some("review"));
        let reason = build_block_reason(&pr, "abc", true);
        assert!(reason.contains("has not reviewed"), "{reason}");
    }

    #[test]
    fn finding_block_reason_names_the_reply_handle() {
        // AC14: an unaddressed finding by a known bot names the handle a reply
        // must address, not just "reply in-thread".
        let pr = PrInfo {
            ci_conclusion: CiConclusion::Success,
            ci_has_pending: false,
            reviewed: false,
            unaddressed_findings: vec![Finding {
                id: 1,
                author: "chatgpt-codex-connector".into(),
                path: "a.rs".into(),
                line: 10,
                created_at: "2026-07-06T01:00:00Z".into(),
                severity: "P1",
            }],
            ..watch_pr()
        };
        let reason = build_block_reason(&pr, "abc", true);
        assert!(reason.contains("@chatgpt-codex-connector"), "{reason}");
    }

    #[test]
    fn nudge_post_is_suppressed_by_the_escape_hatch() {
        // The test suite must never comment on a real PR. With the guard set,
        // post_nudge_comment returns false without spawning gh (a bogus bin here
        // would otherwise error, not silently succeed).
        std::env::set_var("FNO_LOOPCHECK_NO_COMMENT", "1");
        let posted = post_nudge_comment(
            "/nonexistent/gh",
            std::path::Path::new("/tmp"),
            618,
            "@codex review",
        );
        std::env::remove_var("FNO_LOOPCHECK_NO_COMMENT");
        assert!(!posted);
    }

    #[test]
    fn unresponsive_bot_drives_the_giveup_message() {
        // AC13: the NoProgress message names the bot, the nudge count, and the
        // elapsed time instead of a bare fingerprint streak.
        let pr = bot_review_pr(
            "chatgpt-codex-connector",
            vec![bn(
                "chatgpt-codex-connector",
                NudgeClass::Unresponsive,
                3,
                20,
                47,
            )],
        );
        let n = unresponsive_bot(&pr).expect("an unresponsive bot");
        let msg = nudge_giveup_message(n);
        assert!(msg.contains("chatgpt-codex-connector"), "{msg}");
        assert!(msg.contains("3 nudges over 47m"), "{msg}");
        assert!(msg.contains("config.review.optional_apps"), "{msg}");
    }

    #[test]
    fn no_giveup_for_an_awaiting_bot() {
        let pr = bot_review_pr(
            "chatgpt-codex-connector",
            vec![bn("chatgpt-codex-connector", NudgeClass::Awaiting, 1, 3, 3)],
        );
        assert!(unresponsive_bot(&pr).is_none());
    }

    /// The exact state PR #618 sat in for ~15 turns: CI green, no required
    /// bots, no unaddressed findings, and a `reviewers: [sigma]` gate with no
    /// head-pinned attestation. `reviewers_ok` was the sole failing term.
    fn reviewers_gate_pr() -> PrInfo {
        PrInfo {
            ci_conclusion: CiConclusion::Success,
            ci_has_pending: false,
            reviewed: false,
            review_skipped: false,
            missing_bots: vec![],
            bot_nudges: vec![],
            unaddressed_findings: vec![],
            unattested_reviewers: vec![UnattestedReviewer {
                name: "sigma".to_string(),
                superseded_head: None,
                failed_at_head: false,
            }],
            ..watch_pr()
        }
    }

    #[test]
    fn block_reason_names_the_reviewers_gate_not_a_bot() {
        // AC2: the old string claimed a bot had not reviewed while
        // required_bots was empty and the real blocker was local.
        let reason = build_block_reason(&reviewers_gate_pr(), "abc", true);
        assert!(reason.contains("reviewers gate unmet"), "got: {reason}");
        assert!(reason.contains("sigma"), "got: {reason}");
        assert!(reason.contains("/fno:review sigma"), "got: {reason}");
        assert!(!reason.contains("bot reviewer"), "got: {reason}");
    }

    #[test]
    fn block_reason_names_the_local_peer_invocation() {
        let mut pr = reviewers_gate_pr();
        pr.unattested_reviewers[0].name = LOCAL_PEER_REVIEWER.to_string();
        let reason = build_block_reason(&pr, "abc", true);
        assert!(
            reason.contains("/fno:review peer --attest"),
            "got: {reason}"
        );
        assert!(
            !reason.contains("wait on a GitHub reviewer"),
            "got: {reason}"
        );
    }

    #[test]
    fn block_reason_explains_same_model_local_peer_refusal() {
        let mut pr = reviewers_gate_pr();
        pr.unattested_reviewers[0].name = SAME_MODEL_LOCAL_PEER_SENTINEL.to_string();
        let reason = build_block_reason(&pr, "abc", true);
        assert!(
            reason.contains("configure a cross-model peer"),
            "got: {reason}"
        );
        assert!(
            !reason.contains(SAME_MODEL_LOCAL_PEER_SENTINEL),
            "got: {reason}"
        );
    }

    #[test]
    fn block_reason_reviewers_gate_emits_no_idle_ritual() {
        // AC3: async_wait_class already excluded this blocker from idling
        // (watch_idle_rejects_local_attestation_review_gate), so prescribing
        // the arm-and-tag ritual here is the code contradicting itself.
        let pr = reviewers_gate_pr();
        assert_eq!(async_wait_class(&pr, "abc", true), None);
        let reason = build_block_reason(&pr, "abc", true);
        assert!(!reason.contains("<watching"), "got: {reason}");
        assert!(
            !reason.contains("Arm a harness-tracked watcher"),
            "got: {reason}"
        );
        assert!(!reason.contains("gh pr checks"), "got: {reason}");
    }

    #[test]
    fn block_reason_names_a_superseded_attestation_head() {
        // A session that ran sigma and then pushed must not read "you never
        // ran sigma"; name the head the pass is pinned to.
        let pr = PrInfo {
            unattested_reviewers: vec![UnattestedReviewer {
                name: "sigma".to_string(),
                superseded_head: Some("0123456789abcdef".to_string()),
                failed_at_head: false,
            }],
            ..reviewers_gate_pr()
        };
        let reason = build_block_reason(&pr, "abc", true);
        assert!(reason.contains("01234567"), "got: {reason}");
        assert!(reason.contains("superseded"), "got: {reason}");
    }

    #[test]
    fn block_reason_generic_review_fallback_has_no_idle_ritual() {
        // The fallback is only reachable with an EMPTY missing_bots, which
        // async_wait_class refuses to idle. It must not teach the ritual either.
        let pr = PrInfo {
            unattested_reviewers: vec![],
            ..reviewers_gate_pr()
        };
        let reason = build_block_reason(&pr, "abc", true);
        assert!(!reason.contains("<watching"), "got: {reason}");
        assert!(!reason.contains("bot reviewer"), "got: {reason}");
    }

    #[test]
    fn block_reason_missing_bot_still_teaches_the_ritual() {
        // AC7-adjacent regression: a REAL outstanding GitHub bot, and nothing
        // local outstanding, is a valid async wait and keeps today's message.
        let pr = PrInfo {
            missing_bots: vec!["chatgpt-codex-connector".into()],
            bot_nudges: vec![],
            unattested_reviewers: vec![],
            ..reviewers_gate_pr()
        };
        let reason = build_block_reason(&pr, "abc", true);
        assert!(reason.contains("chatgpt-codex-connector"), "got: {reason}");
        assert!(reason.contains("<watching"), "got: {reason}");
    }

    #[test]
    fn block_reason_local_work_outranks_a_bot_wait() {
        // Codex review of this PR: with a bot AND a local reviewer both
        // outstanding, naming only the bot hides the half the session can act
        // on now. Worse, if the bot never posts, the local work never happens
        // and the run dies on budget with the gate still unmet - the #618 shape
        // this node exists to delete.
        let pr = PrInfo {
            missing_bots: vec!["chatgpt-codex-connector".into()],
            bot_nudges: vec![],
            ..reviewers_gate_pr()
        };
        let reason = build_block_reason(&pr, "abc", true);
        assert!(reason.contains("reviewers gate unmet"), "got: {reason}");
        assert!(!reason.contains("<watching"), "got: {reason}");
        // Once the local half is attested, the bot wait is the sole blocker and
        // the arm-and-tag message returns.
        let after = PrInfo {
            unattested_reviewers: vec![],
            ..pr
        };
        assert!(build_block_reason(&after, "abc", true).contains("<watching"));
    }

    #[test]
    fn reviewers_gate_stays_fail_closed() {
        // AC7: promoting the predicate's return value to a list must not move
        // the gate. Missing file, missing event, stale head, and a `fail`
        // verdict all still leave the reviewer unsatisfied.
        let tmp = tempfile::tempdir().unwrap();
        let missing = tmp.path().join("absent.jsonl");
        let sigma = vec!["sigma".to_string()];
        assert!(!unattested_reviewers(&missing, &sigma, "h").is_empty());

        let stale = tmp.path().join("stale.jsonl");
        std::fs::write(
            &stale,
            r#"{"type":"review_attestation","data":{"reviewer":"sigma","head_sha":"OLD","verdict":"pass"}}"#,
        )
        .unwrap();
        let out = unattested_reviewers(&stale, &sigma, "NEW");
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].superseded_head.as_deref(), Some("OLD"));
        assert!(!out[0].failed_at_head);

        let failed = tmp.path().join("fail.jsonl");
        std::fs::write(
            &failed,
            r#"{"type":"review_attestation","data":{"reviewer":"sigma","head_sha":"h","verdict":"fail"}}"#,
        )
        .unwrap();
        let out = unattested_reviewers(&failed, &sigma, "h");
        assert_eq!(out.len(), 1);
        // A head-pinned fail is not a superseded pass; do not offer a stale head.
        assert_eq!(out[0].superseded_head, None);
        // ...but it IS an attestation at this head, and the message says so
        // rather than claiming none exists. Pinned at the PARSER: the message
        // test hand-builds the struct and never exercises this derivation, so
        // `failed_at_head: false` survived the whole suite before this line.
        assert!(
            out[0].failed_at_head,
            "a fail at HEAD must be reported as such"
        );
    }

    #[test]
    fn unpinned_attestation_never_counts_as_evidence() {
        // codex P1 on this PR: defaulting a missing head_sha to "" made an
        // unpinned event MATCH a caller whose own head_sha is "", turning
        // no-evidence into a pass.
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("e.jsonl");
        std::fs::write(
            &p,
            r#"{"type":"review_attestation","data":{"reviewer":"sigma","verdict":"pass"}}"#,
        )
        .unwrap();
        let out = unattested_reviewers(&p, &["sigma".to_string()], "");
        assert_eq!(out.len(), 1, "unpinned evidence must not satisfy the gate");
        assert_eq!(out[0].superseded_head, None);
    }

    #[test]
    fn a_failed_old_head_is_not_reported_as_superseded() {
        // codex P2: "attested at X, superseded" implies a prior PASS. An
        // old-head fail rendered that way invents a review that never passed.
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("e.jsonl");
        std::fs::write(
            &p,
            r#"{"type":"review_attestation","data":{"reviewer":"sigma","head_sha":"OLD","verdict":"fail"}}"#,
        )
        .unwrap();
        let out = unattested_reviewers(&p, &["sigma".to_string()], "NEW");
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].superseded_head, None);
    }

    #[test]
    fn a_corrupt_attestation_line_is_counted_and_named() {
        // A torn write leaves an unparseable review_attestation in the file.
        // The gate must still fail closed, but reporting "no head-pinned
        // review_attestation" over a corrupt one is the same class of lie this
        // node deletes. The sibling review_finding scanner already counts its
        // malformed lines; this one did not.
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("e.jsonl");
        std::fs::write(
            &p,
            concat!(
                r#"{"type":"review_attestation","data":{"reviewer":"sigma","hea"#,
                "\n",
                r#"{"type":"loop_check","data":{}}"#,
            ),
        )
        .unwrap();
        let (out, malformed) = unattested_reviewers_scan(&p, &["sigma".to_string()], "h");
        assert_eq!(out.len(), 1, "a corrupt line never satisfies the gate");
        assert_eq!(malformed, 1, "and it is counted, not silently dropped");

        let pr = PrInfo {
            malformed_attestations: malformed,
            ..reviewers_gate_pr()
        };
        let reason = build_block_reason(&pr, "abc", true);
        assert!(
            reason.contains("unparseable attestation line"),
            "got: {reason}"
        );

        // A clean file adds nothing to the message.
        std::fs::write(&p, r#"{"type":"loop_check","data":{}}"#).unwrap();
        assert_eq!(
            unattested_reviewers_scan(&p, &["sigma".to_string()], "h").1,
            0
        );
        assert!(!build_block_reason(&reviewers_gate_pr(), "abc", true)
            .contains("unparseable attestation line"));
    }

    #[test]
    fn a_revoked_pass_falls_back_to_an_older_passing_head() {
        // codex P2: `pass A, pass B, fail B` with HEAD C. A single "most recent
        // pass" entry overwrites A with B and then drops B, so the message
        // claims no prior pass while A is still a real one - the misleading
        // guidance this whole node exists to delete, reappearing in exactly the
        // multi-round review/fix cycle that produces this sequence.
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("e.jsonl");
        let line = |head: &str, verdict: &str| {
            format!(
                r#"{{"type":"review_attestation","data":{{"reviewer":"sigma","head_sha":"{head}","verdict":"{verdict}"}}}}"#
            )
        };
        std::fs::write(
            &p,
            [
                line("AAA", "pass"),
                line("BBB", "pass"),
                line("BBB", "fail"),
            ]
            .join("\n"),
        )
        .unwrap();
        let out = unattested_reviewers(&p, &["sigma".to_string()], "CCC");
        assert_eq!(out.len(), 1);
        assert_eq!(
            out[0].superseded_head.as_deref(),
            Some("AAA"),
            "a still-valid older pass must survive a newer head's retraction"
        );

        // The newest STILL-PASSING head wins when several are valid.
        std::fs::write(&p, [line("AAA", "pass"), line("BBB", "pass")].join("\n")).unwrap();
        let out = unattested_reviewers(&p, &["sigma".to_string()], "CCC");
        assert_eq!(out[0].superseded_head.as_deref(), Some("BBB"));

        // Every old head retracted -> nothing to name.
        std::fs::write(
            &p,
            [
                line("AAA", "pass"),
                line("BBB", "pass"),
                line("BBB", "fail"),
                line("AAA", "fail"),
            ]
            .join("\n"),
        )
        .unwrap();
        let out = unattested_reviewers(&p, &["sigma".to_string()], "CCC");
        assert_eq!(out[0].superseded_head, None);
    }

    #[test]
    fn a_later_fail_revokes_the_superseded_pass_for_that_head() {
        // Append-ordered pass-then-fail on the SAME old head. The pass was
        // recorded as superseded and the fail merely skipped, so the message
        // kept claiming that head was successfully attested after its latest
        // verdict retracted exactly that (codex P2 on this PR).
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("e.jsonl");
        std::fs::write(
            &p,
            concat!(
                r#"{"type":"review_attestation","data":{"reviewer":"sigma","head_sha":"OLD","verdict":"pass"}}"#,
                "\n",
                r#"{"type":"review_attestation","data":{"reviewer":"sigma","head_sha":"OLD","verdict":"fail"}}"#,
            ),
        )
        .unwrap();
        let out = unattested_reviewers(&p, &["sigma".to_string()], "NEW");
        assert_eq!(out.len(), 1);
        assert_eq!(
            out[0].superseded_head, None,
            "a retracted pass is not evidence"
        );

        // A re-run pass after the fail restores it: revocation is latest-wins,
        // not a one-way latch.
        std::fs::write(
            &p,
            concat!(
                r#"{"type":"review_attestation","data":{"reviewer":"sigma","head_sha":"OLD","verdict":"pass"}}"#,
                "\n",
                r#"{"type":"review_attestation","data":{"reviewer":"sigma","head_sha":"OLD","verdict":"fail"}}"#,
                "\n",
                r#"{"type":"review_attestation","data":{"reviewer":"sigma","head_sha":"OLD","verdict":"pass"}}"#,
            ),
        )
        .unwrap();
        let out = unattested_reviewers(&p, &["sigma".to_string()], "NEW");
        assert_eq!(out[0].superseded_head.as_deref(), Some("OLD"));
    }

    #[test]
    fn short_sha_never_panics_on_multibyte() {
        // codex P2: `&s[..8]` panics when byte 8 lands inside a character, and
        // superseded_head comes from a user-writable events.jsonl.
        assert_eq!(short_sha("0123456789ab"), "01234567");
        assert_eq!(short_sha("abc"), "abc");
        assert_eq!(short_sha(""), "");
        assert_eq!(short_sha("1234567\u{e9}xyz"), "1234567\u{e9}");
        let pr = PrInfo {
            unattested_reviewers: vec![UnattestedReviewer {
                name: "sigma".to_string(),
                superseded_head: Some("1234567\u{e9}abc".to_string()),
                failed_at_head: false,
            }],
            ..reviewers_gate_pr()
        };
        build_block_reason(&pr, "1234567\u{e9}abc", true);
    }

    #[test]
    fn watcher_hint_never_contradicts_the_idle_classifier() {
        // codex P1: the missing-bot branch emitted the ritual unconditionally,
        // including for states async_wait_class refuses to idle (an unaddressed
        // finding, or an open operator finding). The hint is now derived from
        // that same classifier, so the two agree by construction.
        let bot_only = PrInfo {
            missing_bots: vec!["chatgpt-codex-connector".into()],
            bot_nudges: vec![],
            unattested_reviewers: vec![],
            ..reviewers_gate_pr()
        };
        for (label, pr, open_empty) in [
            // Reaches the FINDINGS branch, not the bot branch: unaddressed
            // findings render first. Kept because the invariant under test is
            // "no hint for a non-idlable state", which holds branch-wide - but
            // it is the case below that reaches `missing_bots`, so that one is
            // what would catch a reintroduced unconditional `arm_watch_hint`
            // there. A sigma round caught this test silently losing its teeth
            // when the branch order moved out from under it.
            (
                "bot + unaddressed finding (renders as the finding)",
                PrInfo {
                    missing_bots: vec!["chatgpt-codex-connector".into()],
                    bot_nudges: vec![],
                    unattested_reviewers: vec![],
                    unaddressed_findings: vec![Finding {
                        id: 1,
                        author: "codex".into(),
                        path: "a.rs".into(),
                        line: 1,
                        created_at: "2026-07-27T00:00:00Z".into(),
                        severity: "P1",
                    }],
                    ..reviewers_gate_pr()
                },
                true,
            ),
            (
                // The one that DOES reach `missing_bots` while non-idlable.
                "bot + open operator finding",
                PrInfo {
                    missing_bots: vec!["chatgpt-codex-connector".into()],
                    bot_nudges: vec![],
                    unattested_reviewers: vec![],
                    ..reviewers_gate_pr()
                },
                false,
            ),
        ] {
            let reason = build_block_reason(&pr, "abc", open_empty);
            assert_eq!(async_wait_class(&pr, "abc", open_empty), None, "{label}");
            assert!(!reason.contains("<watching"), "{label}: {reason}");
        }
        // The genuinely idlable state keeps the ritual.
        assert_eq!(async_wait_class(&bot_only, "abc", true), Some("review"));
        assert!(build_block_reason(&bot_only, "abc", true).contains("<watching"));
    }

    #[test]
    fn an_unaddressed_finding_is_named_before_the_reviewers_gate() {
        // Sigma review of this PR: addressing an inline finding MOVES HEAD,
        // which supersedes any attestation produced first. Naming the reviewer
        // first would make the session run the panel twice.
        let pr = PrInfo {
            unaddressed_findings: vec![Finding {
                id: 1,
                author: "codex".into(),
                path: "a.rs".into(),
                line: 7,
                created_at: "2026-07-27T00:00:00Z".into(),
                severity: "P1",
            }],
            ..reviewers_gate_pr()
        };
        let reason = build_block_reason(&pr, "abc", true);
        assert!(reason.contains("unaddressed"), "got: {reason}");
        assert!(!reason.contains("reviewers gate unmet"), "got: {reason}");
        // With the finding cleared, the reviewers gate is what is named.
        let after = PrInfo {
            unaddressed_findings: vec![],
            ..pr
        };
        assert!(build_block_reason(&after, "abc", true).contains("reviewers gate unmet"));
    }

    #[test]
    fn a_failed_attestation_at_this_head_is_not_reported_as_absent() {
        // "no head-pinned review_attestation" reads as "you never ran it" to a
        // session that ran the reviewer and was told no.
        let pr = PrInfo {
            unattested_reviewers: vec![UnattestedReviewer {
                name: "sigma".to_string(),
                superseded_head: None,
                failed_at_head: true,
            }],
            ..reviewers_gate_pr()
        };
        let reason = build_block_reason(&pr, "abc", true);
        assert!(reason.contains("verdict NOT pass"), "got: {reason}");
    }

    #[test]
    fn the_stop_gate_marks_declare_as_a_self_cert() {
        // AC5: every surface that prints `declare` says it asserts nothing.
        // The Rust block message is such a surface.
        let pr = PrInfo {
            unattested_reviewers: vec![UnattestedReviewer {
                name: "declare".to_string(),
                superseded_head: None,
                failed_at_head: false,
            }],
            ..reviewers_gate_pr()
        };
        let reason = build_block_reason(&pr, "abc", true);
        assert!(reason.contains("self-cert"), "got: {reason}");
        assert!(
            reason.contains("asserts no review evidence"),
            "got: {reason}"
        );
        // A real reviewer carries no such mark.
        assert!(!build_block_reason(&reviewers_gate_pr(), "abc", true).contains("self-cert"));
    }

    #[test]
    fn an_empty_head_sha_never_becomes_a_superseded_head() {
        // Option<String> cannot say "non-empty", so normalize at construction
        // rather than leaving is_empty() as a convention every reader re-derives.
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("e.jsonl");
        std::fs::write(
            &p,
            r#"{"type":"review_attestation","data":{"reviewer":"sigma","head_sha":"","verdict":"pass"}}"#,
        )
        .unwrap();
        let out = unattested_reviewers(&p, &["sigma".to_string()], "NEW");
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].superseded_head, None);
    }

    #[test]
    fn an_outstanding_local_reviewer_is_never_an_idlable_wait() {
        // The classifier half of the same fix: with a bot AND a local reviewer
        // outstanding, a stray <watching> tag must not park the session on work
        // it could do now.
        let pr = PrInfo {
            missing_bots: vec!["chatgpt-codex-connector".into()],
            bot_nudges: vec![],
            ..reviewers_gate_pr()
        };
        assert_eq!(async_wait_class(&pr, "abc", true), None);
    }

    #[test]
    fn reviewer_invocations_cover_the_descriptor_table() {
        // The parity script enforces this against the Python side in CI; this
        // keeps the Rust half self-consistent at unit-test speed.
        for (name, inv, self_cert) in REVIEWER_INVOCATIONS {
            assert!(!inv.is_empty(), "{name} has no invocation");
            assert_eq!(reviewer_invocation(name), Some((*inv, *self_cert)));
        }
        assert_eq!(reviewer_invocation("teleport"), None);
        // AC5: the ONE self-cert must stay visibly marked on this surface too.
        assert_eq!(reviewer_invocation("declare").map(|(_, sc)| sc), Some(true));
        assert_eq!(reviewer_invocation("sigma").map(|(_, sc)| sc), Some(false));
    }

    #[test]
    fn unwatched_async_nudge_review_uses_review_aware_watcher() {
        // codex P2: the review-wait watcher must poll REVIEW state, not
        // `gh pr checks --watch` (which exits instantly when CI is green).
        let hint = arm_watch_hint(404, "review");
        assert!(hint.contains("--json reviews"), "got: {hint}");
        assert!(!hint.contains("gh pr checks"), "got: {hint}");
        // The CI-wait watcher still uses checks --watch.
        let ci_hint = arm_watch_hint(404, "ci");
        assert!(ci_hint.contains("gh pr checks"), "got: {ci_hint}");
    }

    #[test]
    fn watch_idle_rejects_head_mismatch() {
        // AC2-ERR: unpushed work (PR head != local HEAD) is never async-wait.
        assert_eq!(async_wait_class(&watch_pr(), "def", true), None);
    }

    #[test]
    fn watch_idle_rejects_ci_red() {
        // AC1-ERR: settled-red CI (no pending) blocks, never idles.
        let pr = PrInfo {
            ci_conclusion: CiConclusion::Failure(Some("unit".into())),
            ci_has_pending: false,
            ..watch_pr()
        };
        assert_eq!(async_wait_class(&pr, "abc", true), None);
    }

    #[test]
    fn watch_idle_rejects_unaddressed_finding() {
        // AC2-ERR: an unaddressed blocking inline finding is not async-wait.
        let pr = PrInfo {
            unaddressed_findings: vec![Finding {
                id: 1,
                author: "codex".into(),
                path: "a.rs".into(),
                line: 1,
                created_at: "none".into(),
                severity: "P1",
            }],
            ..watch_pr()
        };
        assert_eq!(async_wait_class(&pr, "abc", true), None);
    }

    #[test]
    fn watch_idle_rejects_open_operator_finding() {
        // An open operator review_finding for the node also blocks idling.
        assert_eq!(async_wait_class(&watch_pr(), "abc", false), None);
    }

    #[test]
    fn watch_idle_rejects_non_open_pr() {
        // A merged/closed PR is not an async wait (green+merged is DonePRGreen).
        let pr = PrInfo {
            state: PrState::Merged,
            ..watch_pr()
        };
        assert_eq!(async_wait_class(&pr, "abc", true), None);
    }

    #[test]
    fn watch_idle_window_defaults_clamps_and_slacks() {
        // Default (no tag timeout): 30m + 12m slack.
        assert_eq!(watch_window_ms(None), 30 * 60_000 + WATCH_SLACK_MS);
        // Honored within range.
        assert_eq!(watch_window_ms(Some("30m")), 30 * 60_000 + WATCH_SLACK_MS);
        // Below the 5m floor clamps up.
        assert_eq!(watch_window_ms(Some("1m")), 5 * 60_000 + WATCH_SLACK_MS);
        // Above the 2h ceiling clamps down.
        assert_eq!(watch_window_ms(Some("5h")), 2 * 3_600_000 + WATCH_SLACK_MS);
        // Garbage falls back to the default.
        assert_eq!(watch_window_ms(Some("soon")), 30 * 60_000 + WATCH_SLACK_MS);
    }

    #[test]
    fn fingerprint_format() {
        let fp = make_fingerprint("sha123", "OPEN", "SUCCESS", "2026-06-05T01:00:00Z");
        assert_eq!(fp, "sha123|OPEN|SUCCESS|2026-06-05T01:00:00Z");
    }

    #[test]
    fn ci_conclusion_failure_extracts_name() {
        let checks = serde_json::json!([
            {"name": "unit-tests", "state": "FAILURE", "bucket": "fail"}
        ]);
        let result = compute_ci_conclusion(&checks).unwrap();
        assert_eq!(
            result,
            CiConclusion::Failure(Some("unit-tests".to_string()))
        );
        let rendered = result.render();
        assert!(rendered.starts_with("FAILURE:"), "got: {rendered}");
        assert!(rendered.contains("unit-tests"), "got: {rendered}");
    }

    /// A cancelled check is a failure, and a skipping sibling never masks it.
    #[test]
    fn ci_conclusion_cancel_is_failure() {
        let checks = serde_json::json!([
            {"name": "ci", "state": "SUCCESS", "bucket": "pass"},
            {"name": "deploy", "state": "CANCELLED", "bucket": "cancel"}
        ]);
        assert_eq!(
            compute_ci_conclusion(&checks).unwrap(),
            CiConclusion::Failure(Some("deploy".to_string()))
        );
    }

    /// pass + skipping rolls up green; a pending bucket blocks it.
    #[test]
    fn ci_conclusion_bucket_vocabulary() {
        let green = serde_json::json!([
            {"name": "ci", "state": "SUCCESS", "bucket": "pass"},
            {"name": "publish", "state": "SKIPPED", "bucket": "skipping"}
        ]);
        assert_eq!(
            compute_ci_conclusion(&green).unwrap(),
            CiConclusion::Success
        );

        let pending = serde_json::json!([
            {"name": "ci", "state": "SUCCESS", "bucket": "pass"},
            {"name": "smoke", "state": "IN_PROGRESS", "bucket": "pending"}
        ]);
        assert_eq!(
            compute_ci_conclusion(&pending).unwrap(),
            CiConclusion::Pending
        );
    }

    /// An unknown or missing bucket fails closed as Pending, never green.
    #[test]
    fn ci_conclusion_unknown_bucket_fails_closed() {
        let unknown = serde_json::json!([
            {"name": "ci", "state": "SUCCESS", "bucket": "mystery"}
        ]);
        assert_eq!(
            compute_ci_conclusion(&unknown).unwrap(),
            CiConclusion::Pending
        );

        let missing = serde_json::json!([{"name": "ci", "state": "SUCCESS"}]);
        assert_eq!(
            compute_ci_conclusion(&missing).unwrap(),
            CiConclusion::Pending
        );
    }

    #[test]
    fn ci_conclusion_empty_returns_none() {
        let checks = serde_json::json!([]);
        let result = compute_ci_conclusion(&checks).unwrap();
        assert_eq!(result, CiConclusion::None);
        assert_eq!(result.render(), "none");
    }

    #[test]
    fn ci_conclusion_all_success() {
        let checks = serde_json::json!([
            {"name": "ci", "state": "SUCCESS", "bucket": "pass"}
        ]);
        let result = compute_ci_conclusion(&checks).unwrap();
        assert_eq!(result, CiConclusion::Success);
        assert_eq!(result.render(), "SUCCESS");
    }

    // ── DoneAwaitingMerge classifier ───────────────────────────────────────

    #[test]
    fn failing_check_names_collects_fail_and_cancel_only() {
        let checks = serde_json::json!([
            {"name": "smoke",        "bucket": "fail"},
            {"name": "loc-ratchet",  "bucket": "pass"},
            {"name": "prompt-drift", "bucket": "cancel"},
            {"name": "self-test",    "bucket": "pending"},
            {"name": "doc-colo",     "bucket": "skipping"},
        ]);
        let mut got = failing_check_names(&checks);
        got.sort();
        assert_eq!(got, vec!["prompt-drift".to_string(), "smoke".to_string()]);
    }

    #[test]
    fn failing_check_names_empty_when_all_green() {
        let checks = serde_json::json!([{"name": "smoke", "bucket": "pass"}]);
        assert!(failing_check_names(&checks).is_empty());
        // Malformed input never panics, yields empty.
        assert!(failing_check_names(&serde_json::json!({})).is_empty());
    }

    #[test]
    fn ci_has_pending_gates_partial_ci() {
        // One check failed while another still runs -> pending (must hold, not
        // terminate: the pending job could be the session's own new red).
        let partial = serde_json::json!([
            {"name": "smoke",   "bucket": "fail"},
            {"name": "rust-ci", "bucket": "pending"},
        ]);
        assert!(ci_has_pending_checks(&partial));
        // Fully settled red -> no pending -> eligible for the terminal.
        let settled = serde_json::json!([
            {"name": "smoke",   "bucket": "fail"},
            {"name": "rust-ci", "bucket": "pass"},
            {"name": "doc",     "bucket": "skipping"},
        ]);
        assert!(!ci_has_pending_checks(&settled));
        // Unrecognized bucket is treated as pending (fail safe).
        let unknown = serde_json::json!([{"name": "x", "bucket": "queued"}]);
        assert!(ci_has_pending_checks(&unknown));
        // Malformed input never panics.
        assert!(!ci_has_pending_checks(&serde_json::json!({})));
    }

    #[test]
    fn parse_failing_run_ids_only_failures_on_head_sha() {
        // Only failures whose headSha matches the current main HEAD count. Run 4
        // failed but belongs to an OLDER commit (headSha "old"), so a check it
        // failed that main HEAD has since fixed must NOT be classified pre-existing.
        let list = serde_json::json!([
            {"databaseId": 1, "conclusion": "failure", "headSha": "head"},
            {"databaseId": 2, "conclusion": "success", "headSha": "head"},
            {"databaseId": 3, "conclusion": "cancelled", "headSha": "head"},
            {"databaseId": 4, "conclusion": "failure", "headSha": "old"},
            {"databaseId": 5, "conclusion": "failure", "headSha": "head"},
        ]);
        assert_eq!(parse_failing_run_ids(&list, "head"), vec![1, 5]);
        // A different HEAD sha selects that commit's failures only.
        assert_eq!(parse_failing_run_ids(&list, "old"), vec![4]);
    }

    #[test]
    fn parse_failing_job_names_only_failed_jobs() {
        let view = serde_json::json!({
            "jobs": [
                {"name": "codex",   "conclusion": "success"},
                {"name": "cargo test + schema parity", "conclusion": "failure"},
                {"name": "gemini",  "conclusion": "failure"},
            ]
        });
        let mut got = parse_failing_job_names(&view);
        got.sort();
        assert_eq!(
            got,
            vec![
                "cargo test + schema parity".to_string(),
                "gemini".to_string()
            ]
        );
        // No jobs key -> empty, never panics.
        assert!(parse_failing_job_names(&serde_json::json!({})).is_empty());
    }

    /// AC1-HP: the core shape - PR fails only the one check main also fails.
    #[test]
    fn subset_rule_pr_failing_is_covered_by_main() {
        let pr = vec!["cargo test + schema parity".to_string()];
        let main = vec![
            "cargo test + schema parity".to_string(),
            "some other main-only red".to_string(),
        ];
        assert!(is_pre_existing_main_red(&pr, &main));
    }

    /// AC1-EDGE: a PR-unique failing check (its own breakage) blocks the terminal.
    #[test]
    fn subset_rule_pr_unique_red_blocks() {
        let pr = vec![
            "cargo test + schema parity".to_string(),
            "fmt gate".to_string(), // the session's own breakage
        ];
        let main = vec!["cargo test + schema parity".to_string()];
        assert!(!is_pre_existing_main_red(&pr, &main));
    }

    #[test]
    fn subset_rule_empty_pr_failing_never_eligible() {
        // Empty PR-failing is the DonePRGreen path, not this one.
        assert!(!is_pre_existing_main_red(&[], &["x".to_string()]));
        // Non-empty PR vs green main (empty) -> hold.
        assert!(!is_pre_existing_main_red(&["x".to_string()], &[]));
    }

    #[test]
    fn already_emitted_awaiting_merge_detects_prior_and_absence() {
        let dir = tempfile::tempdir().unwrap();
        let events = dir.path().join("events.jsonl");
        // Absent file -> false (fail open).
        assert!(!already_emitted_awaiting_merge(&events, "sess-A"));
        // A DonePRGreen termination for the same session must NOT count.
        std::fs::write(
            &events,
            "{\"type\":\"termination\",\"data\":{\"session_id\":\"sess-A\",\"reason\":\"DonePRGreen\"}}\n",
        )
        .unwrap();
        assert!(!already_emitted_awaiting_merge(&events, "sess-A"));
        // A prior DoneAwaitingMerge for sess-A counts; a different session does not.
        std::fs::write(
            &events,
            "{\"type\":\"termination\",\"data\":{\"session_id\":\"sess-A\",\"reason\":\"DoneAwaitingMerge\"}}\n",
        )
        .unwrap();
        assert!(already_emitted_awaiting_merge(&events, "sess-A"));
        assert!(!already_emitted_awaiting_merge(&events, "sess-B"));
    }

    /// AC5-HP: enums parse known gh strings.
    #[test]
    fn pr_state_parses_known_gh_strings() {
        assert_eq!(PrState::from_gh_str("OPEN"), PrState::Open);
        assert_eq!(PrState::from_gh_str("MERGED"), PrState::Merged);
        assert_eq!(PrState::from_gh_str("CLOSED"), PrState::Closed);
        assert_eq!(PrState::from_gh_str("none"), PrState::None);
    }

    /// AC5-EDGE: an unexpected gh state string maps to PrState::None
    /// (fail-closed), never panics.
    #[test]
    fn pr_state_unknown_string_fails_closed() {
        assert_eq!(PrState::from_gh_str("DRAFT"), PrState::None);
        assert_eq!(PrState::from_gh_str(""), PrState::None);
        assert_eq!(PrState::from_gh_str("open"), PrState::None);
    }

    /// AC5-UI: as_str/render reproduce the exact legacy fingerprint vocabulary.
    #[test]
    fn enum_rendering_byte_identical_to_legacy_strings() {
        assert_eq!(PrState::Open.as_str(), "OPEN");
        assert_eq!(PrState::Merged.as_str(), "MERGED");
        assert_eq!(PrState::Closed.as_str(), "CLOSED");
        assert_eq!(PrState::None.as_str(), "none");
        assert_eq!(CiConclusion::Success.render(), "SUCCESS");
        assert_eq!(
            CiConclusion::Failure(Some("lint".into())).render(),
            "FAILURE:lint"
        );
        assert_eq!(CiConclusion::Failure(None).render(), "FAILURE");
        assert_eq!(CiConclusion::Pending.render(), "PENDING");
        assert_eq!(CiConclusion::Skipped.render(), "skipped");
        assert_eq!(CiConclusion::None.render(), "none");
    }

    /// AC5-ERR: required flags validated in parse_args, which returns Err.
    #[test]
    fn parse_args_missing_required_flags_err() {
        let no_state: Vec<String> = vec![
            "loop-check".into(),
            "--transcript".into(),
            "/t".into(),
            "--cwd".into(),
            "/c".into(),
        ];
        assert_eq!(
            parse_args(&no_state).unwrap_err(),
            "--state is required".to_string()
        );

        let no_transcript: Vec<String> = vec!["loop-check".into(), "--state".into(), "/s".into()];
        assert_eq!(
            parse_args(&no_transcript).unwrap_err(),
            "--transcript is required".to_string()
        );

        let no_cwd: Vec<String> = vec![
            "loop-check".into(),
            "--state".into(),
            "/s".into(),
            "--transcript".into(),
            "/t".into(),
        ];
        assert_eq!(
            parse_args(&no_cwd).unwrap_err(),
            "--cwd is required".to_string()
        );
    }

    /// AC5-FR: an unknown flag is tolerated (forward-compat for the shim).
    #[test]
    fn parse_args_unknown_flag_tolerated() {
        let args: Vec<String> = vec![
            "loop-check".into(),
            "--state".into(),
            "/s".into(),
            "--transcript".into(),
            "/t".into(),
            "--cwd".into(),
            "/c".into(),
            "--future-flag=whatever".into(),
            "--another-unknown".into(),
            "value".into(),
        ];
        let parsed = parse_args(&args).expect("unknown flags must be ignored");
        assert_eq!(parsed.state_path, PathBuf::from("/s"));
        assert_eq!(parsed.transcript_path, PathBuf::from("/t"));
        assert_eq!(parsed.cwd, PathBuf::from("/c"));
    }

    #[test]
    fn budget_flat_key_enforces_cost_cap_ab41b13d9d() {
        // Prove the flat budget_cap key enforces as cost cap for BOTH attended and
        // unattended - this is the ab-41b13d9d fold-in test.
        let settings_cfg = "budget_cap = 0.10\n";
        let settings = parse_settings(settings_cfg);
        assert_eq!(settings.flat_budget_cap, Some(Ok(0.10)));
        // No nested blocks configured
        assert!(settings.attended_cost_cap_usd.is_none());
        assert!(settings.unattended_cost_cap_usd.is_none());
        // The budget resolver picks flat_budget_cap as cost cap fallback
        // for both attended=true and attended=false (tested in check_budget)

        let manifest_att = Manifest {
            session_id: Some("s1".into()),
            created_at: Some("2026-06-05T00:00:00Z".into()),
            attended: true,
            ..Default::default()
        };
        let manifest_unatt = Manifest {
            session_id: Some("s1".into()),
            created_at: Some("2026-06-05T00:00:00Z".into()),
            attended: false,
            ..Default::default()
        };

        // Ledger with cost > 0.10
        let tmp = tempfile::tempdir().unwrap();
        let ledger = tmp.path().join("ledger.json");
        std::fs::write(&ledger, r#"[{"session_id":"s1","cost_usd":0.50}]"#).unwrap();

        let now: DateTime<Utc> = "2026-06-05T01:00:00Z".parse().unwrap();

        assert_eq!(
            check_budget(&manifest_att, &settings, &now, &ledger),
            Some(BudgetTrip::Cost),
            "flat budget_cap must enforce for attended"
        );
        assert_eq!(
            check_budget(&manifest_unatt, &settings, &now, &ledger),
            Some(BudgetTrip::Cost),
            "flat budget_cap must enforce for unattended"
        );
    }

    #[test]
    fn is_bot_reviewer_known_patterns() {
        assert!(is_bot_reviewer("gemini-code-assist[bot]", &[]));
        assert!(is_bot_reviewer("chatgpt-codex-connector", &[]));
        assert!(is_bot_reviewer("some-bot[bot]", &[]));
        assert!(!is_bot_reviewer("human-reviewer", &[]));
    }

    #[test]
    fn is_bot_reviewer_with_external_list() {
        let external = vec!["my-bot".to_string()];
        // "my-bot" is a substring of "my-bot" -> match via configured list
        assert!(is_bot_reviewer("my-bot", &external));
        // "other-bot[bot]" doesn't match "my-bot" substring, but falls back to
        // the [bot] suffix heuristic (configured list must not make reviewed unreachable)
        assert!(is_bot_reviewer("other-bot[bot]", &external));
    }

    #[test]
    fn session_cost_from_ledger_sums_session_only() {
        let tmp = tempfile::tempdir().unwrap();
        let ledger = tmp.path().join("l.json");
        std::fs::write(
            &ledger,
            r#"[{"session_id":"a","cost_usd":1.0},{"session_id":"b","cost_usd":0.5},{"session_id":"a","cost_usd":0.25}]"#,
        )
        .unwrap();
        let cost = session_cost_from_ledger(&ledger, "a");
        assert!((cost - 1.25).abs() < 0.001, "expected 1.25, got {cost}");
    }

    #[test]
    fn session_cost_missing_ledger_returns_zero() {
        let cost = session_cost_from_ledger(Path::new("/nonexistent/l.json"), "s");
        assert_eq!(cost, 0.0);
    }

    #[test]
    fn allow_output_serializes_correctly() {
        let json = allow_output(
            "allow",
            Some(TerminationReason::DonePRGreen),
            "done",
            3,
            Some("fp".into()),
        );
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(v["decision"], "allow");
        // Verify variant names serialize byte-identically to the spec strings.
        assert_eq!(v["termination_reason"], "DonePRGreen");
        assert_eq!(v["fires"], 3);
        assert_eq!(v["fingerprint"], "fp");
    }

    #[test]
    fn allow_output_null_termination_reason() {
        let json = allow_output("block", None, "continue", 1, None);
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert!(v["termination_reason"].is_null());
        assert!(v["fingerprint"].is_null());
    }

    #[test]
    fn watch_idle_event_is_non_terminal_allow() {
        // AC1-HP invariant: the idle branch emits allow + null termination, so
        // the stop-hook shim (which runs finalize only on a NON-null
        // termination_reason) never invokes finalize / stamps the ledger /
        // graduates a plan on an idle fire. This is the exact output shape the
        // idle branch returns.
        let json = allow_output(
            "allow",
            None,
            "watching: idling until watcher fires (PR #404, ci pending)",
            3,
            Some("sha|OPEN|PENDING|none".to_string()),
        );
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(v["decision"], "allow");
        assert!(
            v["termination_reason"].is_null(),
            "idle-allow MUST be non-terminal or finalize would run"
        );
        assert!(v["message"].as_str().unwrap().contains("watching"));
    }

    #[test]
    fn termination_reason_variant_names_byte_identical() {
        // Fix 6: all TerminationReason variants must serialize to the exact strings
        // the spec names - no rename attributes applied.
        let cases = [
            (TerminationReason::DonePRGreen, "DonePRGreen"),
            (TerminationReason::DoneAdvisory, "DoneAdvisory"),
            (TerminationReason::NoWork, "NoWork"),
            (TerminationReason::Budget, "Budget"),
            (TerminationReason::NoProgress, "NoProgress"),
            (TerminationReason::Interrupted, "Interrupted"),
            (TerminationReason::Aborted, "Aborted"),
        ];
        for (variant, expected) in cases {
            let json = serde_json::to_string(&variant).unwrap();
            // serde serializes enum unit variants as "\"VariantName\""
            assert_eq!(
                json,
                format!("\"{expected}\""),
                "variant {expected} serialized incorrectly"
            );
        }
    }

    #[test]
    fn manifest_default_attended_is_true() {
        // Fix 7: manual Default impl must set attended=true (derive would give false)
        let m = Manifest::default();
        assert!(m.attended, "Manifest::default() must have attended=true");
        assert!(!m.advisory);
        assert!(!m.no_ship);
        assert!(!m.no_external);
        assert!(m.session_id.is_none());
        assert!(m.budget_cost_cap_usd.is_none());
        assert!(m.budget_wall_clock_cap_minutes.is_none());
    }

    #[test]
    fn parse_manifest_malformed_cost_cap_fail_closed() {
        // Fix 2: a present but unparseable cost cap must be Err (fail-closed)
        let content =
            "---\nsession_id: s\ncreated_at: 2026-06-05T00:00:00Z\nbudget_cost_cap_usd: 5.OO\n---\n";
        let m = parse_manifest(content).unwrap();
        assert!(
            matches!(m.budget_cost_cap_usd, Some(Err(_))),
            "malformed cost cap must be Some(Err(...))"
        );
    }

    #[test]
    fn parse_manifest_malformed_wall_cap_fail_closed() {
        let content =
            "---\nsession_id: s\ncreated_at: 2026-06-05T00:00:00Z\nbudget_wall_clock_cap_minutes: abc\n---\n";
        let m = parse_manifest(content).unwrap();
        assert!(
            matches!(m.budget_wall_clock_cap_minutes, Some(Err(_))),
            "malformed wall cap must be Some(Err(...))"
        );
    }

    #[test]
    fn parse_settings_malformed_flat_cap_fail_closed() {
        let cfg = "budget_cap = \"not_a_number\"\n";
        let s = parse_settings(cfg);
        assert!(
            matches!(s.flat_budget_cap, Some(Err(_))),
            "malformed flat_budget_cap must be Some(Err(...))"
        );
    }

    #[test]
    fn check_budget_malformed_cost_cap_trips_budget() {
        // Fix 2: malformed cap in manifest -> Budget termination (fail-closed)
        let m = Manifest {
            session_id: Some("s".into()),
            created_at: Some("2026-06-05T00:00:00Z".into()),
            budget_cost_cap_usd: Some(Err("5.OO".into())),
            ..Default::default()
        };
        let s = Settings::default();
        let now: DateTime<Utc> = "2026-06-05T01:00:00Z".parse().unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let ledger = tmp.path().join("ledger.json");
        std::fs::write(&ledger, r#"[{"session_id":"s","cost_usd":0.0}]"#).unwrap();
        assert_eq!(
            check_budget(&m, &s, &now, &ledger),
            Some(BudgetTrip::Cost),
            "malformed cost cap must fail closed"
        );
    }

    #[test]
    fn check_budget_absent_cap_is_unlimited() {
        // ABSENT caps stay unlimited - must not trip
        let m = Manifest {
            session_id: Some("s".into()),
            created_at: Some("2026-06-05T00:00:00Z".into()),
            ..Default::default()
        };
        let s = Settings::default();
        let now: DateTime<Utc> = "2026-06-05T01:00:00Z".parse().unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let ledger = tmp.path().join("ledger.json");
        std::fs::write(&ledger, r#"[{"session_id":"s","cost_usd":9999.0}]"#).unwrap();
        assert_eq!(
            check_budget(&m, &s, &now, &ledger),
            None,
            "absent cap must be unlimited"
        );
    }

    #[test]
    fn check_budget_negative_elapsed_no_trip() {
        // Fix 3: created_at in the future (clock skew) -> elapsed=0 -> no wall-clock trip
        let m = Manifest {
            session_id: Some("s".into()),
            // created_at is 1 hour in the future
            created_at: Some("2026-06-05T02:00:00Z".into()),
            budget_wall_clock_cap_minutes: Some(Ok(30)),
            ..Default::default()
        };
        let s = Settings::default();
        // now is earlier than created_at
        let now: DateTime<Utc> = "2026-06-05T01:00:00Z".parse().unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let ledger = tmp.path().join("ledger.json");
        std::fs::write(&ledger, "[]").unwrap();
        assert_eq!(
            check_budget(&m, &s, &now, &ledger),
            None,
            "negative elapsed (future created_at) must not trip wall clock cap"
        );
    }

    #[test]
    fn is_bot_reviewer_configured_short_names_match_real_logins() {
        // Fix 1: configured entries use substring matching.
        // "gemini" (short config name) must match "gemini-code-assist[bot]"
        // "codex" must match "chatgpt-codex-connector"
        let external = vec!["gemini".to_string(), "codex".to_string()];
        assert!(
            is_bot_reviewer("gemini-code-assist[bot]", &external),
            "gemini short name must substring-match gemini-code-assist[bot]"
        );
        assert!(
            is_bot_reviewer("chatgpt-codex-connector", &external),
            "codex short name must substring-match chatgpt-codex-connector"
        );
    }

    #[test]
    fn is_bot_reviewer_configured_list_falls_back_to_bot_heuristic() {
        // Fix 1: when configured list has [some-human] but a bot review arrives,
        // fallback to endswith-[bot] heuristic so reviewed remains reachable.
        let external = vec!["some-human".to_string()];
        assert!(
            is_bot_reviewer("gemini-code-assist[bot]", &external),
            "configured list with no match must still fall back to [bot] heuristic"
        );
    }

    #[test]
    fn is_bot_reviewer_empty_config_human_only_returns_false() {
        // Fix 1: empty config + human-only review -> false
        assert!(
            !is_bot_reviewer("alice-the-human", &[]),
            "human reviewer with empty config must return false"
        );
    }

    // ── step 2: required_bots parsing + resolution (US1/US3) ────────────────

    #[test]
    fn parse_settings_required_bots_block_list() {
        let cfg = "[review]\nrequired_bots = [\n  \"chatgpt-codex-connector\",\n  \"gemini-code-assist\",\n]\n";
        let s = parse_settings(cfg);
        assert_eq!(
            s.required_bots,
            Some(vec![
                "chatgpt-codex-connector".to_string(),
                "gemini-code-assist".to_string()
            ])
        );
    }

    #[test]
    fn parse_settings_required_bots_inline_empty_is_declared_empty() {
        // The explicit [] form is the ONLY way to declare the no-review-gate
        // path (US3, locked decision 2).
        let cfg = "[review]\nrequired_bots = []\n";
        let s = parse_settings(cfg);
        assert_eq!(s.required_bots, Some(Vec::new()));
    }

    #[test]
    fn parse_settings_required_bots_inline_list() {
        let cfg = "[review]\nrequired_bots = [\"codex\", \"gemini\"]\n";
        let s = parse_settings(cfg);
        assert_eq!(
            s.required_bots,
            Some(vec!["codex".to_string(), "gemini".to_string()])
        );
    }

    /// A bare scalar `required_bots = "gemini"` GATES on that one login (parity
    /// with peers + Python), rather than failing OPEN to no-gate on a
    /// bracket-less typo (codex P1 on #205).
    #[test]
    fn parse_settings_required_bots_scalar_is_singleton() {
        let cfg = "[review]\nrequired_bots = \"gemini\"\n";
        let s = parse_settings(cfg);
        assert_eq!(s.required_bots, Some(vec!["gemini".to_string()]));
        // github_apps behaves identically.
        let g = parse_settings("[review]\ngithub_apps = \"chatgpt-codex-connector\"\n");
        assert_eq!(
            g.github_apps,
            Some(vec!["chatgpt-codex-connector".to_string()])
        );
    }

    /// An ABSENT required_bots key resolves to the default (no gate), and a
    /// following block still parses.
    #[test]
    fn parse_settings_absent_required_bots_defaults() {
        let cfg = "[review]\ngithub_apps = []\n\n[ci]\ndeclared_none = true\n";
        let s = parse_settings(cfg);
        assert_eq!(
            s.required_bots, None,
            "absent key resolves to the no-gate default"
        );
        assert!(s.ci_declared_none, "following blocks still parse");
    }

    /// TOML strips inline comments natively - a `required_bots = []  # note` is
    /// still the declared empty form, and commented list forms still parse.
    #[test]
    fn parse_settings_required_bots_inline_comments_stripped() {
        let empty = parse_settings("[review]\nrequired_bots = []  # no review gate\n");
        assert_eq!(empty.required_bots, Some(Vec::new()));

        let inline =
            parse_settings("[review]\nrequired_bots = [\"chatgpt-codex-connector\"] # required\n");
        assert_eq!(
            inline.required_bots,
            Some(vec!["chatgpt-codex-connector".to_string()])
        );

        let block = parse_settings(
            "[review]\nrequired_bots = [ # the gate\n  \"chatgpt-codex-connector\", # codex\n]\n",
        );
        assert_eq!(
            block.required_bots,
            Some(vec!["chatgpt-codex-connector".to_string()])
        );

        // A scalar (with a trailing comment stripped) coerces to a single-login
        // gate, not no-gate (codex P1 on #205).
        let scalar = parse_settings("[review]\nrequired_bots = \"gemini\" # oops\n");
        assert_eq!(scalar.required_bots, Some(vec!["gemini".to_string()]));
    }

    #[test]
    fn parse_settings_required_bots_multiline_array() {
        let cfg = "[review]\nrequired_bots = [\n  \"chatgpt-codex-connector\",\n]\n";
        let s = parse_settings(cfg);
        assert_eq!(
            s.required_bots,
            Some(vec!["chatgpt-codex-connector".to_string()])
        );
    }

    #[test]
    fn parse_settings_required_bots_reads_under_review_table() {
        // required_bots lives under the flat [review] table (no config: wrapper).
        let cfg = "[review]\nrequired_bots = [\"chatgpt-codex-connector\"]\n";
        let s = parse_settings(cfg);
        assert_eq!(
            s.required_bots,
            Some(vec!["chatgpt-codex-connector".to_string()])
        );
    }

    #[test]
    fn parse_settings_malformed_fails_closed_not_zeroed() {
        // A malformed config.toml must NOT silently zero the gate (the old
        // fail-open); it fails CLOSED with an unsatisfiable sentinel so the ship
        // gate blocks visibly. Here: an unclosed table header.
        let cfg = "[review\nrequired_bots = []\n";
        assert!(
            parse_settings_result(cfg).is_err(),
            "malformed TOML must be a parse error"
        );
        let s = parse_settings(cfg);
        assert_eq!(
            s.required_bots,
            Some(vec![UNPARSEABLE_SETTINGS_SENTINEL.to_string()]),
            "a malformed file must fail closed, not zero the gate"
        );
        // The sentinel can never be satisfied by a real bot login.
        assert!(!login_matches_bot(
            "chatgpt-codex-connector",
            UNPARSEABLE_SETTINGS_SENTINEL
        ));
    }

    #[test]
    fn parse_settings_unparseable_fails_closed() {
        // AC3-UI: a genuinely malformed config file leaves the login gate
        // unsatisfiable (fail closed), never a silent no-gate. The production
        // caller additionally emits loop_check_settings_unparseable.
        let cfg = "[review]\nrequired_bots = [1, 2, 3\n"; // unclosed array
        assert!(parse_settings_result(cfg).is_err());
        let s = parse_settings(cfg);
        assert_eq!(
            resolved_required_bots(&s),
            vec![UNPARSEABLE_SETTINGS_SENTINEL.to_string()]
        );
    }

    #[test]
    fn resolved_required_bots_default_is_empty() {
        // Fresh-install default: no required review bot, so a clone with no
        // review configuration is not blocked waiting for a bot it never set up.
        let s = Settings::default();
        assert!(
            resolved_required_bots(&s).is_empty(),
            "absent required_bots config must resolve to no review gate"
        );
    }

    #[test]
    fn resolved_required_bots_explicit_list_wins() {
        let s = Settings {
            required_bots: Some(vec!["my-bot".to_string()]),
            ..Default::default()
        };
        assert_eq!(resolved_required_bots(&s), vec!["my-bot".to_string()]);
        let empty = Settings {
            required_bots: Some(Vec::new()),
            ..Default::default()
        };
        assert!(resolved_required_bots(&empty).is_empty());
    }

    // --- github_apps rename + required_bots alias (x-4baa US3/US4) ---

    // --- optional_apps: honored-if-present, never required (x-4baa) ---

    #[test]
    fn parse_settings_structural_scalar_degrades_like_python() {
        // A `{...}` flow-mapping value is not a login: scalar_as_singleton
        // returns None so the Rust reader agrees with Python's typed reader
        // (which drops a mapping to None), honoring the two-parser invariant
        // (codex P1 on #205). A numeric scalar stays a singleton (parity too).
        assert_eq!(scalar_as_singleton(" {login: codex}"), None);
        assert_eq!(scalar_as_singleton(" 123"), Some(vec!["123".to_string()]));
        let g = parse_settings("[review]\ngithub_apps = {login = \"codex\"}\n");
        assert_eq!(g.github_apps, None, "an inline table is not a login gate");
        let o = parse_settings("[review]\noptional_apps = {a = \"b\"}\n");
        assert_eq!(o.optional_apps, None);
    }

    #[test]
    fn parse_settings_optional_apps_forms() {
        // Inline, multi-line, and bare-scalar all parse.
        let inline = parse_settings("[review]\noptional_apps = [\"chatgpt-codex-connector\"]\n");
        assert_eq!(
            inline.optional_apps,
            Some(vec!["chatgpt-codex-connector".to_string()])
        );
        let block =
            parse_settings("[review]\noptional_apps = [\n  \"chatgpt-codex-connector\",\n]\n");
        assert_eq!(
            block.optional_apps,
            Some(vec!["chatgpt-codex-connector".to_string()])
        );
        let scalar = parse_settings("[review]\noptional_apps = \"chatgpt-codex-connector\"\n");
        assert_eq!(
            scalar.optional_apps,
            Some(vec!["chatgpt-codex-connector".to_string()])
        );
    }

    // --- reviewers: local-attestation gate (x-e703, Phase 2) ---

    #[test]
    fn parse_settings_reviewers_forms() {
        // Inline, block-under, key-aligned (PyYAML), bare scalar all parse; a
        // leading '/' is normalized off (parity with the Python validator).
        let inline = parse_settings("[review]\nreviewers = [\"sigma\", \"/code-review\"]\n");
        assert_eq!(
            inline.reviewers,
            vec!["sigma".to_string(), "code-review".to_string()]
        );
        let block = parse_settings("[review]\nreviewers = [\n  \"sigma\",\n]\n");
        assert_eq!(block.reviewers, vec!["sigma".to_string()]);
        let scalar = parse_settings("[review]\nreviewers = \"/code-review\"\n");
        assert_eq!(scalar.reviewers, vec!["code-review".to_string()]);
        let absent = parse_settings("[review]\ngithub_apps = []\n");
        assert!(absent.reviewers.is_empty());
    }

    #[test]
    fn parse_settings_reviewers_distinct_from_external_reviewers() {
        // Top-level external_reviewers and review.reviewers must not
        // cross-contaminate their list items.
        let cfg = "external_reviewers = [\"gemini\"]\n\n[review]\nreviewers = [\"sigma\"]\n";
        let s = parse_settings(cfg);
        assert_eq!(s.external_reviewers, vec!["gemini".to_string()]);
        assert_eq!(s.reviewers, vec!["sigma".to_string()]);
    }

    fn write_events(dir: &Path, lines: &[&str]) -> std::path::PathBuf {
        let p = dir.join("events.jsonl");
        std::fs::write(&p, lines.join("\n")).unwrap();
        p
    }

    #[test]
    fn reviewers_all_attested_empty_is_vacuously_true() {
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("nonexistent.jsonl");
        assert!(reviewers_all_attested(&p, &[], "abc"));
    }

    #[test]
    fn reviewers_all_attested_head_pinned_pass() {
        let tmp = tempfile::tempdir().unwrap();
        let p = write_events(
            tmp.path(),
            &[
                r#"{"ts":"t","type":"review_attestation","source":"target","data":{"reviewer":"sigma","head_sha":"abc123","verdict":"pass"}}"#,
            ],
        );
        assert!(reviewers_all_attested(&p, &["sigma".to_string()], "abc123"));
    }

    #[test]
    fn reviewers_all_attested_stale_head_is_unsatisfied() {
        // Head-pin: a pass for a PRIOR commit must not satisfy the current HEAD
        // (AC1-EDGE / AC8-HP). A new commit invalidates the old attestation.
        let tmp = tempfile::tempdir().unwrap();
        let p = write_events(
            tmp.path(),
            &[
                r#"{"ts":"t","type":"review_attestation","source":"target","data":{"reviewer":"sigma","head_sha":"OLD","verdict":"pass"}}"#,
            ],
        );
        assert!(!reviewers_all_attested(&p, &["sigma".to_string()], "NEW"));
    }

    #[test]
    fn reviewers_all_attested_fail_and_missing_are_unsatisfied() {
        let tmp = tempfile::tempdir().unwrap();
        // fail verdict -> unsatisfied
        let fail = write_events(
            tmp.path(),
            &[
                r#"{"ts":"t","type":"review_attestation","source":"target","data":{"reviewer":"sigma","head_sha":"h","verdict":"fail"}}"#,
            ],
        );
        assert!(!reviewers_all_attested(&fail, &["sigma".to_string()], "h"));
        // missing file -> fail closed
        let gone = tmp.path().join("gone.jsonl");
        assert!(!reviewers_all_attested(&gone, &["sigma".to_string()], "h"));
    }

    #[test]
    fn reviewers_all_attested_conjunction_and_slash_normalized() {
        // Every reviewer must be attested (strict conjunction); a '/'-prefixed
        // config entry matches an event that emits the bare name and vice-versa.
        let tmp = tempfile::tempdir().unwrap();
        let p = write_events(
            tmp.path(),
            &[
                r#"{"ts":"t","type":"review_attestation","source":"target","data":{"reviewer":"sigma","head_sha":"h","verdict":"pass"}}"#,
                r#"{"ts":"t","type":"review_attestation","source":"target","data":{"reviewer":"code-review","head_sha":"h","verdict":"pass"}}"#,
            ],
        );
        // Both present -> satisfied ('/code-review' config vs 'code-review' event).
        assert!(reviewers_all_attested(
            &p,
            &["sigma".to_string(), "/code-review".to_string()],
            "h"
        ));
        // One missing -> unsatisfied.
        assert!(!reviewers_all_attested(
            &p,
            &["sigma".to_string(), "declare".to_string()],
            "h"
        ));
    }

    #[test]
    fn parse_settings_reviewers_malformed_mapping_fails_closed() {
        // A `{...}` mapping value must NOT drop to no-gate (Python raises here);
        // Rust stores an unsatisfiable sentinel so the gate stays active but can
        // never clear (codex peer review P1).
        let s = parse_settings("[review]\nreviewers = {a = \"b\"}\n");
        assert_eq!(s.reviewers, vec![MALFORMED_REVIEWERS_SENTINEL.to_string()]);
        let tmp = tempfile::tempdir().unwrap();
        let p = write_events(tmp.path(), &[]);
        assert!(
            !reviewers_all_attested(&p, &s.reviewers, "h"),
            "a malformed-reviewers sentinel must never be satisfiable"
        );
    }

    #[test]
    fn parse_settings_reviewers_seq_with_nonscalar_fails_closed() {
        // gemini medium: a non-scalar item INSIDE the reviewers list (Python
        // raises on it) must fail CLOSED with the sentinel, not silently drop
        // the entry and gate on the survivors.
        let bad = parse_settings("[review]\nreviewers = [\"sigma\", {a = \"b\"}]\n");
        assert_eq!(
            bad.reviewers,
            vec![MALFORMED_REVIEWERS_SENTINEL.to_string()]
        );
        // A clean all-scalar list still parses normally.
        let ok = parse_settings("[review]\nreviewers = [\"sigma\", \"declare\"]\n");
        assert_eq!(
            ok.reviewers,
            vec!["sigma".to_string(), "declare".to_string()]
        );
    }

    #[test]
    fn reviewers_all_attested_latest_verdict_wins() {
        // events.jsonl is append-ordered: a later attestation supersedes an
        // earlier one for the same reviewer at the same head (codex peer P1).
        let tmp = tempfile::tempdir().unwrap();
        // pass THEN fail -> latest is fail -> unsatisfied.
        let pf = write_events(
            tmp.path(),
            &[
                r#"{"ts":"t1","type":"review_attestation","source":"target","data":{"reviewer":"sigma","head_sha":"h","verdict":"pass"}}"#,
                r#"{"ts":"t2","type":"review_attestation","source":"target","data":{"reviewer":"sigma","head_sha":"h","verdict":"fail"}}"#,
            ],
        );
        assert!(
            !reviewers_all_attested(&pf, &["sigma".to_string()], "h"),
            "a fail posted after a pass must revoke it"
        );
        // fail THEN pass -> latest is pass -> satisfied (re-review cleared it).
        let fp = write_events(
            tmp.path(),
            &[
                r#"{"ts":"t1","type":"review_attestation","source":"target","data":{"reviewer":"sigma","head_sha":"h","verdict":"fail"}}"#,
                r#"{"ts":"t2","type":"review_attestation","source":"target","data":{"reviewer":"sigma","head_sha":"h","verdict":"pass"}}"#,
            ],
        );
        assert!(
            reviewers_all_attested(&fp, &["sigma".to_string()], "h"),
            "a pass posted after a fail must restore satisfaction"
        );
    }

    // ── operator review-finding gate (x-f8d4) ────────────────────────────────

    #[test]
    fn review_finding_open_then_resolved_clears() {
        // AC2-HP: an open review_finding gates; an explicit resolve clears it.
        let tmp = tempfile::tempdir().unwrap();
        let open = write_events(
            tmp.path(),
            &[
                r#"{"ts":"t1","type":"review_finding","source":"observer","data":{"finding_id":"f1","node":"x-1","text":"off-by-one in the loop\nsecond line"}}"#,
            ],
        );
        let (findings, malformed) = open_review_findings(&open, "x-1");
        assert_eq!(malformed, 0);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].id, "f1");
        assert_eq!(findings[0].first_line, "off-by-one in the loop"); // first line only

        // resolve clears it (node-scoped, only an explicit resolve).
        let resolved = write_events(
            tmp.path(),
            &[
                r#"{"ts":"t1","type":"review_finding","source":"observer","data":{"finding_id":"f1","node":"x-1","text":"off-by-one"}}"#,
                r#"{"ts":"t2","type":"review_finding_resolved","source":"observer","data":{"finding_id":"f1"}}"#,
            ],
        );
        assert!(open_review_findings(&resolved, "x-1").0.is_empty());
    }

    #[test]
    fn review_finding_is_node_scoped() {
        // A finding for a different node must not gate this node.
        let tmp = tempfile::tempdir().unwrap();
        let p = write_events(
            tmp.path(),
            &[
                r#"{"ts":"t","type":"review_finding","source":"observer","data":{"finding_id":"f1","node":"x-OTHER","text":"not mine"}}"#,
            ],
        );
        assert!(open_review_findings(&p, "x-mine").0.is_empty());
        assert_eq!(open_review_findings(&p, "x-OTHER").0.len(), 1);
    }

    #[test]
    fn review_finding_malformed_notices_not_blocks() {
        // AC3-FR: a structurally-unparseable review_finding line does NOT block
        // (no open finding), but is counted for the audit notice. A review_finding
        // missing its id is likewise a malformed notice, never a gating finding.
        let tmp = tempfile::tempdir().unwrap();
        // A truncated (unparseable) line that still carries the review_finding marker.
        let truncated = r#"{"ts":"t","type":"review_finding","data":{"finding_id":"f1"#;
        let id_less = r#"{"ts":"t","type":"review_finding","source":"observer","data":{"node":"x-1","text":"no id"}}"#;
        let good = r#"{"ts":"t","type":"review_finding","source":"observer","data":{"finding_id":"good","node":"x-1","text":"real one"}}"#;
        let p = write_events(tmp.path(), &[truncated, id_less, good]);
        let (findings, malformed) = open_review_findings(&p, "x-1");
        assert_eq!(findings.len(), 1, "only the well-formed finding gates");
        assert_eq!(findings[0].id, "good");
        assert_eq!(
            malformed, 2,
            "the truncated line + the id-less line are noticed"
        );
    }

    #[test]
    fn review_finding_block_reason_quotes_first_plus_count() {
        let open = vec![
            OpenFinding {
                id: "aaa".into(),
                first_line: "the bug".into(),
            },
            OpenFinding {
                id: "bbb".into(),
                first_line: "another".into(),
            },
        ];
        let r = build_findings_block_reason(&open, 1);
        assert!(r.contains("aaa"));
        assert!(r.contains("the bug"));
        assert!(r.contains("fno annotate resolve aaa"));
        assert!(r.contains("[+1 more]"));
        assert!(r.contains("1 malformed"));
    }

    #[test]
    fn resolved_optional_is_separate_from_required() {
        // An optional-only config leaves the REQUIRED set empty (never waited
        // on) while the optional set carries the honored-if-present login.
        let s = parse_settings(
            "[review]\ngithub_apps = []\noptional_apps = [\"chatgpt-codex-connector\"]\n",
        );
        assert!(
            resolved_required_bots(&s).is_empty(),
            "optional must not be required"
        );
        assert_eq!(
            resolved_optional_bots(&s),
            vec!["chatgpt-codex-connector".to_string()]
        );
    }

    #[test]
    fn parse_settings_github_apps_block_list() {
        let cfg = "[review]\ngithub_apps = [\n  \"chatgpt-codex-connector\",\n]\n";
        let s = parse_settings(cfg);
        assert_eq!(
            s.github_apps,
            Some(vec!["chatgpt-codex-connector".to_string()])
        );
    }

    #[test]
    fn parse_settings_github_apps_inline_and_empty() {
        let s = parse_settings("[review]\ngithub_apps = [\"a\", \"b\"]\n");
        assert_eq!(s.github_apps, Some(vec!["a".to_string(), "b".to_string()]));
        let e = parse_settings("[review]\ngithub_apps = []\n");
        assert_eq!(e.github_apps, Some(Vec::new()));
    }

    #[test]
    fn resolved_github_apps_wins_over_required_bots_alias() {
        // Both set -> github_apps wins (Locked Decision 2).
        let s = Settings {
            github_apps: Some(vec!["new-bot".to_string()]),
            required_bots: Some(vec!["old-bot".to_string()]),
            ..Default::default()
        };
        assert_eq!(resolved_required_bots(&s), vec!["new-bot".to_string()]);
        // required_bots-only still gates (legacy alias, AC2-HP).
        let legacy = Settings {
            required_bots: Some(vec!["old-bot".to_string()]),
            ..Default::default()
        };
        assert_eq!(resolved_required_bots(&legacy), vec!["old-bot".to_string()]);
    }

    // --- peers -> gate union (x-4baa US4) ---

    #[test]
    fn parse_settings_peers_inline_scalars() {
        let cfg = "[review]\npeers = [\"codex\", \"gemini\"]\npeer_identity = \"fno-peer-bot\"\n";
        let s = parse_settings(cfg);
        assert_eq!(s.peers.len(), 2);
        assert_eq!(s.peers[0].provider, "codex");
        assert_eq!(s.peer_identity.as_deref(), Some("fno-peer-bot"));
    }

    #[test]
    fn parse_settings_peers_block_maps_with_identity() {
        // A heterogeneous array: an inline-table peer + a bare scalar provider.
        let cfg = "[review]\npeers = [{provider = \"codex\", identity = \"fno-codex-bot\"}, \"gemini\"]\n";
        let s = parse_settings(cfg);
        assert_eq!(s.peers.len(), 2);
        assert_eq!(s.peers[0].provider, "codex");
        assert_eq!(s.peers[0].identity.as_deref(), Some("fno-codex-bot"));
        assert_eq!(s.peers[1].provider, "gemini");
        assert_eq!(s.peers[1].identity, None);
    }

    #[test]
    fn resolved_peers_shared_identity_collapses_to_one_login() {
        // Scalar peers share peer_identity -> the gate is that one login on top
        // of github_apps (AC1-HP: no App bot, just the peer identity).
        let s = Settings {
            github_apps: Some(Vec::new()),
            peers: vec![
                PeerEntry {
                    provider: "codex".into(),
                    model: None,
                    identity: None,
                },
                PeerEntry {
                    provider: "gemini".into(),
                    model: None,
                    identity: None,
                },
            ],
            peer_identity: Some("fno-peer-bot".into()),
            ..Default::default()
        };
        assert_eq!(resolved_required_bots(&s), vec!["fno-peer-bot".to_string()]);
    }

    #[test]
    fn resolved_peers_per_entry_identities_each_add_a_login() {
        let s = Settings {
            github_apps: Some(vec!["chatgpt-codex-connector".into()]),
            peers: vec![
                PeerEntry {
                    provider: "codex".into(),
                    model: None,
                    identity: Some("fno-codex-bot".into()),
                },
                PeerEntry {
                    provider: "gemini".into(),
                    model: None,
                    identity: Some("fno-gemini-bot".into()),
                },
            ],
            ..Default::default()
        };
        assert_eq!(
            resolved_required_bots(&s),
            vec![
                "chatgpt-codex-connector".to_string(),
                "fno-codex-bot".to_string(),
                "fno-gemini-bot".to_string(),
            ]
        );
    }

    #[test]
    fn parse_settings_github_apps_and_peers_together() {
        // github_apps + peers + peer_identity in one [review] table all parse.
        let cfg = "[review]\ngithub_apps = [\"chatgpt-codex-connector\"]\npeers = [\"codex\"]\npeer_identity = \"fno-peer-bot\"\n";
        let s = parse_settings(cfg);
        assert_eq!(
            s.github_apps,
            Some(vec!["chatgpt-codex-connector".to_string()]),
            "github_apps item must be collected"
        );
        assert_eq!(s.peers.len(), 1, "peers item must be collected");
        assert_eq!(s.peers[0].provider, "codex");
        assert_eq!(s.peer_identity.as_deref(), Some("fno-peer-bot"));
    }

    #[test]
    fn parse_settings_required_bots_single_item() {
        let cfg = "[review]\nrequired_bots = [\"chatgpt-codex-connector\"]\n";
        let s = parse_settings(cfg);
        assert_eq!(
            s.required_bots,
            Some(vec!["chatgpt-codex-connector".to_string()])
        );
    }

    #[test]
    fn parse_settings_peers_single_mapping_is_one_peer() {
        // codex peer review P1: a single top-level table for peers (what
        // Python's coerce_peers wraps as [dict]) must parse as ONE peer, not be
        // silently dropped - dropping it is a fail-open on a configured peer gate.
        let block = parse_settings(
            "[review]\npeers = {provider = \"codex\", identity = \"fno-codex-bot\"}\n",
        );
        assert_eq!(block.peers.len(), 1, "table peers must be one peer");
        assert_eq!(block.peers[0].provider, "codex");
        assert_eq!(block.peers[0].identity.as_deref(), Some("fno-codex-bot"));
        // A dotted-table form parses identically.
        let dotted = parse_settings(
            "[review.peers]\nprovider = \"gemini\"\nidentity = \"fno-gemini-bot\"\n",
        );
        assert_eq!(dotted.peers.len(), 1);
        assert_eq!(dotted.peers[0].provider, "gemini");
        assert_eq!(dotted.peers[0].identity.as_deref(), Some("fno-gemini-bot"));
    }

    #[test]
    fn parse_settings_peers_bare_scalar_is_one_provider() {
        // `peers = "codex"` (scalar) matches Python's coerce_peers -> one peer,
        // NOT a silent drop (which would fail open + diverge from Python).
        let cfg = "[review]\npeers = \"codex\"\npeer_identity = \"fno-peer-bot\"\n";
        let s = parse_settings(cfg);
        assert_eq!(s.peers.len(), 1);
        assert_eq!(s.peers[0].provider, "codex");
        // The gate then resolves on the shared identity (fail-closed if unset).
        assert_eq!(resolved_required_bots(&s), vec!["fno-peer-bot".to_string()]);
    }

    #[test]
    fn parse_settings_peers_array_of_tables() {
        // An array mixing an inline-table peer and a bare scalar provider.
        let cfg = "[review]\npeers = [{provider = \"codex\", identity = \"fno-codex-bot\"}, \"gemini\"]\n";
        let s = parse_settings(cfg);
        assert_eq!(s.peers.len(), 2);
        assert_eq!(s.peers[0].provider, "codex");
        assert_eq!(s.peers[0].identity.as_deref(), Some("fno-codex-bot"));
        assert_eq!(s.peers[1].provider, "gemini");
    }

    #[test]
    fn parse_settings_peers_map_identity_before_provider() {
        // The map parser is order-agnostic (gemini HIGH on #205): `identity`
        // before `provider` must still resolve both fields.
        let cfg = "[review]\npeers = [{identity = \"fno-codex-bot\", provider = \"codex\"}, {provider = \"gemini\", identity = \"fno-gemini-bot\"}]\n";
        let s = parse_settings(cfg);
        assert_eq!(s.peers.len(), 2);
        assert_eq!(s.peers[0].provider, "codex");
        assert_eq!(s.peers[0].identity.as_deref(), Some("fno-codex-bot"));
        assert_eq!(s.peers[1].provider, "gemini");
        assert_eq!(s.peers[1].identity.as_deref(), Some("fno-gemini-bot"));
    }

    #[test]
    fn identity_free_peer_uses_local_attestation_not_a_login() {
        let s = Settings {
            github_apps: Some(Vec::new()),
            peers: vec![PeerEntry {
                provider: "gemini".into(),
                model: None,
                identity: None,
            }],
            peer_identity: None,
            ..Default::default()
        };
        assert!(resolved_required_bots_for_author(&s, Some("codex")).is_empty());
        assert_eq!(
            resolved_local_peer_reviewers_for_author(&s, Some("codex")),
            vec![LOCAL_PEER_REVIEWER.to_string()]
        );
    }

    #[test]
    fn identity_free_same_model_peer_is_an_unsatisfiable_local_gate() {
        let s = Settings {
            peers: vec![PeerEntry {
                provider: "codex".into(),
                model: None,
                identity: None,
            }],
            ..Default::default()
        };
        assert_eq!(
            resolved_local_peer_reviewers_for_author(&s, Some("codex")),
            vec![SAME_MODEL_LOCAL_PEER_SENTINEL.to_string()]
        );
    }

    #[test]
    fn identity_free_mixed_peers_form_one_composite_gate() {
        let s = Settings {
            peers: vec![
                PeerEntry {
                    provider: "codex".into(),
                    model: None,
                    identity: None,
                },
                PeerEntry {
                    provider: "claude".into(),
                    model: Some("zai,glm-5.2".into()),
                    identity: None,
                },
            ],
            ..Default::default()
        };
        assert_eq!(
            resolved_local_peer_reviewers_for_author(&s, Some("codex")),
            vec![LOCAL_PEER_REVIEWER.to_string()]
        );
    }

    #[test]
    fn explicit_peer_identity_keeps_login_gate_only() {
        let s = Settings {
            peers: vec![PeerEntry {
                provider: "gemini".into(),
                model: None,
                identity: Some("fno-gemini-bot".into()),
            }],
            ..Default::default()
        };
        assert_eq!(
            resolved_required_bots_for_author(&s, Some("codex")),
            vec!["fno-gemini-bot".to_string()]
        );
        assert!(resolved_local_peer_reviewers_for_author(&s, Some("codex")).is_empty());
    }

    #[test]
    fn local_peer_attestation_is_head_pinned() {
        let td = tempfile::tempdir().unwrap();
        let events = td.path().join("events.jsonl");
        std::fs::write(
            &events,
            r#"{"type":"review_attestation","data":{"reviewer":"peer","head_sha":"OLD","verdict":"pass"}}"#,
        )
        .unwrap();
        let peer = vec![LOCAL_PEER_REVIEWER.to_string()];
        assert!(!reviewers_all_attested(&events, &peer, "NEW"));
        std::fs::write(
            &events,
            r#"{"type":"review_attestation","data":{"reviewer":"peer","head_sha":"NEW","verdict":"pass"}}"#,
        )
        .unwrap();
        assert!(reviewers_all_attested(&events, &peer, "NEW"));
    }

    // ---- same-model peer guard (x-c2e7) -----------------------------------

    /// US5: effective model family resolution across bare providers, routes,
    /// malformed routes (fall back to provider), and unknown providers (None).
    #[test]
    fn peer_family_mapping_table() {
        let bare = |p: &str| PeerEntry {
            provider: p.into(),
            model: None,
            identity: None,
        };
        let routed = |p: &str, m: &str| PeerEntry {
            provider: p.into(),
            model: Some(m.into()),
            identity: None,
        };
        // harness_family: names + aliases + case-insensitivity; unknown -> None.
        assert_eq!(harness_family("claude"), Some("anthropic"));
        assert_eq!(harness_family("ANTHROPIC"), Some("anthropic"));
        assert_eq!(harness_family("codex"), Some("openai"));
        assert_eq!(harness_family("gemini"), Some("google"));
        assert_eq!(harness_family("zai"), None);
        // route_provider: exactly two non-empty parts, else None (fall back).
        assert_eq!(route_provider("zai,glm-5.2"), Some("zai"));
        assert_eq!(route_provider(" openai , gpt-5 "), Some("openai"));
        assert_eq!(route_provider("gpt-5"), None); // no comma -> malformed
        assert_eq!(route_provider("zai,"), None); // empty model -> malformed
        assert_eq!(route_provider(",glm"), None); // empty provider -> malformed
        assert_eq!(route_provider("a,b,c"), None); // three parts -> malformed

        // peer_family: bare provider, valid route wins, malformed falls back.
        assert_eq!(peer_family(&bare("codex")), Some("openai"));
        assert_eq!(peer_family(&bare("grok")), None); // unknown -> never matches
        assert_eq!(peer_family(&routed("claude", "zai,glm-5.2")), None); // route wins
        assert_eq!(
            peer_family(&routed("codex", "openai,gpt-5")),
            Some("openai")
        );
        assert_eq!(peer_family(&routed("codex", "gpt-5")), Some("openai")); // malformed -> provider
    }

    /// AC1-HP: codex author + `peers: [codex]` -> the peer login is replaced by
    /// the same-model sentinel so the gate cannot clear.
    #[test]
    fn same_model_peer_holds_gate() {
        let s = Settings {
            github_apps: Some(Vec::new()),
            peers: vec![PeerEntry {
                provider: "codex".into(),
                model: None,
                identity: None,
            }],
            peer_identity: Some("fno-peer-bot".into()),
            ..Default::default()
        };
        let logins = resolved_required_bots_for_author(&s, Some("codex"));
        assert!(logins.iter().any(|l| l == SAME_MODEL_PEER_SENTINEL));
        assert!(!logins.iter().any(|l| l == "fno-peer-bot"));
    }

    /// AC2-HP: codex author + `peers: [gemini]` (cross-model) clears exactly as
    /// today - the login stays, no sentinel.
    #[test]
    fn cross_model_peer_login_unchanged() {
        let s = Settings {
            github_apps: Some(Vec::new()),
            peers: vec![PeerEntry {
                provider: "gemini".into(),
                model: None,
                identity: None,
            }],
            peer_identity: Some("fno-peer-bot".into()),
            ..Default::default()
        };
        let logins = resolved_required_bots_for_author(&s, Some("codex"));
        assert_eq!(logins, vec!["fno-peer-bot".to_string()]);
    }

    /// US1 / step-3b: a claude author with a routed claude peer
    /// (`{provider: claude, model: "zai,glm-5.2"}`) is cross-model (GLM via zai)
    /// -> the login stays.
    #[test]
    fn routed_claude_peer_is_cross_model() {
        let s = Settings {
            github_apps: Some(Vec::new()),
            peers: vec![PeerEntry {
                provider: "claude".into(),
                model: Some("zai,glm-5.2".into()),
                identity: None,
            }],
            peer_identity: Some("fno-peer-bot".into()),
            ..Default::default()
        };
        let logins = resolved_required_bots_for_author(&s, Some("claude"));
        assert_eq!(logins, vec!["fno-peer-bot".to_string()]);
    }

    /// AC3-ERR: a claude peer routed back to the author's own family
    /// (`anthropic,...`, hand-edited past the loader) is same-model -> sentinel.
    #[test]
    fn same_family_route_holds_gate() {
        let s = Settings {
            github_apps: Some(Vec::new()),
            peers: vec![PeerEntry {
                provider: "claude".into(),
                model: Some("anthropic,claude-opus".into()),
                identity: None,
            }],
            peer_identity: Some("fno-peer-bot".into()),
            ..Default::default()
        };
        let logins = resolved_required_bots_for_author(&s, Some("claude"));
        assert!(logins.iter().any(|l| l == SAME_MODEL_PEER_SENTINEL));
        assert!(!logins.iter().any(|l| l == "fno-peer-bot"));
    }

    /// AC5-EDGE: codex author + `peers: [codex, gemini]` sharing one identity
    /// stays satisfiable (gemini backs the login) -> login kept, no sentinel.
    #[test]
    fn shared_identity_mixed_peers_stays_satisfiable() {
        let s = Settings {
            github_apps: Some(Vec::new()),
            peers: vec![
                PeerEntry {
                    provider: "codex".into(),
                    model: None,
                    identity: None,
                },
                PeerEntry {
                    provider: "gemini".into(),
                    model: None,
                    identity: None,
                },
            ],
            peer_identity: Some("fno-peer-bot".into()),
            ..Default::default()
        };
        let logins = resolved_required_bots_for_author(&s, Some("codex"));
        assert_eq!(logins, vec!["fno-peer-bot".to_string()]);
    }

    /// AC6-FR: unknown harness (None) leaves the login set byte-identical to the
    /// no-guard wrapper, even for a would-be same-model config.
    #[test]
    fn unknown_harness_is_byte_identical() {
        let s = Settings {
            github_apps: Some(vec!["chatgpt-codex-connector".into()]),
            peers: vec![PeerEntry {
                provider: "codex".into(),
                model: None,
                identity: None,
            }],
            peer_identity: Some("fno-peer-bot".into()),
            ..Default::default()
        };
        // None author => guard inert => equals the no-harness wrapper exactly.
        assert_eq!(
            resolved_required_bots_for_author(&s, None),
            resolved_required_bots(&s)
        );
        assert!(!resolved_required_bots_for_author(&s, None)
            .iter()
            .any(|l| l == SAME_MODEL_PEER_SENTINEL));
    }

    /// A same-model peer whose identity COLLIDES with a required App login is
    /// fail-closed, not exempt (codex peer review on PR #375): the App login is
    /// kept (its requirement is not loosened) AND the sentinel is added, so a
    /// same-model review under the shared login cannot clear the gate.
    #[test]
    fn base_app_login_collision_is_fail_closed() {
        let s = Settings {
            github_apps: Some(vec!["fno-peer-bot".into()]),
            peers: vec![PeerEntry {
                provider: "codex".into(),
                model: None,
                identity: None,
            }],
            peer_identity: Some("fno-peer-bot".into()),
            ..Default::default()
        };
        let logins = resolved_required_bots_for_author(&s, Some("codex"));
        assert!(logins.iter().any(|l| l == "fno-peer-bot")); // App requirement kept
        assert!(logins.iter().any(|l| l == SAME_MODEL_PEER_SENTINEL)); // gate held
    }

    /// A codex/gemini peer's `model` route is NOT honored (only claude transport
    /// executes a route; codex/gemini dispatch runs the bare provider). A codex
    /// peer with a zai route stays openai-family -> same-model on a codex author,
    /// closing the route-bypass codex flagged on PR #375.
    #[test]
    fn non_claude_route_is_ignored() {
        let routed_codex = PeerEntry {
            provider: "codex".into(),
            model: Some("zai,glm-5.2".into()),
            identity: None,
        };
        assert_eq!(peer_family(&routed_codex), Some("openai"));
        let s = Settings {
            github_apps: Some(Vec::new()),
            peers: vec![routed_codex],
            peer_identity: Some("fno-peer-bot".into()),
            ..Default::default()
        };
        let logins = resolved_required_bots_for_author(&s, Some("codex"));
        assert!(logins.iter().any(|l| l == SAME_MODEL_PEER_SENTINEL));
        assert!(!logins.iter().any(|l| l == "fno-peer-bot"));
    }

    #[test]
    fn login_matches_bot_cases() {
        // Full login, [bot]-suffixed login, and short config names all match.
        assert!(login_matches_bot(
            "chatgpt-codex-connector",
            "chatgpt-codex-connector"
        ));
        assert!(login_matches_bot(
            "chatgpt-codex-connector[bot]",
            "chatgpt-codex-connector"
        ));
        assert!(login_matches_bot("chatgpt-codex-connector", "codex"));
        assert!(login_matches_bot("Gemini-Code-Assist[bot]", "gemini"));
        assert!(!login_matches_bot("alice-the-human", "codex"));
        // Empty config entry must never match every login.
        assert!(!login_matches_bot("anyone", ""));
    }

    #[test]
    fn compute_review_info_per_bot_verdict() {
        let required = vec![
            "chatgpt-codex-connector".to_string(),
            "gemini-code-assist".to_string(),
        ];
        // Only codex posted a completed pass (COMMENTED counts).
        let json = serde_json::json!({
            "reviews": [
                {"author": {"login": "chatgpt-codex-connector"}, "state": "COMMENTED",
                 "submittedAt": "2026-06-05T01:00:00Z"}
            ],
            "comments": []
        });
        let info = compute_review_info(&json, &required);
        assert!(!info.all_required_passed());
        assert_eq!(info.missing_bots, vec!["gemini-code-assist".to_string()]);
        assert_eq!(info.latest_ts, "2026-06-05T01:00:00Z");
    }

    // ── x-b167 nudge state ────────────────────────────────────────────────────

    fn nudge_cfg() -> NudgeConfig {
        NudgeConfig {
            login: "chatgpt-codex-connector".into(),
            review_handle: "@codex review".into(),
            wait_minutes: 15,
            ceiling: 3,
        }
    }
    fn nudge_now() -> DateTime<Utc> {
        "2026-07-06T02:00:00Z".parse().unwrap()
    }
    fn mention(body: &str, created: &str) -> Value {
        serde_json::json!({"body": body, "createdAt": created})
    }

    #[test]
    fn nudge_needs_nudge_when_never_mentioned() {
        let cfg = nudge_cfg();
        let b = classify_bot_nudge("chatgpt-codex-connector", &[], Some(&cfg), nudge_now());
        assert_eq!(b.class, NudgeClass::NeedsNudge);
        assert_eq!(b.nudges, 0);
        assert_eq!(b.review_handle, "@codex review");
    }

    #[test]
    fn nudge_awaiting_within_window() {
        let cfg = nudge_cfg();
        let comments = vec![mention("@codex review", "2026-07-06T01:58:00Z")];
        let b = classify_bot_nudge(
            "chatgpt-codex-connector",
            &comments,
            Some(&cfg),
            nudge_now(),
        );
        assert_eq!(b.class, NudgeClass::Awaiting);
        assert_eq!(b.nudges, 1);
        assert!(b.newest_age_min <= 2);
    }

    #[test]
    fn nudge_unresponsive_after_ceiling() {
        // AC3 building block: 3 mentions, newest older than wait_minutes.
        let cfg = nudge_cfg();
        let comments = vec![
            mention("@codex review", "2026-07-06T00:00:00Z"),
            mention("hey @codex review please", "2026-07-06T00:30:00Z"),
            mention("@codex review", "2026-07-06T01:00:00Z"),
        ];
        let b = classify_bot_nudge(
            "chatgpt-codex-connector",
            &comments,
            Some(&cfg),
            nudge_now(),
        );
        assert_eq!(b.class, NudgeClass::Unresponsive);
        assert_eq!(b.nudges, 3);
        assert!(b.span_min >= 120, "span was {}", b.span_min);
    }

    #[test]
    fn nudge_reask_after_timeout_below_ceiling() {
        // One mention 60m ago, ceiling 3: the previous nudge timed out, ask again.
        let cfg = nudge_cfg();
        let comments = vec![mention("@codex review", "2026-07-06T01:00:00Z")];
        let b = classify_bot_nudge(
            "chatgpt-codex-connector",
            &comments,
            Some(&cfg),
            nudge_now(),
        );
        assert_eq!(b.class, NudgeClass::NeedsNudge);
        assert_eq!(b.nudges, 1);
    }

    #[test]
    fn nudge_none_cfg_is_not_nudgeable() {
        // AC7: a peer-login sentinel classifies NotNudgeable.
        let b2 = classify_bot_nudge(SAME_MODEL_PEER_SENTINEL, &[], None, nudge_now());
        assert_eq!(b2.class, NudgeClass::NotNudgeable);
    }

    #[test]
    fn nudge_malformed_created_at_is_needs_nudge() {
        // A mention with an unparseable createdAt must not push toward Unresponsive.
        let cfg = nudge_cfg();
        let comments = vec![mention("@codex review", "not-a-date")];
        let b = classify_bot_nudge(
            "chatgpt-codex-connector",
            &comments,
            Some(&cfg),
            nudge_now(),
        );
        assert_eq!(b.class, NudgeClass::NeedsNudge);
        assert_eq!(b.nudges, 1);
    }

    #[test]
    fn resolved_nudge_configs_default_nudges_codex_only() {
        let cfgs = resolved_nudge_configs(&Settings::default());
        let codex = cfgs
            .iter()
            .find(|c| c.login == "chatgpt-codex-connector")
            .expect("codex nudgeable by default");
        assert_eq!(codex.review_handle, "@codex review");
        assert_eq!(codex.wait_minutes, 15);
        assert_eq!(codex.ceiling, 3);
        // gemini ships with an empty review_handle -> not nudgeable.
        assert!(cfgs.iter().all(|c| c.login != "gemini-code-assist"));
    }

    #[test]
    fn nudge_override_sets_wait_and_ceiling_inheriting_handle() {
        let s = parse_settings(
            "[review.nudge]\n\"chatgpt-codex-connector\" = { wait_minutes = 30, ceiling = 5 }\n",
        );
        let cfgs = resolved_nudge_configs(&s);
        let codex = cfgs
            .iter()
            .find(|c| logins_correspond(&c.login, "chatgpt-codex-connector"))
            .unwrap();
        assert_eq!(codex.wait_minutes, 30);
        assert_eq!(codex.ceiling, 5);
        assert_eq!(codex.review_handle, "@codex review");
    }

    #[test]
    fn nudge_override_disabled_removes_login() {
        let s =
            parse_settings("[review.nudge]\n\"chatgpt-codex-connector\" = { enabled = false }\n");
        let cfgs = resolved_nudge_configs(&s);
        assert!(cfgs
            .iter()
            .all(|c| !logins_correspond(&c.login, "chatgpt-codex-connector")));
    }

    #[test]
    fn nudge_override_new_login() {
        let s = parse_settings(
            "[review.nudge]\n\"some-bot\" = { review_handle = \"@somebot review\", wait_minutes = 10, ceiling = 2 }\n",
        );
        let cfgs = resolved_nudge_configs(&s);
        let b = cfgs.iter().find(|c| c.login == "some-bot").unwrap();
        assert_eq!(b.review_handle, "@somebot review");
        assert_eq!(b.wait_minutes, 10);
        assert_eq!(b.ceiling, 2);
    }

    #[test]
    fn nudge_malformed_override_degrades_to_non_nudgeable() {
        // AC8: a scalar, a list, and a non-integer wait_minutes each drop the
        // login to non-nudgeable without panicking.
        for body in [
            "[review.nudge]\n\"chatgpt-codex-connector\" = \"scalar\"\n",
            "[review.nudge]\n\"chatgpt-codex-connector\" = [1, 2]\n",
            "[review.nudge]\n\"chatgpt-codex-connector\" = { wait_minutes = \"soon\" }\n",
            // An absurd wait_minutes would overflow chrono::Duration::minutes and
            // panic the stop gate; it must degrade to non-nudgeable, not panic.
            "[review.nudge]\n\"chatgpt-codex-connector\" = { wait_minutes = 9999999999999999 }\n",
        ] {
            let s = parse_settings(body);
            let cfgs = resolved_nudge_configs(&s);
            assert!(
                cfgs.iter()
                    .all(|c| !logins_correspond(&c.login, "chatgpt-codex-connector")),
                "malformed override must be non-nudgeable: {body}"
            );
        }
    }

    #[test]
    fn compute_review_info_empty_state_not_a_pass() {
        // A review row with an empty state is not a completed pass.
        let required = vec!["chatgpt-codex-connector".to_string()];
        let json = serde_json::json!({
            "reviews": [
                {"author": {"login": "chatgpt-codex-connector"}, "state": "",
                 "submittedAt": "2026-06-05T01:00:00Z"}
            ],
            "comments": []
        });
        let info = compute_review_info(&json, &required);
        assert!(!info.all_required_passed());
    }

    #[test]
    fn compute_review_info_usage_limited_bot_dropped() {
        // AC1-HP: a required bot that posted only a usage-limit comment (no
        // review) leaves missing_bots for usage_limited, so the gate proceeds.
        let required = vec!["chatgpt-codex-connector".to_string()];
        let json = serde_json::json!({
            "reviews": [],
            "comments": [
                {"author": {"login": "chatgpt-codex-connector"},
                 "body": "You have reached your Codex usage limits for code reviews.",
                 "createdAt": "2026-07-06T01:00:00Z"}
            ]
        });
        let info = compute_review_info(&json, &required);
        assert!(info.missing_bots.is_empty());
        assert_eq!(
            info.usage_limited,
            vec!["chatgpt-codex-connector".to_string()]
        );
        assert!(info.all_required_passed());
    }

    #[test]
    fn compute_review_info_usage_limit_only_own_comment_counts() {
        // AC1-ERR: a usage-limit marker in a HUMAN's comment must not drop the
        // bot - detection is scoped to the bot's own author.login.
        let required = vec!["chatgpt-codex-connector".to_string()];
        let json = serde_json::json!({
            "reviews": [],
            "comments": [
                {"author": {"login": "some-human"},
                 "body": "The bot hit its usage limits for code reviews, ugh.",
                 "createdAt": "2026-07-06T01:00:00Z"}
            ]
        });
        let info = compute_review_info(&json, &required);
        assert_eq!(
            info.missing_bots,
            vec!["chatgpt-codex-connector".to_string()]
        );
        assert!(info.usage_limited.is_empty());
        assert!(!info.all_required_passed());
    }

    #[test]
    fn compute_review_info_real_review_beats_ratelimit_comment() {
        // AC1-EDGE: a bot that posted a usage-limit comment earlier AND a real
        // COMMENTED review is counted as passed, never usage-limited (it is
        // never in missing_bots to be scanned).
        let required = vec!["chatgpt-codex-connector".to_string()];
        let json = serde_json::json!({
            "reviews": [
                {"author": {"login": "chatgpt-codex-connector"}, "state": "COMMENTED",
                 "submittedAt": "2026-07-06T02:00:00Z"}
            ],
            "comments": [
                {"author": {"login": "chatgpt-codex-connector"},
                 "body": "codex usage limits reached",
                 "createdAt": "2026-07-06T01:00:00Z"}
            ]
        });
        let info = compute_review_info(&json, &required);
        assert!(info.missing_bots.is_empty());
        assert!(info.usage_limited.is_empty());
        assert!(info.all_required_passed());
    }

    // ── step 2: inline findings + severity + addressed (US2) ────────────────

    #[test]
    fn blocking_severity_codex_p1_both_forms() {
        // The exact markup codex emits (pinned from PR #447).
        assert_eq!(
            blocking_severity("![P1 Badge](https://img.shields.io/badge/P1-orange?style=flat) Bug"),
            Some("P1")
        );
        // Alt-text only and URL only each match.
        assert_eq!(blocking_severity("![P1 Badge] something"), Some("P1"));
        assert_eq!(
            blocking_severity("see https://img.shields.io/badge/P1-orange"),
            Some("P1")
        );
    }

    #[test]
    fn blocking_severity_codex_p2_p3_advisory() {
        assert_eq!(
            blocking_severity("![P2 Badge](https://img.shields.io/badge/P2-yellow) nit"),
            None
        );
        assert_eq!(
            blocking_severity("![P3 Badge](https://img.shields.io/badge/P3-green) nit"),
            None
        );
    }

    #[test]
    fn blocking_severity_gemini_critical_high_blocking() {
        assert_eq!(
            blocking_severity(
                "![critical](https://www.gstatic.com/codereviewagent/critical-priority.svg) bad"
            ),
            Some("critical")
        );
        assert_eq!(
            blocking_severity(
                "![high](https://www.gstatic.com/codereviewagent/high-priority.svg) bad"
            ),
            Some("high")
        );
    }

    #[test]
    fn blocking_severity_gemini_medium_low_advisory() {
        assert_eq!(
            blocking_severity(
                "![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg) hmm"
            ),
            None
        );
        assert_eq!(
            blocking_severity(
                "![low](https://www.gstatic.com/codereviewagent/low-priority.svg) hmm"
            ),
            None
        );
    }

    /// Boundaries: unrecognized / absent severity tokens classify advisory,
    /// never blocking (locked decision 4).
    #[test]
    fn blocking_severity_unparseable_is_advisory() {
        assert_eq!(blocking_severity("just a comment with no badge"), None);
        assert_eq!(blocking_severity(""), None);
        assert_eq!(blocking_severity("P1 mentioned in prose only"), None);
    }

    #[test]
    fn max_ts_none_handling() {
        assert_eq!(
            max_ts("none", "2026-06-05T01:00:00Z"),
            "2026-06-05T01:00:00Z"
        );
        assert_eq!(
            max_ts("2026-06-05T01:00:00Z", "none"),
            "2026-06-05T01:00:00Z"
        );
        assert_eq!(max_ts("none", "none"), "none");
        assert_eq!(max_ts("", ""), "none");
        assert_eq!(
            max_ts("2026-06-05T01:00:00Z", "2026-06-05T02:00:00Z"),
            "2026-06-05T02:00:00Z"
        );
    }

    fn finding_comment(id: i64, body: &str, created_at: &str) -> Value {
        serde_json::json!({
            "id": id,
            "in_reply_to_id": null,
            "user": {"login": "chatgpt-codex-connector[bot]"},
            "body": body,
            "path": "src/x.rs",
            "line": 42,
            "created_at": created_at
        })
    }

    fn reply_comment(id: i64, parent: i64, login: &str, body: &str, created_at: &str) -> Value {
        serde_json::json!({
            "id": id,
            "in_reply_to_id": parent,
            "user": {"login": login},
            "body": body,
            "created_at": created_at
        })
    }

    const REQ: &[&str] = &["chatgpt-codex-connector"];

    fn req_vec() -> Vec<String> {
        REQ.iter().map(|s| s.to_string()).collect()
    }

    /// AC2-ERR core: a P1 with no reply is unaddressed.
    #[test]
    fn finding_no_reply_is_unaddressed() {
        let comments = vec![finding_comment(
            100,
            "![P1 Badge](https://img.shields.io/badge/P1-orange) bug",
            "2026-06-05T01:10:00Z",
        )];
        let (ts, unaddressed) = compute_unaddressed_findings(&comments, &[], &req_vec(), &[]);
        assert_eq!(ts, "2026-06-05T01:10:00Z");
        assert_eq!(unaddressed.len(), 1);
        assert_eq!(unaddressed[0].path, "src/x.rs");
        assert_eq!(unaddressed[0].line, 42);
        assert_eq!(unaddressed[0].severity, "P1");
    }

    /// AC2-HP commit arm: non-bot reply + commit after the finding -> addressed.
    #[test]
    fn finding_reply_plus_commit_after_is_addressed() {
        let comments = vec![
            finding_comment(
                100,
                "![P1 Badge](https://img.shields.io/badge/P1-orange) bug",
                "2026-06-05T01:10:00Z",
            ),
            reply_comment(
                101,
                100,
                "bllshttng",
                "fixed in abc123",
                "2026-06-05T01:20:00Z",
            ),
        ];
        let commits = vec!["2026-06-05T01:30:00Z".to_string()];
        let (_, unaddressed) = compute_unaddressed_findings(&comments, &commits, &req_vec(), &[]);
        assert!(unaddressed.is_empty(), "commit-after arm must address");
    }

    /// AC2-FR wontfix arm: non-bot reply carrying wontfix:, NO commit after.
    #[test]
    fn finding_wontfix_reply_is_addressed_without_commit() {
        let comments = vec![
            finding_comment(
                100,
                "![P1 Badge](https://img.shields.io/badge/P1-orange) bug",
                "2026-06-05T01:10:00Z",
            ),
            reply_comment(
                101,
                100,
                "bllshttng",
                "wontfix: intentional - documented tradeoff",
                "2026-06-05T01:20:00Z",
            ),
        ];
        // Only commit predates the finding -> commit arm unsatisfied.
        let commits = vec!["2026-06-05T01:00:00Z".to_string()];
        let (_, unaddressed) = compute_unaddressed_findings(&comments, &commits, &req_vec(), &[]);
        assert!(unaddressed.is_empty(), "wontfix arm must address alone");
    }

    /// Anti-gaming: a commit alone (no reply) does NOT address (locked
    /// decision 3 - any unrelated commit would silently clear a P1).
    #[test]
    fn finding_commit_without_reply_is_unaddressed() {
        let comments = vec![finding_comment(
            100,
            "![P1 Badge](https://img.shields.io/badge/P1-orange) bug",
            "2026-06-05T01:10:00Z",
        )];
        let commits = vec!["2026-06-05T01:30:00Z".to_string()];
        let (_, unaddressed) = compute_unaddressed_findings(&comments, &commits, &req_vec(), &[]);
        assert_eq!(unaddressed.len(), 1, "commit alone must not address");
    }

    /// A bot's own reply in the thread is not an ack.
    #[test]
    fn finding_bot_reply_only_is_unaddressed() {
        let comments = vec![
            finding_comment(
                100,
                "![P1 Badge](https://img.shields.io/badge/P1-orange) bug",
                "2026-06-05T01:10:00Z",
            ),
            reply_comment(
                101,
                100,
                "chatgpt-codex-connector[bot]",
                "elaborating on my finding",
                "2026-06-05T01:15:00Z",
            ),
        ];
        let commits = vec!["2026-06-05T01:30:00Z".to_string()];
        let (_, unaddressed) = compute_unaddressed_findings(&comments, &commits, &req_vec(), &[]);
        assert_eq!(unaddressed.len(), 1, "bot self-reply must not count as ack");
    }

    /// Reply present but neither commit-after nor wontfix -> still unaddressed.
    #[test]
    fn finding_reply_without_commit_or_wontfix_is_unaddressed() {
        let comments = vec![
            finding_comment(
                100,
                "![P1 Badge](https://img.shields.io/badge/P1-orange) bug",
                "2026-06-05T01:10:00Z",
            ),
            reply_comment(
                101,
                100,
                "bllshttng",
                "looking into it",
                "2026-06-05T01:20:00Z",
            ),
        ];
        let commits = vec!["2026-06-05T01:00:00Z".to_string()]; // predates finding
        let (_, unaddressed) = compute_unaddressed_findings(&comments, &commits, &req_vec(), &[]);
        assert_eq!(unaddressed.len(), 1);
    }

    /// A finding from a NON-required bot does not gate.
    #[test]
    fn finding_from_non_required_bot_ignored() {
        let comments = vec![serde_json::json!({
            "id": 200,
            "in_reply_to_id": null,
            "user": {"login": "gemini-code-assist[bot]"},
            "body": "![high](https://www.gstatic.com/codereviewagent/high-priority.svg) eh",
            "path": "src/y.rs",
            "line": 7,
            "created_at": "2026-06-05T01:10:00Z"
        })];
        // required = codex only; gemini finding is not gate-relevant
        let (ts, unaddressed) = compute_unaddressed_findings(&comments, &[], &req_vec(), &[]);
        assert!(unaddressed.is_empty());
        // ...but its timestamp still feeds the fingerprint.
        assert_eq!(ts, "2026-06-05T01:10:00Z");
    }

    /// Boundaries: empty comments array -> no findings, ts "none".
    #[test]
    fn empty_comments_no_findings() {
        let (ts, unaddressed) = compute_unaddressed_findings(&[], &[], &req_vec(), &[]);
        assert_eq!(ts, "none");
        assert!(unaddressed.is_empty());
    }

    /// sigma-review: a blocking finding row with a missing id is SKIPPED
    /// (under-block per locked decision 4), never pooled on a default id
    /// where one stray reply could clear multiple findings.
    #[test]
    fn finding_missing_id_skipped_not_pooled() {
        let no_id = serde_json::json!({
            "in_reply_to_id": null,
            "user": {"login": "chatgpt-codex-connector[bot]"},
            "body": "![P1 Badge](https://img.shields.io/badge/P1-orange) idless",
            "path": "src/z.rs", "line": 3,
            "created_at": "2026-06-05T01:05:00Z"
        });
        let real = finding_comment(
            100,
            "![P1 Badge](https://img.shields.io/badge/P1-orange) real",
            "2026-06-05T01:10:00Z",
        );
        // A stray reply keyed to id 0 must not ack anything.
        let stray = reply_comment(
            101,
            0,
            "bllshttng",
            "wontfix: stray",
            "2026-06-05T01:20:00Z",
        );
        let comments = vec![no_id, real, stray];
        let (_, unaddressed) = compute_unaddressed_findings(&comments, &[], &req_vec(), &[]);
        assert_eq!(unaddressed.len(), 1, "only the real finding remains");
        assert_eq!(unaddressed[0].id, 100);
    }

    /// sigma-review: commit-after comparison parses timestamps instead of
    /// string-comparing - an offset-suffixed commit date that lexicographically
    /// sorts above a Zulu finding date but is EARLIER in UTC must not clear
    /// the finding.
    #[test]
    fn ts_after_parses_offsets_correctly() {
        // 23:30+13:00 == 10:30Z, which is BEFORE 11:00Z - but the raw string
        // "2026-06-05T23:30:00+13:00" > "2026-06-05T11:00:00Z".
        assert!(!ts_after(
            "2026-06-05T23:30:00+13:00",
            "2026-06-05T11:00:00Z"
        ));
        // POSITIVE direction proves chrono's FromStr for DateTime<Utc>
        // parses offset-suffixed RFC3339 and converts to UTC (gemini's
        // #448 critical claimed it errors; empirically it returns
        // Ok(2026-06-05T13:30:00Z) here). Without this assertion the
        // offset case above could pass vacuously via the Err arm.
        assert!(ts_after(
            "2026-06-05T23:30:00+10:00", // == 13:30Z
            "2026-06-05T11:00:00Z"
        ));
        assert!(ts_after("2026-06-05T11:00:01Z", "2026-06-05T11:00:00Z"));
        assert!(!ts_after("2026-06-05T11:00:00Z", "2026-06-05T11:00:00Z"));
        // Unparseable on either side never clears a finding.
        assert!(!ts_after("garbage", "2026-06-05T11:00:00Z"));
        assert!(!ts_after("2026-06-05T11:00:00Z", "garbage"));
        assert!(!ts_after("2026-06-05T11:00:00Z", ""));
    }

    /// gemini high on #448: max_ts compares chronologically when both sides
    /// parse, returning the original string either way (byte-stable
    /// fingerprint).
    #[test]
    fn max_ts_chronological_with_offsets() {
        // +13:00 form is EARLIER in UTC despite sorting higher as a string.
        assert_eq!(
            max_ts("2026-06-05T23:30:00+13:00", "2026-06-05T11:00:00Z"),
            "2026-06-05T11:00:00Z"
        );
        // The winner is returned verbatim.
        assert_eq!(
            max_ts("2026-06-05T23:30:00+10:00", "2026-06-05T11:00:00Z"),
            "2026-06-05T23:30:00+10:00"
        );
    }

    /// Concurrency (Failure Modes): a reply arriving BEFORE its parent
    /// finding in the comments array (REST ordering is not guaranteed across
    /// pagination) still acks the finding - no order dependence.
    #[test]
    fn finding_reply_listed_before_finding_still_addressed() {
        let comments = vec![
            reply_comment(
                101,
                100,
                "bllshttng",
                "wontfix: ordering test",
                "2026-06-05T01:20:00Z",
            ),
            finding_comment(
                100,
                "![P1 Badge](https://img.shields.io/badge/P1-orange) bug",
                "2026-06-05T01:10:00Z",
            ),
        ];
        let (_, unaddressed) = compute_unaddressed_findings(&comments, &[], &req_vec(), &[]);
        assert!(
            unaddressed.is_empty(),
            "reply-before-finding ordering must still ack"
        );
    }

    // ── step 2: outage vs no-PR discrimination (US4) ─────────────────────────

    #[test]
    fn no_pr_stderr_detected() {
        assert!(is_no_pr_stderr(
            b"no pull requests found for branch \"feat\""
        ));
        assert!(is_no_pr_stderr(b"No pull requests found for branch \"x\""));
        // Outage shapes are NOT no-PR.
        assert!(!is_no_pr_stderr(b"connect: network is unreachable"));
        assert!(!is_no_pr_stderr(b"API rate limit exceeded"));
        assert!(!is_no_pr_stderr(b""));
    }
}

#[cfg(test)]
mod done_probe_tests {
    use super::*;
    use std::time::Duration;

    fn fm(body: &str) -> String {
        format!("---\ntitle: t\n{body}\n---\n\n# doc\n")
    }

    fn probes_of(doc: &str) -> Vec<String> {
        match parse_done_probes(doc) {
            ProbeDecl::Probes(p) => p,
            other => panic!("expected probes, got {other:?}"),
        }
    }

    #[test]
    fn parses_block_list() {
        let doc = fm("done_probes:\n  - \"fno mail list --since 24h | grep -q groom\"\n  - 'echo ok'\nstatus: ready");
        assert_eq!(
            probes_of(&doc),
            vec![
                "fno mail list --since 24h | grep -q groom".to_string(),
                "echo ok".to_string()
            ]
        );
    }

    #[test]
    fn parses_inline_list_keeping_commas_inside_commands() {
        let doc = fm(r#"done_probes: ["gh api x --jq '.a,.b'", "echo ok"]"#);
        assert_eq!(
            probes_of(&doc),
            vec!["gh api x --jq '.a,.b'".to_string(), "echo ok".to_string()],
            "a comma inside a quoted command must not split it into two probes"
        );
    }

    #[test]
    fn absent_field_and_explicit_empty_list_are_both_no_gate() {
        assert_eq!(parse_done_probes(&fm("done_probes: []")), ProbeDecl::None);
        assert_eq!(parse_done_probes(&fm("status: ready")), ProbeDecl::None);
        assert_eq!(parse_done_probes("no frontmatter here"), ProbeDecl::None);
    }

    #[test]
    fn a_declaration_this_parser_cannot_read_is_never_no_gate() {
        // The vacuous-pass shape: the field is there, so the plan MEANT to gate.
        // Reporting None here would silently drop the gate entirely.
        let multiline_inline = fm("done_probes: [\n  \"echo a\",\n  \"echo b\"\n]");
        assert_eq!(parse_done_probes(&multiline_inline), ProbeDecl::Unparseable);
        assert_eq!(
            parse_done_probes(&fm("done_probes:\nstatus: ready")),
            ProbeDecl::Unparseable,
            "a declared-but-empty block must refuse, not pass"
        );
    }

    #[test]
    fn inline_list_keeps_escaped_quotes_inside_a_command() {
        // A mis-parsed probe is worse than a refused one: it would run a
        // DIFFERENT command than the plan declared and gate on its result.
        let doc = fm(r#"done_probes: ["sh -c \"echo hi\"", "echo ok"]"#);
        assert_eq!(
            probes_of(&doc),
            vec![r#"sh -c "echo hi""#.to_string(), "echo ok".to_string()]
        );
    }

    #[test]
    fn inline_list_preserves_a_trailing_bracket_and_refuses_an_unterminated_one() {
        assert_eq!(
            probes_of(&fm(r#"done_probes: ["echo [hi]"]"#)),
            vec!["echo [hi]".to_string()],
            "only the list's own closing bracket may be stripped"
        );
        assert_eq!(
            parse_done_probes(&fm(r#"done_probes: ["echo a""#)),
            ProbeDecl::Unparseable,
            "an unterminated inline list must refuse, not silently parse"
        );
    }

    #[test]
    fn a_comment_inside_the_block_does_not_swallow_the_probes() {
        let doc = fm("done_probes:\n  # why this probe exists\n  - echo a\n  - echo b\ntags: []");
        assert_eq!(
            probes_of(&doc),
            vec!["echo a".to_string(), "echo b".to_string()]
        );
    }

    #[test]
    fn block_list_stops_at_the_next_key() {
        let doc = fm("done_probes:\n  - echo a\ntags: []\nother: x");
        assert_eq!(probes_of(&doc), vec!["echo a".to_string()]);
    }

    #[test]
    fn probe_outcomes_render_pass_fail_and_exit_code() {
        let tmp = tempfile::tempdir().unwrap();
        let t = Duration::from_secs(10);
        assert_eq!(run_probe("exit 0", tmp.path(), t).render(), "pass");
        assert_eq!(run_probe("exit 3", tmp.path(), t).render(), "fail:3");
        assert_eq!(
            run_probe("fno-no-such-binary-xyz", tmp.path(), t).render(),
            "fail:127",
            "a missing binary must fail closed as 127, never pass"
        );
    }

    #[test]
    fn hanging_probe_is_killed_within_the_timeout_budget() {
        let tmp = tempfile::tempdir().unwrap();
        let start = std::time::Instant::now();
        let outcome = run_probe("sleep 30", tmp.path(), Duration::from_millis(200));
        assert_eq!(outcome.render(), "timeout");
        assert!(
            start.elapsed() < Duration::from_secs(5),
            "run_probe must return on its own timeout, not wait out the child"
        );
    }

    #[test]
    fn chatty_probe_does_not_deadlock_on_the_stderr_pipe() {
        // A probe writing past the 64KB pipe buffer would hang forever if
        // stderr were drained only after exit.
        let tmp = tempfile::tempdir().unwrap();
        let outcome = run_probe(
            "head -c 200000 /dev/zero | tr '\\0' 'x' >&2; exit 1",
            tmp.path(),
            Duration::from_secs(20),
        );
        assert_eq!(outcome.render(), "fail:1");
        match outcome {
            ProbeOutcome::Fail { stderr, .. } => assert!(
                stderr.len() <= PROBE_STDERR_CAP,
                "stderr must be truncated to {PROBE_STDERR_CAP}"
            ),
            _ => panic!("expected Fail"),
        }
    }

    #[test]
    fn over_cap_declaration_refuses_without_running_anything() {
        let tmp = tempfile::tempdir().unwrap();
        let plan = tmp.path().join("plan.md");
        let sentinel = tmp.path().join("ran");
        std::fs::write(
            &plan,
            fm(&format!(
                "done_probes:\n  - touch {0}\n  - echo b\n  - echo c\n  - echo d",
                sentinel.display()
            )),
        )
        .unwrap();
        let events = tmp.path().join("events.jsonl");
        match evaluate_done_probes(
            plan.to_str(),
            None,
            tmp.path(),
            &events,
            "s1",
            Duration::from_secs(10),
        ) {
            ProbeGate::Fail { reason, .. } => {
                assert!(
                    reason.contains("cap is 3"),
                    "reason names the cap: {reason}"
                )
            }
            _ => panic!("over-cap declaration must refuse"),
        }
        assert!(!sentinel.exists(), "an over-cap list must not execute");
    }

    #[test]
    fn unreadable_plan_fails_closed_only_when_probes_were_seen_before() {
        let tmp = tempfile::tempdir().unwrap();
        let events = tmp.path().join("events.jsonl");
        let missing = tmp.path().join("gone.md");

        // AC2-FR: no probe history -> today's behavior exactly.
        assert!(matches!(
            evaluate_done_probes(
                missing.to_str(),
                None,
                tmp.path(),
                &events,
                "s1",
                Duration::from_secs(10)
            ),
            ProbeGate::Absent
        ));

        // AC1-FR: a prior fire recorded probes -> undeterminable, fail closed.
        std::fs::write(
            &events,
            "{\"type\":\"loop_check\",\"data\":{\"session_id\":\"s1\",\"done_probes\":{\"echo ok\":\"pass\"}}}\n",
        )
        .unwrap();
        match evaluate_done_probes(
            missing.to_str(),
            None,
            tmp.path(),
            &events,
            "s1",
            Duration::from_secs(10),
        ) {
            ProbeGate::Fail { reason, .. } => assert!(
                reason.contains("undeterminable"),
                "reason must say undeterminable: {reason}"
            ),
            _ => panic!("unreadable plan with probe history must fail closed"),
        }
    }

    #[test]
    fn a_refusal_where_nothing_ran_still_records_probe_history() {
        // Otherwise prior_fires_declared_probes sees no history, and a plan that
        // tripped the cap and then went missing degrades to "no gate".
        let tmp = tempfile::tempdir().unwrap();
        let plan = tmp.path().join("plan.md");
        std::fs::write(
            &plan,
            fm("done_probes:\n  - echo a\n  - echo b\n  - echo c\n  - echo d"),
        )
        .unwrap();
        let events = tmp.path().join("events.jsonl");
        let ProbeGate::Fail { results, .. } = evaluate_done_probes(
            plan.to_str(),
            None,
            tmp.path(),
            &events,
            "s1",
            Duration::from_secs(10),
        ) else {
            panic!("over-cap must refuse");
        };
        std::fs::write(
            &events,
            format!(
                "{}\n",
                serde_json::json!({
                    "type": "loop_check",
                    "data": {"session_id": "s1", "done_probes": results}
                })
            ),
        )
        .unwrap();
        assert!(
            prior_fires_declared_probes(&events, "s1"),
            "a declared-but-never-ran refusal must be visible as probe history"
        );
    }

    #[test]
    fn relative_plan_path_resolves_against_the_session_cwd() {
        // plan_path is repo-relative in practice; resolving against the process
        // cwd would read nothing and silently drop the gate.
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("plan.md"), fm("done_probes:\n  - exit 0")).unwrap();
        let events = tmp.path().join("events.jsonl");
        assert!(
            matches!(
                evaluate_done_probes(
                    Some("plan.md"),
                    None,
                    tmp.path(),
                    &events,
                    "s1",
                    Duration::from_secs(10)
                ),
                ProbeGate::Pass(_)
            ),
            "a relative plan_path must resolve against cwd, not the process cwd"
        );
    }

    #[test]
    fn timeout_reaches_the_gate_reason() {
        let tmp = tempfile::tempdir().unwrap();
        let plan = tmp.path().join("plan.md");
        std::fs::write(&plan, fm("done_probes:\n  - sleep 30")).unwrap();
        let events = tmp.path().join("events.jsonl");
        match evaluate_done_probes(
            plan.to_str(),
            None,
            tmp.path(),
            &events,
            "s1",
            Duration::from_millis(200),
        ) {
            ProbeGate::Fail { reason, results } => {
                assert!(
                    reason.contains("timed out"),
                    "reason names the timeout: {reason}"
                );
                assert_eq!(results["sleep 30"], "timeout");
            }
            _ => panic!("a hanging probe must refuse done"),
        }
    }

    #[test]
    fn a_pipeline_probe_timeout_does_not_hang_the_gate() {
        // `sh -c "a | b"` forks: killing only sh leaves grandchildren holding
        // the stderr pipe, so the drain thread never sees EOF. This is the
        // documented probe shape, so a regression here wedges every session.
        let tmp = tempfile::tempdir().unwrap();
        let start = std::time::Instant::now();
        let outcome = run_probe("sleep 30 | cat", tmp.path(), Duration::from_millis(200));
        assert_eq!(outcome.render(), "timeout");
        assert!(
            start.elapsed() < Duration::from_secs(10),
            "a pipeline probe must not outlive its timeout (took {:?})",
            start.elapsed()
        );
    }

    #[test]
    fn multibyte_stderr_is_truncated_without_panicking() {
        // String::drain panics off a char boundary; probe stderr routinely
        // carries arrows and box-drawing characters.
        let mut s = "→".repeat(400); // 3 bytes each, straddles the cut
        keep_last_on_char_boundary(&mut s, PROBE_STDERR_CAP);
        assert!(s.len() <= PROBE_STDERR_CAP);
        assert!(s.chars().all(|c| c == '→'), "must not split a character");
    }

    #[test]
    fn stderr_cap_keeps_the_tail_where_the_error_is() {
        let mut s = format!("{}\nthe actual error", "noise ".repeat(200));
        keep_last_on_char_boundary(&mut s, PROBE_STDERR_CAP);
        assert!(
            s.ends_with("the actual error"),
            "the last line is the diagnostic; keeping the prefix drops it: {s}"
        );
    }

    #[test]
    fn block_scalar_escapes_decode_to_the_command_the_plan_meant() {
        // Leaving `\"` in would hand sh a DIFFERENT command than declared, and
        // would key the event by a string the PyYAML-side grader never matches.
        let doc = fm("done_probes:\n  - \"test -n \\\"$(echo hi)\\\"\"");
        assert_eq!(probes_of(&doc), vec![r#"test -n "$(echo hi)""#.to_string()]);
    }

    #[test]
    fn single_quoted_scalar_undoubles_its_quote() {
        let doc = fm("done_probes:\n  - 'echo it''s fine'");
        assert_eq!(probes_of(&doc), vec!["echo it's fine".to_string()]);
    }

    #[test]
    fn plan_path_fragment_is_stripped_before_reading() {
        // `plans/p.md#wave-1` must resolve to plans/p.md, not a literal filename
        // containing the fragment (which would read nothing -> silent Absent).
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("plan.md"), fm("done_probes:\n  - exit 0")).unwrap();
        let events = tmp.path().join("events.jsonl");
        assert!(
            matches!(
                evaluate_done_probes(
                    Some("plan.md#wave-1"),
                    None,
                    tmp.path(),
                    &events,
                    "s1",
                    Duration::from_secs(10)
                ),
                ProbeGate::Pass(_)
            ),
            "a fragment in plan_path must not silently disable the gate"
        );
    }

    #[test]
    fn a_backgrounding_probe_does_not_block_the_drain() {
        // sh exits immediately while the descendant keeps stderr open, so the
        // timeout loop is already over and only the group kill bounds the join.
        let tmp = tempfile::tempdir().unwrap();
        let start = std::time::Instant::now();
        let outcome = run_probe("sleep 300 & exit 0", tmp.path(), Duration::from_secs(30));
        assert_eq!(outcome.render(), "pass");
        assert!(
            start.elapsed() < Duration::from_secs(10),
            "a backgrounded descendant must not hold the drain open (took {:?})",
            start.elapsed()
        );
    }

    // ── project-level done_probes (x-a534) ────────────────────────────────
    //
    // A repo-wide guardrail must apply to every plan in the repo, and no plan
    // doc may switch it off - a guard on one of two reachable paths is
    // decorative.

    fn project(cmds: &[&str]) -> Result<Vec<String>, String> {
        Ok(cmds.iter().map(|c| c.to_string()).collect())
    }

    /// A plan doc that declares no probes of its own.
    fn bare_plan(dir: &Path) -> std::path::PathBuf {
        let plan = dir.join("plan.md");
        std::fs::write(&plan, fm("title: p")).unwrap();
        plan
    }

    #[test]
    fn a_project_probe_gates_a_plan_that_declares_none() {
        // AC1-HP: the repo-wide guardrail runs without being retyped per plan,
        // and its result reaches the event payload.
        let tmp = tempfile::tempdir().unwrap();
        let plan = bare_plan(tmp.path());
        let events = tmp.path().join("events.jsonl");
        match evaluate_done_probes(
            plan.to_str(),
            Some(&project(&["true"])),
            tmp.path(),
            &events,
            "s1",
            Duration::from_secs(10),
        ) {
            ProbeGate::Pass(results) => assert_eq!(results["true"], "pass"),
            _ => panic!("a passing project probe must let the gate through"),
        }
    }

    #[test]
    fn a_failing_project_probe_blocks_and_names_its_source() {
        // AC2-ERR: `probe X exited 1` is ambiguous once there are two
        // declarations; the operator has to know which file to edit.
        let tmp = tempfile::tempdir().unwrap();
        let plan = bare_plan(tmp.path());
        let events = tmp.path().join("events.jsonl");
        match evaluate_done_probes(
            plan.to_str(),
            Some(&project(&["false"])),
            tmp.path(),
            &events,
            "s1",
            Duration::from_secs(10),
        ) {
            ProbeGate::Fail { reason, .. } => assert!(
                reason.contains("project probe `false`"),
                "the reason must name the source: {reason}"
            ),
            _ => panic!("a failing project probe must block"),
        }
    }

    // AC3-INV (a plan declaring `done_probes: []` cannot silence the project's
    // gate) is covered end to end by
    // done_probes_ac3_inv_a_plan_cannot_silence_the_project_gate in
    // tests/loop_check.rs, which drives the real settings merge rather than a
    // hand-built probe list. A unit-level twin would assert strictly less.

    #[test]
    fn an_unparseable_project_declaration_blocks_rather_than_degrading() {
        // AC4-ERR: a config key that degrades to no-gate is a guardrail that
        // disappears when you typo it.
        let tmp = tempfile::tempdir().unwrap();
        let plan = bare_plan(tmp.path());
        let events = tmp.path().join("events.jsonl");
        let junk: Result<Vec<String>, String> = value_as_probe_list(
            &"done_probes = { a = 1 }".parse::<toml::Value>().unwrap()["done_probes"],
        );
        assert!(junk.is_err(), "a mapping is not a probe list");
        match evaluate_done_probes(
            plan.to_str(),
            Some(&junk),
            tmp.path(),
            &events,
            "s1",
            Duration::from_secs(10),
        ) {
            ProbeGate::Fail { reason, results } => {
                assert!(
                    reason.contains("undeterminable"),
                    "must use the plan side's vocabulary: {reason}"
                );
                assert_eq!(results["_undeterminable"], "unparseable-config-declaration");
            }
            _ => panic!("an unreadable project declaration must block"),
        }
    }

    #[test]
    fn the_cap_is_per_source_not_per_union() {
        // AC5-BOUND: 3 + 3 all run. Sharing one budget would make two
        // independent authors compete for one number, so a project policy
        // would eat a plan's operational probes.
        let tmp = tempfile::tempdir().unwrap();
        let plan = tmp.path().join("plan.md");
        std::fs::write(
            &plan,
            fm("done_probes:\n  - echo d\n  - echo e\n  - echo f"),
        )
        .unwrap();
        let events = tmp.path().join("events.jsonl");
        match evaluate_done_probes(
            plan.to_str(),
            Some(&project(&["echo a", "echo b", "echo c"])),
            tmp.path(),
            &events,
            "s1",
            Duration::from_secs(10),
        ) {
            ProbeGate::Pass(results) => assert_eq!(
                results.as_object().unwrap().len(),
                6,
                "all six probes must run: {results}"
            ),
            other => panic!(
                "3 + 3 is within the per-source cap: {}",
                match other {
                    ProbeGate::Fail { reason, .. } => reason,
                    _ => "Absent".to_string(),
                }
            ),
        }

        // A 4th in the project declaration is still a loud refusal.
        match evaluate_done_probes(
            plan.to_str(),
            Some(&project(&["true", "true", "true", "true"])),
            tmp.path(),
            &events,
            "s1",
            Duration::from_secs(10),
        ) {
            ProbeGate::Fail { reason, .. } => assert!(
                reason.contains("config.toml declares 4") && reason.contains("per source"),
                "an over-cap project list must refuse loudly: {reason}"
            ),
            _ => panic!("4 project probes must refuse"),
        }
    }

    #[test]
    fn no_declaration_on_either_source_stays_absent() {
        // The zero-subprocess path must survive the second source.
        let tmp = tempfile::tempdir().unwrap();
        let plan = bare_plan(tmp.path());
        let events = tmp.path().join("events.jsonl");
        assert!(matches!(
            evaluate_done_probes(
                plan.to_str(),
                Some(&project(&[])),
                tmp.path(),
                &events,
                "s1",
                Duration::from_secs(10)
            ),
            ProbeGate::Absent
        ));
    }

    #[test]
    fn config_done_probes_parses_off_the_flat_root() {
        // The file is flat: `done_probes` at the root, not nested under a
        // `config` table.
        let s = parse_settings("done_probes = [\"make a11y-check\"]\n");
        assert_eq!(s.done_probes, Some(Ok(vec!["make a11y-check".to_string()])),);
        assert_eq!(parse_settings("plans_dir = \"x\"\n").done_probes, None);
        assert!(parse_settings("done_probes = \"nope\"\n")
            .done_probes
            .unwrap()
            .is_err());
        assert!(parse_settings("done_probes = [1]\n")
            .done_probes
            .unwrap()
            .is_err());
    }
}