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
//! `fno-agents finalize` (control-plane step 6, ab-f8e5f214): the terminal-only
//! WRITER the stop-hook shim invokes on a terminal-allow `loop-check` decision.
//!
//! It re-homes the mechanical session side-effects out of the skill's
//! pre-promise bash so they fire in EVERY mode (attended, autonomous, megawalk
//! worker) and survive context compaction:
//!
//! - **Always** (any terminal reason): one ledger session-record, carrying
//!   `graph_node_id` + `provider_id` + scalar `session_id` + `cost_usd` + a new
//!   `termination_reason`, so a node's true cost and full session list roll up
//!   by grouping ledger entries on `graph_node_id` (US7).
//! - **Legacy ship** (`DonePRGreen` / `DoneAdvisory`): plan stamp + a mechanical
//!   git-derived handoff artifact. A code ship (DonePRGreen) stamps `in_review`
//!   only (done = merged, x-f34f; the flip happens at merge). An advisory ship
//!   (DoneAdvisory) has no merge event, so it also graduates to `done` here.
//! - **Generic delivery** (`DoneDelivery`): consume the selected strict verdict,
//!   stamp or safely graduate with its receipt, and write a generic handoff.
//! - **`DonePRGreen` only**, when the manifest approves it: arm GitHub's native
//!   auto-merge. This is the one terminal that means "green and reviewed", and
//!   arming it HERE rather than at PR creation is the whole point (x-1951) -
//!   see `should_arm_auto_merge`.
//!
//! ## Why this does not break the read-only stop hook
//!
//! `loop-check` stays a pure read-only DECISION verb; `finalize` is a separate
//! WRITER the shim runs AFTER the allow decision. Nothing `finalize` writes is
//! read by a future `loop-check` decision as a gate:
//!
//! - `loop-check`'s budget axis reads ledger `cost_usd` filtered by THIS
//!   session's `session_id`. `finalize`'s terminal ledger row for the same
//!   session can only push a re-fire toward termination (a higher cost trips
//!   `Budget`, which is itself terminal-allow), never away from it - and a
//!   re-fire early-returns on the `session_finalized` event anyway.
//! - A DIFFERENT session's `loop-check` filters by its own `session_id`, so it
//!   never reads this session's finalize row.
//!
//! ## Non-fatal + idempotent
//!
//! Every sub-step records failures in a `session_finalize_failed` event.
//! Legacy terminal side effects remain non-blocking, while `DoneDelivery`
//! returns failure so the stop-hook can keep the session alive and retry its
//! required receipt, stamp, and handoff writes.
//! `session_finalized` is emitted ONLY when every attempted sub-step succeeded;
//! a partial failure leaves it unemitted so a later stop-hook fire retries the
//! remaining work (each shelled script is itself idempotent: ledger flock +
//! scalar-session-id dedup, first-writer-wins stamp, filename-keyed handoff).
//!
//! The proven Python helpers (`fno.cost._session_cost`, `fno.cost._register`,
//! `fno.plan._stamp`, all in-package modules run via `python3 -m`) do the
//! cost/dedup/flock/stamp work; this verb is a thin orchestrator (Locked
//! Decision 6 - avoids the Python->Rust byte-parity trap), so the shim keeps
//! its Rust-only dependency surface (Domain Pitfall).

use crate::loopcheck::{emit_to_both, now_rfc3339_utc};
use serde_json::{json, Value};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Terminal reasons that ran an actual ship (PR landed or advisory-complete).
/// Only these run the completion side-effects (stamp/graduate/handoff); every
/// terminal reason runs the ledger record. `DoneBatched` and `DoneAwaitingMerge`
/// are deliberately ABSENT: both are terminal-but-not-ship (the batch PR ships a
/// batched member; a human merge past pre-existing main-red closes an
/// awaiting-merge node via reconcile) - they get the always-branch ledger row
/// but must never stamp/graduate the plan.
const SHIP_REASONS: &[&str] = &["DonePRGreen", "DoneAdvisory"];

/// Terminal reasons that signal a STUCK session: the loop-check verb saw no
/// forward progress, or the budget cap tripped, and let the session exit
/// without shipping. These get a postmortem artifact the autocorrect monthly
/// review consumes via `~/.fno/corrections.log` (ab-1a92b677: re-homed here
/// after the control-plane wedge dropped the old stop-hook generator; moved
/// again from ~/.claude/ to ~/.fno/ per the placement rule, ab-f063 Wave 2).
/// Interrupted/Aborted join the set: a session that gave up mid-wedge or got
/// cancelled is stuck-but-differently-terminated and belongs in the corpus.
/// A ship or a benign NoWork terminal is not "stuck": NoWork is megawalk finding
/// nothing to do, and ship reasons succeeded. There is no `Blocked` terminal -
/// a blocked session ends Interrupted/Aborted/NoProgress, all covered here.
const POSTMORTEM_REASONS: &[&str] = &["NoProgress", "Budget", "Interrupted", "Aborted"];

// ── arg parsing ─────────────────────────────────────────────────────────────

#[derive(Debug, Default)]
struct FinalizeArgs {
    state: Option<PathBuf>,
    transcript: Option<PathBuf>,
    cwd: Option<PathBuf>,
    reason: Option<String>,
    // Overrides (primarily for tests / non-default layouts).
    events: Option<PathBuf>,
    global_events: Option<PathBuf>,
    settings: Option<PathBuf>,
    handoffs_dir: Option<PathBuf>,
    postmortems_dir: Option<PathBuf>,
}

fn parse_args(args: &[String]) -> Result<FinalizeArgs, String> {
    let mut a = FinalizeArgs::default();
    let mut it = args.iter();
    while let Some(flag) = it.next() {
        let take = |it: &mut std::slice::Iter<String>| -> Result<String, String> {
            it.next()
                .cloned()
                .ok_or_else(|| format!("{flag} needs a value"))
        };
        match flag.as_str() {
            "--state" => a.state = Some(PathBuf::from(take(&mut it)?)),
            "--transcript" => a.transcript = Some(PathBuf::from(take(&mut it)?)),
            "--cwd" => a.cwd = Some(PathBuf::from(take(&mut it)?)),
            "--reason" => a.reason = Some(take(&mut it)?),
            "--events" => a.events = Some(PathBuf::from(take(&mut it)?)),
            "--global-events" => a.global_events = Some(PathBuf::from(take(&mut it)?)),
            "--settings" => a.settings = Some(PathBuf::from(take(&mut it)?)),
            "--handoffs-dir" => a.handoffs_dir = Some(PathBuf::from(take(&mut it)?)),
            "--postmortems-dir" => a.postmortems_dir = Some(PathBuf::from(take(&mut it)?)),
            other => return Err(format!("unknown flag: {other}")),
        }
    }
    Ok(a)
}

const HELP: &str = "fno-agents finalize - terminal-only side-effect writer (step 6)\n\
Usage: fno-agents finalize --state <target-state.md> --cwd <project-root> --reason <TerminationReason> \\\n\
                           [--transcript <transcript.jsonl>] [--events <p>] [--global-events <p>] \\\n\
                           [--settings <p>] [--handoffs-dir <p>] [--postmortems-dir <p>]\n\
Reason values: DonePRGreen|DoneAdvisory|DoneDelivery|DoneBatched|DoneAwaitingMerge|DonePlanned|NoWork|Budget|NoProgress|Interrupted|Aborted";

// ── manifest fields finalize reads directly ────────────────────────────────

/// The three manifest fields finalize needs itself (everything else is read by
/// the shelled Python helpers from the same manifest path).
#[derive(Debug, Default)]
struct ManifestFields {
    /// Target-minted session id: idempotency key, handoff filename, event data.
    session_id: Option<String>,
    /// Claude transcript UUID: positional arg to fno.cost._session_cost / _register.
    claude_transcript_id: Option<String>,
    /// Plan to stamp/graduate (ship branch only). Empty/absent -> skip.
    plan_path: Option<String>,
    /// Feature title for the handoff header.
    input: Option<String>,
    /// Backlog node id (lives in the manifest BODY, below the frontmatter).
    graph_node_id: Option<String>,
    /// Harness (conversation) session id captured at init: the do-stamp's
    /// identity-continuity input, passed through to the Python primitive.
    harness_session_id: Option<String>,
    /// HEAD at init: baseline for the `initial_head..HEAD` work-evidence range.
    /// Absent on manifests minted before x-0469 -> the do stamp skips.
    initial_head: Option<String>,
    /// Init instant: the author-date floor for work evidence, and the value the
    /// do row carries as `claimed_at` (the start of the implementation window).
    created_at: Option<String>,
    /// Cross-project plan: graduation must wait for ALL project PRs, so the
    /// expected URL count is derived from the plan's `projects:` map, never 1.
    cross_project: bool,
    /// Merge posture resolved by init (config folded with this run's modifiers,
    /// where every refusal outranks every grant). Gates arming GitHub's native
    /// auto-merge at a green terminal. `None` = the key was absent.
    auto_merge_approved: Option<bool>,
}

/// Does this line close the double-quoted scalar `init-target-state.sh` opened?
///
/// The rule is NOT backslash parity. The writer escapes quotes and NOT
/// backslashes (`${INITIAL_INPUT//\"/\\\"}`, init:811), so the manifest is not
/// backslash-escaped YAML and a parity rule is wrong in both directions: user
/// text ending in `\"` arrives as `\\"`, which parity reads as even and closes
/// the scalar early, handing the forgery back.
///
/// What that escaping DOES guarantee is one-directional and enough: every quote
/// the user typed gets exactly one `\` prepended, so a user quote is ALWAYS
/// immediately preceded by a backslash, however many backslashes they typed. A
/// closing quote with no backslash before it therefore cannot have come from the
/// user, and is the terminator.
///
/// The residual ambiguity is input ending in a lone `\`: its own closing quote
/// carries a preceding backslash and so reads as user text, and the scalar
/// instead ends at the next quoted line - `plan_path: "..."` (init:840) in the
/// real layout. That costs one line of reduced trust and nothing else, because
/// `parse_manifest_fields` lets the terminator line fall through and parse; only
/// the merge posture consults the mark, and `plan_path` does not.
fn ends_quoted_scalar(line: &str) -> bool {
    let Some(rest) = line.strip_suffix('"') else {
        return false;
    };
    !rest.ends_with('\\')
}

/// Scan the WHOLE manifest (frontmatter AND body) for the keys we need.
/// `graph_node_id`/`target_claim_*` live below the closing `---`, so a
/// frontmatter-only parse (like loop-check's) would miss them.
fn parse_manifest_fields(content: &str) -> ManifestFields {
    let mut m = ManifestFields::default();
    // Init writes the run's raw argument as `input: "<...>"` (init:839), so a
    // MULTI-LINE argument spills real newlines into the manifest and every
    // continuation line reaches this loop looking like a `key: value` pair.
    // `input` is written BEFORE the canonical `auto_merge_approved` (init:886),
    // so a pasted spec containing that key would be read as the merge posture
    // and outrank the real refusal below it.
    //
    // Lines inside that scalar are tracked as UNTRUSTED rather than skipped.
    // Skipping them is what an earlier cut of this did, and it silently ate
    // `plan_path`: the scalar's terminator is ambiguous for input ending in a
    // lone backslash (see `ends_quoted_scalar`), and an over-long skip swallowed
    // the very next line - dropping the plan stamp with no error. Only the merge
    // posture is withheld here, so every other field parses exactly as it did
    // before this guard existed and an ambiguous scalar costs nothing.
    //
    // That asymmetry is the whole safety argument: an unterminated scalar marks
    // MORE lines untrusted, and untrusted only ever withholds the grant, leaving
    // `auto_merge_approved` as `None` -> no arming. Both directions fail closed.
    let mut untrusted = false;
    for line in content.lines() {
        let line = line.trim();
        // The terminator line closes the scalar for everything AFTER it, but is
        // itself still untrusted: when the scalar ends on the same line as the
        // user's last line of text, that line is user text wearing a closing
        // quote (`auto_merge_approved: true"`). It must still FALL THROUGH and
        // parse, never be consumed - for input ending in a lone backslash the
        // real terminator is `plan_path: "..."` (init:840), and skipping it was
        // how an earlier cut silently dropped the plan stamp.
        let line_untrusted = untrusted;
        if untrusted && ends_quoted_scalar(line) {
            untrusted = false;
        }
        // Skip markdown headings and frontmatter fences; a `key: value` match
        // below is all we want.
        if line.is_empty() || line.starts_with('#') || line == "---" {
            continue;
        }
        let Some((k, v)) = line.split_once(':') else {
            continue;
        };
        let k = k.trim();
        let raw = v.trim();
        // A multi-line `input` opens a quoted scalar here; everything up to its
        // closing quote is the user's text, not manifest keys.
        if !line_untrusted
            && k == "input"
            && raw.starts_with('"')
            && !(raw.len() >= 2 && ends_quoted_scalar(raw))
        {
            untrusted = true;
        }
        let v = raw.trim_matches(|c| c == '"' || c == '\'');
        // First non-empty wins (frontmatter precedes body); never overwrite a
        // real value with a later blank.
        let set = |slot: &mut Option<String>, val: &str| {
            if slot.is_none() && !val.is_empty() && val != "null" {
                *slot = Some(val.to_string());
            }
        };
        match k {
            // fno_id is the canonical target-minted id; session_id is the
            // pre-rename fallback. `set` keeps the first non-empty, so fno_id
            // (written first in the manifest) wins.
            "fno_id" | "session_id" => set(&mut m.session_id, v),
            // Current key is claude_session_id; accept the pre-rename
            // claude_transcript_id as a fallback for one release. `set` keeps the
            // first non-empty value, so the current key (written first) wins.
            "claude_session_id" | "claude_transcript_id" => set(&mut m.claude_transcript_id, v),
            "plan_path" => set(&mut m.plan_path, v),
            "input" => set(&mut m.input, v),
            "graph_node_id" => set(&mut m.graph_node_id, v),
            "harness_session_id" => set(&mut m.harness_session_id, v),
            "initial_head" => set(&mut m.initial_head, v),
            "created_at" => set(&mut m.created_at, v),
            "cross_project" => m.cross_project = v == "true",
            // The merge-authority read, and the only key that consults
            // `untrusted`. First occurrence wins, unlike cross_project's
            // last-wins, so a trailing line cannot overwrite the canonical one
            // either. A line inside the `input` scalar is ignored outright: the
            // "arbitrary prose must never grant merge authority" rule init
            // applies when it folds the posture (x-e938) has to hold here too,
            // or the fold is decorative.
            "auto_merge_approved" if !line_untrusted && m.auto_merge_approved.is_none() => {
                m.auto_merge_approved = Some(v == "true")
            }
            _ => {}
        }
    }
    m
}

// ── idempotency ─────────────────────────────────────────────────────────────

/// Inspect prior `session_finalized` events for this session_id.
///
/// Returns:
/// - `Some(true)`  - a prior finalize completed a SHIP (stamp/graduate/handoff
///   ran); the session is fully done, nothing more to do on any later fire.
/// - `Some(false)` - a prior finalize completed but only the non-ship ledger
///   record (the always-branch); the ledger row exists, but the ship
///   side-effects have NOT run.
/// - `None`        - no completed finalize yet (or only `session_finalize_failed`,
///   which is intentionally not counted so a later fire retries).
///
/// A successful finalize is recorded ONLY when every attempted sub-step
/// succeeded, so a partially-failed prior run leaves this `None` and the next
/// fire retries. The `ship` flag distinguishes a non-ship terminal (Budget /
/// NoProgress / ...) from a real ship, so a session that terminated non-ship
/// first and then ships within the same session still runs its ship
/// side-effects on the ship fire (the lockout bug, sigma-review HIGH).
fn prior_finalize_ship(project_events: &Path, session_id: &str) -> Option<bool> {
    let content = fs::read_to_string(project_events).ok()?;
    let mut seen = None;
    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("session_finalized")
            || val.pointer("/data/session_id").and_then(|v| v.as_str()) != Some(session_id)
        {
            continue;
        }
        let ship = val
            .pointer("/data/ship")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        if ship {
            return Some(true); // a completed ship is terminal-complete
        }
        seen = Some(false);
    }
    seen
}

// ── a2a status-breakpoint run_summary (x-dbaf) ──────────────────────────────

/// Payload cap for the run_summary `data` object (mirrors events.rs
/// MAX_EVENT_PAYLOAD_BYTES). run_summary is lean by construction, but honoring
/// the cap keeps the Rust path's behavior identical to the daemon EventEmitter.
const RUN_SUMMARY_DATA_CAP: usize = 500;

/// Count the run's task ticks in events.jsonl. Correlates on the envelope-level
/// `run` (the target-run id), so a co-located second run's events never mix in.
/// tasks_failed counts task_done events whose outcome is FAILED - the gap
/// (tasks_started > tasks_done) is what exposes a crashed executor (AC2-FR).
fn count_run_tasks(project_events: &Path, run: &str) -> (u64, u64, u64) {
    use std::io::BufRead;
    let (mut started, mut done, mut failed) = (0u64, 0u64, 0u64);
    // Stream line-by-line and reuse one buffer: events.jsonl grows to the
    // rotation cap, so reading it whole would balloon memory (gemini review).
    if let Ok(file) = fs::File::open(project_events) {
        let mut reader = std::io::BufReader::new(file);
        let mut line = String::new();
        while reader.read_line(&mut line).unwrap_or(0) > 0 {
            if let Ok(v) = serde_json::from_str::<Value>(&line) {
                if v.get("run").and_then(|r| r.as_str()) == Some(run) {
                    match v.get("type").and_then(|t| t.as_str()) {
                        Some("task_started") => started += 1,
                        Some("task_done") => {
                            done += 1;
                            if v.get("outcome").and_then(|o| o.as_str()) == Some("FAILED") {
                                failed += 1;
                            }
                        }
                        _ => {}
                    }
                }
            }
            line.clear();
        }
    }
    (started, done, failed)
}

