batty-cli 0.11.63

Supervised agent execution for software teams
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
//! Task-loop helpers extracted from the team daemon.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

use anyhow::{Context, Result, bail};
use tracing::{debug, info, warn};

use super::git_cmd;
use super::retry::{RetryConfig, retry_sync};
use super::test_results::{self, TestRunOutput};

const SHARED_CARGO_CONFIG_MARKER: &str = "# Managed by Batty: shared cargo target";
const WORKTREE_EXCLUDE_MARKER: &str = "# Managed by Batty worktree ignores";

/// Resolve the default branch for a repo (mainline/main/master/trunk). Falls
/// back to "main" for legacy compatibility. Patched for Amazon GitFarm which
/// uses "mainline".
fn default_branch(repo: &Path) -> String {
    git_cmd::default_branch_name(repo).unwrap_or_else(|| "main".to_string())
}

fn effective_trunk_branch(repo: &Path, trunk_branch: &str) -> String {
    if trunk_branch == "main" {
        default_branch(repo)
    } else {
        trunk_branch.to_string()
    }
}

pub(crate) const ADDITIVE_CONFLICT_AUTO_RESOLVE_FENCE: &[&str] =
    &["src/team/task_loop.rs", "src/team/review.rs"];
const MIN_REVIEW_READY_PRODUCTION_ADDITIONS: usize = 10;
const USER_WORKTREE_STATUS_ARGS: &[&str] = &[
    "status",
    "--porcelain=v1",
    "--untracked-files=all",
    "--",
    ".",
    ":(exclude).batty",
    ":(exclude).cargo",
    ":(exclude).batty-target",
];
const PRESERVATION_UNSTAGE_ARGS: &[&str] =
    &["reset", "-q", "--", ".batty", ".cargo", ".batty-target"];

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum WorktreeRefreshAction {
    Unchanged,
    SkippedDirty,
    Rebased,
    Reset,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct WorktreeRefreshOutcome {
    pub(crate) action: WorktreeRefreshAction,
    pub(crate) behind_main: Option<u32>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct DiffStatEntry {
    pub(crate) path: String,
    pub(crate) additions: usize,
    pub(crate) deletions: usize,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct CommitValidationGate {
    pub(crate) blockers: Vec<String>,
}

#[cfg_attr(not(test), allow(dead_code))]
fn priority_rank(p: &str) -> u32 {
    match p {
        "critical" => 0,
        "high" => 1,
        "medium" => 2,
        "low" => 3,
        _ => 4,
    }
}

#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn next_unclaimed_task(board_dir: &Path) -> Result<Option<crate::task::Task>> {
    let tasks = crate::task::load_tasks_from_dir(&board_dir.join("tasks"))?;
    let task_status_by_id: HashMap<u32, String> = tasks
        .iter()
        .map(|task| (task.id, task.status.clone()))
        .collect();

    let mut available: Vec<crate::task::Task> = tasks
        .into_iter()
        .filter(|task| matches!(task.status.as_str(), "backlog" | "todo"))
        .filter(|task| task.claimed_by.is_none())
        .filter(|task| task.blocked.is_none())
        .filter(|task| task.blocked_on.is_none())
        .filter(|task| {
            task.depends_on.iter().all(|dep_id| {
                task_status_by_id
                    .get(dep_id)
                    .is_none_or(|status| status == "done")
            })
        })
        .collect();

    available.sort_by_key(|task| (priority_rank(&task.priority), task.id));
    Ok(available.into_iter().next())
}

pub(crate) fn run_tests_in_worktree(
    worktree_dir: &Path,
    test_command: Option<&str>,
) -> Result<TestRunOutput> {
    let command_text = test_command.unwrap_or("cargo test");
    let mut command = std::process::Command::new("sh");
    let cargo_home = engineer_worktree_project_root(worktree_dir)
        .map(|project_root| project_root.join(".batty").join("cargo-home"))
        .unwrap_or_else(|| worktree_dir.join(".batty").join("cargo-home"));
    std::fs::create_dir_all(&cargo_home)
        .with_context(|| format!("failed to create {}", cargo_home.display()))?;
    // Use `sh -c` (not `sh -lc`): a login shell re-sources profile files and
    // can drop ~/.cargo/bin from PATH on some macOS environments (notably
    // GitHub's hosted runners), causing `cargo` lookups to fail. Plain
    // `sh -c` inherits the parent's PATH unchanged, which is what we want
    // both in production (daemon PATH carries rustup) and in tests.
    command
        .arg("-c")
        .arg(command_text)
        .current_dir(worktree_dir);
    command.env("CARGO_HOME", &cargo_home);
    if let Some(project_root) = engineer_worktree_project_root(worktree_dir) {
        let wt_name = worktree_dir
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| "default".to_string());
        command.env(
            "CARGO_TARGET_DIR",
            shared_cargo_target_dir(&project_root).join(&wt_name),
        );
    }
    let output = command.output().with_context(|| {
        format!(
            "failed while running `{command_text}` in engineer worktree {}",
            worktree_dir.display(),
        )
    })?;

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    let mut combined = String::new();
    combined.push_str(&stdout);
    if !stdout.is_empty() && !stderr.is_empty() && !stdout.ends_with('\n') {
        combined.push('\n');
    }
    combined.push_str(&stderr);

    let lines: Vec<&str> = combined.lines().collect();
    let trimmed = if lines.len() > 50 {
        lines[lines.len() - 50..].join("\n")
    } else {
        combined
    };

    let passed = output.status.success();
    Ok(TestRunOutput {
        passed,
        results: test_results::parse(command_text, &trimmed, passed),
        output: trimmed,
    })
}

pub(crate) fn shared_cargo_target_dir(project_root: &Path) -> PathBuf {
    project_root.join(".batty").join("shared-target")
}

pub(crate) fn validate_review_ready_worktree(
    worktree_dir: &Path,
    task_text: &str,
) -> Result<Vec<String>> {
    let diff = map_git_error(
        retry_git(|| git_cmd::run_git(worktree_dir, &["diff", "--stat", "main..HEAD"])),
        "failed to inspect engineer branch diff",
    )?;
    let declared_scope = crate::team::daemon::verification::parse_scope_fence(task_text);
    Ok(validate_review_ready_diff_stat_with_scope(&diff.stdout, &declared_scope).blockers)
}

#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn validate_review_ready_diff_stat(diff_stat: &str) -> CommitValidationGate {
    validate_review_ready_diff_stat_with_scope(diff_stat, &[])
}

fn validate_review_ready_diff_stat_with_scope(
    diff_stat: &str,
    declared_scope: &[String],
) -> CommitValidationGate {
    let entries = parse_diff_stat_entries(diff_stat);
    let mut blockers = Vec::new();

    if entries.is_empty() {
        blockers.push("engineer branch has no diff against main".to_string());
        return CommitValidationGate { blockers };
    }

    let out_of_scope = if declared_scope.is_empty() {
        Vec::new()
    } else {
        entries
            .iter()
            .filter(|entry| !path_within_declared_scope(&entry.path, declared_scope))
            .map(|entry| entry.path.clone())
            .collect::<Vec<_>>()
    };
    if !out_of_scope.is_empty() {
        blockers.push(format!(
            "changes outside task scope fence: {}",
            out_of_scope.join(", ")
        ));
    }

    let production_entries = entries
        .iter()
        .filter(|entry| {
            entry.path.ends_with(".rs")
                && (declared_scope.is_empty()
                    || path_within_declared_scope(&entry.path, declared_scope))
        })
        .collect::<Vec<_>>();
    let production_additions: usize = production_entries.iter().map(|entry| entry.additions).sum();
    let production_deletions: usize = production_entries.iter().map(|entry| entry.deletions).sum();

    if production_additions < MIN_REVIEW_READY_PRODUCTION_ADDITIONS {
        blockers.push(format!(
            "need at least {MIN_REVIEW_READY_PRODUCTION_ADDITIONS} lines of production Rust added; found {production_additions}"
        ));
    }
    if production_deletions > production_additions {
        blockers.push(format!(
            "production Rust diff is net-destructive ({production_additions} additions, {production_deletions} deletions)"
        ));
    }

    CommitValidationGate { blockers }
}

fn path_within_declared_scope(path: &str, scope_entries: &[String]) -> bool {
    scope_entries.iter().any(|scope| {
        path == scope
            || path
                .strip_prefix(scope)
                .is_some_and(|rest| rest.starts_with('/'))
    })
}

fn parse_diff_stat_entries(diff_stat: &str) -> Vec<DiffStatEntry> {
    diff_stat
        .lines()
        .filter_map(|line| {
            let (path, summary) = line.split_once('|')?;
            let path = path.trim();
            if path.is_empty() {
                return None;
            }

            let additions = summary.chars().filter(|ch| *ch == '+').count();
            let deletions = summary.chars().filter(|ch| *ch == '-').count();
            Some(DiffStatEntry {
                path: path.to_string(),
                additions,
                deletions,
            })
        })
        .collect()
}

fn retry_git<T, F>(operation: F) -> std::result::Result<T, git_cmd::GitError>
where
    F: Fn() -> std::result::Result<T, git_cmd::GitError>,
{
    retry_sync(&RetryConfig::fast(), operation)
}

fn map_git_error<T>(result: std::result::Result<T, git_cmd::GitError>, action: &str) -> Result<T> {
    result.map_err(|error| anyhow::anyhow!("{action}: {error}"))
}

pub(crate) fn read_task_title(board_dir: &Path, task_id: u32) -> String {
    let tasks_dir = board_dir.join("tasks");
    let prefix = format!("{task_id:03}-");
    if let Ok(entries) = std::fs::read_dir(&tasks_dir) {
        for entry in entries.flatten() {
            let name = entry.file_name().to_string_lossy().to_string();
            if name.starts_with(&prefix)
                && name.ends_with(".md")
                && let Ok(content) = std::fs::read_to_string(entry.path())
            {
                for line in content.lines() {
                    if line.starts_with("title:") {
                        return line
                            .trim_start_matches("title:")
                            .trim()
                            .trim_matches(|c| c == '"' || c == '\'')
                            .to_string();
                    }
                }
            }
        }
    }
    format!("Task #{task_id}")
}

/// Set up a git worktree for an engineer with symlinked shared config.
pub(crate) fn setup_engineer_worktree(
    project_root: &Path,
    worktree_dir: &Path,
    branch_name: &str,
    team_config_dir: &Path,
) -> Result<PathBuf> {
    setup_engineer_worktree_from_trunk(
        project_root,
        worktree_dir,
        branch_name,
        team_config_dir,
        "main",
    )
}

pub(crate) fn setup_engineer_worktree_from_trunk(
    project_root: &Path,
    worktree_dir: &Path,
    branch_name: &str,
    team_config_dir: &Path,
    trunk_branch: &str,
) -> Result<PathBuf> {
    if let Some(parent) = worktree_dir.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }

    if !worktree_dir.exists() {
        let path = worktree_dir.to_string_lossy().to_string();
        let start_point = effective_trunk_branch(project_root, trunk_branch);
        match retry_git(|| {
            git_cmd::worktree_add(project_root, worktree_dir, branch_name, &start_point)
        }) {
            Ok(_) => {}
            Err(git_cmd::GitError::Permanent { stderr, .. })
                if stderr.contains("already exists") =>
            {
                map_git_error(
                    retry_git(|| {
                        git_cmd::run_git(project_root, &["worktree", "add", &path, branch_name])
                    }),
                    "failed to create git worktree",
                )?;
            }
            Err(error) => {
                return Err(anyhow::anyhow!("failed to create git worktree: {error}"));
            }
        }

        info!(worktree = %worktree_dir.display(), branch = branch_name, "created engineer worktree");
    }

    ensure_engineer_worktree_links(worktree_dir, team_config_dir)?;
    ensure_shared_cargo_target_config(project_root, worktree_dir)?;
    ensure_engineer_worktree_excludes(worktree_dir)?;

    Ok(worktree_dir.to_path_buf())
}

#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn prepare_engineer_assignment_worktree(
    project_root: &Path,
    worktree_dir: &Path,
    engineer_name: &str,
    task_branch: &str,
    team_config_dir: &Path,
) -> Result<PathBuf> {
    prepare_engineer_assignment_worktree_from_trunk(
        project_root,
        worktree_dir,
        engineer_name,
        task_branch,
        team_config_dir,
        "main",
    )
}

pub(crate) fn prepare_engineer_assignment_worktree_from_trunk(
    project_root: &Path,
    worktree_dir: &Path,
    engineer_name: &str,
    task_branch: &str,
    team_config_dir: &Path,
    trunk_branch: &str,
) -> Result<PathBuf> {
    let base_branch = engineer_base_branch_name(engineer_name);
    ensure_engineer_worktree_health(project_root, worktree_dir, &base_branch)?;
    setup_engineer_worktree_from_trunk(
        project_root,
        worktree_dir,
        &base_branch,
        team_config_dir,
        trunk_branch,
    )?;
    maybe_migrate_legacy_engineer_worktree(
        project_root,
        worktree_dir,
        engineer_name,
        &base_branch,
        trunk_branch,
    )?;
    ensure_task_branch_namespace_available(project_root, engineer_name, trunk_branch)?;

    if worktree_has_user_changes(worktree_dir)? {
        auto_clean_worktree(worktree_dir)?;
    }

    let previous_branch = current_worktree_branch(worktree_dir)?;
    let previous_branch_is_engineer_owned = previous_branch == engineer_name
        || previous_branch.starts_with(&format!("{engineer_name}/"));
    if previous_branch != base_branch
        && previous_branch != task_branch
        && !previous_branch_is_engineer_owned
        && !branch_is_merged_into(
            project_root,
            &previous_branch,
            &effective_trunk_branch(project_root, trunk_branch),
        )?
    {
        bail!(
            "engineer worktree '{}' is on unmerged branch '{}'",
            engineer_name,
            previous_branch
        );
    }

    checkout_worktree_branch_from_trunk(worktree_dir, &base_branch, trunk_branch)?;

    checkout_worktree_branch_from_trunk(worktree_dir, task_branch, trunk_branch)?;
    ensure_engineer_worktree_links(worktree_dir, team_config_dir)?;

    if previous_branch != base_branch
        && previous_branch != task_branch
        && previous_branch_is_engineer_owned
        && branch_is_merged_into(
            project_root,
            &previous_branch,
            &effective_trunk_branch(project_root, trunk_branch),
        )?
    {
        delete_branch(project_root, &previous_branch)?;
    }

    crate::team::checkpoint::remove_preserved_lane_record(project_root, engineer_name);

    Ok(worktree_dir.to_path_buf())
}

/// Set up worktrees for a multi-repo project. Creates one git worktree per
/// sub-repo inside `worktree_dir`, mirroring the original directory layout.
#[allow(dead_code)]
pub(crate) fn setup_multi_repo_worktree(
    project_root: &Path,
    worktree_dir: &Path,
    branch_name: &str,
    team_config_dir: &Path,
    sub_repo_names: &[String],
) -> Result<PathBuf> {
    setup_multi_repo_worktree_from_trunk(
        project_root,
        worktree_dir,
        branch_name,
        team_config_dir,
        sub_repo_names,
        "main",
    )
}

pub(crate) fn setup_multi_repo_worktree_from_trunk(
    project_root: &Path,
    worktree_dir: &Path,
    branch_name: &str,
    team_config_dir: &Path,
    sub_repo_names: &[String],
    trunk_branch: &str,
) -> Result<PathBuf> {
    std::fs::create_dir_all(worktree_dir)
        .with_context(|| format!("failed to create {}", worktree_dir.display()))?;

    for repo_name in sub_repo_names {
        let repo_root = project_root.join(repo_name);
        let sub_wt = worktree_dir.join(repo_name);
        setup_engineer_worktree_from_trunk(
            &repo_root,
            &sub_wt,
            branch_name,
            team_config_dir,
            trunk_branch,
        )?;
    }

    ensure_engineer_worktree_links(worktree_dir, team_config_dir)?;
    Ok(worktree_dir.to_path_buf())
}

/// Prepare worktrees for a multi-repo task assignment. Creates task branches
/// in every sub-repo so the engineer can work across all of them.
#[allow(dead_code)]
pub(crate) fn prepare_multi_repo_assignment_worktree(
    project_root: &Path,
    worktree_dir: &Path,
    engineer_name: &str,
    task_branch: &str,
    team_config_dir: &Path,
    sub_repo_names: &[String],
) -> Result<PathBuf> {
    prepare_multi_repo_assignment_worktree_from_trunk(
        project_root,
        worktree_dir,
        engineer_name,
        task_branch,
        team_config_dir,
        sub_repo_names,
        "main",
    )
}

