loopflow 0.12.0

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

use crate::child_session::{
    body_progress_age, count_recovery_attempts, observe, plan_body_recovery,
    plan_stranded_recovery, task_write_lease_from_env, BodyEvidence, BodyRecoveryPlan,
    CallerAuthority, ChildBodyOutcome, ChildCommandEffect, ChildCommandId, ChildCommandKind,
    ChildCommandSource, ChildCommandState, ChildDecisionId, ChildDirective, ChildLeaseState,
    ChildProcessGeneration, ChildRef, ChildWriteLease, StrandedPlan, DEFAULT_STALL_AFTER,
    MAX_RECOVERY_ATTEMPTS,
};
use crate::engine::config::{load_config_or_default, parse_agent};
use crate::engine::git::{
    checkout, checkout_new_branch_from, cherry_pick_range, current_branch, delete_local_branch,
    fetch, get_default_branch, is_ancestor, is_clean, merge_base, push_with_upstream, ref_exists,
    rev_parse, stash_including_untracked, stash_pop,
};
use crate::engine::naming::sanitize_for_branch;
use crate::engine::process::{
    start_lf_session_with_env, tmux_installed, tmux_live_sessions, tmux_session_exists,
    tmux_session_slug,
};
use crate::engine::worktrees::{
    create_from_placement_plan, plan_placement, PlacementStrategy, WorktreeSegment,
};
use crate::engine::{expand_flow, load_flow, ConcreteStep, InteractionPolicy};
use crate::interaction_review::{
    InteractionReview, InteractionReviewDisposition, InteractionReviewId, InteractionReviewStatus,
    InteractionReviewer,
};
use crate::ops::error::{OpsError, OpsResult};
use crate::session_context::{
    LinearIssueId, LinearIssueSnapshot, LinearProjectId, LinearProjectSnapshot, TaskLaunchReceipt,
};
use crate::store::{
    open_existing_store, open_registry_for_authority, RegistryUnavailable, SharedStore, StoreError,
};
use crate::task::actions::{
    derive_task_actions, ReviewGateState, TaskActionEvidence, TaskActionModel,
};
use crate::task::{
    AfterMerge, CiCheck, CiIncident, CiObservation, CiState, GithubObservation,
    GithubObservationResult, GithubPr, Observation, PmWritebackOperation, PmWritebackState,
    PrPhase, PrPublication, TaskEventKind, TaskLifecyclePhase, TaskPr, TaskPrId, TaskSession,
    TaskSessionId, TaskSessionStatus, TaskSessionSuccession,
};
use crate::wave::Wave;
use sha2::{Digest, Sha256};

use super::ChildReceiptUntil;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TaskWaitUntil {
    Open,
    Terminal,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TaskLaunchOptions {
    pub name: Option<String>,
    pub flow: Option<String>,
    pub stack_on: Option<String>,
    pub directive: Option<String>,
    pub headless: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct TaskControlResult {
    pub issue_id: String,
    pub session_id: String,
    pub command_id: String,
    pub directive_version: Option<u32>,
    pub state: ChildCommandState,
    pub effect: Option<ChildCommandEffect>,
    pub incorporated: bool,
    pub generation: Option<u32>,
    pub accepted_at: Option<time::OffsetDateTime>,
    pub incorporated_at: Option<time::OffsetDateTime>,
    pub error: Option<String>,
    pub observation: Observation,
}

fn task_control_result(
    issue_id: String,
    observation: Observation,
    result: super::child::ChildControlResult,
) -> TaskControlResult {
    TaskControlResult {
        issue_id,
        session_id: result.session_id,
        command_id: result.command_id,
        directive_version: result.directive_version,
        state: result.state,
        effect: result.effect,
        incorporated: result.incorporated,
        generation: result.generation,
        accepted_at: result.accepted_at,
        incorporated_at: result.incorporated_at,
        error: result.error,
        observation,
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TaskReceiptRead {
    pub receipt: TaskControlResult,
    pub timed_out: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct TaskDecisionResult {
    pub issue_id: String,
    pub session_id: String,
    pub decision_id: String,
    pub resolved: bool,
    pub choice: Option<String>,
    pub message: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct TaskSessionSnapshot {
    pub issue_id: String,
    pub issue_identifier: String,
    pub session_id: String,
    pub project_id: String,
    pub project: String,
    pub pm_snapshot_synced_at: i64,
    pub pm_writeback: crate::task::PmWritebackState,
    pub wave: String,
    pub project_session_id: String,
    /// The live Project Session this Task routes to: the historical owner when
    /// it is still live, or its non-terminal successor. `None` when the recorded
    /// Project Session is terminal and no live successor exists (broken chain).
    pub routing_project_session_id: Option<String>,
    /// True when routing followed the chain to a successor — i.e. the Task's
    /// historical `project_session_id` is a terminal predecessor and a live
    /// successor now owns its observations, reviews, and reconciliation.
    pub project_route_succeeded: bool,
    /// Terminal attempt this Session recovered from, when any.
    pub predecessor_session_id: Option<String>,
    /// Live successor that recovered this terminal attempt, when any.
    pub successor_session_id: Option<String>,
    pub current_directive_version: u32,
    pub incorporated_directive_version: u32,
    pub status: TaskSessionStatus,
    pub status_reason: String,
    pub status_at: time::OffsetDateTime,
    pub worktree: String,
    pub workspace_slug: String,
    pub lifecycle: crate::task::TaskLifecyclePlan,
    pub lifecycle_phase: crate::task::TaskLifecyclePhase,
    pub phase_epoch: u32,
    pub phase_cursor: u32,
    pub phase_iteration: u32,
    pub gate_cycle: u32,
    pub gate_proposal: Option<crate::task::TaskGateProposal>,
    pub prs: Vec<TaskPr>,
    pub active_pr: Option<TaskPrId>,
    pub agent: String,
    pub provider: String,
    pub provider_session_id: Option<String>,
    pub process_alive: bool,
    pub latest_process: Option<ChildProcessGeneration>,
    pub latest_event: Option<crate::task::TaskEvent>,
    pub created_at: time::OffsetDateTime,
    pub updated_at: time::OffsetDateTime,
    /// Freshness of the PR state against GitHub as of this read. `Degraded`
    /// means a bounded remote read failed and the PR fields are cached, not
    /// freshly confirmed.
    pub observation: Observation,
    pub actions: TaskActionModel,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct TaskChangedFile {
    pub path: String,
    pub committed: bool,
    pub staged: bool,
    pub unstaged: bool,
    pub untracked: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct TaskChangesSnapshot {
    pub issue_identifier: String,
    pub session_id: String,
    pub base_commit: String,
    pub head_commit: String,
    pub files: Vec<TaskChangedFile>,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct TaskDiffSnapshot {
    pub issue_identifier: String,
    pub session_id: String,
    pub path: Option<String>,
    pub patch: String,
    pub binary: bool,
    pub truncated: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct TaskFileSnapshot {
    pub issue_identifier: String,
    pub session_id: String,
    pub path: String,
    pub content: Option<String>,
    pub binary: bool,
    pub size_bytes: u64,
    pub truncated: bool,
}

#[derive(Debug, Clone, Copy)]
struct TaskWorkspace<'a> {
    issue_identifier: &'a str,
    session_id: &'a crate::task::TaskSessionId,
    worktree: &'a Path,
    base_commit: &'a str,
}

impl<'a> TaskWorkspace<'a> {
    fn new(session: &'a TaskSession, pr: &'a TaskPr) -> Self {
        Self {
            issue_identifier: &session.launch.issue.identifier,
            session_id: &session.id,
            worktree: &session.worktree,
            base_commit: &pr.base_commit,
        }
    }
}

fn active_pr(session: &TaskSession) -> OpsResult<TaskPr> {
    let session_id = session.id.clone();
    block_on_task(async move {
        task_store()
            .await?
            .active_task_pr(&session_id)
            .await
            .map_err(|error| task_error(format!("failed to read active PR: {error}")))?
            .ok_or_else(|| task_error("Task Session has no active PR"))
    })
}

fn task_error(message: impl Into<String>) -> OpsError {
    OpsError::Message(message.into())
}

fn block_on_task<T>(future: impl std::future::Future<Output = OpsResult<T>>) -> OpsResult<T> {
    tokio::runtime::Runtime::new()
        .map_err(|error| task_error(format!("failed to build task runtime: {error}")))?
        .block_on(future)
}

async fn task_store() -> OpsResult<SharedStore> {
    open_existing_store().await.map(Arc::new).ok_or_else(|| {
        task_error("no Loopflow registry on this machine; start the owning Wave first")
    })
}

/// Durable placement for a Task PR forked from another Task's active PR.
#[derive(Debug, Clone)]
pub struct StackedRebase {
    pub fork_base: String,
    pub child: TaskPr,
    /// The live parent branch, or `None` once the parent has merged.
    pub parent_branch: Option<String>,
}

/// Resolve a Task's current cross-Task stack from durable ids, consulting
/// GitHub because an out-of-band parent merge can precede registry reconcile.
/// A worktree that is not a Task worktree yields `None`; a Task worktree whose
/// registry is missing/inaccessible/incompatible is refused with an actionable
/// authority error, so a stacked rebase never silently degrades to generic.
pub fn task_stack(worktree: &Path) -> OpsResult<Option<StackedRebase>> {
    block_on_task(async move {
        let TaskAuthority::Authority { store, session, .. } =
            resolve_task_authority(worktree).await?
        else {
            return Ok(None);
        };
        let Some(active) = store
            .active_task_pr(&session.id)
            .await
            .map_err(|error| task_error(error.to_string()))?
        else {
            return Ok(None);
        };
        let Some(parent_id) = active.parent_pr_id.clone() else {
            return Ok(None);
        };
        let parent = store
            .get_task_pr(&parent_id)
            .await
            .map_err(|error| task_error(error.to_string()))?
            .ok_or_else(|| task_error(format!("stack parent {parent_id} is missing")))?;
        let mut parent_session = store
            .get_task_session(&parent.task_session_id)
            .await
            .map_err(|error| task_error(error.to_string()))?
            .ok_or_else(|| task_error("stack parent Task Session is missing"))?;
        // Reuse the parent's persisted PR number and observation cache. Stack
        // resolution used to enumerate every PR on the branch independently,
        // bypassing both the Task cache and outage-tolerant reconcile.
        reconcile_task_pr(&store, &mut parent_session).await?;
        let parent = store
            .get_task_pr(&parent_id)
            .await
            .map_err(|error| task_error(error.to_string()))?
            .ok_or_else(|| task_error(format!("stack parent {parent_id} disappeared")))?;
        let merged = parent.merge_commit.is_some();
        let closed = parent.abandoned_at.is_some();
        if closed && !merged {
            return Err(task_error(format!(
                "stack parent {} closed without merging; re-place the child deliberately",
                parent.branch
            )));
        }
        Ok(Some(StackedRebase {
            fork_base: active.base_commit.clone(),
            child: active,
            parent_branch: (!merged).then_some(parent.branch),
        }))
    })
}

/// Return a stacked child only after its parent has merged. Landing before that
/// would silently drop a dependency that is not present on the default branch.
pub fn stacked_collapse(worktree: &Path) -> OpsResult<Option<StackedRebase>> {
    let stacked = task_stack(worktree)?;
    if let Some(stacked) = &stacked {
        if let Some(parent) = &stacked.parent_branch {
            return Err(task_error(format!(
                "Task PR is stacked on {parent}, which has not merged; land the parent first"
            )));
        }
    }
    Ok(stacked)
}

/// Persist the exact base reached by a successful deterministic rebase. Clear
/// the parent link only when its work is now present on the default branch.
/// Refuses with an actionable authority error if the registry is not usable, so
/// a post-rebase base is never silently dropped — the rebase already pushed, so
/// the operator must know the durable record did not advance with it.
pub fn record_stack_rebase(
    stacked: &StackedRebase,
    new_base: &str,
    clear_parent: bool,
) -> OpsResult<()> {
    let pr_id = stacked.child.id.clone();
    let new_base = new_base.to_string();
    block_on_task(async move {
        let store = Arc::new(
            open_registry_for_authority()
                .await
                .map_err(registry_authority_error)?,
        );
        // The immutable event log preserves the audit trail — the child's
        // `PrStarted` (parent base) and the parent's `PrMerged` remain — so the
        // collapse only repoints the mutable row to the post-merge truth.
        store
            .rebase_task_pr(
                &pr_id,
                &new_base,
                clear_parent,
                time::OffsetDateTime::now_utc(),
            )
            .await
            .map_err(|error| task_error(error.to_string()))?;
        Ok(())
    })
}

async fn owning_wave(store: &SharedStore, session: &TaskSession) -> OpsResult<Wave> {
    store
        .get_wave(&session.wave_id)
        .await
        .map_err(|error| task_error(format!("failed to read owning Wave: {error}")))?
        .ok_or_else(|| task_error(format!("owning Wave {} is not registered", session.wave_id)))
}

async fn validate_task_caller_authority(
    store: &SharedStore,
    session: &TaskSession,
    authority: &CallerAuthority,
) -> OpsResult<ChildCommandSource> {
    let subject = format!("Task {}", session.launch.issue.identifier);
    let target = crate::child_session::ChildRef::Task(session.id.clone());
    // A Project caller is validated against the *live* routing target, not the
    // historical `project_session_id` (W2-243 routes supervision to a live
    // successor). Resolve the route only when a Project caller is actually
    // present: a Wave or operator command must not fail merely because the
    // parent Project chain is dead.
    let route_current = if matches!(authority, CallerAuthority::Project(_)) {
        Some(
            super::project::resolve_task_project_route(store.as_ref(), session)
                .await?
                .current,
        )
    } else {
        None
    };
    super::util::validate_caller_authority(
        store,
        &session.wave_id,
        &target,
        route_current.as_ref(),
        &subject,
        authority,
    )
    .await
}

fn _defer_task_interactions(session: &mut TaskSession) -> OpsResult<bool> {
    if session.lifecycle.all_interactions_deferred() {
        return Ok(false);
    }
    if session.status.is_terminal() {
        return Err(task_error(format!(
            "Task {} is {}; terminal Tasks cannot change interaction policy",
            session.launch.issue.identifier,
            session.status.as_str()
        )));
    }
    if session.status.is_process_active() {
        return Err(task_error(format!(
            "Task {} has an active body; interrupt or wait for it before marking the Task headless",
            session.launch.issue.identifier
        )));
    }
    session.lifecycle.defer_all_interactions();
    session.updated_at = time::OffsetDateTime::now_utc();
    Ok(true)
}

fn _refuse_current_human_review(
    session: &TaskSession,
    review: Option<&InteractionReview>,
) -> OpsResult<()> {
    if let Some(review) = review.filter(|review| {
        review.reviewer == InteractionReviewer::Human && !review.status.is_terminal()
    }) {
        return Err(task_error(format!(
            "Task {} is awaiting human interaction review {}; no interaction policy was changed",
            session.launch.issue.identifier, review.id
        )));
    }
    Ok(())
}

pub fn task_run(
    repo: &Path,
    issue: &str,
    authority: CallerAuthority,
    options: TaskLaunchOptions,
) -> OpsResult<TaskSession> {
    let TaskLaunchOptions {
        name,
        flow,
        stack_on,
        directive,
        headless,
    } = options;
    let directive = directive
        .map(|directive| {
            let directive = directive.trim().to_string();
            if directive.is_empty() {
                Err(task_error("directive cannot be empty"))
            } else {
                Ok(directive)
            }
        })
        .transpose()?;
    let (existing, terminal_predecessor_id) = block_on_task(async {
        let store = task_store().await?;
        let mut existing = store
            .get_task_session_by_issue(issue)
            .await
            .map_err(|error| task_error(format!("failed to read task registry: {error}")))?;
        if let Some(session) = &mut existing {
            if session.status.is_terminal() {
                // A terminal Task Session leaves its direction to a successor
                // created below; do not return its status here. The placement
                // path re-resolves the issue, derives a distinct worktree slug
                // from this predecessor's id, and carries the cursor and comment
                // ledger onto the new Session.
                let predecessor_id = session.id.clone();
                return Ok((None, Some(predecessor_id)));
            }
            if let Some(requested) = name.as_deref() {
                let requested = parse_workspace_slug(requested)?;
                if requested.as_str() != session.workspace_slug {
                    return Err(task_error(format!(
                        "Task {} already uses workspace name {:?}",
                        session.launch.issue.identifier, session.workspace_slug
                    )));
                }
            }
            if let Some(requested) = flow.as_deref() {
                let requested = resolve_task_flow(&session.worktree, Some(requested))?;
                if requested != session.lifecycle.iterate.flow {
                    return Err(task_error(format!(
                        "Task {} already uses flow {:?}",
                        session.launch.issue.identifier, session.lifecycle.iterate.flow
                    )));
                }
            }
            if let Some(requested) = stack_on.as_deref() {
                let active = store
                    .active_task_pr(&session.id)
                    .await
                    .map_err(|error| task_error(error.to_string()))?
                    .ok_or_else(|| task_error("existing Task has no active PR"))?;
                let parent_id = active.parent_pr_id.as_ref().ok_or_else(|| {
                    task_error(format!(
                        "Task {} is rooted on main, not stacked on {requested}",
                        session.launch.issue.identifier
                    ))
                })?;
                let parent = store
                    .get_task_pr(parent_id)
                    .await
                    .map_err(|error| task_error(error.to_string()))?
                    .ok_or_else(|| task_error(format!("stack parent {parent_id} is missing")))?;
                let parent_session = store
                    .get_task_session(&parent.task_session_id)
                    .await
                    .map_err(|error| task_error(error.to_string()))?
                    .ok_or_else(|| task_error("stack parent Task Session is missing"))?;
                if requested != parent_session.launch.issue.identifier
                    && requested != parent_session.launch.issue.id.as_str()
                {
                    return Err(task_error(format!(
                        "Task {} is stacked on {}, not {requested}",
                        session.launch.issue.identifier, parent_session.launch.issue.identifier
                    )));
                }
            }
            if let Some(requested) = directive.as_deref() {
                let current = store
                    .child_directives(&ChildRef::Task(session.id.clone()))
                    .await
                    .map_err(|error| task_error(error.to_string()))?
                    .into_iter()
                    .find(|value| value.version == session.current_directive_version)
                    .ok_or_else(|| task_error("Task Session has no current directive"))?;
                if current.text != requested {
                    return Err(task_error(format!(
                        "Task {} already exists with directive v{}; use `lf task steer {} <new-direction>` to replace it",
                        session.launch.issue.identifier,
                        current.version,
                        session.launch.issue.identifier,
                    )));
                }
            }
            if headless && !session.lifecycle.all_interactions_deferred() {
                let review = store
                    .interaction_review_at(
                        &session.id,
                        session.phase_epoch,
                        session.phase_iteration,
                        session.phase_cursor,
                    )
                    .await
                    .map_err(|error| task_error(error.to_string()))?;
                _refuse_current_human_review(session, review.as_ref())?;
            }
            if headless && _defer_task_interactions(session)? {
                store
                    .update_task_session(session)
                    .await
                    .map_err(|error| task_error(error.to_string()))?;
            }
        }
        Ok((existing, None))
    })?;
    if let Some(existing) = existing {
        return task_status(existing.launch.issue.id.as_str());
    }
    let main_repo = crate::ops::project::ensure_clean_main(repo, "Task start")
        .map_err(|error| task_error(error.to_string()))?;
    let resolved_flow = resolve_task_flow(&main_repo, flow.as_deref())?;
    let resolved =
        crate::ops::task_pm::resolve_task(&main_repo, issue, crate::ops::pm::PmRefresh::Auto)?;
    let segment = match name.as_deref() {
        Some(name) => parse_workspace_slug(name)?,
        None => match &terminal_predecessor_id {
            // A terminal predecessor may still occupy its worktree and branch on
            // disk (e.g. after `lf task complete`), so the successor places a
            // fresh worktree under a slug derived from the predecessor's id.
            Some(predecessor_id) => succession_workspace_slug(&resolved.item.name, predecessor_id)?,
            None => derive_workspace_slug(&resolved.item.name)?,
        },
    };
    let workspace_slug = segment.as_str().to_string();
    let mut plan = plan_placement(&main_repo, segment)
        .map_err(|error| task_error(format!("failed to plan task worktree: {error}")))?;
    if plan.strategy != PlacementStrategy::Create {
        return Err(task_error(format!(
            "task worktree or branch already exists without a Task Session: {} ({})",
            plan.worktree_path.display(),
            plan.branch
        )));
    }
    let default_branch =
        get_default_branch(&main_repo).map_err(|error| task_error(error.to_string()))?;
    let stack_parent = stack_on
        .as_deref()
        .map(|parent_issue| {
            block_on_task(async {
                let store = task_store().await?;
                let parent_session = store
                    .get_task_session_by_issue(parent_issue)
                    .await
                    .map_err(|error| task_error(format!("failed to read parent Task: {error}")))?
                    .ok_or_else(|| {
                        task_error(format!(
                            "stack parent {parent_issue:?} has no Task Session; run it first"
                        ))
                    })?;
                if parent_session.launch.issue.id.as_str() == resolved.item.id {
                    return Err(task_error("a Task cannot stack on itself"));
                }
                let parent = store
                    .active_task_pr(&parent_session.id)
                    .await
                    .map_err(|error| task_error(format!("failed to read parent PR: {error}")))?
                    .ok_or_else(|| task_error("stack parent has no active PR"))?;
                if parent.github().is_none() {
                    return Err(task_error(format!(
                        "open the parent PR from {} before stacking work on it",
                        parent_session.worktree.display()
                    )));
                }
                Ok(parent)
            })
        })
        .transpose()?;
    let (base_ref, base_commit) = match &stack_parent {
        Some(parent) => {
            fetch(&main_repo, "origin", &parent.branch).map_err(|error| {
                task_error(format!(
                    "failed to fetch parent branch {}: {error}",
                    parent.branch
                ))
            })?;
            let base_ref = format!("origin/{}", parent.branch);
            let base_commit = rev_parse(&main_repo, &base_ref).map_err(|error| {
                task_error(format!("failed to resolve task base {base_ref}: {error}"))
            })?;
            (base_ref, base_commit)
        }
        None => {
            let (base_ref, base_commit) = resolve_upstream_base(&main_repo, &default_branch)?;
            if base_ref.starts_with("origin/") {
                // Placement anchors on fetched origin; stop before contaminating
                // a new worktree with an ahead-of-upstream canonical main.
                refuse_if_canonical_ahead(&main_repo, &default_branch)?;
            }
            (base_ref, base_commit)
        }
    };
    plan.base_ref = base_ref.clone();
    let project_session = crate::ops::project::ensure_project_session_for_task(
        &main_repo,
        crate::ops::task_pm::ResolvedProject {
            snapshot: resolved.snapshot.clone(),
            project: resolved.project.clone(),
        },
        &authority,
    )?;
    let project_session_id = task_project_session_id(&project_session)?;
    let wave_id = project_session.wave_id.clone();
    let config = load_config_or_default(Some(&main_repo));
    let agent = config.agent.as_deref().unwrap_or("claude:opus");
    let (provider, _) = parse_agent(agent);
    let agent = agent.to_string();
    let directive = directive.unwrap_or_else(|| {
        format!(
            "Complete {}: {}\n\n{}",
            resolved.item.identifier, resolved.item.name, resolved.item.description
        )
    });

    block_on_task(async move {
        let store = task_store().await?;
        // Re-resolve after worktree planning: a concurrent run may have created
        // a Session in the gap. A non-terminal Session wins — return it. A
        // terminal one is the predecessor whose direction the successor carries;
        // None means this is the first Session for the issue.
        let predecessor = match store
            .get_task_session_by_issue(&resolved.item.id)
            .await
            .map_err(|error| task_error(format!("failed to read task registry: {error}")))?
        {
            Some(existing) if !existing.status.is_terminal() => return Ok(existing),
            Some(terminal) => Some(terminal),
            None => None,
        };
        let now = time::OffsetDateTime::now_utc();
        let mut session = TaskSession {
            id: crate::task::TaskSessionId::new(),
            launch: TaskLaunchReceipt {
                issue: LinearIssueSnapshot {
                    id: LinearIssueId::new(resolved.item.id.clone())
                        .map_err(|error| task_error(error.to_string()))?,
                    identifier: resolved.item.identifier.clone(),
                    title: resolved.item.name.clone(),
                    description: resolved.item.description.clone(),
                },
                project: LinearProjectSnapshot {
                    id: LinearProjectId::new(resolved.project.id.clone())
                        .map_err(|error| task_error(error.to_string()))?,
                    slug: resolved.project.slug.clone(),
                    name: resolved.project.name.clone(),
                    prompt_context: project_context(&resolved.project),
                },
                pm_snapshot_synced_at: resolved.snapshot.synced_at,
            },
            wave_id,
            project_session_id,
            current_directive_version: 1,
            incorporated_directive_version: 0,
            pm_writeback: PmWritebackState::Current,
            status: TaskSessionStatus::Created,
            status_reason: "Linear task reserved before placement".to_string(),
            status_at: now,
            worktree: plan.worktree_path.clone(),
            workspace_slug: workspace_slug.clone(),
            lifecycle: if headless {
                crate::task::TaskLifecyclePlan::headless(resolved_flow)
            } else {
                crate::task::TaskLifecyclePlan::standard(resolved_flow)
            },
            lifecycle_phase: crate::task::TaskLifecyclePhase::Kickoff,
            phase_epoch: 1,
            phase_cursor: 0,
            phase_iteration: 0,
            gate_cycle: 0,
            gate_proposal: None,
            agent,
            provider,
            provider_session_id: None,
            latest_process: None,
            abandon_intent: None,
            created_at: now,
            updated_at: now,
            observation: crate::task::Observation::NotRequired,
        };
        let pr = TaskPr {
            id: TaskPrId::new(),
            task_session_id: session.id.clone(),
            sequence: 1,
            slug: workspace_slug,
            branch: plan.branch.clone(),
            base_commit,
            parent_pr_id: stack_parent.as_ref().map(|parent| parent.id.clone()),
            publication: None,
            merge_commit: None,
            abandoned_at: None,
            ci_observation: None,
            github_observation: None,
            linear_attachment_id: None,
            linear_comment_id: None,
            linear_link_error: None,
            created_at: now,
            updated_at: now,
        };

        let initial = ChildDirective::initial(
            ChildRef::Task(session.id.clone()),
            directive,
            validate_task_caller_authority(&store, &session, &authority).await?,
        );
        let succession = if let Some(predecessor) = &predecessor {
            store
                .reserve_task_session_successor(predecessor, &session, &pr, &initial)
                .await
                .map_err(|error| task_error(format!("failed to reserve task successor: {error}")))?
        } else {
            match store
                .reserve_task_session_with_directive(&session, &pr, &initial)
                .await
            {
                Ok(()) => TaskSessionSuccession {
                    session: session.clone(),
                    created: true,
                },
                Err(StoreError::Sqlite(_)) => {
                    if let Some(existing) = store
                        .get_task_session_by_issue(&resolved.item.id)
                        .await
                        .map_err(|error| {
                            task_error(format!("failed to recover task reservation: {error}"))
                        })?
                    {
                        if !existing.status.is_terminal() {
                            return Ok(existing);
                        }
                    }
                    return Err(task_error(
                        "task reservation collided with another task placement",
                    ));
                }
                Err(error) => return Err(task_error(format!("failed to reserve task: {error}"))),
            }
        };
        if !succession.created {
            // A concurrent or retried run already created the non-terminal
            // successor; its status is the answer.
            return Ok(succession.session);
        }

        store
            .append_task_event(
                &session.id,
                &TaskEventKind::PrStarted {
                    pr_id: pr.id,
                    sequence: pr.sequence,
                    branch: pr.branch,
                    base_commit: pr.base_commit,
                },
            )
            .await
            .map_err(|error| task_error(error.to_string()))?;

        store
            .append_task_event(
                &session.id,
                &TaskEventKind::DirectiveChanged {
                    directive_id: initial.id,
                    version: initial.version,
                    directive_kind: initial.kind,
                },
            )
            .await
            .map_err(|error| task_error(error.to_string()))?;

        if let Err(error) = create_from_placement_plan(&main_repo, &plan) {
            record_task_failure(
                &store,
                &mut session,
                format!("worktree creation failed: {error}"),
                error.to_string(),
            )
            .await?;
            return Err(task_error(format!(
                "failed to create task worktree: {error}"
            )));
        }

        launch_task_process(&store, &mut session).await?;
        wait_until_running(&store, &session.id).await
    })
}

fn task_project_session_id(
    project: &crate::project_session::ProjectSession,
) -> OpsResult<crate::project_session::ProjectSessionId> {
    match std::env::var("LF_PROJECT_SESSION_ID") {
        Ok(value) => {
            let session_id =
                crate::project_session::ProjectSessionId::parse(&value).map_err(|error| {
                    task_error(format!("invalid ambient Project Session id: {error}"))
                })?;
            if session_id != project.id {
                return Err(task_error(format!(
                    "Project Session {session_id} cannot supervise a Task under Project Session {}",
                    project.id
                )));
            }
            Ok(session_id)
        }
        Err(std::env::VarError::NotPresent) => Ok(project.id.clone()),
        Err(std::env::VarError::NotUnicode(_)) => {
            Err(task_error("ambient Project Session id is not valid UTF-8"))
        }
    }
}

pub(crate) fn project_context(project: &crate::pm::PmProject) -> String {
    let mut context = format!("Definition:\n{}", project.definition.trim());
    if !project.krs.is_empty() {
        context.push_str("\n\nKRs:");
        for kr in &project.krs {
            let mark = if kr.holds { "x" } else { " " };
            context.push_str(&format!("\n- [{mark}] {}", kr.text));
        }
    }
    context
}

pub fn task_start(
    repo: &Path,
    title: String,
    project_id: &str,
    authority: CallerAuthority,
    options: TaskLaunchOptions,
) -> OpsResult<TaskSession> {
    let main = crate::ops::project::ensure_clean_main(repo, "Task start")
        .map_err(|error| task_error(error.to_string()))?;
    let project =
        crate::ops::task_pm::resolve_project(&main, project_id, crate::ops::pm::PmRefresh::Auto)?;
    crate::ops::project::require_registered_wave(&project.snapshot.wave)
        .map_err(|error| task_error(error.to_string()))?;
    let marker = format!(
        "<!-- loopflow-task-start:{} -->",
        hex::encode(Sha256::digest(
            format!("{}\0{}", project.project.id, title).as_bytes()
        ))
    );
    let created = crate::ops::task_pm::create_and_load_task(
        &main,
        &project.snapshot.wave,
        &project.project.slug,
        &title,
        &marker,
    )?;
    task_run(&main, &created.item.id, authority, options)
}

fn resolve_task_flow(repo: &Path, requested: Option<&str>) -> OpsResult<String> {
    let requested = requested.unwrap_or("task");
    let definition = load_flow(requested, repo)
        .map_err(|error| task_error(format!("failed to load Task flow {requested:?}: {error}")))?;
    let steps = expand_flow(&definition, repo).map_err(|error| {
        task_error(format!("failed to expand Task flow {requested:?}: {error}"))
    })?;
    if steps.is_empty() {
        return Err(task_error(format!("Task flow {requested:?} has no steps")));
    }
    if let Some(step) = steps
        .iter()
        .find(|step| !matches!(step, ConcreteStep::Skill(_)))
    {
        return Err(task_error(format!(
            "Task flow {requested:?} contains {step:?}; durable Task flows currently require skills"
        )));
    }
    Ok(definition.name)
}

fn parse_workspace_slug(value: &str) -> OpsResult<WorktreeSegment> {
    let value = value.trim();
    let words = value.split('-').filter(|word| !word.is_empty()).count();
    if sanitize_for_branch(value) != value
        || value.contains(['.', '_', '/'])
        || !(2..=5).contains(&words)
    {
        return Err(task_error(
            "workspace name must be 2-5 lowercase kebab-case words",
        ));
    }
    WorktreeSegment::parse(value).map_err(|error| task_error(error.to_string()))
}

fn derive_workspace_slug(title: &str) -> OpsResult<WorktreeSegment> {
    derive_workspace_slug_with_cap(title, 5)
}

/// Derive a workspace slug, keeping the kebab-word count at or below `max_words`
/// so a caller that appends a suffix word still fits the 2-5 word limit.
fn derive_workspace_slug_with_cap(title: &str, max_words: usize) -> OpsResult<WorktreeSegment> {
    let sanitized = sanitize_for_branch(title);
    let mut words = sanitized
        .split('-')
        .filter(|word| !word.is_empty())
        .take(max_words)
        .collect::<Vec<_>>();
    if words.len() == 1 {
        words.push("task");
    }
    parse_workspace_slug(&words.join("-"))
}

/// A successor's worktree and branch must differ from its terminal
/// predecessor's, which may still occupy its checkout and branch on disk (for
/// example after `lf task complete`). Append a short, per-predecessor suffix
/// derived from the predecessor's id so the successor places a fresh worktree
/// without colliding. The base is capped at four words so the suffix word keeps
/// the segment within the 2-5 word limit.
fn succession_workspace_slug(
    title: &str,
    predecessor_id: &TaskSessionId,
) -> OpsResult<WorktreeSegment> {
    let base = derive_workspace_slug_with_cap(title, 4)?;
    let id = predecessor_id.as_str();
    let tail = &id[id.len().saturating_sub(8)..];
    parse_workspace_slug(&format!("{}-s{}", base.as_str(), tail))
}

fn parse_pr_slug(value: &str) -> OpsResult<String> {
    let value = value.trim();
    let words = value.split('-').filter(|word| !word.is_empty()).count();
    if sanitize_for_branch(value) != value
        || value.contains(['.', '_', '/'])
        || !(1..=5).contains(&words)
    {
        return Err(task_error(
            "next PR name must be 1-5 lowercase kebab-case words",
        ));
    }
    Ok(value.to_string())
}

async fn update_task_pr_with_authority(
    store: &SharedStore,
    pr: &TaskPr,
    lease: Option<&ChildWriteLease>,
) -> Result<(), StoreError> {
    match lease {
        Some(lease) => store.update_task_pr_for_lease(pr, lease).await,
        None => store.update_task_pr(pr).await,
    }
}

async fn settle_task_pr_with_authority(
    store: &SharedStore,
    settled: &TaskPr,
    next: Option<&TaskPr>,
    lease: Option<&ChildWriteLease>,
) -> Result<(), StoreError> {
    match lease {
        Some(lease) => store.settle_task_pr_for_lease(settled, next, lease).await,
        None => store.settle_task_pr(settled, next).await,
    }
}

async fn append_task_event_with_authority(
    store: &SharedStore,
    session_id: &crate::task::TaskSessionId,
    event: &TaskEventKind,
    lease: Option<&ChildWriteLease>,
) -> Result<(), StoreError> {
    match lease {
        Some(lease) => {
            store
                .append_task_event_for_lease(session_id, lease, event)
                .await?;
        }
        None => {
            store.append_task_event(session_id, event).await?;
        }
    }
    Ok(())
}

async fn update_task_session_with_authority(
    store: &SharedStore,
    session: &TaskSession,
    lease: Option<&ChildWriteLease>,
) -> Result<(), StoreError> {
    match lease {
        Some(lease) => store.update_task_session_for_lease(session, lease).await,
        None => store.update_task_session(session).await,
    }
}

async fn complete_task_session_after_pr_with_authority(
    store: &SharedStore,
    session: &TaskSession,
    pr: &TaskPr,
    lease: Option<&ChildWriteLease>,
) -> Result<(), StoreError> {
    match lease {
        Some(lease) => {
            store
                .complete_task_session_after_pr_for_lease(session, pr, lease)
                .await
        }
        None => store.complete_task_session_after_pr(session, pr).await,
    }
}

async fn complete_task_session_with_authority(
    store: &SharedStore,
    session: &TaskSession,
    skipped_pr: Option<&TaskPr>,
    lease: Option<&ChildWriteLease>,
) -> Result<(), StoreError> {
    match lease {
        Some(lease) => {
            store
                .complete_task_session_for_lease(session, skipped_pr, lease)
                .await
        }
        None => store.complete_task_session(session, skipped_pr).await,
    }
}

fn ambient_task_write_lease(session: &TaskSession) -> OpsResult<Option<ChildWriteLease>> {
    let Some(value) = std::env::var_os("LF_TASK_SESSION_ID") else {
        return Ok(None);
    };
    let value = value
        .into_string()
        .map_err(|_| task_error("ambient Task Session id is not valid UTF-8"))?;
    let id = crate::task::TaskSessionId::parse(&value)
        .map_err(|error| task_error(format!("invalid ambient Task Session id: {error}")))?;
    if id != session.id {
        return Err(task_error(format!(
            "ambient Task Session {id} cannot mutate {}",
            session.id
        )));
    }
    task_write_lease_from_env()
        .map(Some)
        .map_err(|error| task_error(format!("ambient Task Session has no authority: {error}")))
}

async fn task_for_worktree(
    store: &SharedStore,
    repo: &Path,
) -> OpsResult<Option<(TaskSession, Option<ChildWriteLease>)>> {
    let checkout = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
    if let Some(value) = std::env::var_os("LF_TASK_SESSION_ID") {
        let value = value
            .into_string()
            .map_err(|_| task_error("ambient Task Session id is not valid UTF-8"))?;
        let id = crate::task::TaskSessionId::parse(&value)
            .map_err(|error| task_error(format!("invalid ambient Task Session id: {error}")))?;
        let session = store
            .get_task_session(&id)
            .await
            .map_err(|error| task_error(format!("failed to read ambient Task Session: {error}")))?
            .ok_or_else(|| task_error(format!("ambient Task Session {id} is not registered")))?;
        let worktree = session
            .worktree
            .canonicalize()
            .unwrap_or_else(|_| session.worktree.clone());
        if checkout != worktree {
            return Err(task_error(format!(
                "ambient Task Session {id} owns {}, not {}",
                session.worktree.display(),
                repo.display()
            )));
        }
        let lease = task_write_lease_from_env().map_err(|error| {
            task_error(format!("ambient Task Session has no authority: {error}"))
        })?;
        return Ok(Some((session, Some(lease))));
    }

    let worktree_keys: BTreeSet<String> = store
        .list_task_sessions(None)
        .await
        .map_err(|error| task_error(format!("failed to inspect Task Sessions: {error}")))?
        .into_iter()
        .filter(|session| {
            session
                .worktree
                .canonicalize()
                .unwrap_or_else(|_| session.worktree.clone())
                == checkout
        })
        .map(|session| session.worktree.display().to_string())
        .collect();
    let mut current = Vec::new();
    for worktree in worktree_keys {
        if let Some(session) = store
            .get_task_session_by_worktree(&worktree)
            .await
            .map_err(|error| task_error(format!("failed to resolve Task worktree: {error}")))?
        {
            current.push(session);
        }
    }
    if current.len() > 1 {
        return Err(task_error(format!(
            "multiple Task Sessions claim worktree {}",
            repo.display()
        )));
    }
    Ok(current.pop().map(|session| (session, None)))
}

/// Proven authority to run a Task-owned PR operation, or an explicit decision
/// that this worktree is not a Task worktree.
///
/// The PR publication, stacking, submit, and land entry points share this one
/// resolver so they cannot disagree about what counts as authority. A missing
/// or incompatible registry never collapses to [`TaskAuthority::NotATaskWorktree`]
/// silently: only a registry file that provably does not exist (no tasks have
/// ever been registered on this machine) and no ambient Task id together prove
/// "not a Task," which preserves ordinary non-Task PR flows. Everything else
/// that cannot be opened is a refusal with an actionable authority error, so a
/// Task entry point never degrades to generic PR behavior.
#[derive(Debug)]
enum TaskAuthority {
    /// This worktree is not a Task worktree. Task-specific bookkeeping is an
    /// explicit no-op; the ordinary PR flow continues unchanged.
    NotATaskWorktree,
    /// Proven authority: the registry is healthy and a Task Session owns this
    /// worktree. `lease` is present only when an ambient Task body proved it.
    /// Boxed so the `NotATaskWorktree` no-op variant stays small.
    Authority {
        store: SharedStore,
        session: Box<TaskSession>,
        lease: Option<ChildWriteLease>,
    },
}

/// Turn a [`RegistryUnavailable`] into an actionable authority error. The
/// message always names the recovery action so the operator can move.
fn registry_authority_error(err: RegistryUnavailable) -> OpsError {
    task_error(match err {
        RegistryUnavailable::MissingFile { path } => format!(
            "Task PR authority refused: the shared Loopflow registry {} is missing. \
             Start the owning Wave (it creates the registry) or run `lf doctor`.",
            path.display()
        ),
        RegistryUnavailable::Unresolved { error } => format!(
            "Task PR authority refused: the shared Loopflow registry path is not usable: {error}. \
             Fix LF_DB_PATH/LF_HOME or run `lf doctor`."
        ),
        RegistryUnavailable::Incompatible { path, error } => format!(
            "Task PR authority refused: the shared Loopflow registry {} is present but \
             inaccessible or schema-incompatible: {error}. Run `lf doctor`.",
            path.display()
        ),
    })
}

/// Resolve Task authority for a PR entry point at `repo`.
///
/// - Registry opens and a session claims this worktree → [`TaskAuthority::Authority`].
/// - Registry opens and no session claims it → [`TaskAuthority::NotATaskWorktree`].
/// - Registry file missing and no ambient Task id → [`TaskAuthority::NotATaskWorktree`]
///   (no registry means no tasks exist, so this is provably an ordinary PR).
/// - Registry missing with an ambient Task id, or present but unopenable → refuse.
async fn resolve_task_authority(repo: &Path) -> OpsResult<TaskAuthority> {
    let ambient = std::env::var_os("LF_TASK_SESSION_ID").is_some();
    let store = match open_registry_for_authority().await {
        Ok(store) => Arc::new(store),
        Err(RegistryUnavailable::MissingFile { .. }) if !ambient => {
            return Ok(TaskAuthority::NotATaskWorktree);
        }
        Err(err) => return Err(registry_authority_error(err)),
    };
    match task_for_worktree(&store, repo).await? {
        Some((session, lease)) => Ok(TaskAuthority::Authority {
            store,
            session: Box::new(session),
            lease,
        }),
        None => Ok(TaskAuthority::NotATaskWorktree),
    }
}

pub(crate) fn request_task_pr_publication(
    repo: &Path,
    after_merge: AfterMerge,
    next_slug: Option<&str>,
) -> OpsResult<bool> {
    let next_slug = next_slug.map(parse_pr_slug).transpose()?;
    if after_merge == AfterMerge::CompleteTask && next_slug.is_some() {
        return Err(task_error("--complete and --next cannot be used together"));
    }
    block_on_task(async move {
        let TaskAuthority::Authority {
            store,
            session,
            lease,
        } = resolve_task_authority(repo).await?
        else {
            return Ok(false);
        };
        let mut pr = store
            .active_task_pr(&session.id)
            .await
            .map_err(|error| task_error(format!("failed to read active PR: {error}")))?
            .ok_or_else(|| {
                task_error(format!(
                    "Task {} has no active PR",
                    session.launch.issue.identifier
                ))
            })?;
        let branch = crate::engine::git::current_branch(repo)?
            .ok_or_else(|| task_error("Task worktree is not on a branch"))?;
        if pr.branch != branch {
            return Err(task_error(format!(
                "Task {} active PR expects branch {:?}, but the worktree is on another branch",
                session.launch.issue.identifier, pr.branch
            )));
        }
        let now = time::OffsetDateTime::now_utc();
        pr.publication = Some(PrPublication {
            requested_at: pr
                .publication
                .as_ref()
                .map_or(now, |publication| publication.requested_at),
            after_merge,
            next_slug,
            github: pr.github().cloned(),
        });
        pr.updated_at = now;
        match lease.as_ref() {
            Some(lease) => store.update_task_pr_for_lease(&pr, lease).await,
            None => store.update_task_pr(&pr).await,
        }
        .map_err(|error| task_error(format!("failed to request PR publication: {error}")))?;
        Ok(true)
    })
}

/// Whether the repository has at least one configured git remote.
fn has_remote(repo: &Path) -> OpsResult<bool> {
    Ok(!git_output(repo, &["remote"])?.trim().is_empty())
}

/// Resolve `(base_ref, base_commit)` for a new Task PR. With a remote, fetch and
/// anchor on `origin/<default>`; without one, fall back explicitly to local
/// `<default>`. The `base_ref` prefix (`origin/` vs `refs/heads/`) tells callers
/// which case applied.
fn resolve_upstream_base(repo: &Path, default_branch: &str) -> OpsResult<(String, String)> {
    let base_ref = if has_remote(repo)? {
        fetch(repo, "origin", default_branch)
            .map_err(|error| task_error(format!("failed to fetch task base: {error}")))?;
        format!("origin/{default_branch}")
    } else {
        format!("refs/heads/{default_branch}")
    };
    let base_commit = rev_parse(repo, &base_ref)
        .map_err(|error| task_error(format!("failed to resolve task base {base_ref}: {error}")))?;
    Ok((base_ref, base_commit))
}

/// Refuse placement when the canonical `<default>` checkout carries commits its
/// upstream lacks. A new Task worktree cut from an ahead-of-origin main inherits
/// the unpushed commit — the control-plane violation behind W2-132/#877 and
/// W2-130/#882. Requires a prior fetch so `origin/<default>` is current.
fn refuse_if_canonical_ahead(repo: &Path, default_branch: &str) -> OpsResult<()> {
    if rev_parse(repo, &format!("refs/heads/{default_branch}")).is_err() {
        // No local default branch checked out (fresh clone / detached) — nothing
        // can be ahead.
        return Ok(());
    }
    let range = format!("origin/{default_branch}..{default_branch}");
    let ahead = git_output(repo, &["log", "--oneline", "--no-decorate", &range])?;
    let ahead = ahead.trim();
    if !ahead.is_empty() {
        return Err(task_error(format!(
            "canonical {default_branch} is ahead of origin/{default_branch}; new Task worktrees \
             would inherit these unpushed commit(s):\n{ahead}\nThis is a control-plane violation. \
             Push or reset {default_branch} to origin/{default_branch} before placing Task worktrees."
        )));
    }
    Ok(())
}

/// Prove the active Task PR's ancestry is uncontaminated before the first push.
/// A worktree that is provably not a Task worktree is an explicit no-op — plain,
/// non-Task PRs are unaffected. A Task worktree whose registry is missing,
/// inaccessible, or schema-incompatible is refused with an actionable authority
/// error before any push, so it never degrades to generic PR behavior.
///
/// This is the **ancestry-only** gate: it runs before
/// `commit_workflow`/`prepare_land` push, where work may still be uncommitted,
/// so it cannot judge emptiness. Use [`require_task_pr_range_nonempty`] after
/// the publication path commits, before any `gh pr` side effect.
///
/// Let `B` = recorded `base_commit`, `O` = upstream tip (`origin/<default>` for
/// a root PR, or the live parent's branch tip for a stacked child), `H` = HEAD,
/// and `M = merge-base(O, H)`. The parity invariant is `M == B`, which
/// guarantees GitHub's range (`M..H`) equals the recorded range (`B..H`) equals
/// `lf task changes`:
/// - `M == B` — parity holds; publish.
/// - `M` ancestor of `B` — the recorded base itself carries commits absent from
///   `O` (inherited foreign ancestry, the #877/#882 shape). Refuse before any
///   push, naming the foreign commits/files and the safe rebase.
/// - `B` ancestor of `M` — `O` advanced past a stale or squash-merged base. Safe:
///   heal `base_commit → M` so the durable evidence and `lf task changes` stay
///   truthful, then publish the minimal `M..H` range.
/// - divergent — ambiguous ancestry; refuse, naming the commits and files on
///   both sides (`M..B` and `B..M`) plus the safe rebase.
pub(crate) fn verify_task_pr_range(repo: &Path) -> OpsResult<()> {
    let repo = repo.to_path_buf();
    block_on_task(async move {
        let TaskAuthority::Authority {
            store,
            session,
            lease,
        } = resolve_task_authority(&repo).await?
        else {
            return Ok(());
        };
        verify_task_pr_range_with_authority(&store, &session, lease.as_ref(), &repo).await
    })
}

/// Prove the active Task PR's range is **authoritative and non-empty** before
/// any `gh pr create/edit/ready/merge` side effect. Runs the ancestry parity
/// proof (healing a stale base), then refuses when the tree at HEAD matches the
/// recorded base — an empty PR that must not reach GitHub. Unconditional: an
/// already-open PR reset or rebased empty is refused just like a first
/// publication. A worktree that is provably not a Task worktree is an explicit
/// no-op; a Task worktree whose registry is unusable is refused with an
/// actionable authority error rather than degrading to generic PR behavior.
pub(crate) fn require_task_pr_range_nonempty(repo: &Path) -> OpsResult<()> {
    let repo = repo.to_path_buf();
    block_on_task(async move {
        let TaskAuthority::Authority {
            store,
            session,
            lease,
        } = resolve_task_authority(&repo).await?
        else {
            return Ok(());
        };
        require_task_pr_range_nonempty_with_authority(&store, &session, lease.as_ref(), &repo).await
    })
}

/// Resolve the upstream a Task PR's ancestry should be measured against. A root
/// PR measures against `origin/<default>` (or local `<default>` without a
/// remote). A stacked child with a live parent measures against the parent's
/// branch tip — so the parent's own commits are expected ancestry, not foreign
/// contamination, and the child's range is `fork_point..HEAD` against the
/// durable parent boundary. A child whose parent merged (or was abandoned) has
/// been collapsed onto `<default>` by [`record_stack_rebase`]; it measures
/// against `origin/<default>` like a root PR.
async fn resolve_verifier_upstream(
    store: &SharedStore,
    pr: &TaskPr,
    repo: &Path,
    default_branch: &str,
) -> OpsResult<(String, String)> {
    if let Some(parent_id) = pr.parent_pr_id.as_ref() {
        let parent = store
            .get_task_pr(parent_id)
            .await
            .map_err(|error| task_error(format!("failed to read stack parent: {error}")))?
            .ok_or_else(|| task_error(format!("stack parent {parent_id} is missing")))?;
        let parent_live = parent.merge_commit.is_none() && parent.abandoned_at.is_none();
        if parent_live {
            let base_ref = if has_remote(repo)? {
                fetch(repo, "origin", &parent.branch).map_err(|error| {
                    task_error(format!("failed to fetch parent branch: {error}"))
                })?;
                format!("origin/{}", parent.branch)
            } else {
                format!("refs/heads/{}", parent.branch)
            };
            let tip = rev_parse(repo, &base_ref).map_err(|error| {
                task_error(format!(
                    "failed to resolve parent branch {base_ref}: {error}"
                ))
            })?;
            return Ok((base_ref, tip));
        }
    }
    resolve_upstream_base(repo, default_branch)
}

/// Core parity proof. Takes the store + session explicitly so it can be
/// exercised in tests without a live LF_HOME (mirrors `ensure_working_pr`).
async fn verify_task_pr_range_with_authority(
    store: &SharedStore,
    session: &TaskSession,
    lease: Option<&ChildWriteLease>,
    repo: &Path,
) -> OpsResult<()> {
    let mut pr = store
        .active_task_pr(&session.id)
        .await
        .map_err(|error| task_error(format!("failed to read active PR: {error}")))?
        .ok_or_else(|| {
            task_error(format!(
                "Task {} has no active PR",
                session.launch.issue.identifier
            ))
        })?;
    let branch =
        current_branch(repo)?.ok_or_else(|| task_error("Task worktree is not on a branch"))?;
    if pr.branch != branch {
        return Err(task_error(format!(
            "Task {} active PR expects branch {:?}, but the worktree is on {:?}",
            session.launch.issue.identifier, pr.branch, branch
        )));
    }

    let default_branch = get_default_branch(repo)?;
    let (base_ref, upstream) = resolve_verifier_upstream(store, &pr, repo, &default_branch).await?;
    let head = rev_parse(repo, "HEAD")
        .map_err(|error| task_error(format!("failed to resolve Task HEAD: {error}")))?;
    let base = pr.base_commit.clone();
    let identifier = &session.launch.issue.identifier;
    let short = |sha: &str| sha.chars().take(12).collect::<String>();

    let merge_base = crate::engine::git::merge_base(repo, &upstream, &head).map_err(|_| {
        task_error(format!(
            "Task {identifier} branch {branch:?} shares no history with {base_ref}; \
             re-cut the branch from {base_ref} before publishing"
        ))
    })?;

    if merge_base == base {
        // Parity holds: the GitHub range is exactly base_commit..HEAD.
        return Ok(());
    }

    if crate::engine::git::is_ancestor(repo, &merge_base, &base)? {
        // M < B: the recorded base carries commits not on the upstream — the
        // foreign ancestry that contaminated #877/#882. Refuse before push.
        let range = format!("{merge_base}..{base}");
        let commits = git_output(repo, &["log", "--oneline", "--no-decorate", &range])?;
        let files = git_output(repo, &["diff", "--name-only", &range])?;
        let commits = commits.trim();
        let files = files.trim();
        return Err(task_error(format!(
            "Task {identifier} PR range is contaminated: recorded base {} carries commit(s) \
             not on {base_ref}, which would leak into the PR:\n{commits}\naffecting files:\n{files}\n\
             Refused before any push. Recover with:\n  git rebase --onto {base_ref} {} {branch}",
            short(&base),
            short(&base),
        )));
    }

    if crate::engine::git::is_ancestor(repo, &base, &merge_base)? {
        // B < M: the upstream advanced past a stale or squash-merged base.
        // Heal the recorded base to the true fork point so lf task changes and
        // the durable evidence report the minimal M..HEAD range.
        pr.base_commit = merge_base.clone();
        pr.updated_at = time::OffsetDateTime::now_utc();
        match lease {
            Some(lease) => store.heal_task_pr_base_for_lease(&pr, lease).await,
            None => store.heal_task_pr_base(&pr).await,
        }
        .map_err(|error| task_error(format!("failed to heal Task PR base: {error}")))?;
        return Ok(());
    }

    // Neither is an ancestor of the other: genuinely ambiguous ancestry. Name
    // the commits and files on both sides so the user can identify exactly which
    // work is foreign without opening raw internals.
    let base_side = format!("{merge_base}..{base}");
    let upstream_side = format!("{base}..{merge_base}");
    let base_commits = git_output(repo, &["log", "--oneline", "--no-decorate", &base_side])?;
    let base_files = git_output(repo, &["diff", "--name-only", &base_side])?;
    let upstream_commits =
        git_output(repo, &["log", "--oneline", "--no-decorate", &upstream_side])?;
    let upstream_files = git_output(repo, &["diff", "--name-only", &upstream_side])?;
    Err(task_error(format!(
        "Task {identifier} PR base {} and {base_ref} have diverged with no common lineage at \
         the recorded base. Refused before any push.\n\
         Commits on the recorded base not on {base_ref}:\n{base_commits}\
         affecting files:\n{base_files}\n\
         Commits on {base_ref} not reachable from the recorded base:\n{upstream_commits}\
         affecting files:\n{upstream_files}\n\
         Recover with:\n  git rebase --onto {base_ref} {} {branch}",
        short(&base),
        short(&base),
    )))
}

/// Core authoritative non-empty proof. Runs the ancestry parity check (which
/// heals a stale base in place), then re-reads the PR and refuses when the tree
/// at HEAD matches the healed recorded base — an empty range that must not
/// reach `gh pr create/edit/ready/merge`. The emptiness check uses the
/// **recorded** `base_commit`, not a recomputed merge-base, so it stays
/// authoritative even when the upstream has advanced.
async fn require_task_pr_range_nonempty_with_authority(
    store: &SharedStore,
    session: &TaskSession,
    lease: Option<&ChildWriteLease>,
    repo: &Path,
) -> OpsResult<()> {
    verify_task_pr_range_with_authority(store, session, lease, repo).await?;
    let pr = store
        .active_task_pr(&session.id)
        .await
        .map_err(|error| task_error(format!("failed to read active PR: {error}")))?
        .ok_or_else(|| {
            task_error(format!(
                "Task {} has no active PR",
                session.launch.issue.identifier
            ))
        })?;
    let base = &pr.base_commit;
    let identifier = &session.launch.issue.identifier;
    let short = base.chars().take(12).collect::<String>();
    let head = rev_parse(repo, "HEAD")
        .map_err(|error| task_error(format!("failed to resolve Task HEAD: {error}")))?;
    if head == *base {
        return Err(task_error(format!(
            "Task {identifier} PR range is empty: HEAD is the recorded base {short}, so the PR has \
             no commits to publish. Commit the Task's work, or complete the Task directly if the \
             work is done. Refused before any GitHub side effect."
        )));
    }
    let range = format!("{base}..HEAD");
    let status = Command::new("git")
        .args(["diff", "--quiet", &range])
        .current_dir(repo)
        .status()?;
    if status.success() {
        return Err(task_error(format!(
            "Task {identifier} PR range is empty: the tree at HEAD matches the recorded base \
             {short}, so the PR has no changes to publish. Commit the Task's work, or complete the \
             Task directly if the work is done. Refused before any GitHub side effect."
        )));
    }
    Ok(())
}

pub(crate) fn attach_task_github_pr(
    repo: &Path,
    github_pr: Option<&crate::ops::pr::PrInfo>,
) -> OpsResult<bool> {
    block_on_task(async move {
        let TaskAuthority::Authority {
            store,
            session,
            lease,
        } = resolve_task_authority(repo).await?
        else {
            return Ok(false);
        };
        let mut pr = store
            .active_task_pr(&session.id)
            .await
            .map_err(|error| task_error(format!("failed to read active PR: {error}")))?
            .ok_or_else(|| {
                task_error(format!(
                    "Task {} has no active PR",
                    session.launch.issue.identifier
                ))
            })?;
        let github_pr = github_pr.ok_or_else(|| {
            task_error(format!(
                "GitHub PR for Task {} could not be read after creation or update",
                session.launch.issue.identifier
            ))
        })?;
        if github_pr.branch != pr.branch {
            return Err(task_error(format!(
                "Task {} active PR expects branch {:?}, but GitHub reported {:?}",
                session.launch.issue.identifier, pr.branch, github_pr.branch
            )));
        }
        let number = u32::try_from(github_pr.number).map_err(|_| {
            task_error(format!(
                "pull request #{} exceeds supported range",
                github_pr.number
            ))
        })?;
        let url = github_pr.url.clone();
        let opened = pr
            .github()
            .is_none_or(|github| github.number != number || github.url != url);
        let publication = pr.publication.as_mut().ok_or_else(|| {
            task_error(format!(
                "Task {} has no durable PR publication request",
                session.launch.issue.identifier
            ))
        })?;
        publication.github = Some(GithubPr {
            number,
            url: url.clone(),
            head_sha: github_pr.head_sha.clone(),
        });
        // Idempotently link the PR on its owning Linear issue. This never fails
        // the attach: a degraded writeback is recorded on the PR and retried by
        // the next publication command.
        link_pr_to_linear(&store, &session, &mut pr).await;
        pr.updated_at = time::OffsetDateTime::now_utc();
        match lease.as_ref() {
            Some(lease) => store.update_task_pr_for_lease(&pr, lease).await,
            None => store.update_task_pr(&pr).await,
        }
        .map_err(|error| task_error(format!("failed to attach GitHub PR: {error}")))?;
        if opened {
            let event = TaskEventKind::PrOpened {
                pr_id: pr.id,
                sequence: pr.sequence,
                number,
                url,
            };
            match lease.as_ref() {
                Some(lease) => {
                    store
                        .append_task_event_for_lease(&session.id, lease, &event)
                        .await
                }
                None => store.append_task_event(&session.id, &event).await,
            }
            .map_err(|error| task_error(error.to_string()))?;
        }
        Ok(true)
    })
}

pub(crate) fn abandon_task_pr(
    repo: &Path,
    force: bool,
    progress: &impl crate::ops::progress::Progress,
) -> OpsResult<bool> {
    block_on_task(async move {
        let TaskAuthority::Authority {
            store,
            session,
            lease,
        } = resolve_task_authority(repo).await?
        else {
            return Ok(false);
        };
        let mut session = session;
        let mut pr = store
            .active_task_pr(&session.id)
            .await
            .map_err(|error| task_error(format!("failed to read active PR: {error}")))?
            .ok_or_else(|| {
                task_error(format!(
                    "Task {} has no active PR to abandon",
                    session.launch.issue.identifier
                ))
            })?;
        let branch =
            current_branch(repo)?.ok_or_else(|| task_error("Task worktree is not on a branch"))?;
        if branch != pr.branch {
            return Err(task_error(format!(
                "Task {} active PR expects branch {:?}, but the worktree is on {:?}",
                session.launch.issue.identifier, pr.branch, branch
            )));
        }
        let dirty = !is_clean(repo)?;
        if dirty && !force {
            return Err(task_error("uncommitted changes; use --force"));
        }
        if let Some(lease) = lease.as_ref() {
            store
                .validate_child_write_lease(&ChildRef::Task(session.id.clone()), lease)
                .await
                .map_err(|error| task_error(format!("Task body lost write authority: {error}")))?;
        }
        if dirty {
            progress.status("Discarding uncommitted Task PR changes...");
            for args in [
                ["reset", "--hard", "HEAD"].as_slice(),
                ["clean", "-fd"].as_slice(),
            ] {
                let output = Command::new("git").args(args).current_dir(repo).output()?;
                if !output.status.success() {
                    return Err(task_error(format!(
                        "failed to discard Task PR changes with `git {}`: {}",
                        args.join(" "),
                        String::from_utf8_lossy(&output.stderr).trim()
                    )));
                }
            }
        }
        progress.status("Closing Task PR...");
        let _ = Command::new("gh")
            .args(["pr", "close", &branch])
            .current_dir(repo)
            .status();
        let now = time::OffsetDateTime::now_utc();
        pr.abandoned_at = Some(now);
        pr.updated_at = now;
        match lease.as_ref() {
            Some(lease) => store.settle_task_pr_for_lease(&pr, None, lease).await,
            None => store.settle_task_pr(&pr, None).await,
        }
        .map_err(|error| task_error(format!("failed to settle Task PR: {error}")))?;
        if !session.status.is_process_active() {
            let from = session.status;
            session.set_status(
                TaskSessionStatus::Waiting,
                format!("PR branch {branch:?} was abandoned; another PR may follow"),
            );
            store
                .update_task_session(&session)
                .await
                .map_err(|error| task_error(error.to_string()))?;
            if from != session.status {
                store
                    .append_task_event(
                        &session.id,
                        &TaskEventKind::StatusChanged {
                            from,
                            to: session.status,
                            reason: session.status_reason.clone(),
                        },
                    )
                    .await
                    .map_err(|error| task_error(error.to_string()))?;
            }
        }
        Ok(true)
    })
}

/// Record a Task Session's transition into `Failed`: set the status, persist it,
/// and append the paired `StatusChanged` + `Failed` events. Callers keep their
/// own return value; this only writes the durable failure record.
async fn record_task_failure(
    store: &SharedStore,
    session: &mut TaskSession,
    reason: impl Into<String>,
    error: String,
) -> OpsResult<()> {
    let from = session.status;
    session.set_status(TaskSessionStatus::Failed, reason);
    store
        .update_task_session(session)
        .await
        .map_err(|store_error| task_error(store_error.to_string()))?;
    store
        .append_task_event(
            &session.id,
            &TaskEventKind::StatusChanged {
                from,
                to: TaskSessionStatus::Failed,
                reason: session.status_reason.clone(),
            },
        )
        .await
        .map_err(|store_error| task_error(store_error.to_string()))?;
    store
        .append_task_event(
            &session.id,
            &TaskEventKind::Failed {
                error,
                resumable: true,
            },
        )
        .await
        .map_err(|store_error| task_error(store_error.to_string()))?;
    Ok(())
}

/// Atomically start a fresh process generation for an inactive Session.
pub(crate) async fn relaunch_inactive_process(
    store: &SharedStore,
    session: &mut TaskSession,
) -> OpsResult<()> {
    let Some(_) = ensure_working_pr(store, session).await? else {
        return Err(task_error(format!(
            "Task {} is {}; terminal Task Sessions cannot start a process",
            session.launch.issue.identifier,
            session.status.as_str()
        )));
    };
    launch_task_process(store, session).await
}

/// Clear a `revoked` lease whose body is provably gone, in place.
///
/// A no-op for every other lease state, and for a body that is present or whose
/// absence cannot be proven — there the lease keeps doing its actual job.
async fn release_dead_revoked_task_lease(
    store: &SharedStore,
    session: &mut TaskSession,
) -> OpsResult<()> {
    let Some(revoked) = session
        .latest_process
        .as_ref()
        .filter(|process| process.state == ChildLeaseState::Revoked)
        .cloned()
    else {
        return Ok(());
    };
    if let Some(finished) = super::child::release_dead_revoked_child_body(
        store,
        &ChildRef::Task(session.id.clone()),
        &revoked,
    )
    .await?
    {
        session.latest_process = Some(finished);
    }
    Ok(())
}

async fn launch_task_process(store: &SharedStore, session: &mut TaskSession) -> OpsResult<()> {
    // Resolve the current Home lf before reserving anything, ignoring any
    // LF_CONTROL_* pin a legacy body carries: we always launch through the
    // current binary, store, and home. A missing or incompatible lf fails
    // without burning a generation reservation.
    let execution = crate::engine::process::current_home_execution_context()
        .map_err(|error| task_error(format!("cannot resolve current lf binary: {error}")))?;
    let tmux_name = format!(
        "lf-task-{}-{}",
        tmux_session_slug(&session.launch.issue.identifier),
        &session.id.as_str()[3..11]
    );
    // A lease stuck at `revoked` bars every future generation — the reserve CAS
    // accepts only NULL or `finished` — and nothing else in the system ever
    // revisits it. Release it here when the body is provably gone, so a resume
    // is not permanently refused by a corpse. A body still present, or one we
    // cannot prove gone, keeps its lease and fails the reservation below with
    // the real cause.
    release_dead_revoked_task_lease(store, session).await?;
    let from = session.status;
    let mut launch = session.clone();
    // The reserved generation records no provenance: nothing has run yet. The
    // child stamps its own binary's provenance when it boots (mark_booted), so
    // the audit row describes what ran, never merely what launched it.
    let generation = launch.begin_generation(tmux_name.clone());
    let Some(lease) = store
        .reserve_task_process(&launch, from)
        .await
        .map_err(|error| task_error(format!("failed to reserve task process: {error}")))?
    else {
        let current = store
            .get_task_session(&session.id)
            .await
            .map_err(|error| task_error(format!("failed to reread task process: {error}")))?
            .ok_or_else(|| task_error("Task Session disappeared during process reservation"))?;
        if current.status.is_process_active() {
            *session = current;
            return Ok(());
        }
        if current.status.is_terminal() {
            return Err(task_error(format!(
                "task {} became {}; terminal Task Sessions cannot start a process",
                current.launch.issue.identifier,
                current.status.as_str()
            )));
        }
        // The reserve CAS pins the lease state as well as the status. Without
        // this arm a lease miss is reported as "changed from waiting to
        // waiting; retry the command" — which names the wrong thing and tells a
        // machine to retry a command that cannot ever pass.
        if let Some(process) = current.latest_process.as_ref() {
            if process.state != ChildLeaseState::Finished {
                return Err(task_error(format!(
                    "task {} holds a `{}` lease on body generation {}; a new generation \
                     cannot be reserved until that lease is released",
                    current.launch.issue.identifier,
                    process.state.as_str(),
                    process.generation
                )));
            }
        }
        return Err(task_error(format!(
            "task {} changed from {} to {} during process reservation; retry the command",
            current.launch.issue.identifier,
            from.as_str(),
            current.status.as_str()
        )));
    };
    *session = launch;

    // argv[0] and the store come from the Session, never from this process:
    // whoever queued the command does not get to choose the child's binary or
    // its database.
    let argv = vec![
        execution.lf_bin.to_string_lossy().to_string(),
        "__task".to_string(),
        session.id.to_string(),
        "--generation".to_string(),
        generation.to_string(),
    ];
    let generation_text = generation.to_string();
    let control_bin = execution.lf_bin.to_string_lossy().to_string();
    let db_path = execution.db_path.to_string_lossy().to_string();
    let lf_home = execution.lf_home.to_string_lossy().to_string();
    // Inherit the Wave's execution home so this Task's routed shipping commands
    // (`lf commit`, `lf pr open`) target the same host as its Wave.
    let wave_home = match owning_wave(store, session).await {
        Ok(wave) => crate::engine::wave_config::read_wave_home(Path::new(wave.repo()), wave.name())
            .to_string(),
        Err(_) => crate::engine::wave_config::default_local_home(&session.worktree).to_string(),
    };
    let environment = [
        (
            crate::engine::wave_context::WAVE_ID_ENV,
            session.wave_id.as_str(),
        ),
        ("LF_TASK_SESSION_ID", session.id.as_str()),
        ("LF_TASK_GENERATION", generation_text.as_str()),
        (
            crate::child_session::TASK_LEASE_TOKEN_ENV,
            lease.token.as_str(),
        ),
        (crate::store::CONTROL_BIN_ENV, control_bin.as_str()),
        (crate::store::CONTROL_DB_PATH_ENV, db_path.as_str()),
        (crate::store::CONTROL_HOME_ENV, lf_home.as_str()),
        (crate::engine::wave_home::WAVE_HOME_ENV, wave_home.as_str()),
    ];
    if let Err(error) =
        start_lf_session_with_env(&tmux_name, &session.worktree, &argv, &environment).await
    {
        session.latest_process = Some(
            super::child::revoke_and_reap_child_body(
                store,
                &ChildRef::Task(session.id.clone()),
                crate::child_session::ChildBodyOutcome::Lost {
                    reason: format!("task process launch failed: {error}"),
                },
            )
            .await?,
        );
        record_task_failure(
            store,
            session,
            format!("task process launch failed: {error}"),
            error.to_string(),
        )
        .await?;
        return Err(task_error(format!(
            "failed to launch task process: {error}"
        )));
    }
    Ok(())
}

async fn wait_until_running(
    store: &SharedStore,
    session_id: &crate::task::TaskSessionId,
) -> OpsResult<TaskSession> {
    let deadline = tokio::time::Instant::now() + super::child::CHILD_STARTUP_GRACE;
    loop {
        let session = store
            .get_task_session(session_id)
            .await
            .map_err(|error| task_error(format!("failed to observe task startup: {error}")))?
            .ok_or_else(|| task_error("task session disappeared during startup"))?;
        if session.status != TaskSessionStatus::Starting {
            return if session.status == TaskSessionStatus::Running {
                Ok(session)
            } else {
                Err(task_error(format!(
                    "task {} did not start: {}",
                    session.launch.issue.identifier, session.status_reason
                )))
            };
        }
        if tokio::time::Instant::now() >= deadline {
            return Err(task_error(format!(
                "task {} process did not report running within 10 seconds",
                session.launch.issue.identifier
            )));
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
}

pub(crate) async fn reconcile_process_liveness(
    store: &SharedStore,
    session: &mut TaskSession,
) -> OpsResult<()> {
    if session
        .latest_process
        .as_ref()
        .is_some_and(super::child::child_body_reservation_is_fresh)
    {
        return Ok(());
    }
    let alive = match session.latest_process.as_ref() {
        Some(process) => tmux_session_exists(&process.tmux_name)
            .await
            .map_err(|error| task_error(error.to_string()))?,
        None => false,
    };
    if alive {
        return Ok(());
    }
    // A dead lease is reaped regardless of Session status. A Waiting or Failed
    // Session can still carry a stale Legacy/Reserved/Active lease from a body
    // that vanished without recording a terminal outcome; an explicit resume
    // must revoke it here, or the fresh process can never reserve the slot.
    let lost_reason = "task process disappeared before recording a terminal outcome";
    if session.latest_process.as_ref().is_some_and(|process| {
        matches!(
            process.state,
            crate::child_session::ChildLeaseState::Legacy
                | crate::child_session::ChildLeaseState::Reserved
                | crate::child_session::ChildLeaseState::Active
        )
    }) {
        let outcome = super::child::lost_child_body_outcome(
            session
                .latest_process
                .as_ref()
                .expect("matched child process must still be present"),
            lost_reason,
        );
        session.latest_process = Some(
            super::child::revoke_and_reap_child_body(
                store,
                &ChildRef::Task(session.id.clone()),
                outcome,
            )
            .await?,
        );
    }
    // Only a Session whose status still claims a live process needs a terminal
    // transition here. One already Waiting or Failed keeps its status; the
    // resume that follows relaunches it against the now-reaped lease.
    if !session.status.is_process_active() {
        return Ok(());
    }
    let active = store
        .active_task_pr(&session.id)
        .await
        .map_err(|error| task_error(format!("failed to read active PR: {error}")))?;
    if active.as_ref().is_none_or(|pr| pr.phase() == PrPhase::Open) {
        // W2-144 gen 7: before settling a dead-process open-PR Task to Waiting,
        // consume a queued manual Resume. The command was queued (by
        // `lf task resume` or a queued steer) but never claimed because the
        // process died first. Relaunching lets the new generation drain and
        // honor it — one relaunch path, shared with the ci-fix wake.
        let commands = store
            .list_child_commands(&ChildRef::Task(session.id.clone()))
            .await
            .map_err(|error| task_error(format!("failed to read command queue: {error}")))?;
        let has_pending_resume = commands.iter().any(|cmd| {
            matches!(cmd.kind, ChildCommandKind::Resume { .. }) && !cmd.state.is_terminal()
        });
        if has_pending_resume {
            return relaunch_inactive_process(store, session).await;
        }
        let from = session.status;
        session.set_status(
            TaskSessionStatus::Waiting,
            match active {
                Some(pr) => format!("PR {} is open; waiting for review", pr.sequence),
                None => "the previous PR settled; another PR may follow".to_string(),
            },
        );
        store
            .update_task_session(session)
            .await
            .map_err(|error| task_error(error.to_string()))?;
        store
            .append_task_event(
                &session.id,
                &TaskEventKind::StatusChanged {
                    from,
                    to: session.status,
                    reason: session.status_reason.clone(),
                },
            )
            .await
            .map_err(|error| task_error(error.to_string()))?;
        return Ok(());
    }
    // Do not write a human instruction into a durable field and stop. This line
    // was the strand: it told a person to type `lf task resume` and nothing ever
    // read it, so 13 Sessions sat frozen until someone swept them by hand. State
    // the fact; the supervision tick's `recover_stranded_task_body` re-dispatches
    // it, and only announces a verdict a resume cannot fix.
    let reason = "task process is missing; Loopflow will recover this Task Session";
    record_task_failure(store, session, reason, reason.to_string()).await
}

/// Let one live Project body supervise the progress leases of its Task bodies.
///
/// This is deliberately parent-driven: Project and Task Sessions do not grow a
/// second watchdog process. A live Project runner calls this on its existing
/// control tick and recovers only children whose durable progress deadline has
/// passed on a machine that can still observe their tmux body.
/// How far back the recovery attempt count reads. Comfortably past the lease and
/// status churn a few consecutive recoveries write, and far short of a long
/// Task's full event log.
const RECOVERY_ATTEMPT_WINDOW: u32 = 64;

pub(crate) async fn reconcile_project_tasks(
    store: &SharedStore,
    project: &crate::project_session::ProjectSession,
) -> OpsResult<Vec<TaskSession>> {
    let project_tasks = |tasks: Vec<TaskSession>| {
        tasks
            .into_iter()
            .filter(|task| task.launch.project.id == project.launch.project.id)
            .collect::<Vec<_>>()
    };
    let mut tasks = project_tasks(
        store
            .list_task_sessions(Some(&project.wave_id))
            .await
            .map_err(|error| task_error(format!("failed to list supervised Tasks: {error}")))?,
    );
    for task in &mut tasks {
        if task.status.is_terminal() {
            continue;
        }
        if let Err(error) = task_recovery_adoption(store, task).await {
            tracing::warn!(
                task = %task.launch.issue.identifier,
                %error,
                "supervisor skipped Task recovery: unsafe worktree/branch state"
            );
            continue;
        }
        let observed = reconcile_task_pr(store, task).await?;
        refuse_dirty_between_prs(store, task).await?;
        reconcile_process_liveness(store, task).await?;
        reconcile_task_completion(store, task, None).await?;
        if task.status.is_terminal() {
            continue;
        }
        // A merged, complete Task whose final directive was applied but never
        // incorporated is reconcilable, not recoverable: its work already shipped
        // in the merged head, so only an explicit Wave/Operator attestation can
        // settle it. The supervisor must never synthesize that attestation — it
        // leaves the `Reconcile` recommendation standing rather than relaunching a
        // body, rotating a PR, or queuing a CI fix. A *durable* attestation was
        // already consumed by `reconcile_task_completion` above (which clears the
        // gate and completes the Task), so reaching here means none exists yet.
        //
        // Gate on the cheap session-local predicates first — a pending directive
        // that a body actually ran — so the common loop never pays a `task_prs`
        // query. Only that rare shape reads PR history, and only to confirm the
        // settled set is reconcilable: no non-abandoned PR still in flight and the
        // latest non-abandoned PR merged (any disposition). A later merged Review,
        // or a trailing abandoned successor, leaves the Reconcile recommendation
        // standing instead of relaunching a body — suppression never completes.
        if has_pending_directive(task) && current_directive_applied(store, task).await? {
            let task_prs = store
                .task_prs(&task.id)
                .await
                .map_err(|error| task_error(format!("failed to read Task PRs: {error}")))?;
            if reconcilable_pr_set(&task_prs) {
                continue;
            }
        }
        let no_active_pr = if observed.is_none() {
            store
                .active_task_pr(&task.id)
                .await
                .map_err(|error| task_error(format!("failed to read active PR: {error}")))?
                .is_none()
        } else {
            false
        };
        let settled = observed.as_ref().is_some_and(TaskPr::is_settled) || no_active_pr;
        let completing = observed.as_ref().is_some_and(|pr| {
            pr.is_settled()
                && pr
                    .publication
                    .as_ref()
                    .is_some_and(|publication| publication.after_merge == AfterMerge::CompleteTask)
        });
        if settled && !completing {
            ensure_working_pr(store, task).await?;
            if !task.status.is_process_active() {
                relaunch_inactive_process(store, task).await?;
            }
        } else {
            let Some(pr) = observed.as_ref() else {
                continue;
            };
            if pr.review_ready()
                && task.lifecycle_phase == crate::task::TaskLifecyclePhase::Gate
                && task.phase_cursor == 0
                && task.phase_iteration == 0
            {
                if !task.status.is_process_active() {
                    relaunch_inactive_process(store, task).await?;
                }
            } else {
                queue_ci_fix_command(store, task, pr).await?;
            }
        }
    }

    let refreshed = store
        .list_task_sessions(Some(&project.wave_id))
        .await
        .map_err(|error| task_error(format!("failed to reread supervised Tasks: {error}")))?;
    Ok(project_tasks(refreshed))
}

pub(crate) async fn supervise_project_task_bodies(
    store: &SharedStore,
    project: &crate::project_session::ProjectSession,
) -> OpsResult<usize> {
    let tasks = reconcile_project_tasks(store, project).await?;
    if !tmux_installed() {
        return Ok(0);
    }
    let live_sessions = tmux_live_sessions()
        .await
        .map_err(|error| task_error(format!("failed to observe Task bodies: {error}")))?;
    let now = time::OffsetDateTime::now_utc();
    let mut recovered = 0;
    let mine = tasks
        .into_iter()
        .filter(|task| task.project_session_id == project.id)
        .collect::<Vec<_>>();
    // A strand is a body this machine can see is gone. It is deliberately a
    // separate cohort from the stall sweep below, which only ever looks at
    // bodies that are alive: the two conditions are disjoint, and folding them
    // together would make one predicate answer two different questions.
    for mut task in mine
        .iter()
        .filter(|task| {
            task.latest_process.as_ref().is_some_and(|process| {
                !live_sessions.contains(&process.tmux_name)
                    // A reservation inside its startup grace is a relaunch in
                    // flight, not a strand.
                    && !super::child::child_body_reservation_is_fresh(process)
            })
        })
        .cloned()
    {
        match recover_stranded_task_body(store, &mut task).await {
            Ok(true) => recovered += 1,
            Ok(false) => {}
            Err(error) => {
                tracing::warn!(
                    project_session = %project.id,
                    task = %task.launch.issue.identifier,
                    error = %error,
                    "stranded Task recovery failed"
                );
            }
        }
    }
    for task in mine.into_iter().filter(|task| {
        task.status.is_process_active()
            && task.latest_process.as_ref().is_some_and(|process| {
                process.state == ChildLeaseState::Active
                    && live_sessions.contains(&process.tmux_name)
            })
    }) {
        let latest_event = store
            .latest_task_event(&task.id)
            .await
            .map_err(|error| task_error(format!("failed to read Task progress: {error}")))?;
        let observation = observe(
            &BodyEvidence {
                intent: task.status.body_intent(),
                observable: true,
                process_alive: true,
                progress_age: body_progress_age(
                    latest_event.as_ref().map(|event| event.created_at),
                    task.status_at,
                    now,
                ),
                step: Some(task.lifecycle_phase.as_str().to_string()),
                reason: task.status_reason.clone(),
            },
            DEFAULT_STALL_AFTER,
        );
        match recover_stalled_task_body(
            store,
            task,
            &observation,
            latest_event.as_ref().map(|event| event.id),
        )
        .await
        {
            Ok(true) => recovered += 1,
            Ok(false) => {}
            Err(error) => {
                tracing::warn!(
                    project_session = %project.id,
                    error = %error,
                    "Task body recovery failed"
                );
            }
        }
    }
    Ok(recovered)
}

/// Re-dispatch one Session whose body is gone while its status still claims one.
///
/// This is the strand path: the body died, and nothing but a resume was ever
/// going to bring it back. Before this existed, `reconcile_process_liveness`
/// wrote *"resume the same Task Session with `lf task resume`"* into a durable
/// field and stopped — a human instruction with no reader.
///
/// Returns whether a generation was launched.
async fn recover_stranded_task_body(
    store: &SharedStore,
    task: &mut TaskSession,
) -> OpsResult<bool> {
    // A bounded tail is enough: the count only ever walks back over the lease
    // and status churn a recovery itself writes.
    let events = store
        .recent_task_events(&task.id, RECOVERY_ATTEMPT_WINDOW)
        .await
        .map_err(|error| task_error(format!("failed to read Task recovery history: {error}")))?;
    let attempts = count_recovery_attempts(&events);
    // A lease stuck at `revoked` is not a strand recovery can plan around — the
    // reserve CAS can never accept it, so redispatch would burn the whole
    // attempt budget on a CAS that cannot pass. Release it first when the body
    // is provably gone: the verdict table then reads the finished lease and its
    // own outcome, and reaches `Redispatch` with no new plan variant. A lease
    // that cannot be released still surfaces its true cause below.
    release_dead_revoked_task_lease(store, task).await?;
    let plan = plan_stranded_recovery(
        task.status.body_intent(),
        true,
        false,
        task.latest_process.as_ref(),
        attempts,
    );
    let (attempt, reason) = match plan {
        StrandedPlan::LeaveAlone => return Ok(false),
        StrandedPlan::Surface { reason } => {
            // Say it once. A Session already parked on this verdict must not
            // re-announce it every 5s tick.
            if task.status == TaskSessionStatus::Failed && task.status_reason == reason {
                return Ok(false);
            }
            record_task_failure(store, task, reason.clone(), reason).await?;
            return Ok(false);
        }
        StrandedPlan::Redispatch { attempt } => {
            let generation = task
                .latest_process
                .as_ref()
                .map_or(0, |process| process.generation);
            (
                attempt,
                format!(
                    "body generation {generation} died without recording an outcome; \
                     recovering the same Task Session (attempt {attempt}/{MAX_RECOVERY_ATTEMPTS})"
                ),
            )
        }
    };
    // A successor commits into the worktree, so it must clear the same adoption
    // preconditions as an explicit resume. `task_recovery_adoption` owns that
    // refusal; do not second-guess it here.
    if let Err(error) = task_recovery_adoption(store, task).await {
        tracing::info!(
            task = %task.launch.issue.identifier,
            "not recovering stranded Task: {error}"
        );
        return Ok(false);
    }
    // Reap the dead lease before reserving the successor: `reserve_task_process`
    // CASes on a `finished` lease, so a strand still holding `active` can never
    // launch until this runs.
    if let Some(process) = task.latest_process.as_ref() {
        if matches!(
            process.state,
            ChildLeaseState::Legacy | ChildLeaseState::Reserved | ChildLeaseState::Active
        ) {
            let outcome = super::child::lost_child_body_outcome(process, &reason);
            task.latest_process = Some(
                super::child::revoke_and_reap_child_body(
                    store,
                    &ChildRef::Task(task.id.clone()),
                    outcome,
                )
                .await?,
            );
        }
    }
    let generation = task
        .latest_process
        .as_ref()
        .map_or(0, |process| process.generation);
    // Record the attempt before launching. A launch that fails still reaps as
    // `Lost` and fails the Session, so counting only successful launches would
    // let an unlaunchable Session retry forever.
    store
        .append_task_event(
            &task.id,
            &TaskEventKind::BodyRecoveryAttempted {
                generation,
                attempt,
                reason: reason.clone(),
            },
        )
        .await
        .map_err(|error| task_error(error.to_string()))?;
    super::child::redispatch_task_body(store, task).await?;
    tracing::info!(
        task = %task.launch.issue.identifier,
        attempt,
        "recovered a stranded Task body"
    );
    Ok(true)
}

async fn recover_stalled_task_body(
    store: &SharedStore,
    task: TaskSession,
    observation: &crate::child_session::BodyObservation,
    latest_event_id: Option<i64>,
) -> OpsResult<bool> {
    let commands = store
        .list_child_commands(&ChildRef::Task(task.id.clone()))
        .await
        .map_err(|error| task_error(format!("failed to inspect Task commands: {error}")))?;
    let generation = task
        .latest_process
        .as_ref()
        .map(|process| process.generation)
        .ok_or_else(|| task_error("stalled Task has no process generation"))?;
    let plan = plan_body_recovery(observation, &commands, generation);
    if plan == BodyRecoveryPlan::LeaveAlone {
        return Ok(false);
    }
    let active_pr = store
        .active_task_pr(&task.id)
        .await
        .map_err(|error| task_error(format!("failed to inspect Task PR: {error}")))?;
    if let Some(reason) = task.supervisor_restart_bar(active_pr.as_ref()) {
        tracing::info!(task = %task.launch.issue.identifier, "not recovering Task body: {reason}");
        return Ok(false);
    }
    let progress_age = observation.progress_age_secs.unwrap_or_default();
    let uncertain = match &plan {
        BodyRecoveryPlan::NeedsInput { commands } => Some(commands.clone()),
        BodyRecoveryPlan::Restart => None,
        BodyRecoveryPlan::LeaveAlone => unreachable!("leave-alone plan returned above"),
    };
    // A restart commits a successor body into the worktree, so it must clear the
    // same adoption preconditions as an explicit resume — refuse before the lease
    // is reaped rather than after rotation rejects the branch. An uncertain plan
    // launches nothing, so it still records the loss honestly; the explicit
    // resume that follows is where the refusal belongs.
    if uncertain.is_none() {
        if let Err(error) = task_recovery_adoption(store, &task).await {
            tracing::info!(
                task = %task.launch.issue.identifier,
                "not recovering Task body: {error}"
            );
            return Ok(false);
        }
    }
    let reason = uncertain.as_ref().map_or_else(
        || {
            format!(
                "body generation {generation} stalled after {progress_age}s without durable progress; recovering the same Task Session"
            )
        },
        |commands| {
            let commands = commands
                .iter()
                .map(ToString::to_string)
                .collect::<Vec<_>>()
                .join(", ");
            format!(
                "body generation {generation} stalled after {progress_age}s during provider delivery ({commands}); delivery outcome is uncertain, inspect the transcript and resume explicitly"
            )
        },
    );
    let outcome = if uncertain.is_some() {
        ChildBodyOutcome::Lost {
            reason: reason.clone(),
        }
    } else {
        ChildBodyOutcome::Superseded {
            reason: reason.clone(),
        }
    };
    let Some(revoked) = store
        .revoke_task_process_if_unchanged(
            &task.id,
            generation,
            task.status_at,
            latest_event_id,
            &outcome,
        )
        .await
        .map_err(|error| task_error(format!("failed to claim stalled Task body: {error}")))?
    else {
        return Ok(false);
    };
    if let Err(error) =
        super::child::reap_revoked_child_body(store, &ChildRef::Task(task.id.clone()), revoked)
            .await
    {
        let mut current = store
            .get_task_session(&task.id)
            .await
            .map_err(|store_error| task_error(store_error.to_string()))?
            .ok_or_else(|| task_error("Task Session disappeared during recovery"))?;
        // Reaching here means the reap failed *and* the body could not be proven
        // gone, since a provable absence would have released the lease. Say that,
        // rather than instructing a human who is not reading this field: the
        // lease releases itself on the next reservation once the body is
        // verifiably absent.
        let failure = format!(
            "body generation {generation} lease was revoked after a stall but its body could not \
             be reaped or proven gone: {error}; the lease stays blocked and releases itself once \
             the body is verifiably absent"
        );
        record_task_failure(store, &mut current, failure.clone(), failure).await?;
        return Err(error);
    }

    let mut current = store
        .get_task_session(&task.id)
        .await
        .map_err(|error| task_error(error.to_string()))?
        .ok_or_else(|| task_error("Task Session disappeared during recovery"))?;
    if uncertain.is_some() {
        let successor_generation = generation
            .checked_add(1)
            .ok_or_else(|| task_error("Task process generation overflow"))?;
        let changed = store
            .mark_stale_child_deliveries_uncertain(
                &ChildRef::Task(task.id.clone()),
                successor_generation,
            )
            .await
            .map_err(|error| {
                task_error(format!("failed to preserve uncertain delivery: {error}"))
            })?;
        for command in changed {
            store
                .append_task_event(
                    &task.id,
                    &TaskEventKind::CommandChanged {
                        command_id: command.id,
                        state: ChildCommandState::Uncertain,
                        effect: command.effect,
                        error: command.error,
                    },
                )
                .await
                .map_err(|error| task_error(error.to_string()))?;
        }
    }
    let from = current.status;
    current.set_status(TaskSessionStatus::Waiting, reason);
    store
        .update_task_session(&current)
        .await
        .map_err(|error| task_error(error.to_string()))?;
    store
        .append_task_event(
            &current.id,
            &TaskEventKind::StatusChanged {
                from,
                to: TaskSessionStatus::Waiting,
                reason: current.status_reason.clone(),
            },
        )
        .await
        .map_err(|error| task_error(error.to_string()))?;
    if uncertain.is_none() {
        if let Err(error) = relaunch_inactive_process(store, &mut current).await {
            let mut persisted = store
                .get_task_session(&task.id)
                .await
                .map_err(|store_error| task_error(store_error.to_string()))?
                .ok_or_else(|| task_error("Task Session disappeared during relaunch"))?;
            if persisted.status == TaskSessionStatus::Waiting {
                let failure = format!(
                    "body generation {generation} was reaped after a stall but its successor could not start: {error}"
                );
                record_task_failure(store, &mut persisted, failure.clone(), failure).await?;
            }
            return Err(error);
        }
    }
    Ok(true)
}

pub(crate) async fn reconcile_task_pr(
    store: &SharedStore,
    session: &mut TaskSession,
) -> OpsResult<Option<TaskPr>> {
    reconcile_task_pr_with_authority(
        store,
        session,
        None,
        crate::ops::pr::PrReadFreshness::Cached,
    )
    .await
}

/// Status for a Task whose PR is open, decided after a body turn completed.
///
/// Only the runner may call this: it is the sole caller that knows whether the
/// turn that just ran pushed anything. A passive reconcile has no such evidence
/// and leaves an open PR `Waiting`, so the `ci-fix` wake stays armed.
///
/// `head_advanced` is true when the PR head moved during the iteration — the
/// body pushed a fix, so the Task waits for CI to resolve even if the reading is
/// currently `Failing`. A failing head the body did *not* move is a repair that
/// did not happen: block rather than report false progress. `github_degraded`
/// carries `Observation::Degraded`'s reason and dominates — a turn that ran
/// blind to GitHub cannot be said to have repaired anything.
pub(crate) fn decide_open_pr_status(
    pr: &TaskPr,
    github_degraded: Option<&str>,
    head_advanced: bool,
) -> (TaskSessionStatus, String) {
    let number = pr
        .github()
        .expect("open Task PR requires a GitHub receipt")
        .number;
    if let Some(reason) = github_degraded {
        return (
            TaskSessionStatus::Blocked,
            format!(
                "ci-fix blocked by github-observation: {reason}. Resume when GitHub recovers; pull request #{number} stays attached."
            ),
        );
    }
    let failing = pr
        .ci_observation
        .as_ref()
        .is_some_and(|observation| observation.state == CiState::Failing);
    if failing && !head_advanced {
        return (
            TaskSessionStatus::Blocked,
            format!(
                "CI failing on pull request #{number}; the Task body did not repair the head. Needs a new directive or human review; pull request #{number} stays attached."
            ),
        );
    }
    (
        TaskSessionStatus::Waiting,
        format!("pull request #{number} is open for review"),
    )
}

/// The incident this PR's current reading warrants, if any.
///
/// The single mint point for a wake's identity. The enqueue and the arm must
/// derive it the same way or a claimed wake could never be matched to the failure
/// it names, so both call this rather than composing the parts themselves.
/// `None` when the current head is not failing a required check — including when
/// the head has moved past the reading (`fresh_ci`), which makes any wake for the
/// old head moot.
pub(crate) fn current_ci_incident(pr: &TaskPr) -> Option<CiIncident> {
    let observation = pr.fresh_ci().filter(|reading| reading.wake_legal())?;
    ci_incident(pr, observation)
}

/// Enqueue one durable `ci-fix` wake for this PR's current failed head.
///
/// Replaces the old direct `wake_task_ci_fix` launch. A no-op unless the current
/// head is failing a required check — that is the legality question, and it is
/// the only one asked here. Whether this exact failure already woke a body is the
/// ledger's question, answered by `ensure_child_ci_fix_command` on the incident
/// identity; a repeat observation lands on the existing command and mints
/// nothing. `queue_command` owns the trigger link and the launch from there, in
/// that order — the wake is attributable before anything can service it.
pub(crate) async fn queue_ci_fix_command(
    store: &SharedStore,
    session: &TaskSession,
    pr: &TaskPr,
) -> OpsResult<()> {
    let Some(kind) = ci_fix_wake_kind(pr) else {
        return Ok(());
    };
    super::child::queue_command(
        store,
        super::child::ChildSession::Task(Box::new(session.clone())),
        ChildCommandSource::System,
        kind,
    )
    .await?;
    Ok(())
}

/// The wake this PR's current reading warrants, as a command payload.
///
/// The one place a `CiFix` payload is built. `arm_ci_fix_wake` matches a claimed
/// command against `current_ci_incident`, so the identity minted here and the
/// identity matched there must come from the same derivation — two that drift
/// would match nothing and every wake would be superseded as stale.
pub(crate) fn ci_fix_wake_kind(pr: &TaskPr) -> Option<ChildCommandKind> {
    let incident = current_ci_incident(pr)?;
    let observation = pr.fresh_ci()?;
    Some(ChildCommandKind::CiFix {
        incident_identity: incident.identity,
        pr_number: incident.pr_number,
        head_sha: incident.failed_head_sha,
        // Names come from the incident; the log URLs only exist here, on the
        // observation the incident was minted from.
        failing_checks: observation.failing_checks.clone(),
    })
}

pub(crate) async fn reconcile_task_pr_for_lease(
    store: &SharedStore,
    session: &mut TaskSession,
    lease: &ChildWriteLease,
) -> OpsResult<Option<TaskPr>> {
    reconcile_task_pr_with_authority(
        store,
        session,
        Some(lease),
        crate::ops::pr::PrReadFreshness::Cached,
    )
    .await
}

/// Reconcile the PR reading GitHub live, bypassing both the store observation
/// cache and `gh`'s HTTP cache. The ci-fix settlement path uses this so it judges
/// head advancement against the authoritative remote head the repair body just
/// pushed — never a warm pre-turn observation.
pub(crate) async fn reconcile_task_pr_fresh_for_lease(
    store: &SharedStore,
    session: &mut TaskSession,
    lease: &ChildWriteLease,
) -> OpsResult<Option<TaskPr>> {
    reconcile_task_pr_with_authority(
        store,
        session,
        Some(lease),
        crate::ops::pr::PrReadFreshness::Fresh,
    )
    .await
}

/// Read the open PR's required checks and classify them for `head_sha`. Returns
/// `None` — CI state unknown, status falls back to plain review waiting — when
/// GitHub reports no head, there are no required checks, or gh is unavailable.
/// Failure dominates: any failing required check makes the head `Failing` even
/// while others are still pending.
fn observe_required_checks(
    worktree: &Path,
    branch: &str,
    head_sha: Option<&str>,
    now: time::OffsetDateTime,
) -> Option<CiObservation> {
    let head_sha = head_sha?.to_string();
    let checks = crate::ops::pr::merge_gate_state(worktree, branch)?;
    let state = if checks.failing {
        CiState::Failing
    } else if checks.pending {
        CiState::Pending
    } else {
        CiState::Passing
    };
    Some(CiObservation {
        head_sha,
        state,
        // Seed with the actionable leaf failures, never the required aggregate:
        // a ci-fix turn needs the broken job, not the roll-up.
        failing_checks: checks
            .failing_leaves
            .into_iter()
            .map(|check| CiCheck {
                name: check.name,
                url: check.url,
            })
            .collect(),
        observed_at: now,
    })
}

fn ci_incident(pr: &TaskPr, observation: &CiObservation) -> Option<CiIncident> {
    if observation.state != CiState::Failing {
        return None;
    }
    let identity = pr.pr_identity()?;
    let failure_set = observation.failure_set();
    let mut digest = Sha256::new();
    for check in &failure_set {
        digest.update(check.as_bytes());
        digest.update([0]);
    }
    Some(CiIncident {
        identity: format!(
            "github:ci:{}:{}:{}:{}",
            identity.repo,
            identity.number,
            observation.head_sha,
            hex::encode(digest.finalize())
        ),
        task_session_id: pr.task_session_id.clone(),
        pr_id: pr.id.clone(),
        repo: identity.repo,
        pr_number: identity.number,
        failed_head_sha: observation.head_sha.clone(),
        repaired_head_sha: None,
        failure_set,
        provider_completed_at: None,
        poll_observed_at: Some(observation.observed_at),
        webhook_received_at: None,
        trigger_command_id: None,
        responded_at: None,
        green_at: None,
        merged_at: None,
        blocked_at: None,
        blocked_reason: None,
        created_at: observation.observed_at,
        updated_at: observation.observed_at,
    })
}

// Local control commands often arrive in a burst (`status`, then `follow-up`,
// then another `status`). One minute keeps merge/CI state responsive while
// bounding those bursts to one GitHub read. A failed read opens a longer circuit:
// a quota or outage should not be hammered by every short-lived `lf` process.
const PR_OBSERVATION_TTL: time::Duration = time::Duration::seconds(60);
const PR_OBSERVATION_DEGRADED_BACKOFF: time::Duration = time::Duration::minutes(5);

fn cached_github_observation(pr: &TaskPr, now: time::OffsetDateTime) -> Option<Observation> {
    let observation = pr.github_observation.as_ref()?;
    let retry_at = observation.checked_at
        + match observation.result {
            GithubObservationResult::Fresh => PR_OBSERVATION_TTL,
            GithubObservationResult::Degraded { .. } => PR_OBSERVATION_DEGRADED_BACKOFF,
        };
    if retry_at <= now {
        return None;
    }
    Some(match &observation.result {
        GithubObservationResult::Fresh => Observation::Cached {
            observed_at: observation.checked_at,
        },
        GithubObservationResult::Degraded { reason } => Observation::Degraded {
            reason: reason.clone(),
            cached_as_of: pr.updated_at,
            retry_at,
        },
    })
}

/// The PR this reconcile answers for: the active row, else the newest published
/// row GitHub could still contradict.
///
/// `abandoned_at` on a published PR caches GitHub's closed state rather than
/// deciding it — `lf pr abandon` runs `gh pr close` before stamping it — so a
/// reopen must be able to clear it. A merge is terminal: GitHub cannot unmerge.
async fn reconcile_subject(
    store: &SharedStore,
    session: &TaskSession,
) -> OpsResult<Option<TaskPr>> {
    if let Some(active) = store
        .active_task_pr(&session.id)
        .await
        .map_err(|error| task_error(format!("failed to read active PR: {error}")))?
    {
        return Ok(Some(active));
    }
    let prs = store
        .task_prs(&session.id)
        .await
        .map_err(|error| task_error(format!("failed to read Task PRs: {error}")))?;
    Ok(prs
        .into_iter()
        .next_back()
        .filter(|pr| pr.phase() == PrPhase::Abandoned && pr.github().is_some()))
}

async fn reconcile_task_pr_with_authority(
    store: &SharedStore,
    session: &mut TaskSession,
    lease: Option<&ChildWriteLease>,
    freshness: crate::ops::pr::PrReadFreshness,
) -> OpsResult<Option<TaskPr>> {
    let Some(mut pr) = reconcile_subject(store, session).await? else {
        return Ok(None);
    };
    // GitHub is a reconciliation input, not the Task's store of record. Read the
    // one persisted PR by number (a single bounded REST call, never `gh pr
    // list`); an unpublished working PR has no number and is not read remotely.
    // Recent attempts are reused across processes. A quota/network/GitHub failure
    // opens a durable circuit and keeps the cached row rather than erroring the
    // control command that triggered reconcile.
    let Some(number) = pr.github().map(|github| github.number) else {
        session.observation = Observation::NotRequired;
        return Ok(Some(pr));
    };
    let now = time::OffsetDateTime::now_utc();
    // A `Fresh` read (ci-fix settlement) must never be served from the store's
    // observation cache: the repair body may have pushed a new head seconds ago,
    // and the warm cache still names the pre-turn head.
    if matches!(freshness, crate::ops::pr::PrReadFreshness::Cached) {
        if let Some(observation) = cached_github_observation(&pr, now) {
            session.observation = observation;
            return Ok(Some(pr));
        }
    }
    let previous = pr.clone();
    let github_pr = match crate::ops::pr::observe_pr_by_number(
        &session.worktree,
        number,
        &pr.branch,
        freshness,
    ) {
        crate::ops::pr::PrObservation::Fresh(info) => {
            pr.github_observation = Some(GithubObservation {
                checked_at: now,
                result: GithubObservationResult::Fresh,
            });
            session.observation = Observation::Fresh { observed_at: now };
            info
        }
        crate::ops::pr::PrObservation::NotFound => {
            // The PR ref was deleted remotely; a merge (if any) is already
            // persisted. Cache the successful absence briefly and keep the
            // settled/working state.
            pr.github_observation = Some(GithubObservation {
                checked_at: now,
                result: GithubObservationResult::Fresh,
            });
            pr.updated_at = now;
            update_task_pr_with_authority(store, &pr, lease)
                .await
                .map_err(|error| task_error(error.to_string()))?;
            session.observation = Observation::Fresh { observed_at: now };
            return Ok(Some(pr));
        }
        crate::ops::pr::PrObservation::Degraded { reason } => {
            let retry_at = now + PR_OBSERVATION_DEGRADED_BACKOFF;
            pr.github_observation = Some(GithubObservation {
                checked_at: now,
                result: GithubObservationResult::Degraded {
                    reason: reason.clone(),
                },
            });
            // `updated_at` remains the time of the cached PR data, not the
            // failed attempt. Only the observation metadata changes.
            update_task_pr_with_authority(store, &pr, lease)
                .await
                .map_err(|error| task_error(error.to_string()))?;
            session.observation = Observation::Degraded {
                reason,
                cached_as_of: pr.updated_at,
                retry_at,
            };
            return Ok(Some(pr));
        }
    };
    let number = u32::try_from(github_pr.number).map_err(|_| {
        task_error(format!(
            "pull request #{} exceeds supported range",
            github_pr.number
        ))
    })?;
    let url = github_pr.url.clone();
    let previous_phase = previous.phase();
    let previous_github = previous.github().cloned();
    let previous_session_status = session.status;
    let previous_status_reason = session.status_reason.clone();
    let previous_pm_writeback = session.pm_writeback.clone();
    let publication = pr.publication.get_or_insert(PrPublication {
        requested_at: now,
        after_merge: AfterMerge::Review,
        next_slug: None,
        github: None,
    });
    publication.github = Some(GithubPr {
        number,
        url: url.clone(),
        head_sha: github_pr.head_sha.clone(),
    });

    let mut observed_incident = None;
    let mut green_at = None;
    let mut merged_at = None;
    let pr_event = match github_pr.state.as_str() {
        "merged" => {
            let merge_commit = github_pr.merge_commit.clone().ok_or_else(|| {
                task_error(format!(
                    "GitHub reports pull request #{} merged without a merge commit",
                    github_pr.number
                ))
            })?;
            pr.merge_commit = Some(merge_commit.clone());
            pr.ci_observation = None;
            merged_at = Some(now);
            // Record the merge, but withhold completion while an accepted
            // directive is unincorporated — an auto-merge armed by `lf pr land`
            // must not silently erase direction accepted after it was armed — or
            // while the branch holds follow-up committed past the merged tip,
            // which another serial PR still owes. The PR is settling in flight and
            // is not on disk yet, so its range is read from it directly.
            let completes = pr
                .publication
                .as_ref()
                .is_some_and(|publication| publication.after_merge == AfterMerge::CompleteTask)
                && !has_pending_directive(session)
                && matches!(
                    committed_follow_up_range(&session.worktree, &pr)?,
                    CommittedFollowUp::ProvenEmpty
                );
            if completes {
                // The completion gate: even with the PR merged, the Task cannot
                // be completed in the PM until every required review is
                // approved. The PR is settling in flight, so only the review
                // half of the gate applies here. Do not weaken the review gate
                // or infer merge from a green head.
                let gate = review_gate(store, session).await?;
                if gate.satisfied {
                    session.set_status(
                        TaskSessionStatus::Completed,
                        format!(
                            "pull request #{} merged and completed the Task",
                            github_pr.number
                        ),
                    );
                    reconcile_pm_writeback(store, session, Some(&url)).await;
                } else if !session.status.is_process_active() {
                    session.set_status(
                        TaskSessionStatus::Waiting,
                        format!(
                            "pull request #{} merged; awaiting gate before completion: {}",
                            github_pr.number,
                            gate.reason()
                        ),
                    );
                }
            } else if !session.status.is_process_active() {
                let reason = if has_pending_directive(session) {
                    format!(
                        "pull request #{} merged, but directive v{} is not yet incorporated; \
                         acknowledge it or re-steer before completing",
                        github_pr.number, session.current_directive_version
                    )
                } else {
                    format!(
                        "pull request #{} merged; another PR may follow",
                        github_pr.number
                    )
                };
                session.set_status(TaskSessionStatus::Waiting, reason);
            }
            Some(TaskEventKind::PrMerged {
                pr_id: pr.id.clone(),
                sequence: pr.sequence,
                number,
                url: url.clone(),
                merge_commit,
            })
        }
        "closed" => {
            // A PR the flow already abandoned settles again when GitHub's
            // `closed` is observed. Re-stamping the time makes the second
            // settle differ from the first and wedges the session on
            // "already settled differently" — the first abandonment is the
            // fact; observation only confirms it.
            pr.abandoned_at = pr.abandoned_at.or(Some(now));
            pr.ci_observation = None;
            if !session.status.is_process_active() {
                session.set_status(
                    TaskSessionStatus::Waiting,
                    format!("pull request #{} closed without merge", github_pr.number),
                );
            }
            None
        }
        _ => {
            // GitHub has it open, so any `abandoned_at` here is a stale claim that
            // it was closed. Clearing it returns the same row to `Open`.
            pr.abandoned_at = None;
            if !session.status.is_process_active() {
                session.set_status(
                    TaskSessionStatus::Waiting,
                    format!("pull request #{} is open for review", github_pr.number),
                );
            }
            if let Some(ci_observation) = observe_required_checks(
                &session.worktree,
                &pr.branch,
                github_pr.head_sha.as_deref(),
                now,
            ) {
                if ci_observation.state == CiState::Passing {
                    green_at = Some(ci_observation.observed_at);
                } else {
                    observed_incident = ci_incident(&pr, &ci_observation);
                }
                pr.ci_observation = Some(ci_observation);
            }
            Some(TaskEventKind::PrOpened {
                pr_id: pr.id.clone(),
                sequence: pr.sequence,
                number,
                url: url.clone(),
            })
        }
    };

    let pr_changed = pr != previous;
    let completes_task = pr.phase() == PrPhase::Merged
        && session.status == TaskSessionStatus::Completed
        && pr
            .publication
            .as_ref()
            .is_some_and(|publication| publication.after_merge == AfterMerge::CompleteTask);
    let mut session_saved_with_pr = false;
    if pr_changed {
        pr.updated_at = now;
        if completes_task {
            complete_task_session_after_pr_with_authority(store, session, &pr, lease)
                .await
                .map_err(|error| task_error(error.to_string()))?;
            session_saved_with_pr = true;
        } else if pr.is_settled() {
            settle_task_pr_with_authority(store, &pr, None, lease)
                .await
                .map_err(|error| task_error(error.to_string()))?;
        } else {
            update_task_pr_with_authority(store, &pr, lease)
                .await
                .map_err(|error| task_error(error.to_string()))?;
        }
    }
    if let Some(incident) = observed_incident {
        store
            .observe_ci_incident(&incident)
            .await
            .map_err(|error| task_error(error.to_string()))?;
    }
    if let Some(green_at) = green_at {
        store
            .mark_ci_incidents_green(&pr.id, green_at)
            .await
            .map_err(|error| task_error(error.to_string()))?;
    }
    if let Some(merged_at) = merged_at {
        store
            .mark_ci_incidents_merged(&pr.id, merged_at)
            .await
            .map_err(|error| task_error(error.to_string()))?;
    }
    if !session_saved_with_pr
        && (session.status != previous_session_status
            || session.status_reason != previous_status_reason
            || session.pm_writeback != previous_pm_writeback)
    {
        update_task_session_with_authority(store, session, lease)
            .await
            .map_err(|error| task_error(error.to_string()))?;
    }
    if session.status != previous_session_status {
        append_task_event_with_authority(
            store,
            &session.id,
            &TaskEventKind::StatusChanged {
                from: previous_session_status,
                to: session.status,
                reason: session.status_reason.clone(),
            },
            lease,
        )
        .await
        .map_err(|error| task_error(error.to_string()))?;
    }
    if pr_changed {
        if let Some(event) = pr_event {
            let should_append = match &event {
                TaskEventKind::PrOpened { .. } => previous_github.as_ref() != pr.github(),
                TaskEventKind::PrMerged { .. } => previous_phase != PrPhase::Merged,
                _ => true,
            };
            if should_append {
                append_task_event_with_authority(store, &session.id, &event, lease)
                    .await
                    .map_err(|error| task_error(error.to_string()))?;
            }
        }
    }
    if previous_session_status != TaskSessionStatus::Completed
        && session.status == TaskSessionStatus::Completed
    {
        append_task_event_with_authority(
            store,
            &session.id,
            &TaskEventKind::Completed {
                summary: "pull request merge completed the Task".to_string(),
            },
            lease,
        )
        .await
        .map_err(|error| task_error(error.to_string()))?;
    }
    Ok(Some(pr))
}

/// The slug for the next serial PR: the operator's `--next` override, else the
/// settled PR's recorded `next_slug`, else the sequence number. One computation
/// shared by the recovery gate and the rotation.
fn next_pr_slug(settled: &TaskPr, slug_override: Option<&str>) -> String {
    slug_override
        .map(str::to_string)
        .or_else(|| {
            settled
                .publication
                .as_ref()
                .and_then(|publication| publication.next_slug.clone())
        })
        .unwrap_or_else(|| (settled.sequence + 1).to_string())
}

/// The deterministic next serial branch for a settled Task PR — the same branch
/// `ensure_working_pr_with_authority` would cut. The recovery gate reads this so
/// a partial rotation (worktree already on the next branch) is adopted, not
/// refused as an unrelated branch.
fn deterministic_next_branch(
    session: &TaskSession,
    settled: &TaskPr,
    slug_override: Option<&str>,
) -> OpsResult<String> {
    let slug = next_pr_slug(settled, slug_override);
    let author = settled
        .branch
        .split_once('/')
        .map(|(author, _)| author)
        .ok_or_else(|| {
            task_error(format!(
                "Task PR branch {:?} has no author prefix",
                settled.branch
            ))
        })?;
    Ok(format!("{author}/{}-{slug}", session.workspace_slug))
}

/// The branch/worktree state a Task recovery must adopt, computed read-only
/// from the durable PR sequence and the worktree before any ownership moves.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum TaskRecoveryAdoption {
    /// An active PR owns the worktree; the body continues on its branch. A dirty
    /// working tree is allowed — ongoing work survives recovery.
    Active { branch: String },
    /// No active PR: between-PR recovery. The worktree sits on the settled
    /// branch or the deterministic next serial branch; the runner rotates.
    BetweenPrs { settled: String, next: String },
}

/// Compute every branch/worktree/PR adoption precondition for Task recovery
/// before any durable ownership moves. Read-only: it touches neither the store,
/// the lease, the PR sequence, nor the worktree, so refusal leaves the
/// predecessor, successor link, PR sequence, leases, and worktree untouched.
pub(crate) async fn task_recovery_adoption(
    store: &SharedStore,
    session: &TaskSession,
) -> OpsResult<TaskRecoveryAdoption> {
    let worktree = &session.worktree;
    let identifier = &session.launch.issue.identifier;
    if !worktree.exists() {
        return Err(task_error(format!(
            "Task {identifier} worktree {} is missing; recovery refused before moving any ownership",
            worktree.display()
        )));
    }
    if let Some(state) = crate::engine::git::intervention_state(worktree)
        .map_err(|error| task_error(format!("failed to inspect Task worktree state: {error}")))?
    {
        return Err(task_error(format!(
            "Task {identifier} worktree {} is mid-{state}; resolve or abort it before resuming, \
             recovery refused before moving any ownership",
            worktree.display()
        )));
    }
    let current = current_branch(worktree)
        .map_err(|error| task_error(format!("failed to inspect Task branch: {error}")))?
        .ok_or_else(|| {
            task_error(format!(
                "Task {identifier} worktree {} is detached; recovery needs a branch",
                worktree.display()
            ))
        })?;
    if !ref_exists(worktree, &format!("refs/heads/{current}"))
        .map_err(|error| task_error(format!("failed to inspect Task branch: {error}")))?
    {
        return Err(task_error(format!(
            "Task {identifier} worktree {} is on branch {current:?} which no longer exists; \
             re-create it or recover the worktree before resuming",
            worktree.display()
        )));
    }
    if let Some(active) = store
        .active_task_pr(&session.id)
        .await
        .map_err(|error| task_error(format!("failed to read active PR: {error}")))?
    {
        if current != active.branch {
            return Err(task_error(format!(
                "Task {identifier} active PR expects branch {:?}, but the worktree is on \
                 {current:?}; recovery refused before moving any ownership",
                active.branch
            )));
        }
        return Ok(TaskRecoveryAdoption::Active {
            branch: active.branch,
        });
    }
    let prs = store
        .task_prs(&session.id)
        .await
        .map_err(|error| task_error(format!("failed to read Task PRs: {error}")))?;
    let settled = prs
        .last()
        .cloned()
        .ok_or_else(|| task_error("Task Session has no PR history"))?;
    if !settled.is_settled() {
        return Err(task_error(format!(
            "Task PR {} is neither active nor settled",
            settled.id
        )));
    }
    let next = deterministic_next_branch(session, &settled, None)?;
    if current != settled.branch && current != next {
        return Err(task_error(format!(
            "Task {identifier} between-PR recovery expected settled branch {:?} or next branch \
             {next:?}, but the worktree is on {current:?}; recovery refused before moving any \
             ownership",
            settled.branch
        )));
    }
    if !is_clean(worktree)
        .map_err(|error| task_error(format!("failed to inspect Task worktree: {error}")))?
    {
        return Err(task_error(format!(
            "Task {identifier} cannot recover between PRs while {} has uncommitted changes; \
             carry them forward with `lf pr next` or commit before resuming, recovery refused \
             before moving any ownership",
            worktree.display()
        )));
    }
    Ok(TaskRecoveryAdoption::BetweenPrs {
        settled: settled.branch,
        next,
    })
}

/// Refuse a dirty between-PR worktree after PR reconciliation. The runner's
/// strict rotation cannot carry a dirty tree, so catching this before the lease
/// is reaped or a successor body is launched keeps ownership put. Read-only.
pub(crate) async fn refuse_dirty_between_prs(
    store: &SharedStore,
    session: &TaskSession,
) -> OpsResult<()> {
    if store
        .active_task_pr(&session.id)
        .await
        .map_err(|error| task_error(format!("failed to read active PR: {error}")))?
        .is_some()
    {
        return Ok(());
    }
    if is_clean(&session.worktree)
        .map_err(|error| task_error(format!("failed to inspect Task worktree: {error}")))?
    {
        return Ok(());
    }
    Err(task_error(format!(
        "Task {} cannot recover between PRs while {} has uncommitted changes; carry them \
         forward with `lf pr next` or commit before resuming",
        session.launch.issue.identifier,
        session.worktree.display()
    )))
}

pub(crate) async fn ensure_working_pr(
    store: &SharedStore,
    session: &mut TaskSession,
) -> OpsResult<Option<TaskPr>> {
    ensure_working_pr_with_authority(store, session, None, RotateOptions::runner()).await
}

pub(crate) async fn ensure_working_pr_for_lease(
    store: &SharedStore,
    session: &mut TaskSession,
    lease: &ChildWriteLease,
) -> OpsResult<Option<TaskPr>> {
    ensure_working_pr_with_authority(store, session, Some(lease), RotateOptions::runner()).await
}

/// How a serial-PR rotation treats the worktree. The runner rotates only a clean
/// tree (`carry_dirty = false`); the operator's `lf pr next` carries the
/// preserved follow-up edits forward onto the next serial branch
/// (`carry_dirty = true`) and may name that branch via `slug_override`.
#[derive(Debug, Clone, Default)]
pub(crate) struct RotateOptions {
    carry_dirty: bool,
    slug_override: Option<String>,
}

impl RotateOptions {
    fn runner() -> Self {
        Self::default()
    }
}

enum CommittedFollowUp {
    ProvenEmpty,
    Range { from: String, to: String },
    Unprovable { reason: &'static str },
}

/// Classify the commits reachable from `branch` but not from `cut`. The cut is
/// the boundary past which commits are work this classification is asked about;
/// each caller picks it. A cut that cannot be placed on the branch is
/// `Unprovable` rather than empty: `is_ancestor` maps every nonzero exit to
/// false, so a rewritten branch and a missing object arrive here identically and
/// neither proves there is nothing there.
fn commits_past(
    worktree: &Path,
    branch: &str,
    cut: &str,
    not_ancestor: &'static str,
) -> OpsResult<CommittedFollowUp> {
    let tip = rev_parse(worktree, branch)
        .map_err(|error| task_error(format!("failed to resolve settled branch tip: {error}")))?;
    if tip == cut {
        return Ok(CommittedFollowUp::ProvenEmpty);
    }
    let ancestor = is_ancestor(worktree, cut, branch)
        .map_err(|error| task_error(format!("failed to check follow-up ancestry: {error}")))?;
    if !ancestor {
        return Ok(CommittedFollowUp::Unprovable {
            reason: not_ancestor,
        });
    }
    Ok(CommittedFollowUp::Range {
        from: cut.to_string(),
        to: branch.to_string(),
    })
}

/// Classify follow-up work committed on the settled branch *after* its PR
/// merged. The merged branch tip is `head_sha` — recorded by reconcile from
/// GitHub's `headRefOid`; commits reachable from the branch but not from
/// `head_sha` are the post-merge follow-up. A missing or unrelated recorded tip
/// cannot prove the range empty: rotation still skips an unsafe carry, while
/// completion fails closed until the boundary becomes provable.
fn committed_follow_up_range(worktree: &Path, settled: &TaskPr) -> OpsResult<CommittedFollowUp> {
    let Some(head_sha) = settled.github().and_then(|github| github.head_sha.clone()) else {
        return Ok(CommittedFollowUp::Unprovable {
            reason: "the published pull request head is missing",
        });
    };
    commits_past(
        worktree,
        &settled.branch,
        &head_sha,
        "the published pull request head is not an ancestor of the settled branch",
    )
}

/// Classify the authored work an unpublished PR holds. The cut is the fork point
/// recorded when the PR was minted, so commits past it are this PR's own work and
/// `ProvenEmpty` means the branch never moved off its base. Same tri-state, same
/// ancestry rule as the merged cut above — only the boundary differs.
fn unpublished_work(worktree: &Path, pr: &TaskPr) -> OpsResult<CommittedFollowUp> {
    commits_past(
        worktree,
        &pr.branch,
        &pr.base_commit,
        "the recorded base is not an ancestor of the unpublished branch",
    )
}

/// The commit `branch` forks from — the one authority for `base_commit`, and the
/// same expression `verify_task_pr_range_with_authority` asserts before every
/// publish. A merge-base is always an ancestor of both inputs, so a base recorded
/// here can never read `Unprovable` for incoherence.
fn fork_point(worktree: &Path, base_ref: &str, branch: &str) -> OpsResult<String> {
    merge_base(worktree, base_ref, branch).map_err(|error| {
        task_error(format!(
            "{branch:?} shares no history with {base_ref}: {error}"
        ))
    })
}

/// Re-derive a `base_commit` an older mint left incoherent with its branch, which
/// wedged completion on `Unprovable` forever (W2-300). The mint can no longer
/// write such a row; this frees the ones it already did. Fail-soft throughout: any
/// failure leaves the row for the gate to refuse, so this heals the data the gate
/// reads and never relaxes the gate.
///
/// Scoped to the legacy mint's exact signature, `M <= B <= upstream`: it sourced
/// `B` from the upstream line, so a base it wrote is always a commit the upstream
/// carries. Merely "the fork point is an ancestor of `B`" is too weak — a sibling
/// or foreign base satisfies that too, and is contamination rather than a stale
/// mint. Those stay `Unprovable`, which is the fail-closed answer.
async fn heal_incoherent_base(
    store: &SharedStore,
    session: &TaskSession,
    pr: TaskPr,
    lease: Option<&ChildWriteLease>,
) -> OpsResult<TaskPr> {
    if pr.phase() != PrPhase::Working || !session.worktree.exists() {
        return Ok(pr);
    }
    // Local, so a coherent row costs no fetch.
    if is_ancestor(&session.worktree, &pr.base_commit, &pr.branch).unwrap_or(false) {
        return Ok(pr);
    }
    let Ok(default_branch) = get_default_branch(&session.worktree) else {
        return Ok(pr);
    };
    let Ok((base_ref, _)) = resolve_upstream_base(&session.worktree, &default_branch) else {
        return Ok(pr);
    };
    let Ok(fork) = fork_point(&session.worktree, &base_ref, &pr.branch) else {
        tracing::warn!(
            task = %session.launch.issue.identifier,
            branch = %pr.branch,
            base = %pr.base_commit,
            "Task PR base is incoherent and shares no history with the upstream; \
             leaving the row for the completion gate to refuse"
        );
        return Ok(pr);
    };
    let ancestry = |commit: &str, descendant: &str| {
        is_ancestor(&session.worktree, commit, descendant).unwrap_or(false)
    };
    if !(ancestry(&fork, &pr.base_commit) && ancestry(&pr.base_commit, &base_ref)) {
        tracing::warn!(
            task = %session.launch.issue.identifier,
            branch = %pr.branch,
            base = %pr.base_commit,
            "Task PR base is incoherent but is not on the upstream line, so no past mint \
             wrote it; leaving the row for the completion gate to refuse"
        );
        return Ok(pr);
    }
    let mut healed = pr;
    tracing::info!(
        task = %session.launch.issue.identifier,
        branch = %healed.branch,
        from = %healed.base_commit,
        to = %fork,
        "healing a Task PR base that is not an ancestor of its branch"
    );
    healed.base_commit = fork;
    healed.updated_at = time::OffsetDateTime::now_utc();
    match lease {
        Some(lease) => store.heal_task_pr_base_for_lease(&healed, lease).await,
        None => store.heal_task_pr_base(&healed).await,
    }
    .map_err(|error| task_error(format!("failed to heal Task PR base: {error}")))?;
    Ok(healed)
}

/// A directive was accepted (its version advanced) but the body has not yet
/// acknowledged it. Completion — manual or an armed auto-merge — must not fire
/// while this holds, or the accepted direction is silently erased.
pub(crate) fn has_pending_directive(session: &TaskSession) -> bool {
    session.current_directive_version > session.incorporated_directive_version
}

/// Whether the Task's *newest* PR (by sequence) is a merged `CompleteTask` — the
/// disposition that means the Task is settling, not rotating a serial successor.
///
/// The strict predicate for *automatic* completion: the sole input to
/// `merged_completing_pr` (and thus `advance_completion_after_gate`). Keying on
/// the newest PR — not `any` merged PR — is load-bearing: an older `CompleteTask`
/// behind a later `Review`/next-PR merge must never auto-complete the Task.
///
/// Reconciliation is looser and uses [`reconcilable_pr_set`] instead — an
/// out-of-band attestation backed by a live Linear-complete read can trust the
/// whole settled PR set, where the machine cannot.
pub(crate) fn latest_pr_completes_task(prs: &[TaskPr]) -> bool {
    prs.iter().max_by_key(|pr| pr.sequence).is_some_and(|pr| {
        pr.phase() == PrPhase::Merged
            && pr
                .publication
                .as_ref()
                .is_some_and(|publication| publication.after_merge == AfterMerge::CompleteTask)
    })
}

/// Whether the Task's settled PR set permits *reconciliation* — a broader,
/// attestation-gated predicate than [`latest_pr_completes_task`].
///
/// Automatic completion stays strict (newest PR a merged `CompleteTask`). But an
/// out-of-band `lf task reconcile`, backed by an explicit Wave/Operator
/// attestation and a live Linear-complete observation, trusts the settled set
/// instead. The directive's three clauses, in one place:
///
/// 1. *Ignore abandoned unpublished successor rows* — select the **latest
///    non-abandoned PR** by sequence, so a rotated successor that never became a
///    real PR (and any other abandoned row) never hides the real settled merge.
/// 2. *Require no active or unmerged non-abandoned PR* — nothing still in flight
///    (a non-abandoned PR that has not merged is Working/Publishing/Open).
/// 3. *Allow the latest non-abandoned PR to be any merged disposition* — a merged
///    `Review` sitting ahead of an older `CompleteTask` reconciles too.
///
/// Shared by the reconcile command guard, the supervisor's Reconcile
/// suppression, and the action model's Reconcile recommendation.
pub(crate) fn reconcilable_pr_set(prs: &[TaskPr]) -> bool {
    let none_in_flight = !prs
        .iter()
        .any(|pr| pr.abandoned_at.is_none() && pr.phase() != PrPhase::Merged);
    let latest_non_abandoned_merged = prs
        .iter()
        .filter(|pr| pr.abandoned_at.is_none())
        .max_by_key(|pr| pr.sequence)
        .is_some_and(|pr| pr.phase() == PrPhase::Merged);
    none_in_flight && latest_non_abandoned_merged
}

/// The directive at `current_directive_version`, or `None` when the row is
/// missing (a broken chain, never on a healthy Session).
pub(crate) async fn current_directive(
    store: &SharedStore,
    session: &TaskSession,
) -> OpsResult<Option<ChildDirective>> {
    let directives = store
        .child_directives(&ChildRef::Task(session.id.clone()))
        .await
        .map_err(|error| task_error(format!("failed to read Task directives: {error}")))?;
    Ok(directives
        .into_iter()
        .find(|directive| directive.version == session.current_directive_version))
}

/// The reconcilable shape's delivery half: the current directive was *applied* to
/// a body (`applied_at` set) but never incorporated. Proof of delivery, not of
/// semantic incorporation — the incorporation evidence is an explicit
/// Wave/Operator attestation, never this predicate. `false` when the current
/// directive is already incorporated or was never applied.
pub(crate) async fn current_directive_applied(
    store: &SharedStore,
    session: &TaskSession,
) -> OpsResult<bool> {
    Ok(current_directive(store, session)
        .await?
        .is_some_and(|directive| directive.applied_at.is_some()))
}

pub(crate) fn no_active_pr_resume_refusal(
    identifier: &str,
    active: Option<&TaskPr>,
    latest: Option<&TaskPr>,
) -> Option<String> {
    if active.is_some() {
        return None;
    }
    let suffix = match latest {
        Some(pr) => {
            let which = pr
                .github()
                .map(|github| format!("pull request #{}", github.number))
                .unwrap_or_else(|| format!("PR sequence {}", pr.sequence));
            format!("{which} {}", pr.phase().as_str())
        }
        None => "no PR history recorded".to_string(),
    };
    Some(format!(
        "Task {identifier} has no active PR to resume; {suffix}"
    ))
}

fn roll_back_failed_rotation(
    worktree: &Path,
    settled_branch: &str,
    recovery_branch: &str,
    stashed: bool,
) -> OpsResult<()> {
    checkout(worktree, settled_branch)
        .map_err(|error| task_error(format!("failed to restore settled branch: {error}")))?;
    delete_local_branch(worktree, recovery_branch)
        .map_err(|error| task_error(format!("failed to remove recovery branch: {error}")))?;
    if stashed {
        stash_pop(worktree)
            .map_err(|error| task_error(format!("failed to restore follow-up edits: {error}")))?;
    }
    Ok(())
}

async fn ensure_working_pr_with_authority(
    store: &SharedStore,
    session: &mut TaskSession,
    lease: Option<&ChildWriteLease>,
    rotate: RotateOptions,
) -> OpsResult<Option<TaskPr>> {
    reconcile_task_pr_with_authority(
        store,
        session,
        lease,
        crate::ops::pr::PrReadFreshness::Cached,
    )
    .await?;
    if session.status.is_terminal() {
        return Ok(None);
    }
    if let Some(active) = store
        .active_task_pr(&session.id)
        .await
        .map_err(|error| task_error(format!("failed to read active PR: {error}")))?
    {
        return Ok(Some(
            heal_incoherent_base(store, session, active, lease).await?,
        ));
    }

    let prs = store
        .task_prs(&session.id)
        .await
        .map_err(|error| task_error(format!("failed to read Task PRs: {error}")))?;
    let settled = prs
        .last()
        .cloned()
        .ok_or_else(|| task_error("Task Session has no PR history"))?;
    if !settled.is_settled() {
        return Err(task_error(format!(
            "Task PR {} is neither active nor settled",
            settled.id
        )));
    }
    // Rotating past an abandoned predecessor needs GitHub to have confirmed it
    // closed; the reconcile above read this row, so its verdict is already in
    // `session.observation`. A degraded read leaves the claim unverified, and a
    // successor minted on it strands an empty branch under a still-open PR.
    if let (PrPhase::Abandoned, Some(github)) = (settled.phase(), settled.github()) {
        if let Observation::Degraded { reason, .. } = &session.observation {
            return Err(task_error(format!(
                "cannot confirm pull request #{} is closed before starting the next PR: {reason}. \
                 Retry once GitHub is readable; if the PR was reopened, it continues as-is.",
                github.number
            )));
        }
    }
    let committed_carry = committed_follow_up_range(&session.worktree, &settled)?;
    // A settled completing PR normally never rotates: completion is pending on
    // the review gate, not on a follow-up PR. `reconcile_task_completion`
    // advances the Session to `Completed` once the gate closes. Two things
    // independently authorize one more serial PR: follow-up committed past the
    // merged tip, which the completion gate refuses to settle over, and a pending
    // directive that still needs a body to incorporate it. An applied-but-
    // unincorporated directive does *not* — its work already shipped in the merged
    // head, so it settles by an out-of-band reconciliation attestation, never
    // another provider turn.
    let pending_needs_body =
        has_pending_directive(session) && !current_directive_applied(store, session).await?;
    if settled
        .publication
        .as_ref()
        .is_some_and(|publication| publication.after_merge == AfterMerge::CompleteTask)
        && !pending_needs_body
        && !matches!(&committed_carry, CommittedFollowUp::Range { .. })
    {
        return Ok(None);
    }
    if let Some(lease) = lease {
        store
            .validate_child_write_lease(&ChildRef::Task(session.id.clone()), lease)
            .await
            .map_err(|error| task_error(format!("Task body lost write authority: {error}")))?;
    }
    let sequence = settled.sequence + 1;
    let slug = next_pr_slug(&settled, rotate.slug_override.as_deref());
    let branch = deterministic_next_branch(session, &settled, rotate.slug_override.as_deref())?;
    let default_branch = get_default_branch(&session.worktree)
        .map_err(|error| task_error(format!("failed to resolve default branch: {error}")))?;
    // `base_ref` positions the branch below; the recorded `base_commit` is read
    // from the branch itself once it is positioned, never from a parallel read of
    // the upstream — see `fork_point`.
    let (base_ref, _) = resolve_upstream_base(&session.worktree, &default_branch)?;
    if !rotate.carry_dirty
        && !is_clean(&session.worktree)
            .map_err(|error| task_error(format!("failed to inspect Task worktree: {error}")))?
    {
        return Err(task_error(format!(
            "Task {} cannot rotate PRs while {} has uncommitted changes",
            session.launch.issue.identifier,
            session.worktree.display()
        )));
    }
    // The merged branch tip GitHub recorded (`head_sha`) is the cut between
    // already-merged work and the follow-up the worker committed on top after the
    // merge. Rotation carries that committed range forward — plus any dirty edits
    // — so no work is dropped when moving onto the next serial branch.
    let current = current_branch(&session.worktree)
        .map_err(|error| task_error(format!("failed to inspect Task branch: {error}")))?
        .ok_or_else(|| task_error("Task worktree is detached"))?;
    if current != branch {
        if current != settled.branch {
            return Err(task_error(format!(
                "Task {} expected settled branch {:?} or recovery branch {:?}, but {} is on {:?}",
                session.launch.issue.identifier,
                settled.branch,
                branch,
                session.worktree.display(),
                current
            )));
        }
        let local_ref = format!("refs/heads/{branch}");
        let remote_ref = format!("refs/remotes/origin/{branch}");
        let collision = ref_exists(&session.worktree, &local_ref)
            .map_err(|error| task_error(format!("failed to inspect branch collision: {error}")))?
            || ref_exists(&session.worktree, &remote_ref).map_err(|error| {
                task_error(format!("failed to inspect branch collision: {error}"))
            })?;
        if collision {
            return Err(task_error(format!(
                "next PR branch {branch:?} already exists; retry the settling command with a clearer --next name"
            )));
        }
        // Stash dirty edits so the new branch starts clean: `checkout -b` then
        // carries nothing, the committed range cherry-picks onto a clean index,
        // and the stash pop reapplies the dirty edits on top.
        let stashed = stash_including_untracked(&session.worktree)
            .map_err(|error| task_error(format!("failed to stash follow-up edits: {error}")))?;
        if let Err(error) = checkout_new_branch_from(&session.worktree, &branch, &base_ref) {
            let recovered = current_branch(&session.worktree)
                .map_err(|read_error| {
                    task_error(format!("failed to inspect recovery branch: {read_error}"))
                })?
                .as_deref()
                == Some(branch.as_str());
            if !recovered {
                if stashed {
                    stash_pop(&session.worktree).map_err(|recovery_error| {
                        task_error(format!(
                            "failed to rotate Task worktree: {error}; restoring follow-up edits \
                             also failed: {recovery_error}"
                        ))
                    })?;
                }
                return Err(task_error(format!(
                    "failed to rotate Task worktree: {error}; follow-up edits were restored"
                )));
            }
        }
        if let CommittedFollowUp::Range { from, to } = &committed_carry {
            if let Err(error) = cherry_pick_range(&session.worktree, from, to) {
                roll_back_failed_rotation(&session.worktree, &settled.branch, &branch, stashed)
                    .map_err(|recovery_error| {
                        task_error(format!(
                        "failed to carry committed follow-up from {:?} onto {branch}: {error}; \
                         automatic recovery also failed: {recovery_error}",
                        settled.branch
                    ))
                    })?;
                return Err(task_error(format!(
                    "failed to carry committed follow-up from {:?} onto {branch}: {error}; \
                     restored {:?} with its follow-up edits so the rotation can be retried",
                    settled.branch, settled.branch
                )));
            }
        }
        if stashed {
            stash_pop(&session.worktree).map_err(|error| {
                task_error(format!(
                    "carried the committed follow-up but could not reapply dirty edits: {error}; \
                     the recovery branch and retained stash are in {} for conflict resolution",
                    session.worktree.display()
                ))
            })?;
        }
    }
    // The branch is now positioned — freshly cut at `base_ref`, or reused where a
    // partial rotation already left it. Record the base it actually forks from, so
    // the pair agrees by construction whichever of those two it was. Reading the
    // upstream tip here instead is what paired a fresh base with a stale branch
    // and left completion unable to prove the successor empty (W2-300).
    let base_commit = fork_point(&session.worktree, &base_ref, &branch)?;

    push_with_upstream(&session.worktree, "origin", &branch)
        .map_err(|error| task_error(format!("failed to push next PR branch: {error}")))?;

    let now = time::OffsetDateTime::now_utc();
    let next = TaskPr {
        id: TaskPrId::new(),
        task_session_id: session.id.clone(),
        sequence,
        slug,
        branch,
        base_commit,
        parent_pr_id: None,
        publication: None,
        merge_commit: None,
        abandoned_at: None,
        ci_observation: None,
        github_observation: None,
        linear_attachment_id: None,
        linear_comment_id: None,
        linear_link_error: None,
        created_at: now,
        updated_at: now,
    };
    match settle_task_pr_with_authority(store, &settled, Some(&next), lease).await {
        Ok(()) => {
            append_task_event_with_authority(
                store,
                &session.id,
                &TaskEventKind::PrStarted {
                    pr_id: next.id.clone(),
                    sequence: next.sequence,
                    branch: next.branch.clone(),
                    base_commit: next.base_commit.clone(),
                },
                lease,
            )
            .await
            .map_err(|error| task_error(error.to_string()))?;
            Ok(Some(next))
        }
        Err(error) => {
            let recovered = store
                .task_prs(&session.id)
                .await
                .map_err(|read_error| task_error(read_error.to_string()))?
                .into_iter()
                .find(|pr| pr.sequence == sequence);
            match recovered {
                Some(pr)
                    if pr.branch == next.branch
                        && pr.base_commit == next.base_commit
                        && pr.phase() == PrPhase::Working =>
                {
                    Ok(Some(pr))
                }
                _ => Err(task_error(format!(
                    "failed to record next Task PR after branch rotation: {error}"
                ))),
            }
        }
    }
}

/// Advance a Task to its next serial PR after an out-of-band merge. Reconciles
/// the merge into the settled PR, then rotates the worktree to sequence N+1 —
/// carrying preserved follow-up edits forward — so a stopped worker (or an
/// operator) can push the next PR without manual git surgery. `slug` names the
/// next branch; otherwise the settled PR's `next_slug`, otherwise the sequence.
pub fn pr_next(repo: &Path, slug: Option<&str>) -> OpsResult<TaskPr> {
    let slug_override = slug.map(parse_pr_slug).transpose()?;
    let repo = repo.to_path_buf();
    block_on_task(async move {
        let store = task_store().await?;
        let (mut session, lease) = task_for_worktree(&store, &repo)
            .await?
            .ok_or_else(|| task_error("no Task Session owns this worktree"))?;
        // Observe an out-of-band merge before deciding whether to rotate.
        reconcile_task_pr_with_authority(
            &store,
            &mut session,
            lease.as_ref(),
            crate::ops::pr::PrReadFreshness::Cached,
        )
        .await?;
        if let Some(active) = store
            .active_task_pr(&session.id)
            .await
            .map_err(|error| task_error(format!("failed to read active PR: {error}")))?
        {
            let which = active
                .github()
                .map(|github| format!("#{}", github.number))
                .unwrap_or_else(|| format!("sequence {}", active.sequence));
            return Err(task_error(format!(
                "current PR {which} is not merged yet; land it or wait for the merge before `lf pr next`"
            )));
        }
        if session.status.is_terminal() {
            return Err(task_error(format!(
                "Task {} is already {}; nothing to rotate",
                session.launch.issue.identifier,
                session.status.as_str()
            )));
        }
        let rotate = RotateOptions {
            carry_dirty: true,
            slug_override,
        };
        ensure_working_pr_with_authority(&store, &mut session, lease.as_ref(), rotate)
            .await?
            .ok_or_else(|| task_error("Task has no settled PR to rotate from"))
    })
}

pub fn task_status(issue: &str) -> OpsResult<TaskSession> {
    block_on_task(async move {
        let store = task_store().await?;
        let mut session = store
            .get_task_session_by_issue(issue)
            .await
            .map_err(|error| task_error(format!("failed to read task status: {error}")))?
            .ok_or_else(|| task_error(format!("no Task Session exists for {issue:?}")))?;
        reconcile_task_pr(&store, &mut session).await?;
        reconcile_process_liveness(&store, &mut session).await?;
        reconcile_task_completion(&store, &mut session, None).await?;
        Ok(session)
    })
}

pub fn task_complete(issue: &str, summary: String) -> OpsResult<TaskSession> {
    let summary = summary.trim().to_string();
    if summary.is_empty() {
        return Err(task_error("completion summary cannot be empty"));
    }
    block_on_task(async move {
        let store = task_store().await?;
        let mut session = store
            .get_task_session_by_issue(issue)
            .await
            .map_err(|error| task_error(format!("failed to read Task Session: {error}")))?
            .ok_or_else(|| task_error(format!("no Task Session exists for {issue:?}")))?;
        reconcile_task_pr(&store, &mut session).await?;
        let lease = ambient_task_write_lease(&session)?;
        if let Some(lease) = lease.as_ref() {
            store
                .validate_child_write_lease(&ChildRef::Task(session.id.clone()), lease)
                .await
                .map_err(|error| task_error(format!("Task body lost write authority: {error}")))?;
        }
        if session.status == TaskSessionStatus::Completed {
            return Ok(session);
        }
        if session.status == TaskSessionStatus::Abandoned {
            return Err(task_error(format!(
                "Task {} is abandoned and cannot be completed",
                session.launch.issue.identifier
            )));
        }
        settle_completed_session(&store, &mut session, lease.as_ref(), summary).await?;
        Ok(session)
    })
}

/// Drive an inactive Session through the completion gate to `Completed`: the
/// clean-tree check, the gate, the PM writeback, the terminal transaction, and
/// the `StatusChanged`/`Completed` events. Shared by `lf task complete` (in-body
/// or operator) and `lf task reconcile` (out-of-band attestation). The caller
/// owns everything upstream — reconciling the PR, resolving the lease, and any
/// gate-clearing side effects (e.g. incorporating a pending directive).
async fn settle_completed_session(
    store: &SharedStore,
    session: &mut TaskSession,
    lease: Option<&ChildWriteLease>,
    summary: String,
) -> OpsResult<()> {
    if !is_clean(&session.worktree)
        .map_err(|error| task_error(format!("failed to inspect Task worktree: {error}")))?
    {
        return Err(task_error(
            "Task worktree has uncommitted changes; publish or explicitly abandon them first",
        ));
    }
    // The completion gate: every active PR must be settled and every required
    // review approved before the Task can be completed in the PM. Do not
    // weaken the review gate or infer merge from a green head.
    let gate = task_completion_gate(store, session).await?;
    if let Some(refusal) = gate.refusal(&session.launch.issue.identifier) {
        // Nothing has been written. A refusal here — an open review, a
        // committed follow-up, anything — leaves a discardable successor
        // active, so the Task keeps its PR and no rotation is provoked.
        return Err(task_error(refusal));
    }
    let from = session.status;
    session.set_status(TaskSessionStatus::Completed, summary.clone());
    reconcile_pm_writeback(store, session, None).await;
    // Every other condition is now proven, so the rotation's empty artifact
    // is dropped as part of completing — one transaction that deletes the row
    // and writes the terminal status together. There is no instant at which
    // the successor is gone and the Task is not yet terminal, which is the
    // only state `ensure_working_pr_with_authority` would rotate from.
    complete_task_session_with_authority(
        store,
        session,
        gate.discardable_successor.as_ref(),
        lease,
    )
    .await
    .map_err(|error| task_error(format!("failed to complete Task Session: {error}")))?;
    append_task_event_with_authority(
        store,
        &session.id,
        &TaskEventKind::StatusChanged {
            from,
            to: TaskSessionStatus::Completed,
            reason: session.status_reason.clone(),
        },
        lease,
    )
    .await
    .map_err(|error| task_error(error.to_string()))?;
    append_task_event_with_authority(
        store,
        &session.id,
        &TaskEventKind::Completed { summary },
        lease,
    )
    .await
    .map_err(|error| task_error(error.to_string()))?;
    Ok(())
}

/// The concise publication-state label carried by a PR's Linear linkage. Derived
/// purely from the PR model — its phase and after-merge disposition — so the label
/// is a projection of the source of truth, not a second state.
fn pr_link_state_label(pr: &TaskPr) -> String {
    match pr.phase() {
        PrPhase::Merged => "Merged".to_string(),
        PrPhase::Abandoned => "Abandoned".to_string(),
        _ => {
            let completes = pr
                .publication
                .as_ref()
                .is_some_and(|publication| publication.after_merge == AfterMerge::CompleteTask);
            if completes {
                "Open · completes task on merge".to_string()
            } else {
                "Open · in review".to_string()
            }
        }
    }
}

/// Idempotently refresh the PR's Linear linkage (attachment + managed comment) and
/// record the outcome on the PR. Best-effort: a degraded writeback lands in
/// `linear_link_error` and leaves the GitHub result intact; the next publication
/// command retries. Does nothing for a PR with no GitHub URL yet.
async fn link_pr_to_linear(store: &SharedStore, session: &TaskSession, pr: &mut TaskPr) {
    let Some(github) = pr.github().cloned() else {
        return;
    };
    let state = pr_link_state_label(pr);
    let title = format!("GitHub PR #{}", github.number);
    let body = format!("[GitHub PR #{}]({}) — {}", github.number, github.url, state);
    let wave = match owning_wave(store, session).await {
        Ok(wave) => wave,
        Err(error) => {
            pr.linear_link_error = Some(error.to_string());
            return;
        }
    };
    let prior = crate::ops::pm::PrLinkageIds {
        attachment_id: pr.linear_attachment_id.clone(),
        comment_id: pr.linear_comment_id.clone(),
    };
    let request = crate::ops::pm::PrLinkRequest {
        issue_id: session.launch.issue.id.as_str().to_string(),
        url: github.url.clone(),
        title,
        subtitle: state,
        body,
    };
    let outcome =
        crate::ops::pm::pm_link_pr_async(&session.worktree, wave.name(), &request, &prior).await;
    // Say so at publish time. The PR line in `lf task status` carries the durable
    // reading, but an operator running `lf pr open` should not have to go looking.
    if let Some(error) = &outcome.error {
        tracing::warn!(
            issue = session.launch.issue.identifier,
            pr = github.number,
            "Linear link degraded; the GitHub PR is published and the next publish retries: {error}"
        );
    }
    pr.linear_attachment_id = outcome.ids.attachment_id;
    pr.linear_comment_id = outcome.ids.comment_id;
    pr.linear_link_error = outcome.error;
}

fn writeback_state(result: OpsResult<()>) -> PmWritebackState {
    writeback_state_for(PmWritebackOperation::CompleteTask, result)
}

fn writeback_state_for(operation: PmWritebackOperation, result: OpsResult<()>) -> PmWritebackState {
    match result {
        Ok(()) => PmWritebackState::Current,
        Err(error) => PmWritebackState::Pending {
            operation,
            error: error.to_string(),
        },
    }
}

pub(crate) async fn reconcile_pm_writeback(
    store: &SharedStore,
    session: &mut TaskSession,
    pr_url: Option<&str>,
) {
    let Ok(wave) = owning_wave(store, session).await else {
        session.pm_writeback = PmWritebackState::Pending {
            operation: PmWritebackOperation::CompleteTask,
            error: format!("owning Wave {} is not registered", session.wave_id),
        };
        return;
    };
    session.pm_writeback = writeback_state(
        crate::ops::task_pm::complete_task(
            &session.worktree,
            wave.name(),
            session.launch.issue.id.as_str(),
            pr_url,
        )
        .await,
    );
}

async fn retry_pm_writeback(store: &SharedStore, session: &mut TaskSession) {
    let Ok(prs) = store.task_prs(&session.id).await else {
        return;
    };
    let pr_url = prs
        .iter()
        .rev()
        .find_map(|pr| pr.github().map(|github| github.url.as_str()));
    let Ok(wave) = owning_wave(store, session).await else {
        session.pm_writeback = PmWritebackState::Pending {
            operation: PmWritebackOperation::CompleteTask,
            error: format!("owning Wave {} is not registered", session.wave_id),
        };
        return;
    };
    session.pm_writeback = {
        let operation = match &session.pm_writeback {
            PmWritebackState::Pending { operation, .. } => *operation,
            PmWritebackState::Current => PmWritebackOperation::CompleteTask,
        };
        let result = match operation {
            PmWritebackOperation::CompleteTask => {
                crate::ops::task_pm::retry_complete_task(
                    &session.worktree,
                    wave.name(),
                    session.launch.issue.id.as_str(),
                    pr_url,
                )
                .await
            }
            PmWritebackOperation::ReopenTask => {
                crate::ops::task_pm::retry_reopen_task(
                    &session.worktree,
                    wave.name(),
                    session.launch.issue.id.as_str(),
                )
                .await
            }
        };
        writeback_state_for(operation, result)
    };
    session.updated_at = time::OffsetDateTime::now_utc();
}

// ---------------------------------------------------------------------------
// Completion gate: the single source of truth for "may this Task be completed
// in the PM yet?" A Task is completable only when every active PR is settled
// (merged or explicitly abandoned) AND every required interaction review has an
// explicit Approved outcome. Every path that sets a Task to `Completed` and
// fires the `CompleteTask` PM writeback consults this gate, so the PM row, the
// durable Session, the PR state, and the review state converge monotonically.
// ---------------------------------------------------------------------------

/// The outcome of evaluating the completion gate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct CompletionGate {
    pub satisfied: bool,
    pub blockers: Vec<String>,
    /// A successor the lifecycle rotated after the Task's work merged that
    /// provably holds nothing — never published, branch never moved off its
    /// recorded base. It is the rotation's artifact, not work, so it does not
    /// block completion; it must not outlive one either.
    ///
    /// Classification only, and exactly one thing acts on it: [`task_complete`]
    /// passes it as the completion transaction's `skipped_pr`, which drops the
    /// row and writes the terminal status together. Discarding it any earlier
    /// would leave a non-terminal Task with no active PR — the state
    /// [`ensure_working_pr_with_authority`] rotates another empty PR from.
    pub discardable_successor: Option<TaskPr>,
}

impl CompletionGate {
    /// One actionable, human-readable sentence. Empty when the gate is
    /// satisfied.
    pub fn reason(&self) -> String {
        if self.blockers.is_empty() {
            String::new()
        } else {
            self.blockers.join("; ")
        }
    }

    pub(crate) fn refusal(&self, identifier: &str) -> Option<String> {
        (!self.satisfied).then(|| {
            format!(
                "Task {identifier} cannot complete until its gates close: {}",
                self.reason()
            )
        })
    }
}

impl CompletionGate {
    fn unsatisfied(blockers: Vec<String>) -> Self {
        Self {
            satisfied: false,
            blockers,
            discardable_successor: None,
        }
    }
}

/// The required interaction reviews that still speak for this Task attempt.
/// Current-epoch reviews hold their live waitpoint, and only the newest Gate
/// epoch holds the standing settlement verdict. Superseded reviews remain audit
/// history without becoming permanent completion blockers.
async fn required_reviews_for_task(
    store: &SharedStore,
    session: &TaskSession,
) -> OpsResult<Vec<InteractionReview>> {
    let reviews = store
        .list_interaction_reviews(Some(&session.wave_id))
        .await
        .map_err(|error| task_error(format!("failed to read interaction reviews: {error}")))?;
    let newest_gate_epoch = reviews
        .iter()
        .filter(|review| {
            review.task_session_id == session.id
                && review.policy == InteractionPolicy::Require
                && review.phase == TaskLifecyclePhase::Gate
        })
        .map(|review| review.phase_epoch)
        .max();
    Ok(reviews
        .into_iter()
        .filter(|review| {
            review.task_session_id == session.id
                && review.policy == InteractionPolicy::Require
                && (review.phase_epoch == session.phase_epoch
                    || (review.phase == TaskLifecyclePhase::Gate
                        && Some(review.phase_epoch) == newest_gate_epoch))
        })
        .collect())
}

/// The review half of the completion gate: every required interaction review
/// must be completed with an `Approved` disposition. Used on the merge path,
/// where the PR being reconciled is settling in flight and must not be re-read
/// from the store as an active PR.
async fn review_gate(store: &SharedStore, session: &TaskSession) -> OpsResult<CompletionGate> {
    let mut blockers = Vec::new();
    for review in required_reviews_for_task(store, session).await? {
        let approved = review.status == InteractionReviewStatus::Completed
            && review
                .disposition
                .is_some_and(|disposition| disposition == InteractionReviewDisposition::Approved);
        if !approved {
            let kind = review.reviewer.kind();
            let state = if review.status == InteractionReviewStatus::Completed {
                "completed without approval"
            } else {
                "awaiting review"
            };
            blockers.push(format!("required {kind} review {} is {state}", review.id));
        }
    }
    Ok(if blockers.is_empty() {
        CompletionGate {
            satisfied: true,
            blockers: Vec::new(),
            discardable_successor: None,
        }
    } else {
        CompletionGate::unsatisfied(blockers)
    })
}

/// Evaluate the completion gate against the Session's durable PR and review
/// state. Pure over store state: running it twice changes nothing. Use this from
/// paths where the PR state is already persisted (`task_complete`, the
/// reconcile advance, the repair). The merge-reconcile path uses
/// [`review_gate`] instead, since the PR it is settling is not yet on disk.
pub(crate) async fn task_completion_gate(
    store: &SharedStore,
    session: &TaskSession,
) -> OpsResult<CompletionGate> {
    let mut gate = review_gate(store, session).await?;

    // An accepted but unincorporated directive blocks completion: an auto-merge
    // armed by `lf pr land` must not silently erase direction accepted after it
    // was armed.
    if has_pending_directive(session) {
        gate.blockers.push(format!(
            "directive v{} is not yet incorporated; acknowledge it or re-steer before completing",
            session.current_directive_version
        ));
    }

    // Work committed past the tip GitHub merged is owned by no PR; completing
    // would strand it outside the Task. Only the newest PR can still hold it: a
    // rotation carries the range onto its successor but leaves the settled
    // branch's commits in place, so scanning every merged PR would never clear.
    let prs = store
        .task_prs(&session.id)
        .await
        .map_err(|error| task_error(format!("failed to read Task PRs: {error}")))?;
    // Discarding a successor is only ever settling *over* landed work. Without a
    // merged predecessor there is nothing to settle, and an empty unpublished PR
    // keeps today's refusal.
    let has_merged_predecessor = prs.iter().any(|pr| pr.phase() == PrPhase::Merged);
    if let Some(newest) = prs.last() {
        if newest.phase() == PrPhase::Merged
            && newest
                .publication
                .as_ref()
                .is_some_and(|publication| publication.after_merge == AfterMerge::CompleteTask)
        {
            let number = newest
                .github()
                .map(|github| github.number)
                .unwrap_or_default();
            match committed_follow_up_range(&session.worktree, newest)? {
                CommittedFollowUp::ProvenEmpty => {}
                CommittedFollowUp::Range { .. } => gate.blockers.push(format!(
                    "follow-up work is committed past merged pull request #{number}"
                )),
                // Missing later evidence blocks entry into completion, but it
                // cannot reverse a terminal fact. Repair still reopens on a
                // proven range or any other concrete gate blocker.
                CommittedFollowUp::Unprovable { .. }
                    if session.status == TaskSessionStatus::Completed => {}
                CommittedFollowUp::Unprovable { reason } => gate.blockers.push(format!(
                    "cannot prove merged pull request #{number} has no committed follow-up: {reason}"
                )),
            }
        }
    }

    // Every active PR must be settled (merged or explicitly abandoned).
    if let Some(pr) = store
        .active_task_pr(&session.id)
        .await
        .map_err(|error| task_error(format!("failed to read active PR: {error}")))?
    {
        let which = pr
            .github()
            .map(|github| format!("#{}", github.number))
            .unwrap_or_else(|| format!("sequence {}", pr.sequence));
        match pr.phase() {
            PrPhase::Open => gate.blockers.push(format!(
                "pull request {which} is open for review; merge it or run `lf pr abandon`"
            )),
            PrPhase::Publishing => gate.blockers.push(format!(
                "pull request {which} is still publishing; wait for it to land or run `lf pr abandon`"
            )),
            // An unpublished PR means three different things; say which. The
            // classification is inert: a gate that goes on to refuse leaves the
            // row exactly as it found it.
            PrPhase::Working => match unpublished_work(&session.worktree, &pr)? {
                CommittedFollowUp::ProvenEmpty if has_merged_predecessor => {
                    gate.discardable_successor = Some(pr.clone());
                }
                CommittedFollowUp::ProvenEmpty => gate.blockers.push(format!(
                    "pull request {which} is unpublished; publish and merge it or run `lf pr abandon`"
                )),
                CommittedFollowUp::Range { .. } => gate.blockers.push(format!(
                    "follow-up work is committed on unpublished pull request {which}; \
                     publish and merge it or run `lf pr abandon`"
                )),
                CommittedFollowUp::Unprovable { reason } => gate.blockers.push(format!(
                    "cannot prove unpublished pull request {which} is empty: {reason}"
                )),
            },
            PrPhase::Merged | PrPhase::Abandoned => {}
        }
    }

    gate.satisfied = gate.blockers.is_empty();
    Ok(gate)
}

/// The newest PR (by sequence) when it is the Task's *completing* merge — i.e.
/// completion is pending on the gate, not on a future PR. `None` when the newest
/// PR is not a merged `CompleteTask`, so an older `CompleteTask` behind a later
/// `Review`/next-PR merge never drives automatic completion. Shares the one
/// disposition predicate with the reconcile command and supervisor suppression.
async fn merged_completing_pr(
    store: &SharedStore,
    session: &TaskSession,
) -> OpsResult<Option<TaskPr>> {
    let prs = store
        .task_prs(&session.id)
        .await
        .map_err(|error| task_error(format!("failed to read Task PRs: {error}")))?;
    if !latest_pr_completes_task(&prs) {
        return Ok(None);
    }
    Ok(prs.into_iter().max_by_key(|pr| pr.sequence))
}

/// Complete a Task Session after its gate closed, persisting the merged
/// `CompleteTask` PR and firing the `CompleteTask` PM writeback. Used by the
/// reconcile advance path (no lease) once a required review approves after a
/// merge. Idempotent: a Session already `Completed` is left untouched.
async fn advance_completion_after_gate(
    store: &SharedStore,
    session: &mut TaskSession,
    lease: Option<&ChildWriteLease>,
) -> OpsResult<bool> {
    if session.status.is_terminal() || session.status.is_process_active() {
        return Ok(false);
    }
    let Some(pr) = merged_completing_pr(store, session).await? else {
        return Ok(false);
    };
    let gate = task_completion_gate(store, session).await?;
    if !gate.satisfied {
        return Ok(false);
    }
    // This path completes through `complete_task_session_after_pr`, which settles
    // the merged PR and has no `skipped_pr`, so it cannot drop a successor in the
    // same transaction. Rather than complete and leave the row active — a
    // completed Task still holding an active PR — decline and let `lf task
    // complete` own this shape. Unreachable on current rows: a `CompleteTask`
    // merge no longer rotates, so it never has a successor to discard.
    if gate.discardable_successor.is_some() {
        return Ok(false);
    }
    let from = session.status;
    let url = pr.github().map(|github| github.url.clone());
    session.set_status(
        TaskSessionStatus::Completed,
        format!(
            "pull request #{} merged and completed the Task",
            pr.github().map(|github| github.number).unwrap_or_default()
        ),
    );
    reconcile_pm_writeback(store, session, url.as_deref()).await;
    complete_task_session_after_pr_with_authority(store, session, &pr, lease)
        .await
        .map_err(|error| task_error(error.to_string()))?;
    append_task_event_with_authority(
        store,
        &session.id,
        &TaskEventKind::StatusChanged {
            from,
            to: TaskSessionStatus::Completed,
            reason: session.status_reason.clone(),
        },
        lease,
    )
    .await
    .map_err(|error| task_error(error.to_string()))?;
    Ok(true)
}

/// Repair a prematurely completed Task: the PM row says `done` but a PR is still
/// unsettled or a required review is still open. Revert the Session to `Waiting`
/// with an actionable reason and queue a `ReopenTask` PM writeback so Linear
/// reopens and the PM row reconverges. No Session, PR, directive, or review row
/// is deleted. Idempotent: a Session already repaired (writeback Pending
/// ReopenTask) is not repaired twice.
async fn repair_premature_completion(
    store: &SharedStore,
    session: &mut TaskSession,
    lease: Option<&ChildWriteLease>,
) -> OpsResult<bool> {
    if session.status != TaskSessionStatus::Completed {
        return Ok(false);
    }
    // A writeback already in flight (either direction) owns the PM state; do not
    // stack a second repair on top of a pending completion or reopen.
    if matches!(session.pm_writeback, PmWritebackState::Pending { .. }) {
        return Ok(false);
    }
    let gate = task_completion_gate(store, session).await?;
    if gate.satisfied {
        return Ok(false);
    }
    let from = session.status;
    session.set_status(
        TaskSessionStatus::Waiting,
        format!("reopened: completion outran its gates ({})", gate.reason()),
    );
    session.pm_writeback = PmWritebackState::Pending {
        operation: PmWritebackOperation::ReopenTask,
        error: "premature completion pending reopen".to_string(),
    };
    if let Some(lease) = lease {
        store
            .update_task_session_for_lease(session, lease)
            .await
            .map_err(|error| task_error(error.to_string()))?;
    } else {
        store
            .update_task_session(session)
            .await
            .map_err(|error| task_error(error.to_string()))?;
    }
    append_task_event_with_authority(
        store,
        &session.id,
        &TaskEventKind::StatusChanged {
            from,
            to: TaskSessionStatus::Waiting,
            reason: session.status_reason.clone(),
        },
        lease,
    )
    .await
    .map_err(|error| task_error(error.to_string()))?;
    Ok(true)
}

/// Reconcile completion toward the gate: retry any in-flight PM writeback,
/// repair a premature completion, or advance completion once the gate closes.
/// Shared by every read-side reconcile (`task_status`, Project Session task
/// reconcile) so out-of-band merge, delayed review, writeback retry, restart,
/// and duplicate observation all funnel through one idempotent path.
pub(crate) async fn reconcile_task_completion(
    store: &SharedStore,
    session: &mut TaskSession,
    lease: Option<&ChildWriteLease>,
) -> OpsResult<()> {
    if session.status == TaskSessionStatus::Completed
        && matches!(session.pm_writeback, PmWritebackState::Pending { .. })
    {
        retry_pm_writeback(store, session).await;
        if let Some(lease) = lease {
            store
                .update_task_session_for_lease(session, lease)
                .await
                .map_err(|error| task_error(error.to_string()))?;
        } else {
            store
                .update_task_session(session)
                .await
                .map_err(|error| task_error(error.to_string()))?;
        }
        return Ok(());
    }
    if repair_premature_completion(store, session, lease).await? {
        return Ok(());
    }
    advance_completion_after_gate(store, session, lease).await?;
    Ok(())
}

fn review_gate_from(review: &InteractionReview) -> ReviewGateState {
    match review.status {
        InteractionReviewStatus::Requested => ReviewGateState::Requested,
        InteractionReviewStatus::Active => ReviewGateState::Active,
        InteractionReviewStatus::Completed => match review.disposition {
            Some(InteractionReviewDisposition::Approved) => ReviewGateState::Approved,
            Some(InteractionReviewDisposition::ChangesRequested) => {
                ReviewGateState::ChangesRequested
            }
            None => ReviewGateState::Approved,
        },
    }
}

pub fn task_snapshot(session: &TaskSession) -> OpsResult<TaskSessionSnapshot> {
    let session = session.clone();
    block_on_task(async move {
        let store = task_store().await?;
        let wave = owning_wave(&store, &session).await?;
        let process_alive = if session.status.is_process_active() {
            match session.latest_process.as_ref() {
                Some(process) => tmux_session_exists(&process.tmux_name)
                    .await
                    .map_err(|error| task_error(error.to_string()))?,
                None => false,
            }
        } else {
            false
        };
        let latest_event = store
            .task_events_after(&session.id, 0)
            .await
            .map_err(|error| task_error(format!("failed to read task events: {error}")))?
            .into_iter()
            .last();
        let prs = store
            .task_prs(&session.id)
            .await
            .map_err(|error| task_error(format!("failed to read Task PRs: {error}")))?;
        let latest = prs.last();
        let active = prs.iter().find(|pr| pr.is_active());
        let active_pr = active.map(|pr| pr.id.clone());
        let predecessor_phase = match active.and_then(|pr| pr.parent_pr_id.as_ref()) {
            Some(parent_id) => store
                .get_task_pr(parent_id)
                .await
                .map_err(|error| task_error(format!("failed to read parent PR: {error}")))?
                .map(|pr| pr.phase()),
            None => None,
        };
        let review_gate = store
            .interaction_review_at(
                &session.id,
                session.phase_epoch,
                session.phase_iteration,
                session.phase_cursor,
            )
            .await
            .map_err(|error| task_error(format!("failed to read review gate: {error}")))?
            .map(|r| review_gate_from(&r));
        let completion_gate = task_completion_gate(&store, &session).await?;
        let completion_refusal = completion_gate.refusal(&session.launch.issue.identifier);
        let resume_refusal =
            no_active_pr_resume_refusal(&session.launch.issue.identifier, active, latest);
        let action_evidence = TaskActionEvidence {
            status: session.status,
            latest_pr_phase: latest.map(|pr| pr.phase()),
            latest_pr_after_merge: latest
                .and_then(|pr| pr.publication.as_ref())
                .map(|p| p.after_merge),
            latest_pr_next_slug: latest
                .and_then(|pr| pr.publication.as_ref())
                .and_then(|p| p.next_slug.as_deref()),
            completion_refusal: completion_refusal.as_deref(),
            resume_refusal: resume_refusal.as_deref(),
            pending_directive: has_pending_directive(&session),
            directive_applied: current_directive_applied(&store, &session).await?,
            reconcilable: reconcilable_pr_set(&prs),
            ci: active.and_then(|pr| pr.fresh_ci()),
            process_alive: if session.status.is_process_active() {
                Some(process_alive)
            } else {
                None
            },
            predecessor_phase,
            review_gate,
            abandon_intent: session.abandon_intent.is_some(),
            local_progress_unsettled: None,
        };
        let actions = derive_task_actions(&action_evidence);
        let (predecessor_session_id, successor_session_id) = store
            .task_session_chain_neighbors(&session.id)
            .await
            .map_err(|error| task_error(format!("failed to read Task chain: {error}")))?;
        // Resolve the live routing target for this Task's parent Project. The
        // historical project_session_id stays as provenance; the routing target
        // is its non-terminal successor when the historical session is terminal.
        // A broken chain (terminal historical, no live successor) surfaces as
        // `None` rather than failing status — the actionable failure belongs to
        // the routing operations (wake, review), not the read.
        let (routing_project_session_id, project_route_succeeded) =
            match crate::ops::project::resolve_task_project_route(store.as_ref(), &session).await {
                Ok(route) => (Some(route.current.to_string()), route.succeeded),
                Err(_) => (None, false),
            };
        Ok(TaskSessionSnapshot {
            issue_id: session.launch.issue.id.as_str().to_string(),
            issue_identifier: session.launch.issue.identifier,
            session_id: session.id.to_string(),
            project_id: session.launch.project.id.as_str().to_string(),
            project: session.launch.project.slug,
            pm_snapshot_synced_at: session.launch.pm_snapshot_synced_at,
            pm_writeback: session.pm_writeback,
            wave: wave.name().to_string(),
            project_session_id: session.project_session_id.to_string(),
            routing_project_session_id,
            project_route_succeeded,
            predecessor_session_id,
            successor_session_id,
            current_directive_version: session.current_directive_version,
            incorporated_directive_version: session.incorporated_directive_version,
            status: session.status,
            status_reason: session.status_reason,
            status_at: session.status_at,
            worktree: session.worktree.display().to_string(),
            workspace_slug: session.workspace_slug,
            lifecycle: session.lifecycle,
            lifecycle_phase: session.lifecycle_phase,
            phase_epoch: session.phase_epoch,
            phase_cursor: session.phase_cursor,
            phase_iteration: session.phase_iteration,
            gate_cycle: session.gate_cycle,
            gate_proposal: session.gate_proposal,
            prs,
            active_pr,
            agent: session.agent,
            provider: session.provider,
            provider_session_id: session.provider_session_id,
            process_alive,
            latest_process: session.latest_process,
            latest_event,
            created_at: session.created_at,
            updated_at: session.updated_at,
            observation: session.observation,
            actions,
        })
    })
}

pub fn task_changes(issue: &str) -> OpsResult<TaskChangesSnapshot> {
    let session = task_status(issue)?;
    let pr = active_pr(&session)?;
    changes_snapshot(TaskWorkspace::new(&session, &pr))
}

fn changes_snapshot(workspace: TaskWorkspace<'_>) -> OpsResult<TaskChangesSnapshot> {
    let mut files = BTreeMap::<String, TaskChangedFile>::new();
    record_changed_paths(
        workspace.worktree,
        &[
            "diff",
            "--name-only",
            "-z",
            &format!("{}..HEAD", workspace.base_commit),
        ],
        &mut files,
        |file| file.committed = true,
    )?;
    record_changed_paths(
        workspace.worktree,
        &["diff", "--cached", "--name-only", "-z"],
        &mut files,
        |file| file.staged = true,
    )?;
    record_changed_paths(
        workspace.worktree,
        &["diff", "--name-only", "-z"],
        &mut files,
        |file| file.unstaged = true,
    )?;
    record_changed_paths(
        workspace.worktree,
        &["ls-files", "--others", "--exclude-standard", "-z"],
        &mut files,
        |file| file.untracked = true,
    )?;
    let head_commit = git_output(workspace.worktree, &["rev-parse", "HEAD"])?
        .trim()
        .to_string();
    Ok(TaskChangesSnapshot {
        issue_identifier: workspace.issue_identifier.to_string(),
        session_id: workspace.session_id.to_string(),
        base_commit: workspace.base_commit.to_string(),
        head_commit,
        files: files.into_values().collect(),
    })
}

pub fn task_diff(issue: &str, path: Option<&str>) -> OpsResult<TaskDiffSnapshot> {
    let session = task_status(issue)?;
    let pr = active_pr(&session)?;
    diff_snapshot(TaskWorkspace::new(&session, &pr), path)
}

fn diff_snapshot(workspace: TaskWorkspace<'_>, path: Option<&str>) -> OpsResult<TaskDiffSnapshot> {
    const MAX_PATCH_BYTES: usize = 1_000_000;

    let relative = path.map(validate_task_relative_path).transpose()?;
    let mut args = vec![
        "diff".to_string(),
        "--no-ext-diff".to_string(),
        "--no-color".to_string(),
        workspace.base_commit.to_string(),
        "--".to_string(),
    ];
    if let Some(path) = &relative {
        args.push(path.clone());
    }
    let mut patch = git_output_owned(workspace.worktree, &args)?;
    let untracked = untracked_paths(workspace.worktree)?;
    let include_untracked = untracked
        .into_iter()
        .filter(|candidate| relative.as_ref().is_none_or(|path| path == candidate));
    for path in include_untracked {
        let output = Command::new("git")
            .current_dir(workspace.worktree)
            .args(["diff", "--no-index", "--no-color", "--", "/dev/null", &path])
            .output()
            .map_err(|error| {
                task_error(format!("failed to diff untracked file {path}: {error}"))
            })?;
        if !output.status.success() && output.status.code() != Some(1) {
            return Err(task_error(format!(
                "failed to diff untracked file {path}: {}",
                String::from_utf8_lossy(&output.stderr).trim()
            )));
        }
        patch.extend_from_slice(&output.stdout);
    }
    let truncated = patch.len() > MAX_PATCH_BYTES;
    if truncated {
        patch.truncate(MAX_PATCH_BYTES);
    }
    let patch = String::from_utf8_lossy(&patch).into_owned();
    let binary = patch.contains("Binary files ") || patch.contains("GIT binary patch");
    Ok(TaskDiffSnapshot {
        issue_identifier: workspace.issue_identifier.to_string(),
        session_id: workspace.session_id.to_string(),
        path: relative,
        patch,
        binary,
        truncated,
    })
}

pub fn task_file(issue: &str, path: &str) -> OpsResult<TaskFileSnapshot> {
    let session = task_status(issue)?;
    let pr = active_pr(&session)?;
    file_snapshot(TaskWorkspace::new(&session, &pr), path)
}

fn file_snapshot(workspace: TaskWorkspace<'_>, path: &str) -> OpsResult<TaskFileSnapshot> {
    const MAX_FILE_BYTES: usize = 1_000_000;

    let relative = validate_task_relative_path(path)?;
    let root = workspace
        .worktree
        .canonicalize()
        .map_err(|error| task_error(format!("cannot resolve Task worktree: {error}")))?;
    let absolute = root
        .join(&relative)
        .canonicalize()
        .map_err(|error| task_error(format!("cannot open Task file {relative:?}: {error}")))?;
    if !absolute.starts_with(&root) || !absolute.is_file() {
        return Err(task_error(format!(
            "Task file {relative:?} does not resolve to a file inside the Task worktree"
        )));
    }
    let bytes = std::fs::read(&absolute)
        .map_err(|error| task_error(format!("cannot read Task file {relative:?}: {error}")))?;
    let size_bytes = bytes.len() as u64;
    let binary = bytes.iter().take(8_192).any(|byte| *byte == 0);
    let truncated = bytes.len() > MAX_FILE_BYTES;
    let visible = &bytes[..bytes.len().min(MAX_FILE_BYTES)];
    let content = (!binary).then(|| String::from_utf8_lossy(visible).into_owned());
    Ok(TaskFileSnapshot {
        issue_identifier: workspace.issue_identifier.to_string(),
        session_id: workspace.session_id.to_string(),
        path: relative,
        content,
        binary,
        size_bytes,
        truncated,
    })
}

fn validate_task_relative_path(path: &str) -> OpsResult<String> {
    let path = Path::new(path);
    if path.as_os_str().is_empty() || path.is_absolute() {
        return Err(task_error(
            "Task paths must stay relative to the Task worktree",
        ));
    }
    let mut normalized = PathBuf::new();
    for component in path.components() {
        match component {
            Component::Normal(value) => normalized.push(value),
            Component::CurDir => {}
            _ => {
                return Err(task_error(
                    "Task paths must stay relative to the Task worktree",
                ))
            }
        }
    }
    if normalized.as_os_str().is_empty() {
        return Err(task_error("Task paths must name a file"));
    }
    Ok(normalized.to_string_lossy().to_string())
}

fn record_changed_paths(
    worktree: &Path,
    args: &[&str],
    files: &mut BTreeMap<String, TaskChangedFile>,
    mark: impl Fn(&mut TaskChangedFile),
) -> OpsResult<()> {
    for path in nul_paths(&git_output_bytes(worktree, args)?) {
        let file = files.entry(path.clone()).or_insert(TaskChangedFile {
            path,
            committed: false,
            staged: false,
            unstaged: false,
            untracked: false,
        });
        mark(file);
    }
    Ok(())
}

fn untracked_paths(worktree: &Path) -> OpsResult<Vec<String>> {
    Ok(nul_paths(&git_output_bytes(
        worktree,
        &["ls-files", "--others", "--exclude-standard", "-z"],
    )?))
}

fn nul_paths(output: &[u8]) -> Vec<String> {
    output
        .split(|byte| *byte == 0)
        .filter(|path| !path.is_empty())
        .map(|path| String::from_utf8_lossy(path).into_owned())
        .collect()
}

fn git_output(worktree: &Path, args: &[&str]) -> OpsResult<String> {
    Ok(String::from_utf8_lossy(&git_output_bytes(worktree, args)?).into_owned())
}

fn git_output_bytes(worktree: &Path, args: &[&str]) -> OpsResult<Vec<u8>> {
    let output = Command::new("git")
        .current_dir(worktree)
        .args(args)
        .output()
        .map_err(|error| task_error(format!("failed to run git {}: {error}", args.join(" "))))?;
    if !output.status.success() {
        return Err(task_error(format!(
            "git {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&output.stderr).trim()
        )));
    }
    Ok(output.stdout)
}

fn git_output_owned(worktree: &Path, args: &[String]) -> OpsResult<Vec<u8>> {
    let output = Command::new("git")
        .current_dir(worktree)
        .args(args)
        .output()
        .map_err(|error| task_error(format!("failed to run git diff: {error}")))?;
    if !output.status.success() {
        return Err(task_error(format!(
            "git diff failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        )));
    }
    Ok(output.stdout)
}

fn queue_command(
    issue: &str,
    authority: CallerAuthority,
    kind: ChildCommandKind,
) -> OpsResult<TaskControlResult> {
    block_on_task(async move {
        let store = task_store().await?;
        let mut session = store
            .get_task_session_by_issue(issue)
            .await
            .map_err(|error| task_error(format!("failed to resolve task: {error}")))?
            .ok_or_else(|| task_error(format!("no Task Session exists for {issue:?}")))?;
        reconcile_task_pr(&store, &mut session).await?;
        reconcile_process_liveness(&store, &mut session).await?;
        let issue_id = session.launch.issue.identifier.clone();
        let observation = session.observation.clone();
        let source = validate_task_caller_authority(&store, &session, &authority).await?;
        let result = super::child::queue_command(
            &store,
            super::child::ChildSession::Task(Box::new(session)),
            source,
            kind,
        )
        .await?;
        Ok(task_control_result(issue_id, observation, result))
    })
}

pub fn task_follow_up(
    issue: &str,
    authority: CallerAuthority,
    message: String,
) -> OpsResult<TaskControlResult> {
    queue_command(
        issue,
        authority,
        ChildCommandKind::FollowUp { text: message },
    )
}

pub fn task_steer(
    issue: &str,
    authority: CallerAuthority,
    message: String,
) -> OpsResult<TaskControlResult> {
    queue_command(issue, authority, ChildCommandKind::Steer { text: message })
}

pub fn task_interrupt(
    issue: &str,
    authority: CallerAuthority,
    replacement: Option<String>,
) -> OpsResult<TaskControlResult> {
    queue_command(
        issue,
        authority,
        ChildCommandKind::Interrupt { replacement },
    )
}

/// Recover an abandoned Task as one linked successor that adopts its worktree,
/// serial PR history, and current directive.
pub fn task_recover(
    issue: &str,
    authority: CallerAuthority,
    reason: Option<String>,
) -> OpsResult<TaskSession> {
    let issue = issue.to_string();
    block_on_task(async move {
        let store = task_store().await?;
        _recover_abandoned_task(&store, &issue, &authority, reason).await
    })
}

async fn _recover_abandoned_task(
    store: &SharedStore,
    issue: &str,
    authority: &CallerAuthority,
    reason: Option<String>,
) -> OpsResult<TaskSession> {
    let reason = reason
        .map(|value| value.trim().to_string())
        .map(|value| {
            if value.is_empty() {
                Err(task_error("recovery reason cannot be empty"))
            } else {
                Ok(value)
            }
        })
        .transpose()?;
    let predecessor = store
        .get_task_session_by_issue(issue)
        .await
        .map_err(|error| task_error(format!("failed to resolve task: {error}")))?
        .ok_or_else(|| task_error(format!("no Task Session exists for {issue:?}")))?;
    validate_task_caller_authority(store, &predecessor, authority).await?;

    if predecessor.status != TaskSessionStatus::Abandoned {
        if predecessor.status == TaskSessionStatus::Completed {
            return Err(task_error(format!(
                "Task {} is completed; start a new Task rather than recovering it",
                predecessor.launch.issue.identifier
            )));
        }
        // A retry after a successful recovery resolves to the live successor.
        // Return it only when it demonstrably adopted the abandoned attempt's
        // worktree; an ordinary new attempt uses a different worktree and is not
        // misreported as recovered.
        let (prior_id, _) = store
            .task_session_chain_neighbors(&predecessor.id)
            .await
            .map_err(|error| task_error(format!("failed to read Task chain: {error}")))?;
        if let Some(prior_id) = prior_id {
            let prior_id = TaskSessionId::parse(&prior_id)
                .map_err(|error| task_error(format!("invalid Task predecessor: {error}")))?;
            if let Some(prior) = store
                .get_task_session(&prior_id)
                .await
                .map_err(|error| task_error(format!("failed to read Task predecessor: {error}")))?
            {
                if prior.status == TaskSessionStatus::Abandoned
                    && prior.worktree == predecessor.worktree
                {
                    return Ok(predecessor);
                }
            }
        }
        return Err(task_error(format!(
            "Task {} is {}; resume it with `lf task resume {}`. Recover is only for abandoned Tasks.",
            predecessor.launch.issue.identifier,
            predecessor.status.as_str(),
            predecessor.launch.issue.identifier
        )));
    }

    // Refuse every unsafe worktree/branch/PR shape before moving ownership.
    task_recovery_adoption(store, &predecessor).await?;
    let carried = store
        .child_directives(&ChildRef::Task(predecessor.id.clone()))
        .await
        .map_err(|error| task_error(error.to_string()))?
        .into_iter()
        .find(|directive| directive.version == predecessor.current_directive_version)
        .ok_or_else(|| task_error("abandoned Task Session has no current directive"))?;
    let now = time::OffsetDateTime::now_utc();
    let status_reason = reason.map_or_else(
        || format!("recovered from {}; resume to continue", predecessor.id),
        |reason| {
            format!(
                "recovered from {}: {reason}; resume to continue",
                predecessor.id
            )
        },
    );
    let successor = TaskSession {
        id: TaskSessionId::new(),
        launch: predecessor.launch.clone(),
        pm_writeback: PmWritebackState::Current,
        wave_id: predecessor.wave_id.clone(),
        project_session_id: predecessor.project_session_id.clone(),
        current_directive_version: 1,
        incorporated_directive_version: 0,
        status: TaskSessionStatus::Waiting,
        status_reason,
        status_at: now,
        worktree: predecessor.worktree.clone(),
        workspace_slug: predecessor.workspace_slug.clone(),
        lifecycle: predecessor.lifecycle.clone(),
        lifecycle_phase: crate::task::TaskLifecyclePhase::Kickoff,
        phase_epoch: 1,
        phase_cursor: 0,
        phase_iteration: 0,
        gate_cycle: 0,
        gate_proposal: None,
        agent: predecessor.agent.clone(),
        provider: predecessor.provider.clone(),
        provider_session_id: None,
        latest_process: None,
        abandon_intent: None,
        created_at: now,
        updated_at: now,
        observation: Observation::NotRequired,
    };
    let directive = ChildDirective::initial(
        ChildRef::Task(successor.id.clone()),
        carried.text,
        carried.source,
    );
    let succession = store
        .recover_task_session_successor(&predecessor, &successor, &directive)
        .await
        .map_err(|error| task_error(format!("failed to recover Task: {error}")))?;
    Ok(succession.session)
}

pub fn task_resume(
    issue: &str,
    authority: CallerAuthority,
    message: Option<String>,
    model: Option<String>,
    reason: Option<String>,
) -> OpsResult<TaskControlResult> {
    let issue = issue.to_string();
    block_on_task(async move { resume_task_async(&issue, authority, message, model, reason).await })
}

/// Async core of [`task_resume`], reusable from callers already inside a runtime
/// (e.g. `lf handoff complete` waking the parent it just resolved).
pub(crate) async fn resume_task_async(
    issue: &str,
    authority: CallerAuthority,
    message: Option<String>,
    model: Option<String>,
    reason: Option<String>,
) -> OpsResult<TaskControlResult> {
    let store = task_store().await?;
    let mut session = store
        .get_task_session_by_issue(issue)
        .await
        .map_err(|error| task_error(format!("failed to resolve task: {error}")))?
        .ok_or_else(|| task_error(format!("no Task Session exists for {issue:?}")))?;
    // Compute every branch/worktree/PR adoption precondition before moving any
    // durable ownership — a no-active-PR recovery must not commit the successor
    // before PR rotation rejects an unrelated branch.
    task_recovery_adoption(&store, &session).await?;
    reconcile_task_pr(&store, &mut session).await?;
    let prs = store
        .task_prs(&session.id)
        .await
        .map_err(|error| task_error(format!("failed to read Task PRs: {error}")))?;
    let latest = prs.last();
    let active = prs.iter().find(|pr| pr.is_active());
    if let Some(refusal) =
        no_active_pr_resume_refusal(&session.launch.issue.identifier, active, latest)
    {
        return Err(task_error(refusal));
    }
    // Reconcile may settle an active PR that merged out of band, moving the
    // worktree into a between-PR state; refuse a dirty between-PR before the
    // lease is reaped or a successor body is launched.
    refuse_dirty_between_prs(&store, &session).await?;
    reconcile_process_liveness(&store, &mut session).await?;
    let issue_id = session.launch.issue.identifier.clone();
    let observation = session.observation.clone();
    let source = validate_task_caller_authority(&store, &session, &authority).await?;
    let result = super::child::resume_session(
        &store,
        super::child::ChildSession::Task(Box::new(session)),
        source,
        message,
        model,
        reason,
    )
    .await?;
    Ok(task_control_result(issue_id, observation, result))
}

pub fn task_receipt(
    command_id: &str,
    until: Option<ChildReceiptUntil>,
    timeout: Duration,
) -> OpsResult<TaskReceiptRead> {
    let command_id =
        ChildCommandId::parse(command_id).map_err(|error| task_error(error.to_string()))?;
    block_on_task(async move {
        let store = task_store().await?;
        let (command, timed_out) = if let Some(until) = until {
            super::child::wait_for_receipt_condition(&store, &command_id, until, timeout).await?
        } else {
            (
                super::child::read_receipt(&store, &command_id).await?,
                false,
            )
        };
        let ChildRef::Task(session_id) = &command.target else {
            return Err(task_error(format!(
                "command {command_id} belongs to a Project Session"
            )));
        };
        let session = store
            .get_task_session(session_id)
            .await
            .map_err(|error| task_error(format!("failed to read Task Session: {error}")))?
            .ok_or_else(|| task_error(format!("Task Session {session_id} disappeared")))?;
        let result = super::child::control_result(&store, &command, command.clone()).await?;
        Ok(TaskReceiptRead {
            receipt: task_control_result(
                session.launch.issue.identifier,
                Observation::NotRequired,
                result,
            ),
            timed_out,
        })
    })
}

pub fn task_decide(
    issue: &str,
    authority: CallerAuthority,
    decision_id: &str,
    choice: String,
    message: Option<String>,
) -> OpsResult<TaskControlResult> {
    let decision_id =
        ChildDecisionId::parse(decision_id).map_err(|error| task_error(error.to_string()))?;
    let choice = choice.trim().to_string();
    if choice.is_empty() {
        return Err(task_error("decision choice cannot be empty"));
    }
    let decision = block_on_task(async {
        let store = task_store().await?;
        let session = store
            .get_task_session_by_issue(issue)
            .await
            .map_err(|error| task_error(format!("failed to resolve task: {error}")))?
            .ok_or_else(|| task_error(format!("no Task Session exists for {issue:?}")))?;
        let events = store
            .task_events_after(&session.id, 0)
            .await
            .map_err(|error| task_error(format!("failed to read task decisions: {error}")))?;
        events
            .into_iter()
            .find_map(|event| match event.kind {
                TaskEventKind::DecisionRequested {
                    decision_id: requested_id,
                    options,
                    ..
                } if requested_id == decision_id => Some(options),
                _ => None,
            })
            .ok_or_else(|| task_error(format!("decision {decision_id} was not requested")))
    })?;
    if !decision.iter().any(|option| option == &choice) {
        return Err(task_error(format!(
            "choice {choice:?} is not one of: {}",
            decision.join(", ")
        )));
    }
    queue_command(
        issue,
        authority,
        ChildCommandKind::Decide {
            decision_id,
            choice,
            message,
        },
    )
}

pub fn task_request_decision(
    issue: &str,
    prompt: String,
    options: Vec<String>,
    wait: bool,
    timeout: Duration,
) -> OpsResult<TaskDecisionResult> {
    let prompt = prompt.trim().to_string();
    let options: Vec<String> = options
        .into_iter()
        .map(|option| option.trim().to_string())
        .filter(|option| !option.is_empty())
        .collect();
    if prompt.is_empty() || options.len() < 2 {
        return Err(task_error(
            "a decision requires a non-empty prompt and at least two options",
        ));
    }
    block_on_task(async move {
        let store = task_store().await?;
        let session = store
            .get_task_session_by_issue(issue)
            .await
            .map_err(|error| task_error(format!("failed to resolve task: {error}")))?
            .ok_or_else(|| task_error(format!("no Task Session exists for {issue:?}")))?;
        let ambient = std::env::var("LF_TASK_SESSION_ID")
            .map_err(|_| task_error("decision requests must run inside the owning Task Session"))?;
        if ambient != session.id.as_str() {
            return Err(task_error(format!(
                "Task Session {ambient} cannot request a decision for {}",
                session.id
            )));
        }
        let lease = task_write_lease_from_env()
            .map_err(|error| task_error(format!("Task body has no write authority: {error}")))?;
        let decision_id = ChildDecisionId::new();
        store
            .append_task_event_for_lease(
                &session.id,
                &lease,
                &TaskEventKind::DecisionRequested {
                    decision_id: decision_id.clone(),
                    prompt,
                    options,
                },
            )
            .await
            .map_err(|error| task_error(format!("failed to persist decision request: {error}")))?;

        let deadline = Instant::now() + timeout;
        loop {
            let events = store
                .task_events_after(&session.id, 0)
                .await
                .map_err(|error| {
                    task_error(format!("failed to read decision response: {error}"))
                })?;
            if let Some((choice, message)) = events.into_iter().find_map(|event| match event.kind {
                TaskEventKind::DecisionResolved {
                    decision_id: resolved_id,
                    choice,
                    message,
                } if resolved_id == decision_id => Some((choice, message)),
                _ => None,
            }) {
                return Ok(TaskDecisionResult {
                    issue_id: session.launch.issue.identifier.clone(),
                    session_id: session.id.to_string(),
                    decision_id: decision_id.to_string(),
                    resolved: true,
                    choice: Some(choice),
                    message,
                });
            }
            if !wait || Instant::now() >= deadline {
                return Ok(TaskDecisionResult {
                    issue_id: session.launch.issue.identifier.clone(),
                    session_id: session.id.to_string(),
                    decision_id: decision_id.to_string(),
                    resolved: false,
                    choice: None,
                    message: None,
                });
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
    })
}

pub fn task_review_reply(review_id: &str, text: String) -> OpsResult<InteractionReview> {
    let review_id = InteractionReviewId::parse(review_id)
        .map_err(|error| task_error(format!("invalid interaction review: {error}")))?;
    block_on_task(async move {
        let store = task_store().await?;
        let review = store
            .get_interaction_review(&review_id)
            .await
            .map_err(|error| task_error(error.to_string()))?
            .ok_or_else(|| task_error(format!("interaction review {review_id} not found")))?;
        let ambient = std::env::var("LF_TASK_SESSION_ID").map_err(|_| {
            task_error("interaction review replies must run inside the reviewed Task Session")
        })?;
        if ambient != review.task_session_id.as_str() {
            return Err(task_error(format!(
                "Task Session {ambient} cannot reply to review {review_id} for {}",
                review.task_session_id
            )));
        }
        let lease = task_write_lease_from_env()
            .map_err(|error| task_error(format!("Task body has no write authority: {error}")))?;
        store
            .reply_to_interaction_review(&review_id, &review.task_session_id, &lease, &text)
            .await
            .map_err(|error| task_error(error.to_string()))?;
        store
            .get_interaction_review(&review_id)
            .await
            .map_err(|error| task_error(error.to_string()))?
            .ok_or_else(|| task_error(format!("interaction review {review_id} disappeared")))
    })
}

/// An agent session is named by its session id, and only by that. `LF_RUN_ID`
/// and `LF_PROCESS_ID` name a *run* — the journal mints both into this
/// process's own environment when any top-level `lf` command starts, so a guard
/// that reads them refuses the human CLI it exists to serve, whenever it reads.
fn _require_human_review_authority() -> OpsResult<()> {
    for variable in ["LF_TASK_SESSION_ID", "LF_PROJECT_SESSION_ID", "LF_WAVE_ID"] {
        if std::env::var_os(variable).is_some() {
            return Err(task_error(
                "human review commands cannot run inside a Task, Project, or Wave agent session",
            ));
        }
    }
    Ok(())
}

pub fn task_review_message(review_id: &str, text: String) -> OpsResult<InteractionReview> {
    _require_human_review_authority()?;
    let review_id = InteractionReviewId::parse(review_id)
        .map_err(|error| task_error(format!("invalid interaction review: {error}")))?;
    block_on_task(async move {
        let store = task_store().await?;
        store
            .send_human_interaction_review_message(&review_id, ChildCommandSource::Human, &text)
            .await
            .map_err(|error| task_error(error.to_string()))?;
        store
            .get_interaction_review(&review_id)
            .await
            .map_err(|error| task_error(error.to_string()))?
            .ok_or_else(|| task_error(format!("interaction review {review_id} disappeared")))
    })
}

pub fn task_review_complete(
    review_id: &str,
    disposition: &str,
    outcome: String,
) -> OpsResult<InteractionReview> {
    _require_human_review_authority()?;
    let review_id = InteractionReviewId::parse(review_id)
        .map_err(|error| task_error(format!("invalid interaction review: {error}")))?;
    let disposition = disposition
        .replace('-', "_")
        .parse::<InteractionReviewDisposition>()
        .map_err(|error| task_error(error.to_string()))?;
    block_on_task(async move {
        let store = task_store().await?;
        store
            .complete_human_interaction_review(&review_id, disposition, &outcome)
            .await
            .map_err(|error| task_error(error.to_string()))
            .map(|(review, _)| review)
    })
}

pub fn task_acknowledge(issue: &str, version: u32, summary: String) -> OpsResult<ChildDirective> {
    let summary = summary.trim().to_string();
    if summary.is_empty() {
        return Err(task_error(
            "directive acknowledgement summary cannot be empty",
        ));
    }
    block_on_task(async move {
        let store = task_store().await?;
        let session = store
            .get_task_session_by_issue(issue)
            .await
            .map_err(|error| task_error(format!("failed to resolve task: {error}")))?
            .ok_or_else(|| task_error(format!("no Task Session exists for {issue:?}")))?;
        let ambient = std::env::var("LF_TASK_SESSION_ID").map_err(|_| {
            task_error("directive acknowledgements must run inside the owning Task Session")
        })?;
        if ambient != session.id.as_str() {
            return Err(task_error(format!(
                "Task Session {ambient} cannot acknowledge a directive for {}",
                session.id
            )));
        }
        let lease = task_write_lease_from_env()
            .map_err(|error| task_error(format!("Task body has no write authority: {error}")))?;
        let (directive, incorporated) = store
            .incorporate_child_directive_for_lease(
                &ChildRef::Task(session.id.clone()),
                &lease,
                version,
                &summary,
            )
            .await
            .map_err(|error| task_error(format!("failed to acknowledge directive: {error}")))?;
        if incorporated {
            store
                .append_task_event_for_lease(
                    &session.id,
                    &lease,
                    &TaskEventKind::DirectiveIncorporated {
                        directive_id: directive.id.clone(),
                        version,
                        summary,
                    },
                )
                .await
                .map_err(|error| task_error(error.to_string()))?;
        }
        Ok(directive)
    })
}

/// What a reconciliation settled: the now-terminal Session, who attested the
/// directive, and the persisted recovery commands cleared in place.
#[derive(Debug, Clone)]
pub struct TaskReconcileResult {
    pub session: TaskSession,
    pub attested_by: ChildCommandSource,
    pub cleared_commands: Vec<ChildCommandId>,
}

/// Terminalize every still-`Persisted` command for a Task that has settled
/// terminal — they can never be delivered. Each row moves to `failed` in place;
/// no new or superseding command is created. Returns the ids cleared.
async fn reject_orphaned_persisted_commands(
    store: &SharedStore,
    session: &TaskSession,
    reason: &str,
) -> OpsResult<Vec<ChildCommandId>> {
    let commands = store
        .list_child_commands(&ChildRef::Task(session.id.clone()))
        .await
        .map_err(|error| task_error(format!("failed to read Task commands: {error}")))?;
    let mut cleared = Vec::new();
    for command in commands
        .into_iter()
        .filter(|command| command.state == ChildCommandState::Persisted)
    {
        store
            .reject_persisted_child_command(&command.id, reason.to_string())
            .await
            .map_err(|error| task_error(format!("failed to clear orphaned command: {error}")))?;
        cleared.push(command.id);
    }
    Ok(cleared)
}

/// Settle a merged, Linear-complete Task whose final directive was applied but
/// never incorporated, by an explicit out-of-band Wave/Operator attestation.
///
/// The predicates (`applied_at`, merged `CompleteTask`, no active body) only
/// decide whether reconciliation is *permitted*. The incorporation *evidence* is
/// the caller's attestation: they name the exact current directive version and a
/// non-empty semantic summary, and that summary becomes the incorporated summary.
/// This never impersonates the Task (no `LF_TASK_SESSION_ID`, no body lease),
/// never launches a provider or rotates a PR, and clears the orphaned persisted
/// recovery command in place rather than queuing a duplicate.
pub fn task_reconcile(
    issue: &str,
    authority: CallerAuthority,
    version: u32,
    summary: String,
) -> OpsResult<TaskReconcileResult> {
    let summary = summary.trim().to_string();
    if summary.is_empty() {
        return Err(task_error("reconciliation summary cannot be empty"));
    }
    block_on_task(async move {
        let store = task_store().await?;
        let mut session = store
            .get_task_session_by_issue(issue)
            .await
            .map_err(|error| task_error(format!("failed to resolve task: {error}")))?
            .ok_or_else(|| task_error(format!("no Task Session exists for {issue:?}")))?;

        // Authority: only an Operator or the owning Wave may attest the semantic
        // handoff. A Project is the automatic actor — it may recommend Reconcile
        // or consume a durable attestation, but never *create* one, or the
        // attestation would be a machine-authored receipt of adoption that never
        // happened.
        if matches!(authority, CallerAuthority::Project(_)) {
            return Err(task_error(format!(
                "Task {} reconciliation must be attested by an operator or the owning Wave, \
                 not a Project Session; a Project may recommend it, never create the attestation",
                session.launch.issue.identifier
            )));
        }
        let attested_by = validate_task_caller_authority(&store, &session, &authority).await?;

        // Reconcile PR and body state from ground truth first so a stale local row
        // cannot pass the merged/complete or no-active-body guards.
        reconcile_task_pr(&store, &mut session).await?;
        reconcile_process_liveness(&store, &mut session).await?;

        // Idempotent: an already-settled Task needs no reconciliation. Still clear
        // any orphaned persisted command so a retry converges.
        if session.status.is_terminal() {
            let cleared = reject_orphaned_persisted_commands(
                &store,
                &session,
                &format!(
                    "Task already {}; reconciliation is moot",
                    session.status.as_str()
                ),
            )
            .await?;
            return Ok(TaskReconcileResult {
                session,
                attested_by,
                cleared_commands: cleared,
            });
        }

        // --- Guards. Each refusal names the exact failing condition. ---
        if version != session.current_directive_version {
            return Err(task_error(format!(
                "Task {} is at directive v{}; reconcile must name the exact current directive (got v{version})",
                session.launch.issue.identifier, session.current_directive_version
            )));
        }
        // Applied delivery: a body actually ran under the current directive. This
        // is proof of delivery, never of incorporation — the attestation carries
        // the latter.
        let directive = current_directive(&store, &session)
            .await?
            .ok_or_else(|| task_error("Task Session has no current directive"))?;
        if directive.applied_at.is_none() {
            return Err(task_error(format!(
                "Task {} directive v{version} was never delivered to a body; it needs a provider turn, not reconciliation",
                session.launch.issue.identifier
            )));
        }
        // No active body: reconcile only settles a dead Session.
        if session.status.is_process_active() {
            return Err(task_error(format!(
                "Task {} still has an active body ({}); reconcile only settles an inactive Session",
                session.launch.issue.identifier,
                session.status.as_str()
            )));
        }
        if let Some(process) = session.latest_process.as_ref() {
            if tmux_session_exists(&process.tmux_name)
                .await
                .map_err(|error| task_error(format!("failed to inspect Task body: {error}")))?
            {
                return Err(task_error(format!(
                    "Task {} body process is still live; reconcile only settles a dead body",
                    session.launch.issue.identifier
                )));
            }
        }
        // Shipped work: a merged `CompleteTask` PR and nothing still open. This is
        // necessary but not sufficient — the publication is only an intent.
        if store
            .active_task_pr(&session.id)
            .await
            .map_err(|error| task_error(format!("failed to read active PR: {error}")))?
            .is_some()
        {
            return Err(task_error(format!(
                "Task {} still has an active pull request; settle it before reconciling",
                session.launch.issue.identifier
            )));
        }
        let prs = store
            .task_prs(&session.id)
            .await
            .map_err(|error| task_error(format!("failed to read Task PRs: {error}")))?;
        // The settled PR set must be reconcilable: no non-abandoned PR still in
        // flight, and the latest non-abandoned PR merged in any disposition
        // (`Review` or `CompleteTask`). A trailing abandoned unpublished successor
        // is ignored; a later non-abandoned open/unmerged Review still refuses.
        // Looser than automatic completion by design — the attestation and the
        // Linear-complete proof below carry the truth the newest merge cannot.
        if !reconcilable_pr_set(&prs) {
            return Err(task_error(format!(
                "Task {} has no settled merge to reconcile; its latest non-abandoned pull request \
                 has not merged, or a non-abandoned PR is still in flight. Reconcile settles only a \
                 Task whose latest non-abandoned PR has merged",
                session.launch.issue.identifier
            )));
        }
        // Linear-complete: the owning team's issue is *actually* in a completed
        // state. A `CompleteTask` publication is only an intent, and its write can
        // fail (ENG-29/ENG-75), so prove completion by observing the issue itself
        // rather than trusting the PR. Fail closed if Linear cannot be reached.
        //
        // The PM/GOAL root is the Wave's canonical repo, never `session.worktree`:
        // this command targets old, merged, dead Tasks whose worker worktree may
        // already be pruned, and PM ownership is Wave-durable.
        let wave = owning_wave(&store, &session).await?;
        let linear_complete = crate::ops::task_pm::issue_is_complete(
            Path::new(wave.repo()),
            wave.name(),
            session.launch.issue.id.as_str(),
        )
        .await
        .map_err(|error| {
            task_error(format!(
                "cannot confirm Task {} is Linear-complete: {error}",
                session.launch.issue.identifier
            ))
        })?;
        if !linear_complete {
            return Err(task_error(format!(
                "Task {} is not Linear-complete; its owning-team issue is not in a completed state. \
                 A merged CompleteTask publication is only an intent — reconcile requires the \
                 completion to have actually landed",
                session.launch.issue.identifier
            )));
        }

        // --- Record the attestation AS the incorporation evidence. Out-of-band:
        // no lease, no LF_TASK_SESSION_ID. The operator's summary becomes the
        // incorporated summary; a distinct `DirectiveReconciled` event names who
        // attested, so the trail never reads as a forged body acknowledgement. ---
        if has_pending_directive(&session) {
            let (incorporated_directive, incorporated) = store
                .incorporate_child_directive(&ChildRef::Task(session.id.clone()), version, &summary)
                .await
                .map_err(|error| {
                    task_error(format!(
                        "failed to record reconciliation attestation: {error}"
                    ))
                })?;
            if incorporated {
                append_task_event_with_authority(
                    &store,
                    &session.id,
                    &TaskEventKind::DirectiveReconciled {
                        directive_id: incorporated_directive.id.clone(),
                        version,
                        summary: summary.clone(),
                        attested_by: attested_by.clone(),
                    },
                    None,
                )
                .await
                .map_err(|error| task_error(error.to_string()))?;
            }
            // Re-read so `incorporated_directive_version` reflects the attestation
            // before the completion gate re-evaluates it.
            session = store
                .get_task_session(&session.id)
                .await
                .map_err(|error| task_error(format!("failed to reread Task Session: {error}")))?
                .ok_or_else(|| task_error("Task Session disappeared during reconciliation"))?;
        }

        // Complete out-of-band. The pending-directive blocker is now clear.
        let completion_summary =
            format!("reconciled: directive v{version} incorporated by out-of-band attestation");
        settle_completed_session(&store, &mut session, None, completion_summary).await?;

        // Clear the orphaned persisted recovery command(s) in place — no duplicate.
        let cleared = reject_orphaned_persisted_commands(
            &store,
            &session,
            &format!("Task reconciled and completed out of band; directive v{version} attested"),
        )
        .await?;

        Ok(TaskReconcileResult {
            session,
            attested_by,
            cleared_commands: cleared,
        })
    })
}

pub fn task_abandon(
    issue: &str,
    authority: CallerAuthority,
    reason: String,
) -> OpsResult<TaskControlResult> {
    let reason = reason.trim();
    if reason.is_empty() {
        return Err(task_error("`lf task abandon --reason` cannot be empty"));
    }
    queue_command(
        issue,
        authority,
        ChildCommandKind::Abandon {
            reason: reason.to_string(),
        },
    )
}

pub fn task_wait(
    issue: &str,
    until: TaskWaitUntil,
    timeout: Option<Duration>,
) -> OpsResult<TaskSession> {
    let started = Instant::now();
    loop {
        let session = task_status(issue)?;
        let reached = match until {
            TaskWaitUntil::Open => {
                session.status.is_terminal()
                    || active_pr(&session).is_ok_and(|pr| pr.phase() == PrPhase::Open)
            }
            TaskWaitUntil::Terminal => session.status.is_terminal(),
        };
        if reached || timeout.is_some_and(|limit| started.elapsed() >= limit) {
            return Ok(session);
        }
        std::thread::sleep(Duration::from_secs(1));
    }
}

pub fn task_attach(issue: &str) -> OpsResult<()> {
    let session = task_status(issue)?;
    if !session.status.is_process_active() {
        return Err(task_error(format!(
            "task {} is {}; resume it before attaching",
            session.launch.issue.identifier,
            session.status.as_str()
        )));
    }
    let tmux_name = session
        .latest_process
        .as_ref()
        .map(|process| process.tmux_name.as_str())
        .filter(|name| !name.is_empty())
        .ok_or_else(|| task_error("task has no attachable process; resume it first"))?;
    let status = std::process::Command::new("tmux")
        .args(["attach-session", "-t", tmux_name])
        .status()
        .map_err(|error| task_error(format!("failed to attach to task: {error}")))?;
    if !status.success() {
        return Err(task_error(format!("tmux attach failed for {tmux_name}")));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::ffi::OsString;
    use std::io::{BufRead, BufReader};
    use std::os::unix::fs::PermissionsExt;
    use std::os::unix::process::CommandExt;
    use std::path::Path;
    use std::process::Command;
    use std::sync::Arc;
    use std::time::Duration;

    use super::{
        _defer_task_interactions, _recover_abandoned_task, advance_completion_after_gate,
        cached_github_observation, changes_snapshot, count_recovery_attempts, current_directive,
        decide_open_pr_status, derive_workspace_slug, diff_snapshot, ensure_working_pr,
        ensure_working_pr_with_authority, file_snapshot, latest_pr_completes_task, next_pr_slug,
        owning_wave, parse_pr_slug, parse_workspace_slug, project_context, reconcilable_pr_set,
        reconcile_process_liveness, reconcile_project_tasks, reconcile_task_pr,
        recover_stalled_task_body, recover_stranded_task_body, refuse_dirty_between_prs,
        refuse_if_canonical_ahead, require_task_pr_range_nonempty_with_authority,
        resolve_task_flow, resolve_upstream_base, resume_task_async, succession_workspace_slug,
        supervise_project_task_bodies, task_reconcile, task_recovery_adoption, task_snapshot,
        unpublished_work, verify_task_pr_range_with_authority, CommittedFollowUp, RotateOptions,
        TaskControlResult, TaskRecoveryAdoption, TaskWorkspace,
    };
    use crate::child_session::{
        observe, BodyEvidence, BodyIntent, CallerAuthority, ChildBodyOutcome, ChildCommand,
        ChildCommandId, ChildCommandKind, ChildCommandSource, ChildCommandState, ChildDirective,
        ChildDirectiveId, ChildLeaseState, ChildProcessGeneration, ChildRef, ChildWriteLease,
        DirectiveKind, MAX_RECOVERY_ATTEMPTS,
    };
    use crate::engine::git::is_ancestor;
    use crate::id::WaveId;
    use crate::pm::{PmKr, PmProject};
    use crate::project_session::{ProjectSession, ProjectSessionId, ProjectSessionStatus};
    use crate::session_context::{
        LinearIssueId, LinearIssueSnapshot, LinearProjectId, LinearProjectSnapshot,
        ProjectLaunchReceipt, TaskLaunchReceipt,
    };
    use crate::store::{open_store, SharedStore, StorageConfig};
    use crate::task::actions::TaskAction;
    use crate::task::{
        AfterMerge, CiCheck, CiObservation, CiState, GithubObservation, GithubObservationResult,
        GithubPr, Observation, PmWritebackState, PrPhase, PrPublication, TaskEventKind, TaskPr,
        TaskPrId, TaskSession, TaskSessionId, TaskSessionStatus,
    };
    use crate::wave::Wave;
    use loopflow_test_support::TestRepo;
    use time::OffsetDateTime;

    fn git(repo: &Path, args: &[&str]) -> String {
        let output = Command::new("git")
            .current_dir(repo)
            .args(args)
            .output()
            .expect("run git");
        assert!(
            output.status.success(),
            "git {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&output.stderr)
        );
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    }

    struct TaskLaunchEnv {
        previous: Vec<(&'static str, Option<OsString>)>,
        _bin: tempfile::TempDir,
    }

    impl TaskLaunchEnv {
        fn install(home: &Path) -> Self {
            let bin = tempfile::tempdir().expect("fake tmux bin");
            let tmux = bin.path().join("tmux");
            std::fs::write(
                &tmux,
                "#!/bin/sh\nif [ \"$1\" = \"list-sessions\" ]; then printf 'lf-live-idle-control\\n'; fi\nexit 0\n",
            )
            .expect("write fake tmux");
            let mut permissions = std::fs::metadata(&tmux)
                .expect("stat fake tmux")
                .permissions();
            permissions.set_mode(0o755);
            std::fs::set_permissions(&tmux, permissions).expect("make fake tmux executable");

            let keys = [
                "PATH",
                "LF_BIN",
                "LF_HOME",
                "LF_DB_PATH",
                "LF_CONTROL_BIN",
                "LF_CONTROL_HOME",
                "LF_CONTROL_DB_PATH",
                crate::provider_account::lease::ACCOUNT_LEASE_ENV,
            ];
            let previous = keys
                .into_iter()
                .map(|key| (key, std::env::var_os(key)))
                .collect::<Vec<_>>();
            let path = std::env::var_os("PATH").map_or_else(
                || bin.path().as_os_str().to_os_string(),
                |path| {
                    let mut paths = vec![bin.path().to_path_buf()];
                    paths.extend(std::env::split_paths(&path));
                    std::env::join_paths(paths).expect("join fake tmux PATH")
                },
            );
            let db = home.join("loopflow.db");
            std::env::set_var("PATH", path);
            std::env::set_var("LF_BIN", "/usr/bin/true");
            std::env::set_var("LF_HOME", home);
            std::env::set_var("LF_DB_PATH", &db);
            std::env::set_var("LF_CONTROL_BIN", "/usr/bin/true");
            std::env::set_var("LF_CONTROL_HOME", home);
            std::env::set_var("LF_CONTROL_DB_PATH", db);
            std::env::remove_var(crate::provider_account::lease::ACCOUNT_LEASE_ENV);
            Self {
                previous,
                _bin: bin,
            }
        }
    }

    impl Drop for TaskLaunchEnv {
        fn drop(&mut self) {
            for (key, value) in self.previous.drain(..) {
                match value {
                    Some(value) => std::env::set_var(key, value),
                    None => std::env::remove_var(key),
                }
            }
        }
    }

    /// Point the store at a temp home, and nothing else. Tests that only read
    /// persisted state must not borrow `TaskLaunchEnv`: it puts a fake tmux on
    /// the process-global `PATH`, which reads as a live body to any concurrent
    /// test resolving tmux.
    struct StoreEnvGuard {
        _lock: std::sync::MutexGuard<'static, ()>,
        previous: Vec<(&'static str, Option<OsString>)>,
    }

    impl StoreEnvGuard {
        fn new(home: &Path) -> Self {
            let lock = crate::journal::test_env_lock();
            let names = [
                "LF_HOME",
                "LF_DB_PATH",
                crate::store::CONTROL_HOME_ENV,
                crate::store::CONTROL_DB_PATH_ENV,
            ];
            let previous = names
                .into_iter()
                .map(|name| (name, std::env::var_os(name)))
                .collect();
            std::env::set_var("LF_HOME", home);
            std::env::set_var("LF_DB_PATH", home.join("loopflow.db"));
            std::env::remove_var(crate::store::CONTROL_HOME_ENV);
            std::env::remove_var(crate::store::CONTROL_DB_PATH_ENV);
            Self {
                _lock: lock,
                previous,
            }
        }
    }

    impl Drop for StoreEnvGuard {
        fn drop(&mut self) {
            for (name, value) in &self.previous {
                match value {
                    Some(value) => std::env::set_var(name, value),
                    None => std::env::remove_var(name),
                }
            }
        }
    }

    #[test]
    fn task_flow_selection_accepts_skill_flows_and_rejects_ops() {
        let repo = tempfile::tempdir().unwrap();
        assert_eq!(
            resolve_task_flow(repo.path(), Some("code")).unwrap(),
            "code"
        );
        let error = resolve_task_flow(repo.path(), Some("deploy")).unwrap_err();
        assert!(error
            .to_string()
            .contains("durable Task flows currently require skills"));
    }

    /// The launch resolver ignores `LF_CONTROL_BIN`. A legacy body carries
    /// `LF_CONTROL_BIN` pointing at the (real, existing) binary that created it;
    /// launch must not relaunch through it. Here `LF_CONTROL_BIN` names a real
    /// binary while the current Home `LF_BIN` is gone: the launch fails at
    /// binary resolution, proving the control pin was never consulted (had it
    /// been, resolution would have succeeded through the real control binary).
    #[tokio::test]
    async fn launch_task_process_ignores_control_bin_and_resolves_current_home() {
        let home = tempfile::tempdir().unwrap();
        let store: SharedStore = Arc::new(
            open_store(&StorageConfig::sqlite(home.path().join("loopflow.db")))
                .await
                .unwrap(),
        );
        let now = OffsetDateTime::now_utc();
        let mut session = TaskSession {
            id: TaskSessionId::new(),
            launch: TaskLaunchReceipt {
                issue: LinearIssueSnapshot {
                    id: LinearIssueId::new("issue-no-pin").unwrap(),
                    identifier: "INF-NO-PIN".to_string(),
                    title: "Resolve through current lf".to_string(),
                    description: "Never read the pinned binary".to_string(),
                },
                project: LinearProjectSnapshot {
                    id: LinearProjectId::new("project-no-pin").unwrap(),
                    slug: "no-pin".to_string(),
                    name: "No pin".to_string(),
                    prompt_context: String::new(),
                },
                pm_snapshot_synced_at: now.unix_timestamp(),
            },
            pm_writeback: PmWritebackState::Current,
            wave_id: WaveId::new(),
            project_session_id: ProjectSessionId::new(),
            current_directive_version: 0,
            incorporated_directive_version: 0,
            status: TaskSessionStatus::Waiting,
            status_reason: "ready".to_string(),
            status_at: now,
            worktree: home.path().join("worktree"),
            workspace_slug: "task-no-pin".to_string(),
            lifecycle: crate::task::TaskLifecyclePlan::standard("task"),
            lifecycle_phase: crate::task::TaskLifecyclePhase::Iterate,
            phase_epoch: 1,
            phase_cursor: 0,
            phase_iteration: 0,
            gate_cycle: 0,
            gate_proposal: None,
            agent: "codex".to_string(),
            provider: "codex".to_string(),
            provider_session_id: None,
            latest_process: None,
            abandon_intent: None,
            created_at: now,
            updated_at: now,
            observation: crate::task::Observation::NotRequired,
        };

        // LF_CONTROL_BIN names a real, existing binary (the historical pin);
        // the current Home LF_BIN is gone. The launch must fail at resolution
        // without burning a generation or spawning tmux.
        let previous_control_bin = std::env::var_os("LF_CONTROL_BIN");
        let previous_lf_bin = std::env::var_os("LF_BIN");
        std::env::set_var("LF_CONTROL_BIN", "/bin/sh");
        std::env::set_var("LF_BIN", "/loopflow-test/does-not-exist/lf");
        let result = super::launch_task_process(&store, &mut session).await;
        match previous_lf_bin {
            Some(value) => std::env::set_var("LF_BIN", value),
            None => std::env::remove_var("LF_BIN"),
        }
        match previous_control_bin {
            Some(value) => std::env::set_var("LF_CONTROL_BIN", value),
            None => std::env::remove_var("LF_CONTROL_BIN"),
        }

        let error = result.expect_err("launch must fail when the current Home lf is missing");
        assert!(
            error
                .to_string()
                .contains("cannot resolve current lf binary"),
            "launch must resolve the current Home lf, not the LF_CONTROL_BIN pin: {error}"
        );
        // No generation was reserved: the session never started a process.
        assert!(session.latest_process.is_none());
    }

    fn changed_workspace() -> (tempfile::TempDir, String, TaskSessionId) {
        let repo = tempfile::tempdir().expect("create temp repo");
        git(repo.path(), &["init", "-b", "main"]);
        git(repo.path(), &["config", "user.name", "Loopflow Test"]);
        git(
            repo.path(),
            &["config", "user.email", "loopflow@example.com"],
        );
        std::fs::write(repo.path().join("tracked.txt"), "base\n").expect("write base");
        git(repo.path(), &["add", "tracked.txt"]);
        git(repo.path(), &["commit", "-m", "base"]);
        let base = git(repo.path(), &["rev-parse", "HEAD"]);

        std::fs::write(repo.path().join("committed.txt"), "committed\n")
            .expect("write committed file");
        git(repo.path(), &["add", "committed.txt"]);
        git(repo.path(), &["commit", "-m", "task commit"]);
        std::fs::write(repo.path().join("tracked.txt"), "staged\n").expect("write staged");
        git(repo.path(), &["add", "tracked.txt"]);
        std::fs::write(repo.path().join("tracked.txt"), "unstaged\n").expect("write unstaged");
        std::fs::write(repo.path().join("untracked.txt"), "untracked\n").expect("write untracked");

        (repo, base, TaskSessionId::new())
    }

    async fn rotation_task(
        repo: &TestRepo,
        branch: &str,
        base_commit: &str,
    ) -> (tempfile::TempDir, SharedStore, TaskSession, TaskPr) {
        rotation_task_with_lease(repo, branch, base_commit, None).await
    }

    /// Like `rotation_task`, but optionally seeds a dead lease + status — the
    /// shape an explicit resume must reconcile before reaping the lease and
    /// launching a successor. The worktree stays the real `repo.path()`.
    async fn rotation_task_with_lease(
        repo: &TestRepo,
        branch: &str,
        base_commit: &str,
        lease: Option<(
            crate::child_session::ChildLeaseState,
            TaskSessionStatus,
            Option<ChildBodyOutcome>,
        )>,
    ) -> (tempfile::TempDir, SharedStore, TaskSession, TaskPr) {
        let home = tempfile::tempdir().expect("task home");
        let store = Arc::new(
            open_store(&StorageConfig::sqlite(home.path().join("loopflow.db")))
                .await
                .expect("open store"),
        );
        let now = OffsetDateTime::now_utc();
        let lease_seed = lease.map(|(state, status, outcome)| {
            (
                status,
                ChildProcessGeneration {
                    generation: 1,
                    pid: None,
                    process_group_id: None,
                    // A name no tmux server knows, so the liveness probe reads
                    // it as dead.
                    tmux_name: format!("dead-lease-{}", WaveId::new()),
                    agent: "codex".to_string(),
                    provider: "codex".to_string(),
                    provider_session_id: None,
                    started_at: now - time::Duration::hours(1),
                    state,
                    outcome,
                    provenance: None,
                },
            )
        });
        let wave = Wave::new(
            WaveId::new(),
            "task-pr-rotation".to_string(),
            repo.path().display().to_string(),
        );
        let project = ProjectSession {
            id: ProjectSessionId::new(),
            launch: ProjectLaunchReceipt {
                project: LinearProjectSnapshot {
                    id: LinearProjectId::new(format!("project-{}", WaveId::new()))
                        .expect("project id"),
                    slug: "task-pr-rotation".to_string(),
                    name: "Task PR rotation".to_string(),
                    prompt_context: "Keep one stable worktree.".to_string(),
                },
                pm_snapshot_synced_at: now.unix_timestamp(),
            },
            wave_id: wave.id().clone(),
            current_directive_version: 0,
            incorporated_directive_version: 0,
            status: ProjectSessionStatus::Running,
            status_reason: "test project is running".to_string(),
            status_at: now,
            iteration: 1,
            observation_cursor: 0,
            last_state_fingerprint: None,
            agent: "codex".to_string(),
            provider: "codex".to_string(),
            provider_session_id: Some("task-pr-rotation".to_string()),
            latest_process: Some(ChildProcessGeneration {
                generation: 1,
                pid: None,
                process_group_id: None,
                tmux_name: "task-pr-rotation".to_string(),
                agent: "codex".to_string(),
                provider: "codex".to_string(),
                provider_session_id: Some("task-pr-rotation".to_string()),
                started_at: now,
                state: crate::child_session::ChildLeaseState::Active,
                outcome: None,
                provenance: None,
            }),
            abandon_intent: None,
            created_at: now,
            updated_at: now,
        };
        let session = TaskSession {
            id: TaskSessionId::new(),
            launch: TaskLaunchReceipt {
                issue: LinearIssueSnapshot {
                    id: LinearIssueId::new(format!("issue-{}", WaveId::new())).expect("issue id"),
                    identifier: "INF-ROTATE".to_string(),
                    title: "Rotate Task PRs".to_string(),
                    description: "Keep the worktree stable.".to_string(),
                },
                project: project.launch.project.clone(),
                pm_snapshot_synced_at: now.unix_timestamp(),
            },
            pm_writeback: PmWritebackState::Current,
            wave_id: wave.id().clone(),
            project_session_id: project.id.clone(),
            current_directive_version: 0,
            incorporated_directive_version: 0,
            status: lease_seed
                .as_ref()
                .map(|(status, _)| *status)
                .unwrap_or(TaskSessionStatus::Waiting),
            status_reason: if lease_seed.is_some() {
                "recovered from a vanished body".to_string()
            } else {
                "first PR settled".to_string()
            },
            status_at: now,
            worktree: repo.path().to_path_buf(),
            workspace_slug: "task-pr-proof".to_string(),
            lifecycle: crate::task::TaskLifecyclePlan::standard("task"),
            lifecycle_phase: crate::task::TaskLifecyclePhase::Iterate,
            phase_epoch: 1,
            phase_cursor: 0,
            phase_iteration: 0,
            gate_cycle: 0,
            gate_proposal: None,
            agent: "codex".to_string(),
            provider: "codex".to_string(),
            provider_session_id: None,
            latest_process: lease_seed.map(|(_, process)| process),
            abandon_intent: None,
            created_at: now,
            updated_at: now,
            observation: crate::task::Observation::NotRequired,
        };
        let pr = TaskPr {
            id: TaskPrId::new(),
            task_session_id: session.id.clone(),
            sequence: 1,
            slug: session.workspace_slug.clone(),
            branch: branch.to_string(),
            base_commit: base_commit.to_string(),
            parent_pr_id: None,
            publication: None,
            merge_commit: None,
            abandoned_at: None,
            created_at: now,
            updated_at: now,
            ci_observation: None,
            github_observation: None,
            linear_attachment_id: None,
            linear_comment_id: None,
            linear_link_error: None,
        };
        store.create_wave(&wave).await.expect("create wave");
        store
            .create_project_session(&project)
            .await
            .expect("create project");
        store
            .create_task_session(&session, &pr)
            .await
            .expect("create Task");
        (home, store, session, pr)
    }

    async fn parked_gate_task(
        repo: &TestRepo,
        branch: &str,
        ci_state: Option<CiState>,
        phase_cursor: u32,
    ) -> (
        tempfile::TempDir,
        SharedStore,
        ProjectSession,
        TaskSession,
        TaskPr,
    ) {
        let base = repo.head_sha();
        repo.create_branch(branch);
        let (home, store, session, mut pr) =
            gate_task_fixture(repo, branch, &base, false, phase_cursor).await;
        let project = store
            .get_project_session(&session.project_session_id)
            .await
            .expect("read Project")
            .expect("Project exists");
        let now = OffsetDateTime::now_utc();
        let head = repo.head_sha();

        pr.publication = Some(PrPublication {
            requested_at: now,
            after_merge: AfterMerge::Review,
            next_slug: None,
            github: Some(GithubPr {
                number: 1054,
                url: "https://github.com/loopflowstudio/loopflow/pull/1054".to_string(),
                head_sha: Some(head.clone()),
            }),
        });
        pr.github_observation = Some(GithubObservation {
            checked_at: now,
            result: GithubObservationResult::Fresh,
        });
        pr.ci_observation = ci_state.map(|state| CiObservation {
            head_sha: head,
            state,
            failing_checks: if state == CiState::Failing {
                vec![CiCheck {
                    name: "rust-test".to_string(),
                    url: Some("https://ci.example/rust-test".to_string()),
                }]
            } else {
                Vec::new()
            },
            observed_at: now,
        });
        pr.updated_at = now;
        store.update_task_pr(&pr).await.expect("publish fixture PR");
        if let Some(incident) = super::current_ci_incident(&pr) {
            store
                .observe_ci_incident(&incident)
                .await
                .expect("record failing CI incident");
        }

        (home, store, project, session, pr)
    }

    /// Settle a rotation Task PR as merged, optionally recording a `next_slug`.
    async fn settle_pr(store: &SharedStore, mut pr: TaskPr, merge: &str, next_slug: Option<&str>) {
        pr.publication = Some(PrPublication {
            requested_at: OffsetDateTime::now_utc(),
            after_merge: AfterMerge::Review,
            next_slug: next_slug.map(str::to_string),
            github: Some(GithubPr {
                number: 900,
                url: "https://example.com/pr/900".to_string(),
                head_sha: None,
            }),
        });
        pr.merge_commit = Some(merge.to_string());
        pr.updated_at = OffsetDateTime::now_utc();
        store.settle_task_pr(&pr, None).await.expect("settle PR");
    }

    async fn settle_completing_pr(store: &SharedStore, mut pr: TaskPr, merge: &str) {
        pr.publication = Some(PrPublication {
            requested_at: OffsetDateTime::now_utc(),
            after_merge: AfterMerge::CompleteTask,
            next_slug: None,
            github: Some(GithubPr {
                number: 1037,
                url: "https://example.com/pr/1037".to_string(),
                head_sha: None,
            }),
        });
        pr.merge_commit = Some(merge.to_string());
        pr.updated_at = OffsetDateTime::now_utc();
        store.settle_task_pr(&pr, None).await.expect("settle PR");
    }

    #[tokio::test]
    async fn merged_task_resume_refuses_before_reserving_a_generation() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let branch = "jack/no-doomed-resume";
        repo.create_branch(branch);
        let (home, store, session, pr) = rotation_task(&repo, branch, &base).await;
        settle_completing_pr(&store, pr, "merge-1037").await;
        let _env = StoreEnvGuard::new(home.path());

        let before = store
            .get_task_session(&session.id)
            .await
            .expect("read before")
            .expect("Task exists")
            .latest_process;
        let error = resume_task_async(
            &session.launch.issue.identifier,
            CallerAuthority::Operator,
            None,
            None,
            Some("status recommended Resume".to_string()),
        )
        .await
        .expect_err("merged Task has no active PR to resume");
        let after = store
            .get_task_session(&session.id)
            .await
            .expect("read after")
            .expect("Task exists")
            .latest_process;

        assert_eq!(
            error.to_string(),
            "Task INF-ROTATE has no active PR to resume; pull request #1037 merged"
        );
        assert_eq!(after, before, "a refusal must not reserve a generation");
    }

    #[tokio::test]
    async fn pending_directive_authorizes_a_completing_pr_successor() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let branch = "jack/pending-direction";
        repo.create_branch(branch);
        let (_home, store, mut session, pr) = rotation_task(&repo, branch, &base).await;
        settle_completing_pr(&store, pr, "merge-pending").await;
        session.current_directive_version = 2;
        session.incorporated_directive_version = 1;

        let next =
            ensure_working_pr_with_authority(&store, &mut session, None, RotateOptions::runner())
                .await
                .expect("pending direction may rotate")
                .expect("serial successor");

        assert_eq!(next.sequence, 2);
        assert_ne!(next.branch, branch);
    }

    #[test]
    fn merged_snapshot_routes_the_persisted_directive_gate() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let branch = "jack/persisted-action-proof";
        repo.create_branch(branch);
        let runtime = tokio::runtime::Runtime::new().expect("test runtime");
        let (home, expected_complete_refusal, session) = runtime.block_on(async {
            let (home, store, mut session, pr) = rotation_task(&repo, branch, &base).await;
            settle_completing_pr(&store, pr, "merge-pending").await;
            session.current_directive_version = 2;
            session.incorporated_directive_version = 1;
            store
                .update_task_session(&session)
                .await
                .expect("persist pending directive");
            let gate = task_completion_gate(&store, &session)
                .await
                .expect("completion gate");
            let refusal = gate
                .refusal(&session.launch.issue.identifier)
                .expect("pending directive refuses completion");
            (home, refusal, session)
        });
        drop(runtime);
        let _env = StoreEnvGuard::new(home.path());

        let snapshot = task_snapshot(&session).expect("snapshot merged Task");
        assert_eq!(snapshot.active_pr, None);
        assert_eq!(snapshot.actions.recommended, Some(TaskAction::StartNextPr));
        assert_eq!(
            snapshot
                .actions
                .status(TaskAction::Complete)
                .expect("Complete action")
                .reason,
            expected_complete_refusal
        );
        assert_eq!(
            snapshot
                .actions
                .status(TaskAction::Resume)
                .expect("Resume action")
                .reason,
            "Task INF-ROTATE has no active PR to resume; pull request #1037 merged"
        );
    }

    /// Force [`crate::ops::task_pm::issue_is_complete`] to a fixed verdict for the
    /// duration of a test, so reconciliation exercises without a live Linear read.
    /// Resets on drop; the env lock its callers hold serializes the global.
    struct LinearCompleteOverride;

    impl LinearCompleteOverride {
        fn set(complete: bool) -> Self {
            crate::ops::task_pm::test_hooks::set_issue_complete_override(Some(complete));
            Self
        }
    }

    impl Drop for LinearCompleteOverride {
        fn drop(&mut self) {
            crate::ops::task_pm::test_hooks::set_issue_complete_override(None);
        }
    }

    /// Build the exact impossible shape ENG-30 fixes: a merged, Linear-complete
    /// Task (`CompleteTask` disposition) whose final directive at `version` was
    /// delivered to a body but never incorporated, with a dead body and an
    /// orphaned `Persisted` recovery command. Hermetic — the merged PR carries a
    /// fresh GitHub observation and a `head_sha` equal to the branch tip, so no
    /// `gh` runs and the completion gate proves no committed follow-up. Returns
    /// `(home, store, session, recovery_command_id)`.
    async fn applied_unincorporated_task(
        repo: &TestRepo,
        branch: &str,
        pr_number: u32,
        version: u32,
        applied: bool,
    ) -> (tempfile::TempDir, SharedStore, TaskSession, ChildCommandId) {
        let base = repo.head_sha();
        repo.create_branch(branch);
        let (home, store, mut session, mut pr) = rotation_task(repo, branch, &base).await;
        let now = OffsetDateTime::now_utc();

        pr.publication = Some(PrPublication {
            requested_at: now,
            after_merge: AfterMerge::CompleteTask,
            next_slug: None,
            github: Some(GithubPr {
                number: pr_number,
                url: format!("https://example.com/pr/{pr_number}"),
                head_sha: Some(base.clone()),
            }),
        });
        pr.merge_commit = Some(format!("merge-{pr_number}"));
        pr.github_observation = Some(GithubObservation {
            checked_at: now,
            result: GithubObservationResult::Fresh,
        });
        pr.updated_at = now;
        store
            .settle_task_pr(&pr, None)
            .await
            .expect("settle merged PR");

        // The final directive: created via a (superseded) steer so the session's
        // current version advances to `version`, optionally marked applied.
        let target = ChildRef::Task(session.id.clone());
        let steer = ChildCommand {
            id: ChildCommandId::new(),
            target: target.clone(),
            source: ChildCommandSource::Human,
            kind: ChildCommandKind::Steer {
                text: format!("final direction v{version}"),
            },
            state: ChildCommandState::Accepted,
            effect: None,
            created_at: now,
            claimed_by_generation: Some(1),
            accepted_at: Some(now),
            error: None,
        };
        let directive = ChildDirective {
            id: ChildDirectiveId::new(),
            target: target.clone(),
            version,
            kind: DirectiveKind::Replacement,
            text: format!("final direction v{version}"),
            source: ChildCommandSource::Human,
            command_id: Some(steer.id.clone()),
            issued_at: now,
            applied_at: None,
            incorporated_at: None,
            incorporated_summary: None,
        };
        store
            .create_child_command_with_directive(&steer, &directive)
            .await
            .expect("seed final directive");
        if applied {
            store
                .mark_child_directive_applied(&target, version)
                .await
                .expect("mark directive applied");
        }

        // The orphaned recovery command: Persisted, never claimed, no generation.
        let recovery = ChildCommand {
            id: ChildCommandId::new(),
            target: target.clone(),
            source: ChildCommandSource::Project(session.project_session_id.clone()),
            kind: ChildCommandKind::Resume {
                message: Some("recover the stranded Task".to_string()),
            },
            state: ChildCommandState::Persisted,
            effect: None,
            created_at: now,
            claimed_by_generation: None,
            accepted_at: None,
            error: None,
        };
        store
            .create_child_command(&recovery)
            .await
            .expect("seed orphaned recovery command");

        // Reflect the applied-but-unincorporated shape: current is `version`,
        // incorporated one behind, a dead body, Waiting.
        session.current_directive_version = version;
        session.incorporated_directive_version = version - 1;
        session.status = TaskSessionStatus::Waiting;
        session.status_reason = "final directive applied; acknowledgement interrupted".to_string();
        session.latest_process = None;
        store
            .update_task_session(&session)
            .await
            .expect("persist reconcilable shape");
        let session = store
            .get_task_session(&session.id)
            .await
            .unwrap()
            .expect("reread session");
        (home, store, session, recovery.id)
    }

    /// The W2-308 reproduction: a merged, complete Task whose applied final
    /// directive (v5) was never acknowledged settles by an operator attestation —
    /// no provider turn, no new PR, orphan recovery command cleared in place.
    #[test]
    fn reconcile_settles_a_merged_task_whose_applied_directive_was_never_acknowledged() {
        let repo = TestRepo::new();
        let runtime = tokio::runtime::Runtime::new().expect("test runtime");
        let (home, store, session, recovery_id) = runtime.block_on(async {
            let (home, store, session, recovery_id) =
                applied_unincorporated_task(&repo, "jack/w2-308", 1064, 5, true).await;
            let project = store
                .get_project_session(&session.project_session_id)
                .await
                .unwrap()
                .expect("project exists");

            // The supervisor recognizes the shape: it must not relaunch a body,
            // rotate a PR, or error — it leaves the Reconcile recommendation.
            reconcile_project_tasks(&store, &project)
                .await
                .expect("supervisor tolerates the reconcilable shape");
            let after = store.get_task_session(&session.id).await.unwrap().unwrap();
            assert_eq!(
                after.status,
                TaskSessionStatus::Waiting,
                "supervisor leaves it awaiting attestation, never settles it hands-off"
            );
            assert_eq!(
                store.task_prs(&session.id).await.unwrap().len(),
                1,
                "no successor PR minted"
            );
            assert!(after.latest_process.is_none(), "no body relaunched");
            (home, store, after, recovery_id)
        });
        drop(runtime);
        let _env = StoreEnvGuard::new(home.path());
        let _linear = LinearCompleteOverride::set(true);

        // Legal-action reporting points at Reconcile, never Resume/StartNextPr.
        let snapshot = task_snapshot(&session).expect("snapshot the reconcilable Task");
        assert_eq!(snapshot.actions.recommended, Some(TaskAction::Reconcile));
        assert!(
            !snapshot
                .actions
                .status(TaskAction::Resume)
                .unwrap()
                .available
        );

        let summary =
            "Directive v5 shipped in the merged head; the acknowledgement turn was interrupted.";
        let result = task_reconcile(
            &session.launch.issue.identifier,
            CallerAuthority::Operator,
            5,
            summary.to_string(),
        )
        .expect("operator attestation settles the Task");

        assert_eq!(result.session.status, TaskSessionStatus::Completed);
        assert_eq!(
            result.cleared_commands,
            vec![recovery_id.clone()],
            "the orphaned Persisted recovery command is cleared in place"
        );

        let runtime = tokio::runtime::Runtime::new().expect("verify runtime");
        runtime.block_on(async {
            let settled = store.get_task_session(&session.id).await.unwrap().unwrap();
            assert_eq!(settled.status, TaskSessionStatus::Completed);
            assert_eq!(settled.incorporated_directive_version, 5);
            let directive = current_directive(&store, &settled)
                .await
                .unwrap()
                .expect("current directive");
            assert!(directive.incorporated_at.is_some());
            assert_eq!(directive.incorporated_summary.as_deref(), Some(summary));
            let recovery = store
                .get_child_command(&recovery_id)
                .await
                .unwrap()
                .expect("recovery command still readable");
            assert_eq!(
                recovery.state,
                ChildCommandState::Failed,
                "orphan terminalized in place, not superseded by a duplicate"
            );
            let events = store.task_events_after(&settled.id, 0).await.unwrap();
            assert!(
                events.iter().any(|event| matches!(
                    &event.kind,
                    TaskEventKind::DirectiveReconciled { version: 5, attested_by, .. }
                        if *attested_by == ChildCommandSource::Human
                )),
                "a DirectiveReconciled event names the out-of-band attester"
            );
            // No new command was created — only the seeded steer + recovery exist.
            let commands = store
                .list_child_commands(&ChildRef::Task(settled.id.clone()))
                .await
                .unwrap();
            assert_eq!(commands.len(), 2, "reconciliation created no command");
        });
    }

    /// The W2-127 reproduction: supervisor-owned work merged as PR #876 while the
    /// provider stayed stopped; the Wave attests directive v2 out of band.
    #[test]
    fn reconcile_settles_w2_127_supervisor_owned_merge() {
        let repo = TestRepo::new();
        let runtime = tokio::runtime::Runtime::new().expect("test runtime");
        let (home, store, session, recovery_id) = runtime.block_on(async {
            applied_unincorporated_task(&repo, "jack/w2-127", 876, 2, true).await
        });
        drop(runtime);
        let _env = StoreEnvGuard::new(home.path());
        let _linear = LinearCompleteOverride::set(true);

        let summary = "Provider stayed stopped; no branch-built lf touched the live registry; \
             supervisor-owned implementation merged as PR #876.";
        let result = task_reconcile(
            &session.launch.issue.identifier,
            CallerAuthority::Operator,
            2,
            summary.to_string(),
        )
        .expect("attestation settles W2-127");

        assert_eq!(result.session.status, TaskSessionStatus::Completed);
        assert_eq!(result.cleared_commands, vec![recovery_id]);

        let runtime = tokio::runtime::Runtime::new().expect("verify runtime");
        runtime.block_on(async {
            let settled = store.get_task_session(&session.id).await.unwrap().unwrap();
            assert_eq!(settled.incorporated_directive_version, 2);
            let directive = current_directive(&store, &settled).await.unwrap().unwrap();
            assert_eq!(directive.incorporated_summary.as_deref(), Some(summary));
        });
    }

    /// Reconcile refuses everything outside its exact shape: an empty summary, a
    /// stale directive version, a Project caller, and a not-yet-applied directive.
    #[test]
    fn reconcile_refuses_outside_its_exact_shape() {
        let repo = TestRepo::new();
        let runtime = tokio::runtime::Runtime::new().expect("test runtime");
        let (home, _store, session, project_id) = runtime.block_on(async {
            let (home, store, session, _rec) =
                applied_unincorporated_task(&repo, "jack/guard-applied", 900, 5, true).await;
            let project_id = session.project_session_id.clone();
            (home, store, session, project_id)
        });
        drop(runtime);
        let _env = StoreEnvGuard::new(home.path());
        let issue = session.launch.issue.identifier.clone();

        let empty = task_reconcile(&issue, CallerAuthority::Operator, 5, "   ".to_string())
            .expect_err("empty summary refused");
        assert!(
            empty.to_string().contains("summary cannot be empty"),
            "{empty}"
        );

        let stale = task_reconcile(&issue, CallerAuthority::Operator, 4, "attest".to_string())
            .expect_err("stale version refused");
        assert!(
            stale.to_string().contains("exact current directive"),
            "{stale}"
        );

        let project = task_reconcile(
            &issue,
            CallerAuthority::Project(project_id),
            5,
            "attest".to_string(),
        )
        .expect_err("a Project may not create the attestation");
        assert!(
            project
                .to_string()
                .contains("must be attested by an operator or the owning Wave"),
            "{project}"
        );
    }

    /// A pending directive that was never *applied* is a post-land steer that
    /// still needs a body: reconcile refuses it, and legal-action reporting keeps
    /// recommending StartNextPr rather than Reconcile.
    #[test]
    fn reconcile_refuses_a_directive_that_was_never_delivered() {
        let repo = TestRepo::new();
        let runtime = tokio::runtime::Runtime::new().expect("test runtime");
        let (home, _store, session) = runtime.block_on(async {
            let (home, store, session, _rec) =
                applied_unincorporated_task(&repo, "jack/never-applied", 901, 3, false).await;
            (home, store, session)
        });
        drop(runtime);
        let _env = StoreEnvGuard::new(home.path());

        let snapshot = task_snapshot(&session).expect("snapshot");
        assert_eq!(
            snapshot.actions.recommended,
            Some(TaskAction::StartNextPr),
            "a not-applied pending directive still needs a body"
        );

        let refusal = task_reconcile(
            &session.launch.issue.identifier,
            CallerAuthority::Operator,
            3,
            "attest".to_string(),
        )
        .expect_err("a never-delivered directive cannot be reconciled");
        assert!(
            refusal.to_string().contains("never delivered to a body"),
            "{refusal}"
        );
    }

    /// Reconcile refuses when the owning-team Linear issue is not actually in a
    /// completed state — a merged CompleteTask publication is only an intent, and
    /// its write can fail (ENG-29/ENG-75). Sabotage guard for the Linear proof:
    /// dropping the `issue_is_complete` check lets this attest a still-open issue.
    #[test]
    fn reconcile_refuses_when_the_linear_issue_is_not_complete() {
        let repo = TestRepo::new();
        let runtime = tokio::runtime::Runtime::new().expect("test runtime");
        let (home, _store, session) = runtime.block_on(async {
            let (home, store, session, _rec) =
                applied_unincorporated_task(&repo, "jack/open-issue", 903, 5, true).await;
            (home, store, session)
        });
        drop(runtime);
        let _env = StoreEnvGuard::new(home.path());
        let _linear = LinearCompleteOverride::set(false);

        let refusal = task_reconcile(
            &session.launch.issue.identifier,
            CallerAuthority::Operator,
            5,
            "attest".to_string(),
        )
        .expect_err("a not-Linear-complete issue cannot be reconciled");
        assert!(
            refusal.to_string().contains("not Linear-complete"),
            "{refusal}"
        );
    }

    /// Reconcile resolves the PM/GOAL root from the owning Wave's canonical repo,
    /// not the (possibly pruned) worker worktree. Sabotage guard for v6/v7:
    /// reading `session.worktree` here would break reconciliation of a dead Task.
    #[test]
    fn reconcile_reads_the_linear_proof_from_the_wave_repo_not_the_worktree() {
        let repo = TestRepo::new();
        let dead_worktree = tempfile::tempdir().expect("dead worktree parent");
        let missing = dead_worktree.path().join("pruned-worker-tree");
        let runtime = tokio::runtime::Runtime::new().expect("test runtime");
        let (home, store, session, wave_repo) = runtime.block_on(async {
            let (home, store, mut session, _rec) =
                applied_unincorporated_task(&repo, "jack/dead-tree", 905, 5, true).await;
            let wave_repo = owning_wave(&store, &session)
                .await
                .unwrap()
                .repo()
                .to_string();
            // Point the Session at a worktree that does not exist — the shape this
            // command targets. PM ownership stays Wave-durable at `wave_repo`.
            session.worktree = missing.clone();
            store.update_task_session(&session).await.unwrap();
            let session = store.get_task_session(&session.id).await.unwrap().unwrap();
            (home, store, session, wave_repo)
        });
        drop(runtime);
        let _env = StoreEnvGuard::new(home.path());
        let _linear = LinearCompleteOverride::set(true);
        crate::ops::task_pm::test_hooks::record_root(Path::new("unset"));

        // The clean-tree gate (deliberately preserved) fails on the missing
        // worktree — but only *after* the Linear proof was reached against the
        // Wave repo, which is the point under test.
        let err = task_reconcile(
            &session.launch.issue.identifier,
            CallerAuthority::Operator,
            5,
            "attest".to_string(),
        )
        .expect_err("clean-tree gate still fires on the missing worktree");
        assert!(
            err.to_string().contains("worktree"),
            "the preserved clean-tree gate should fail on the missing worktree: {err}"
        );
        let root = crate::ops::task_pm::test_hooks::last_root().expect("Linear proof was reached");
        assert_eq!(root, wave_repo, "PM root must be the Wave repo");
        assert_ne!(
            root,
            missing.display().to_string(),
            "PM root must not be the dead worker worktree"
        );
        drop(store);
    }

    /// Append a serial successor to `first` and merge it with a `Review`
    /// disposition — a later, non-completing merge stacked on an older
    /// `CompleteTask`. Leaves the Task with no active PR.
    async fn append_merged_review_pr(store: &SharedStore, first: &TaskPr, number: u32) {
        let now = OffsetDateTime::now_utc();
        let mut next = TaskPr {
            id: TaskPrId::new(),
            task_session_id: first.task_session_id.clone(),
            sequence: first.sequence + 1,
            slug: format!("{}-next", first.slug),
            branch: format!("{}-next", first.branch),
            base_commit: first.base_commit.clone(),
            parent_pr_id: None,
            publication: None,
            merge_commit: None,
            abandoned_at: None,
            created_at: now,
            updated_at: now,
            ci_observation: None,
            github_observation: None,
            linear_attachment_id: None,
            linear_comment_id: None,
            linear_link_error: None,
        };
        store
            .settle_task_pr(first, Some(&next))
            .await
            .expect("insert successor working PR");
        next.publication = Some(PrPublication {
            requested_at: now,
            after_merge: AfterMerge::Review,
            next_slug: None,
            github: Some(GithubPr {
                number,
                url: format!("https://example.com/pr/{number}"),
                head_sha: None,
            }),
        });
        next.merge_commit = Some(format!("merge-{number}"));
        next.updated_at = now;
        store
            .settle_task_pr(&next, None)
            .await
            .expect("settle successor as Review-merged");
    }

    /// Append a rotated successor that never published and was then abandoned —
    /// the trailing row in the live ENG-29 shape. It is the newest PR by sequence
    /// but carries no publication and no merge, so it must not hide the real
    /// settled merge underneath it.
    async fn append_abandoned_unpublished_successor(store: &SharedStore, prev: &TaskPr) {
        let now = OffsetDateTime::now_utc();
        let mut succ = TaskPr {
            id: TaskPrId::new(),
            task_session_id: prev.task_session_id.clone(),
            sequence: prev.sequence + 1,
            slug: format!("{}-succ", prev.slug),
            branch: format!("{}-succ", prev.branch),
            base_commit: prev.base_commit.clone(),
            parent_pr_id: None,
            publication: None,
            merge_commit: None,
            abandoned_at: None,
            created_at: now,
            updated_at: now,
            ci_observation: None,
            github_observation: None,
            linear_attachment_id: None,
            linear_comment_id: None,
            linear_link_error: None,
        };
        store
            .settle_task_pr(prev, Some(&succ))
            .await
            .expect("insert successor working PR");
        succ.abandoned_at = Some(now);
        succ.updated_at = now;
        store
            .update_task_pr(&succ)
            .await
            .expect("abandon the unpublished successor");
    }

    /// Append a later, non-abandoned, *open* (unmerged) `Review` successor — the
    /// sabotage the reconcile predicate must still refuse: real work is in flight,
    /// so the Task has not settled no matter what merged before it.
    async fn append_open_review_successor(store: &SharedStore, prev: &TaskPr, number: u32) {
        let now = OffsetDateTime::now_utc();
        let mut succ = TaskPr {
            id: TaskPrId::new(),
            task_session_id: prev.task_session_id.clone(),
            sequence: prev.sequence + 1,
            slug: format!("{}-open", prev.slug),
            branch: format!("{}-open", prev.branch),
            base_commit: prev.base_commit.clone(),
            parent_pr_id: None,
            publication: None,
            merge_commit: None,
            abandoned_at: None,
            created_at: now,
            updated_at: now,
            ci_observation: None,
            github_observation: None,
            linear_attachment_id: None,
            linear_comment_id: None,
            linear_link_error: None,
        };
        store
            .settle_task_pr(prev, Some(&succ))
            .await
            .expect("insert successor working PR");
        succ.publication = Some(PrPublication {
            requested_at: now,
            after_merge: AfterMerge::Review,
            next_slug: None,
            github: Some(GithubPr {
                number,
                url: format!("https://example.com/pr/{number}"),
                head_sha: Some("open-head".to_string()),
            }),
        });
        succ.updated_at = now;
        store
            .update_task_pr(&succ)
            .await
            .expect("open the successor PR");
    }

    /// The exact live ENG-29 shape, exposed once ENG-30 merged: an older merged
    /// `CompleteTask`, a **later merged `Review`**, and a trailing **abandoned
    /// unpublished successor**, with an applied-but-unincorporated final directive
    /// and a Linear-complete issue. Reconciliation now *succeeds* and clears the
    /// orphan — where the strict `latest_pr_completes_task` (kept for automatic
    /// completion) would refuse. The supervisor leaves the Reconcile
    /// recommendation standing and never auto-completes.
    #[test]
    fn reconcile_settles_a_later_merged_review_over_an_older_completetask_with_abandoned_successor()
    {
        let repo = TestRepo::new();
        let runtime = tokio::runtime::Runtime::new().expect("test runtime");
        let (home, store, session, recovery_id) = runtime.block_on(async {
            let (home, store, session, recovery_id) =
                applied_unincorporated_task(&repo, "jack/eng-29", 1064, 5, true).await;
            let first = store
                .task_prs(&session.id)
                .await
                .unwrap()
                .into_iter()
                .next()
                .expect("first PR");
            append_merged_review_pr(&store, &first, 1099).await;
            let review = store
                .task_prs(&session.id)
                .await
                .unwrap()
                .into_iter()
                .max_by_key(|pr| pr.sequence)
                .expect("merged Review PR");
            append_abandoned_unpublished_successor(&store, &review).await;
            let session = store.get_task_session(&session.id).await.unwrap().unwrap();

            let prs = store.task_prs(&session.id).await.unwrap();
            assert_eq!(prs.len(), 3);
            // Automatic completion stays strict: the newest PR is not a completing
            // merge, so this Task must never auto-complete.
            assert!(
                !latest_pr_completes_task(&prs),
                "the newest row is an abandoned successor, not a merged CompleteTask"
            );
            // Reconciliation trusts the settled set: latest non-abandoned PR is the
            // merged Review, nothing in flight.
            assert!(
                reconcilable_pr_set(&prs),
                "a merged Review under a trailing abandoned successor is reconcilable"
            );

            // Supervisor recognizes the shape: leaves it awaiting attestation.
            let project = store
                .get_project_session(&session.project_session_id)
                .await
                .unwrap()
                .unwrap();
            reconcile_project_tasks(&store, &project)
                .await
                .expect("supervisor tolerates the reconcilable shape");
            let after = store.get_task_session(&session.id).await.unwrap().unwrap();
            assert_eq!(
                after.status,
                TaskSessionStatus::Waiting,
                "supervisor never settles it hands-off"
            );
            assert!(after.latest_process.is_none(), "no body relaunched");
            (home, store, after, recovery_id)
        });
        drop(runtime);
        let _env = StoreEnvGuard::new(home.path());
        let _linear = LinearCompleteOverride::set(true);

        // Legal-action reporting points at Reconcile, never StartNextPr.
        let snapshot = task_snapshot(&session).expect("snapshot the reconcilable Task");
        assert_eq!(snapshot.actions.recommended, Some(TaskAction::Reconcile));
        assert!(
            !snapshot
                .actions
                .status(TaskAction::StartNextPr)
                .unwrap()
                .available
        );

        let summary = "Directive v5 shipped in the merged head; the Review landed after the \
                       CompleteTask and the acknowledgement turn was interrupted.";
        let result = task_reconcile(
            &session.launch.issue.identifier,
            CallerAuthority::Operator,
            5,
            summary.to_string(),
        )
        .expect("operator attestation settles the later-Review shape");
        assert_eq!(result.session.status, TaskSessionStatus::Completed);
        assert_eq!(
            result.cleared_commands,
            vec![recovery_id],
            "the orphaned Persisted recovery command is cleared in place"
        );
        drop(store);
    }

    /// Preserved sabotage: a later, non-abandoned, *open* (unmerged) `Review`
    /// successor is genuine in-flight work, so the settled set is not
    /// reconcilable and the command refuses. Loosening `reconcilable_pr_set` to
    /// accept an unmerged non-abandoned PR flips the predicate assertion.
    #[test]
    fn reconcile_refuses_a_later_nonabandoned_unmerged_review() {
        let repo = TestRepo::new();
        let runtime = tokio::runtime::Runtime::new().expect("test runtime");
        let (home, store, session) = runtime.block_on(async {
            let (home, store, session, _rec) =
                applied_unincorporated_task(&repo, "jack/open-review", 1064, 5, true).await;
            let first = store
                .task_prs(&session.id)
                .await
                .unwrap()
                .into_iter()
                .next()
                .expect("first PR");
            append_open_review_successor(&store, &first, 1099).await;
            let session = store.get_task_session(&session.id).await.unwrap().unwrap();

            let prs = store.task_prs(&session.id).await.unwrap();
            assert!(
                !reconcilable_pr_set(&prs),
                "a later non-abandoned unmerged Review is in-flight work, not reconcilable"
            );
            (home, store, session)
        });
        drop(runtime);
        let _env = StoreEnvGuard::new(home.path());
        let _linear = LinearCompleteOverride::set(true);

        let err = task_reconcile(
            &session.launch.issue.identifier,
            CallerAuthority::Operator,
            5,
            "attest".to_string(),
        )
        .expect_err("an in-flight later Review is refused");
        let message = err.to_string();
        assert!(
            message.contains("active pull request") || message.contains("has not merged"),
            "{message}"
        );
        drop(store);
    }

    /// Automatic completion (`advance_completion_after_gate`) must select the
    /// newest PR's disposition: with the gate otherwise clear, an older
    /// `CompleteTask` behind a later `Review` merge must not complete the Task.
    /// Reverting `merged_completing_pr` to `find(any CompleteTask)` fails here.
    #[tokio::test]
    async fn advance_completion_never_completes_from_an_older_disposition() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        repo.create_branch("jack/adv-older");
        let (_home, store, mut session, pr) = rotation_task(&repo, "jack/adv-older", &base).await;
        settle_completing_pr(&store, pr, "merge-adv").await;
        let first = store
            .task_prs(&session.id)
            .await
            .unwrap()
            .into_iter()
            .next()
            .expect("first PR");
        append_merged_review_pr(&store, &first, 2).await;
        session = store.get_task_session(&session.id).await.unwrap().unwrap();

        let advanced = advance_completion_after_gate(&store, &mut session, None)
            .await
            .expect("advance completion");
        assert!(
            !advanced,
            "the newest merge is Review, not CompleteTask — must not complete"
        );
        assert_ne!(session.status, TaskSessionStatus::Completed);
    }

    /// The shared disposition predicate keys on the newest PR by sequence.
    #[test]
    fn latest_pr_completes_task_keys_on_the_newest_pr() {
        fn merged(sequence: u32, after_merge: AfterMerge) -> TaskPr {
            let now = OffsetDateTime::UNIX_EPOCH;
            TaskPr {
                id: TaskPrId::new(),
                task_session_id: TaskSessionId::new(),
                sequence,
                slug: format!("s{sequence}"),
                branch: format!("b{sequence}"),
                base_commit: "base".to_string(),
                parent_pr_id: None,
                publication: Some(PrPublication {
                    requested_at: now,
                    after_merge,
                    next_slug: None,
                    github: Some(GithubPr {
                        number: sequence,
                        url: "u".to_string(),
                        head_sha: None,
                    }),
                }),
                merge_commit: Some("m".to_string()),
                abandoned_at: None,
                created_at: now,
                updated_at: now,
                ci_observation: None,
                github_observation: None,
                linear_attachment_id: None,
                linear_comment_id: None,
                linear_link_error: None,
            }
        }
        // Newest is CompleteTask → reconcilable.
        assert!(latest_pr_completes_task(&[
            merged(1, AfterMerge::Review),
            merged(2, AfterMerge::CompleteTask),
        ]));
        // Older CompleteTask behind a newer Review → not reconcilable.
        assert!(!latest_pr_completes_task(&[
            merged(1, AfterMerge::CompleteTask),
            merged(2, AfterMerge::Review),
        ]));
        // Order-independent: sequence, not vector order, decides.
        assert!(!latest_pr_completes_task(&[
            merged(2, AfterMerge::Review),
            merged(1, AfterMerge::CompleteTask),
        ]));
        assert!(!latest_pr_completes_task(&[]));
    }

    /// The reconcile predicate selects the latest *non-abandoned* PR and accepts
    /// any merged disposition, but refuses any non-abandoned unmerged PR.
    #[test]
    fn reconcilable_pr_set_selects_the_latest_non_abandoned_merge() {
        #[derive(Clone, Copy)]
        enum Shape {
            Merged(AfterMerge),
            Open,
            AbandonedUnpublished,
        }
        fn pr(sequence: u32, shape: Shape) -> TaskPr {
            let now = OffsetDateTime::UNIX_EPOCH;
            let (publication, merge_commit, abandoned_at) = match shape {
                Shape::Merged(after_merge) => (
                    Some(PrPublication {
                        requested_at: now,
                        after_merge,
                        next_slug: None,
                        github: Some(GithubPr {
                            number: sequence,
                            url: "u".to_string(),
                            head_sha: None,
                        }),
                    }),
                    Some("m".to_string()),
                    None,
                ),
                Shape::Open => (
                    Some(PrPublication {
                        requested_at: now,
                        after_merge: AfterMerge::Review,
                        next_slug: None,
                        github: Some(GithubPr {
                            number: sequence,
                            url: "u".to_string(),
                            head_sha: Some("h".to_string()),
                        }),
                    }),
                    None,
                    None,
                ),
                Shape::AbandonedUnpublished => (None, None, Some(now)),
            };
            TaskPr {
                id: TaskPrId::new(),
                task_session_id: TaskSessionId::new(),
                sequence,
                slug: format!("s{sequence}"),
                branch: format!("b{sequence}"),
                base_commit: "base".to_string(),
                parent_pr_id: None,
                publication,
                merge_commit,
                abandoned_at,
                created_at: now,
                updated_at: now,
                ci_observation: None,
                github_observation: None,
                linear_attachment_id: None,
                linear_comment_id: None,
                linear_link_error: None,
            }
        }
        // The live ENG-29 shape: merged CompleteTask, later merged Review, trailing
        // abandoned unpublished successor → reconcilable.
        assert!(reconcilable_pr_set(&[
            pr(1, Shape::Merged(AfterMerge::CompleteTask)),
            pr(2, Shape::Merged(AfterMerge::Review)),
            pr(3, Shape::AbandonedUnpublished),
        ]));
        // A plain completing merge is reconcilable too.
        assert!(reconcilable_pr_set(&[pr(
            1,
            Shape::Merged(AfterMerge::CompleteTask)
        )]));
        // A later non-abandoned open PR is in-flight work → not reconcilable.
        assert!(!reconcilable_pr_set(&[
            pr(1, Shape::Merged(AfterMerge::CompleteTask)),
            pr(2, Shape::Open),
        ]));
        // Nothing merged (only an abandoned row) → not reconcilable.
        assert!(!reconcilable_pr_set(&[pr(1, Shape::AbandonedUnpublished)]));
        assert!(!reconcilable_pr_set(&[]));
    }

    /// Create a parent Task with a published (not merged) PR, then a child Task
    /// stacked on the parent's tip. The parent's branch is pushed so
    /// `resolve_verifier_upstream` can fetch `origin/<parent_branch>`. The child
    /// claims `repo.path()` (the verifier resolves by worktree); the parent is
    /// moved to a dummy path so both sessions coexist under the `worktree`
    /// UNIQUE constraint.
    async fn stacked_rotation_task(
        repo: &TestRepo,
        parent_branch: &str,
        child_branch: &str,
        parent_base: &str,
    ) -> (
        tempfile::TempDir,
        SharedStore,
        TaskSession,
        TaskPr,
        TaskSession,
        TaskPr,
    ) {
        // Parent: create the branch, commit work, push, then register.
        repo.create_branch(parent_branch);
        repo.create_file("parent.txt", "parent work\n");
        repo.stage_all();
        repo.commit("parent commit");
        repo.push_new_branch(parent_branch);
        let parent_tip = repo.head_sha();

        let (home, store, mut parent_session, mut parent_pr) =
            rotation_task(repo, parent_branch, parent_base).await;

        // Publish the parent PR (not merged) so the child's `parent_pr_id` is live.
        parent_pr.publication = Some(PrPublication {
            requested_at: OffsetDateTime::now_utc(),
            after_merge: AfterMerge::Review,
            next_slug: None,
            github: Some(GithubPr {
                number: 900,
                url: "https://example.com/pr/900".to_string(),
                head_sha: None,
            }),
        });
        parent_pr.updated_at = OffsetDateTime::now_utc();
        store
            .update_task_pr(&parent_pr)
            .await
            .expect("publish parent PR");

        // Move the parent off repo.path() so the child can claim it.
        parent_session.worktree = std::path::PathBuf::from("/dummy/parent-worktree");
        store
            .update_task_session(&parent_session)
            .await
            .expect("reparent parent worktree");

        // Child: cut from the parent's tip, claim the repo worktree.
        repo.checkout("main");
        git(repo.path(), &["branch", child_branch, &parent_tip]);
        repo.checkout(child_branch);

        let now = OffsetDateTime::now_utc();
        let child_session = TaskSession {
            id: TaskSessionId::new(),
            launch: TaskLaunchReceipt {
                issue: LinearIssueSnapshot {
                    id: LinearIssueId::new(format!("issue-{}", WaveId::new())).expect("issue id"),
                    identifier: "INF-STACK".to_string(),
                    title: "Stacked child".to_string(),
                    description: "Stacked on the parent.".to_string(),
                },
                project: parent_session.launch.project.clone(),
                pm_snapshot_synced_at: now.unix_timestamp(),
            },
            pm_writeback: PmWritebackState::Current,
            wave_id: parent_session.wave_id.clone(),
            project_session_id: parent_session.project_session_id.clone(),
            current_directive_version: 0,
            incorporated_directive_version: 0,
            status: TaskSessionStatus::Waiting,
            status_reason: "stacked child".to_string(),
            status_at: now,
            worktree: repo.path().to_path_buf(),
            workspace_slug: "stacked-child".to_string(),
            lifecycle: crate::task::TaskLifecyclePlan::standard("task"),
            lifecycle_phase: crate::task::TaskLifecyclePhase::Iterate,
            phase_epoch: 1,
            phase_cursor: 0,
            phase_iteration: 0,
            gate_cycle: 0,
            gate_proposal: None,
            agent: "codex".to_string(),
            provider: "codex".to_string(),
            provider_session_id: None,
            latest_process: None,
            abandon_intent: None,
            created_at: now,
            updated_at: now,
            observation: crate::task::Observation::NotRequired,
        };
        let child_pr = TaskPr {
            id: TaskPrId::new(),
            task_session_id: child_session.id.clone(),
            sequence: 1,
            slug: "stacked-child".to_string(),
            branch: child_branch.to_string(),
            base_commit: parent_tip,
            parent_pr_id: Some(parent_pr.id.clone()),
            publication: None,
            merge_commit: None,
            abandoned_at: None,
            ci_observation: None,
            github_observation: None,
            linear_attachment_id: None,
            linear_comment_id: None,
            linear_link_error: None,
            created_at: now,
            updated_at: now,
        };
        store
            .create_task_session(&child_session, &child_pr)
            .await
            .expect("create child Task");
        (
            home,
            store,
            parent_session,
            parent_pr,
            child_session,
            child_pr,
        )
    }

    #[tokio::test]
    async fn nonempty_refuses_when_head_is_the_recorded_base() {
        let repo = TestRepo::new();
        let base = repo.head_sha();

        let branch = "jack/empty-head";
        repo.create_branch(branch);
        let (_home, store, session, _pr) = rotation_task(&repo, branch, &base).await;

        let err =
            require_task_pr_range_nonempty_with_authority(&store, &session, None, repo.path())
                .await
                .expect_err("HEAD == base must refuse as empty");
        assert!(
            err.to_string().contains("empty"),
            "expected empty-range refusal, got: {err}"
        );
    }

    #[tokio::test]
    async fn nonempty_refuses_a_range_with_no_tree_change() {
        let repo = TestRepo::new();
        let base = repo.head_sha();

        let branch = "jack/no-tree-change";
        repo.create_branch(branch);
        repo.create_file("ephemeral.txt", "gone\n");
        repo.stage_all();
        repo.commit("add ephemeral");
        git(repo.path(), &["rm", "ephemeral.txt"]);
        repo.commit("remove ephemeral");

        let (_home, store, session, _pr) = rotation_task(&repo, branch, &base).await;

        let err =
            require_task_pr_range_nonempty_with_authority(&store, &session, None, repo.path())
                .await
                .expect_err("zero net tree change must refuse as empty");
        assert!(
            err.to_string().contains("empty"),
            "expected empty-range refusal for zero tree change, got: {err}"
        );
    }

    /// The core hole W2-254 closes: the old `task_pr_has_changes` guard skipped
    /// emptiness when `pr.github().is_some()`. The shared verifier is
    /// unconditional — an existing PR with an empty range is refused.
    #[tokio::test]
    async fn nonempty_refuses_even_when_the_pr_already_has_a_github_number() {
        let repo = TestRepo::new();
        let base = repo.head_sha();

        let branch = "jack/empty-existing";
        repo.create_branch(branch);
        let (_home, store, session, mut pr) = rotation_task(&repo, branch, &base).await;

        pr.publication = Some(PrPublication {
            requested_at: OffsetDateTime::now_utc(),
            after_merge: AfterMerge::Review,
            next_slug: None,
            github: Some(GithubPr {
                number: 925,
                url: "https://example.com/pr/925".to_string(),
                head_sha: None,
            }),
        });
        pr.updated_at = OffsetDateTime::now_utc();
        store.update_task_pr(&pr).await.expect("set github number");

        let err =
            require_task_pr_range_nonempty_with_authority(&store, &session, None, repo.path())
                .await
                .expect_err("an existing PR with an empty range must refuse");
        assert!(
            err.to_string().contains("empty"),
            "expected empty-range refusal despite github number, got: {err}"
        );
    }

    #[tokio::test]
    async fn nonempty_passes_for_a_real_range() {
        let repo = TestRepo::new();
        let base = repo.head_sha();

        let branch = "jack/real-range";
        repo.create_branch(branch);
        repo.create_file("task.txt", "real work\n");
        repo.stage_all();
        repo.commit("real task commit");
        let (_home, store, session, _pr) = rotation_task(&repo, branch, &base).await;

        require_task_pr_range_nonempty_with_authority(&store, &session, None, repo.path())
            .await
            .expect("a real range must pass the non-empty check");
    }

    #[tokio::test]
    async fn stacked_child_measures_from_live_parent_tip() {
        let repo = TestRepo::new();
        let origin_tip = repo.head_sha();

        let (_home, store, _, _, child_session, _) =
            stacked_rotation_task(&repo, "jack/stack-parent", "jack/stack-child", &origin_tip)
                .await;

        repo.create_file("child.txt", "child work\n");
        repo.stage_all();
        repo.commit("child commit");

        require_task_pr_range_nonempty_with_authority(&store, &child_session, None, repo.path())
            .await
            .expect("stacked child with own work passes against the parent tip");
    }

    #[tokio::test]
    async fn stacked_child_refuses_when_empty_against_live_parent() {
        let repo = TestRepo::new();
        let origin_tip = repo.head_sha();

        let (_home, store, _, _, child_session, _) = stacked_rotation_task(
            &repo,
            "jack/stack-parent-empty",
            "jack/stack-child-empty",
            &origin_tip,
        )
        .await;

        let err = require_task_pr_range_nonempty_with_authority(
            &store,
            &child_session,
            None,
            repo.path(),
        )
        .await
        .expect_err("empty stacked child must refuse against the parent tip");
        assert!(
            err.to_string().contains("empty"),
            "expected empty-range refusal for stacked child, got: {err}"
        );
    }

    #[tokio::test]
    async fn stacked_child_measures_from_origin_after_parent_collapsed() {
        let repo = TestRepo::new();
        let origin_tip = repo.head_sha();

        let (_home, store, _, mut parent_pr, child_session, mut child_pr) = stacked_rotation_task(
            &repo,
            "jack/collapse-parent",
            "jack/collapse-child",
            &origin_tip,
        )
        .await;

        repo.create_file("child.txt", "child work\n");
        repo.stage_all();
        repo.commit("child commit");

        // Parent merged: land the parent's work on origin/main.
        repo.checkout("main");
        repo.create_file("parent.txt", "parent work\n");
        repo.stage_all();
        repo.commit("merge parent into main");
        repo.push();
        let main_tip = repo.head_sha();

        // Collapse the child onto origin/main (replay only base..HEAD).
        repo.checkout("jack/collapse-child");
        git(
            repo.path(),
            &[
                "rebase",
                "--onto",
                "origin/main",
                &parent_pr.base_commit,
                "jack/collapse-child",
            ],
        );

        parent_pr.merge_commit = Some("merge-sha".to_string());
        parent_pr.updated_at = OffsetDateTime::now_utc();
        store
            .update_task_pr(&parent_pr)
            .await
            .expect("mark parent merged");

        // `base_commit` is part of `update_task_pr`'s optimistic identity, so
        // healing it forward needs the dedicated `heal_task_pr_base` write.
        child_pr.base_commit = main_tip;
        child_pr.updated_at = OffsetDateTime::now_utc();
        store
            .heal_task_pr_base(&child_pr)
            .await
            .expect("heal child base to main");

        require_task_pr_range_nonempty_with_authority(&store, &child_session, None, repo.path())
            .await
            .expect("collapsed child with own work passes against origin/main");
    }

    #[tokio::test]
    async fn stacked_child_refuses_when_empty_after_parent_collapsed() {
        let repo = TestRepo::new();
        let origin_tip = repo.head_sha();

        let (_home, store, _, mut parent_pr, child_session, mut child_pr) = stacked_rotation_task(
            &repo,
            "jack/collapse-parent-empty",
            "jack/collapse-child-empty",
            &origin_tip,
        )
        .await;

        // Parent merged: land the parent's work on origin/main.
        repo.checkout("main");
        repo.create_file("parent.txt", "parent work\n");
        repo.stage_all();
        repo.commit("merge parent into main");
        repo.push();
        let main_tip = repo.head_sha();

        // Collapse the child onto origin/main — no own work to replay.
        repo.checkout("jack/collapse-child-empty");
        git(
            repo.path(),
            &[
                "rebase",
                "--onto",
                "origin/main",
                &parent_pr.base_commit,
                "jack/collapse-child-empty",
            ],
        );

        parent_pr.merge_commit = Some("merge-sha".to_string());
        parent_pr.updated_at = OffsetDateTime::now_utc();
        store
            .update_task_pr(&parent_pr)
            .await
            .expect("mark parent merged");

        child_pr.base_commit = main_tip;
        child_pr.updated_at = OffsetDateTime::now_utc();
        store
            .heal_task_pr_base(&child_pr)
            .await
            .expect("heal child base to main");

        let err = require_task_pr_range_nonempty_with_authority(
            &store,
            &child_session,
            None,
            repo.path(),
        )
        .await
        .expect_err("empty collapsed child must refuse against origin/main");
        assert!(
            err.to_string().contains("empty"),
            "expected empty-range refusal for collapsed child, got: {err}"
        );
    }

    #[test]
    fn task_context_captures_project_definition_and_kr_state() {
        let project = PmProject {
            id: "project-1".to_string(),
            slug: "pr".to_string(),
            name: "PR".to_string(),
            summary: "Ship reliably".to_string(),
            definition: "Every task has one durable session.".to_string(),
            krs: vec![
                PmKr {
                    text: "Review resumes the same session".to_string(),
                    holds: true,
                },
                PmKr {
                    text: "Merge wakes the Wave".to_string(),
                    holds: false,
                },
            ],
            initiative_ids: vec!["initiative-1".to_string()],
            team_ids: None,
        };

        assert_eq!(
            project_context(&project),
            "Definition:\nEvery task has one durable session.\n\nKRs:\n- [x] Review resumes the same session\n- [ ] Merge wakes the Wave"
        );
    }

    #[tokio::test]
    async fn idle_task_can_defer_its_remaining_interactive_steps() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let (_home, _store, mut session, _pr) =
            rotation_task(&repo, "jack/task-headless", &base).await;

        assert!(_defer_task_interactions(&mut session).unwrap());
        assert!(session.lifecycle.all_interactions_deferred());
        assert!(!_defer_task_interactions(&mut session).unwrap());

        session.lifecycle = crate::task::TaskLifecyclePlan::standard("task");
        session.status = TaskSessionStatus::Completed;
        assert!(_defer_task_interactions(&mut session)
            .unwrap_err()
            .to_string()
            .contains("terminal Tasks cannot change interaction policy"));
    }

    /// Seed a second Task under the rotation scaffolding whose durable state is a
    /// non-active status still carrying a dead lease — the exact shape an explicit
    /// resume must reconcile before it can reserve a fresh body.
    /// `outcome` is seeded at row creation because the lease outcome belongs to
    /// the revoke/finish CAS path — `update_task_session` does not persist it.
    /// `identity` is the recorded `(pid, process_group_id)`. Both `None` leaves
    /// the tmux name as the only evidence.
    async fn dead_lease_task(
        repo: &TestRepo,
        branch: &str,
        base: &str,
        status: TaskSessionStatus,
        lease_state: crate::child_session::ChildLeaseState,
        outcome: Option<ChildBodyOutcome>,
        identity: (Option<u32>, Option<u32>),
    ) -> (tempfile::TempDir, SharedStore, TaskSession) {
        let (pid, process_group_id) = identity;
        let (home, store, base_session, _pr) = rotation_task(repo, branch, base).await;
        let now = OffsetDateTime::now_utc();
        let mut session = base_session.clone();
        session.id = TaskSessionId::new();
        session.workspace_slug = "dead-lease-proof".to_string();
        // Distinct worktree and issue: both columns are UNIQUE and the base Task
        // already holds the repo root and the rotation issue.
        session.worktree = repo.path().join(format!("dead-{}", session.id));
        session.launch.issue.id =
            LinearIssueId::new(format!("issue-{}", session.id)).expect("issue id");
        session.launch.issue.identifier = format!("INF-DEAD-{}", session.id);
        session.set_status(status, "recovered from a vanished body");
        session.latest_process = Some(ChildProcessGeneration {
            generation: 1,
            pid,
            process_group_id,
            // A name no tmux server knows, so the liveness probe reads it as dead.
            tmux_name: format!("dead-lease-{}", session.id),
            agent: session.agent.clone(),
            provider: session.provider.clone(),
            provider_session_id: None,
            started_at: now - time::Duration::hours(1),
            state: lease_state,
            outcome,
            provenance: None,
        });
        let pr = TaskPr {
            id: TaskPrId::new(),
            task_session_id: session.id.clone(),
            sequence: 1,
            slug: session.workspace_slug.clone(),
            branch: format!("{branch}-dead"),
            base_commit: base.to_string(),
            parent_pr_id: None,
            publication: None,
            merge_commit: None,
            abandoned_at: None,
            created_at: now,
            updated_at: now,
            ci_observation: None,
            github_observation: None,
            linear_attachment_id: None,
            linear_comment_id: None,
            linear_link_error: None,
        };
        store
            .create_task_session(&session, &pr)
            .await
            .expect("create dead-lease Task");
        (home, store, session)
    }

    /// Pin the body launcher to a binary that does not exist.
    ///
    /// A successful spawn needs a real Home `lf`, tmux, and `/bin/zsh` — a CI
    /// container has none of them, so a test that spawns passes only on a
    /// developer laptop and is no proof at all. Pinning the launch to a missing
    /// binary fails it the *same way everywhere*, which leaves the recovery
    /// decision — the part this module owns — as the only variable.
    /// `launch_task_process` owns the spawn and is tested separately.
    fn pin_unlaunchable_body() -> Option<std::ffi::OsString> {
        let previous = std::env::var_os("LF_BIN");
        std::env::set_var("LF_BIN", "/loopflow-test/does-not-exist/lf");
        previous
    }

    fn restore_lf_bin(previous: Option<std::ffi::OsString>) {
        match previous {
            Some(value) => std::env::set_var("LF_BIN", value),
            None => std::env::remove_var("LF_BIN"),
        }
    }

    async fn stranded_task(
        repo: &TestRepo,
        branch: &str,
    ) -> (tempfile::TempDir, SharedStore, TaskSession) {
        let base = repo.head_sha();
        let (home, store, session, _pr) = rotation_task_with_lease(
            repo,
            branch,
            &base,
            Some((ChildLeaseState::Active, TaskSessionStatus::Running, None)),
        )
        .await;
        // The body owned its PR branch when it died; put the worktree back where
        // it was so the successor clears the same adoption preconditions an
        // explicit resume would.
        git(repo.path(), &["checkout", "-b", branch]);
        (home, store, session)
    }

    /// The proof: a Task whose body died is re-dispatched with nobody asking.
    ///
    /// The seeded lease names a tmux session no server knows, so the liveness
    /// probe reads the body as genuinely gone — the same evidence a
    /// `tmux kill-session` produces. No human command is issued anywhere in this
    /// test; the supervision path decides on its own.
    #[allow(clippy::await_holding_lock)] // the env lock is the test serializer
    #[tokio::test]
    async fn a_killed_body_under_a_live_task_is_redispatched_with_no_human_action() {
        // `pin_unlaunchable_body` mutates process-global LF_BIN, and the sibling
        // test below pins it too: without this lock one restores LF_BIN while the
        // other still depends on it, and the launch it requires to fail succeeds.
        let _env_lock = crate::journal::test_env_lock();
        let repo = TestRepo::new();
        let (_home, store, mut session) = stranded_task(&repo, "jack/w2-267-recovers").await;

        let pinned = pin_unlaunchable_body();
        let outcome = recover_stranded_task_body(&store, &mut session).await;
        restore_lf_bin(pinned);

        // The spawn is pinned to fail, so recovery reports the launch error...
        assert!(outcome.is_err(), "the pinned-missing binary must fail");
        // ...but it had already reaped the strand and recorded its attempt, and
        // it did so without any human typing `lf task resume`.
        let events = store.recent_task_events(&session.id, 64).await.unwrap();
        assert_eq!(
            count_recovery_attempts(&events),
            1,
            "recovery must durably record the attempt it made"
        );
        assert!(
            events.iter().any(|event| matches!(
                event.kind,
                TaskEventKind::BodyRecoveryAttempted { attempt: 1, .. }
            )),
            "recovery must be observable, not silent"
        );
    }

    /// Retry is bounded: a strand that cannot launch stops and says why rather
    /// than minting dead generations forever.
    ///
    /// This runs the real dispatcher against a launch that always fails — the
    /// W2-210 shape, where the body's binary is gone. Each failed launch counts
    /// as an attempt (`launch_task_process` reaps as `Lost` on the way out), so
    /// the budget is spent by design rather than reset.
    #[allow(clippy::await_holding_lock)] // the env lock is the test serializer
    #[tokio::test]
    async fn an_unlaunchable_strand_exhausts_instead_of_minting_dead_generations() {
        let _env_lock = crate::journal::test_env_lock();
        let repo = TestRepo::new();
        let (_home, store, mut session) = stranded_task(&repo, "jack/w2-267-exhausts").await;

        for expected in 1..=MAX_RECOVERY_ATTEMPTS {
            let mut current = store.get_task_session(&session.id).await.unwrap().unwrap();
            let pinned = pin_unlaunchable_body();
            let _ = recover_stranded_task_body(&store, &mut current).await;
            restore_lf_bin(pinned);
            let events = store.recent_task_events(&session.id, 64).await.unwrap();
            assert_eq!(
                count_recovery_attempts(&events),
                expected,
                "attempt {expected} must be recorded"
            );
        }

        // The budget is spent. The next pass must refuse to mint another
        // generation and must say why instead.
        let mut spent = store.get_task_session(&session.id).await.unwrap().unwrap();
        let pinned = pin_unlaunchable_body();
        let recovered = recover_stranded_task_body(&store, &mut spent).await;
        restore_lf_bin(pinned);
        let recovered = recovered.expect("a spent budget surfaces rather than erroring");
        assert!(!recovered, "an exhausted strand must not redispatch");

        let events = store.recent_task_events(&session.id, 64).await.unwrap();
        assert_eq!(
            count_recovery_attempts(&events),
            MAX_RECOVERY_ATTEMPTS,
            "exhaustion must not append a further attempt"
        );
        let persisted = store.get_task_session(&session.id).await.unwrap().unwrap();
        assert_eq!(persisted.status, TaskSessionStatus::Failed);
        assert!(
            persisted.status_reason.contains("did not survive"),
            "an exhausted strand must say why: {}",
            persisted.status_reason
        );
        session = persisted;
        let _ = &session;
    }

    /// The other half of the proof, and the triage's central trap: a Task that
    /// finished *successfully* also reaps its body as `lost` (W2-171/#913,
    /// W2-226/#965, W2-227, W2-233/#982). Recovery must not chase it.
    ///
    /// Two things are deliberate, and without either the test passes vacuously
    /// while the terminal guard rots: the `lost` outcome is seeded (an absent one
    /// would be left alone for the wrong reason), and the worktree is real and on
    /// the PR branch (otherwise `task_recovery_adoption` refuses first and the
    /// guard is never reached). Both were caught by mutating the guard away and
    /// watching this test keep passing.
    #[tokio::test]
    async fn a_completed_task_whose_body_was_reaped_triggers_nothing() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let (_home, store, mut session, _pr) = rotation_task_with_lease(
            &repo,
            "jack/w2-267-completed",
            &base,
            Some((
                ChildLeaseState::Finished,
                TaskSessionStatus::Completed,
                Some(ChildBodyOutcome::Lost {
                    reason: "task process disappeared before recording a terminal outcome"
                        .to_string(),
                }),
            )),
        )
        .await;
        git(repo.path(), &["checkout", "-b", "jack/w2-267-completed"]);
        let before = store.get_task_session(&session.id).await.unwrap().unwrap();
        assert!(
            matches!(
                before
                    .latest_process
                    .as_ref()
                    .and_then(|p| p.outcome.as_ref()),
                Some(ChildBodyOutcome::Lost { .. })
            ),
            "the trap only exists when a completed Task carries a lost body"
        );

        let recovered = recover_stranded_task_body(&store, &mut session)
            .await
            .expect("classify a completed Task");

        assert!(!recovered, "a completed Task must never be recovered");
        let after = store.get_task_session(&session.id).await.unwrap().unwrap();
        assert_eq!(after.status, TaskSessionStatus::Completed);
        assert_eq!(
            after.latest_process.map(|process| process.generation),
            before.latest_process.map(|process| process.generation),
            "a completed Task's body must not be replaced"
        );
        let events = store.recent_task_events(&session.id, 64).await.unwrap();
        assert_eq!(
            count_recovery_attempts(&events),
            0,
            "a completed Task must record no recovery attempt"
        );
    }

    /// A process group that has certainly exited: spawn one, reap it, reuse its
    /// id. Racy only if the kernel recycles this exact pgid mid-test, which reads
    /// as `Present` — a false failure, never a false pass.
    fn exited_process_group() -> u32 {
        let mut child = std::process::Command::new("/bin/sh")
            .arg("-c")
            .arg("exit 0")
            .process_group(0)
            .spawn()
            .expect("spawn a short-lived process group");
        let group = child.id();
        child.wait().expect("reap the short-lived group");
        group
    }

    /// ENG-4, end to end over a real kernel: a lease pinned at `revoked` by a
    /// corpse releases itself, and the reservation path is executable **only
    /// after** it does.
    ///
    /// The live unrelated pid is the load-bearing part. It models the recycled
    /// pid a stuck lease accumulates by construction, and under an
    /// all-identities conjunction this test cannot pass — the stranger's
    /// `Present` would pin the lease forever, which is the very defect being
    /// removed, rebuilt inside its own fix.
    #[tokio::test]
    async fn a_revoked_lease_over_a_dead_group_releases_and_only_then_reserves() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let mut stranger = std::process::Command::new("/bin/sh")
            .arg("-c")
            .arg("sleep 60")
            .spawn()
            .expect("spawn an unrelated live process");
        let recycled_pid = stranger.id();
        let (_home, store, session) = dead_lease_task(
            &repo,
            "jack/eng-4-released",
            &base,
            TaskSessionStatus::Waiting,
            crate::child_session::ChildLeaseState::Revoked,
            Some(ChildBodyOutcome::Superseded {
                reason: "body generation 1 stalled; recovering the same Task Session".to_string(),
            }),
            // The corpse that pins the lease, plus a pid that is emphatically alive.
            (Some(recycled_pid), Some(exited_process_group())),
        )
        .await;
        let target = ChildRef::Task(session.id.clone());
        let revoked = session
            .latest_process
            .as_ref()
            .expect("seeded generation")
            .clone();
        // tmux answers `no sessions`, so this test's subject is the lease and the
        // real process group -- not whether the host running it has tmux. Without
        // it the (correct) production rule reads an unspawnable tmux as
        // Unprovable and decides the probe before the group is ever asked.
        let _tmux = crate::engine::process::FakeTmux::no_session();

        // Before the release the CAS cannot pass: `revoked` satisfies neither
        // `IS NULL` nor `= 'finished'`. This is the permanent refusal.
        let mut blocked = session.clone();
        let generation = blocked.begin_generation("lf-task-eng4-blocked".to_string());
        assert_eq!(generation, 2);
        assert!(store
            .reserve_task_process(&blocked, TaskSessionStatus::Waiting)
            .await
            .expect("reserve against a revoked lease")
            .is_none());

        let finished =
            crate::ops::child::release_dead_revoked_child_body(&store, &target, &revoked)
                .await
                .expect("probe and release a lease over a dead group")
                .expect("a provably absent body releases its lease");

        stranger.kill().expect("kill the unrelated process");
        stranger.wait().expect("reap the unrelated process");
        assert_eq!(
            finished.state,
            crate::child_session::ChildLeaseState::Finished
        );
        assert_eq!(finished.generation, revoked.generation);

        // The release is durable, and the outcome that says *why* the body
        // stopped survives it — that tag is what the recovery verdict reads next.
        let persisted = store.get_task_session(&session.id).await.unwrap().unwrap();
        let persisted_process = persisted.latest_process.as_ref().expect("generation");
        assert_eq!(
            persisted_process.state,
            crate::child_session::ChildLeaseState::Finished
        );
        assert!(matches!(
            persisted_process.outcome,
            Some(ChildBodyOutcome::Superseded { .. })
        ));
        // Status is untouched: releasing a lease is not a decision about work.
        assert_eq!(persisted.status, TaskSessionStatus::Waiting);

        // ...and only now can a successor reserve.
        let mut launch = persisted.clone();
        launch.begin_generation("lf-task-eng4-successor".to_string());
        assert!(store
            .reserve_task_process(&launch, TaskSessionStatus::Waiting)
            .await
            .expect("reserve after the release")
            .is_some());
    }

    /// The CAS pins the generation as well as the state, so a release can only
    /// ever settle the exact generation still awaiting reap.
    #[tokio::test]
    async fn only_the_matching_revoked_generation_can_finish() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let (_home, store, session) = dead_lease_task(
            &repo,
            "jack/eng-4-cas",
            &base,
            TaskSessionStatus::Waiting,
            crate::child_session::ChildLeaseState::Revoked,
            Some(ChildBodyOutcome::Superseded {
                reason: "stalled".to_string(),
            }),
            (None, Some(exited_process_group())),
        )
        .await;
        let target = ChildRef::Task(session.id.clone());
        let revoked = session.latest_process.as_ref().expect("generation").clone();
        let _tmux = crate::engine::process::FakeTmux::no_session();

        // A generation that is not the revoked one is refused.
        let mismatched = ChildProcessGeneration {
            generation: revoked.generation + 1,
            ..revoked.clone()
        };
        assert!(
            crate::ops::child::release_dead_revoked_child_body(&store, &target, &mismatched)
                .await
                .is_err(),
            "a release must not settle a generation the store is not holding"
        );

        // The real one settles once.
        crate::ops::child::release_dead_revoked_child_body(&store, &target, &revoked)
            .await
            .expect("release the matching generation")
            .expect("a provably absent body releases");

        // A lease no longer at `revoked` is not releasable again — no double settle.
        let settled = store.get_task_session(&session.id).await.unwrap().unwrap();
        let finished = settled.latest_process.as_ref().expect("generation").clone();
        assert!(
            crate::ops::child::release_dead_revoked_child_body(&store, &target, &finished)
                .await
                .expect("a finished lease is a no-op, not an error")
                .is_none()
        );
    }

    /// The other half of the boundary: a body that is still there keeps its
    /// lease, and the refusal names the lease rather than blaming the status.
    #[tokio::test]
    async fn a_live_group_keeps_its_lease_and_the_refusal_names_it() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let mut child = std::process::Command::new("/bin/sh")
            .arg("-c")
            .arg("sleep 60")
            .process_group(0)
            .spawn()
            .expect("spawn a live process group");
        let live_group = child.id();
        let (_home, store, mut session) = dead_lease_task(
            &repo,
            "jack/eng-4-live",
            &base,
            TaskSessionStatus::Waiting,
            crate::child_session::ChildLeaseState::Revoked,
            Some(ChildBodyOutcome::Superseded {
                reason: "stalled".to_string(),
            }),
            (Some(live_group), Some(live_group)),
        )
        .await;
        let revoked = session.latest_process.as_ref().expect("generation").clone();

        // Without a deterministic tmux this passes for the WRONG reason on a host
        // with no tmux: the probe reads Unprovable, the release returns None, and
        // `is_none()` below holds while proving nothing about the live group.
        let _tmux = crate::engine::process::FakeTmux::no_session();

        let released = crate::ops::child::release_dead_revoked_child_body(
            &store,
            &ChildRef::Task(session.id.clone()),
            &revoked,
        )
        .await
        .expect("probe a live group");

        // The in-place helper the reservation boundary uses leaves it alone too.
        super::release_dead_revoked_task_lease(&store, &mut session)
            .await
            .expect("a live body is not an error, it is a reason to hold");
        child.kill().expect("kill the live group");
        child.wait().expect("reap the live group");

        assert!(released.is_none(), "a live body must keep its lease");
        assert_eq!(
            session.latest_process.as_ref().map(|process| process.state),
            Some(crate::child_session::ChildLeaseState::Revoked)
        );
        let persisted = store.get_task_session(&session.id).await.unwrap().unwrap();
        assert_eq!(
            persisted.latest_process.map(|process| process.state),
            Some(crate::child_session::ChildLeaseState::Revoked),
            "the lease must still be doing its job in the store"
        );
    }

    /// An unprovable identity is not absence. `process_target_exists` answers
    /// `false` — "absent" — to an id that does not fit `i32`; a release that
    /// reused it would unbar a second body over a generation nobody could ask
    /// about.
    #[tokio::test]
    async fn an_unprovable_identity_does_not_release_the_lease() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let unaddressable = u32::try_from(i32::MAX).expect("i32::MAX fits u32") + 1;
        let (_home, store, session) = dead_lease_task(
            &repo,
            "jack/eng-4-unprovable",
            &base,
            TaskSessionStatus::Waiting,
            crate::child_session::ChildLeaseState::Revoked,
            Some(ChildBodyOutcome::Superseded {
                reason: "stalled".to_string(),
            }),
            (None, Some(unaddressable)),
        )
        .await;
        let revoked = session.latest_process.as_ref().expect("generation").clone();

        // tmux answers, so the Unprovable asserted below is the identity's.
        let _tmux = crate::engine::process::FakeTmux::no_session();

        let released = crate::ops::child::release_dead_revoked_child_body(
            &store,
            &ChildRef::Task(session.id.clone()),
            &revoked,
        )
        .await
        .expect("an unprovable probe is not an error");

        assert!(released.is_none());
        let persisted = store.get_task_session(&session.id).await.unwrap().unwrap();
        assert_eq!(
            persisted.latest_process.map(|process| process.state),
            Some(crate::child_session::ChildLeaseState::Revoked)
        );
    }

    #[tokio::test]
    // Liveness resolves tmux off the process-global PATH, which a concurrent
    // `TaskLaunchEnv` test replaces with a fake that answers "alive".
    #[allow(clippy::await_holding_lock)] // the env lock serializes process-global launch vars
    async fn resume_revokes_a_dead_legacy_lease_on_a_waiting_task() {
        let _env_lock = crate::journal::test_env_lock();
        // W2-135: a Waiting Task still pinned by a Legacy lease whose body vanished.
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let (_home, store, mut session) = dead_lease_task(
            &repo,
            "jack/w2-135",
            &base,
            TaskSessionStatus::Waiting,
            crate::child_session::ChildLeaseState::Legacy,
            None,
            (None, None),
        )
        .await;

        reconcile_process_liveness(&store, &mut session)
            .await
            .expect("reconcile a waiting task with a dead legacy lease");

        // The dead lease is reaped so the resume can reserve a fresh body...
        assert_eq!(
            session.latest_process.as_ref().map(|process| process.state),
            Some(crate::child_session::ChildLeaseState::Finished)
        );
        // ...while the Session keeps its Waiting status for the resume that follows.
        assert_eq!(session.status, TaskSessionStatus::Waiting);

        let persisted = store.get_task_session(&session.id).await.unwrap().unwrap();
        assert_eq!(
            persisted.latest_process.map(|process| process.state),
            Some(crate::child_session::ChildLeaseState::Finished)
        );
        assert_eq!(persisted.status, TaskSessionStatus::Waiting);
    }

    #[tokio::test]
    // Liveness resolves tmux off the process-global PATH, which a concurrent
    // `TaskLaunchEnv` test replaces with a fake that answers "alive".
    #[allow(clippy::await_holding_lock)] // the env lock serializes process-global launch vars
    async fn resume_revokes_a_dead_active_lease_on_a_failed_task() {
        let _env_lock = crate::journal::test_env_lock();
        // W2-122: a Failed Task still holding an Active lease whose body vanished.
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let (_home, store, mut session) = dead_lease_task(
            &repo,
            "jack/w2-122",
            &base,
            TaskSessionStatus::Failed,
            crate::child_session::ChildLeaseState::Active,
            None,
            (None, None),
        )
        .await;

        reconcile_process_liveness(&store, &mut session)
            .await
            .expect("reconcile a failed task with a dead active lease");

        assert_eq!(
            session.latest_process.as_ref().map(|process| process.state),
            Some(crate::child_session::ChildLeaseState::Finished)
        );
        assert_eq!(session.status, TaskSessionStatus::Failed);

        let persisted = store.get_task_session(&session.id).await.unwrap().unwrap();
        assert_eq!(
            persisted.latest_process.map(|process| process.state),
            Some(crate::child_session::ChildLeaseState::Finished)
        );
        assert_eq!(persisted.status, TaskSessionStatus::Failed);
    }

    #[tokio::test]
    async fn stalled_delivery_is_reaped_and_waits_without_replay() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let (_home, store, mut session, _pr) =
            rotation_task(&repo, "jack/stalled-delivery", &base).await;
        session.begin_generation(format!("stalled-body-{}", session.id));
        let lease = store
            .reserve_task_process(&session, TaskSessionStatus::Waiting)
            .await
            .unwrap()
            .expect("reserve stalled body");

        let mut child = std::process::Command::new("/bin/sh")
            .arg("-c")
            .arg("sleep 60 & echo $!; wait")
            .process_group(0)
            .stdout(std::process::Stdio::piped())
            .spawn()
            .expect("spawn stalled process group");
        let group = child.id();
        let stdout = child.stdout.take().expect("capture grandchild pid");
        let mut line = String::new();
        BufReader::new(stdout)
            .read_line(&mut line)
            .expect("read grandchild pid");
        let grandchild: u32 = line.trim().parse().expect("grandchild pid");
        let waiter = std::thread::spawn(move || child.wait().expect("reap shell"));

        let process = session.latest_process.as_mut().expect("reserved process");
        process.pid = Some(group);
        process.process_group_id = Some(group);
        process.state = ChildLeaseState::Active;
        session.set_status(TaskSessionStatus::Running, "fake provider is alive");
        store.activate_task_process(&session, &lease).await.unwrap();

        let mut command = ChildCommand::new(
            ChildRef::Task(session.id.clone()),
            ChildCommandSource::Human,
            ChildCommandKind::Steer {
                text: "do the external thing".to_string(),
            },
        );
        store.create_child_command(&command).await.unwrap();
        let claimed = store
            .claim_child_commands_for_lease(&command.target, &lease)
            .await
            .unwrap();
        command = claimed.into_iter().next().expect("claimed command");
        store
            .mark_child_command_delivering_for_lease(
                &command.target,
                &lease,
                &command.id,
                crate::child_session::ChildCommandEffect::LiveSteer,
            )
            .await
            .unwrap();
        session = store.get_task_session(&session.id).await.unwrap().unwrap();

        let observation = observe(
            &BodyEvidence {
                intent: BodyIntent::Active,
                observable: true,
                process_alive: true,
                progress_age: Duration::from_secs(31 * 60),
                step: Some("task_pursue".to_string()),
                reason: "fake provider is alive".to_string(),
            },
            Duration::from_secs(30 * 60),
        );
        let latest_event_id = store
            .latest_task_event(&session.id)
            .await
            .unwrap()
            .map(|event| event.id);
        assert!(
            recover_stalled_task_body(&store, session.clone(), &observation, latest_event_id,)
                .await
                .unwrap()
        );
        waiter.join().unwrap();

        // SAFETY: signal 0 is an existence probe and uses no pointers.
        assert_ne!(unsafe { libc::kill(group as i32, 0) }, 0);
        // SAFETY: signal 0 is an existence probe and uses no pointers.
        assert_ne!(unsafe { libc::kill(grandchild as i32, 0) }, 0);
        let persisted = store.get_task_session(&session.id).await.unwrap().unwrap();
        assert_eq!(persisted.status, TaskSessionStatus::Waiting);
        assert_eq!(
            persisted.latest_process.map(|process| process.state),
            Some(ChildLeaseState::Finished)
        );
        assert!(persisted.status_reason.contains(command.id.as_str()));
        let receipt = store.get_child_command(&command.id).await.unwrap().unwrap();
        assert_eq!(receipt.state, ChildCommandState::Uncertain);
    }

    #[tokio::test]
    async fn progress_wins_the_race_against_stall_recovery() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let (_home, store, mut session, _pr) =
            rotation_task(&repo, "jack/progress-race", &base).await;
        session.begin_generation(format!("progress-race-{}", session.id));
        let lease = store
            .reserve_task_process(&session, TaskSessionStatus::Waiting)
            .await
            .unwrap()
            .expect("reserve body");
        session
            .latest_process
            .as_mut()
            .expect("reserved process")
            .state = ChildLeaseState::Active;
        session.set_status(TaskSessionStatus::Running, "provider is alive");
        store.activate_task_process(&session, &lease).await.unwrap();
        session = store.get_task_session(&session.id).await.unwrap().unwrap();
        let observed_event_id = store
            .latest_task_event(&session.id)
            .await
            .unwrap()
            .map(|event| event.id);

        store
            .append_task_event(
                &session.id,
                &TaskEventKind::Progress {
                    summary: "body advanced before revocation".to_string(),
                },
            )
            .await
            .unwrap();
        let revoked = store
            .revoke_task_process_if_unchanged(
                &session.id,
                1,
                session.status_at,
                observed_event_id,
                &ChildBodyOutcome::Superseded {
                    reason: "stale observation".to_string(),
                },
            )
            .await
            .unwrap();

        assert!(revoked.is_none());
        let persisted = store.get_task_session(&session.id).await.unwrap().unwrap();
        assert_eq!(
            persisted.latest_process.map(|process| process.state),
            Some(ChildLeaseState::Active),
        );
        assert_eq!(persisted.status, TaskSessionStatus::Running);
    }

    #[test]
    fn readable_task_names_are_semantic_and_bounded() {
        assert_eq!(
            derive_workspace_slug("Release scoped migrations across every target")
                .unwrap()
                .as_str(),
            "release-scoped-migrations-across-every"
        );
        assert_eq!(
            derive_workspace_slug("Investigate").unwrap().as_str(),
            "investigate-task"
        );
        assert!(parse_workspace_slug("one").is_err());
        assert!(parse_workspace_slug("release_scoped-migrations").is_err());
        assert_eq!(
            parse_pr_slug("released-upgrade-proof").unwrap(),
            "released-upgrade-proof"
        );
        assert!(parse_pr_slug("released/upgrade").is_err());
    }

    #[test]
    fn succession_slug_is_distinct_capped_and_per_predecessor() {
        // A successor's slug must differ from its predecessor's so the successor
        // can place a fresh worktree when the terminal predecessor's still
        // occupies disk. The base is capped at four words so the `-s<tail>`
        // suffix word keeps the segment within the 2-5 word limit.
        let title = "Release scoped migrations across every target";
        let base = derive_workspace_slug(title).unwrap();
        assert_eq!(base.as_str(), "release-scoped-migrations-across-every");

        let pred_a = TaskSessionId::new();
        let pred_b = TaskSessionId::new();
        let succ_a = succession_workspace_slug(title, &pred_a).unwrap();
        let succ_b = succession_workspace_slug(title, &pred_b).unwrap();

        // Distinct from the predecessor slug and from each other.
        assert_ne!(succ_a.as_str(), base.as_str());
        assert_ne!(succ_a.as_str(), succ_b.as_str());

        // Valid and within the 2-5 word bound; the base is capped at four words.
        let words = succ_a.as_str().split('-').count();
        assert!(
            (2..=5).contains(&words),
            "got {words} words in {}",
            succ_a.as_str()
        );
        // The four-word cap holds: the longest title still leaves room for the suffix.
        let capped =
            succession_workspace_slug("one two three four five six seven", &pred_a).unwrap();
        assert_eq!(
            capped.as_str().split('-').count(),
            5,
            "four base words + one suffix word"
        );
    }

    #[tokio::test]
    async fn settled_pr_rotates_the_same_worktree_from_fetched_main() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let first_branch = "jack/task-pr-proof";
        repo.create_branch(first_branch);
        repo.create_file("first.txt", "first PR\n");
        repo.stage_all();
        repo.commit("first PR");
        let (_home, store, mut session, mut first) =
            rotation_task(&repo, first_branch, &base).await;
        first.publication = Some(PrPublication {
            requested_at: OffsetDateTime::now_utc(),
            after_merge: AfterMerge::Review,
            next_slug: Some("follow-up-proof".to_string()),
            github: Some(GithubPr {
                number: 911,
                url: "https://example.com/pr/911".to_string(),
                head_sha: None,
            }),
        });
        first.merge_commit = Some("merge-911".to_string());
        first.updated_at = OffsetDateTime::now_utc();
        store
            .settle_task_pr(&first, None)
            .await
            .expect("settle first PR");

        let second = ensure_working_pr(&store, &mut session)
            .await
            .expect("rotate PR")
            .expect("working PR");

        assert_eq!(session.worktree, repo.path());
        assert_eq!(second.sequence, 2);
        assert_eq!(second.branch, "jack/task-pr-proof-follow-up-proof");
        assert_eq!(second.base_commit, base);
        assert_eq!(second.phase(), PrPhase::Working);
        assert_eq!(
            git(repo.path(), &["rev-parse", "--abbrev-ref", "HEAD"]),
            second.branch
        );
        let prs = store.task_prs(&session.id).await.expect("read PR history");
        assert_eq!(prs.iter().map(|pr| pr.sequence).collect::<Vec<_>>(), [1, 2]);
        assert_eq!(prs[0].phase(), PrPhase::Merged);
        assert_eq!(prs[1].id, second.id);
    }

    /// The state only a re-mint can produce: sequence 1 merged, the successor
    /// branch already cut at `b1` and left checked out — the documented
    /// "partial rotation adopted" shape — with `origin/main` advanced to `b2`
    /// underneath it. A first mint cuts the branch at its base, so the pair
    /// agrees by accident and the defect is invisible; only main moving under an
    /// already-positioned branch separates base from branch.
    struct RemintFixture {
        _home: tempfile::TempDir,
        repo: TestRepo,
        store: SharedStore,
        session: TaskSession,
        settled: TaskPr,
        b1: String,
        b2: String,
    }

    impl RemintFixture {
        const SUCCESSOR: &str = "jack/task-pr-proof-2";

        /// `carry` names a file committed onto the successor before main moves.
        async fn new(carry: Option<&str>) -> Self {
            let repo = TestRepo::new();
            let b1 = repo.head_sha();
            let settled_branch = "jack/task-pr-proof";
            repo.create_branch(settled_branch);
            repo.create_file("first.txt", "first PR\n");
            repo.stage_all();
            repo.commit("first PR");
            let (home, store, session, mut settled) =
                rotation_task(&repo, settled_branch, &b1).await;
            settled.publication = Some(PrPublication {
                requested_at: OffsetDateTime::now_utc(),
                after_merge: AfterMerge::Review,
                next_slug: None,
                github: Some(GithubPr {
                    number: 1050,
                    url: "https://example.com/pr/1050".to_string(),
                    head_sha: None,
                }),
            });
            settled.merge_commit = Some("merge-1050".to_string());
            settled.updated_at = OffsetDateTime::now_utc();

            git(repo.path(), &["checkout", "-b", Self::SUCCESSOR, &b1]);
            if let Some(file) = carry {
                repo.create_file(file, "work a partial rotation already carried\n");
                repo.stage_all();
                repo.commit("carried follow-up");
            }
            repo.checkout("main");
            repo.create_file("elsewhere.txt", "another PR merged\n");
            repo.stage_all();
            repo.commit("main advances");
            repo.push();
            let b2 = repo.head_sha();
            assert_ne!(b1, b2, "origin/main must move or the defect cannot show");
            repo.checkout(Self::SUCCESSOR);

            Self {
                _home: home,
                repo,
                store,
                session,
                settled,
                b1,
                b2,
            }
        }

        async fn settle(&self, next: Option<&TaskPr>) {
            self.store
                .settle_task_pr(&self.settled, next)
                .await
                .expect("settle merged PR");
        }

        async fn rotate(&mut self) -> TaskPr {
            ensure_working_pr(&self.store, &mut self.session)
                .await
                .expect("rotate")
                .expect("working PR")
        }

        fn cut(&self, pr: &TaskPr) -> CommittedFollowUp {
            unpublished_work(&self.session.worktree, pr).expect("classify")
        }

        /// An unpublished successor row recording `base`, as a past mint would have.
        fn successor_row(&self, base: &str) -> TaskPr {
            let mut pr = self.settled.clone();
            pr.id = TaskPrId::new();
            pr.sequence = 2;
            pr.slug = "2".to_string();
            pr.branch = Self::SUCCESSOR.to_string();
            pr.base_commit = base.to_string();
            pr.publication = None;
            pr.merge_commit = None;
            pr.created_at = OffsetDateTime::now_utc();
            pr.updated_at = OffsetDateTime::now_utc();
            pr
        }

        /// A commit on a sibling branch off `b1` — never on the upstream line.
        fn sibling_commit(&self) -> String {
            git(
                self.repo.path(),
                &["checkout", "-b", "jack/sibling", &self.b1],
            );
            self.repo
                .create_file("sibling.txt", "another branch's work\n");
            self.repo.stage_all();
            self.repo.commit("sibling work");
            let tip = self.repo.head_sha();
            self.repo.checkout(Self::SUCCESSOR);
            tip
        }
    }

    /// Sabotage: record `resolve_upstream_base`'s `base_commit` again and this
    /// goes red, while every first-mint rotation test stays green.
    #[tokio::test]
    async fn a_re_mint_after_main_advances_records_the_base_its_branch_forks_from() {
        let mut fx = RemintFixture::new(None).await;
        fx.settle(None).await;

        let next = fx.rotate().await;

        assert_eq!(next.sequence, 2);
        assert_eq!(next.branch, RemintFixture::SUCCESSOR);
        assert_eq!(
            next.base_commit, fx.b1,
            "the fork point of the reused branch, not the upstream tip"
        );
        assert_ne!(next.base_commit, fx.b2);
        assert!(
            is_ancestor(fx.repo.path(), &next.base_commit, &next.branch).expect("ancestry"),
            "the recorded base must be an ancestor of its branch"
        );
        assert!(matches!(fx.cut(&next), CommittedFollowUp::ProvenEmpty));
    }

    /// Recording the branch tip instead would read `ProvenEmpty` here and let the
    /// gate discard committed work — the fail-open hole #1050 closed.
    #[tokio::test]
    async fn a_re_mint_holding_committed_work_still_reads_range() {
        let mut fx = RemintFixture::new(Some("carried.txt")).await;
        fx.settle(None).await;
        let carried_tip = fx.repo.head_sha();

        let next = fx.rotate().await;

        assert_eq!(
            next.base_commit, fx.b1,
            "the fork point, not the carried tip"
        );
        assert_ne!(next.base_commit, carried_tip);
        assert!(matches!(fx.cut(&next), CommittedFollowUp::Range { .. }));
    }

    /// The live repair: a row an older mint already wrote heals on adopt, so
    /// W2-300's wedged successor becomes provable.
    #[tokio::test]
    async fn an_incoherent_recorded_base_is_healed_when_the_active_pr_is_adopted() {
        let mut fx = RemintFixture::new(None).await;
        // Exactly W2-300's row: base at the newer main tip, branch still at the
        // older — the legacy signature, M <= B <= upstream.
        let incoherent = fx.successor_row(&fx.b2);
        fx.settle(Some(&incoherent)).await;
        assert!(
            matches!(fx.cut(&incoherent), CommittedFollowUp::Unprovable { .. }),
            "fixture must start wedged, or it proves nothing"
        );

        let adopted = fx.rotate().await;

        assert_eq!(
            adopted.id, incoherent.id,
            "the same row, healed — not a new one"
        );
        assert_eq!(adopted.base_commit, fx.b1);
        assert!(matches!(fx.cut(&adopted), CommittedFollowUp::ProvenEmpty));
        let stored = fx
            .store
            .task_prs(&fx.session.id)
            .await
            .expect("read PR history")
            .into_iter()
            .find(|pr| pr.sequence == 2)
            .expect("successor row");
        assert_eq!(stored.base_commit, fx.b1, "the heal must reach the store");
    }

    /// A foreign base is not a stale mint and must stay fail-closed. It is built
    /// so the true fork point IS its ancestor (M <= B holds), which is what makes
    /// this catch an M<=B-only heal: only `B <= upstream` separates the legacy
    /// signature from contamination.
    #[tokio::test]
    async fn a_recorded_base_off_the_upstream_line_is_refused_not_healed() {
        let mut fx = RemintFixture::new(None).await;
        let sibling = fx.sibling_commit();
        let foreign = fx.successor_row(&sibling);
        fx.settle(Some(&foreign)).await;

        // The two preconditions that give this test its teeth.
        assert!(
            is_ancestor(fx.repo.path(), &fx.b1, &sibling).expect("ancestry"),
            "M <= B must hold, or an M<=B-only heal would refuse this anyway and the test proves nothing"
        );
        assert!(
            !is_ancestor(fx.repo.path(), &sibling, "origin/main").expect("ancestry"),
            "B must be off the upstream line"
        );
        assert!(matches!(
            fx.cut(&foreign),
            CommittedFollowUp::Unprovable { .. }
        ));

        let adopted = fx.rotate().await;

        assert_eq!(
            adopted.base_commit, sibling,
            "a base no past mint could have written must not be healed"
        );
        assert!(
            matches!(fx.cut(&adopted), CommittedFollowUp::Unprovable { .. }),
            "contamination stays Unprovable — the gate keeps refusing"
        );
        let stored = fx
            .store
            .task_prs(&fx.session.id)
            .await
            .expect("read PR history")
            .into_iter()
            .find(|pr| pr.sequence == 2)
            .expect("successor row");
        assert_eq!(stored.base_commit, sibling, "the store row is untouched");
    }

    #[tokio::test]
    async fn rotate_forward_carries_uncommitted_follow_up_edits() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let first_branch = "jack/task-pr-proof";
        repo.create_branch(first_branch);
        repo.create_file("first.txt", "first PR\n");
        repo.stage_all();
        repo.commit("first PR");
        let (_home, store, mut session, mut first) =
            rotation_task(&repo, first_branch, &base).await;
        first.publication = Some(PrPublication {
            requested_at: OffsetDateTime::now_utc(),
            after_merge: AfterMerge::Review,
            next_slug: None,
            github: Some(GithubPr {
                number: 907,
                url: "https://example.com/pr/907".to_string(),
                head_sha: None,
            }),
        });
        first.merge_commit = Some("merge-907".to_string());
        first.updated_at = OffsetDateTime::now_utc();
        store
            .settle_task_pr(&first, None)
            .await
            .expect("settle first PR");

        // The worker stopped before pushing: follow-up work sits uncommitted.
        repo.create_file("follow-up.txt", "second PR work\n");

        // The runner's strict path refuses to rotate over a dirty tree.
        assert!(ensure_working_pr(&store, &mut session.clone())
            .await
            .is_err());

        let second = ensure_working_pr_with_authority(
            &store,
            &mut session,
            None,
            RotateOptions {
                carry_dirty: true,
                slug_override: Some("keep-going".to_string()),
            },
        )
        .await
        .expect("rotate forward")
        .expect("working PR");

        assert_eq!(second.sequence, 2);
        assert_eq!(second.branch, "jack/task-pr-proof-keep-going");
        assert_eq!(second.base_commit, base);
        assert_eq!(second.phase(), PrPhase::Working);
        assert_eq!(
            git(repo.path(), &["rev-parse", "--abbrev-ref", "HEAD"]),
            second.branch
        );
        // The preserved follow-up edit survived the rotation onto the new branch.
        assert_eq!(
            std::fs::read_to_string(repo.path().join("follow-up.txt")).expect("follow-up survives"),
            "second PR work\n"
        );
        let prs = store.task_prs(&session.id).await.expect("read PR history");
        assert_eq!(prs.iter().map(|pr| pr.sequence).collect::<Vec<_>>(), [1, 2]);
        assert_eq!(prs[0].phase(), PrPhase::Merged);
    }

    #[tokio::test]
    async fn reconcile_degrades_and_preserves_cache_when_the_github_read_fails() {
        // A published PR whose remote can't be read (TestRepo's origin is a local
        // bare repo, not GitHub, so the read cannot resolve) must not error
        // reconcile: the cached row stands and freshness degrades. This is what
        // keeps follow-up/steer/status usable during a quota or network outage —
        // each funnels through reconcile, which previously `?`-failed on the read.
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let branch = "jack/task-pr-proof";
        repo.create_branch(branch);
        repo.create_file("first.txt", "first PR\n");
        repo.stage_all();
        repo.commit("first PR");
        let (_home, store, mut session, mut pr) = rotation_task(&repo, branch, &base).await;
        pr.publication = Some(PrPublication {
            requested_at: OffsetDateTime::now_utc(),
            after_merge: AfterMerge::Review,
            next_slug: None,
            github: Some(GithubPr {
                number: 914,
                url: "https://example.com/pr/914".to_string(),
                head_sha: None,
            }),
        });
        pr.updated_at = OffsetDateTime::now_utc();
        store.update_task_pr(&pr).await.expect("publish PR");

        let observed = reconcile_task_pr(&store, &mut session)
            .await
            .expect("reconcile does not error on a failed GitHub read")
            .expect("the cached PR is preserved");

        // Cache stands: still Open, no merge fabricated from a failed read.
        assert_eq!(observed.phase(), PrPhase::Open);
        assert_eq!(observed.merge_commit, None);
        match &session.observation {
            Observation::Degraded { reason, .. } => assert!(!reason.is_empty()),
            other => panic!("a failed GitHub read must degrade freshness, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn reconcile_skips_the_remote_read_for_an_unpublished_working_pr() {
        // A working PR has no persisted number; reconcile must neither enumerate
        // nor read remotely. Proof: a read here WOULD fail (no GitHub origin), yet
        // freshness says no read was required.
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let branch = "jack/task-pr-proof";
        repo.create_branch(branch);
        let (_home, store, mut session, pr) = rotation_task(&repo, branch, &base).await;
        assert!(pr.github().is_none(), "fixture PR is unpublished");

        let observed = reconcile_task_pr(&store, &mut session)
            .await
            .expect("reconcile succeeds")
            .expect("working PR preserved");

        assert_eq!(observed.phase(), PrPhase::Working);
        assert_eq!(session.observation, Observation::NotRequired);
    }

    #[test]
    fn github_observation_cache_expires_fresh_reads_before_degraded_circuits() {
        let now = OffsetDateTime::now_utc();
        let mut pr = TaskPr {
            id: TaskPrId::new(),
            task_session_id: TaskSessionId::new(),
            sequence: 1,
            slug: "cache-proof".to_string(),
            branch: "jack/cache-proof".to_string(),
            base_commit: "base".to_string(),
            parent_pr_id: None,
            publication: None,
            merge_commit: None,
            abandoned_at: None,
            ci_observation: None,
            github_observation: Some(GithubObservation {
                checked_at: now - time::Duration::seconds(59),
                result: GithubObservationResult::Fresh,
            }),
            linear_attachment_id: None,
            linear_comment_id: None,
            linear_link_error: None,
            created_at: now,
            updated_at: now - time::Duration::hours(1),
        };
        assert!(matches!(
            cached_github_observation(&pr, now),
            Some(Observation::Cached { .. })
        ));
        pr.github_observation.as_mut().unwrap().checked_at = now - time::Duration::seconds(60);
        assert_eq!(cached_github_observation(&pr, now), None);

        pr.github_observation = Some(GithubObservation {
            checked_at: now - time::Duration::minutes(4),
            result: GithubObservationResult::Degraded {
                reason: "rate limit exhausted".to_string(),
            },
        });
        assert!(matches!(
            cached_github_observation(&pr, now),
            Some(Observation::Degraded { .. })
        ));
        pr.github_observation.as_mut().unwrap().checked_at = now - time::Duration::minutes(5);
        assert_eq!(cached_github_observation(&pr, now), None);
    }

    #[tokio::test]
    async fn rotate_carries_committed_follow_up_and_dirty_edits_after_an_out_of_band_merge() {
        // W2-166 shape: PR merged out of band, then the worker committed *unique*
        // follow-up work on the settled branch plus left a dirty edit. Rotating to
        // the next serial PR must carry BOTH the committed range and the dirty
        // edit — and never re-apply the already-merged work.
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let settled_branch = "jack/task-pr-proof";
        repo.create_branch(settled_branch);
        repo.create_file("merged.txt", "merged work\n");
        repo.stage_all();
        repo.commit("merged work");
        let merged_tip = repo.head_sha();
        // The merge landed on main (simulated by advancing origin/main to the tip
        // GitHub merged), so the rotated branch bases on main which already
        // carries the merged work.
        git(repo.path(), &["push", "origin", "jack/task-pr-proof:main"]);

        // Post-merge follow-up: two committed commits, then an uncommitted edit.
        repo.create_file("follow1.txt", "follow-up one\n");
        repo.stage_all();
        repo.commit("follow-up one");
        repo.create_file("follow2.txt", "follow-up two\n");
        repo.stage_all();
        repo.commit("follow-up two");
        repo.create_file("wip.txt", "uncommitted work\n");

        let (_home, store, mut session, mut settled) =
            rotation_task(&repo, settled_branch, &base).await;
        settled.publication = Some(PrPublication {
            requested_at: OffsetDateTime::now_utc(),
            after_merge: AfterMerge::Review,
            next_slug: Some("keep-going".to_string()),
            github: Some(GithubPr {
                number: 907,
                url: "https://example.com/pr/907".to_string(),
                // The merged branch tip — the cut between merged work and follow-up.
                head_sha: Some(merged_tip.clone()),
            }),
        });
        settled.merge_commit = Some("merge-907".to_string());
        settled.updated_at = OffsetDateTime::now_utc();
        store
            .settle_task_pr(&settled, None)
            .await
            .expect("settle merged PR");

        let next = ensure_working_pr_with_authority(
            &store,
            &mut session,
            None,
            RotateOptions {
                carry_dirty: true,
                slug_override: Some("keep-going".to_string()),
            },
        )
        .await
        .expect("rotate forward")
        .expect("working PR");

        assert_eq!(next.sequence, 2);
        assert_eq!(
            git(repo.path(), &["rev-parse", "--abbrev-ref", "HEAD"]),
            next.branch
        );
        // Committed follow-up carried forward.
        assert_eq!(
            std::fs::read_to_string(repo.path().join("follow1.txt")).expect("follow1 carried"),
            "follow-up one\n"
        );
        assert_eq!(
            std::fs::read_to_string(repo.path().join("follow2.txt")).expect("follow2 carried"),
            "follow-up two\n"
        );
        // Dirty edit carried forward, still uncommitted.
        assert_eq!(
            std::fs::read_to_string(repo.path().join("wip.txt")).expect("dirty edit carried"),
            "uncommitted work\n"
        );
        // The already-merged work lives in the base, not re-applied as a commit:
        // exactly the two follow-up commits sit beyond origin/main.
        let beyond = git(
            repo.path(),
            &["log", "origin/main..HEAD", "--oneline", "--format=%s"],
        );
        let subjects: Vec<&str> = beyond.lines().collect();
        assert_eq!(subjects, vec!["follow-up two", "follow-up one"]);
        // The merged work is present exactly once (from the base), not duplicated.
        assert!(repo.path().join("merged.txt").exists());
    }

    #[tokio::test]
    async fn a_completing_pr_rotates_only_to_carry_committed_follow_up() {
        // A completing PR has nothing to rotate to — except follow-up committed
        // past the merged tip (W2-293), which the completion gate refuses to
        // settle over. Both halves read the same range, so both are proven here.
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let settled_branch = "jack/task-pr-proof";
        repo.create_branch(settled_branch);
        repo.create_file("merged.txt", "merged work\n");
        repo.stage_all();
        repo.commit("merged work");
        let merged_tip = repo.head_sha();
        git(repo.path(), &["push", "origin", "jack/task-pr-proof:main"]);

        let (_home, store, mut session, mut settled) =
            rotation_task(&repo, settled_branch, &base).await;
        settled.publication = Some(PrPublication {
            requested_at: OffsetDateTime::now_utc(),
            after_merge: AfterMerge::CompleteTask,
            next_slug: None,
            github: Some(GithubPr {
                number: 1042,
                url: "https://example.com/pr/1042".to_string(),
                head_sha: Some(merged_tip.clone()),
            }),
        });
        settled.merge_commit = Some("merge-1042".to_string());
        settled.updated_at = OffsetDateTime::now_utc();
        store
            .settle_task_pr(&settled, None)
            .await
            .expect("settle merged completing PR");

        // Nothing past the merged tip: the completing PR does not rotate.
        let none =
            ensure_working_pr_with_authority(&store, &mut session, None, RotateOptions::runner())
                .await
                .expect("completing PR with no follow-up");
        assert!(
            none.is_none(),
            "a completing PR with no follow-up must not mint a successor"
        );

        // The body commits the follow-up its directive asked for, after the merge.
        repo.create_file("follow-up.txt", "acknowledged follow-up\n");
        repo.stage_all();
        repo.commit("follow-up the directive asked for");

        let next =
            ensure_working_pr_with_authority(&store, &mut session, None, RotateOptions::runner())
                .await
                .expect("rotate to carry follow-up")
                .expect("successor PR");

        assert_eq!(next.sequence, 2);
        assert_eq!(
            git(repo.path(), &["rev-parse", "--abbrev-ref", "HEAD"]),
            next.branch
        );
        // The follow-up survives on the successor, and only the follow-up: the
        // merged work rides in from the base rather than being re-applied.
        assert_eq!(
            std::fs::read_to_string(repo.path().join("follow-up.txt")).expect("follow-up carried"),
            "acknowledged follow-up\n"
        );
        let beyond = git(
            repo.path(),
            &["log", "origin/main..HEAD", "--oneline", "--format=%s"],
        );
        assert_eq!(
            beyond.lines().collect::<Vec<_>>(),
            vec!["follow-up the directive asked for"]
        );
    }

    #[tokio::test]
    async fn failed_committed_carry_restores_the_settled_branch_for_retry() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let settled_branch = "jack/task-pr-proof";
        repo.create_branch(settled_branch);
        repo.create_file("shared.txt", "merged\n");
        repo.stage_all();
        repo.commit("merged work");
        let merged_tip = repo.head_sha();

        // Main and the post-merge follow-up edit the same line differently, so
        // carrying the follow-up onto current main must conflict.
        git(repo.path(), &["checkout", "-b", "main-update", &merged_tip]);
        repo.create_file("shared.txt", "main moved on\n");
        repo.stage_all();
        repo.commit("main update");
        git(repo.path(), &["push", "origin", "main-update:main"]);
        git(repo.path(), &["checkout", settled_branch]);
        repo.create_file("shared.txt", "follow-up edit\n");
        repo.stage_all();
        repo.commit("post-merge follow-up");
        repo.create_file("wip.txt", "dirty follow-up\n");

        let (_home, store, mut session, mut settled) =
            rotation_task(&repo, settled_branch, &base).await;
        settled.publication = Some(PrPublication {
            requested_at: OffsetDateTime::now_utc(),
            after_merge: AfterMerge::Review,
            next_slug: None,
            github: Some(GithubPr {
                number: 918,
                url: "https://example.com/pr/918".to_string(),
                head_sha: Some(merged_tip),
            }),
        });
        settled.merge_commit = Some("merge-918".to_string());
        settled.updated_at = OffsetDateTime::now_utc();
        store
            .settle_task_pr(&settled, None)
            .await
            .expect("settle merged PR");

        let error = ensure_working_pr_with_authority(
            &store,
            &mut session,
            None,
            RotateOptions {
                carry_dirty: true,
                slug_override: Some("retry".to_string()),
            },
        )
        .await
        .expect_err("conflicting carry must fail");

        assert!(error.to_string().contains("restored"));
        assert_eq!(
            git(repo.path(), &["rev-parse", "--abbrev-ref", "HEAD"]),
            settled_branch
        );
        assert_eq!(
            std::fs::read_to_string(repo.path().join("shared.txt")).expect("commit restored"),
            "follow-up edit\n"
        );
        assert_eq!(
            std::fs::read_to_string(repo.path().join("wip.txt")).expect("dirty edit restored"),
            "dirty follow-up\n"
        );
        assert_eq!(
            git(repo.path(), &["branch", "--list", "*/task-pr-proof-retry"]),
            ""
        );
        assert_eq!(git(repo.path(), &["stash", "list"]), "");
    }

    #[test]
    fn task_control_json_reports_durable_state_and_effect() {
        let result = TaskControlResult {
            issue_id: "INF-123".to_string(),
            session_id: "ts_example".to_string(),
            command_id: "cc_example".to_string(),
            directive_version: Some(2),
            state: crate::child_session::ChildCommandState::Accepted,
            effect: Some(crate::child_session::ChildCommandEffect::LiveSteer),
            incorporated: true,
            generation: Some(2),
            accepted_at: None,
            incorporated_at: None,
            error: None,
            observation: Observation::NotRequired,
        };

        assert_eq!(
            serde_json::to_value(result).unwrap(),
            serde_json::json!({
                "issue_id": "INF-123",
                "session_id": "ts_example",
                "command_id": "cc_example",
                "directive_version": 2,
                "state": "accepted",
                "effect": "live_steer",
                "incorporated": true,
                "generation": 2,
                "accepted_at": null,
                "incorporated_at": null,
                "error": null,
                "observation": {"freshness": "not_required"},
            })
        );
    }

    #[test]
    fn task_workspace_reports_committed_staged_unstaged_and_untracked_files() {
        let (repo, base, session_id) = changed_workspace();
        let workspace = TaskWorkspace {
            issue_identifier: "INF-123",
            session_id: &session_id,
            worktree: repo.path(),
            base_commit: &base,
        };

        let snapshot = changes_snapshot(workspace).expect("inspect task changes");
        let committed = snapshot
            .files
            .iter()
            .find(|file| file.path == "committed.txt")
            .expect("committed file");
        assert!(committed.committed);
        let tracked = snapshot
            .files
            .iter()
            .find(|file| file.path == "tracked.txt")
            .expect("tracked file");
        assert!(tracked.staged && tracked.unstaged);
        let untracked = snapshot
            .files
            .iter()
            .find(|file| file.path == "untracked.txt")
            .expect("untracked file");
        assert!(untracked.untracked);

        let patch = diff_snapshot(workspace, None).expect("inspect task diff");
        assert!(patch.patch.contains("committed.txt"));
        assert!(patch.patch.contains("tracked.txt"));
        assert!(patch.patch.contains("untracked.txt"));

        let untracked_patch =
            diff_snapshot(workspace, Some("./untracked.txt")).expect("inspect one file");
        assert_eq!(untracked_patch.path.as_deref(), Some("untracked.txt"));
        assert!(untracked_patch.patch.contains("+untracked"));
    }

    #[test]
    fn task_file_reads_only_files_inside_the_task_worktree() {
        let (repo, base, session_id) = changed_workspace();
        let workspace = TaskWorkspace {
            issue_identifier: "INF-123",
            session_id: &session_id,
            worktree: repo.path(),
            base_commit: &base,
        };

        let file = file_snapshot(workspace, "./tracked.txt").expect("read task file");
        assert_eq!(file.path, "tracked.txt");
        assert_eq!(file.content.as_deref(), Some("unstaged\n"));
        assert!(file_snapshot(workspace, "../outside.txt").is_err());

        #[cfg(unix)]
        {
            let outside = tempfile::NamedTempFile::new().expect("outside file");
            std::os::unix::fs::symlink(outside.path(), repo.path().join("outside-link"))
                .expect("create outside symlink");
            assert!(file_snapshot(workspace, "outside-link").is_err());
        }
    }

    #[tokio::test]
    async fn verify_refuses_a_base_carrying_a_foreign_commit() {
        // The #877/#882 shape: the branch was cut from a local main that carried
        // an unpushed commit, so the recorded base itself is off-origin.
        let repo = TestRepo::new();
        // Advance local main ahead of origin with a foreign commit; never push it.
        repo.create_file("foreign.txt", "not this task's work\n");
        repo.stage_all();
        repo.commit("foreign canonical-main commit");
        let contaminated_base = repo.head_sha();

        let branch = "jack/contaminated";
        repo.create_branch(branch);
        repo.create_file("task.txt", "task work\n");
        repo.stage_all();
        repo.commit("task commit");
        let (_home, store, session, _pr) = rotation_task(&repo, branch, &contaminated_base).await;

        let err = verify_task_pr_range_with_authority(&store, &session, None, repo.path())
            .await
            .expect_err("contaminated base must refuse");
        let message = err.to_string();
        assert!(
            message.contains("contaminated"),
            "expected contamination refusal, got: {message}"
        );
        assert!(
            message.contains("foreign canonical-main commit"),
            "refusal must name the foreign commit, got: {message}"
        );
        assert!(
            message.contains("rebase --onto"),
            "refusal must print the recovery action, got: {message}"
        );
    }

    #[tokio::test]
    async fn verify_heals_a_stale_base_after_origin_advances() {
        let repo = TestRepo::new();
        let stale_base = repo.head_sha(); // origin/main at placement time

        // origin advances: land a commit on main and push it.
        repo.create_file("upstream.txt", "landed upstream\n");
        repo.stage_all();
        repo.commit("upstream advance");
        repo.push();
        let advanced = repo.head_sha();

        // The Task branch already sits on the advanced origin (e.g. after an
        // lf pr open rebase), but the recorded base is still the pre-advance sha.
        let branch = "jack/stale-base";
        repo.create_branch(branch);
        repo.create_file("task.txt", "task work\n");
        repo.stage_all();
        repo.commit("task commit");
        let (_home, store, session, _pr) = rotation_task(&repo, branch, &stale_base).await;

        verify_task_pr_range_with_authority(&store, &session, None, repo.path())
            .await
            .expect("stale-but-compatible base verifies");

        let healed = store
            .active_task_pr(&session.id)
            .await
            .expect("read active PR")
            .expect("active PR exists");
        assert_eq!(
            healed.base_commit, advanced,
            "the stale base should heal forward to the current fork point"
        );
    }

    #[tokio::test]
    async fn verify_falls_back_to_local_main_without_a_remote() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        // Drop the remote entirely: placement fell back to local main.
        git(repo.path(), &["remote", "remove", "origin"]);

        let branch = "jack/no-remote";
        repo.create_branch(branch);
        repo.create_file("task.txt", "task work\n");
        repo.stage_all();
        repo.commit("task commit");
        let (_home, store, session, _pr) = rotation_task(&repo, branch, &base).await;

        verify_task_pr_range_with_authority(&store, &session, None, repo.path())
            .await
            .expect("no-remote repo verifies against local main");
    }

    #[tokio::test]
    async fn verify_passes_for_a_rotated_continuation_pr() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let first_branch = "jack/task-pr-proof";
        repo.create_branch(first_branch);
        repo.create_file("first.txt", "first PR\n");
        repo.stage_all();
        repo.commit("first PR");
        let (_home, store, mut session, mut first) =
            rotation_task(&repo, first_branch, &base).await;
        first.publication = Some(PrPublication {
            requested_at: OffsetDateTime::now_utc(),
            after_merge: AfterMerge::Review,
            next_slug: Some("follow-up".to_string()),
            github: Some(GithubPr {
                number: 938,
                url: "https://example.com/pr/938".to_string(),
                head_sha: None,
            }),
        });
        first.merge_commit = Some("merge-938".to_string());
        first.updated_at = OffsetDateTime::now_utc();
        store
            .settle_task_pr(&first, None)
            .await
            .expect("settle first PR");

        // Rotation cuts PR2 from fetched origin/main; its recorded base is the
        // fork point, so parity holds by construction.
        let second = ensure_working_pr(&store, &mut session)
            .await
            .expect("rotate PR")
            .expect("working PR");
        assert_eq!(second.sequence, 2);
        repo.create_file("second.txt", "second PR work\n");
        repo.stage_all();
        repo.commit("second PR commit");

        verify_task_pr_range_with_authority(&store, &session, None, repo.path())
            .await
            .expect("rotated continuation PR verifies");
    }

    #[tokio::test]
    async fn verify_refuses_divergent_ancestry_naming_both_sides() {
        let repo = TestRepo::new();
        let origin_tip = repo.head_sha(); // P

        // A foreign commit advances local main ahead of origin (not pushed).
        repo.create_file("foreign.txt", "not this task's work\n");
        repo.stage_all();
        repo.commit("foreign canonical-main commit");
        let contaminated_base = repo.head_sha(); // F = P → F

        // Cut the task branch from the contaminated base.
        let branch = "jack/divergent";
        repo.create_branch(branch);
        repo.create_file("task.txt", "task work\n");
        repo.stage_all();
        repo.commit("task commit");

        // Undo the foreign commit on main and advance origin with a *different*
        // commit so the recorded base and origin diverge from P.
        repo.checkout("main");
        git(repo.path(), &["reset", "--hard", &origin_tip]);
        repo.create_file("upstream.txt", "landed upstream\n");
        repo.stage_all();
        repo.commit("upstream advance");
        repo.push(); // origin/main = P → U

        // Rebase the task branch onto the current origin, simulating a manual
        // recovery that forgot to update the recorded base. After this, the
        // branch history is U → task', but the record still says base = F.
        repo.checkout(branch);
        git(
            repo.path(),
            &[
                "rebase",
                "--onto",
                "origin/main",
                &contaminated_base,
                branch,
            ],
        );

        let (_home, store, session, _pr) = rotation_task(&repo, branch, &contaminated_base).await;

        let err = verify_task_pr_range_with_authority(&store, &session, None, repo.path())
            .await
            .expect_err("divergent ancestry must refuse");
        let message = err.to_string();
        assert!(
            message.contains("diverged"),
            "expected divergence refusal, got: {message}"
        );
        // The base side (M..B) names the foreign commit.
        assert!(
            message.contains("foreign canonical-main commit"),
            "refusal must name the base-side foreign commit, got: {message}"
        );
        assert!(
            message.contains("foreign.txt"),
            "refusal must name the base-side file, got: {message}"
        );
        // The upstream side (B..M) names the upstream commit.
        assert!(
            message.contains("upstream advance"),
            "refusal must name the upstream-side commit, got: {message}"
        );
        assert!(
            message.contains("upstream.txt"),
            "refusal must name the upstream-side file, got: {message}"
        );
        assert!(
            message.contains("rebase --onto"),
            "refusal must print the recovery action, got: {message}"
        );
    }

    #[tokio::test]
    async fn verify_refuses_contaminated_range_without_a_remote() {
        let repo = TestRepo::new();
        let base = repo.head_sha(); // P

        // Drop the remote: the no-remote path must still catch contamination.
        git(repo.path(), &["remote", "remove", "origin"]);

        // Advance local main with a foreign commit, cut the branch from it, then
        // reset main to P — the recorded base is off-local-main.
        repo.create_file("foreign.txt", "not this task's work\n");
        repo.stage_all();
        repo.commit("foreign local-main commit");
        let contaminated_base = repo.head_sha();

        let branch = "jack/no-remote-contaminated";
        repo.create_branch(branch);
        repo.create_file("task.txt", "task work\n");
        repo.stage_all();
        repo.commit("task commit");

        repo.checkout("main");
        git(repo.path(), &["reset", "--hard", &base]);
        repo.checkout(branch);

        let (_home, store, session, _pr) = rotation_task(&repo, branch, &contaminated_base).await;

        let err = verify_task_pr_range_with_authority(&store, &session, None, repo.path())
            .await
            .expect_err("no-remote contaminated range must refuse");
        let message = err.to_string();
        assert!(
            message.contains("contaminated"),
            "expected contamination refusal, got: {message}"
        );
        assert!(
            message.contains("foreign local-main commit"),
            "refusal must name the foreign commit, got: {message}"
        );
    }

    #[tokio::test]
    async fn verify_refuses_contaminated_range_after_squash_merged_parent() {
        // Serial PR shape: PR1 was squash-merged, so origin/main carries a
        // squash commit rather than PR1's original commits. PR2 was cut from
        // PR1's original tip (not the squash), so its recorded base carries
        // commits origin/main doesn't have — the contaminated case.
        let repo = TestRepo::new();

        // PR1: two commits cut from the initial origin tip.
        let first_branch = "jack/pr-one";
        repo.create_branch(first_branch);
        repo.create_file("pr1-a.txt", "a\n");
        repo.stage_all();
        repo.commit("PR1 first commit");
        repo.create_file("pr1-b.txt", "b\n");
        repo.stage_all();
        repo.commit("PR1 second commit");
        let pr1_tip = repo.head_sha();

        // Squash-merge PR1: origin/main gets a single squash commit on P.
        repo.checkout("main");
        git(repo.path(), &["merge", "--squash", first_branch]);
        repo.stage_all();
        repo.commit("squash-merge PR1");
        repo.push();

        // PR2 cut from PR1's original tip (the pre-squash branch), not from the
        // squash commit — the real-world mistake this test catches.
        let second_branch = "jack/pr-two";
        git(repo.path(), &["branch", second_branch, &pr1_tip]);
        repo.checkout(second_branch);
        repo.create_file("pr2.txt", "PR2 work\n");
        repo.stage_all();
        repo.commit("PR2 commit");

        let (_home, store, session, _pr) = rotation_task(&repo, second_branch, &pr1_tip).await;

        let err = verify_task_pr_range_with_authority(&store, &session, None, repo.path())
            .await
            .expect_err("squash-merged parent contamination must refuse");
        let message = err.to_string();
        assert!(
            message.contains("contaminated"),
            "expected contamination refusal after squash-merge, got: {message}"
        );
        assert!(
            message.contains("PR1 first commit"),
            "refusal must name the first pre-squash commit, got: {message}"
        );
        assert!(
            message.contains("PR1 second commit"),
            "refusal must name the second pre-squash commit, got: {message}"
        );
        assert!(
            message.contains("rebase --onto"),
            "refusal must print the recovery action, got: {message}"
        );
    }

    #[test]
    fn placement_base_anchors_on_origin_when_a_remote_exists() {
        let repo = TestRepo::new();
        let origin = repo.head_sha();
        // A local-only commit ahead of origin must NOT move the recorded base.
        repo.create_file("local.txt", "unpushed\n");
        repo.stage_all();
        repo.commit("unpushed local commit");

        let (base_ref, base_commit) =
            resolve_upstream_base(repo.path(), "main").expect("resolve base");
        assert_eq!(base_ref, "origin/main");
        assert_eq!(
            base_commit, origin,
            "the base must anchor on fetched origin, not the ahead-of-origin local tip"
        );
    }

    #[test]
    fn placement_base_falls_back_to_local_main_without_a_remote() {
        let repo = TestRepo::new();
        git(repo.path(), &["remote", "remove", "origin"]);
        repo.create_file("local.txt", "local only\n");
        repo.stage_all();
        repo.commit("local commit");
        let local_tip = repo.head_sha();

        let (base_ref, base_commit) =
            resolve_upstream_base(repo.path(), "main").expect("resolve base");
        assert_eq!(base_ref, "refs/heads/main");
        assert_eq!(base_commit, local_tip);
    }

    #[test]
    fn placement_refuses_when_canonical_main_is_ahead_of_origin() {
        let repo = TestRepo::new();
        // Simulate the #877/#882 root cause: canonical main carries an unpushed
        // commit its upstream lacks.
        repo.create_file("ahead.txt", "unpushed canonical work\n");
        repo.stage_all();
        repo.commit("unpushed canonical commit");

        let err = refuse_if_canonical_ahead(repo.path(), "main")
            .expect_err("ahead-of-origin canonical main must refuse placement");
        let message = err.to_string();
        assert!(
            message.contains("ahead of origin/main"),
            "expected control-plane refusal, got: {message}"
        );
        assert!(
            message.contains("unpushed canonical commit"),
            "refusal must name the unpushed commit, got: {message}"
        );
    }

    /// W2-144 gen 7: a dead process on an open-PR Task with a queued `Resume`
    /// must relaunch (consuming the Resume) instead of settling to `Waiting`.
    /// Without a queued Resume, the existing settle-to-Waiting behavior holds.
    #[tokio::test]
    // Liveness resolves tmux off the process-global PATH, which a concurrent
    // `TaskLaunchEnv` test replaces with a fake that answers "alive".
    #[allow(clippy::await_holding_lock)] // the env lock serializes process-global launch vars
    async fn reconcile_process_liveness_consumes_queued_resume_before_settling() {
        let _env_lock = crate::journal::test_env_lock();
        let dir = tempfile::tempdir().unwrap();
        let store: SharedStore = Arc::new(
            open_store(&StorageConfig::sqlite(dir.path().join("registry.db")))
                .await
                .unwrap(),
        );
        let now = OffsetDateTime::now_utc();
        let wave = Wave::new(
            WaveId::new(),
            "queue-bridge".to_string(),
            dir.path().display().to_string(),
        );
        store.create_wave(&wave).await.unwrap();
        let project = ProjectSession {
            id: ProjectSessionId::new(),
            launch: ProjectLaunchReceipt {
                project: LinearProjectSnapshot {
                    id: LinearProjectId::new(format!("project-{}", WaveId::new())).unwrap(),
                    slug: "queue-bridge".to_string(),
                    name: "Queue bridge".to_string(),
                    prompt_context: "Test".to_string(),
                },
                pm_snapshot_synced_at: now.unix_timestamp(),
            },
            wave_id: wave.id().clone(),
            current_directive_version: 0,
            incorporated_directive_version: 0,
            status: ProjectSessionStatus::Running,
            status_reason: "test".to_string(),
            status_at: now,
            iteration: 1,
            observation_cursor: 0,
            last_state_fingerprint: None,
            agent: "codex".to_string(),
            provider: "codex".to_string(),
            provider_session_id: Some("thread".to_string()),
            latest_process: Some(ChildProcessGeneration {
                generation: 1,
                pid: None,
                process_group_id: None,
                tmux_name: "lf-project-test".to_string(),
                agent: "codex".to_string(),
                provider: "codex".to_string(),
                provider_session_id: Some("thread".to_string()),
                started_at: now,
                state: crate::child_session::ChildLeaseState::Active,
                outcome: None,
                provenance: None,
            }),
            abandon_intent: None,
            created_at: now,
            updated_at: now,
        };
        store.create_project_session(&project).await.unwrap();

        let task = TaskSession {
            id: TaskSessionId::new(),
            launch: TaskLaunchReceipt {
                issue: LinearIssueSnapshot {
                    id: LinearIssueId::new(format!("issue-{}", WaveId::new())).unwrap(),
                    identifier: "INF-QUEUE".to_string(),
                    title: "Queue bridge proof".to_string(),
                    description: "Resume must be consumed.".to_string(),
                },
                project: project.launch.project.clone(),
                pm_snapshot_synced_at: now.unix_timestamp(),
            },
            pm_writeback: PmWritebackState::Current,
            wave_id: wave.id().clone(),
            project_session_id: project.id.clone(),
            current_directive_version: 0,
            incorporated_directive_version: 0,
            status: TaskSessionStatus::Running,
            status_reason: "task is running".to_string(),
            status_at: now,
            worktree: dir.path().to_path_buf(),
            workspace_slug: "queue-bridge".to_string(),
            lifecycle: crate::task::TaskLifecyclePlan::standard("task"),
            lifecycle_phase: crate::task::TaskLifecyclePhase::Iterate,
            phase_epoch: 1,
            phase_cursor: 0,
            phase_iteration: 0,
            gate_cycle: 0,
            gate_proposal: None,
            agent: "codex".to_string(),
            provider: "codex".to_string(),
            provider_session_id: Some("thread".to_string()),
            latest_process: Some(ChildProcessGeneration {
                generation: 1,
                pid: None,
                process_group_id: None,
                tmux_name: "lf-task-queue-bridge".to_string(),
                agent: "codex".to_string(),
                provider: "codex".to_string(),
                provider_session_id: Some("thread".to_string()),
                started_at: now - time::Duration::seconds(30),
                state: crate::child_session::ChildLeaseState::Active,
                outcome: None,
                provenance: None,
            }),
            abandon_intent: None,
            created_at: now,
            updated_at: now,
            observation: crate::task::Observation::NotRequired,
        };

        let mut pr = TaskPr {
            id: TaskPrId::new(),
            task_session_id: task.id.clone(),
            sequence: 1,
            slug: task.workspace_slug.clone(),
            branch: "jack/queue-bridge".to_string(),
            base_commit: "0".repeat(40),
            parent_pr_id: None,
            publication: None,
            merge_commit: None,
            abandoned_at: None,
            ci_observation: None,
            github_observation: None,
            linear_attachment_id: None,
            linear_comment_id: None,
            linear_link_error: None,
            created_at: now,
            updated_at: now,
        };
        store.create_task_session(&task, &pr).await.unwrap();

        // Promote the PR to Open (published on GitHub) after creation.
        pr.publication = Some(PrPublication {
            requested_at: now,
            after_merge: AfterMerge::Review,
            next_slug: None,
            github: Some(GithubPr {
                number: 999,
                url: "https://github.com/loopflow/loopflow/pull/999".to_string(),
                head_sha: Some("head-1".to_string()),
            }),
        });
        pr.updated_at = OffsetDateTime::now_utc();
        store.update_task_pr(&pr).await.unwrap();

        // --- Without a queued Resume: settles to Waiting (existing behavior) ---
        let mut idle = store.get_task_session(&task.id).await.unwrap().unwrap();
        super::reconcile_process_liveness(&store, &mut idle)
            .await
            .expect("settle without Resume");
        assert_eq!(
            idle.status,
            TaskSessionStatus::Waiting,
            "idle task settles to Waiting"
        );

        // --- With a queued Resume: relaunches, does NOT settle to Waiting ---
        // Re-arm the task to Running with a stale process for the second pass.
        idle.set_status(TaskSessionStatus::Running, "re-armed for resume proof");
        idle.latest_process = Some(ChildProcessGeneration {
            generation: 2,
            pid: None,
            process_group_id: None,
            tmux_name: "lf-task-queue-bridge-2".to_string(),
            agent: "codex".to_string(),
            provider: "codex".to_string(),
            provider_session_id: Some("thread".to_string()),
            started_at: OffsetDateTime::now_utc() - time::Duration::seconds(30),
            state: crate::child_session::ChildLeaseState::Active,
            outcome: None,
            provenance: None,
        });
        store.update_task_session(&idle).await.unwrap();

        let resume = ChildCommand::new(
            ChildRef::Task(task.id.clone()),
            ChildCommandSource::Human,
            ChildCommandKind::Resume { message: None },
        );
        store.create_child_command(&resume).await.unwrap();

        let mut with_resume = store.get_task_session(&task.id).await.unwrap().unwrap();
        let result = super::reconcile_process_liveness(&store, &mut with_resume).await;

        // The bridge fired: relaunch was attempted. In the test env the launch
        // fails (lf_bin = /usr/bin/false), so we get an error — but the key
        // proof is that the status is NOT Waiting (it took the relaunch path).
        assert_ne!(
            with_resume.status,
            TaskSessionStatus::Waiting,
            "a queued Resume must prevent the Waiting settle"
        );
        // Either the launch failed (error returned) or a new generation started
        // (Starting). Both prove the bridge consumed the Resume.
        assert!(
            result.is_err() || with_resume.status == TaskSessionStatus::Starting,
            "bridge should relaunch, got status={}, result={:?}",
            with_resume.status.as_str(),
            result.as_ref().err().map(|e| e.to_string())
        );

        // The Resume command is still in the queue (not yet claimed by a
        // successful generation), but it was not discarded — the bridge
        // attempted a relaunch to consume it.
        let commands = store
            .list_child_commands(&ChildRef::Task(task.id))
            .await
            .unwrap();
        let resume_still_pending = commands.iter().any(|cmd| {
            matches!(cmd.kind, ChildCommandKind::Resume { .. }) && !cmd.state.is_terminal()
        });
        assert!(
            resume_still_pending,
            "the Resume command is still in the queue, not discarded"
        );
    }

    #[tokio::test]
    async fn recover_refuses_a_non_abandoned_task() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let branch = "jack/task-pr-proof";
        repo.create_branch(branch);
        let (_home, store, session, _pr) = rotation_task(&repo, branch, &base).await;

        let authority = CallerAuthority::Operator;
        let error =
            _recover_abandoned_task(&store, &session.launch.issue.identifier, &authority, None)
                .await
                .expect_err("a waiting Task resumes instead of recovering");
        assert!(error.to_string().contains("lf task resume"), "{error}");
        assert_eq!(
            store
                .get_task_session_by_issue(&session.launch.issue.identifier)
                .await
                .unwrap()
                .unwrap()
                .id,
            session.id
        );
    }

    #[tokio::test]
    async fn recover_abandoned_task_adopts_existing_worktree_pr_and_direction() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let branch = "jack/task-pr-proof";
        repo.create_branch(branch);
        repo.create_file("recovery.txt", "work survives abandonment\n");
        repo.stage_all();
        repo.commit("task work");
        let (_home, store, session, pr) = rotation_task(&repo, branch, &base).await;

        let target = ChildRef::Task(session.id.clone());
        let command = ChildCommand::new(
            target.clone(),
            ChildCommandSource::Human,
            ChildCommandKind::Steer {
                text: "finish the existing PR".to_string(),
            },
        );
        let directive = ChildDirective::replacement(
            target,
            1,
            "finish the existing PR".to_string(),
            command.source.clone(),
            command.id.clone(),
        );
        store
            .create_child_command_with_directive(&command, &directive)
            .await
            .expect("record current direction");
        let mut abandoned = store.get_task_session(&session.id).await.unwrap().unwrap();
        abandoned.set_status(TaskSessionStatus::Abandoned, "operator stopped the attempt");
        store.update_task_session(&abandoned).await.unwrap();

        let successor = _recover_abandoned_task(
            &store,
            &abandoned.launch.issue.identifier,
            &CallerAuthority::Operator,
            Some("the work is still valid".to_string()),
        )
        .await
        .expect("recover abandoned Task");
        assert_ne!(successor.id, abandoned.id);
        assert_eq!(successor.status, TaskSessionStatus::Waiting);
        assert_eq!(successor.worktree, abandoned.worktree);
        assert_eq!(successor.workspace_slug, abandoned.workspace_slug);
        assert!(successor.latest_process.is_none());
        assert_eq!(
            successor.lifecycle_phase,
            crate::task::TaskLifecyclePhase::Kickoff
        );
        assert!(successor.status_reason.contains("the work is still valid"));

        assert!(store.task_prs(&abandoned.id).await.unwrap().is_empty());
        let adopted_prs = store.task_prs(&successor.id).await.unwrap();
        assert_eq!(adopted_prs.len(), 1);
        assert_eq!(adopted_prs[0].id, pr.id);
        let carried = store
            .child_directives(&ChildRef::Task(successor.id.clone()))
            .await
            .unwrap();
        assert_eq!(carried.len(), 1);
        assert_eq!(carried[0].text, directive.text);
        assert_eq!(carried[0].source, directive.source);

        let repeated = _recover_abandoned_task(
            &store,
            &successor.launch.issue.identifier,
            &CallerAuthority::Operator,
            Some("the work is still valid".to_string()),
        )
        .await
        .expect("recovery retry converges");
        assert_eq!(repeated.id, successor.id);

        let mut completed = repeated;
        completed.set_status(TaskSessionStatus::Completed, "recovered work landed");
        store.update_task_session(&completed).await.unwrap();
        let error = _recover_abandoned_task(
            &store,
            &completed.launch.issue.identifier,
            &CallerAuthority::Operator,
            Some("try again".to_string()),
        )
        .await
        .expect_err("a completed recovered Task cannot be recovered again");
        assert!(error.to_string().contains("is completed"), "{error}");
    }

    // ── Task recovery adoption preconditions (W2-251) ───────────────────────
    //
    // Recovery must refuse unsafe worktree/branch state before moving any
    // durable ownership. Each test proves one adoption precondition; the
    // unrelated-branch test additionally proves refusal leaves the predecessor,
    // successor link, PR sequence, lease, and worktree untouched.

    fn checkout_branch(repo: &TestRepo, branch: &str) {
        let status = Command::new("git")
            .current_dir(repo.path())
            .args(["checkout", branch])
            .status()
            .expect("checkout");
        assert!(status.success(), "checkout {branch} failed");
    }

    #[tokio::test]
    async fn recovery_refuses_an_unrelated_branch_before_moving_ownership() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let first_branch = "jack/task-pr-proof";
        repo.create_branch(first_branch);
        repo.create_file("first.txt", "first PR\n");
        repo.stage_all();
        repo.commit("first PR");
        // Seed a dead Active lease so refusal's "leases untouched" is load-bearing:
        // without the gate, reconcile_process_liveness would reap it.
        let (_home, store, session, first) = rotation_task_with_lease(
            &repo,
            first_branch,
            &base,
            Some((
                crate::child_session::ChildLeaseState::Active,
                TaskSessionStatus::Waiting,
                None,
            )),
        )
        .await;
        settle_pr(&store, first, "merge-unrelated", None).await;

        // The worktree is on an unrelated branch — neither settled nor the
        // deterministic next branch.
        repo.create_branch("jack/unrelated");
        let prs_before = store.task_prs(&session.id).await.expect("read PRs");
        let lease_before = store
            .get_task_session(&session.id)
            .await
            .unwrap()
            .unwrap()
            .latest_process
            .clone()
            .expect("dead lease seeded");

        let err = task_recovery_adoption(&store, &session)
            .await
            .expect_err("unrelated branch must refuse");
        let message = err.to_string();
        assert!(
            message.contains("between-PR recovery expected settled branch"),
            "expected unrelated-branch refusal, got: {message}"
        );
        assert!(
            message.contains("jack/unrelated"),
            "refusal must name the current branch, got: {message}"
        );
        assert!(
            message.contains("refused before moving any ownership"),
            "refusal must name the contract, got: {message}"
        );

        // Refusal left the PR sequence, lease, status, and worktree untouched.
        assert_eq!(
            store.task_prs(&session.id).await.expect("reread PRs"),
            prs_before,
            "PR sequence untouched"
        );
        let after = store.get_task_session(&session.id).await.unwrap().unwrap();
        assert_eq!(
            after.latest_process,
            Some(lease_before),
            "dead lease untouched — the gate is what prevents the reap"
        );
        assert_eq!(after.status, TaskSessionStatus::Waiting, "status untouched");
        assert_eq!(
            git(repo.path(), &["rev-parse", "--abbrev-ref", "HEAD"]),
            "jack/unrelated",
            "worktree branch untouched"
        );
    }

    /// The supervisor's stall recovery restarts a body into the Task worktree, so
    /// it clears the same adoption gate as an explicit resume. Without it a stalled
    /// Task sitting on an unrelated branch has its lease reaped and a successor
    /// committed, only for rotation to reject the branch afterwards.
    #[tokio::test]
    async fn supervised_restart_refuses_an_unrelated_branch() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let first_branch = "jack/task-pr-proof";
        repo.create_branch(first_branch);
        repo.create_file("first.txt", "first PR\n");
        repo.stage_all();
        repo.commit("first PR");
        let (_home, store, session, first) = rotation_task_with_lease(
            &repo,
            first_branch,
            &base,
            Some((ChildLeaseState::Active, TaskSessionStatus::Running, None)),
        )
        .await;
        settle_pr(&store, first, "merge-supervised", None).await;
        repo.create_branch("jack/unrelated");
        // Re-read as the supervisor does: a stale status_at would make the
        // revoke's compare-and-swap decline on its own and prove nothing.
        let session = store.get_task_session(&session.id).await.unwrap().unwrap();
        let lease_before = session.latest_process.clone().expect("active lease seeded");

        // No delivering command, so the plan is a plain restart: the path that
        // would otherwise commit a successor.
        let observation = observe(
            &BodyEvidence {
                intent: BodyIntent::Active,
                observable: true,
                process_alive: true,
                progress_age: Duration::from_secs(31 * 60),
                step: Some("task_pursue".to_string()),
                reason: "body is alive but stalled".to_string(),
            },
            Duration::from_secs(30 * 60),
        );
        let latest_event_id = store
            .latest_task_event(&session.id)
            .await
            .unwrap()
            .map(|event| event.id);

        assert!(
            !recover_stalled_task_body(&store, session.clone(), &observation, latest_event_id)
                .await
                .expect("an unsafe worktree declines recovery; it does not fail the supervisor"),
            "an unrelated branch must not be restarted"
        );

        let after = store.get_task_session(&session.id).await.unwrap().unwrap();
        assert_eq!(
            after.latest_process,
            Some(lease_before),
            "lease untouched — the gate is what prevents the reap"
        );
        assert_eq!(after.status, TaskSessionStatus::Running, "status untouched");
    }

    #[tokio::test]
    async fn recovery_refuses_a_dirty_worktree_between_prs() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let first_branch = "jack/task-pr-proof";
        repo.create_branch(first_branch);
        repo.create_file("first.txt", "first PR\n");
        repo.stage_all();
        repo.commit("first PR");
        let (_home, store, session, first) =
            rotation_task_with_lease(&repo, first_branch, &base, None).await;
        settle_pr(&store, first, "merge-dirty", None).await;

        // Uncommitted follow-up work on the settled branch: the runner's strict
        // rotation cannot carry it, so recovery must refuse before moving
        // ownership and point the human at `lf pr next`.
        repo.create_file("follow-up.txt", "uncommitted\n");

        let err = task_recovery_adoption(&store, &session)
            .await
            .expect_err("dirty between-PR worktree must refuse");
        let message = err.to_string();
        assert!(
            message.contains("uncommitted changes"),
            "expected dirty refusal, got: {message}"
        );
        assert!(
            message.contains("lf pr next"),
            "refusal must name the recovery action, got: {message}"
        );
        assert!(
            message.contains("refused before moving any ownership"),
            "refusal must name the contract, got: {message}"
        );
    }

    #[tokio::test]
    async fn recovery_refuses_a_missing_branch() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let first_branch = "jack/task-pr-proof";
        repo.create_branch(first_branch);
        repo.create_file("first.txt", "first PR\n");
        repo.stage_all();
        repo.commit("first PR");
        let (_home, store, session, first) =
            rotation_task_with_lease(&repo, first_branch, &base, None).await;
        settle_pr(&store, first, "merge-missing", None).await;

        // Delete the ref the worktree is checked out on; HEAD dangles off a
        // branch that no longer exists.
        Command::new("git")
            .current_dir(repo.path())
            .args(["update-ref", "-d", &format!("refs/heads/{first_branch}")])
            .status()
            .expect("delete branch ref");
        assert_eq!(
            git(repo.path(), &["symbolic-ref", "--short", "HEAD"]),
            first_branch,
            "HEAD still names the deleted branch"
        );

        let err = task_recovery_adoption(&store, &session)
            .await
            .expect_err("missing branch must refuse");
        let message = err.to_string();
        assert!(
            message.contains("no longer exists"),
            "expected missing-branch refusal, got: {message}"
        );
        assert!(
            message.contains(first_branch),
            "refusal must name the missing branch, got: {message}"
        );
    }

    #[tokio::test]
    async fn recovery_adopts_an_active_pr_branch_and_allows_ongoing_work() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let branch = "jack/task-pr-proof";
        repo.create_branch(branch);
        repo.create_file("first.txt", "first PR\n");
        repo.stage_all();
        repo.commit("first PR");
        // rotation_task seeds an active (Working) PR on `branch`.
        let (_home, store, session, _pr) =
            rotation_task_with_lease(&repo, branch, &base, None).await;

        // Dirty ongoing work on the active PR's branch is allowed — recovery
        // must not drop in-progress work.
        repo.create_file("wip.txt", "ongoing\n");

        let adoption = task_recovery_adoption(&store, &session)
            .await
            .expect("active PR on its branch is adopted, dirty work allowed");
        assert_eq!(
            adoption,
            TaskRecoveryAdoption::Active {
                branch: branch.to_string()
            }
        );
    }

    #[tokio::test]
    async fn recovery_refuses_a_crash_boundary() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let branch = "jack/task-pr-proof";
        repo.create_branch(branch);
        repo.create_file("first.txt", "first PR\n");
        repo.stage_all();
        repo.commit("first PR");
        let (_home, store, session, _pr) =
            rotation_task_with_lease(&repo, branch, &base, None).await;

        // Drive the worktree into a conflicting rebase: advance main with a
        // conflicting edit, then rebase the branch onto it.
        repo.checkout("main");
        repo.create_file("first.txt", "main wins\n");
        repo.stage_all();
        repo.commit("main advance");
        checkout_branch(&repo, branch);
        let rebase = Command::new("git")
            .current_dir(repo.path())
            .args(["rebase", "main"])
            .output()
            .expect("run rebase");
        assert!(
            !rebase.status.success(),
            "rebase must conflict to seed a crash boundary"
        );

        let err = task_recovery_adoption(&store, &session)
            .await
            .expect_err("crash boundary must refuse");
        let message = err.to_string();
        assert!(
            message.contains("mid-rebase"),
            "expected crash-boundary refusal, got: {message}"
        );
        assert!(
            message.contains("refused before moving any ownership"),
            "refusal must name the contract, got: {message}"
        );

        // Cleanup so the temp repo drops cleanly.
        let _ = Command::new("git")
            .current_dir(repo.path())
            .args(["rebase", "--abort"])
            .status();
    }

    #[tokio::test]
    async fn between_prs_recovery_selects_the_deterministic_next_branch() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let first_branch = "jack/task-pr-proof";
        repo.create_branch(first_branch);
        repo.create_file("first.txt", "first PR\n");
        repo.stage_all();
        repo.commit("first PR");
        let (_home, store, session, first) =
            rotation_task_with_lease(&repo, first_branch, &base, None).await;
        settle_pr(&store, first, "merge-942", Some("follow-up")).await;

        // The deterministic next branch the gate must select, read from the
        // settled PR the gate reads (not the pre-settle local copy).
        let settled = store
            .task_prs(&session.id)
            .await
            .expect("read settled PR")
            .pop()
            .expect("settled PR");
        let next = format!("{first_branch}-follow-up");
        assert_eq!(next_pr_slug(&settled, None), "follow-up");

        // The worktree is already on the next branch — a partial rotation the
        // gate must adopt, not refuse as an unrelated branch.
        Command::new("git")
            .current_dir(repo.path())
            .args(["checkout", "-b", &next])
            .status()
            .expect("cut next branch");

        let adoption = task_recovery_adoption(&store, &session)
            .await
            .expect("partial rotation onto the next branch is adopted");
        assert_eq!(
            adoption,
            TaskRecoveryAdoption::BetweenPrs {
                settled: first_branch.to_string(),
                next
            }
        );
    }

    #[tokio::test]
    async fn refuse_dirty_between_prs_blocks_after_an_out_of_band_merge() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let first_branch = "jack/task-pr-proof";
        repo.create_branch(first_branch);
        repo.create_file("first.txt", "first PR\n");
        repo.stage_all();
        repo.commit("first PR");
        let (_home, store, session, first) =
            rotation_task_with_lease(&repo, first_branch, &base, None).await;
        repo.create_file("wip.txt", "ongoing\n");

        // While the PR is active, dirty ongoing work is fine.
        refuse_dirty_between_prs(&store, &session)
            .await
            .expect("active PR with dirty work is allowed");

        // The PR merges out of band -> settled -> between-PR. The post-reconcile
        // guard must now refuse the dirty between-PR before the lease is reaped
        // or a successor body is launched.
        settle_pr(&store, first, "merge-out-of-band", None).await;
        let err = refuse_dirty_between_prs(&store, &session)
            .await
            .expect_err("dirty between-PR after merge must refuse");
        assert!(
            err.to_string().contains("lf pr next"),
            "expected dirty between-PR refusal, got: {err}"
        );
    }

    // ── completion gate (W2-237) ───────────────────────────────────────────
    // A Task may be completed in the PM only once every active PR is settled
    // and every required review is approved. The tests below prove the gate and
    // the reconcile advance/repair around it reproduce the W2-151 / W2-138
    // ordering: a merge observed while a required review is open does not close
    // the Task; the Task closes exactly once after the review approves.

    use super::{
        complete_task_session_with_authority, reconcile_task_completion, task_completion_gate,
    };
    use crate::interaction_review::{
        InteractionReview, InteractionReviewDisposition, InteractionReviewEvidence,
        InteractionReviewId, InteractionReviewPr, InteractionReviewStatus, InteractionReviewer,
    };
    use crate::task::{
        PmWritebackOperation, TaskGateProposal, TaskLifecyclePhase, TaskLifecyclePlan,
    };

    /// A Gate-phase Task Session whose initial PR may be left working or settled.
    async fn gate_task_fixture(
        repo: &TestRepo,
        branch: &str,
        base_commit: &str,
        settle: bool,
        phase_cursor: u32,
    ) -> (tempfile::TempDir, SharedStore, TaskSession, TaskPr) {
        let home = tempfile::tempdir().expect("task home");
        let db_path = home.path().join("loopflow.db");
        let store = Arc::new(
            open_store(&StorageConfig::sqlite(db_path.clone()))
                .await
                .expect("open store"),
        );
        let now = OffsetDateTime::now_utc();
        let wave = Wave::new(
            WaveId::new(),
            "completion-gate".to_string(),
            repo.path().display().to_string(),
        );
        let project = ProjectSession {
            id: ProjectSessionId::new(),
            launch: ProjectLaunchReceipt {
                project: LinearProjectSnapshot {
                    id: LinearProjectId::new(format!("project-{}", WaveId::new()))
                        .expect("project id"),
                    slug: "completion-gate".to_string(),
                    name: "Completion gate".to_string(),
                    prompt_context: "Keep the gate honest.".to_string(),
                },
                pm_snapshot_synced_at: now.unix_timestamp(),
            },
            wave_id: wave.id().clone(),
            current_directive_version: 0,
            incorporated_directive_version: 0,
            status: ProjectSessionStatus::Running,
            status_reason: "test project is running".to_string(),
            status_at: now,
            iteration: 1,
            observation_cursor: 0,
            last_state_fingerprint: None,
            agent: "codex".to_string(),
            provider: "codex".to_string(),
            provider_session_id: Some("completion-gate".to_string()),
            latest_process: Some(ChildProcessGeneration {
                generation: 1,
                pid: None,
                process_group_id: None,
                tmux_name: "completion-gate".to_string(),
                agent: "codex".to_string(),
                provider: "codex".to_string(),
                provider_session_id: Some("completion-gate".to_string()),
                started_at: now,
                state: crate::child_session::ChildLeaseState::Active,
                outcome: None,
                provenance: None,
            }),
            abandon_intent: None,
            created_at: now,
            updated_at: now,
        };
        let session = TaskSession {
            id: TaskSessionId::new(),
            launch: TaskLaunchReceipt {
                issue: LinearIssueSnapshot {
                    id: LinearIssueId::new(format!("issue-{}", WaveId::new())).expect("issue id"),
                    identifier: "INF-GATE".to_string(),
                    title: "Prove the completion gate".to_string(),
                    description: "Completion waits on the review gate.".to_string(),
                },
                project: project.launch.project.clone(),
                pm_snapshot_synced_at: now.unix_timestamp(),
            },
            pm_writeback: PmWritebackState::Current,
            wave_id: wave.id().clone(),
            project_session_id: project.id.clone(),
            current_directive_version: 0,
            incorporated_directive_version: 0,
            status: TaskSessionStatus::Waiting,
            status_reason: "merged; awaiting gate".to_string(),
            status_at: now,
            worktree: repo.path().to_path_buf(),
            workspace_slug: "completion-gate".to_string(),
            lifecycle: TaskLifecyclePlan::standard("task"),
            lifecycle_phase: TaskLifecyclePhase::Gate,
            phase_epoch: 2,
            phase_cursor,
            phase_iteration: 0,
            gate_cycle: 1,
            gate_proposal: Some(TaskGateProposal {
                status: TaskSessionStatus::Completed,
                reason: "merged and reviewed".to_string(),
            }),
            agent: "codex".to_string(),
            provider: "codex".to_string(),
            provider_session_id: None,
            latest_process: None,
            abandon_intent: None,
            created_at: now,
            updated_at: now,
            observation: crate::task::Observation::NotRequired,
        };
        let pr = TaskPr {
            id: TaskPrId::new(),
            task_session_id: session.id.clone(),
            sequence: 1,
            slug: session.workspace_slug.clone(),
            branch: branch.to_string(),
            base_commit: base_commit.to_string(),
            parent_pr_id: None,
            publication: None,
            merge_commit: None,
            abandoned_at: None,
            ci_observation: None,
            github_observation: None,
            linear_attachment_id: None,
            linear_comment_id: None,
            linear_link_error: None,
            created_at: now,
            updated_at: now,
        };
        store.create_wave(&wave).await.expect("create wave");
        store
            .create_project_session(&project)
            .await
            .expect("create project");
        store
            .create_task_session(&session, &pr)
            .await
            .expect("create Task");
        if !settle {
            return (home, store, session, pr);
        }
        // Settle the PR as merged-with-complete-task after creation (the session
        // is created with a sequence-1 Working PR).
        let mut merged = pr.clone();
        merged.publication = Some(PrPublication {
            requested_at: now,
            after_merge: AfterMerge::CompleteTask,
            next_slug: None,
            github: Some(GithubPr {
                number: 912,
                url: "https://example.com/pr/912".to_string(),
                head_sha: Some(repo.head_sha()),
            }),
        });
        merged.merge_commit = Some("merge-912".to_string());
        merged.updated_at = OffsetDateTime::now_utc();
        store
            .update_task_pr(&merged)
            .await
            .expect("settle merged PR");
        (home, store, session, merged)
    }

    /// A Gate-phase Task Session with one merged `CompleteTask` PR, ready for a
    /// required review to be opened against its gate waitpoint.
    async fn gate_task(
        repo: &TestRepo,
        branch: &str,
        base_commit: &str,
    ) -> (tempfile::TempDir, SharedStore, TaskSession, TaskPr) {
        gate_task_fixture(repo, branch, base_commit, true, 0).await
    }

    /// Open a required Human review at the Session's current waitpoint and
    /// return its id with the lease that opened it. Pass `None` to reserve a
    /// fresh lease; pass a prior lease to open a second review on the same
    /// generation, which a Session can only do while that lease stays active.
    async fn open_gate_review(
        store: &SharedStore,
        session: &mut TaskSession,
        pr: &TaskPr,
        lease: Option<ChildWriteLease>,
    ) -> (InteractionReviewId, ChildWriteLease) {
        let lease = if let Some(lease) = lease {
            lease
        } else {
            session.begin_generation("gate-review".to_string());
            let lease = store
                .reserve_task_process(session, TaskSessionStatus::Waiting)
                .await
                .expect("reserve process")
                .expect("lease");
            if let Some(process) = &mut session.latest_process {
                process.state = crate::child_session::ChildLeaseState::Active;
            }
            session.set_status(TaskSessionStatus::Running, "gate review active");
            store
                .activate_task_process(session, &lease)
                .await
                .expect("activate process");
            lease
        };
        let plan = session.phase_plan();
        let review = InteractionReview {
            id: InteractionReviewId::new(),
            wave_id: session.wave_id.clone(),
            project_session_id: session.project_session_id.clone(),
            task_session_id: session.id.clone(),
            phase: session.lifecycle_phase,
            phase_epoch: session.phase_epoch,
            flow: plan.flow.clone(),
            step: "demo".to_string(),
            step_index: session.phase_cursor,
            phase_iteration: session.phase_iteration,
            policy: plan.interaction_policy,
            reviewer: InteractionReviewer::Human,
            status: InteractionReviewStatus::Requested,
            reason: "Prove the gate holds.".to_string(),
            prompt: "Prove the gate holds.".to_string(),
            evidence: InteractionReviewEvidence {
                worktree: session.worktree.clone(),
                branch: pr.branch.clone(),
                base_commit: pr.base_commit.clone(),
                head_commit: pr.base_commit.clone(),
                worktree_fingerprint: "fingerprint".to_string(),
                pr: Some(InteractionReviewPr {
                    number: 912,
                    url: "https://example.com/pr/912".to_string(),
                }),
            },
            requested_by_generation: lease.generation,
            reviewer_generation: None,
            disposition: None,
            outcome: None,
            requested_at: OffsetDateTime::now_utc(),
            completed_at: None,
        };
        store
            .open_interaction_review(session, &review, &lease)
            .await
            .expect("open gate review");
        (review.id, lease)
    }

    #[test]
    fn merged_snapshot_routes_the_persisted_review_gate() {
        let repo = TestRepo::new();
        let branch = "jack/merged-review-proof";
        repo.create_branch(branch);
        let base = repo.head_sha();
        let runtime = tokio::runtime::Runtime::new().expect("test runtime");
        let (home, expected_complete_refusal, review_id, session) = runtime.block_on(async {
            let (home, store, mut session, pr) = gate_task(&repo, branch, &base).await;
            let (review_id, _lease) = open_gate_review(&store, &mut session, &pr, None).await;
            let gate = task_completion_gate(&store, &session)
                .await
                .expect("completion gate");
            let refusal = gate
                .refusal(&session.launch.issue.identifier)
                .expect("required review refuses completion");
            (home, refusal, review_id, session)
        });
        drop(runtime);
        let _env = StoreEnvGuard::new(home.path());

        let snapshot = task_snapshot(&session).expect("snapshot review-blocked Task");
        assert_eq!(snapshot.active_pr, None);
        assert_eq!(snapshot.actions.recommended, Some(TaskAction::Review));
        assert_eq!(
            snapshot
                .actions
                .status(TaskAction::Complete)
                .expect("Complete action")
                .reason,
            expected_complete_refusal
        );
        assert!(
            expected_complete_refusal.contains(review_id.as_str()),
            "completion refusal must name the actual required review"
        );
        assert_eq!(
            snapshot
                .actions
                .status(TaskAction::Resume)
                .expect("Resume action")
                .reason,
            "Task INF-GATE has no active PR to resume; pull request #912 merged"
        );
    }

    #[test]
    fn merged_snapshot_with_a_clear_gate_recommends_completion() {
        let repo = TestRepo::new();
        let branch = "jack/merged-complete-proof";
        repo.create_branch(branch);
        let base = repo.head_sha();
        let runtime = tokio::runtime::Runtime::new().expect("test runtime");
        let (home, session) = runtime.block_on(async {
            let (home, _store, session, _pr) = gate_task(&repo, branch, &base).await;
            (home, session)
        });
        drop(runtime);
        let _env = StoreEnvGuard::new(home.path());

        let snapshot = task_snapshot(&session).expect("snapshot completable Task");
        assert_eq!(snapshot.active_pr, None);
        assert_eq!(snapshot.actions.recommended, Some(TaskAction::Complete));
        assert!(
            snapshot
                .actions
                .status(TaskAction::Complete)
                .expect("Complete action")
                .available
        );
        assert_eq!(
            snapshot
                .actions
                .status(TaskAction::Resume)
                .expect("Resume action")
                .reason,
            "Task INF-GATE has no active PR to resume; pull request #912 merged"
        );
    }

    #[tokio::test]
    async fn completion_gate_is_satisfied_with_no_prs_and_no_reviews() {
        let repo = TestRepo::new();
        let branch = "jack/gate-proof";
        repo.create_branch(branch);
        let (_home, store, mut session, _pr) = gate_task(&repo, branch, &repo.head_sha()).await;
        // The PR is settled (merged) and no required reviews are open: the gate
        // is satisfied, so clean no-PR / no-review work can still complete.
        session.status = TaskSessionStatus::Waiting;
        let gate = task_completion_gate(&store, &session).await.expect("gate");
        assert!(
            gate.satisfied,
            "gate should be satisfied: {:?}",
            gate.blockers
        );
    }

    // ── settling over a proven-empty successor (W2-304) ────────────────────
    // The lifecycle rotates a serial successor after a `Review` merge. When the
    // work is done that successor is never published and never authored, and
    // `lf task complete` refused on it: publishing opens a zero-commit PR, and
    // abandoning leaves the Session `Waiting` so the next rotation mints PR N+1.
    // `task_complete` resolves the machine registry itself, so these drive the two
    // functions it composes: `task_completion_gate` and
    // `complete_task_session_with_authority`.

    const SUCCESSOR_BRANCH: &str = "jack/gate-proof-2";

    /// Merged work on `jack/gate-proof`, plus a successor rotated behind it whose
    /// branch starts at `successor_base`. The merged PR is relanded `Review` — the
    /// disposition that actually rotates.
    async fn merged_task_with_successor(
        repo: &TestRepo,
        successor_base: Option<&str>,
    ) -> (tempfile::TempDir, SharedStore, TaskSession, TaskPr, TaskPr) {
        let merged_branch = "jack/gate-proof";
        let base = repo.head_sha();
        repo.create_branch(merged_branch);
        repo.create_file("merged.txt", "the real work\n");
        repo.stage_all();
        repo.commit("merged work");
        let (home, store, mut session, merged) = gate_task(repo, merged_branch, &base).await;
        session.status = TaskSessionStatus::Waiting;

        let mut merged = merged;
        merged
            .publication
            .as_mut()
            .expect("published PR")
            .after_merge = AfterMerge::Review;
        merged.updated_at = OffsetDateTime::now_utc();
        store
            .update_task_pr(&merged)
            .await
            .expect("reland merged PR for review");
        // `settle_task_pr` re-presents the settled row and compares it field for
        // field; `publication.requested_at` loses sub-second precision through the
        // store, so only the round-tripped row compares equal to itself.
        let merged = store
            .get_task_pr(&merged.id)
            .await
            .expect("read merged PR")
            .expect("merged row");

        match successor_base {
            Some(base) => git(repo.path(), &["checkout", "-b", SUCCESSOR_BRANCH, base]),
            None => {
                git(repo.path(), &["checkout", "--orphan", SUCCESSOR_BRANCH]);
                git(
                    repo.path(),
                    &["commit", "--allow-empty", "-m", "rewritten successor"],
                )
            }
        };
        let now = OffsetDateTime::now_utc();
        let successor = TaskPr {
            id: TaskPrId::new(),
            task_session_id: session.id.clone(),
            sequence: merged.sequence + 1,
            slug: "successor".to_string(),
            branch: SUCCESSOR_BRANCH.to_string(),
            base_commit: successor_base.unwrap_or(&base).to_string(),
            parent_pr_id: None,
            publication: None,
            merge_commit: None,
            abandoned_at: None,
            ci_observation: None,
            github_observation: None,
            linear_attachment_id: None,
            linear_comment_id: None,
            linear_link_error: None,
            created_at: now,
            updated_at: now,
        };
        store
            .settle_task_pr(&merged, Some(&successor))
            .await
            .expect("rotate successor");
        (home, store, session, merged, successor)
    }

    async fn pr_phase(store: &SharedStore, id: &TaskPrId) -> PrPhase {
        store
            .get_task_pr(id)
            .await
            .expect("read PR")
            .expect("PR row")
            .phase()
    }

    #[tokio::test]
    async fn a_merged_task_settles_over_a_proven_empty_successor() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let (_home, store, mut session, _merged, successor) =
            merged_task_with_successor(&repo, Some(&base)).await;

        let gate = task_completion_gate(&store, &session)
            .await
            .expect("gate over empty successor");
        assert!(
            gate.satisfied,
            "the rotation's empty artifact must not block merged work: {:?}",
            gate.blockers
        );
        assert_eq!(
            gate.discardable_successor.as_ref().map(|pr| &pr.id),
            Some(&successor.id)
        );
        assert_eq!(
            pr_phase(&store, &successor.id).await,
            PrPhase::Working,
            "the gate must classify without mutating"
        );

        session.set_status(TaskSessionStatus::Completed, "merged work settled");
        complete_task_session_with_authority(
            &store,
            &session,
            gate.discardable_successor.as_ref(),
            None,
        )
        .await
        .expect("complete over the empty successor");

        let prs = store.task_prs(&session.id).await.expect("read PRs");
        assert_eq!(
            prs.len(),
            1,
            "the artifact must be gone and no replacement minted: {prs:?}"
        );
        assert_eq!(prs[0].phase(), PrPhase::Merged);
        assert!(store
            .active_task_pr(&session.id)
            .await
            .expect("read active PR")
            .is_none());

        // Terminal status has proven non-monotonic in this wave (W2-296/W2-299),
        // so reconciling a settled Task must not walk it back or mint a PR.
        reconcile_task_completion(&store, &mut session, None)
            .await
            .expect("reconcile after settling");
        assert_eq!(session.status, TaskSessionStatus::Completed);
        assert_eq!(
            store.task_prs(&session.id).await.expect("read PRs").len(),
            1
        );
    }

    #[tokio::test]
    async fn a_pending_required_review_blocks_completion_and_keeps_the_successor() {
        let repo = TestRepo::new();
        let base = repo.head_sha();
        let (_home, store, mut session, merged, successor) =
            merged_task_with_successor(&repo, Some(&base)).await;

        // If the discard were a precondition rather than part of completing, this
        // review would block *after* the successor was dropped, leaving a
        // non-terminal Task with no active PR — the exact shape
        // `ensure_working_pr_with_authority` rotates a fresh empty PR from.
        let (review_id, _lease) = open_gate_review(&store, &mut session, &merged, None).await;
        session.set_status(TaskSessionStatus::Waiting, "merged; awaiting gate");

        let gate = task_completion_gate(&store, &session)
            .await
            .expect("gate with review open");
        assert!(!gate.satisfied);
        assert!(
            gate.reason().contains("awaiting review"),
            "the refusal must name the review: {}",
            gate.reason()
        );
        assert_eq!(
            pr_phase(&store, &successor.id).await,
            PrPhase::Working,
            "a completion blocked for any other reason must leave the successor active"
        );

        // The store, not caller ordering, is what makes a pre-gate discard
        // unrepresentable: skipping a PR is legal only while completing.
        assert!(
            complete_task_session_with_authority(&store, &session, Some(&successor), None)
                .await
                .is_err(),
            "dropping a successor outside a completing transaction must refuse"
        );

        store
            .complete_human_interaction_review(
                &review_id,
                InteractionReviewDisposition::Approved,
                "approved",
            )
            .await
            .expect("approve review");

        let gate = task_completion_gate(&store, &session)
            .await
            .expect("gate after approval");
        assert!(gate.satisfied, "{:?}", gate.blockers);
        session.set_status(TaskSessionStatus::Completed, "merged work settled");
        complete_task_session_with_authority(
            &store,
            &session,
            gate.discardable_successor.as_ref(),
            None,
        )
        .await
        .expect("complete after approval");
        assert_eq!(
            store.task_prs(&session.id).await.expect("read PRs").len(),
            1,
            "one completion must settle it with no replacement minted"
        );
    }

    /// Only a successor proven to hold nothing may be discarded. A `Range` is
    /// authored work that completing would strand; an `Unprovable` base means the
    /// branch cannot be *shown* empty, which is not the same as being empty —
    /// `is_ancestor` reports the same false for a base whose object is gone.
    #[tokio::test]
    async fn a_successor_that_is_not_proven_empty_is_never_discardable() {
        for (case, commits_work, expected) in [
            ("range", true, "follow-up work is committed on unpublished"),
            (
                "unprovable",
                false,
                "recorded base is not an ancestor of the unpublished branch",
            ),
        ] {
            let repo = TestRepo::new();
            let base = repo.head_sha();
            let (_home, store, session, _merged, successor) =
                merged_task_with_successor(&repo, commits_work.then_some(base.as_str())).await;
            if commits_work {
                repo.create_file("follow-up.txt", "work that must not be dropped\n");
                repo.stage_all();
                repo.commit("follow-up work");
            }

            let gate = task_completion_gate(&store, &session)
                .await
                .unwrap_or_else(|error| panic!("{case}: {error}"));
            assert!(!gate.satisfied, "{case} must fail closed");
            assert!(
                gate.discardable_successor.is_none(),
                "{case} must never be classified discardable"
            );
            assert!(
                gate.reason().contains(expected),
                "{case} must say why: {}",
                gate.reason()
            );
            assert_eq!(
                pr_phase(&store, &successor.id).await,
                PrPhase::Working,
                "{case} must leave the row untouched"
            );
            if commits_work {
                assert_eq!(
                    super::rev_parse(repo.path(), SUCCESSOR_BRANCH).expect("resolve tip"),
                    repo.head_sha(),
                    "{case} must preserve the committed follow-up"
                );
            }
        }
    }

    #[tokio::test]
    async fn completion_gate_blocks_when_follow_up_range_is_unprovable() {
        let repo = TestRepo::new();
        let branch = "jack/gate-proof";
        let base = repo.head_sha();
        repo.create_branch(branch);
        let (_home, store, session, pr) = gate_task(&repo, branch, &base).await;

        let mut unprovable = pr.clone();
        unprovable
            .publication
            .as_mut()
            .and_then(|publication| publication.github.as_mut())
            .expect("published github PR")
            .head_sha = None;
        unprovable.updated_at = OffsetDateTime::now_utc();
        store
            .update_task_pr(&unprovable)
            .await
            .expect("remove published head");

        let gate = task_completion_gate(&store, &session)
            .await
            .expect("gate with missing head");
        assert!(!gate.satisfied);
        assert!(
            gate.reason()
                .contains("published pull request head is missing"),
            "missing head must fail closed: {}",
            gate.reason()
        );

        git(
            repo.path(),
            &["checkout", "--orphan", "jack/rewritten-head"],
        );
        git(
            repo.path(),
            &["commit", "--allow-empty", "-m", "rewritten published head"],
        );
        let rewritten_head = repo.head_sha();
        git(repo.path(), &["checkout", branch]);

        unprovable
            .publication
            .as_mut()
            .and_then(|publication| publication.github.as_mut())
            .expect("published github PR")
            .head_sha = Some(rewritten_head);
        unprovable.updated_at = OffsetDateTime::now_utc();
        store
            .update_task_pr(&unprovable)
            .await
            .expect("record rewritten published head");

        let gate = task_completion_gate(&store, &session)
            .await
            .expect("gate with rewritten head");
        assert!(!gate.satisfied);
        assert!(
            gate.reason()
                .contains("published pull request head is not an ancestor"),
            "rewritten head must fail closed: {}",
            gate.reason()
        );
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)] // the env lock is the test serializer
    async fn completion_is_withheld_over_work_committed_past_the_merged_tip() {
        let repo = TestRepo::new();
        let branch = "jack/gate-proof";
        let base = repo.head_sha();
        repo.create_branch(branch);
        repo.create_file("merged.txt", "merged work\n");
        repo.stage_all();
        repo.commit("merged work");
        let merged_tip = repo.head_sha();

        let (_home, store, mut session, pr) = gate_task(&repo, branch, &base).await;
        let mut open = pr.clone();
        open.merge_commit = None;
        open.github_observation = None;
        open.publication
            .as_mut()
            .and_then(|publication| publication.github.as_mut())
            .expect("published github PR")
            .head_sha = Some(merged_tip.clone());
        store.update_task_pr(&open).await.expect("open fixture PR");

        repo.create_file("follow-up.txt", "acknowledged follow-up\n");
        repo.stage_all();
        repo.commit("follow-up the directive asked for");

        git(
            repo.path(),
            &[
                "remote",
                "set-url",
                "origin",
                "https://github.com/test/repo.git",
            ],
        );
        let bin = tempfile::tempdir().expect("fake gh bin");
        let gh = bin.path().join("gh");
        std::fs::write(
            &gh,
            format!(
                "#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then exit 0; fi\nprintf '%s\\n' '{{\"merged\":true,\"state\":\"closed\",\"merge_commit_sha\":\"merge-912\",\"number\":912,\"html_url\":\"https://example.com/pr/912\",\"head\":{{\"sha\":\"{merged_tip}\"}}}}'\n"
            ),
        )
        .expect("write fake gh");
        let mut permissions = std::fs::metadata(&gh).expect("stat fake gh").permissions();
        permissions.set_mode(0o755);
        std::fs::set_permissions(&gh, permissions).expect("make fake gh executable");
        let _env_lock = crate::journal::test_env_lock();
        let previous_path = std::env::var_os("PATH");
        let path = match &previous_path {
            Some(previous) => format!("{}:{}", bin.path().display(), previous.to_string_lossy()),
            None => bin.path().display().to_string(),
        };
        std::env::set_var("PATH", path);
        let observed = reconcile_task_pr(&store, &mut session).await;
        match previous_path {
            Some(path) => std::env::set_var("PATH", path),
            None => std::env::remove_var("PATH"),
        }

        let observed = observed
            .expect("observe merged PR")
            .expect("persist merged PR");
        assert_eq!(observed.phase(), PrPhase::Merged);
        assert_ne!(
            session.status,
            TaskSessionStatus::Completed,
            "merge observation must not complete over committed follow-up"
        );

        reconcile_task_completion(&store, &mut session, None)
            .await
            .expect("reconcile with follow-up outstanding");
        assert_ne!(
            session.status,
            TaskSessionStatus::Completed,
            "reconcile must not complete over committed follow-up"
        );
        assert_eq!(session.pm_writeback, PmWritebackState::Current);
        assert!(repo.path().join("follow-up.txt").exists());
    }

    #[tokio::test]
    async fn completion_gate_blocks_on_a_pending_required_review() {
        let repo = TestRepo::new();
        let branch = "jack/gate-proof";
        repo.create_branch(branch);
        let base = repo.head_sha();
        let (_home, store, mut session, pr) = gate_task(&repo, branch, &base).await;
        let (review_id, _lease) = open_gate_review(&store, &mut session, &pr, None).await;

        // The merged PR is settled, but the required Human review is open: the
        // gate must block on the review, not on the PR.
        let gate = task_completion_gate(&store, &session).await.expect("gate");
        assert!(!gate.satisfied);
        assert!(
            gate.reason().contains(&review_id.as_str().to_string()),
            "blocker should name the open review {}: {}",
            review_id,
            gate.reason()
        );

        // Approve the review and the gate closes.
        store
            .complete_human_interaction_review(
                &review_id,
                InteractionReviewDisposition::Approved,
                "approved",
            )
            .await
            .expect("approve review");
        let gate = task_completion_gate(&store, &session)
            .await
            .expect("gate after approve");
        assert!(
            gate.satisfied,
            "gate should close after approval: {:?}",
            gate.blockers
        );
    }

    #[tokio::test]
    async fn a_superseded_kickoff_changes_request_does_not_bar_completion() {
        let repo = TestRepo::new();
        let branch = "jack/gate-proof";
        repo.create_branch(branch);
        let base = repo.head_sha();
        let (_home, store, mut session, pr) = gate_task(&repo, branch, &base).await;
        session.lifecycle_phase = TaskLifecyclePhase::Kickoff;
        session.phase_epoch = 1;
        session.gate_cycle = 0;
        session.gate_proposal = None;
        let (review_id, _lease) = open_gate_review(&store, &mut session, &pr, None).await;
        store
            .complete_human_interaction_review(
                &review_id,
                InteractionReviewDisposition::ChangesRequested,
                "repair the design",
            )
            .await
            .expect("request kickoff changes");
        session.enter_iterate().expect("enter repair iteration");

        let gate = task_completion_gate(&store, &session).await.expect("gate");

        assert!(
            gate.satisfied,
            "superseded kickoff review: {:?}",
            gate.blockers
        );
    }

    #[tokio::test]
    async fn the_newest_gate_cycle_supersedes_an_earlier_changes_request() {
        let repo = TestRepo::new();
        let branch = "jack/gate-proof";
        repo.create_branch(branch);
        let base = repo.head_sha();
        let (_home, store, mut session, pr) = gate_task(&repo, branch, &base).await;
        let (first, lease) = open_gate_review(&store, &mut session, &pr, None).await;
        store
            .complete_human_interaction_review(
                &first,
                InteractionReviewDisposition::ChangesRequested,
                "repair cycle one",
            )
            .await
            .expect("request gate changes");
        session.enter_iterate().expect("enter repair iteration");
        session
            .enter_gate(TaskGateProposal {
                status: TaskSessionStatus::Completed,
                reason: "repair verified".to_string(),
            })
            .expect("enter the next gate cycle");
        store
            .update_task_session_for_lease(&session, &lease)
            .await
            .expect("persist the next gate cycle");
        let (second, _lease) = open_gate_review(&store, &mut session, &pr, Some(lease)).await;
        store
            .complete_human_interaction_review(
                &second,
                InteractionReviewDisposition::Approved,
                "repair approved",
            )
            .await
            .expect("approve the latest gate");

        let gate = task_completion_gate(&store, &session).await.expect("gate");

        assert!(
            gate.satisfied,
            "newest gate should supersede: {:?}",
            gate.blockers
        );
    }

    #[tokio::test]
    async fn a_rejected_gate_cycle_still_bars_completion_from_iterate() {
        let repo = TestRepo::new();
        let branch = "jack/gate-proof";
        repo.create_branch(branch);
        let base = repo.head_sha();
        let (_home, store, mut session, pr) = gate_task(&repo, branch, &base).await;
        let (review_id, _lease) = open_gate_review(&store, &mut session, &pr, None).await;
        store
            .complete_human_interaction_review(
                &review_id,
                InteractionReviewDisposition::ChangesRequested,
                "repair the implementation",
            )
            .await
            .expect("request gate changes");
        session.enter_iterate().expect("return to iteration");

        let gate = task_completion_gate(&store, &session).await.expect("gate");

        assert!(!gate.satisfied);
        assert!(gate.reason().contains(review_id.as_str()));
    }

    #[tokio::test]
    async fn reconcile_advances_completion_once_the_gate_closes() {
        let repo = TestRepo::new();
        let branch = "jack/gate-proof";
        repo.create_branch(branch);
        let base = repo.head_sha();
        let (_home, store, mut session, pr) = gate_task(&repo, branch, &base).await;
        let (review_id, _lease) = open_gate_review(&store, &mut session, &pr, None).await;
        session.set_status(TaskSessionStatus::Waiting, "merged; awaiting gate");

        // Reconcile with the review still open: no completion, no writeback.
        reconcile_task_completion(&store, &mut session, None)
            .await
            .expect("reconcile while gate open");
        assert_ne!(
            session.status,
            TaskSessionStatus::Completed,
            "Task must not complete while the required review is open"
        );
        assert_eq!(session.pm_writeback, PmWritebackState::Current);

        // Approve the review; the next reconcile completes the Task exactly once.
        store
            .complete_human_interaction_review(
                &review_id,
                InteractionReviewDisposition::Approved,
                "approved",
            )
            .await
            .expect("approve review");
        reconcile_task_completion(&store, &mut session, None)
            .await
            .expect("reconcile after gate closes");
        assert_eq!(session.status, TaskSessionStatus::Completed);
        // The advance fires the CompleteTask writeback exactly once. In the test
        // environment there is no Linear initiative, so the writeback lands as
        // Pending (it attempted and will retry) — never Current-without-attempt,
        // and never a second stacked operation.
        assert!(
            matches!(
                session.pm_writeback,
                PmWritebackState::Pending {
                    operation: PmWritebackOperation::CompleteTask,
                    ..
                }
            ),
            "advance must fire the CompleteTask writeback once, got {:?}",
            session.pm_writeback
        );

        // A duplicate reconcile does not stack a second operation: still
        // Completed, still a single Pending CompleteTask writeback.
        reconcile_task_completion(&store, &mut session, None)
            .await
            .expect("duplicate reconcile");
        assert_eq!(session.status, TaskSessionStatus::Completed);
        assert!(
            matches!(
                session.pm_writeback,
                PmWritebackState::Pending {
                    operation: PmWritebackOperation::CompleteTask,
                    ..
                }
            ),
            "duplicate reconcile must not stack a second writeback, got {:?}",
            session.pm_writeback
        );
    }

    #[tokio::test]
    async fn repair_reverts_a_premature_completion_to_waiting() {
        let repo = TestRepo::new();
        let branch = "jack/gate-proof";
        repo.create_branch(branch);
        let base = repo.head_sha();
        let (_home, store, mut session, pr) = gate_task(&repo, branch, &base).await;
        let (review_id, _lease) = open_gate_review(&store, &mut session, &pr, None).await;
        // Simulate the W2-151 premature completion: the PM says done while the
        // required review is still open.
        session.set_status(TaskSessionStatus::Completed, "merged and completed");
        session.pm_writeback = PmWritebackState::Current;

        reconcile_task_completion(&store, &mut session, None)
            .await
            .expect("repair reconcile");

        assert_eq!(
            session.status,
            TaskSessionStatus::Waiting,
            "premature completion must revert to Waiting"
        );
        assert!(
            matches!(
                session.pm_writeback,
                PmWritebackState::Pending {
                    operation: PmWritebackOperation::ReopenTask,
                    ..
                }
            ),
            "repair must queue a ReopenTask writeback, got {:?}",
            session.pm_writeback
        );
        assert!(
            session
                .status_reason
                .contains(&review_id.as_str().to_string())
                || session.status_reason.contains("outran its gates"),
            "repair reason should be actionable: {}",
            session.status_reason
        );

        // Nothing was lost: the PR, the review, and the directive rows survive.
        let prs = store.task_prs(&session.id).await.expect("read PRs");
        assert_eq!(prs.len(), 1, "PR row must survive repair");
        assert!(
            store
                .list_interaction_reviews(Some(&session.wave_id))
                .await
                .expect("read reviews")
                .iter()
                .any(|review| review.id == review_id),
            "review row must survive repair"
        );
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)] // the env lock serializes process-global launch vars
    async fn project_supervision_keeps_pending_and_unknown_gate_tasks_parked() {
        let _env_lock = crate::journal::test_env_lock();
        for (label, state) in [("pending", Some(CiState::Pending)), ("unknown", None)] {
            let repo = TestRepo::new();
            let branch = format!("jack/gate-{label}");
            let (home, store, project, session, _pr) =
                parked_gate_task(&repo, &branch, state, 0).await;
            let _launch_env = TaskLaunchEnv::install(home.path());

            supervise_project_task_bodies(&store, &project)
                .await
                .expect("supervise parked Gate");

            let persisted = store
                .get_task_session(&session.id)
                .await
                .expect("read Task")
                .expect("Task exists");
            assert_eq!(persisted.status, TaskSessionStatus::Waiting, "{label}");
            assert_eq!(
                persisted.lifecycle_phase,
                crate::task::TaskLifecyclePhase::Gate,
                "{label}"
            );
            assert_eq!(persisted.phase_cursor, 0, "{label}");
            assert!(persisted.latest_process.is_none(), "{label}");
            assert!(
                store
                    .list_child_commands(&ChildRef::Task(session.id.clone()))
                    .await
                    .expect("read Task commands")
                    .is_empty(),
                "{label}"
            );
            assert!(
                store
                    .list_interaction_reviews(Some(&session.wave_id))
                    .await
                    .expect("read interaction reviews")
                    .is_empty(),
                "{label}"
            );
        }
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)] // the env lock serializes process-global launch vars
    async fn project_supervision_creates_one_existing_ci_fix_wake_for_red() {
        let _env_lock = crate::journal::test_env_lock();
        let repo = TestRepo::new();
        let (home, store, project, session, _pr) =
            parked_gate_task(&repo, "jack/gate-red", Some(CiState::Failing), 0).await;
        let _launch_env = TaskLaunchEnv::install(home.path());

        supervise_project_task_bodies(&store, &project)
            .await
            .expect("first red supervision");
        supervise_project_task_bodies(&store, &project)
            .await
            .expect("duplicate red supervision");

        let commands = store
            .list_child_commands(&ChildRef::Task(session.id.clone()))
            .await
            .expect("read Task commands");
        assert_eq!(
            commands.len(),
            1,
            "the incident identity deduplicates wakes"
        );
        assert!(matches!(commands[0].kind, ChildCommandKind::CiFix { .. }));
        let persisted = store
            .get_task_session(&session.id)
            .await
            .expect("read Task")
            .expect("Task exists");
        assert_eq!(
            persisted
                .latest_process
                .as_ref()
                .expect("ci-fix launch reserves a generation")
                .generation,
            1
        );
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)] // the env lock serializes process-global launch vars
    async fn project_supervision_enqueues_one_attributable_wake_for_live_idle_red() {
        let _env_lock = crate::journal::test_env_lock();
        let repo = TestRepo::new();
        let (home, store, project, mut session, _pr) =
            parked_gate_task(&repo, "jack/gate-live-idle", Some(CiState::Failing), 0).await;
        session.begin_generation("lf-live-idle-control".to_string());
        let lease = store
            .reserve_task_process(&session, TaskSessionStatus::Waiting)
            .await
            .expect("reserve live control body")
            .expect("waiting Task reserves one generation");
        if let Some(process) = session.latest_process.as_mut() {
            process.state = crate::child_session::ChildLeaseState::Active;
        }
        session.set_status(
            TaskSessionStatus::Running,
            "Project review owns the Gate step; provider turn is idle",
        );
        store
            .activate_task_process(&session, &lease)
            .await
            .expect("activate live control body");
        let _launch_env = TaskLaunchEnv::install(home.path());

        supervise_project_task_bodies(&store, &project)
            .await
            .expect("first live-idle red supervision");
        supervise_project_task_bodies(&store, &project)
            .await
            .expect("duplicate live-idle red supervision");

        let commands = store
            .list_child_commands(&ChildRef::Task(session.id.clone()))
            .await
            .expect("read Task commands");
        assert_eq!(commands.len(), 1, "the current failure wakes once");
        assert!(matches!(commands[0].kind, ChildCommandKind::CiFix { .. }));
        assert_eq!(commands[0].state, ChildCommandState::Persisted);
        assert_eq!(commands[0].claimed_by_generation, None);

        let incidents = store
            .ci_incidents_since(OffsetDateTime::UNIX_EPOCH, None, None)
            .await
            .expect("read CI incidents");
        let incident = incidents
            .iter()
            .find(|row| row.incident.task_session_id == session.id)
            .expect("live-idle incident exists");
        assert_eq!(
            incident.incident.trigger_command_id.as_ref(),
            Some(&commands[0].id),
            "the wake must be attributable before the live control body claims it"
        );
        assert_eq!(incident.incident.responded_at, None);

        let persisted = store
            .get_task_session(&session.id)
            .await
            .expect("read Task")
            .expect("Task exists");
        assert_eq!(
            persisted.status,
            TaskSessionStatus::Running,
            "{}",
            persisted.status_reason
        );
        assert_eq!(
            persisted
                .latest_process
                .as_ref()
                .expect("control generation remains active")
                .generation,
            lease.generation,
            "supervision must not interrupt or replace the live control body"
        );
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)] // the env lock serializes process-global launch vars
    async fn project_supervision_relaunches_a_fresh_green_gate_exactly_once() {
        let _env_lock = crate::journal::test_env_lock();
        let repo = TestRepo::new();
        let (home, store, project, session, _pr) =
            parked_gate_task(&repo, "jack/gate-green", Some(CiState::Passing), 0).await;
        let _launch_env = TaskLaunchEnv::install(home.path());

        supervise_project_task_bodies(&store, &project)
            .await
            .expect("first green supervision");
        supervise_project_task_bodies(&store, &project)
            .await
            .expect("duplicate green supervision");

        let persisted = store
            .get_task_session(&session.id)
            .await
            .expect("read Task")
            .expect("Task exists");
        assert_eq!(persisted.status, TaskSessionStatus::Starting);
        assert_eq!(
            persisted
                .latest_process
                .as_ref()
                .expect("green Gate relaunch reserves a generation")
                .generation,
            1,
            "the second observation must not reserve another generation"
        );
        assert!(
            store
                .list_interaction_reviews(Some(&session.wave_id))
                .await
                .expect("read interaction reviews")
                .is_empty(),
            "Project reconciliation launches Gate; the Gate body owns review creation"
        );
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)] // the env lock serializes process-global launch vars
    async fn project_supervision_does_not_relaunch_green_after_gate_advances() {
        let _env_lock = crate::journal::test_env_lock();
        let repo = TestRepo::new();
        let (home, store, project, session, _pr) =
            parked_gate_task(&repo, "jack/gate-advanced", Some(CiState::Passing), 1).await;
        let _launch_env = TaskLaunchEnv::install(home.path());

        supervise_project_task_bodies(&store, &project)
            .await
            .expect("supervise advanced Gate");

        let persisted = store
            .get_task_session(&session.id)
            .await
            .expect("read Task")
            .expect("Task exists");
        assert_eq!(persisted.phase_cursor, 1);
        assert!(
            persisted.latest_process.is_none(),
            "green observation cannot reopen an advanced Gate"
        );
        assert!(
            store
                .list_interaction_reviews(Some(&session.wave_id))
                .await
                .expect("read interaction reviews")
                .is_empty(),
            "Project reconciliation cannot create a second review"
        );
    }

    /// Build an open Task PR with a GitHub receipt and an optional CI reading
    /// for `head_sha`, the minimal shape `decide_open_pr_status` reads.
    fn open_pr_with_ci(number: u32, head_sha: &str, state: Option<CiState>) -> TaskPr {
        let now = OffsetDateTime::now_utc();
        TaskPr {
            id: TaskPrId::new(),
            task_session_id: TaskSessionId::new(),
            sequence: 1,
            slug: "w2-231".to_string(),
            branch: "feature".to_string(),
            base_commit: "base".to_string(),
            parent_pr_id: None,
            publication: Some(PrPublication {
                requested_at: now,
                after_merge: AfterMerge::Review,
                next_slug: None,
                github: Some(GithubPr {
                    number,
                    url: format!("https://github.com/loopflow/loopflow/pull/{number}"),
                    head_sha: Some(head_sha.to_string()),
                }),
            }),
            merge_commit: None,
            abandoned_at: None,
            github_observation: None,
            ci_observation: state.map(|state| CiObservation {
                head_sha: head_sha.to_string(),
                state,
                failing_checks: if state == CiState::Failing {
                    vec![CiCheck {
                        name: "build".to_string(),
                        url: Some("https://ci/build".to_string()),
                    }]
                } else {
                    Vec::new()
                },
                observed_at: now,
            }),
            linear_attachment_id: None,
            linear_comment_id: None,
            linear_link_error: None,
            created_at: now,
            updated_at: now,
        }
    }

    #[test]
    fn decide_open_pr_status_blocks_on_degraded_github_observation() {
        // A turn that ran blind to GitHub cannot be said to have repaired the
        // head: block on the named capability with the PR still attached.
        let pr = open_pr_with_ci(42, "sha-1", Some(CiState::Failing));
        let (status, reason) =
            decide_open_pr_status(&pr, Some("GitHub API rate limit exceeded"), false);
        assert_eq!(status, TaskSessionStatus::Blocked);
        assert!(reason.contains("github-observation"), "reason: {reason}");
        assert!(reason.contains("rate limit"), "reason: {reason}");
        assert!(reason.contains("#42 stays attached"), "reason: {reason}");
    }

    #[test]
    fn decide_open_pr_status_blocks_on_no_change_failing_ci() {
        // The body completed but the head did not advance and CI is still
        // Failing — a no-change report, not a healthy PR observation.
        let pr = open_pr_with_ci(42, "sha-1", Some(CiState::Failing));
        let (status, reason) = decide_open_pr_status(&pr, None, false);
        assert_eq!(status, TaskSessionStatus::Blocked);
        assert!(reason.contains("did not repair"), "reason: {reason}");
        assert!(reason.contains("#42 stays attached"), "reason: {reason}");
    }

    #[test]
    fn decide_open_pr_status_waits_when_head_advanced_even_if_failing() {
        // The body pushed (head advanced) — that is progress, so the Task waits
        // for CI to resolve instead of blocking a genuine attempt.
        let pr = open_pr_with_ci(42, "sha-2", Some(CiState::Failing));
        let (status, reason) = decide_open_pr_status(&pr, None, true);
        assert_eq!(status, TaskSessionStatus::Waiting);
        assert!(reason.contains("open for review"), "reason: {reason}");
    }

    #[test]
    fn decide_open_pr_status_waits_on_healthy_ci() {
        let pending = open_pr_with_ci(42, "sha-1", Some(CiState::Pending));
        assert_eq!(
            decide_open_pr_status(&pending, None, false).0,
            TaskSessionStatus::Waiting
        );
        let passing = open_pr_with_ci(42, "sha-1", Some(CiState::Passing));
        assert_eq!(
            decide_open_pr_status(&passing, None, false).0,
            TaskSessionStatus::Waiting
        );
        // No required checks / gh unavailable reads as unknown-healthy, so an
        // env without CI configured is never penalized with a block.
        let unknown = open_pr_with_ci(42, "sha-1", None);
        assert_eq!(
            decide_open_pr_status(&unknown, None, false).0,
            TaskSessionStatus::Waiting
        );
    }

    #[test]
    fn decide_open_pr_status_degraded_dominates_healthy_ci() {
        // A degraded observation blocks even when the cached CI reading looks
        // healthy: the reading may simply be stale.
        let pr = open_pr_with_ci(42, "sha-1", Some(CiState::Passing));
        let (status, reason) = decide_open_pr_status(&pr, Some("network unreachable"), true);
        assert_eq!(status, TaskSessionStatus::Blocked);
        assert!(reason.contains("github-observation"), "reason: {reason}");
    }
}