/// Append a pre-built extended envelope as one events.jsonl line (O_APPEND,
/// create-if-missing). Non-fatal: a write failure logs and returns, never
/// wedging finalize. Kept local to finalize (not loopcheck's fixed-envelope
/// writer) because run_summary carries envelope-level routable fields.
fn append_envelope(path: &Path, envelope: &Value) {
    use std::io::Write;
    let Ok(mut line) = serde_json::to_string(envelope) else {
        eprintln!("finalize: failed to serialize run_summary");
        return;
    };
    line.push('\n');
    if let Some(parent) = path.parent() {
        let _ = fs::create_dir_all(parent);
    }
    match fs::OpenOptions::new().create(true).append(true).open(path) {
        Ok(mut f) => {
            if let Err(e) = f.write_all(line.as_bytes()) {
                eprintln!(
                    "finalize: run_summary write to {} failed: {e}",
                    path.display()
                );
            }
        }
        Err(e) => eprintln!("finalize: run_summary open {} failed: {e}", path.display()),
    }
}

/// Build + emit the run_summary terminal event to both event logs. Best-effort
/// throughout: emission never changes the exit code or holds session_finalized.
#[allow(clippy::too_many_arguments)]
fn emit_run_summary(
    project_events: &Path,
    global_events: &Path,
    run: &str,
    node: Option<&str>,
    ship: bool,
    reason: &str,
    pr_url: Option<&str>,
) {
    let (started, done, failed) = count_run_tasks(project_events, run);
    // Terminal reason -> return-contract outcome: a ship terminal is SUCCESS
    // (DONE_WITH_CONCERNS if any task failed); a non-ship terminal (Budget /
    // NoProgress / Interrupted) is FAILED.
    let outcome = if !ship {
        "FAILED"
    } else if failed > 0 {
        "DONE_WITH_CONCERNS"
    } else {
        "SUCCESS"
    };
    let mut data = json!({
        "tasks_started": started,
        "tasks_done": done,
        "tasks_failed": failed,
        "termination_reason": reason,
    });
    if let Some(url) = pr_url {
        data["pr_url"] = json!(url);
    }
    // Honor the payload cap (AC2-EDGE, Rust path): oversized data -> the small
    // meta-event, so an auditor sees the drop rather than a silently huge line.
    let payload_len = serde_json::to_string(&data).map(|s| s.len()).unwrap_or(0);
    if payload_len > RUN_SUMMARY_DATA_CAP {
        data = json!({"intended_kind": "run_summary", "size": payload_len});
    }
    let mut env = json!({
        "ts": now_rfc3339_utc(),
        "v": 1,
        "type": "run_summary",
        "source": "target",
        "run": run,
        "outcome": outcome,
        "data": data,
    });
    if let Some(n) = node {
        env["node"] = json!(n);
    }
    append_envelope(project_events, &env);
    if project_events != global_events {
        append_envelope(global_events, &env);
    }
}

/// Push leg for run_summary (x-dbaf): notify the parent handle. run_summary
/// emits natively above, so the push shells the Python resolver (`fno event
/// push-parent`) rather than reimplementing registry lookup + mail in Rust.
/// Best-effort: a missing `fno` / no spawn lineage is a silent skip; the
/// events.jsonl line already landed independently (AC1-FR). `fno` (not a bare
/// interpreter) is safe to shell - a PATH miss just skips.
fn push_run_summary_to_parent(run: &str, node: Option<&str>, reason: &str) {
    let mut cmd = Command::new("fno");
    cmd.args([
        "event",
        "push-parent",
        "--type",
        "run_summary",
        "--run",
        run,
        "--reason",
        reason,
    ]);
    if let Some(n) = node {
        cmd.args(["--node", n]);
    }
    if let Err(e) = cmd.output() {
        eprintln!("finalize: run_summary parent push skipped (non-fatal): {e}");
    }
}

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

/// `fno-agents finalize ...`. Returns 0 for a completed write, 1 when generic
/// delivery must retry, and 2 for CLI misuse. Legacy side-effect failures stay
/// non-fatal.
pub fn run_finalize(args: &[String]) -> i32 {
    if args
        .iter()
        .any(|a| a == "-h" || a == "--help" || a == "help")
    {
        println!("{HELP}");
        return 0;
    }
    let a = match parse_args(args) {
        Ok(a) => a,
        Err(msg) => {
            eprintln!("finalize: {msg}\n{HELP}");
            return 2;
        }
    };
    let (Some(state), Some(cwd), Some(reason)) = (a.state, a.cwd, a.reason) else {
        eprintln!("finalize: --state, --cwd and --reason are required\n{HELP}");
        return 2;
    };
    let delivery_ship = reason == "DoneDelivery";

    let home = std::env::var_os("HOME").map(PathBuf::from);
    let project_events = a.events.unwrap_or_else(|| cwd.join(".fno/events.jsonl"));
    let global_events = a.global_events.unwrap_or_else(|| {
        home.clone()
            .unwrap_or_else(|| cwd.clone())
            .join(".fno/events.jsonl")
    });

    // Missing manifests are the non-fatal delegated-session path for legacy
    // reasons. Generic delivery must retry because its required writes cannot
    // be proven without the session-bound manifest.
    let content = match fs::read_to_string(&state) {
        Ok(c) => c,
        Err(e) => {
            eprintln!(
                "finalize: manifest {} unreadable ({e}); nothing to finalize (likely delegated/archived)",
                state.display()
            );
            return i32::from(delivery_ship);
        }
    };
    let m = parse_manifest_fields(&content);
    let Some(session_id) = m
        .session_id
        .clone()
        .filter(|value| !value.trim().is_empty())
    else {
        eprintln!("finalize: manifest has no session_id; skipping (cannot dedup)");
        return i32::from(delivery_ship);
    };

    let legacy_ship = SHIP_REASONS.contains(&reason.as_str());
    let ship = legacy_ship || delivery_ship;

    // Idempotency, ship-aware (sigma-review HIGH): a prior COMPLETED ship means
    // the whole session is done. A prior non-ship finalize means only the ledger
    // row exists; if THIS fire is also non-ship there is nothing new to do, but
    // if THIS fire is a SHIP it must still run the ship side-effects - a session
    // that hit a non-ship terminal (Budget / NoProgress) and then shipped within
    // the same session would otherwise never get stamped/graduated/handed off.
    let mut skip_ledger = false;
    match prior_finalize_ship(&project_events, &session_id) {
        Some(true) => {
            eprintln!("finalize: session {session_id} already finalized (ship); early-return");
            return 0;
        }
        // `DoneAwaitingMerge` is not in SHIP_REASONS, so without this it would
        // early-return here and never reach the always-run tail. A session that
        // hits Budget and then resumes to DoneAwaitingMerge would silently lose
        // its do stamp - the same "correct wiring, missing coverage" failure this
        // backstop exists to fix. Everything downstream is idempotent.
        Some(false) if !ship && !is_do_stamp_terminal(&reason) => {
            eprintln!(
                "finalize: session {session_id} ledger already recorded (non-ship); early-return"
            );
            return 0;
        }
        Some(false) => {
            // Ledger row already written by the prior non-ship finalize; skip the
            // redundant ledger step (register-task would dedup it anyway) and run
            // only the ship side-effects below.
            skip_ledger = true;
        }
        None => {}
    }

    // Transcript UUID for the cost/ledger scripts: prefer the manifest's
    // canonical claude_transcript_id, fall back to the --transcript basename.
    let transcript_uuid = m
        .claude_transcript_id
        .clone()
        .or_else(|| {
            a.transcript
                .as_ref()
                .and_then(|p| p.file_stem())
                .map(|s| s.to_string_lossy().into_owned())
        })
        .unwrap_or_default();

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

    // ── ALWAYS: ledger session-record (skipped only when a prior non-ship
    //    finalize already wrote this session's row) ──────────────────────────
    let ledger_written = if skip_ledger {
        true // the prior non-ship finalize already wrote the row
    } else {
        match write_ledger_record(&cwd, &state, &transcript_uuid, &reason) {
            Ok(()) => true,
            Err(e) => {
                eprintln!("finalize: ledger record failed: {e}");
                failed.push("ledger".into());
                false
            }
        }
    };

    // ── SHIP ONLY: stamp (+ graduate for advisory) + handoff ───────────────
    // For a CODE ship (DonePRGreen) the plan is stamped `in_review` only: done now
    // means MERGED (x-f34f), and the `in_review -> done` flip happens at merge via
    // the write-time status projection. An ADVISORY/doc ship (DoneAdvisory) has
    // NO merge event - ship IS its completion - so it must still graduate to
    // `done` here, else the plan is stranded at `in_review` on the active board
    // (codex P2). expected_url_count is still recorded either way for the manual
    // `graduate` verb and the cross-project safety net.
    let mut stamped = false;
    let mut handoff_path: Option<String> = None;
    let mut delivery_terminal_message: Option<String> = None;
    if legacy_ship {
        let plan = m.plan_path.clone().unwrap_or_default();
        if !plan.is_empty() {
            let expected = derive_expected_url_count(&cwd, &plan, m.cross_project);
            // Graduate only for the merge-less advisory terminal; a cross-project
            // advisory still waits for a derivable count (never graduate early).
            let do_graduate = reason == "DoneAdvisory" && (!m.cross_project || expected.is_some());
            match stamp_and_graduate(&cwd, &plan, &session_id, expected, do_graduate, None) {
                Ok(()) => stamped = true,
                Err(step) => {
                    eprintln!("finalize: {step} failed");
                    failed.push(step);
                }
            }
        }
        match write_handoff(
            &cwd,
            &state,
            &session_id,
            &m,
            &transcript_uuid,
            a.handoffs_dir.as_deref(),
            a.settings.as_deref(),
            home.as_deref(),
        ) {
            Ok(p) => handoff_path = Some(p),
            Err(e) => {
                eprintln!("finalize: handoff failed: {e}");
                failed.push("handoff".into());
            }
        }

        // W6 verifier advisory (x-f063): AC-vs-diff verdict, recorded then
        // ignored. Log-only and never pushed to `failed` - an advisory must
        // never wedge the loop or hold session_finalized open for retry.
        // Events paths are forwarded so the module's per-session exactly-once
        // guard reads the same log finalize writes (a retried fire after a
        // partial failure must not double-emit or re-spend on a spawn).
        let mut adv = py_module(&cwd);
        adv.arg("-m")
            .arg("fno.verify_advise")
            .arg("--node-id")
            .arg(m.graph_node_id.as_deref().unwrap_or(""))
            .arg("--plan-path")
            .arg(m.plan_path.as_deref().unwrap_or(""))
            .arg("--session-id")
            .arg(&session_id)
            .arg("--reason")
            .arg(&reason)
            .arg("--events")
            .arg(&project_events)
            .arg("--global-events")
            .arg(&global_events);
        match adv.output() {
            Ok(out) if !out.status.success() => eprintln!(
                "finalize: verify_advise failed with exit {:?}: {}",
                out.status.code(),
                String::from_utf8_lossy(&out.stderr).trim()
            ),
            Ok(out) => {
                // rc=0 is the module's contract even when its internals failed
                // (verifier died, event emit failed): forward any stderr so
                // those messages reach the stop hook's finalize log instead of
                // dying in a dead channel (sigma silent-failure P1).
                let err_raw = String::from_utf8_lossy(&out.stderr);
                let err = err_raw.trim();
                if !err.is_empty() {
                    eprintln!("finalize: verify_advise: {err}");
                }
            }
            Err(e) => eprintln!("finalize: verify_advise spawn failed: {e}"),
        }
    }

    if delivery_ship {
        match crate::delivery_completion::selected_receipt(
            &project_events,
            m.graph_node_id.as_deref(),
            &session_id,
        ) {
            Some(receipt) => {
                delivery_terminal_message =
                    Some(format!("generic delivery finalized via {}", receipt.uri));
                let plan = m.plan_path.clone().unwrap_or_default();
                if !plan.is_empty() {
                    let expected = derive_expected_url_count(&cwd, &plan, m.cross_project);
                    let do_graduate = !m.cross_project || expected.is_some();
                    match stamp_and_graduate(
                        &cwd,
                        &plan,
                        &session_id,
                        expected,
                        do_graduate,
                        Some(&receipt.uri),
                    ) {
                        Ok(()) => stamped = true,
                        Err(step) => failed.push(step),
                    }
                }
                let dir = resolve_handoffs_dir(
                    a.handoffs_dir.as_deref(),
                    a.settings.as_deref(),
                    &cwd,
                    home.as_deref(),
                );
                match crate::delivery_completion::write_receipt_handoff(&dir, &session_id, &receipt)
                {
                    Ok(path) => handoff_path = Some(path),
                    Err(error) => {
                        eprintln!("finalize: generic handoff failed: {error}");
                        failed.push("handoff".into());
                    }
                }
            }
            None => {
                eprintln!("finalize: selected delivery verdict event missing");
                failed.push("delivery_receipt".into());
            }
        }
    }

    // ── STUCK ONLY: postmortem artifact (ab-1a92b677) ──────────────────────
    // A stuck terminal (NoProgress/Budget/Interrupted/Aborted) means the session
    // gave up, ran out of budget, or was cancelled mid-wedge without shipping.
    // Re-home the BLOCKED-postmortem generator the wedge dropped when the stop
    // hook became a thin shim: write a structured artifact + a corrections.log
    // pointer so the autocorrect monthly review can mechanically consume what
    // went wrong. Non-fatal and idempotent (filename keyed by date+session) like
    // every other sub-step. A ship reason is never in POSTMORTEM_REASONS, so a
    // session that hit Budget/NoProgress and later shipped writes the postmortem
    // exactly once (on the stuck fire), never on the ship fire.
    let mut postmortem_path: Option<String> = None;
    if POSTMORTEM_REASONS.contains(&reason.as_str()) {
        match write_postmortem(
            &cwd,
            &session_id,
            &m,
            &reason,
            a.transcript.as_deref(),
            a.postmortems_dir.as_deref(),
            a.settings.as_deref(),
            home.as_deref(),
        ) {
            Ok(p) => postmortem_path = Some(p),
            Err(e) => {
                eprintln!("finalize: postmortem failed: {e}");
                failed.push("postmortem".into());
            }
        }
    }

    // ── bg worker terminal-stop marker (x-fcbf) ────────────────────────────
    // A fire-and-forget `claude --bg` /target|/think worker parks at its idle
    // prompt on a terminal loop decision and never exits (the stop hook allows
    // the TURN, not the PROCESS), piling up against agents.max_live. finalize
    // cannot self-exit (it is the worker's child), so it drops a marker the
    // external daemon sweep consumes to `claude stop` the parked worker. Gated
    // to footnote-SPAWNED (FNO_AGENT_SELF) + non-loop-driven (FNO_DRIVER_LIB
    // unset) sessions so an operator's own terminal /target and loop-run
    // children stay parked. Best-effort + log-only: never held for retry, never
    // rolls back the ledger/stamp (mirrors verify_advise's non-wedge contract).
    let agent_self = std::env::var_os("FNO_AGENT_SELF").is_some();
    let driver_lib = std::env::var_os("FNO_DRIVER_LIB").is_some();
    let mut terminal_stop_marked = false;
    if let Some(uuid) =
        crate::terminal_stop::should_mark(agent_self, driver_lib, m.claude_transcript_id.as_deref())
    {
        let agents_home = crate::paths::AgentsHome::from_env();
        match crate::terminal_stop::write_marker(&agents_home, uuid, &reason) {
            Ok(p) => {
                terminal_stop_marked = true;
                eprintln!("finalize: terminal-stop marker written: {}", p.display());
            }
            Err(e) => eprintln!("finalize: terminal-stop marker failed (non-fatal): {e}"),
        }
    }

    // ── a2a status-breakpoint run_summary (x-dbaf) ──────────────────────────
    // One per-run terminal summary carrying task counts + termination reason,
    // in the extended envelope. Best-effort; the pull leg (events.jsonl) is
    // authoritative and the push leg (task 1.4) rides it. gh is shelled for the
    // PR url only on a ship terminal.
    let run_summary_pr = if legacy_ship { gh_pr_url(&cwd) } else { None };
    emit_run_summary(
        &project_events,
        &global_events,
        &session_id,
        m.graph_node_id.as_deref(),
        ship,
        &reason,
        run_summary_pr.as_deref(),
    );
    push_run_summary_to_parent(&session_id, m.graph_node_id.as_deref(), &reason);

    // ── node<->PR pr_number backstop stamp (x-280d) ────────────────────────
    // Runs in the always-run tail (first fire of every reason), so it stamps
    // even a non-ship/awaiting-merge terminal that left an open PR. Non-fatal;
    // deliberately not returned into `failed`.
    if !delivery_ship {
        stamp_node_pr(&cwd, m.graph_node_id.as_deref());
    }

    // ── guarded do-provenance backstop (x-0469) ────────────────────────────
    // Same shape and same fatality as the stamp above: log-only, deliberately
    // not returned into `failed` (a guard skip must never wedge the loop).
    stamp_node_do(&cwd, &m, &reason);

    // ── arm auto-merge at the green gate, not at PR creation (x-1951) ──────
    // Last, so the plan stamp and both node<->PR stamps have already landed
    // before the merge is handed to GitHub. Same log-only fatality as the two
    // stamps above.
    let approved = m.auto_merge_approved.unwrap_or(false);
    let (auto_merge_armed, auto_merge_blocked_reason) = if should_arm_auto_merge(&reason, approved)
    {
        match optional_review_block_reason(&cwd) {
            None => (arm_auto_merge(&cwd), None),
            Some(blocked) => {
                eprintln!("finalize: native auto-merge withheld: {blocked}");
                (false, Some(blocked))
            }
        }
    } else {
        (false, None)
    };
    // Without this, "approved but this terminal is ineligible" and "never
    // approved" are the same silence, and the event's `auto_merge_armed: false`
    // cannot tell them apart either.
    if approved && !should_arm_auto_merge(&reason, approved) {
        eprintln!(
            "finalize: auto-merge approved but {reason} is not an arming terminal; not armed"
        );
    }

    // ── emit terminal event ────────────────────────────────────────────────
    let mut data = json!({
        "session_id": session_id,
        "termination_reason": reason,
        "ship": ship,
        "ledger_written": ledger_written,
        "stamped": stamped,
        "handoff_path": handoff_path,
        "postmortem_path": postmortem_path,
        "terminal_stop_marked": terminal_stop_marked,
        "graph_node_id": m.graph_node_id,
        // Re-homed from `fno worker ship`'s return dict (x-1951): the fact now
        // belongs to the terminal that authorized it, not to PR creation.
        "auto_merge_armed": auto_merge_armed,
    });
    if let Some(blocked) = auto_merge_blocked_reason {
        data["auto_merge_blocked_reason"] = json!(blocked);
    }
    if delivery_ship && failed.is_empty() {
        let emitted = delivery_terminal_message.as_deref().is_some_and(|message| {
            crate::delivery_completion::emit_terminal(
                &project_events,
                &global_events,
                &session_id,
                message,
            )
        });
        if !emitted {
            failed.push("delivery_terminal".into());
        }
    }
    let delivery_retry = delivery_ship && !failed.is_empty();
    if failed.is_empty() {
        emit_to_both(&project_events, &global_events, "session_finalized", data);
    } else {
        data["failed_steps"] = json!(failed);
        // session_finalized intentionally NOT emitted: a later fire retries the
        // failed step (each shelled helper is idempotent).
        emit_to_both(
            &project_events,
            &global_events,
            "session_finalize_failed",
            data,
        );
    }
    if delivery_retry {
        1
    } else {
        0
    }
}

