clt-rs 0.6.19

File-backed task manager with a TUI Kanban board and multi-project Codex agent registry
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
use std::{
    collections::BTreeMap,
    fs,
    io::Write,
    path::{Path, PathBuf},
    process::{Command, Stdio},
    sync::{Arc, Mutex, mpsc},
    thread,
    time::{Duration, Instant},
};

use anyhow::{Context, Result};
use tempfile::TempDir;

use crate::{
    agent::{
        self, AGENT_ABANDONED_UNBOUND_JOURNAL_REASON, AgentGitMode, GitFinalizationState,
        open_agent_store_at, with_agent_store_at,
    },
    application::{AgentLeaseHolderLiveness, AgentRunJob, AgentTaskSelection},
    platform::{configure_agent_child_command, stop_agent_child_process},
    runner::{agent_timestamp, agent_timestamp_after},
    scheduler::{
        agent_lease_for_project, agent_lease_holder_liveness, agent_lease_renew_interval,
        remaining_agent_delay,
    },
    session_control::InteractiveAgentLease,
    task::{
        CODEX_TASK_SESSION_PREFIX, StatusStore, TASK_DETAIL_FILES, TASK_STATUSES, TaskBoard,
        TaskEntry, TaskSource, TaskStatus, acquire_board_mutation_lock,
        acquire_board_mutation_lock_with_contention_callback,
        attach_codex_session_to_task_after_lock, cleanup_clt_atomic_task_temporaries,
        codex_session_id_from_task_content, codex_session_markers_in_task_content,
        durable_task_identity, follow_up_matches_status, follow_up_session, get_status_store,
        get_tasks_dir, move_task_without_reordering_after_lock, read_task_entries,
        remove_task_entry_without_reordering, starts_with_task_note_date, task_content_is_blocked,
        task_entry_is_ready, task_tree_contains_session_marker,
        terminal_task_for_codex_session_in_board, title_from_path,
    },
};

const AGENT_GIT_REMOTE_TIMEOUT_SECONDS: u64 = 30;
// A commit-and-push reconciliation can perform two three-step remote proofs
// around one push. Its dedicated renewable lease stays beyond that bounded
// single-pass worst case without inheriting the ordinary one-hour worker TTL.
pub(super) const AGENT_GIT_FINALIZATION_LEASE_SECONDS: u64 =
    AGENT_GIT_REMOTE_TIMEOUT_SECONDS * 8 + 60;
pub(super) const AGENT_GIT_IDENTITY_NAME: &str = "CLT Agent";
pub(super) const AGENT_GIT_IDENTITY_EMAIL: &str = "clt-agent@localhost";
const AGENT_GIT_BOARD_CHECKPOINT_MESSAGE: &str = "Record CLT task board";

pub(super) struct AgentGitFinalizationLease {
    lease: Option<InteractiveAgentLease>,
    pub(super) holder: String,
    stop_heartbeat: Option<mpsc::Sender<()>>,
    heartbeat: Option<thread::JoinHandle<()>>,
    heartbeat_error: Arc<Mutex<Option<String>>>,
}

impl AgentGitFinalizationLease {
    fn start(lease: InteractiveAgentLease, timeout: Duration) -> Result<Self> {
        let state_dir = lease.state_dir.clone();
        let project_id = lease.project_id;
        let holder = lease.holder.clone();
        let timeout_seconds = timeout.as_secs().max(1);
        let renew_interval = agent_lease_renew_interval(timeout);
        let (stop_heartbeat, stop_receiver) = mpsc::channel();
        let heartbeat_error = Arc::new(Mutex::new(None));
        let heartbeat_error_for_thread = Arc::clone(&heartbeat_error);
        let heartbeat_holder = holder.clone();
        let heartbeat = thread::Builder::new()
            .name(format!("clt-git-finalizer-{project_id}"))
            .spawn(move || loop {
                match stop_receiver.recv_timeout(renew_interval) {
                    Ok(()) | Err(mpsc::RecvTimeoutError::Disconnected) => break,
                    Err(mpsc::RecvTimeoutError::Timeout) => {}
                }
                let expires_at = agent_timestamp_after(timeout_seconds);
                let renewal = with_agent_store_at(&state_dir, |store| {
                    store.renew_git_finalization_lease_blocking(
                        project_id,
                        &heartbeat_holder,
                        &expires_at,
                    )
                });
                let error = match renewal {
                    Ok(true) => continue,
                    Ok(false) => format!(
                        "Git finalizer lost its exact project lease for project {project_id}"
                    ),
                    Err(error) => format!(
                        "Git finalizer could not renew its exact project lease for project {project_id}: {error:#}"
                    ),
                };
                let mut recorded = heartbeat_error_for_thread
                    .lock()
                    .unwrap_or_else(|poisoned| poisoned.into_inner());
                if recorded.is_none() {
                    *recorded = Some(error);
                }
                break;
            })
            .context("Failed to start the Git finalization lease heartbeat")?;
        Ok(Self {
            lease: Some(lease),
            holder,
            stop_heartbeat: Some(stop_heartbeat),
            heartbeat: Some(heartbeat),
            heartbeat_error,
        })
    }

    fn project_id(&self) -> i64 {
        self.lease
            .as_ref()
            .expect("Git finalization lease remains present until release")
            .project_id
    }

    fn state_dir(&self) -> &Path {
        &self
            .lease
            .as_ref()
            .expect("Git finalization lease remains present until release")
            .state_dir
    }

    fn heartbeat_error(&self) -> Option<String> {
        self.heartbeat_error
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .clone()
    }

    pub(super) fn ensure_owned(&self) -> Result<()> {
        if let Some(error) = self.heartbeat_error() {
            anyhow::bail!(error);
        }
        let owned = with_agent_store_at(self.state_dir(), |store| {
            store.git_finalization_lease_is_owned_blocking(
                self.project_id(),
                &self.holder,
                &agent_timestamp(),
            )
        })?;
        if !owned {
            anyhow::bail!(
                "Git finalizer lost its exact project lease for project {}",
                self.project_id()
            );
        }
        if let Some(error) = self.heartbeat_error() {
            anyhow::bail!(error);
        }
        Ok(())
    }

    fn stop_heartbeat(&mut self) -> Result<()> {
        if let Some(stop) = self.stop_heartbeat.take() {
            let _ = stop.send(());
        }
        if let Some(heartbeat) = self.heartbeat.take() {
            heartbeat
                .join()
                .map_err(|_| anyhow::anyhow!("Git finalization lease heartbeat panicked"))?;
        }
        Ok(())
    }

    pub(super) fn release(mut self) -> Result<()> {
        let heartbeat_result = self.stop_heartbeat();
        let fence_result = self.ensure_owned();
        let release_result = self
            .lease
            .take()
            .expect("Git finalization lease is released once")
            .release();
        heartbeat_result?;
        fence_result?;
        release_result
    }
}

impl Drop for AgentGitFinalizationLease {
    fn drop(&mut self) {
        let _ = self.stop_heartbeat();
        drop(self.lease.take());
    }
}

pub(super) fn try_acquire_agent_git_finalization_lease_with_timeout(
    state_dir: &Path,
    project: &agent::AgentProject,
    reclaim_current_process_leases: bool,
    timeout: Duration,
) -> Result<Option<AgentGitFinalizationLease>> {
    let holder = InteractiveAgentLease::holder_for_current_process_with_prefix("clt-git-finalizer");
    let existing = agent_lease_for_project(state_dir, project.id)?;
    let reclaim_holder = existing.as_ref().and_then(|lease| {
        matches!(
            agent_lease_holder_liveness(&lease.holder),
            AgentLeaseHolderLiveness::Dead
        )
        .then_some(lease.holder.as_str())
        .or_else(|| {
            (reclaim_current_process_leases
                && agent_lease_holder_liveness(&lease.holder)
                    == AgentLeaseHolderLiveness::CurrentProcess)
                .then_some(lease.holder.as_str())
        })
    });
    let acquired_at = agent_timestamp();
    let expires_at = agent_timestamp_after(timeout.as_secs().max(1));
    let acquired = with_agent_store_at(state_dir, |store| {
        store.try_acquire_git_finalization_lease_blocking(
            project.id,
            &holder,
            &acquired_at,
            &expires_at,
            reclaim_holder,
        )
    })?;
    if !acquired {
        return Ok(None);
    }
    let lease = InteractiveAgentLease {
        state_dir: state_dir.to_path_buf(),
        project_id: project.id,
        holder,
        released: false,
    };
    AgentGitFinalizationLease::start(lease, timeout).map(Some)
}

pub(super) fn try_acquire_agent_git_finalization_lease(
    state_dir: &Path,
    project: &agent::AgentProject,
    reclaim_current_process_leases: bool,
) -> Result<Option<AgentGitFinalizationLease>> {
    try_acquire_agent_git_finalization_lease_with_timeout(
        state_dir,
        project,
        reclaim_current_process_leases,
        Duration::from_secs(AGENT_GIT_FINALIZATION_LEASE_SECONDS),
    )
}

pub(super) fn record_agent_git_push_retry_error(
    state_dir: &Path,
    project_id: i64,
    error: &anyhow::Error,
    finalization_lease: &AgentGitFinalizationLease,
) -> Result<()> {
    record_agent_git_push_retry_error_message(
        state_dir,
        project_id,
        &format!("{error:#}"),
        finalization_lease,
    )
}

pub(super) fn record_agent_git_push_retry_error_message(
    state_dir: &Path,
    project_id: i64,
    error: &str,
    finalization_lease: &AgentGitFinalizationLease,
) -> Result<()> {
    for _ in 0..3 {
        finalization_lease.ensure_owned()?;
        let finalization = with_agent_store_at(state_dir, |store| {
            Ok(store
                .list_pending_git_finalizations_blocking(Some(project_id))?
                .into_iter()
                .find(|finalization| finalization.state == GitFinalizationState::PushPending))
        })?;
        let Some(finalization) = finalization else {
            return Ok(());
        };
        finalization_lease.ensure_owned()?;
        let changed = with_agent_store_at(state_dir, |store| {
            store.compare_and_set_git_finalization_blocking(
                finalization.project_id,
                &finalization.codex_session_id,
                finalization.generation,
                GitFinalizationState::PushPending,
                finalization.owner_run_token.as_deref(),
                None,
                Some(error),
                &agent_timestamp(),
            )
        })?;
        if changed {
            return Ok(());
        }
    }
    anyhow::bail!(
        "Git push retry state changed repeatedly before CLT could persist its retry backoff"
    )
}

pub(super) fn agent_git_push_retry_backoff_remaining(
    finalizations: &[agent::GitFinalizationRecord],
    now: u64,
    failure_backoff: Duration,
) -> Option<u64> {
    finalizations
        .iter()
        .find(|finalization| {
            finalization.state == GitFinalizationState::PushPending
                && finalization.last_error.is_some()
        })
        .and_then(|finalization| {
            remaining_agent_delay(Some(&finalization.updated_at), now, failure_backoff)
        })
}

pub(super) fn repair_working_git_task_link(
    store: &agent::TursoAgentStore,
    project_root: &Path,
    finalization: &agent::GitFinalizationRecord,
) -> Result<bool> {
    repair_working_git_task_link_with_before_lock(store, project_root, finalization, || {})
}

pub(super) fn exact_working_git_finalization_snapshot(
    current: &agent::GitFinalizationRecord,
    expected: &agent::GitFinalizationRecord,
) -> bool {
    current.state == GitFinalizationState::Working
        && expected.state == GitFinalizationState::Working
        && current.project_id == expected.project_id
        && current.codex_session_id == expected.codex_session_id
        && current.generation == expected.generation
        && current.task_identity == expected.task_identity
        && current.owner_run_token == expected.owner_run_token
        && current.git_mode == expected.git_mode
        && current.starting_head == expected.starting_head
        && current.branch_ref == expected.branch_ref
        && current.upstream_ref == expected.upstream_ref
        && current.worktree_baseline == expected.worktree_baseline
        && current.commit_oid == expected.commit_oid
        && current.created_at == expected.created_at
}

pub(super) fn cancel_orphaned_working_git_finalization(
    store: &agent::TursoAgentStore,
    project_root: &Path,
    expected: &agent::GitFinalizationRecord,
    lease: &AgentGitFinalizationLease,
) -> Result<bool> {
    cancel_orphaned_working_git_finalization_with_before_lock(
        store,
        project_root,
        expected,
        lease,
        || {},
    )
}

pub(super) fn cancel_orphaned_working_git_finalization_with_before_lock(
    store: &agent::TursoAgentStore,
    project_root: &Path,
    expected: &agent::GitFinalizationRecord,
    lease: &AgentGitFinalizationLease,
    before_lock: impl FnOnce(),
) -> Result<bool> {
    if expected.state != GitFinalizationState::Working
        || expected.task_identity.is_some()
        || expected.commit_oid.is_some()
        || expected.owner_run_token.is_some()
    {
        return Ok(false);
    }
    // Validate the baseline, and reject every non-null sealed field even if its
    // type is malformed. Retirement must never discard saved commit proof.
    if AgentGitWorktreeBaseline::from_json(&expected.worktree_baseline).is_err() {
        return Ok(false);
    }
    let baseline: serde_json::Value = serde_json::from_str(&expected.worktree_baseline)?;
    if [
        "staged_non_task_patch_ids",
        "staged_index_tree",
        "manifest_parent_head",
    ]
    .iter()
    .any(|field| baseline.get(field).is_some_and(|value| !value.is_null()))
    {
        return Ok(false);
    }
    anyhow::ensure!(
        lease.project_id() == expected.project_id,
        "Orphan journal recovery requires the matching project lease"
    );
    let registered_root = store
        .list_projects_blocking()?
        .into_iter()
        .find(|project| project.id == expected.project_id)
        .context("Orphan journal project is no longer registered")?
        .path;
    // Registered paths may retain aliases such as macOS /var -> /private/var.
    anyhow::ensure!(
        fs::canonicalize(project_root)? == fs::canonicalize(&registered_root)?,
        "Orphan journal recovery requires the registered project directory"
    );
    lease.ensure_owned()?;
    before_lock();
    let board_dir = get_tasks_dir(project_root);
    let _mutation_lock = acquire_board_mutation_lock(&board_dir)?;
    if task_tree_contains_session_marker(&board_dir, &expected.codex_session_id)? {
        return Ok(false);
    }
    lease.ensure_owned()?;
    store.cancel_orphaned_working_git_finalization_blocking(
        expected,
        &lease.holder,
        "Abandoned unbound Git journal: no task identity or board marker remains",
        &agent_timestamp(),
    )
}

/// Retire unbound journals whose owning run already ended and whose session no
/// longer has any board marker. A run that stops before claiming a task leaves
/// exactly this shape behind; its recorded owner token belongs to a finished
/// run, so the ordinary owner-fenced retirement can never match it again and
/// the project would otherwise stay wedged forever.
pub(super) fn retire_abandoned_unbound_git_journals(
    state_dir: &Path,
    project: &agent::AgentProject,
) -> Result<usize> {
    let candidates = with_agent_store_at(state_dir, |store| {
        Ok(store
            .list_pending_git_finalizations_blocking(Some(project.id))?
            .into_iter()
            .filter(|journal| {
                journal.state == GitFinalizationState::Working
                    && journal.task_identity.is_none()
                    && journal.commit_oid.is_none()
            })
            .collect::<Vec<_>>())
    })?;
    if candidates.is_empty() {
        return Ok(0);
    }
    let board_dir = get_tasks_dir(&project.path);
    let _mutation_lock = acquire_board_mutation_lock(&board_dir)?;
    let mut retired = 0;
    for journal in candidates {
        if task_tree_contains_session_marker(&board_dir, &journal.codex_session_id)? {
            continue;
        }
        let done = with_agent_store_at(state_dir, |store| {
            store.retire_abandoned_unbound_git_finalization_blocking(
                project.id,
                &journal.codex_session_id,
                journal.generation,
                AGENT_ABANDONED_UNBOUND_JOURNAL_REASON,
                &agent_timestamp(),
            )
        })?;
        if done {
            retired += 1;
        }
    }
    Ok(retired)
}