pub(crate) fn prepare_multi_repo_assignment_worktree_from_trunk(
    project_root: &Path,
    worktree_dir: &Path,
    engineer_name: &str,
    task_branch: &str,
    team_config_dir: &Path,
    sub_repo_names: &[String],
    trunk_branch: &str,
) -> Result<PathBuf> {
    std::fs::create_dir_all(worktree_dir)
        .with_context(|| format!("failed to create {}", worktree_dir.display()))?;

    for repo_name in sub_repo_names {
        let repo_root = project_root.join(repo_name);
        let sub_wt = worktree_dir.join(repo_name);
        prepare_engineer_assignment_worktree_from_trunk(
            &repo_root,
            &sub_wt,
            engineer_name,
            task_branch,
            team_config_dir,
            trunk_branch,
        )?;
    }

    ensure_engineer_worktree_links(worktree_dir, team_config_dir)?;
    Ok(worktree_dir.to_path_buf())
}

pub(crate) fn worktree_commits_behind_main(worktree_dir: &Path) -> Result<u32> {
    worktree_commits_behind_trunk(worktree_dir, "main")
}

pub(crate) fn worktree_commits_behind_trunk(
    worktree_dir: &Path,
    trunk_branch: &str,
) -> Result<u32> {
    // Multi-repo mode: aggregate staleness as the MAX behind-count across sub-repos.
    if !git_cmd::is_git_repo(worktree_dir) {
        let sub_repos = git_cmd::discover_sub_repos(worktree_dir);
        if !sub_repos.is_empty() {
            let mut max_behind: u32 = 0;
            for repo in sub_repos {
                let default = effective_trunk_branch(&repo, trunk_branch);
                let behind = map_git_error(
                    retry_git(|| git_cmd::rev_list_count(&repo, &format!("HEAD..{default}"))),
                    &format!("failed to measure sub-repo worktree staleness against {default}"),
                )?;
                if behind > max_behind {
                    max_behind = behind;
                }
            }
            return Ok(max_behind);
        }
    }
    let default = effective_trunk_branch(worktree_dir, trunk_branch);
    map_git_error(
        retry_git(|| git_cmd::rev_list_count(worktree_dir, &format!("HEAD..{default}"))),
        &format!("failed to measure worktree staleness against {default}"),
    )
}

#[allow(dead_code)]
pub(crate) fn refresh_engineer_worktree_if_stale(
    project_root: &Path,
    worktree_dir: &Path,
    branch_name: &str,
    team_config_dir: &Path,
    stale_threshold: u32,
) -> Result<WorktreeRefreshOutcome> {
    refresh_engineer_worktree_if_stale_from_trunk(
        project_root,
        worktree_dir,
        branch_name,
        team_config_dir,
        stale_threshold,
        "main",
    )
}

pub(crate) fn refresh_engineer_worktree_if_stale_from_trunk(
    project_root: &Path,
    worktree_dir: &Path,
    branch_name: &str,
    team_config_dir: &Path,
    stale_threshold: u32,
    trunk_branch: &str,
) -> Result<WorktreeRefreshOutcome> {
    if !worktree_dir.exists() {
        return Ok(WorktreeRefreshOutcome {
            action: WorktreeRefreshAction::Unchanged,
            behind_main: None,
        });
    }

    let behind_main = Some(worktree_commits_behind_trunk(worktree_dir, trunk_branch)?);
    if behind_main.is_none_or(|count| count <= stale_threshold) {
        return Ok(WorktreeRefreshOutcome {
            action: WorktreeRefreshAction::Unchanged,
            behind_main,
        });
    }

    let action = refresh_engineer_worktree_from_trunk(
        project_root,
        worktree_dir,
        branch_name,
        team_config_dir,
        trunk_branch,
    )?;
    Ok(WorktreeRefreshOutcome {
        action,
        behind_main,
    })
}

fn ensure_engineer_worktree_health(
    project_root: &Path,
    worktree_dir: &Path,
    _base_branch: &str,
) -> Result<()> {
    if !worktree_dir.exists() {
        return Ok(());
    }

    if !worktree_registered(project_root, worktree_dir)? {
        bail!(
            "engineer worktree path exists but is not registered in git worktree list: {}",
            worktree_dir.display()
        );
    }

    Ok(())
}

#[allow(dead_code)] // Retained for existing tests and as a lower-level helper.
pub(crate) fn refresh_engineer_worktree(
    project_root: &Path,
    worktree_dir: &Path,
    branch_name: &str,
    team_config_dir: &Path,
) -> Result<WorktreeRefreshAction> {
    refresh_engineer_worktree_from_trunk(
        project_root,
        worktree_dir,
        branch_name,
        team_config_dir,
        "main",
    )
}

pub(crate) fn refresh_engineer_worktree_from_trunk(
    project_root: &Path,
    worktree_dir: &Path,
    branch_name: &str,
    team_config_dir: &Path,
    trunk_branch: &str,
) -> Result<WorktreeRefreshAction> {
    if !worktree_dir.exists() {
        return Ok(WorktreeRefreshAction::Unchanged);
    }

    if worktree_has_user_changes(worktree_dir)? {
        warn!(
            worktree = %worktree_dir.display(),
            branch = branch_name,
            "skipping worktree refresh because worktree is dirty"
        );
        return Ok(WorktreeRefreshAction::SkippedDirty);
    }

    if map_git_error(
        retry_git(|| {
            git_cmd::merge_base_is_ancestor(
                project_root,
                &effective_trunk_branch(project_root, trunk_branch),
                branch_name,
            )
        }),
        &format!("failed to compare worktree branch with {trunk_branch}"),
    )? {
        return Ok(WorktreeRefreshAction::Unchanged);
    }

    let rebase_target = effective_trunk_branch(worktree_dir, trunk_branch);
    let rebase_result = retry_git(|| git_cmd::rebase(worktree_dir, &rebase_target));
    if rebase_result.is_ok() {
        info!(
            worktree = %worktree_dir.display(),
            branch = branch_name,
            "refreshed engineer worktree"
        );
        return Ok(WorktreeRefreshAction::Rebased);
    }

    let stderr = match rebase_result {
        Ok(_) => unreachable!("successful rebase returned early"),
        Err(git_cmd::GitError::Transient { stderr, .. })
        | Err(git_cmd::GitError::Permanent { stderr, .. })
        | Err(git_cmd::GitError::RebaseFailed { stderr, .. })
        | Err(git_cmd::GitError::MergeFailed { stderr, .. }) => stderr.trim().to_string(),
        Err(git_cmd::GitError::RevParseFailed { stderr, .. }) => stderr.trim().to_string(),
        Err(git_cmd::GitError::InvalidRevListCount { output, .. }) => output.trim().to_string(),
        Err(git_cmd::GitError::Exec { source, .. }) => source.to_string(),
    };
    let _ = retry_git(|| git_cmd::rebase_abort(worktree_dir));

    if !is_worktree_safe_to_mutate(worktree_dir)? {
        bail!(
            "worktree at {} has uncommitted changes on a task branch after failed rebase — refusing to destroy. Commit or stash first.",
            worktree_dir.display()
        );
    }

    map_git_error(
        retry_git(|| git_cmd::worktree_remove(project_root, worktree_dir, true)),
        &format!("failed to remove conflicted worktree after rebase error '{stderr}'"),
    )?;

    map_git_error(
        retry_git(|| git_cmd::branch_delete(project_root, branch_name)),
        &format!("failed to delete conflicted worktree branch after rebase error '{stderr}'"),
    )?;

    warn!(
        worktree = %worktree_dir.display(),
        branch = branch_name,
        rebase_error = %stderr,
        "recreating engineer worktree after rebase conflict"
    );
    setup_engineer_worktree_from_trunk(
        project_root,
        worktree_dir,
        branch_name,
        team_config_dir,
        trunk_branch,
    )?;
    Ok(WorktreeRefreshAction::Reset)
}

pub(crate) fn engineer_base_branch_name(engineer_name: &str) -> String {
    format!("eng-main/{engineer_name}")
}

fn maybe_migrate_legacy_engineer_worktree(
    project_root: &Path,
    worktree_dir: &Path,
    engineer_name: &str,
    base_branch: &str,
    trunk_branch: &str,
) -> Result<()> {
    if !worktree_dir.exists() {
        return Ok(());
    }

    let current_branch = current_worktree_branch(worktree_dir)?;
    if current_branch != engineer_name {
        return Ok(());
    }

    if worktree_has_user_changes(worktree_dir)? {
        bail!(
            "legacy engineer branch '{}' is still checked out in {} with uncommitted changes; resolve it before assigning a new task branch",
            engineer_name,
            worktree_dir.display()
        );
    }

    checkout_worktree_branch_from_trunk(worktree_dir, base_branch, trunk_branch)?;
    if branch_is_merged_into(
        project_root,
        engineer_name,
        &effective_trunk_branch(project_root, trunk_branch),
    )? {
        delete_branch(project_root, engineer_name)?;
        info!(
            branch = engineer_name,
            base_branch,
            worktree = %worktree_dir.display(),
            "auto-migrated legacy engineer worktree to base branch"
        );
        return Ok(());
    }

    let archive_branch = archived_legacy_branch_name(project_root, engineer_name)?;
    rename_branch(project_root, engineer_name, &archive_branch)?;
    warn!(
        old_branch = engineer_name,
        new_branch = %archive_branch,
        base_branch,
        worktree = %worktree_dir.display(),
        "auto-migrated unmerged legacy engineer worktree to base branch"
    );
    Ok(())
}

fn ensure_task_branch_namespace_available(
    project_root: &Path,
    engineer_name: &str,
    trunk_branch: &str,
) -> Result<()> {
    if !branch_exists(project_root, engineer_name)? {
        return Ok(());
    }

    if branch_is_checked_out_in_any_worktree(project_root, engineer_name)? {
        bail!(
            "legacy engineer branch '{}' is still checked out in a worktree; resolve it before assigning a new task branch",
            engineer_name
        );
    }

    if branch_is_merged_into(
        project_root,
        engineer_name,
        &effective_trunk_branch(project_root, trunk_branch),
    )? {
        delete_branch(project_root, engineer_name)?;
        info!(
            branch = engineer_name,
            "deleted merged legacy engineer branch to free task namespace"
        );
        return Ok(());
    }

    let archive_branch = archived_legacy_branch_name(project_root, engineer_name)?;
    rename_branch(project_root, engineer_name, &archive_branch)?;
    warn!(
        old_branch = engineer_name,
        new_branch = %archive_branch,
        "archived legacy engineer branch to free task namespace"
    );
    Ok(())
}

fn ensure_engineer_worktree_links(worktree_dir: &Path, team_config_dir: &Path) -> Result<()> {
    let wt_batty_dir = worktree_dir.join(".batty");
    std::fs::create_dir_all(&wt_batty_dir).ok();
    let wt_config_link = wt_batty_dir.join("team_config");

    if !wt_config_link.exists() {
        #[cfg(unix)]
        std::os::unix::fs::symlink(team_config_dir, &wt_config_link).with_context(|| {
            format!(
                "failed to symlink {} -> {}",
                wt_config_link.display(),
                team_config_dir.display()
            )
        })?;

        #[cfg(not(unix))]
        {
            warn!("symlinks not supported on this platform, copying config instead");
            let _ = std::fs::create_dir_all(&wt_config_link);
        }

        debug!(
            link = %wt_config_link.display(),
            target = %team_config_dir.display(),
            "symlinked team config into worktree"
        );
    }

    Ok(())
}

fn ensure_shared_cargo_target_config(project_root: &Path, worktree_dir: &Path) -> Result<()> {
    // Each worktree gets its own target subdirectory so parallel builds
    // don't contend on the same Cargo lock. The shared parent is kept for
    // disk-pressure cleanup scans.
    let worktree_name = worktree_dir
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| "default".to_string());
    let target_dir = shared_cargo_target_dir(project_root).join(&worktree_name);
    std::fs::create_dir_all(&target_dir)
        .with_context(|| format!("failed to create {}", target_dir.display()))?;

    let config_rel_path = Path::new(".cargo").join("config.toml");
    if worktree_relative_path_is_tracked(worktree_dir, &config_rel_path)? {
        // .cargo/config.toml must NOT be tracked — it contains worktree-specific
        // target-dir paths that pollute other worktrees on rebase.  Untrack it.
        warn!(
            config = %worktree_dir.join(&config_rel_path).display(),
            "untracking .cargo/config.toml — worktree-specific file must not be in git"
        );
        let _ =
            run_git_command_with_fallback(worktree_dir, &["rm", "--cached", ".cargo/config.toml"]);
        // Remove the stale file so the managed config gets written below.
        let _ = std::fs::remove_file(worktree_dir.join(&config_rel_path));
    }

    let cargo_dir = worktree_dir.join(".cargo");
    std::fs::create_dir_all(&cargo_dir)
        .with_context(|| format!("failed to create {}", cargo_dir.display()))?;
    let config_path = cargo_dir.join("config.toml");

    let managed = format!(
        "{SHARED_CARGO_CONFIG_MARKER}\n[build]\ntarget-dir = {:?}\n",
        target_dir
    );

    match std::fs::read_to_string(&config_path) {
        Ok(existing) if existing == managed => return Ok(()),
        Ok(existing) if !existing.is_empty() && !existing.contains(SHARED_CARGO_CONFIG_MARKER) => {
            warn!(
                config = %config_path.display(),
                "leaving existing cargo config unchanged; shared target must be configured manually"
            );
            return Ok(());
        }
        Ok(_) | Err(_) => {}
    }

    std::fs::write(&config_path, managed)
        .with_context(|| format!("failed to write {}", config_path.display()))?;
    Ok(())
}

fn worktree_relative_path_is_tracked(worktree_dir: &Path, rel_path: &Path) -> Result<bool> {
    let rel_path_text = rel_path.to_string_lossy().into_owned();
    let output = run_git_command_with_fallback(
        worktree_dir,
        &["ls-files", "--error-unmatch", &rel_path_text],
    )
    .with_context(|| {
        format!(
            "failed to check whether {} is tracked in {}",
            rel_path.display(),
            worktree_dir.display()
        )
    })?;

    Ok(output.status.success())
}

fn ensure_engineer_worktree_excludes(worktree_dir: &Path) -> Result<()> {
    let output = run_git_command_with_fallback(worktree_dir, &["rev-parse", "--git-dir"])
        .with_context(|| format!("failed to resolve git dir for {}", worktree_dir.display()))?;
    if !output.status.success() {
        bail!(
            "failed to resolve git dir for {}: {}",
            worktree_dir.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }

    let git_dir_text = String::from_utf8_lossy(&output.stdout).trim().to_string();
    let git_dir = if Path::new(&git_dir_text).is_absolute() {
        PathBuf::from(git_dir_text)
    } else {
        worktree_dir.join(git_dir_text)
    };
    let exclude_path = git_dir.join("info").join("exclude");
    if let Some(parent) = exclude_path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }

    let mut content = std::fs::read_to_string(&exclude_path).unwrap_or_default();
    if !content.contains(WORKTREE_EXCLUDE_MARKER) {
        if !content.is_empty() && !content.ends_with('\n') {
            content.push('\n');
        }
        content.push_str(WORKTREE_EXCLUDE_MARKER);
        content.push('\n');
    }

    for rule in [".cargo/", ".cargo/config.toml", ".batty/team_config"] {
        if !content.lines().any(|line| line.trim() == rule) {
            content.push_str(rule);
            content.push('\n');
        }
    }

    std::fs::write(&exclude_path, content)
        .with_context(|| format!("failed to write {}", exclude_path.display()))?;
    Ok(())
}

fn run_git_command_with_fallback(
    worktree_dir: &Path,
    args: &[&str],
) -> std::io::Result<std::process::Output> {
    let mut last_not_found = None;
    for program in ["git", "/usr/bin/git", "/opt/homebrew/bin/git"] {
        match Command::new(program)
            .args(args)
            .current_dir(worktree_dir)
            .output()
        {
            Ok(output) => return Ok(output),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                last_not_found = Some(error);
            }
            Err(error) => return Err(error),
        }
    }

    Err(last_not_found.unwrap_or_else(|| {
        std::io::Error::new(std::io::ErrorKind::NotFound, "git binary not found")
    }))
}