// ── ledger (always) ─────────────────────────────────────────────────────────

/// Build a `python3` command (for `-m <module>`) rooted at `cwd`, injecting the
/// repo's `cli/src` onto PYTHONPATH when running from a source checkout so the
/// in-package `fno.*` modules import without an installed/editable package
/// (codex PR #515 P1). When the stop hook resolves the checkout-built binary,
/// these children otherwise run with only `cwd` on `sys.path`, where `fno` is
/// not importable, so every terminal finalize silently failed to write the
/// ledger / stamp the plan. In an installed environment `cli/src` is not found
/// relative to the binary, PYTHONPATH is left untouched, and the installed
/// `fno` package is used.
fn py_module(cwd: &Path) -> Command {
    let mut cmd = Command::new(py_interpreter(cwd));
    cmd.current_dir(cwd);
    if let Some(src) = repo_cli_src(cwd) {
        let joined = match std::env::var_os("PYTHONPATH") {
            Some(prev) if !prev.is_empty() => {
                // APPEND (not prepend): cli/src is only a fallback that resolves
                // `fno` when nothing else does (the codex P1 source-checkout
                // case). An existing PYTHONPATH - a deliberate override, or the
                // finalize_e2e stub package - must keep precedence, so we add
                // cli/src AFTER it rather than shadowing it.
                let mut s = prev;
                s.push(":");
                s.push(&src);
                s
            }
            _ => std::ffi::OsString::from(&src),
        };
        cmd.env("PYTHONPATH", joined);
    }
    cmd
}

/// A `cli/.venv/bin/python3` under `root`, but ONLY when `root` is genuinely a
/// footnote source checkout (it also holds `cli/src/fno/__init__.py`). Gating on
/// the co-located package guards two cases (codex review on the x-b74b PR): a
/// foreign project `cwd` that happens to carry its own `cli/.venv` without `fno`
/// installed, and a mis-derived canonical root from a nonstandard git-dir
/// layout - either would otherwise hand back a venv where `import fno` fails and
/// silently regress ledger/stamp finalization.
fn footnote_venv(root: &Path) -> Option<String> {
    let venv = root.join("cli/.venv/bin/python3");
    if venv.is_file() && root.join("cli/src/fno/__init__.py").is_file() {
        return Some(venv.to_string_lossy().into_owned());
    }
    None
}

/// Locate `<repo>/cli/src` (the dir holding `cli/src/fno/__init__.py`). Anchored
/// on the target PROJECT (`cwd`), NOT the running binary: the DEPLOYED
/// fno-agents binary lives in `~/.local/bin`, whose ancestors hold no checkout,
/// so a `current_exe()` walk found neither `cli/src` nor `cli/.venv` and every
/// deployed-binary finalize dropped its ledger row (x-b74b). `cwd` is the
/// worktree, which tracks `cli/src`. Falls back to the canonical repo, then to a
/// `current_exe()` walk (checkout-built binary run outside its repo). `None`
/// when nothing resolves, so PYTHONPATH stays unset and an installed `fno` is
/// used.
fn repo_cli_src(cwd: &Path) -> Option<String> {
    for anc in cwd.ancestors() {
        if anc.join("cli/src/fno/__init__.py").is_file() {
            return Some(anc.join("cli/src").to_string_lossy().into_owned());
        }
    }
    if let Some(root) = crate::paths::canonical_repo_root(cwd) {
        if root.join("cli/src/fno/__init__.py").is_file() {
            return Some(root.join("cli/src").to_string_lossy().into_owned());
        }
    }
    let exe = std::env::current_exe().ok()?;
    for anc in exe.ancestors() {
        if anc.join("cli/src/fno/__init__.py").is_file() {
            return Some(anc.join("cli/src").to_string_lossy().into_owned());
        }
    }
    None
}

/// The interpreter finalize's Python helpers run under. In a source checkout,
/// prefer the repo's `cli/.venv` python: bare `python3` on PATH (e.g. Homebrew's
/// `/opt/homebrew/opt/python@3.x`) resolves the `fno` package off PYTHONPATH but
/// lacks fno's third-party deps (pydantic, ...), so `import fno.config` raised
/// ModuleNotFoundError and every terminal finalize logged `ledger record failed`
/// / `stamp failed` and wrote no termination_reason row. The venv has both fno
/// and its deps. PYTHONPATH entries still precede site-packages, so the
/// finalize_e2e stub package keeps precedence over the venv's installed `fno`.
/// Falls back to `python3` when no venv is found (installed-wheel or bare
/// environment). Anchored on `cwd`, then the CANONICAL repo, then a
/// `current_exe()` walk: a linked worktree has `cli/src` but NO `cli/.venv`, and
/// bare Homebrew `python3` lacks fno's deps (pydantic, ...), so a worktree
/// finalize must resolve the canonical checkout's venv (x-b74b) - PYTHONPATH
/// alone would still fail on the missing dep.
fn py_interpreter(cwd: &Path) -> String {
    for anc in cwd.ancestors() {
        if let Some(v) = footnote_venv(anc) {
            return v;
        }
    }
    if let Some(root) = crate::paths::canonical_repo_root(cwd) {
        if let Some(v) = footnote_venv(&root) {
            return v;
        }
    }
    if let Ok(exe) = std::env::current_exe() {
        for anc in exe.ancestors() {
            if let Some(v) = footnote_venv(anc) {
                return v;
            }
        }
    }
    "python3".to_string()
}

/// Run `python3 -m fno.cost._session_cost` for cost, then
/// `python3 -m fno.cost._register` to append exactly one ledger row carrying
/// graph_node_id + provider_id + session_id + cost + termination_reason.
/// Dedup/flock stay in _register (proven). A missing transcript yields
/// cost=null - the row still lands (US7-ERR).
fn write_ledger_record(
    cwd: &Path,
    state: &Path,
    transcript_uuid: &str,
    reason: &str,
) -> Result<(), String> {
    // Cost JSON (best-effort: empty string -> register-task records cost=null).
    let cost_json = if transcript_uuid.is_empty() {
        String::new()
    } else {
        match py_module(cwd)
            .arg("-m")
            .arg("fno.cost._session_cost")
            .arg("--json")
            .arg(transcript_uuid)
            .output()
        {
            Ok(out) if out.status.success() => {
                String::from_utf8_lossy(&out.stdout).trim().to_string()
            }
            Ok(out) => {
                eprintln!(
                    "finalize: fno.cost._session_cost exit {:?}: {}",
                    out.status.code(),
                    String::from_utf8_lossy(&out.stderr).trim()
                );
                String::new()
            }
            Err(e) => {
                eprintln!("finalize: fno.cost._session_cost spawn failed: {e}");
                String::new()
            }
        }
    };

    let mut cmd = py_module(cwd);
    cmd.arg("-m")
        .arg("fno.cost._register")
        .arg(state)
        .arg(transcript_uuid)
        .arg("--termination-reason")
        .arg(reason);
    if !cost_json.is_empty() {
        cmd.arg("--cost-json").arg(&cost_json);
    }
    let out = cmd
        .output()
        .map_err(|e| format!("fno.cost._register spawn failed: {e}"))?;
    if out.status.success() {
        Ok(())
    } else {
        Err(format!(
            "fno.cost._register exit {:?}: {}",
            out.status.code(),
            String::from_utf8_lossy(&out.stderr).trim()
        ))
    }
}

// ── stamp (ship only) ────────────────────────────────────────────────────────

/// After a stamp writes, validate the plan's frontmatter via `fno plan validate`
/// (the same read-only verb). Non-fatal-but-loud: a non-zero exit (e.g. a stamp
/// that left `status` unset) is reported on stderr for the next session to fix;
/// the stamp is never rolled back and finalize never fails on it (AC1-FR). A
/// concurrent edit is fine - the verb reads whatever snapshot is on disk.
fn validate_stamped_frontmatter(cwd: &Path, plan_path: &str) {
    if plan_path.is_empty() {
        return;
    }
    let full = cwd.join(plan_path);
    match py_module(cwd)
        .arg("-m")
        .arg("fno.cli")
        .arg("plan")
        .arg("validate")
        .arg(&full)
        .output()
    {
        Ok(out) if out.status.success() => {}
        Ok(out) => eprintln!(
            "finalize: post-stamp `fno plan validate` FAILED (exit {:?}); stamp NOT rolled back - fix the plan frontmatter next session:\n{}\n{}",
            out.status.code(),
            String::from_utf8_lossy(&out.stdout).trim(),
            String::from_utf8_lossy(&out.stderr).trim()
        ),
        Err(e) => eprintln!("finalize: post-stamp `fno plan validate` spawn failed: {e}"),
    }
}

/// Stamp the plan `in_review` and, when `do_graduate`, flip it to `done`.
///
/// For a CODE ship (`DonePRGreen`) the caller passes `do_graduate = false`: done
/// means merged (x-f34f), so the `in_review -> done` flip happens later via the
/// write-time projection at merge, not here. For an ADVISORY ship
/// (`DoneAdvisory`) there is no merge event, so the caller passes `true` and
/// this graduates the plan now. `expected_url_count` is recorded either way for
/// the manual `graduate` verb and the cross-project safety net.
fn stamp_and_graduate(
    cwd: &Path,
    plan_path: &str,
    session_id: &str,
    expected_url_count: Option<u32>,
    do_graduate: bool,
    url_override: Option<&str>,
) -> Result<(), String> {
    let pr_url = url_override.map(str::to_owned).or_else(|| gh_pr_url(cwd));
    let mut stamp = py_module(cwd);
    stamp
        .arg("-m")
        .arg("fno.plan._stamp")
        .arg("stamp")
        .arg("--plan-path")
        .arg(plan_path)
        .arg("--session-id")
        .arg(session_id);
    if let Some(n) = expected_url_count {
        stamp.arg("--expected-url-count").arg(n.to_string());
    }
    if let Some(url) = &pr_url {
        stamp.arg("--url").arg(url);
    }
    let out = stamp.output().map_err(|_| "stamp".to_string())?;
    if !out.status.success() {
        eprintln!(
            "finalize: fno.plan._stamp stamp exit {:?}: {}",
            out.status.code(),
            String::from_utf8_lossy(&out.stderr).trim()
        );
        return Err("stamp".into());
    }

    // Post-stamp schema check (AC1-FR): validate the freshly-stamped frontmatter
    // against fno.plan.schema. Non-fatal-but-loud - a schema-invalidating stamp
    // is surfaced for the next session, never rolled back and never failing
    // finalize (finalize is idempotent/non-fatal by design).
    validate_stamped_frontmatter(cwd, plan_path);

    // A code ship stamps `in_review` only; done flips at merge via the projection.
    if !do_graduate {
        return Ok(());
    }

    let out = py_module(cwd)
        .arg("-m")
        .arg("fno.plan._stamp")
        .arg("graduate")
        .arg("--plan-path")
        .arg(plan_path)
        .output()
        .map_err(|_| "graduate".to_string())?;
    if !out.status.success() {
        eprintln!(
            "finalize: fno.plan._stamp graduate exit {:?}: {}",
            out.status.code(),
            String::from_utf8_lossy(&out.stderr).trim()
        );
        return Err("graduate".into());
    }
    Ok(())
}

/// Derive the expected URL count for graduation. Returns `None` for a
/// single-project plan (let fno.plan._stamp keep any declared count, else
/// default to 1) and `Some(n)` for a cross-project plan, counting the direct keys under
/// the plan's frontmatter `projects:` map. Returns `None` for a cross-project
/// plan whose count can't be read (missing/garbled projects map) so the caller
/// can skip graduate rather than guess. This restores the pre-promise contract:
/// cross-project graduation waits for ALL project PRs (codex P1).
fn derive_expected_url_count(cwd: &Path, plan_path: &str, cross_project: bool) -> Option<u32> {
    if !cross_project {
        return None;
    }
    let doc = cwd.join(plan_path);
    let content = fs::read_to_string(&doc).ok()?;

    let mut in_fm = false;
    let mut in_projects = false;
    let mut child_indent: Option<usize> = None;
    let mut count: u32 = 0;
    for line in content.lines() {
        let t = line.trim();
        if t == "---" {
            if !in_fm {
                in_fm = true;
                continue;
            }
            break; // end of frontmatter
        }
        if !in_fm {
            continue;
        }
        let indent = line.len() - line.trim_start().len();
        if !in_projects {
            if indent == 0 && t.starts_with("projects:") {
                in_projects = true;
            }
            continue;
        }
        if t.is_empty() || t.starts_with('#') {
            continue;
        }
        if indent == 0 {
            break; // next top-level frontmatter key ends the projects map
        }
        match child_indent {
            None => {
                child_indent = Some(indent);
                count += 1;
            }
            Some(ci) if indent == ci => count += 1,
            _ => {} // deeper-nested key under a project entry; not a project
        }
    }
    if count >= 1 {
        Some(count)
    } else {
        None
    }
}

// ── mechanical handoff artifact (ship only) ──────────────────────────────────

/// Write a git-derived end-of-session summary to the persistent handoffs dir.
/// Filename keyed by session-id so a re-run overwrites rather than duplicating.
#[allow(clippy::too_many_arguments)]
fn write_handoff(
    cwd: &Path,
    state: &Path,
    session_id: &str,
    m: &ManifestFields,
    transcript_uuid: &str,
    handoffs_override: Option<&Path>,
    settings_override: Option<&Path>,
    home: Option<&Path>,
) -> Result<String, String> {
    let dir = resolve_handoffs_dir(handoffs_override, settings_override, cwd, home);
    fs::create_dir_all(&dir).map_err(|e| format!("mkdir {}: {e}", dir.display()))?;

    let date = &now_rfc3339_utc()[..10]; // YYYY-MM-DD
    let sid_prefix: String = session_id.chars().take(16).collect();
    let file = dir.join(format!("{date}-{sid_prefix}-handoff.md"));

    let title = m.input.clone().unwrap_or_else(|| "Untitled".into());
    let plan = m.plan_path.clone().unwrap_or_else(|| "-".into());
    let node = m.graph_node_id.clone().unwrap_or_else(|| "-".into());
    let pr = gh_pr_url(cwd).unwrap_or_else(|| "-".into());
    let diffstat = git_capture(cwd, &["diff", "--stat", "origin/main...HEAD"])
        .filter(|s| !s.trim().is_empty())
        .or_else(|| git_capture(cwd, &["diff", "--stat", "HEAD~5..HEAD"]))
        .unwrap_or_else(|| "(diff unavailable)".into());
    let commits = git_capture(cwd, &["log", "--oneline", "origin/main..HEAD"])
        .filter(|s| !s.trim().is_empty())
        .or_else(|| git_capture(cwd, &["log", "--oneline", "-10"]))
        .unwrap_or_else(|| "(log unavailable)".into());
    let cost = handoff_cost_line(cwd, transcript_uuid);
    // Completed commit + idempotency keys (x-c3a2): a worker that died after
    // shipping but before the terminal journal write is reconcilable from this
    // artifact. The keys are derived from the delivered HEAD so a resumed worker
    // checking them skips a replayed publish/PR-create/comment/merge.
    let head = git_capture(cwd, &["rev-parse", "HEAD"]).unwrap_or_else(|| "-".into());
    let head_short: String = head.chars().take(7).collect();

    let body = format!(
        "# Session handoff: {title}\n\n\
         - session: `{session_id}`\n\
         - node: `{node}`\n\
         - plan: `{plan}`\n\
         - PR: {pr}\n\
         - completed_commit: `{head}`\n\
         - idempotency_keys: `pr_create:{head_short}`, `merge:{head_short}`\n\
         - cost: {cost}\n\
         - generated: {generated} (mechanical, by `fno-agents finalize`)\n\n\
         ## Files changed (origin/main...HEAD)\n\n```\n{diffstat}\n```\n\n\
         ## Commits\n\n```\n{commits}\n```\n",
        generated = now_rfc3339_utc(),
    );

    // Keep the manifest path referenced so the variable is meaningful even when
    // we add fields later; it is the canonical source of the fields above.
    let _ = state;
    fs::write(&file, body).map_err(|e| format!("write {}: {e}", file.display()))?;
    Ok(file.to_string_lossy().into_owned())
}