/// Retire only unbound orphan journals; this does not finalize or publish work.
pub(super) fn reconcile_orphaned_agent_git_journals(
    state_dir: &Path,
    project: &agent::AgentProject,
) -> Result<usize> {
    let retired = retire_abandoned_unbound_git_journals(state_dir, project)?;
    let pending = with_agent_store_at(state_dir, |store| {
        store.list_pending_git_finalizations_blocking(Some(project.id))
    })?;
    if pending.is_empty() {
        return Ok(retired);
    }
    let lease = try_acquire_agent_git_finalization_lease(state_dir, project, false)?
        .context("Project is still owned by an agent or interactive session; retry reconciliation after it stops")?;
    let result: Result<usize> = (|| {
        let store = open_agent_store_at(state_dir)?;
        let mut retired = 0;
        for journal in store.list_pending_git_finalizations_blocking(Some(project.id))? {
            if cancel_orphaned_working_git_finalization(&store, &project.path, &journal, &lease)? {
                retired += 1;
            }
        }
        Ok(retired)
    })();
    let released = lease.release();
    let retired_orphans = result?;
    released?;
    Ok(retired + retired_orphans)
}

/// Retire a journal this run owns once the run has proven it never claimed a
/// task. The board lock inside the cancellation keeps this race-free with any
/// concurrent Done move, and a live owner token still keeps its journal.
pub(super) fn retire_unlinked_working_git_finalization_after_run(
    job: &AgentRunJob,
    finalization: &agent::GitFinalizationRecord,
    session_run_token: Option<&str>,
) -> Result<bool> {
    let Some(owner_run_token) = session_run_token
        .filter(|run_token| finalization.owner_run_token.as_deref() == Some(*run_token))
    else {
        return Ok(false);
    };
    with_agent_store_at(&job.state_dir, |store| {
        cancel_unlinked_working_git_finalization(
            store,
            &job.project.path,
            finalization,
            owner_run_token,
        )
    })
}

pub(super) fn cancel_unlinked_working_git_finalization(
    store: &agent::TursoAgentStore,
    project_root: &Path,
    finalization: &agent::GitFinalizationRecord,
    owner_run_token: &str,
) -> Result<bool> {
    cancel_unlinked_working_git_finalization_with_before_lock(
        store,
        project_root,
        finalization,
        owner_run_token,
        || {},
    )
}

pub(super) fn cancel_unlinked_working_git_finalization_with_before_lock(
    store: &agent::TursoAgentStore,
    project_root: &Path,
    finalization: &agent::GitFinalizationRecord,
    owner_run_token: &str,
    before_lock: impl FnOnce(),
) -> Result<bool> {
    cancel_unlinked_working_git_finalization_with_lock_callbacks(
        store,
        project_root,
        finalization,
        owner_run_token,
        before_lock,
        || {},
        || {},
    )
}

pub(super) fn cancel_unlinked_working_git_finalization_with_lock_callbacks(
    store: &agent::TursoAgentStore,
    project_root: &Path,
    finalization: &agent::GitFinalizationRecord,
    owner_run_token: &str,
    before_lock: impl FnOnce(),
    after_validation: impl FnOnce(),
    on_contention: impl FnOnce(),
) -> Result<bool> {
    before_lock();
    let board_dir = get_tasks_dir(project_root);
    let _mutation_lock =
        acquire_board_mutation_lock_with_contention_callback(&board_dir, on_contention)?;
    if TaskBoard::new(&board_dir)
        .terminal_task_for_session(&finalization.codex_session_id)?
        .is_some()
    {
        return Ok(false);
    }
    let Some(current) =
        store.git_finalization_blocking(finalization.project_id, &finalization.codex_session_id)?
    else {
        return Ok(false);
    };
    if !exact_working_git_finalization_snapshot(&current, finalization)
        || current.owner_run_token.as_deref() != Some(owner_run_token)
    {
        return Ok(false);
    }
    after_validation();
    store.compare_and_set_owned_git_finalization_blocking(
        current.project_id,
        &current.codex_session_id,
        current.generation,
        GitFinalizationState::Cancelled,
        owner_run_token,
        None,
        None,
        &agent_timestamp(),
    )
}

pub(super) fn repair_working_git_task_link_with_before_lock(
    store: &agent::TursoAgentStore,
    project_root: &Path,
    finalization: &agent::GitFinalizationRecord,
    before_lock: impl FnOnce(),
) -> Result<bool> {
    repair_working_git_task_link_with_lock_callbacks(
        store,
        project_root,
        finalization,
        before_lock,
        || {},
        || {},
    )
}

pub(super) fn repair_working_git_task_link_with_lock_callbacks(
    store: &agent::TursoAgentStore,
    project_root: &Path,
    finalization: &agent::GitFinalizationRecord,
    before_lock: impl FnOnce(),
    after_validation: impl FnOnce(),
    on_contention: impl FnOnce(),
) -> Result<bool> {
    let Some(task_identity) = finalization.task_identity.as_deref() else {
        return Ok(false);
    };
    let Some(starting_head) = finalization.starting_head.as_deref() else {
        return Ok(false);
    };
    if !working_git_history_is_safe(store, project_root, finalization, starting_head)? {
        return Ok(false);
    }
    before_lock();
    let board_dir = get_tasks_dir(project_root);
    let _mutation_lock =
        acquire_board_mutation_lock_with_contention_callback(&board_dir, on_contention)?;
    let Some(current) =
        store.git_finalization_blocking(finalization.project_id, &finalization.codex_session_id)?
    else {
        return Ok(false);
    };
    if !exact_working_git_finalization_snapshot(&current, finalization)
        || !working_git_history_is_safe(store, project_root, &current, starting_head)?
    {
        return Ok(false);
    }
    after_validation();
    cleanup_clt_atomic_task_temporaries(&board_dir)?;
    let mut linked = Vec::new();
    for status in [TaskStatus::Todo, TaskStatus::Doing] {
        for (index, entry) in read_task_entries(&board_dir, status)?
            .into_iter()
            .enumerate()
        {
            if codex_session_id_from_task_content(&entry.content)
                == Some(finalization.codex_session_id.as_str())
                && durable_task_identity(&entry.content).as_deref() == Some(task_identity)
            {
                linked.push((status, index + 1, entry));
            }
        }
    }
    match linked.as_slice() {
        [(TaskStatus::Doing, _, _)] => return Ok(true),
        [(TaskStatus::Todo, index, _)] => {
            move_task_without_reordering_after_lock(
                &board_dir,
                TaskStatus::Todo,
                TaskStatus::Doing,
                *index,
            )?;
            return Ok(true);
        }
        [(first_status, _, first), (second_status, _, second)]
            if [*first_status, *second_status].contains(&TaskStatus::Todo)
                && [*first_status, *second_status].contains(&TaskStatus::Doing)
                && first.content.trim_end() == second.content.trim_end()
                && [first, second].iter().all(|entry| {
                    matches!(
                        entry.source,
                        TaskSource::MarkdownLine { .. } | TaskSource::Path { is_dir: false, .. }
                    )
                }) =>
        {
            let (_, _, todo_duplicate) = linked
                .iter()
                .find(|(status, _, _)| *status == TaskStatus::Todo)
                .expect("one linked crash duplicate is in Todo");
            TaskBoard::new(&board_dir)
                .remove_entry_without_reordering(TaskStatus::Todo, todo_duplicate)?;
            return Ok(true);
        }
        [] => {}
        _ => return Ok(false),
    }
    let mut matches = Vec::new();
    for status in [TaskStatus::Todo, TaskStatus::Doing] {
        for (index, entry) in read_task_entries(&board_dir, status)?
            .into_iter()
            .enumerate()
        {
            if durable_task_identity(&entry.content).as_deref() == Some(task_identity) {
                matches.push((status, index + 1, entry));
            }
        }
    }
    let [(status, index, entry)] = matches.as_slice() else {
        return Ok(false);
    };
    attach_codex_session_to_task_after_lock(
        project_root,
        *status,
        entry,
        &finalization.codex_session_id,
        || {},
    )?;
    if *status == TaskStatus::Todo {
        move_task_without_reordering_after_lock(
            &board_dir,
            TaskStatus::Todo,
            TaskStatus::Doing,
            *index,
        )?;
    }
    Ok(true)
}

pub(super) fn working_git_history_is_safe(
    store: &agent::TursoAgentStore,
    project_root: &Path,
    finalization: &agent::GitFinalizationRecord,
    starting_head: &str,
) -> Result<bool> {
    let current_branch = git_optional_stdout(
        project_root,
        &["symbolic-ref", "-q", "HEAD"],
        &[1],
        "verify the Working task repair branch",
    )?;
    if current_branch.as_deref() != finalization.branch_ref.as_deref() {
        return Ok(false);
    }
    let current_head = resolve_git_commit(
        project_root,
        "HEAD",
        "verify the Working task repair history",
    )?;
    if !git_commit_is_ancestor(project_root, starting_head, &current_head)?
        || !agent_git_range_is_safe_before_manifest(
            AgentGitProofContext {
                store,
                project_id: finalization.project_id,
            },
            project_root,
            starting_head,
            &current_head,
            &finalization.codex_session_id,
        )?
    {
        return Ok(false);
    }
    Ok(true)
}

pub(super) fn configure_agent_git_identity(command: &mut Command, git_mode: AgentGitMode) {
    if git_mode == AgentGitMode::Off {
        return;
    }

    command
        .env("GIT_AUTHOR_NAME", AGENT_GIT_IDENTITY_NAME)
        .env("GIT_AUTHOR_EMAIL", AGENT_GIT_IDENTITY_EMAIL)
        .env("GIT_COMMITTER_NAME", AGENT_GIT_IDENTITY_NAME)
        .env("GIT_COMMITTER_EMAIL", AGENT_GIT_IDENTITY_EMAIL);
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) struct AgentGitStartState {
    pub(super) starting_head: String,
    pub(super) branch_ref: Option<String>,
    pub(super) upstream_ref: Option<String>,
    pub(super) worktree_baseline: String,
}

#[derive(Clone, Copy)]
pub(super) struct AgentGitProofContext<'a> {
    pub(super) store: &'a agent::TursoAgentStore,
    pub(super) project_id: i64,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) struct AgentGitUpstreamDestination {
    remote: String,
    merge_ref: String,
    push_url: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) struct AgentGitWorktreeBaseline {
    version: u64,
    tracked_patch_ids: BTreeMap<String, String>,
    untracked_blob_ids: BTreeMap<String, String>,
    require_clean: bool,
    initial_index_tree: Option<String>,
    staged_non_task_patch_ids: Option<BTreeMap<String, String>>,
    staged_index_tree: Option<String>,
    manifest_parent_head: Option<String>,
    upstream_remote: Option<String>,
    upstream_merge_ref: Option<String>,
    upstream_push_url: Option<String>,
}

impl Default for AgentGitWorktreeBaseline {
    fn default() -> Self {
        Self {
            version: 2,
            tracked_patch_ids: BTreeMap::new(),
            untracked_blob_ids: BTreeMap::new(),
            require_clean: false,
            initial_index_tree: None,
            staged_non_task_patch_ids: None,
            staged_index_tree: None,
            manifest_parent_head: None,
            upstream_remote: None,
            upstream_merge_ref: None,
            upstream_push_url: None,
        }
    }
}

impl AgentGitWorktreeBaseline {
    fn to_json(&self) -> Result<String> {
        serde_json::to_string(&serde_json::json!({
            "version": self.version,
            "tracked_patch_ids": self.tracked_patch_ids,
            "untracked_blob_ids": self.untracked_blob_ids,
            "require_clean": self.require_clean,
            "initial_index_tree": self.initial_index_tree,
            "staged_non_task_patch_ids": self.staged_non_task_patch_ids,
            "staged_index_tree": self.staged_index_tree,
            "manifest_parent_head": self.manifest_parent_head,
            "upstream_remote": self.upstream_remote,
            "upstream_merge_ref": self.upstream_merge_ref,
            "upstream_push_url": self.upstream_push_url,
        }))
        .context("Failed to serialize the automated Git worktree baseline")
    }

    pub(super) fn from_json(raw: &str) -> Result<Self> {
        let value: serde_json::Value = serde_json::from_str(raw)
            .context("Failed to parse the automated Git worktree baseline")?;
        let version = value.get("version").and_then(serde_json::Value::as_u64);
        if !matches!(version, Some(1 | 2)) {
            anyhow::bail!("Unsupported automated Git worktree baseline version");
        }
        let parse_map = |field: &str| -> Result<BTreeMap<String, String>> {
            let object = value
                .get(field)
                .and_then(serde_json::Value::as_object)
                .with_context(|| format!("Git worktree baseline is missing {field}"))?;
            object
                .iter()
                .map(|(path, value)| {
                    value
                        .as_str()
                        .map(|value| (path.clone(), value.to_string()))
                        .with_context(|| {
                            format!("Git worktree baseline entry {field}.{path} is not text")
                        })
                })
                .collect()
        };
        Ok(Self {
            version: version.expect("supported baseline version"),
            tracked_patch_ids: parse_map("tracked_patch_ids")?,
            untracked_blob_ids: parse_map("untracked_blob_ids")?,
            require_clean: value
                .get("require_clean")
                .and_then(serde_json::Value::as_bool)
                .unwrap_or(false),
            initial_index_tree: value
                .get("initial_index_tree")
                .filter(|value| !value.is_null())
                .map(|value| {
                    value.as_str().map(str::to_string)
                        .context("Git worktree baseline initial_index_tree is not text")
                })
                .transpose()?,
            staged_non_task_patch_ids: value
                .get("staged_non_task_patch_ids")
                .and_then(serde_json::Value::as_object)
                .map(|object| {
                    object
                        .iter()
                        .map(|(path, value)| {
                            value
                                .as_str()
                                .map(|value| (path.clone(), value.to_string()))
                                .with_context(|| {
                                    format!(
                                        "Git worktree baseline entry staged_non_task_patch_ids.{path} is not text"
                                    )
                                })
                        })
                        .collect::<Result<BTreeMap<_, _>>>()
                })
                .transpose()?,
            staged_index_tree: value
                .get("staged_index_tree")
                .and_then(serde_json::Value::as_str)
                .map(str::to_string),
            manifest_parent_head: value
                .get("manifest_parent_head")
                .and_then(serde_json::Value::as_str)
                .map(str::to_string),
            upstream_remote: value
                .get("upstream_remote")
                .and_then(serde_json::Value::as_str)
                .map(str::to_string),
            upstream_merge_ref: value
                .get("upstream_merge_ref")
                .and_then(serde_json::Value::as_str)
                .map(str::to_string),
            upstream_push_url: value
                .get("upstream_push_url")
                .and_then(serde_json::Value::as_str)
                .map(str::to_string),
        })
    }
}

pub(super) fn ensure_agent_git_index_preflight(
    project: &agent::AgentProject,
    resuming_known_session: bool,
) -> Result<()> {
    if project.git_mode == AgentGitMode::Off || resuming_known_session {
        return Ok(());
    }

    // Staged work is a launch baseline, not a reason to reject the project.
    // write-tree still reports real index problems such as unresolved merges.
    agent_git_index_tree(&project.path)?;
    Ok(())
}

pub(super) fn prepare_agent_git_start_state_for_run(
    store: &agent::TursoAgentStore,
    project: &agent::AgentProject,
    task_selection: AgentTaskSelection,
    has_known_session: bool,
    has_existing_session_finalization: bool,
    run_token: &str,
) -> Result<Option<AgentGitStartState>> {
    if project.git_mode == AgentGitMode::Off {
        return Ok(None);
    }
    if has_known_session && !has_existing_session_finalization {
        anyhow::bail!(
            "Known Codex session has no frozen Git start journal; CLT will not reconstruct the task boundary from a later checkout"
        );
    }
    if has_existing_session_finalization {
        return Ok(None);
    }
    if task_selection != AgentTaskSelection::NextTodo {
        anyhow::bail!(
            "Git-enabled task recovery has no frozen start journal; only a fresh NextTodo run may establish a new task boundary"
        );
    }
    if store.has_other_git_launch_state_blocking(project.id, run_token)? {
        let (prior_run_token, prior_mode, prior_start) = store
            .git_launch_state_for_project_blocking(project.id)?
            .context("The prior Git launch boundary disappeared during recovery")?;
        let checkout_is_unchanged = prior_mode == project.git_mode
            && verify_agent_git_start_state_unchanged(&project.path, prior_mode, &prior_start)
                .is_ok();
        let reclaimed = checkout_is_unchanged
            && store.reclaim_unchanged_git_launch_state_blocking(
                project.id,
                &prior_run_token,
                prior_mode,
                &prior_start,
            )?;
        if !reclaimed {
            anyhow::bail!(
                "An earlier released Git-enabled run has an unconsumed launch boundary; its exact worker is not proven dead or the checkout changed, so CLT will not overwrite it or start another task"
            );
        }
    }
    if store
        .git_launch_state_blocking(project.id, run_token)?
        .is_some()
    {
        anyhow::bail!(
            "Automated run {run_token} already has an unconsumed Git launch boundary; CLT will not recapture it from a later checkout"
        );
    }
    let project_has_working_boundary = store
        .list_pending_git_finalizations_blocking(Some(project.id))?
        .into_iter()
        .any(|finalization| finalization.state == GitFinalizationState::Working);
    if task_selection == AgentTaskSelection::NextTodo && !project_has_working_boundary {
        synchronize_agent_git_checkout_before_launch(&project.path)?;
    }
    {
        let board_dir = get_tasks_dir(&project.path);
        let _mutation_lock = acquire_board_mutation_lock(&board_dir)?;
        cleanup_clt_atomic_task_temporaries(&board_dir)?;
        require_agent_git_board_storage_compatible(&project.path)?;
        checkpoint_agent_git_task_board_before_launch(&project.path)?;
    }
    let start = capture_agent_git_start_state(&project.path, project.git_mode)?;
    require_agent_git_todo_candidates_committed(&project.path, &start.starting_head)?;
    Ok(Some(start))
}