fn engineer_worktree_project_root(worktree_dir: &Path) -> Option<PathBuf> {
    for ancestor in worktree_dir.ancestors() {
        if ancestor.file_name().is_some_and(|name| name == "worktrees")
            && ancestor
                .parent()
                .and_then(Path::file_name)
                .is_some_and(|name| name == ".batty")
        {
            return ancestor
                .parent()
                .and_then(Path::parent)
                .map(Path::to_path_buf);
        }
    }
    None
}

pub(crate) fn worktree_has_user_changes(worktree_dir: &Path) -> Result<bool> {
    Ok(!current_worktree_user_change_paths(worktree_dir)?.is_empty())
}

pub(crate) fn current_worktree_user_change_paths(worktree_dir: &Path) -> Result<Vec<String>> {
    // Multi-repo mode: worktree root isn't a git repo itself, it holds per-package
    // git worktrees underneath. Iterate sub-repos and aggregate (mirrors preflight.rs
    // and discover_sub_repos elsewhere). Single-repo path unchanged.
    if !git_cmd::is_git_repo(worktree_dir) {
        let sub_repos = git_cmd::discover_sub_repos(worktree_dir);
        if sub_repos.is_empty() {
            // Not a git repo and no git sub-repos — nothing we can inspect.
            // Fall through to single-repo path to surface the original error.
        } else {
            let mut aggregated = Vec::new();
            for repo in sub_repos {
                let status = map_git_error(
                    retry_git(|| {
                        git_cmd::run_git(&repo, USER_WORKTREE_STATUS_ARGS)
                            .map(|output| output.stdout)
                    }),
                    "failed to inspect sub-repo worktree status",
                )?;
                let repo_name = repo
                    .file_name()
                    .map(|n| n.to_string_lossy().into_owned())
                    .unwrap_or_default();
                for path in parse_status_paths(&status) {
                    if repo_name.is_empty() {
                        aggregated.push(path);
                    } else {
                        aggregated.push(format!("{repo_name}/{path}"));
                    }
                }
            }
            return Ok(aggregated);
        }
    }
    let status = map_git_error(
        retry_git(|| {
            git_cmd::run_git(worktree_dir, USER_WORKTREE_STATUS_ARGS).map(|output| output.stdout)
        }),
        "failed to inspect worktree status",
    )?;
    Ok(parse_status_paths(&status))
}

pub(crate) fn current_staged_change_paths(worktree_dir: &Path) -> Result<Vec<String>> {
    let output = map_git_error(
        retry_git(|| git_cmd::run_git(worktree_dir, &["diff", "--cached", "--name-only"])),
        "failed to inspect staged worktree changes",
    )?;
    Ok(output
        .stdout
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .map(ToOwned::to_owned)
        .collect())
}

fn parse_status_paths(status: &str) -> Vec<String> {
    status
        .lines()
        .filter_map(|line| {
            if line.len() < 4 {
                return None;
            }
            let path = line[3..].trim();
            (!path.is_empty()).then(|| path.to_string())
        })
        .collect()
}

pub(crate) fn log_worktree_mutation_audit(
    worktree_dir: &Path,
    subsystem: &str,
    operation: &str,
    files: &[String],
) {
    let branch = crate::worktree::git_current_branch(worktree_dir)
        .unwrap_or_else(|_| "<detached-or-unavailable>".to_string());
    let file_summary = if files.is_empty() {
        "<none>".to_string()
    } else {
        files.join(", ")
    };
    info!(
        subsystem,
        operation,
        cwd = %worktree_dir.display(),
        branch,
        files = %file_summary,
        "worktree mutation audit"
    );
}

fn rollback_newly_staged_paths(
    worktree_dir: &Path,
    original_staged_paths: &HashSet<String>,
    subsystem: &str,
) {
    let rollback_paths = match current_staged_change_paths(worktree_dir) {
        Ok(paths) => paths
            .into_iter()
            .filter(|path| !original_staged_paths.contains(path))
            .collect::<Vec<_>>(),
        Err(error) => {
            warn!(
                subsystem,
                cwd = %worktree_dir.display(),
                error = %error,
                "failed to inspect staged paths while rolling back preservation staging"
            );
            return;
        }
    };

    if rollback_paths.is_empty() {
        return;
    }

    log_worktree_mutation_audit(worktree_dir, subsystem, "git reset -q --", &rollback_paths);
    let mut last_not_found = None;
    for program in ["git", "/usr/bin/git", "/opt/homebrew/bin/git"] {
        let output = Command::new(program)
            .arg("-C")
            .arg(worktree_dir)
            .args(["reset", "-q", "--"])
            .args(&rollback_paths)
            .output();
        match output {
            Ok(output) if output.status.success() => return,
            Ok(output) => {
                warn!(
                    subsystem,
                    cwd = %worktree_dir.display(),
                    stderr = %String::from_utf8_lossy(&output.stderr).trim(),
                    "failed to roll back newly staged paths after preserve failure"
                );
                return;
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                last_not_found = Some(error);
            }
            Err(error) => {
                warn!(
                    subsystem,
                    cwd = %worktree_dir.display(),
                    error = %error,
                    "failed to launch git while rolling back preservation staging"
                );
                return;
            }
        }
    }

    if let Some(error) = last_not_found {
        warn!(
            subsystem,
            cwd = %worktree_dir.display(),
            error = %error,
            "git binary unavailable while rolling back preservation staging"
        );
    }
}

pub(crate) fn git_has_unresolved_conflicts(repo_dir: &Path) -> Result<bool> {
    let status = map_git_error(
        retry_git(|| git_cmd::status_porcelain(repo_dir)),
        "failed to inspect git conflict state",
    )?;
    Ok(status.lines().any(line_has_unresolved_conflict))
}

fn line_has_unresolved_conflict(line: &str) -> bool {
    let bytes = line.as_bytes();
    bytes.len() >= 2
        && matches!(
            (bytes[0], bytes[1]),
            (b'U', _) | (_, b'U') | (b'A', b'A') | (b'D', b'D')
        )
}

pub(crate) fn merge_additive_only_text(
    base: &str,
    current: &str,
    incoming: &str,
) -> Option<String> {
    let base_lines = split_lines_preserving_endings(base);
    let current_slots = insertion_slots_relative_to_base(&base_lines, current)?;
    let incoming_slots = insertion_slots_relative_to_base(&base_lines, incoming)?;
    let mut merged = String::new();

    for (index, base_line) in base_lines.iter().enumerate() {
        append_slot(&mut merged, &current_slots[index], &incoming_slots[index]);
        merged.push_str(base_line);
    }
    append_slot(
        &mut merged,
        &current_slots[base_lines.len()],
        &incoming_slots[base_lines.len()],
    );

    Some(merged)
}

fn split_lines_preserving_endings(text: &str) -> Vec<&str> {
    if text.is_empty() {
        Vec::new()
    } else {
        text.split_inclusive('\n').collect()
    }
}

fn insertion_slots_relative_to_base<'a>(
    base_lines: &[&str],
    variant: &'a str,
) -> Option<Vec<Vec<&'a str>>> {
    let variant_lines = split_lines_preserving_endings(variant);
    let mut slots = vec![Vec::new(); base_lines.len() + 1];
    let mut variant_index = 0usize;

    for (base_index, base_line) in base_lines.iter().enumerate() {
        while variant_index < variant_lines.len() && variant_lines[variant_index] != *base_line {
            slots[base_index].push(variant_lines[variant_index]);
            variant_index += 1;
        }
        if variant_index == variant_lines.len() {
            return None;
        }
        variant_index += 1;
    }

    while variant_index < variant_lines.len() {
        slots[base_lines.len()].push(variant_lines[variant_index]);
        variant_index += 1;
    }

    Some(slots)
}

fn append_slot(output: &mut String, current_slot: &[&str], incoming_slot: &[&str]) {
    for line in current_slot {
        output.push_str(line);
    }
    if current_slot != incoming_slot {
        for line in incoming_slot {
            output.push_str(line);
        }
    }
}

/// Returns `false` if the worktree has uncommitted changes on a task branch
/// (i.e. not an `eng-main/*` base branch). This gate should be checked before
/// any operation that would destroy worktree state (reset, clean, checkout).
pub(crate) fn is_worktree_safe_to_mutate(worktree_dir: &Path) -> Result<bool> {
    if !worktree_dir.exists() {
        return Ok(true);
    }

    let has_changes = worktree_has_user_changes(worktree_dir)?;
    if !has_changes {
        return Ok(true);
    }

    let branch = match map_git_error(
        retry_git(|| git_cmd::rev_parse_branch(worktree_dir)),
        "failed to determine worktree branch for safety check",
    ) {
        Ok(b) => b,
        Err(_) => return Ok(true), // Can't determine branch — allow mutation
    };

    // eng-main/* branches are base branches with no user work worth preserving.
    if branch.starts_with("eng-main/") {
        return Ok(true);
    }

    // Task branch with uncommitted changes — NOT safe to mutate.
    warn!(
        worktree = %worktree_dir.display(),
        branch = %branch,
        "worktree has uncommitted changes on task branch, refusing to mutate"
    );
    Ok(false)
}

fn run_git_with_timeout(worktree_dir: &Path, args: &[&str], timeout: Duration) -> Result<()> {
    let mut last_not_found = None;
    let mut child = None;
    for program in ["git", "/usr/bin/git", "/opt/homebrew/bin/git"] {
        let mut command = Command::new(program);
        command.arg("-C").arg(worktree_dir).args(args);
        // Pipe stderr so we can surface it in error messages. Without this,
        // failures like `git add -A -- . :(exclude).batty :(exclude).cargo`
        // just say "exit status: 1" with no reason, making preserve-worktree
        // bugs impossible to diagnose from daemon logs alone. Stdout goes to
        // /dev/null because we never consume it in this helper.
        command
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::piped());
        #[cfg(unix)]
        {
            use std::os::unix::process::CommandExt;
            command.process_group(0);
        }
        match command.spawn() {
            Ok(process) => {
                child = Some(process);
                break;
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                last_not_found = Some(error);
            }
            Err(error) => {
                return Err(error).with_context(|| {
                    format!(
                        "failed to launch `git {}` in {}",
                        args.join(" "),
                        worktree_dir.display()
                    )
                });
            }
        }
    }
    let mut child = child
        .ok_or_else(|| {
            last_not_found.unwrap_or_else(|| {
                std::io::Error::new(std::io::ErrorKind::NotFound, "git binary not found")
            })
        })
        .with_context(|| {
            format!(
                "failed to launch `git {}` in {}",
                args.join(" "),
                worktree_dir.display()
            )
        })?;

    let deadline = Instant::now() + timeout;
    loop {
        if let Some(status) = child.try_wait()? {
            if status.success() {
                // Drain stderr so the pipe closes cleanly; discard contents.
                if let Some(mut err) = child.stderr.take() {
                    let mut sink = Vec::new();
                    let _ = std::io::Read::read_to_end(&mut err, &mut sink);
                }
                return Ok(());
            }
            let mut stderr_buf = Vec::new();
            if let Some(mut err) = child.stderr.take() {
                let _ = std::io::Read::read_to_end(&mut err, &mut stderr_buf);
            }
            let stderr = String::from_utf8_lossy(&stderr_buf);
            let stderr_trimmed = stderr.trim();
            if stderr_trimmed.is_empty() {
                bail!(
                    "`git {}` failed in {} with status {}",
                    args.join(" "),
                    worktree_dir.display(),
                    status
                );
            } else {
                bail!(
                    "`git {}` failed in {} with status {}: {}",
                    args.join(" "),
                    worktree_dir.display(),
                    status,
                    stderr_trimmed
                );
            }
        }

        if Instant::now() >= deadline {
            terminate_process_tree(&mut child);
            let _ = child.wait();
            bail!(
                "`git {}` timed out after {}s in {}",
                args.join(" "),
                timeout.as_secs(),
                worktree_dir.display()
            );
        }

        std::thread::sleep(Duration::from_millis(50));
    }
}

#[cfg(unix)]
fn terminate_process_tree(child: &mut std::process::Child) {
    let _ = unsafe { libc::kill(-(child.id() as libc::pid_t), libc::SIGKILL) };
}

#[cfg(not(unix))]
fn terminate_process_tree(child: &mut std::process::Child) {
    let _ = child.kill();
}

#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn preserve_worktree_with_commit(
    worktree_dir: &Path,
    commit_message: &str,
    timeout: Duration,
) -> Result<bool> {
    preserve_worktree_with_commit_for(worktree_dir, commit_message, timeout, "task-loop/preserve")
}