/// One-line cost summary for the handoff header, sourced from the in-package
/// _session_cost module (`python3 -m fno.cost._session_cost`).
fn handoff_cost_line(cwd: &Path, transcript_uuid: &str) -> String {
    if transcript_uuid.is_empty() {
        return "(unavailable)".into();
    }
    // Route through py_module so this shares the interpreter + PYTHONPATH
    // resolution used by the ledger write; a raw `python3` here (no PYTHONPATH,
    // no venv) was the source of the recurring `handoff cost: ... exit` errors.
    match py_module(cwd)
        .arg("-m")
        .arg("fno.cost._session_cost")
        .arg("--json")
        .arg(transcript_uuid)
        .output()
    {
        Ok(out) if out.status.success() => {
            match serde_json::from_slice::<Value>(&out.stdout) {
                Ok(v) => match v.get("cost_usd").and_then(|c| c.as_f64()) {
                    Some(c) => format!("${c:.2}"),
                    None => "(unavailable)".into(),
                },
                Err(e) => {
                    // Surface a crashed/garbage cost module (mirrors
                    // write_ledger_record): a reader must tell "no transcript"
                    // from "fno.cost._session_cost emitted non-JSON".
                    eprintln!(
                        "finalize: handoff cost: fno.cost._session_cost emitted non-JSON: {e}"
                    );
                    "(unavailable)".into()
                }
            }
        }
        Ok(out) => {
            eprintln!(
                "finalize: handoff cost: fno.cost._session_cost exit {:?}: {}",
                out.status.code(),
                String::from_utf8_lossy(&out.stderr).trim()
            );
            "(unavailable)".into()
        }
        Err(e) => {
            eprintln!("finalize: handoff cost: fno.cost._session_cost spawn failed: {e}");
            "(unavailable)".into()
        }
    }
}

// ── helpers ─────────────────────────────────────────────────────────────────

/// Resolve the persistent handoffs directory:
///   1. explicit `--handoffs-dir`
///   2. `$HANDOFFS_DIR`
///   3. `config.paths.handoffs_dir` from project then global settings.yaml,
///      with `~` and `{project}` expanded (skipped if it still has `{...}`)
///   4. vault-derived `<vault>/internal/<project>/handoffs/` when
///      `obsidian.enabled` + `obsidian.vault` are set (placement rule,
///      ab-f063 Wave 2 - mirrors `paths.handoffs_dir()` in the Python CLI)
///   5. fallback `~/.fno/handoffs/<project>`
///
/// Pure-Rust resolution: it never shells `fno`, so the verb keeps its Python-CLI
/// independence (it only ever runs the in-package metric modules via
/// `python3 -m`).
fn resolve_handoffs_dir(
    override_dir: Option<&Path>,
    settings_override: Option<&Path>,
    cwd: &Path,
    home: Option<&Path>,
) -> PathBuf {
    if let Some(d) = override_dir {
        return d.to_path_buf();
    }
    if let Some(d) = env_dir_unless_null("HANDOFFS_DIR") {
        return d;
    }
    let project = resolve_project_name(settings_override, home, cwd);
    let mut candidates: Vec<PathBuf> = Vec::new();
    if let Some(s) = settings_override {
        candidates.push(s.to_path_buf());
    }
    candidates.push(cwd.join(".fno/config.toml"));
    if let Some(h) = home {
        candidates.push(h.join(".fno/config.toml"));
    }
    for sp in &candidates {
        if let Some(raw) = read_path_setting(sp, "handoffs_dir") {
            if let Some(expanded) = expand_handoffs_template(&raw, home, &project) {
                return expanded;
            }
        }
    }
    if let Some(vault) = resolve_obsidian_vault(&candidates) {
        if let Some(vroot) = resolve_vault_root(&vault, home) {
            return vroot.join("internal").join(&project).join("handoffs");
        }
    }
    let base = home
        .map(Path::to_path_buf)
        .unwrap_or_else(|| cwd.to_path_buf());
    base.join(".fno/handoffs").join(project)
}

/// One file's `obsidian:` block, keyed per-field so a caller can merge across
/// project/global candidates the same way `fno.config._deep_merge` merges
/// settings.yaml: per KEY, not per file. `None` in either field means that
/// file's `obsidian:` block (if any) did not set that key, so the caller
/// should keep looking in the next, lower-priority candidate - NOT that the
/// key is false/absent overall (codex review, PR #185: a project file that
/// sets only `enabled: false` must still inherit `vault:` from global, and
/// must NOT let its own absence of an opinion fall through to a lower-priority
/// file that re-enables obsidian).
#[derive(Default)]
struct ObsidianBlock {
    enabled: Option<bool>,
    vault: Option<String>,
}

/// Parse a config.toml file into a table; None on a missing or unparseable file.
fn load_config_toml(path: &Path) -> Option<toml::Table> {
    fs::read_to_string(path).ok()?.parse::<toml::Table>().ok()
}

/// A dotted string value from a config.toml table (e.g. `["paths","handoffs_dir"]`).
fn toml_string_at(t: &toml::Table, path: &[&str]) -> Option<String> {
    let mut cur = t.get(*path.first()?)?;
    for k in &path[1..] {
        cur = cur.as_table()?.get(*k)?;
    }
    cur.as_str().map(str::to_string)
}

/// Read the `[obsidian]` block (enabled + vault) from a flat config.toml. `None`
/// in a field means that file did not set the key, so the caller keeps looking
/// in the next candidate (per-KEY merge, not per-file).
fn read_obsidian_block(path: &Path) -> ObsidianBlock {
    let Some(t) = load_config_toml(path) else {
        return ObsidianBlock::default();
    };
    let ob = t.get("obsidian").and_then(|v| v.as_table());
    ObsidianBlock {
        enabled: ob.and_then(|o| o.get("enabled")).and_then(|v| v.as_bool()),
        vault: ob
            .and_then(|o| o.get("vault"))
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty() && !s.eq_ignore_ascii_case("null"))
            .map(str::to_string),
    }
}

/// Resolve `obsidian.enabled` + `obsidian.vault`, merged key-by-key across
/// `candidates` in priority order (project before global) - matching
/// `fno.config._deep_merge` semantics, NOT "first file with an opinion wins
/// wholesale". Returns the vault name only when the merged `enabled` is true
/// AND a `vault` value was found somewhere in the chain.
fn resolve_obsidian_vault(candidates: &[PathBuf]) -> Option<String> {
    let mut enabled: Option<bool> = None;
    let mut vault: Option<String> = None;
    for sp in candidates {
        let block = read_obsidian_block(sp);
        if enabled.is_none() {
            enabled = block.enabled;
        }
        if vault.is_none() {
            vault = block.vault;
        }
        if enabled.is_some() && vault.is_some() {
            break;
        }
    }
    if enabled == Some(true) {
        vault
    } else {
        None
    }
}

/// Expand a vault name to its filesystem root - mirrors `paths.vault_root()`:
/// a bare name (e.g. `c3po`) maps to `~/c3po`; an already-absolute or
/// `~`-prefixed value is honored as-is.
fn resolve_vault_root(vault: &str, home: Option<&Path>) -> Option<PathBuf> {
    if let Some(rest) = vault.strip_prefix("~/") {
        return home.map(|h| h.join(rest));
    }
    if vault == "~" {
        return home.map(Path::to_path_buf);
    }
    if Path::new(vault).is_absolute() {
        return Some(PathBuf::from(vault));
    }
    home.map(|h| h.join(vault))
}

/// Read a `<key>:` path value from a settings.yaml (any indent level). The
/// `config.paths.*` keys (`handoffs_dir`, `postmortems_dir`, ...) are
/// distinctive enough that a flat scan is safe.
/// Read a dir from an env var, treating an empty or literal-"null" value as
/// unset. emit_shell never emits "null", but a stale/hand-edited environment
/// can, and trusting it verbatim is what wrote `./null/` inside the repo
/// (x-54c2). Mirrors the same guard in read_path_setting.
fn env_dir_unless_null(key: &str) -> Option<PathBuf> {
    let v = std::env::var_os(key)?;
    // Only the string-decodable "null"/empty sentinel is filtered; a non-UTF-8
    // value (valid arbitrary-byte path on Unix) is preserved verbatim, matching
    // the original var_os behavior (gemini review).
    if let Some(s) = v.to_str() {
        let t = s.trim();
        if t.is_empty() || t.eq_ignore_ascii_case("null") {
            return None;
        }
        return Some(PathBuf::from(t));
    }
    Some(PathBuf::from(v))
}

/// Read a `paths.<key>` value (e.g. `handoffs_dir`, `postmortems_dir`) from a
/// flat config.toml. A literal `"null"` string is treated as absent (the "use
/// default" sentinel), so the caller falls through to `~/.fno/<dir>` (x-54c2).
fn read_path_setting(path: &Path, key: &str) -> Option<String> {
    let t = load_config_toml(path)?;
    toml_string_at(&t, &["paths", key]).filter(|v| !v.is_empty() && !v.eq_ignore_ascii_case("null"))
}

/// Expand `~` and `{project}` in a handoffs_dir template. Returns None when the
/// result still contains an unresolved `{...}` token (e.g. `{vault}`), so the
/// caller falls back rather than writing to a literal-brace path.
fn expand_handoffs_template(raw: &str, home: Option<&Path>, project: &str) -> Option<PathBuf> {
    let mut s = raw.to_string();
    // Cannot expand a leading ~ without a home; return None so the caller falls
    // back to the default dir rather than writing to a literal "~..." path
    // (gemini review).
    if let Some(stripped) = s.strip_prefix("~/") {
        let h = home?;
        s = h.join(stripped).to_string_lossy().into_owned();
    } else if s == "~" {
        let h = home?;
        s = h.to_string_lossy().into_owned();
    }
    s = s.replace("{project}", project);
    if s.contains('{') {
        return None;
    }
    Some(PathBuf::from(s))
}

/// Project name = basename of the MAIN worktree (the first `git worktree list
/// --porcelain` entry), so a linked worktree resolves to "fno", not the
/// worktree directory name. The porcelain first-entry is robust across layouts
/// (--separate-git-dir, bare) where the `--git-common-dir` parent is wrong
/// (gemini review HIGH). Falls back to the cwd basename.
fn repo_project_name(cwd: &Path) -> String {
    if let Some(porcelain) = git_capture(cwd, &["worktree", "list", "--porcelain"]) {
        if let Some(path_str) = porcelain
            .lines()
            .next()
            .and_then(|l| l.strip_prefix("worktree "))
        {
            if let Some(name) = Path::new(path_str.trim()).file_name() {
                return name.to_string_lossy().into_owned();
            }
        }
    }
    cwd.file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| "project".into())
}

/// Last path segment of a git remote URL, one trailing `.git` stripped. Mirrors
/// the Python `_remote_url_to_slug` (paths.py): takes the last `/`-or-`:` segment
/// so scp-like (`git@host:org/repo.git`), https, and local-path remotes all
/// resolve. Returns None for an empty URL or a degenerate segment that would
/// escape `internal/<project>/`.
fn slug_from_remote_url(url: &str) -> Option<String> {
    let url = url.trim().trim_end_matches('/');
    if url.is_empty() {
        return None;
    }
    let tail = url.rsplit(['/', ':']).next()?;
    let tail = tail.strip_suffix(".git").unwrap_or(tail);
    // A Windows-style/local remote (`C:\repos\foo.git`) leaves backslashes in the
    // tail; reject any separator so the slug can never become a stray path
    // segment, matching the Python `_remote_url_to_slug` (paths.py).
    if tail.is_empty() || tail == "." || tail == ".." || tail.contains(['/', '\\']) {
        return None;
    }
    Some(tail.to_string())
}

/// `remote.origin.url` slug for `cwd` - stable across worktrees and clones.
/// Best-effort: any git failure or missing remote returns None so the caller
/// falls through to the basename.
fn slug_from_git_remote(cwd: &Path) -> Option<String> {
    let url = git_capture(cwd, &["config", "--get", "remote.origin.url"])?;
    slug_from_remote_url(&url)
}

/// Resolve the `{project}` path token, matching the Python resolver
/// `fno.paths._project_name`: `config.project.id` (project-local then global
/// settings.yaml) -> git-remote slug (stable across worktrees/clones) ->
/// git main-worktree basename via `repo_project_name`. The remote-slug tier is
/// load-bearing for parity: the Python side writes `internal/<remote-slug>/` for
/// an id-unset repo, so this terminal handoff writer must agree or it recreates
/// the very `internal/<basename>/` strays the Python change removes. Non-fatal:
/// a missing/malformed settings file, an unset/`null` id, or no remote degrades
/// to the basename, so unconfigured installs never break. Uses the SAME
/// project-then-global candidate order the callers use for `config.paths.*_dir`.
fn resolve_project_name(
    settings_override: Option<&Path>,
    home: Option<&Path>,
    cwd: &Path,
) -> String {
    let mut candidates: Vec<PathBuf> = Vec::new();
    if let Some(s) = settings_override {
        candidates.push(s.to_path_buf());
    }
    candidates.push(cwd.join(".fno/config.toml"));
    if let Some(h) = home {
        candidates.push(h.join(".fno/config.toml"));
    }
    for sp in candidates {
        if let Some(id) = read_project_id(&sp) {
            return id;
        }
    }
    if let Some(slug) = slug_from_git_remote(cwd) {
        return slug;
    }
    repo_project_name(cwd)
}

/// Read the project id from a flat config.toml (`[project]\nid = "..."`). The
/// legacy top-level `project.id` and the canonical `config.project.id` both map
/// to the same flat `project.id`, so one lookup covers both. An empty/`null`
/// value, an unreadable file, or an id outside `[A-Za-z0-9._-]` yields None so
/// the caller falls back to the basename.
fn read_project_id(path: &Path) -> Option<String> {
    let t = load_config_toml(path)?;
    let id = toml_string_at(&t, &["project", "id"])?;
    // The Python settings model rejects ids outside [A-Za-z0-9._-]
    // (config/__init__.py). A hand-edited invalid value (e.g. `foo/bar`) must
    // never be spliced into a `{project}` path segment, so degrade to the
    // basename rather than write artifacts outside the project dir.
    valid_project_id(&id).then_some(id)
}

/// Project ids are restricted to `[A-Za-z0-9._-]`, matching the Python
/// `validate_project_id` regex. ASCII byte check (no `regex` dependency).
fn valid_project_id(s: &str) -> bool {
    !s.is_empty()
        && s.bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'_' || b == b'-')
}

/// Best-effort PR URL for the current HEAD/branch via `gh`.
fn gh_pr_url(cwd: &Path) -> Option<String> {
    let out = Command::new("gh")
        .args(["pr", "view", "--json", "url", "-q", ".url"])
        .current_dir(cwd)
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let url = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if url.is_empty() {
        None
    } else {
        Some(url)
    }
}

/// Resolve the branch's open PR as `(number, url)` for the node<->PR backstop
/// stamp (x-280d). Returns None when gh fails/rate-limits, no PR exists, or the
/// JSON is malformed - all of which the caller treats as "nothing to stamp".
fn gh_pr_ref(cwd: &Path) -> Option<(u64, String)> {
    let out = Command::new("gh")
        .args(["pr", "view", "--json", "number,url"])
        .current_dir(cwd)
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    parse_pr_ref(&out.stdout)
}

/// Pure parse of `gh pr view --json number,url` stdout. Split from the shell-out
/// so the malformed/missing-field cases are unit-testable without gh.
fn parse_pr_ref(stdout: &[u8]) -> Option<(u64, String)> {
    let v: Value = serde_json::from_slice(stdout).ok()?;
    let number = v.get("number")?.as_u64()?;
    let url = v.get("url")?.as_str()?.trim().to_string();
    if url.is_empty() {
        None
    } else {
        Some((number, url))
    }
}

/// Deterministic node<->PR `pr_number` backstop (x-280d): the create-time skill
/// stamp (pr-creator §5.5) is best-effort and was skipped for x-1829/#358,
/// leaving `pr_number` null so the derived `in_review` status never engaged.
/// Gated on node-presence + PR-exists (NOT `ship`) so `DoneAwaitingMerge` - the
/// exact terminal `in_review` covers - is included. Best-effort + non-fatal +
/// idempotent: never returned into `failed`, never changes the exit code; a
/// re-stamp of the same value is a no-op via `fno backlog update`'s lock.
fn stamp_node_pr(cwd: &Path, node: Option<&str>) {
    let Some(node) = node else { return };
    let Some((number, url)) = gh_pr_ref(cwd) else {
        eprintln!("finalize: no open PR found for branch; skipped pr_number stamp for node {node}");
        return;
    };
    let ok = Command::new("fno")
        .args([
            "backlog",
            "update",
            node,
            "--pr-number",
            &number.to_string(),
            "--pr-url",
            &url,
        ])
        .current_dir(cwd)
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    if ok {
        eprintln!("finalize: stamped pr_number {number} on node {node}");
    } else {
        eprintln!("finalize: pr_number stamp failed for node {node} (non-fatal)");
    }
}

/// Whether this terminal fire should arm GitHub's native auto-merge (x-1951).
///
/// Auto-merge used to be armed by `fno worker ship` at PR-CREATION time, gated
/// only on the manifest's posture. That pre-authorized a merge before any gate
/// had run: from the moment `--auto` is set GitHub owns the timing and fires the
/// instant ITS OWN branch protections pass, so footnote is no longer in the
/// decision path and a reviewer who posts a blocking finding after CI greens
/// loses the race (the PR #566 shape). Arming here instead authorizes exactly
/// the state `loop-check` just verified - PR up, CI green, no unaddressed
/// blocking finding - and buys every reviewer the whole CI duration to post
/// before the merge is armed at all.
///
/// `DonePRGreen` only. `DoneAdvisory` is the other `SHIP_REASONS` member but is
/// a doc ship with no PR, and `DoneAwaitingMerge` is by definition a merge a
/// human performs past pre-existing main-red - arming either would merge
/// something no gate greened.
fn should_arm_auto_merge(reason: &str, auto_merge_approved: bool) -> bool {
    auto_merge_approved && reason == "DonePRGreen"
}