pub(super) fn checkpoint_agent_git_task_board_before_launch(
    project_root: &Path,
) -> Result<Option<String>> {
    let starting_index_tree = agent_git_index_tree(project_root)?;
    let starting_head = resolve_git_commit(
        project_root,
        "HEAD",
        "resolve the parent for the automated task-board checkpoint",
    )?;
    let branch_ref = git_optional_stdout(
        project_root,
        &["symbolic-ref", "-q", "HEAD"],
        &[1],
        "resolve the branch for the automated task-board checkpoint",
    )?
    .context("Git-enabled automated tasks require an attached branch before CLT checkpoints the task board")?;
    let starting_tree = git_stdout(
        project_root,
        &[
            "rev-parse",
            "--verify",
            &format!("{starting_head}^{{tree}}"),
        ],
        "resolve the tree before the automated task-board checkpoint",
    )?;
    let (_projection, index_path, _) =
        create_agent_git_tree_projection(project_root, &starting_head)?;
    run_agent_git_projection_command(
        project_root,
        &index_path,
        None,
        &["add", "-A", "--", "tasks"],
        "stage the prelaunch task-board checkpoint",
    )?;
    let checkpoint_tree = run_agent_git_projection_command(
        project_root,
        &index_path,
        None,
        &["write-tree"],
        "snapshot the prelaunch task board",
    )?;
    if checkpoint_tree == starting_tree {
        return Ok(None);
    }

    require_agent_git_index_tree(project_root, &starting_index_tree)?;
    let rechecked_head = resolve_git_commit(
        project_root,
        "HEAD",
        "recheck the task-board checkpoint parent",
    )?;
    let rechecked_branch = git_optional_stdout(
        project_root,
        &["symbolic-ref", "-q", "HEAD"],
        &[1],
        "recheck the task-board checkpoint branch",
    )?;
    run_agent_git_projection_command(
        project_root,
        &index_path,
        None,
        &["add", "-A", "--", "tasks"],
        "recheck the prelaunch task-board checkpoint",
    )?;
    let rechecked_tree = run_agent_git_projection_command(
        project_root,
        &index_path,
        None,
        &["write-tree"],
        "recheck the prelaunch task-board tree",
    )?;
    if rechecked_head != starting_head
        || rechecked_branch.as_deref() != Some(branch_ref.as_str())
        || rechecked_tree != checkpoint_tree
    {
        anyhow::bail!(
            "Git HEAD, branch, index, or task board changed while CLT was preparing its prelaunch checkpoint; retry"
        );
    }

    let output = Command::new("git")
        .current_dir(project_root)
        .env("GIT_AUTHOR_NAME", AGENT_GIT_IDENTITY_NAME)
        .env("GIT_AUTHOR_EMAIL", AGENT_GIT_IDENTITY_EMAIL)
        .env("GIT_COMMITTER_NAME", AGENT_GIT_IDENTITY_NAME)
        .env("GIT_COMMITTER_EMAIL", AGENT_GIT_IDENTITY_EMAIL)
        .args([
            "commit-tree",
            checkpoint_tree.as_str(),
            "-p",
            starting_head.as_str(),
            "-m",
            AGENT_GIT_BOARD_CHECKPOINT_MESSAGE,
        ])
        .output()
        .with_context(|| {
            format!(
                "Failed to create the automated task-board checkpoint in {}",
                project_root.display()
            )
        })?;
    if !output.status.success() {
        anyhow::bail!(
            "Failed to create the automated task-board checkpoint in {}: {}",
            project_root.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    let checkpoint_commit = String::from_utf8(output.stdout)
        .context("Git returned a non-UTF-8 task-board checkpoint commit")?
        .trim()
        .to_string();

    require_agent_git_index_tree(project_root, &starting_index_tree)?;
    if resolve_git_commit(
        project_root,
        "HEAD",
        "recheck the task-board checkpoint parent",
    )? != starting_head
        || git_optional_stdout(
            project_root,
            &["symbolic-ref", "-q", "HEAD"],
            &[1],
            "recheck the task-board checkpoint branch",
        )?
        .as_deref()
            != Some(branch_ref.as_str())
    {
        anyhow::bail!(
            "Git HEAD, branch, or index changed before CLT could publish its task-board checkpoint; retry"
        );
    }
    // Align only board paths that were not already staged. A partially staged
    // board file can contain work absent from both HEAD and the worktree.
    let staged_board_paths = git_nul_separated_paths(
        project_root,
        &[
            "diff",
            "--name-only",
            "--no-renames",
            "-z",
            &starting_head,
            &starting_index_tree,
            "--",
            "tasks",
        ],
        "identify pre-existing staged task-board paths",
    )?;
    let checkpoint_paths = git_nul_separated_paths(
        project_root,
        &[
            "diff",
            "--name-only",
            "--no-renames",
            "-z",
            &starting_head,
            &checkpoint_commit,
            "--",
            "tasks",
        ],
        "identify checkpoint task-board paths",
    )?;
    let align_paths = checkpoint_paths
        .iter()
        .filter(|path| !staged_board_paths.contains(path))
        .map(String::as_str)
        .collect::<Vec<_>>();
    let mut align_args = vec![
        "--literal-pathspecs",
        "reset",
        "--quiet",
        checkpoint_commit.as_str(),
        "--",
    ];
    align_args.extend(align_paths.iter().copied());
    let (_index_projection, preserved_index, _) =
        create_agent_git_tree_projection(project_root, &starting_index_tree)?;
    if !align_paths.is_empty() {
        run_agent_git_projection_command(
            project_root,
            &preserved_index,
            None,
            &align_args,
            "project the task-board checkpoint into the existing index",
        )?;
    }
    let expected_index_tree = run_agent_git_projection_command(
        project_root,
        &preserved_index,
        None,
        &["write-tree"],
        "snapshot the preserved prelaunch index",
    )?;
    require_agent_git_index_tree(project_root, &starting_index_tree)?;
    git_stdout(
        project_root,
        &[
            "update-ref",
            branch_ref.as_str(),
            checkpoint_commit.as_str(),
            starting_head.as_str(),
        ],
        "publish the automated task-board checkpoint",
    )?;
    if !align_paths.is_empty() {
        git_stdout(
            project_root,
            &align_args,
            "align unstaged task-board paths with their automated checkpoint",
        )?;
    }
    require_agent_git_index_tree(project_root, &expected_index_tree)?;
    run_agent_git_projection_command(
        project_root,
        &index_path,
        None,
        &["add", "-A", "--", "tasks"],
        "verify the checkpointed task-board worktree",
    )?;
    if run_agent_git_projection_command(
        project_root,
        &index_path,
        None,
        &["write-tree"],
        "verify the checkpointed task-board tree",
    )? != checkpoint_tree
    {
        anyhow::bail!(
            "The task board changed while CLT was publishing its prelaunch checkpoint; retry"
        );
    }

    Ok(Some(checkpoint_commit))
}

pub(super) fn require_agent_git_todo_candidates_committed(
    project_root: &Path,
    starting_head: &str,
) -> Result<()> {
    let candidates = read_task_entries(&get_tasks_dir(project_root), TaskStatus::Todo)?
        .into_iter()
        .filter(task_entry_is_ready)
        .collect::<Vec<_>>();
    if candidates.is_empty() {
        anyhow::bail!("Fresh Git-enabled automation has no unblocked Todo task to start");
    }
    for candidate in candidates {
        let task_identity = durable_task_identity(&candidate.content)
            .context("A Todo candidate has no durable task identity")?;
        require_agent_git_start_task_identity(project_root, starting_head, &task_identity)
            .with_context(|| {
                format!(
                    "Todo candidate {:?} is not committed exactly once at the frozen task boundary",
                    candidate.summary
                )
            })?;
    }
    Ok(())
}

pub(super) fn require_agent_git_board_storage_compatible(project_root: &Path) -> Result<()> {
    let board_dir = get_tasks_dir(project_root);
    let todo_is_directory = matches!(
        get_status_store(&board_dir, TaskStatus::Todo)?,
        StatusStore::Directory(_)
    );
    let doing_is_directory = matches!(
        get_status_store(&board_dir, TaskStatus::Doing)?,
        StatusStore::Directory(_)
    );
    let done_is_directory = matches!(
        get_status_store(&board_dir, TaskStatus::Done)?,
        StatusStore::Directory(_)
    );
    if todo_is_directory && !doing_is_directory {
        anyhow::bail!(
            "Git-enabled automation requires folder-backed Doing storage when Todo is folder-backed; expand and commit the board layout before scheduling"
        );
    }
    if doing_is_directory && !done_is_directory {
        anyhow::bail!(
            "Git-enabled automation requires folder-backed Done storage when Doing is folder-backed; expand and commit the board layout before scheduling"
        );
    }
    Ok(())
}

pub(super) fn synchronize_agent_git_checkout_before_launch(project_root: &Path) -> Result<()> {
    if !git_stdout(
        project_root,
        &["status", "--porcelain", "--untracked-files=all"],
        "inspect the checkout before automated startup synchronization",
    )?
    .is_empty()
    {
        // Do not pull, stash, or unstage shared work just to start an agent.
        return Ok(());
    }
    let branch_ref = git_optional_stdout(
        project_root,
        &["symbolic-ref", "-q", "HEAD"],
        &[1],
        "resolve the branch for automated startup synchronization",
    )?;
    let Some(branch_ref) = branch_ref else {
        return Ok(());
    };
    let upstream_ref = resolve_agent_git_upstream(project_root, Some(&branch_ref))?;
    let Some(upstream_ref) = upstream_ref else {
        return Ok(());
    };
    let starting_head = resolve_git_commit(
        project_root,
        "HEAD",
        "resolve the commit before automated startup synchronization",
    )?;
    let mut command = Command::new("git");
    command
        .current_dir(project_root)
        .env("GIT_TERMINAL_PROMPT", "0")
        .args(["pull", "--ff-only", "--no-rebase"]);
    let output = run_agent_git_remote_command(
        &mut command,
        &format!("fast-forward the automated checkout from {upstream_ref}"),
    )?;
    if !output.status.success() {
        anyhow::bail!(
            "Failed to fast-forward the automated checkout from {upstream_ref}: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    require_agent_git_index_matches_head(project_root)?;
    let current_branch = git_optional_stdout(
        project_root,
        &["symbolic-ref", "-q", "HEAD"],
        &[1],
        "recheck the branch after automated startup synchronization",
    )?;
    let current_upstream = resolve_agent_git_upstream(project_root, current_branch.as_deref())?;
    let current_head = resolve_git_commit(
        project_root,
        "HEAD",
        "recheck the commit after automated startup synchronization",
    )?;
    if current_branch.as_deref() != Some(branch_ref.as_str())
        || current_upstream.as_deref() != Some(upstream_ref.as_str())
        || !git_commit_is_ancestor(project_root, &starting_head, &current_head)?
    {
        anyhow::bail!(
            "Git branch, upstream, or history changed incompatibly during automated startup synchronization"
        );
    }
    Ok(())
}

pub(super) fn git_nul_separated_paths(
    project_root: &Path,
    args: &[&str],
    operation: &str,
) -> Result<Vec<String>> {
    let output = Command::new("git")
        .current_dir(project_root)
        .args(args)
        .output()
        .with_context(|| format!("Failed to {operation} in {}", project_root.display()))?;
    if !output.status.success() {
        anyhow::bail!(
            "Failed to {operation} in {}: {}",
            project_root.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    output
        .stdout
        .split(|byte| *byte == 0)
        .filter(|path| !path.is_empty())
        .map(|path| {
            std::str::from_utf8(path)
                .with_context(|| {
                    format!("Git returned a non-UTF-8 path while trying to {operation}")
                })
                .map(str::to_string)
        })
        .collect()
}

#[cfg(test)]
mod tests;

pub(super) fn git_hash_stdin(project_root: &Path, bytes: &[u8], operation: &str) -> Result<String> {
    let mut child = Command::new("git")
        .current_dir(project_root)
        .args(["hash-object", "--stdin"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .with_context(|| format!("Failed to start Git while trying to {operation}"))?;
    child
        .stdin
        .take()
        .context("git hash-object did not expose stdin")?
        .write_all(bytes)
        .with_context(|| format!("Failed to send content to Git while trying to {operation}"))?;
    let output = child
        .wait_with_output()
        .with_context(|| format!("Failed to finish Git while trying to {operation}"))?;
    if !output.status.success() {
        anyhow::bail!(
            "Failed to {operation}: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    String::from_utf8(output.stdout)
        .with_context(|| format!("Git returned non-UTF-8 output while trying to {operation}"))
        .map(|value| value.trim().to_string())
}

pub(super) fn git_delta_id_for_path(
    project_root: &Path,
    diff_arguments: &[&str],
    path: &str,
) -> Result<String> {
    let diff = Command::new("git")
        .current_dir(project_root)
        .arg("diff")
        .args(diff_arguments)
        .args([
            "--no-ext-diff",
            "--binary",
            "--full-index",
            "--unified=0",
            "--",
            path,
        ])
        .output()
        .with_context(|| {
            format!(
                "Failed to read the Git delta for {path} in {}",
                project_root.display()
            )
        })?;
    if !diff.status.success() {
        anyhow::bail!(
            "Failed to read the Git delta for {path} in {}: {}",
            project_root.display(),
            String::from_utf8_lossy(&diff.stderr).trim()
        );
    }
    if diff.stdout.is_empty() {
        anyhow::bail!("Git state changed while CLT was capturing the delta for {path}");
    }

    let mut canonical = Vec::new();
    let mut in_binary_patch = false;
    let mut in_hunk = false;
    for line in diff.stdout.split_inclusive(|byte| *byte == b'\n') {
        if line.starts_with(b"GIT binary patch") {
            in_binary_patch = true;
        }
        if line.starts_with(b"@@") {
            in_hunk = true;
            continue;
        }
        if in_binary_patch
            || line.starts_with(b"+")
            || line.starts_with(b"-")
            || line.starts_with(b"old mode ")
            || line.starts_with(b"new mode ")
            || line.starts_with(b"new file mode ")
            || line.starts_with(b"deleted file mode ")
            || line.starts_with(b"rename from ")
            || line.starts_with(b"rename to ")
            || line.starts_with(b"copy from ")
            || line.starts_with(b"copy to ")
            || line.starts_with(b"\\ No newline at end of file")
        {
            if !in_hunk && (line.starts_with(b"--- ") || line.starts_with(b"+++ ")) {
                continue;
            }
            canonical.extend_from_slice(line);
        }
    }
    if canonical.is_empty() {
        anyhow::bail!("Git produced no canonical delta for {path}");
    }
    git_hash_stdin(
        project_root,
        &canonical,
        &format!("fingerprint the exact Git delta for {path}"),
    )
}

pub(super) fn git_worktree_delta_id_for_path(project_root: &Path, path: &str) -> Result<String> {
    git_delta_id_for_path(project_root, &[], path)
}

pub(super) fn git_untracked_blob_id(project_root: &Path, path: &str) -> Result<String> {
    git_stdout(
        project_root,
        &["hash-object", "--no-filters", "--", path],
        "fingerprint an untracked worktree file",
    )
}

pub(super) fn capture_agent_git_worktree_baseline(
    project_root: &Path,
) -> Result<AgentGitWorktreeBaseline> {
    capture_agent_git_worktree_state(project_root)
}

fn agent_git_index_tree(project_root: &Path) -> Result<String> {
    git_stdout(project_root, &["write-tree"], "snapshot the Git index")
}

fn require_agent_git_index_tree(project_root: &Path, expected_tree: &str) -> Result<()> {
    anyhow::ensure!(
        agent_git_index_tree(project_root)? == expected_tree,
        "Git index changed while CLT was preparing the automated task; retry"
    );
    Ok(())
}

pub(super) fn require_agent_git_index_matches_head(project_root: &Path) -> Result<()> {
    let cached = Command::new("git")
        .current_dir(project_root)
        .args(["diff", "--cached", "--quiet", "--exit-code", "--"])
        .output()
        .with_context(|| {
            format!(
                "Failed to verify the staged Git index in {}",
                project_root.display()
            )
        })?;
    match cached.status.code() {
        Some(0) => Ok(()),
        Some(1) => {
            anyhow::bail!("Automated Git finalization requires the staged index to match HEAD")
        }
        _ => anyhow::bail!(
            "Failed to verify the staged Git index in {}: {}",
            project_root.display(),
            String::from_utf8_lossy(&cached.stderr).trim()
        ),
    }
}

pub(super) fn capture_agent_git_worktree_state(
    project_root: &Path,
) -> Result<AgentGitWorktreeBaseline> {
    let tracked_paths = git_nul_separated_paths(
        project_root,
        &["diff", "--name-only", "-z", "--"],
        "list modified tracked files",
    )?;
    let untracked_paths = git_nul_separated_paths(
        project_root,
        &["ls-files", "--others", "--exclude-standard", "-z", "--"],
        "list untracked files",
    )?;
    let mut baseline = AgentGitWorktreeBaseline::default();
    for path in tracked_paths {
        baseline.tracked_patch_ids.insert(
            path.clone(),
            git_worktree_delta_id_for_path(project_root, &path)?,
        );
    }
    for path in untracked_paths {
        baseline
            .untracked_blob_ids
            .insert(path.clone(), git_untracked_blob_id(project_root, &path)?);
    }
    Ok(baseline)
}

pub(super) fn git_ref_has_one_active_session_task(
    project_root: &Path,
    reference: &str,
    session_id: &str,
    task_identity: &str,
) -> Result<bool> {
    let entries = git_ref_task_entries(project_root, reference)?;
    let marker_count = entries
        .iter()
        .flat_map(|entry| codex_session_markers_in_task_content(&entry.content))
        .filter(|(_, _, candidate)| *candidate == session_id)
        .count();
    let active_count = entries
        .iter()
        .filter(|entry| {
            matches!(entry.status.as_str(), "todo" | "doing")
                && codex_session_id_from_task_content(&entry.content) == Some(session_id)
                && durable_task_identity(&entry.content).as_deref() == Some(task_identity)
        })
        .count();
    Ok(marker_count == 1 && active_count == 1)
}

pub(super) fn git_ref_has_one_completed_session_task(
    project_root: &Path,
    reference: &str,
    session_id: &str,
    task_identity: &str,
) -> Result<bool> {
    let entries = git_ref_task_entries(project_root, reference)?;
    let marker_count = entries
        .iter()
        .flat_map(|entry| codex_session_markers_in_task_content(&entry.content))
        .filter(|(_, _, candidate)| *candidate == session_id)
        .count();
    let completed_count = entries
        .iter()
        .filter(|entry| {
            entry.status == "done"
                && codex_session_id_from_task_content(&entry.content) == Some(session_id)
                && durable_task_identity(&entry.content).as_deref() == Some(task_identity)
                && task_content_has_completed_note(&entry.content)
        })
        .count();
    Ok(marker_count == 1 && completed_count == 1)
}

pub(super) fn run_agent_git_projection_command(
    project_root: &Path,
    index_path: &Path,
    worktree_path: Option<&Path>,
    args: &[&str],
    operation: &str,
) -> Result<String> {
    let mut command = Command::new("git");
    command
        .current_dir(project_root)
        .env("GIT_INDEX_FILE", index_path)
        .args(args);
    if let Some(worktree_path) = worktree_path {
        command.env("GIT_WORK_TREE", worktree_path);
    }
    let output = command.output().with_context(|| {
        format!(
            "Failed to {operation} while projecting the sealed task tree in {}",
            project_root.display()
        )
    })?;
    if !output.status.success() {
        anyhow::bail!(
            "Failed to {operation} while projecting the sealed task tree in {}: {}",
            project_root.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    String::from_utf8(output.stdout)
        .with_context(|| format!("Git returned non-UTF-8 output while trying to {operation}"))
        .map(|value| value.trim().to_string())
}

pub(super) fn materialize_agent_git_task_tree(
    project_root: &Path,
    index_path: &Path,
    staged_tree: &str,
    checkout_prefix: &str,
) -> Result<()> {
    let task_paths = Command::new("git")
        .current_dir(project_root)
        .args([
            "ls-tree",
            "-r",
            "-z",
            "--name-only",
            staged_tree,
            "--",
            "tasks",
        ])
        .output()
        .with_context(|| {
            format!(
                "Failed to list the staged task tree in {}",
                project_root.display()
            )
        })?;
    if !task_paths.status.success() {
        anyhow::bail!(
            "Failed to list the staged task tree in {}: {}",
            project_root.display(),
            String::from_utf8_lossy(&task_paths.stderr).trim()
        );
    }
    let checkout_argument = format!("--prefix={checkout_prefix}");
    let mut child = Command::new("git")
        .current_dir(project_root)
        .env("GIT_INDEX_FILE", index_path)
        .args([
            "checkout-index",
            "--force",
            "--stdin",
            "-z",
            &checkout_argument,
        ])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .context("Failed to start Git while materializing the staged task tree")?;
    child
        .stdin
        .take()
        .context("git checkout-index did not expose stdin")?
        .write_all(&task_paths.stdout)
        .context("Failed to send staged task paths to git checkout-index")?;
    let output = child
        .wait_with_output()
        .context("Failed to finish materializing the staged task tree")?;
    if !output.status.success() {
        anyhow::bail!(
            "Failed to materialize the staged task tree in {}: {}",
            project_root.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(())
}

pub(super) fn create_agent_git_tree_projection(
    project_root: &Path,
    source_tree: &str,
) -> Result<(TempDir, PathBuf, PathBuf)> {
    // Atomically reserve a random name and retry collisions; timestamps can
    // repeat across threads. The guard also removes partial projections on error.
    let mut projection_builder = tempfile::Builder::new();
    projection_builder.prefix("clt-git-finalization-");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        projection_builder.permissions(fs::Permissions::from_mode(0o700));
    }
    let projection = projection_builder
        .tempdir()
        .context("Failed to create sealed task projection directory")?;
    let index_path = projection.path().join("index");
    let worktree_path = projection.path().join("worktree");
    fs::create_dir(&worktree_path).with_context(|| {
        format!(
            "Failed to create sealed task projection worktree {:?}",
            worktree_path
        )
    })?;
    run_agent_git_projection_command(
        project_root,
        &index_path,
        None,
        &["read-tree", source_tree],
        "load the staged task tree",
    )?;
    let mut checkout_prefix = worktree_path.as_os_str().to_os_string();
    checkout_prefix.push(std::path::MAIN_SEPARATOR.to_string());
    let checkout_prefix = checkout_prefix
        .to_str()
        .context("Sealed task projection path is not valid UTF-8")?;
    materialize_agent_git_task_tree(project_root, &index_path, source_tree, checkout_prefix)?;
    Ok((projection, index_path, worktree_path))
}

pub(super) fn git_task_subtree(project_root: &Path, root_tree: &str) -> Result<String> {
    // A folder-backed board may have no tracked entries after removing the
    // selected task and its follow-up from the private comparison. ls-tree
    // represents that empty scope without treating the absent directory as an error.
    git_stdout(
        project_root,
        &["ls-tree", root_tree, "--", "tasks"],
        "resolve the exact task-board tree",
    )
}

pub(super) fn stage_projected_task_tree(
    project_root: &Path,
    index_path: &Path,
    worktree_path: &Path,
    operation: &str,
) -> Result<String> {
    run_agent_git_projection_command(
        project_root,
        index_path,
        Some(worktree_path),
        &["add", "-A", "--", "tasks"],
        operation,
    )?;
    run_agent_git_projection_command(
        project_root,
        index_path,
        Some(worktree_path),
        &["write-tree"],
        operation,
    )
}

pub(super) fn projected_task_entry(
    board_dir: &Path,
    statuses: &[TaskStatus],
    session_id: Option<&str>,
    task_identity: &str,
) -> Result<(TaskStatus, usize, TaskEntry)> {
    let mut selected = Vec::new();
    for status in statuses {
        for (index, entry) in read_task_entries(board_dir, *status)?
            .into_iter()
            .enumerate()
        {
            if session_id.is_none_or(|session_id| {
                codex_session_id_from_task_content(&entry.content) == Some(session_id)
            }) && durable_task_identity(&entry.content).as_deref() == Some(task_identity)
            {
                selected.push((*status, index + 1, entry));
            }
        }
    }
    let [selected] = selected.as_slice() else {
        anyhow::bail!("The task projection must contain exactly one matching task");
    };
    Ok(selected.clone())
}

pub(super) fn agent_git_task_scope_without_selected(
    project_root: &Path,
    source_tree: &str,
    task_identity: &str,
) -> Result<String> {
    let (_projection, index_path, worktree_path) =
        create_agent_git_tree_projection(project_root, source_tree)?;
    let board_dir = get_tasks_dir(&worktree_path);
    let mut selected = Vec::new();
    for status in [TaskStatus::Todo, TaskStatus::Doing] {
        for entry in read_task_entries(&board_dir, status)? {
            if durable_task_identity(&entry.content).as_deref() == Some(task_identity) {
                selected.push((status, entry));
            }
        }
    }
    match selected.as_slice() {
        [] => anyhow::bail!(
            "The selected Git-enabled task is not present in the checkpointed manifest parent"
        ),
        [(status, entry)] => remove_task_entry_without_reordering(&board_dir, *status, entry)?,
        _ => {
            anyhow::bail!(
                "The Git manifest parent contains more than one active task with the selected identity"
            )
        }
    }
    let sanitized_tree = stage_projected_task_tree(
        project_root,
        &index_path,
        &worktree_path,
        "sanitize the selected task from the manifest parent",
    )?;
    git_task_subtree(project_root, &sanitized_tree)
}

pub(super) fn agent_git_completed_scope_without_selected(
    project_root: &Path,
    completed_tree: &str,
    parent_tree: &str,
    session_id: &str,
    task_identity: &str,
) -> Result<String> {
    let (_projection, index_path, worktree_path) =
        create_agent_git_tree_projection(project_root, completed_tree)?;
    let board_dir = get_tasks_dir(&worktree_path);
    let (_, _, entry) = projected_task_entry(
        &board_dir,
        &[TaskStatus::Done],
        Some(session_id),
        task_identity,
    )?;
    remove_task_entry_without_reordering(&board_dir, TaskStatus::Done, &entry)?;
    // Only new, explicitly linked follow-ups may accompany the selected
    // task. Removing them from this private projection must restore the exact
    // parent board; edits to existing tasks, headers, paths and attachments still fail.
    let parent_entries = git_ref_task_entries(project_root, parent_tree)?;
    let mut follow_ups = Vec::new();
    for status in [TaskStatus::Todo, TaskStatus::Doing] {
        for entry in read_task_entries(&board_dir, status)? {
            if follow_up_session(&entry.content) == Some(session_id)
                && follow_up_matches_status(&entry.content, status)
                && match &entry.source {
                    TaskSource::MarkdownLine { .. } => true,
                    TaskSource::Path {
                        path,
                        is_dir: false,
                    } => fs::symlink_metadata(path)
                        .is_ok_and(|metadata| metadata.file_type().is_file()),
                    TaskSource::Path { is_dir: true, .. } => false,
                }
                && !parent_entries
                    .iter()
                    .any(|parent| follow_up_session(&parent.content) == Some(session_id))
            {
                follow_ups.push((status, entry));
            }
        }
    }
    anyhow::ensure!(
        follow_ups.len() <= 1,
        "Only one new follow-up may accompany a task commit"
    );
    for (status, follow_up) in follow_ups.iter().rev() {
        remove_task_entry_without_reordering(&board_dir, *status, follow_up)?;
    }
    let sanitized_tree = stage_projected_task_tree(
        project_root,
        &index_path,
        &worktree_path,
        "sanitize the selected task from the completed manifest",
    )?;
    git_task_subtree(project_root, &sanitized_tree)
}

pub(super) fn project_agent_git_completed_tree(
    project_root: &Path,
    staged_tree: &str,
    session_id: &str,
    task_identity: &str,
    parent_tree: &str,
    expected_task_scope_tree: &str,
) -> Result<String> {
    let (_projection, index_path, worktree_path) =
        create_agent_git_tree_projection(project_root, staged_tree)?;
    let board_dir = get_tasks_dir(&worktree_path);
    let (status, task_index, _) = projected_task_entry(
        &board_dir,
        &[TaskStatus::Todo, TaskStatus::Doing],
        Some(session_id),
        task_identity,
    )?;
    move_task_without_reordering_after_lock(&board_dir, status, TaskStatus::Done, task_index)?;
    let completed_tree = stage_projected_task_tree(
        project_root,
        &index_path,
        &worktree_path,
        "stage the projected Done transition",
    )?;
    if git_ref_completed_task_identity(project_root, &completed_tree, session_id)?.as_deref()
        != Some(task_identity)
    {
        anyhow::bail!("CLT could not project the selected task into an exact completed Git tree");
    }
    if agent_git_completed_scope_without_selected(
        project_root,
        &completed_tree,
        parent_tree,
        session_id,
        task_identity,
    )? != expected_task_scope_tree
    {
        anyhow::bail!(
            "The staged task board contains raw changes outside the selected task; leave unrelated task files, ordering, headers, archives, and attachments unstaged"
        );
    }
    Ok(completed_tree)
}

pub(super) fn capture_agent_git_staged_manifest(
    proof: AgentGitProofContext<'_>,
    project_root: &Path,
    raw_baseline: &str,
    session_id: &str,
    task_identity: &str,
    starting_head: &str,
    branch_ref: Option<&str>,
) -> Result<String> {
    let baseline = AgentGitWorktreeBaseline::from_json(raw_baseline)?;
    let manifest_parent_head = resolve_git_commit(
        project_root,
        "HEAD",
        "freeze the staged task manifest parent",
    )?;
    if !git_commit_is_ancestor(project_root, starting_head, &manifest_parent_head)?
        || !agent_git_range_is_safe_before_manifest(
            proof,
            project_root,
            starting_head,
            &manifest_parent_head,
            session_id,
        )?
    {
        anyhow::bail!(
            "Automated Git completion found an unproven intervening commit before the sealed manifest; keep the implementation and Done transition in one task commit"
        );
    }

    let expected_task_scope_tree =
        agent_git_task_scope_without_selected(project_root, &manifest_parent_head, task_identity)?;
    let staged_paths = git_nul_separated_paths(
        project_root,
        &["diff", "--cached", "--name-only", "-z", "--"],
        "list staged task files",
    )?;
    // A user commit or board checkpoint may already include all implementation
    // and Doing-note edits. The projected Done move below still supplies the
    // task commit; its identity and COMPLETED note must exist in the index.
    let mut staged_non_task_patch_ids = BTreeMap::new();
    for path in staged_paths
        .iter()
        .filter(|path| !path.starts_with("tasks/"))
    {
        staged_non_task_patch_ids.insert(
            path.clone(),
            git_delta_id_for_path(project_root, &["--cached"], path)?,
        );
    }
    // Unstaged and untracked work belongs to the shared checkout, not this
    // manifest. The index is the agent-reviewed payload; seal only that tree.
    let staged_index_tree = git_stdout(
        project_root,
        &["write-tree"],
        "snapshot the staged task manifest",
    )?;
    if !git_ref_has_one_active_session_task(
        project_root,
        &staged_index_tree,
        session_id,
        task_identity,
    )? {
        anyhow::bail!(
            "Stage the selected Doing task, including its terminal codex:{session_id} marker and COMPLETED note, before `clt done`"
        );
    }
    let sealed_commit_tree = project_agent_git_completed_tree(
        project_root,
        &staged_index_tree,
        session_id,
        task_identity,
        &manifest_parent_head,
        &expected_task_scope_tree,
    )?;
    let rechecked_parent =
        resolve_git_commit(project_root, "HEAD", "recheck the staged manifest parent")?;
    let rechecked_tree = git_stdout(
        project_root,
        &["write-tree"],
        "recheck the staged task manifest",
    )?;
    let rechecked_branch = git_optional_stdout(
        project_root,
        &["symbolic-ref", "-q", "HEAD"],
        &[1],
        "recheck the frozen task branch",
    )?;
    if rechecked_parent != manifest_parent_head
        || rechecked_tree != staged_index_tree
        || rechecked_branch.as_deref() != branch_ref
        || !git_commit_is_ancestor(project_root, starting_head, &rechecked_parent)?
    {
        anyhow::bail!(
            "Git HEAD, branch, or index changed while CLT was sealing the task manifest; retry `clt done`"
        );
    }

    let mut baseline = baseline;
    baseline.staged_non_task_patch_ids = Some(staged_non_task_patch_ids);
    baseline.staged_index_tree = Some(sealed_commit_tree);
    baseline.manifest_parent_head = Some(manifest_parent_head);
    baseline.to_json()
}

pub(super) fn capture_agent_git_resealed_manifest(
    proof: AgentGitProofContext<'_>,
    project_root: &Path,
    raw_baseline: &str,
    session_id: &str,
    task_identity: &str,
    starting_head: &str,
    branch_ref: Option<&str>,
) -> Result<String> {
    let mut baseline = AgentGitWorktreeBaseline::from_json(raw_baseline)?;
    if baseline.version < 2 {
        anyhow::bail!("Legacy Git finalizations cannot be resealed");
    }
    let manifest_parent_head =
        resolve_git_commit(project_root, "HEAD", "freeze the corrected manifest parent")?;
    let current_branch = git_optional_stdout(
        project_root,
        &["symbolic-ref", "-q", "HEAD"],
        &[1],
        "verify the corrected manifest branch",
    )?;
    if current_branch.as_deref() != branch_ref
        || !git_commit_is_ancestor(project_root, starting_head, &manifest_parent_head)?
        || git_ref_contains_completed_task(project_root, &manifest_parent_head, session_id)?
        || !agent_git_range_is_safe_before_manifest(
            proof,
            project_root,
            starting_head,
            &manifest_parent_head,
            session_id,
        )?
    {
        anyhow::bail!(
            "The branch or history changed incompatibly before the provisional Done manifest could be resealed"
        );
    }

    let staged_paths = git_nul_separated_paths(
        project_root,
        &["diff", "--cached", "--name-only", "-z", "--"],
        "list corrected staged task files",
    )?;
    if staged_paths.is_empty() {
        anyhow::bail!("Resealing requires the complete corrected task commit to be staged");
    }
    let mut staged_non_task_patch_ids = BTreeMap::new();
    for path in staged_paths
        .iter()
        .filter(|path| !path.starts_with("tasks/"))
    {
        staged_non_task_patch_ids.insert(
            path.clone(),
            git_delta_id_for_path(project_root, &["--cached"], path)?,
        );
    }
    let sealed_commit_tree = git_stdout(
        project_root,
        &["write-tree"],
        "snapshot the corrected completed-task manifest",
    )?;
    if !git_ref_has_one_completed_session_task(
        project_root,
        &sealed_commit_tree,
        session_id,
        task_identity,
    )? {
        anyhow::bail!(
            "The corrected staged index must contain exactly one completed task for Codex session {session_id}"
        );
    }
    let expected_task_scope_tree =
        agent_git_task_scope_without_selected(project_root, &manifest_parent_head, task_identity)?;
    if agent_git_completed_scope_without_selected(
        project_root,
        &sealed_commit_tree,
        &manifest_parent_head,
        session_id,
        task_identity,
    )? != expected_task_scope_tree
    {
        anyhow::bail!("The corrected staged task board changes evidence outside the selected task");
    }
    let rechecked_parent = resolve_git_commit(
        project_root,
        "HEAD",
        "recheck the corrected manifest parent",
    )?;
    let rechecked_tree = git_stdout(
        project_root,
        &["write-tree"],
        "recheck the corrected completed-task manifest",
    )?;
    let rechecked_branch = git_optional_stdout(
        project_root,
        &["symbolic-ref", "-q", "HEAD"],
        &[1],
        "recheck the corrected manifest branch",
    )?;
    if rechecked_parent != manifest_parent_head
        || rechecked_tree != sealed_commit_tree
        || rechecked_branch.as_deref() != branch_ref
    {
        anyhow::bail!(
            "Git HEAD, branch, or index changed while CLT was resealing the task manifest; retry"
        );
    }
    baseline.staged_non_task_patch_ids = Some(staged_non_task_patch_ids);
    baseline.staged_index_tree = Some(sealed_commit_tree);
    baseline.manifest_parent_head = Some(manifest_parent_head);
    baseline.to_json()
}

pub(super) fn agent_git_range_is_safe_before_manifest(
    proof: AgentGitProofContext<'_>,
    project_root: &Path,
    starting_head: &str,
    manifest_parent: &str,
    current_session_id: &str,
) -> Result<bool> {
    if starting_head == manifest_parent {
        return Ok(true);
    }
    if !git_commit_is_first_parent_ancestor(project_root, starting_head, manifest_parent)? {
        return Ok(false);
    }
    let range = format!("{starting_head}..{manifest_parent}");
    let revisions = git_stdout(
        project_root,
        &["rev-list", "--first-parent", "--reverse", &range],
        "audit commits created before the task manifest",
    )?;
    for commit in revisions.lines().filter(|commit| !commit.is_empty()) {
        if git_commit_is_compatible_concurrent_work(project_root, commit, current_session_id)? {
            continue;
        }
        let is_proven_completed_task = git_commit_is_proven_completed_other_session(
            proof,
            project_root,
            commit,
            current_session_id,
        )?;
        if !is_proven_completed_task {
            return Ok(false);
        }
    }
    Ok(true)
}

fn git_commit_is_compatible_concurrent_work(
    project_root: &Path,
    commit_oid: &str,
    current_session_id: &str,
) -> Result<bool> {
    // The launch commit remains the history anchor, but ordinary commits may
    // advance this shared branch before we freeze the task's actual parent.
    // A task claim must still pass the separate journal/manifest proof.
    if !git_commit_task_trailers(project_root, commit_oid)?.is_empty()
        || git_ref_contains_completed_task(project_root, commit_oid, current_session_id)?
    {
        return Ok(false);
    }
    let metadata = git_stdout(
        project_root,
        &[
            "show",
            "-s",
            "--format=%P%x00%an%x00%ae%x00%cn%x00%ce%x00%B",
            commit_oid,
        ],
        "inspect concurrent commit ownership and parents",
    )?;
    let fields = metadata.splitn(6, '\0').collect::<Vec<_>>();
    let [
        parents,
        author_name,
        author_email,
        committer_name,
        committer_email,
        message,
    ] = fields.as_slice()
    else {
        return Ok(false);
    };
    if parents.split_whitespace().count() != 1 {
        return Ok(false);
    }
    // Inspect both identities: overriding only an agent commit's author (or
    // committer) must not disguise a premature implementation commit.
    let has_agent_identity = [*author_name, *committer_name].contains(&AGENT_GIT_IDENTITY_NAME)
        || [*author_email, *committer_email].contains(&AGENT_GIT_IDENTITY_EMAIL);
    if !has_agent_identity {
        return Ok(true);
    }
    // CLT may checkpoint the board for a later run while an older Working
    // journal is blocked. Recognize only the board-only checkpoint shape;
    // ordinary agent implementation commits still need completion proof.
    if message.trim_end() != AGENT_GIT_BOARD_CHECKPOINT_MESSAGE
        || !git_commit_uses_agent_identity(project_root, commit_oid)?
    {
        return Ok(false);
    }
    let paths = git_nul_separated_paths(
        project_root,
        &[
            "diff-tree",
            "--no-commit-id",
            "--name-only",
            "--no-renames",
            "-r",
            "-z",
            commit_oid,
            "--",
        ],
        "verify the concurrent task-board checkpoint scope",
    )?;
    Ok(!paths.is_empty() && paths.iter().all(|path| path.starts_with("tasks/")))
}

pub(super) fn git_commit_is_proven_completed_other_session(
    proof: AgentGitProofContext<'_>,
    project_root: &Path,
    commit_oid: &str,
    current_session_id: &str,
) -> Result<bool> {
    let trailers = git_commit_task_trailers(project_root, commit_oid)?;
    let [trailer] = trailers.as_slice() else {
        return Ok(false);
    };
    let Some(session_id) = trailer.strip_prefix(CODEX_TASK_SESSION_PREFIX) else {
        return Ok(false);
    };
    if session_id.is_empty()
        || session_id == current_session_id
        || !git_commit_uses_agent_identity(project_root, commit_oid)?
    {
        return Ok(false);
    }
    let Some(finalization) = proof
        .store
        .git_finalization_blocking(proof.project_id, session_id)?
    else {
        return Ok(false);
    };
    let Some(task_identity) = finalization.task_identity.as_deref() else {
        return Ok(false);
    };
    let baseline = AgentGitWorktreeBaseline::from_json(&finalization.worktree_baseline)?;
    if finalization.state != GitFinalizationState::Completed
        || baseline.version < 2
        || finalization.commit_oid.as_deref() != Some(commit_oid)
    {
        return Ok(false);
    }
    git_commit_matches_agent_staged_manifest(
        project_root,
        commit_oid,
        session_id,
        task_identity,
        &finalization.worktree_baseline,
        true,
    )
}

pub(super) fn git_commit_matches_agent_staged_manifest(
    project_root: &Path,
    commit_oid: &str,
    session_id: &str,
    task_identity: &str,
    raw_baseline: &str,
    require_manifest_parent: bool,
) -> Result<bool> {
    let baseline = AgentGitWorktreeBaseline::from_json(raw_baseline)?;
    let (Some(_expected_non_task), Some(sealed_commit_tree)) = (
        baseline.staged_non_task_patch_ids.as_ref(),
        baseline.staged_index_tree.as_deref(),
    ) else {
        // Version-one journals predate staged manifests. Their immutable tree,
        // identity, trailer, and author proof is still safe to adopt; new
        // journals always take the stronger manifest path.
        return Ok(baseline.version == 1);
    };
    let parents = git_stdout(
        project_root,
        &["show", "-s", "--format=%P", commit_oid],
        "read the task commit parent for manifest verification",
    )?;
    let parent_oids = parents.split_whitespace().collect::<Vec<_>>();
    if parent_oids.len() != 1 {
        return Ok(false);
    }
    let parent = parent_oids[0];
    if require_manifest_parent && baseline.manifest_parent_head.as_deref() != Some(parent) {
        return Ok(false);
    }
    let tree_reference = format!("{commit_oid}^{{tree}}");
    let committed_tree = git_stdout(
        project_root,
        &["rev-parse", "--verify", &tree_reference],
        "resolve the committed task tree",
    )?;
    if committed_tree != sealed_commit_tree
        || git_ref_completed_task_identity(project_root, commit_oid, session_id)?.as_deref()
            != Some(task_identity)
    {
        return Ok(false);
    }
    Ok(true)
}

pub(super) fn capture_agent_git_start_state(
    project_root: &Path,
    git_mode: AgentGitMode,
) -> Result<AgentGitStartState> {
    let starting_index_tree = agent_git_index_tree(project_root)?;
    let starting_head = git_stdout(
        project_root,
        &["rev-parse", "--verify", "HEAD^{commit}"],
        "resolve the starting Git commit",
    )?;
    let branch_ref = git_optional_stdout(
        project_root,
        &["symbolic-ref", "-q", "HEAD"],
        &[1],
        "resolve the current Git branch",
    )?;
    if branch_ref.is_none() {
        anyhow::bail!(
            "Git-enabled automated tasks require an attached branch before CLT freezes the task boundary"
        );
    }
    let upstream_ref = git_optional_stdout(
        project_root,
        &[
            "rev-parse",
            "--symbolic-full-name",
            "--verify",
            "@{upstream}",
        ],
        &[1, 128],
        "resolve the current Git upstream",
    )?;
    if git_mode == AgentGitMode::CommitAndPush && upstream_ref.is_none() {
        anyhow::bail!(
            "Automated commit-and-push tasks require an attached branch with a configured upstream before entering Doing"
        );
    }
    let upstream_destination = if git_mode == AgentGitMode::CommitAndPush {
        Some(
            capture_agent_git_upstream_destination(project_root, branch_ref.as_deref())?
                .context("Automated commit-and-push tasks require one stable push destination")?,
        )
    } else {
        None
    };
    let mut baseline = capture_agent_git_worktree_baseline(project_root)?;
    baseline.initial_index_tree = Some(starting_index_tree.clone());
    if let Some(destination) = upstream_destination.as_ref() {
        baseline.upstream_remote = Some(destination.remote.clone());
        baseline.upstream_merge_ref = Some(destination.merge_ref.clone());
        baseline.upstream_push_url = destination.push_url.clone();
    }
    let worktree_baseline = baseline.to_json()?;
    require_agent_git_index_tree(project_root, &starting_index_tree)?;
    let rechecked_head = resolve_git_commit(project_root, "HEAD", "recheck the task start commit")?;
    let rechecked_branch = git_optional_stdout(
        project_root,
        &["symbolic-ref", "-q", "HEAD"],
        &[1],
        "recheck the current Git branch",
    )?;
    let rechecked_upstream = resolve_agent_git_upstream(project_root, branch_ref.as_deref())?;
    let rechecked_destination = if git_mode == AgentGitMode::CommitAndPush {
        capture_agent_git_upstream_destination(project_root, branch_ref.as_deref())?
    } else {
        None
    };
    if rechecked_head != starting_head
        || rechecked_branch != branch_ref
        || rechecked_upstream != upstream_ref
        || rechecked_destination != upstream_destination
    {
        anyhow::bail!(
            "Git HEAD, branch, upstream, or index changed while CLT was freezing the task start state; retry the Todo-to-Doing move"
        );
    }

    Ok(AgentGitStartState {
        starting_head,
        branch_ref,
        upstream_ref,
        worktree_baseline,
    })
}

pub(super) fn verify_agent_git_start_state_unchanged(
    project_root: &Path,
    git_mode: AgentGitMode,
    start: &AgentGitStartState,
) -> Result<()> {
    let current_head = resolve_git_commit(project_root, "HEAD", "verify the prelaunch Git commit")?;
    let current_branch = git_optional_stdout(
        project_root,
        &["symbolic-ref", "-q", "HEAD"],
        &[1],
        "verify the prelaunch Git branch",
    )?;
    let current_upstream = resolve_agent_git_upstream(project_root, current_branch.as_deref())?;
    let expected_baseline = AgentGitWorktreeBaseline::from_json(&start.worktree_baseline)?;
    let current_index_tree = agent_git_index_tree(project_root)?;
    let current_baseline = capture_agent_git_worktree_baseline(project_root)?;
    // Older journals were created under the clean-index requirement.
    let expected_index_tree = match expected_baseline.initial_index_tree.as_deref() {
        Some(tree) => tree.to_string(),
        None => git_stdout(
            project_root,
            &[
                "rev-parse",
                "--verify",
                &format!("{}^{{tree}}", start.starting_head),
            ],
            "resolve the legacy prelaunch index",
        )?,
    };
    let worktree_is_unchanged = current_baseline.tracked_patch_ids
        == expected_baseline.tracked_patch_ids
        && current_baseline.untracked_blob_ids == expected_baseline.untracked_blob_ids;
    let upstream_is_unchanged = if git_mode == AgentGitMode::CommitAndPush {
        capture_agent_git_upstream_destination(project_root, current_branch.as_deref())?
            == Some(AgentGitUpstreamDestination {
                remote: expected_baseline
                    .upstream_remote
                    .clone()
                    .unwrap_or_default(),
                merge_ref: expected_baseline
                    .upstream_merge_ref
                    .clone()
                    .unwrap_or_default(),
                push_url: expected_baseline.upstream_push_url.clone(),
            })
    } else {
        true
    };
    if current_head != start.starting_head
        || current_branch != start.branch_ref
        || current_upstream != start.upstream_ref
        || current_index_tree != expected_index_tree
        || !worktree_is_unchanged
        || !upstream_is_unchanged
    {
        anyhow::bail!(
            "Git HEAD, branch, upstream, index, or worktree changed after CLT froze the automated run; start the task before making implementation changes or commits"
        );
    }
    require_agent_git_index_tree(project_root, &current_index_tree)?;
    Ok(())
}

pub(super) fn ensure_agent_git_working_record(
    store: &agent::TursoAgentStore,
    project: &agent::AgentProject,
    session_id: &str,
    run_token: &str,
    git_start_state: Option<&AgentGitStartState>,
) -> Result<()> {
    if project.git_mode == AgentGitMode::Off {
        return Ok(());
    }
    if let Some(existing) = store.git_finalization_blocking(project.id, session_id)? {
        if existing.state.is_terminal() {
            return Ok(());
        }
        if existing.git_mode != project.git_mode {
            anyhow::bail!(
                "Codex session {session_id} already has a Git journal with mode {}, not {}",
                existing.git_mode.label(),
                project.git_mode.label()
            );
        }
        // A journal that never bound a task can be adopted by the run that now
        // owns this session. Without this, a resumed run inherits the token of a
        // run that already finished and can never retire its own journal again.
        if existing.state == GitFinalizationState::Working
            && existing.task_identity.is_none()
            && existing.commit_oid.is_none()
            && existing.owner_run_token.as_deref() != Some(run_token)
        {
            let adopted = store.compare_and_set_git_finalization_blocking(
                project.id,
                session_id,
                existing.generation,
                GitFinalizationState::Working,
                Some(run_token),
                None,
                None,
                &agent_timestamp(),
            )?;
            if !adopted {
                anyhow::bail!(
                    "Codex session {session_id} lost its unbound Git journal to a concurrent run before adoption"
                );
            }
        }
        return Ok(());
    }
    let git = git_start_state.with_context(|| {
        format!("Git start state was not captured for Codex session {session_id}")
    })?;
    if worktree_completed_task_identity(&project.path, session_id)?.is_some() {
        anyhow::bail!(
            "Codex session {session_id} has completed task evidence but no frozen Git start journal; CLT cannot safely reconstruct the exact-one-commit boundary"
        );
    }
    let created = store.create_git_finalization_blocking(agent::NewGitFinalization {
        project_id: project.id,
        codex_session_id: session_id,
        git_mode: project.git_mode,
        starting_head: Some(&git.starting_head),
        branch_ref: git.branch_ref.as_deref(),
        upstream_ref: git.upstream_ref.as_deref(),
        worktree_baseline: &git.worktree_baseline,
        task_identity: None,
        owner_run_token: Some(run_token),
        created_at: &agent_timestamp(),
    })?;
    if !created {
        anyhow::bail!(
            "Codex session {session_id} lost its running-session fence before CLT could record the Git start state"
        );
    }
    Ok(())
}

pub(super) fn bind_agent_git_working_task_identity(
    store: &agent::TursoAgentStore,
    project: &agent::AgentProject,
    session_id: &str,
    run_token: &str,
) -> Result<bool> {
    let Some(finalization) = store.git_finalization_blocking(project.id, session_id)? else {
        return Ok(false);
    };
    let Some((_, task)) =
        terminal_task_for_codex_session_in_board(&get_tasks_dir(&project.path), session_id)?
    else {
        return Ok(false);
    };
    let task_identity = durable_task_identity(&task.content)
        .context("CLT could not derive a durable identity for the session-linked task")?;
    let starting_head = finalization
        .starting_head
        .as_deref()
        .context("The Git finalization has no frozen starting commit")?;
    require_agent_git_start_task_identity(&project.path, starting_head, &task_identity)?;
    if let Some(bound_identity) = finalization.task_identity.as_deref() {
        if bound_identity != task_identity {
            anyhow::bail!(
                "Codex session {session_id} is attached to task content that no longer matches its frozen Git journal"
            );
        }
        if finalization.state == GitFinalizationState::Working
            && finalization.owner_run_token.as_deref() != Some(run_token)
            && !store.compare_and_set_git_finalization_with_identity_blocking(
                project.id,
                session_id,
                finalization.generation,
                GitFinalizationState::Working,
                &task_identity,
                Some(run_token),
                &agent_timestamp(),
            )?
        {
            anyhow::bail!(
                "Codex session {session_id} lost its running-session fence while rotating its Working Git journal to the resumed run"
            );
        }
        return Ok(true);
    }
    if finalization.state != GitFinalizationState::Working {
        anyhow::bail!(
            "Git finalization for Codex session {session_id} entered {} before its task identity was bound",
            finalization.state.database_value()
        );
    }
    let changed = store.compare_and_set_git_finalization_with_identity_blocking(
        project.id,
        session_id,
        finalization.generation,
        GitFinalizationState::Working,
        &task_identity,
        Some(run_token),
        &agent_timestamp(),
    )?;
    if !changed {
        anyhow::bail!(
            "Codex session {session_id} lost its running-session fence before CLT could bind its task identity"
        );
    }
    Ok(true)
}

pub(super) fn git_stdout(project_root: &Path, args: &[&str], operation: &str) -> Result<String> {
    let output = Command::new("git")
        .current_dir(project_root)
        .args(args)
        .output()
        .with_context(|| format!("Failed to {operation} in {}", project_root.display()))?;
    if !output.status.success() {
        anyhow::bail!(
            "Failed to {operation} in {}: {}",
            project_root.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    String::from_utf8(output.stdout)
        .with_context(|| format!("Git output for {operation} was not valid UTF-8"))
        .map(|value| value.trim().to_string())
}

pub(super) fn git_optional_stdout(
    project_root: &Path,
    args: &[&str],
    absent_exit_codes: &[i32],
    operation: &str,
) -> Result<Option<String>> {
    let output = Command::new("git")
        .current_dir(project_root)
        .args(args)
        .output()
        .with_context(|| format!("Failed to {operation} in {}", project_root.display()))?;
    if output.status.success() {
        return String::from_utf8(output.stdout)
            .with_context(|| format!("Git output for {operation} was not valid UTF-8"))
            .map(|value| Some(value.trim().to_string()));
    }
    if output
        .status
        .code()
        .is_some_and(|code| absent_exit_codes.contains(&code))
    {
        return Ok(None);
    }
    anyhow::bail!(
        "Failed to {operation} in {}: {}",
        project_root.display(),
        String::from_utf8_lossy(&output.stderr).trim()
    )
}

pub(super) fn task_content_has_completed_note(content: &str) -> bool {
    !task_content_is_blocked(content)
        && content.lines().any(|line| {
            let uppercase = line.to_ascii_uppercase();
            uppercase
                .match_indices("COMPLETED ")
                .any(|(index, matched)| {
                    let has_word_boundary = uppercase[..index]
                        .chars()
                        .next_back()
                        .is_none_or(|ch| !ch.is_ascii_alphanumeric() && ch != '_');
                    has_word_boundary
                        && starts_with_task_note_date(
                            &uppercase.as_bytes()[index + matched.len()..],
                        )
                })
        })
}

pub(super) fn git_ref_contains_completed_task(
    project_root: &Path,
    reference: &str,
    session_id: &str,
) -> Result<bool> {
    Ok(git_ref_completed_task_identity(project_root, reference, session_id)?.is_some())
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) struct GitTaskProofEntry {
    pub(super) status: String,
    pub(super) content: String,
}

pub(super) fn git_ref_task_entries(
    project_root: &Path,
    reference: &str,
) -> Result<Vec<GitTaskProofEntry>> {
    let output = Command::new("git")
        .current_dir(project_root)
        .args(["ls-tree", "-r", "-z", reference, "--", "tasks"])
        .output()
        .with_context(|| {
            format!(
                "Failed to list tasks at {reference} in {}",
                project_root.display()
            )
        })?;
    if !output.status.success() {
        anyhow::bail!(
            "Failed to list tasks at {reference} in {}: {}",
            project_root.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }

    let mut paths = Vec::new();
    for raw in output
        .stdout
        .split(|byte| *byte == 0)
        .filter(|raw| !raw.is_empty())
    {
        let entry = std::str::from_utf8(raw)
            .context("Git returned a non-UTF-8 tree entry while proving finalization")?;
        let (metadata, path) = entry
            .split_once('\t')
            .context("Git returned an invalid tree entry while proving finalization")?;
        let mut metadata = metadata.split_whitespace();
        let mode = metadata.next().unwrap_or_default();
        let object_type = metadata.next().unwrap_or_default();
        if mode.starts_with("100") && object_type == "blob" {
            paths.push(path.to_string());
        }
    }
    let mut entries = Vec::new();
    collect_git_ref_board_task_entries(project_root, reference, &paths, "tasks", &mut entries)?;
    Ok(entries)
}

pub(super) fn git_tree_has_directory(paths: &[String], directory: &str) -> bool {
    let prefix = format!("{directory}/");
    paths.iter().any(|path| path.starts_with(&prefix))
}

pub(super) fn git_tree_board_has_any_status_store(paths: &[String], board_dir: &str) -> bool {
    TASK_STATUSES.iter().any(|status| {
        paths
            .iter()
            .any(|path| path == &format!("{board_dir}/{status}.md"))
            || git_tree_has_directory(paths, &format!("{board_dir}/{status}"))
    })
}

pub(super) fn git_ref_blob_content(
    project_root: &Path,
    reference: &str,
    path: &str,
) -> Result<String> {
    let object = format!("{reference}:{path}");
    git_stdout(
        project_root,
        &["cat-file", "blob", object.as_str()],
        "read a committed task",
    )
}

pub(super) fn collect_git_ref_board_task_entries(
    project_root: &Path,
    reference: &str,
    paths: &[String],
    board_dir: &str,
    entries: &mut Vec<GitTaskProofEntry>,
) -> Result<()> {
    for status in TASK_STATUSES {
        let status_dir = format!("{board_dir}/{status}");
        if git_tree_has_directory(paths, &status_dir) {
            let prefix = format!("{status_dir}/");
            let mut children = BTreeMap::<String, bool>::new();
            for path in paths.iter().filter(|path| path.starts_with(&prefix)) {
                let remainder = &path[prefix.len()..];
                let child = remainder.split('/').next().unwrap_or_default();
                if child.is_empty() || child.starts_with('.') {
                    continue;
                }
                let is_directory = remainder.len() > child.len();
                children
                    .entry(child.to_string())
                    .and_modify(|known_directory| *known_directory |= is_directory)
                    .or_insert(is_directory);
            }
            for (child, is_directory) in children {
                let task_path = format!("{status_dir}/{child}");
                let content = if is_directory {
                    let detail_path = TASK_DETAIL_FILES
                        .iter()
                        .map(|detail| format!("{task_path}/{detail}"))
                        .find(|detail_path| paths.iter().any(|path| path == detail_path));
                    match detail_path {
                        Some(detail_path) => {
                            git_ref_blob_content(project_root, reference, &detail_path)?
                        }
                        None => title_from_path(Path::new(&child)),
                    }
                } else {
                    git_ref_blob_content(project_root, reference, &task_path)?
                };
                entries.push(GitTaskProofEntry {
                    status: status.to_string(),
                    content,
                });
                if is_directory && git_tree_board_has_any_status_store(paths, &task_path) {
                    collect_git_ref_board_task_entries(
                        project_root,
                        reference,
                        paths,
                        &task_path,
                        entries,
                    )?;
                }
            }
        } else {
            let markdown_path = format!("{board_dir}/{status}.md");
            if paths.iter().any(|path| path == &markdown_path) {
                let content = git_ref_blob_content(project_root, reference, &markdown_path)?;
                entries.extend(content.lines().filter_map(|line| {
                    line.strip_prefix("- ").map(|content| GitTaskProofEntry {
                        status: status.to_string(),
                        content: content.to_string(),
                    })
                }));
            }
        }
    }
    Ok(())
}

pub(super) fn git_ref_completed_task_identity(
    project_root: &Path,
    reference: &str,
    session_id: &str,
) -> Result<Option<String>> {
    let entries = git_ref_task_entries(project_root, reference)?;
    let mut marker_count = 0;
    let mut completed_matches = 0;
    let mut completed_identity = None;
    for entry in entries {
        let matching_markers = codex_session_markers_in_task_content(&entry.content)
            .into_iter()
            .filter(|(_, _, candidate)| *candidate == session_id)
            .count();
        marker_count += matching_markers;
        if matching_markers == 1
            && codex_session_id_from_task_content(&entry.content) == Some(session_id)
            && entry.status == "done"
            && task_content_has_completed_note(&entry.content)
        {
            completed_matches += 1;
            if completed_matches == 1 {
                completed_identity = durable_task_identity(&entry.content);
            }
        }
    }
    Ok((marker_count == 1 && completed_matches == 1)
        .then_some(completed_identity)
        .flatten())
}

pub(super) fn git_ref_active_task_identity_count(
    project_root: &Path,
    reference: &str,
    task_identity: &str,
) -> Result<usize> {
    Ok(git_ref_task_entries(project_root, reference)?
        .into_iter()
        .filter(|entry| {
            matches!(entry.status.as_str(), "todo" | "doing")
                && durable_task_identity(&entry.content).as_deref() == Some(task_identity)
        })
        .count())
}

pub(super) fn require_agent_git_start_task_identity(
    project_root: &Path,
    starting_head: &str,
    task_identity: &str,
) -> Result<()> {
    let count = git_ref_active_task_identity_count(project_root, starting_head, task_identity)?;
    if count != 1 {
        anyhow::bail!(
            "Git-enabled automated work requires the selected task to be committed exactly once in Todo or Doing before the task starts (found {count})"
        );
    }
    Ok(())
}

pub(super) fn git_ref_contains_active_task_identity(
    project_root: &Path,
    reference: &str,
    task_identity: &str,
) -> Result<bool> {
    Ok(git_ref_task_entries(project_root, reference)?
        .into_iter()
        .any(|entry| {
            matches!(entry.status.as_str(), "todo" | "doing")
                && durable_task_identity(&entry.content).as_deref() == Some(task_identity)
        }))
}

pub(super) fn git_commit_task_trailers(
    project_root: &Path,
    commit_oid: &str,
) -> Result<Vec<String>> {
    Ok(git_stdout(
        project_root,
        &[
            "show",
            "-s",
            "--format=%(trailers:key=CLT-Task,valueonly)",
            commit_oid,
        ],
        "read the task commit trailer",
    )?
    .lines()
    .map(str::trim)
    .filter(|value| !value.is_empty())
    .map(str::to_string)
    .collect())
}

pub(super) fn git_commit_uses_agent_identity(
    project_root: &Path,
    commit_oid: &str,
) -> Result<bool> {
    let identity = git_stdout(
        project_root,
        &[
            "show",
            "-s",
            "--format=%an%x00%ae%x00%cn%x00%ce",
            commit_oid,
        ],
        "read commit identity",
    )?;
    let fields = identity.split('\0').collect::<Vec<_>>();
    Ok(fields
        == [
            AGENT_GIT_IDENTITY_NAME,
            AGENT_GIT_IDENTITY_EMAIL,
            AGENT_GIT_IDENTITY_NAME,
            AGENT_GIT_IDENTITY_EMAIL,
        ])
}

pub(super) fn git_commit_is_ancestor(
    project_root: &Path,
    ancestor: &str,
    descendant: &str,
) -> Result<bool> {
    let output = Command::new("git")
        .current_dir(project_root)
        .args(["merge-base", "--is-ancestor", ancestor, descendant])
        .output()
        .with_context(|| {
            format!(
                "Failed to compare Git ancestry in {}",
                project_root.display()
            )
        })?;
    match output.status.code() {
        Some(0) => Ok(true),
        Some(1) => Ok(false),
        _ => anyhow::bail!(
            "Failed to compare Git ancestry in {}: {}",
            project_root.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        ),
    }
}

pub(super) fn git_commit_is_first_parent_ancestor(
    project_root: &Path,
    ancestor: &str,
    descendant: &str,
) -> Result<bool> {
    if ancestor == descendant {
        return Ok(true);
    }
    Ok(git_stdout(
        project_root,
        &["rev-list", "--first-parent", descendant],
        "verify the first-parent task history",
    )?
    .lines()
    .any(|commit| commit == ancestor))
}

pub(super) fn resolve_git_commit(
    project_root: &Path,
    reference: &str,
    operation: &str,
) -> Result<String> {
    let commit_reference = format!("{reference}^{{commit}}");
    git_stdout(
        project_root,
        &["rev-parse", "--verify", commit_reference.as_str()],
        operation,
    )
}

#[cfg(test)]
pub(super) fn find_agent_git_task_commit(
    project_root: &Path,
    starting_head: &str,
    branch_ref: Option<&str>,
    session_id: &str,
    task_identity: &str,
) -> Result<Option<String>> {
    find_agent_git_task_commit_with_policy(
        project_root,
        starting_head,
        branch_ref,
        session_id,
        task_identity,
        true,
    )
}

pub(super) fn find_agent_git_task_commit_with_policy(
    project_root: &Path,
    starting_head: &str,
    branch_ref: Option<&str>,
    session_id: &str,
    task_identity: &str,
    legacy_identity_checks: bool,
) -> Result<Option<String>> {
    let branch_ref = branch_ref.unwrap_or("HEAD");
    let branch_tip = resolve_git_commit(project_root, branch_ref, "resolve the finalization tip")?;
    let starting_identity_count =
        git_ref_active_task_identity_count(project_root, starting_head, task_identity)?;
    if (legacy_identity_checks && starting_identity_count > 1)
        || !git_commit_is_first_parent_ancestor(project_root, starting_head, &branch_tip)?
        || git_ref_completed_task_identity(project_root, &branch_tip, session_id)?.as_deref()
            != Some(task_identity)
        || (legacy_identity_checks
            && git_ref_contains_active_task_identity(project_root, &branch_tip, task_identity)?)
    {
        return Ok(None);
    }
    if git_ref_contains_completed_task(project_root, starting_head, session_id)? {
        return Ok(None);
    }

    let range = format!("{starting_head}..{branch_tip}");
    let revisions = git_stdout(
        project_root,
        &["rev-list", "--first-parent", "--reverse", range.as_str()],
        "list task finalization commits",
    )?;
    let mut candidates = Vec::new();
    let expected_trailer = format!("{CODEX_TASK_SESSION_PREFIX}{session_id}");
    let mut session_commit_count = 0;
    for commit in revisions.lines().filter(|line| !line.is_empty()) {
        let trailers = git_commit_task_trailers(project_root, commit)?;
        if trailers.contains(&expected_trailer) {
            session_commit_count += 1;
        }
        if trailers.len() != 1
            || trailers[0] != expected_trailer
            || !git_commit_uses_agent_identity(project_root, commit)?
            || git_ref_completed_task_identity(project_root, commit, session_id)?.as_deref()
                != Some(task_identity)
            || (legacy_identity_checks
                && git_ref_contains_active_task_identity(project_root, commit, task_identity)?)
        {
            continue;
        }
        let parents = git_stdout(
            project_root,
            &["show", "-s", "--format=%P", commit],
            "read task commit parents",
        )?;
        let parent_oids = parents.split_whitespace().collect::<Vec<_>>();
        let introduced_completion = parent_oids.len() == 1
            && parent_oids[0] == starting_head
            && !git_ref_contains_completed_task(project_root, parent_oids[0], session_id)?
            && (!legacy_identity_checks
                || git_ref_active_task_identity_count(
                    project_root,
                    parent_oids[0],
                    task_identity,
                )? == starting_identity_count);
        if introduced_completion {
            candidates.push(commit.to_string());
        }
    }
    // Exactly one commit must claim this task and descend directly from its
    // frozen parent. Unrelated commits may advance the branch afterward; they
    // do not invalidate the task's immutable tree or completion evidence.
    if candidates.len() != 1 || session_commit_count != 1 {
        return Ok(None);
    }
    let candidate = candidates.remove(0);

    if resolve_git_commit(project_root, branch_ref, "recheck the finalization tip")? != branch_tip {
        return Ok(None);
    }

    Ok(Some(candidate))
}

pub(super) fn resolve_agent_git_upstream(
    project_root: &Path,
    branch_ref: Option<&str>,
) -> Result<Option<String>> {
    let branch = branch_ref
        .and_then(|branch| branch.strip_prefix("refs/heads/"))
        .unwrap_or("HEAD");
    let upstream = format!("{branch}@{{upstream}}");
    git_optional_stdout(
        project_root,
        &[
            "rev-parse",
            "--symbolic-full-name",
            "--verify",
            upstream.as_str(),
        ],
        &[1, 128],
        "resolve the task finalization upstream",
    )
}

pub(super) fn capture_agent_git_upstream_destination(
    project_root: &Path,
    branch_ref: Option<&str>,
) -> Result<Option<AgentGitUpstreamDestination>> {
    let Some(branch_name) = branch_ref.and_then(|branch| branch.strip_prefix("refs/heads/")) else {
        return Ok(None);
    };
    let remote_key = format!("branch.{branch_name}.remote");
    let merge_key = format!("branch.{branch_name}.merge");
    let Some(upstream_remote) = git_optional_stdout(
        project_root,
        &["config", "--get", remote_key.as_str()],
        &[1],
        "resolve the configured upstream remote",
    )?
    else {
        return Ok(None);
    };
    let push_remote_key = format!("branch.{branch_name}.pushRemote");
    let branch_push_remote = git_optional_stdout(
        project_root,
        &["config", "--get", push_remote_key.as_str()],
        &[1],
        "resolve the configured branch push remote",
    )?;
    let default_push_remote = git_optional_stdout(
        project_root,
        &["config", "--get", "remote.pushDefault"],
        &[1],
        "resolve the configured default push remote",
    )?;
    let remote = branch_push_remote
        .or(default_push_remote)
        .unwrap_or(upstream_remote);
    if remote.is_empty() {
        anyhow::bail!("Automated commit-and-push tasks require a non-empty push remote");
    }
    let Some(merge_ref) = git_optional_stdout(
        project_root,
        &["config", "--get", merge_key.as_str()],
        &[1],
        "resolve the configured upstream branch",
    )?
    else {
        return Ok(None);
    };
    if !merge_ref.starts_with("refs/heads/") {
        anyhow::bail!(
            "Automated commit-and-push tasks require an upstream branch ref under refs/heads/"
        );
    }
    if remote == "." {
        anyhow::bail!(
            "Automated commit-and-push tasks require a named remote with one explicit push URL"
        );
    }
    let urls = git_stdout(
        project_root,
        &["remote", "get-url", "--push", "--all", &remote],
        "resolve the configured upstream push destination",
    )?;
    let urls = urls
        .lines()
        .filter(|url| !url.is_empty())
        .collect::<Vec<_>>();
    let [url] = urls.as_slice() else {
        anyhow::bail!(
            "Automated commit-and-push tasks require exactly one configured push URL for remote {remote}"
        );
    };
    let push_url = Some((*url).to_string());
    Ok(Some(AgentGitUpstreamDestination {
        remote,
        merge_ref,
        push_url,
    }))
}

pub(super) fn run_agent_git_remote_command(
    command: &mut Command,
    operation: &str,
) -> Result<std::process::Output> {
    command.stdout(Stdio::piped()).stderr(Stdio::piped());
    configure_agent_child_command(command);
    let mut child = command
        .spawn()
        .with_context(|| format!("Failed to start Git while trying to {operation}"))?;
    let started = Instant::now();
    loop {
        if child
            .try_wait()
            .with_context(|| format!("Failed to poll Git while trying to {operation}"))?
            .is_some()
        {
            return child.wait_with_output().with_context(|| {
                format!("Failed to collect Git output while trying to {operation}")
            });
        }
        if started.elapsed() >= Duration::from_secs(AGENT_GIT_REMOTE_TIMEOUT_SECONDS) {
            stop_agent_child_process(&mut child).with_context(|| {
                format!("Timed-out Git process could not be stopped while trying to {operation}")
            })?;
            anyhow::bail!(
                "Git timed out after {AGENT_GIT_REMOTE_TIMEOUT_SECONDS} seconds while trying to {operation}"
            );
        }
        thread::sleep(Duration::from_millis(25));
    }
}

pub(super) fn ensure_agent_git_finalization_fence(
    finalization_lease: Option<&AgentGitFinalizationLease>,
) -> Result<()> {
    if let Some(finalization_lease) = finalization_lease {
        finalization_lease.ensure_owned()?;
    }
    Ok(())
}

pub(super) fn push_agent_git_commit_to_frozen_destination(
    project_root: &Path,
    branch_ref: Option<&str>,
    expected_upstream_ref: Option<&str>,
    baseline: &AgentGitWorktreeBaseline,
    commit_oid: &str,
    finalization_lease: Option<&AgentGitFinalizationLease>,
) -> Result<()> {
    ensure_agent_git_finalization_fence(finalization_lease)?;
    let expected_destination = AgentGitUpstreamDestination {
        remote: baseline.upstream_remote.clone().unwrap_or_default(),
        merge_ref: baseline.upstream_merge_ref.clone().unwrap_or_default(),
        push_url: baseline.upstream_push_url.clone(),
    };
    let push_url = expected_destination
        .push_url
        .as_deref()
        .context("The frozen Git push destination has no explicit URL")?;
    if expected_destination.remote.is_empty()
        || expected_destination.merge_ref.is_empty()
        || resolve_agent_git_upstream(project_root, branch_ref)?.as_deref() != expected_upstream_ref
        || capture_agent_git_upstream_destination(project_root, branch_ref)?.as_ref()
            != Some(&expected_destination)
    {
        anyhow::bail!(
            "The Git upstream or push destination changed after CLT froze it; leaving the task PUSH-PENDING"
        );
    }

    let refspec = format!("{commit_oid}:{}", expected_destination.merge_ref);
    let mut command = Command::new("git");
    command
        .current_dir(project_root)
        .env("GIT_TERMINAL_PROMPT", "0")
        .args([
            "-c",
            "push.followTags=false",
            "-c",
            "push.recurseSubmodules=no",
            "push",
            "--porcelain",
            "--no-follow-tags",
            "--recurse-submodules=no",
            "--",
            push_url,
            refspec.as_str(),
        ]);
    ensure_agent_git_finalization_fence(finalization_lease)?;
    let output = run_agent_git_remote_command(
        &mut command,
        &format!(
            "push sealed commit {commit_oid} to {}",
            expected_destination.merge_ref
        ),
    )?;
    ensure_agent_git_finalization_fence(finalization_lease)?;
    if !output.status.success() {
        anyhow::bail!(
            "Failed to push sealed commit {commit_oid} to {}: {}",
            expected_destination.merge_ref,
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    if resolve_agent_git_upstream(project_root, branch_ref)?.as_deref() != expected_upstream_ref
        || capture_agent_git_upstream_destination(project_root, branch_ref)?.as_ref()
            != Some(&expected_destination)
    {
        anyhow::bail!(
            "The Git push destination changed while CLT was publishing; remote proof is required before completion"
        );
    }
    ensure_agent_git_finalization_fence(finalization_lease)?;
    Ok(())
}

fn tracking_tip_for_push_destination(
    project_root: &Path,
    branch_ref: Option<&str>,
    upstream_ref: Option<&str>,
    destination: &AgentGitUpstreamDestination,
) -> Result<Option<String>> {
    let Some(branch) = branch_ref.and_then(|value| value.strip_prefix("refs/heads/")) else {
        return Ok(None);
    };
    let Some(upstream_ref) = upstream_ref.filter(|value| value.starts_with("refs/remotes/")) else {
        return Ok(None);
    };
    // The branch can fetch from one repository and push to another. Only
    // refresh its tracking ref when it represents this exact destination.
    let remote = git_optional_stdout(
        project_root,
        &["config", "--get", &format!("branch.{branch}.remote")],
        &[1],
        "resolve the upstream fetch remote",
    )?;
    if remote.as_deref() != Some(destination.remote.as_str()) {
        return Ok(None);
    }
    let urls = git_stdout(
        project_root,
        &["remote", "get-url", "--all", &destination.remote],
        "resolve the upstream fetch URL",
    )?;
    if Some(urls.as_str()) != destination.push_url.as_deref() {
        return Ok(None);
    }
    git_optional_stdout(
        project_root,
        &["rev-parse", "--verify", upstream_ref],
        &[1, 128],
        "read the upstream tracking ref before publication proof",
    )
}

fn refresh_agent_git_tracking_ref(
    project_root: &Path,
    upstream_ref: &str,
    previous_tip: &str,
    verified_tip: &str,
) {
    // Explicit-URL pushes/fetches do not maintain the named remote's cache.
    // Compare-and-swap so a concurrent fetch cannot be overwritten. A cache
    // update failure must not turn a proven publication into a failed task.
    if previous_tip != verified_tip
        && let Err(error) = git_stdout(
            project_root,
            &[
                "update-ref",
                "--no-deref",
                "-m",
                "clt: verified task publication",
                upstream_ref,
                verified_tip,
                previous_tip,
            ],
            "refresh the upstream tracking ref",
        )
    {
        eprintln!(
            "CLT verified the remote publication but could not refresh {upstream_ref}: {error:#}"
        );
    }
}

pub(super) fn fetch_agent_git_upstream_tip(
    project_root: &Path,
    branch_ref: Option<&str>,
    expected_upstream_ref: Option<&str>,
    baseline: &AgentGitWorktreeBaseline,
    finalization_lease: Option<&AgentGitFinalizationLease>,
) -> Result<Option<String>> {
    ensure_agent_git_finalization_fence(finalization_lease)?;
    if resolve_agent_git_upstream(project_root, branch_ref)?.as_deref() != expected_upstream_ref {
        return Ok(None);
    }
    let expected_destination = AgentGitUpstreamDestination {
        remote: baseline.upstream_remote.clone().unwrap_or_default(),
        merge_ref: baseline.upstream_merge_ref.clone().unwrap_or_default(),
        push_url: baseline.upstream_push_url.clone(),
    };
    if expected_destination.remote.is_empty()
        || expected_destination.merge_ref.is_empty()
        || capture_agent_git_upstream_destination(project_root, branch_ref)?.as_ref()
            != Some(&expected_destination)
    {
        return Ok(None);
    }
    if expected_destination.remote == "." {
        let tip = resolve_git_commit(
            project_root,
            &expected_destination.merge_ref,
            "resolve the local upstream tip",
        )?;
        ensure_agent_git_finalization_fence(finalization_lease)?;
        return Ok(
            (resolve_agent_git_upstream(project_root, branch_ref)?.as_deref()
                == expected_upstream_ref
                && capture_agent_git_upstream_destination(project_root, branch_ref)?.as_ref()
                    == Some(&expected_destination))
            .then_some(tip),
        );
    }
    let Some(push_url) = expected_destination.push_url.as_deref() else {
        return Ok(None);
    };
    let previous_tracking_tip = tracking_tip_for_push_destination(
        project_root,
        branch_ref,
        expected_upstream_ref,
        &expected_destination,
    )?;

    let read_remote_tip = || -> Result<Option<String>> {
        ensure_agent_git_finalization_fence(finalization_lease)?;
        let mut command = Command::new("git");
        command
            .current_dir(project_root)
            .env("GIT_TERMINAL_PROMPT", "0")
            .args([
                "ls-remote",
                "--refs",
                push_url,
                &expected_destination.merge_ref,
            ]);
        let output = run_agent_git_remote_command(
            &mut command,
            &format!(
                "query the frozen Git push destination for {}",
                expected_destination.merge_ref
            ),
        )?;
        ensure_agent_git_finalization_fence(finalization_lease)?;
        if !output.status.success() {
            anyhow::bail!(
                "Failed to query the frozen Git push destination for {}: {}",
                expected_destination.merge_ref,
                String::from_utf8_lossy(&output.stderr).trim()
            );
        }
        let stdout = String::from_utf8(output.stdout)
            .context("Configured Git remote returned non-UTF-8 output")?;
        let tips = stdout
            .lines()
            .filter_map(|line| line.split_whitespace().next())
            .collect::<Vec<_>>();
        Ok(match tips.as_slice() {
            [] => None,
            [tip] => Some((*tip).to_string()),
            _ => None,
        })
    };

    let Some(observed_tip) = read_remote_tip()? else {
        return Ok(None);
    };
    ensure_agent_git_finalization_fence(finalization_lease)?;
    let mut fetch_command = Command::new("git");
    fetch_command
        .current_dir(project_root)
        .env("GIT_TERMINAL_PROMPT", "0")
        .args([
            "fetch",
            "--no-tags",
            "--quiet",
            push_url,
            &expected_destination.merge_ref,
        ]);
    let fetch = run_agent_git_remote_command(
        &mut fetch_command,
        &format!(
            "fetch the frozen Git push destination for {}",
            expected_destination.merge_ref
        ),
    )?;
    ensure_agent_git_finalization_fence(finalization_lease)?;
    if !fetch.status.success() {
        anyhow::bail!(
            "Failed to fetch the frozen Git push destination for {}: {}",
            expected_destination.merge_ref,
            String::from_utf8_lossy(&fetch.stderr).trim()
        );
    }
    let fetched_tip = resolve_git_commit(
        project_root,
        "FETCH_HEAD",
        "resolve the fetched upstream tip",
    )?;
    let rechecked_tip = read_remote_tip()?;
    if resolve_agent_git_upstream(project_root, branch_ref)?.as_deref() != expected_upstream_ref
        || capture_agent_git_upstream_destination(project_root, branch_ref)?.as_ref()
            != Some(&expected_destination)
    {
        return Ok(None);
    }
    ensure_agent_git_finalization_fence(finalization_lease)?;
    if Some(fetched_tip.clone()) != rechecked_tip || fetched_tip != observed_tip {
        return Ok(None);
    }
    if let (Some(upstream_ref), Some(previous_tip)) =
        (expected_upstream_ref, previous_tracking_tip.as_deref())
        && tracking_tip_for_push_destination(
            project_root,
            branch_ref,
            expected_upstream_ref,
            &expected_destination,
        )?
        .as_deref()
            == Some(previous_tip)
    {
        ensure_agent_git_finalization_fence(finalization_lease)?;
        refresh_agent_git_tracking_ref(project_root, upstream_ref, previous_tip, &fetched_tip);
    }
    ensure_agent_git_finalization_fence(finalization_lease)?;
    Ok(Some(fetched_tip))
}

pub(super) fn worktree_contains_completed_done_task(
    project_root: &Path,
    session_id: &str,
) -> Result<bool> {
    let Some((status, task)) =
        terminal_task_for_codex_session_in_board(&get_tasks_dir(project_root), session_id)?
    else {
        return Ok(false);
    };
    Ok(status == TaskStatus::Done && task_content_has_completed_note(&task.content))
}

pub(super) fn agent_git_upstream_tip_proves_task_commit(
    project_root: &Path,
    upstream_tip: &str,
    local_commit_oid: &str,
    session_id: &str,
    task_identity: &str,
    legacy_identity_checks: bool,
) -> Result<bool> {
    Ok(
        git_commit_is_ancestor(project_root, local_commit_oid, upstream_tip)?
            && git_ref_completed_task_identity(project_root, upstream_tip, session_id)?.as_deref()
                == Some(task_identity)
            && (!legacy_identity_checks
                || !git_ref_contains_active_task_identity(
                    project_root,
                    upstream_tip,
                    task_identity,
                )?),
    )
}

pub(super) fn agent_git_manifest_parent_is_current(
    project_root: &Path,
    finalization: &agent::GitFinalizationRecord,
) -> Result<bool> {
    if git_optional_stdout(
        project_root,
        &["symbolic-ref", "-q", "HEAD"],
        &[1],
        "verify the task-recovery branch",
    )?
    .as_deref()
        != finalization.branch_ref.as_deref()
    {
        return Ok(false);
    }
    let current_head = resolve_git_commit(project_root, "HEAD", "verify the task-recovery commit")?;
    let baseline = AgentGitWorktreeBaseline::from_json(&finalization.worktree_baseline)?;
    if baseline.version >= 2 {
        return Ok(baseline.manifest_parent_head.as_deref() == Some(current_head.as_str()));
    }
    let Some(starting_head) = finalization.starting_head.as_deref() else {
        return Ok(false);
    };
    git_commit_is_ancestor(project_root, starting_head, &current_head)
}

pub(super) fn local_agent_git_task_commit_is_retained(
    project_root: &Path,
    branch_ref: Option<&str>,
    commit_oid: &str,
    session_id: &str,
    task_identity: &str,
) -> Result<bool> {
    let Some(branch_ref) = branch_ref else {
        return Ok(false);
    };
    if git_optional_stdout(
        project_root,
        &["symbolic-ref", "-q", "HEAD"],
        &[1],
        "verify the frozen push branch",
    )?
    .as_deref()
        != Some(branch_ref)
        || worktree_completed_task_identity(project_root, session_id)?.as_deref()
            != Some(task_identity)
    {
        return Ok(false);
    }
    let branch_tip =
        resolve_git_commit(project_root, branch_ref, "resolve the frozen push branch")?;
    if !git_commit_is_ancestor(project_root, commit_oid, &branch_tip)?
        || git_ref_completed_task_identity(project_root, &branch_tip, session_id)?.as_deref()
            != Some(task_identity)
        || git_ref_contains_active_task_identity(project_root, &branch_tip, task_identity)?
    {
        return Ok(false);
    }
    Ok(
        resolve_git_commit(project_root, branch_ref, "recheck the frozen push branch")?
            == branch_tip,
    )
}

pub(super) fn matching_agent_session_tasks(
    board_dir: &Path,
    status: TaskStatus,
    session_id: &str,
    task_identity: &str,
) -> Result<Vec<TaskEntry>> {
    Ok(read_task_entries(board_dir, status)?
        .into_iter()
        .filter(|entry| {
            codex_session_id_from_task_content(&entry.content) == Some(session_id)
                && durable_task_identity(&entry.content).as_deref() == Some(task_identity)
                && task_content_has_completed_note(&entry.content)
        })
        .collect())
}

pub(super) fn repair_tracking_agent_git_board(
    project_root: &Path,
    session_id: &str,
    task_identity: &str,
) -> Result<bool> {
    let board_dir = get_tasks_dir(project_root);
    let _mutation_lock = acquire_board_mutation_lock(&board_dir)?;
    cleanup_clt_atomic_task_temporaries(&board_dir)?;
    if [TaskStatus::Backlog]
        .into_iter()
        .map(|status| matching_agent_session_tasks(&board_dir, status, session_id, task_identity))
        .collect::<Result<Vec<_>>>()?
        .into_iter()
        .any(|entries| !entries.is_empty())
    {
        return Ok(false);
    }

    let mut done =
        matching_agent_session_tasks(&board_dir, TaskStatus::Done, session_id, task_identity)?;
    let mut active = Vec::new();
    for status in [TaskStatus::Todo, TaskStatus::Doing] {
        for entry in matching_agent_session_tasks(&board_dir, status, session_id, task_identity)? {
            active.push((status, entry));
        }
    }
    if done.is_empty() {
        let [(status, entry)] = active.as_slice() else {
            return Ok(false);
        };
        let task_index = read_task_entries(&board_dir, *status)?
            .iter()
            .position(|candidate| candidate.source == entry.source)
            .map(|index| index + 1)
            .context("The tracked Git task changed while CLT was repairing its Done move")?;
        move_task_without_reordering_after_lock(&board_dir, *status, TaskStatus::Done, task_index)?;
        return Ok(true);
    }

    let canonical_content = done[0].content.trim_end().to_string();
    let crash_duplicates_are_safe_entries = done
        .iter()
        .chain(active.iter().map(|(_, entry)| entry))
        .all(|entry| {
            matches!(
                entry.source,
                TaskSource::MarkdownLine { .. } | TaskSource::Path { is_dir: false, .. }
            ) && entry.content.trim_end() == canonical_content
        });
    if (!active.is_empty() || done.len() > 1) && !crash_duplicates_are_safe_entries {
        return Ok(false);
    }
    while done.len() > 1 {
        let duplicate = done.pop().expect("Done duplicate exists");
        remove_task_entry_without_reordering(&board_dir, TaskStatus::Done, &duplicate)?;
        done =
            matching_agent_session_tasks(&board_dir, TaskStatus::Done, session_id, task_identity)?;
    }
    for status in [TaskStatus::Todo, TaskStatus::Doing] {
        loop {
            let mut duplicates =
                matching_agent_session_tasks(&board_dir, status, session_id, task_identity)?;
            let Some(duplicate) = duplicates.pop() else {
                break;
            };
            remove_task_entry_without_reordering(&board_dir, status, &duplicate)?;
        }
    }
    Ok(true)
}

pub(super) fn worktree_completed_task_identity(
    project_root: &Path,
    session_id: &str,
) -> Result<Option<String>> {
    let Some((status, task)) =
        terminal_task_for_codex_session_in_board(&get_tasks_dir(project_root), session_id)?
    else {
        return Ok(None);
    };
    if status != TaskStatus::Done || !task_content_has_completed_note(&task.content) {
        return Ok(None);
    }
    Ok(durable_task_identity(&task.content))
}

pub(super) fn reconcile_agent_git_finalization(
    store: &agent::TursoAgentStore,
    project_root: &Path,
    mut finalization: agent::GitFinalizationRecord,
    owner_run_token: Option<&str>,
    finalization_lease: Option<&AgentGitFinalizationLease>,
) -> Result<agent::GitFinalizationRecord> {
    for _ in 0..6 {
        ensure_agent_git_finalization_fence(finalization_lease)?;
        let effective_owner = owner_run_token.or(finalization.owner_run_token.as_deref());
        match finalization.state {
            GitFinalizationState::Working => {
                if let Some(lease) = finalization_lease
                    && cancel_orphaned_working_git_finalization(
                        store,
                        project_root,
                        &finalization,
                        lease,
                    )?
                {
                    return store
                        .git_finalization_blocking(
                            finalization.project_id,
                            &finalization.codex_session_id,
                        )?
                        .context("Retired orphan Git journal disappeared");
                }
                let Some(task_identity) = finalization.task_identity.as_deref() else {
                    return Ok(finalization);
                };
                let baseline =
                    AgentGitWorktreeBaseline::from_json(&finalization.worktree_baseline)?;
                if baseline.version >= 2
                    && (baseline.staged_non_task_patch_ids.is_none()
                        || baseline.staged_index_tree.is_none()
                        || baseline.manifest_parent_head.is_none())
                {
                    return Ok(finalization);
                }
                if !worktree_contains_completed_done_task(
                    project_root,
                    &finalization.codex_session_id,
                )? || !agent_git_manifest_parent_is_current(project_root, &finalization)?
                {
                    return Ok(finalization);
                }
                ensure_agent_git_finalization_fence(finalization_lease)?;
                let changed = store.recover_git_finalization_intent_blocking(
                    finalization.project_id,
                    &finalization.codex_session_id,
                    finalization.generation,
                    task_identity,
                    effective_owner,
                    &agent_timestamp(),
                )?;
                if !changed {
                    finalization = store
                        .git_finalization_blocking(
                            finalization.project_id,
                            &finalization.codex_session_id,
                        )?
                        .context("Git journal disappeared during completion-intent recovery")?;
                    continue;
                }
            }
            GitFinalizationState::Tracking => {
                let Some(task_identity) = finalization.task_identity.as_deref() else {
                    return Ok(finalization);
                };
                if !agent_git_manifest_parent_is_current(project_root, &finalization)? {
                    return Ok(finalization);
                }
                ensure_agent_git_finalization_fence(finalization_lease)?;
                if !repair_tracking_agent_git_board(
                    project_root,
                    &finalization.codex_session_id,
                    task_identity,
                )? {
                    return Ok(finalization);
                }
                ensure_agent_git_finalization_fence(finalization_lease)?;
                if !worktree_contains_completed_done_task(
                    project_root,
                    &finalization.codex_session_id,
                )? {
                    return Ok(finalization);
                }
                ensure_agent_git_finalization_fence(finalization_lease)?;
                let changed = store.compare_and_set_git_finalization_blocking(
                    finalization.project_id,
                    &finalization.codex_session_id,
                    finalization.generation,
                    GitFinalizationState::CommitPending,
                    effective_owner,
                    None,
                    None,
                    &agent_timestamp(),
                )?;
                if !changed {
                    finalization = store
                        .git_finalization_blocking(
                            finalization.project_id,
                            &finalization.codex_session_id,
                        )?
                        .context("Git finalization disappeared during task-move reconciliation")?;
                    continue;
                }
            }
            GitFinalizationState::CommitPending => {
                let Some(starting_head) = finalization.starting_head.as_deref() else {
                    return Ok(finalization);
                };
                let Some(task_identity) = finalization.task_identity.as_deref() else {
                    return Ok(finalization);
                };
                let baseline =
                    AgentGitWorktreeBaseline::from_json(&finalization.worktree_baseline)?;
                let proof_start = if baseline.version >= 2 {
                    baseline
                        .manifest_parent_head
                        .as_deref()
                        .unwrap_or(starting_head)
                } else {
                    starting_head
                };
                let Some(commit_oid) = find_agent_git_task_commit_with_policy(
                    project_root,
                    proof_start,
                    finalization.branch_ref.as_deref(),
                    &finalization.codex_session_id,
                    task_identity,
                    baseline.version == 1,
                )?
                else {
                    return Ok(finalization);
                };
                if !git_commit_matches_agent_staged_manifest(
                    project_root,
                    &commit_oid,
                    &finalization.codex_session_id,
                    task_identity,
                    &finalization.worktree_baseline,
                    true,
                )? || !local_agent_git_task_commit_is_retained(
                    project_root,
                    finalization.branch_ref.as_deref(),
                    &commit_oid,
                    &finalization.codex_session_id,
                    task_identity,
                )? {
                    return Ok(finalization);
                }
                ensure_agent_git_finalization_fence(finalization_lease)?;
                let next_state = match finalization.git_mode {
                    AgentGitMode::Off => {
                        anyhow::bail!("Pending Git finalization unexpectedly has Git mode off")
                    }
                    AgentGitMode::Commit => GitFinalizationState::Completed,
                    AgentGitMode::CommitAndPush => GitFinalizationState::PushPending,
                };
                let changed = store.compare_and_set_git_finalization_blocking(
                    finalization.project_id,
                    &finalization.codex_session_id,
                    finalization.generation,
                    next_state,
                    effective_owner,
                    Some(&commit_oid),
                    None,
                    &agent_timestamp(),
                )?;
                if !changed {
                    finalization = store
                        .git_finalization_blocking(
                            finalization.project_id,
                            &finalization.codex_session_id,
                        )?
                        .context("Git finalization disappeared during commit reconciliation")?;
                    continue;
                }
            }
            GitFinalizationState::PushPending => {
                let Some(task_identity) = finalization.task_identity.as_deref() else {
                    return Ok(finalization);
                };
                let baseline =
                    AgentGitWorktreeBaseline::from_json(&finalization.worktree_baseline)?;
                let Some(local_commit_oid) = finalization.commit_oid.as_deref() else {
                    return Ok(finalization);
                };
                if !git_commit_matches_agent_staged_manifest(
                    project_root,
                    local_commit_oid,
                    &finalization.codex_session_id,
                    task_identity,
                    &finalization.worktree_baseline,
                    true,
                )? || !local_agent_git_task_commit_is_retained(
                    project_root,
                    finalization.branch_ref.as_deref(),
                    local_commit_oid,
                    &finalization.codex_session_id,
                    task_identity,
                )? {
                    return Ok(finalization);
                }
                let mut upstream_tip = fetch_agent_git_upstream_tip(
                    project_root,
                    finalization.branch_ref.as_deref(),
                    finalization.upstream_ref.as_deref(),
                    &baseline,
                    finalization_lease,
                )?;
                let already_published = match upstream_tip.as_deref() {
                    Some(upstream_tip) => agent_git_upstream_tip_proves_task_commit(
                        project_root,
                        upstream_tip,
                        local_commit_oid,
                        &finalization.codex_session_id,
                        task_identity,
                        baseline.version == 1,
                    )?,
                    None => false,
                };
                if !already_published {
                    push_agent_git_commit_to_frozen_destination(
                        project_root,
                        finalization.branch_ref.as_deref(),
                        finalization.upstream_ref.as_deref(),
                        &baseline,
                        local_commit_oid,
                        finalization_lease,
                    )?;
                    upstream_tip = fetch_agent_git_upstream_tip(
                        project_root,
                        finalization.branch_ref.as_deref(),
                        finalization.upstream_ref.as_deref(),
                        &baseline,
                        finalization_lease,
                    )?;
                }
                let Some(upstream_tip) = upstream_tip else {
                    return Ok(finalization);
                };
                if !agent_git_upstream_tip_proves_task_commit(
                    project_root,
                    &upstream_tip,
                    local_commit_oid,
                    &finalization.codex_session_id,
                    task_identity,
                    baseline.version == 1,
                )? || !local_agent_git_task_commit_is_retained(
                    project_root,
                    finalization.branch_ref.as_deref(),
                    local_commit_oid,
                    &finalization.codex_session_id,
                    task_identity,
                )? {
                    return Ok(finalization);
                }
                ensure_agent_git_finalization_fence(finalization_lease)?;
                let changed = store.compare_and_set_git_finalization_blocking(
                    finalization.project_id,
                    &finalization.codex_session_id,
                    finalization.generation,
                    GitFinalizationState::Completed,
                    effective_owner,
                    Some(local_commit_oid),
                    None,
                    &agent_timestamp(),
                )?;
                if !changed {
                    finalization = store
                        .git_finalization_blocking(
                            finalization.project_id,
                            &finalization.codex_session_id,
                        )?
                        .context("Git finalization disappeared during push reconciliation")?;
                    continue;
                }
            }
            GitFinalizationState::Completed | GitFinalizationState::Cancelled => {
                return Ok(finalization);
            }
        }

        finalization = store
            .git_finalization_blocking(finalization.project_id, &finalization.codex_session_id)?
            .context("Git finalization disappeared after a successful reconciliation step")?;
    }

    anyhow::bail!(
        "Git finalization for session {} changed too many times during reconciliation",
        finalization.codex_session_id
    )
}

pub(super) fn reconcile_pending_agent_git_finalizations(
    state_dir: &Path,
    project: &agent::AgentProject,
    finalization_lease: Option<&AgentGitFinalizationLease>,
) -> Result<Vec<agent::GitFinalizationRecord>> {
    let store = open_agent_store_at(state_dir)?;
    store
        .list_pending_git_finalizations_blocking(Some(project.id))?
        .into_iter()
        .map(|finalization| {
            reconcile_agent_git_finalization(
                &store,
                &project.path,
                finalization,
                None,
                finalization_lease,
            )
        })
        .collect()
}