pub(crate) fn preserve_worktree_with_commit_for(
    worktree_dir: &Path,
    commit_message: &str,
    timeout: Duration,
    subsystem: &str,
) -> Result<bool> {
    let dirty_paths = current_worktree_user_change_paths(worktree_dir)?;
    if dirty_paths.is_empty() {
        return Ok(false);
    }

    // Stage from the repository root, then unstage Batty-managed runtime dirs.
    // Explicit `:(exclude)` pathspecs against ignored dirs can make `git add`
    // fail before it stages the real user changes we need to preserve.
    let original_staged_paths = current_staged_change_paths(worktree_dir)?
        .into_iter()
        .collect::<HashSet<_>>();
    let preserve_result = (|| -> Result<bool> {
        log_worktree_mutation_audit(worktree_dir, subsystem, "git add -A", &dirty_paths);
        run_git_with_timeout(worktree_dir, &["add", "-A"], timeout)?;
        run_git_with_timeout(worktree_dir, PRESERVATION_UNSTAGE_ARGS, timeout)?;

        let staged_paths = current_staged_change_paths(worktree_dir)?;
        if staged_paths.is_empty() {
            return Ok(false);
        }

        log_worktree_mutation_audit(worktree_dir, subsystem, "git commit", &staged_paths);
        run_git_with_timeout(
            worktree_dir,
            &[
                "-c",
                "commit.gpgSign=false",
                "-c",
                "core.hooksPath=/dev/null",
                "commit",
                "-m",
                commit_message,
            ],
            timeout,
        )?;
        Ok(true)
    })();

    if preserve_result.is_err() {
        rollback_newly_staged_paths(worktree_dir, &original_staged_paths, subsystem);
    }

    preserve_result
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn quarantine_completed_lane_for_recovery(
    project_root: &Path,
    worktree_dir: &Path,
    engineer_name: &str,
    task: &crate::task::Task,
    current_branch: &str,
    reason: &str,
    team_config_dir: &Path,
    timeout: Duration,
) -> Result<Option<crate::team::checkpoint::PreservedLaneRecord>> {
    let base_branch = engineer_base_branch_name(engineer_name);
    if !worktree_has_user_changes(worktree_dir)? {
        let reset_reason = crate::worktree::reset_worktree_to_base_with_options_for(
            worktree_dir,
            &base_branch,
            &format!("wip: preserve completed task #{} before recovery", task.id),
            timeout,
            crate::worktree::PreserveFailureMode::SkipReset,
            "completed-task branch recovery",
        )?;
        if !reset_reason.reset_performed() {
            bail!(
                "{}",
                dirty_worktree_preservation_blocked_reason(
                    worktree_dir,
                    "completed-task branch recovery"
                )
            );
        }
        return Ok(None);
    }

    let source_head = git_cmd::run_git(worktree_dir, &["rev-parse", "HEAD"])
        .ok()
        .map(|output| output.stdout.trim().to_string())
        .filter(|value| !value.is_empty());
    let commit_message = format!(
        "wip: preserve completed task #{} before branch recovery [{}]",
        task.id, current_branch
    );

    match preserve_worktree_with_commit_for(
        worktree_dir,
        &commit_message,
        timeout,
        "completed-task branch recovery",
    ) {
        Ok(true) => {
            let preserved_commit = git_cmd::run_git(worktree_dir, &["rev-parse", "HEAD"])
                .map_err(|error| anyhow::anyhow!("failed to read preservation commit: {error}"))?
                .stdout
                .trim()
                .to_string();
            let record = crate::team::checkpoint::PreservedLaneRecord::commit(
                engineer_name,
                task,
                current_branch,
                &base_branch,
                reason,
                source_head,
                preserved_commit,
            );
            crate::team::checkpoint::write_preserved_lane_record(project_root, &record)?;

            let reset_reason = crate::worktree::reset_worktree_to_base_with_options_for(
                worktree_dir,
                &base_branch,
                &commit_message,
                timeout,
                crate::worktree::PreserveFailureMode::SkipReset,
                "completed-task branch recovery",
            )?;
            if !reset_reason.reset_performed() {
                bail!(
                    "{}",
                    dirty_worktree_preservation_blocked_reason(
                        worktree_dir,
                        "completed-task branch recovery"
                    )
                );
            }

            Ok(Some(record))
        }
        Ok(false) => Ok(None),
        Err(commit_error) => {
            let snapshot_path = crate::team::checkpoint::write_dirty_lane_snapshot(
                project_root,
                worktree_dir,
                engineer_name,
                task,
                current_branch,
                &base_branch,
                reason,
                source_head.as_deref(),
            )
            .map_err(|snapshot_error| {
                anyhow::anyhow!(
                    "failed to preserve completed task #{} dirty lane: commit preservation failed ({commit_error}); snapshot fallback failed ({snapshot_error})",
                    task.id
                )
            })?;
            let snapshot_relative = snapshot_path
                .strip_prefix(project_root)
                .unwrap_or(&snapshot_path)
                .display()
                .to_string();
            let record = crate::team::checkpoint::PreservedLaneRecord::snapshot(
                engineer_name,
                task,
                current_branch,
                &base_branch,
                reason,
                source_head,
                snapshot_relative.clone(),
            );
            crate::team::checkpoint::write_preserved_lane_record(project_root, &record)?;

            map_git_error(
                retry_git(|| git_cmd::worktree_remove(project_root, worktree_dir, true)),
                &format!(
                    "failed to remove preserved completed lane worktree after writing snapshot '{}'",
                    snapshot_relative
                ),
            )?;
            setup_engineer_worktree(project_root, worktree_dir, &base_branch, team_config_dir)
                .with_context(|| {
                    format!(
                        "failed to recreate clean engineer worktree after saving completed lane snapshot '{}'",
                        snapshot_relative
                    )
                })?;

            Ok(Some(record))
        }
    }
}

pub(crate) fn dirty_worktree_preservation_blocked_reason(
    worktree_dir: &Path,
    context: &str,
) -> String {
    format!(
        "Batty could not safely auto-save dirty worktree {} before {context}. Commit or clean the lane manually.",
        worktree_dir.display()
    )
}

fn auto_clean_worktree(worktree_dir: &Path) -> Result<()> {
    let branch = retry_git(|| git_cmd::rev_parse_branch(worktree_dir)).unwrap_or_default();
    let message = format!("wip: auto-save before worktree reset [{branch}]");
    let reason = crate::worktree::prepare_worktree_for_reset(
        worktree_dir,
        &message,
        Duration::from_secs(5),
        crate::worktree::PreserveFailureMode::SkipReset,
        "dispatch/reset recovery",
    )?;
    if reason == crate::worktree::WorktreeResetReason::PreserveFailedResetSkipped {
        bail!(
            "{}",
            dirty_worktree_preservation_blocked_reason(worktree_dir, "dispatch/reset recovery")
        );
    }
    info!(
        worktree = %worktree_dir.display(),
        reset_reason = reason.as_str(),
        "prepared engineer worktree for reset"
    );

    if worktree_has_user_changes(worktree_dir)? {
        bail!(
            "engineer worktree at {} still dirty after auto-clean",
            worktree_dir.display()
        );
    }
    Ok(())
}

/// Auto-commit uncommitted changes before a worktree reset to avoid stash
/// accumulation. Returns `true` if changes were successfully committed or
/// there was nothing to commit.
///
/// Kept as a stable wrapper for the common-case reset flow; production code
/// currently uses `preserve_worktree_with_commit` directly with custom
/// messages. Test-only `dead_code` allow keeps the wrapper exercised via
/// its tests without generating a build warning.
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn auto_commit_before_reset(worktree_dir: &Path) -> bool {
    let branch = retry_git(|| git_cmd::rev_parse_branch(worktree_dir)).unwrap_or_default();
    let msg = format!("wip: auto-save before worktree reset [{}]", branch);
    match preserve_worktree_with_commit_for(
        worktree_dir,
        &msg,
        Duration::from_secs(5),
        "auto-clean before reset",
    ) {
        Ok(true) => {
            info!(
                worktree = %worktree_dir.display(),
                branch = %branch,
                "auto-committed uncommitted changes before worktree reset"
            );
            true
        }
        Ok(false) => true,
        Err(e) => {
            warn!(
                worktree = %worktree_dir.display(),
                error = %e,
                "auto-commit failed"
            );
            false
        }
    }
}

pub(crate) fn current_worktree_branch(worktree_dir: &Path) -> Result<String> {
    map_git_error(
        retry_git(|| git_cmd::rev_parse_branch(worktree_dir)),
        "failed to determine worktree branch",
    )
}

#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn checkout_worktree_branch_from_main(
    worktree_dir: &Path,
    branch_name: &str,
) -> Result<()> {
    checkout_worktree_branch_from_trunk(worktree_dir, branch_name, "main")
}

pub(crate) fn checkout_worktree_branch_from_trunk(
    worktree_dir: &Path,
    branch_name: &str,
    trunk_branch: &str,
) -> Result<()> {
    let start = effective_trunk_branch(worktree_dir, trunk_branch);
    map_git_error(
        retry_git(|| git_cmd::checkout_new_branch(worktree_dir, branch_name, &start)),
        &format!("failed to switch worktree to branch '{branch_name}'"),
    )
}

fn branch_exists(project_root: &Path, branch_name: &str) -> Result<bool> {
    map_git_error(
        retry_git(|| git_cmd::show_ref_exists(project_root, branch_name)),
        &format!("failed to check whether branch '{branch_name}' exists"),
    )
}

fn worktree_registered(project_root: &Path, worktree_dir: &Path) -> Result<bool> {
    let output = map_git_error(
        retry_git(|| git_cmd::worktree_list(project_root)),
        "failed to list git worktrees",
    )?;
    let target = worktree_dir
        .canonicalize()
        .unwrap_or_else(|_| worktree_dir.to_path_buf());

    for line in output.lines() {
        let Some(candidate) = line.strip_prefix("worktree ") else {
            continue;
        };
        let candidate = PathBuf::from(candidate.trim());
        let candidate = candidate.canonicalize().unwrap_or(candidate);
        if candidate == target {
            return Ok(true);
        }
    }

    Ok(false)
}

fn branch_is_checked_out_in_any_worktree(project_root: &Path, branch_name: &str) -> Result<bool> {
    let output = map_git_error(
        retry_git(|| git_cmd::worktree_list(project_root)),
        "failed to list git worktrees",
    )?;
    let target = format!("branch refs/heads/{branch_name}");
    Ok(output.lines().any(|line| line.trim() == target))
}

pub(crate) fn branch_is_merged_into(
    project_root: &Path,
    branch_name: &str,
    base_branch: &str,
) -> Result<bool> {
    map_git_error(
        retry_git(|| git_cmd::merge_base_is_ancestor(project_root, branch_name, base_branch)),
        &format!("failed to compare branch '{branch_name}' with '{base_branch}'"),
    )
}

#[allow(dead_code)]
pub(crate) fn engineer_worktree_ready_for_dispatch(
    project_root: &Path,
    worktree_dir: &Path,
    engineer_name: &str,
) -> Result<()> {
    engineer_worktree_ready_for_dispatch_from_trunk(
        project_root,
        worktree_dir,
        engineer_name,
        "main",
    )
}

pub(crate) fn engineer_worktree_ready_for_dispatch_from_trunk(
    project_root: &Path,
    worktree_dir: &Path,
    engineer_name: &str,
    trunk_branch: &str,
) -> Result<()> {
    if !worktree_dir.exists() {
        return Ok(());
    }

    if !worktree_registered(project_root, worktree_dir)? {
        bail!(
            "engineer worktree path exists but is not registered in git worktree list: {}",
            worktree_dir.display()
        );
    }

    let base_branch = engineer_base_branch_name(engineer_name);
    let current_branch = current_worktree_branch(worktree_dir)?;
    if current_branch != base_branch {
        bail!(
            "engineer worktree '{}' is checked out on '{}' instead of '{}'",
            engineer_name,
            current_branch,
            base_branch
        );
    }

    if worktree_has_user_changes(worktree_dir)? {
        bail!(
            "engineer worktree '{}' has uncommitted changes",
            engineer_name
        );
    }

    let ahead_of_main = map_git_error(
        retry_git(|| git_cmd::rev_list_count(worktree_dir, &format!("{trunk_branch}..HEAD"))),
        &format!("failed to compare worktree against {trunk_branch}"),
    )?;
    let behind_main = map_git_error(
        retry_git(|| git_cmd::rev_list_count(worktree_dir, &format!("HEAD..{trunk_branch}"))),
        &format!("failed to compare worktree against {trunk_branch}"),
    )?;
    if ahead_of_main != 0 || behind_main != 0 {
        bail!(
            "engineer worktree '{}' is not based on current {} (ahead {}, behind {})",
            engineer_name,
            trunk_branch,
            ahead_of_main,
            behind_main
        );
    }

    Ok(())
}

pub(crate) fn delete_branch(project_root: &Path, branch_name: &str) -> Result<()> {
    map_git_error(
        retry_git(|| git_cmd::branch_delete(project_root, branch_name)),
        &format!("failed to delete branch '{branch_name}'"),
    )
}

fn archived_legacy_branch_name(project_root: &Path, engineer_name: &str) -> Result<String> {
    let short_sha = map_git_error(
        retry_git(|| git_cmd::run_git(project_root, &["rev-parse", "--short", engineer_name])),
        &format!("failed to resolve legacy branch '{engineer_name}'"),
    )?
    .stdout
    .trim()
    .to_string();
    let mut candidate = format!("legacy/{engineer_name}-{short_sha}");
    let mut counter = 1usize;
    while branch_exists(project_root, &candidate)? {
        counter += 1;
        candidate = format!("legacy/{engineer_name}-{short_sha}-{counter}");
    }
    Ok(candidate)
}

fn rename_branch(project_root: &Path, old_branch: &str, new_branch: &str) -> Result<()> {
    map_git_error(
        retry_git(|| git_cmd::branch_rename(project_root, old_branch, new_branch)),
        &format!("failed to rename branch '{old_branch}' to '{new_branch}'"),
    )
}