/// Return why configured optional-review evidence forbids native auto-merge,
/// or `None` when arming may proceed.
///
/// This is deliberately an authorization check, not a completion gate. A
/// missing or usage-limited optional App still lets finalization complete and
/// leaves the green PR available for a human merge; it only prevents GitHub
/// from merging without the review coverage the operator configured.
fn optional_review_block_reason(cwd: &Path) -> Option<String> {
    let optional_apps = crate::agents_config::review_optional_apps(cwd);
    if optional_apps.is_empty() {
        return None;
    }

    let output = match Command::new("gh")
        .args(["pr", "view", "--json", "reviews,comments"])
        .current_dir(cwd)
        .output()
    {
        Ok(output) if output.status.success() => output,
        Ok(output) => {
            eprintln!(
                "finalize: optional-review evidence read failed (non-fatal): {}",
                String::from_utf8_lossy(&output.stderr).trim()
            );
            return Some("optional-review-read-failed".to_string());
        }
        Err(error) => {
            eprintln!("finalize: optional-review evidence read failed (non-fatal): {error}");
            return Some("optional-review-read-failed".to_string());
        }
    };

    let payload: Value = match serde_json::from_slice(&output.stdout) {
        Ok(value) => value,
        Err(error) => {
            eprintln!("finalize: optional-review evidence parse failed (non-fatal): {error}");
            return Some("optional-review-read-failed".to_string());
        }
    };
    let Some(reviews) = payload.get("reviews").and_then(Value::as_array) else {
        return Some("optional-review-read-failed".to_string());
    };
    let Some(comments) = payload.get("comments").and_then(Value::as_array) else {
        return Some("optional-review-read-failed".to_string());
    };

    for app in optional_apps {
        let reviewed = reviews.iter().any(|review| {
            let login = review
                .pointer("/author/login")
                .and_then(Value::as_str)
                .unwrap_or("");
            let state = review.get("state").and_then(Value::as_str).unwrap_or("");
            !state.is_empty() && crate::loopcheck::login_matches_bot(login, &app)
        });
        if reviewed {
            continue;
        }

        let usage_limited = comments.iter().any(|comment| {
            let login = comment
                .pointer("/author/login")
                .and_then(Value::as_str)
                .unwrap_or("");
            let body = comment
                .get("body")
                .and_then(Value::as_str)
                .unwrap_or("")
                .to_lowercase();
            crate::loopcheck::login_matches_bot(login, &app)
                && crate::loopcheck::body_is_usage_limit(&body)
        });
        if usage_limited {
            return Some(format!("optional-review-usage-limited:{app}"));
        }

        return Some(format!("optional-review-outstanding:{app}"));
    }

    None
}

/// Arm GitHub's native auto-merge for the branch's open PR. Returns whether it
/// armed, for the terminal event's `auto_merge_armed` field.
///
/// Best-effort and log-only, the same fatality as `stamp_node_pr` and every
/// other gh-dependent step here: it is deliberately NOT returned into `failed`.
/// Failing to arm leaves a green, reviewed, mergeable PR for a human, which is
/// the safe direction; holding `session_finalized` open to retry an arm would
/// re-run the stamp/handoff steps for a merge GitHub may already have performed.
///
/// Re-arming needs no per-head dedup: `--auto` sets a PR-level flag rather than
/// appending anything, so a retried terminal fire is a no-op on GitHub's side.
///
/// `config.auto_merge.merge_strategy` and `.delete_branch_on_merge` shape the
/// argv, matching `fno pr merge`. The strategy used to be hardcoded `--merge`,
/// carried over verbatim from the PR-creation call site this replaced, so a
/// squash-only repo was armed with a merge method it forbids - and because
/// arming is log-only, GitHub's rejection was one stderr line inside a stop
/// hook. The symptom was not a wrong commit shape but auto-merge silently never
/// working, indistinguishable from nobody having opted in.
///
/// `require_checks_pass` is deliberately NOT read. On `fno pr merge` it decides
/// whether `--auto` is passed at all (false meaning "merge now, do not wait");
/// here `--auto` IS the operation and `loop-check` has already verified green,
/// so honoring it would let a config value turn arming into a no-op.
fn arm_auto_merge(cwd: &Path) -> bool {
    let Some((number, _url)) = gh_pr_ref(cwd) else {
        eprintln!("finalize: no open PR found for branch; auto-merge not armed");
        return false;
    };
    let strategy = crate::agents_config::auto_merge_strategy(cwd);
    let mut args = vec![
        "pr".to_string(),
        "merge".to_string(),
        number.to_string(),
        "--auto".to_string(),
        format!("--{strategy}"),
    ];
    if crate::agents_config::auto_merge_delete_branch(cwd) {
        args.push("--delete-branch".to_string());
    }
    // The strategy is named in every failure line below: a repo that forbids the
    // configured merge method fails here exactly like stale auth or an
    // unmergeable state would, and the config key is the only way to tell them
    // apart from a log nobody is watching live.
    match Command::new("gh").args(&args).current_dir(cwd).output() {
        Ok(o) if o.status.success() => {
            eprintln!("finalize: auto-merge armed for PR {number} with --{strategy}");
            true
        }
        // Surface gh's own message so an operator can tell a repo with the
        // auto-merge feature disabled from stale auth or an unmergeable state.
        Ok(o) => {
            eprintln!(
                "finalize: auto-merge arm failed for PR {number} with --{strategy} \
                 (from config.auto_merge.merge_strategy; check the repo allows that \
                 merge method) (non-fatal): {}",
                String::from_utf8_lossy(&o.stderr).trim()
            );
            false
        }
        Err(e) => {
            eprintln!(
                "finalize: auto-merge arm failed for PR {number} with --{strategy} \
                 (from config.auto_merge.merge_strategy) (non-fatal): {e}"
            );
            false
        }
    }
}

/// The terminals a `do` stamp is allowed on. Planner-only sessions exit via
/// Budget/NoProgress/Interrupted, so those never stamp.
///
/// Deliberately NOT `SHIP_REASONS`, which also contains `DoneAdvisory`: a doc
/// ship authors no branch commits, so reusing that constant here would stamp
/// every doc ship. The two sets disagree on purpose.
fn is_do_stamp_terminal(reason: &str) -> bool {
    matches!(reason, "DonePRGreen" | "DoneAwaitingMerge")
}

/// Guarded `do` lifecycle stamp (x-0469). `/do` Step 1.5 is the earlier truthful
/// stamp, but most `/target` runs implement inline and never invoke `/do`, so the
/// phase was recorded twice across ~2800 nodes. This is the backstop: one record
/// per implementing session, at its own finish line.
///
/// `sessions[]` is append-only and every worker-session resolver trusts it, so a
/// WRONG stamp is strictly worse than none - stamping at init recorded the
/// PLANNER (PR #504, reverted). G1 (ship reason) and G4 (authored-commit
/// evidence) evaluate here; G2 (identity continuity) and G3 (plan agreement)
/// ride flags into `fno backlog session add`, which already owns ambient-identity
/// precedence.
///
/// G1, G2 and G4 fail closed. G3 is the deliberate exception: an unreadable plan
/// or an absent `claims:` counts as agreement (mirroring `/do` Step 1.5, since
/// absent evidence of conflict is not conflict), and only a positive
/// disagreement skips. The primitive says so on stderr when it could not
/// evaluate, so that leniency is never silent.
///
/// Log-only and never retried: a guard skip is a designed outcome, and retrying
/// one would spin.
fn stamp_node_do(cwd: &Path, m: &ManifestFields, reason: &str) {
    let Some(node) = m.graph_node_id.as_deref() else {
        return;
    };
    let skip = |guard: &str, why: String| {
        eprintln!("finalize: do stamp skipped for node {node} ({guard}: {why})");
    };
    if !is_do_stamp_terminal(reason) {
        return skip("G1", format!("{reason} is not a ship terminal"));
    }
    // G2 input: an absent id cannot prove continuity, so it is not stamped.
    let Some(session) = m.harness_session_id.as_deref() else {
        return skip("G2", "manifest carries no harness_session_id".into());
    };
    let (Some(created_at), Some(head)) = (m.created_at.as_deref(), m.initial_head.as_deref())
    else {
        return skip("G4", "manifest predates initial_head/created_at".into());
    };
    let Some(floor) = parse_utc_epoch(created_at) else {
        return skip("G4", format!("unparseable created_at {created_at}"));
    };
    if !authored_work_since(cwd, head, floor) {
        return skip(
            "G4",
            format!("no non-merge commit in {head}..HEAD authored at/after {created_at}"),
        );
    }

    let mut cmd = Command::new("fno");
    cmd.args(["backlog", "session", "add", node, "--phase", "do"]);
    cmd.args(["--require-session", session]);
    if let Some(plan) = m.plan_path.as_deref() {
        cmd.args(["--guard-plan", plan]);
    }
    cmd.args(["--claimed-at", created_at]);
    let ok = cmd
        .current_dir(cwd)
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    if !ok {
        eprintln!("finalize: do stamp failed for node {node} (non-fatal)");
    }
}

/// True when `initial_head..HEAD` holds a non-merge commit on HEAD's own
/// first-parent chain authored at or after `floor` (epoch seconds).
///
/// Author dates, never committer dates: `git rebase` rewrites the committer date
/// to now while preserving the author date, so a successor that merely rebased a
/// predecessor's branch onto main moves HEAD maximally while authoring nothing.
/// `--since` filters on committer date and would re-open exactly that hole.
///
/// `--first-parent` closes the sibling hole. The range is set subtraction over
/// the whole DAG, and `--no-merges` drops a merge commit but KEEPS its payload,
/// so a session that authored nothing and only ran `git merge origin/main` would
/// otherwise pass on other contributors' commits - genuinely recent, so the
/// author-date floor cannot catch them. The session's own commits sit on HEAD's
/// first-parent chain, so they still count.
///
/// The `:/` pathspec (repo root, cwd-independent) requires the commit to have
/// actually changed a file, so an empty commit is not evidence of work.
///
/// The range survives a rebased-away `initial_head`; any git failure (GC'd
/// baseline, deleted worktree) reads as no evidence, and so does a single
/// unparseable timestamp - partial evidence is not evidence.
///
/// Accepted residual: the floor is inclusive at one-second resolution, so a
/// predecessor commit authored in the same second as this session's init would
/// count. Tightening to exclusive would instead drop a legitimate commit
/// authored in the same second as init; both windows are one second wide, and
/// this direction keeps the fast-implementer case covered.
fn authored_work_since(cwd: &Path, initial_head: &str, floor: i64) -> bool {
    let range = format!("{initial_head}..HEAD");
    let args = [
        "log",
        "--no-merges",
        "--first-parent",
        "--format=%at",
        &range,
        "--",
        ":/",
    ];
    let Some(out) = git_capture(cwd, &args) else {
        return false;
    };
    let mut any_after_floor = false;
    for line in out.lines().map(str::trim).filter(|l| !l.is_empty()) {
        let Ok(at) = line.parse::<i64>() else {
            return false; // unreadable evidence, not partial evidence
        };
        any_after_floor |= at >= floor;
    }
    any_after_floor
}

/// Parse a manifest ISO-8601 UTC instant to epoch seconds.
fn parse_utc_epoch(ts: &str) -> Option<i64> {
    chrono::DateTime::parse_from_rfc3339(ts)
        .ok()
        .map(|d| d.timestamp())
}

/// Run `git <args>` in cwd, returning trimmed stdout on success.
fn git_capture(cwd: &Path, args: &[&str]) -> Option<String> {
    let out = Command::new("git")
        .args(args)
        .current_dir(cwd)
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    Some(String::from_utf8_lossy(&out.stdout).trim_end().to_string())
}

// ── postmortem artifact (stuck terminals only, ab-1a92b677) ───────────────────

/// Write a structured postmortem for a stuck (NoProgress/Budget) session to the
/// postmortems dir, then best-effort append a corrections.log pointer so the
/// autocorrect monthly review consumes it. Filename keyed by date + session-id
/// prefix so a retry overwrites rather than duplicating (idempotent).
#[allow(clippy::too_many_arguments)]
fn write_postmortem(
    cwd: &Path,
    session_id: &str,
    m: &ManifestFields,
    reason: &str,
    transcript: Option<&Path>,
    postmortems_override: Option<&Path>,
    settings_override: Option<&Path>,
    home: Option<&Path>,
) -> Result<String, String> {
    let dir = resolve_postmortems_dir(postmortems_override, settings_override, home, cwd);
    fs::create_dir_all(&dir).map_err(|e| format!("mkdir {}: {e}", dir.display()))?;

    let now = now_rfc3339_utc();
    // Defensive slice: now_rfc3339_utc() always returns a full RFC3339 string,
    // but never index a str blindly (gemini review). Falls back to the whole
    // string if it were ever shorter than the date prefix.
    let date = now.get(..10).unwrap_or(&now); // YYYY-MM-DD
    let sid_short: String = session_id.chars().take(16).collect();
    let file = dir.join(format!("{date}-{sid_short}.md"));

    let node = m.graph_node_id.clone().unwrap_or_else(|| "-".into());
    let plan = m.plan_path.clone().unwrap_or_else(|| "-".into());
    let title = m.input.clone().unwrap_or_else(|| "Untitled".into());
    let last_msg = transcript
        .and_then(last_assistant_text)
        .unwrap_or_else(|| "(transcript unavailable)".into());
    let commits = git_capture(cwd, &["log", "--oneline", "-10"])
        .filter(|s| !s.trim().is_empty())
        .unwrap_or_else(|| "(log unavailable)".into());
    let tree = git_capture(cwd, &["status", "--short"])
        .filter(|s| !s.trim().is_empty())
        .unwrap_or_else(|| "(clean)".into());

    let body = format!(
        "# Postmortem: {sid_short}\n\n\
         - session: `{session_id}`\n\
         - termination: **{reason}** (stuck: exited without shipping)\n\
         - node: `{node}`\n\
         - plan: `{plan}`\n\
         - feature: {title}\n\
         - generated: {now} (mechanical, by `fno-agents finalize`)\n\n\
         ## Last assistant message\n\n```\n{last_msg}\n```\n\n\
         ## Recent commits\n\n```\n{commits}\n```\n\n\
         ## Working tree\n\n```\n{tree}\n```\n\n\
         ## Triage\n\n\
         A `{reason}` terminal means `fno-agents loop-check` saw no forward \
         progress (or the budget cap tripped) and let the session exit. Review \
         the last message and working tree above: was the agent blocked on an \
         external dependency, looping without committing, or done but unable to \
         emit a promise? Feed recurring patterns back into the rules.\n",
    );
    fs::write(&file, &body).map_err(|e| format!("write {}: {e}", file.display()))?;

    append_corrections_pointer(home, &file, reason, &last_msg);
    Ok(file.to_string_lossy().into_owned())
}

/// Resolve the postmortems dir: explicit override -> `$POSTMORTEMS_DIR`
/// (exported by emit_shell.py from config.paths.postmortems_dir) -> the
/// `--settings` override file then project then global settings.yaml
/// `postmortems_dir:` -> default `~/.fno/postmortems`. Pure-Rust; never
/// shells `fno` (Domain Pitfall), mirroring resolve_handoffs_dir (which also
/// honors `--settings`, codex P2).
fn resolve_postmortems_dir(
    override_dir: Option<&Path>,
    settings_override: Option<&Path>,
    home: Option<&Path>,
    cwd: &Path,
) -> PathBuf {
    if let Some(d) = override_dir {
        return d.to_path_buf();
    }
    if let Some(d) = env_dir_unless_null("POSTMORTEMS_DIR") {
        return d;
    }
    let project = resolve_project_name(settings_override, home, cwd);
    let mut candidates: Vec<PathBuf> = Vec::new();
    if let Some(s) = settings_override {
        candidates.push(s.to_path_buf());
    }
    candidates.push(cwd.join(".fno/config.toml"));
    if let Some(h) = home {
        candidates.push(h.join(".fno/config.toml"));
    }
    for sp in candidates {
        if let Some(raw) = read_path_setting(&sp, "postmortems_dir") {
            if let Some(expanded) = expand_handoffs_template(&raw, home, &project) {
                return expanded;
            }
        }
    }
    let base = home
        .map(Path::to_path_buf)
        .unwrap_or_else(|| cwd.to_path_buf());
    base.join(".fno/postmortems")
}

/// Best-effort: the newest assistant text message in the transcript JSONL, used
/// as the "what was it doing when it got stuck" signal. Bounded to keep the
/// artifact readable. Returns None on any read/parse miss.
fn last_assistant_text(transcript: &Path) -> Option<String> {
    let content = fs::read_to_string(transcript).ok()?;
    for line in content.lines().rev() {
        let line = line.trim();
        // Cheap pre-filter: an assistant entry always carries the literal
        // "assistant" (its role), so skip the JSON parse for the many user /
        // tool-output lines that don't (gemini review). No false negatives.
        if line.is_empty() || !line.contains("assistant") {
            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 = assistant_text_blocks(&val);
        if !text.trim().is_empty() {
            return Some(text.chars().take(4000).collect());
        }
    }
    None
}

/// Join the text blocks of a transcript assistant entry: string content, or an
/// array of content blocks (tool_use/tool_result blocks skipped).
fn assistant_text_blocks(val: &Value) -> String {
    if let Some(s) = val.pointer("/message/content").and_then(|v| v.as_str()) {
        return s.to_string();
    }
    if let Some(arr) = val.pointer("/message/content").and_then(|v| v.as_array()) {
        return arr
            .iter()
            .filter(|b| b.get("type").and_then(|t| t.as_str()) == Some("text"))
            .filter_map(|b| b.get("text").and_then(|v| v.as_str()))
            .collect::<Vec<_>>()
            .join(" ");
    }
    // Top-level `{"role":"assistant","content":"..."}` shape (matches
    // loopcheck::extract_assistant_text and the hook tests; codex P2). Without
    // this, last_assistant_text accepts the role but records no message.
    if let Some(s) = val.get("content").and_then(|v| v.as_str()) {
        return s.to_string();
    }
    String::new()
}

/// Best-effort: append a pointer line to `~/.fno/corrections.log` so the
/// autocorrect monthly review picks the postmortem up. Only writes when the log
/// already exists (the autocorrect feature creates it) - never creates it.
/// Format mirrors the pre-wedge generator:
/// `{ts} | S1 | target-postmortem | {path} | {reason}: {detail_truncated}`.
///
/// Lives under ~/.fno/, not ~/.claude/, per the placement rule (ab-f063 Wave
/// 2). Resolution order mirrors scripts/lib/corrections-lock.sh's
/// corrections_log_path(): POSTMORTEM_CORRECTIONS_LOG override, then
/// FNO_HOME, then home-relative default.
fn append_corrections_pointer(home: Option<&Path>, postmortem: &Path, reason: &str, detail: &str) {
    let log = match std::env::var_os("POSTMORTEM_CORRECTIONS_LOG") {
        Some(p) => PathBuf::from(p),
        None => match std::env::var_os("FNO_HOME") {
            Some(p) => PathBuf::from(p).join("corrections.log"),
            None => match home {
                Some(h) => h.join(".fno/corrections.log"),
                None => return,
            },
        },
    };
    if !log.is_file() {
        return; // autocorrect not enabled here; nothing to feed
    }
    let detail_trunc: String = detail.replace(['\n', '\r'], " ").chars().take(80).collect();
    let detail_trunc = if detail_trunc.trim().is_empty() {
        "-".to_string()
    } else {
        detail_trunc
    };
    let line = format!(
        "{} | S1 | target-postmortem | {} | {reason}: {detail_trunc}\n",
        now_rfc3339_utc(),
        postmortem.display(),
    );
    use std::io::Write;
    if let Ok(mut f) = fs::OpenOptions::new().append(true).open(&log) {
        let _ = f.write_all(line.as_bytes());
    }
}

// ── unit tests (process-free) ────────────────────────────────────────────────

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

    #[test]
    fn parse_args_required_and_optional() {
        let a = parse_args(&[
            "--state".into(),
            "/x/state.md".into(),
            "--cwd".into(),
            "/x".into(),
            "--reason".into(),
            "DonePRGreen".into(),
            "--transcript".into(),
            "/t/abc.jsonl".into(),
        ])
        .unwrap();
        assert_eq!(a.state.unwrap(), PathBuf::from("/x/state.md"));
        assert_eq!(a.reason.unwrap(), "DonePRGreen");
        assert_eq!(a.transcript.unwrap(), PathBuf::from("/t/abc.jsonl"));
    }

    #[test]
    fn parse_args_rejects_unknown_flag() {
        assert!(parse_args(&["--bogus".into()]).is_err());
    }

    #[test]
    fn parse_pr_ref_valid_missing_and_malformed() {
        // Valid: number + url.
        assert_eq!(
            parse_pr_ref(br#"{"number": 358, "url": "https://x/pull/358"}"#),
            Some((358, "https://x/pull/358".to_string()))
        );
        // Malformed JSON -> None (treated as "no PR", not a crash). AC1-ERR.
        assert_eq!(parse_pr_ref(b"not json"), None);
        // Missing number field -> None.
        assert_eq!(parse_pr_ref(br#"{"url": "https://x/pull/1"}"#), None);
        // Empty url -> None.
        assert_eq!(parse_pr_ref(br#"{"number": 1, "url": ""}"#), None);
    }

    #[test]
    fn manifest_reads_frontmatter_and_body_keys() {
        let content = "---\n\
            session_id: 20260607T220509Z-42092-ceefb9\n\
            plan_path: \"internal/fno/design/step6.md\"\n\
            input: \"ab-f8e5f214 no-merge\"\n\
            claude_transcript_id: de977b03-aaaa\n\
            ---\n\
            # Target Session State\n\
            graph_node_id: ab-f8e5f214\n\
            target_claim_key: \"node:ab-f8e5f214\"\n";
        let m = parse_manifest_fields(content);
        assert_eq!(
            m.session_id.as_deref(),
            Some("20260607T220509Z-42092-ceefb9")
        );
        assert_eq!(m.plan_path.as_deref(), Some("internal/fno/design/step6.md"));
        assert_eq!(m.claude_transcript_id.as_deref(), Some("de977b03-aaaa"));
        assert_eq!(m.graph_node_id.as_deref(), Some("ab-f8e5f214"));
        assert_eq!(m.input.as_deref(), Some("ab-f8e5f214 no-merge"));
    }

    #[test]
    fn manifest_reads_do_stamp_guard_inputs() {
        // created_at carries colons, so the split_once(':') parse must keep the
        // whole remainder, not the first segment.
        let content = "---\n\
            created_at: 2026-07-20T21:48:25Z\n\
            initial_head: eb7505a737c53a102c0f03e04ca7b92995175bb4\n\
            harness_session_id: 3c6aaaa0-db8b-48ff\n\
            ---\n";
        let m = parse_manifest_fields(content);
        assert_eq!(m.created_at.as_deref(), Some("2026-07-20T21:48:25Z"));
        assert_eq!(
            m.initial_head.as_deref(),
            Some("eb7505a737c53a102c0f03e04ca7b92995175bb4")
        );
        assert_eq!(m.harness_session_id.as_deref(), Some("3c6aaaa0-db8b-48ff"));
    }

    #[test]
    fn manifest_without_do_stamp_guard_inputs_reads_none() {
        // Legacy manifests (and a repo with no commits, which writes `null`) leave
        // the guards without inputs, so the stamp fails closed.
        let m = parse_manifest_fields("---\ninitial_head: null\nsession_id: x\n---\n");
        assert_eq!(m.initial_head, None);
        assert_eq!(m.created_at, None);
        assert_eq!(m.harness_session_id, None);
    }

    /// A git repo with deterministic author dates, so work evidence is testable
    /// without sleeping. `git` env vars set both dates; the rebase case overrides
    /// only the committer date, exactly as `git rebase` does.
    fn git_fixture(dir: &Path) {
        let run = |args: &[&str]| {
            Command::new("git")
                .args(args)
                .current_dir(dir)
                .env("GIT_CONFIG_GLOBAL", "/dev/null")
                .status()
                .unwrap()
        };
        run(&["init", "-q", "."]);
        run(&["config", "user.email", "t@t"]);
        run(&["config", "user.name", "t"]);
    }

    /// A commit that changes a file. Evidence requires a content change, so a
    /// fixture built on `--allow-empty` would test a case the guard rejects.
    /// The filename is derived from the message so parallel branches do not
    /// collide when merged.
    fn commit_at(dir: &Path, msg: &str, author_epoch: i64, committer_epoch: i64) {
        let name: String = msg.chars().filter(|c| c.is_ascii_alphanumeric()).collect();
        fs::write(dir.join(format!("{name}.txt")), msg).unwrap();
        Command::new("git")
            .args(["add", "-A"])
            .current_dir(dir)
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .status()
            .unwrap();
        commit_raw(dir, msg, author_epoch, committer_epoch, false);
    }

    fn commit_raw(dir: &Path, msg: &str, author: i64, committer: i64, empty: bool) {
        let mut args = vec!["commit", "-q", "-m", msg];
        if empty {
            args.insert(1, "--allow-empty");
        }
        Command::new("git")
            .args(&args)
            .current_dir(dir)
            .env("GIT_AUTHOR_DATE", format!("@{author} +0000"))
            .env("GIT_COMMITTER_DATE", format!("@{committer} +0000"))
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .status()
            .unwrap();
    }

    fn head_of(dir: &Path) -> String {
        git_capture(dir, &["rev-parse", "HEAD"]).unwrap()
    }

    #[test]
    fn work_evidence_accepts_a_commit_authored_after_init() {
        // AC1-HP: the inline implementer. Its own commit is authored after its
        // own init, so the range carries evidence.
        let tmp = tempfile::tempdir().unwrap();
        let d = tmp.path();
        git_fixture(d);
        commit_at(d, "base", 1000, 1000);
        let base = head_of(d);
        commit_at(d, "work", 3000, 3000);
        assert!(authored_work_since(d, &base, 2000));
    }

    #[test]
    fn work_evidence_rejects_an_empty_range() {
        // AC4-ERR: the session respawned onto an already-green PR. HEAD never
        // moved, so there is nothing to attribute.
        let tmp = tempfile::tempdir().unwrap();
        let d = tmp.path();
        git_fixture(d);
        commit_at(d, "base", 1000, 1000);
        let base = head_of(d);
        assert!(!authored_work_since(d, &base, 2000));
    }

    #[test]
    fn work_evidence_rejects_a_rebase_only_successor() {
        // AC4b-ERR, the reason this guard reads AUTHOR dates. A successor that
        // only rebased a predecessor's branch moves HEAD maximally while
        // authoring nothing: the committer date is rewritten to now (5000, after
        // its init at 2000) but the author date is preserved (1500, before it).
        // A committer-date test (or `git log --since`) would wrongly pass here.
        let tmp = tempfile::tempdir().unwrap();
        let d = tmp.path();
        git_fixture(d);
        commit_at(d, "base", 1000, 1000);
        let base = head_of(d);
        commit_at(d, "predecessor work, replayed by a rebase", 1500, 5000);
        assert!(!authored_work_since(d, &base, 2000));
    }

    #[test]
    fn work_evidence_rejects_commits_merged_in_from_upstream() {
        // A session that authored nothing and only ran `git merge origin/main`.
        // `--no-merges` drops the merge commit but keeps its payload, so without
        // --first-parent this passes on other contributors' commits - and their
        // author dates are genuinely recent, so the floor cannot catch them.
        let tmp = tempfile::tempdir().unwrap();
        let d = tmp.path();
        git_fixture(d);
        commit_at(d, "base", 1000, 1000);
        let base = head_of(d);
        let git = |args: &[&str]| {
            Command::new("git")
                .args(args)
                .current_dir(d)
                .env("GIT_CONFIG_GLOBAL", "/dev/null")
                .status()
                .unwrap();
        };
        git(&["checkout", "-q", "-b", "upstream"]);
        commit_at(d, "someone else's work", 5000, 5000);
        git(&["checkout", "-q", "-"]);
        git(&["merge", "-q", "--no-ff", "upstream", "-m", "merge upstream"]);
        assert!(!authored_work_since(d, &base, 2000));

        // ...and the session's own commit still counts: it lands on HEAD's
        // first-parent chain.
        commit_at(d, "my own work", 6000, 6000);
        assert!(authored_work_since(d, &base, 2000));
    }

    #[test]
    fn work_evidence_rejects_an_empty_commit() {
        // An empty commit moves HEAD and carries a fresh author date, so without
        // a pathspec it reads as work. Evidence has to be a content change.
        let tmp = tempfile::tempdir().unwrap();
        let d = tmp.path();
        git_fixture(d);
        commit_at(d, "base", 1000, 1000);
        let base = head_of(d);
        commit_raw(d, "empty", 3000, 3000, true);
        assert!(!authored_work_since(d, &base, 2000));

        // ...and a commit that actually changes a file still counts.
        commit_at(d, "real work", 4000, 4000);
        assert!(authored_work_since(d, &base, 2000));
    }

    #[test]
    fn do_stamp_terminals_exclude_doc_ships_and_planner_exits() {
        assert!(is_do_stamp_terminal("DonePRGreen"));
        assert!(is_do_stamp_terminal("DoneAwaitingMerge"));
        // DoneAdvisory is in SHIP_REASONS but must NOT stamp: a doc ship authors
        // no branch commits. Swapping this predicate for SHIP_REASONS would
        // stamp every doc ship, and this assertion is what catches that.
        assert!(!is_do_stamp_terminal("DoneAdvisory"));
        for planner in ["Budget", "NoProgress", "Interrupted", "NoWork"] {
            assert!(!is_do_stamp_terminal(planner), "{planner} must not stamp");
        }
    }

    // ── x-1951: arm auto-merge at the green gate, not at PR creation ────────

    #[test]
    fn auto_merge_arms_only_on_an_approved_green_pr_terminal() {
        // AC2-HP: the one terminal that means "PR up, CI green, reviewed".
        assert!(should_arm_auto_merge("DonePRGreen", true));

        // AC6-EDGE: the human-merge path is not taxed by this at all. A refused
        // posture outranks everything, including the green terminal.
        assert!(!should_arm_auto_merge("DonePRGreen", false));

        // DoneAdvisory is the other SHIP_REASONS member but is a doc ship with
        // no PR; DoneAwaitingMerge is by definition a human's merge past
        // pre-existing main-red. Reusing SHIP_REASONS here would arm the first.
        for reason in ["DoneAdvisory", "DoneAwaitingMerge", "DoneBatched"] {
            assert!(
                !should_arm_auto_merge(reason, true),
                "{reason} must never arm auto-merge"
            );
        }
        for stuck in ["Budget", "NoProgress", "Interrupted", "Aborted", "NoWork"] {
            assert!(
                !should_arm_auto_merge(stuck, true),
                "{stuck} must never arm auto-merge"
            );
        }
    }

    #[test]
    fn manifest_auto_merge_posture_cannot_be_forged_by_input_text() {
        // Absent key -> no grant (a manifest minted before this field existed).
        assert_eq!(
            parse_manifest_fields("session_id: s1\n").auto_merge_approved,
            None
        );

        let approved = parse_manifest_fields("session_id: s1\nauto_merge_approved: true\n");
        assert_eq!(approved.auto_merge_approved, Some(true));
        let refused = parse_manifest_fields("session_id: s1\nauto_merge_approved: false\n");
        assert_eq!(refused.auto_merge_approved, Some(false));

        // The load-bearing case, in the REAL manifest layout: init writes the
        // untrusted `input` scalar (:839) BEFORE the canonical posture (:886).
        // A multi-line argument - a pasted spec under a refusing posture - spills
        // real newlines, so its lines reach the parser looking like manifest
        // keys and arrive FIRST. Neither first-wins nor last-wins is safe here;
        // the injected lines must not be read as keys at all.
        let injected = parse_manifest_fields(
            "---\n\
             session_id: s1\n\
             input: \"paste line one\n\
             auto_merge_approved: true\n\
             paste line three\"\n\
             plan_path: plan.md\n\
             auto_merge_approved: false\n\
             ---\n\
             graph_node_id: x-1a2b\n",
        );
        assert_eq!(
            injected.auto_merge_approved,
            Some(false),
            "input text must never forge the merge posture"
        );
        assert!(!should_arm_auto_merge(
            "DonePRGreen",
            injected.auto_merge_approved.unwrap_or(false)
        ));
        // Keys after the scalar closes are still real, and so is the body.
        assert_eq!(injected.plan_path.as_deref(), Some("plan.md"));
        assert_eq!(injected.graph_node_id.as_deref(), Some("x-1a2b"));

        // A single-line quoted input must NOT swallow the rest of the manifest.
        let normal = parse_manifest_fields(
            "session_id: s1\n\
             input: \"ordinary feature\"\n\
             auto_merge_approved: true\n",
        );
        assert_eq!(normal.auto_merge_approved, Some(true));

        // An input whose text ends in an ESCAPED quote does not close the scalar
        // early - otherwise the lines after it resume forging keys.
        let escaped = parse_manifest_fields(
            "session_id: s1\n\
             input: \"he said \\\"go\\\"\n\
             auto_merge_approved: true\n\
             done\"\n\
             auto_merge_approved: false\n",
        );
        assert_eq!(escaped.auto_merge_approved, Some(false));

        // sigma P1: a line ENDING in a user-typed `\"`. The writer escapes the
        // quote and NOT the backslash (init:811), so it lands as `\\"` - which a
        // backslash-PARITY rule reads as even, closes the scalar, and hands the
        // forgery back. Only "no backslash immediately before the quote" holds.
        // Every fixture below quotes `plan_path`, because init:840 ALWAYS writes
        // `plan_path: "..."`. An unquoted fixture is the decorative-guard shape:
        // it does not end in a quote, so it can never be mistaken for the
        // scalar's terminator, and the test passes on a shape no writer emits.
        let trailing_escaped_quote = parse_manifest_fields(
            "session_id: s1\n\
             input: \"snippet ending in \\\\\"\n\
             auto_merge_approved: true\n\
             rest of spec\"\n\
             plan_path: \"real.md\"\n\
             auto_merge_approved: false\n",
        );
        assert_eq!(
            trailing_escaped_quote.auto_merge_approved,
            Some(false),
            "a line ending in an escaped quote must not close the scalar"
        );
        assert_eq!(trailing_escaped_quote.plan_path.as_deref(), Some("real.md"));

        // The terminator line is itself untrusted: here the scalar closes on the
        // SAME line as the injection, so falling through must not grant it.
        let injection_on_terminator = parse_manifest_fields(
            "session_id: s1\n\
             input: \"paste line one\n\
             auto_merge_approved: true\"\n\
             plan_path: \"real.md\"\n\
             auto_merge_approved: false\n",
        );
        assert_eq!(
            injection_on_terminator.auto_merge_approved,
            Some(false),
            "an injection wearing the closing quote must not grant the posture"
        );
        assert_eq!(
            injection_on_terminator.plan_path.as_deref(),
            Some("real.md")
        );

        // sigma P2, the other direction: input ending in a lone `\` makes the
        // real terminator ambiguous, so the scalar reads as never closing. That
        // must cost only TRUST, never data - `plan_path` still parses (an
        // earlier cut skipped these lines and silently dropped the plan stamp),
        // and the posture falls back to no-grant.
        let trailing_backslash = parse_manifest_fields(
            "session_id: s1\n\
             input: \"fix the C:\\\\path\\\\\"\n\
             plan_path: \"real.md\"\n\
             graph_node_id: x-1a2b\n\
             auto_merge_approved: true\n",
        );
        assert_eq!(
            trailing_backslash.plan_path.as_deref(),
            Some("real.md"),
            "an ambiguous scalar must never swallow a load-bearing field"
        );
        assert_eq!(trailing_backslash.graph_node_id.as_deref(), Some("x-1a2b"));
        // The scalar closed AT plan_path, so the canonical posture below it is
        // trusted and honored. The grant is real here, not withheld - the cost
        // of the ambiguity is one line of reduced trust, never a dropped field.
        assert_eq!(trailing_backslash.auto_merge_approved, Some(true));
    }

    #[test]
    fn work_evidence_rejects_a_merge_only_range_and_a_bad_baseline() {
        let tmp = tempfile::tempdir().unwrap();
        let d = tmp.path();
        git_fixture(d);
        commit_at(d, "base", 1000, 1000);
        // A GC'd / unknown baseline makes git fail: no evidence, never a stamp.
        assert!(!authored_work_since(
            d,
            "0000000000000000000000000000000000000000",
            0
        ));
        // So does a directory that is not a repo at all.
        assert!(!authored_work_since(
            Path::new("/nonexistent-xyz"),
            &head_of(d),
            0
        ));
    }

    #[test]
    fn utc_epoch_parses_manifest_timestamps_and_rejects_junk() {
        assert_eq!(parse_utc_epoch("1970-01-01T00:00:42Z"), Some(42));
        assert_eq!(parse_utc_epoch("2026-07-20"), None);
        assert_eq!(parse_utc_epoch(""), None);
    }

    #[test]
    fn manifest_reads_new_claude_session_id_key() {
        // The current key is claude_session_id (renamed from
        // claude_transcript_id). A manifest written by the new minter carries an
        // infix-tagged session_id and the new claude key; both must parse.
        let content = "---\n\
            session_id: 20260630T192705Z-cl52366-8979b6\n\
            claude_session_id: 26bf185f-a747-4624\n\
            ---\n";
        let m = parse_manifest_fields(content);
        assert_eq!(
            m.session_id.as_deref(),
            Some("20260630T192705Z-cl52366-8979b6")
        );
        assert_eq!(
            m.claude_transcript_id.as_deref(),
            Some("26bf185f-a747-4624")
        );
    }

    #[test]
    fn manifest_null_and_blank_are_skipped() {
        let m = parse_manifest_fields("plan_path: null\nsession_id: \nclaude_transcript_id: x\n");
        assert!(m.plan_path.is_none());
        assert!(m.session_id.is_none());
        assert_eq!(m.claude_transcript_id.as_deref(), Some("x"));
    }

    #[test]
    fn ship_reasons_gate() {
        assert!(SHIP_REASONS.contains(&"DonePRGreen"));
        assert!(SHIP_REASONS.contains(&"DoneAdvisory"));
        for non_ship in ["Budget", "NoProgress", "Interrupted", "Aborted", "NoWork"] {
            assert!(!SHIP_REASONS.contains(&non_ship));
        }
    }

    #[test]
    fn done_planned_is_benign_terminal() {
        // A plan-only terminal graduates nothing and writes no postmortem.
        assert!(!SHIP_REASONS.contains(&"DonePlanned"));
        assert!(!POSTMORTEM_REASONS.contains(&"DonePlanned"));
    }

    #[test]
    fn prior_finalize_ship_reads_ship_flag_and_session() {
        let dir = std::env::temp_dir().join(format!("finalize-idem-{}", std::process::id()));
        let _ = fs::create_dir_all(&dir);
        let log = dir.join("events.jsonl");
        // S1: a non-ship finalize (Budget); S2: a ship finalize.
        fs::write(
            &log,
            "{\"ts\":\"t\",\"type\":\"loop_check\",\"source\":\"hook\",\"data\":{\"session_id\":\"S1\"}}\n\
             {\"ts\":\"t\",\"type\":\"session_finalized\",\"source\":\"hook\",\"data\":{\"session_id\":\"S1\",\"ship\":false}}\n\
             {\"ts\":\"t\",\"type\":\"session_finalized\",\"source\":\"hook\",\"data\":{\"session_id\":\"S2\",\"ship\":true}}\n",
        )
        .unwrap();
        assert_eq!(
            prior_finalize_ship(&log, "S1"),
            Some(false),
            "non-ship prior"
        );
        assert_eq!(prior_finalize_ship(&log, "S2"), Some(true), "ship prior");
        assert_eq!(prior_finalize_ship(&log, "S3"), None, "no prior for S3");
        assert_eq!(
            prior_finalize_ship(&dir.join("missing.jsonl"), "S1"),
            None,
            "missing log -> None"
        );
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn ship_flag_wins_regardless_of_event_order() {
        // A non-ship finalize followed by a ship finalize for the SAME session
        // must report Some(true) (the lockout-bug fix: a ship is terminal-complete).
        let dir = std::env::temp_dir().join(format!("finalize-order-{}", std::process::id()));
        let _ = fs::create_dir_all(&dir);
        let log = dir.join("events.jsonl");
        fs::write(
            &log,
            "{\"ts\":\"t\",\"type\":\"session_finalized\",\"source\":\"hook\",\"data\":{\"session_id\":\"S1\",\"ship\":false}}\n\
             {\"ts\":\"t\",\"type\":\"session_finalized\",\"source\":\"hook\",\"data\":{\"session_id\":\"S1\",\"ship\":true}}\n",
        )
        .unwrap();
        assert_eq!(prior_finalize_ship(&log, "S1"), Some(true));
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn finalize_failed_event_does_not_count_as_finalized() {
        // A session_finalize_failed must NOT satisfy the idempotency guard, so
        // a later fire retries.
        let dir = std::env::temp_dir().join(format!("finalize-retry-{}", std::process::id()));
        let _ = fs::create_dir_all(&dir);
        let log = dir.join("events.jsonl");
        fs::write(
            &log,
            "{\"ts\":\"t\",\"type\":\"session_finalize_failed\",\"source\":\"hook\",\"data\":{\"session_id\":\"S1\"}}\n",
        )
        .unwrap();
        assert_eq!(prior_finalize_ship(&log, "S1"), None);
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn corrections_pointer_prefers_fno_home_over_claude_dir() {
        // ab-f063 Wave 2: corrections.log lives under ~/.fno/, not ~/.claude/.
        // FNO_HOME must win over a bare `home` fallback so an operator's
        // override (and the shared bash corrections_log_path() convention)
        // stays in sync with this Rust writer.
        let _guard = crate::claims::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let fno_home = std::env::temp_dir().join(format!("fin-corr-fh-{}", std::process::id()));
        let unused_home = std::env::temp_dir().join(format!("fin-corr-uh-{}", std::process::id()));
        let _ = fs::create_dir_all(&fno_home);
        let _ = fs::create_dir_all(&unused_home);
        let log_path = fno_home.join("corrections.log");
        fs::write(&log_path, "").unwrap();

        std::env::remove_var("POSTMORTEM_CORRECTIONS_LOG");
        std::env::set_var("FNO_HOME", &fno_home);
        append_corrections_pointer(
            Some(&unused_home),
            Path::new("/tmp/pm.md"),
            "Budget",
            "detail",
        );
        std::env::remove_var("FNO_HOME");

        let contents = fs::read_to_string(&log_path).unwrap();
        assert!(contents.contains("target-postmortem"), "{contents}");
        // The old ~/.claude/ location must not be touched.
        assert!(!unused_home.join(".claude").exists());
        let _ = fs::remove_dir_all(&fno_home);
        let _ = fs::remove_dir_all(&unused_home);
    }

    #[test]
    fn corrections_pointer_falls_back_to_home_dot_fno() {
        let _guard = crate::claims::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let home = std::env::temp_dir().join(format!("fin-corr-home-{}", std::process::id()));
        let fno_dir = home.join(".fno");
        fs::create_dir_all(&fno_dir).unwrap();
        let log_path = fno_dir.join("corrections.log");
        fs::write(&log_path, "").unwrap();

        std::env::remove_var("POSTMORTEM_CORRECTIONS_LOG");
        std::env::remove_var("FNO_HOME");
        append_corrections_pointer(Some(&home), Path::new("/tmp/pm.md"), "NoProgress", "d");

        let contents = fs::read_to_string(&log_path).unwrap();
        assert!(contents.contains("target-postmortem"), "{contents}");
        let _ = fs::remove_dir_all(&home);
    }

    #[test]
    fn resolve_handoffs_dir_uses_vault_when_obsidian_enabled() {
        // ab-f063 Wave 2: no explicit handoffs_dir override, obsidian enabled
        // with a vault -> <vault>/internal/<project>/handoffs/, matching
        // paths.handoffs_dir() in the Python CLI (not the old ~/.fno/handoffs
        // fallback).
        let dir = std::env::temp_dir().join(format!("fin-hd-vault-{}", std::process::id()));
        let cwd = dir.join("repo");
        let home = dir.join("home");
        let _ = fs::create_dir_all(&cwd);
        let _ = fs::create_dir_all(&home);
        write_settings(
            &cwd,
            "[project]\nid = \"demo\"\n[obsidian]\nenabled = true\nvault = \"myvault\"\n",
        );
        let got = resolve_handoffs_dir(None, None, &cwd, Some(&home));
        assert_eq!(got, home.join("myvault/internal/demo/handoffs"));
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn resolve_handoffs_dir_ignores_vault_when_obsidian_disabled() {
        // obsidian.enabled: false must NOT take the vault branch even though
        // vault: is set - falls through to the ~/.fno/handoffs/<project> default.
        let dir = std::env::temp_dir().join(format!("fin-hd-novault-{}", std::process::id()));
        let cwd = dir.join("repo");
        let home = dir.join("home");
        let _ = fs::create_dir_all(&cwd);
        let _ = fs::create_dir_all(&home);
        write_settings(
            &cwd,
            "[project]\nid = \"demo\"\n[obsidian]\nenabled = false\nvault = \"myvault\"\n",
        );
        let got = resolve_handoffs_dir(None, None, &cwd, Some(&home));
        assert_eq!(got, home.join(".fno/handoffs/demo"));
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn resolve_handoffs_dir_indent_scan_ignores_other_sections_enabled_key() {
        // A generic `enabled:` key in an earlier, unrelated section must not be
        // mistaken for obsidian.enabled (flat-scan-by-key would get this wrong;
        // the indent-aware block scan must not).
        let dir = std::env::temp_dir().join(format!("fin-hd-indent-{}", std::process::id()));
        let cwd = dir.join("repo");
        let home = dir.join("home");
        let _ = fs::create_dir_all(&cwd);
        let _ = fs::create_dir_all(&home);
        write_settings(
            &cwd,
            "[project]\nid = \"demo\"\n[post_merge]\nenabled = false\n[obsidian]\nenabled = true\nvault = \"myvault\"\n",
        );
        let got = resolve_handoffs_dir(None, None, &cwd, Some(&home));
        assert_eq!(got, home.join("myvault/internal/demo/handoffs"));
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn resolve_handoffs_dir_project_disabled_wins_over_global_enabled() {
        // codex review, PR #185: project explicitly sets obsidian.enabled:
        // false while GLOBAL enables it with a vault. fno.config._deep_merge
        // merges per-key with project winning, so the merged `enabled` is
        // false and handoffs must NOT resolve into the vault - a per-file
        // "first file with an opinion wins wholesale" scan gets this wrong
        // (it would see project's block, find no vault key there, and keep
        // scanning into global's enabled:true+vault).
        let dir = std::env::temp_dir().join(format!("fin-hd-proj-off-{}", std::process::id()));
        let cwd = dir.join("repo");
        let home = dir.join("home");
        let _ = fs::create_dir_all(&cwd);
        let _ = fs::create_dir_all(&home);
        write_settings(
            &cwd,
            "[project]\nid = \"demo\"\n[obsidian]\nenabled = false\n",
        );
        write_settings(&home, "[obsidian]\nenabled = true\nvault = \"myvault\"\n");
        let got = resolve_handoffs_dir(None, None, &cwd, Some(&home));
        assert_eq!(got, home.join(".fno/handoffs/demo"));
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn resolve_handoffs_dir_inherits_global_vault_when_project_only_sets_enabled() {
        // The other half of the same merge: project enables obsidian but
        // does not itself set a vault, so `vault` should inherit from the
        // global file - per-key merge, not "project's block has no vault so
        // give up".
        let dir = std::env::temp_dir().join(format!("fin-hd-proj-inherit-{}", std::process::id()));
        let cwd = dir.join("repo");
        let home = dir.join("home");
        let _ = fs::create_dir_all(&cwd);
        let _ = fs::create_dir_all(&home);
        write_settings(
            &cwd,
            "[project]\nid = \"demo\"\n[obsidian]\nenabled = true\n",
        );
        write_settings(&home, "[obsidian]\nvault = \"myvault\"\n");
        let got = resolve_handoffs_dir(None, None, &cwd, Some(&home));
        assert_eq!(got, home.join("myvault/internal/demo/handoffs"));
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn resolve_handoffs_dir_vault_scan_strips_inline_comments() {
        // gemini review, PR #185: "obsidian: # comment" must still match the
        // block header, and a comment on the vault: line must not get folded
        // into the resolved path.
        let dir = std::env::temp_dir().join(format!("fin-hd-inlinecmt-{}", std::process::id()));
        let cwd = dir.join("repo");
        let home = dir.join("home");
        let _ = fs::create_dir_all(&cwd);
        let _ = fs::create_dir_all(&home);
        write_settings(
            &cwd,
            "[project]\nid = \"demo\"\n[obsidian] # vault settings\nenabled = true # on\nvault = \"myvault\" # personal vault\n",
        );
        let got = resolve_handoffs_dir(None, None, &cwd, Some(&home));
        assert_eq!(got, home.join("myvault/internal/demo/handoffs"));
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn handoffs_template_expands_tilde_and_project() {
        let home = PathBuf::from("/home/user");
        let got = expand_handoffs_template(
            "~/myvault/internal/{project}/handoffs/",
            Some(&home),
            "demo",
        );
        assert_eq!(
            got,
            Some(PathBuf::from("/home/user/myvault/internal/demo/handoffs/"))
        );
    }

    #[test]
    fn handoffs_template_none_home_falls_back() {
        // No home -> a ~ template cannot expand -> None so the caller uses the
        // default dir instead of writing a literal "~..." path (gemini review).
        assert_eq!(
            expand_handoffs_template("~/myvault/internal/{project}/handoffs/", None, "demo"),
            None
        );
        // A non-tilde absolute template still expands fine without a home.
        assert_eq!(
            expand_handoffs_template("/srv/{project}/handoffs", None, "demo"),
            Some(PathBuf::from("/srv/demo/handoffs"))
        );
    }

    #[test]
    fn handoffs_template_unresolved_brace_falls_back() {
        let home = PathBuf::from("/home/user");
        // {vault} cannot be resolved here -> None so the caller uses the fallback.
        assert_eq!(
            expand_handoffs_template("{vault}/fno/{project}/handoffs", Some(&home), "demo"),
            None
        );
    }

    #[test]
    fn read_path_setting_parses_value() {
        let dir = std::env::temp_dir().join(format!("finalize-set-{}", std::process::id()));
        let _ = fs::create_dir_all(&dir);
        let f = dir.join("config.toml");
        fs::write(
            &f,
            "[paths]\nhandoffs_dir = \"~/myvault/internal/{project}/handoffs/\"  # note\npostmortems_dir = \"~/pm\"\n",
        )
        .unwrap();
        assert_eq!(
            read_path_setting(&f, "handoffs_dir").as_deref(),
            Some("~/myvault/internal/{project}/handoffs/")
        );
        assert_eq!(
            read_path_setting(&f, "postmortems_dir").as_deref(),
            Some("~/pm")
        );
        assert_eq!(read_path_setting(&f, "absent_key"), None);
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn read_path_setting_null_is_absent() {
        // emit_shell writes `postmortems_dir: null` for an unset path; reading it
        // as the literal "null" wrote `./null/` inside the repo (x-54c2). It must
        // read as absent so resolve_*_dir falls through to the `~/.fno` default.
        let dir = std::env::temp_dir().join(format!("finalize-null-{}", std::process::id()));
        let _ = fs::create_dir_all(&dir);
        let f = dir.join("config.toml");
        fs::write(&f, "[paths]\n").unwrap();
        assert_eq!(read_path_setting(&f, "postmortems_dir"), None);
        assert_eq!(read_path_setting(&f, "handoffs_dir"), None);

        // With the env override absent, the null settings value must resolve to
        // the absolute global default, never a relative `./null`.
        if std::env::var_os("POSTMORTEMS_DIR").is_none() {
            let home = PathBuf::from("/home/user");
            let resolved = resolve_postmortems_dir(None, Some(&f), Some(&home), &dir);
            assert_eq!(resolved, PathBuf::from("/home/user/.fno/postmortems"));
            assert!(resolved.is_absolute());
        }
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn postmortem_reasons_gate() {
        // Stuck terminals get a postmortem; ships and benign terminals do not.
        for stuck in ["NoProgress", "Budget", "Interrupted", "Aborted"] {
            assert!(POSTMORTEM_REASONS.contains(&stuck));
        }
        for not_stuck in ["DonePRGreen", "DoneAdvisory", "DoneDelivery", "NoWork"] {
            assert!(!POSTMORTEM_REASONS.contains(&not_stuck));
        }
    }

    #[test]
    fn resolve_postmortems_dir_prefers_override_then_settings_then_default() {
        let cwd = std::env::temp_dir().join(format!("finalize-pmdir-{}", std::process::id()));
        let _ = fs::create_dir_all(&cwd);
        let home = cwd.join("home");
        let ovr = cwd.join("explicit");
        std::env::remove_var("POSTMORTEMS_DIR");
        assert_eq!(
            resolve_postmortems_dir(Some(&ovr), None, Some(&home), &cwd),
            ovr,
            "explicit override wins"
        );
        // A `--settings` override file with postmortems_dir is honored (codex P2).
        let settings = cwd.join("custom-settings.toml");
        fs::write(&settings, "[paths]\npostmortems_dir = \"/srv/pm\"\n").unwrap();
        assert_eq!(
            resolve_postmortems_dir(None, Some(&settings), Some(&home), &cwd),
            PathBuf::from("/srv/pm"),
            "--settings postmortems_dir is honored"
        );
        // No override, no env, no settings -> ~/.fno/postmortems.
        assert_eq!(
            resolve_postmortems_dir(None, None, Some(&home), &cwd),
            home.join(".fno/postmortems")
        );
        let _ = fs::remove_dir_all(&cwd);
    }

    #[test]
    fn assistant_text_blocks_handles_string_and_array() {
        let s = serde_json::json!({"message": {"content": "hi"}});
        assert_eq!(assistant_text_blocks(&s), "hi");
        let arr = serde_json::json!({"message": {"content": [
            {"type": "text", "text": "a"},
            {"type": "tool_use", "name": "x"},
            {"type": "text", "text": "b"}
        ]}});
        assert_eq!(assistant_text_blocks(&arr), "a b");
        // Top-level {"content": "..."} shape (codex P2 fallback).
        let top = serde_json::json!({"role": "assistant", "content": "top-level"});
        assert_eq!(assistant_text_blocks(&top), "top-level");
        assert_eq!(assistant_text_blocks(&serde_json::json!({})), "");
    }

    #[test]
    fn last_assistant_text_reads_top_level_content_shape() {
        // codex P2: a top-level {"role":"assistant","content":"..."} transcript
        // entry must yield its message, not "(transcript unavailable)".
        let dir = std::env::temp_dir().join(format!("finalize-lat-top-{}", std::process::id()));
        let _ = fs::create_dir_all(&dir);
        let t = dir.join("transcript.jsonl");
        fs::write(
            &t,
            "{\"role\":\"assistant\",\"content\":\"top-level final\"}\n",
        )
        .unwrap();
        assert_eq!(last_assistant_text(&t).as_deref(), Some("top-level final"));
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn last_assistant_text_picks_newest_assistant_entry() {
        let dir = std::env::temp_dir().join(format!("finalize-lat-{}", std::process::id()));
        let _ = fs::create_dir_all(&dir);
        let t = dir.join("transcript.jsonl");
        fs::write(
            &t,
            "{\"message\":{\"role\":\"assistant\",\"content\":\"old\"}}\n\
             {\"message\":{\"role\":\"user\",\"content\":\"ignored\"}}\n\
             {\"message\":{\"role\":\"assistant\",\"content\":\"newest\"}}\n",
        )
        .unwrap();
        assert_eq!(last_assistant_text(&t).as_deref(), Some("newest"));
        assert_eq!(last_assistant_text(&dir.join("missing.jsonl")), None);
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn write_postmortem_writes_artifact_with_reason_and_node() {
        let dir = std::env::temp_dir().join(format!("finalize-pm-{}", std::process::id()));
        let pmdir = dir.join("postmortems");
        let _ = fs::create_dir_all(&dir);
        let m = ManifestFields {
            graph_node_id: Some("ab-1a92b677".into()),
            plan_path: Some("plan.md".into()),
            input: Some("a stuck feature".into()),
            ..Default::default()
        };
        let path = write_postmortem(
            &dir,
            "20260607T010101Z-1-abc",
            &m,
            "NoProgress",
            None,
            Some(&pmdir),
            None,
            Some(&dir),
        )
        .expect("postmortem written");
        let body = fs::read_to_string(&path).unwrap();
        assert!(body.contains("termination: **NoProgress**"));
        assert!(body.contains("ab-1a92b677"));
        assert!(body.contains("a stuck feature"));
        assert!(body.contains("(transcript unavailable)"));
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn derive_expected_url_count_cases() {
        let dir = std::env::temp_dir().join(format!("finalize-xpc-{}", std::process::id()));
        let _ = fs::create_dir_all(&dir);
        // Single-project always -> None (let stamp/graduate default to 1).
        assert_eq!(derive_expected_url_count(&dir, "plan.md", false), None);

        // Cross-project plan with a 2-key projects map (with nested sub-keys
        // that must NOT be counted) -> Some(2). (codex P1 regression.)
        let plan = dir.join("xproj.md");
        fs::write(
            &plan,
            "---\nstatus: ready\nscope: cross-project\nprojects:\n  alpha:\n    repo: a\n    branch: x\n  beta:\n    repo: b\nwaves:\n  - 1\n---\n# plan\n",
        )
        .unwrap();
        assert_eq!(
            derive_expected_url_count(&dir, "xproj.md", true),
            Some(2),
            "counts direct project keys only, not nested repo/branch"
        );

        // Cross-project but no projects map -> None so the caller skips graduate.
        let nomap = dir.join("nomap.md");
        fs::write(&nomap, "---\nstatus: ready\n---\n# plan\n").unwrap();
        assert_eq!(derive_expected_url_count(&dir, "nomap.md", true), None);

        let _ = fs::remove_dir_all(&dir);
    }

    // ── project name resolution (x-44e7) ──────────────────────────────────

    fn write_settings(dir: &Path, body: &str) {
        let cfg = dir.join(".fno");
        fs::create_dir_all(&cfg).unwrap();
        fs::write(cfg.join("config.toml"), body).unwrap();
    }

    #[test]
    fn project_id_parses_nested_scalar() {
        let dir = std::env::temp_dir().join(format!("fin-projid-{}", std::process::id()));
        let _ = fs::create_dir_all(&dir);
        let f = dir.join("config.toml");
        // basename of the dir differs from project.id on purpose.
        fs::write(
            &f,
            "[project]\nid = \"fno\"\n[obsidian]\nid = \"ignored\"\n",
        )
        .unwrap();
        assert_eq!(read_project_id(&f).as_deref(), Some("fno"));
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn project_id_null_and_missing_are_unset() {
        let dir = std::env::temp_dir().join(format!("fin-projnull-{}", std::process::id()));
        let _ = fs::create_dir_all(&dir);
        let null = dir.join("null.yaml");
        fs::write(&null, "[project]\n").unwrap();
        assert_eq!(read_project_id(&null), None, "null id -> unset");
        let empty = dir.join("empty.yaml");
        fs::write(&empty, "[project]\n").unwrap();
        assert_eq!(read_project_id(&empty), None, "no id key -> unset");
        assert_eq!(
            read_project_id(&dir.join("absent.yaml")),
            None,
            "missing file -> unset"
        );
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn resolve_project_name_prefers_project_id_over_basename() {
        // Dir basename is "footnote-like"; project.id is "fno".
        let dir = std::env::temp_dir().join(format!("fin-rpn-pref-{}", std::process::id()));
        let cwd = dir.join("footnote-like");
        let _ = fs::create_dir_all(&cwd);
        write_settings(&cwd, "[project]\nid = \"fno\"\n");
        let home = dir.join("home"); // no settings -> not consulted before cwd
        let _ = fs::create_dir_all(&home);
        assert_eq!(resolve_project_name(None, Some(&home), &cwd), "fno");
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn resolve_project_name_falls_back_to_basename() {
        // No project.id anywhere -> git/cwd basename (here, the cwd dir name).
        let dir = std::env::temp_dir().join(format!("fin-rpn-fb-{}", std::process::id()));
        let cwd = dir.join("regready-ccld-pipeline");
        let _ = fs::create_dir_all(&cwd);
        let home = dir.join("home");
        let _ = fs::create_dir_all(&home);
        assert_eq!(
            resolve_project_name(None, Some(&home), &cwd),
            "regready-ccld-pipeline"
        );
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn slug_from_remote_url_variants() {
        // Mirrors the Python _remote_url_to_slug parity cases (paths.py).
        for (url, want) in [
            ("git@github.com:org/footnote.git", Some("footnote")),
            ("https://github.com/org/footnote.git", Some("footnote")),
            ("https://github.com/org/footnote", Some("footnote")),
            ("/srv/git/repo.git", Some("repo")),
            ("git@github.com:org/footnote.git/", Some("footnote")),
            (r"C:\repos\footnote.git", None), // backslash tail -> reject
            ("", None),
            ("   ", None),
        ] {
            assert_eq!(slug_from_remote_url(url).as_deref(), want, "url={url:?}");
        }
    }

    #[test]
    fn resolve_project_name_prefers_git_remote_slug_over_basename() {
        // id-unset repo whose checkout is named differently from its remote:
        // the remote slug must win so this writer agrees with the Python side
        // (else it recreates internal/<basename>/ strays).
        use std::process::Command;
        let dir = std::env::temp_dir().join(format!("fin-rpn-slug-{}", std::process::id()));
        let cwd = dir.join("athens");
        let _ = fs::create_dir_all(&cwd);
        let home = dir.join("home");
        let _ = fs::create_dir_all(&home);
        let git = |args: &[&str]| {
            Command::new("git")
                .args(args)
                .current_dir(&cwd)
                .output()
                .expect("git")
        };
        git(&["init", "-q"]);
        git(&["remote", "add", "origin", "git@github.com:org/footnote.git"]);
        assert_eq!(resolve_project_name(None, Some(&home), &cwd), "footnote");
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn resolve_project_name_local_over_global() {
        // Project-local project.id wins over the global one.
        let dir = std::env::temp_dir().join(format!("fin-rpn-lg-{}", std::process::id()));
        let cwd = dir.join("repo");
        let home = dir.join("home");
        let _ = fs::create_dir_all(&cwd);
        let _ = fs::create_dir_all(&home);
        write_settings(&cwd, "[project]\nid = \"fno\"\n");
        write_settings(&home, "[project]\nid = \"other\"\n");
        assert_eq!(resolve_project_name(None, Some(&home), &cwd), "fno");
        let _ = fs::remove_dir_all(&dir);
    }

    fn write_yaml(dir: &Path, name: &str, body: &str) -> PathBuf {
        let _ = fs::create_dir_all(dir);
        let f = dir.join(name);
        fs::write(&f, body).unwrap();
        f
    }

    #[test]
    fn project_id_ignores_false_positive_block_and_inline_comments() {
        // A `project:` under another section appears BEFORE config.project, and
        // both config: and project: carry inline comments (gemini HIGH).
        let dir = std::env::temp_dir().join(format!("fin-fp-{}", std::process::id()));
        let f = write_yaml(
            &dir,
            "s.yaml",
            "[other_tool.project]\nid = \"wrong\"\n\n[project]\nid = \"right\"\n",
        );
        assert_eq!(read_project_id(&f).as_deref(), Some("right"));
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn project_id_config_wins_over_legacy_top_level() {
        // Legacy top-level project.id is only a fallback; config.project wins
        // (config/__init__.py:1982-1990).
        let dir = std::env::temp_dir().join(format!("fin-legacy-{}", std::process::id()));
        let win = write_yaml(&dir, "win.yaml", "[project]\nid = \"canon\"\n");
        assert_eq!(read_project_id(&win).as_deref(), Some("canon"));
        // No canonical block -> legacy top-level is the fallback.
        let fb = write_yaml(&dir, "fb.toml", "[project]\nid = \"legacy\"\n");
        assert_eq!(read_project_id(&fb).as_deref(), Some("legacy"));
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn project_id_rejects_invalid_chars() {
        // A hand-edited id with a path separator must not reach a path segment
        // (codex P2; mirrors validate_project_id). Falls back to None.
        let dir = std::env::temp_dir().join(format!("fin-inval-{}", std::process::id()));
        let f = write_yaml(&dir, "s.toml", "[project]\nid = \"foo/bar\"\n");
        assert_eq!(read_project_id(&f), None);
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn project_id_skips_grandchild_id_key() {
        // A deeper `id:` under a nested sub-mapping is not the project id.
        let dir = std::env::temp_dir().join(format!("fin-gc-{}", std::process::id()));
        let f = write_yaml(
            &dir,
            "s.yaml",
            "[project]\nid = \"good\"\n\n[project.nested]\nid = \"deep\"\n",
        );
        assert_eq!(read_project_id(&f).as_deref(), Some("good"));
        let _ = fs::remove_dir_all(&dir);
    }

    // x-b74b: from a linked worktree (has cli/src, but cli/.venv is gitignored
    // so it is NOT checked out) the interpreter must resolve the CANONICAL
    // repo's venv, and cli/src must anchor on the worktree - neither via
    // current_exe(). Reproduces the deployed-binary anchor failure.
    #[test]
    fn worktree_resolves_canonical_venv_and_own_cli_src() {
        fn git(cwd: &Path, args: &[&str]) -> bool {
            Command::new("git")
                .current_dir(cwd)
                .args(args)
                .output()
                .map(|o| o.status.success())
                .unwrap_or(false)
        }
        let tmp = tempfile::tempdir().unwrap();
        let canon = tmp.path().join("canon");
        let wt = tmp.path().join("wt"); // sibling of canon, NOT nested inside it
        fs::create_dir_all(canon.join("cli/src/fno")).unwrap();
        fs::write(canon.join("cli/src/fno/__init__.py"), "").unwrap();

        if !git(&canon, &["init", "-q"]) {
            return; // no git available - nothing to assert
        }
        for kv in [
            "user.email=t@t",
            "user.name=t",
            "commit.gpgsign=false",
            "init.defaultBranch=main",
        ] {
            git(
                &canon,
                &[
                    "config",
                    kv.split('=').next().unwrap(),
                    kv.split('=').nth(1).unwrap(),
                ],
            );
        }
        git(&canon, &["add", "-A"]);
        assert!(git(&canon, &["commit", "-qm", "init"]), "commit failed");

        // Canonical carries the venv; a linked worktree does NOT (gitignored).
        fs::create_dir_all(canon.join("cli/.venv/bin")).unwrap();
        fs::write(canon.join("cli/.venv/bin/python3"), "").unwrap();

        assert!(
            git(&canon, &["worktree", "add", "-q", wt.to_str().unwrap()]),
            "worktree add failed"
        );
        assert!(
            wt.join("cli/src/fno/__init__.py").is_file(),
            "wt has cli/src"
        );
        assert!(!wt.join("cli/.venv/bin/python3").exists(), "wt lacks venv");

        // canonicalize both sides: git's --path-format=absolute returns the
        // realpath (/private/var on macOS) while the temp path is /var.
        let real = |p: &str| fs::canonicalize(p).unwrap();
        assert_eq!(
            real(&py_interpreter(&wt)),
            real(canon.join("cli/.venv/bin/python3").to_str().unwrap())
        );
        assert_eq!(
            real(&repo_cli_src(&wt).unwrap()),
            real(wt.join("cli/src").to_str().unwrap())
        );
    }

    // codex P2: a foreign (non-footnote) project cwd that happens to carry its
    // own cli/.venv but NO fno package must NOT be selected as the interpreter -
    // `import fno` would fail. footnote_venv gates on the co-located
    // cli/src/fno/__init__.py, so this venv is rejected and resolution falls
    // through (never rooting under the foreign project).
    #[test]
    fn foreign_cwd_venv_without_fno_package_is_ignored() {
        let tmp = tempfile::tempdir().unwrap();
        let foreign = tmp.path().join("foreign");
        fs::create_dir_all(foreign.join("cli/.venv/bin")).unwrap();
        fs::write(foreign.join("cli/.venv/bin/python3"), "").unwrap();
        // deliberately NO cli/src/fno/__init__.py -> not a footnote checkout.
        assert_eq!(footnote_venv(&foreign), None);
        let interp = py_interpreter(&foreign);
        assert!(
            !interp.starts_with(foreign.to_str().unwrap()),
            "must not pick the foreign venv, got {interp}"
        );
    }

    // ── x-dbaf run_summary ──────────────────────────────────────────────────

    #[test]
    fn count_run_tasks_correlates_on_run_and_flags_failures() {
        let tmp = tempfile::tempdir().unwrap();
        let events = tmp.path().join("events.jsonl");
        fs::write(
            &events,
            "{\"type\":\"task_started\",\"run\":\"R1\",\"data\":{}}\n\
             {\"type\":\"task_started\",\"run\":\"R1\",\"data\":{}}\n\
             {\"type\":\"task_done\",\"run\":\"R1\",\"outcome\":\"SUCCESS\",\"data\":{}}\n\
             {\"type\":\"task_done\",\"run\":\"R1\",\"outcome\":\"FAILED\",\"data\":{}}\n\
             {\"type\":\"task_started\",\"run\":\"OTHER\",\"data\":{}}\n\
             not json\n",
        )
        .unwrap();
        // R1: 2 started, 2 done, 1 failed; the OTHER-run line and the junk line
        // are ignored.
        assert_eq!(count_run_tasks(&events, "R1"), (2, 2, 1));
    }

    #[test]
    fn emit_run_summary_writes_extended_envelope() {
        let tmp = tempfile::tempdir().unwrap();
        let events = tmp.path().join("events.jsonl");
        // pre-seed one started with no matching done -> exposes the gap (AC2-FR).
        fs::write(
            &events,
            "{\"type\":\"task_started\",\"run\":\"R9\",\"data\":{}}\n",
        )
        .unwrap();
        emit_run_summary(
            &events,
            &events,
            "R9",
            Some("prj-0001"),
            true,
            "DonePRGreen",
            None,
        );
        let content = fs::read_to_string(&events).unwrap();
        let last: Value = serde_json::from_str(content.lines().last().unwrap()).unwrap();
        assert_eq!(last["type"], "run_summary");
        assert_eq!(last["v"], 1);
        assert_eq!(last["run"], "R9");
        assert_eq!(last["node"], "prj-0001");
        assert_eq!(last["outcome"], "SUCCESS");
        assert_eq!(last["data"]["tasks_started"], 1);
        assert_eq!(last["data"]["tasks_done"], 0);
        assert_eq!(last["data"]["termination_reason"], "DonePRGreen");
    }

    #[test]
    fn emit_run_summary_non_ship_is_failed() {
        let tmp = tempfile::tempdir().unwrap();
        let events = tmp.path().join("events.jsonl");
        emit_run_summary(&events, &events, "R2", None, false, "NoProgress", None);
        let content = fs::read_to_string(&events).unwrap();
        let ev: Value = serde_json::from_str(content.lines().last().unwrap()).unwrap();
        assert_eq!(ev["outcome"], "FAILED");
        assert!(ev.get("node").is_none(), "no node -> omitted, not null");
    }
}