/// Recycle done cron tasks back to todo when their next occurrence is due.
///
/// Returns a list of (task_id, cron_expression) for each recycled task.
pub(crate) fn recycle_cron_tasks(board_dir: &Path) -> Result<Vec<(u32, String)>> {
    use chrono::Utc;
    use cron::Schedule;
    use serde_yaml::Value;
    use std::str::FromStr;

    use super::task_cmd::{
        StatusTransitionAttribution, find_task_path, record_status_transition_activity,
        set_optional_string, update_task_frontmatter, yaml_key,
    };

    let tasks_dir = board_dir.join("tasks");
    let tasks = crate::task::load_tasks_from_dir(&tasks_dir)
        .with_context(|| format!("failed to load tasks from {}", tasks_dir.display()))?;

    let now = Utc::now();
    let mut recycled = Vec::new();

    for task in &tasks {
        // Skip non-done tasks
        if task.status != "done" {
            continue;
        }

        // Skip tasks without a cron schedule
        let cron_expr = match &task.cron_schedule {
            Some(expr) => expr.clone(),
            None => continue,
        };

        // Skip archived tasks
        if task.tags.iter().any(|t| t == "archived") {
            continue;
        }

        // Parse the cron expression
        let schedule = match Schedule::from_str(&cron_expr) {
            Ok(s) => s,
            Err(err) => {
                warn!(task_id = task.id, cron = %cron_expr, error = %err, "invalid cron expression, skipping");
                continue;
            }
        };

        // Determine the reference point: cron_last_run or now - 1 day
        let reference = task
            .cron_last_run
            .as_deref()
            .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
            .map(|dt| dt.with_timezone(&Utc))
            .unwrap_or_else(|| now - chrono::Duration::days(1));

        // Find next occurrence after reference
        let next = match schedule.after(&reference).next() {
            Some(dt) => dt,
            None => continue,
        };

        // If next occurrence is in the future, skip
        if next > now {
            continue;
        }

        // Compute next FUTURE occurrence for scheduled_for
        let next_future = schedule.after(&now).next().map(|dt| dt.to_rfc3339());

        let now_str = now.to_rfc3339();
        let task_id = task.id;
        let task_path = find_task_path(board_dir, task_id)?;

        update_task_frontmatter(&task_path, |mapping| {
            // Set status to todo
            mapping.insert(yaml_key("status"), Value::String("todo".to_string()));

            // Update scheduled_for to next future occurrence
            set_optional_string(mapping, "scheduled_for", next_future.as_deref());

            // Update cron_last_run to now
            set_optional_string(mapping, "cron_last_run", Some(&now_str));

            // Clear transient fields
            mapping.remove(yaml_key("claimed_by"));
            mapping.remove(yaml_key("branch"));
            mapping.remove(yaml_key("commit"));
            mapping.remove(yaml_key("artifacts"));
            mapping.remove(yaml_key("next_action"));
            mapping.remove(yaml_key("review_owner"));
            mapping.remove(yaml_key("blocked_on"));
            mapping.remove(yaml_key("worktree_path"));
        })?;
        record_status_transition_activity(
            board_dir,
            task_id,
            &task.status,
            "todo",
            &StatusTransitionAttribution::daemon("daemon.task_loop.cron_recycle"),
        )?;

        info!(task_id, cron = %cron_expr, "recycled cron task back to todo");
        recycled.push((task_id, cron_expr));
    }

    Ok(recycled)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::team::test_support::{EnvVarGuard, PATH_LOCK, git, git_ok, git_stdout};
    use std::sync::MutexGuard;

    fn git_binary_path() -> Option<&'static str> {
        ["git", "/usr/bin/git", "/opt/homebrew/bin/git"]
            .into_iter()
            .find(|program| Command::new(program).arg("--version").output().is_ok())
    }

    fn git_binary_available() -> bool {
        git_binary_path().is_some()
    }

    fn git_test_guard() -> Option<MutexGuard<'static, ()>> {
        let guard = PATH_LOCK.lock().unwrap_or_else(|error| error.into_inner());
        if git_binary_available() {
            Some(guard)
        } else {
            eprintln!("skipping git-dependent task_loop test: git binary unavailable");
            None
        }
    }

    fn production_unwrap_expect_count(path: &Path) -> usize {
        let content = std::fs::read_to_string(path).unwrap();
        let test_split = content.split("\n#[cfg(test)]").next().unwrap_or(&content);
        test_split
            .lines()
            .filter(|line| line.contains(".unwrap(") || line.contains(".expect("))
            .count()
    }

    fn init_git_repo(tmp: &tempfile::TempDir) -> PathBuf {
        let repo = tmp.path();
        git_ok(repo, &["init", "-b", "main"]);
        git_ok(repo, &["config", "user.email", "batty-test@example.com"]);
        git_ok(repo, &["config", "user.name", "Batty Test"]);
        std::fs::create_dir_all(repo.join(".batty").join("team_config")).unwrap();
        std::fs::write(repo.join("README.md"), "initial\n").unwrap();
        git_ok(repo, &["add", "README.md", ".batty/team_config"]);
        git_ok(repo, &["commit", "-m", "initial"]);
        repo.to_path_buf()
    }

    fn write_task_file(
        dir: &Path,
        id: u32,
        title: &str,
        status: &str,
        priority: &str,
        claimed_by: Option<&str>,
        depends_on: &[u32],
    ) {
        let tasks_dir = dir.join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();
        let mut content =
            format!("---\nid: {id}\ntitle: {title}\nstatus: {status}\npriority: {priority}\n");
        if let Some(cb) = claimed_by {
            content.push_str(&format!("claimed_by: {cb}\n"));
        }
        if !depends_on.is_empty() {
            content.push_str("depends_on:\n");
            for dep in depends_on {
                content.push_str(&format!("    - {dep}\n"));
            }
        }
        content.push_str("class: standard\n---\n\nTask description.\n");
        std::fs::write(tasks_dir.join(format!("{id:03}-{title}.md")), content).unwrap();
    }

    fn write_task_file_with_workflow_frontmatter(
        dir: &Path,
        id: u32,
        title: &str,
        extra_frontmatter: &str,
    ) {
        let tasks_dir = dir.join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();
        std::fs::write(
            tasks_dir.join(format!("{id:03}-{title}.md")),
            format!(
                "---\nid: {id}\ntitle: {title}\nstatus: todo\npriority: critical\n{extra_frontmatter}class: standard\n---\n\nTask description.\n"
            ),
        )
        .unwrap();
    }

    #[test]
    fn test_refresh_worktree_rebases_behind_main() {
        let Some(_path_lock) = git_test_guard() else {
            return;
        };
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let worktree_dir = repo.join(".batty").join("worktrees").join("eng-1");
        let team_config_dir = repo.join(".batty").join("team_config");

        setup_engineer_worktree(&repo, &worktree_dir, "eng-1", &team_config_dir).unwrap();

        std::fs::write(repo.join("main.txt"), "new main content\n").unwrap();
        git_ok(&repo, &["add", "main.txt"]);
        git_ok(&repo, &["commit", "-m", "advance main"]);

        refresh_engineer_worktree(&repo, &worktree_dir, "eng-1", &team_config_dir).unwrap();

        assert!(worktree_dir.join("main.txt").exists());
        assert_eq!(
            git_stdout(&repo, &["rev-parse", "main"]),
            git_stdout(&worktree_dir, &["rev-parse", "HEAD"])
        );
    }

    #[test]
    fn test_refresh_worktree_recreates_on_conflict() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let worktree_dir = repo.join(".batty").join("worktrees").join("eng-2");
        let team_config_dir = repo.join(".batty").join("team_config");

        std::fs::write(repo.join("file.txt"), "A\n").unwrap();
        git_ok(&repo, &["add", "file.txt"]);
        git_ok(&repo, &["commit", "-m", "add file"]);

        setup_engineer_worktree(&repo, &worktree_dir, "eng-2", &team_config_dir).unwrap();

        std::fs::write(worktree_dir.join("file.txt"), "B\n").unwrap();
        git_ok(&worktree_dir, &["add", "file.txt"]);
        git_ok(&worktree_dir, &["commit", "-m", "engineer change"]);

        std::fs::write(repo.join("file.txt"), "C\n").unwrap();
        git_ok(&repo, &["add", "file.txt"]);
        git_ok(&repo, &["commit", "-m", "main change"]);

        refresh_engineer_worktree(&repo, &worktree_dir, "eng-2", &team_config_dir).unwrap();

        assert!(worktree_dir.exists());
        assert_eq!(
            std::fs::read_to_string(worktree_dir.join("file.txt")).unwrap(),
            "C\n"
        );
        assert_eq!(
            git_stdout(&repo, &["rev-parse", "main"]),
            git_stdout(&worktree_dir, &["rev-parse", "HEAD"])
        );
    }

    #[test]
    fn test_refresh_worktree_skips_dirty() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let worktree_dir = repo.join(".batty").join("worktrees").join("eng-3");
        let team_config_dir = repo.join(".batty").join("team_config");

        setup_engineer_worktree(&repo, &worktree_dir, "eng-3", &team_config_dir).unwrap();
        std::fs::write(worktree_dir.join("scratch.txt"), "uncommitted\n").unwrap();

        std::fs::write(repo.join("main.txt"), "new main content\n").unwrap();
        git_ok(&repo, &["add", "main.txt"]);
        git_ok(&repo, &["commit", "-m", "advance main"]);

        refresh_engineer_worktree(&repo, &worktree_dir, "eng-3", &team_config_dir).unwrap();

        assert!(!worktree_dir.join("main.txt").exists());
        assert_eq!(
            std::fs::read_to_string(worktree_dir.join("scratch.txt")).unwrap(),
            "uncommitted\n"
        );
    }

    #[test]
    fn test_refresh_worktree_noop_when_current() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let worktree_dir = repo.join(".batty").join("worktrees").join("eng-4");
        let team_config_dir = repo.join(".batty").join("team_config");

        setup_engineer_worktree(&repo, &worktree_dir, "eng-4", &team_config_dir).unwrap();
        let before = git_stdout(&worktree_dir, &["rev-parse", "HEAD"]);

        refresh_engineer_worktree(&repo, &worktree_dir, "eng-4", &team_config_dir).unwrap();

        let after = git_stdout(&worktree_dir, &["rev-parse", "HEAD"]);
        assert_eq!(before, after);
        assert!(worktree_dir.exists());
    }

    #[test]
    fn test_prepare_assignment_worktree_checks_out_task_branch_from_main() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let worktree_dir = repo.join(".batty").join("worktrees").join("eng-5");
        let team_config_dir = repo.join(".batty").join("team_config");

        prepare_engineer_assignment_worktree(
            &repo,
            &worktree_dir,
            "eng-5",
            "eng-5/123",
            &team_config_dir,
        )
        .unwrap();

        assert_eq!(
            git_stdout(&worktree_dir, &["rev-parse", "--abbrev-ref", "HEAD"]),
            "eng-5/123"
        );
        assert_eq!(
            git_stdout(&repo, &["rev-parse", "main"]),
            git_stdout(&worktree_dir, &["rev-parse", "HEAD"])
        );
        assert!(worktree_dir.join(".batty").join("team_config").exists());
    }

    #[test]
    fn test_prepare_assignment_worktree_recreates_stale_task_branch_from_current_main() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let worktree_dir = repo.join(".batty").join("worktrees").join("eng-5b");
        let team_config_dir = repo.join(".batty").join("team_config");

        prepare_engineer_assignment_worktree(
            &repo,
            &worktree_dir,
            "eng-5b",
            "eng-5b/123",
            &team_config_dir,
        )
        .unwrap();
        let stale_commit = git_stdout(&repo, &["rev-parse", "eng-5b/123"]);

        git_ok(&repo, &["checkout", "main"]);
        std::fs::write(repo.join("fresh.txt"), "fresh main content\n").unwrap();
        git_ok(&repo, &["add", "fresh.txt"]);
        git_ok(&repo, &["commit", "-m", "advance main"]);
        let current_main = git_stdout(&repo, &["rev-parse", "main"]);

        prepare_engineer_assignment_worktree(
            &repo,
            &worktree_dir,
            "eng-5b",
            "eng-5b/123",
            &team_config_dir,
        )
        .unwrap();

        assert_ne!(stale_commit, current_main);
        assert_eq!(
            git_stdout(&repo, &["rev-parse", "eng-5b/123"]),
            current_main
        );
        assert_eq!(
            git_stdout(&worktree_dir, &["rev-parse", "HEAD"]),
            current_main
        );
        assert_eq!(
            git_stdout(&worktree_dir, &["rev-parse", "--abbrev-ref", "HEAD"]),
            "eng-5b/123"
        );
    }

    #[test]
    fn test_prepare_assignment_worktree_resets_mismatched_engineer_task_branch() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let worktree_dir = repo.join(".batty").join("worktrees").join("eng-5c");
        let team_config_dir = repo.join(".batty").join("team_config");

        setup_engineer_worktree(
            &repo,
            &worktree_dir,
            &engineer_base_branch_name("eng-5c"),
            &team_config_dir,
        )
        .unwrap();

        git_ok(&worktree_dir, &["checkout", "-B", "eng-5c/300"]);
        std::fs::write(worktree_dir.join("stale.txt"), "stale work\n").unwrap();
        git_ok(&worktree_dir, &["add", "stale.txt"]);
        git_ok(&worktree_dir, &["commit", "-m", "stale task work"]);

        git_ok(&repo, &["checkout", "main"]);
        std::fs::write(repo.join("fresh.txt"), "fresh main content\n").unwrap();
        git_ok(&repo, &["add", "fresh.txt"]);
        git_ok(&repo, &["commit", "-m", "advance main"]);

        prepare_engineer_assignment_worktree(
            &repo,
            &worktree_dir,
            "eng-5c",
            "eng-5c/301",
            &team_config_dir,
        )
        .unwrap();

        assert_eq!(
            git_stdout(&worktree_dir, &["rev-parse", "--abbrev-ref", "HEAD"]),
            "eng-5c/301"
        );
        assert_eq!(
            git_stdout(&worktree_dir, &["rev-parse", "HEAD"]),
            git_stdout(&repo, &["rev-parse", "main"])
        );
        assert!(!worktree_dir.join("stale.txt").exists());
    }

    #[test]
    fn test_setup_engineer_worktree_writes_shared_cargo_target_config() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let worktree_dir = repo.join(".batty").join("worktrees").join("eng-shared");
        let team_config_dir = repo.join(".batty").join("team_config");

        setup_engineer_worktree(&repo, &worktree_dir, "eng-shared", &team_config_dir).unwrap();

        let config =
            std::fs::read_to_string(worktree_dir.join(".cargo").join("config.toml")).unwrap();
        assert!(config.contains(SHARED_CARGO_CONFIG_MARKER));
        assert!(config.contains(shared_cargo_target_dir(&repo).to_string_lossy().as_ref()));
    }

    #[test]
    fn test_setup_engineer_worktree_preserves_existing_cargo_config() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let worktree_dir = repo.join(".batty").join("worktrees").join("eng-preserve");
        let team_config_dir = repo.join(".batty").join("team_config");

        setup_engineer_worktree(&repo, &worktree_dir, "eng-preserve", &team_config_dir).unwrap();
        let config_path = worktree_dir.join(".cargo").join("config.toml");
        std::fs::write(&config_path, "[term]\nverbose = true\n").unwrap();

        setup_engineer_worktree(&repo, &worktree_dir, "eng-preserve", &team_config_dir).unwrap();

        assert_eq!(
            std::fs::read_to_string(config_path).unwrap(),
            "[term]\nverbose = true\n"
        );
    }

    #[test]
    fn test_setup_engineer_worktree_untracks_cargo_config_and_writes_managed() {
        let Some(_guard) = git_test_guard() else {
            return;
        };

        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let team_config_dir = repo.join(".batty").join("team_config");

        // Simulate the pollution scenario: .cargo/config.toml committed to git
        std::fs::create_dir_all(repo.join(".cargo")).unwrap();
        std::fs::write(
            repo.join(".cargo").join("config.toml"),
            "[alias]\nxtask = \"run\"\n",
        )
        .unwrap();
        git_ok(&repo, &["add", ".cargo/config.toml"]);
        git_ok(&repo, &["commit", "-m", "track cargo config"]);

        let worktree_dir = repo
            .join(".batty")
            .join("worktrees")
            .join("eng-tracked-config");
        setup_engineer_worktree(&repo, &worktree_dir, "eng-tracked-config", &team_config_dir)
            .unwrap();

        // After setup, the file should contain managed config (not the old alias)
        let config =
            std::fs::read_to_string(worktree_dir.join(".cargo").join("config.toml")).unwrap();
        assert!(
            config.contains(SHARED_CARGO_CONFIG_MARKER),
            "cargo config should be managed after untracking: {config}"
        );
        assert!(
            !config.contains("[alias]"),
            "old tracked content should be replaced with managed config"
        );
    }

    #[test]
    fn test_setup_engineer_worktree_excludes_cargo_config_toml() {
        let Some(_guard) = git_test_guard() else {
            return;
        };

        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let team_config_dir = repo.join(".batty").join("team_config");
        let worktree_dir = repo
            .join(".batty")
            .join("worktrees")
            .join("eng-exclude-test");

        setup_engineer_worktree(&repo, &worktree_dir, "eng-exclude-test", &team_config_dir)
            .unwrap();

        // The git exclude file should contain .cargo/config.toml
        let git_dir_output = git_stdout(&worktree_dir, &["rev-parse", "--git-dir"]);
        let git_dir = if Path::new(git_dir_output.trim()).is_absolute() {
            PathBuf::from(git_dir_output.trim())
        } else {
            worktree_dir.join(git_dir_output.trim())
        };
        let exclude_content =
            std::fs::read_to_string(git_dir.join("info").join("exclude")).unwrap();
        assert!(
            exclude_content.contains(".cargo/config.toml"),
            "worktree exclude should contain .cargo/config.toml: {exclude_content}"
        );
        assert!(
            exclude_content.contains(".cargo/"),
            "worktree exclude should contain .cargo/: {exclude_content}"
        );
    }

    #[test]
    fn test_setup_engineer_worktree_finds_git_when_path_is_stripped() {
        let _path_lock = PATH_LOCK.lock().unwrap_or_else(|error| error.into_inner());
        if !git_binary_available() {
            eprintln!("skipping git-dependent task_loop test: git binary unavailable");
            return;
        }
        let _path_guard = EnvVarGuard::set("PATH", "/definitely/missing");

        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let worktree_dir = repo.join(".batty").join("worktrees").join("eng-fallback");
        let team_config_dir = repo.join(".batty").join("team_config");

        setup_engineer_worktree(&repo, &worktree_dir, "eng-fallback", &team_config_dir).unwrap();

        assert_eq!(
            git_stdout(&worktree_dir, &["rev-parse", "--abbrev-ref", "HEAD"]),
            "eng-fallback"
        );
    }

    #[test]
    fn test_prepare_assignment_worktree_auto_cleans_dirty() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let worktree_dir = repo.join(".batty").join("worktrees").join("eng-6");
        let team_config_dir = repo.join(".batty").join("team_config");

        setup_engineer_worktree(
            &repo,
            &worktree_dir,
            &engineer_base_branch_name("eng-6"),
            &team_config_dir,
        )
        .unwrap();
        std::fs::write(worktree_dir.join("scratch.txt"), "uncommitted\n").unwrap();

        // Should succeed — auto-clean commits the dirty file.
        prepare_engineer_assignment_worktree(
            &repo,
            &worktree_dir,
            "eng-6",
            "eng-6/7",
            &team_config_dir,
        )
        .unwrap();

        // Worktree should be clean now.
        assert!(!worktree_has_user_changes(&worktree_dir).unwrap());

        // No stash should be created (commit-before-reset discipline).
        let stash_list = git_stdout(&worktree_dir, &["stash", "list"]);
        assert!(
            stash_list.trim().is_empty(),
            "no stash should be created, changes should be auto-committed"
        );
    }

    #[test]
    fn test_prepare_assignment_worktree_auto_migrates_clean_legacy_worktree_branch() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let worktree_dir = repo.join(".batty").join("worktrees").join("eng-6b");
        let team_config_dir = repo.join(".batty").join("team_config");

        setup_engineer_worktree(&repo, &worktree_dir, "eng-6b", &team_config_dir).unwrap();

        prepare_engineer_assignment_worktree(
            &repo,
            &worktree_dir,
            "eng-6b",
            "eng-6b/17",
            &team_config_dir,
        )
        .unwrap();

        let legacy_check = git(&repo, &["rev-parse", "--verify", "eng-6b"]);
        assert!(!legacy_check.status.success());
        assert_eq!(
            git_stdout(&worktree_dir, &["rev-parse", "--abbrev-ref", "HEAD"]),
            "eng-6b/17"
        );
        assert_eq!(
            git_stdout(&repo, &["rev-parse", "--verify", "eng-main/eng-6b"]),
            git_stdout(&repo, &["rev-parse", "--verify", "main"])
        );
    }

    #[test]
    fn test_prepare_assignment_worktree_deletes_merged_legacy_branch_namespace() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let worktree_dir = repo.join(".batty").join("worktrees").join("eng-7");
        let team_config_dir = repo.join(".batty").join("team_config");

        git_ok(&repo, &["branch", "eng-7"]);

        prepare_engineer_assignment_worktree(
            &repo,
            &worktree_dir,
            "eng-7",
            "eng-7/99",
            &team_config_dir,
        )
        .unwrap();

        let legacy_check = git(&repo, &["rev-parse", "--verify", "eng-7"]);
        assert!(!legacy_check.status.success());
        assert_eq!(
            git_stdout(&worktree_dir, &["rev-parse", "--abbrev-ref", "HEAD"]),
            "eng-7/99"
        );
    }

    #[test]
    fn test_prepare_assignment_worktree_archives_unmerged_legacy_branch_namespace() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let worktree_dir = repo.join(".batty").join("worktrees").join("eng-8");
        let team_config_dir = repo.join(".batty").join("team_config");

        git_ok(&repo, &["checkout", "-b", "eng-8"]);
        std::fs::write(repo.join("legacy.txt"), "legacy branch work\n").unwrap();
        git_ok(&repo, &["add", "legacy.txt"]);
        git_ok(&repo, &["commit", "-m", "legacy work"]);
        git_ok(&repo, &["checkout", "main"]);

        prepare_engineer_assignment_worktree(
            &repo,
            &worktree_dir,
            "eng-8",
            "eng-8/100",
            &team_config_dir,
        )
        .unwrap();

        let legacy_check = git(&repo, &["rev-parse", "--verify", "eng-8"]);
        assert!(!legacy_check.status.success());
        assert!(!git_stdout(&repo, &["branch", "--list", "legacy/eng-8-*"]).is_empty());
        assert_eq!(
            git_stdout(&worktree_dir, &["rev-parse", "--abbrev-ref", "HEAD"]),
            "eng-8/100"
        );
    }

    #[test]
    fn test_prepare_assignment_worktree_rejects_unregistered_existing_path() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let worktree_dir = repo.join(".batty").join("worktrees").join("eng-9");
        let team_config_dir = repo.join(".batty").join("team_config");

        std::fs::create_dir_all(&worktree_dir).unwrap();

        let err = prepare_engineer_assignment_worktree(
            &repo,
            &worktree_dir,
            "eng-9",
            "eng-9/1",
            &team_config_dir,
        )
        .unwrap_err();

        assert!(
            err.to_string()
                .contains("not registered in git worktree list")
        );
    }

    #[test]
    fn test_next_unclaimed_task_picks_highest_priority() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_file(tmp.path(), 1, "low-task", "todo", "low", None, &[]);
        write_task_file(tmp.path(), 2, "high-task", "todo", "high", None, &[]);
        write_task_file(
            tmp.path(),
            3,
            "critical-task",
            "todo",
            "critical",
            None,
            &[],
        );

        let task = next_unclaimed_task(tmp.path()).unwrap().unwrap();
        assert_eq!(task.id, 3);
        assert_eq!(task.title, "critical-task");
    }

    #[test]
    fn test_next_unclaimed_task_skips_claimed() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_file(
            tmp.path(),
            1,
            "claimed-task",
            "todo",
            "critical",
            Some("eng-1-1"),
            &[],
        );
        write_task_file(tmp.path(), 2, "open-task", "todo", "low", None, &[]);

        let task = next_unclaimed_task(tmp.path()).unwrap().unwrap();
        assert_eq!(task.id, 2);
        assert_eq!(task.title, "open-task");
    }

    #[test]
    fn test_next_unclaimed_task_skips_blocked_dependency() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_file(tmp.path(), 1, "first-task", "backlog", "medium", None, &[]);
        write_task_file(tmp.path(), 2, "second-task", "todo", "critical", None, &[1]);

        let task = next_unclaimed_task(tmp.path()).unwrap().unwrap();
        assert_eq!(task.id, 1);
        assert_eq!(task.title, "first-task");
    }

    #[test]
    fn test_next_unclaimed_task_skips_blocked_on_frontmatter() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_file_with_workflow_frontmatter(
            tmp.path(),
            1,
            "blocked-task",
            "blocked_on: waiting-for-review\n",
        );
        write_task_file(tmp.path(), 2, "open-task", "todo", "high", None, &[]);

        let task = next_unclaimed_task(tmp.path()).unwrap().unwrap();
        assert_eq!(task.id, 2);
        assert_eq!(task.title, "open-task");
    }

    #[test]
    fn test_next_unclaimed_task_returns_none_when_empty() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join("tasks")).unwrap();

        let task = next_unclaimed_task(tmp.path()).unwrap();
        assert!(task.is_none());
    }

    #[test]
    fn test_run_tests_in_worktree_returns_pass_fail() {
        let tmp = tempfile::tempdir().unwrap();
        let worktree = tmp.path();
        std::fs::create_dir_all(worktree.join("src")).unwrap();
        std::fs::write(
            worktree.join("Cargo.toml"),
            "[package]\nname = \"batty-testcrate\"\nversion = \"0.1.0\"\nedition = \"2024\"\n",
        )
        .unwrap();

        std::fs::write(
            worktree.join("src").join("lib.rs"),
            "#[cfg(test)]\nmod tests {\n    #[test]\n    fn passes() {\n        assert_eq!(2 + 2, 4);\n    }\n}\n",
        )
        .unwrap();
        let run = run_tests_in_worktree(worktree, None).unwrap();
        assert!(run.passed);
        assert!(run.output.contains("test result: ok"));
        assert_eq!(run.results.framework, "cargo");

        std::fs::write(
            worktree.join("src").join("lib.rs"),
            "#[cfg(test)]\nmod tests {\n    #[test]\n    fn fails() {\n        assert_eq!(2 + 2, 5);\n    }\n}\n",
        )
        .unwrap();
        let run = run_tests_in_worktree(worktree, None).unwrap();
        assert!(!run.passed);
        assert!(run.output.contains("FAILED"));
        assert_eq!(run.results.failed, 1);
        assert_eq!(run.results.failures[0].test_name, "tests::fails");
    }

    #[test]
    fn test_run_tests_in_worktree_uses_configured_command() {
        let tmp = tempfile::tempdir().unwrap();
        let worktree = tmp.path();
        std::fs::write(
            worktree.join("check.sh"),
            "#!/bin/sh\necho CONFIG_TEST_OK\n",
        )
        .unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(
                worktree.join("check.sh"),
                std::fs::Permissions::from_mode(0o755),
            )
            .unwrap();
        }

        let run = run_tests_in_worktree(worktree, Some("./check.sh")).unwrap();
        assert!(run.passed);
        assert!(run.output.contains("CONFIG_TEST_OK"));
    }

    #[test]
    fn test_run_tests_in_worktree_sets_shared_target_dir_for_engineer_worktree() {
        let Some(_path_lock) = git_test_guard() else {
            return;
        };
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let worktree_dir = repo.join(".batty").join("worktrees").join("eng-target");
        let team_config_dir = repo.join(".batty").join("team_config");

        setup_engineer_worktree(&repo, &worktree_dir, "eng-target", &team_config_dir).unwrap();
        std::fs::write(
            worktree_dir.join("check.sh"),
            "#!/bin/sh\nprintf '%s\\n' \"$CARGO_TARGET_DIR\"\n",
        )
        .unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(
                worktree_dir.join("check.sh"),
                std::fs::Permissions::from_mode(0o755),
            )
            .unwrap();
        }

        let run = run_tests_in_worktree(&worktree_dir, Some("./check.sh")).unwrap();
        assert!(run.passed);
        assert!(
            run.output
                .contains(shared_cargo_target_dir(&repo).to_string_lossy().as_ref())
        );
    }

    #[test]
    fn test_read_task_title_from_file() {
        let tmp = tempfile::tempdir().unwrap();
        let tasks_dir = tmp.path().join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();
        std::fs::write(
            tasks_dir.join("042-my-cool-task.md"),
            "---\ntitle: My Cool Task\nstatus: in-progress\npriority: high\n---\nBody here\n",
        )
        .unwrap();
        let title = read_task_title(tmp.path(), 42);
        assert_eq!(title, "My Cool Task");
    }

    #[test]
    fn test_read_task_title_fallback() {
        let tmp = tempfile::tempdir().unwrap();
        let title = read_task_title(tmp.path(), 99);
        assert_eq!(title, "Task #99");
    }

    #[test]
    fn review_ready_gate_accepts_valid_commit_diff() {
        let gate = validate_review_ready_diff_stat(
            " src/team/completion.rs | 12 ++++++++++++\n 1 file changed, 12 insertions(+)\n",
        );
        assert!(gate.blockers.is_empty());
    }

    #[test]
    fn review_ready_gate_rejects_zero_commit_diff() {
        let gate = validate_review_ready_diff_stat("");
        assert!(
            gate.blockers
                .contains(&"engineer branch has no diff against main".to_string())
        );
    }

    #[test]
    fn review_ready_gate_rejects_config_only_diff() {
        let gate = validate_review_ready_diff_stat(
            " Cargo.toml | 14 ++++++++++++++\n docs/notes.md | 6 ++++++\n 2 files changed, 20 insertions(+)\n",
        );
        assert!(
            gate.blockers
                .iter()
                .any(|blocker| blocker.contains("need at least 10 lines of production Rust added"))
        );
    }

    #[test]
    fn review_ready_gate_rejects_destructive_net_deletion_diff() {
        let gate = validate_review_ready_diff_stat(
            " src/team/review.rs | 12 ++++--------\n 1 file changed, 4 insertions(+), 8 deletions(-)\n",
        );
        assert!(
            gate.blockers
                .iter()
                .any(|blocker| blocker.contains("net-destructive"))
        );
    }

    #[test]
    fn review_ready_gate_rejects_out_of_scope_diff() {
        let gate = validate_review_ready_diff_stat_with_scope(
            " src/team/daemon.rs | 15 +++++++++++++++\n 1 file changed, 15 insertions(+)\n",
            &["src/team/completion.rs".to_string()],
        );
        assert!(
            gate.blockers
                .iter()
                .any(|blocker| blocker.contains("changes outside task scope fence"))
        );
    }

    #[test]
    fn review_ready_gate_accepts_scope_fenced_rust_diff() {
        let gate = validate_review_ready_diff_stat_with_scope(
            " src/team/daemon/verification.rs | 15 +++++++++++++++\n 1 file changed, 15 insertions(+)\n",
            &["src/team/daemon".to_string()],
        );
        assert!(gate.blockers.is_empty());
    }

    #[test]
    fn production_task_loop_has_no_unwrap_or_expect_calls() {
        let count = production_unwrap_expect_count(Path::new(file!()));
        assert_eq!(
            count, 0,
            "production task_loop.rs should avoid unwrap/expect"
        );
    }

    // -- Cron recycling tests --

    fn write_cron_task(board_dir: &Path, id: u32, status: &str, cron: &str, extra: &str) {
        let tasks_dir = board_dir.join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();
        let path = tasks_dir.join(format!("{id:03}-cron-task.md"));
        let content = format!(
            "---\nid: {id}\ntitle: Cron Task {id}\nstatus: {status}\npriority: medium\ncron_schedule: \"{cron}\"\n{extra}---\n\nCron task body.\n"
        );
        std::fs::write(path, content).unwrap();
    }

    #[test]
    fn cron_recycle_resets_done_task_to_todo() {
        let tmp = tempfile::tempdir().unwrap();
        let board_dir = tmp.path();
        write_cron_task(
            board_dir,
            1,
            "done",
            "0 * * * * *",
            "cron_last_run: \"2020-01-01T00:00:00+00:00\"\n",
        );

        let recycled = recycle_cron_tasks(board_dir).unwrap();
        assert_eq!(recycled.len(), 1);
        assert_eq!(recycled[0].0, 1);

        let task = crate::task::Task::from_file(&board_dir.join("tasks").join("001-cron-task.md"))
            .unwrap();
        assert_eq!(task.status, "todo");
        assert!(task.cron_last_run.is_some(), "cron_last_run should be set");
        assert!(task.scheduled_for.is_some(), "scheduled_for should be set");
        assert!(task.claimed_by.is_none(), "claimed_by should be cleared");
    }

    #[test]
    fn cron_recycle_skips_archived_task() {
        let tmp = tempfile::tempdir().unwrap();
        let board_dir = tmp.path();
        write_cron_task(
            board_dir,
            2,
            "done",
            "0 * * * * *",
            "cron_last_run: \"2020-01-01T00:00:00+00:00\"\ntags:\n  - archived\n",
        );

        let recycled = recycle_cron_tasks(board_dir).unwrap();
        assert!(recycled.is_empty(), "archived tasks should be skipped");
    }

    #[test]
    fn cron_recycle_skips_in_progress_task() {
        let tmp = tempfile::tempdir().unwrap();
        let board_dir = tmp.path();
        write_cron_task(
            board_dir,
            3,
            "in-progress",
            "0 * * * * *",
            "cron_last_run: \"2020-01-01T00:00:00+00:00\"\n",
        );

        let recycled = recycle_cron_tasks(board_dir).unwrap();
        assert!(recycled.is_empty(), "in-progress tasks should be skipped");
    }

    #[test]
    fn cron_recycle_missed_trigger_skips_to_next_future() {
        let tmp = tempfile::tempdir().unwrap();
        let board_dir = tmp.path();
        write_cron_task(
            board_dir,
            4,
            "done",
            "0 * * * * *",
            "cron_last_run: \"2020-01-01T00:00:00+00:00\"\n",
        );

        let recycled = recycle_cron_tasks(board_dir).unwrap();
        assert_eq!(recycled.len(), 1);

        let task = crate::task::Task::from_file(&board_dir.join("tasks").join("004-cron-task.md"))
            .unwrap();
        assert_eq!(task.status, "todo");

        let scheduled = task.scheduled_for.as_deref().unwrap();
        let scheduled_dt = chrono::DateTime::parse_from_rfc3339(scheduled).unwrap();
        assert!(
            scheduled_dt > chrono::Utc::now(),
            "scheduled_for should be in the future, got: {scheduled}"
        );
    }

    #[test]
    fn cron_recycle_clears_transient_fields() {
        let tmp = tempfile::tempdir().unwrap();
        let board_dir = tmp.path();
        write_cron_task(
            board_dir,
            5,
            "done",
            "0 * * * * *",
            "cron_last_run: \"2020-01-01T00:00:00+00:00\"\nclaimed_by: eng-1-1\nbranch: eng-1-1/5\ncommit: abc123\nnext_action: review\nreview_owner: manager\nblocked_on: other\nworktree_path: /tmp/wt\n",
        );

        let recycled = recycle_cron_tasks(board_dir).unwrap();
        assert_eq!(recycled.len(), 1);

        let task = crate::task::Task::from_file(&board_dir.join("tasks").join("005-cron-task.md"))
            .unwrap();
        assert!(task.claimed_by.is_none());
        assert!(task.branch.is_none());
        assert!(task.commit.is_none());
        assert!(task.next_action.is_none());
        assert!(task.review_owner.is_none());
        assert!(task.blocked_on.is_none());
        assert!(task.worktree_path.is_none());
    }

    #[test]
    fn cron_recycle_emits_event() {
        use crate::team::events::TeamEvent;

        let event = TeamEvent::task_recycled(42, "0 9 * * 1");
        assert_eq!(event.event, "task_recycled");
        assert_eq!(event.task.as_deref(), Some("#42"));
        assert_eq!(event.reason.as_deref(), Some("0 9 * * 1"));
    }

    #[test]
    fn task_recycled_event_format() {
        use crate::team::events::TeamEvent;

        let event = TeamEvent::task_recycled(7, "30 8 * * *");
        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains("\"event\":\"task_recycled\""));
        assert!(json.contains("\"task\":\"#7\""));
        assert!(json.contains("\"reason\":\"30 8 * * *\""));
    }

    // -- Integration tests --

    #[test]
    fn cron_recycler_integration_resets_done_task() {
        let tmp = tempfile::tempdir().unwrap();
        let board_dir = tmp.path();

        // cron_last_run 2 minutes ago — next minutely trigger is already past
        let two_min_ago = (chrono::Utc::now() - chrono::Duration::minutes(2)).to_rfc3339();
        write_cron_task(
            board_dir,
            10,
            "done",
            "0 * * * * *",
            &format!(
                "cron_last_run: \"{two_min_ago}\"\nclaimed_by: eng-1-1\nbranch: eng-1-1/10\ncommit: deadbeef\nnext_action: review\nreview_owner: manager\nblocked_on: other\nworktree_path: /tmp/wt\n"
            ),
        );

        let recycled = recycle_cron_tasks(board_dir).unwrap();
        assert_eq!(recycled.len(), 1, "done cron task should be recycled");
        assert_eq!(recycled[0].0, 10);

        let task = crate::task::Task::from_file(&board_dir.join("tasks").join("010-cron-task.md"))
            .unwrap();

        // Status reset to todo
        assert_eq!(task.status, "todo");

        // scheduled_for set to a future time
        let scheduled = task
            .scheduled_for
            .as_deref()
            .expect("scheduled_for should be set");
        let scheduled_dt = chrono::DateTime::parse_from_rfc3339(scheduled).unwrap();
        assert!(
            scheduled_dt > chrono::Utc::now(),
            "scheduled_for should be in the future, got: {scheduled}"
        );

        // cron_last_run updated (should be more recent than 2 min ago)
        let last_run = task
            .cron_last_run
            .as_deref()
            .expect("cron_last_run should be set");
        let last_run_dt = chrono::DateTime::parse_from_rfc3339(last_run).unwrap();
        let two_min_ago_dt = chrono::DateTime::parse_from_rfc3339(&two_min_ago).unwrap();
        assert!(
            last_run_dt > two_min_ago_dt,
            "cron_last_run should be updated to now, not the old value"
        );

        // Transient fields cleared
        assert!(task.claimed_by.is_none(), "claimed_by should be cleared");
        assert!(task.branch.is_none(), "branch should be cleared");
        assert!(task.commit.is_none(), "commit should be cleared");
        assert!(task.next_action.is_none(), "next_action should be cleared");
        assert!(
            task.review_owner.is_none(),
            "review_owner should be cleared"
        );
        assert!(task.blocked_on.is_none(), "blocked_on should be cleared");
        assert!(
            task.worktree_path.is_none(),
            "worktree_path should be cleared"
        );
    }

    #[test]
    fn cron_recycler_skips_non_cron_done_task() {
        let tmp = tempfile::tempdir().unwrap();
        let board_dir = tmp.path();

        // Done task WITHOUT cron_schedule
        let tasks_dir = board_dir.join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();
        let path = tasks_dir.join("011-regular-task.md");
        std::fs::write(
            &path,
            "---\nid: 11\ntitle: Regular Task\nstatus: done\npriority: medium\n---\n\nNon-cron task.\n",
        )
        .unwrap();

        let recycled = recycle_cron_tasks(board_dir).unwrap();
        assert!(
            recycled.is_empty(),
            "non-cron done task should not be recycled"
        );

        // Verify task unchanged
        let task = crate::task::Task::from_file(&path).unwrap();
        assert_eq!(task.status, "done", "status should remain done");
    }

    #[test]
    fn e2e_done_cron_task_recycled() {
        use crate::team::resolver::{ResolutionStatus, resolve_board};
        use crate::team::test_support::{engineer_member, manager_member};

        let tmp = tempfile::tempdir().unwrap();
        let board_dir = tmp.path();

        // Create a done cron task with old cron_last_run
        write_cron_task(
            board_dir,
            10,
            "done",
            "0 * * * * *",
            "cron_last_run: \"2020-01-01T00:00:00+00:00\"\n",
        );

        // Before recycling: task is done, so resolve_board excludes it
        let members = vec![
            manager_member("manager", None),
            engineer_member("eng-1", Some("manager"), false),
        ];
        let resolutions_before = resolve_board(board_dir, &members).unwrap();
        assert!(
            resolutions_before.is_empty(),
            "done task should not appear in resolve_board"
        );

        // Recycle the cron task
        let recycled = recycle_cron_tasks(board_dir).unwrap();
        assert_eq!(recycled.len(), 1, "one task should be recycled");
        assert_eq!(recycled[0].0, 10);

        // Verify task file was updated
        let task = crate::task::Task::from_file(&board_dir.join("tasks").join("010-cron-task.md"))
            .unwrap();
        assert_eq!(task.status, "todo", "status should be reset to todo");
        assert!(task.claimed_by.is_none(), "claimed_by should be cleared");
        assert!(
            task.cron_last_run.is_some(),
            "cron_last_run should be updated"
        );

        // scheduled_for should be set to a future time
        let scheduled = task.scheduled_for.as_deref().unwrap();
        let scheduled_dt = chrono::DateTime::parse_from_rfc3339(scheduled).unwrap();
        assert!(
            scheduled_dt > chrono::Utc::now(),
            "scheduled_for should be in the future, got: {scheduled}"
        );

        // After recycling: task is now todo with future scheduled_for → Blocked
        let resolutions_after = resolve_board(board_dir, &members).unwrap();
        assert_eq!(resolutions_after.len(), 1);
        assert_eq!(
            resolutions_after[0].status,
            ResolutionStatus::Blocked,
            "recycled cron task with future scheduled_for should be Blocked until its time"
        );
        assert!(
            resolutions_after[0]
                .blocking_reason
                .as_ref()
                .unwrap()
                .contains("scheduled for"),
            "blocking reason should mention 'scheduled for'"
        );
    }

    // --- is_worktree_safe_to_mutate tests ---

    #[test]
    fn safe_to_mutate_nonexistent_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let missing = tmp.path().join("does-not-exist");
        assert!(is_worktree_safe_to_mutate(&missing).unwrap());
    }

    #[test]
    fn safe_to_mutate_clean_worktree() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let wt_dir = repo.join(".batty").join("worktrees").join("eng-safe");
        let team_config_dir = repo.join(".batty").join("team_config");

        prepare_engineer_assignment_worktree(
            &repo,
            &wt_dir,
            "eng-safe",
            "eng-safe/99",
            &team_config_dir,
        )
        .unwrap();

        // No uncommitted changes — safe to mutate.
        assert!(is_worktree_safe_to_mutate(&wt_dir).unwrap());
    }

    #[test]
    fn unsafe_to_mutate_dirty_task_branch() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let wt_dir = repo.join(".batty").join("worktrees").join("eng-dirty");
        let team_config_dir = repo.join(".batty").join("team_config");

        prepare_engineer_assignment_worktree(
            &repo,
            &wt_dir,
            "eng-dirty",
            "eng-dirty/42",
            &team_config_dir,
        )
        .unwrap();

        // Create uncommitted changes.
        std::fs::write(wt_dir.join("wip.txt"), "work in progress\n").unwrap();
        git_ok(&wt_dir, &["add", "wip.txt"]);

        // Dirty task branch — NOT safe.
        assert!(!is_worktree_safe_to_mutate(&wt_dir).unwrap());
    }

    #[test]
    fn safe_to_mutate_dirty_base_branch() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let wt_dir = repo.join(".batty").join("worktrees").join("eng-base");
        let team_config_dir = repo.join(".batty").join("team_config");

        let base = engineer_base_branch_name("eng-base");
        setup_engineer_worktree(&repo, &wt_dir, &base, &team_config_dir).unwrap();

        std::fs::write(wt_dir.join("junk.txt"), "junk\n").unwrap();
        git_ok(&wt_dir, &["add", "junk.txt"]);

        // Dirty but on eng-main/* — safe to mutate.
        assert!(is_worktree_safe_to_mutate(&wt_dir).unwrap());
    }

    #[test]
    fn unsafe_to_mutate_dirty_untracked_files_on_task_branch() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let wt_dir = repo.join(".batty").join("worktrees").join("eng-ut");
        let team_config_dir = repo.join(".batty").join("team_config");

        prepare_engineer_assignment_worktree(
            &repo,
            &wt_dir,
            "eng-ut",
            "eng-ut/55",
            &team_config_dir,
        )
        .unwrap();

        // Untracked file (not in .batty/) counts as user changes.
        std::fs::write(wt_dir.join("new_file.rs"), "fn main() {}\n").unwrap();

        assert!(!is_worktree_safe_to_mutate(&wt_dir).unwrap());
    }

    #[test]
    fn safe_to_mutate_only_batty_untracked() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let wt_dir = repo.join(".batty").join("worktrees").join("eng-bt");
        let team_config_dir = repo.join(".batty").join("team_config");

        prepare_engineer_assignment_worktree(
            &repo,
            &wt_dir,
            "eng-bt",
            "eng-bt/33",
            &team_config_dir,
        )
        .unwrap();

        // Only .batty/ untracked files — not user changes, safe.
        std::fs::create_dir_all(wt_dir.join(".batty").join("temp")).unwrap();
        std::fs::write(wt_dir.join(".batty").join("temp").join("log.txt"), "log\n").unwrap();

        assert!(is_worktree_safe_to_mutate(&wt_dir).unwrap());
    }

    // --- auto_commit_before_reset tests ---

    #[test]
    fn auto_commit_saves_uncommitted_changes() {
        let Some(_path_lock) = git_test_guard() else {
            return;
        };
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let wt_dir = repo.join(".batty").join("worktrees").join("eng-ac");
        let team_config_dir = repo.join(".batty").join("team_config");

        prepare_engineer_assignment_worktree(
            &repo,
            &wt_dir,
            "eng-ac",
            "eng-ac/77",
            &team_config_dir,
        )
        .unwrap();

        // Create uncommitted changes.
        std::fs::write(wt_dir.join("work.rs"), "fn hello() {}\n").unwrap();
        git_ok(&wt_dir, &["add", "work.rs"]);

        assert!(auto_commit_before_reset(&wt_dir));

        // Worktree should now be clean.
        crate::team::test_support::assert_worktree_clean(&wt_dir);

        // Verify the commit message contains the wip marker.
        let log = git_stdout(&wt_dir, &["log", "--oneline", "-1"]);
        assert!(
            log.contains("wip: auto-save"),
            "commit should have wip marker, got: {log}"
        );
    }

    #[test]
    fn auto_commit_noop_on_clean_worktree() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let wt_dir = repo.join(".batty").join("worktrees").join("eng-cl");
        let team_config_dir = repo.join(".batty").join("team_config");

        prepare_engineer_assignment_worktree(
            &repo,
            &wt_dir,
            "eng-cl",
            "eng-cl/88",
            &team_config_dir,
        )
        .unwrap();

        let before = git_stdout(&wt_dir, &["rev-parse", "HEAD"]);

        // No changes — should succeed without creating a commit.
        assert!(auto_commit_before_reset(&wt_dir));

        let after = git_stdout(&wt_dir, &["rev-parse", "HEAD"]);
        assert_eq!(
            before, after,
            "no new commit should be created for clean worktree"
        );
    }

    #[test]
    fn auto_commit_saves_untracked_files() {
        let Some(_path_lock) = git_test_guard() else {
            return;
        };
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let wt_dir = repo.join(".batty").join("worktrees").join("eng-ut2");
        let team_config_dir = repo.join(".batty").join("team_config");

        prepare_engineer_assignment_worktree(
            &repo,
            &wt_dir,
            "eng-ut2",
            "eng-ut2/99",
            &team_config_dir,
        )
        .unwrap();

        // Create untracked file (not staged).
        std::fs::write(wt_dir.join("new_file.txt"), "new content\n").unwrap();

        assert!(auto_commit_before_reset(&wt_dir));

        // Worktree should be clean.
        crate::team::test_support::assert_worktree_clean(&wt_dir);
    }

    #[test]
    fn auto_clean_worktree_uses_commit_not_stash() {
        let Some(_path_lock) = git_test_guard() else {
            return;
        };
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let wt_dir = repo.join(".batty").join("worktrees").join("eng-ns");
        let team_config_dir = repo.join(".batty").join("team_config");

        prepare_engineer_assignment_worktree(
            &repo,
            &wt_dir,
            "eng-ns",
            "eng-ns/66",
            &team_config_dir,
        )
        .unwrap();

        // Create both tracked and untracked changes so the shared reset helper
        // preserves the full dirty worktree before cleanup.
        std::fs::write(wt_dir.join("tracked.txt"), "tracked work\n").unwrap();
        git_ok(&wt_dir, &["add", "tracked.txt"]);
        std::fs::write(wt_dir.join("untracked.txt"), "untracked work\n").unwrap();

        auto_clean_worktree(&wt_dir).unwrap();

        crate::team::test_support::assert_worktree_clean(&wt_dir);

        // No stashes should have been created.
        let stash = git_stdout(&wt_dir, &["stash", "list"]);
        assert!(
            stash.trim().is_empty(),
            "no stash should be created, got: {stash}"
        );

        // A wip commit should exist.
        let log = git_stdout(&wt_dir, &["log", "--oneline", "-1"]);
        assert!(
            log.contains("wip: auto-save"),
            "should have wip commit, got: {log}"
        );
        assert_eq!(
            git_stdout(&wt_dir, &["show", "HEAD:tracked.txt"]),
            "tracked work"
        );
        assert_eq!(
            git_stdout(&wt_dir, &["show", "HEAD:untracked.txt"]),
            "untracked work"
        );
    }

    #[test]
    fn auto_clean_worktree_blocks_when_preserve_fails() {
        let Some(_path_lock) = git_test_guard() else {
            return;
        };
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let wt_dir = repo.join(".batty").join("worktrees").join("eng-blocked");
        let team_config_dir = repo.join(".batty").join("team_config");

        prepare_engineer_assignment_worktree(
            &repo,
            &wt_dir,
            "eng-blocked",
            "eng-blocked/77",
            &team_config_dir,
        )
        .unwrap();

        std::fs::write(wt_dir.join("tracked.txt"), "tracked dirty work\n").unwrap();
        git_ok(&wt_dir, &["add", "tracked.txt"]);
        std::fs::write(wt_dir.join("unstaged.txt"), "leave unstaged\n").unwrap();
        let git_dir = PathBuf::from(git_stdout(&wt_dir, &["rev-parse", "--git-dir"]));
        let git_dir = if git_dir.is_absolute() {
            git_dir
        } else {
            wt_dir.join(git_dir)
        };
        std::fs::write(git_dir.join("index.lock"), "locked\n").unwrap();

        let error = auto_clean_worktree(&wt_dir).unwrap_err();
        assert!(
            error
                .to_string()
                .contains("could not safely auto-save dirty worktree"),
            "expected explicit preservation blocker, got: {error}"
        );
        assert_eq!(current_worktree_branch(&wt_dir).unwrap(), "eng-blocked/77");
        let status = git_stdout(&wt_dir, &["status", "--short"]);
        assert!(
            status.contains("A  tracked.txt"),
            "original staged work should remain staged after preserve failure: {status}"
        );
        assert!(
            status.contains("?? unstaged.txt"),
            "preserve failure must not stage previously unstaged files: {status}"
        );
    }

    #[test]
    fn preserve_worktree_with_commit_returns_false_when_clean() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let wt_dir = repo
            .join(".batty")
            .join("worktrees")
            .join("eng-clean-preserve");
        let team_config_dir = repo.join(".batty").join("team_config");

        prepare_engineer_assignment_worktree(
            &repo,
            &wt_dir,
            "eng-clean-preserve",
            "eng-clean-preserve/101",
            &team_config_dir,
        )
        .unwrap();

        let saved = preserve_worktree_with_commit(
            &wt_dir,
            "wip: auto-save before restart [batty]",
            Duration::from_secs(5),
        )
        .unwrap();
        assert!(!saved);
    }

    #[test]
    fn preserve_worktree_with_commit_saves_dirty_changes() {
        let Some(_path_lock) = git_test_guard() else {
            return;
        };
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let wt_dir = repo.join(".batty").join("worktrees").join("eng-preserve");
        let team_config_dir = repo.join(".batty").join("team_config");

        prepare_engineer_assignment_worktree(
            &repo,
            &wt_dir,
            "eng-preserve",
            "eng-preserve/103",
            &team_config_dir,
        )
        .unwrap();

        std::fs::write(wt_dir.join("preserved.txt"), "keep this work\n").unwrap();

        let saved = preserve_worktree_with_commit(
            &wt_dir,
            "wip: auto-save before restart [batty]",
            Duration::from_secs(5),
        )
        .unwrap();
        assert!(saved, "dirty worktree should be auto-committed");

        crate::team::test_support::assert_worktree_clean(&wt_dir);

        let log = git_stdout(&wt_dir, &["log", "--oneline", "-1"]);
        assert!(
            log.contains("wip: auto-save before restart [batty]"),
            "expected restart preservation commit, got: {log}"
        );
    }

    #[test]
    fn preserve_worktree_with_commit_ignores_batty_untracked_only() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let wt_dir = repo
            .join(".batty")
            .join("worktrees")
            .join("eng-batty-clean");
        let team_config_dir = repo.join(".batty").join("team_config");

        prepare_engineer_assignment_worktree(
            &repo,
            &wt_dir,
            "eng-batty-clean",
            "eng-batty-clean/104",
            &team_config_dir,
        )
        .unwrap();

        std::fs::create_dir_all(wt_dir.join(".batty").join("scratch")).unwrap();
        std::fs::write(
            wt_dir.join(".batty").join("scratch").join("session.log"),
            "transient\n",
        )
        .unwrap();

        let head_before = git_stdout(&wt_dir, &["rev-parse", "HEAD"]);
        let saved = preserve_worktree_with_commit(
            &wt_dir,
            "wip: auto-save before restart [batty]",
            Duration::from_secs(1),
        )
        .unwrap();
        assert!(
            !saved,
            "only .batty untracked files should not trigger commit"
        );

        let head_after = git_stdout(&wt_dir, &["rev-parse", "HEAD"]);
        assert_eq!(head_before, head_after, "no commit should be created");
    }

    #[test]
    fn preserve_worktree_with_commit_succeeds_with_ignored_batty_and_cargo_dirs_present() {
        let Some(_path_lock) = git_test_guard() else {
            return;
        };
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let wt_dir = repo
            .join(".batty")
            .join("worktrees")
            .join("eng-preserve-ignored");
        let team_config_dir = repo.join(".batty").join("team_config");

        prepare_engineer_assignment_worktree(
            &repo,
            &wt_dir,
            "eng-preserve-ignored",
            "eng-preserve-ignored/105",
            &team_config_dir,
        )
        .unwrap();

        std::fs::write(wt_dir.join("preserved.txt"), "keep this work\n").unwrap();
        std::fs::create_dir_all(wt_dir.join(".batty").join("scratch")).unwrap();
        std::fs::create_dir_all(wt_dir.join(".cargo")).unwrap();
        std::fs::write(
            wt_dir.join(".batty").join("scratch").join("session.log"),
            "transient\n",
        )
        .unwrap();
        std::fs::write(wt_dir.join(".cargo").join("config.toml"), "build = {}\n").unwrap();

        let saved = preserve_worktree_with_commit(
            &wt_dir,
            "wip: auto-save before restart [batty]",
            Duration::from_secs(5),
        )
        .unwrap();
        assert!(saved, "dirty worktree should still be auto-committed");

        crate::team::test_support::assert_worktree_clean(&wt_dir);

        let log = git_stdout(&wt_dir, &["log", "--oneline", "-1"]);
        assert!(
            log.contains("wip: auto-save before restart [batty]"),
            "expected restart preservation commit, got: {log}"
        );
        assert_eq!(
            git_stdout(&wt_dir, &["show", "HEAD:preserved.txt"]),
            "keep this work"
        );
    }

    #[test]
    fn preserve_worktree_with_commit_is_idempotent_for_same_state() {
        let Some(_path_lock) = git_test_guard() else {
            return;
        };
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let wt_dir = repo.join(".batty").join("worktrees").join("eng-idempotent");
        let team_config_dir = repo.join(".batty").join("team_config");

        prepare_engineer_assignment_worktree(
            &repo,
            &wt_dir,
            "eng-idempotent",
            "eng-idempotent/105",
            &team_config_dir,
        )
        .unwrap();

        std::fs::write(wt_dir.join("preserved.txt"), "keep this work\n").unwrap();

        let first = preserve_worktree_with_commit(
            &wt_dir,
            "wip: auto-save before restart [batty]",
            Duration::from_secs(5),
        )
        .unwrap();
        assert!(
            first,
            "first preservation should create the checkpoint commit"
        );

        let head_after_first = git_stdout(&wt_dir, &["rev-parse", "HEAD"]);
        let second = preserve_worktree_with_commit(
            &wt_dir,
            "wip: auto-save before restart [batty]",
            Duration::from_secs(5),
        )
        .unwrap();
        assert!(
            !second,
            "second preservation on identical state should be a no-op"
        );
        let head_after_second = git_stdout(&wt_dir, &["rev-parse", "HEAD"]);
        assert_eq!(head_after_first, head_after_second);
        crate::team::test_support::assert_worktree_clean(&wt_dir);
    }

    #[test]
    fn preserve_worktree_with_commit_ignores_gitignored_runtime_dirs() {
        let Some(_path_lock) = git_test_guard() else {
            return;
        };
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let wt_dir = repo
            .join(".batty")
            .join("worktrees")
            .join("eng-runtime-ignored");
        let team_config_dir = repo.join(".batty").join("team_config");

        std::fs::write(repo.join(".gitignore"), ".batty-target/\n").unwrap();
        git_ok(&repo, &["add", ".gitignore"]);
        git_ok(&repo, &["commit", "-m", "ignore runtime target"]);

        prepare_engineer_assignment_worktree(
            &repo,
            &wt_dir,
            "eng-runtime-ignored",
            "eng-runtime-ignored/106",
            &team_config_dir,
        )
        .unwrap();

        std::fs::create_dir_all(wt_dir.join(".batty-target").join("debug")).unwrap();
        std::fs::write(
            wt_dir.join(".batty-target").join("debug").join("build.log"),
            "transient\n",
        )
        .unwrap();

        assert!(
            !worktree_has_user_changes(&wt_dir).unwrap(),
            ".batty-target noise should not count as user changes"
        );
        let saved = preserve_worktree_with_commit(
            &wt_dir,
            "wip: auto-save before restart [batty]",
            Duration::from_secs(5),
        )
        .unwrap();
        assert!(
            !saved,
            "gitignored runtime dirs should not trigger preservation"
        );
    }

    #[test]
    fn preserve_worktree_with_commit_times_out() {
        let Some(_path_lock) = git_test_guard() else {
            return;
        };
        let tmp = tempfile::tempdir().unwrap();
        let repo = init_git_repo(&tmp);
        let wt_dir = repo.join(".batty").join("worktrees").join("eng-timeout");
        let team_config_dir = repo.join(".batty").join("team_config");

        prepare_engineer_assignment_worktree(
            &repo,
            &wt_dir,
            "eng-timeout",
            "eng-timeout/102",
            &team_config_dir,
        )
        .unwrap();

        std::fs::write(wt_dir.join("slow.txt"), "pending\n").unwrap();

        // The timeout path is hard to test reliably because
        // run_git_with_timeout falls back to hardcoded git paths
        // (/usr/bin/git, /opt/homebrew/bin/git) bypassing PATH shims.
        // Instead, verify that a very fast commit with a generous timeout
        // succeeds — proving the timeout doesn't fire spuriously.
        let result = preserve_worktree_with_commit(
            &wt_dir,
            "wip: auto-save before restart [batty]",
            Duration::from_secs(30),
        );
        assert!(
            result.is_ok(),
            "commit with generous timeout should succeed"
        );
    }

    // --- priority_rank tests ---

    #[test]
    fn priority_rank_known_values() {
        assert_eq!(priority_rank("critical"), 0);
        assert_eq!(priority_rank("high"), 1);
        assert_eq!(priority_rank("medium"), 2);
        assert_eq!(priority_rank("low"), 3);
    }

    #[test]
    fn priority_rank_unknown_returns_lowest() {
        assert_eq!(priority_rank(""), 4);
        assert_eq!(priority_rank("urgent"), 4);
        assert_eq!(priority_rank("CRITICAL"), 4); // case-sensitive
    }

    // --- next_unclaimed_task edge cases ---

    #[test]
    fn next_unclaimed_task_all_done_returns_none() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_file(tmp.path(), 1, "done-task", "done", "high", None, &[]);
        write_task_file(
            tmp.path(),
            2,
            "in-progress-task",
            "in-progress",
            "critical",
            None,
            &[],
        );

        let task = next_unclaimed_task(tmp.path()).unwrap();
        assert!(task.is_none());
    }

    #[test]
    fn next_unclaimed_task_respects_backlog_status() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_file(
            tmp.path(),
            1,
            "backlog-task",
            "backlog",
            "medium",
            None,
            &[],
        );

        let task = next_unclaimed_task(tmp.path()).unwrap().unwrap();
        assert_eq!(task.id, 1);
    }

    #[test]
    fn next_unclaimed_task_tiebreaks_by_id() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_file(tmp.path(), 10, "task-ten", "todo", "high", None, &[]);
        write_task_file(tmp.path(), 5, "task-five", "todo", "high", None, &[]);
        write_task_file(tmp.path(), 20, "task-twenty", "todo", "high", None, &[]);

        let task = next_unclaimed_task(tmp.path()).unwrap().unwrap();
        assert_eq!(task.id, 5, "should pick lowest id when priority is tied");
    }

    #[test]
    fn next_unclaimed_task_skips_blocked_frontmatter() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_file_with_workflow_frontmatter(tmp.path(), 1, "blocked-task", "blocked: yes\n");
        write_task_file(tmp.path(), 2, "free-task", "todo", "low", None, &[]);

        let task = next_unclaimed_task(tmp.path()).unwrap().unwrap();
        assert_eq!(task.id, 2);
    }

    #[test]
    fn next_unclaimed_task_allows_done_dependency() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_file(tmp.path(), 1, "done-dep", "done", "low", None, &[]);
        write_task_file(tmp.path(), 2, "depends-on-done", "todo", "high", None, &[1]);

        let task = next_unclaimed_task(tmp.path()).unwrap().unwrap();
        assert_eq!(task.id, 2, "task with done dependency should be available");
    }

    #[test]
    fn next_unclaimed_task_blocks_on_undone_dependency() {
        let tmp = tempfile::tempdir().unwrap();
        write_task_file(
            tmp.path(),
            1,
            "in-progress-dep",
            "in-progress",
            "low",
            None,
            &[],
        );
        write_task_file(
            tmp.path(),
            2,
            "blocked-by-dep",
            "todo",
            "critical",
            None,
            &[1],
        );

        // Task 2 depends on task 1 which is in-progress — should not be picked
        let task = next_unclaimed_task(tmp.path()).unwrap();
        assert!(
            task.is_none(),
            "task with in-progress dependency should not be available"
        );
    }

    #[test]
    fn next_unclaimed_task_nonexistent_dependency_treated_as_done() {
        let tmp = tempfile::tempdir().unwrap();
        // Task depends on id 999 which doesn't exist — treated as satisfied
        write_task_file(tmp.path(), 1, "orphan-dep", "todo", "high", None, &[999]);

        let task = next_unclaimed_task(tmp.path()).unwrap().unwrap();
        assert_eq!(task.id, 1);
    }

    // --- read_task_title edge cases ---

    #[test]
    fn read_task_title_quoted_title() {
        let tmp = tempfile::tempdir().unwrap();
        let tasks_dir = tmp.path().join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();
        std::fs::write(
            tasks_dir.join("007-quoted.md"),
            "---\ntitle: 'My Quoted Task'\nstatus: todo\n---\nBody\n",
        )
        .unwrap();
        let title = read_task_title(tmp.path(), 7);
        assert_eq!(title, "My Quoted Task");
    }

    #[test]
    fn read_task_title_double_quoted() {
        let tmp = tempfile::tempdir().unwrap();
        let tasks_dir = tmp.path().join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();
        std::fs::write(
            tasks_dir.join("008-double.md"),
            "---\ntitle: \"Double Quoted\"\nstatus: todo\n---\nBody\n",
        )
        .unwrap();
        let title = read_task_title(tmp.path(), 8);
        assert_eq!(title, "Double Quoted");
    }

    #[test]
    fn read_task_title_no_title_line_returns_fallback() {
        let tmp = tempfile::tempdir().unwrap();
        let tasks_dir = tmp.path().join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();
        std::fs::write(
            tasks_dir.join("009-no-title.md"),
            "---\nstatus: todo\npriority: low\n---\nBody\n",
        )
        .unwrap();
        let title = read_task_title(tmp.path(), 9);
        assert_eq!(title, "Task #9");
    }

    #[test]
    fn read_task_title_three_digit_id_prefix() {
        let tmp = tempfile::tempdir().unwrap();
        let tasks_dir = tmp.path().join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();
        std::fs::write(
            tasks_dir.join("123-big-id.md"),
            "---\ntitle: Big ID Task\nstatus: todo\n---\n",
        )
        .unwrap();
        let title = read_task_title(tmp.path(), 123);
        assert_eq!(title, "Big ID Task");
    }

    // --- engineer_base_branch_name ---

    #[test]
    fn engineer_base_branch_name_format() {
        assert_eq!(engineer_base_branch_name("eng-1-1"), "eng-main/eng-1-1");
        assert_eq!(engineer_base_branch_name("eng-2"), "eng-main/eng-2");
    }

    // --- map_git_error ---

    #[test]
    fn map_git_error_ok_passes_through() {
        let result: std::result::Result<i32, super::git_cmd::GitError> = Ok(42);
        let mapped = map_git_error(result, "test action");
        assert_eq!(mapped.unwrap(), 42);
    }

    #[test]
    fn map_git_error_err_wraps_message() {
        let result: std::result::Result<i32, super::git_cmd::GitError> =
            Err(super::git_cmd::GitError::Permanent {
                message: "git status failed".to_string(),
                stderr: "fatal: something".to_string(),
            });
        let err = map_git_error(result, "checking status").unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("checking status"), "got: {msg}");
    }

    // --- cron edge cases ---

    #[test]
    fn cron_recycle_invalid_expression_skips() {
        let tmp = tempfile::tempdir().unwrap();
        write_cron_task(
            tmp.path(),
            1,
            "done",
            "not a cron expression",
            "cron_last_run: \"2020-01-01T00:00:00+00:00\"\n",
        );

        let recycled = recycle_cron_tasks(tmp.path()).unwrap();
        assert!(
            recycled.is_empty(),
            "invalid cron expression should be skipped"
        );
    }

    #[test]
    fn cron_recycle_no_last_run_defaults_to_yesterday() {
        let tmp = tempfile::tempdir().unwrap();
        // Done cron task with no cron_last_run — should use now - 1 day as reference
        write_cron_task(tmp.path(), 1, "done", "0 * * * * *", "");

        let recycled = recycle_cron_tasks(tmp.path()).unwrap();
        assert_eq!(
            recycled.len(),
            1,
            "should recycle even without cron_last_run"
        );
    }

    #[test]
    fn cron_recycle_future_trigger_skips() {
        let tmp = tempfile::tempdir().unwrap();
        // Set last run to now so next trigger is in the future
        let now = chrono::Utc::now().to_rfc3339();
        write_cron_task(
            tmp.path(),
            1,
            "done",
            "0 0 1 1 * 2099",
            &format!("cron_last_run: \"{now}\"\n"),
        );

        let recycled = recycle_cron_tasks(tmp.path()).unwrap();
        assert!(recycled.is_empty(), "future trigger should be skipped");
    }

    // --- sentinel tests for error resilience (#311) ---

    /// Refresh on a stale/nonexistent worktree should return Ok, not panic.
    #[test]
    fn refresh_nonexistent_worktree_returns_ok() {
        let tmp = tempfile::tempdir().unwrap();
        let fake_worktree = tmp.path().join("does-not-exist");
        let team_cfg = tmp.path().join("team_config");
        std::fs::create_dir_all(&team_cfg).unwrap();

        let result = refresh_engineer_worktree(tmp.path(), &fake_worktree, "no-branch", &team_cfg);
        // Non-existent worktree should be handled gracefully (early return Ok)
        assert!(
            result.is_ok(),
            "refresh on nonexistent worktree should not panic: {result:?}"
        );
    }

    /// run_tests_in_worktree should return a clean error when cargo is not
    /// found, and should surface an invalid worktree as a failed test run
    /// instead of panicking.
    #[test]
    fn test_gating_missing_dir_returns_error() {
        let tmp = tempfile::tempdir().unwrap();
        let fake_dir = tmp.path().join("missing-worktree");
        assert!(!fake_dir.exists(), "test requires a nonexistent directory");
        let result = run_tests_in_worktree(&fake_dir, None);
        let output = result.expect("missing worktree should surface as a failed test run");
        assert!(
            !output.passed,
            "run_tests_in_worktree on missing dir should fail cleanly"
        );
        let err_msg = output.output;
        assert!(
            err_msg.contains("No such file")
                || err_msg.contains("failed")
                || err_msg.contains("could not find"),
            "error should describe the failed test operation, got: {err_msg}"
        );
    }

    /// checkout_worktree_branch_from_main should propagate an error cleanly
    /// when run against a non-git directory, not panic.
    #[test]
    fn checkout_branch_in_non_git_dir_returns_error() {
        let tmp = tempfile::tempdir().unwrap();
        // tmp is not a git repo, so git operations should fail
        let result = checkout_worktree_branch_from_main(tmp.path(), "fake-branch");
        assert!(
            result.is_err(),
            "checkout on non-git dir should return Err, not panic"
        );
    }

    /// Verify the production code in this file has zero bare .unwrap() or
    /// .expect() calls (only safe fallback variants like unwrap_or_default).
    #[test]
    fn no_panicking_unwraps_in_production_code() {
        let count = production_unwrap_expect_count(Path::new("src/team/task_loop.rs"));
        assert_eq!(
            count, 0,
            "production code should have zero bare .unwrap()/.expect() calls, found {count}"
        );
    }

    #[test]
    fn git_has_unresolved_conflicts_detects_unmerged_status_entries() {
        assert!(line_has_unresolved_conflict("UU src/team/verification.rs"));
        assert!(line_has_unresolved_conflict("AA src/lib.rs"));
        assert!(line_has_unresolved_conflict("DU src/main.rs"));
        assert!(!line_has_unresolved_conflict(" M src/main.rs"));
        assert!(!line_has_unresolved_conflict("?? scratch.txt"));
    }

    #[test]
    fn merge_additive_only_text_keeps_both_insertions() {
        let base = "const CHECKS: &[&str] = &[\n    \"existing\",\n];\n";
        let current = "const CHECKS: &[&str] = &[\n    \"main\",\n    \"existing\",\n];\n";
        let incoming = "const CHECKS: &[&str] = &[\n    \"engineer\",\n    \"existing\",\n];\n";

        let merged = merge_additive_only_text(base, current, incoming)
            .expect("pure insertions should auto-merge");

        assert!(merged.contains("\"main\""));
        assert!(merged.contains("\"engineer\""));
        assert!(merged.contains("\"existing\""));
    }

    #[test]
    fn merge_additive_only_text_rejects_modified_base_lines() {
        let base = "const CHECKS: &[&str] = &[\n    \"existing\",\n];\n";
        let current = "const CHECKS: &[&str] = &[\n    \"existing\",\n    \"main\",\n];\n";
        let incoming = "const CHECKS: &[&str] = &[\n    \"renamed\",\n];\n";

        assert!(merge_additive_only_text(base, current, incoming).is_none());
    }
}